@code-partner/codepipe 0.12.1-dev.252.gaefd16e → 0.12.1-dev.254.g36ac0c7

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 +177 -174
  2. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -1,38 +1,38 @@
1
1
  #!/usr/bin/env node
2
- var tb=Object.defineProperty;var x=(t,e)=>()=>(t&&(e=t(t=0)),e);var ze=(t,e)=>{for(var r in e)tb(t,r,{get:e[r],enumerable:!0})};var Ve,mt,Ws=x(()=>{"use strict";Ve="0.12.1-dev.252.gaefd16e",mt="https://hub.dev.codepipe.dev"});function zn(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=ku&&t<=ht}var ht,ku,bu=x(()=>{"use strict";Ws();ht=4,ku=4});var $u=x(()=>{"use strict";Ws()});function Vn(t=6){return`# CodePipe Context Repo format version.
2
+ var nb=Object.defineProperty;var x=(t,e)=>()=>(t&&(e=t(t=0)),e);var ze=(t,e)=>{for(var r in e)nb(t,r,{get:e[r],enumerable:!0})};var Ve,mt,qs=x(()=>{"use strict";Ve="0.12.1-dev.254.g36ac0c7",mt="https://hub.dev.codepipe.dev"});function Vn(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=$u&&t<=ht}var ht,$u,vu=x(()=>{"use strict";qs();ht=4,$u=4});var xu=x(()=>{"use strict";qs()});function Xn(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 Ys(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 zs(t,e=qs){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 Vs(t,e=qs){return e.filter(r=>r.version>t)}var vu,gt,Gr,qs,xu=x(()=>{"use strict";vu=6,gt=".codepipe-context.yaml",Gr=".devpipe-context.yaml",qs=[{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",gt]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[gt]},{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 Jn(t){return`model/facts/identity/${t}.yaml`}function hr(t){return`model/facts/events/${t}.yaml`}function Zs(t){return`model/facts/annotations/${t}.md`}function Qs(t){return`model/derived/correlates/${t}.yaml`}function ea(t){return`model/derived/touched/${t}.yaml`}function Su(t){return t===""?"root":t.replace(/\//g,"-")}function ta(t,e){return`model/derived/structure/${t}/${Su(e)}.yaml`}function Jo(t){return typeof t=="string"&&Tu.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(!Eu.includes(n))return null;let o=t.slice(e+1,r),i=t.slice(r+1);return o===""&&!sb.includes(n)||i===""?null:{level:n,repo:o,path:i}}function ve(t){return`task::${t}`}function ye(t,e,r){return`${t}:${e}:${r}`}function Zn(t){let e=[];return vt(t)?(Qo(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(!vt(r)){e.push(`edges[${n}]: not an object`);return}ra.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 Iu(t){return{...t,edges:Kr(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function gr(t){return wr(Iu(t))}function vt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Qo(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function yt(t){return typeof t=="string"&&t.length>0}function cb(t){return t.modelFormatVersion!==2}function jt(t){let e=[];if(!vt(t))return{ok:!1,errors:["shard: not an object"]};Qo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),yt(t.repo)||e.push("repo: missing or empty"),yt(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(!vt(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&&!Jo(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(!vt(o)){e.push(`edges[${i}]: not an object`);return}ra.includes(o.kind)||e.push(`edges[${i}].kind: unknown "${String(o.kind)}"`),(!yt(o.to)||!re(o.to))&&e.push(`edges[${i}].to: malformed nodeKey`),(!yt(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 Qn(t){let e=[];if(!vt(t))return{ok:!1,errors:["identity: not an object"]};if(Qo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),yt(t.repo)||e.push("repo: missing or empty"),t.builtFromCommit!==void 0&&!yt(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(!vt(n)){e.push(`entities[${o}]: not an object`);return}Jo(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`),yt(n.firstSeen)||e.push(`entities[${o}].firstSeen: missing`),yt(n.lastSeen)||e.push(`entities[${o}].lastSeen: missing`),n.aliases!==void 0&&(Array.isArray(n.aliases)?n.aliases.forEach((i,s)=>{(!vt(i)||!re(i.key)||!yt(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 Nt(t){let e=[];return vt(t)?(Qo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),yt(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=>!yt(r)))&&e.push("commits: not an array of non-empty strings"),Array.isArray(t.files)?t.files.forEach((r,n)=>{if(!vt(r)||!re(r.key)){e.push(`files[${n}].key: malformed nodeKey`);return}r.entityId!==void 0&&!Jo(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 Kr(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function Ru(t){return{...t,nodes:Kr(t.nodes,e=>e.key),edges:Kr(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function Cu(t){return{...t,entities:Kr(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:Kr(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function Pu(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:Kr(t.files,r=>r.key),...e?{links:e}:{}}}function Xn(t){return lb.test(t)?t:JSON.stringify(t)}function Au(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 _u(t){return t===null||["boolean","number","string"].includes(typeof t)}function Xs(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function ju(t,e,r){if(Array.isArray(t)){for(let n of t)if(_u(n))r.push(`${e}- ${Au(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=Xs(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([i,s],a)=>{let c=a===0?`${e}- `:`${e} `;Js(i,s,c,`${e} `,r)})}}return}for(let[n,o]of Xs(t))Js(n,o,e,e,r)}function Js(t,e,r,n,o){if(_u(e))o.push(`${r}${Xn(t)}: ${Au(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${Xn(t)}: []`):(o.push(`${r}${Xn(t)}:`),ju(e,`${n} `,o));else{let i=Xs(e);if(i.length===0)o.push(`${r}${Xn(t)}: {}`);else{o.push(`${r}${Xn(t)}:`);for(let[s,a]of i)Js(s,a,`${n} `,`${n} `,o)}}}function wr(t){let e=[];return ju(t,"",e),e.join(`
5
+ `}function zs(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 Vs(t,e=Ys){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 Xs(t,e=Ys){return e.filter(r=>r.version>t)}var Su,gt,Kr,Ys,Eu=x(()=>{"use strict";Su=6,gt=".codepipe-context.yaml",Kr=".devpipe-context.yaml",Ys=[{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",gt]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[gt]},{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 Zn(t){return`model/facts/identity/${t}.yaml`}function gr(t){return`model/facts/events/${t}.yaml`}function Qs(t){return`model/facts/annotations/${t}.md`}function ea(t){return`model/derived/correlates/${t}.yaml`}function ta(t){return`model/derived/touched/${t}.yaml`}function Tu(t){return t===""?"root":t.replace(/\//g,"-")}function ra(t,e){return`model/derived/structure/${t}/${Tu(e)}.yaml`}function Qo(t){return typeof t=="string"&&Iu.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(!Ru.includes(n))return null;let o=t.slice(e+1,r),i=t.slice(r+1);return o===""&&!cb.includes(n)||i===""?null:{level:n,repo:o,path:i}}function xe(t){return`task::${t}`}function ye(t,e,r){return`${t}:${e}:${r}`}function Qn(t){let e=[];return vt(t)?(ti(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(!vt(r)){e.push(`edges[${n}]: not an object`);return}na.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 Cu(t){return{...t,edges:Hr(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function yr(t){return kr(Cu(t))}function vt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ti(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function yt(t){return typeof t=="string"&&t.length>0}function ub(t){return t.modelFormatVersion!==2}function jt(t){let e=[];if(!vt(t))return{ok:!1,errors:["shard: not an object"]};ti(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),yt(t.repo)||e.push("repo: missing or empty"),yt(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(!vt(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&&!Qo(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(!vt(o)){e.push(`edges[${i}]: not an object`);return}na.includes(o.kind)||e.push(`edges[${i}].kind: unknown "${String(o.kind)}"`),(!yt(o.to)||!re(o.to))&&e.push(`edges[${i}].to: malformed nodeKey`),(!yt(o.from)||!n.has(o.from))&&e.push(`edges[${i}].from: "${String(o.from)}" is not a node of this shard`),o.weight!==void 0&&!(typeof o.weight=="number"&&Number.isFinite(o.weight))&&e.push(`edges[${i}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}}function eo(t){let e=[];if(!vt(t))return{ok:!1,errors:["identity: not an object"]};if(ti(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),yt(t.repo)||e.push("repo: missing or empty"),t.builtFromCommit!==void 0&&!yt(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(!vt(n)){e.push(`entities[${o}]: not an object`);return}Qo(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`),yt(n.firstSeen)||e.push(`entities[${o}].firstSeen: missing`),yt(n.lastSeen)||e.push(`entities[${o}].lastSeen: missing`),n.aliases!==void 0&&(Array.isArray(n.aliases)?n.aliases.forEach((i,s)=>{(!vt(i)||!re(i.key)||!yt(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 Nt(t){let e=[];return vt(t)?(ti(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),yt(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=>!yt(r)))&&e.push("commits: not an array of non-empty strings"),Array.isArray(t.files)?t.files.forEach((r,n)=>{if(!vt(r)||!re(r.key)){e.push(`files[${n}].key: malformed nodeKey`);return}r.entityId!==void 0&&!Qo(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 Hr(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function Pu(t){return{...t,nodes:Hr(t.nodes,e=>e.key),edges:Hr(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function Au(t){return{...t,entities:Hr(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:Hr(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function _u(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:Hr(t.files,r=>r.key),...e?{links:e}:{}}}function Jn(t){return db.test(t)?t:JSON.stringify(t)}function ju(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 Nu(t){return t===null||["boolean","number","string"].includes(typeof t)}function Js(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function Ou(t,e,r){if(Array.isArray(t)){for(let n of t)if(Nu(n))r.push(`${e}- ${ju(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=Js(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([i,s],a)=>{let c=a===0?`${e}- `:`${e} `;Zs(i,s,c,`${e} `,r)})}}return}for(let[n,o]of Js(t))Zs(n,o,e,e,r)}function Zs(t,e,r,n,o){if(Nu(e))o.push(`${r}${Jn(t)}: ${ju(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${Jn(t)}: []`):(o.push(`${r}${Jn(t)}:`),Ou(e,`${n} `,o));else{let i=Js(e);if(i.length===0)o.push(`${r}${Jn(t)}: {}`);else{o.push(`${r}${Jn(t)}:`);for(let[s,a]of i)Zs(s,a,`${n} `,`${n} `,o)}}}function kr(t){let e=[];return Ou(t,"",e),e.join(`
6
6
  `)+`
7
- `}function aa(t){return wr(Ru(t))}function ca(t){return wr(Cu(t))}function Hr(t){return wr(Pu(t))}var Oe,rb,nb,ob,ib,Xo,mr,Eu,ra,Tu,sb,nt,na,oa,ia,Zo,ab,sa,yr,lb,la=x(()=>{"use strict";Oe=2,rb="model",nb="model/README.md",ob="model/facts",ib="model/derived",Xo="model/derived/INDEX.yaml",mr="model/derived/relates.yaml";Eu=["system","container","component","code","task","adr"],ra=["contains","touched_by","correlates","relates","references","depends_on"],Tu=/^e_[0-9a-f]{8}$/;sb=["system","task","adr"];nt={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};na=2,oa=5,ia=50,Zo=2e3,ab=5e4,sa={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},yr={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};lb=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});function ub(t){return t==="DONE"}function db(t){return t==="AWAITING_EXTERNAL_FIX"?!1:ua.indexOf(t)>=ua.indexOf("IMPLEMENTING")}var ua,Nu=x(()=>{"use strict";ua=["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 fb(t){for(let e of da)if(e.phases.includes(t))return e.id;return null}function mb(t){for(let e of Ou)if(e.phases.includes(t))return e.id;return null}var da,pb,Ou,Lu=x(()=>{"use strict";da=[{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"]}],pb=da.flatMap(t=>t.phases),Ou=[{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 hb(t){return Mu.includes(t)?"planning":"implementation"}function Ht(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var pa,Mu,gb,fa=x(()=>{"use strict";pa=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat","observer","council","testing"],Mu=["draft","analysis","chat","observer","council"];gb=1});function Du(t,e){return e.toLowerCase().includes(t.toLowerCase())}function ga(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||Ku.every(o=>e.some(i=>Du(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 Gu){let i=n.find(s=>Du(o,s.id));if(i)return i.id}return n[0].id}function Wr(){return{default:null,roles:{}}}function yb(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():to[e]??Fu}function wb(t){let e=t?.provider;return typeof e=="string"&&e.trim().length>0?e.trim():Xe}function kb(t){let e=Wr();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 bb(t){let e=typeof t.provider=="string"&&t.provider.trim().length>0&&t.provider.trim()!==Xe;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 $b(t){if(!t)return Wr();try{let e=JSON.parse(t);if(!e||typeof e!="object")return Wr();let r=e,n=Wr();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 Wr()}}var Xe,ma,Pe,eo,ei,ti,Uu,Bu,ha,to,Fu,Gu,Ku,ya=x(()=>{"use strict";fa();Xe="claude",ma=[Xe],Pe="opus",eo="sonnet",ei="haiku",ti=[Pe,eo,ei],Uu="build-discovery",Bu=[Uu],ha=[...pa,...Bu],to={analyze:Pe,implement:Pe,"resolve-conflict":Pe,rework:Pe,estimate:eo,build:ei,"build-discovery":Pe,"code-review":Pe,draft:eo,index:Pe,backfill:Pe,analysis:Pe,chat:Pe,observer:Pe,council:Pe,testing:Pe},Fu=Pe,Gu=[Pe,eo,ei],Ku=Array.from(new Set(Object.values(to)))});function Ot(t){return vb.has(t)?!0:xb.some(e=>t.startsWith(e))}function ri(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function kr(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function ka(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function $a(t,e){let r=ri(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=kr(r.id,"id")??n;if(!wa.test(o))throw new Error(`id must match ${wa} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=kr(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=ri(r.env,"env");s={};for(let[d,m]of Object.entries(p)){if(!Je.test(d))throw new Error(`env name "${d}" must match ${Je}`);if(typeof m!="string"&&typeof m!="number"&&typeof m!="boolean")throw new Error(`env.${d} must be a scalar`);s[d]=String(m)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>Hu)throw new Error(`too many params (max ${Hu})`);let p=new Set;a=c.map((d,m)=>Sb(d,m,p))}let l=r.steps;if(!Array.isArray(l)||l.length===0)throw new Error("steps must be a non-empty list");if(l.length>Wu)throw new Error(`too many steps (max ${Wu})`);let u=l.map((p,d)=>{let m=ri(p,`steps[${d}]`),f=kr(m.run,`steps[${d}].run`);if(!f||f.trim().length===0)throw new Error(`steps[${d}].run is required`);let g=kr(m.name,`steps[${d}].name`),k=ka(m.timeout_sec,`steps[${d}].timeout_sec`);if(k!==void 0&&(!Number.isInteger(k)||k<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:f,...g?{name:g}:{},...k!==void 0?{timeout_sec:k}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function Sb(t,e,r){let n=ri(t,`params[${e}]`),o=kr(n.name,`params[${e}].name`);if(!o||!Je.test(o))throw new Error(`params[${e}].name must match ${Je}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let m=n.enum;if(!Array.isArray(m)||m.length===0||!m.every(f=>typeof f=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=m}let a=kr(n.label,`params[${e}].label`),c=kr(n.help,`params[${e}].help`),l=n.required===!0,u=ka(n.min,`params[${e}].min`),p=ka(n.max,`params[${e}].max`),d=n.default;if(d!=null&&typeof d!="string"&&typeof d!="number"&&typeof d!="boolean")throw new Error(`params[${e}].default must be a scalar`);return{name:o,type:i,...a?{label:a}:{},...c?{help:c}:{},...l?{required:!0}:{},...s?{enum:s}:{},...u!==void 0?{min:u}:{},...p!==void 0?{max:p}:{},...d!=null?{default:d}:{}}}function va(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 Je,vb,xb,ba,wa,Hu,Wu,xa=x(()=>{"use strict";Je=/^[A-Z][A-Z0-9_]*$/,vb=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),xb=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];ba=600,wa=/^[a-z0-9-]+$/,Hu=32,Wu=64});function qu(){return{primary:xe,context:xe,tasks:xe,docs:xe,code_comments:xe,chat:xe}}function Yu(t){return!t||t.trim().length===0||t.trim().toLowerCase()===xe}function Eb(t){if(typeof t!="string")return xe;let e=t.trim().replace(/\s+/g," ");return e.length===0||e.length>40||e.toLowerCase()===xe?xe:e}function Tb(t){let e=qu();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 ro)e[o]=Eb(n[o]);return e}function Ib(t){return ro.every(e=>Yu(t[e]))}var xe,ro,qr,no,Sa=x(()=>{"use strict";xe="auto",ro=["primary","context","tasks","docs","code_comments","chat"],qr=["English","Russian","German","Spanish","French","Portuguese","Italian","Chinese","Japanese","Korean"],no=40});function Ra(t=zu){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...Ra(r.groups));return e}function Vu(t,e){let r=JSON.stringify(e);return Ra().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function Ca(t){let e=Vu(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.type==="string"&&e.mustContain&&!i.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:e.maxLength!==void 0&&i.length>e.maxLength?{ok:!1,error:`${e.id} must be \u2264 ${e.maxLength} chars`}:{ok:!0,field:e,value:i}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}case"string_map":{if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,error:`${e.id} must be a name\u2192value map`};let i=Object.entries(r);if(i.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(i.length>Ea)return{ok:!1,error:`${e.id} must have \u2264 ${Ea} entries`};let s={};for(let[a,c]of i){if(!Je.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Je}`};if(Ot(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>Ta)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${Ta} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var Rb,Cb,Ea,Ta,Ia,zu,Xu=x(()=>{"use strict";xa();ya();la();Sa();Rb={primary:"Primary language",context:"Context documents",tasks:"Tracker issues",docs:"Repo documentation",code_comments:"Code comments",chat:"Agent chat"},Cb={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."},Ea=64,Ta=2e3,Ia=2e3,zu=[{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:[...ma],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:[...ti],help:"Overrides the recommended defaults for every role not listed below."},...ha.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...ti],help:`recommended: ${to[t]}`}))]}]},{id:"apply.style",label:"Commits & PRs",help:"Instructions for the AI agent on how to write commit messages and PR descriptions. Empty \u21D2 built-in templates.",fields:[{id:"apply.commit_style",file:"project.yaml",path:["apply","commit_style"],type:"string",label:"Commit message style",nullable:!0,multiline:!0,maxLength:Ia,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:Ia,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:"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:"gates",label:"Gates",help:"Approval gate before the pipeline starts (on by default; orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on (default), a task taken from Develop waits in the QUEUE for a single Confirm before the pipeline starts \u2014 the Confirm pulls in dependency closure and topologically orders the queue. Off \u21D2 conveyor: the task starts the pipeline immediately."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]},{id:"language",label:"Language",help:"Languages the agent writes in, per area. Empty \u21D2 auto: mirror the language of the user's material.",fields:ro.map(t=>({id:`language.${t}`,file:"project.yaml",path:["language",t],type:"string",label:Rb[t],nullable:!0,maxLength:40,suggestions:t==="chat"?[xe,...qr]:[...qr],help:Cb[t]}))},{id:"context.model",label:"Project map",help:"Parameters of the project map (built from git history by the CLI). Empty fields keep the defaults.",fields:[{id:"context.model.enabled",file:"regimen.yaml",path:["context","model","enabled"],type:"boolean",label:"Enable in the pipeline",nullable:!1,help:"When on, agents are asked to record intent annotations and (once available) receive an assembled context pack. Off \u21D2 the pipeline ignores the map entirely."},{id:"context.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 ${nt.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 ${nt.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 ${nt.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 ${nt.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 ${nt.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 ${nt.topK}.`}]},{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."}]}]});function Ju(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 Aa(t){let{name:e,body:r,origin:n}=t;if(!Pa.test(e))return{ok:!1,error:`role name must match ${Pa} (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=Ju(i.refs);if(a===null)return{ok:!1,error:"refs must be a list of non-empty paths"};if(a.length>10)return{ok:!1,error:"refs must list at most 10 files \u2014 a role is a narrow view"};for(let d of a)if(d.startsWith("/")||d.includes(".."))return{ok:!1,error:`ref "${d}" must be a path inside the Context Repo`};let c=Ju(i.scenarios);if(c===null)return{ok:!1,error:"scenarios must be a list"};let l=[];for(let d of c){if(!ni.includes(d))return{ok:!1,error:`unknown scenario "${d}" \u2014 one of: ${ni.join(", ")}`};l.includes(d)||l.push(d)}if(l.length===0)return{ok:!1,error:`scenarios must name at least one of: ${ni.join(", ")}`};let u=i.model;if(u!==void 0&&(typeof u!="string"||u.trim().length===0))return{ok:!1,error:"model must be a non-empty string when set"};let p=i.enabled;return p!==void 0&&typeof p!="boolean"?{ok:!1,error:"enabled must be true or false"}:{ok:!0,role:{name:e,description:s.trim(),...typeof u=="string"?{model:u.trim()}:{},refs:a,scenarios:l,enabled:p!==!1,body:r.trim(),origin:n}}}function _a(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 ja(t,e){return t.filter(r=>r.enabled&&r.scenarios.includes(e))}var ni,Pa,lA,uA,Zu=x(()=>{"use strict";ni=["plan_review","code_review","council"],Pa=/^[a-z][a-z0-9-]{1,39}$/,lA=10,uA=300});function Na(t){return Qu.includes(t)}function Oa(t){return`prompts/${t}.md`}var Qu,ed=x(()=>{"use strict";Qu=["analysis","analyze","backfill","build","chat","code-review","code-review-external","code-review-fix","council","draft","estimate","implement","index","observer","resolve-conflict","rework","testing"]});function Ma(t){if(!La.test(t.name))return{ok:!1,error:`skill directory name must match ${La}`};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 Da(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 rd(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(!Pb.test(n))return{ok:!1,error:`"${t}": expected <owner>/<repo>[@<40-hex sha>]`};let i=td.find(s=>s.repo.toLowerCase()===n.toLowerCase());return o&&!Ab.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 _b(t){let e=[],r=[],n=new Set;for(let o of t){if(!o.trim())continue;let i=rd(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 Nb(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(!jb.test(s)||!r.has(s.slice(s.indexOf("@")+1))){o.push(s);continue}n[s]=!0}}return{enabled:n,unknown:o}}var La,fA,td,Pb,Ab,jb,nd=x(()=>{"use strict";La=/^[a-z][a-z0-9-]{1,39}$/,fA=300;td=[{repo:"anthropics/skills",name:"anthropic-agent-skills"},{repo:"anthropics/claude-plugins-official",name:"claude-plugins-official"}],Pb=/^[A-Za-z0-9][\w.-]*\/[A-Za-z0-9][\w.-]*$/,Ab=/^[0-9a-f]{40}$/;jb=/^[A-Za-z0-9][\w.-]*@[A-Za-z0-9][\w.-]*$/});function od(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 Ob(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=od(n.order,e.length);if(o===null)return{ok:!1,error:"order must be a list of task keys"};for(let f of o)if(!r.has(f))return{ok:!1,error:`order names ${f}, which is not in this batch`};if(new Set(o).size!==o.length)return{ok:!1,error:"order repeats a task key"};let i=e.filter(f=>!o.includes(f));if(o.length>0&&i.length>0)return{ok:!1,error:`order omits ${i.join(", ")}`};let s=n.tasks,a=[];if(s!=null){if(!Array.isArray(s))return{ok:!1,error:"tasks must be a list"};for(let f of s){if(!f||typeof f!="object")return{ok:!1,error:"each task entry must be an object"};let g=f,k=typeof g.taskKey=="string"?g.taskKey.trim():"";if(!r.has(k))return{ok:!1,error:`tasks names ${k||"(empty)"}, which is not in this batch`};let h=od(g.after,e.length);if(h===null)return{ok:!1,error:`${k}: after must be a list of task keys`};for(let $ of h){if(!r.has($))return{ok:!1,error:`${k}: after names ${$}, not in this batch`};if($===k)return{ok:!1,error:`${k}: cannot come after itself`}}let w=typeof g.decisions=="string"?g.decisions.trim():"";a.push({taskKey:k,decisions:w.slice(0,4e3),after:h})}}let c=[],l=n.conflicts;if(Array.isArray(l))for(let f of l){if(!f||typeof f!="object")continue;let g=f,k=typeof g.taskKey=="string"?g.taskKey.trim():"",h=typeof g.adr=="string"?g.adr.trim():"",w=typeof g.detail=="string"?g.detail.trim():"";!r.has(k)||!w||c.push({taskKey:k,adr:h,detail:w.slice(0,4e3)})}let u=[],p=n.related;if(Array.isArray(p))for(let f of p){if(!f||typeof f!="object")continue;let g=f,k=typeof g.taskKey=="string"?g.taskKey.trim():"",h=typeof g.detail=="string"?g.detail.trim():"";!k||!h||u.push({taskKey:k,detail:h.slice(0,4e3)})}let d=typeof n.summary=="string"?n.summary.trim().slice(0,4e3):"",m=n.deferBehind===!0;return{ok:!0,plan:{order:o,tasks:a,conflicts:c,related:u,summary:d,deferBehind:m}}}var hA,gA,id=x(()=>{"use strict";hA=4e3,gA=4e3});function Lb(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 wA,sd=x(()=>{"use strict";wA=4e3});function Ub(t){let e=t.replace(/^#+\s*/,"").trim();for(let r of Mb)if(r.re.test(e))return{kind:r.kind,letter:r.letter};return null}function Ua(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=Ub(n),i=null;continue}let l=Db.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 Bb(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 Fb(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 ca(t){return kr(Pu(t))}function la(t){return kr(Au(t))}function Wr(t){return kr(_u(t))}var Oe,ob,ib,sb,ab,Zo,hr,Ru,na,Iu,cb,nt,oa,ia,sa,ei,lb,aa,wr,db,ua=x(()=>{"use strict";Oe=2,ob="model",ib="model/README.md",sb="model/facts",ab="model/derived",Zo="model/derived/INDEX.yaml",hr="model/derived/relates.yaml";Ru=["system","container","component","code","task","adr"],na=["contains","touched_by","correlates","relates","references","depends_on"],Iu=/^e_[0-9a-f]{8}$/;cb=["system","task","adr"];nt={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};oa=2,ia=5,sa=50,ei=2e3,lb=5e4,aa={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},wr={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};db=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});function pb(t){return t==="DONE"}function fb(t){return t==="AWAITING_EXTERNAL_FIX"?!1:da.indexOf(t)>=da.indexOf("IMPLEMENTING")}var da,Lu=x(()=>{"use strict";da=["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 hb(t){for(let e of pa)if(e.phases.includes(t))return e.id;return null}function gb(t){for(let e of Mu)if(e.phases.includes(t))return e.id;return null}var pa,mb,Mu,Du=x(()=>{"use strict";pa=[{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"]}],mb=pa.flatMap(t=>t.phases),Mu=[{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 yb(t){return Uu.includes(t)?"planning":"implementation"}function Ht(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var fa,Uu,wb,ma=x(()=>{"use strict";fa=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat","observer","council","testing"],Uu=["draft","analysis","chat","observer","council"];wb=1});function Bu(t,e){return e.toLowerCase().includes(t.toLowerCase())}function ya(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||Wu.every(o=>e.some(i=>Bu(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 Hu){let i=n.find(s=>Bu(o,s.id));if(i)return i.id}return n[0].id}function qr(){return{default:null,roles:{}}}function kb(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]??Ku}function bb(t){let e=t?.provider;return typeof e=="string"&&e.trim().length>0?e.trim():Xe}function $b(t){let e=qr();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 vb(t){let e=typeof t.provider=="string"&&t.provider.trim().length>0&&t.provider.trim()!==Xe;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 xb(t){if(!t)return qr();try{let e=JSON.parse(t);if(!e||typeof e!="object")return qr();let r=e,n=qr();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 qr()}}var Xe,ha,Pe,to,ri,ni,Fu,Gu,ga,ro,Ku,Hu,Wu,wa=x(()=>{"use strict";ma();Xe="claude",ha=[Xe],Pe="opus",to="sonnet",ri="haiku",ni=[Pe,to,ri],Fu="build-discovery",Gu=[Fu],ga=[...fa,...Gu],ro={analyze:Pe,implement:Pe,"resolve-conflict":Pe,rework:Pe,estimate:to,build:ri,"build-discovery":Pe,"code-review":Pe,draft:to,index:Pe,backfill:Pe,analysis:Pe,chat:Pe,observer:Pe,council:Pe,testing:Pe},Ku=Pe,Hu=[Pe,to,ri],Wu=Array.from(new Set(Object.values(ro)))});function Ot(t){return Sb.has(t)?!0:Eb.some(e=>t.startsWith(e))}function oi(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function br(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function ba(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function va(t,e){let r=oi(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=br(r.id,"id")??n;if(!ka.test(o))throw new Error(`id must match ${ka} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=br(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=oi(r.env,"env");s={};for(let[d,m]of Object.entries(p)){if(!Je.test(d))throw new Error(`env name "${d}" must match ${Je}`);if(typeof m!="string"&&typeof m!="number"&&typeof m!="boolean")throw new Error(`env.${d} must be a scalar`);s[d]=String(m)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>qu)throw new Error(`too many params (max ${qu})`);let p=new Set;a=c.map((d,m)=>Tb(d,m,p))}let l=r.steps;if(!Array.isArray(l)||l.length===0)throw new Error("steps must be a non-empty list");if(l.length>Yu)throw new Error(`too many steps (max ${Yu})`);let u=l.map((p,d)=>{let m=oi(p,`steps[${d}]`),f=br(m.run,`steps[${d}].run`);if(!f||f.trim().length===0)throw new Error(`steps[${d}].run is required`);let g=br(m.name,`steps[${d}].name`),k=ba(m.timeout_sec,`steps[${d}].timeout_sec`);if(k!==void 0&&(!Number.isInteger(k)||k<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:f,...g?{name:g}:{},...k!==void 0?{timeout_sec:k}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function Tb(t,e,r){let n=oi(t,`params[${e}]`),o=br(n.name,`params[${e}].name`);if(!o||!Je.test(o))throw new Error(`params[${e}].name must match ${Je}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let m=n.enum;if(!Array.isArray(m)||m.length===0||!m.every(f=>typeof f=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=m}let a=br(n.label,`params[${e}].label`),c=br(n.help,`params[${e}].help`),l=n.required===!0,u=ba(n.min,`params[${e}].min`),p=ba(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 xa(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 Je,Sb,Eb,$a,ka,qu,Yu,Sa=x(()=>{"use strict";Je=/^[A-Z][A-Z0-9_]*$/,Sb=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),Eb=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];$a=600,ka=/^[a-z0-9-]+$/,qu=32,Yu=64});function zu(){return{primary:$e,context:$e,tasks:$e,docs:$e,code_comments:$e,chat:$e,code_review:$e}}function Vu(t){return!t||t.trim().length===0||t.trim().toLowerCase()===$e}function Rb(t){if(typeof t!="string")return $e;let e=t.trim().replace(/\s+/g," ");return e.length===0||e.length>40||e.toLowerCase()===$e?$e:e}function Ib(t){let e=zu();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]=Rb(n[o]);return e}function Cb(t){return no.every(e=>Vu(t[e]))}var $e,no,Yr,oo,Ea=x(()=>{"use strict";$e="auto",no=["primary","context","tasks","docs","code_comments","chat","code_review"],Yr=["English","Russian","German","Spanish","French","Portuguese","Italian","Chinese","Japanese","Korean"],oo=40});function Ca(t=Xu){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...Ca(r.groups));return e}function Ju(t,e){let r=JSON.stringify(e);return Ca().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function Pa(t){let e=Ju(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.type==="string"&&e.mustContain&&!i.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:e.maxLength!==void 0&&i.length>e.maxLength?{ok:!1,error:`${e.id} must be \u2264 ${e.maxLength} chars`}:{ok:!0,field:e,value:i}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}case"string_map":{if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,error:`${e.id} must be a name\u2192value map`};let i=Object.entries(r);if(i.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(i.length>Ta)return{ok:!1,error:`${e.id} must have \u2264 ${Ta} entries`};let s={};for(let[a,c]of i){if(!Je.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Je}`};if(Ot(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>Ra)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${Ra} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var Pb,Ab,Ta,Ra,Ia,Xu,Zu=x(()=>{"use strict";Sa();wa();ua();Ea();Pb={primary:"Primary language",context:"Context documents",tasks:"Tracker issues",docs:"Repo documentation",code_comments:"Code comments",chat:"Agent chat",code_review:"Code review comments"},Ab={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."},Ta=64,Ra=2e3,Ia=2e3,Xu=[{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:[...ha],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:[...ni],help:"Overrides the recommended defaults for every role not listed below."},...ga.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...ni],help:`recommended: ${ro[t]}`}))]}]},{id:"apply.style",label:"Commits & PRs",help:"Instructions for the AI agent on how to write commit messages and PR descriptions. Empty \u21D2 built-in templates.",fields:[{id:"apply.commit_style",file:"project.yaml",path:["apply","commit_style"],type:"string",label:"Commit message style",nullable:!0,multiline:!0,maxLength:Ia,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:Ia,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:"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:"gates",label:"Gates",help:"Approval gate before the pipeline starts (on by default; orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on (default), a task taken from Develop waits in the QUEUE for a single Confirm before the pipeline starts \u2014 the Confirm pulls in dependency closure and topologically orders the queue. Off \u21D2 conveyor: the task starts the pipeline immediately."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]},{id:"language",label:"Language",help:"Languages the agent writes in, per area. Empty \u21D2 auto: mirror the language of the user's material.",fields:no.map(t=>({id:`language.${t}`,file:"project.yaml",path:["language",t],type:"string",label:Pb[t],nullable:!0,maxLength:40,suggestions:t==="chat"?[$e,...Yr]:[...Yr],help:Ab[t]}))},{id:"context.model",label:"Project map",help:"Parameters of the project map (built from git history by the CLI). Empty fields keep the defaults.",fields:[{id:"context.model.enabled",file:"regimen.yaml",path:["context","model","enabled"],type:"boolean",label:"Enable in the pipeline",nullable:!1,help:"When on, agents are asked to record intent annotations and (once available) receive an assembled context pack. Off \u21D2 the pipeline ignores the map entirely."},{id:"context.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 ${nt.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 ${nt.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 ${nt.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 ${nt.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 ${nt.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 ${nt.topK}.`}]},{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."}]}]});function Qu(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 _a(t){let{name:e,body:r,origin:n}=t;if(!Aa.test(e))return{ok:!1,error:`role name must match ${Aa} (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=Qu(i.refs);if(a===null)return{ok:!1,error:"refs must be a list of non-empty paths"};if(a.length>10)return{ok:!1,error:"refs must list at most 10 files \u2014 a role is a narrow view"};for(let d of a)if(d.startsWith("/")||d.includes(".."))return{ok:!1,error:`ref "${d}" must be a path inside the Context Repo`};let c=Qu(i.scenarios);if(c===null)return{ok:!1,error:"scenarios must be a list"};let l=[];for(let d of c){if(!ii.includes(d))return{ok:!1,error:`unknown scenario "${d}" \u2014 one of: ${ii.join(", ")}`};l.includes(d)||l.push(d)}if(l.length===0)return{ok:!1,error:`scenarios must name at least one of: ${ii.join(", ")}`};let u=i.model;if(u!==void 0&&(typeof u!="string"||u.trim().length===0))return{ok:!1,error:"model must be a non-empty string when set"};let p=i.enabled;return p!==void 0&&typeof p!="boolean"?{ok:!1,error:"enabled must be true or false"}:{ok:!0,role:{name:e,description:s.trim(),...typeof u=="string"?{model:u.trim()}:{},refs:a,scenarios:l,enabled:p!==!1,body:r.trim(),origin:n}}}function ja(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 Na(t,e){return t.filter(r=>r.enabled&&r.scenarios.includes(e))}var ii,Aa,fA,mA,ed=x(()=>{"use strict";ii=["plan_review","code_review","council"],Aa=/^[a-z][a-z0-9-]{1,39}$/,fA=10,mA=300});function Oa(t){return td.includes(t)}function La(t){return`prompts/${t}.md`}var td,rd=x(()=>{"use strict";td=["analysis","analyze","backfill","build","chat","code-review","code-review-external","code-review-fix","council","draft","estimate","implement","index","observer","resolve-conflict","review-comment","rework","testing"]});function Da(t){if(!Ma.test(t.name))return{ok:!1,error:`skill directory name must match ${Ma}`};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 Ua(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 od(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(!_b.test(n))return{ok:!1,error:`"${t}": expected <owner>/<repo>[@<40-hex sha>]`};let i=nd.find(s=>s.repo.toLowerCase()===n.toLowerCase());return o&&!jb.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 Nb(t){let e=[],r=[],n=new Set;for(let o of t){if(!o.trim())continue;let i=od(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 Lb(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(!Ob.test(s)||!r.has(s.slice(s.indexOf("@")+1))){o.push(s);continue}n[s]=!0}}return{enabled:n,unknown:o}}var Ma,yA,nd,_b,jb,Ob,id=x(()=>{"use strict";Ma=/^[a-z][a-z0-9-]{1,39}$/,yA=300;nd=[{repo:"anthropics/skills",name:"anthropic-agent-skills"},{repo:"anthropics/claude-plugins-official",name:"claude-plugins-official"}],_b=/^[A-Za-z0-9][\w.-]*\/[A-Za-z0-9][\w.-]*$/,jb=/^[0-9a-f]{40}$/;Ob=/^[A-Za-z0-9][\w.-]*@[A-Za-z0-9][\w.-]*$/});function sd(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 Mb(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=sd(n.order,e.length);if(o===null)return{ok:!1,error:"order must be a list of task keys"};for(let f of o)if(!r.has(f))return{ok:!1,error:`order names ${f}, which is not in this batch`};if(new Set(o).size!==o.length)return{ok:!1,error:"order repeats a task key"};let i=e.filter(f=>!o.includes(f));if(o.length>0&&i.length>0)return{ok:!1,error:`order omits ${i.join(", ")}`};let s=n.tasks,a=[];if(s!=null){if(!Array.isArray(s))return{ok:!1,error:"tasks must be a list"};for(let f of s){if(!f||typeof f!="object")return{ok:!1,error:"each task entry must be an object"};let g=f,k=typeof g.taskKey=="string"?g.taskKey.trim():"";if(!r.has(k))return{ok:!1,error:`tasks names ${k||"(empty)"}, which is not in this batch`};let h=sd(g.after,e.length);if(h===null)return{ok:!1,error:`${k}: after must be a list of task keys`};for(let $ of h){if(!r.has($))return{ok:!1,error:`${k}: after names ${$}, not in this batch`};if($===k)return{ok:!1,error:`${k}: cannot come after itself`}}let w=typeof g.decisions=="string"?g.decisions.trim():"";a.push({taskKey:k,decisions:w.slice(0,4e3),after:h})}}let c=[],l=n.conflicts;if(Array.isArray(l))for(let f of l){if(!f||typeof f!="object")continue;let g=f,k=typeof g.taskKey=="string"?g.taskKey.trim():"",h=typeof g.adr=="string"?g.adr.trim():"",w=typeof g.detail=="string"?g.detail.trim():"";!r.has(k)||!w||c.push({taskKey:k,adr:h,detail:w.slice(0,4e3)})}let u=[],p=n.related;if(Array.isArray(p))for(let f of p){if(!f||typeof f!="object")continue;let g=f,k=typeof g.taskKey=="string"?g.taskKey.trim():"",h=typeof g.detail=="string"?g.detail.trim():"";!k||!h||u.push({taskKey:k,detail:h.slice(0,4e3)})}let d=typeof n.summary=="string"?n.summary.trim().slice(0,4e3):"",m=n.deferBehind===!0;return{ok:!0,plan:{order:o,tasks:a,conflicts:c,related:u,summary:d,deferBehind:m}}}var kA,bA,ad=x(()=>{"use strict";kA=4e3,bA=4e3});function Db(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 vA,cd=x(()=>{"use strict";vA=4e3});function Fb(t){let e=t.replace(/^#+\s*/,"").trim();for(let r of Ub)if(r.re.test(e))return{kind:r.kind,letter:r.letter};return null}function Ba(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=Fb(n),i=null;continue}let l=Bb.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 Gb(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 Kb(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 Ba(t){let e=new Set;for(let r of t.items)if(r.kind==="procedure")for(let n of r.text.matchAll(Gb))e.add(n[1]);return[...e]}var Mb,Db,Gb,ad=x(()=>{"use strict";Mb=[{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"}],Db=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*(.*)$/;Gb=/`([a-z][a-z0-9-]{1,39})`/g});function Wb(t){let e=[],r=null;for(let o of t.split(`
12
- `)){let i=Hb.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 qb(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 Kb,Hb,cd=x(()=>{"use strict";Kb=["done","deviated","partial","dropped"],Hb=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*[—:-]?\s*(done|deviated|partial|dropped)\b\s*[—:-]?\s*(.*)$/i});var ld=x(()=>{"use strict"});var ud=x(()=>{"use strict"});var dd=x(()=>{"use strict"});function Fa(t){return`codepipe-host-${t}`}function Yb(t){let e=t.filter(r=>r!=="self-hosted");return`runs-on: [self-hosted${e.length?", "+e.join(", "):""}]`}var pd=x(()=>{"use strict"});function zb(t,e){return(t&&t.includes("<TASK_ID>")?t:fd).replace(/<TASK_ID>/g,e.toLowerCase())}function Vb(t,e){if(t)return`${t.replace(/\/+$/,"")}/issue/${encodeURIComponent(e)}`}function oo(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 Ga(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 Ka(t){if(!t.mirror)return t;let{mirror:e,...r}=t;return{...r,host:e.host,owner:e.owner,repoName:e.repoName}}function xt(t){return`${t}${md}`}var fd,Wt,md,hd=x(()=>{"use strict";fd="codepipe/<TASK_ID>";Wt=/^[a-z][a-z0-9-]{1,30}$/,md="-codepipe-ctx"});function Xb(t,e){return`${t}:${e}`}var gd=x(()=>{"use strict"});function yd(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)?"conflict":/^(build_failed|ci_failed)\b/.test(e)?"loop_exhausted":"error"}function Jb(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.to==="NEEDS_MANUAL")return r}return null}function Zb(t,e){if(t==="AWAITING_ANSWER")return{kind:"question"};if(t==="NEEDS_MANUAL"){let n=Jb(e)?.reason,o={kind:yd(n)};return n&&(o.reason=n),o}}var wd=x(()=>{"use strict"});function br(t){for(let e of kd){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var kd,bd=x(()=>{"use strict";kd=[{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 $d=x(()=>{"use strict"});function vd(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 Qb(t,e=Date.now()){return`${vd((e-t)/1e3)} ago`}function e$(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 xd=x(()=>{"use strict"});var Sd=x(()=>{"use strict"});function Ed(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function Wa(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=Ed(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if($r.test(r))return r;let n=Ed(t);return $r.test(n)?n:oi}function qa(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 zr(t){return`tasks/${t}/issue.yaml`}var Ha,io,oi,$r,ii,t$,so,Yr,Td=x(()=>{"use strict";Ha=["bug","feature","epic"],io="feature",oi="TASK",$r=/^[A-Z][A-Z0-9]{1,9}$/;ii={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},t$=ii.backlog,so="tracker/config.yaml",Yr="tracker/counter"});var r$,Id=x(()=>{"use strict";r$="youtrack"});function vr(t){let e=t.match(/^git@([^:/]+):/);if(e)return e[1]??null;let r=t.match(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)/);if(r)return r[1]??null;let n=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return n?n[1]??null:null}function ao(t){switch(t){case Vr.gitlab:return"oauth2";case Vr.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Vr,Lt,Rd=x(()=>{"use strict";Vr={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Lt="x-bitbucket-api-token-auth"});var Cd=x(()=>{"use strict"});var Pd=x(()=>{"use strict";Id();Rd();Cd()});var Ad={};ze(Ad,{ACTION_ID_RE:()=>wa,ACTION_STEP_DEFAULT_TIMEOUT_SEC:()=>ba,ALL_JOB_ROLES:()=>pa,ALL_MODEL_ROLE_KEYS:()=>ha,ANALYSIS_MAX_DRAFTS:()=>Ya,ANNOTATION_MAX_PER_TASK:()=>oa,BACKFILL_MAX_DRAFTS:()=>n$,BITBUCKET_API_TOKEN_GIT_USER:()=>Lt,BUILD_DISCOVERY:()=>Uu,COCHANGE_DEFAULTS:()=>nt,CODEPIPE_COMMANDS:()=>kd,COMMIT_STYLE_MAX_LENGTH:()=>Ia,CONTEXT_PACK_DECAY:()=>sa,CONTEXT_PACK_DEFAULTS:()=>yr,CONTEXT_REPO_SUFFIX:()=>md,CONTEXT_STAMP_FILE:()=>gt,CONTEXT_TEMPLATE_CHANGELOG:()=>qs,CONTEXT_TEMPLATE_VERSION:()=>vu,COUNCIL_MAX_ANSWER:()=>wA,DEFAULT_BRANCH_PATTERN:()=>fd,DEFAULT_HUB_URL:()=>mt,DEFAULT_INTERNAL_ISSUE_TYPE:()=>io,DEFAULT_INTERNAL_TRACKER_PREFIX:()=>oi,DEFAULT_LLM_PROVIDER:()=>Xe,DEFAULT_REGIMEN_ALIASES:()=>Ku,DEFAULT_TRACKER_PROVIDER:()=>r$,ENV_NAME_RE:()=>Je,FALLBACK_MODEL:()=>Fu,GIT_HOST_DOMAINS:()=>Vr,INTERNAL_ISSUE_TYPES:()=>Ha,INTERNAL_TRACKER_CONFIG_PATH:()=>so,INTERNAL_TRACKER_COUNTER_PATH:()=>Yr,INTERNAL_TRACKER_DEFAULT_STATUS:()=>t$,INTERNAL_TRACKER_PREFIX_RE:()=>$r,INTERNAL_TRACKER_STATUSES:()=>ii,LANE_PHASES:()=>pb,LANE_SEGMENTS:()=>da,LANGUAGE_AUTO:()=>xe,LANGUAGE_SUGGESTIONS:()=>qr,LANGUAGE_VALUE_MAX_LENGTH:()=>no,LEGACY_CONTEXT_STAMP_FILE:()=>Gr,LLM_PROVIDER_SUGGESTIONS:()=>ma,MIN_SUPPORTED_PROTOCOL:()=>ku,MODEL_ALIAS_SUGGESTIONS:()=>ti,MODEL_DERIVED_DIR:()=>ib,MODEL_DERIVED_INDEX_PATH:()=>Xo,MODEL_DIR:()=>rb,MODEL_EDGE_KINDS:()=>ra,MODEL_ENTITY_ID_RE:()=>Tu,MODEL_FACTS_DIR:()=>ob,MODEL_FAMILY_PREFERENCE:()=>Gu,MODEL_HAIKU:()=>ei,MODEL_LEVELS:()=>Eu,MODEL_OPUS:()=>Pe,MODEL_README_PATH:()=>nb,MODEL_RELATES_PATH:()=>mr,MODEL_SEARCH_MAX_LIMIT:()=>ia,MODEL_SEARCH_MAX_ROWS:()=>ab,MODEL_SEARCH_ROW_TEXT_MAX:()=>Zo,MODEL_SONNET:()=>eo,MODEL_SUB_ROLES:()=>Bu,OBSERVER_MAX_DECISION:()=>hA,OBSERVER_MAX_SUMMARY:()=>gA,OFFICIAL_MARKETPLACES:()=>td,PHASES:()=>ua,PIPELINE_COLUMNS:()=>Ou,PLANNING_LANE_MAX_JOBS:()=>gb,PLANNING_ROLES:()=>Mu,PLATFORM_VERSION:()=>Ve,PROJECT_ID_RE:()=>Wt,PROJECT_LANGUAGE_SECTIONS:()=>ro,PROJECT_MODEL_FORMAT_VERSION:()=>Oe,PROJECT_SETTINGS_MANIFEST:()=>zu,PROMPT_ROLES:()=>Qu,PROTOCOL_VERSION:()=>ht,RECOMMENDED_ROLE_MODELS:()=>to,RELATES_MIN_OVERLAP:()=>na,ROLE_MAX_DESCRIPTION:()=>uA,ROLE_MAX_REFS:()=>lA,ROLE_NAME_RE:()=>Pa,ROLE_SCENARIOS:()=>ni,SKILL_MAX_DESCRIPTION:()=>fA,SKILL_NAME_RE:()=>La,SOLUTION_STATUSES:()=>Kb,STRING_MAP_MAX_ENTRIES:()=>Ea,STRING_MAP_MAX_VALUE_LENGTH:()=>Ta,additionsSince:()=>zs,ago:()=>Qb,attentionFor:()=>Zb,autoLanguageConfig:()=>qu,autoModelDefault:()=>ga,canonicalizeModelEdgeSheet:()=>Iu,canonicalizeModelIdentityTable:()=>Cu,canonicalizeModelShard:()=>Ru,canonicalizeModelTaskEvent:()=>Pu,changesSince:()=>Vs,classifyAttentionReason:()=>yd,compilePlanRework:()=>Fb,contextRepoName:()=>xt,deserializeModelConfig:()=>$b,emptyModelConfig:()=>Wr,enabledPluginsSetting:()=>Nb,extractLanguageConfig:()=>Tb,findSettingField:()=>Vu,firstFreeInternalTrackerPrefix:()=>qa,flattenSettingFields:()=>Ra,fmtDuration:()=>vd,fmtUptime:()=>e$,ghRunnerHostLabel:()=>Fa,ghRunnerRunsOnSnippet:()=>Yb,gitCloneUrlDomain:()=>vr,httpsTokenUser:()=>ao,internalIssueYamlPath:()=>zr,isAllAutoLanguage:()=>Ib,isAutoLanguage:()=>Yu,isBodyEditFrozen:()=>db,isModelEntityId:()=>Jo,isPromptRole:()=>Na,isProtocolCompatible:()=>zn,isReservedEnvName:()=>Ot,isTerminalPhase:()=>ub,isValidBranchName:()=>oo,jobLane:()=>hb,laneSegmentForPhase:()=>fb,makeTaskId:()=>Xb,mergeRoles:()=>_a,mergeSkills:()=>Da,mismatchedIds:()=>Bb,modelAnnotationPath:()=>Zs,modelComponentSlug:()=>Su,modelCorrelatesPath:()=>Qs,modelEventPath:()=>hr,modelIdentityPath:()=>Jn,modelNodeKey:()=>ye,modelShardNeedsRebuild:()=>cb,modelStructureShardPath:()=>ta,modelTaskNodeKey:()=>ve,modelTouchedPath:()=>ea,parseActionDefinition:()=>$a,parseCodepipeCommand:()=>br,parseContextStamp:()=>Ys,parseMarketplaceSource:()=>rd,parseMarketplaces:()=>_b,parseModelConfig:()=>kb,parseModelNodeKey:()=>re,parsePlanItems:()=>Ua,parseRepoMirror:()=>Ga,parseSolutionItems:()=>Wb,pipelineColumnForPhase:()=>mb,pipelineRepoSpec:()=>Ka,prescribedSkills:()=>Ba,promptOverridePath:()=>Oa,renderContextStamp:()=>Vn,resolveBranchName:()=>zb,resolveModelForRole:()=>yb,resolveProvider:()=>wb,rolesForScenario:()=>ja,serializeModelConfig:()=>bb,serializeModelEdgeSheet:()=>gr,serializeModelIdentityTable:()=>ca,serializeModelShard:()=>aa,serializeModelTaskEvent:()=>Hr,serializeModelYaml:()=>wr,solutionCoverage:()=>qb,suggestInternalTrackerPrefix:()=>Wa,validateActionInput:()=>va,validateCouncilVerdict:()=>Lb,validateModelEdgeSheet:()=>Zn,validateModelIdentityTable:()=>Qn,validateModelShard:()=>jt,validateModelTaskEvent:()=>Nt,validateObserverPlan:()=>Ob,validateRoleDefinition:()=>Aa,validateSettingEdit:()=>Ca,validateSkill:()=>Ma,youtrackIssueUrl:()=>Vb,zeroUsage:()=>Ht});var Ya,n$,F=x(()=>{"use strict";bu();$u();xu();la();Nu();Lu();fa();ya();Xu();Sa();xa();Zu();ed();nd();id();sd();ad();cd();ld();ud();dd();pd();hd();gd();wd();bd();$d();xd();Sd();Td();Pd();Ya=20,n$=15});function V(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Fe=x(()=>{"use strict"});import{existsSync as o$,readFileSync as i$,readdirSync as s$}from"node:fs";import{dirname as a$,join as za}from"node:path";import{parse as c$}from"yaml";function l$(t=process.cwd()){let e=t;for(;;){if(o$(za(e,ot,"project.yaml")))return e;let r=a$(e);if(r===e)return null;e=r}}function u$(t){return za(t,ot)}function Ae(t=process.cwd()){let e=l$(t);if(!e)return null;let r=u$(e),n=d$(i$(za(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function _d(t,e,r){return s$(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 Xr(t,e=process.cwd()){try{let r=Ae(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function d$(t){let e=c$(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),n=String(e.name??r),o=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of o){if(!s||typeof s!="object")continue;let a=s,c=String(a.repo??a.repoName??""),l=String(a.name??c);if(!l||!c)continue;let u=a.host,p=u==="bitbucket"?"bitbucket":u==="gitlab"?"gitlab":"github",d=Ga(a.mirror);i.push({name:l,host:p,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l),...d?{mirror:d}:{}})}return{projectId:r,name:n,repos:i}}function si(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}var ot,it=x(()=>{"use strict";F();ot=".codepipe"});import{homedir as jd}from"node:os";import{mkdirSync as p$,readFileSync as f$,writeFileSync as m$,existsSync as Va}from"node:fs";import{dirname as Od,join as ai,resolve as h$}from"node:path";import{fileURLToPath as g$}from"node:url";function Ld(t){let e=ai(Nd,".env");if(Va(e)&&process.loadEnvFile(e),t){let r=ai(Nd,"profiles",t,".env");Va(r)&&process.loadEnvFile(r)}}function Jr(t){let e=V("CONFIG");return e||(t?ai(jd(),".codepipe","profiles",t,"config.json"):ai(jd(),".codepipe","config.json"))}function wt(t){let e=Jr(t);if(!Va(e))return null;let r=f$(e,"utf-8");return JSON.parse(r)}function Mt(t,e){let r=Jr(e);p$(Od(r),{recursive:!0}),m$(r,JSON.stringify(t,null,2)+`
14
- `,{mode:384})}function Zr(t){if(t)return{cfg:st(t),profile:t};let e;try{e=Ae()?.spec.projectId||void 0}catch{}if(e){let r=wt(e);if(r)return console.log(`[profile] ${e} \u2014 resolved from this folder's workspace`),{cfg:r,profile:e};console.error(`this folder is the workspace of project '${e}', but that CLI profile is not initialised on this machine \u2014 run \`codepipe init\` here (or pass --profile).`),process.exit(1)}return{cfg:st(void 0),profile:void 0}}function st(t){let e=wt(t);if(!e){let r=t?`codepipe init --profile ${t} --hub <url> --token <token> --project ${t}`:"codepipe init --hub <url> --token <token> --project <id>";console.error(t?`CLI profile '${t}' is not initialised. run \`${r}\` first.`:`CLI is not initialised. run \`${r}\` first.`),process.exit(1)}return e.projectId||(console.error(`config at ${Jr(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var Nd,Ge=x(()=>{"use strict";Fe();it();Nd=h$(Od(g$(import.meta.url)),"..")});import{homedir as Md}from"node:os";import{existsSync as Dd,mkdirSync as Ud,readFileSync as Bd,writeFileSync as Fd}from"node:fs";import{dirname as Gd,join as Kd}from"node:path";function Hd(t,e,r){let n=q(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},ae(n)}function Wd(t,e){let r=q(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],ae(r),!0)}function qd(t){return Object.keys(q(t)?.secrets??{}).sort()}function ci(t,e,r){let n=q(t);if(!n)return"mismatch";let o=n.sandboxPins??{},i=o[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(o[e]=r,n.sandboxPins=o,ae(n),"pinned")}function Yd(t,e){let r=q(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],ae(r),!0):!1}function St(t){return Kd(Md(),".codepipe","secrets",`${t}.json`)}function q(t){let e=St(t);return Dd(e)?JSON.parse(Bd(e,"utf-8")):null}function ae(t){let e=St(t.projectId);Ud(Gd(e),{recursive:!0}),Fd(e,JSON.stringify(t,null,2)+`
15
- `,{mode:384})}function li(){return Kd(Md(),".codepipe","shared.json")}function Xa(){let t=li();return Dd(t)?JSON.parse(Bd(t,"utf-8")):null}function zd(t){let e=li();Ud(Gd(e),{recursive:!0}),Fd(e,JSON.stringify(t,null,2)+`
16
- `,{mode:384})}function Qr(t){let e=q(t)?.claude?.oauthToken;return e||Xa()?.claude?.oauthToken}function co(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 Ja){let n=e[r];n&&!process.env[r]&&(process.env[r]=n)}}function en(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var Ja,fe=x(()=>{"use strict";Ja=["GH_TOKEN","BITBUCKET_EMAIL","BITBUCKET_API_TOKEN","GITLAB_TOKEN","YOUTRACK_URL","YOUTRACK_TOKEN"]});import{appendFileSync as y$,existsSync as Xd,mkdirSync as w$,renameSync as Jd,statSync as k$,unlinkSync as b$}from"node:fs";import{Writable as $$}from"node:stream";import{join as v$}from"node:path";function ui(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=x$(process.env[`${t}_MAX_BYTES`]??String(Zd.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):Zd.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function x$(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 di(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(S$(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 S$(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:E$(o)).join(" ");return`${r} ${t} ${n}`}function E$(t){try{return JSON.stringify(t)}catch{return String(t)}}var Zd,tn,Za=x(()=>{"use strict";Zd={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},tn=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&w$(e.dir,{recursive:!0}),this.currentPath=v$(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
11
+ `)}function Fa(t){let e=new Set;for(let r of t.items)if(r.kind==="procedure")for(let n of r.text.matchAll(Hb))e.add(n[1]);return[...e]}var Ub,Bb,Hb,ld=x(()=>{"use strict";Ub=[{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"}],Bb=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*(.*)$/;Hb=/`([a-z][a-z0-9-]{1,39})`/g});function Yb(t){let e=[],r=null;for(let o of t.split(`
12
+ `)){let i=qb.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 zb(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 Wb,qb,ud=x(()=>{"use strict";Wb=["done","deviated","partial","dropped"],qb=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*[—:-]?\s*(done|deviated|partial|dropped)\b\s*[—:-]?\s*(.*)$/i});var dd=x(()=>{"use strict"});var pd=x(()=>{"use strict"});var fd=x(()=>{"use strict"});function Ga(t){return`codepipe-host-${t}`}function Vb(t){let e=t.filter(r=>r!=="self-hosted");return`runs-on: [self-hosted${e.length?", "+e.join(", "):""}]`}var md=x(()=>{"use strict"});function Xb(t,e){return(t&&t.includes("<TASK_ID>")?t:hd).replace(/<TASK_ID>/g,e.toLowerCase())}function Jb(t,e){if(t)return`${t.replace(/\/+$/,"")}/issue/${encodeURIComponent(e)}`}function io(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 Ka(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 Ha(t){if(!t.mirror)return t;let{mirror:e,...r}=t;return{...r,host:e.host,owner:e.owner,repoName:e.repoName}}function xt(t){return`${t}${gd}`}var hd,Wt,gd,yd=x(()=>{"use strict";hd="codepipe/<TASK_ID>";Wt=/^[a-z][a-z0-9-]{1,30}$/,gd="-codepipe-ctx"});function Zb(t,e){return`${t}:${e}`}var wd=x(()=>{"use strict"});function kd(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)?"conflict":/^(build_failed|ci_failed)\b/.test(e)?"loop_exhausted":"error"}function Qb(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.to==="NEEDS_MANUAL")return r}return null}function e$(t,e){if(t==="AWAITING_ANSWER")return{kind:"question"};if(t==="NEEDS_MANUAL"){let n=Qb(e)?.reason,o={kind:kd(n)};return n&&(o.reason=n),o}}var bd=x(()=>{"use strict"});function $r(t){for(let e of $d){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var $d,vd=x(()=>{"use strict";$d=[{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 xd=x(()=>{"use strict"});function Sd(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 t$(t,e=Date.now()){return`${Sd((e-t)/1e3)} ago`}function r$(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 Ed=x(()=>{"use strict"});var Td=x(()=>{"use strict"});function Rd(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function qa(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=Rd(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(vr.test(r))return r;let n=Rd(t);return vr.test(n)?n:si}function Ya(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 Vr(t){return`tasks/${t}/issue.yaml`}var Wa,so,si,vr,ai,n$,ao,zr,Id=x(()=>{"use strict";Wa=["bug","feature","epic"],so="feature",si="TASK",vr=/^[A-Z][A-Z0-9]{1,9}$/;ai={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},n$=ai.backlog,ao="tracker/config.yaml",zr="tracker/counter"});var o$,Cd=x(()=>{"use strict";o$="youtrack"});function xr(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 co(t){switch(t){case Xr.gitlab:return"oauth2";case Xr.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Xr,Lt,Pd=x(()=>{"use strict";Xr={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Lt="x-bitbucket-api-token-auth"});var Ad=x(()=>{"use strict"});var _d=x(()=>{"use strict";Cd();Pd();Ad()});var jd={};ze(jd,{ACTION_ID_RE:()=>ka,ACTION_STEP_DEFAULT_TIMEOUT_SEC:()=>$a,ALL_JOB_ROLES:()=>fa,ALL_MODEL_ROLE_KEYS:()=>ga,ANALYSIS_MAX_DRAFTS:()=>za,ANNOTATION_MAX_PER_TASK:()=>ia,BACKFILL_MAX_DRAFTS:()=>i$,BITBUCKET_API_TOKEN_GIT_USER:()=>Lt,BUILD_DISCOVERY:()=>Fu,COCHANGE_DEFAULTS:()=>nt,CODEPIPE_COMMANDS:()=>$d,COMMIT_STYLE_MAX_LENGTH:()=>Ia,CONTEXT_PACK_DECAY:()=>aa,CONTEXT_PACK_DEFAULTS:()=>wr,CONTEXT_REPO_SUFFIX:()=>gd,CONTEXT_STAMP_FILE:()=>gt,CONTEXT_TEMPLATE_CHANGELOG:()=>Ys,CONTEXT_TEMPLATE_VERSION:()=>Su,COUNCIL_MAX_ANSWER:()=>vA,DEFAULT_BRANCH_PATTERN:()=>hd,DEFAULT_HUB_URL:()=>mt,DEFAULT_INTERNAL_ISSUE_TYPE:()=>so,DEFAULT_INTERNAL_TRACKER_PREFIX:()=>si,DEFAULT_LLM_PROVIDER:()=>Xe,DEFAULT_REGIMEN_ALIASES:()=>Wu,DEFAULT_TRACKER_PROVIDER:()=>o$,ENV_NAME_RE:()=>Je,FALLBACK_MODEL:()=>Ku,GIT_HOST_DOMAINS:()=>Xr,INTERNAL_ISSUE_TYPES:()=>Wa,INTERNAL_TRACKER_CONFIG_PATH:()=>ao,INTERNAL_TRACKER_COUNTER_PATH:()=>zr,INTERNAL_TRACKER_DEFAULT_STATUS:()=>n$,INTERNAL_TRACKER_PREFIX_RE:()=>vr,INTERNAL_TRACKER_STATUSES:()=>ai,LANE_PHASES:()=>mb,LANE_SEGMENTS:()=>pa,LANGUAGE_AUTO:()=>$e,LANGUAGE_SUGGESTIONS:()=>Yr,LANGUAGE_VALUE_MAX_LENGTH:()=>oo,LEGACY_CONTEXT_STAMP_FILE:()=>Kr,LLM_PROVIDER_SUGGESTIONS:()=>ha,MIN_SUPPORTED_PROTOCOL:()=>$u,MODEL_ALIAS_SUGGESTIONS:()=>ni,MODEL_DERIVED_DIR:()=>ab,MODEL_DERIVED_INDEX_PATH:()=>Zo,MODEL_DIR:()=>ob,MODEL_EDGE_KINDS:()=>na,MODEL_ENTITY_ID_RE:()=>Iu,MODEL_FACTS_DIR:()=>sb,MODEL_FAMILY_PREFERENCE:()=>Hu,MODEL_HAIKU:()=>ri,MODEL_LEVELS:()=>Ru,MODEL_OPUS:()=>Pe,MODEL_README_PATH:()=>ib,MODEL_RELATES_PATH:()=>hr,MODEL_SEARCH_MAX_LIMIT:()=>sa,MODEL_SEARCH_MAX_ROWS:()=>lb,MODEL_SEARCH_ROW_TEXT_MAX:()=>ei,MODEL_SONNET:()=>to,MODEL_SUB_ROLES:()=>Gu,OBSERVER_MAX_DECISION:()=>kA,OBSERVER_MAX_SUMMARY:()=>bA,OFFICIAL_MARKETPLACES:()=>nd,PHASES:()=>da,PIPELINE_COLUMNS:()=>Mu,PLANNING_LANE_MAX_JOBS:()=>wb,PLANNING_ROLES:()=>Uu,PLATFORM_VERSION:()=>Ve,PROJECT_ID_RE:()=>Wt,PROJECT_LANGUAGE_SECTIONS:()=>no,PROJECT_MODEL_FORMAT_VERSION:()=>Oe,PROJECT_SETTINGS_MANIFEST:()=>Xu,PROMPT_ROLES:()=>td,PROTOCOL_VERSION:()=>ht,RECOMMENDED_ROLE_MODELS:()=>ro,RELATES_MIN_OVERLAP:()=>oa,ROLE_MAX_DESCRIPTION:()=>mA,ROLE_MAX_REFS:()=>fA,ROLE_NAME_RE:()=>Aa,ROLE_SCENARIOS:()=>ii,SKILL_MAX_DESCRIPTION:()=>yA,SKILL_NAME_RE:()=>Ma,SOLUTION_STATUSES:()=>Wb,STRING_MAP_MAX_ENTRIES:()=>Ta,STRING_MAP_MAX_VALUE_LENGTH:()=>Ra,additionsSince:()=>Vs,ago:()=>t$,attentionFor:()=>e$,autoLanguageConfig:()=>zu,autoModelDefault:()=>ya,canonicalizeModelEdgeSheet:()=>Cu,canonicalizeModelIdentityTable:()=>Au,canonicalizeModelShard:()=>Pu,canonicalizeModelTaskEvent:()=>_u,changesSince:()=>Xs,classifyAttentionReason:()=>kd,compilePlanRework:()=>Kb,contextRepoName:()=>xt,deserializeModelConfig:()=>xb,emptyModelConfig:()=>qr,enabledPluginsSetting:()=>Lb,extractLanguageConfig:()=>Ib,findSettingField:()=>Ju,firstFreeInternalTrackerPrefix:()=>Ya,flattenSettingFields:()=>Ca,fmtDuration:()=>Sd,fmtUptime:()=>r$,ghRunnerHostLabel:()=>Ga,ghRunnerRunsOnSnippet:()=>Vb,gitCloneUrlDomain:()=>xr,httpsTokenUser:()=>co,internalIssueYamlPath:()=>Vr,isAllAutoLanguage:()=>Cb,isAutoLanguage:()=>Vu,isBodyEditFrozen:()=>fb,isModelEntityId:()=>Qo,isPromptRole:()=>Oa,isProtocolCompatible:()=>Vn,isReservedEnvName:()=>Ot,isTerminalPhase:()=>pb,isValidBranchName:()=>io,jobLane:()=>yb,laneSegmentForPhase:()=>hb,makeTaskId:()=>Zb,mergeRoles:()=>ja,mergeSkills:()=>Ua,mismatchedIds:()=>Gb,modelAnnotationPath:()=>Qs,modelComponentSlug:()=>Tu,modelCorrelatesPath:()=>ea,modelEventPath:()=>gr,modelIdentityPath:()=>Zn,modelNodeKey:()=>ye,modelShardNeedsRebuild:()=>ub,modelStructureShardPath:()=>ra,modelTaskNodeKey:()=>xe,modelTouchedPath:()=>ta,parseActionDefinition:()=>va,parseCodepipeCommand:()=>$r,parseContextStamp:()=>zs,parseMarketplaceSource:()=>od,parseMarketplaces:()=>Nb,parseModelConfig:()=>$b,parseModelNodeKey:()=>re,parsePlanItems:()=>Ba,parseRepoMirror:()=>Ka,parseSolutionItems:()=>Yb,pipelineColumnForPhase:()=>gb,pipelineRepoSpec:()=>Ha,prescribedSkills:()=>Fa,promptOverridePath:()=>La,renderContextStamp:()=>Xn,resolveBranchName:()=>Xb,resolveModelForRole:()=>kb,resolveProvider:()=>bb,rolesForScenario:()=>Na,serializeModelConfig:()=>vb,serializeModelEdgeSheet:()=>yr,serializeModelIdentityTable:()=>la,serializeModelShard:()=>ca,serializeModelTaskEvent:()=>Wr,serializeModelYaml:()=>kr,solutionCoverage:()=>zb,suggestInternalTrackerPrefix:()=>qa,validateActionInput:()=>xa,validateCouncilVerdict:()=>Db,validateModelEdgeSheet:()=>Qn,validateModelIdentityTable:()=>eo,validateModelShard:()=>jt,validateModelTaskEvent:()=>Nt,validateObserverPlan:()=>Mb,validateRoleDefinition:()=>_a,validateSettingEdit:()=>Pa,validateSkill:()=>Da,youtrackIssueUrl:()=>Jb,zeroUsage:()=>Ht});var za,i$,F=x(()=>{"use strict";vu();xu();Eu();ua();Lu();Du();ma();wa();Zu();Ea();Sa();ed();rd();id();ad();cd();ld();ud();dd();pd();fd();md();yd();wd();bd();vd();xd();Ed();Td();Id();_d();za=20,i$=15});function X(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Fe=x(()=>{"use strict"});import{existsSync as s$,readFileSync as a$,readdirSync as c$}from"node:fs";import{dirname as l$,join as Va}from"node:path";import{parse as u$}from"yaml";function d$(t=process.cwd()){let e=t;for(;;){if(s$(Va(e,ot,"project.yaml")))return e;let r=l$(e);if(r===e)return null;e=r}}function p$(t){return Va(t,ot)}function Ae(t=process.cwd()){let e=d$(t);if(!e)return null;let r=p$(e),n=f$(a$(Va(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function Nd(t,e,r){return c$(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 Jr(t,e=process.cwd()){try{let r=Ae(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function f$(t){let e=u$(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),n=String(e.name??r),o=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of o){if(!s||typeof s!="object")continue;let a=s,c=String(a.repo??a.repoName??""),l=String(a.name??c);if(!l||!c)continue;let u=a.host,p=u==="bitbucket"?"bitbucket":u==="gitlab"?"gitlab":"github",d=Ka(a.mirror);i.push({name:l,host:p,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l),...d?{mirror:d}:{}})}return{projectId:r,name:n,repos:i}}function ci(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}var ot,it=x(()=>{"use strict";F();ot=".codepipe"});import{homedir as Od}from"node:os";import{mkdirSync as m$,readFileSync as h$,writeFileSync as g$,existsSync as Xa}from"node:fs";import{dirname as Md,join as li,resolve as y$}from"node:path";import{fileURLToPath as w$}from"node:url";function Dd(t){let e=li(Ld,".env");if(Xa(e)&&process.loadEnvFile(e),t){let r=li(Ld,"profiles",t,".env");Xa(r)&&process.loadEnvFile(r)}}function Zr(t){let e=X("CONFIG");return e||(t?li(Od(),".codepipe","profiles",t,"config.json"):li(Od(),".codepipe","config.json"))}function wt(t){let e=Zr(t);if(!Xa(e))return null;let r=h$(e,"utf-8");return JSON.parse(r)}function Mt(t,e){let r=Zr(e);m$(Md(r),{recursive:!0}),g$(r,JSON.stringify(t,null,2)+`
14
+ `,{mode:384})}function Qr(t){if(t)return{cfg:st(t),profile:t};let e;try{e=Ae()?.spec.projectId||void 0}catch{}if(e){let r=wt(e);if(r)return console.log(`[profile] ${e} \u2014 resolved from this folder's workspace`),{cfg:r,profile:e};console.error(`this folder is the workspace of project '${e}', but that CLI profile is not initialised on this machine \u2014 run \`codepipe init\` here (or pass --profile).`),process.exit(1)}return{cfg:st(void 0),profile:void 0}}function st(t){let e=wt(t);if(!e){let r=t?`codepipe init --profile ${t} --hub <url> --token <token> --project ${t}`:"codepipe init --hub <url> --token <token> --project <id>";console.error(t?`CLI profile '${t}' is not initialised. run \`${r}\` first.`:`CLI is not initialised. run \`${r}\` first.`),process.exit(1)}return e.projectId||(console.error(`config at ${Zr(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var Ld,Ge=x(()=>{"use strict";Fe();it();Ld=y$(Md(w$(import.meta.url)),"..")});import{homedir as Ud}from"node:os";import{existsSync as Bd,mkdirSync as Fd,readFileSync as Gd,writeFileSync as Kd}from"node:fs";import{dirname as Hd,join as Wd}from"node:path";function qd(t,e,r){let n=q(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},ae(n)}function Yd(t,e){let r=q(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],ae(r),!0)}function zd(t){return Object.keys(q(t)?.secrets??{}).sort()}function ui(t,e,r){let n=q(t);if(!n)return"mismatch";let o=n.sandboxPins??{},i=o[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(o[e]=r,n.sandboxPins=o,ae(n),"pinned")}function Vd(t,e){let r=q(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],ae(r),!0):!1}function St(t){return Wd(Ud(),".codepipe","secrets",`${t}.json`)}function q(t){let e=St(t);return Bd(e)?JSON.parse(Gd(e,"utf-8")):null}function ae(t){let e=St(t.projectId);Fd(Hd(e),{recursive:!0}),Kd(e,JSON.stringify(t,null,2)+`
15
+ `,{mode:384})}function di(){return Wd(Ud(),".codepipe","shared.json")}function Ja(){let t=di();return Bd(t)?JSON.parse(Gd(t,"utf-8")):null}function Xd(t){let e=di();Fd(Hd(e),{recursive:!0}),Kd(e,JSON.stringify(t,null,2)+`
16
+ `,{mode:384})}function en(t){let e=q(t)?.claude?.oauthToken;return e||Ja()?.claude?.oauthToken}function lo(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 Za){let n=e[r];n&&!process.env[r]&&(process.env[r]=n)}}function tn(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var Za,me=x(()=>{"use strict";Za=["GH_TOKEN","BITBUCKET_EMAIL","BITBUCKET_API_TOKEN","GITLAB_TOKEN","YOUTRACK_URL","YOUTRACK_TOKEN"]});import{appendFileSync as k$,existsSync as Zd,mkdirSync as b$,renameSync as Qd,statSync as $$,unlinkSync as v$}from"node:fs";import{Writable as x$}from"node:stream";import{join as S$}from"node:path";function pi(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=E$(process.env[`${t}_MAX_BYTES`]??String(ep.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):ep.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function E$(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(T$(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 T$(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:R$(o)).join(" ");return`${r} ${t} ${n}`}function R$(t){try{return JSON.stringify(t)}catch{return String(t)}}var ep,rn,Qa=x(()=>{"use strict";ep={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},rn=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&b$(e.dir,{recursive:!0}),this.currentPath=S$(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
17
17
  `)?e:e+`
18
- `;y$(this.currentPath,r,"utf-8")}asWritable(){return new $$({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||!Xd(this.currentPath)||k$(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;Xd(n)&&(r>=this.cfg.maxFiles?b$(n):Jd(n,`${this.currentPath}.${r+1}`))}Jd(this.currentPath,`${this.currentPath}.1`)}}}});function fi(t){return t===429||t>=500}function tp(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
19
- `+t.slice(t.length-e)}async function qt(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),pi);try{let i;try{i=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new at(`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(fi(i.status))throw new at(`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 mi(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),pi);try{let s;try{s=await fetch(n,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},signal:o.signal})}catch(c){throw new at(`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(fi(s.status))throw new at(`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 Yt(t,e,r){let n=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",o=new AbortController,i=setTimeout(()=>o.abort(),pi);try{let s;try{s=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new at(`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(fi(s.status))throw new at(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await _$(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 _$(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function hi(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=rp.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: ${rp.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function zt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),pi);try{let n;try{n=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"},signal:e.signal})}catch(i){throw new at(`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(fi(n.status))throw new at(`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 np(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 j$(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 ec(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 lo(t,e){let r=Ka(e);if(!e.mirror)return{spec:r,host:Sr(r)};let n=t?q(t)?.mirrorWrite:void 0;return{spec:r,host:Sr(r,n?.token?{token:n.token,...n.email?{bitbucketEmail:n.email}:{}}:void 0)}}function Sr(t,e){if(t.host==="github"){let r=e?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(r)return new rc(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 tc(r,n)}if(t.host==="gitlab"){let r=e?.token??process.env.GITLAB_TOKEN;if(r)return new nc(r)}return new oc}var xr,at,pi,rp,tc,rc,nc,oc,Vt=x(()=>{"use strict";F();fe();xr=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},at=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},pi=5e3;rp=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];tc=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 xr(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){let i=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:o})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:n}})});if(!o.ok)throw new Error(`bitbucket comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},rc=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 xr(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),a=!1,c=!1,l=!1;if(i.ok){let u=await i.json();for(let p of u.check_runs??[])l=!0,p.status!=="completed"?a=!0:p.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(p.conclusion)&&(c=!0)}if(s.ok){let u=await s.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${o}/pulls/${r}`,{headers:n});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${o}/actions/runs?head_sha=${a}&per_page=20`,{headers:n});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],u=[];for(let p of l.filter(d=>d.conclusion&&i.includes(d.conclusion))){let d=await fetch(`${o}/actions/runs/${p.id}/jobs?per_page=50`,{headers:n});if(!d.ok)continue;let m=(await d.json()).jobs??[];for(let f of m.filter(g=>g.conclusion==="failure")){let g=await fetch(`${o}/actions/jobs/${f.id}/logs`,{headers:n});if(!g.ok)continue;let k=await g.text();u.push(`### CI job: ${f.name}
18
+ `;k$(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||!Zd(this.currentPath)||$$(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;Zd(n)&&(r>=this.cfg.maxFiles?v$(n):Qd(n,`${this.currentPath}.${r+1}`))}Qd(this.currentPath,`${this.currentPath}.1`)}}}});function hi(t){return t===429||t>=500}function np(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
19
+ `+t.slice(t.length-e)}async function qt(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),mi);try{let i;try{i=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new at(`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 at(`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 gi(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),mi);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 at(`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 at(`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 Yt(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(),mi);try{let s;try{s=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new at(`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 at(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await N$(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 N$(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function yi(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=op.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: ${op.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function zt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),mi);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 at(`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 at(`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 ip(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 O$(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 tc(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 uo(t,e){let r=Ha(e);if(!e.mirror)return{spec:r,host:Er(r)};let n=t?q(t)?.mirrorWrite:void 0;return{spec:r,host:Er(r,n?.token?{token:n.token,...n.email?{bitbucketEmail:n.email}:{}}:void 0)}}function Er(t,e){if(t.host==="github"){let r=e?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(r)return new nc(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 rc(r,n)}if(t.host==="gitlab"){let r=e?.token??process.env.GITLAB_TOKEN;if(r)return new oc(r)}return new ic}var Sr,at,mi,op,rc,nc,oc,ic,Vt=x(()=>{"use strict";F();me();Sr=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},at=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},mi=5e3;op=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];rc=class{constructor(e,r){this.email=e;this.apiToken=r}name="bitbucket";authHeader(){return"Basic "+Buffer.from(`${this.email}:${this.apiToken}`).toString("base64")}async createPullRequest(e,r){let n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json"},body:JSON.stringify({title:r.title,description:r.body,source:{branch:{name:r.branchName}},destination:{branch:{name:r.baseBranch}}})});if(!n.ok)throw new Error(`bitbucket pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.links?.html?.href??"",number:o.id}}async findOpenPrByBranch(e,r){let n=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${n}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!o.ok)return null;let s=(await o.json()).values?.[0];return s?{url:s.links?.html?.href??"",number:s.id}:null}async getPullRequest(e,r){let n=`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(o.status===404)throw new Sr(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){let i=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:o})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:n}})});if(!o.ok)throw new Error(`bitbucket comment PR #${r}: ${o.status} ${await o.text()}`)}async 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()}`)}},nc=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json"},body:JSON.stringify({title:r.title,body:r.body,head:r.branchName,base:r.baseBranch})});if(!n.ok)throw new Error(`github pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.html_url,number:o.number}}async findOpenPrByBranch(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls?state=open&head=${encodeURIComponent(`${e.owner}:${r}`)}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.html_url,number:i.number}:null}async getPullRequest(e,r){let n=`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(o.status===404)throw new Sr(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),a=!1,c=!1,l=!1;if(i.ok){let u=await i.json();for(let p of u.check_runs??[])l=!0,p.status!=="completed"?a=!0:p.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(p.conclusion)&&(c=!0)}if(s.ok){let u=await s.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${o}/pulls/${r}`,{headers:n});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${o}/actions/runs?head_sha=${a}&per_page=20`,{headers:n});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],u=[];for(let p of l.filter(d=>d.conclusion&&i.includes(d.conclusion))){let d=await fetch(`${o}/actions/runs/${p.id}/jobs?per_page=50`,{headers:n});if(!d.ok)continue;let m=(await d.json()).jobs??[];for(let f of m.filter(g=>g.conclusion==="failure")){let g=await fetch(`${o}/actions/jobs/${f.id}/logs`,{headers:n});if(!g.ok)continue;let k=await g.text();u.push(`### CI job: ${f.name}
20
20
 
21
- ${tp(k,8e3)}`)}}return u.length===0?void 0:tp(u.join(`
21
+ ${np(k,8e3)}`)}}return u.length===0?void 0:np(u.join(`
22
22
 
23
- `),16e3)}catch{return}}async mergePR(e,r,n,o){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},nc=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 xr(`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=j$(i.head_pipeline?.status??i.pipeline?.status),a=i.merge_status==="cannot_be_merged"||i.has_conflicts===!0?"conflict":i.merge_status==="can_be_merged"&&i.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:s,mergeable:a}}async mergePR(e,r,n,o){let i=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,s,a=await fetch(i,{headers:this.headers()});if(a.ok){let u=await a.json().catch(()=>null);s=u?.sha??u?.diff_refs?.head_sha}let c=await fetch(`${i}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:n==="squash",should_remove_source_branch:o,...s?{sha:s}:{}})});if(!c.ok)throw new Error(`gitlab merge MR !${r}: ${c.status} ${await c.text()}`);let l=await c.json().catch(()=>null);return l?.merge_commit_sha?{mergedSha:l.merge_commit_sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`gitlab comment MR !${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!o.ok)throw new Error(`gitlab close MR !${r}: ${o.status} ${await o.text()}`)}};oc=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(ec(e,r,"merge"))}async closePR(e,r,n){throw new Error(ec(e,r,"close"))}async addPRComment(e,r,n){throw new Error(ec(e,r,"comment"))}}});import{X509Certificate as sp}from"node:crypto";import{readFileSync as N$}from"node:fs";import Xt from"node:tls";function O$(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function lp(t=cp){if(op)return;op=!0;let e=V("EXTRA_CA_FILE");if(!(!e||!ap))try{let r=O$(N$(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Xt.setDefaultCACertificates([...Xt.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 up(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 L$(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
24
- `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function M$(t,e,r){return new Promise((n,o)=>{let i=Xt.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 sp(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function ic(t,e,r){return new Promise(n=>{let o=Xt.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 D$(t){try{let e=await fetch(t);return e.ok?new sp(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function dp(t,e=443,r=cp){let n=`${t}:${e}`,o=ip.get(n);if(o)return o;let i=U$(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return ip.set(n,i),i}async function U$(t,e,r){if(!ap)return!1;let n=8e3;if(await ic(t,e,n))return!0;let o=await M$(t,e,n),i=Xt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=L$(o);if(!c)break;let l=await D$(c);if(!l)break;if(s.push(l.toString()),Xt.setDefaultCACertificates([...i,...s]),await ic(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 ic(t,e,n)}var ap,op,ip,cp,pp=x(()=>{"use strict";Fe();ap=typeof Xt.getCACertificates=="function"&&typeof Xt.setDefaultCACertificates=="function",op=!1,ip=new Map,cp=t=>console.warn(t)});function gp(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function ct(t,e,r){lp();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(up(s)&&await dp(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function B$(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function F$(){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 sc(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=F$(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await ct(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&&B$(l.status,u)){await fp(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await fp(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Jt(t){let e;try{e=await ct(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 yp(t){try{let e=await ct(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function G$(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=mp.get(o);if(i)return i;let s=await ct(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 mp.set(o,l.id),l.id}async function wp(t,e,r,n=uo){let o=await G$(t,e,r,n);await sc(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 kp(t,e,r){return await(await sc(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function bp(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await sc(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function $p(t,e){let r=hp.get(e);if(r)return r;let n=await ct(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 hp.set(e,i.id),i.id}async function vp(t,e,r,n,o,i=uo){let s=await $p(t,e),a=await ct(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 xp(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await ct(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 Tp(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 Ip(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 Rp(t,e){let r=e.stageField??uo,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=${Ep}&$top=200`,s=await ct(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=>Ap(c,r))}async function Cp(t,e,r=uo){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Ep}`,o=await ct(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Ap(await o.json(),r)}async function Pp(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${H$}&$top=500`,o=await ct(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=Tp(s.attachments);return c&&(a.attachments=c),a})}function W$(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 Ap(t,e=uo){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=Tp(t.attachments);a&&(s.attachments=a);let c=W$(t.links);return c&&(s.links=c),s}async function _p(t,e){let r=await q$(t,e);return r.length>0?r:Y$(t,e)}async function q$(t,e){let r=await $p(t,e),n=await ct(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:jp(s.bundle)});return i}async function Y$(t,e){let r=`project: ${e}`,n=await ct(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:jp(s.projectCustomField?.bundle)});return i}function jp(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var fp,uo,mp,hp,Sp,K$,Ep,H$,Er=x(()=>{"use strict";pp();fp=t=>new Promise(e=>setTimeout(e,t));uo="Stage",mp=new Map;hp=new Map;Sp="attachments(id,name,url,size,mimeType)",K$="links(direction,linkType(name),issues(idReadable))",Ep=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Sp},${K$}`,H$=`id,text,created,author(login),${Sp}`});function kt(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function rn(t){return t instanceof at}async function Np(t,e){let r=q(t),n=[],o=[],i=()=>Date.now();if(e?.trackerProvider==="internal")n.push({name:"tracker",ok:!0,detail:"built-in tracker"});else if(r?.youtrack?.url&&r.youtrack.token)try{let c=await Jt({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:kt(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:kt(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 qt(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){rn(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:kt(c)}),o.push({kind:"github",present:!0,ok:!1,detail:kt(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 Yt(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){rn(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:kt(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:kt(c),checkedAt:i()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await zt(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){rn(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:kt(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:kt(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 mi(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){rn(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:kt(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await mi(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){rn(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:kt(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await mi(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){rn(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:i()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:kt(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=Qr(t);if(!a)n.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),o.push({kind:"claude",present:!1,checkedAt:i()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:i()});else{let c=await Dt(a);if(c==="invalid"){let l="Claude 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 Dt(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:z$,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 Op(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 z$,nn=x(()=>{"use strict";fe();Vt();Er();z$="claude-haiku-4-5-20251001"});import V$ from"node:http";import ac from"node:crypto";function gi(){let t=cc(ac.randomBytes(32)),e=cc(ac.createHash("sha256").update(t).digest()),r=cc(ac.randomBytes(32));return{verifier:t,challenge:e,state:r}}function uc(t){let e=new URL(X$);return e.search=new URLSearchParams({response_type:"code",client_id:Lp,redirect_uri:t.redirectUri,scope:Z$,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function ev(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 Mp(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 tv(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 dc(t){let e=await fetch(J$,{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:Lp,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return tv(await e.json())}async function pc(t){let e=t.timeoutMs??Q$,r=V$.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=uc({redirectUri:o,challenge:t.challenge,state:t.state}),s,a=new Promise((l,u)=>{s=setTimeout(()=>u(new Error("no-callback")),e),r.on("request",(p,d)=>{let m=new URL(p.url??"/",o);if(m.pathname!=="/callback"){d.statusCode=404,d.end();return}clearTimeout(s),d.setHeader("content-type","text/html"),d.end("<h3>Authorized \u2014 you can close this tab.</h3>");try{l(ev(m.searchParams,t.state))}catch(f){u(f)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>dc({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function Dp(t){let e=await pc(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
25
- ${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var Lp,X$,J$,lc,Z$,Q$,cc,fc=x(()=>{"use strict";Lp="9d1c250a-e61b-44d9-88ed-5944d1962f5e",X$="https://platform.claude.com/oauth/authorize",J$="https://platform.claude.com/v1/oauth/token",lc="https://platform.claude.com/oauth/code/callback",Z$="org:create_api_key user:profile user:inference",Q$=12e4,cc=t=>Buffer.from(t).toString("base64url")});import{spawn as rv}from"node:child_process";function Tr(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=rv(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var yi=x(()=>{"use strict"});import{existsSync as Zt,mkdirSync as zp,readFileSync as gc,writeFileSync as on}from"node:fs";import{homedir as dv}from"node:os";import{join as Et}from"node:path";import{simpleGit as pv}from"simple-git";function fo(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=Et(t,o);Zt(s)||(on(s,i),r.push(o))}return r}function Qt(t,e,r){let n=Et(dv(),".codepipe","profiles",t,"context-config");return zp(n,{recursive:!0}),on(Et(n,"project.yaml"),e.projectYaml),on(Et(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function bi(t,e,r){if(Zt(e))for(let n of sn){let o=Et(e,n),i=Et(t,n);if(!(!Zt(o)||Zt(i)))try{on(i,gc(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 an(t){let e=Et(t,".gitignore"),r=Zt(e)?gc(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(sn.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
23
+ `),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()}`)}},oc=class{constructor(e){this.token=e}name="gitlab";pid(e){return encodeURIComponent(`${e.owner}/${e.repoName}`)}headers(e=!1){let r={"PRIVATE-TOKEN":this.token,"User-Agent":"codepipe-cli"};return e&&(r["Content-Type"]="application/json"),r}async createPullRequest(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({source_branch:r.branchName,target_branch:r.baseBranch,title:r.title,description:r.body})});if(!n.ok)throw new Error(`gitlab mr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.web_url??"",number:o.iid}}async findOpenPrByBranch(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests?state=opened&source_branch=${encodeURIComponent(r)}`,{headers:this.headers()});if(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.web_url??"",number:i.iid}:null}async getPullRequest(e,r){let n=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,o=await fetch(n,{method:"GET",headers:this.headers()});if(o.status===404)throw new Sr(`GitLab MR not found: ${e.owner}/${e.repoName}!${r}`);if(o.status>=400)throw new Error(`gitlab GET merge_requests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="merged")return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed"||i.state==="locked")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=O$(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()}`)}};ic=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(tc(e,r,"merge"))}async closePR(e,r,n){throw new Error(tc(e,r,"close"))}async addPRComment(e,r,n){throw new Error(tc(e,r,"comment"))}}});import{X509Certificate as cp}from"node:crypto";import{readFileSync as L$}from"node:fs";import Xt from"node:tls";function M$(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function dp(t=up){if(sp)return;sp=!0;let e=X("EXTRA_CA_FILE");if(!(!e||!lp))try{let r=M$(L$(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Xt.setDefaultCACertificates([...Xt.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 pp(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 D$(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
24
+ `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function U$(t,e,r){return new Promise((n,o)=>{let i=Xt.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 cp(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function sc(t,e,r){return new Promise(n=>{let o=Xt.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 B$(t){try{let e=await fetch(t);return e.ok?new cp(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function fp(t,e=443,r=up){let n=`${t}:${e}`,o=ap.get(n);if(o)return o;let i=F$(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return ap.set(n,i),i}async function F$(t,e,r){if(!lp)return!1;let n=8e3;if(await sc(t,e,n))return!0;let o=await U$(t,e,n),i=Xt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=D$(o);if(!c)break;let l=await B$(c);if(!l)break;if(s.push(l.toString()),Xt.setDefaultCACertificates([...i,...s]),await sc(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 sc(t,e,n)}var lp,sp,ap,up,mp=x(()=>{"use strict";Fe();lp=typeof Xt.getCACertificates=="function"&&typeof Xt.setDefaultCACertificates=="function",sp=!1,ap=new Map,up=t=>console.warn(t)});function wp(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function ct(t,e,r){dp();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(pp(s)&&await fp(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function G$(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function K$(){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 ac(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=K$(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await ct(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&&G$(l.status,u)){await hp(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await hp(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Jt(t){let e;try{e=await ct(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 kp(t){try{let e=await ct(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function H$(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=gp.get(o);if(i)return i;let s=await ct(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 gp.set(o,l.id),l.id}async function bp(t,e,r,n=po){let o=await H$(t,e,r,n);await ac(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 $p(t,e,r){return await(await ac(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function vp(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await ac(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function xp(t,e){let r=yp.get(e);if(r)return r;let n=await ct(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 yp.set(e,i.id),i.id}async function Sp(t,e,r,n,o,i=po){let s=await xp(t,e),a=await ct(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 Ep(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await ct(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 Ip(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 Cp(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 Pp(t,e){let r=e.stageField??po,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=${Rp}&$top=200`,s=await ct(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=>jp(c,r))}async function Ap(t,e,r=po){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Rp}`,o=await ct(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return jp(await o.json(),r)}async function _p(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${q$}&$top=500`,o=await ct(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=Ip(s.attachments);return c&&(a.attachments=c),a})}function Y$(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 jp(t,e=po){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=Ip(t.attachments);a&&(s.attachments=a);let c=Y$(t.links);return c&&(s.links=c),s}async function Np(t,e){let r=await z$(t,e);return r.length>0?r:V$(t,e)}async function z$(t,e){let r=await xp(t,e),n=await ct(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:Op(s.bundle)});return i}async function V$(t,e){let r=`project: ${e}`,n=await ct(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:Op(s.projectCustomField?.bundle)});return i}function Op(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var hp,po,gp,yp,Tp,W$,Rp,q$,Tr=x(()=>{"use strict";mp();hp=t=>new Promise(e=>setTimeout(e,t));po="Stage",gp=new Map;yp=new Map;Tp="attachments(id,name,url,size,mimeType)",W$="links(direction,linkType(name),issues(idReadable))",Rp=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Tp},${W$}`,q$=`id,text,created,author(login),${Tp}`});function kt(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function nn(t){return t instanceof at}async function Lp(t,e){let r=q(t),n=[],o=[],i=()=>Date.now();if(e?.trackerProvider==="internal")n.push({name:"tracker",ok:!0,detail:"built-in tracker"});else if(r?.youtrack?.url&&r.youtrack.token)try{let c=await Jt({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:kt(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:kt(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 qt(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){nn(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:kt(c)}),o.push({kind:"github",present:!0,ok:!1,detail:kt(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 Yt(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){nn(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:kt(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:kt(c),checkedAt:i()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await zt(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){nn(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:kt(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:kt(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 gi(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){nn(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:kt(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await gi(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){nn(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:kt(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await gi(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){nn(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:i()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:kt(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=en(t);if(!a)n.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),o.push({kind:"claude",present:!1,checkedAt:i()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:i()});else{let c=await Dt(a);if(c==="invalid"){let l="Claude 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 Dt(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:X$,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 Mp(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 X$,on=x(()=>{"use strict";me();Vt();Tr();X$="claude-haiku-4-5-20251001"});import J$ from"node:http";import cc from"node:crypto";function wi(){let t=lc(cc.randomBytes(32)),e=lc(cc.createHash("sha256").update(t).digest()),r=lc(cc.randomBytes(32));return{verifier:t,challenge:e,state:r}}function dc(t){let e=new URL(Z$);return e.search=new URLSearchParams({response_type:"code",client_id:Dp,redirect_uri:t.redirectUri,scope:ev,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function rv(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 Up(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 nv(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 pc(t){let e=await fetch(Q$,{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:Dp,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return nv(await e.json())}async function fc(t){let e=t.timeoutMs??tv,r=J$.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=dc({redirectUri:o,challenge:t.challenge,state:t.state}),s,a=new Promise((l,u)=>{s=setTimeout(()=>u(new Error("no-callback")),e),r.on("request",(p,d)=>{let m=new URL(p.url??"/",o);if(m.pathname!=="/callback"){d.statusCode=404,d.end();return}clearTimeout(s),d.setHeader("content-type","text/html"),d.end("<h3>Authorized \u2014 you can close this tab.</h3>");try{l(rv(m.searchParams,t.state))}catch(f){u(f)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>pc({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function Bp(t){let e=await fc(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
25
+ ${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var Dp,Z$,Q$,uc,ev,tv,lc,mc=x(()=>{"use strict";Dp="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Z$="https://platform.claude.com/oauth/authorize",Q$="https://platform.claude.com/v1/oauth/token",uc="https://platform.claude.com/oauth/code/callback",ev="org:create_api_key user:profile user:inference",tv=12e4,lc=t=>Buffer.from(t).toString("base64url")});import{spawn as ov}from"node:child_process";function Rr(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=ov(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var ki=x(()=>{"use strict"});import{existsSync as Zt,mkdirSync as Xp,readFileSync as yc,writeFileSync as sn}from"node:fs";import{homedir as fv}from"node:os";import{join as Et}from"node:path";import{simpleGit as mv}from"simple-git";function mo(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=Et(t,o);Zt(s)||(sn(s,i),r.push(o))}return r}function Qt(t,e,r){let n=Et(fv(),".codepipe","profiles",t,"context-config");return Xp(n,{recursive:!0}),sn(Et(n,"project.yaml"),e.projectYaml),sn(Et(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function vi(t,e,r){if(Zt(e))for(let n of an){let o=Et(e,n),i=Et(t,n);if(!(!Zt(o)||Zt(i)))try{sn(i,yc(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 cn(t){let e=Et(t,".gitignore"),r=Zt(e)?yc(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(an.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
26
26
  `)?"":`
27
- `;return on(e,r+i+fv.join(`
27
+ `;return sn(e,r+i+hv.join(`
28
28
  `)+`
29
- `),!0}async function Vp(t,e){try{if(!Zt(Et(t,".git")))return;let r=pv(t),n=(await r.raw(["ls-files","--",...sn])).split(`
30
- `).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;an(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 kc(t),e.info(`[config] migrated ${n.join(", ")} out of the Context Repo \u2014 the local copies are now the config`)}catch(r){e.warn(`[config] context-config migration failed (will retry on next start): ${r instanceof Error?r.message:String(r)}`)}}function yc(t){let e=new Map;for(let r of sn){let n=Et(t,r);Zt(n)&&e.set(r,gc(n))}return e}function wc(t,e){zp(t,{recursive:!0});for(let[r,n]of e){let o=Et(t,r);Zt(o)||on(o,n)}}var sn,fv,Ut=x(()=>{"use strict";lt();sn=["project.yaml","regimen.yaml"];fv=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as mv,mkdirSync as hv,rmSync as gv,writeFileSync as bc}from"node:fs";import{dirname as yv,isAbsolute as wv,join as Zp,normalize as xi}from"node:path";import{simpleGit as Qp}from"simple-git";async function $c(t,e){let r=xi(t),o=(vi.get(r)??Promise.resolve()).catch(()=>{}).then(e);vi.set(r,o);try{return await o}finally{vi.get(r)===o&&vi.delete(r)}}async function Re(t,e,r){return $c(t,()=>vc(t,e,r))}async function vc(t,e,r){if(!mv(Zp(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=Se(t,a.path);if(a.deleted){gv(c,{force:!0});continue}hv(yv(c),{recursive:!0}),a.encoding==="base64"?bc(c,Buffer.from(a.content,"base64")):bc(c,a.content)}let n=Qp(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+=$i)await n.raw(["add","-A","-f","--",...o.slice(a,a+$i)]);for(let a=0;a<i.length;a+=$i)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...i.slice(a,a+$i)]);await n.raw(["reset","-q","--",...sn]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await kc(t))}async function kc(t){let e=Qp(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=Xp;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 vv(e);if(i.length>0&&i.every(a=>kv.has(a)||Jp.test(a)||bv.test(a))){for(let a of i)Jp.test(a)?await $v(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 ${Xp} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function $v(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(`
31
- `)){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);bc(Se(e,r),i.join(`
29
+ `),!0}async function Jp(t,e){try{if(!Zt(Et(t,".git")))return;let r=mv(t),n=(await r.raw(["ls-files","--",...an])).split(`
30
+ `).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;cn(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 bc(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 wc(t){let e=new Map;for(let r of an){let n=Et(t,r);Zt(n)&&e.set(r,yc(n))}return e}function kc(t,e){Xp(t,{recursive:!0});for(let[r,n]of e){let o=Et(t,r);Zt(o)||sn(o,n)}}var an,hv,Ut=x(()=>{"use strict";lt();an=["project.yaml","regimen.yaml"];hv=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as gv,mkdirSync as yv,rmSync as wv,writeFileSync as $c}from"node:fs";import{dirname as kv,isAbsolute as bv,join as ef,normalize as Ei}from"node:path";import{simpleGit as tf}from"simple-git";async function vc(t,e){let r=Ei(t),o=(Si.get(r)??Promise.resolve()).catch(()=>{}).then(e);Si.set(r,o);try{return await o}finally{Si.get(r)===o&&Si.delete(r)}}async function Ie(t,e,r){return vc(t,()=>xc(t,e,r))}async function xc(t,e,r){if(!gv(ef(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=Se(t,a.path);if(a.deleted){wv(c,{force:!0});continue}yv(kv(c),{recursive:!0}),a.encoding==="base64"?$c(c,Buffer.from(a.content,"base64")):$c(c,a.content)}let n=tf(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+=xi)await n.raw(["add","-A","-f","--",...o.slice(a,a+xi)]);for(let a=0;a<i.length;a+=xi)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...i.slice(a,a+xi)]);await n.raw(["reset","-q","--",...an]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await bc(t))}async function bc(t){let e=tf(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=Zp;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 Sv(e);if(i.length>0&&i.every(a=>$v.has(a)||Qp.test(a)||vv.test(a))){for(let a of i)Qp.test(a)?await xv(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 ${Zp} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function xv(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(`
31
+ `)){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);$c(Se(e,r),i.join(`
32
32
  `)+(i.length>0?`
33
- `:""))}async function vv(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
34
- `).map(r=>r.trim()).filter(Boolean)}function Se(t,e){if(wv(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=xi(Zp(t,e)),n=xi(t+"/");if(r!==xi(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var Xp,kv,bv,Jp,$i,vi,lt=x(()=>{"use strict";Ut();Xp=3,kv=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),bv=/^model\/derived\//,Jp=/^tasks\/[^/]+\/comments\.jsonl$/,$i=500,vi=new Map});import{cpSync as Av,existsSync as mo,mkdirSync as nf,readFileSync as _v,readdirSync as jv,rmSync as of,statSync as Nv,writeFileSync as Ov}from"node:fs";import{join as er}from"node:path";function cn(t,e,r){let n=er(t,"skills"),o=er(e,".claude","skills"),i=er(o,Lv),s=Mv(i),a={written:[],removed:[],skipped:[]},c=Dv(n);for(let u of s)c.includes(u)||(of(er(o,u),{recursive:!0,force:!0}),a.removed.push(u));let l=[];for(let u of c){let p=er(o,u);if(mo(p)&&!s.includes(u)){a.skipped.push(u);continue}nf(o,{recursive:!0}),of(p,{recursive:!0,force:!0}),Av(er(n,u),p,{recursive:!0}),l.push(u),a.written.push(u)}(l.length>0||a.removed.length>0||mo(i))&&(nf(o,{recursive:!0}),Ov(i,JSON.stringify({managed:l.sort()},null,2)+`
35
- `)),(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 Mv(t){if(!mo(t))return[];try{let e=JSON.parse(_v(t,"utf-8"));return Array.isArray(e.managed)?e.managed.filter(r=>typeof r=="string"):[]}catch{return[]}}function Dv(t){return mo(t)?jv(t).filter(e=>{if(e.startsWith("."))return!1;let r=er(t,e);try{return Nv(r).isDirectory()&&mo(er(r,"SKILL.md"))}catch{return!1}}):[]}var Lv,Si=x(()=>{"use strict";Lv=".codepipe-managed.json"});import{existsSync as tr,readFileSync as ln,readdirSync as lf}from"node:fs";import{join as Sc}from"node:path";import{simpleGit as uf}from"simple-git";import{parse as df}from"yaml";function pf(t){try{let e=Se(t,so);if(!tr(e))return null;let r=df(ln(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!$r.test(n)?null:{prefix:n}}catch{return null}}function ff(t){return`# Built-in tracker configuration \u2014 shared by every team member.
33
+ `:""))}async function Sv(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
34
+ `).map(r=>r.trim()).filter(Boolean)}function Se(t,e){if(bv(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=Ei(ef(t,e)),n=Ei(t+"/");if(r!==Ei(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var Zp,$v,vv,Qp,xi,Si,lt=x(()=>{"use strict";Ut();Zp=3,$v=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),vv=/^model\/derived\//,Qp=/^tasks\/[^/]+\/comments\.jsonl$/,xi=500,Si=new Map});import{cpSync as jv,existsSync as ho,mkdirSync as sf,readFileSync as Nv,readdirSync as Ov,rmSync as af,statSync as Lv,writeFileSync as Mv}from"node:fs";import{join as er}from"node:path";function ln(t,e,r){let n=er(t,"skills"),o=er(e,".claude","skills"),i=er(o,Dv),s=Uv(i),a={written:[],removed:[],skipped:[]},c=Bv(n);for(let u of s)c.includes(u)||(af(er(o,u),{recursive:!0,force:!0}),a.removed.push(u));let l=[];for(let u of c){let p=er(o,u);if(ho(p)&&!s.includes(u)){a.skipped.push(u);continue}sf(o,{recursive:!0}),af(p,{recursive:!0,force:!0}),jv(er(n,u),p,{recursive:!0}),l.push(u),a.written.push(u)}(l.length>0||a.removed.length>0||ho(i))&&(sf(o,{recursive:!0}),Mv(i,JSON.stringify({managed:l.sort()},null,2)+`
35
+ `)),(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 Uv(t){if(!ho(t))return[];try{let e=JSON.parse(Nv(t,"utf-8"));return Array.isArray(e.managed)?e.managed.filter(r=>typeof r=="string"):[]}catch{return[]}}function Bv(t){return ho(t)?Ov(t).filter(e=>{if(e.startsWith("."))return!1;let r=er(t,e);try{return Lv(r).isDirectory()&&ho(er(r,"SKILL.md"))}catch{return!1}}):[]}var Dv,Ti=x(()=>{"use strict";Dv=".codepipe-managed.json"});import{existsSync as tr,readFileSync as un,readdirSync as df}from"node:fs";import{join as Ec}from"node:path";import{simpleGit as pf}from"simple-git";import{parse as ff}from"yaml";function mf(t){try{let e=Se(t,ao);if(!tr(e))return null;let r=ff(un(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!vr.test(n)?null:{prefix:n}}catch{return null}}function hf(t){return`# Built-in tracker configuration \u2014 shared by every team member.
36
36
  # The issue-key prefix (<PREFIX>-<N>). Fixed at project init: changing it
37
37
  # later would orphan existing tasks/<KEY>/ directories.
38
38
  prefix: ${t}
@@ -40,15 +40,15 @@ prefix: ${t}
40
40
  # Statuses are the built-in default set for now:
41
41
  # Backlog | To Do | In Progress | Review | Done | Rejected
42
42
  # A configurable status set / pipeline mapping is a planned extension.
43
- `}function Ec(t=0){return`${t}
44
- `}function Gv(t){return t==="depends_on"||t==="subtask"}function Kv(t){let e;try{e=df(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=Ha.includes(r.type)?r.type:io,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;Gv(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 Tc(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(`
43
+ `}function Tc(t=0){return`${t}
44
+ `}function Hv(t){return t==="depends_on"||t==="subtask"}function Wv(t){let e;try{e=ff(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=Wa.includes(r.type)?r.type:so,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;Hv(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 Rc(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(`
45
45
  `)+`
46
- `}function go(t,e){let r=Se(t,zr(e));return tr(r)?Kv(ln(r,"utf-8")):null}function mf(t){let e=Sc(t,"tasks");if(!tr(e))return[];let r=[];for(let n of lf(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=go(t,n.name);o&&r.push(o)}return r}function Hv(t,e){let r=Se(t,`tasks/${e}/task.md`);if(!tr(r))return;let n=ln(r,"utf-8").split(`
46
+ `}function yo(t,e){let r=Se(t,Vr(e));return tr(r)?Wv(un(r,"utf-8")):null}function gf(t){let e=Ec(t,"tasks");if(!tr(e))return[];let r=[];for(let n of df(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=yo(t,n.name);o&&r.push(o)}return r}function qv(t,e){let r=Se(t,`tasks/${e}/task.md`);if(!tr(r))return;let n=un(r,"utf-8").split(`
47
47
  `),o=n.indexOf("---");if(o<0)return;let i=n.slice(o+1),s=i.lastIndexOf("## Attachments");s>=0&&i.slice(s+1).every(u=>u.trim()===""||/^- \[[^\]]*\]\(attachments\/[^)]*\)$/.test(u.trim()))&&(i=i.slice(0,s));let a=i.join(`
48
- `).trim();if(!(!a||a==="_(no description)_"))return a}function yo(t,e,r={}){let n=r.withDescription?Hv(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:Wv(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function Wv(t){return t.charAt(0).toUpperCase()+t.slice(1)}function qv(t){let e=Se(t,Yr);if(!tr(e))return 0;let r=Number.parseInt(ln(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function Yv(t,e){let r=Sc(t,"tasks");if(!tr(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of lf(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 zv(t,e){return Math.max(qv(t),Yv(t,e))+1}async function hf(t,e,r,n){return $c(t,()=>Vv(t,e,r,n))}async function Vv(t,e,r,n){if(!tr(Sc(t,".git")))throw new Error(`context repo clone not found at ${t}`);await ho(t);let o=null;for(let i=0;i<cf;i++){let s=zv(t,e),a=`${e}-${s}`,c=[...r(a),{path:Yr,content:Ec(s)}];try{return await vc(t,c,n(a)),a}catch(l){if(o=l,await Jv(t,n(a)),await ho(t),Xv(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${cf} attempts: ${o instanceof Error?o.message:String(o)}`)}function Xv(t,e){for(let r of e){let n=Se(t,r.path);if(!tr(n)||(r.encoding==="base64"?ln(n).toString("base64"):ln(n,"utf-8"))!==r.content)return!1}return!0}async function ho(t){let e=uf(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 Jv(t,e){let r=uf(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
48
+ `).trim();if(!(!a||a==="_(no description)_"))return a}function wo(t,e,r={}){let n=r.withDescription?qv(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:Yv(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function Yv(t){return t.charAt(0).toUpperCase()+t.slice(1)}function zv(t){let e=Se(t,zr);if(!tr(e))return 0;let r=Number.parseInt(un(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function Vv(t,e){let r=Ec(t,"tasks");if(!tr(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of df(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 Xv(t,e){return Math.max(zv(t),Vv(t,e))+1}async function yf(t,e,r,n){return vc(t,()=>Jv(t,e,r,n))}async function Jv(t,e,r,n){if(!tr(Ec(t,".git")))throw new Error(`context repo clone not found at ${t}`);await go(t);let o=null;for(let i=0;i<uf;i++){let s=Xv(t,e),a=`${e}-${s}`,c=[...r(a),{path:zr,content:Tc(s)}];try{return await xc(t,c,n(a)),a}catch(l){if(o=l,await Qv(t,n(a)),await go(t),Zv(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${uf} attempts: ${o instanceof Error?o.message:String(o)}`)}function Zv(t,e){for(let r of e){let n=Se(t,r.path);if(!tr(n)||(r.encoding==="base64"?un(n).toString("base64"):un(n,"utf-8"))!==r.content)return!1}return!0}async function go(t){let e=pf(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 Qv(t,e){let r=pf(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
49
49
  `)[0]||!(await r.raw(["log","@{u}..HEAD","--pretty=%s"]).catch(()=>"")).trim().split(`
50
50
  `).some(i=>i.trim()===e.split(`
51
- `)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var cf,Ti=x(()=>{"use strict";F();lt();cf=5});function un(t,e,r,n){return[{path:"README.md",content:dx(t,e)},{path:".gitignore",content:nx()},{path:"CLAUDE.md",content:ix(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:ox()},{path:"knowledge/README.md",content:sx()},{path:"knowledge/build.yaml",content:ux()},{path:"actions/README.md",content:ax()},{path:"roles/README.md",content:cx()},{path:"skills/README.md",content:lx()},{path:"model/README.md",content:Zv()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:rx()},{path:"adr/README.md",content:Qv()},{path:"adr/0000-template.md",content:ex()},{path:"adr/INDEX.md",content:tx()},{path:gt,content:Vn()},...t.trackerProvider==="internal"?[{path:so,content:ff(t.youtrackProjectKey??oi)},{path:Yr,content:Ec()}]:[]]}function Zv(){return`# model/ \u2014 the project map
51
+ `)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var uf,Ii=x(()=>{"use strict";F();lt();uf=5});function dn(t,e,r,n){return[{path:"README.md",content:fx(t,e)},{path:".gitignore",content:ix()},{path:"CLAUDE.md",content:ax(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:sx()},{path:"knowledge/README.md",content:cx()},{path:"knowledge/build.yaml",content:px()},{path:"actions/README.md",content:lx()},{path:"roles/README.md",content:ux()},{path:"skills/README.md",content:dx()},{path:"model/README.md",content:ex()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:ox()},{path:"adr/README.md",content:tx()},{path:"adr/0000-template.md",content:rx()},{path:"adr/INDEX.md",content:nx()},{path:gt,content:Xn()},...t.trackerProvider==="internal"?[{path:ao,content:hf(t.youtrackProjectKey??si)},{path:zr,content:Tc()}]:[]]}function ex(){return`# model/ \u2014 the project map
52
52
 
53
53
  A graph of the project built from **git history and task artifacts**: files
54
54
  and directories connected by the fact of changing together and the fact of
@@ -75,7 +75,7 @@ asset \u2014 treat it like \`knowledge/\`.
75
75
 
76
76
  Every YAML file carries \`modelFormatVersion\`; a reader that meets a
77
77
  different version treats it as "rebuild needed", not as an error.
78
- `}function Qv(){return`# ADR \u2014 architecture decision records
78
+ `}function tx(){return`# ADR \u2014 architecture decision records
79
79
 
80
80
  Accepted architectural decisions of this project \u2014 its **framework**. The
81
81
  agent reads this section (start with \`INDEX.md\`) at the beginning of every
@@ -103,7 +103,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
103
103
  canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
104
104
  is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
105
105
  open a PR to this repository.
106
- `}function ex(){return`# ADR-NNNN: <title>
106
+ `}function rx(){return`# ADR-NNNN: <title>
107
107
 
108
108
  - **Status:** accepted | superseded by ADR-NNNN
109
109
  - **Date:** YYYY-MM-DD
@@ -125,12 +125,12 @@ What becomes easier, what becomes harder, what future tasks must keep doing.
125
125
  ## Alternatives considered
126
126
 
127
127
  - **<alternative>** \u2014 why it was rejected.
128
- `}function tx(){return`# ADR index
128
+ `}function nx(){return`# ADR index
129
129
 
130
130
  <!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->
131
131
 
132
132
  (no accepted ADRs yet)
133
- `}function rx(){return`# Audit
133
+ `}function ox(){return`# Audit
134
134
 
135
135
  Pipeline event logs. Naming is per-writer: each codepipe
136
136
  project appends only to its own file \u2014
@@ -139,14 +139,14 @@ project appends only to its own file \u2014
139
139
 
140
140
  \u2014 so several team members' CLIs never contend on one file. Do not create a
141
141
  shared aggregate here.
142
- `}function Tt(t,e,r,n,o=Xe,i){let s=t.trackerProvider==="internal";return{projectYaml:s?px(t):fx(t,r,n),regimenYaml:mx(t.automationLevel,s?!0:e,s,o,i)}}function nx(){return`# codepipe project config is local to each member's workspace
142
+ `}function Tt(t,e,r,n,o=Xe,i){let s=t.trackerProvider==="internal";return{projectYaml:s?mx(t):hx(t,r,n),regimenYaml:gx(t.automationLevel,s?!0:e,s,o,i)}}function ix(){return`# codepipe project config is local to each member's workspace
143
143
  project.yaml
144
144
  regimen.yaml
145
145
 
146
146
  # codepipe runtime
147
147
  session.log
148
148
  apply-queue.json
149
- `}function ox(){return`# Index prompt
149
+ `}function sx(){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 ix(t){return`# Project context for the CodePipe agent
206
+ `}function ax(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 sx(){return`# Knowledge
234
+ `}function cx(){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 ax(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
251
+ `}function lx(){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 cx(){return`# roles/ \u2014 who reviews your work
290
+ `}function ux(){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 lx(){return`# skills/ \u2014 procedures the agent can invoke
318
+ `}function dx(){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 ux(){return`# BUILD phase config. Discovered & maintained by the agent.
377
+ `}function px(){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 dx(t,e){return`# ${e.name}
393
+ `}function fx(t,e){return`# ${e.name}
394
394
 
395
395
  Context Repo for the **${t.name}** project (CodePipe).
396
396
 
@@ -416,7 +416,7 @@ PRs to this repository (and the agent also writes to \`knowledge/\` and
416
416
  pipeline \u2014 don't edit them by hand.
417
417
 
418
418
  Automation level: **${t.automationLevel}**.
419
- `}function px(t){return`# Project description for CodePipe.
419
+ `}function mx(t){return`# Project description for CodePipe.
420
420
  id: ${t.projectId}
421
421
  name: ${t.name}
422
422
 
@@ -441,9 +441,9 @@ adapters:
441
441
  # Branch (must keep the <TASK_ID> placeholder).
442
442
  branch:
443
443
  pattern: codepipe/<TASK_ID>
444
- ${gf(t)}
444
+ ${wf(t)}
445
445
  repos:
446
- ${yf(t)}
446
+ ${kf(t)}
447
447
  # A repo may declare a mirror \u2014 a repository CodePipe owns that stands in for
448
448
  # origin for the whole pipeline: task branches, PRs and merges happen there and
449
449
  # your own repository is never written. All-or-nothing: either every repo
@@ -453,21 +453,21 @@ ${yf(t)}
453
453
  # host: github
454
454
  # owner: your-org
455
455
  # repo: api-codepipe-mirror
456
- `}function gf(t){let e=t.language;return!e||Object.keys(e).length===0?"":`
456
+ `}function wf(t){let e=t.language;return!e||Object.keys(e).length===0?"":`
457
457
  # Languages the agent writes in, per area. \`auto\` = mirror the language of
458
458
  # the user's material. Also editable from the dashboard: project card \u2192
459
459
  # Settings \u2192 Language.
460
460
  language:
461
461
  ${Object.entries(e).map(([n,o])=>` ${n}: ${o}`).join(`
462
462
  `)}
463
- `}function yf(t){return t.repos.length===0?` [] # add repos here
463
+ `}function kf(t){return t.repos.length===0?` [] # add repos here
464
464
  `:t.repos.map(e=>` - name: ${e.name}
465
465
  host: ${e.host}
466
466
  owner: ${e.owner}
467
467
  repo: ${e.repoName}
468
468
  mount_as: ${e.mountAs??e.name}`+(e.defaultBranch?`
469
469
  default_branch: ${e.defaultBranch}`:"")).join(`
470
- `)}function fx(t,e,r){let n=e?`
470
+ `)}function hx(t,e,r){let n=e?`
471
471
  tracker_url: ${e}`:`
472
472
  # tracker_url: https://your.youtrack.cloud`,o=r?`require_assignee: true
473
473
  assignee: ${r}`:`require_assignee: false
@@ -515,7 +515,7 @@ ${Object.entries(e).map(([n,o])=>` ${n}: ${o}`).join(`
515
515
  # non-empty assignee. assignee only takes effect when require_assignee=true.
516
516
  ${o}`:` # project_key: \u2026
517
517
  # tracker_url: https://your.youtrack.cloud
518
- poll_interval_sec: 60`,s=yf(t);return`# Project description for CodePipe.
518
+ poll_interval_sec: 60`,s=kf(t);return`# Project description for CodePipe.
519
519
  id: ${t.projectId}
520
520
  name: ${t.name}
521
521
 
@@ -547,10 +547,10 @@ adapters:
547
547
  # Branch (must keep the <TASK_ID> placeholder).
548
548
  branch:
549
549
  pattern: codepipe/<TASK_ID>
550
- ${gf(t)}
550
+ ${wf(t)}
551
551
  repos:
552
552
  ${s}
553
- `}function mx(t,e,r=!1,n=Xe,o){let i=t==="full",s=e?"true":"false",a=o?` # Model selection. This project's Claude subscription did not include every
553
+ `}function gx(t,e,r=!1,n=Xe,o){let i=t==="full",s=e?"true":"false",a=o?` # Model selection. This project's Claude subscription did not include every
554
554
  # model in the recommended per-role split, so CodePipe set a single default
555
555
  # your subscription can serve for all roles. Tune per role later from the
556
556
  # dashboard (Project Settings \u2192 llm.models) or by editing this file.
@@ -692,35 +692,35 @@ ${a}
692
692
  # sandbox quota (how many runners the account may occupy), enforced by the HUB
693
693
  # and sized on the farm. A solo 'codepipe up' runs one worker. (ADR-0030)
694
694
 
695
- `}var Ir=x(()=>{"use strict";F();Ti()});function Sf(t){xf=t}function Rr(t,e="info"){xf(t,e)}var xf,Ri=x(()=>{"use strict";xf=t=>console.log(t)});import{homedir as Px,tmpdir as x0}from"node:os";import{existsSync as Ax,mkdirSync as _x,mkdtempSync as E0,rmSync as T0}from"node:fs";import{join as Rc}from"node:path";import{simpleGit as Cc}from"simple-git";function _e(t,e,r){let n=r??Rc(Px(),".codepipe","repos");return Rc(n,t,e)}async function rr(t,e,r={}){let n=_e(t,e.name,r.baseDir),o=r.cloneUrlOverride??Ac(e);if(!Ax(Rc(n,".git"))){_x(n,{recursive:!0});let a=Cc();Rr(`[git] clone ${o} \u2192 ${n}`);try{await a.clone(o,n)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${o}
696
- ${l.trim()}`)}}let i=Cc(n);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
697
- ${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function dn(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function jx(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&&Rr(`[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 dn(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await dn(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([...Pc,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function Nx(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await dn(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await dn(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 Tf(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 Nx(t,i,()=>jx(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));p&&await t.raw(["branch","-D",a]).catch(()=>{});let m=`origin/${c}`;await dn(t,m)||(m=`origin/${u??c}`);let f=(await t.revparse([m])).trim(),g=0;if(f===s)await t.raw(["branch","-f",a,d]),await t.checkout(a);else{g=parseInt((await t.raw(["rev-list","--count",`${s}..${f}`]).catch(()=>"1")).trim(),10)||1,await t.checkout(["-B",a,m]);try{await t.raw([...Pc,"cherry-pick",d])}catch(w){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let $=w instanceof Error?w.message:String(w);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
698
- ${$.trim()}`)}}let k=(await t.revparse(["HEAD"])).trim(),h=r.push!==!1;if(h){let w=p?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push(w)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:k,pushed:h,...g>0?{baseMoved:g}:{}}}async function If(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 Rf(t,e,r){let{branchName:n,dropTaskKeys:o}=r,i=`origin/${n}`;if(!await dn(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(`
695
+ `}var Ir=x(()=>{"use strict";F();Ii()});function Tf(t){Ef=t}function rr(t,e="info"){Ef(t,e)}var Ef,Pi=x(()=>{"use strict";Ef=t=>console.log(t)});import{homedir as _x,tmpdir as R0}from"node:os";import{existsSync as jx,mkdirSync as Nx,mkdtempSync as C0,rmSync as P0}from"node:fs";import{join as Cc}from"node:path";import{simpleGit as Pc}from"simple-git";function _e(t,e,r){let n=r??Cc(_x(),".codepipe","repos");return Cc(n,t,e)}async function nr(t,e,r={}){let n=_e(t,e.name,r.baseDir),o=r.cloneUrlOverride??_c(e);if(!jx(Cc(n,".git"))){Nx(n,{recursive:!0});let a=Pc();rr(`[git] clone ${o} \u2192 ${n}`);try{await a.clone(o,n)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${o}
696
+ ${l.trim()}`)}}let i=Pc(n);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
697
+ ${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function pn(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function Ox(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&&rr(`[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 pn(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await pn(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([...Ac,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function Lx(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await pn(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await pn(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 If(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 Lx(t,i,()=>Ox(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));p&&await t.raw(["branch","-D",a]).catch(()=>{});let m=`origin/${c}`;await pn(t,m)||(m=`origin/${u??c}`);let f=(await t.revparse([m])).trim(),g=0;if(f===s)await t.raw(["branch","-f",a,d]),await t.checkout(a);else{g=parseInt((await t.raw(["rev-list","--count",`${s}..${f}`]).catch(()=>"1")).trim(),10)||1,await t.checkout(["-B",a,m]);try{await t.raw([...Ac,"cherry-pick",d])}catch(w){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let $=w instanceof Error?w.message:String(w);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
698
+ ${$.trim()}`)}}let k=(await t.revparse(["HEAD"])).trim(),h=r.push!==!1;if(h){let w=p?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push(w)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:k,pushed:h,...g>0?{baseMoved:g}:{}}}async function Cf(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 Pf(t,e,r){let{branchName:n,dropTaskKeys:o}=r,i=`origin/${n}`;if(!await pn(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(`
699
699
  `).map(m=>m.trim()).filter(m=>m.length>0),l=new Set(o.map(m=>m.toUpperCase())),u=[],p=0;for(let m of c)(await t.raw(["show","-s","--format=%(trailers:key=CodePipe-Task,valueonly)",m])).split(`
700
- `).map(k=>k.trim().toUpperCase()).filter(k=>k.length>0).some(k=>l.has(k))?p++:u.push(m);if(p===0)return{commit:(await t.revparse([i])).trim(),dropped:0};await t.checkout(["-B",n,a]);for(let m of u)try{await t.raw([...Pc,"cherry-pick","--allow-empty","--keep-redundant-commits",m])}catch(f){await t.raw(["cherry-pick","--abort"]).catch(()=>{}),await t.checkout(["-B",n,i]).catch(()=>{});let g=f instanceof Error?f.message:String(f);throw new Error(`rewrite_cluster_branch: replaying ${m.slice(0,10)} after dropping ${o.join(", ")} hit conflicts
701
- ${g.trim()}`)}let d=(await t.revparse(["HEAD"])).trim();return await t.push(["--force-with-lease","-u","origin",n]),{commit:d,dropped:p}}async function Cf(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 Ac(t){return t.mirror?Ef(t.mirror.host,t.mirror.owner,t.mirror.repoName):Ef(t.host,t.owner,t.repoName)}function Ef(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 Ci(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 Pf(t){return(await Cc().listRemote(["--heads",t])).split(`
702
- `).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 Af(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}var Pc,ko=x(()=>{"use strict";Ri();Pc=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{createCipheriv as Ox,createDecipheriv as Lx,createHash as Mx,createPrivateKey as Dx,createPublicKey as _c,diffieHellman as _f,generateKeyPairSync as jf,hkdfSync as Nf,randomBytes as Ux}from"node:crypto";function Pi(){let{publicKey:t,privateKey:e}=jf("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function Ke(t){let e=Buffer.from(t,"base64");return(Mx("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function Bt(t,e){let r=_c({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=jf("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=_f({privateKey:o,publicKey:r}),c=Buffer.from(Nf("sha256",a,Buffer.concat([i,s]),Of,32)),l=Ux(12),u=Ox("aes-256-gcm",c,l),p=typeof e=="string"?Buffer.from(e,"utf-8"):e,d=Buffer.concat([u.update(p),u.final()]),m=u.getAuthTag(),f={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:m.toString("base64"),ct:d.toString("base64")};return Buffer.from(JSON.stringify(f),"utf-8").toString("base64")}function pn(t,e){let r=JSON.parse(Buffer.from(e,"base64").toString("utf-8"));if(r.v!==1)throw new Error(`sealedbox: unsupported envelope version ${r.v}`);let n=Dx({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=_c({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=_c(n).export({type:"spki",format:"der"}),a=_f({privateKey:n,publicKey:o}),c=Buffer.from(Nf("sha256",a,Buffer.concat([i,s]),Of,32)),l=Lx("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 Of,ut=x(()=>{"use strict";Of=Buffer.from("devpipe-sealedbox-v1","utf-8")});function bo(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 $o(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 vo(t,e=process.env){if(!t)return!1;let r=`https://${Lt}:${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 jc(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 Mf(t,e=process.env){return jc(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>bo(t,e),e)}function Df(t,e=process.env){return jc(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>$o(t,e),e)}function Uf(t,e=process.env){return jc(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Lt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>vo(t,e),e)}var Ai=x(()=>{"use strict";F()});import{existsSync as Vf,readFileSync as Xf,writeFileSync as Jf}from"node:fs";import{join as Zf}from"node:path";import{isMap as _i,parseDocument as Qf}from"yaml";async function em(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||!oo(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=Zf(t,"project.yaml");if(!Vf(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=Qf(Xf(o,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>_i(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!_i(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),Jf(o,i.toString()),{repoName:r,defaultBranch:n}}function tm(t,e,r){let n=Zf(t,"project.yaml");if(!Vf(n))throw new Error(`project.yaml not found in context repo (${t})`);let o=Qf(Xf(n,"utf-8")),i=o.get("repos"),a=(i&&typeof i=="object"&&"items"in i?i.items:[]).find(c=>_i(c)&&String(c.get("name")??c.get("repo")??"")===e);if(!_i(a))throw new Error(`repo "${e}" not found in project.yaml repos[]`);a.set("mirror",{host:r.host,owner:r.owner,repo:r.repoName}),Jf(n,o.toString())}var Nc=x(()=>{"use strict";F()});import{existsSync as Uc,readFileSync as Bc}from"node:fs";import{join as Fc}from"node:path";import{simpleGit as am}from"simple-git";import{parse as Gc}from"yaml";function lm(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(iS.source,"g")}function um(t){let e=Fc(t,"project.yaml");if(Uc(e))try{let o=Gc(Bc(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=Fc(t,"tracker","config.yaml");if(Uc(r))try{let o=Gc(Bc(r,"utf-8"))?.prefix;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return null}function dm(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 sS(t,e,r){let o=await am(t).raw(["log","--numstat","--format=@@@ %H %ct %P %x09%s","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
703
- `))if(a.startsWith("@@@ ")){let c=a.indexOf(" "),l=(c>=0?a.slice(4,c):a.slice(4)).trim().split(/\s+/),u=c>=0?a.slice(c+1):"",p=l[0]??"",d=Number(l[1]??0),m=l.slice(2),f=Kc.exec(u)??cm.exec(u);s={sha:p,timeSec:d,subject:u,files:[],prNumber:f?Number(f[1]):null,isMerge:m.length>1},i.push(s)}else if(a.trim()&&s){let c=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(a);if(!c)continue;let l=c[1]==="-"?0:Number(c[1]),u=c[2]==="-"?0:Number(c[2]);s.files.push({path:dm(c[3]),churn:l+u})}return i}async function aS(t,e){let n=await am(t).raw(["diff","--numstat",`${e}^1`,e]).catch(()=>""),o=[];for(let i of n.split(`
704
- `)){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:dm(s[3]),churn:a+c})}return o}function cS(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(Kc,"").trim();else if(c.prNumber!==null){if((t.trackerProjectKey??"").toUpperCase()==="PR")continue;u=`PR-${c.prNumber}`,p=c.subject.replace(Kc,"").replace(cm,"").replace(/^from\s+/,"").trim()||c.subject}else continue;if(!/^[A-Za-z0-9._-]+$/.test(u))continue;let m=new Map;for(let k of c.files){let h=o.get(k.path)??k.path;s(h)||m.set(h,(m.get(h)??0)+k.churn)}if(m.size===0)continue;let g=a.get(u)??{modelFormatVersion:2,taskKey:u,origin:"bootstrap",title:"",commits:[],files:[]};p&&(g.title=p),c.timeSec>0&&(g.date=new Date(c.timeSec*1e3).toISOString().slice(0,10)),g.commits.push(c.sha);for(let[k,h]of m){let w=ye("code",e,k),$=g.files.find(S=>S.key===w);if($)$.churn=($.churn??0)+h;else{let S=i.get(w);g.files.push({key:w,...S?{entityId:S}:{},churn:h})}}if(d.length>0){let k=new Set([...g.links?.tasks??[],...d]);k.delete(u),g.links={...g.links??{},tasks:[...k].sort()}}a.set(u,g)}return a}function sm(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 pm(t){let e=await sS(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 aS(t.repoDir,r.sha))}return cS({repo:t.repo,issueKeyRe:t.issueKeyRe,commits:e,pathToCurrent:t.pathToCurrent,entityByKey:t.entityByKey,ignored:t.ignored,trackerProjectKey:t.trackerProjectKey??null})}function fm(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?sm(c,a)??c:a)}let n=[],o=0;for(let[i,s]of[...r.entries()].sort(([a],[c])=>a<c?-1:1)){let a=sm(Oi(t,i),s);if(!a){o++;continue}n.push({path:hr(i),content:Hr(a)})}return{files:n,skippedPipeline:o}}function Oi(t,e){let r=Fc(t,hr(e));if(!Uc(r))return null;try{let n=Nt(Gc(Bc(r,"utf-8")));return n.ok?n.value:null}catch{return null}}var iS,Kc,cm,Hc=x(()=>{"use strict";F();iS=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g,Kc=/\(#(\d+)\)\s*$/,cm=/^Merge pull request #(\d+)\b/});import{simpleGit as lS}from"simple-git";async function hm(t,e,r){let o=await lS(t).raw(["log","--no-merges","--name-only","--format=@@@ %H %ct","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
705
- `))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 Li(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 gm(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 h of n){let w=new Set;for(let v of h.files){let b=o.get(v)??v;!i.has(b)||s(b)||w.add(b)}if(w.size<2||w.size>a.commitFileCap)continue;let $=Math.max(0,r-h.timeSec),S=Math.pow(.5,$/c),T=[...w].sort();for(let v of T)l.set(v,(l.get(v)??0)+S);for(let v=0;v<T.length;v++)for(let b=v+1;b<T.length;b++){let I=`${T[v]}\0${T[b]}`;u.set(I,(u.get(I)??0)+S),p.set(I,(p.get(I)??0)+1)}}let d=[],m=a.jaccardMinPct/100;for(let[h,w]of u){if((p.get(h)??0)<a.supportMin)continue;let[$,S]=h.split("\0"),T=(l.get($)??0)+(l.get(S)??0)-w,v=T>0?w/T:0;v<m||d.push({a:$,b:S,weight:Math.round(v*mm)/mm})}let f=new Map;for(let h of d)for(let w of[h.a,h.b])f.has(w)||f.set(w,[]),f.get(w).push(h);let g=new Map;for(let[,h]of f)h.sort((w,$)=>$.weight-w.weight||(w.a<$.a?-1:w.a>$.a?1:w.b<$.b?-1:1)).slice(0,a.topK).forEach(w=>g.set(w,(g.get(w)??0)+1));return[...g.entries()].filter(([,h])=>h===2).map(([h])=>h).map(h=>({kind:"correlates",from:ye("code",e,h.a),to:ye("code",e,h.b),weight:h.weight})).sort((h,w)=>h.from<w.from?-1:h.from>w.from?1:h.to<w.to?-1:1)}var mn,mm,Mi=x(()=>{"use strict";F();mn=["package-lock.json","pnpm-lock.yaml","yarn.lock"];mm=1e4});import{createHash as uS}from"node:crypto";function pS(t,e,r,n){for(let o=0;;o++){let s=`e_${uS("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(s))return s}}function ym(t){let{repo:e,headCommit:r,headDate:n,prev:o,renameChains:i,prevBlobByPath:s,headBlobByPath:a}=t,c=[...t.currentKeys].sort(),l=new Set(c),u=o?.entities??[],p=new Set(u.map(b=>b.entityId)),d=new Set,m=[],f=new Map,g=(b,I)=>{d.add(I),f.set(I,b.entityId),m.push(b)},k=[];for(let b of u)l.has(b.currentKey)&&!d.has(b.currentKey)?g({...b,status:"active",lastSeen:r},b.currentKey):k.push(b);let h=[],w=[];for(let b of k){let I=re(b.currentKey),_=I?i.get(I.path):void 0;if(I&&_){let G=ye(I.level,e,_.finalPath);if(l.has(G)&&!d.has(G)){h.push({entity:b,newKey:G,untilCommit:_.commit}),d.add(G);continue}}w.push(b)}let $=[];if(s){let b=new Map;for(let _ of c){if(d.has(_))continue;let G=re(_);if(G?.level!=="code")continue;let z=a.get(G.path);z&&b.set(z,b.has(z)?null:_)}let I=new Map;for(let _ of w){let G=re(_.currentKey);if(G?.level!=="code")continue;let z=s.get(G.path);z&&I.set(z,I.has(z)?null:_)}for(let _ of w){let G=re(_.currentKey),z=G?.level==="code"?s.get(G.path):void 0,A=z?b.get(z):void 0;z&&A&&I.get(z)===_&&!d.has(A)?(h.push({entity:_,newKey:A,untilCommit:r}),d.add(A)):$.push(_)}}else $.push(...w);let S=new Map;for(let b of h){let I=re(b.entity.currentKey),_=re(b.newKey);if(I?.level!=="code"||!_)continue;let G=I.path,z=_.path;for(let A=G.lastIndexOf("/");A>0;A=G.lastIndexOf("/",A-1)){let y=G.slice(0,A),U=G.slice(A+1);if(!z.endsWith(`/${U}`))continue;let j=z.slice(0,z.length-U.length-1);if(j===y)continue;let H=`${y}\0${j}`,J=S.get(H);S.set(H,{count:(J?.count??0)+1,commit:J&&J.commit>b.untilCommit?J.commit:b.untilCommit})}}let T=[...S.entries()].filter(([,b])=>b.count>=dS).map(([b,I])=>{let[_,G]=b.split("\0");return{from:_,to:G,commit:I.commit}}).sort((b,I)=>I.from.length-b.from.length||(b.from<I.from?-1:1)),v=[];for(let b of $){let I=re(b.currentKey),_=!1;if(I?.level==="component")for(let G of T){let z=null;if(I.path===G.from?z=G.to:I.path.startsWith(`${G.from}/`)&&(z=G.to+I.path.slice(G.from.length)),z===null)continue;let A=ye("component",e,z);l.has(A)&&!d.has(A)&&(h.push({entity:b,newKey:A,untilCommit:G.commit}),d.add(A),_=!0);break}_||v.push(b)}for(let b of h.sort((I,_)=>I.newKey<_.newKey?-1:1))g({...b.entity,currentKey:b.newKey,aliases:[...b.entity.aliases??[],{key:b.entity.currentKey,until:b.untilCommit}],status:"active",lastSeen:r},b.newKey);for(let b of v)m.push({...b,status:"orphaned"});for(let b of c){if(d.has(b))continue;let I=pS(e,b,r,p);p.add(I),g({entityId:I,currentKey:b,firstSeen:n,lastSeen:r,status:"active"},b)}return{table:{modelFormatVersion:2,repo:e,builtFromCommit:r,entities:m},byKey:f}}var dS,wm=x(()=>{"use strict";F();dS=5});import{simpleGit as fS}from"simple-git";async function km(t,e,r){let n=fS(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
706
- `).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 bm(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 $m=x(()=>{"use strict"});function Di(t){return ye("container",t,mS)}function vm(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function xm(t,e,r,n){let o=[],i=u=>{let p=ye("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:vm(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,hS)}},s=(u,p)=>{let d=ye("component",t,u),m=n.get(d);return{key:d,level:"component",label:vm(u),...m?{entityId:m}:{},...p?{aggregate:!0}:{}}},a=(u,p,d)=>{let m=r.filesByDir.get(d)??[],f=r.childDirs.get(d)??[],g=[p,...m.map(i)],k=[...m.map(h=>({kind:"contains",from:p.key,to:ye("code",t,h.path)})),...f.map(h=>({kind:"contains",from:p.key,to:ye("component",t,h)}))];c(u,g,k)},c=(u,p,d)=>{let m={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},f=jt(m);if(!f.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${f.errors.join("; ")}`);o.push({path:ta(t,u),content:aa(m)})},l={key:Di(t),level:"container",label:t,...n.get(Di(t))?{entityId:n.get(Di(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 Sm(t,e){let r=[Di(t)];for(let n of e.components)r.push(ye("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(ye("code",t,o.path));return r.sort()}var mS,hS,Em=x(()=>{"use strict";F();mS=".";hS=12});import{simpleGit as Im}from"simple-git";function Cr(t){let e=new Set,r=[],n=new Set;for(let o of t){let i=o.trim();if(i)if(i.endsWith("/"))e.add(i.slice(0,-1));else if(i.includes("*")){let s=i.replace(/[.*+?^${}()|[\]\\]/g,a=>a==="*"?"\0":`\\${a}`).replace(/\0/g,".*");r.push(new RegExp(`^${s}$`))}else n.add(i)}return o=>{let i=o.split("/"),s=i[i.length-1]??o;if(n.has(o))return!0;for(let a of i)if(e.has(a)||n.has(a))return!0;return r.some(a=>a.test(s))}}async function Cm(t,e="HEAD"){let r=Im(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 xo(t,n)}}async function xo(t,e){let n=await Im(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 Tm(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function Pm(t,e){let r=[...t].sort((f,g)=>f.path<g.path?-1:f.path>g.path?1:0),n=new Map,o=new Map;for(let f of r){let g=Tm(f.path);n.has(g)||n.set(g,[]),n.get(g).push(f);let k=g;for(;k!=="";){let h=Tm(k);o.has(h)||o.set(h,new Set),o.get(h).add(k),k=h}}let i=f=>[...o.get(f)??[]].sort(),s=Math.max(e,1)-1,a=new Set,c=new Set,l=[""];for(;l.length>0;){let f=l.shift(),g=(n.get(f)??[]).length+i(f).length;if(g<=s)s-=g,c.add(f),l.push(...i(f));else{if(f==="")return{components:[],collapsed:new Set,filesByDir:new Map,childDirs:new Map,counts:{component:0,code:0}};a.add(f)}}let u=[],p=new Map,d=new Map,m=0;for(let f of[...c].sort()){let g=n.get(f)??[];p.set(f,g),d.set(f,i(f)),m+=g.length,f!==""&&u.push(f)}for(let f of a)u.push(f);return u.sort(),{components:u,collapsed:a,filesByDir:p,childDirs:d,counts:{component:u.length,code:m}}}var Rm,So=x(()=>{"use strict";Rm=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as Am,readFileSync as _m}from"node:fs";import{join as jm}from"node:path";import{simpleGit as gS}from"simple-git";import{parse as Nm}from"yaml";function hn(t){let e={ignore:Rm,containerNodeCap:yS,cochange:{...nt},issueKeyPattern:null,enabled:!1},r=jm(t,"regimen.yaml");if(!Am(r))return e;let n;try{n=Nm(_m(r,"utf-8"))}catch{return e}let o=n?.context,i=o&&typeof o=="object"?o.model:void 0;if(!i||typeof i!="object")return e;let s=i,a=Array.isArray(s.ignore)?s.ignore.filter(m=>typeof m=="string"&&m.trim().length>0):e.ignore,c=(m,f)=>typeof m=="number"&&Number.isInteger(m)&&m>0?m:f,l=c(s.container_node_cap,e.containerNodeCap),u=s.cochange&&typeof s.cochange=="object"?s.cochange:{},p={windowCommits:c(u.window_commits,e.cochange.windowCommits),commitFileCap:c(u.commit_file_cap,e.cochange.commitFileCap),supportMin:c(u.support_min,e.cochange.supportMin),jaccardMinPct:typeof u.jaccard_min_pct=="number"&&Number.isInteger(u.jaccard_min_pct)&&u.jaccard_min_pct>=0&&u.jaccard_min_pct<=100?u.jaccard_min_pct:e.cochange.jaccardMinPct,halfLifeDays:c(u.half_life_days,e.cochange.halfLifeDays),topK:c(u.top_k,e.cochange.topK)},d=typeof s.issue_key_pattern=="string"&&s.issue_key_pattern.trim().length>0?s.issue_key_pattern.trim():null;return{ignore:a,containerNodeCap:l,cochange:p,issueKeyPattern:d,enabled:s.enabled===!0}}function Wc(t,e){let r=jm(t,Jn(e));if(!Am(r))return null;let n=Nm(_m(r,"utf-8")),o=Qn(n);if(!o.ok)throw new Error(`model: ${Jn(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function qc(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await Cm(r,t.ref??"HEAD"),s=Cr(o.ignore),a=i.files.filter(w=>!s(w.path)),c=Pm(a,o.containerNodeCap),l=Wc(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await gS(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=bm(await km(r,l.builtFromCommit,i.commit)),p=new Map((await xo(r,l.builtFromCommit)).map(S=>[S.path,S.blobHash]))):l?.builtFromCommit===i.commit&&(p=new Map(a.map(w=>[w.path,w.blobHash])));let d=new Map(a.map(w=>[w.path,w.blobHash])),m=ym({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:Sm(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),f=xm(e,i.commit,c,m.byKey),g=Cr([...o.ignore,...mn]),k=gm({repo:e,headTimeSec:i.commitTimeSec,filesets:await hm(r,i.commit,o.cochange.windowCommits),pathToCurrent:Li(m.table),currentPaths:new Set(a.map(w=>w.path)),ignored:g,settings:o.cochange}),h=[{path:Jn(e),content:ca(m.table)},...f.files.map(w=>({path:w.path,content:w.content})),{path:Qs(e),content:gr({modelFormatVersion:2,repo:e,builtFromCommit:i.commit,edges:k})}];return{repo:e,headCommit:i.commit,files:h,emittedShardPaths:new Set(f.files.map(w=>w.path)),counts:{...f.counts,correlates:k.length},identityTable:m.table,entityByKey:m.byKey}}var yS,Yc=x(()=>{"use strict";F();Mi();wm();$m();Em();So();yS=1500});import{existsSync as Lm,readFileSync as Mm,readdirSync as wS}from"node:fs";import{join as zc}from"node:path";import{parse as Dm}from"yaml";function kS(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 Um(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<na)return null;let s=i/Math.min(n.size,o.size),a=kS(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(s*c*Om)/Om;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[ve(t.taskKey),ve(e.taskKey)]:[ve(e.taskKey),ve(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function Bm(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=Um(r.get(l),r.get(u),e);d&&i.push(d)}return i.sort((s,a)=>s.from<a.from?-1:s.from>a.from?1:s.to<a.to?-1:1)}function Fm(t,e,r,n){let o=ve(r),i=t.filter(a=>a.from!==o&&a.to!==o),s=e.find(a=>a.taskKey===r);if(s){let a=new Set(s.files.map(c=>c.key));for(let c of e){if(c.taskKey===r||!c.files.some(u=>a.has(u.key)))continue;let l=Um(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 Ui(t){let e=zc(t,"model/facts/events");if(!Lm(e))return[];let r=[];for(let n of wS(e).sort())if(n.endsWith(".yaml"))try{let o=Nt(Dm(Mm(zc(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function Gm(t){let e=zc(t,mr);if(!Lm(e))return[];try{let r=Zn(Dm(Mm(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function Bi(t){return gr({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var Om,Vc=x(()=>{"use strict";F();Om=1e4});var Eo={};ze(Eo,{collectSearchRows:()=>Hm,readContextIndexHub:()=>bS,rebuildSearchIndex:()=>Wm,searchIndexPath:()=>Hi,searchModelIndex:()=>$S,toFtsQuery:()=>qm});import{existsSync as yn,readFileSync as gn,readdirSync as Gi}from"node:fs";import{join as bt}from"node:path";import{parse as Ki}from"yaml";function Hi(t){return bt(t,".git","codepipe-model-index.sqlite")}function bS(t){let e=bt(t,"regimen.yaml");if(!yn(e))return"off";try{let n=Ki(gn(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 Km(){try{let{createRequire:t}=await import("node:module");return t(import.meta.url)("node:sqlite")}catch{return null}}function Fi(t){return t.length>Zo?t.slice(0,Zo):t}function Xc(t){if(!yn(t))return[];let e=[];for(let r of Gi(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=bt(t,r.name);r.isDirectory()?e.push(...Xc(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function Hm(t){let e=[];for(let i of Xc(bt(t,"model/derived/structure"))){let s;try{s=Ki(gn(i,"utf-8"))}catch{continue}let a=jt(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:Fi(`${l.path} ${c.label??""}`.trim())})}}let r=bt(t,"model/facts/events");if(yn(r)){for(let i of Gi(r).sort())if(i.endsWith(".yaml"))try{let s=Nt(Ki(gn(bt(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:Fi(`${a.taskKey} ${a.title??""} ${c}`.trim())})}catch{}}let n=bt(t,"model/facts/annotations");if(yn(n)){let i=new Map;for(let s of Xc(bt(t,"model/facts/identity")))try{let a=Ki(gn(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 Gi(n).sort())if(s.endsWith(".md"))try{let a=gn(bt(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:Fi(c[2].trim())})}catch{}}let o=bt(t,"adr");if(yn(o))for(let i of Gi(o).sort()){let s=/^(\d{4})-/.exec(i)?.[1];if(!(!s||!i.endsWith(".md")))try{let a=gn(bt(o,i),"utf-8").split(`
707
- `).slice(0,6);e.push({nodeId:`adr::ADR-${s}`,kind:"adr",text:Fi(a.filter(c=>c.trim()).join(" "))})}catch{}}return e}async function Wm(t){let e=Hm(t),r=await Km();if(!r)return{rows:e,indexed:!1};let n=new r.DatabaseSync(Hi(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 qm(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 $S(t,e,r){let n=await Km();if(!n)throw new Error("model search needs Node with built-in sqlite (>= 22.13) on this CLI");yn(Hi(t))||await Wm(t);let o=qm(e);if(!o)return[];let i=Math.min(Math.max(r??20,1),ia),s=new n.DatabaseSync(Hi(t));try{return s.prepare(`SELECT node_id AS nodeId, kind, snippet(model_fts, 2, '[', ']', '\u2026', 10) AS snippet,
700
+ `).map(k=>k.trim().toUpperCase()).filter(k=>k.length>0).some(k=>l.has(k))?p++:u.push(m);if(p===0)return{commit:(await t.revparse([i])).trim(),dropped:0};await t.checkout(["-B",n,a]);for(let m of u)try{await t.raw([...Ac,"cherry-pick","--allow-empty","--keep-redundant-commits",m])}catch(f){await t.raw(["cherry-pick","--abort"]).catch(()=>{}),await t.checkout(["-B",n,i]).catch(()=>{});let g=f instanceof Error?f.message:String(f);throw new Error(`rewrite_cluster_branch: replaying ${m.slice(0,10)} after dropping ${o.join(", ")} hit conflicts
701
+ ${g.trim()}`)}let d=(await t.revparse(["HEAD"])).trim();return await t.push(["--force-with-lease","-u","origin",n]),{commit:d,dropped:p}}async function Af(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 _c(t){return t.mirror?Rf(t.mirror.host,t.mirror.owner,t.mirror.repoName):Rf(t.host,t.owner,t.repoName)}function Rf(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 Ai(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 _f(t){return(await Pc().listRemote(["--heads",t])).split(`
702
+ `).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 jf(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}var Ac,bo=x(()=>{"use strict";Pi();Ac=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{createCipheriv as Mx,createDecipheriv as Dx,createHash as Ux,createPrivateKey as Bx,createPublicKey as jc,diffieHellman as Nf,generateKeyPairSync as Of,hkdfSync as Lf,randomBytes as Fx}from"node:crypto";function _i(){let{publicKey:t,privateKey:e}=Of("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function Ke(t){let e=Buffer.from(t,"base64");return(Ux("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function Bt(t,e){let r=jc({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=Of("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=Nf({privateKey:o,publicKey:r}),c=Buffer.from(Lf("sha256",a,Buffer.concat([i,s]),Mf,32)),l=Fx(12),u=Mx("aes-256-gcm",c,l),p=typeof e=="string"?Buffer.from(e,"utf-8"):e,d=Buffer.concat([u.update(p),u.final()]),m=u.getAuthTag(),f={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:m.toString("base64"),ct:d.toString("base64")};return Buffer.from(JSON.stringify(f),"utf-8").toString("base64")}function fn(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=Bx({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=jc({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=jc(n).export({type:"spki",format:"der"}),a=Nf({privateKey:n,publicKey:o}),c=Buffer.from(Lf("sha256",a,Buffer.concat([i,s]),Mf,32)),l=Dx("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 Mf,ut=x(()=>{"use strict";Mf=Buffer.from("devpipe-sealedbox-v1","utf-8")});function $o(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@github.com:"),o(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function vo(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 xo(t,e=process.env){if(!t)return!1;let r=`https://${Lt}:${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 Nc(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 Uf(t,e=process.env){return Nc(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>$o(t,e),e)}function Bf(t,e=process.env){return Nc(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>vo(t,e),e)}function Ff(t,e=process.env){return Nc(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Lt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>xo(t,e),e)}var ji=x(()=>{"use strict";F()});import{existsSync as Jf,readFileSync as Zf,writeFileSync as Qf}from"node:fs";import{join as em}from"node:path";import{isMap as Ni,parseDocument as tm}from"yaml";async function rm(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||!io(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=em(t,"project.yaml");if(!Jf(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=tm(Zf(o,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>Ni(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!Ni(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),Qf(o,i.toString()),{repoName:r,defaultBranch:n}}function nm(t,e,r){let n=em(t,"project.yaml");if(!Jf(n))throw new Error(`project.yaml not found in context repo (${t})`);let o=tm(Zf(n,"utf-8")),i=o.get("repos"),a=(i&&typeof i=="object"&&"items"in i?i.items:[]).find(c=>Ni(c)&&String(c.get("name")??c.get("repo")??"")===e);if(!Ni(a))throw new Error(`repo "${e}" not found in project.yaml repos[]`);a.set("mirror",{host:r.host,owner:r.owner,repo:r.repoName}),Qf(n,o.toString())}var Oc=x(()=>{"use strict";F()});import{existsSync as Bc,readFileSync as Fc}from"node:fs";import{join as Gc}from"node:path";import{simpleGit as lm}from"simple-git";import{parse as Kc}from"yaml";function dm(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(aS.source,"g")}function pm(t){let e=Gc(t,"project.yaml");if(Bc(e))try{let o=Kc(Fc(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=Gc(t,"tracker","config.yaml");if(Bc(r))try{let o=Kc(Fc(r,"utf-8"))?.prefix;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return null}function fm(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 cS(t,e,r){let o=await lm(t).raw(["log","--numstat","--format=@@@ %H %ct %P %x09%s","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
703
+ `))if(a.startsWith("@@@ ")){let c=a.indexOf(" "),l=(c>=0?a.slice(4,c):a.slice(4)).trim().split(/\s+/),u=c>=0?a.slice(c+1):"",p=l[0]??"",d=Number(l[1]??0),m=l.slice(2),f=Hc.exec(u)??um.exec(u);s={sha:p,timeSec:d,subject:u,files:[],prNumber:f?Number(f[1]):null,isMerge:m.length>1},i.push(s)}else if(a.trim()&&s){let c=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(a);if(!c)continue;let l=c[1]==="-"?0:Number(c[1]),u=c[2]==="-"?0:Number(c[2]);s.files.push({path:fm(c[3]),churn:l+u})}return i}async function lS(t,e){let n=await lm(t).raw(["diff","--numstat",`${e}^1`,e]).catch(()=>""),o=[];for(let i of n.split(`
704
+ `)){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:fm(s[3]),churn:a+c})}return o}function uS(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(Hc,"").trim();else if(c.prNumber!==null){if((t.trackerProjectKey??"").toUpperCase()==="PR")continue;u=`PR-${c.prNumber}`,p=c.subject.replace(Hc,"").replace(um,"").replace(/^from\s+/,"").trim()||c.subject}else continue;if(!/^[A-Za-z0-9._-]+$/.test(u))continue;let m=new Map;for(let k of c.files){let h=o.get(k.path)??k.path;s(h)||m.set(h,(m.get(h)??0)+k.churn)}if(m.size===0)continue;let g=a.get(u)??{modelFormatVersion:2,taskKey:u,origin:"bootstrap",title:"",commits:[],files:[]};p&&(g.title=p),c.timeSec>0&&(g.date=new Date(c.timeSec*1e3).toISOString().slice(0,10)),g.commits.push(c.sha);for(let[k,h]of m){let w=ye("code",e,k),$=g.files.find(S=>S.key===w);if($)$.churn=($.churn??0)+h;else{let S=i.get(w);g.files.push({key:w,...S?{entityId:S}:{},churn:h})}}if(d.length>0){let k=new Set([...g.links?.tasks??[],...d]);k.delete(u),g.links={...g.links??{},tasks:[...k].sort()}}a.set(u,g)}return a}function cm(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 mm(t){let e=await cS(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 lS(t.repoDir,r.sha))}return uS({repo:t.repo,issueKeyRe:t.issueKeyRe,commits:e,pathToCurrent:t.pathToCurrent,entityByKey:t.entityByKey,ignored:t.ignored,trackerProjectKey:t.trackerProjectKey??null})}function hm(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?cm(c,a)??c:a)}let n=[],o=0;for(let[i,s]of[...r.entries()].sort(([a],[c])=>a<c?-1:1)){let a=cm(Mi(t,i),s);if(!a){o++;continue}n.push({path:gr(i),content:Wr(a)})}return{files:n,skippedPipeline:o}}function Mi(t,e){let r=Gc(t,gr(e));if(!Bc(r))return null;try{let n=Nt(Kc(Fc(r,"utf-8")));return n.ok?n.value:null}catch{return null}}var aS,Hc,um,Wc=x(()=>{"use strict";F();aS=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g,Hc=/\(#(\d+)\)\s*$/,um=/^Merge pull request #(\d+)\b/});import{simpleGit as dS}from"simple-git";async function ym(t,e,r){let o=await dS(t).raw(["log","--no-merges","--name-only","--format=@@@ %H %ct","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
705
+ `))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 Di(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 wm(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 h of n){let w=new Set;for(let v of h.files){let b=o.get(v)??v;!i.has(b)||s(b)||w.add(b)}if(w.size<2||w.size>a.commitFileCap)continue;let $=Math.max(0,r-h.timeSec),S=Math.pow(.5,$/c),T=[...w].sort();for(let v of T)l.set(v,(l.get(v)??0)+S);for(let v=0;v<T.length;v++)for(let b=v+1;b<T.length;b++){let R=`${T[v]}\0${T[b]}`;u.set(R,(u.get(R)??0)+S),p.set(R,(p.get(R)??0)+1)}}let d=[],m=a.jaccardMinPct/100;for(let[h,w]of u){if((p.get(h)??0)<a.supportMin)continue;let[$,S]=h.split("\0"),T=(l.get($)??0)+(l.get(S)??0)-w,v=T>0?w/T:0;v<m||d.push({a:$,b:S,weight:Math.round(v*gm)/gm})}let f=new Map;for(let h of d)for(let w of[h.a,h.b])f.has(w)||f.set(w,[]),f.get(w).push(h);let g=new Map;for(let[,h]of f)h.sort((w,$)=>$.weight-w.weight||(w.a<$.a?-1:w.a>$.a?1:w.b<$.b?-1:1)).slice(0,a.topK).forEach(w=>g.set(w,(g.get(w)??0)+1));return[...g.entries()].filter(([,h])=>h===2).map(([h])=>h).map(h=>({kind:"correlates",from:ye("code",e,h.a),to:ye("code",e,h.b),weight:h.weight})).sort((h,w)=>h.from<w.from?-1:h.from>w.from?1:h.to<w.to?-1:1)}var hn,gm,Ui=x(()=>{"use strict";F();hn=["package-lock.json","pnpm-lock.yaml","yarn.lock"];gm=1e4});import{createHash as pS}from"node:crypto";function mS(t,e,r,n){for(let o=0;;o++){let s=`e_${pS("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(s))return s}}function km(t){let{repo:e,headCommit:r,headDate:n,prev:o,renameChains:i,prevBlobByPath:s,headBlobByPath:a}=t,c=[...t.currentKeys].sort(),l=new Set(c),u=o?.entities??[],p=new Set(u.map(b=>b.entityId)),d=new Set,m=[],f=new Map,g=(b,R)=>{d.add(R),f.set(R,b.entityId),m.push(b)},k=[];for(let b of u)l.has(b.currentKey)&&!d.has(b.currentKey)?g({...b,status:"active",lastSeen:r},b.currentKey):k.push(b);let h=[],w=[];for(let b of k){let R=re(b.currentKey),_=R?i.get(R.path):void 0;if(R&&_){let G=ye(R.level,e,_.finalPath);if(l.has(G)&&!d.has(G)){h.push({entity:b,newKey:G,untilCommit:_.commit}),d.add(G);continue}}w.push(b)}let $=[];if(s){let b=new Map;for(let _ of c){if(d.has(_))continue;let G=re(_);if(G?.level!=="code")continue;let z=a.get(G.path);z&&b.set(z,b.has(z)?null:_)}let R=new Map;for(let _ of w){let G=re(_.currentKey);if(G?.level!=="code")continue;let z=s.get(G.path);z&&R.set(z,R.has(z)?null:_)}for(let _ of w){let G=re(_.currentKey),z=G?.level==="code"?s.get(G.path):void 0,A=z?b.get(z):void 0;z&&A&&R.get(z)===_&&!d.has(A)?(h.push({entity:_,newKey:A,untilCommit:r}),d.add(A)):$.push(_)}}else $.push(...w);let S=new Map;for(let b of h){let R=re(b.entity.currentKey),_=re(b.newKey);if(R?.level!=="code"||!_)continue;let G=R.path,z=_.path;for(let A=G.lastIndexOf("/");A>0;A=G.lastIndexOf("/",A-1)){let y=G.slice(0,A),U=G.slice(A+1);if(!z.endsWith(`/${U}`))continue;let j=z.slice(0,z.length-U.length-1);if(j===y)continue;let H=`${y}\0${j}`,J=S.get(H);S.set(H,{count:(J?.count??0)+1,commit:J&&J.commit>b.untilCommit?J.commit:b.untilCommit})}}let T=[...S.entries()].filter(([,b])=>b.count>=fS).map(([b,R])=>{let[_,G]=b.split("\0");return{from:_,to:G,commit:R.commit}}).sort((b,R)=>R.from.length-b.from.length||(b.from<R.from?-1:1)),v=[];for(let b of $){let R=re(b.currentKey),_=!1;if(R?.level==="component")for(let G of T){let z=null;if(R.path===G.from?z=G.to:R.path.startsWith(`${G.from}/`)&&(z=G.to+R.path.slice(G.from.length)),z===null)continue;let A=ye("component",e,z);l.has(A)&&!d.has(A)&&(h.push({entity:b,newKey:A,untilCommit:G.commit}),d.add(A),_=!0);break}_||v.push(b)}for(let b of h.sort((R,_)=>R.newKey<_.newKey?-1:1))g({...b.entity,currentKey:b.newKey,aliases:[...b.entity.aliases??[],{key:b.entity.currentKey,until:b.untilCommit}],status:"active",lastSeen:r},b.newKey);for(let b of v)m.push({...b,status:"orphaned"});for(let b of c){if(d.has(b))continue;let R=mS(e,b,r,p);p.add(R),g({entityId:R,currentKey:b,firstSeen:n,lastSeen:r,status:"active"},b)}return{table:{modelFormatVersion:2,repo:e,builtFromCommit:r,entities:m},byKey:f}}var fS,bm=x(()=>{"use strict";F();fS=5});import{simpleGit as hS}from"simple-git";async function $m(t,e,r){let n=hS(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
706
+ `).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 vm(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 xm=x(()=>{"use strict"});function Bi(t){return ye("container",t,gS)}function Sm(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function Em(t,e,r,n){let o=[],i=u=>{let p=ye("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:Sm(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,yS)}},s=(u,p)=>{let d=ye("component",t,u),m=n.get(d);return{key:d,level:"component",label:Sm(u),...m?{entityId:m}:{},...p?{aggregate:!0}:{}}},a=(u,p,d)=>{let m=r.filesByDir.get(d)??[],f=r.childDirs.get(d)??[],g=[p,...m.map(i)],k=[...m.map(h=>({kind:"contains",from:p.key,to:ye("code",t,h.path)})),...f.map(h=>({kind:"contains",from:p.key,to:ye("component",t,h)}))];c(u,g,k)},c=(u,p,d)=>{let m={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},f=jt(m);if(!f.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${f.errors.join("; ")}`);o.push({path:ra(t,u),content:ca(m)})},l={key:Bi(t),level:"container",label:t,...n.get(Bi(t))?{entityId:n.get(Bi(t))}:{}};a("",l,"");for(let u of r.components)r.collapsed.has(u)?c(u,[s(u,!0)],[]):a(u,s(u,!1),u);return o.sort((u,p)=>u.path<p.path?-1:u.path>p.path?1:0),{files:o,counts:r.counts}}function Tm(t,e){let r=[Bi(t)];for(let n of e.components)r.push(ye("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(ye("code",t,o.path));return r.sort()}var gS,yS,Rm=x(()=>{"use strict";F();gS=".";yS=12});import{simpleGit as Cm}from"simple-git";function Cr(t){let e=new Set,r=[],n=new Set;for(let o of t){let i=o.trim();if(i)if(i.endsWith("/"))e.add(i.slice(0,-1));else if(i.includes("*")){let s=i.replace(/[.*+?^${}()|[\]\\]/g,a=>a==="*"?"\0":`\\${a}`).replace(/\0/g,".*");r.push(new RegExp(`^${s}$`))}else n.add(i)}return o=>{let i=o.split("/"),s=i[i.length-1]??o;if(n.has(o))return!0;for(let a of i)if(e.has(a)||n.has(a))return!0;return r.some(a=>a.test(s))}}async function Am(t,e="HEAD"){let r=Cm(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 So(t,n)}}async function So(t,e){let n=await Cm(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 Im(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function _m(t,e){let r=[...t].sort((f,g)=>f.path<g.path?-1:f.path>g.path?1:0),n=new Map,o=new Map;for(let f of r){let g=Im(f.path);n.has(g)||n.set(g,[]),n.get(g).push(f);let k=g;for(;k!=="";){let h=Im(k);o.has(h)||o.set(h,new Set),o.get(h).add(k),k=h}}let i=f=>[...o.get(f)??[]].sort(),s=Math.max(e,1)-1,a=new Set,c=new Set,l=[""];for(;l.length>0;){let f=l.shift(),g=(n.get(f)??[]).length+i(f).length;if(g<=s)s-=g,c.add(f),l.push(...i(f));else{if(f==="")return{components:[],collapsed:new Set,filesByDir:new Map,childDirs:new Map,counts:{component:0,code:0}};a.add(f)}}let u=[],p=new Map,d=new Map,m=0;for(let f of[...c].sort()){let g=n.get(f)??[];p.set(f,g),d.set(f,i(f)),m+=g.length,f!==""&&u.push(f)}for(let f of a)u.push(f);return u.sort(),{components:u,collapsed:a,filesByDir:p,childDirs:d,counts:{component:u.length,code:m}}}var Pm,Eo=x(()=>{"use strict";Pm=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as jm,readFileSync as Nm}from"node:fs";import{join as Om}from"node:path";import{simpleGit as wS}from"simple-git";import{parse as Lm}from"yaml";function gn(t){let e={ignore:Pm,containerNodeCap:kS,cochange:{...nt},issueKeyPattern:null,enabled:!1},r=Om(t,"regimen.yaml");if(!jm(r))return e;let n;try{n=Lm(Nm(r,"utf-8"))}catch{return e}let o=n?.context,i=o&&typeof o=="object"?o.model:void 0;if(!i||typeof i!="object")return e;let s=i,a=Array.isArray(s.ignore)?s.ignore.filter(m=>typeof m=="string"&&m.trim().length>0):e.ignore,c=(m,f)=>typeof m=="number"&&Number.isInteger(m)&&m>0?m:f,l=c(s.container_node_cap,e.containerNodeCap),u=s.cochange&&typeof s.cochange=="object"?s.cochange:{},p={windowCommits:c(u.window_commits,e.cochange.windowCommits),commitFileCap:c(u.commit_file_cap,e.cochange.commitFileCap),supportMin:c(u.support_min,e.cochange.supportMin),jaccardMinPct:typeof u.jaccard_min_pct=="number"&&Number.isInteger(u.jaccard_min_pct)&&u.jaccard_min_pct>=0&&u.jaccard_min_pct<=100?u.jaccard_min_pct:e.cochange.jaccardMinPct,halfLifeDays:c(u.half_life_days,e.cochange.halfLifeDays),topK:c(u.top_k,e.cochange.topK)},d=typeof s.issue_key_pattern=="string"&&s.issue_key_pattern.trim().length>0?s.issue_key_pattern.trim():null;return{ignore:a,containerNodeCap:l,cochange:p,issueKeyPattern:d,enabled:s.enabled===!0}}function qc(t,e){let r=Om(t,Zn(e));if(!jm(r))return null;let n=Lm(Nm(r,"utf-8")),o=eo(n);if(!o.ok)throw new Error(`model: ${Zn(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function Yc(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await Am(r,t.ref??"HEAD"),s=Cr(o.ignore),a=i.files.filter(w=>!s(w.path)),c=_m(a,o.containerNodeCap),l=qc(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await wS(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=vm(await $m(r,l.builtFromCommit,i.commit)),p=new Map((await So(r,l.builtFromCommit)).map(S=>[S.path,S.blobHash]))):l?.builtFromCommit===i.commit&&(p=new Map(a.map(w=>[w.path,w.blobHash])));let d=new Map(a.map(w=>[w.path,w.blobHash])),m=km({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:Tm(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),f=Em(e,i.commit,c,m.byKey),g=Cr([...o.ignore,...hn]),k=wm({repo:e,headTimeSec:i.commitTimeSec,filesets:await ym(r,i.commit,o.cochange.windowCommits),pathToCurrent:Di(m.table),currentPaths:new Set(a.map(w=>w.path)),ignored:g,settings:o.cochange}),h=[{path:Zn(e),content:la(m.table)},...f.files.map(w=>({path:w.path,content:w.content})),{path:ea(e),content:yr({modelFormatVersion:2,repo:e,builtFromCommit:i.commit,edges:k})}];return{repo:e,headCommit:i.commit,files:h,emittedShardPaths:new Set(f.files.map(w=>w.path)),counts:{...f.counts,correlates:k.length},identityTable:m.table,entityByKey:m.byKey}}var kS,zc=x(()=>{"use strict";F();Ui();bm();xm();Rm();Eo();kS=1500});import{existsSync as Dm,readFileSync as Um,readdirSync as bS}from"node:fs";import{join as Vc}from"node:path";import{parse as Bm}from"yaml";function $S(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 Fm(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<oa)return null;let s=i/Math.min(n.size,o.size),a=$S(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(s*c*Mm)/Mm;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[xe(t.taskKey),xe(e.taskKey)]:[xe(e.taskKey),xe(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function Gm(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=Fm(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 Km(t,e,r,n){let o=xe(r),i=t.filter(a=>a.from!==o&&a.to!==o),s=e.find(a=>a.taskKey===r);if(s){let a=new Set(s.files.map(c=>c.key));for(let c of e){if(c.taskKey===r||!c.files.some(u=>a.has(u.key)))continue;let l=Fm(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 Fi(t){let e=Vc(t,"model/facts/events");if(!Dm(e))return[];let r=[];for(let n of bS(e).sort())if(n.endsWith(".yaml"))try{let o=Nt(Bm(Um(Vc(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function Hm(t){let e=Vc(t,hr);if(!Dm(e))return[];try{let r=Qn(Bm(Um(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function Gi(t){return yr({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var Mm,Xc=x(()=>{"use strict";F();Mm=1e4});var To={};ze(To,{collectSearchRows:()=>qm,readContextIndexHub:()=>vS,rebuildSearchIndex:()=>Ym,searchIndexPath:()=>qi,searchModelIndex:()=>xS,toFtsQuery:()=>zm});import{existsSync as wn,readFileSync as yn,readdirSync as Hi}from"node:fs";import{join as bt}from"node:path";import{parse as Wi}from"yaml";function qi(t){return bt(t,".git","codepipe-model-index.sqlite")}function vS(t){let e=bt(t,"regimen.yaml");if(!wn(e))return"off";try{let n=Wi(yn(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 Wm(){try{let{createRequire:t}=await import("node:module");return t(import.meta.url)("node:sqlite")}catch{return null}}function Ki(t){return t.length>ei?t.slice(0,ei):t}function Jc(t){if(!wn(t))return[];let e=[];for(let r of Hi(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=bt(t,r.name);r.isDirectory()?e.push(...Jc(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function qm(t){let e=[];for(let i of Jc(bt(t,"model/derived/structure"))){let s;try{s=Wi(yn(i,"utf-8"))}catch{continue}let a=jt(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:Ki(`${l.path} ${c.label??""}`.trim())})}}let r=bt(t,"model/facts/events");if(wn(r)){for(let i of Hi(r).sort())if(i.endsWith(".yaml"))try{let s=Nt(Wi(yn(bt(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:Ki(`${a.taskKey} ${a.title??""} ${c}`.trim())})}catch{}}let n=bt(t,"model/facts/annotations");if(wn(n)){let i=new Map;for(let s of Jc(bt(t,"model/facts/identity")))try{let a=Wi(yn(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 Hi(n).sort())if(s.endsWith(".md"))try{let a=yn(bt(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:Ki(c[2].trim())})}catch{}}let o=bt(t,"adr");if(wn(o))for(let i of Hi(o).sort()){let s=/^(\d{4})-/.exec(i)?.[1];if(!(!s||!i.endsWith(".md")))try{let a=yn(bt(o,i),"utf-8").split(`
707
+ `).slice(0,6);e.push({nodeId:`adr::ADR-${s}`,kind:"adr",text:Ki(a.filter(c=>c.trim()).join(" "))})}catch{}}return e}async function Ym(t){let e=qm(t),r=await Wm();if(!r)return{rows:e,indexed:!1};let n=new r.DatabaseSync(qi(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 zm(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 xS(t,e,r){let n=await Wm();if(!n)throw new Error("model search needs Node with built-in sqlite (>= 22.13) on this CLI");wn(qi(t))||await Ym(t);let o=zm(e);if(!o)return[];let i=Math.min(Math.max(r??20,1),sa),s=new n.DatabaseSync(qi(t));try{return s.prepare(`SELECT node_id AS nodeId, kind, snippet(model_fts, 2, '[', ']', '\u2026', 10) AS snippet,
708
708
  bm25(model_fts) AS rank
709
- 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 To=x(()=>{"use strict";F()});import{homedir as MS}from"node:os";import{existsSync as DS,mkdirSync as US,readFileSync as BS,writeFileSync as FS}from"node:fs";import{dirname as GS,join as KS}from"node:path";function el(){return V("FARM_PINS")??KS(MS(),".codepipe","farm-pins.json")}function nh(){let t=el();if(!DS(t))return{};try{return JSON.parse(BS(t,"utf-8"))}catch{return{}}}function HS(t){let e=el();US(GS(e),{recursive:!0}),FS(e,JSON.stringify(t,null,2)+`
710
- `,{mode:384})}function WS(t){return nh()[t]}function Vi(t,e){let r=nh();r[t]=e,HS(r)}function Xi(t,e){let r=Ke(e),n=WS(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 ${el()}.`);return r}var tl=x(()=>{"use strict";Fe();ut()});import{setTimeout as qS}from"node:timers/promises";import YS from"ws";function Ji(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new YS(r)}async function nr(t,e,r){return or(t,e,"/projects",r)}async function oh(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new K(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function Zi(t,e,r,n){return or(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function ih(t,e,r,n){return or(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function sh(t,e,r,n){return or(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function ah(t,e){let r=await fetch(`${t}/sandbox/me`,{headers:{Authorization:`Bearer ${e}`}});if(r.ok)return"ok";if(r.status===401)return"unknown";if(r.status===404)return"unsupported";throw new K(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function Qi(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new K(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function rl(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new K(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function ch(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await rl(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 qS(r.delayMs??1500)}throw o}async function lh(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 Po(e)}if(!r.ok)throw new K(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function uh(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new K(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function dh(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new K(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function ph(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new K(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function fh(t,e,r,n,o){return or(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function Ao(t,e,r,n){return or(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function nl(t,e,r,n){await or(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function mh(t,e,r,n){return or(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function hh(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/repos/${encodeURIComponent(n)}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new K(o.status,s,a)}return s}async function se(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new K(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function or(t,e,r,n){let o=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new K(o.status,s,a)}return s}async function gh(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/deliverables`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new K(n.status,null,`GET /deliverables HTTP ${n.status}`);return(await n.json()).deliverables}var K,Po,je=x(()=>{"use strict";K=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};Po=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});var al={};ze(al,{mirrorLag:()=>lE,syncUpstream:()=>cE});import{simpleGit as Oh}from"simple-git";async function cE(t,e,r,n){let o=Oh(e),i=t.defaultBranch??"main",s=n?.upstream??Lh(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/*:${Pr}/*`,["--prune"]);let a=(await o.revparse([`${Pr}/${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?Mh(t.mirror):null);if(!c)return{repo:t.name,upstreamHead:a,updated:!1};let l=await uE(o),u=await sl(o,c),p=[];for(let d of l){if(d==="codepipe"||d.startsWith("codepipe/"))continue;let m=(await o.revparse([`${Pr}/${d}`]).catch(()=>"")).trim();!m||u.get(d)===m||p.push(`+${m}:refs/heads/${d}`)}return p.length===0?{repo:t.name,upstreamHead:a,updated:!1}:(await o.push([c,...p]),r.info(`${t.name}: mirror \u2190 ${p.length} branch(es), ${i} @ ${a.slice(0,10)}`),{repo:t.name,upstreamHead:a,updated:!0})}catch(a){let c=a instanceof Error?a.message.split(`
711
- `)[0]:String(a);return{repo:t.name,upstreamHead:null,updated:!1,error:c}}}async function lE(t,e,r){let n=r?.mirror??(t.mirror?Mh(t.mirror):null);if(!n)return null;let o=r?.upstream??Lh(t);if(!o)return null;let i=Oh(e),s=t.defaultBranch??"main";try{let a=(await sl(i,n,s)).get(s);if(!a)return null;let c=(await sl(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}:${Pr}/${s}`),await l())}catch{return null}}function Lh(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 Mh(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 uE(t){return(await t.raw(["for-each-ref",Pr,"--format=%(refname)"]).catch(()=>"")).split(`
712
- `).map(r=>r.trim()).filter(r=>r.startsWith(`${Pr}/`)).map(r=>r.slice(Pr.length+1))}async function sl(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(`
713
- `)){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 Pr,cl=x(()=>{"use strict";Pr="refs/codepipe/upstream"});import{existsSync as Dh,readFileSync as dE,readdirSync as pE}from"node:fs";import{join as Uh}from"node:path";import{simpleGit as fE}from"simple-git";import{parse as mE}from"yaml";function ll(t){let e=new Map,r=Uh(t,Xo);if(!Dh(r))return e;let n;try{n=mE(dE(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 hE(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return wr({modelFormatVersion:2,repos:e})}function Bh(t,e){let r=Uh(t,e);if(!Dh(r))return[];let n=[];for(let o of pE(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...Bh(t,i)):n.push(i)}return n}async function rs(t,e,r={}){let n=[],o=0;for(let d of e){n.push(...d.files);let m=`model/derived/structure/${d.repo}`;for(let f of Bh(t,m))d.emittedShardPaths.has(f)||(n.push({path:f,content:"",deleted:!0}),o++)}let i=ll(t);for(let d of e)i.set(d.repo,{builtFromCommit:d.headCommit,counts:d.counts});n.push({path:Xo,content:hE(i)});let s=Ui(t),a=Bm(s,r.halfLifeDays??nt.halfLifeDays);n.push({path:mr,content:Bi(a)});for(let d of e){let m=[];for(let f of s)for(let g of f.files)re(g.key)?.repo===d.repo&&m.push({kind:"touched_by",from:ve(f.taskKey),to:g.key,...g.churn!==void 0?{weight:g.churn}:{}});n.push({path:ea(d.repo),content:gr({modelFormatVersion:2,repo:d.repo,builtFromCommit:d.headCommit,edges:m})})}let c=fE(t),l=(await c.revparse(["HEAD"]).catch(()=>"")).trim(),u=`model: build ${e.map(d=>`${d.repo}@${d.headCommit.slice(0,10)}`).join(", ")}`;await Re(t,n,u);let p=(await c.revparse(["HEAD"]).catch(()=>"")).trim();if(p!==l){let{rebuildSearchIndex:d}=await Promise.resolve().then(()=>(To(),Eo));await d(t).catch(()=>{})}return{committed:p!==l,filesWritten:n.filter(d=>!d.deleted).length,filesDeleted:o}}var Fh=x(()=>{"use strict";F();Vc();lt()});var is={};ze(is,{bootstrapDaemonModel:()=>yE,bootstrapModelForTargets:()=>hl,bootstrapWorkspaceModel:()=>qh,modelBootstrapCommand:()=>ml,modelBuildCommand:()=>fl,rebuildWorkspaceModelIfStale:()=>wE});import{existsSync as ns}from"node:fs";import{join as ir}from"node:path";import{cancel as gE,intro as Gh,log as ul,outro as dl}from"@clack/prompts";import{simpleGit as pl}from"simple-git";function os(t){gE(t),process.exit(1)}function Kh(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:ir(t.root,i.mountAs);if(!ns(ir(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 Hh(t){let e=pl(t.dir),r=`origin/${t.defaultBranch}`;return await e.raw(["rev-parse","--verify",r]).then(()=>!0).catch(()=>!1)?r:"HEAD"}async function Wh(t,e,r,n){let o=[];for(let i of e)try{let s=await qc({repo:i.name,repoDir:i.dir,contextDir:t,settings:r,ref:await Hh(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 fl(t){Gh("codepipe model build");let e=Ae();e||os("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{let r=hn(e.contextDir),n=Kh(e,t.repo,s=>ul.warn(s)),o=await Wh(e.contextDir,n,r,s=>ul.info(s)),i=await rs(e.contextDir,o,{halfLifeDays:r.cochange.halfLifeDays});i.committed?dl(`model updated: ${i.filesWritten} files written, ${i.filesDeleted} stale removed`):dl("model already up to date (no changes)")}catch(r){os(r instanceof Error?r.message:String(r))}}async function ml(t){Gh("codepipe model bootstrap");let e=Ae();e||os("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{await qh(e,t.repo,{onLog:r=>ul.info(r)})}catch(r){os(r instanceof Error?r.message:String(r))}dl("bootstrap complete")}async function qh(t,e,r){let n=Kh(t,e,r.onLog);return hl(t.contextDir,n,r)}async function hl(t,e,r){let n=hn(t),o=await Wh(t,e,n,r.onLog),i=um(t),s=lm(n.issueKeyPattern,i),a=Cr([...n.ignore,...mn]),c=[];for(let p of o){let d=e.find(f=>f.name===p.repo),m=await pm({repo:p.repo,repoDir:d.dir,headCommit:p.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:s,pathToCurrent:Li(p.identityTable),entityByKey:p.entityByKey,ignored:a,trackerProjectKey:i});c.push(m),r.onLog(`${p.repo}: ${m.size} task events mined from history`)}let{files:l,skippedPipeline:u}=fm(t,c);return u>0&&r.onLog(`${u} events already recorded by the live pipeline \u2014 left untouched`),l.length>0&&await Re(t,l,`model: bootstrap ${l.length} task events from history`),await rs(t,o,{halfLifeDays:n.cochange.halfLifeDays}),{events:l.length}}async function yE(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:ir(e.root,a),l=s.defaultBranch||"main";c!==e.contextDir&&ns(ir(c,".git"))?(await pl(c).fetch(["origin",l]).catch(()=>{}),o.push({name:s.name,dir:c,defaultBranch:l})):(n(`${s.name}: materializing clone in the daemon layout`),await rr(t,s),o.push({name:s.name,dir:_e(t,s.name),defaultBranch:l}))}let i=await hl(e.contextDir,o,{onLog:n});return{repos:o.length,events:i.events}}async function wE(t,e={}){let r=e.onLog??(()=>{}),n=hn(t.contextDir),o=new Map;for(let l of t.repos){if(!l.mirror)continue;let u=l.mountAs==="."?t.root:ir(t.root,l.mountAs);if(!ns(ir(u,".git")))continue;let{syncUpstream:p}=await Promise.resolve().then(()=>(cl(),al)),d=await p(l,u,{info:m=>r(`[mirror] ${m}`),warn:m=>r(`[mirror] ${m}`)});if(d.error||!d.upstreamHead){r(`[mirror] ${l.name}: sync failed (${d.error??"no upstream head"})`);continue}o.set(l.name,d.upstreamHead)}if(!n.enabled)return{rebuilt:[],skipped:[]};let i=[],s=[],a=ll(t.contextDir),c=[];for(let l of t.repos){let u=l.mountAs==="."?t.root:ir(t.root,l.mountAs);if(!ns(ir(u,".git")))continue;let p=pl(u),d=l.defaultBranch||"main",m=null;if(l.mirror){if(m=o.get(l.name)??null,!m){r(`[mirror] ${l.name}: map not rebuilt \u2014 sync did not complete`);continue}}else e.fetch&&await p.fetch(["origin",d]).catch(()=>{});let f=m??await Hh({name:l.name,dir:u,defaultBranch:d}),g=(await p.revparse([f]).catch(()=>"")).trim();if(g){if(a.get(l.name)?.builtFromCommit===g){s.push(l.name);continue}try{c.push(await qc({repo:l.name,repoDir:u,contextDir:t.contextDir,settings:n,ref:g})),i.push(l.name)}catch(k){r(`[model] rebuild of ${l.name} failed: ${k instanceof Error?k.message:String(k)}`)}}}return c.length>0&&(await rs(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 _o=x(()=>{"use strict";lt();Fh();Yc();Hc();Mi();So();ko();it()});var zh={};ze(zh,{computeDriftReport:()=>xE,supersededAdrIds:()=>Yh});import{existsSync as gl,readFileSync as yl,readdirSync as wl}from"node:fs";import{join as wn}from"node:path";import{parse as kE}from"yaml";import{simpleGit as bE}from"simple-git";function vE(t,e){let r=wn(t,`model/derived/structure/${e}`),n=[],o="";if(!gl(r))return{nodes:n,builtFromCommit:o};for(let i of wl(r).sort()){if(!i.endsWith(".yaml"))continue;let s;try{let a=jt(kE(yl(wn(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 Yh(t){let e=new Set,r=wn(t,"adr");if(!gl(r))return e;for(let n of wl(r).sort()){let o=/^(\d{4})-/.exec(n)?.[1];if(!(!o||!n.endsWith(".md")))try{let i=yl(wn(r,n),"utf-8").slice(0,600).toLowerCase();/status[^\n]*superseded/.test(i)&&e.add(`ADR-${o}`)}catch{}}return e}async function xE(t,e,r){let{nodes:n,builtFromCommit:o}=vE(e,r),i=(await bE(t).revparse(["HEAD"])).trim(),s=await xo(t,i),a=new Map(s.map(w=>[w.path,w.blobHash])),c=[],l=[],u=new Set,p=[];for(let w of n){if(w.level==="component"){p.push(w);continue}u.add(w.path);let $=a.get(w.path);$?w.contentHash&&$.slice(0,$E)!==w.contentHash&&c.push(w.key):l.push(w.key)}let d=0,m=new Map,f=new Set;for(let w of s){let $=w.path.lastIndexOf("/"),S=$<0?"":w.path.slice(0,$);m.has(S)||m.set(S,new Set),m.get(S).add(w.path),u.has(w.path)||d++;let T=S;for(;T!==""&&!f.has(T);)f.add(T),T=T.includes("/")?T.slice(0,T.lastIndexOf("/")):""}let g=new Map;for(let w of u){let $=w.lastIndexOf("/"),S=$<0?"":w.slice(0,$);g.has(S)||g.set(S,new Set),g.get(S).add(w)}for(let w of p){if(!f.has(w.path)){l.push(w.key);continue}let $=g.get(w.path)??new Set,S=m.get(w.path)??new Set;($.size!==S.size||[...$].some(v=>!S.has(v)))&&c.push(w.key)}let k=[],h=Yh(e);if(h.size>0){let w=wn(e,"model/facts/annotations"),$=new Map(n.filter(S=>S.entityId).map(S=>[S.entityId,S.key]));if(gl(w))for(let S of wl(w).sort()){if(!S.endsWith(".md"))continue;let T=S.replace(/\.md$/,""),v=$.get(T);if(v)try{(yl(wn(w,S),"utf-8").match(/\bADR-(\d{3,4})\b/g)??[]).map(_=>`ADR-${_.slice(4).padStart(4,"0")}`).some(_=>h.has(_))&&k.push(v)}catch{}}}return{repo:r,builtFromCommit:o,headCommit:i,stale:[...new Set(c)].sort(),orphaned:[...new Set(l)].sort(),superseded:[...new Set(k)].sort(),newFiles:d}}var $E,Vh=x(()=>{"use strict";F();So();$E=12});import{execFileSync as _E}from"node:child_process";import{mkdtempSync as jE,mkdirSync as NE,readFileSync as Zh,rmSync as OE,writeFileSync as LE}from"node:fs";import{tmpdir as ME}from"node:os";import{dirname as DE,join as Qh}from"node:path";function eg(t="codepipe-context"){let e=jE(Qh(ME(),"codepipe-ssh-")),r=Qh(e,"id_ed25519");try{return _E("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Zh(r,"utf-8"),publicKey:Zh(`${r}.pub`,"utf-8").trim()}}finally{OE(e,{recursive:!0,force:!0})}}async function tg(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 rg(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 ng(t,e){NE(DE(t),{recursive:!0});let r=e.endsWith(`
709
+ FROM model_fts WHERE model_fts MATCH ? ORDER BY bm25(model_fts), node_id LIMIT ?`).all(o,i).map(c=>({nodeId:c.nodeId,kind:c.kind,score:-c.rank,snippet:c.snippet}))}finally{s.close()}}var Ro=x(()=>{"use strict";F()});import{homedir as US}from"node:os";import{existsSync as BS,mkdirSync as FS,readFileSync as GS,writeFileSync as KS}from"node:fs";import{dirname as HS,join as WS}from"node:path";function tl(){return X("FARM_PINS")??WS(US(),".codepipe","farm-pins.json")}function sh(){let t=tl();if(!BS(t))return{};try{return JSON.parse(GS(t,"utf-8"))}catch{return{}}}function qS(t){let e=tl();FS(HS(e),{recursive:!0}),KS(e,JSON.stringify(t,null,2)+`
710
+ `,{mode:384})}function YS(t){return sh()[t]}function Xi(t,e){let r=sh();r[t]=e,qS(r)}function Ji(t,e){let r=Ke(e),n=YS(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 ${tl()}.`);return r}var rl=x(()=>{"use strict";Fe();ut()});import{setTimeout as zS}from"node:timers/promises";import VS from"ws";function Zi(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new VS(r)}async function or(t,e,r){return ir(t,e,"/projects",r)}async function ah(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new K(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function Qi(t,e,r,n){return ir(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function ch(t,e,r,n){return ir(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function lh(t,e,r,n){return ir(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function uh(t,e){let r=await fetch(`${t}/sandbox/me`,{headers:{Authorization:`Bearer ${e}`}});if(r.ok)return"ok";if(r.status===401)return"unknown";if(r.status===404)return"unsupported";throw new K(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function es(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new K(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function nl(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new K(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function dh(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await nl(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 zS(r.delayMs??1500)}throw o}async function ph(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 _o(e)}if(!r.ok)throw new K(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function fh(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new K(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function mh(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new K(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function hh(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new K(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function gh(t,e,r,n,o){return ir(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function jo(t,e,r,n){return ir(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function ol(t,e,r,n){await ir(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function yh(t,e,r,n){return ir(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function wh(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/repos/${encodeURIComponent(n)}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new K(o.status,s,a)}return s}async function se(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new K(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function ir(t,e,r,n){let o=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new K(o.status,s,a)}return s}async function kh(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/deliverables`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new K(n.status,null,`GET /deliverables HTTP ${n.status}`);return(await n.json()).deliverables}var K,_o,je=x(()=>{"use strict";K=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};_o=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});var cl={};ze(cl,{mirrorLag:()=>dE,syncUpstream:()=>uE});import{simpleGit as Dh}from"simple-git";async function uE(t,e,r,n){let o=Dh(e),i=t.defaultBranch??"main",s=n?.upstream??Uh(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/*:${Pr}/*`,["--prune"]);let a=(await o.revparse([`${Pr}/${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?Bh(t.mirror):null);if(!c)return{repo:t.name,upstreamHead:a,updated:!1};let l=await pE(o),u=await al(o,c),p=[];for(let d of l){if(d==="codepipe"||d.startsWith("codepipe/"))continue;let m=(await o.revparse([`${Pr}/${d}`]).catch(()=>"")).trim();!m||u.get(d)===m||p.push(`+${m}:refs/heads/${d}`)}return p.length===0?{repo:t.name,upstreamHead:a,updated:!1}:(await o.push([c,...p]),r.info(`${t.name}: mirror \u2190 ${p.length} branch(es), ${i} @ ${a.slice(0,10)}`),{repo:t.name,upstreamHead:a,updated:!0})}catch(a){let c=a instanceof Error?a.message.split(`
711
+ `)[0]:String(a);return{repo:t.name,upstreamHead:null,updated:!1,error:c}}}async function dE(t,e,r){let n=r?.mirror??(t.mirror?Bh(t.mirror):null);if(!n)return null;let o=r?.upstream??Uh(t);if(!o)return null;let i=Dh(e),s=t.defaultBranch??"main";try{let a=(await al(i,n,s)).get(s);if(!a)return null;let c=(await al(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}:${Pr}/${s}`),await l())}catch{return null}}function Uh(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 Bh(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 pE(t){return(await t.raw(["for-each-ref",Pr,"--format=%(refname)"]).catch(()=>"")).split(`
712
+ `).map(r=>r.trim()).filter(r=>r.startsWith(`${Pr}/`)).map(r=>r.slice(Pr.length+1))}async function al(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(`
713
+ `)){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 Pr,ll=x(()=>{"use strict";Pr="refs/codepipe/upstream"});import{existsSync as Fh,readFileSync as fE,readdirSync as mE}from"node:fs";import{join as Gh}from"node:path";import{simpleGit as hE}from"simple-git";import{parse as gE}from"yaml";function ul(t){let e=new Map,r=Gh(t,Zo);if(!Fh(r))return e;let n;try{n=gE(fE(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 yE(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return kr({modelFormatVersion:2,repos:e})}function Kh(t,e){let r=Gh(t,e);if(!Fh(r))return[];let n=[];for(let o of mE(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...Kh(t,i)):n.push(i)}return n}async function ns(t,e,r={}){let n=[],o=0;for(let d of e){n.push(...d.files);let m=`model/derived/structure/${d.repo}`;for(let f of Kh(t,m))d.emittedShardPaths.has(f)||(n.push({path:f,content:"",deleted:!0}),o++)}let i=ul(t);for(let d of e)i.set(d.repo,{builtFromCommit:d.headCommit,counts:d.counts});n.push({path:Zo,content:yE(i)});let s=Fi(t),a=Gm(s,r.halfLifeDays??nt.halfLifeDays);n.push({path:hr,content:Gi(a)});for(let d of e){let m=[];for(let f of s)for(let g of f.files)re(g.key)?.repo===d.repo&&m.push({kind:"touched_by",from:xe(f.taskKey),to:g.key,...g.churn!==void 0?{weight:g.churn}:{}});n.push({path:ta(d.repo),content:yr({modelFormatVersion:2,repo:d.repo,builtFromCommit:d.headCommit,edges:m})})}let c=hE(t),l=(await c.revparse(["HEAD"]).catch(()=>"")).trim(),u=`model: build ${e.map(d=>`${d.repo}@${d.headCommit.slice(0,10)}`).join(", ")}`;await Ie(t,n,u);let p=(await c.revparse(["HEAD"]).catch(()=>"")).trim();if(p!==l){let{rebuildSearchIndex:d}=await Promise.resolve().then(()=>(Ro(),To));await d(t).catch(()=>{})}return{committed:p!==l,filesWritten:n.filter(d=>!d.deleted).length,filesDeleted:o}}var Hh=x(()=>{"use strict";F();Xc();lt()});var ss={};ze(ss,{bootstrapDaemonModel:()=>kE,bootstrapModelForTargets:()=>gl,bootstrapWorkspaceModel:()=>Vh,modelBootstrapCommand:()=>hl,modelBuildCommand:()=>ml,rebuildWorkspaceModelIfStale:()=>bE});import{existsSync as os}from"node:fs";import{join as sr}from"node:path";import{cancel as wE,intro as Wh,log as dl,outro as pl}from"@clack/prompts";import{simpleGit as fl}from"simple-git";function is(t){wE(t),process.exit(1)}function qh(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:sr(t.root,i.mountAs);if(!os(sr(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 Yh(t){let e=fl(t.dir),r=`origin/${t.defaultBranch}`;return await e.raw(["rev-parse","--verify",r]).then(()=>!0).catch(()=>!1)?r:"HEAD"}async function zh(t,e,r,n){let o=[];for(let i of e)try{let s=await Yc({repo:i.name,repoDir:i.dir,contextDir:t,settings:r,ref:await Yh(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 ml(t){Wh("codepipe model build");let e=Ae();e||is("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{let r=gn(e.contextDir),n=qh(e,t.repo,s=>dl.warn(s)),o=await zh(e.contextDir,n,r,s=>dl.info(s)),i=await ns(e.contextDir,o,{halfLifeDays:r.cochange.halfLifeDays});i.committed?pl(`model updated: ${i.filesWritten} files written, ${i.filesDeleted} stale removed`):pl("model already up to date (no changes)")}catch(r){is(r instanceof Error?r.message:String(r))}}async function hl(t){Wh("codepipe model bootstrap");let e=Ae();e||is("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{await Vh(e,t.repo,{onLog:r=>dl.info(r)})}catch(r){is(r instanceof Error?r.message:String(r))}pl("bootstrap complete")}async function Vh(t,e,r){let n=qh(t,e,r.onLog);return gl(t.contextDir,n,r)}async function gl(t,e,r){let n=gn(t),o=await zh(t,e,n,r.onLog),i=pm(t),s=dm(n.issueKeyPattern,i),a=Cr([...n.ignore,...hn]),c=[];for(let p of o){let d=e.find(f=>f.name===p.repo),m=await mm({repo:p.repo,repoDir:d.dir,headCommit:p.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:s,pathToCurrent:Di(p.identityTable),entityByKey:p.entityByKey,ignored:a,trackerProjectKey:i});c.push(m),r.onLog(`${p.repo}: ${m.size} task events mined from history`)}let{files:l,skippedPipeline:u}=hm(t,c);return u>0&&r.onLog(`${u} events already recorded by the live pipeline \u2014 left untouched`),l.length>0&&await Ie(t,l,`model: bootstrap ${l.length} task events from history`),await ns(t,o,{halfLifeDays:n.cochange.halfLifeDays}),{events:l.length}}async function kE(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:sr(e.root,a),l=s.defaultBranch||"main";c!==e.contextDir&&os(sr(c,".git"))?(await fl(c).fetch(["origin",l]).catch(()=>{}),o.push({name:s.name,dir:c,defaultBranch:l})):(n(`${s.name}: materializing clone in the daemon layout`),await nr(t,s),o.push({name:s.name,dir:_e(t,s.name),defaultBranch:l}))}let i=await gl(e.contextDir,o,{onLog:n});return{repos:o.length,events:i.events}}async function bE(t,e={}){let r=e.onLog??(()=>{}),n=gn(t.contextDir),o=new Map;for(let l of t.repos){if(!l.mirror)continue;let u=l.mountAs==="."?t.root:sr(t.root,l.mountAs);if(!os(sr(u,".git")))continue;let{syncUpstream:p}=await Promise.resolve().then(()=>(ll(),cl)),d=await p(l,u,{info:m=>r(`[mirror] ${m}`),warn:m=>r(`[mirror] ${m}`)});if(d.error||!d.upstreamHead){r(`[mirror] ${l.name}: sync failed (${d.error??"no upstream head"})`);continue}o.set(l.name,d.upstreamHead)}if(!n.enabled)return{rebuilt:[],skipped:[]};let i=[],s=[],a=ul(t.contextDir),c=[];for(let l of t.repos){let u=l.mountAs==="."?t.root:sr(t.root,l.mountAs);if(!os(sr(u,".git")))continue;let p=fl(u),d=l.defaultBranch||"main",m=null;if(l.mirror){if(m=o.get(l.name)??null,!m){r(`[mirror] ${l.name}: map not rebuilt \u2014 sync did not complete`);continue}}else e.fetch&&await p.fetch(["origin",d]).catch(()=>{});let f=m??await Yh({name:l.name,dir:u,defaultBranch:d}),g=(await p.revparse([f]).catch(()=>"")).trim();if(g){if(a.get(l.name)?.builtFromCommit===g){s.push(l.name);continue}try{c.push(await Yc({repo:l.name,repoDir:u,contextDir:t.contextDir,settings:n,ref:g})),i.push(l.name)}catch(k){r(`[model] rebuild of ${l.name} failed: ${k instanceof Error?k.message:String(k)}`)}}}return c.length>0&&(await ns(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 No=x(()=>{"use strict";lt();Hh();zc();Wc();Ui();Eo();bo();it()});var Jh={};ze(Jh,{computeDriftReport:()=>EE,supersededAdrIds:()=>Xh});import{existsSync as yl,readFileSync as wl,readdirSync as kl}from"node:fs";import{join as kn}from"node:path";import{parse as $E}from"yaml";import{simpleGit as vE}from"simple-git";function SE(t,e){let r=kn(t,`model/derived/structure/${e}`),n=[],o="";if(!yl(r))return{nodes:n,builtFromCommit:o};for(let i of kl(r).sort()){if(!i.endsWith(".yaml"))continue;let s;try{let a=jt($E(wl(kn(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 Xh(t){let e=new Set,r=kn(t,"adr");if(!yl(r))return e;for(let n of kl(r).sort()){let o=/^(\d{4})-/.exec(n)?.[1];if(!(!o||!n.endsWith(".md")))try{let i=wl(kn(r,n),"utf-8").slice(0,600).toLowerCase();/status[^\n]*superseded/.test(i)&&e.add(`ADR-${o}`)}catch{}}return e}async function EE(t,e,r){let{nodes:n,builtFromCommit:o}=SE(e,r),i=(await vE(t).revparse(["HEAD"])).trim(),s=await So(t,i),a=new Map(s.map(w=>[w.path,w.blobHash])),c=[],l=[],u=new Set,p=[];for(let w of n){if(w.level==="component"){p.push(w);continue}u.add(w.path);let $=a.get(w.path);$?w.contentHash&&$.slice(0,xE)!==w.contentHash&&c.push(w.key):l.push(w.key)}let d=0,m=new Map,f=new Set;for(let w of s){let $=w.path.lastIndexOf("/"),S=$<0?"":w.path.slice(0,$);m.has(S)||m.set(S,new Set),m.get(S).add(w.path),u.has(w.path)||d++;let T=S;for(;T!==""&&!f.has(T);)f.add(T),T=T.includes("/")?T.slice(0,T.lastIndexOf("/")):""}let g=new Map;for(let w of u){let $=w.lastIndexOf("/"),S=$<0?"":w.slice(0,$);g.has(S)||g.set(S,new Set),g.get(S).add(w)}for(let w of p){if(!f.has(w.path)){l.push(w.key);continue}let $=g.get(w.path)??new Set,S=m.get(w.path)??new Set;($.size!==S.size||[...$].some(v=>!S.has(v)))&&c.push(w.key)}let k=[],h=Xh(e);if(h.size>0){let w=kn(e,"model/facts/annotations"),$=new Map(n.filter(S=>S.entityId).map(S=>[S.entityId,S.key]));if(yl(w))for(let S of kl(w).sort()){if(!S.endsWith(".md"))continue;let T=S.replace(/\.md$/,""),v=$.get(T);if(v)try{(wl(kn(w,S),"utf-8").match(/\bADR-(\d{3,4})\b/g)??[]).map(_=>`ADR-${_.slice(4).padStart(4,"0")}`).some(_=>h.has(_))&&k.push(v)}catch{}}}return{repo:r,builtFromCommit:o,headCommit:i,stale:[...new Set(c)].sort(),orphaned:[...new Set(l)].sort(),superseded:[...new Set(k)].sort(),newFiles:d}}var xE,Zh=x(()=>{"use strict";F();Eo();xE=12});import{execFileSync as NE}from"node:child_process";import{mkdtempSync as OE,mkdirSync as LE,readFileSync as tg,rmSync as ME,writeFileSync as DE}from"node:fs";import{tmpdir as UE}from"node:os";import{dirname as BE,join as rg}from"node:path";function ng(t="codepipe-context"){let e=OE(rg(UE(),"codepipe-ssh-")),r=rg(e,"id_ed25519");try{return NE("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:tg(r,"utf-8"),publicKey:tg(`${r}.pub`,"utf-8").trim()}}finally{ME(e,{recursive:!0,force:!0})}}async function og(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 ig(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 sg(t,e){LE(BE(t),{recursive:!0});let r=e.endsWith(`
714
714
  `)?e:e+`
715
- `;return LE(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var $l=x(()=>{"use strict"});import{existsSync as og,mkdirSync as ig}from"node:fs";import{dirname as sg}from"node:path";import{simpleGit as kn}from"simple-git";function UE(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 BE(t,e){return e?.contextWrite?.token?{user:ao(t),secret:e.contextWrite.token}:t===Vr.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Vr.bitbucket?e?.bitbucket?.apiToken?{user:Lt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function ag(t,e){let r=e.sleep??(i=>new Promise(s=>setTimeout(s,i))),n=e.initialDelayMs??5e3,o=e.maxDelayMs??6e4;for(;;)try{return await t()}catch(i){if(!(i instanceof as))throw i;e.log.warn(`[ctx] ${i.message} \u2014 retrying in ${Math.round(n/1e3)}s (the HUB may be deploying)`),await r(n),n=Math.min(n*2,o)}}async function cs(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 as(c)}let s=i.contextRepo;if(!s)return o.warn("[ctx] project has no Context Repo on HUB \u2014 daemon stays headless (no config report)"),null;let a=BE(vr(s.cloneUrl),r);if(a){let c=await FE({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 GE({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 FE(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=UE(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(og(`${r}/.git`)){let l=kn(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=yc(r);await l.reset(["--hard",`origin/${s}`]),wc(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else ig(sg(r),{recursive:!0}),await kn().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await cg(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 GE(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=ng(i,n),a=rg(e.cloneUrl),c=e.branch;try{if(og(`${r}/.git`)){let l=kn(r);await l.addConfig("core.sshCommand",s,!1,"local"),await l.remote(["set-url","origin",a]),await l.fetch("origin",c),await l.checkout(c);let u=yc(r);await l.reset(["--hard",`origin/${c}`]),wc(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else ig(sg(r),{recursive:!0}),await kn().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await kn(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await cg(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 cg(t){let e=kn(t);await e.raw(["config","user.email"]).then(n=>n.trim()).catch(()=>"")||(await e.addConfig("user.email","farm@codepipe.local",!1,"local"),await e.addConfig("user.name","CodePipe Farm CLI",!1,"local"))}var as,vl=x(()=>{"use strict";F();je();Ut();$l();as=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as KE}from"node:child_process";function HE(){try{return KE("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function ug(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:HE(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var dg=x(()=>{"use strict"});import{homedir as WE}from"node:os";import{mkdirSync as qE,readFileSync as YE,writeFileSync as zE,existsSync as pg}from"node:fs";import{dirname as VE,join as Sl}from"node:path";function XE(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function $t(t){let e=V("SANDBOX_CONFIG");if(e)return e;let r=Sl(WE(),".codepipe","worker");return t?Sl(r,"profiles",t,"config.json"):Sl(r,"config.json")}function fg(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function Le(t){let e=$t(t),r=null;return pg(e)&&(r=JSON.parse(YE(e,"utf-8"))),r?(r.planningLane=XE(),r):null}function mg(t,e){let r=$t(e);qE(VE(r),{recursive:!0}),zE(r,JSON.stringify(t,null,2)+`
716
- `,{mode:384})}var ls=x(()=>{"use strict";Fe();pg(".env")&&process.loadEnvFile(".env")});import JE from"ws";var bn,El=x(()=>{"use strict";bn=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};e&&(n.signal=e);let o=r?`${this.hubUrl}/jobs/claim?lane=${encodeURIComponent(r)}`:`${this.hubUrl}/jobs/claim`;return fetch(o,n)}async submitResult(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/jobs/result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});if(!r.ok)throw new Error(`submitResult failed: ${r.status} ${await r.text()}`)}async heartbeat(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e})};r&&(n.signal=r);let o=await fetch(`${this.hubUrl}/jobs/heartbeat`,n);if(o.status===410)return"claim_lost";if(!o.ok)throw new Error(`heartbeat failed: ${o.status} ${await o.text()}`);return"ok"}async releaseJob(e,r,n){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e,reason:r})};n&&(o.signal=n);let i=await fetch(`${this.hubUrl}/jobs/release`,o);if(!i.ok&&i.status!==409&&i.status!==404)throw new Error(`release failed: ${i.status} ${await i.text()}`)}openControlSocket(){if(!this.token)throw new Error("no sandbox token");let e=this.hubUrl.replace(/^http/,"ws")+`/sandbox/connect?token=${encodeURIComponent(this.token)}`;return new JE(e)}}});import{hostname as ZE}from"node:os";async function _r(t){let e=Le(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${$t(t.profile)}.`),process.exit(1));let r=t.name??ZE(),n=ug({projects:t.projects??[],llm:t.llm??null}),o=new bn(t.hub.replace(/\/$/,"")),i=Pi(),s=Ke(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});mg({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 ${$t(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 hg=x(()=>{"use strict";ut();dg();ls();El()});function gg(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 us(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 yg(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 $n(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 ds=x(()=>{"use strict"});import{spawn as QE}from"node:child_process";function Tl(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function tT(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 rT(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function jr(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Il(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}})+`
717
- `}async function $g(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Ft;let r=$n(e.metadata),n=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",gg(r)];e.model&&e.model.trim().length>0&&n.push("--model",e.model.trim());for(let l of e.addDirs??[])n.push("--add-dir",l);let o=e.onActivity,i=l=>{if(o)try{o(l)}catch{}},s=[],a=null,c=l=>{let u=Date.now(),p=l.type;if(p==="assistant"){let d=l.message;for(let m of d?.content??[]){let f=m.type;if(f==="text"){let g=String(m.text??"").trim();g&&i({ts:u,kind:"text",author:"agent",text:Tl(g,wg)})}else if(f==="tool_use"){let g=String(m.name??""),k=m.input?.file_path??m.input?.path,h=tT(k,e.workspaceDir);i({ts:u,kind:"tool",author:"agent",tool:g,...h?{file:h}:{}})}}return}if(p==="user"){let d=l.message;for(let m of d?.content??[])if(m.type==="tool_result"){let f=m.is_error===!0,g=f?Tl(rT(m.content),200):"";i({ts:u,kind:"tool_result",author:"agent",isError:f,...g?{text:g}:{}})}return}if(p==="result"){a=l;let d=String(l.subtype??"").trim();i({ts:u,kind:"result",author:"agent",...d?{text:d}:{}});return}if(p==="system"){let d=String(l.subtype??"").trim();d&&i({ts:u,kind:"system",author:"agent",text:d})}};return i({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((l,u)=>{let p=QE(t,n,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});p.stdout.setEncoding("utf-8"),p.stderr.setEncoding("utf-8");let d=!1,m=!1,f=null,g=()=>{d=!0,p.kill("SIGTERM"),f=setTimeout(()=>p.kill("SIGKILL"),kg)};e.signal?.addEventListener("abort",g,{once:!0});let k=null,h=()=>{k&&clearTimeout(k),k=setTimeout(()=>{m=!0,console.warn(`[claude:chat] idle for ${bg}ms \u2014 ending session`),p.kill("SIGTERM"),f=setTimeout(()=>p.kill("SIGKILL"),kg)},bg)},w=()=>{f&&clearTimeout(f),k&&clearTimeout(k),e.signal?.removeEventListener("abort",g)},$=!0,S=b=>{if(!(!$||p.stdin.destroyed))try{p.stdin.write(b)}catch{}};S(Il(e.prompt)),h(),(async()=>{try{for await(let b of e.interactive.inbox){if(d||!$)break;if(h(),b.kind==="user")i({ts:Date.now(),kind:"text",author:"user",text:Tl(b.text,wg)}),S(Il(b.text,yg(r)));else{S(Il(eT)),$=!1;try{p.stdin.end()}catch{}break}}}catch{}})();let T="",v=b=>{let I;try{I=JSON.parse(b)}catch{return}c(I)};p.stdout.on("data",b=>{s.push(b),h(),T+=b;let I;for(;(I=T.indexOf(`
718
- `))!==-1;){let _=T.slice(0,I).trim();T=T.slice(I+1),_&&v(_)}}),p.stderr.on("data",b=>{s.push(b);for(let I of b.split(`
719
- `)){let _=I.trim();_&&console.warn(`[claude:chat:stderr] ${_}`)}}),p.on("error",b=>{w(),u(b)}),p.on("close",b=>{if(w(),d){u(new Ft);return}if(m){u(new Error("chat session ended: idle for too long without a reply"));return}T.trim()&&v(T.trim()),console.log(`[claude:chat] exit code=${b}`),l({artifactPaths:[],log:s.join(""),usage:nT(a)})})})}function nT(t){let e=Ht();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=jr(r.input_tokens),e.outputTokens=jr(r.output_tokens),e.cacheReadInputTokens=jr(r.cache_read_input_tokens),e.cacheCreationInputTokens=jr(r.cache_creation_input_tokens)),e.totalCostUsd=jr(t.total_cost_usd),e.numTurns=jr(t.num_turns),e.durationMs=jr(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var wg,kg,bg,eT,vg=x(()=>{"use strict";F();vn();ds();wg=16e3,kg=5e3,bg=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),eT="The user has finished the conversation. Now, based on everything discussed, write the DRAFT.md file in your current working directory following the contract from your instructions (line 1 \u2014 the issue title, \u2264 80 chars; line 2 \u2014 blank; lines 3+ \u2014 the body in Markdown), in the language of the conversation, and end your turn. Write nothing else."});import{spawn as oT}from"node:child_process";import{existsSync as iT}from"node:fs";function aT(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function xg(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: ${sr(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=uT(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=Eg(o.content);console.log(`[claude] tool_result (error)${i?`: ${sr(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)} ${sr(JSON.stringify(e),200)}`),e}function cT(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(sr(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(sr(r.trim().split(`
715
+ `;return DE(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var vl=x(()=>{"use strict"});import{existsSync as ag,mkdirSync as cg}from"node:fs";import{dirname as lg}from"node:path";import{simpleGit as bn}from"simple-git";function FE(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 GE(t,e){return e?.contextWrite?.token?{user:co(t),secret:e.contextWrite.token}:t===Xr.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Xr.bitbucket?e?.bitbucket?.apiToken?{user:Lt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function ug(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 cs))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 ls(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 cs(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=GE(xr(s.cloneUrl),r);if(a){let c=await KE({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 HE({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 KE(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=FE(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(ag(`${r}/.git`)){let l=bn(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=wc(r);await l.reset(["--hard",`origin/${s}`]),kc(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else cg(lg(r),{recursive:!0}),await bn().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await dg(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 HE(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=sg(i,n),a=ig(e.cloneUrl),c=e.branch;try{if(ag(`${r}/.git`)){let l=bn(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=wc(r);await l.reset(["--hard",`origin/${c}`]),kc(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else cg(lg(r),{recursive:!0}),await bn().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await bn(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await dg(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 dg(t){let e=bn(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 cs,xl=x(()=>{"use strict";F();je();Ut();vl();cs=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as WE}from"node:child_process";function qE(){try{return WE("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function fg(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:qE(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var mg=x(()=>{"use strict"});import{homedir as YE}from"node:os";import{mkdirSync as zE,readFileSync as VE,writeFileSync as XE,existsSync as hg}from"node:fs";import{dirname as JE,join as El}from"node:path";function ZE(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function $t(t){let e=X("SANDBOX_CONFIG");if(e)return e;let r=El(YE(),".codepipe","worker");return t?El(r,"profiles",t,"config.json"):El(r,"config.json")}function gg(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function Le(t){let e=$t(t),r=null;return hg(e)&&(r=JSON.parse(VE(e,"utf-8"))),r?(r.planningLane=ZE(),r):null}function yg(t,e){let r=$t(e);zE(JE(r),{recursive:!0}),XE(r,JSON.stringify(t,null,2)+`
716
+ `,{mode:384})}var us=x(()=>{"use strict";Fe();hg(".env")&&process.loadEnvFile(".env")});import QE from"ws";var $n,Tl=x(()=>{"use strict";$n=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};e&&(n.signal=e);let o=r?`${this.hubUrl}/jobs/claim?lane=${encodeURIComponent(r)}`:`${this.hubUrl}/jobs/claim`;return fetch(o,n)}async submitResult(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/jobs/result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});if(!r.ok)throw new Error(`submitResult failed: ${r.status} ${await r.text()}`)}async heartbeat(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e})};r&&(n.signal=r);let o=await fetch(`${this.hubUrl}/jobs/heartbeat`,n);if(o.status===410)return"claim_lost";if(!o.ok)throw new Error(`heartbeat failed: ${o.status} ${await o.text()}`);return"ok"}async releaseJob(e,r,n){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e,reason:r})};n&&(o.signal=n);let i=await fetch(`${this.hubUrl}/jobs/release`,o);if(!i.ok&&i.status!==409&&i.status!==404)throw new Error(`release failed: ${i.status} ${await i.text()}`)}openControlSocket(){if(!this.token)throw new Error("no sandbox token");let e=this.hubUrl.replace(/^http/,"ws")+`/sandbox/connect?token=${encodeURIComponent(this.token)}`;return new QE(e)}}});import{hostname as eT}from"node:os";async function _r(t){let e=Le(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${$t(t.profile)}.`),process.exit(1));let r=t.name??eT(),n=fg({projects:t.projects??[],llm:t.llm??null}),o=new $n(t.hub.replace(/\/$/,"")),i=_i(),s=Ke(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});yg({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 ${$t(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 wg=x(()=>{"use strict";ut();mg();us();Tl()});function kg(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 ds(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 bg(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 vn(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 ps=x(()=>{"use strict"});import{spawn as tT}from"node:child_process";function Rl(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function nT(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 oT(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function jr(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Il(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}})+`
717
+ `}async function Sg(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Ft;let r=vn(e.metadata),n=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",kg(r)];e.model&&e.model.trim().length>0&&n.push("--model",e.model.trim());for(let l of e.addDirs??[])n.push("--add-dir",l);let o=e.onActivity,i=l=>{if(o)try{o(l)}catch{}},s=[],a=null,c=l=>{let u=Date.now(),p=l.type;if(p==="assistant"){let d=l.message;for(let m of d?.content??[]){let f=m.type;if(f==="text"){let g=String(m.text??"").trim();g&&i({ts:u,kind:"text",author:"agent",text:Rl(g,$g)})}else if(f==="tool_use"){let g=String(m.name??""),k=m.input?.file_path??m.input?.path,h=nT(k,e.workspaceDir);i({ts:u,kind:"tool",author:"agent",tool:g,...h?{file:h}:{}})}}return}if(p==="user"){let d=l.message;for(let m of d?.content??[])if(m.type==="tool_result"){let f=m.is_error===!0,g=f?Rl(oT(m.content),200):"";i({ts:u,kind:"tool_result",author:"agent",isError:f,...g?{text:g}:{}})}return}if(p==="result"){a=l;let d=String(l.subtype??"").trim();i({ts:u,kind:"result",author:"agent",...d?{text:d}:{}});return}if(p==="system"){let d=String(l.subtype??"").trim();d&&i({ts:u,kind:"system",author:"agent",text:d})}};return i({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((l,u)=>{let p=tT(t,n,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});p.stdout.setEncoding("utf-8"),p.stderr.setEncoding("utf-8");let d=!1,m=!1,f=null,g=()=>{d=!0,p.kill("SIGTERM"),f=setTimeout(()=>p.kill("SIGKILL"),vg)};e.signal?.addEventListener("abort",g,{once:!0});let k=null,h=()=>{k&&clearTimeout(k),k=setTimeout(()=>{m=!0,console.warn(`[claude:chat] idle for ${xg}ms \u2014 ending session`),p.kill("SIGTERM"),f=setTimeout(()=>p.kill("SIGKILL"),vg)},xg)},w=()=>{f&&clearTimeout(f),k&&clearTimeout(k),e.signal?.removeEventListener("abort",g)},$=!0,S=b=>{if(!(!$||p.stdin.destroyed))try{p.stdin.write(b)}catch{}};S(Il(e.prompt)),h(),(async()=>{try{for await(let b of e.interactive.inbox){if(d||!$)break;if(h(),b.kind==="user")i({ts:Date.now(),kind:"text",author:"user",text:Rl(b.text,$g)}),S(Il(b.text,bg(r)));else{S(Il(rT)),$=!1;try{p.stdin.end()}catch{}break}}}catch{}})();let T="",v=b=>{let R;try{R=JSON.parse(b)}catch{return}c(R)};p.stdout.on("data",b=>{s.push(b),h(),T+=b;let R;for(;(R=T.indexOf(`
718
+ `))!==-1;){let _=T.slice(0,R).trim();T=T.slice(R+1),_&&v(_)}}),p.stderr.on("data",b=>{s.push(b);for(let R of b.split(`
719
+ `)){let _=R.trim();_&&console.warn(`[claude:chat:stderr] ${_}`)}}),p.on("error",b=>{w(),u(b)}),p.on("close",b=>{if(w(),d){u(new Ft);return}if(m){u(new Error("chat session ended: idle for too long without a reply"));return}T.trim()&&v(T.trim()),console.log(`[claude:chat] exit code=${b}`),l({artifactPaths:[],log:s.join(""),usage:iT(a)})})})}function iT(t){let e=Ht();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=jr(r.input_tokens),e.outputTokens=jr(r.output_tokens),e.cacheReadInputTokens=jr(r.cache_read_input_tokens),e.cacheCreationInputTokens=jr(r.cache_creation_input_tokens)),e.totalCostUsd=jr(t.total_cost_usd),e.numTurns=jr(t.num_turns),e.durationMs=jr(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var $g,vg,xg,rT,Eg=x(()=>{"use strict";F();xn();ps();$g=16e3,vg=5e3,xg=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),rT="The user has finished the conversation. Now, based on everything discussed, write the DRAFT.md file in your current working directory following the contract from your instructions (line 1 \u2014 the issue title, \u2264 80 chars; line 2 \u2014 blank; lines 3+ \u2014 the body in Markdown), in the language of the conversation, and end your turn. Write nothing else."});import{spawn as sT}from"node:child_process";import{existsSync as aT}from"node:fs";function lT(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function Tg(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: ${ar(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=pT(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=Ig(o.content);console.log(`[claude] tool_result (error)${i?`: ${ar(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)} ${ar(JSON.stringify(e),200)}`),e}function uT(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(ar(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(ar(r.trim().split(`
720
720
  `).slice(-5).join(`
721
- `),500)),n.join(" \u2014 ")}function lT(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 Eg(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function uT(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=${sr(r,80)}`}return""}function sr(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function He(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function dT(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=He(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:He(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 pT(t,e,r,n){let o=Ht(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=He(i.input_tokens),o.outputTokens=He(i.output_tokens),o.cacheReadInputTokens=He(i.cache_read_input_tokens),o.cacheCreationInputTokens=He(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=He(t?.total_cost_usd),o.numTurns=t&&He(t.num_turns)>0?He(t.num_turns):r,o.durationMs=He(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}function fT(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:sr(c,Sg)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,p=mT(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?sr(Eg(s.content),Sg):"";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 mT(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 xn,Ft,sT,No,Sg,vn=x(()=>{"use strict";F();vg();ds();xn=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Ft=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},sT=5e3;No=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return $g(this.binary,e);if(e.signal?.aborted)throw new Ft;let r=["-p",aT(e.prompt),"--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",us($n(e.metadata))];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let f of e.addDirs??[])r.push("--add-dir",f);e.settings&&Object.keys(e.settings).length>0&&r.push("--settings",JSON.stringify(e.settings));let n=[],o=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,u=f=>{if(f){if(f.type==="result"){i=f;return}if(f.type==="rate_limit_event"){let g=dT(f.rate_limit_info);g&&(!l||g.utilization>l.utilization)&&(l=g);return}if(f.type==="assistant"){let g=f.message;typeof g?.model=="string"&&(c=g.model);let k=g?.usage;k&&(a+=1,s.input+=He(k.input_tokens),s.output+=He(k.output_tokens),s.cacheRead+=He(k.cache_read_input_tokens),s.cacheCreate+=He(k.cache_creation_input_tokens))}}},p=e.role,d=e.onActivity,m=f=>{if(d)for(let g of fT(f,e.workspaceDir))try{d(g)}catch{}};return d?.({ts:Date.now(),kind:"start",text:`${p} job started`}),console.log(`[claude] spawn ${this.binary} role=${p}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((f,g)=>{let k=oT(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{},CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:"1800000"}});k.stdout.setEncoding("utf-8"),k.stderr.setEncoding("utf-8");let h=!1,w=null,$=()=>{h=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${p}`),k.kill("SIGTERM"),w=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),k.kill("SIGKILL")},sT)};e.signal?.addEventListener("abort",$,{once:!0});let S=()=>{w&&clearTimeout(w),e.signal?.removeEventListener("abort",$)},T="";k.stdout.on("data",v=>{n.push(v),T+=v;let b;for(;(b=T.indexOf(`
722
- `))!==-1;){let I=T.slice(0,b).trim();if(T=T.slice(b+1),I){let _=xg(I);u(_),_&&m(_)}}}),k.stderr.on("data",v=>{n.push(v),o.push(v);for(let b of v.split(`
723
- `)){let I=b.trim();I&&console.warn(`[claude:stderr] ${I}`)}}),k.on("error",v=>{S(),g(v)}),k.on("close",v=>{if(S(),h){g(new Ft);return}if(T.trim()){let I=xg(T.trim());u(I),I&&m(I)}let b=i?.is_error===!0;if(v!==0||b){let I=typeof i?.api_error_status=="number"?i.api_error_status:void 0,_=typeof i?.subtype=="string"?i.subtype:void 0,G=typeof i?.result=="string"?i.result:void 0;g(new xn(cT(v,i,o.join("")),{code:v,apiErrorStatus:I,subtype:_,resultText:G,retryAfterMs:lT(i)}));return}console.log("[claude] exit code=0"),f({artifactPaths:[],log:n.join(""),usage:pT(i,s,a,c),...l?{rateLimit:l}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(n=>n.includes("/")&&iT(n))}};Sg=200});import{mkdirSync as hT,writeFileSync as Sn}from"node:fs";import{dirname as gT,join as En}from"node:path";function Tg(t,e,r){let n=En(t,e);hT(gT(n),{recursive:!0}),Sn(n,r)}function yT(t,e,r){return`# ${t} \u2014 Estimate
721
+ `),500)),n.join(" \u2014 ")}function dT(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 Ig(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function pT(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=${ar(r,80)}`}return""}function ar(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function He(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function fT(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=He(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:He(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 mT(t,e,r,n){let o=Ht(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=He(i.input_tokens),o.outputTokens=He(i.output_tokens),o.cacheReadInputTokens=He(i.cache_read_input_tokens),o.cacheCreationInputTokens=He(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=He(t?.total_cost_usd),o.numTurns=t&&He(t.num_turns)>0?He(t.num_turns):r,o.durationMs=He(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}function hT(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:ar(c,Rg)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,p=gT(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?ar(Ig(s.content),Rg):"";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 gT(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 Sn,Ft,cT,Lo,Rg,xn=x(()=>{"use strict";F();Eg();ps();Sn=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Ft=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},cT=5e3;Lo=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return Sg(this.binary,e);if(e.signal?.aborted)throw new Ft;let r=["-p",lT(e.prompt),"--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",ds(vn(e.metadata))];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let f of e.addDirs??[])r.push("--add-dir",f);e.settings&&Object.keys(e.settings).length>0&&r.push("--settings",JSON.stringify(e.settings));let n=[],o=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,u=f=>{if(f){if(f.type==="result"){i=f;return}if(f.type==="rate_limit_event"){let g=fT(f.rate_limit_info);g&&(!l||g.utilization>l.utilization)&&(l=g);return}if(f.type==="assistant"){let g=f.message;typeof g?.model=="string"&&(c=g.model);let k=g?.usage;k&&(a+=1,s.input+=He(k.input_tokens),s.output+=He(k.output_tokens),s.cacheRead+=He(k.cache_read_input_tokens),s.cacheCreate+=He(k.cache_creation_input_tokens))}}},p=e.role,d=e.onActivity,m=f=>{if(d)for(let g of hT(f,e.workspaceDir))try{d(g)}catch{}};return d?.({ts:Date.now(),kind:"start",text:`${p} job started`}),console.log(`[claude] spawn ${this.binary} role=${p}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((f,g)=>{let k=sT(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{},CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:"1800000"}});k.stdout.setEncoding("utf-8"),k.stderr.setEncoding("utf-8");let h=!1,w=null,$=()=>{h=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${p}`),k.kill("SIGTERM"),w=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),k.kill("SIGKILL")},cT)};e.signal?.addEventListener("abort",$,{once:!0});let S=()=>{w&&clearTimeout(w),e.signal?.removeEventListener("abort",$)},T="";k.stdout.on("data",v=>{n.push(v),T+=v;let b;for(;(b=T.indexOf(`
722
+ `))!==-1;){let R=T.slice(0,b).trim();if(T=T.slice(b+1),R){let _=Tg(R);u(_),_&&m(_)}}}),k.stderr.on("data",v=>{n.push(v),o.push(v);for(let b of v.split(`
723
+ `)){let R=b.trim();R&&console.warn(`[claude:stderr] ${R}`)}}),k.on("error",v=>{S(),g(v)}),k.on("close",v=>{if(S(),h){g(new Ft);return}if(T.trim()){let R=Tg(T.trim());u(R),R&&m(R)}let b=i?.is_error===!0;if(v!==0||b){let R=typeof i?.api_error_status=="number"?i.api_error_status:void 0,_=typeof i?.subtype=="string"?i.subtype:void 0,G=typeof i?.result=="string"?i.result:void 0;g(new Sn(uT(v,i,o.join("")),{code:v,apiErrorStatus:R,subtype:_,resultText:G,retryAfterMs:dT(i)}));return}console.log("[claude] exit code=0"),f({artifactPaths:[],log:n.join(""),usage:mT(i,s,a,c),...l?{rateLimit:l}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(n=>n.includes("/")&&aT(n))}};Rg=200});import{mkdirSync as yT,writeFileSync as En}from"node:fs";import{dirname as wT,join as Tn}from"node:path";function Cg(t,e,r){let n=Tn(t,e);yT(wT(n),{recursive:!0}),En(n,r)}function kT(t,e,r){return`# ${t} \u2014 Estimate
724
724
 
725
725
  **Title:** ${e}
726
726
 
@@ -741,7 +741,7 @@ production-grade estimates.)
741
741
  ${r.split(`
742
742
  `).slice(0,8).join(`
743
743
  `).trim()||"(empty)"}
744
- `}function wT(t,e,r,n){let o=n?`
744
+ `}function bT(t,e,r,n){let o=n?`
745
745
  ## Reviewer rework instruction
746
746
 
747
747
  > ${n.split(`
@@ -770,10 +770,10 @@ TBD (mock runner does not yet inspect project code).
770
770
  ${r.split(`
771
771
  `).slice(0,8).join(`
772
772
  `).trim()||"(empty)"}
773
- `}function kT(t){return`# ${t} \u2014 Open questions
773
+ `}function $T(t){return`# ${t} \u2014 Open questions
774
774
 
775
775
  (none \u2014 mock runner did not surface ambiguities.)
776
- `}function bT(t,e,r){let n=r?` (rework: ${r.split(`
776
+ `}function vT(t,e,r){let n=r?` (rework: ${r.split(`
777
777
  `)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
778
778
  index 0000000..1111111 100644
779
779
  --- a/CHANGELOG.md
@@ -784,7 +784,7 @@ index 0000000..1111111 100644
784
784
  +- mock-runner placeholder change for slice 5 testing.
785
785
  +
786
786
  # Changelog
787
- `}function $T(t,e,r){return`# ${t} \u2014 Diff summary
787
+ `}function xT(t,e,r){return`# ${t} \u2014 Diff summary
788
788
 
789
789
  **Title:** ${e}
790
790
  ${r?`
@@ -795,156 +795,156 @@ ${r?`
795
795
  - \`CHANGELOG.md\` \u2014 added entry for ${t}.
796
796
 
797
797
  (Mock-runner output. Replace with claude-headless for production patches.)
798
- `}var Oo,Rl=x(()=>{"use strict";F();vn();Oo=class{name(){return"mock"}async run(e){if(e.interactive)return this.runInteractive(e);let r=e.metadata??{},n=r.trackerIssueKey??"TASK",o=r.taskTitle??"(unknown task)",i=r.taskDescription??"",s=[];if(e.role==="estimate"){let a=yT(n,o,i);Sn(En(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(En(e.workspaceDir,"PLAN.md"),wT(n,o,i,a)),s.push("PLAN.md"),Sn(En(e.workspaceDir,"QUESTIONS.md"),kT(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Tg(e.workspaceDir,"changes/sample.patch",bT(n,o,a)),s.push("changes/sample.patch"),Tg(e.workspaceDir,"SOLUTION.md",$T(n,o,a)),s.push("SOLUTION.md")}else e.role==="rework"&&(Sn(En(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
799
- `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:Ht()}}async runInteractive(e){let r=e.onActivity,n=i=>{r?.({ts:Date.now(),kind:"text",author:"agent",text:i}),r?.({ts:Date.now(),kind:"result",author:"agent",text:"success"})};r?.({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),n("Hi! Describe the task you'd like to formulate.");let o="Draft from chat";for await(let i of e.interactive.inbox){if(e.signal?.aborted)throw new Ft;if(i.kind==="user")r?.({ts:Date.now(),kind:"text",author:"user",text:i.text}),i.text.trim()&&(o=i.text.trim().slice(0,80)),n(`Got it: **${i.text.trim()}**. Anything else to clarify?`);else break}return Sn(En(e.workspaceDir,"DRAFT.md"),`${o}
798
+ `}var Mo,Cl=x(()=>{"use strict";F();xn();Mo=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=kT(n,o,i);En(Tn(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;En(Tn(e.workspaceDir,"PLAN.md"),bT(n,o,i,a)),s.push("PLAN.md"),En(Tn(e.workspaceDir,"QUESTIONS.md"),$T(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Cg(e.workspaceDir,"changes/sample.patch",vT(n,o,a)),s.push("changes/sample.patch"),Cg(e.workspaceDir,"SOLUTION.md",xT(n,o,a)),s.push("SOLUTION.md")}else e.role==="rework"&&(En(Tn(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
799
+ `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:Ht()}}async runInteractive(e){let r=e.onActivity,n=i=>{r?.({ts:Date.now(),kind:"text",author:"agent",text:i}),r?.({ts:Date.now(),kind:"result",author:"agent",text:"success"})};r?.({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),n("Hi! Describe the task you'd like to formulate.");let o="Draft from chat";for await(let i of e.interactive.inbox){if(e.signal?.aborted)throw new Ft;if(i.kind==="user")r?.({ts:Date.now(),kind:"text",author:"user",text:i.text}),i.text.trim()&&(o=i.text.trim().slice(0,80)),n(`Got it: **${i.text.trim()}**. Anything else to clarify?`);else break}return En(Tn(e.workspaceDir,"DRAFT.md"),`${o}
800
800
 
801
801
  Produced by the interactive chat (mock runner).
802
- `),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:Ht()}}}});function Ig(t){switch(t){case"mock":return new Oo;case"claude-headless":return new No;default:return null}}function Rg(t,e){let r=e&&e.trim().length>0?e.trim():Xe;return t==="mock"?!0:t==="claude-headless"?r==="claude":!1}var Cg=x(()=>{"use strict";F();vn();Rl();vn();Rl()});function _g(t=process.env){return{maxAttempts:ps(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:ps(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:ps(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:ps(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function ET(t){if(t instanceof xn){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return xT.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&ST.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:vT.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:Pg.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 Pg.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function jg(t){if(t instanceof xn){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&Ag.test(n)}let e=t instanceof Error?t.message:String(t);return Ag.test(e)}function TT(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 Ng(t,e,r){let n=r.sleep??(s=>new Promise(a=>setTimeout(a,s))),o=Date.now()+r.policy.totalBudgetMs,i="";for(let s=1;;s++)try{return await t.run(e)}catch(a){i=a instanceof Error?a.message:String(a);let c=ET(a),l=s>=r.policy.maxAttempts;if(!c.retryable||l||r.aborted())throw s>1?new Error(`agent failed after ${s} attempts: ${i}`):a;let u=TT(s,r.policy,c.retryAfterMs);if(Date.now()+u>o)throw new Error(`agent failed after ${s} attempts (retry budget exhausted): ${i}`);console.warn(`[job] ${r.jobId} agent attempt ${s}/${r.policy.maxAttempts} failed (retryable: ${c.reason}) \u2014 cleaning workspace, backoff ${u}ms`),await r.onBeforeRetry(),await n(u)}}function ps(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}var vT,Pg,xT,ST,Ag,Og=x(()=>{"use strict";vn();vT=new Set([429,500,502,503,529]),Pg=/(\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,xT=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,ST=new Set(["error_max_turns"]);Ag=/(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 IT,writeFileSync as RT}from"node:fs";import{homedir as CT}from"node:os";import{join as Lg}from"node:path";function Dg(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 Ug(t,e,r,n){try{let o=Lg(CT(),".codepipe","debug",Mg(t));IT(o,{recursive:!0});let i=new Date().toISOString().replace(/[:.]/g,"-"),s=Lg(o,`${i}-${Mg(e)}-${r}.md`);return RT(s,n),s}catch{return null}}var Mg,Bg=x(()=>{"use strict";Mg=t=>t.replace(/[^A-Za-z0-9._-]/g,"_")});import{mkdtempSync as PT,rmSync as AT,writeFileSync as Fg}from"node:fs";import{tmpdir as _T}from"node:os";import{join as Cl}from"node:path";function fs(t){return`[url "https://${t}/"]
802
+ `),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:Ht()}}}});function Pg(t){switch(t){case"mock":return new Mo;case"claude-headless":return new Lo;default:return null}}function Ag(t,e){let r=e&&e.trim().length>0?e.trim():Xe;return t==="mock"?!0:t==="claude-headless"?r==="claude":!1}var _g=x(()=>{"use strict";F();xn();Cl();xn();Cl()});function Og(t=process.env){return{maxAttempts:fs(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:fs(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:fs(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:fs(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function RT(t){if(t instanceof Sn){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return ET.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&TT.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:ST.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:jg.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 jg.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function Lg(t){if(t instanceof Sn){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&Ng.test(n)}let e=t instanceof Error?t.message:String(t);return Ng.test(e)}function IT(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 Mg(t,e,r){let n=r.sleep??(s=>new Promise(a=>setTimeout(a,s))),o=Date.now()+r.policy.totalBudgetMs,i="";for(let s=1;;s++)try{return await t.run(e)}catch(a){i=a instanceof Error?a.message:String(a);let c=RT(a),l=s>=r.policy.maxAttempts;if(!c.retryable||l||r.aborted())throw s>1?new Error(`agent failed after ${s} attempts: ${i}`):a;let u=IT(s,r.policy,c.retryAfterMs);if(Date.now()+u>o)throw new Error(`agent failed after ${s} attempts (retry budget exhausted): ${i}`);console.warn(`[job] ${r.jobId} agent attempt ${s}/${r.policy.maxAttempts} failed (retryable: ${c.reason}) \u2014 cleaning workspace, backoff ${u}ms`),await r.onBeforeRetry(),await n(u)}}function fs(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}var ST,jg,ET,TT,Ng,Dg=x(()=>{"use strict";xn();ST=new Set([429,500,502,503,529]),jg=/(\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,ET=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,TT=new Set(["error_max_turns"]);Ng=/(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 CT,writeFileSync as PT}from"node:fs";import{homedir as AT}from"node:os";import{join as Ug}from"node:path";function Fg(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 Gg(t,e,r,n){try{let o=Ug(AT(),".codepipe","debug",Bg(t));CT(o,{recursive:!0});let i=new Date().toISOString().replace(/[:.]/g,"-"),s=Ug(o,`${i}-${Bg(e)}-${r}.md`);return PT(s,n),s}catch{return null}}var Bg,Kg=x(()=>{"use strict";Bg=t=>t.replace(/[^A-Za-z0-9._-]/g,"_")});import{mkdtempSync as _T,rmSync as jT,writeFileSync as Hg}from"node:fs";import{tmpdir as NT}from"node:os";import{join as Pl}from"node:path";function ms(t){return`[url "https://${t}/"]
803
803
  insteadOf = git@${t}:
804
804
  insteadOf = ssh://git@${t}/
805
- `}function Wg(t,e){if(t.length===0)return null;let r=PT(Cl(_T(),"devpipe-gitcreds-")),n=Cl(r,"credentials"),o=Cl(r,"gitconfig");return Fg(n,t.join(`
805
+ `}function zg(t,e){if(t.length===0)return null;let r=_T(Pl(NT(),"devpipe-gitcreds-")),n=Pl(r,"credentials"),o=Pl(r,"gitconfig");return Hg(n,t.join(`
806
806
  `)+`
807
- `,{mode:384}),Fg(o,`[credential]
807
+ `,{mode:384}),Hg(o,`[credential]
808
808
  helper = store --file=${n}
809
- `+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{AT(r,{recursive:!0,force:!0})}catch{}}}}function Pl(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(Gg)),(!n||n==="gitlab")&&(e.push(`https://oauth2:${t.mirrorWrite.token}@gitlab.com`),r.push(Hg)),(!n||n==="bitbucket")&&(e.push(`https://${Lt}:${encodeURIComponent(t.mirrorWrite.token)}@bitbucket.org`),r.push(Kg))}return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(Gg)),t.bitbucket?.apiToken&&(e.push(`https://${Lt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(Kg)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(Hg)),Wg(e,r)}function qg(t,e){if(t.contextWrite?.token){let r=vr(e)??"github.com",n=ao(r);return Wg([`https://${n}:${t.contextWrite.token}@${r}`],[fs(r)])}return Pl(t)}var Gg,Kg,Hg,Yg=x(()=>{"use strict";F();Gg=fs("github.com"),Kg=fs("bitbucket.org"),Hg=fs("gitlab.com")});import{spawn as Vg}from"node:child_process";import{existsSync as ms,mkdirSync as Lo,readFileSync as jT,rmSync as Al,symlinkSync as NT}from"node:fs";import{homedir as OT}from"node:os";import{dirname as In,join as ar}from"node:path";function Xg(t){let e=ar(OT(),".codepipe-sandbox","repos");return t?ar(e,t):e}function Jg(t,e){let n=(Tn.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{Tn.get(t)===o&&Tn.delete(t)},()=>{Tn.get(t)===o&&Tn.delete(t)});return Tn.set(t,o),n}function zg(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 LT(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 Zg(t,e,r,n,o){let i=async c=>{await ue(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await ue(t,["reset","--hard",`origin/${c}`],o),await ue(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!zg(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{ms(t)&&Al(t,{recursive:!0,force:!0}),Lo(In(t),{recursive:!0});try{return await ue(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!zg(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),ms(t)&&Al(t,{recursive:!0,force:!0}),Lo(In(t),{recursive:!0}),await ue(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(ms(ar(t,".git")))try{return await s()}catch(c){if(!LT(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 Qg(t){await ue(t.workspacePath,["reset","--hard",t.baseSha]),await ue(t.workspacePath,["clean","-fdx"])}async function ey(t,e){let r=t.workspacePath;await ue(r,["add","-A"]);let n=(await Ne(r,["write-tree"])).trim(),o=(await Ne(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:Rn,GIT_AUTHOR_EMAIL:Cn,GIT_COMMITTER_NAME:Rn,GIT_COMMITTER_EMAIL:Cn};return(await Ne(r,["commit-tree",n,"-m",e],i)).trim()}async function ty(t,e,r,n,o){try{await ue(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw vr(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 ry(t,e){return Ne(t.workspacePath,["diff","--binary",t.baseSha,e])}async function ny(t,e,r,n,o){await ue(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await ue(t.workspacePath,["checkout","--force",r])}async function oy(t,e,r,n,o,i){let s=t.workspacePath;await ue(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await Ne(s,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=f=>Ne(s,["rev-parse","-q","--verify",`${f}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await Ne(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ue(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(g=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(g)}`)}),await c(n)||await ue(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:Rn,GIT_AUTHOR_EMAIL:Cn,GIT_COMMITTER_NAME:Rn,GIT_COMMITTER_EMAIL:Cn},u=(await Ne(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),p=(await Ne(s,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await ue(s,["cherry-pick","--quit"],l).catch(()=>{});let d=null;try{await ue(s,["cherry-pick","--no-commit",p],l)}catch(f){d=f instanceof Error?f.message:String(f)}let m=(await Ne(s,["diff","--name-only","--diff-filter=U"])).split(`
810
- `).map(f=>f.trim()).filter(f=>f.length>0);if(d&&m.length===0)throw await ue(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${d}`);return m}async function _l(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:Rn,GIT_AUTHOR_EMAIL:Cn,GIT_COMMITTER_NAME:Rn,GIT_COMMITTER_EMAIL:Cn};(await Ne(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ue(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 ue(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await ue(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await Ne(n,["diff","--name-only","--diff-filter=U"])).split(`
811
- `).map(l=>l.trim()).filter(l=>l.length>0),c=await Ne(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}function ue(t,e,r){return new Promise((n,o)=>{let i=Vg("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}):
812
- ${s.join("").trim()||"(no stderr)"}`))})})}function Ne(t,e,r){return new Promise((n,o)=>{let i=Vg("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}):
813
- ${a.join("").trim()||"(no stderr)"}`))})})}function iy(t,e){ms(t)&&Al(t,{recursive:!0,force:!0}),Lo(In(t),{recursive:!0}),NT(e,t,"dir")}async function sy(t,e,r){await ue(t,["worktree","prune"]).catch(()=>{}),Lo(In(r),{recursive:!0}),await ue(t,["worktree","add","--detach",r,`origin/${e}`])}async function MT(t,e,r){Lo(In(r),{recursive:!0}),await ue(In(r),["clone","--quiet","--no-checkout",t,r]),await ue(r,["checkout","--force","--detach",e])}async function ay(t,e,r,n="worktree",o,i){return r.length===0?[]:Jg(e,async()=>{let s=[];for(let a of r){let c=ar(Xg(i),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await Zg(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 Ne(c,["rev-parse","HEAD"])).trim(),p=ar(t,"code",a.name);n==="direct"?(iy(p,c),console.log(`[git] code: linked ${p} \u2192 ${c} @ ${u.slice(0,10)}`)):n==="clone"?(await MT(c,u,p),console.log(`[git] code: clone ${p} \u2190 ${c} @ ${u.slice(0,10)}`)):(await sy(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 cy(t,e,r,n="worktree",o,i){if(!r||!r.cloneUrl)return null;let s=r;return Jg(e,async()=>{let a=ar(Xg(i),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);try{await Zg(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=ar(t,"context");n==="direct"?(iy(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await sy(a,s.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await Ne(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function ly(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await ue(r,["add","-A",...n]).catch(()=>{});let o;try{o=await Ne(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
814
- `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=jT(ar(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var Tn,Rn,Cn,uy=x(()=>{"use strict";F();Tn=new Map;Rn="CodePipe Agent",Cn="codepipe@codepartner.ee"});import{existsSync as DT,readFileSync as UT}from"node:fs";import{join as BT}from"node:path";import{parse as FT}from"yaml";function dy(t){if(!t)return!1;let e=BT(t,jl);if(!DT(e))return!1;try{let r=FT(UT(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 jl,py=x(()=>{"use strict";jl="knowledge/build.yaml"});import{readFileSync as GT}from"node:fs";import{join as KT}from"node:path";function fy(t){let e=KT(t,Mo),r;try{r=GT(e,"utf-8")}catch{throw new cr(`BUILD produced no ${Mo} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new cr(`${Mo} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new cr(`${Mo} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new cr(`${Mo}: "ok" must be a boolean`);let i=o.ok,a=(Array.isArray(o.steps)?o.steps:[]).flatMap(u=>{if(!u||typeof u!="object")return[];let p=u,d=typeof p.name=="string"?p.name:null,m=typeof p.exitCode=="number"?p.exitCode:null;if(d===null||m===null)return[];let f={name:d,exitCode:m};return typeof p.durationMs=="number"&&(f.durationMs=p.durationMs),[f]}),c=typeof o.logTail=="string"?HT(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 HT(t){let e=Buffer.from(t,"utf-8");return e.length<=Nl?t:`\u2026 [${e.length-Nl} bytes elided] \u2026
815
- `+e.subarray(e.length-Nl).toString("utf-8")}var Nl,cr,Mo,my=x(()=>{"use strict";Nl=8*1024,cr=class extends Error{},Mo="meta/build-result.json"});import{readFileSync as WT}from"node:fs";import{join as qT}from"node:path";function gy(t){let e=qT(t,Pn),r;try{r=WT(e,"utf-8")}catch{throw new Gt(`code review produced no ${Pn} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(c){throw new Gt(`${Pn} is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(!n||typeof n!="object")throw new Gt(`${Pn} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new Gt(`${Pn}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?hy(o.remarks,YT):"";if(!i&&s.trim().length===0)throw new Gt(`${Pn}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?hy(o.summary,zT):"";return{approved:i,remarks:s,summary:a}}function hy(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
816
- \u2026 [${r.length-e} bytes elided]`}var YT,zT,Gt,Pn,yy=x(()=>{"use strict";YT=16*1024,zT=4*1024,Gt=class extends Error{},Pn="meta/review-result.json"});import{readFileSync as VT,statSync as XT}from"node:fs";import{join as wy}from"node:path";function nI(t){return t.startsWith("meta/")||rI.has(t)}function oI(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 iI(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function ky(t,e,r){let n=r?.maxBytes??JT,o=r?.totalBytes??ZT,i=r?.maxCount??QT,s=e.map((f,g)=>{let k=null;try{k=XT(wy(t,f)).size}catch{}return{path:f,index:g,size:k}}),a=[...s].sort((f,g)=>{let k=h=>nI(h.path)?0:1;return k(f)!==k(g)?k(f)-k(g):(f.size??0)-(g.size??0)}),c=a.slice(0,i),l=a.slice(i).sort((f,g)=>f.index-g.index).map(f=>f.path),u=new Array(s.length),p=[],d=0;for(let f of c){let g=null;if(f.size!==null&&f.size<=n&&d+f.size<=o)try{g=VT(wy(t,f.path))}catch{}if(g!==null){d+=g.length,u[f.index]={path:f.path,contentBase64:g.toString("base64")};continue}let k=f.size===null?iI(f.path):oI(f.path,f.size,n,o),h=Buffer.from(k,"utf-8");d+=h.length,u[f.index]={path:f.path,contentBase64:h.toString("base64")},p.push({path:f.path,bytes:f.size??0})}let m=u.filter(f=>f!==void 0);if(l.length>0){let f=l.slice(0,tI),g=`# Artifacts omitted from upload
809
+ `+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{jT(r,{recursive:!0,force:!0})}catch{}}}}function Al(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(Wg)),(!n||n==="gitlab")&&(e.push(`https://oauth2:${t.mirrorWrite.token}@gitlab.com`),r.push(Yg)),(!n||n==="bitbucket")&&(e.push(`https://${Lt}:${encodeURIComponent(t.mirrorWrite.token)}@bitbucket.org`),r.push(qg))}return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(Wg)),t.bitbucket?.apiToken&&(e.push(`https://${Lt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(qg)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(Yg)),zg(e,r)}function Vg(t,e){if(t.contextWrite?.token){let r=xr(e)??"github.com",n=co(r);return zg([`https://${n}:${t.contextWrite.token}@${r}`],[ms(r)])}return Al(t)}var Wg,qg,Yg,Xg=x(()=>{"use strict";F();Wg=ms("github.com"),qg=ms("bitbucket.org"),Yg=ms("gitlab.com")});import{spawn as Zg}from"node:child_process";import{existsSync as hs,mkdirSync as Do,readFileSync as OT,rmSync as _l,symlinkSync as LT}from"node:fs";import{homedir as MT}from"node:os";import{dirname as In,join as cr}from"node:path";function Qg(t){let e=cr(MT(),".codepipe-sandbox","repos");return t?cr(e,t):e}function ey(t,e){let n=(Rn.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{Rn.get(t)===o&&Rn.delete(t)},()=>{Rn.get(t)===o&&Rn.delete(t)});return Rn.set(t,o),n}function Jg(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 DT(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 ty(t,e,r,n,o){let i=async c=>{await de(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await de(t,["reset","--hard",`origin/${c}`],o),await de(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!Jg(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{hs(t)&&_l(t,{recursive:!0,force:!0}),Do(In(t),{recursive:!0});try{return await de(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!Jg(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),hs(t)&&_l(t,{recursive:!0,force:!0}),Do(In(t),{recursive:!0}),await de(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(hs(cr(t,".git")))try{return await s()}catch(c){if(!DT(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 ry(t){await de(t.workspacePath,["reset","--hard",t.baseSha]),await de(t.workspacePath,["clean","-fdx"])}async function ny(t,e){let r=t.workspacePath;await de(r,["add","-A"]);let n=(await Ne(r,["write-tree"])).trim(),o=(await Ne(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:Cn,GIT_AUTHOR_EMAIL:Pn,GIT_COMMITTER_NAME:Cn,GIT_COMMITTER_EMAIL:Pn};return(await Ne(r,["commit-tree",n,"-m",e],i)).trim()}async function oy(t,e,r,n,o){try{await de(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw xr(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 iy(t,e){return Ne(t.workspacePath,["diff","--binary",t.baseSha,e])}async function sy(t,e,r,n,o){await de(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await de(t.workspacePath,["checkout","--force",r])}async function ay(t,e,r,n,o,i){let s=t.workspacePath;await de(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await Ne(s,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=f=>Ne(s,["rev-parse","-q","--verify",`${f}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await Ne(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await de(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(g=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(g)}`)}),await c(n)||await de(s,["fetch","origin",n],i).catch(()=>{}),!await c(n)))throw new Error(`moved-base apply: delivery base ${n.slice(0,10)} is unreachable \u2014 cannot re-apply the previous iteration onto the fresh ${t.ref}`);let l={...i??process.env,GIT_AUTHOR_NAME:Cn,GIT_AUTHOR_EMAIL:Pn,GIT_COMMITTER_NAME:Cn,GIT_COMMITTER_EMAIL:Pn},u=(await Ne(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),p=(await Ne(s,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await de(s,["cherry-pick","--quit"],l).catch(()=>{});let d=null;try{await de(s,["cherry-pick","--no-commit",p],l)}catch(f){d=f instanceof Error?f.message:String(f)}let m=(await Ne(s,["diff","--name-only","--diff-filter=U"])).split(`
810
+ `).map(f=>f.trim()).filter(f=>f.length>0);if(d&&m.length===0)throw await de(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${d}`);return m}async function jl(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:Cn,GIT_AUTHOR_EMAIL:Pn,GIT_COMMITTER_NAME:Cn,GIT_COMMITTER_EMAIL:Pn};(await Ne(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await de(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 de(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await de(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await Ne(n,["diff","--name-only","--diff-filter=U"])).split(`
811
+ `).map(l=>l.trim()).filter(l=>l.length>0),c=await Ne(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}function de(t,e,r){return new Promise((n,o)=>{let i=Zg("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}):
812
+ ${s.join("").trim()||"(no stderr)"}`))})})}function Ne(t,e,r){return new Promise((n,o)=>{let i=Zg("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}):
813
+ ${a.join("").trim()||"(no stderr)"}`))})})}function cy(t,e){hs(t)&&_l(t,{recursive:!0,force:!0}),Do(In(t),{recursive:!0}),LT(e,t,"dir")}async function ly(t,e,r){await de(t,["worktree","prune"]).catch(()=>{}),Do(In(r),{recursive:!0}),await de(t,["worktree","add","--detach",r,`origin/${e}`])}async function UT(t,e,r){Do(In(r),{recursive:!0}),await de(In(r),["clone","--quiet","--no-checkout",t,r]),await de(r,["checkout","--force","--detach",e])}async function uy(t,e,r,n="worktree",o,i){return r.length===0?[]:ey(e,async()=>{let s=[];for(let a of r){let c=cr(Qg(i),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await ty(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 Ne(c,["rev-parse","HEAD"])).trim(),p=cr(t,"code",a.name);n==="direct"?(cy(p,c),console.log(`[git] code: linked ${p} \u2192 ${c} @ ${u.slice(0,10)}`)):n==="clone"?(await UT(c,u,p),console.log(`[git] code: clone ${p} \u2190 ${c} @ ${u.slice(0,10)}`)):(await ly(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 dy(t,e,r,n="worktree",o,i){if(!r||!r.cloneUrl)return null;let s=r;return ey(e,async()=>{let a=cr(Qg(i),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);try{await ty(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=cr(t,"context");n==="direct"?(cy(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await ly(a,s.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await Ne(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function py(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await de(r,["add","-A",...n]).catch(()=>{});let o;try{o=await Ne(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
814
+ `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=OT(cr(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var Rn,Cn,Pn,fy=x(()=>{"use strict";F();Rn=new Map;Cn="CodePipe Agent",Pn="codepipe@codepartner.ee"});import{existsSync as BT,readFileSync as FT}from"node:fs";import{join as GT}from"node:path";import{parse as KT}from"yaml";function my(t){if(!t)return!1;let e=GT(t,Nl);if(!BT(e))return!1;try{let r=KT(FT(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 Nl,hy=x(()=>{"use strict";Nl="knowledge/build.yaml"});import{readFileSync as HT}from"node:fs";import{join as WT}from"node:path";function gy(t){let e=WT(t,Uo),r;try{r=HT(e,"utf-8")}catch{throw new lr(`BUILD produced no ${Uo} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new lr(`${Uo} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new lr(`${Uo} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new lr(`${Uo}: "ok" must be a boolean`);let i=o.ok,a=(Array.isArray(o.steps)?o.steps:[]).flatMap(u=>{if(!u||typeof u!="object")return[];let p=u,d=typeof p.name=="string"?p.name:null,m=typeof p.exitCode=="number"?p.exitCode:null;if(d===null||m===null)return[];let f={name:d,exitCode:m};return typeof p.durationMs=="number"&&(f.durationMs=p.durationMs),[f]}),c=typeof o.logTail=="string"?qT(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 qT(t){let e=Buffer.from(t,"utf-8");return e.length<=Ol?t:`\u2026 [${e.length-Ol} bytes elided] \u2026
815
+ `+e.subarray(e.length-Ol).toString("utf-8")}var Ol,lr,Uo,yy=x(()=>{"use strict";Ol=8*1024,lr=class extends Error{},Uo="meta/build-result.json"});import{readFileSync as YT}from"node:fs";import{join as zT}from"node:path";function wy(t){let e=zT(t,An),r;try{r=YT(e,"utf-8")}catch{throw new Gt(`code review produced no ${An} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(l){throw new Gt(`${An} is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}if(!n||typeof n!="object")throw new Gt(`${An} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new Gt(`${An}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?Nr(o.remarks,VT):"";if(!i&&s.trim().length===0)throw new Gt(`${An}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?Nr(o.summary,XT):"",c=ZT(o.findings);return{approved:i,remarks:s,summary:a,...c.length>0?{findings:c}:{}}}function ZT(t){if(!Array.isArray(t))return[];let e=[];for(let r of t.slice(0,JT)){if(!r||typeof r!="object")continue;let n=r,o=typeof n.title=="string"?Nr(n.title,512).trim():"",i=typeof n.problem=="string"?Nr(n.problem,Ll).trim():"";if(!o||!i)continue;let s=typeof n.line=="number"&&Number.isInteger(n.line)&&n.line>0?n.line:void 0;e.push({severity:n.severity==="blocker"?"blocker":"other",title:o,problem:i,...typeof n.repo=="string"&&n.repo?{repo:n.repo}:{},...typeof n.file=="string"&&n.file?{file:Nr(n.file,1024)}:{},...s!==void 0?{line:s}:{},...typeof n.scenario=="string"&&n.scenario.trim()?{scenario:Nr(n.scenario,Ll)}:{},...typeof n.suggestion=="string"&&n.suggestion.trim()?{suggestion:Nr(n.suggestion,Ll)}:{}})}return e}function Nr(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
816
+ \u2026 [${r.length-e} bytes elided]`}var VT,XT,Gt,An,Ll,JT,ky=x(()=>{"use strict";VT=16*1024,XT=4*1024,Gt=class extends Error{},An="meta/review-result.json";Ll=8*1024,JT=50});import{readFileSync as QT,statSync as eR}from"node:fs";import{join as by}from"node:path";function aR(t){return t.startsWith("meta/")||sR.has(t)}function cR(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 lR(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function $y(t,e,r){let n=r?.maxBytes??tR,o=r?.totalBytes??rR,i=r?.maxCount??nR,s=e.map((f,g)=>{let k=null;try{k=eR(by(t,f)).size}catch{}return{path:f,index:g,size:k}}),a=[...s].sort((f,g)=>{let k=h=>aR(h.path)?0:1;return k(f)!==k(g)?k(f)-k(g):(f.size??0)-(g.size??0)}),c=a.slice(0,i),l=a.slice(i).sort((f,g)=>f.index-g.index).map(f=>f.path),u=new Array(s.length),p=[],d=0;for(let f of c){let g=null;if(f.size!==null&&f.size<=n&&d+f.size<=o)try{g=QT(by(t,f.path))}catch{}if(g!==null){d+=g.length,u[f.index]={path:f.path,contentBase64:g.toString("base64")};continue}let k=f.size===null?lR(f.path):cR(f.path,f.size,n,o),h=Buffer.from(k,"utf-8");d+=h.length,u[f.index]={path:f.path,contentBase64:h.toString("base64")},p.push({path:f.path,bytes:f.size??0})}let m=u.filter(f=>f!==void 0);if(l.length>0){let f=l.slice(0,iR),g=`# Artifacts omitted from upload
817
817
 
818
818
  ${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.
819
819
 
820
820
  `+f.map(k=>`- ${k}
821
821
  `).join("")+(l.length>f.length?`
822
822
  \u2026and ${l.length-f.length} more.
823
- `:"");m.push({path:eI,contentBase64:Buffer.from(g,"utf-8").toString("base64")})}return{artifacts:m,omitted:p,dropped:l}}var JT,ZT,QT,eI,tI,rI,by=x(()=>{"use strict";JT=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),ZT=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),QT=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),eI="artifacts-omitted.md",tI=500,rI=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 sI,mkdtempSync as aI,readFileSync as cI,readdirSync as vy,rmSync as $y}from"node:fs";import{tmpdir as lI}from"node:os";import{join as hs,relative as uI}from"node:path";function xy(t){let e=aI(hs(lI(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>$y(e,{recursive:!0,force:!0}),listFiles:()=>Sy(e,e),readFile:r=>cI(hs(e,r),"utf-8"),clean:()=>{for(let r of vy(e))pI.has(r)||$y(hs(e,r),{recursive:!0,force:!0})}}}function Sy(t,e){let r=[];for(let n of vy(e)){let o=hs(e,n),i=sI(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&dI.has(n))continue;r.push(...Sy(t,o))}else r.push(uI(t,o))}return r}var dI,pI,Ey=x(()=>{"use strict";dI=new Set(["code","context","scratch",".claude"]),pI=new Set(["code","context"])});import{existsSync as ys,readFileSync as Ty,readdirSync as Ol}from"node:fs";import{join as Kt}from"node:path";import{parse as fI}from"yaml";function ws(t){if(!ys(t))return[];let e=[];for(let r of Ol(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=Kt(t,r.name);r.isDirectory()?e.push(...ws(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function gs(t){try{return fI(Ty(t,"utf-8"))}catch{return null}}function Iy(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 ws(Kt(t,"model/derived/structure"))){let s=jt(gs(i));if(s.ok){for(let a of s.value.nodes)e.nodes.set(a.key,a);for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}}for(let i of[...ws(Kt(t,"model/derived/correlates")),Kt(t,"model/derived/relates.yaml")]){if(!ys(i))continue;let s=Zn(gs(i));if(s.ok)for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}let n=Kt(t,"model/facts/events");if(ys(n))for(let i of Ol(n).sort()){if(!i.endsWith(".yaml"))continue;let s=Nt(gs(Kt(n,i)));if(!s.ok)continue;let a=s.value;e.events.set(a.taskKey,a);let c=ve(a.taskKey);for(let l of a.files)r(c,l.key,"touched_by",1);for(let l of a.links?.adr??[])r(c,`adr::${l}`,"references",1);for(let l of a.links?.tasks??[])r(c,ve(l),"references",1)}for(let i of ws(Kt(t,"model/facts/identity"))){let s=Qn(gs(i));if(s.ok)for(let a of s.value.entities)a.status==="orphaned"?e.orphanedEntities.add(a.entityId):e.keyByEntity.set(a.entityId,a.currentKey)}let o=Kt(t,"model/facts/annotations");if(ys(o)){for(let i of Ol(o).sort())if(i.endsWith(".md"))try{let s=Ty(Kt(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 Ry=x(()=>{"use strict";F()});function Py(t){return new Set((t.toLowerCase().match(/[a-zа-я0-9_]{4,}/g)??[]).filter(e=>!/^\d+$/.test(e)))}function bI(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 Ay(t){let{taskKey:e,title:r,text:n,model:o}=t,i=new Map,s=(m,f)=>{(i.get(m)??0)<f&&i.set(m,f)};(o.events.has(e)||o.adjacency.has(ve(e)))&&s(ve(e),Cy);for(let m of`${r}
824
- ${n}`.match(kI)??[]){if(m===e)continue;let f=ve(m);(o.events.has(m)||o.adjacency.has(f))&&s(f,Cy)}let a=new Map;for(let m of o.nodes.keys()){let f=re(m);if(f?.level!=="code")continue;let g=f.path.slice(f.path.lastIndexOf("/")+1);for(let k of[f.path,g])a.has(k)||a.set(k,[]),a.get(k).push(m)}let c=`${r}
825
- ${n}`.split(/[\s,;()[\]{}<>"'!?]+/);for(let m of c){let f=m.replace(/^[`*_]+|[`*_.:]+$/g,"");if(!f||!f.includes("/")&&!f.includes("."))continue;let g=a.get(f)??[];g.length===1&&s(g[0],mI)}let l=new Map,u=(m,f)=>{let g=m.toLowerCase();!g||g.length<4||l.set(g,l.has(g)&&l.get(g)!==f?null:f)};for(let m of o.nodes.keys()){let f=re(m);if(!f)continue;let g=f.path.slice(f.path.lastIndexOf("/")+1);f.level==="code"&&u(g.replace(/\.[a-z0-9]+$/i,""),m),f.level==="component"&&u(g,m)}for(let m of`${r}
826
- ${n}`.match(/[A-Za-z][A-Za-z0-9_-]{3,}/g)??[]){let f=l.get(m.toLowerCase());f&&s(f,hI)}let p=Py(`${r}
827
- ${n}`),d=[];for(let[m,f]of o.events){if(m===e||!f.title)continue;let g=bI(p,Py(f.title));g>=yI&&d.push({key:ve(m),score:g})}return d.sort((m,f)=>f.score-m.score||(m.key<f.key?-1:1)).slice(0,wI).forEach(m=>s(m.key,gI)),i}var Cy,mI,hI,gI,yI,wI,kI,_y=x(()=>{"use strict";F();Cy=1,mI=.9,hI=.7,gI=.5,yI=.15,wI=3,kI=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g});function jy(t,e,r={}){let n=r.cutoff??yr.activationCutoff,o=r.topK??yr.topKPerNode,i=r.nodeCap??yr.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=sa[p.kind]??.3,m=l.activation*d*Math.min(p.weight,1);if(m<n)continue;let f=s.get(p.to);(!f||f.activation<m)&&(s.set(p.to,{activation:m,via:{from:l.key,kind:p.kind}}),a.push({key:p.to,activation:m}))}}return s}var Ny=x(()=>{"use strict";F()});import{existsSync as Ml,readFileSync as Oy,readdirSync as $I}from"node:fs";import{join as $s}from"node:path";function Ll(t){return Math.ceil(t.length/4)}function ks(t,e){return[...t.entries()].filter(([r])=>e(r)).map(([r,n])=>({key:r,activation:n.activation,via:n.via})).sort((r,n)=>n.activation-r.activation||(r.key<n.key?-1:1))}function lr(t){let e=re(t);return e?(e.level==="task"||e.level==="adr",e.path):t}function bs(t){if(!t.via)return"matched from the task text";let e=lr(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 EI(t,e){let r=/^ADR-(\d{3,4})$/.exec(e)?.[1];if(!r)return null;let n=$s(t,"adr");if(!Ml(n))return null;let o=r.padStart(4,"0");for(let i of $I(n).sort())if(!(!i.startsWith(`${o}-`)||!i.endsWith(".md")))try{return{file:`adr/${i}`,content:Oy($s(n,i),"utf-8").trim()}}catch{return null}return null}function Ly(t){let{taskKey:e,title:r,contextDir:n,model:o,activated:i}=t,s=t.budgetTokens??yr.budgetTokens,a=[],c=0,l=v=>{let b=Ll(v);return c+b>s?!1:(a.push(v),c+=b,!0)};l([`# Context pack \u2014 ${e}: ${r}`,"","Assembled deterministically from the project map (git history, past","tasks, decisions). No file bodies here \u2014 the paths are ENTRY POINTS","into the repositories; each line says why it made the list."].join(`
828
- `));let u=ks(i,v=>v.startsWith("adr::")),p=!1;for(let v of u){let b=EI(n,lr(v.key));if(!b)continue;let I=`${p?"":`
823
+ `:"");m.push({path:oR,contentBase64:Buffer.from(g,"utf-8").toString("base64")})}return{artifacts:m,omitted:p,dropped:l}}var tR,rR,nR,oR,iR,sR,vy=x(()=>{"use strict";tR=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),rR=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),nR=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),oR="artifacts-omitted.md",iR=500,sR=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 uR,mkdtempSync as dR,readFileSync as pR,readdirSync as Sy,rmSync as xy}from"node:fs";import{tmpdir as fR}from"node:os";import{join as gs,relative as mR}from"node:path";function Ey(t){let e=dR(gs(fR(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>xy(e,{recursive:!0,force:!0}),listFiles:()=>Ty(e,e),readFile:r=>pR(gs(e,r),"utf-8"),clean:()=>{for(let r of Sy(e))gR.has(r)||xy(gs(e,r),{recursive:!0,force:!0})}}}function Ty(t,e){let r=[];for(let n of Sy(e)){let o=gs(e,n),i=uR(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&hR.has(n))continue;r.push(...Ty(t,o))}else r.push(mR(t,o))}return r}var hR,gR,Ry=x(()=>{"use strict";hR=new Set(["code","context","scratch",".claude"]),gR=new Set(["code","context"])});import{existsSync as ws,readFileSync as Iy,readdirSync as Ml}from"node:fs";import{join as Kt}from"node:path";import{parse as yR}from"yaml";function ks(t){if(!ws(t))return[];let e=[];for(let r of Ml(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=Kt(t,r.name);r.isDirectory()?e.push(...ks(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function ys(t){try{return yR(Iy(t,"utf-8"))}catch{return null}}function Cy(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 ks(Kt(t,"model/derived/structure"))){let s=jt(ys(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[...ks(Kt(t,"model/derived/correlates")),Kt(t,"model/derived/relates.yaml")]){if(!ws(i))continue;let s=Qn(ys(i));if(s.ok)for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}let n=Kt(t,"model/facts/events");if(ws(n))for(let i of Ml(n).sort()){if(!i.endsWith(".yaml"))continue;let s=Nt(ys(Kt(n,i)));if(!s.ok)continue;let a=s.value;e.events.set(a.taskKey,a);let c=xe(a.taskKey);for(let l of a.files)r(c,l.key,"touched_by",1);for(let l of a.links?.adr??[])r(c,`adr::${l}`,"references",1);for(let l of a.links?.tasks??[])r(c,xe(l),"references",1)}for(let i of ks(Kt(t,"model/facts/identity"))){let s=eo(ys(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=Kt(t,"model/facts/annotations");if(ws(o)){for(let i of Ml(o).sort())if(i.endsWith(".md"))try{let s=Iy(Kt(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 Py=x(()=>{"use strict";F()});function _y(t){return new Set((t.toLowerCase().match(/[a-zа-я0-9_]{4,}/g)??[]).filter(e=>!/^\d+$/.test(e)))}function SR(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 jy(t){let{taskKey:e,title:r,text:n,model:o}=t,i=new Map,s=(m,f)=>{(i.get(m)??0)<f&&i.set(m,f)};(o.events.has(e)||o.adjacency.has(xe(e)))&&s(xe(e),Ay);for(let m of`${r}
824
+ ${n}`.match(xR)??[]){if(m===e)continue;let f=xe(m);(o.events.has(m)||o.adjacency.has(f))&&s(f,Ay)}let a=new Map;for(let m of o.nodes.keys()){let f=re(m);if(f?.level!=="code")continue;let g=f.path.slice(f.path.lastIndexOf("/")+1);for(let k of[f.path,g])a.has(k)||a.set(k,[]),a.get(k).push(m)}let c=`${r}
825
+ ${n}`.split(/[\s,;()[\]{}<>"'!?]+/);for(let m of c){let f=m.replace(/^[`*_]+|[`*_.:]+$/g,"");if(!f||!f.includes("/")&&!f.includes("."))continue;let g=a.get(f)??[];g.length===1&&s(g[0],wR)}let l=new Map,u=(m,f)=>{let g=m.toLowerCase();!g||g.length<4||l.set(g,l.has(g)&&l.get(g)!==f?null:f)};for(let m of o.nodes.keys()){let f=re(m);if(!f)continue;let g=f.path.slice(f.path.lastIndexOf("/")+1);f.level==="code"&&u(g.replace(/\.[a-z0-9]+$/i,""),m),f.level==="component"&&u(g,m)}for(let m of`${r}
826
+ ${n}`.match(/[A-Za-z][A-Za-z0-9_-]{3,}/g)??[]){let f=l.get(m.toLowerCase());f&&s(f,kR)}let p=_y(`${r}
827
+ ${n}`),d=[];for(let[m,f]of o.events){if(m===e||!f.title)continue;let g=SR(p,_y(f.title));g>=$R&&d.push({key:xe(m),score:g})}return d.sort((m,f)=>f.score-m.score||(m.key<f.key?-1:1)).slice(0,vR).forEach(m=>s(m.key,bR)),i}var Ay,wR,kR,bR,$R,vR,xR,Ny=x(()=>{"use strict";F();Ay=1,wR=.9,kR=.7,bR=.5,$R=.15,vR=3,xR=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g});function Oy(t,e,r={}){let n=r.cutoff??wr.activationCutoff,o=r.topK??wr.topKPerNode,i=r.nodeCap??wr.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=aa[p.kind]??.3,m=l.activation*d*Math.min(p.weight,1);if(m<n)continue;let f=s.get(p.to);(!f||f.activation<m)&&(s.set(p.to,{activation:m,via:{from:l.key,kind:p.kind}}),a.push({key:p.to,activation:m}))}}return s}var Ly=x(()=>{"use strict";F()});import{existsSync as Ul,readFileSync as My,readdirSync as ER}from"node:fs";import{join as vs}from"node:path";function Dl(t){return Math.ceil(t.length/4)}function bs(t,e){return[...t.entries()].filter(([r])=>e(r)).map(([r,n])=>({key:r,activation:n.activation,via:n.via})).sort((r,n)=>n.activation-r.activation||(r.key<n.key?-1:1))}function ur(t){let e=re(t);return e?(e.level==="task"||e.level==="adr",e.path):t}function $s(t){if(!t.via)return"matched from the task text";let e=ur(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 CR(t,e){let r=/^ADR-(\d{3,4})$/.exec(e)?.[1];if(!r)return null;let n=vs(t,"adr");if(!Ul(n))return null;let o=r.padStart(4,"0");for(let i of ER(n).sort())if(!(!i.startsWith(`${o}-`)||!i.endsWith(".md")))try{return{file:`adr/${i}`,content:My(vs(n,i),"utf-8").trim()}}catch{return null}return null}function Dy(t){let{taskKey:e,title:r,contextDir:n,model:o,activated:i}=t,s=t.budgetTokens??wr.budgetTokens,a=[],c=0,l=v=>{let b=Dl(v);return c+b>s?!1:(a.push(v),c+=b,!0)};l([`# Context pack \u2014 ${e}: ${r}`,"","Assembled deterministically from the project map (git history, past","tasks, decisions). No file bodies here \u2014 the paths are ENTRY POINTS","into the repositories; each line says why it made the list."].join(`
828
+ `));let u=bs(i,v=>v.startsWith("adr::")),p=!1;for(let v of u){let b=CR(n,ur(v.key));if(!b)continue;let R=`${p?"":`
829
829
  ## Governing decisions
830
830
  `}
831
- ### ${lr(v.key)} (\`${b.file}\`, ${bs(v)})
831
+ ### ${ur(v.key)} (\`${b.file}\`, ${$s(v)})
832
832
 
833
833
  ${b.content}
834
- `;if(!l(I))break;p=!0}let d=ks(i,v=>o.nodes.get(v)?.entityId!==void 0).filter(v=>o.annotations.has(o.nodes.get(v.key).entityId)),m=t.staleKeys??new Set,f=!1;for(let v of d){let b=o.nodes.get(v.key).entityId,I=o.annotations.get(b),_=m.has(v.key)?" \u2014 \u26A0 the file changed since the map was built":o.orphanedEntities.has(b)?" \u2014 \u26A0 the file no longer exists":"",G=`${f?"":`
834
+ `;if(!l(R))break;p=!0}let d=bs(i,v=>o.nodes.get(v)?.entityId!==void 0).filter(v=>o.annotations.has(o.nodes.get(v.key).entityId)),m=t.staleKeys??new Set,f=!1;for(let v of d){let b=o.nodes.get(v.key).entityId,R=o.annotations.get(b),_=m.has(v.key)?" \u2014 \u26A0 the file changed since the map was built":o.orphanedEntities.has(b)?" \u2014 \u26A0 the file no longer exists":"",G=`${f?"":`
835
835
  ## Why the code is shaped this way (intent notes)
836
836
  `}
837
- ### \`${lr(v.key)}\`${_}
837
+ ### \`${ur(v.key)}\`${_}
838
838
 
839
- ${I}
840
- `;if(!l(G))break;f=!0}let g=ve(e),k=ks(i,v=>v.startsWith("task::")&&v!==g).slice(0,vI),h=!1;for(let v of k){let b=o.events.get(lr(v.key));if(!b)continue;let I=[...b.files].filter(y=>!m.has(y.key)&&(!y.entityId||!o.orphanedEntities.has(y.entityId))).sort((y,U)=>(U.churn??0)-(y.churn??0)||(y.key<U.key?-1:1)).slice(0,3).map(y=>`\`${lr(y.key)}\``).join(", "),_="",G=b.links?.solution??[`tasks/${b.taskKey}/PLAN.md`,`tasks/${b.taskKey}/SOLUTION.md`].find(y=>Ml($s(n,y)))??`tasks/${b.taskKey}/PLAN.md`,z=$s(n,G);if(Ml(z))try{_=`
841
- > ${Oy(z,"utf-8").trim().slice(0,SI).replace(/\n+/g," ").trim()}\u2026
839
+ ${R}
840
+ `;if(!l(G))break;f=!0}let g=xe(e),k=bs(i,v=>v.startsWith("task::")&&v!==g).slice(0,TR),h=!1;for(let v of k){let b=o.events.get(ur(v.key));if(!b)continue;let R=[...b.files].filter(y=>!m.has(y.key)&&(!y.entityId||!o.orphanedEntities.has(y.entityId))).sort((y,U)=>(U.churn??0)-(y.churn??0)||(y.key<U.key?-1:1)).slice(0,3).map(y=>`\`${ur(y.key)}\``).join(", "),_="",G=b.links?.solution??[`tasks/${b.taskKey}/PLAN.md`,`tasks/${b.taskKey}/SOLUTION.md`].find(y=>Ul(vs(n,y)))??`tasks/${b.taskKey}/PLAN.md`,z=vs(n,G);if(Ul(z))try{_=`
841
+ > ${My(z,"utf-8").trim().slice(0,IR).replace(/\n+/g," ").trim()}\u2026
842
842
  > _(full text: \`${G}\`)_`}catch{}let A=`${h?"":`
843
843
  ## Related past tasks
844
844
  `}
845
- - **${b.taskKey}**${b.title?` \u2014 ${b.title}`:""}${b.date?` (${b.date})`:""}, ${bs(v)}. Files: ${I||"\u2014"}.${_}`;if(!l(A))break;h=!0}let w=v=>{if(m.has(v.key))return!1;let b=o.nodes.get(v.key)?.entityId;return!b||!o.orphanedEntities.has(b)},$=ks(i,v=>v.startsWith("code:")),S=$.filter(w).slice(0,xI);if(S.length>0){let v=["","## Files likely involved",""];for(let b of S){let I=`- \`${lr(b.key)}\` \u2014 ${bs(b)}`;if(c+Ll(v.join(`
846
- `))+Ll(I)>s)break;v.push(I)}v.length>3&&l(v.join(`
847
- `))}let T=$.filter(v=>!w(v)).slice(0,10);if(T.length>0){let v=["","## 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(b=>`- \`${lr(b.key)}\` \u2014 ${bs(b)}${m.has(b.key)?" (changed since the map was built)":" (file gone)"}`)];l(v.join(`
845
+ - **${b.taskKey}**${b.title?` \u2014 ${b.title}`:""}${b.date?` (${b.date})`:""}, ${$s(v)}. Files: ${R||"\u2014"}.${_}`;if(!l(A))break;h=!0}let w=v=>{if(m.has(v.key))return!1;let b=o.nodes.get(v.key)?.entityId;return!b||!o.orphanedEntities.has(b)},$=bs(i,v=>v.startsWith("code:")),S=$.filter(w).slice(0,RR);if(S.length>0){let v=["","## Files likely involved",""];for(let b of S){let R=`- \`${ur(b.key)}\` \u2014 ${$s(b)}`;if(c+Dl(v.join(`
846
+ `))+Dl(R)>s)break;v.push(R)}v.length>3&&l(v.join(`
847
+ `))}let T=$.filter(v=>!w(v)).slice(0,10);if(T.length>0){let v=["","## 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(b=>`- \`${ur(b.key)}\` \u2014 ${$s(b)}${m.has(b.key)?" (changed since the map was built)":" (file gone)"}`)];l(v.join(`
848
848
  `))}return a.length<=1?null:a.join(`
849
849
  `)+`
850
- `}var vI,xI,SI,My=x(()=>{"use strict";F();vI=5,xI=300,SI=400});var Fy={};ze(Fy,{assembleContextPack:()=>CI});import{createHash as TI}from"node:crypto";import{existsSync as Dy,readFileSync as Uy}from"node:fs";import{join as By}from"node:path";function II(t){return TI("sha1").update(`blob ${t.length}\0`).update(t).digest("hex")}function RI(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=By(a,i.path);try{if(!Dy(c)){n.add(o);continue}II(Uy(c)).startsWith(s.contentHash)||n.add(o)}catch{}}return n}function CI(t){let e=Iy(t.contextDir);if(e.empty)return null;let r="",n=By(t.contextDir,`tasks/${t.taskKey}/task.md`);if(Dy(n))try{r=Uy(n,"utf-8")}catch{r=""}let o=Ay({taskKey:t.taskKey,title:t.title,text:r,model:e});if(o.size===0)return null;let i=jy(e,o),s=t.repoDirs?RI(e,i,t.repoDirs):new Set;return Ly({taskKey:t.taskKey,title:t.title,contextDir:t.contextDir,model:e,activated:i,staleKeys:s,...t.budgetTokens!==void 0?{budgetTokens:t.budgetTokens}:{}})}var Gy=x(()=>{"use strict";F();Ry();_y();Ny();My()});var Ky={};ze(Ky,{SKILLS_DIR:()=>Dl,loadSkills:()=>FI,materializeSkills:()=>GI,renderSkillsBlock:()=>KI});import{cpSync as PI,existsSync as AI,mkdirSync as _I,readFileSync as jI,readdirSync as NI}from"node:fs";import{dirname as OI,join as An}from"node:path";import{fileURLToPath as LI}from"node:url";import{parse as MI}from"yaml";function UI(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
850
+ `}var TR,RR,IR,Uy=x(()=>{"use strict";F();TR=5,RR=300,IR=400});var Ky={};ze(Ky,{assembleContextPack:()=>jR});import{createHash as PR}from"node:crypto";import{existsSync as By,readFileSync as Fy}from"node:fs";import{join as Gy}from"node:path";function AR(t){return PR("sha1").update(`blob ${t.length}\0`).update(t).digest("hex")}function _R(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=Gy(a,i.path);try{if(!By(c)){n.add(o);continue}AR(Fy(c)).startsWith(s.contentHash)||n.add(o)}catch{}}return n}function jR(t){let e=Cy(t.contextDir);if(e.empty)return null;let r="",n=Gy(t.contextDir,`tasks/${t.taskKey}/task.md`);if(By(n))try{r=Fy(n,"utf-8")}catch{r=""}let o=jy({taskKey:t.taskKey,title:t.title,text:r,model:e});if(o.size===0)return null;let i=Oy(e,o),s=t.repoDirs?_R(e,i,t.repoDirs):new Set;return Dy({taskKey:t.taskKey,title:t.title,contextDir:t.contextDir,model:e,activated:i,staleKeys:s,...t.budgetTokens!==void 0?{budgetTokens:t.budgetTokens}:{}})}var Hy=x(()=>{"use strict";F();Py();Ny();Ly();Uy()});var Wy={};ze(Wy,{SKILLS_DIR:()=>Bl,loadSkills:()=>WR,materializeSkills:()=>qR,renderSkillsBlock:()=>YR});import{cpSync as NR,existsSync as OR,mkdirSync as LR,readFileSync as MR,readdirSync as DR}from"node:fs";import{dirname as UR,join as _n}from"node:path";import{fileURLToPath as BR}from"node:url";import{parse as FR}from"yaml";function KR(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
851
851
  ---`,3);return r===-1?null:{yaml:e.slice(e.indexOf(`
852
852
  `,3)+1,r),body:e.slice(e.indexOf(`
853
- `,r+1)+1)}}function BI(t,e,r){let n=[],o=[];if(!AI(t))return{skills:n,errors:o};let i;try{i=NI(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=An(t,s),c=`${r}/${s}`,l;try{l=jI(An(a,"SKILL.md"),"utf-8")}catch{o.push({source:c,error:"no SKILL.md in the directory"});continue}let u=UI(l);if(!u){o.push({source:c,error:"SKILL.md has no frontmatter block"});continue}let p;try{p=MI(u.yaml)}catch(m){o.push({source:c,error:`frontmatter is not valid YAML: ${String(m)}`});continue}let d=Ma({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 FI(t){let e=[],r=(s,a,c)=>{let l=BI(s,a,c);return e.push(...l.errors),l.skills},n=t.sources.bundled?r(DI,"bundled","bundled"):[],o=t.sources.context&&t.contextDir?r(An(t.contextDir,"skills"),"context","skills"):[],i=t.sources.repo?t.repoDirs.flatMap(s=>r(An(s,".claude","skills"),"repo","repo")):[];return{skills:Da(n,o,i),errors:e}}function GI(t,e){if(e.length===0)return[];let r=An(t,Dl);_I(r,{recursive:!0});let n=[];for(let o of e)PI(o.dir,An(r,o.name),{recursive:!0}),n.push(`${Dl}/${o.name}`);return n}function KI(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(`
854
- `)}var Dl,DI,Hy=x(()=>{"use strict";F();Dl=".claude/skills",DI=OI(LI(import.meta.url))});var zy={};ze(zy,{seedMarketplaces:()=>QI});import{spawn as HI}from"node:child_process";import{cpSync as WI,existsSync as Wy,mkdirSync as qy,rmSync as Ul,symlinkSync as qI,writeFileSync as YI}from"node:fs";import{homedir as zI}from"node:os";import{join as ur}from"node:path";function Yy(){return ur(zI(),".codepipe-sandbox","plugins")}function JI(t){return ur(Yy(),"src",`${t.name}@${t.sha||"head"}`)}function Do(t,e){return new Promise((r,n)=>{let o=HI("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 ZI(t){let e=JI(t);if(Wy(ur(e,".claude-plugin","marketplace.json")))return e;Ul(e,{recursive:!0,force:!0}),qy(e,{recursive:!0});let r=`https://github.com/${t.repo}.git`;if(t.sha?(await Do(["init","--quiet"],e),await Do(["remote","add","origin",r],e),await Do(["fetch","--quiet","--depth","1","origin",t.sha],e),await Do(["checkout","--quiet","FETCH_HEAD"],e)):await Do(["clone","--quiet","--depth","1",r,e]),!Wy(ur(e,".claude-plugin","marketplace.json")))throw Ul(e,{recursive:!0,force:!0}),new Error("no .claude-plugin/marketplace.json \u2014 this repository is not a marketplace");return e}async function QI(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 ZI(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=ur(Yy(),"seed",r.map(a=>`${a.name}@${a.sha||"head"}`).sort().join("_")),i=ur(o,VI);qy(i,{recursive:!0});let s={};for(let a of r){let c=ur(i,a.name);Ul(c,{recursive:!0,force:!0}),eR(n.get(a.name),c),s[a.name]={source:{source:"github",repo:a.repo},installLocation:c,...a.sha?{commit:a.sha}:{}}}return YI(ur(o,XI),`${JSON.stringify(s,null,2)}
855
- `),{dir:o,ready:r,errors:e}}function eR(t,e){try{qI(t,e,"dir")}catch{WI(t,e,{recursive:!0,filter:r=>!/(^|\/)\.git(\/|$)/.test(r)})}}var VI,XI,Vy=x(()=>{"use strict";VI="marketplaces",XI="known_marketplaces.json"});var Zy={};ze(Zy,{loadRoles:()=>lR});import{existsSync as tR,readFileSync as rR,readdirSync as nR}from"node:fs";import{dirname as oR,join as Jy}from"node:path";import{fileURLToPath as iR}from"node:url";import{parse as sR}from"yaml";function cR(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
853
+ `,r+1)+1)}}function HR(t,e,r){let n=[],o=[];if(!OR(t))return{skills:n,errors:o};let i;try{i=DR(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=_n(t,s),c=`${r}/${s}`,l;try{l=MR(_n(a,"SKILL.md"),"utf-8")}catch{o.push({source:c,error:"no SKILL.md in the directory"});continue}let u=KR(l);if(!u){o.push({source:c,error:"SKILL.md has no frontmatter block"});continue}let p;try{p=FR(u.yaml)}catch(m){o.push({source:c,error:`frontmatter is not valid YAML: ${String(m)}`});continue}let d=Da({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 WR(t){let e=[],r=(s,a,c)=>{let l=HR(s,a,c);return e.push(...l.errors),l.skills},n=t.sources.bundled?r(GR,"bundled","bundled"):[],o=t.sources.context&&t.contextDir?r(_n(t.contextDir,"skills"),"context","skills"):[],i=t.sources.repo?t.repoDirs.flatMap(s=>r(_n(s,".claude","skills"),"repo","repo")):[];return{skills:Ua(n,o,i),errors:e}}function qR(t,e){if(e.length===0)return[];let r=_n(t,Bl);LR(r,{recursive:!0});let n=[];for(let o of e)NR(o.dir,_n(r,o.name),{recursive:!0}),n.push(`${Bl}/${o.name}`);return n}function YR(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(`
854
+ `)}var Bl,GR,qy=x(()=>{"use strict";F();Bl=".claude/skills",GR=UR(BR(import.meta.url))});var Xy={};ze(Xy,{seedMarketplaces:()=>nI});import{spawn as zR}from"node:child_process";import{cpSync as VR,existsSync as Yy,mkdirSync as zy,rmSync as Fl,symlinkSync as XR,writeFileSync as JR}from"node:fs";import{homedir as ZR}from"node:os";import{join as dr}from"node:path";function Vy(){return dr(ZR(),".codepipe-sandbox","plugins")}function tI(t){return dr(Vy(),"src",`${t.name}@${t.sha||"head"}`)}function Bo(t,e){return new Promise((r,n)=>{let o=zR("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 rI(t){let e=tI(t);if(Yy(dr(e,".claude-plugin","marketplace.json")))return e;Fl(e,{recursive:!0,force:!0}),zy(e,{recursive:!0});let r=`https://github.com/${t.repo}.git`;if(t.sha?(await Bo(["init","--quiet"],e),await Bo(["remote","add","origin",r],e),await Bo(["fetch","--quiet","--depth","1","origin",t.sha],e),await Bo(["checkout","--quiet","FETCH_HEAD"],e)):await Bo(["clone","--quiet","--depth","1",r,e]),!Yy(dr(e,".claude-plugin","marketplace.json")))throw Fl(e,{recursive:!0,force:!0}),new Error("no .claude-plugin/marketplace.json \u2014 this repository is not a marketplace");return e}async function nI(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 rI(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=dr(Vy(),"seed",r.map(a=>`${a.name}@${a.sha||"head"}`).sort().join("_")),i=dr(o,QR);zy(i,{recursive:!0});let s={};for(let a of r){let c=dr(i,a.name);Fl(c,{recursive:!0,force:!0}),oI(n.get(a.name),c),s[a.name]={source:{source:"github",repo:a.repo},installLocation:c,...a.sha?{commit:a.sha}:{}}}return JR(dr(o,eI),`${JSON.stringify(s,null,2)}
855
+ `),{dir:o,ready:r,errors:e}}function oI(t,e){try{XR(t,e,"dir")}catch{VR(t,e,{recursive:!0,filter:r=>!/(^|\/)\.git(\/|$)/.test(r)})}}var QR,eI,Jy=x(()=>{"use strict";QR="marketplaces",eI="known_marketplaces.json"});var ew={};ze(ew,{loadRoles:()=>fI});import{existsSync as iI,readFileSync as sI,readdirSync as aI}from"node:fs";import{dirname as cI,join as Qy}from"node:path";import{fileURLToPath as lI}from"node:url";import{parse as uI}from"yaml";function pI(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
856
856
  ---`,3);if(r===-1)return null;let n=e.slice(e.indexOf(`
857
857
  `,3)+1,r),o=e.indexOf(`
858
- `,r+1);return{yaml:n,body:o===-1?"":e.slice(o+1)}}function Xy(t,e,r){let n=[],o=[];if(!tR(t))return{roles:n,errors:o};let i;try{i=nR(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=rR(Jy(t,s),"utf-8")}catch(d){o.push({file:a,error:`cannot read: ${String(d)}`});continue}let l=cR(c);if(!l){o.push({file:a,error:"missing frontmatter block (--- \u2026 ---) at the top of the file"});continue}let u;try{u=sR(l.yaml)}catch(d){o.push({file:a,error:`frontmatter is not valid YAML: ${String(d)}`});continue}let p=Aa({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 lR(t){let e=Xy(aR,"bundled","bundled"),r=t?Xy(Jy(t,"roles"),"project","roles"):{roles:[],errors:[]};return{roles:_a(e.roles,r.roles),errors:[...e.errors,...r.errors]}}var aR,Qy=x(()=>{"use strict";F();aR=oR(iR(import.meta.url))});var ew={};ze(ew,{ROLE_AGENTS_DIR:()=>Fl,materializeRoleAgents:()=>fR,renderRolesBlock:()=>mR});import{mkdirSync as uR,writeFileSync as dR}from"node:fs";import{join as Bl}from"node:path";function pR(t,e){let r=["---",`name: ${t.name}`,`description: ${t.description}`,...t.model?[`model: ${t.model}`]:[],"---",""].join(`
859
- `),n=t.refs.length>0&&e?["","## Read these first","",...t.refs.map(o=>`- \`${Bl(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(`
858
+ `,r+1);return{yaml:n,body:o===-1?"":e.slice(o+1)}}function Zy(t,e,r){let n=[],o=[];if(!iI(t))return{roles:n,errors:o};let i;try{i=aI(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=sI(Qy(t,s),"utf-8")}catch(d){o.push({file:a,error:`cannot read: ${String(d)}`});continue}let l=pI(c);if(!l){o.push({file:a,error:"missing frontmatter block (--- \u2026 ---) at the top of the file"});continue}let u;try{u=uI(l.yaml)}catch(d){o.push({file:a,error:`frontmatter is not valid YAML: ${String(d)}`});continue}let p=_a({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 fI(t){let e=Zy(dI,"bundled","bundled"),r=t?Zy(Qy(t,"roles"),"project","roles"):{roles:[],errors:[]};return{roles:ja(e.roles,r.roles),errors:[...e.errors,...r.errors]}}var dI,tw=x(()=>{"use strict";F();dI=cI(lI(import.meta.url))});var rw={};ze(rw,{ROLE_AGENTS_DIR:()=>Kl,materializeRoleAgents:()=>yI,renderRolesBlock:()=>wI});import{mkdirSync as mI,writeFileSync as hI}from"node:fs";import{join as Gl}from"node:path";function gI(t,e){let r=["---",`name: ${t.name}`,`description: ${t.description}`,...t.model?[`model: ${t.model}`]:[],"---",""].join(`
859
+ `),n=t.refs.length>0&&e?["","## Read these first","",...t.refs.map(o=>`- \`${Gl(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(`
860
860
  `):"";return`${r}${t.body}
861
- ${n}`}function fR(t,e,r,n){let o=ja(e,r);if(o.length===0)return{roles:[],files:[]};let i=Bl(t,Fl);uR(i,{recursive:!0});let s=[];for(let a of o)dR(Bl(i,`${a.name}.md`),pR(a,n)),s.push(`${Fl}/${a.name}.md`);return{roles:o,files:s}}function mR(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(`
861
+ ${n}`}function yI(t,e,r,n){let o=Na(e,r);if(o.length===0)return{roles:[],files:[]};let i=Gl(t,Kl);mI(i,{recursive:!0});let s=[];for(let a of o)hI(Gl(i,`${a.name}.md`),gI(a,n)),s.push(`${Kl}/${a.name}.md`);return{roles:o,files:s}}function wI(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(`
862
862
  `),"","Delegate to **every** role above \u2014 **in parallel**, all Task calls in one","turn, giving each the change under review. 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(`
863
- `)}var Fl,tw=x(()=>{"use strict";F();Fl=".claude/agents"});var nw={};ze(nw,{COUNCIL_ANSWER_PATH:()=>rw,readCouncilVerdict:()=>yR});import{readFileSync as hR}from"node:fs";import{join as gR}from"node:path";function yR(t){let e;try{e=hR(gR(t,rw),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var rw,ow=x(()=>{"use strict";rw="meta/council-answer.json"});var sw={};ze(sw,{QUEUE_PLAN_PATH:()=>iw,readQueuePlan:()=>bR});import{readFileSync as wR}from"node:fs";import{join as kR}from"node:path";function bR(t){let e;try{e=wR(kR(t,iw),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var iw,aw=x(()=>{"use strict";iw="meta/queue-plan.json"});import{mkdirSync as cw,readFileSync as vs,readdirSync as $R,writeFileSync as lw}from"node:fs";import{homedir as vR}from"node:os";import{dirname as xR,join as Rt}from"node:path";function ER(t){let e=Buffer.from(t,"utf-8");if(e.length<=xs)return t;let r=Math.floor(xs/4),n=xs-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}
863
+ `)}var Kl,nw=x(()=>{"use strict";F();Kl=".claude/agents"});var iw={};ze(iw,{COUNCIL_ANSWER_PATH:()=>ow,readCouncilVerdict:()=>$I});import{readFileSync as kI}from"node:fs";import{join as bI}from"node:path";function $I(t){let e;try{e=kI(bI(t,ow),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var ow,sw=x(()=>{"use strict";ow="meta/council-answer.json"});var cw={};ze(cw,{QUEUE_PLAN_PATH:()=>aw,readQueuePlan:()=>SI});import{readFileSync as vI}from"node:fs";import{join as xI}from"node:path";function SI(t){let e;try{e=vI(xI(t,aw),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var aw,lw=x(()=>{"use strict";aw="meta/queue-plan.json"});import{mkdirSync as uw,readFileSync as xs,readdirSync as EI,writeFileSync as dw}from"node:fs";import{homedir as TI}from"node:os";import{dirname as RI,join as It}from"node:path";function CI(t){let e=Buffer.from(t,"utf-8");if(e.length<=Ss)return t;let r=Math.floor(Ss/4),n=Ss-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}
864
864
 
865
- \u2026 [${s} bytes elided \u2014 log capped at ${xs} bytes for upload] \u2026
865
+ \u2026 [${s} bytes elided \u2014 log capped at ${Ss} bytes for upload] \u2026
866
866
 
867
- ${i}`}function TR(){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 Uo(t={}){let e=Le(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=fg(t.profile,e.sandboxId,!!V("SANDBOX_CONFIG")),s=Rt(vR(),".codepipe","logs"),a=ui("SANDBOX_LOG",i,s);if(a.enabled){let A=new tn(a);di(A),console.log(`[log] file logging \u2192 ${A.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${Ve} (protocol ${ht})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=Ig(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=_g();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let u=new bn(e.hubUrl,e.token),p=!1,d=new AbortController,m=new Map,f=null,g=null,k=!1,h=()=>{let A=u.openControlSocket();return f=A,A.on("open",()=>{console.log("[ws] connected");let y={type:"sandbox_hello",platformVersion:Ve,protocolVersion:ht};A.send(JSON.stringify(y))}),A.on("message",y=>{let U=y.toString("utf-8"),j=null;try{let H=JSON.parse(U);H&&typeof H=="object"&&(j=H)}catch{}if(j&&j.type==="hello"){let H=j;g=zn(H.protocolVersion);let J=g?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${H.platformVersion} (protocol ${H.protocolVersion}) \u2014 ${J}`),g&&(k=!1);return}if(j&&j.type==="pause_job"){let H=typeof j.jobId=="string"?j.jobId:"",J=H?m.get(H):void 0;J?(console.warn(`[ws] pause_job ${H} \u2014 aborting agent`),J.paused=!0,J.abort.abort()):console.log(`[ws] pause_job ${H} \u2014 not a running job, ignoring`),H&&A.send(JSON.stringify({type:"job_paused",jobId:H}));return}if(j&&(j.type==="chat_user_message"||j.type==="chat_finalize")){let H=typeof j.jobId=="string"?j.jobId:"",J=H?m.get(H):void 0;if(J?.chatInbox)if(j.type==="chat_user_message"){let oe=typeof j.text=="string"?j.text:"";oe.trim()&&J.chatInbox.push({kind:"user",text:oe})}else J.chatInbox.finalize();else console.log(`[ws] ${String(j.type)} ${H} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${U}`)}),A.on("close",(y,U)=>{console.log(`[ws] closed code=${y} reason=${U?.toString()||""}`),f===A&&(f=null),!p&&setTimeout(h,2e3)}),A.on("error",y=>console.warn(`[ws] error: ${y.message}`)),A},w=h(),$=async A=>{for(;!p;){if(g===!1){k||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${Ve}, protocol ${ht}) \u2014 not claiming jobs until versions align.`),k=!0),await new Promise(y=>setTimeout(y,5e3));continue}try{let y=await u.claim(d.signal,A);if(y.status===204)continue;if(y.status===401){console.error("[claim] 401 unauthorized \u2014 the HUB does not know this worker registration. It was removed; re-register with `codepipe up --reregister` (or `codepipe worker register --force`). exiting."),process.exitCode=1,p=!0;break}if(!y.ok){console.warn(`[claim:${A}] ${y.status} \u2014 backoff 5s`),await new Promise(j=>setTimeout(j,5e3));continue}let U=await y.json();await S(u,U)}catch(y){if(d.signal.aborted)break;let U=y instanceof Error?y.message:String(y);console.warn(`[claim:${A}] error: ${U} \u2014 backoff 5s`),await new Promise(j=>setTimeout(j,5e3))}}};async function S(A,y){let U={abort:new AbortController,paused:!1};y.role==="chat"&&(U.chatInbox=TR()),m.set(y.jobId,U);let j=!1,H=null,J=null,oe=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),At=async()=>{try{await A.heartbeat(y.jobId)==="claim_lost"&&(j=!0,console.warn(`[job] ${y.jobId} claim lost \u2014 HUB sweeper took it`))}catch(N){let de=N instanceof Error?N.message:String(N);console.warn(`[job] ${y.jobId} heartbeat error: ${de}`)}};At();let pt=setInterval(()=>{At()},oe),Ue=new Date().toISOString();console.log(`[job] ${y.jobId} claimed \u2014 role=${y.role} task=${y.taskId} phase=${y.phase}`),console.log(`[job] ${y.jobId} prompt (${y.prompt.length} chars):`),console.log(v(y.prompt," \u2502 "));let L=[],B=null,M=400,Y=25,W=500,E=()=>{if(B&&(clearTimeout(B),B=null),L.length===0)return;let N=L.splice(0,L.length),de=f;if(!de||de.readyState!==de.OPEN)return;let Te={type:"agent_activity",jobId:y.jobId,taskId:y.taskId,projectId:y.projectId,role:y.role,phase:y.phase,events:N};try{de.send(JSON.stringify(Te))}catch{}},R=N=>{L.push(N),L.length>W&&L.shift(),L.length>=Y?E():B||(B=setTimeout(E,M))},Q=y.role==="analysis"&&y.taskId.startsWith("draft::")?y.taskId.slice(7):null,ie=new Set,P=null;try{if(!c){j||await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:Ue,finishedAt:new Date().toISOString()});return}if(!Rg(o,y.provider??null)){j||await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${y.provider??"claude"}"`},startedAt:Ue,finishedAt:new Date().toISOString()});return}let N=xy(y.jobId);console.log(`[job] ${y.jobId} workspace=${N.dir}`);let de=T(y,r);H=de.gitCreds,J=de.contextGitCreds;let Te=H?.env,ft=de.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:de.claudeOauthToken}:void 0,pe=[],ne=null,Us=null;try{let O=y.role==="build"?"clone":"worktree";pe=await ay(N.dir,y.projectId,y.projectRepos,O,Te,n);let D=await cy(N.dir,y.projectId,y.contextRepo,"worktree",Te,n);Us=D,ne=D?.workspacePath??null}catch(O){let D=O instanceof Error?O.message:String(O);console.warn(`[job] ${y.jobId} materialize failed: ${D}`),j||await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${D}`},startedAt:Ue,finishedAt:new Date().toISOString()}),N.dispose();return}let Kn=y.model;y.role==="build"&&y.modelDiscovery&&!dy(ne)&&(Kn=y.modelDiscovery,console.log(`[job] ${y.jobId} BUILD discovery (no steps in ${jl}) \u2014 model=${Kn}`));let du=async()=>{if(!y.deliveries||y.deliveries.length===0)return[];let O=y.contextRepo?.cloneUrl;if(!O||!Te)throw new Error(O?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let D=[];for(let ee of y.deliveries){let Z=pe.find(le=>le.name===ee.name);if(Z){if(y.role==="implement"&&ee.baseSha&&ee.baseSha!==Z.baseSha){let le=await oy(Z,ee.deliveryRef,ee.deliverySha,ee.baseSha,O,Te);console.log(`[job] ${y.jobId} ${Z.name}: base moved ${ee.baseSha.slice(0,10)} \u2192 ${Z.baseSha.slice(0,10)} \u2014 re-applied delivery ${ee.deliverySha.slice(0,10)} (${le.length} conflicted file(s))`),le.length>0&&D.push(`- **${Z.name}**:`,...le.map(tt=>` - \`${tt}\``));continue}await ny(Z,ee.deliveryRef,ee.deliverySha,O,Te),console.log(`[job] ${y.jobId} ${Z.name}: checked out delivery ${ee.deliverySha.slice(0,10)} for ${y.role}`)}}return D},Bs=[];if(y.role==="build"||y.role==="implement"||y.role==="code-review")try{Bs=await du()}catch(O){let D=O instanceof Error?O.message:String(O);console.warn(`[job] ${y.jobId} delivery checkout failed: ${D}`),j||await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${D}`},startedAt:Ue,finishedAt:new Date().toISOString()}),N.dispose();return}let Fs=y.role==="resolve-conflict"?y.metadata?.taskBranchByRepo??{}:{},pu="";if(y.role==="resolve-conflict"){if(!pe.some(O=>Fs[O.name])){let O="resolve-conflict job carries no task branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${y.jobId} ${O}`),j||await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:O},startedAt:Ue,finishedAt:new Date().toISOString()}),N.dispose();return}try{let O=[];for(let D of pe){let ee=Fs[D.name];if(!ee)continue;let Z=await _l(D,ee,Te);console.log(`[job] ${y.jobId} ${D.name}: merged ${ee} into ${D.ref} \u2014 ${Z.length} conflicted file(s)`),Z.length>0?O.push(`- **${D.name}**:`,...Z.map(le=>` - \`${le}\``)):O.push(`- **${D.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}pu=`
867
+ ${i}`}function PI(){let t=[],e=!1,r=null,n=i=>{if(r){let s=r;r=null,s({value:i,done:!1})}else t.push(i)},o=()=>{if(r){let i=r;r=null,i({value:void 0,done:!0})}};return{push(i){e||n(i)},finalize(){e||(n({kind:"finalize"}),e=!0)},close(){e=!0,t.length=0,o()},iterable:{[Symbol.asyncIterator](){return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):e?Promise.resolve({value:void 0,done:!0}):new Promise(i=>{r=i})}}}}}}async function Fo(t={}){let e=Le(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=gg(t.profile,e.sandboxId,!!X("SANDBOX_CONFIG")),s=It(TI(),".codepipe","logs"),a=pi("SANDBOX_LOG",i,s);if(a.enabled){let A=new rn(a);fi(A),console.log(`[log] file logging \u2192 ${A.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${Ve} (protocol ${ht})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=Pg(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=Og();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let u=new $n(e.hubUrl,e.token),p=!1,d=new AbortController,m=new Map,f=null,g=null,k=!1,h=()=>{let A=u.openControlSocket();return f=A,A.on("open",()=>{console.log("[ws] connected");let y={type:"sandbox_hello",platformVersion:Ve,protocolVersion:ht};A.send(JSON.stringify(y))}),A.on("message",y=>{let U=y.toString("utf-8"),j=null;try{let H=JSON.parse(U);H&&typeof H=="object"&&(j=H)}catch{}if(j&&j.type==="hello"){let H=j;g=Vn(H.protocolVersion);let J=g?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${H.platformVersion} (protocol ${H.protocolVersion}) \u2014 ${J}`),g&&(k=!1);return}if(j&&j.type==="pause_job"){let H=typeof j.jobId=="string"?j.jobId:"",J=H?m.get(H):void 0;J?(console.warn(`[ws] pause_job ${H} \u2014 aborting agent`),J.paused=!0,J.abort.abort()):console.log(`[ws] pause_job ${H} \u2014 not a running job, ignoring`),H&&A.send(JSON.stringify({type:"job_paused",jobId:H}));return}if(j&&(j.type==="chat_user_message"||j.type==="chat_finalize")){let H=typeof j.jobId=="string"?j.jobId:"",J=H?m.get(H):void 0;if(J?.chatInbox)if(j.type==="chat_user_message"){let oe=typeof j.text=="string"?j.text:"";oe.trim()&&J.chatInbox.push({kind:"user",text:oe})}else J.chatInbox.finalize();else console.log(`[ws] ${String(j.type)} ${H} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${U}`)}),A.on("close",(y,U)=>{console.log(`[ws] closed code=${y} reason=${U?.toString()||""}`),f===A&&(f=null),!p&&setTimeout(h,2e3)}),A.on("error",y=>console.warn(`[ws] error: ${y.message}`)),A},w=h(),$=async A=>{for(;!p;){if(g===!1){k||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${Ve}, protocol ${ht}) \u2014 not claiming jobs until versions align.`),k=!0),await new Promise(y=>setTimeout(y,5e3));continue}try{let y=await u.claim(d.signal,A);if(y.status===204)continue;if(y.status===401){console.error("[claim] 401 unauthorized \u2014 the HUB does not know this worker registration. It was removed; re-register with `codepipe up --reregister` (or `codepipe worker register --force`). exiting."),process.exitCode=1,p=!0;break}if(!y.ok){console.warn(`[claim:${A}] ${y.status} \u2014 backoff 5s`),await new Promise(j=>setTimeout(j,5e3));continue}let U=await y.json();await S(u,U)}catch(y){if(d.signal.aborted)break;let U=y instanceof Error?y.message:String(y);console.warn(`[claim:${A}] error: ${U} \u2014 backoff 5s`),await new Promise(j=>setTimeout(j,5e3))}}};async function S(A,y){let U={abort:new AbortController,paused:!1};y.role==="chat"&&(U.chatInbox=PI()),m.set(y.jobId,U);let j=!1,H=null,J=null,oe=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),At=async()=>{try{await A.heartbeat(y.jobId)==="claim_lost"&&(j=!0,console.warn(`[job] ${y.jobId} claim lost \u2014 HUB sweeper took it`))}catch(N){let pe=N instanceof Error?N.message:String(N);console.warn(`[job] ${y.jobId} heartbeat error: ${pe}`)}};At();let pt=setInterval(()=>{At()},oe),Ue=new Date().toISOString();console.log(`[job] ${y.jobId} claimed \u2014 role=${y.role} task=${y.taskId} phase=${y.phase}`),console.log(`[job] ${y.jobId} prompt (${y.prompt.length} chars):`),console.log(v(y.prompt," \u2502 "));let L=[],B=null,M=400,Y=25,W=500,E=()=>{if(B&&(clearTimeout(B),B=null),L.length===0)return;let N=L.splice(0,L.length),pe=f;if(!pe||pe.readyState!==pe.OPEN)return;let Te={type:"agent_activity",jobId:y.jobId,taskId:y.taskId,projectId:y.projectId,role:y.role,phase:y.phase,events:N};try{pe.send(JSON.stringify(Te))}catch{}},I=N=>{L.push(N),L.length>W&&L.shift(),L.length>=Y?E():B||(B=setTimeout(E,M))},Q=y.role==="analysis"&&y.taskId.startsWith("draft::")?y.taskId.slice(7):null,ie=new Set,P=null;try{if(!c){j||await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:Ue,finishedAt:new Date().toISOString()});return}if(!Ag(o,y.provider??null)){j||await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${y.provider??"claude"}"`},startedAt:Ue,finishedAt:new Date().toISOString()});return}let N=Ey(y.jobId);console.log(`[job] ${y.jobId} workspace=${N.dir}`);let pe=T(y,r);H=pe.gitCreds,J=pe.contextGitCreds;let Te=H?.env,ft=pe.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:pe.claudeOauthToken}:void 0,fe=[],ne=null,Bs=null;try{let O=y.role==="build"?"clone":"worktree";fe=await uy(N.dir,y.projectId,y.projectRepos,O,Te,n);let D=await dy(N.dir,y.projectId,y.contextRepo,"worktree",Te,n);Bs=D,ne=D?.workspacePath??null}catch(O){let D=O instanceof Error?O.message:String(O);console.warn(`[job] ${y.jobId} materialize failed: ${D}`),j||await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${D}`},startedAt:Ue,finishedAt:new Date().toISOString()}),N.dispose();return}let Hn=y.model;y.role==="build"&&y.modelDiscovery&&!my(ne)&&(Hn=y.modelDiscovery,console.log(`[job] ${y.jobId} BUILD discovery (no steps in ${Nl}) \u2014 model=${Hn}`));let fu=async()=>{if(!y.deliveries||y.deliveries.length===0)return[];let O=y.contextRepo?.cloneUrl;if(!O||!Te)throw new Error(O?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let D=[];for(let ee of y.deliveries){let Z=fe.find(le=>le.name===ee.name);if(Z){if(y.role==="implement"&&ee.baseSha&&ee.baseSha!==Z.baseSha){let le=await ay(Z,ee.deliveryRef,ee.deliverySha,ee.baseSha,O,Te);console.log(`[job] ${y.jobId} ${Z.name}: base moved ${ee.baseSha.slice(0,10)} \u2192 ${Z.baseSha.slice(0,10)} \u2014 re-applied delivery ${ee.deliverySha.slice(0,10)} (${le.length} conflicted file(s))`),le.length>0&&D.push(`- **${Z.name}**:`,...le.map(tt=>` - \`${tt}\``));continue}await sy(Z,ee.deliveryRef,ee.deliverySha,O,Te),console.log(`[job] ${y.jobId} ${Z.name}: checked out delivery ${ee.deliverySha.slice(0,10)} for ${y.role}`)}}return D},Fs=[];if(y.role==="build"||y.role==="implement"||y.role==="code-review")try{Fs=await fu()}catch(O){let D=O instanceof Error?O.message:String(O);console.warn(`[job] ${y.jobId} delivery checkout failed: ${D}`),j||await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${D}`},startedAt:Ue,finishedAt:new Date().toISOString()}),N.dispose();return}let Gs=y.role==="resolve-conflict"?y.metadata?.taskBranchByRepo??{}:{},mu="";if(y.role==="resolve-conflict"){if(!fe.some(O=>Gs[O.name])){let O="resolve-conflict job carries no task branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${y.jobId} ${O}`),j||await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:O},startedAt:Ue,finishedAt:new Date().toISOString()}),N.dispose();return}try{let O=[];for(let D of fe){let ee=Gs[D.name];if(!ee)continue;let Z=await jl(D,ee,Te);console.log(`[job] ${y.jobId} ${D.name}: merged ${ee} into ${D.ref} \u2014 ${Z.length} conflicted file(s)`),Z.length>0?O.push(`- **${D.name}**:`,...Z.map(le=>` - \`${le}\``)):O.push(`- **${D.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}mu=`
868
868
 
869
869
  ## Conflicts to resolve
870
870
 
871
871
  `+(O.length>0?O.join(`
872
872
  `):"(no task branches to merge)")+`
873
- `}catch(O){let D=O instanceof Error?O.message:String(O);console.warn(`[job] ${y.jobId} conflict merge failed: ${D}`),j||await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${D}`},startedAt:Ue,finishedAt:new Date().toISOString()}),N.dispose();return}}let Gs=null;if(y.contextPack&&ne)try{let{assembleContextPack:O}=await Promise.resolve().then(()=>(Gy(),Fy)),D=O({contextDir:ne,taskKey:String(y.metadata?.trackerIssueKey??y.taskId.split(":")[1]??""),title:String(y.metadata?.taskTitle??""),repoDirs:new Map(pe.map(ee=>[ee.name,ee.workspacePath]))});D?(cw(Rt(N.dir,"meta"),{recursive:!0}),lw(Rt(N.dir,"meta","context-pack.md"),D),Gs=D,console.log(`[job] ${y.jobId} context pack: ${D.length} chars \u2192 meta/context-pack.md`)):console.log(`[job] ${y.jobId} context pack: model empty or no signal \u2014 skipped`)}catch(O){let D=O instanceof Error?O.message:String(O);console.warn(`[job] ${y.jobId} context pack failed (non-fatal): ${D}`)}let fu="",Vo=null,Ks=null;try{let{loadSkills:O,materializeSkills:D,renderSkillsBlock:ee}=await Promise.resolve().then(()=>(Hy(),Ky)),Z=y.skills??{bundled:!0,context:!0,repo:!0},le=O({contextDir:ne,repoDirs:pe.map(rt=>rt.workspacePath),sources:Z});for(let rt of le.errors)console.warn(`[job] ${y.jobId} skill ${rt.source}: ${rt.error}`);let tt=D(N.dir,le.skills),ge=["implement","rework","testing"].includes(y.role)?Ba(Ua(I(ne,y.taskId))):[];fu=ee(le.skills,ge),tt.length>0&&console.log(`[job] ${y.jobId} skills: ${le.skills.map(rt=>rt.name).join(", ")}`);let{parseMarketplaces:Be,enabledPluginsSetting:Mr}=await Promise.resolve().then(()=>(F(),Ad)),{sources:Dr,errors:Wn}=Be(Z.marketplaces??[]);for(let rt of Wn)console.warn(`[job] ${y.jobId} marketplace ${rt}`);if(Dr.length>0&&(Z.plugins??[]).length>0){let{seedMarketplaces:rt}=await Promise.resolve().then(()=>(Vy(),zy)),Ur=await rt(Dr);for(let te of Ur.errors)console.warn(`[job] ${y.jobId} marketplace ${te.repo}: ${te.error}`);let{enabled:Br,unknown:Fr}=Mr(Z.plugins??[],Ur.ready);for(let te of Fr)console.warn(`[job] ${y.jobId} plugin ${te}: no such marketplace in this project`);Ur.dir&&Object.keys(Br).length>0&&(Vo=Ur.dir,Ks={enabledPlugins:Br},console.log(`[job] ${y.jobId} plugins: ${Object.keys(Br).join(", ")}`))}}catch(O){let D=O instanceof Error?O.message:String(O);console.warn(`[job] ${y.jobId} skills unavailable (non-fatal): ${D}`)}let mu="";if(["code-review","council","analyze","testing"].includes(y.role))try{let{loadRoles:O}=await Promise.resolve().then(()=>(Qy(),Zy)),{materializeRoleAgents:D,renderRolesBlock:ee}=await Promise.resolve().then(()=>(tw(),ew)),Z=O(ne);for(let Be of Z.errors)console.warn(`[job] ${y.jobId} role ${Be.file}: ${Be.error}`);let le=y.role==="council"?"council":y.role==="analyze"?"plan_review":"code_review",tt=y.role==="council"?"council":y.role==="analyze"?"plan-review":y.role==="testing"?"testing":"code-review",ge=D(N.dir,Z.roles,le,ne);mu=ee(ge,tt),console.log(`[job] ${y.jobId} review panel: ${ge.roles.length>0?ge.roles.map(Be=>Be.name).join(", "):"(no roles)"}`)}catch(O){let D=O instanceof Error?O.message:String(O);console.warn(`[job] ${y.jobId} review panel unavailable (non-fatal): ${D}`)}let Zk=Bs.length>0?`
873
+ `}catch(O){let D=O instanceof Error?O.message:String(O);console.warn(`[job] ${y.jobId} conflict merge failed: ${D}`),j||await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${D}`},startedAt:Ue,finishedAt:new Date().toISOString()}),N.dispose();return}}let Ks=null;if(y.contextPack&&ne)try{let{assembleContextPack:O}=await Promise.resolve().then(()=>(Hy(),Ky)),D=O({contextDir:ne,taskKey:String(y.metadata?.trackerIssueKey??y.taskId.split(":")[1]??""),title:String(y.metadata?.taskTitle??""),repoDirs:new Map(fe.map(ee=>[ee.name,ee.workspacePath]))});D?(uw(It(N.dir,"meta"),{recursive:!0}),dw(It(N.dir,"meta","context-pack.md"),D),Ks=D,console.log(`[job] ${y.jobId} context pack: ${D.length} chars \u2192 meta/context-pack.md`)):console.log(`[job] ${y.jobId} context pack: model empty or no signal \u2014 skipped`)}catch(O){let D=O instanceof Error?O.message:String(O);console.warn(`[job] ${y.jobId} context pack failed (non-fatal): ${D}`)}let hu="",Jo=null,Hs=null;try{let{loadSkills:O,materializeSkills:D,renderSkillsBlock:ee}=await Promise.resolve().then(()=>(qy(),Wy)),Z=y.skills??{bundled:!0,context:!0,repo:!0},le=O({contextDir:ne,repoDirs:fe.map(rt=>rt.workspacePath),sources:Z});for(let rt of le.errors)console.warn(`[job] ${y.jobId} skill ${rt.source}: ${rt.error}`);let tt=D(N.dir,le.skills),ge=["implement","rework","testing"].includes(y.role)?Fa(Ba(R(ne,y.taskId))):[];hu=ee(le.skills,ge),tt.length>0&&console.log(`[job] ${y.jobId} skills: ${le.skills.map(rt=>rt.name).join(", ")}`);let{parseMarketplaces:Be,enabledPluginsSetting:Dr}=await Promise.resolve().then(()=>(F(),jd)),{sources:Ur,errors:qn}=Be(Z.marketplaces??[]);for(let rt of qn)console.warn(`[job] ${y.jobId} marketplace ${rt}`);if(Ur.length>0&&(Z.plugins??[]).length>0){let{seedMarketplaces:rt}=await Promise.resolve().then(()=>(Jy(),Xy)),Br=await rt(Ur);for(let te of Br.errors)console.warn(`[job] ${y.jobId} marketplace ${te.repo}: ${te.error}`);let{enabled:Fr,unknown:Gr}=Dr(Z.plugins??[],Br.ready);for(let te of Gr)console.warn(`[job] ${y.jobId} plugin ${te}: no such marketplace in this project`);Br.dir&&Object.keys(Fr).length>0&&(Jo=Br.dir,Hs={enabledPlugins:Fr},console.log(`[job] ${y.jobId} plugins: ${Object.keys(Fr).join(", ")}`))}}catch(O){let D=O instanceof Error?O.message:String(O);console.warn(`[job] ${y.jobId} skills unavailable (non-fatal): ${D}`)}let gu="";if(["code-review","council","analyze","testing"].includes(y.role))try{let{loadRoles:O}=await Promise.resolve().then(()=>(tw(),ew)),{materializeRoleAgents:D,renderRolesBlock:ee}=await Promise.resolve().then(()=>(nw(),rw)),Z=O(ne);for(let Be of Z.errors)console.warn(`[job] ${y.jobId} role ${Be.file}: ${Be.error}`);let le=y.role==="council"?"council":y.role==="analyze"?"plan_review":"code_review",tt=y.role==="council"?"council":y.role==="analyze"?"plan-review":y.role==="testing"?"testing":"code-review",ge=D(N.dir,Z.roles,le,ne);gu=ee(ge,tt),console.log(`[job] ${y.jobId} review panel: ${ge.roles.length>0?ge.roles.map(Be=>Be.name).join(", "):"(no roles)"}`)}catch(O){let D=O instanceof Error?O.message:String(O);console.warn(`[job] ${y.jobId} review panel unavailable (non-fatal): ${D}`)}let eb=Fs.length>0?`
874
874
 
875
875
  ## Base branch moved \u2014 conflicts to resolve
876
876
 
877
877
  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:
878
878
 
879
- `+Bs.join(`
879
+ `+Fs.join(`
880
880
  `)+`
881
- `:"",hu=_(b(y.prompt,pe,ne),ne,y.taskId).replace(/\{\{rolesBlock\}\}/g,mu).replace(/\{\{skillsBlock\}\}/g,fu)+pu+Zk,Hn=[...pe.map(O=>O.workspacePath),...ne?[ne]:[]];if(Hn.length>0&&console.log(`[job] ${y.jobId} --add-dir: ${Hn.join(", ")}`),Dg("agent-request")){let O=us($n(y.metadata??{})),D=Ug(y.projectId,y.jobId,"agent-request",[`# Agent request \u2014 job ${y.jobId}`,"",`- project: ${y.projectId}`,`- task: ${y.taskId}`,`- role: ${y.role}`,`- model: ${Kn??"(backend default)"}`,`- add-dirs:${Hn.length>0?"":" (none)"}`,...Hn.map(ee=>` - ${ee}`),"","## Append-system-prompt (language directive)","","```",O,"```","","## Prompt","",hu,"",...Gs?["## Context pack (meta/context-pack.md)","",Gs]:["## Context pack","","(not generated for this job)"],""].join(`
882
- `));D&&console.log(`[debug] ${y.jobId} agent request \u2192 ${D}`)}Q&&(P=setInterval(()=>{let D=f;if(!D||D.readyState!==D.OPEN)return;let ee;try{ee=$R(Rt(N.dir,"drafts")).filter(Z=>Z.endsWith(".json")).sort()}catch{return}for(let Z of ee){if(ie.has(Z))continue;if(ie.size>=Ya)break;let le;try{let ge=JSON.parse(vs(Rt(N.dir,"drafts",Z),"utf-8")),Be=typeof ge.localRef=="string"?ge.localRef:"",Mr=typeof ge.title=="string"?ge.title:"",Dr=typeof ge.body=="string"?ge.body:"";if(!Be||!Mr)continue;le={localRef:Be,title:Mr,body:Dr,...ge.isEpic===!0?{isEpic:!0}:{},...Array.isArray(ge.links)?{links:ge.links}:{}}}catch{continue}ie.add(Z);let tt={type:"child_draft",jobId:y.jobId,projectId:y.projectId,draftId:Q,child:le};try{D.send(JSON.stringify(tt))}catch{}}},1500));try{let O={workspaceDir:N.dir,role:y.role,prompt:hu,addDirs:Hn,metadata:y.metadata??{},...Kn?{model:Kn}:{},...ft||Vo?{env:{...ft??{},...Vo?{CLAUDE_CODE_PLUGIN_SEED_DIR:Vo}:{}}}:{},...Ks?{settings:Ks}:{},signal:U.abort.signal,onActivity:R},D=U.chatInbox?await c.run({...O,interactive:{inbox:U.chatInbox.iterable}}):await Ng(c,O,{jobId:y.jobId,policy:l,onBeforeRetry:async()=>{N.clean();for(let te of pe)try{await Qg(te);let Ie=Fs[te.name];y.role==="resolve-conflict"&&Ie&&await _l(te,Ie,Te)}catch(Ie){let qn=Ie instanceof Error?Ie.message:String(Ie);console.warn(`[job] ${y.jobId} worktree reset failed (${te.name}): ${qn}`)}try{await du()}catch(te){let Ie=te instanceof Error?te.message:String(te);console.warn(`[job] ${y.jobId} delivery re-checkout failed: ${Ie}`)}},aborted:()=>j||U.paused}),ee=[];if(SR.has(y.role)&&pe.length>0){let te=y.metadata??{},Ie=typeof te.commitMessage=="string"?te.commitMessage:`${y.taskId}: changes`,qn=y.contextRepo?.cloneUrl,gu=J?.env;if(!qn||!gu)throw new Error("delivery requested but "+(qn?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let Qk=y.taskId.includes(":")?y.taskId.slice(y.taskId.indexOf(":")+1):y.taskId;for(let _t of pe){let Yn=await ey(_t,Ie);if(!Yn){console.log(`[job] ${y.jobId} ${_t.name}: no changes \u2014 no delivery`);continue}let Hs=`codepipe/deliveries/${Qk}/${y.jobId}/${_t.name}`;await ty(_t,Yn,Hs,qn,gu),ee.push({name:_t.name,deliveryRef:Hs,deliverySha:Yn,baseSha:_t.baseSha}),console.log(`[job] ${y.jobId} ${_t.name}: delivered ${Yn.slice(0,10)} \u2192 ${Hs}`);let yu=await ry(_t,Yn);if(yu.trim().length>0){let eb=Rt("display",`${_t.name}.diff`),wu=Rt(N.dir,eb);cw(xR(wu),{recursive:!0}),lw(wu,yu)}}}if(y.role==="resolve-conflict"&&ee.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's SOLUTION.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let Z;y.role==="build"&&(Z=fy(N.dir),console.log(`[job] ${y.jobId} build verdict: ok=${Z.ok}`+(Z.failedStep?` failedStep=${Z.failedStep}`:"")));let le;y.role==="code-review"&&(le=gy(N.dir),console.log(`[job] ${y.jobId} review verdict: approved=${le.approved}`));let tt;if(y.role==="council"){let{readCouncilVerdict:te}=await Promise.resolve().then(()=>(ow(),nw));tt=te(N.dir)??void 0,console.log(`[job] ${y.jobId} council: ${tt?"answered":"no verdict \u2014 task stops for a human"}`)}let ge;if(y.role==="testing"){try{let te=vs(Rt(N.dir,"meta","test-result.json"),"utf-8");ge=JSON.parse(te)}catch{ge=void 0}console.log(`[job] ${y.jobId} test verdict: ${ge?"written":"none \u2014 proceeding to the PR"}`)}let Be;if(y.role==="observer"){let{readQueuePlan:te}=await Promise.resolve().then(()=>(aw(),sw));Be=te(N.dir)??void 0,console.log(`[job] ${y.jobId} queue plan: ${Be?"produced":"none \u2014 batch keeps the staged order"}`)}let Mr=D.artifactPaths.length>0?D.artifactPaths:N.listFiles(),Dr=Array.from(new Set(Mr)),Wn;if(Us)try{let te=y.role==="index"?["adr/SOURCES.md"]:y.role==="backfill"?["adr"]:[],Ie=await ly(Us,te);Ie.length>0&&(Wn=Ie,console.log(`[job] ${y.jobId} captured ${Ie.length} knowledge file(s) for Context Repo`))}catch(te){let Ie=te instanceof Error?te.message:String(te);console.warn(`[job] ${y.jobId} knowledge capture failed (non-fatal): ${Ie}`)}let{artifacts:rt,omitted:Ur,dropped:Br}=ky(N.dir,Dr);for(let te of Ur)console.warn(`[job] ${y.jobId} artifact ${te.path} (${te.bytes} bytes) exceeded upload budget \u2014 content omitted`);Br.length>0&&console.warn(`[job] ${y.jobId} artifact listing truncated: ${Br.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let Fr={jobId:y.jobId,status:"succeeded",artifacts:rt,...Wn?{contextWrites:Wn}:{},...ee.length>0?{deliveries:ee}:{},log:ER(D.log),startedAt:Ue,finishedAt:new Date().toISOString(),usage:D.usage,...D.rateLimit?{rateLimit:D.rateLimit}:{},...Z?{build:Z}:{},...le?{review:le}:{},...Be!==void 0?{queuePlan:Be}:{},...tt!==void 0?{council:tt}:{},...ge!==void 0?{test:ge}:{}};if(j||U.paused)console.warn(`[job] ${y.jobId} skipping result upload \u2014 ${U.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await A.submitResult(Fr),console.log(`[job] ${y.jobId} done \u2014 uploaded ${Fr.artifacts.length} artifact(s):`);for(let te of Fr.artifacts){let Ie=Buffer.from(te.contentBase64,"base64").length;console.log(` \xB7 ${te.path} (${Ie} bytes)`)}Fr.artifacts.length===0&&console.warn(`[job] ${y.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(O){let D=O instanceof Error?O.message:String(O);if(U.paused)console.log(`[job] ${y.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(j)console.warn(`[job] ${y.jobId} failed after claim lost (${D}) \u2014 skipping result upload`);else{let ee=jg(O),Z=O instanceof cr,le=O instanceof Gt;console.warn(ee?`[job] ${y.jobId} failed: ${D} (Claude auth \u2014 token invalid/expired)`:Z?`[job] ${y.jobId} failed: ${D} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:le?`[job] ${y.jobId} failed: ${D} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${y.jobId} failed: ${D}`),await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:D},startedAt:Ue,finishedAt:new Date().toISOString(),...ee?{authError:!0}:{},...Z?{buildInconclusive:!0}:{},...le?{reviewInconclusive:!0}:{}})}}finally{N.dispose()}}finally{clearInterval(pt),P&&clearInterval(P),E(),U.chatInbox?.close(),m.delete(y.jobId),H?.cleanup(),J?.cleanup()}}function T(A,y){if(!A.credBundle)return{gitCreds:null,contextGitCreds:null};if(!y)return console.warn(`[job] ${A.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let U;try{U=JSON.parse(pn(y,A.credBundle).toString("utf-8"))}catch(oe){return console.warn(`[job] ${A.jobId} failed to open credBundle: ${oe instanceof Error?oe.message:String(oe)}`),{gitCreds:null,contextGitCreds:null}}let j=Pl(U);j&&console.log(`[job] ${A.jobId} cred bundle opened \u2014 git creds configured`);let H=qg(U,A.contextRepo.cloneUrl),J={gitCreds:j,contextGitCreds:H};return U.claudeOauthToken&&(J.claudeOauthToken=U.claudeOauthToken),J}function v(A,y){return A.split(`
881
+ `:"",yu=_(b(y.prompt,fe,ne),ne,y.taskId).replace(/\{\{rolesBlock\}\}/g,gu).replace(/\{\{skillsBlock\}\}/g,hu)+mu+eb,Wn=[...fe.map(O=>O.workspacePath),...ne?[ne]:[]];if(Wn.length>0&&console.log(`[job] ${y.jobId} --add-dir: ${Wn.join(", ")}`),Fg("agent-request")){let O=ds(vn(y.metadata??{})),D=Gg(y.projectId,y.jobId,"agent-request",[`# Agent request \u2014 job ${y.jobId}`,"",`- project: ${y.projectId}`,`- task: ${y.taskId}`,`- role: ${y.role}`,`- model: ${Hn??"(backend default)"}`,`- add-dirs:${Wn.length>0?"":" (none)"}`,...Wn.map(ee=>` - ${ee}`),"","## Append-system-prompt (language directive)","","```",O,"```","","## Prompt","",yu,"",...Ks?["## Context pack (meta/context-pack.md)","",Ks]:["## Context pack","","(not generated for this job)"],""].join(`
882
+ `));D&&console.log(`[debug] ${y.jobId} agent request \u2192 ${D}`)}Q&&(P=setInterval(()=>{let D=f;if(!D||D.readyState!==D.OPEN)return;let ee;try{ee=EI(It(N.dir,"drafts")).filter(Z=>Z.endsWith(".json")).sort()}catch{return}for(let Z of ee){if(ie.has(Z))continue;if(ie.size>=za)break;let le;try{let ge=JSON.parse(xs(It(N.dir,"drafts",Z),"utf-8")),Be=typeof ge.localRef=="string"?ge.localRef:"",Dr=typeof ge.title=="string"?ge.title:"",Ur=typeof ge.body=="string"?ge.body:"";if(!Be||!Dr)continue;le={localRef:Be,title:Dr,body:Ur,...ge.isEpic===!0?{isEpic:!0}:{},...Array.isArray(ge.links)?{links:ge.links}:{}}}catch{continue}ie.add(Z);let tt={type:"child_draft",jobId:y.jobId,projectId:y.projectId,draftId:Q,child:le};try{D.send(JSON.stringify(tt))}catch{}}},1500));try{let O={workspaceDir:N.dir,role:y.role,prompt:yu,addDirs:Wn,metadata:y.metadata??{},...Hn?{model:Hn}:{},...ft||Jo?{env:{...ft??{},...Jo?{CLAUDE_CODE_PLUGIN_SEED_DIR:Jo}:{}}}:{},...Hs?{settings:Hs}:{},signal:U.abort.signal,onActivity:I},D=U.chatInbox?await c.run({...O,interactive:{inbox:U.chatInbox.iterable}}):await Mg(c,O,{jobId:y.jobId,policy:l,onBeforeRetry:async()=>{N.clean();for(let te of fe)try{await ry(te);let Re=Gs[te.name];y.role==="resolve-conflict"&&Re&&await jl(te,Re,Te)}catch(Re){let Yn=Re instanceof Error?Re.message:String(Re);console.warn(`[job] ${y.jobId} worktree reset failed (${te.name}): ${Yn}`)}try{await fu()}catch(te){let Re=te instanceof Error?te.message:String(te);console.warn(`[job] ${y.jobId} delivery re-checkout failed: ${Re}`)}},aborted:()=>j||U.paused}),ee=[];if(II.has(y.role)&&fe.length>0){let te=y.metadata??{},Re=typeof te.commitMessage=="string"?te.commitMessage:`${y.taskId}: changes`,Yn=y.contextRepo?.cloneUrl,wu=J?.env;if(!Yn||!wu)throw new Error("delivery requested but "+(Yn?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let tb=y.taskId.includes(":")?y.taskId.slice(y.taskId.indexOf(":")+1):y.taskId;for(let _t of fe){let zn=await ny(_t,Re);if(!zn){console.log(`[job] ${y.jobId} ${_t.name}: no changes \u2014 no delivery`);continue}let Ws=`codepipe/deliveries/${tb}/${y.jobId}/${_t.name}`;await oy(_t,zn,Ws,Yn,wu),ee.push({name:_t.name,deliveryRef:Ws,deliverySha:zn,baseSha:_t.baseSha}),console.log(`[job] ${y.jobId} ${_t.name}: delivered ${zn.slice(0,10)} \u2192 ${Ws}`);let ku=await iy(_t,zn);if(ku.trim().length>0){let rb=It("display",`${_t.name}.diff`),bu=It(N.dir,rb);uw(RI(bu),{recursive:!0}),dw(bu,ku)}}}if(y.role==="resolve-conflict"&&ee.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's SOLUTION.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let Z;y.role==="build"&&(Z=gy(N.dir),console.log(`[job] ${y.jobId} build verdict: ok=${Z.ok}`+(Z.failedStep?` failedStep=${Z.failedStep}`:"")));let le;y.role==="code-review"&&(le=wy(N.dir),console.log(`[job] ${y.jobId} review verdict: approved=${le.approved}`));let tt;if(y.role==="council"){let{readCouncilVerdict:te}=await Promise.resolve().then(()=>(sw(),iw));tt=te(N.dir)??void 0,console.log(`[job] ${y.jobId} council: ${tt?"answered":"no verdict \u2014 task stops for a human"}`)}let ge;if(y.role==="testing"){try{let te=xs(It(N.dir,"meta","test-result.json"),"utf-8");ge=JSON.parse(te)}catch{ge=void 0}console.log(`[job] ${y.jobId} test verdict: ${ge?"written":"none \u2014 proceeding to the PR"}`)}let Be;if(y.role==="observer"){let{readQueuePlan:te}=await Promise.resolve().then(()=>(lw(),cw));Be=te(N.dir)??void 0,console.log(`[job] ${y.jobId} queue plan: ${Be?"produced":"none \u2014 batch keeps the staged order"}`)}let Dr=D.artifactPaths.length>0?D.artifactPaths:N.listFiles(),Ur=Array.from(new Set(Dr)),qn;if(Bs)try{let te=y.role==="index"?["adr/SOURCES.md"]:y.role==="backfill"?["adr"]:[],Re=await py(Bs,te);Re.length>0&&(qn=Re,console.log(`[job] ${y.jobId} captured ${Re.length} knowledge file(s) for Context Repo`))}catch(te){let Re=te instanceof Error?te.message:String(te);console.warn(`[job] ${y.jobId} knowledge capture failed (non-fatal): ${Re}`)}let{artifacts:rt,omitted:Br,dropped:Fr}=$y(N.dir,Ur);for(let te of Br)console.warn(`[job] ${y.jobId} artifact ${te.path} (${te.bytes} bytes) exceeded upload budget \u2014 content omitted`);Fr.length>0&&console.warn(`[job] ${y.jobId} artifact listing truncated: ${Fr.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let Gr={jobId:y.jobId,status:"succeeded",artifacts:rt,...qn?{contextWrites:qn}:{},...ee.length>0?{deliveries:ee}:{},log:CI(D.log),startedAt:Ue,finishedAt:new Date().toISOString(),usage:D.usage,...D.rateLimit?{rateLimit:D.rateLimit}:{},...Z?{build:Z}:{},...le?{review:le}:{},...Be!==void 0?{queuePlan:Be}:{},...tt!==void 0?{council:tt}:{},...ge!==void 0?{test:ge}:{}};if(j||U.paused)console.warn(`[job] ${y.jobId} skipping result upload \u2014 ${U.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await A.submitResult(Gr),console.log(`[job] ${y.jobId} done \u2014 uploaded ${Gr.artifacts.length} artifact(s):`);for(let te of Gr.artifacts){let Re=Buffer.from(te.contentBase64,"base64").length;console.log(` \xB7 ${te.path} (${Re} bytes)`)}Gr.artifacts.length===0&&console.warn(`[job] ${y.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(O){let D=O instanceof Error?O.message:String(O);if(U.paused)console.log(`[job] ${y.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(j)console.warn(`[job] ${y.jobId} failed after claim lost (${D}) \u2014 skipping result upload`);else{let ee=Lg(O),Z=O instanceof lr,le=O instanceof Gt;console.warn(ee?`[job] ${y.jobId} failed: ${D} (Claude auth \u2014 token invalid/expired)`:Z?`[job] ${y.jobId} failed: ${D} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:le?`[job] ${y.jobId} failed: ${D} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${y.jobId} failed: ${D}`),await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:D},startedAt:Ue,finishedAt:new Date().toISOString(),...ee?{authError:!0}:{},...Z?{buildInconclusive:!0}:{},...le?{reviewInconclusive:!0}:{}})}}finally{N.dispose()}}finally{clearInterval(pt),P&&clearInterval(P),E(),U.chatInbox?.close(),m.delete(y.jobId),H?.cleanup(),J?.cleanup()}}function T(A,y){if(!A.credBundle)return{gitCreds:null,contextGitCreds:null};if(!y)return console.warn(`[job] ${A.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let U;try{U=JSON.parse(fn(y,A.credBundle).toString("utf-8"))}catch(oe){return console.warn(`[job] ${A.jobId} failed to open credBundle: ${oe instanceof Error?oe.message:String(oe)}`),{gitCreds:null,contextGitCreds:null}}let j=Al(U);j&&console.log(`[job] ${A.jobId} cred bundle opened \u2014 git creds configured`);let H=Vg(U,A.contextRepo.cloneUrl),J={gitCreds:j,contextGitCreds:H};return U.claudeOauthToken&&(J.claudeOauthToken=U.claudeOauthToken),J}function v(A,y){return A.split(`
883
883
  `).map(U=>y+U).join(`
884
- `)}function b(A,y,U){let j=y[0]?.workspacePath??"";return A.replace(/\{\{codeDir\}\}/g,j).replace(/\{\{codeRoot\}\}/g,j?j.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,U??"")}function I(A,y){let U=y.includes("::")?"":y.split(":",2)[1]??"";if(!A||!U)return"";for(let j of["PLAN.md","SOLUTION.md"])try{return vs(Rt(A,"tasks",U,j),"utf-8")}catch{}return""}function _(A,y,U){let j=A,H=U.includes("::")?"":U.split(":",2)[1]??"",J=oe=>{if(!y||!H)return"";try{return vs(Rt(y,"tasks",H,oe),"utf-8").trim()}catch{return""}};if(j.includes("{{planMd}}")||j.includes("{{solutionMd}}")){let oe=J("PLAN.md")||J("SOLUTION.md")||"(PLAN.md missing \u2014 proceed from the task description)";j=j.replace(/\{\{planMd\}\}/g,()=>oe),j=j.replace(/\{\{solutionMd\}\}/g,()=>oe)}if(j.includes("{{taskDescription}}")){let oe=J("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";j=j.replace(/\{\{taskDescription\}\}/g,()=>oe)}return j}let G=A=>{if(p)return;p=!0,console.log(`
885
- [${A}] shutting down`),d.abort();let y=[...m.keys()];for(let H of m.values())H.abort.abort();let U=new AbortController,j=setTimeout(()=>U.abort(),3e3);(async()=>(await Promise.all(y.map(async H=>{try{await u.releaseJob(H,`sandbox ${A}`,U.signal),console.log(`[${A}] released job ${H}`)}catch(J){let oe=J instanceof Error?J.message:String(J);console.warn(`[${A}] release failed: ${oe} (sweeper will reclaim)`)}})),clearTimeout(j),w.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>G("SIGINT")),process.on("SIGTERM",()=>G("SIGTERM"));let z=[$("implementation")];e.planningLane!==!1?z.push($("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(z)}var xs,SR,uw=x(()=>{"use strict";F();ut();Za();Cg();ds();Og();Bg();Fe();ls();Yg();El();uy();py();my();yy();by();Ey();xs=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),SR=new Set(["implement","resolve-conflict"])});var _n=x(()=>{"use strict";hg();uw();ls()});import{cancel as IR,isCancel as pw,log as Ze,password as RR,text as CR}from"@clack/prompts";function PR(t){return pw(t)&&(IR("aborted"),process.exit(1)),typeof t=="string"?t:""}function fw(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function AR(t){let e=uc({redirectUri:lc,challenge:t.challenge,state:t.state});Ze.message(`Open this URL, approve the access, and paste the code shown:
886
- ${e}`);let r=await CR({message:"Authorization code \u2014 blank to skip"});if(pw(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=Mp(r,t.state);return await dc({code:n,verifier:t.verifier,state:t.state,redirectUri:lc})}catch(n){return Ze.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function _R(t){if(Xa()?.claude?.oauthToken&&!t.farm)return Ze.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;Ze.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=gi(),n;try{n=await Dp({...r,openUrl:Tr,log:i=>Ze.message(i)})}catch(i){Ze.warn(`Browser sign-in didn't complete (${i instanceof Error?i.message:String(i)}) \u2014 trying the code-paste fallback.`);let s=await AR(r);if(s===null)return null;n=s}let o=await Dt(n.oauthToken);return o==="invalid"?(Ze.warn("Claude rejected the obtained token (401) \u2014 falling back to manual entry."),null):(Ze.success(`Claude: logged in \u2014 ${fw(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function mw(t){Ze.message(`Claude \u2014 the pipeline's agents run on your Claude subscription.
884
+ `)}function b(A,y,U){let j=y[0]?.workspacePath??"";return A.replace(/\{\{codeDir\}\}/g,j).replace(/\{\{codeRoot\}\}/g,j?j.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,U??"")}function R(A,y){let U=y.includes("::")?"":y.split(":",2)[1]??"";if(!A||!U)return"";for(let j of["PLAN.md","SOLUTION.md"])try{return xs(It(A,"tasks",U,j),"utf-8")}catch{}return""}function _(A,y,U){let j=A,H=U.includes("::")?"":U.split(":",2)[1]??"",J=oe=>{if(!y||!H)return"";try{return xs(It(y,"tasks",H,oe),"utf-8").trim()}catch{return""}};if(j.includes("{{planMd}}")||j.includes("{{solutionMd}}")){let oe=J("PLAN.md")||J("SOLUTION.md")||"(PLAN.md missing \u2014 proceed from the task description)";j=j.replace(/\{\{planMd\}\}/g,()=>oe),j=j.replace(/\{\{solutionMd\}\}/g,()=>oe)}if(j.includes("{{taskDescription}}")){let oe=J("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";j=j.replace(/\{\{taskDescription\}\}/g,()=>oe)}return j}let G=A=>{if(p)return;p=!0,console.log(`
885
+ [${A}] shutting down`),d.abort();let y=[...m.keys()];for(let H of m.values())H.abort.abort();let U=new AbortController,j=setTimeout(()=>U.abort(),3e3);(async()=>(await Promise.all(y.map(async H=>{try{await u.releaseJob(H,`sandbox ${A}`,U.signal),console.log(`[${A}] released job ${H}`)}catch(J){let oe=J instanceof Error?J.message:String(J);console.warn(`[${A}] release failed: ${oe} (sweeper will reclaim)`)}})),clearTimeout(j),w.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>G("SIGINT")),process.on("SIGTERM",()=>G("SIGTERM"));let z=[$("implementation")];e.planningLane!==!1?z.push($("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(z)}var Ss,II,pw=x(()=>{"use strict";F();ut();Qa();_g();ps();Dg();Kg();Fe();us();Xg();Tl();fy();hy();yy();ky();vy();Ry();Ss=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),II=new Set(["implement","resolve-conflict"])});var jn=x(()=>{"use strict";wg();pw();us()});import{cancel as AI,isCancel as mw,log as Ze,password as _I,text as jI}from"@clack/prompts";function NI(t){return mw(t)&&(AI("aborted"),process.exit(1)),typeof t=="string"?t:""}function hw(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function OI(t){let e=dc({redirectUri:uc,challenge:t.challenge,state:t.state});Ze.message(`Open this URL, approve the access, and paste the code shown:
886
+ ${e}`);let r=await jI({message:"Authorization code \u2014 blank to skip"});if(mw(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=Up(r,t.state);return await pc({code:n,verifier:t.verifier,state:t.state,redirectUri:uc})}catch(n){return Ze.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function LI(t){if(Ja()?.claude?.oauthToken&&!t.farm)return Ze.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;Ze.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=wi(),n;try{n=await Bp({...r,openUrl:Rr,log:i=>Ze.message(i)})}catch(i){Ze.warn(`Browser sign-in didn't complete (${i instanceof Error?i.message:String(i)}) \u2014 trying the code-paste fallback.`);let s=await OI(r);if(s===null)return null;n=s}let o=await Dt(n.oauthToken);return o==="invalid"?(Ze.warn("Claude rejected the obtained token (401) \u2014 falling back to manual entry."),null):(Ze.success(`Claude: logged in \u2014 ${hw(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function gw(t){Ze.message(`Claude \u2014 the pipeline's agents run on your Claude subscription.
887
887
  In another terminal:
888
888
  1. install Claude Code \u2014 https://claude.com/claude-code
889
889
  2. run \`claude setup-token\`
890
890
  3. paste the token it prints (starts with sk-ant-) below`+(t.farm?`
891
- Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=PR(await RR({message:"Claude OAuth token \u2014 blank to skip"})).trim();if(!e)return Ze.warn(t.farm?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"";e.startsWith("sk-ant-")||Ze.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`.");let r=await Dt(e);return r==="invalid"?(Ze.warn("Claude refused this token. Run `claude setup-token` again and paste the new one."),mw(t)):(Ze.success(`Claude: ${fw(e)} \u2014 ${r==="valid"?"verified":"check inconclusive, saved"}.`),e)}var hw,gw=x(()=>{"use strict";yi();nn();fe();fc();hw={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:_R,promptManual:mw,validate:Dt}});function yw(t){return hw}async function ww(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var kw=x(()=>{"use strict";gw()});async function jn(t,e,r){return e.host==="github"?NR(t,e,r):e.host==="gitlab"?BR(t,e,r):GR(t,e,r)}async function bw(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 Qe(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await $w(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 We(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await vw(e.gitlabToken,t):o}}return e.bitbucket?(await Ct(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await xw(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 $w(t,e){let r=!1;try{r=(await Qe(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 vw(t,e){let r=!1;try{r=(await We(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 xw(t,e){let r=!1;try{r=(await Ct(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 Qe(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(jR+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 NR(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 OR(n,e,r),i=await LR(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 MR(n,o.owner,o.name,a.path,i)||await DR(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 OR(t,e,r){let n=await Qe(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 $w(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Gl(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 Qe(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 Gl(t,e){let{status:r,data:n}=await Qe(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function LR(t,e,r){let{data:n}=await Qe(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function MR(t,e,r,n,o){let{status:i,data:s}=await Qe(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function DR(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 Qe(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function We(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(UR+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 BR(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 We(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 vw(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await We(n,"GET","/user"),d={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(p.data?.username!==e.owner){let f=await We(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(f.status===404||!f.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);d.namespace_id=f.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let m=await We(n,"POST","/projects",d);if(!m.data)throw new Error("GitLab create project: empty response");i=m.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=un(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let m=(await We(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let f of m)l.add(f.path);if(m.length<100)break}let u=c.filter(p=>!l.has(p.path)).map(p=>({action:"create",file_path:p.path,content:p.content}));return u.length>0?await We(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 Ct(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(FR+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 GR(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 Ct(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 xw(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 Ct(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 Ct(n,"GET",`${o}/src/${encodeURIComponent(a)}/${p.path}?format=meta`)).status===404&&l.push(p);if(l.length>0){let p=new URLSearchParams;p.set("message","chore(codepipe): scaffold context repo files"),p.set("branch",a);for(let m of l)p.set(m.path,m.content);if((await Ct(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 jR,UR,FR,Bo=x(()=>{"use strict";Ir();jR="https://api.github.com";UR="https://gitlab.com/api/v4";FR="https://api.bitbucket.org/2.0"});function qe(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=KR[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 KR,Ss=x(()=>{"use strict";KR={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as HR}from"node:crypto";import{existsSync as Sw,mkdirSync as WR,readFileSync as Ew,readdirSync as qR,rmSync as Es,writeFileSync as YR}from"node:fs";import{homedir as zR}from"node:os";import{dirname as VR,join as Kl}from"node:path";function Tw(){return Kl(zR(),".codepipe","init-drafts")}function Hl(t){let e=HR("sha256").update(t).digest("hex").slice(0,16);return Kl(Tw(),`${e}.json`)}function Iw(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=XR)}function Rw(t){let e=Hl(t);if(!Sw(e))return null;try{let r=JSON.parse(Ew(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Iw(r.savedAt)?(Es(e,{force:!0}),null):r}catch{return null}}function Wl(t){Es(Hl(t),{force:!0})}function Cw(){let t=Tw();if(Sw(t))for(let e of qR(t)){let r=Kl(t,e);try{let n=JSON.parse(Ew(r,"utf-8"));Iw(n.savedAt)&&Es(r,{force:!0})}catch{Es(r,{force:!0})}}}var XR,Nn,Pw=x(()=>{"use strict";XR=24*60*60*1e3;Nn=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(){Wl(this.cwd)}persist(){let e=Hl(this.cwd);WR(VR(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};YR(e,JSON.stringify(r,null,2)+`
892
- `,{mode:384})}}});function Aw(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 _w(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 jw=x(()=>{"use strict"});import{existsSync as JR}from"node:fs";import{join as ZR}from"node:path";import{simpleGit as QR}from"simple-git";function nC(t){let e=t.split("/");return e[e.length-1]??t}function Nw(t){if(t.filter(r=>!tC.test(nC(r))).length>eC)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(rC.has(n))return!0}return!1}async function oC(t){try{let r=(await QR(t).raw(["ls-files"])).split(`
893
- `).map(n=>n.trim()).filter(Boolean);return Nw(r)}catch{return!1}}async function iC(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)?Nw(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function Ow(t,e){for(let r of t)try{let n=e.localRoot!=null?ZR(e.localRoot,r.mountAs??r.name):null;if(n&&JR(n)?await oC(n):await iC(r,e.tokens))return!0}catch{}return!1}var eC,tC,rC,Lw=x(()=>{"use strict";eC=3,tC=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,rC=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as Mw}from"node:fs";import{join as Dw}from"node:path";import{simpleGit as Uw}from"simple-git";async function Go(t,e,r={}){let n=r.log??sC,o=[];for(let i of e){let s=Dw(t,i.mountAs),a=si(i);if(!Mw(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 Uw().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let p=Fo(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(!Mw(Dw(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=Uw(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!aC(l,a)){n.warn(`${i.mountAs}/ origin (${Fo(l)||"none"}) != expected (${Fo(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:Fo(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=Fo(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 aC(t,e){return Bw(t)===Bw(e)}function Bw(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function Fo(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function Fw(t={}){let e=Ae();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 Go(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 sC,Ts=x(()=>{"use strict";it();sC={info:t=>console.log(t),warn:t=>console.warn(t)}});import{simpleGit as cC}from"simple-git";async function Gw(t,e,r){return t.host==="github"?lC(t,e,r):t.host==="gitlab"?uC(t,e,r):dC(t,e,r)}function ql(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 lC(t,e,r){let n=e.githubToken;if(!n)throw new Error("GitHub token required to create a github-hosted mirror");let o=await Qe(n,"GET",`/repos/${t.owner}/${encodeURIComponent(t.repoName)}`);if(o.status===200&&o.data){if(o.data.private!==!0)throw ql(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 Qe(n,"GET","/user")).data?.login??"",s=i.toLowerCase()===t.owner.toLowerCase(),a=!s&&await Gl(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 Qe(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 Kw(t,e,r){try{return t==="github"?(await Qe(e,"GET","/user")).data?.login??null:t==="gitlab"?(await We(e,"GET","/user")).data?.username??null:r?(await Ct({email:r,apiToken:e},"GET","/workspaces?role=contributor&pagelen=1")).data?.values?.[0]?.slug??null:null}catch{return null}}async function uC(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 We(n,"GET",`/projects/${o}`);if(i.status===200&&i.data){if(i.data.visibility!=="private")throw ql(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 We(n,"GET","/user")).data?.username!==t.owner){let l=await We(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 We(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 dC(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 Ct(n,"GET",o);if(s.status===200&&s.data){if(s.data.is_private!==!0)throw ql(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 Ct(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 Hw(t,e,r){let n=cC(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(`
894
- `).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 Ww(t){return`${t}-codepipe-mirror`}var qw=x(()=>{"use strict";Bo()});var Jw={};ze(Jw,{ensureEmbeddedWorker:()=>Rs,spawnWorkerProcess:()=>Cs,upCommand:()=>Ps,workerChildEnv:()=>Xw,workerStartArgs:()=>Vw});import{spawn as zw}from"node:child_process";import{existsSync as Yw}from"node:fs";import{homedir as pC,hostname as fC}from"node:os";import{join as Is}from"node:path";async function mC(t,e,r){let n=Le(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${$t(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 ah(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 ${$t(e)} still holds its token.
895
- 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`),Yd(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function hC(t,e,r){let n=Le(e)!==null;if(!await mC(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 Qi(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof K&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof K&&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 K?i:new Error(`cannot reach the HUB at ${t.hubUrl} (${i instanceof Error?i.message:String(i)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await _r({hub:t.hubUrl,token:o,name:r.name??`${fC()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function gC(t,e){let r=Le(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=Ke(r.sealPublicKey);if(!q(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=ci(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 Rs(t,e,r){await hC(t,e,r),gC(t.projectId,e)}function Vw(t){return[...t?["--profile",t]:[],"worker","start"]}function Xw(t){let e={...t};for(let r of Ja)delete e[r];return e}function Cs(t){let e=zw(process.execPath,[t.entry,...Vw(t.profile)],{stdio:["ignore","pipe","pipe"],env:Xw(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
896
- `))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function yC(t,e){let r=process.cwd(),n=Is(r,ot);if(Xr(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(Yw(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 Yl(r);if(!_d(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=q(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await cs({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=Is(pC(),".codepipe",e?Is("profiles",e,"context-config"):"context-config");if(bi(c.contextDir,l,a),!Yw(Is(c.contextDir,"project.yaml"))){an(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};fo(c.contextDir,Tt(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 Ps(t){let{cfg:e,profile:r}=Zr(t.profile);if(t.debug){let m=typeof t.debug=="string"&&t.debug.trim()?t.debug.trim():"agent-request";process.env.CODEPIPE_DEBUG=m,console.log(`[up] debug logging on (${m}) \u2192 ~/.codepipe/debug/${e.projectId}/`)}await yC(e,r),await Rs(e,r,t);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(m,f)=>{let g=k=>h=>{for(let w of h.toString("utf-8").split(`
891
+ Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=NI(await _I({message:"Claude OAuth token \u2014 blank to skip"})).trim();if(!e)return Ze.warn(t.farm?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"";e.startsWith("sk-ant-")||Ze.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`.");let r=await Dt(e);return r==="invalid"?(Ze.warn("Claude refused this token. Run `claude setup-token` again and paste the new one."),gw(t)):(Ze.success(`Claude: ${hw(e)} \u2014 ${r==="valid"?"verified":"check inconclusive, saved"}.`),e)}var yw,ww=x(()=>{"use strict";ki();on();me();mc();yw={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:LI,promptManual:gw,validate:Dt}});function kw(t){return yw}async function bw(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var $w=x(()=>{"use strict";ww()});async function Nn(t,e,r){return e.host==="github"?DI(t,e,r):e.host==="gitlab"?HI(t,e,r):qI(t,e,r)}async function vw(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 Qe(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await xw(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 We(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Sw(e.gitlabToken,t):o}}return e.bitbucket?(await Ct(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Ew(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 xw(t,e){let r=!1;try{r=(await Qe(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 Sw(t,e){let r=!1;try{r=(await We(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 Ew(t,e){let r=!1;try{r=(await Ct(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 Qe(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(MI+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 DI(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 UI(n,e,r),i=await BI(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=dn(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await FI(n,o.owner,o.name,a.path,i)||await GI(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 UI(t,e,r){let n=await Qe(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 xw(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Hl(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 Qe(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 Hl(t,e){let{status:r,data:n}=await Qe(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function BI(t,e,r){let{data:n}=await Qe(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function FI(t,e,r,n,o){let{status:i,data:s}=await Qe(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function GI(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 Qe(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function We(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(KI+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 HI(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 We(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 Sw(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await We(n,"GET","/user"),d={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(p.data?.username!==e.owner){let f=await We(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(f.status===404||!f.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);d.namespace_id=f.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let m=await We(n,"POST","/projects",d);if(!m.data)throw new Error("GitLab create project: empty response");i=m.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=dn(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let m=(await We(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let f of m)l.add(f.path);if(m.length<100)break}let u=c.filter(p=>!l.has(p.path)).map(p=>({action:"create",file_path:p.path,content:p.content}));return u.length>0?await We(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 Ct(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(WI+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 qI(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 Ct(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 Ew(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 Ct(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=dn(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await Ct(n,"GET",`${o}/src/${encodeURIComponent(a)}/${p.path}?format=meta`)).status===404&&l.push(p);if(l.length>0){let p=new URLSearchParams;p.set("message","chore(codepipe): scaffold context repo files"),p.set("branch",a);for(let m of l)p.set(m.path,m.content);if((await Ct(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 MI,KI,WI,Go=x(()=>{"use strict";Ir();MI="https://api.github.com";KI="https://gitlab.com/api/v4";WI="https://api.bitbucket.org/2.0"});function qe(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=YI[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 YI,Es=x(()=>{"use strict";YI={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as zI}from"node:crypto";import{existsSync as Tw,mkdirSync as VI,readFileSync as Rw,readdirSync as XI,rmSync as Ts,writeFileSync as JI}from"node:fs";import{homedir as ZI}from"node:os";import{dirname as QI,join as Wl}from"node:path";function Iw(){return Wl(ZI(),".codepipe","init-drafts")}function ql(t){let e=zI("sha256").update(t).digest("hex").slice(0,16);return Wl(Iw(),`${e}.json`)}function Cw(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=eC)}function Pw(t){let e=ql(t);if(!Tw(e))return null;try{let r=JSON.parse(Rw(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Cw(r.savedAt)?(Ts(e,{force:!0}),null):r}catch{return null}}function Yl(t){Ts(ql(t),{force:!0})}function Aw(){let t=Iw();if(Tw(t))for(let e of XI(t)){let r=Wl(t,e);try{let n=JSON.parse(Rw(r,"utf-8"));Cw(n.savedAt)&&Ts(r,{force:!0})}catch{Ts(r,{force:!0})}}}var eC,On,_w=x(()=>{"use strict";eC=24*60*60*1e3;On=class{constructor(e,r){this.cwd=e;this.answers=r?.answers?{...r.answers}:{}}answers;get(e){return this.answers[e]}set(e,r){this.answers[e]=r,this.persist()}delete(e){delete this.answers[e],this.persist()}async ask(e,r){if(e in this.answers)return this.answers[e];let n=await r();return this.set(e,n),n}clear(){Yl(this.cwd)}persist(){let e=ql(this.cwd);VI(QI(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};JI(e,JSON.stringify(r,null,2)+`
892
+ `,{mode:384})}}});function jw(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 Nw(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 Ow=x(()=>{"use strict"});import{existsSync as tC}from"node:fs";import{join as rC}from"node:path";import{simpleGit as nC}from"simple-git";function aC(t){let e=t.split("/");return e[e.length-1]??t}function Lw(t){if(t.filter(r=>!iC.test(aC(r))).length>oC)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(sC.has(n))return!0}return!1}async function cC(t){try{let r=(await nC(t).raw(["ls-files"])).split(`
893
+ `).map(n=>n.trim()).filter(Boolean);return Lw(r)}catch{return!1}}async function lC(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)?Lw(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function Mw(t,e){for(let r of t)try{let n=e.localRoot!=null?rC(e.localRoot,r.mountAs??r.name):null;if(n&&tC(n)?await cC(n):await lC(r,e.tokens))return!0}catch{}return!1}var oC,iC,sC,Dw=x(()=>{"use strict";oC=3,iC=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,sC=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as Uw}from"node:fs";import{join as Bw}from"node:path";import{simpleGit as Fw}from"simple-git";async function Ho(t,e,r={}){let n=r.log??uC,o=[];for(let i of e){let s=Bw(t,i.mountAs),a=ci(i);if(!Uw(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 Fw().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let p=Ko(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(!Uw(Bw(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=Fw(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!dC(l,a)){n.warn(`${i.mountAs}/ origin (${Ko(l)||"none"}) != expected (${Ko(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:Ko(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=Ko(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 dC(t,e){return Gw(t)===Gw(e)}function Gw(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function Ko(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function Kw(t={}){let e=Ae();e||(console.error("no .codepipe/ workspace found in this directory or any parent. run `codepipe init` first."),process.exit(1)),console.log(`codepipe sync \u2014 project ${e.spec.projectId} (${e.spec.repos.length} repos)`);let r=await Ho(e.root,e.spec.repos,{dryRun:t.dryRun===!0});for(let n of r)console.log(` ${n.mountAs}: ${n.status}${n.detail?` \u2014 ${n.detail}`:""}`)}var uC,Rs=x(()=>{"use strict";it();uC={info:t=>console.log(t),warn:t=>console.warn(t)}});import{simpleGit as pC}from"simple-git";async function Hw(t,e,r){return t.host==="github"?fC(t,e,r):t.host==="gitlab"?mC(t,e,r):hC(t,e,r)}function zl(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 fC(t,e,r){let n=e.githubToken;if(!n)throw new Error("GitHub token required to create a github-hosted mirror");let o=await Qe(n,"GET",`/repos/${t.owner}/${encodeURIComponent(t.repoName)}`);if(o.status===200&&o.data){if(o.data.private!==!0)throw zl(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 Qe(n,"GET","/user")).data?.login??"",s=i.toLowerCase()===t.owner.toLowerCase(),a=!s&&await Hl(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 Qe(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 Ww(t,e,r){try{return t==="github"?(await Qe(e,"GET","/user")).data?.login??null:t==="gitlab"?(await We(e,"GET","/user")).data?.username??null:r?(await Ct({email:r,apiToken:e},"GET","/workspaces?role=contributor&pagelen=1")).data?.values?.[0]?.slug??null:null}catch{return null}}async function mC(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 We(n,"GET",`/projects/${o}`);if(i.status===200&&i.data){if(i.data.visibility!=="private")throw zl(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 We(n,"GET","/user")).data?.username!==t.owner){let l=await We(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 We(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 hC(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 Ct(n,"GET",o);if(s.status===200&&s.data){if(s.data.is_private!==!0)throw zl(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 Ct(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 qw(t,e,r){let n=pC(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(`
894
+ `).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 Yw(t){return`${t}-codepipe-mirror`}var zw=x(()=>{"use strict";Go()});var Qw={};ze(Qw,{ensureEmbeddedWorker:()=>Cs,spawnWorkerProcess:()=>Ps,upCommand:()=>As,workerChildEnv:()=>Zw,workerStartArgs:()=>Jw});import{spawn as Xw}from"node:child_process";import{existsSync as Vw}from"node:fs";import{homedir as gC,hostname as yC}from"node:os";import{join as Is}from"node:path";async function wC(t,e,r){let n=Le(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${$t(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 uh(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 ${$t(e)} still holds its token.
895
+ 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`),Vd(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function kC(t,e,r){let n=Le(e)!==null;if(!await wC(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 es(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof K&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof K&&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 K?i:new Error(`cannot reach the HUB at ${t.hubUrl} (${i instanceof Error?i.message:String(i)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await _r({hub:t.hubUrl,token:o,name:r.name??`${yC()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function bC(t,e){let r=Le(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=Ke(r.sealPublicKey);if(!q(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=ui(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 Cs(t,e,r){await kC(t,e,r),bC(t.projectId,e)}function Jw(t){return[...t?["--profile",t]:[],"worker","start"]}function Zw(t){let e={...t};for(let r of Za)delete e[r];return e}function Ps(t){let e=Xw(process.execPath,[t.entry,...Jw(t.profile)],{stdio:["ignore","pipe","pipe"],env:Zw(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
896
+ `))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function $C(t,e){let r=process.cwd(),n=Is(r,ot);if(Jr(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(Vw(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 Vl(r);if(!Nd(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=q(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await ls({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=Is(gC(),".codepipe",e?Is("profiles",e,"context-config"):"context-config");if(vi(c.contextDir,l,a),!Vw(Is(c.contextDir,"project.yaml"))){cn(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};mo(c.contextDir,Tt(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 As(t){let{cfg:e,profile:r}=Qr(t.profile);if(t.debug){let m=typeof t.debug=="string"&&t.debug.trim()?t.debug.trim():"agent-request";process.env.CODEPIPE_DEBUG=m,console.log(`[up] debug logging on (${m}) \u2192 ~/.codepipe/debug/${e.projectId}/`)}await $C(e,r),await Cs(e,r,t);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(m,f)=>{let g=k=>h=>{for(let w of h.toString("utf-8").split(`
897
897
  `))w.length>0&&k.write(`${f} ${w}
898
- `)};m.stdout?.on("data",g(process.stdout)),m.stderr?.on("data",g(process.stderr))},i=(m,f)=>{let g=zw(process.execPath,[n,...f],{stdio:["ignore","pipe","pipe"],env:process.env});return o(g,m),g};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=Cs({entry:n,profile:r,onLine:m=>process.stdout.write(`[worker] ${m}
898
+ `)};m.stdout?.on("data",g(process.stdout)),m.stderr?.on("data",g(process.stderr))},i=(m,f)=>{let g=Xw(process.execPath,[n,...f],{stdio:["ignore","pipe","pipe"],env:process.env});return o(g,m),g};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=Ps({entry:n,profile:r,onLine:m=>process.stdout.write(`[worker] ${m}
899
899
  `)}),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,u=m=>{if(!l){l=!0,console.log(`
900
- [up] ${m} \u2014 stopping both roles`);for(let{child:f}of c)f.exitCode===null&&f.kill(m);setTimeout(()=>{for(let{name:f,child:g}of c)g.exitCode===null&&(console.warn(`[up] ${f} did not stop \u2014 SIGKILL`),g.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:m,child:f})=>new Promise(g=>{f.on("exit",(k,h)=>g({name:m,code:k??(h?1:0)}))})),d=await Promise.race(p);l||(console.log(`[up] ${d.name} exited (code ${d.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(p),process.exit(d.code)}var As=x(()=>{"use strict";ut();_n();Ge();Ut();vl();Ir();je();fe();it();Ko()});import{existsSync as Nr,mkdirSync as Qw,readFileSync as _s,readdirSync as wC,writeFileSync as ek}from"node:fs";import{join as Ye,resolve as tk}from"node:path";import{setTimeout as zl}from"node:timers/promises";import{cancel as rk,confirm as Ho,intro as nk,isCancel as Jl,log as C,multiselect as kC,outro as Vl,password as Wo,select as dt,spinner as Zl,text as ke}from"@clack/prompts";import{simpleGit as On}from"simple-git";function he(t){rk(t),process.exit(1)}function we(t){return Jl(t)&&he("aborted"),t}function ce(t){return Jl(t)&&he("aborted"),typeof t=="string"?t:""}async function ok(t={}){nk("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Cw();let r=Rw(e),n,o=!1;r&&Object.keys(r.answers).length>0?we(await Ho({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(C.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new Nn(e,r),o=!0):(Wl(e),n=new Nn(e)):n=new Nn(e);let i=t.force===!0?null:await Yl(e),s=await n.ask("target",async()=>we(await dt({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 $C(e,n)),a?C.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||sk(e,t.force===!0));let c=await n.ask("hubUrl",async()=>ce(await ke({message:"HUB URL",placeholder:mt,initialValue:V("HUB_URL")??mt,validate:P=>P.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>Ln()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>Mn(c,l)),d=null;s==="farm"&&(d=await bC(c,u));let m=a?SC(a.parsed.repoName):"",f=await n.ask("projectId",async()=>ce(await ke({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:P=>Wt.test(P.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await n.ask("projectName",async()=>ce(await ke({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:P=>P.trim().length>0?void 0:"required"})).trim()),k=await n.ask("language",()=>NC()),h=await n.ask("automationLevel",async()=>we(await dt({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"}))),$=(s==="farm"?"no":await n.ask("mirrorChoice",async()=>we(await dt({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";$&&C.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 S=await n.ask("trackerProvider",async()=>we(await dt({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=S==="internal",v=null,b,I=!0;if(T){let P,N=Zl();N.start("checking task-key prefixes on your account\u2026");try{P=await ch(c,u,{excludeProjectId:f}),N.stop("prefixes checked")}catch{N.stop("could not reach the HUB",1),he("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 de=qa(Wa(g),P);b=await n.ask("trackerPrefix",async()=>ce(await ke({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:de,initialValue:de,validate:Te=>{let ft=Te.trim();if(!$r.test(ft))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(P.has(ft.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else v=await n.ask("youtrack",()=>hk()),b=await n.ask("youtrackProjectKey",async()=>ce(await ke({message:"YouTrack project key",placeholder:"DEV",validate:P=>P.trim().length>0?void 0:"required"})).trim()),I=await n.ask("youtrackWrites",async()=>we(await Ho({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let _=n.get("tokens")??{},G=()=>n.set("tokens",_),z=await n.ask("repos",()=>RC(_,l,a,{onCred:G,initial:n.get("reposPartial")??[],onProgress:P=>n.set("reposPartial",P)}));n.delete("reposPartial");let A=null,y="",U="";if($){let P=we(await n.ask("mirrorHost",async()=>we(await dt({message:"where should the mirrors live? (your Context Repo will default there too)",options:["github","gitlab","bitbucket"].map(pe=>({value:pe,label:pe===z[0]?.host?`${pe} (same as your repositories)`:pe})),initialValue:z[0]?.host??"github"}))));y=ce(await n.ask("mirrorToken",async()=>we(await Wo({message:`token that may CREATE and PUSH repositories on ${P}`})))).trim(),P==="bitbucket"&&(U=ce(await n.ask("mirrorEmail",async()=>we(await ke({message:"Atlassian account email for that token",..._.bitbucket?.email?{placeholder:_.bitbucket.email,defaultValue:_.bitbucket.email}:{}})))).trim());let N=await Kw(P,y,U||void 0),de=P==="bitbucket"?"workspace slug":"username or organization (not an email)",ft=ce(await n.ask("mirrorOwnerLogin",async()=>we(await ke({message:`account for the mirrors \u2014 ${P} ${de}`,...N?{placeholder:N,defaultValue:N}:{},validate:pe=>{let ne=(pe??"").trim();if(!ne&&!N)return"required";if(ne.includes("@"))return`that looks like an email \u2014 a ${P} ${de} is expected`;if(/\s/.test(ne))return"no spaces"}})))).trim()||N||"";if(!ft||ft.includes("@")){rk("mirrors need a host account to live in (a username/organization, not an email)");return}A={host:P,owner:ft}}let j=await CC(await n.ask("contextRepo",()=>pk(f,z,_,l,A??void 0)),f,z,_,l,G,P=>n.set("contextRepo",P),A??void 0),{spec:H,mode:J}=j,oe;T||(C.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),oe=await n.ask("assigneeLogin",async()=>ce(await ke({message:"your YouTrack login (the assignee value)",...v?.login?{initialValue:v.login}:{},validate:P=>P.trim().length>0?void 0:"required"})).trim()));let At=await n.ask("llmProvider",async()=>{for(;;){if(we(await dt({message:"LLM provider",options:[{value:"claude",label:"Claude",hint:"recommended"},{value:"codex",label:"Codex",hint:"coming soon"}],initialValue:"claude"}))==="claude")return"claude";C.warn("Codex support is coming soon \u2014 pick Claude for now.")}}),pt=At==="claude"?await n.ask("claudeToken",()=>ww(yw("claude"),{farm:s==="farm"})):"",Ue;if(pt){let P=await Op(pt);if(P){let N=ga(P);N&&(Ue=N,C.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${N} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let L={projectId:f,name:g,automationLevel:h,repos:z,trackerProvider:S,youtrackProjectKey:b,language:k};C.step(`${J==="attach"?"attaching to":"provisioning"} Context Repo ${H.owner}/${H.name} (${H.host})\u2026`);let B;try{B=await jn(L,H,{...fk(_),youtrackWrites:I,...v?{trackerUrl:v.url}:{},mode:J,log:{info:P=>C.message(P),warn:P=>C.warn(P)}})}catch(P){he(`Context Repo provisioning failed: ${P instanceof Error?P.message:String(P)}`)}L.contextRepo=B,C.success(`Context Repo ready: ${B.owner}/${B.name}@${B.branch}`),C.step(`registering project on ${c}\u2026`);let M;try{M=await nr(c,u,L)}catch(P){if(P instanceof K&&P.status===409){C.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{M=await se(c,u,f)}catch(N){throw N instanceof K&&he(`HUB \u2192 ${N.status} ${N.message}`),N}}else if(P instanceof K&&P.status===401)n.delete("cliToken"),he("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(P instanceof K)he(`HUB \u2192 ${P.status} ${P.message}`);else throw P}let Y=M.contextRepo??B;C.success(`project ${M.projectId} ready (${M.provisioningStatus})`);let W=v?{url:v.url,token:v.token}:void 0;if(s==="farm"){let P=d,N={..._,...pt?{claude:{oauthToken:pt}}:{},...W?{youtrack:W}:{}},de=_.github?.token;if(Y.host==="github"&&de)try{let ne=eg(`devpipe-${f}`);await tg(Y,de,ne.publicKey,`devpipe-${f}`),N.contextSsh={privateKey:ne.privateKey},C.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(ne){C.warn(`could not set up Context Repo SSH deploy key (${ne instanceof Error?ne.message:String(ne)}); the farm will fall back to the token path.`)}let Te={projectId:f,config:{hubUrl:c,cliToken:u,projectId:f},secrets:N,contextRepo:Y,projectConfig:Tt(L,I,v?.url,oe||void 0,At,Ue)},ft=Bt(P.farm.publicKey,JSON.stringify(Te));C.step(`handing project ${f} to farm ${P.farm.name}\u2026`);let pe;try{pe=await Zi(c,u,P.farm.farmId,{projectId:f,sealedBundle:ft})}catch(ne){throw ne instanceof K&&he(ne.status===409?`farm ${P.farm.name} is offline \u2014 start it and re-run.`:ne.status===504?`farm ${P.farm.name} did not respond in time.`:`HUB \u2192 ${ne.status} ${ne.message}`),ne}pe.ok||he(`farm rejected provisioning: ${pe.error??"unknown error"}`),await Xl(c,u,f,Y,de,M.repos,null,_),n.clear(),Vl(`done. project ${f} is now hosted on farm ${P.farm.name} (daemon ${pe.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}mk(_),await lk(e,Y.cloneUrl,Y.branch),dk(e);try{cn(Ye(e,ot),e,{info:P=>C.message(P),warn:P=>C.warn(P)})}catch(P){C.warn(`skills materialize failed \u2014 ${P instanceof Error?P.message:String(P)}`)}a&&await TC(e);{let P=Ye(e,ot);an(P);let N=Tt(L,I,v?.url,oe||void 0,At,Ue),de=fo(P,N);de.length>0&&C.success(`local project config \u2192 .codepipe/{${de.join(", ")}}`),Qt(f,N,{info:Te=>C.message(Te),warn:Te=>C.warn(Te)})}await uk(e,M.repos);let E=!1;if($&&A&&(E=await IC(e,Ye(e,ot),M.repos,{host:A.host,owner:A.owner,token:y,...U?{email:U}:{}}),E)){let P=Ye(e,ot);Qt(f,{projectYaml:_s(Ye(P,"project.yaml"),"utf-8"),regimenYaml:_s(Ye(P,"regimen.yaml"),"utf-8")},{info:N=>C.message(N),warn:N=>C.warn(N)})}let R={hubUrl:c,cliToken:u,projectId:f,..._,...pt?{claude:{oauthToken:pt}}:{},...W?{youtrack:W}:{},...E?{mirrorWrite:{token:y,host:A.host,...U?{email:U}:{}}}:{}};ae(R),Mt({hubUrl:c,cliToken:u,projectId:f,accountEmail:p},f),C.success(`secrets \u2192 ${St(f)}`),await Xl(c,u,f,Y,_.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,M.repos,e,_),n.clear();let Q=`${c}/?project=${encodeURIComponent(f)}`;Tr(Q),Vl(`done. your project on the dashboard (sign in there to work with it):
900
+ [up] ${m} \u2014 stopping both roles`);for(let{child:f}of c)f.exitCode===null&&f.kill(m);setTimeout(()=>{for(let{name:f,child:g}of c)g.exitCode===null&&(console.warn(`[up] ${f} did not stop \u2014 SIGKILL`),g.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:m,child:f})=>new Promise(g=>{f.on("exit",(k,h)=>g({name:m,code:k??(h?1:0)}))})),d=await Promise.race(p);l||(console.log(`[up] ${d.name} exited (code ${d.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(p),process.exit(d.code)}var _s=x(()=>{"use strict";ut();jn();Ge();Ut();xl();Ir();je();me();it();Wo()});import{existsSync as Or,mkdirSync as tk,readFileSync as js,readdirSync as vC,writeFileSync as rk}from"node:fs";import{join as Ye,resolve as nk}from"node:path";import{setTimeout as Xl}from"node:timers/promises";import{cancel as ok,confirm as qo,intro as ik,isCancel as Ql,log as C,multiselect as xC,outro as Jl,password as Yo,select as dt,spinner as eu,text as ke}from"@clack/prompts";import{simpleGit as Ln}from"simple-git";function he(t){ok(t),process.exit(1)}function we(t){return Ql(t)&&he("aborted"),t}function ce(t){return Ql(t)&&he("aborted"),typeof t=="string"?t:""}async function sk(t={}){ik("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Aw();let r=Pw(e),n,o=!1;r&&Object.keys(r.answers).length>0?we(await qo({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(C.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new On(e,r),o=!0):(Yl(e),n=new On(e)):n=new On(e);let i=t.force===!0?null:await Vl(e),s=await n.ask("target",async()=>we(await dt({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 EC(e,n)),a?C.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||ck(e,t.force===!0));let c=await n.ask("hubUrl",async()=>ce(await ke({message:"HUB URL",placeholder:mt,initialValue:X("HUB_URL")??mt,validate:P=>P.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>Mn()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>Dn(c,l)),d=null;s==="farm"&&(d=await SC(c,u));let m=a?IC(a.parsed.repoName):"",f=await n.ask("projectId",async()=>ce(await ke({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:P=>Wt.test(P.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await n.ask("projectName",async()=>ce(await ke({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:P=>P.trim().length>0?void 0:"required"})).trim()),k=await n.ask("language",()=>DC()),h=await n.ask("automationLevel",async()=>we(await dt({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"}))),$=(s==="farm"?"no":await n.ask("mirrorChoice",async()=>we(await dt({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";$&&C.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 S=await n.ask("trackerProvider",async()=>we(await dt({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=S==="internal",v=null,b,R=!0;if(T){let P,N=eu();N.start("checking task-key prefixes on your account\u2026");try{P=await dh(c,u,{excludeProjectId:f}),N.stop("prefixes checked")}catch{N.stop("could not reach the HUB",1),he("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 pe=Ya(qa(g),P);b=await n.ask("trackerPrefix",async()=>ce(await ke({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:pe,initialValue:pe,validate:Te=>{let ft=Te.trim();if(!vr.test(ft))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(P.has(ft.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else v=await n.ask("youtrack",()=>yk()),b=await n.ask("youtrackProjectKey",async()=>ce(await ke({message:"YouTrack project key",placeholder:"DEV",validate:P=>P.trim().length>0?void 0:"required"})).trim()),R=await n.ask("youtrackWrites",async()=>we(await qo({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let _=n.get("tokens")??{},G=()=>n.set("tokens",_),z=await n.ask("repos",()=>_C(_,l,a,{onCred:G,initial:n.get("reposPartial")??[],onProgress:P=>n.set("reposPartial",P)}));n.delete("reposPartial");let A=null,y="",U="";if($){let P=we(await n.ask("mirrorHost",async()=>we(await dt({message:"where should the mirrors live? (your Context Repo will default there too)",options:["github","gitlab","bitbucket"].map(fe=>({value:fe,label:fe===z[0]?.host?`${fe} (same as your repositories)`:fe})),initialValue:z[0]?.host??"github"}))));y=ce(await n.ask("mirrorToken",async()=>we(await Yo({message:`token that may CREATE and PUSH repositories on ${P}`})))).trim(),P==="bitbucket"&&(U=ce(await n.ask("mirrorEmail",async()=>we(await ke({message:"Atlassian account email for that token",..._.bitbucket?.email?{placeholder:_.bitbucket.email,defaultValue:_.bitbucket.email}:{}})))).trim());let N=await Ww(P,y,U||void 0),pe=P==="bitbucket"?"workspace slug":"username or organization (not an email)",ft=ce(await n.ask("mirrorOwnerLogin",async()=>we(await ke({message:`account for the mirrors \u2014 ${P} ${pe}`,...N?{placeholder:N,defaultValue:N}:{},validate:fe=>{let ne=(fe??"").trim();if(!ne&&!N)return"required";if(ne.includes("@"))return`that looks like an email \u2014 a ${P} ${pe} is expected`;if(/\s/.test(ne))return"no spaces"}})))).trim()||N||"";if(!ft||ft.includes("@")){ok("mirrors need a host account to live in (a username/organization, not an email)");return}A={host:P,owner:ft}}let j=await jC(await n.ask("contextRepo",()=>mk(f,z,_,l,A??void 0)),f,z,_,l,G,P=>n.set("contextRepo",P),A??void 0),{spec:H,mode:J}=j,oe;T||(C.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),oe=await n.ask("assigneeLogin",async()=>ce(await ke({message:"your YouTrack login (the assignee value)",...v?.login?{initialValue:v.login}:{},validate:P=>P.trim().length>0?void 0:"required"})).trim()));let At=await n.ask("llmProvider",async()=>{for(;;){if(we(await dt({message:"LLM provider",options:[{value:"claude",label:"Claude",hint:"recommended"},{value:"codex",label:"Codex",hint:"coming soon"}],initialValue:"claude"}))==="claude")return"claude";C.warn("Codex support is coming soon \u2014 pick Claude for now.")}}),pt=At==="claude"?await n.ask("claudeToken",()=>bw(kw("claude"),{farm:s==="farm"})):"",Ue;if(pt){let P=await Mp(pt);if(P){let N=ya(P);N&&(Ue=N,C.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${N} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let L={projectId:f,name:g,automationLevel:h,repos:z,trackerProvider:S,youtrackProjectKey:b,language:k};C.step(`${J==="attach"?"attaching to":"provisioning"} Context Repo ${H.owner}/${H.name} (${H.host})\u2026`);let B;try{B=await Nn(L,H,{...hk(_),youtrackWrites:R,...v?{trackerUrl:v.url}:{},mode:J,log:{info:P=>C.message(P),warn:P=>C.warn(P)}})}catch(P){he(`Context Repo provisioning failed: ${P instanceof Error?P.message:String(P)}`)}L.contextRepo=B,C.success(`Context Repo ready: ${B.owner}/${B.name}@${B.branch}`),C.step(`registering project on ${c}\u2026`);let M;try{M=await or(c,u,L)}catch(P){if(P instanceof K&&P.status===409){C.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{M=await se(c,u,f)}catch(N){throw N instanceof K&&he(`HUB \u2192 ${N.status} ${N.message}`),N}}else if(P instanceof K&&P.status===401)n.delete("cliToken"),he("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(P instanceof K)he(`HUB \u2192 ${P.status} ${P.message}`);else throw P}let Y=M.contextRepo??B;C.success(`project ${M.projectId} ready (${M.provisioningStatus})`);let W=v?{url:v.url,token:v.token}:void 0;if(s==="farm"){let P=d,N={..._,...pt?{claude:{oauthToken:pt}}:{},...W?{youtrack:W}:{}},pe=_.github?.token;if(Y.host==="github"&&pe)try{let ne=ng(`devpipe-${f}`);await og(Y,pe,ne.publicKey,`devpipe-${f}`),N.contextSsh={privateKey:ne.privateKey},C.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(ne){C.warn(`could not set up Context Repo SSH deploy key (${ne instanceof Error?ne.message:String(ne)}); the farm will fall back to the token path.`)}let Te={projectId:f,config:{hubUrl:c,cliToken:u,projectId:f},secrets:N,contextRepo:Y,projectConfig:Tt(L,R,v?.url,oe||void 0,At,Ue)},ft=Bt(P.farm.publicKey,JSON.stringify(Te));C.step(`handing project ${f} to farm ${P.farm.name}\u2026`);let fe;try{fe=await Qi(c,u,P.farm.farmId,{projectId:f,sealedBundle:ft})}catch(ne){throw ne instanceof K&&he(ne.status===409?`farm ${P.farm.name} is offline \u2014 start it and re-run.`:ne.status===504?`farm ${P.farm.name} did not respond in time.`:`HUB \u2192 ${ne.status} ${ne.message}`),ne}fe.ok||he(`farm rejected provisioning: ${fe.error??"unknown error"}`),await Zl(c,u,f,Y,pe,M.repos,null,_),n.clear(),Jl(`done. project ${f} is now hosted on farm ${P.farm.name} (daemon ${fe.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}gk(_),await dk(e,Y.cloneUrl,Y.branch),fk(e);try{ln(Ye(e,ot),e,{info:P=>C.message(P),warn:P=>C.warn(P)})}catch(P){C.warn(`skills materialize failed \u2014 ${P instanceof Error?P.message:String(P)}`)}a&&await PC(e);{let P=Ye(e,ot);cn(P);let N=Tt(L,R,v?.url,oe||void 0,At,Ue),pe=mo(P,N);pe.length>0&&C.success(`local project config \u2192 .codepipe/{${pe.join(", ")}}`),Qt(f,N,{info:Te=>C.message(Te),warn:Te=>C.warn(Te)})}await pk(e,M.repos);let E=!1;if($&&A&&(E=await AC(e,Ye(e,ot),M.repos,{host:A.host,owner:A.owner,token:y,...U?{email:U}:{}}),E)){let P=Ye(e,ot);Qt(f,{projectYaml:js(Ye(P,"project.yaml"),"utf-8"),regimenYaml:js(Ye(P,"regimen.yaml"),"utf-8")},{info:N=>C.message(N),warn:N=>C.warn(N)})}let I={hubUrl:c,cliToken:u,projectId:f,..._,...pt?{claude:{oauthToken:pt}}:{},...W?{youtrack:W}:{},...E?{mirrorWrite:{token:y,host:A.host,...U?{email:U}:{}}}:{}};ae(I),Mt({hubUrl:c,cliToken:u,projectId:f,accountEmail:p},f),C.success(`secrets \u2192 ${St(f)}`),await Zl(c,u,f,Y,_.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,M.repos,e,_),n.clear();let Q=`${c}/?project=${encodeURIComponent(f)}`;Rr(Q),Jl(`done. your project on the dashboard (sign in there to work with it):
901
901
  ${Q}
902
- 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:ie}=await Promise.resolve().then(()=>(As(),Jw));await ie({profile:void 0})}async function Xl(t,e,r,n,o,i=[],s=null,a={}){let c=await _w(n,o),l=!1;if(!c)try{l=await Ow(i,{localRoot:s,tokens:a})}catch{l=!1}let u=Aw({indexExists:c,localClones:s!==null,reposNonEmpty:l}),p=await kC({message:u.message,options:u.options,initialValues:u.initialValues,required:!1});if(Jl(p))return;let d=new Set(p);if(d.has("map")&&s!==null)try{let m=Ae(s);if(!m)throw new Error("workspace not found");let{bootstrapWorkspaceModel:f}=await Promise.resolve().then(()=>(_o(),is)),g=await f(m,void 0,{onLog:k=>C.message(k)});C.success(`project map ready: ${g.events} task events mined from history`)}catch(m){C.warn(`could not build the project map: ${m instanceof Error?m.message:String(m)}. Registration is not affected \u2014 run \`codepipe model bootstrap\` later.`)}if(d.has("backfill"))try{let{jobId:m}=await Ao(t,e,r,{reindex:!1,backfill:!0});C.success(`retrospective architecture analysis queued (job ${m}); decision drafts will appear on the project card for review once a SANDBOX picks up the job.`)}catch(m){C.warn(`could not start the retrospective analysis: ${m instanceof Error?m.message:String(m)}. Registration is not affected.`)}if(d.has("index"))try{let{jobId:m}=await Ao(t,e,r,{reindex:u.reindex});C.success(`indexing queued (job ${m}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(m){C.warn(`could not start indexing: ${m instanceof Error?m.message:String(m)}. You can retry later \u2014 registration is not affected.`)}}async function bC(t,e){let r;try{r=await oh(t,e)}catch(c){throw c instanceof K&&he(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&he("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=we(await dt({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=Xi(i.farmId,i.publicKey)}catch(c){he(c instanceof Error?c.message:String(c))}return we(await Ho({message:`confirm farm ${i.name} cred-channel fingerprint:
902
+ 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:ie}=await Promise.resolve().then(()=>(_s(),Qw));await ie({profile:void 0})}async function Zl(t,e,r,n,o,i=[],s=null,a={}){let c=await Nw(n,o),l=!1;if(!c)try{l=await Mw(i,{localRoot:s,tokens:a})}catch{l=!1}let u=jw({indexExists:c,localClones:s!==null,reposNonEmpty:l}),p=await xC({message:u.message,options:u.options,initialValues:u.initialValues,required:!1});if(Ql(p))return;let d=new Set(p);if(d.has("map")&&s!==null)try{let m=Ae(s);if(!m)throw new Error("workspace not found");let{bootstrapWorkspaceModel:f}=await Promise.resolve().then(()=>(No(),ss)),g=await f(m,void 0,{onLog:k=>C.message(k)});C.success(`project map ready: ${g.events} task events mined from history`)}catch(m){C.warn(`could not build the project map: ${m instanceof Error?m.message:String(m)}. Registration is not affected \u2014 run \`codepipe model bootstrap\` later.`)}if(d.has("backfill"))try{let{jobId:m}=await jo(t,e,r,{reindex:!1,backfill:!0});C.success(`retrospective architecture analysis queued (job ${m}); decision drafts will appear on the project card for review once a SANDBOX picks up the job.`)}catch(m){C.warn(`could not start the retrospective analysis: ${m instanceof Error?m.message:String(m)}. Registration is not affected.`)}if(d.has("index"))try{let{jobId:m}=await jo(t,e,r,{reindex:u.reindex});C.success(`indexing queued (job ${m}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(m){C.warn(`could not start indexing: ${m instanceof Error?m.message:String(m)}. You can retry later \u2014 registration is not affected.`)}}async function SC(t,e){let r;try{r=await ah(t,e)}catch(c){throw c instanceof K&&he(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&he("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=we(await dt({message:"target farm",options:n.map(c=>({value:c.farmId,label:`${c.name}${c.online?"":" (offline)"} \u2014 ${c.keyFingerprint??"no fingerprint"}`}))})),i=n.find(c=>c.farmId===o),s;try{s=Ji(i.farmId,i.publicKey)}catch(c){he(c instanceof Error?c.message:String(c))}return we(await qo({message:`confirm farm ${i.name} cred-channel fingerprint:
903
903
  ${s}
904
- (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||he("farm fingerprint not confirmed \u2014 aborting."),Vi(i.farmId,s),{farm:i,fingerprint:s}}async function ik(t){nk(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();sk(e,t.force===!0);let r=ce(await ke({message:"HUB URL",initialValue:V("HUB_URL")??mt,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await Ln(),{cliToken:o,accountEmail:i}=await Mn(r,n);C.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await se(r,o,t.projectId)}catch(d){throw d instanceof K&&he(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||he(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await hk(),l={},u=new Set(s.repos.map(d=>d.host));u.add(s.contextRepo.host);for(let d of u){let m=s.repos.find(f=>f.host===d);await js(d,l,m?.owner??s.contextRepo.owner,n,m?.repoName)}mk(l),await lk(e,s.contextRepo.cloneUrl,s.contextRepo.branch),dk(e);{let d=Ye(e,ot);an(d);let m={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.trackerProvider?{trackerProvider:s.trackerProvider}:{},...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{},...s.language?{language:s.language}:{}},f=Tt(m,!0,c?.url,void 0,s.llmProvider??Xe),g=fo(d,f);g.length>0&&C.success(`local project config \u2192 .codepipe/{${g.join(", ")}} (defaults \u2014 review and adjust)`),Qt(t.projectId,f,{info:k=>C.message(k),warn:k=>C.warn(k)})}await uk(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};ae(p),Mt({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),C.success(`secrets \u2192 ${St(t.projectId)}`),await Xl(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),Vl("done.")}function sk(t,e){if(!Nr(t)){Qw(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=wC(t).filter(o=>!r.has(o));n.length!==0&&(e||he(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function Yl(t){if(!Nr(Ye(t,".git")))return null;try{let e=qe(await ak(t));return e?{parsed:e,defaultBranch:await ck(t)}:null}catch{return null}}async function ak(t){try{return(await On(t).remote(["get-url","origin"])||"").toString().trim()}catch{return""}}async function $C(t,e){if(!Nr(Ye(t,".git")))return null;let r=await e.ask("inPlaceOrigin",async()=>{let o=await ak(t);return C.warn(o?`this folder is a git checkout, but its origin (${o}) is not a github.com / gitlab.com / bitbucket.org URL`:"this folder is a git checkout without an `origin` remote"),ce(await ke({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()||qe(i)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim()}),n=r?qe(r):null;return n?{parsed:n,defaultBranch:await ck(t)}:null}async function vC(t){try{let e=await On().listRemote(["--symref",t,"HEAD"]);return/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m.exec(e)?.[1]??null}catch{return null}}async function xC(t,e){try{return(await On().listRemote([t,`refs/heads/${e}`])).trim().length>0}catch{return!0}}async function ck(t){let e=On(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 SC(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Wt.test(e)?e:""}function EC(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function TC(t){let e=Ye(t,".gitignore"),r=Nr(e)?_s(e,"utf-8"):"";if(EC(r))return;if(!we(await Ho({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){C.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
904
+ (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||he("farm fingerprint not confirmed \u2014 aborting."),Xi(i.farmId,s),{farm:i,fingerprint:s}}async function ak(t){ik(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();ck(e,t.force===!0);let r=ce(await ke({message:"HUB URL",initialValue:X("HUB_URL")??mt,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await Mn(),{cliToken:o,accountEmail:i}=await Dn(r,n);C.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await se(r,o,t.projectId)}catch(d){throw d instanceof K&&he(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||he(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await yk(),l={},u=new Set(s.repos.map(d=>d.host));u.add(s.contextRepo.host);for(let d of u){let m=s.repos.find(f=>f.host===d);await Ns(d,l,m?.owner??s.contextRepo.owner,n,m?.repoName)}gk(l),await dk(e,s.contextRepo.cloneUrl,s.contextRepo.branch),fk(e);{let d=Ye(e,ot);cn(d);let m={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.trackerProvider?{trackerProvider:s.trackerProvider}:{},...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{},...s.language?{language:s.language}:{}},f=Tt(m,!0,c?.url,void 0,s.llmProvider??Xe),g=mo(d,f);g.length>0&&C.success(`local project config \u2192 .codepipe/{${g.join(", ")}} (defaults \u2014 review and adjust)`),Qt(t.projectId,f,{info:k=>C.message(k),warn:k=>C.warn(k)})}await pk(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};ae(p),Mt({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),C.success(`secrets \u2192 ${St(t.projectId)}`),await Zl(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),Jl("done.")}function ck(t,e){if(!Or(t)){tk(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=vC(t).filter(o=>!r.has(o));n.length!==0&&(e||he(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function Vl(t){if(!Or(Ye(t,".git")))return null;try{let e=qe(await lk(t));return e?{parsed:e,defaultBranch:await uk(t)}:null}catch{return null}}async function lk(t){try{return(await Ln(t).remote(["get-url","origin"])||"").toString().trim()}catch{return""}}async function EC(t,e){if(!Or(Ye(t,".git")))return null;let r=await e.ask("inPlaceOrigin",async()=>{let o=await lk(t);return C.warn(o?`this folder is a git checkout, but its origin (${o}) is not a github.com / gitlab.com / bitbucket.org URL`:"this folder is a git checkout without an `origin` remote"),ce(await ke({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()||qe(i)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim()}),n=r?qe(r):null;return n?{parsed:n,defaultBranch:await uk(t)}:null}async function TC(t){try{let e=await Ln().listRemote(["--symref",t,"HEAD"]);return/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m.exec(e)?.[1]??null}catch{return null}}async function RC(t,e){try{return(await Ln().listRemote([t,`refs/heads/${e}`])).trim().length>0}catch{return!0}}async function uk(t){let e=Ln(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 IC(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Wt.test(e)?e:""}function CC(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function PC(t){let e=Ye(t,".gitignore"),r=Or(e)?js(e,"utf-8"):"";if(CC(r))return;if(!we(await qo({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){C.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
905
905
  `)?"":`
906
- `;ek(e,r+o+`
906
+ `;rk(e,r+o+`
907
907
  # codepipe workspace (added by \`codepipe init\`)
908
908
  .codepipe/
909
- `),C.success(`.codepipe/ added to ${tk(e)}`)}async function Ln(){let t="";try{t=(await On().raw(["config","--global","user.email"])||"").trim()}catch{}return ce(await ke({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function Mn(t,e){C.step(`connecting account ${e}`);let r;try{r=await lh(t,e)}catch(s){throw s instanceof Po&&he(`${e} is not authorized on this HUB yet.
909
+ `),C.success(`.codepipe/ added to ${nk(e)}`)}async function Mn(){let t="";try{t=(await Ln().raw(["config","--global","user.email"])||"").trim()}catch{}return ce(await ke({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function Dn(t,e){C.step(`connecting account ${e}`);let r;try{r=await ph(t,e)}catch(s){throw s instanceof _o&&he(`${e} is not authorized on this HUB yet.
910
910
  Sign up at ${t} (registration form on the login screen),
911
911
  wait for the operator to approve it by email, then re-run
912
- \`codepipe init\` with the same email.`),s}r.accountCreated&&C.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&C.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(Tr(r.authorizeUrl),C.message(`a browser tab was opened to confirm this CLI:
912
+ \`codepipe init\` with the same email.`),s}r.accountCreated&&C.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&C.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(Rr(r.authorizeUrl),C.message(`a browser tab was opened to confirm this CLI:
913
913
  ${r.authorizeUrl}
914
914
  `+(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
915
- otherwise use the emailed link the page offers.`))),r.approvalRequired&&C.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),C.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 uh(t,r.requestId)}catch(a){C.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await zl(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&C.message(`connected as ${a} (the account confirmed in the browser).`),C.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&he("the HUB rejected this account"),s.status==="expired"&&he("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,C.message(`email confirmed. waiting for the operator to approve your account\u2026
916
- (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await zl(5e3);continue}await zl(2e3)}he("bootstrap timed out")}async function lk(t,e,r){let n=Ye(t,ot);if(Nr(Ye(n,".git"))){C.message(`${n} already cloned \u2014 skipping`);return}Nr(n)&&he(`${n} exists but is not a git repo \u2014 remove it and re-run`),Qw(n,{recursive:!0}),C.step(`cloning Context Repo \u2192 ${n}`);try{await On().clone(e,n,["--branch",r]),C.success(`cloned ${e}`)}catch(o){he(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function IC(t,e,r,n){if(r.length===0)return!1;C.step(`setting up ${r.length} mirror(s) \u2014 your repositories stay read-only`);let o={info:a=>C.message(` ${a}`),warn:a=>C.warn(` ${a}`)},i={...n.host==="github"?{githubToken:n.token}:{},...n.host==="gitlab"?{gitlabToken:n.token}:{},...n.host==="bitbucket"&&n.email?{bitbucket:{email:n.email,apiToken:n.token}}:{}},s=[];for(let a of r){let c={host:n.host,owner:n.owner,repoName:Ww(a.repoName)};try{let l=await Gw(c,i,o);await Hw(Ye(t,a.mountAs??a.name),l.sshUrl,o),s.push({repoName:a.name,spec:c})}catch(l){return C.warn(` ${a.name}: mirror not set up \u2014 ${l instanceof Error?l.message:String(l)}`),C.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 a of s)tm(e,a.repoName,a.spec);for(let a of s)C.success(` ${a.repoName} \u2192 ${a.spec.owner}/${a.spec.repoName}`);return!0}async function uk(t,e){if(e.length===0)return;C.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 Go(t,r,{log:{info:o=>C.message(o),warn:o=>C.warn(o)}});for(let o of n)C.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function dk(t){let e=Ye(t,ot,".gitignore"),r="";if(Nr(e)&&(r=_s(e,"utf-8")),Zw.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
915
+ otherwise use the emailed link the page offers.`))),r.approvalRequired&&C.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),C.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 fh(t,r.requestId)}catch(a){C.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await Xl(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&C.message(`connected as ${a} (the account confirmed in the browser).`),C.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&he("the HUB rejected this account"),s.status==="expired"&&he("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,C.message(`email confirmed. waiting for the operator to approve your account\u2026
916
+ (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await Xl(5e3);continue}await Xl(2e3)}he("bootstrap timed out")}async function dk(t,e,r){let n=Ye(t,ot);if(Or(Ye(n,".git"))){C.message(`${n} already cloned \u2014 skipping`);return}Or(n)&&he(`${n} exists but is not a git repo \u2014 remove it and re-run`),tk(n,{recursive:!0}),C.step(`cloning Context Repo \u2192 ${n}`);try{await Ln().clone(e,n,["--branch",r]),C.success(`cloned ${e}`)}catch(o){he(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function AC(t,e,r,n){if(r.length===0)return!1;C.step(`setting up ${r.length} mirror(s) \u2014 your repositories stay read-only`);let o={info:a=>C.message(` ${a}`),warn:a=>C.warn(` ${a}`)},i={...n.host==="github"?{githubToken:n.token}:{},...n.host==="gitlab"?{gitlabToken:n.token}:{},...n.host==="bitbucket"&&n.email?{bitbucket:{email:n.email,apiToken:n.token}}:{}},s=[];for(let a of r){let c={host:n.host,owner:n.owner,repoName:Yw(a.repoName)};try{let l=await Hw(c,i,o);await qw(Ye(t,a.mountAs??a.name),l.sshUrl,o),s.push({repoName:a.name,spec:c})}catch(l){return C.warn(` ${a.name}: mirror not set up \u2014 ${l instanceof Error?l.message:String(l)}`),C.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 a of s)nm(e,a.repoName,a.spec);for(let a of s)C.success(` ${a.repoName} \u2192 ${a.spec.owner}/${a.spec.repoName}`);return!0}async function pk(t,e){if(e.length===0)return;C.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(o=>({name:o.name,host:o.host,owner:o.owner,repoName:o.repoName,defaultBranch:o.defaultBranch??"main",mountAs:o.mountAs??o.name})),n=await Ho(t,r,{log:{info:o=>C.message(o),warn:o=>C.warn(o)}});for(let o of n)C.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function fk(t){let e=Ye(t,ot,".gitignore"),r="";if(Or(e)&&(r=js(e,"utf-8")),ek.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
917
917
  `)||r.length===0?"":`
918
- `,i=Zw.join(`
918
+ `,i=ek.join(`
919
919
  `)+`
920
- `;ek(e,r+o+(r?`
921
- `:"")+i),C.message(`appended runtime entries to ${tk(e)}`)}async function RC(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;await js(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),C.success(`added this repository: ${s.host}: ${s.owner}/${s.repoName} (this folder, default branch ${a})`)}for(;we(await Ho({message:o.length===0?"Add a project repository?":`Project repositories: ${o.map(f=>f.name).join(", ")}. Add another one?`,initialValue:o.length===0}));){let a=ce(await ke({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:f=>!f||!f.trim()||qe(f)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!a)continue;let c=qe(a);C.message(`${c.host}: ${c.owner}/${c.repoName}`),await js(c.host,t,c.owner,e,c.repoName),i?.();let l=ce(await ke({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:f=>f.trim().length>0?void 0:"required"})).trim(),u=await vC(a),p="";for(;p=ce(await ke({message:"default branch",placeholder:u??"main",...u?{initialValue:u}:{}})).trim(),!(!p||!u||p===u||await xC(a,p));)C.warn(`branch "${p}" does not exist in ${c.owner}/${c.repoName} (the repository's default is "${u}")`);let d=ce(await ke({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),m={name:l,host:c.host,owner:c.owner,repoName:c.repoName};p&&(m.defaultBranch=p),d&&d!==l&&(m.mountAs=d),o.push(m),n.onProgress?.(o)}return o}async function pk(t,e,r,n,o){C.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=we(await dt({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"&&C.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let s=o?.host??e[0]?.host,a=o?.owner??e[0]?.owner,c;if(s&&a){let l=ce(await ke({message:`Context Repo \u2014 a name (hosted at ${s}: ${a}/<name>) or a full clone URL`,initialValue:xt(t),validate:p=>{let d=(p??"").trim();if(!d)return"required";if(!qe(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=qe(l);c=u?{host:u.host,owner:u.owner,name:u.repoName}:{host:s,owner:a,name:l}}else{let l=await PC(),u=ce(await ke({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:d=>d.trim().length>0?void 0:"required"})).trim(),p=ce(await ke({message:"Context Repo name",placeholder:xt(t),initialValue:xt(t),validate:d=>d.trim().length>0?void 0:"required"})).trim();c={host:l,owner:u,name:p}}return{spec:c,mode:i}}function fk(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??en()}}async function CC(t,e,r,n,o,i,s,a){let c=t;for(;;){let{spec:l,mode:u}=c;await js(l.host,n,l.owner,o),i?.();let p=Zl();p.start(`checking ${l.owner}/${l.name} on ${l.host}\u2026`);let d=await bw(l,fk(n),{explain:u==="attach"});if(d.found===!0)return p.stop(`${l.owner}/${l.name} found${u==="create"?" \u2014 existing repo will be reused":""}`),c;if(d.found==="unknown")return p.stop(`could not check ${l.owner}/${l.name} (${d.detail}) \u2014 continuing`,1),c;if(u==="create")return p.stop(`${l.owner}/${l.name} not found \u2014 will be created`),c;p.stop(d.detail,1);let m=we(await dt({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(m==="abort"&&he("aborted"),m==="create")return c={spec:l,mode:"create"},s(c),c;c=await pk(e,r,n,o,a),s(c)}}async function PC(){return we(await dt({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Ns(t,e){let r=Zl();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 mk(t){bo(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),$o(t.gitlab?.token??process.env.GITLAB_TOKEN),vo(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function js(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await AC(r);i?e.github=i:C.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:C.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 jC();i?e.gitlab=i:C.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function AC(t){for(;;){let e=ce(await Wo({message:`GitHub PAT \u2014 blank to skip
920
+ `;rk(e,r+o+(r?`
921
+ `:"")+i),C.message(`appended runtime entries to ${nk(e)}`)}async function _C(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;await Ns(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),C.success(`added this repository: ${s.host}: ${s.owner}/${s.repoName} (this folder, default branch ${a})`)}for(;we(await qo({message:o.length===0?"Add a project repository?":`Project repositories: ${o.map(f=>f.name).join(", ")}. Add another one?`,initialValue:o.length===0}));){let a=ce(await ke({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:f=>!f||!f.trim()||qe(f)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!a)continue;let c=qe(a);C.message(`${c.host}: ${c.owner}/${c.repoName}`),await Ns(c.host,t,c.owner,e,c.repoName),i?.();let l=ce(await ke({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:f=>f.trim().length>0?void 0:"required"})).trim(),u=await TC(a),p="";for(;p=ce(await ke({message:"default branch",placeholder:u??"main",...u?{initialValue:u}:{}})).trim(),!(!p||!u||p===u||await RC(a,p));)C.warn(`branch "${p}" does not exist in ${c.owner}/${c.repoName} (the repository's default is "${u}")`);let d=ce(await ke({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),m={name:l,host:c.host,owner:c.owner,repoName:c.repoName};p&&(m.defaultBranch=p),d&&d!==l&&(m.mountAs=d),o.push(m),n.onProgress?.(o)}return o}async function mk(t,e,r,n,o){C.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=we(await dt({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"&&C.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let s=o?.host??e[0]?.host,a=o?.owner??e[0]?.owner,c;if(s&&a){let l=ce(await ke({message:`Context Repo \u2014 a name (hosted at ${s}: ${a}/<name>) or a full clone URL`,initialValue:xt(t),validate:p=>{let d=(p??"").trim();if(!d)return"required";if(!qe(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=qe(l);c=u?{host:u.host,owner:u.owner,name:u.repoName}:{host:s,owner:a,name:l}}else{let l=await NC(),u=ce(await ke({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:d=>d.trim().length>0?void 0:"required"})).trim(),p=ce(await ke({message:"Context Repo name",placeholder:xt(t),initialValue:xt(t),validate:d=>d.trim().length>0?void 0:"required"})).trim();c={host:l,owner:u,name:p}}return{spec:c,mode:i}}function hk(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??tn()}}async function jC(t,e,r,n,o,i,s,a){let c=t;for(;;){let{spec:l,mode:u}=c;await Ns(l.host,n,l.owner,o),i?.();let p=eu();p.start(`checking ${l.owner}/${l.name} on ${l.host}\u2026`);let d=await vw(l,hk(n),{explain:u==="attach"});if(d.found===!0)return p.stop(`${l.owner}/${l.name} found${u==="create"?" \u2014 existing repo will be reused":""}`),c;if(d.found==="unknown")return p.stop(`could not check ${l.owner}/${l.name} (${d.detail}) \u2014 continuing`,1),c;if(u==="create")return p.stop(`${l.owner}/${l.name} not found \u2014 will be created`),c;p.stop(d.detail,1);let m=we(await dt({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(m==="abort"&&he("aborted"),m==="create")return c={spec:l,mode:"create"},s(c),c;c=await mk(e,r,n,o,a),s(c)}}async function NC(){return we(await dt({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Os(t,e){let r=eu();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 gk(t){$o(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),vo(t.gitlab?.token??process.env.GITLAB_TOKEN),xo(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Ns(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await OC(r);i?e.github=i:C.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let i=await LC(r,n,o);i?e.bitbucket=i:C.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 MC();i?e.gitlab=i:C.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function OC(t){for(;;){let e=ce(await Yo({message:`GitHub PAT \u2014 blank to skip
922
922
  classic PAT: 'repo' + 'workflow'
923
923
  fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
924
924
  if org: approve token in org Settings \u2192 Personal access tokens.
925
- (Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo.)`})).trim();if(!e)return;if(await Ns("GitHub",()=>qt(e,t?{owner:t}:void 0)))return{token:e};C.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function _C(t,e,r){for(C.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
925
+ (Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo.)`})).trim();if(!e)return;if(await Os("GitHub",()=>qt(e,t?{owner:t}:void 0)))return{token:e};C.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function LC(t,e,r){for(C.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
926
926
  How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
927
927
  'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes:
928
928
  read:repository:bitbucket + write:repository:bitbucket +
929
929
  read:pullrequest:bitbucket + write:pullrequest:bitbucket
930
930
  \u2014 write scopes do NOT include read: pick BOTH scopes of each pair
931
931
  (+ admin:repository:bitbucket if this token will provision the Context Repo).
932
- The token is shown ONCE \u2014 copy it right away.`);;){let n=ce(await ke({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:i=>!i||!i.trim()||i.includes("@")?void 0:"must be an email"})).trim();if(!n)return;let o=ce(await Wo({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){C.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await Ns("Bitbucket",async()=>{let i=await Yt(n,o,t);if(t&&r){let s=await hi(n,o,t,r);if(s)throw new Error(s)}return i}))return{email:n,apiToken:o};C.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function jC(){for(;;){let t=ce(await Wo({message:`GitLab PAT \u2014 blank to skip
933
- scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Ns("GitLab",()=>zt(t))){let e=await np(t);return e&&C.warn(e),{token:t}}C.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function NC(){let t="__other__",e=async()=>ce(await ke({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=we(await dt({message:"project language",options:[...qr.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:xe};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:xe}],i={primary:n};for(let s of o){let a=new Set,c=[s.initial,n,"English",xe].filter(u=>a.has(u)?!1:(a.add(u),!0)).map(u=>({value:u,label:u===xe?"auto \u2014 mirror the language of the user's material":u}));c.push({value:t,label:"other\u2026"});let l=we(await dt({message:`language for ${s.label}`,options:c,initialValue:s.initial}));i[s.key]=l===t?await e():l}return i}async function hk(){for(;;){let t=ce(await ke({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let n=r.trim();if(!n)return"required";if(!n.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=ce(await Wo({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Ns("YouTrack",()=>Jt({baseUrl:t,token:e}))){let r=await yp({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}C.warn("re-enter the YouTrack URL / token.")}}var Zw,Ko=x(()=>{"use strict";Fe();F();ut();kw();yi();Ge();Ut();Ir();nn();Bo();$l();Ss();Vt();Er();Pw();je();jw();Lw();tl();Ai();fe();Ts();Nc();qw();Si();it();Zw=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});F();Fe();Ge();import{Command as FP}from"commander";Ge();fe();async function Vd(t){let e=t.profile??t.project;t.profile&&t.profile!==t.project&&(console.error(`--profile (${t.profile}) must equal --project (${t.project}). Profile id is the project id.`),process.exit(1));let r=wt(e);r&&!t.force&&(console.error(`already configured at ${Jr(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");Mt({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...q(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};ae(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${Jr(e)}`)}Za();Ge();import{homedir as xl}from"node:os";import{join as jo}from"node:path";Fe();F();import{existsSync as Jh,rmSync as SE}from"node:fs";import{join as Ar}from"node:path";import{simpleGit as EE}from"simple-git";import"ws";Fe();fe();import{createHash as T$}from"node:crypto";import{existsSync as I$,readFileSync as R$}from"node:fs";import{homedir as C$,hostname as Qa}from"node:os";import{join as P$}from"node:path";function Qd(t){return T$("sha256").update(t).digest("hex").slice(0,12)}function A$(){let t=V("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=P$(C$(),".claude","credentials.json");if(!I$(e))return;let r=JSON.parse(R$(e,"utf-8")),n=[r.email,r.account?.email,r.user?.email];for(let o of n)if(typeof o=="string"&&o.includes("@"))return o.trim().toLowerCase()}catch{}}function ep(t){let e=A$(),r=V("ACCOUNT_ID")?.trim(),n=V("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=Qr(t);return o?{accountId:`acct-${Qd(o)}`,label:n||Qa(),...e?{email:e}:{}}:{accountId:`acct-${Qd(`host:${Qa()}`)}`,label:n||Qa(),...e?{email:e}:{}}}Fe();nn();fe();fc();async function Up(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(V("ORIGIN")==="farm"||V("CLAUDE_AUTOLOGIN")!=="1"){s("autologin_disabled");return}let a;try{a=await pc(gi())}catch(c){s(`listener failed: ${c instanceof Error?c.message:String(c)}`);return}i({type:"agent_login_url",requestId:r.requestId,projectId:t.projectId,authUrl:a.authUrl}),n.info(`[agent-auth] authorize Claude in a browser on THIS machine: ${a.authUrl}`),n.info(`[agent-auth] waiting for the redirect on ${a.redirectUri} \u2026`);try{let c=await a.waitForToken(),l=await Dt(c.oauthToken);if(l==="invalid"){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"token rejected (401) \u2014 previous token kept"}),n.warn("[agent-auth] new Claude token rejected (401) \u2014 previous token kept");return}let u=q(t.projectId);if(!u){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"no secrets file for this project on the CLI"}),n.warn("[agent-auth] no secrets file for this project \u2014 token not saved");return}u.claude={oauthToken:c.oauthToken},ae(u),n.info(`[agent-auth] Claude token replaced (${c.oauthToken.slice(0,12)}\u2026, ${c.oauthToken.length} chars)`),i({type:"agent_login_result",projectId:t.projectId,ok:!0,...l==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}}),o()}catch(c){let l=c instanceof Error?c.message:String(c);i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:l}),n.warn(`[agent-auth] browser authorization failed: ${l}`)}finally{a.close()}}Fe();function Bp(t,e){let r=t.find(n=>n.kind==="claude");return r?.present===!0&&r.ok===!1?V("ORIGIN")==="farm"||V("CLAUDE_AUTOLOGIN")!=="1"||e?"none":"open":r?.ok===!0?"rearm":"none"}function Fp(t,e){return`${t.replace(/\/$/,"")}/?project=${encodeURIComponent(e)}`}yi();import{existsSync as nv}from"node:fs";import{join as ov}from"node:path";import{simpleGit as iv}from"simple-git";async function Gp(t,e){if(!nv(ov(t,".git")))return{status:"skipped"};let r=iv(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${sv(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 sv(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as hc,readFileSync as Yp,readdirSync as lv,watch as uv}from"node:fs";import{join as po}from"node:path";F();import{existsSync as Kp,readFileSync as Hp,readdirSync as av,statSync as cv}from"node:fs";import{join as mc}from"node:path";import{parse as Wp}from"yaml";function wi(t){let e=mc(t,"actions"),r=[],n=[];if(!Kp(e))return{defs:r,errors:n};let o;try{o=av(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=mc(e,s);try{if(!cv(a).isFile())continue;let c=$a(s,Wp(Hp(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 qp(t){let e={},r=mc(t,"project.yaml");if(!Kp(r))return e;let n;try{n=Wp(Hp(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))!Je.test(i)||Ot(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var ki=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,po(this.contextDir,"prompts"),po(this.contextDir,"actions")];for(let n of r)if(hc(n))try{let o=uv(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=wi(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=po(this.contextDir,e);if(!hc(r))return null;try{return Yp(r,"utf-8")}catch{return null}}readPrompts(){let e=po(this.contextDir,"prompts"),r={};if(!hc(e))return r;let n;try{n=lv(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=Yp(po(e,o),"utf-8")}catch{}}return r}};lt();import{existsSync as xc,readFileSync as ef,readdirSync as xv}from"node:fs";import{join as tf}from"node:path";import{simpleGit as Sv}from"simple-git";var Ev=/^(\d{4})-(.+)\.md$/,Tv="0000-template.md";function Iv(t){let e=t.split(`
934
- `),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 Rv(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
932
+ The token is shown ONCE \u2014 copy it right away.`);;){let n=ce(await ke({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:i=>!i||!i.trim()||i.includes("@")?void 0:"must be an email"})).trim();if(!n)return;let o=ce(await Yo({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){C.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await Os("Bitbucket",async()=>{let i=await Yt(n,o,t);if(t&&r){let s=await yi(n,o,t,r);if(s)throw new Error(s)}return i}))return{email:n,apiToken:o};C.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function MC(){for(;;){let t=ce(await Yo({message:`GitLab PAT \u2014 blank to skip
933
+ scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Os("GitLab",()=>zt(t))){let e=await ip(t);return e&&C.warn(e),{token:t}}C.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function DC(){let t="__other__",e=async()=>ce(await ke({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=we(await dt({message:"project language",options:[...Yr.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:$e};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:$e}],i={primary:n};for(let s of o){let a=new Set,c=[s.initial,n,"English",$e].filter(u=>a.has(u)?!1:(a.add(u),!0)).map(u=>({value:u,label:u===$e?"auto \u2014 mirror the language of the user's material":u}));c.push({value:t,label:"other\u2026"});let l=we(await dt({message:`language for ${s.label}`,options:c,initialValue:s.initial}));i[s.key]=l===t?await e():l}return i}async function yk(){for(;;){let t=ce(await ke({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let n=r.trim();if(!n)return"required";if(!n.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=ce(await Yo({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Os("YouTrack",()=>Jt({baseUrl:t,token:e}))){let r=await kp({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}C.warn("re-enter the YouTrack URL / token.")}}var ek,Wo=x(()=>{"use strict";Fe();F();ut();$w();ki();Ge();Ut();Ir();on();Go();vl();Es();Vt();Tr();_w();je();Ow();Dw();rl();ji();me();Rs();Oc();zw();Ti();it();ek=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});F();Fe();Ge();import{Command as WP}from"commander";Ge();me();async function Jd(t){let e=t.profile??t.project;t.profile&&t.profile!==t.project&&(console.error(`--profile (${t.profile}) must equal --project (${t.project}). Profile id is the project id.`),process.exit(1));let r=wt(e);r&&!t.force&&(console.error(`already configured at ${Zr(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");Mt({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...q(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};ae(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${Zr(e)}`)}Qa();Ge();import{homedir as Sl}from"node:os";import{join as Oo}from"node:path";Fe();F();import{existsSync as eg,rmSync as TE}from"node:fs";import{join as Ar}from"node:path";import{simpleGit as RE}from"simple-git";import"ws";Fe();me();import{createHash as I$}from"node:crypto";import{existsSync as C$,readFileSync as P$}from"node:fs";import{homedir as A$,hostname as ec}from"node:os";import{join as _$}from"node:path";function tp(t){return I$("sha256").update(t).digest("hex").slice(0,12)}function j$(){let t=X("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=_$(A$(),".claude","credentials.json");if(!C$(e))return;let r=JSON.parse(P$(e,"utf-8")),n=[r.email,r.account?.email,r.user?.email];for(let o of n)if(typeof o=="string"&&o.includes("@"))return o.trim().toLowerCase()}catch{}}function rp(t){let e=j$(),r=X("ACCOUNT_ID")?.trim(),n=X("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=en(t);return o?{accountId:`acct-${tp(o)}`,label:n||ec(),...e?{email:e}:{}}:{accountId:`acct-${tp(`host:${ec()}`)}`,label:n||ec(),...e?{email:e}:{}}}Fe();on();me();mc();async function Fp(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(X("ORIGIN")==="farm"||X("CLAUDE_AUTOLOGIN")!=="1"){s("autologin_disabled");return}let a;try{a=await fc(wi())}catch(c){s(`listener failed: ${c instanceof Error?c.message:String(c)}`);return}i({type:"agent_login_url",requestId:r.requestId,projectId:t.projectId,authUrl:a.authUrl}),n.info(`[agent-auth] authorize Claude in a browser on THIS machine: ${a.authUrl}`),n.info(`[agent-auth] waiting for the redirect on ${a.redirectUri} \u2026`);try{let c=await a.waitForToken(),l=await Dt(c.oauthToken);if(l==="invalid"){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"token rejected (401) \u2014 previous token kept"}),n.warn("[agent-auth] new Claude token rejected (401) \u2014 previous token kept");return}let u=q(t.projectId);if(!u){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"no secrets file for this project on the CLI"}),n.warn("[agent-auth] no secrets file for this project \u2014 token not saved");return}u.claude={oauthToken:c.oauthToken},ae(u),n.info(`[agent-auth] Claude token replaced (${c.oauthToken.slice(0,12)}\u2026, ${c.oauthToken.length} chars)`),i({type:"agent_login_result",projectId:t.projectId,ok:!0,...l==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}}),o()}catch(c){let l=c instanceof Error?c.message:String(c);i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:l}),n.warn(`[agent-auth] browser authorization failed: ${l}`)}finally{a.close()}}Fe();function Gp(t,e){let r=t.find(n=>n.kind==="claude");return r?.present===!0&&r.ok===!1?X("ORIGIN")==="farm"||X("CLAUDE_AUTOLOGIN")!=="1"||e?"none":"open":r?.ok===!0?"rearm":"none"}function Kp(t,e){return`${t.replace(/\/$/,"")}/?project=${encodeURIComponent(e)}`}ki();import{existsSync as iv}from"node:fs";import{join as sv}from"node:path";import{simpleGit as av}from"simple-git";async function Hp(t,e){if(!iv(sv(t,".git")))return{status:"skipped"};let r=av(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${cv(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 cv(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as gc,readFileSync as Vp,readdirSync as dv,watch as pv}from"node:fs";import{join as fo}from"node:path";F();import{existsSync as Wp,readFileSync as qp,readdirSync as lv,statSync as uv}from"node:fs";import{join as hc}from"node:path";import{parse as Yp}from"yaml";function bi(t){let e=hc(t,"actions"),r=[],n=[];if(!Wp(e))return{defs:r,errors:n};let o;try{o=lv(e).sort()}catch{return{defs:r,errors:n}}let i=new Set;for(let s of o){if(!/\.(yml|yaml)$/i.test(s))continue;let a=hc(e,s);try{if(!uv(a).isFile())continue;let c=va(s,Yp(qp(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 zp(t){let e={},r=hc(t,"project.yaml");if(!Wp(r))return e;let n;try{n=Yp(qp(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))!Je.test(i)||Ot(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var $i=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,fo(this.contextDir,"prompts"),fo(this.contextDir,"actions")];for(let n of r)if(gc(n))try{let o=pv(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=bi(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=fo(this.contextDir,e);if(!gc(r))return null;try{return Vp(r,"utf-8")}catch{return null}}readPrompts(){let e=fo(this.contextDir,"prompts"),r={};if(!gc(e))return r;let n;try{n=dv(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=Vp(fo(e,o),"utf-8")}catch{}}return r}};lt();import{existsSync as Sc,readFileSync as rf,readdirSync as Ev}from"node:fs";import{join as nf}from"node:path";import{simpleGit as Tv}from"simple-git";var Rv=/^(\d{4})-(.+)\.md$/,Iv="0000-template.md";function Cv(t){let e=t.split(`
934
+ `),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 Pv(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
935
935
  `),a=s.findIndex(h=>h.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),u=[],p="",d=null,m=a>=0?a+1:0;for(let h=m;h<s.length;h++){let w=(s[h]??"").trim();if(w===""){m=h+1;continue}let $=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(w);if(!$)break;let S=($[1]??"").trim().toLowerCase(),T=($[2]??"").trim(),v=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(w);v&&(d=parseInt(v[1]??"",10)),S==="tasks"&&(p=T),l.has(S)||u.push(w),m=h+1}let f=p?p.includes(n)?p:`${p}, ${n}`:n,g=s.slice(m).join(`
936
936
  `).replace(/^\n+/,""),k=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${f}`,...u,"",g].join(`
937
937
  `);return{content:k.endsWith(`
938
938
  `)?k:k+`
939
- `,supersedes:d}}function Cv(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
939
+ `,supersedes:d}}function Av(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
940
940
 
941
- - **Status:** superseded by ADR-${r}`):n}function Pv(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(`
941
+ - **Status:** superseded by ADR-${r}`):n}function _v(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(`
942
942
  `)+`
943
- `}async function rf(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await Sv(t).pull(void 0,void 0,["--rebase"])}catch{}let i=k=>o==="staging"?`adr/DRAFT-${k}.md`:`tasks/${e}/adr/DRAFT-${k}.md`,s=[],a=[];for(let k of r){let h=Se(t,i(k));if(!xc(h)){a.push(k);continue}s.push({slug:k,content:ef(h,"utf-8")})}let c=tf(t,"adr"),l=new Map;if(xc(c))for(let k of xv(c)){let h=Ev.exec(k);!h||k===Tv||l.set(k,{num:parseInt(h[1]??"",10),slug:h[2]??"",content:ef(tf(c,k),"utf-8")})}let u=Math.max(0,...[...l.values()].map(k=>k.num))+1,p=new Map,d=[],m=[];for(let k of s){if([...l.entries()].find(([,v])=>v.slug===k.slug&&v.content.includes(e))){m.push(k.slug);continue}let w=u++,$=`${String(w).padStart(4,"0")}-${k.slug}.md`,{content:S,supersedes:T}=Rv(k.content,w,k.slug,e,n);if(p.set($,S),l.set($,{num:w,slug:k.slug,content:S}),d.push(`adr/${$}`),T!==null){let v=[...l.keys()].find(b=>b.startsWith(`${String(T).padStart(4,"0")}-`));if(v&&v!==$){let b=Cv(p.get(v)??l.get(v).content,w);p.set(v,b),l.set(v,{...l.get(v),content:b})}}}let f=[];if(o==="staging")for(let k of s)xc(Se(t,`adr/DRAFT-${k.slug}.md`))&&f.push({path:`adr/DRAFT-${k.slug}.md`,content:"",deleted:!0});if(d.length===0&&f.length===0)return{promoted:d,skipped:m,missing:a};if(d.length>0){let k=[...l.entries()].map(([h,w])=>({num:w.num,file:h,header:Iv(w.content)}));p.set("INDEX.md",Pv(k))}for(let[k,h]of p.entries())f.push({path:`adr/${k}`,content:h});let g=d.length>0?`adr(${e}): promote ${s.map(k=>k.slug).join(", ")}`:`adr(${e}): drop stale staged ${m.join(", ")}`;return await Re(t,f,g),{promoted:d,skipped:m,missing:a}}lt();Si();Ut();F();import{existsSync as sf,readFileSync as Uv}from"node:fs";import{join as af}from"node:path";function Bv(t){for(let e of[gt,Gr]){let r=af(t,e);if(sf(r))try{return Ys(Uv(r,"utf-8"))}catch{return 0}}return 0}function Fv(t,e,r,n=6){let o=e<n,i=o?zs(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function Ei(t,e){return Fv(e,Bv(t),r=>sf(af(t,r)))}F();Vt();import{existsSync as wf,mkdirSync as hx,mkdtempSync as gx,rmSync as kf,writeFileSync as bf}from"node:fs";import{tmpdir as yx}from"node:os";import{dirname as wx,join as Ii}from"node:path";import{simpleGit as Ic}from"simple-git";Ir();function kx(t){return`codepipe/context-migration-v${t}`}function bx(t){let e=Vs(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 \`${gt}\` stamp (renamed from \`${Gr}\``,"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(`
944
- `)}async function $f(t,e,r,n){let o=Ic(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Ei(t,e);if(!i.outdated)return i;let s=kx(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 $x(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=Sr(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:bx(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 $x(t,e,r,n,o,i,s){let a=Ic(t),c=gx(Ii(yx(),"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(g=>[g.path,g.content])),d=0;for(let g of n.missingPaths){if(g===gt)continue;let k=p.get(g);if(k==null){s.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let h=Ii(c,g);wf(h)||(hx(wx(h),{recursive:!0}),bf(h,k),d++)}bf(Ii(c,gt),Vn(n.currentVersion)),d++;let m=Ii(c,Gr);wf(m)&&(kf(m,{force:!0}),d++);let f=Ic(c);await f.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await f.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await f.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${d} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),kf(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{existsSync as vx,readFileSync as xx,writeFileSync as Sx}from"node:fs";import{homedir as Ex}from"node:os";import{join as vf}from"node:path";import{parseDocument as Tx}from"yaml";function Ix(t){let e={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(e.default_branch=t.defaultBranch),e}function Rx(t,e){let r=Tx(t);return r.set("repos",e.map(Ix)),r.toString()}function Cx(t,e){let r=[vf(Ex(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(vf(e,"project.yaml")),r}function wo(t,e,r){let n=[],o=[];for(let i of Cx(t,r))if(vx(i))try{let s=xx(i,"utf-8"),a=Rx(s,e);a!==s&&(Sx(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}ko();ut();fe();function Bx(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 Lf(t,e,r,n){let o=Bx(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=ci(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=Bt(a.publicKey,i)}catch(u){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}ut();fe();Vt();Er();nn();Ai();function Bf(t){let e=q(t);if(!e)return null;if(!e.sealKey){let r=Pi();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},ae(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:Ke(e.sealKey.publicKey)}}async function Ff(t,e,r,n){let o;try{o=JSON.parse(pn(n,r).toString("utf-8"))}catch(s){return{ok:!1,detail:`cannot open the sealed credential (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}let i=q(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 qt(o.token);return i.github={token:o.token},fn(i,()=>{process.env.GH_TOKEN=o.token,Mf(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await zt(o.token);return i.gitlab={token:o.token},fn(i,()=>{process.env.GITLAB_TOKEN=o.token,Df(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 Yt(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},fn(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,Uf(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 Jt({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},fn(i,()=>{process.env.YOUTRACK_URL=s,process.env.YOUTRACK_TOKEN=o.token}),{ok:!0,detail:`authenticated as ${a}`}}case"claude":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Dt(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},fn(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},fn(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 fn(t,e){ae(t),e()}F();F();import{spawn as Fx}from"node:child_process";var Gx=124,Gf=16*1024,Kf=4e3;function Kx(t,e,r,n,o,i){let s={...t},a=(c,l)=>{Ot(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 Hf(t){let{def:e,onEvent:r}=t,n=Kx(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
945
- `,o.length>Gf&&(o=o.slice(o.length-Gf))},s=(a,c)=>{let l=c.length>Kf?c.slice(0,Kf)+"\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 Hx(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 Hx(t,e,r,n,o){return new Promise(i=>{let s=Fx("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??ba)*1e3,l=setTimeout(()=>{a=!0,o("stderr",`step timed out after ${c/1e3}s \u2014 killing`),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},c);l.unref?.();let u=m=>{let f="";return{data:g=>{f+=g.toString("utf-8");let k;for(;(k=f.indexOf(`
946
- `))!==-1;)o(m,f.slice(0,k).replace(/\r$/,"")),f=f.slice(k+1)},flush:()=>{f.length>0&&o(m,f.replace(/\r$/,"")),f=""}}},p=u("stdout"),d=u("stderr");s.stdout?.on("data",p.data),s.stderr?.on("data",d.data),s.on("error",m=>{clearTimeout(l),o("stderr",`spawn failed: ${m.message}`),i(127)}),s.on("close",(m,f)=>{clearTimeout(l),p.flush(),d.flush(),i(a?Gx:m??(f?1:0))})})}lt();lt();import{existsSync as Wx,readFileSync as qx,statSync as Wf}from"node:fs";var qf=2*1024*1024;function Yx(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function Yf(t,e){let r=Se(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!Wx(r)||!Wf(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=Wf(r);if(n>qf)throw new Error(`file too large: ${e} is ${n} bytes (limit ${qf})`);let o=qx(r);return Yx(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}fe();F();import{existsSync as zx,readFileSync as Vx,writeFileSync as Xx}from"node:fs";import{join as Jx}from"node:path";import{parseDocument as Zx}from"yaml";async function zf(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=Ca(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=Jx(t,o);if(!zx(s))throw new Error(`${o} not found in context repo (${t})`);let a=Zx(Vx(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);Xx(s,a.toString()),n.push(o)}return{files:n}}Nc();import{existsSync as Oc,readFileSync as Lc,writeFileSync as Qx}from"node:fs";import{join as ji}from"node:path";import{parseDocument as Mc}from"yaml";async function rm(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=ji(t,"project.yaml");if(!Oc(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=Mc(Lc(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=ji(t,"regimen.yaml");if(!Oc(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=Mc(Lc(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)Qx(ji(t,i.path),i.content);return{files:r.map(i=>i.path)}}function Ni(t){if(!t)return"Stage";try{let e=ji(t,"project.yaml");if(!Oc(e))return"Stage";let n=Mc(Lc(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}Vt();Ri();ko();F();lt();import{existsSync as vS,readFileSync as xS}from"node:fs";import{join as Ym}from"node:path";import{simpleGit as Jc}from"simple-git";F();import{existsSync as nm,readFileSync as om,readdirSync as eS}from"node:fs";import{join as Dc}from"node:path";import{simpleGit as tS}from"simple-git";function rS(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(`
947
- `)){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 nS(t,e){let r=Dc(t,`tasks/${e}/annotations`);if(!nm(r))return[];let n=[];for(let o of eS(r).sort())if(o.endsWith(".md")){try{let i=rS(o,om(Dc(r,o),"utf-8"));i&&n.push(i)}catch{}if(n.length>=oa)break}return n}var oS=12;async function im(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=tS(o),p=[];for(let d of nS(e,r)){if(d.repo!==n)continue;let m=ye("code",n,d.path);if(!a.has(m))continue;let f=l.get(m);if(!f)continue;let g=(await u.raw(["rev-parse",`${i}:${d.path}`]).catch(()=>"")).trim().slice(0,oS),k=Zs(f),h=Dc(e,k),w=p.find(I=>I.path===k),$=w?.content??(nm(h)?om(h,"utf-8"):null),S=`<!-- ${r}${g?`:${g}`:""} -->`;if($?.includes(S))continue;let T=$??`---
943
+ `}async function of(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await Tv(t).pull(void 0,void 0,["--rebase"])}catch{}let i=k=>o==="staging"?`adr/DRAFT-${k}.md`:`tasks/${e}/adr/DRAFT-${k}.md`,s=[],a=[];for(let k of r){let h=Se(t,i(k));if(!Sc(h)){a.push(k);continue}s.push({slug:k,content:rf(h,"utf-8")})}let c=nf(t,"adr"),l=new Map;if(Sc(c))for(let k of Ev(c)){let h=Rv.exec(k);!h||k===Iv||l.set(k,{num:parseInt(h[1]??"",10),slug:h[2]??"",content:rf(nf(c,k),"utf-8")})}let u=Math.max(0,...[...l.values()].map(k=>k.num))+1,p=new Map,d=[],m=[];for(let k of s){if([...l.entries()].find(([,v])=>v.slug===k.slug&&v.content.includes(e))){m.push(k.slug);continue}let w=u++,$=`${String(w).padStart(4,"0")}-${k.slug}.md`,{content:S,supersedes:T}=Pv(k.content,w,k.slug,e,n);if(p.set($,S),l.set($,{num:w,slug:k.slug,content:S}),d.push(`adr/${$}`),T!==null){let v=[...l.keys()].find(b=>b.startsWith(`${String(T).padStart(4,"0")}-`));if(v&&v!==$){let b=Av(p.get(v)??l.get(v).content,w);p.set(v,b),l.set(v,{...l.get(v),content:b})}}}let f=[];if(o==="staging")for(let k of s)Sc(Se(t,`adr/DRAFT-${k.slug}.md`))&&f.push({path:`adr/DRAFT-${k.slug}.md`,content:"",deleted:!0});if(d.length===0&&f.length===0)return{promoted:d,skipped:m,missing:a};if(d.length>0){let k=[...l.entries()].map(([h,w])=>({num:w.num,file:h,header:Cv(w.content)}));p.set("INDEX.md",_v(k))}for(let[k,h]of p.entries())f.push({path:`adr/${k}`,content:h});let g=d.length>0?`adr(${e}): promote ${s.map(k=>k.slug).join(", ")}`:`adr(${e}): drop stale staged ${m.join(", ")}`;return await Ie(t,f,g),{promoted:d,skipped:m,missing:a}}lt();Ti();Ut();F();import{existsSync as cf,readFileSync as Fv}from"node:fs";import{join as lf}from"node:path";function Gv(t){for(let e of[gt,Kr]){let r=lf(t,e);if(cf(r))try{return zs(Fv(r,"utf-8"))}catch{return 0}}return 0}function Kv(t,e,r,n=6){let o=e<n,i=o?Vs(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function Ri(t,e){return Kv(e,Gv(t),r=>cf(lf(t,r)))}F();Vt();import{existsSync as bf,mkdirSync as yx,mkdtempSync as wx,rmSync as $f,writeFileSync as vf}from"node:fs";import{tmpdir as kx}from"node:os";import{dirname as bx,join as Ci}from"node:path";import{simpleGit as Ic}from"simple-git";Ir();function $x(t){return`codepipe/context-migration-v${t}`}function vx(t){let e=Xs(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 \`${gt}\` stamp (renamed from \`${Kr}\``,"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(`
944
+ `)}async function xf(t,e,r,n){let o=Ic(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Ri(t,e);if(!i.outdated)return i;let s=$x(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 xx(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=Er(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:vx(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 xx(t,e,r,n,o,i,s){let a=Ic(t),c=wx(Ci(kx(),"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(dn(l,u).map(g=>[g.path,g.content])),d=0;for(let g of n.missingPaths){if(g===gt)continue;let k=p.get(g);if(k==null){s.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let h=Ci(c,g);bf(h)||(yx(bx(h),{recursive:!0}),vf(h,k),d++)}vf(Ci(c,gt),Xn(n.currentVersion)),d++;let m=Ci(c,Kr);bf(m)&&($f(m,{force:!0}),d++);let f=Ic(c);await f.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await f.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await f.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${d} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),$f(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{existsSync as Sx,readFileSync as Ex,writeFileSync as Tx}from"node:fs";import{homedir as Rx}from"node:os";import{join as Sf}from"node:path";import{parseDocument as Ix}from"yaml";function Cx(t){let e={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(e.default_branch=t.defaultBranch),e}function Px(t,e){let r=Ix(t);return r.set("repos",e.map(Cx)),r.toString()}function Ax(t,e){let r=[Sf(Rx(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(Sf(e,"project.yaml")),r}function ko(t,e,r){let n=[],o=[];for(let i of Ax(t,r))if(Sx(i))try{let s=Ex(i,"utf-8"),a=Px(s,e);a!==s&&(Tx(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}bo();ut();me();function Gx(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 Df(t,e,r,n){let o=Gx(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=ui(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=Bt(a.publicKey,i)}catch(u){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}ut();me();Vt();Tr();on();ji();function Gf(t){let e=q(t);if(!e)return null;if(!e.sealKey){let r=_i();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},ae(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:Ke(e.sealKey.publicKey)}}async function Kf(t,e,r,n){let o;try{o=JSON.parse(fn(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=q(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 qt(o.token);return i.github={token:o.token},mn(i,()=>{process.env.GH_TOKEN=o.token,Uf(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await zt(o.token);return i.gitlab={token:o.token},mn(i,()=>{process.env.GITLAB_TOKEN=o.token,Bf(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 Yt(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},mn(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,Ff(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 Jt({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},mn(i,()=>{process.env.YOUTRACK_URL=s,process.env.YOUTRACK_TOKEN=o.token}),{ok:!0,detail:`authenticated as ${a}`}}case"claude":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Dt(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},mn(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},mn(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 mn(t,e){ae(t),e()}F();F();import{spawn as Kx}from"node:child_process";var Hx=124,Hf=16*1024,Wf=4e3;function Wx(t,e,r,n,o,i){let s={...t},a=(c,l)=>{Ot(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 qf(t){let{def:e,onEvent:r}=t,n=Wx(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
945
+ `,o.length>Hf&&(o=o.slice(o.length-Hf))},s=(a,c)=>{let l=c.length>Wf?c.slice(0,Wf)+"\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 qx(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 qx(t,e,r,n,o){return new Promise(i=>{let s=Kx("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??$a)*1e3,l=setTimeout(()=>{a=!0,o("stderr",`step timed out after ${c/1e3}s \u2014 killing`),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},c);l.unref?.();let u=m=>{let f="";return{data:g=>{f+=g.toString("utf-8");let k;for(;(k=f.indexOf(`
946
+ `))!==-1;)o(m,f.slice(0,k).replace(/\r$/,"")),f=f.slice(k+1)},flush:()=>{f.length>0&&o(m,f.replace(/\r$/,"")),f=""}}},p=u("stdout"),d=u("stderr");s.stdout?.on("data",p.data),s.stderr?.on("data",d.data),s.on("error",m=>{clearTimeout(l),o("stderr",`spawn failed: ${m.message}`),i(127)}),s.on("close",(m,f)=>{clearTimeout(l),p.flush(),d.flush(),i(a?Hx:m??(f?1:0))})})}lt();lt();import{existsSync as Yx,readFileSync as zx,statSync as Yf}from"node:fs";var zf=2*1024*1024;function Vx(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function Vf(t,e){let r=Se(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!Yx(r)||!Yf(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=Yf(r);if(n>zf)throw new Error(`file too large: ${e} is ${n} bytes (limit ${zf})`);let o=zx(r);return Vx(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}me();F();import{existsSync as Xx,readFileSync as Jx,writeFileSync as Zx}from"node:fs";import{join as Qx}from"node:path";import{parseDocument as eS}from"yaml";async function Xf(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=Pa(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=Qx(t,o);if(!Xx(s))throw new Error(`${o} not found in context repo (${t})`);let a=eS(Jx(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);Zx(s,a.toString()),n.push(o)}return{files:n}}Oc();import{existsSync as Lc,readFileSync as Mc,writeFileSync as tS}from"node:fs";import{join as Oi}from"node:path";import{parseDocument as Dc}from"yaml";async function om(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=Oi(t,"project.yaml");if(!Lc(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=Dc(Mc(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=Oi(t,"regimen.yaml");if(!Lc(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=Dc(Mc(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)tS(Oi(t,i.path),i.content);return{files:r.map(i=>i.path)}}function Li(t){if(!t)return"Stage";try{let e=Oi(t,"project.yaml");if(!Lc(e))return"Stage";let n=Dc(Mc(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}Vt();Pi();bo();F();lt();import{existsSync as SS,readFileSync as ES}from"node:fs";import{join as Vm}from"node:path";import{simpleGit as Zc}from"simple-git";F();import{existsSync as im,readFileSync as sm,readdirSync as rS}from"node:fs";import{join as Uc}from"node:path";import{simpleGit as nS}from"simple-git";function oS(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(`
947
+ `)){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 iS(t,e){let r=Uc(t,`tasks/${e}/annotations`);if(!im(r))return[];let n=[];for(let o of rS(r).sort())if(o.endsWith(".md")){try{let i=oS(o,sm(Uc(r,o),"utf-8"));i&&n.push(i)}catch{}if(n.length>=ia)break}return n}var sS=12;async function am(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=nS(o),p=[];for(let d of iS(e,r)){if(d.repo!==n)continue;let m=ye("code",n,d.path);if(!a.has(m))continue;let f=l.get(m);if(!f)continue;let g=(await u.raw(["rev-parse",`${i}:${d.path}`]).catch(()=>"")).trim().slice(0,sS),k=Qs(f),h=Uc(e,k),w=p.find(R=>R.path===k),$=w?.content??(im(h)?sm(h,"utf-8"):null),S=`<!-- ${r}${g?`:${g}`:""} -->`;if($?.includes(S))continue;let T=$??`---
948
948
  entityId: ${f}
949
949
  ---
950
950
 
@@ -952,31 +952,34 @@ entityId: ${f}
952
952
 
953
953
  Append-only. Keyed by entityId \u2014 never by path; entries survive renames.
954
954
  `,v=["",`## ${s} \u2014 ${r}`,S,"",d.body,""].join(`
955
- `),b=T+v;w?w.content=b:p.push({path:k,content:b})}return p}Hc();Yc();Mi();Vc();So();async function SS(t,e){let n=await Jc(t).raw(["diff","--numstat",`${e}^`,e]).catch(()=>""),o=[];for(let i of n.split(`
956
- `)){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 ES(t,e){let n=[`tasks/${e}/PLAN.md`,`tasks/${e}/SOLUTION.md`].find(i=>vS(Ym(t,i)));if(!n)return{};let o=Ym(t,n);try{let i=xS(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 zm(t){let{contextDir:e,repoDir:r,repoName:n,taskKey:o,commitSha:i}=t,s=hn(e),a=Cr([...s.ignore,...mn]),c=await SS(r,i),l=(await Jc(r).raw(["show","-s","--format=%cs",i])).trim(),u=null,p=new Map;try{u=Wc(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 v=ye("code",n,T.path),b=p.get(v);d.push({key:v,...b?{entityId:b}:{},churn:T.churn})}if(d.length===0)return{recorded:!1};let m=ES(e,o),f=Oi(e,o),g=f?.origin==="pipeline"?f.files.filter(T=>re(T.key)?.repo!==n):[],k=f?.origin==="pipeline"?f.commits:[],h={modelFormatVersion:2,taskKey:o,origin:"pipeline",...f?.title?{title:f.title}:{},...l?{date:l}:{},commits:[...new Set([...k,i])],files:[...g,...d],links:{...f?.origin==="pipeline"?f.links:{},...m}};h.links&&Object.keys(h.links).length===0&&delete h.links;let w=[...Ui(e).filter(T=>T.taskKey!==o),h],$=Fm(Gm(e),w,o,s.cochange.halfLifeDays),S=await im({contextDir:e,taskKey:o,repoName:n,repoDir:r,commitSha:i,date:l,touchedKeys:new Set(d.map(T=>T.key)),identity:u}).catch(()=>[]);await Re(e,[{path:hr(o),content:Hr(h)},{path:mr,content:Bi($)},...S],`model: task event ${o}`);{let{rebuildSearchIndex:T}=await Promise.resolve().then(()=>(To(),Eo));await T(e).catch(()=>{})}return{recorded:!0}}async function Vm(t){let e=new Set([t.fallbackTaskKey]);try{let r=Jc(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(`
957
- `)){let s=i.trim();s&&e.add(s)}}catch{}for(let r of[...e].sort())await TS(t.contextDir,r,t.prUrl)}async function TS(t,e,r){let n=Oi(t,e);if(!n||n.origin!=="pipeline"||n.links?.pr===r)return;let o={...n,links:{...n.links??{},pr:r}};await Re(t,[{path:hr(e),content:Hr(o)}],`model: pr link for ${e}`)}Er();import{existsSync as Zm,readFileSync as Qm}from"node:fs";import{join as eh}from"node:path";import{parseDocument as th}from"yaml";Er();var Io=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return Rp(this.cfg,e)}getIssue(e,r){return Cp(this.cfg,e,r??Ni(this.contextDir))}listComments(e,r){return Pp(this.cfg,e,r)}downloadAttachment(e){return Ip(this.cfg,e)}updateStatus(e,r){return wp(this.cfg,e,r,Ni(this.contextDir))}addComment(e,r,n){return kp(this.cfg,e,r)}createIssue(e){return vp(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,Ni(this.contextDir))}editIssue(e,r){return bp(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return xp(this.cfg,e,r,n)}fetchStateFields(e){return _p(this.cfg,e)}};F();lt();import{existsSync as jS,readFileSync as NS}from"node:fs";import{randomBytes as OS}from"node:crypto";import{existsSync as Zc,readFileSync as IS,readdirSync as RS}from"node:fs";F();lt();function Wi(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=_S(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:CS(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:AS(PS(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 Xm(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),Zc(Se(t,`tasks/${c}/task.md`))))continue;let l=null;try{l=await r(c)}catch{continue}l&&(a.push({issue:l,comments:[],attachments:[]}),i.push(...s(l)))}return a}async function qi(t,e,r){if(r.length===0)return;let n=Wi(t,e,r),o=r.map(i=>i.issue.key);await Re(t,n,`sync(${o.join(", ")}): task data`)}function CS(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(`
958
- `)}function PS(t,e,r){let n=new Map,o=Se(t,`tasks/${e}/comments.jsonl`);if(Zc(o))for(let i of IS(o,"utf-8").split(`
959
- `)){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=br(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function AS(t){return t.map(e=>JSON.stringify(e)).join(`
955
+ `),b=T+v;w?w.content=b:p.push({path:k,content:b})}return p}Wc();zc();Ui();Xc();Eo();async function TS(t,e){let n=await Zc(t).raw(["diff","--numstat",`${e}^`,e]).catch(()=>""),o=[];for(let i of n.split(`
956
+ `)){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 RS(t,e){let n=[`tasks/${e}/PLAN.md`,`tasks/${e}/SOLUTION.md`].find(i=>SS(Vm(t,i)));if(!n)return{};let o=Vm(t,n);try{let i=ES(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 Xm(t){let{contextDir:e,repoDir:r,repoName:n,taskKey:o,commitSha:i}=t,s=gn(e),a=Cr([...s.ignore,...hn]),c=await TS(r,i),l=(await Zc(r).raw(["show","-s","--format=%cs",i])).trim(),u=null,p=new Map;try{u=qc(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 v=ye("code",n,T.path),b=p.get(v);d.push({key:v,...b?{entityId:b}:{},churn:T.churn})}if(d.length===0)return{recorded:!1};let m=RS(e,o),f=Mi(e,o),g=f?.origin==="pipeline"?f.files.filter(T=>re(T.key)?.repo!==n):[],k=f?.origin==="pipeline"?f.commits:[],h={modelFormatVersion:2,taskKey:o,origin:"pipeline",...f?.title?{title:f.title}:{},...l?{date:l}:{},commits:[...new Set([...k,i])],files:[...g,...d],links:{...f?.origin==="pipeline"?f.links:{},...m}};h.links&&Object.keys(h.links).length===0&&delete h.links;let w=[...Fi(e).filter(T=>T.taskKey!==o),h],$=Km(Hm(e),w,o,s.cochange.halfLifeDays),S=await am({contextDir:e,taskKey:o,repoName:n,repoDir:r,commitSha:i,date:l,touchedKeys:new Set(d.map(T=>T.key)),identity:u}).catch(()=>[]);await Ie(e,[{path:gr(o),content:Wr(h)},{path:hr,content:Gi($)},...S],`model: task event ${o}`);{let{rebuildSearchIndex:T}=await Promise.resolve().then(()=>(Ro(),To));await T(e).catch(()=>{})}return{recorded:!0}}async function Jm(t){let e=new Set([t.fallbackTaskKey]);try{let r=Zc(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(`
957
+ `)){let s=i.trim();s&&e.add(s)}}catch{}for(let r of[...e].sort())await IS(t.contextDir,r,t.prUrl)}async function IS(t,e,r){let n=Mi(t,e);if(!n||n.origin!=="pipeline"||n.links?.pr===r)return;let o={...n,links:{...n.links??{},pr:r}};await Ie(t,[{path:gr(e),content:Wr(o)}],`model: pr link for ${e}`)}Tr();import{existsSync as eh,readFileSync as th}from"node:fs";import{join as rh}from"node:path";import{parseDocument as nh}from"yaml";Tr();var Io=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return Pp(this.cfg,e)}getIssue(e,r){return Ap(this.cfg,e,r??Li(this.contextDir))}listComments(e,r){return _p(this.cfg,e,r)}downloadAttachment(e){return Cp(this.cfg,e)}updateStatus(e,r){return bp(this.cfg,e,r,Li(this.contextDir))}addComment(e,r,n){return $p(this.cfg,e,r)}createIssue(e){return Sp(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,Li(this.contextDir))}editIssue(e,r){return vp(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return Ep(this.cfg,e,r,n)}fetchStateFields(e){return Np(this.cfg,e)}};F();lt();import{existsSync as OS,readFileSync as LS}from"node:fs";import{randomBytes as MS}from"node:crypto";import{existsSync as Qc,readFileSync as CS,readdirSync as PS}from"node:fs";F();lt();function Yi(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=NS(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:AS(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:jS(_S(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 Zm(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),Qc(Se(t,`tasks/${c}/task.md`))))continue;let l=null;try{l=await r(c)}catch{continue}l&&(a.push({issue:l,comments:[],attachments:[]}),i.push(...s(l)))}return a}async function zi(t,e,r){if(r.length===0)return;let n=Yi(t,e,r),o=r.map(i=>i.issue.key);await Ie(t,n,`sync(${o.join(", ")}): task data`)}function AS(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(`
958
+ `)}function _S(t,e,r){let n=new Map,o=Se(t,`tasks/${e}/comments.jsonl`);if(Qc(o))for(let i of CS(o,"utf-8").split(`
959
+ `)){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=$r(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function jS(t){return t.map(e=>JSON.stringify(e)).join(`
960
960
  `)+(t.length>0?`
961
- `:"")}function _S(t,e,r){let n=[],o=Se(t,`tasks/${e}/attachments`);if(Zc(o))for(let i of RS(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}Ti();var Ro=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await ho(this.contextDir);let r=e.columns??[];return mf(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>yo(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=go(this.contextDir,e);return r?yo(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return Jm(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 ho(this.contextDir),!go(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${OS(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=br(r);s&&(i.parsedCommand=s);let c=[...Jm(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
961
+ `:"")}function NS(t,e,r){let n=[],o=Se(t,`tasks/${e}/attachments`);if(Qc(o))for(let i of PS(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}Ii();var Co=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await go(this.contextDir);let r=e.columns??[];return gf(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>wo(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=yo(this.contextDir,e);return r?wo(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return Qm(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 go(this.contextDir),!yo(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${MS(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=$r(r);s&&(i.parsedCommand=s);let c=[...Qm(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
962
962
  `)+`
963
- `;return await Re(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 hf(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:ii.statusColumns}]}async mutateRecord(e,r,n){let o=go(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=yo(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:zr(e),content:Tc(i)},...Wi(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await Re(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:io,status:r.targetStatus,links:[],created:n,updated:n},i=yo(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:zr(e),content:Tc(o)},...Wi(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}};function Jm(t,e){let r=Se(t,`tasks/${e}/comments.jsonl`);if(!jS(r))return[];let n=[];for(let o of NS(r,"utf-8").split(`
964
- `)){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}Ti();function Qc(t){if(!t)return"youtrack";try{let e=eh(t,"project.yaml");return Zm(e)&&th(Qm(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function It(t){let e=Qc(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=pf(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=LS(n);return i?{ok:!0,kind:e,provider:new Ro(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=gp();return r?{ok:!0,kind:e,provider:new Io(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function LS(t){try{let e=eh(t,"project.yaml");if(!Zm(e))return null;let r=th(Qm(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var Yi=new Map;async function Co(t,e){let n=(Yi.get(t)??Promise.resolve()).catch(()=>{}).then(e);Yi.set(t,n);try{return await n}finally{Yi.get(t)===n&&Yi.delete(t)}}function zi(t,e){return lo(t.split(":",2)[0]??"",e)}async function rh(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;Rr(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return X("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Co(`${i}/${r.name}`,async()=>{let s=await rr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir),{commit:c,pushed:l,baseMoved:u}=await Tf(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 zm({contextDir:t.contextDir,repoDir:a,repoName:r.name,taskKey:p,commitSha:c}).catch(d=>{Rr(`[model] task event for ${p} failed: ${d instanceof Error?d.message:String(d)}`)})}return me({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 X("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Co(`${i}/${r.name}`,async()=>{let s=await rr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir);return await If(s,a,{branchName:e.branchName,force:e.force}),me({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"create_pr":{if(!r)return X("no repo spec");let{spec:i,host:s}=zi(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 Vm({contextDir:t.contextDir,repoDir:_e(l,r.name,t.baseDir),branchName:e.branchName,baseBranch:e.baseBranch,fallbackTaskKey:c,prUrl:a.url}).catch(u=>{Rr(`[model] pr link for ${c} failed: ${u instanceof Error?u.message:String(u)}`)})}return me({url:a.url,number:a.number,host:s.name})}case"merge_pr":{if(!r)return X("no repo spec");let{spec:i,host:s}=zi(e.taskId,r),a=await s.mergePR(i,e.prNumber,e.mergeMethod,e.deleteBranch);return me({prNumber:e.prNumber,host:s.name,...a.mergedSha?{mergedSha:a.mergedSha}:{}})}case"close_pr":{if(!r)return X("no repo spec");let{spec:i,host:s}=zi(e.taskId,r);return await s.closePR(i,e.prNumber,e.comment),me({prNumber:e.prNumber,host:s.name})}case"rewrite_cluster_branch":{if(!r)return X("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Co(`${i}/${r.name}`,async()=>{let s=await rr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir),{commit:c,dropped:l}=await Rf(s,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:r.defaultBranch});return me({branch:e.branchName,commit:c,dropped:l,pushed:l>0})})}case"merge_branch":{if(!r)return X("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Co(`${i}/${r.name}`,async()=>{let s=await rr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir),{mergedSha:c}=await Cf(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return me({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return X("no repo spec");let i=t.cloneUrlOverride??Ci(r),a=(await Pf(i)).filter(u=>Af(u,e.issueKey)),c=Sr(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 me({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return X("no repo spec");let{spec:i,host:s}=e.upstream?(()=>{let{mirror:a,...c}=r;return{spec:c,host:Sr(c)}})():zi(e.taskId,r);return await s.addPRComment(i,e.prNumber,e.body),me({prNumber:e.prNumber,host:s.name})}case"tracker_status":{let i=It({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),me({issueId:t.trackerIssueId,newStatus:e.newStatus})):X("no tracker_issue_id provided"):X(i.error)}case"tracker_comment":{let i=It({contextDir:t.contextDir});if(!i.ok)return X(i.error);if(!t.trackerIssueId)return X("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return me({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=It({contextDir:t.contextDir});if(!i.ok)return X(i.error);if(!e.projectKey)return X("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 me({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=It({contextDir:t.contextDir});if(!i.ok)return X(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 X(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return me({applied:s})}case"set_project_setting":{if(!t.contextDir)return X("no context repo clone on this CLI");let i=await zf(t.contextDir,e.edits);return me({files:i.files})}case"set_prompt_override":{if(!t.contextDir)return X("no context repo clone on this CLI");if(!Na(e.role))return X(`unknown prompt operation: ${e.role}`);let i=Oa(e.role);return await Re(t.contextDir,[e.content===null?{path:i,content:"",deleted:!0}:{path:i,content:e.content}],e.commitMessage),t.requestConfigReport?.(),me({path:i,reset:e.content===null})}case"tracker_edit":{let i=It({contextDir:t.contextDir});if(!i.ok)return X(i.error);if(!t.contextDir)return X("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 qi(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),me({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return X("no context repo clone on this CLI");let i=await rm(t.contextDir,e);return me({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return X("no context repo clone on this CLI");let i=await em(t.contextDir,e);return me({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),me({reported:!0})):X("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return X("no context repo clone on this CLI");let i=await t.refreshContextStatus();return me({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return X("no project workspace on this CLI");if(!r)return X("no repo spec");if(!t.onRunActivity)return X("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=wi(t.contextDir),c=s.find(m=>m.id===e.actionId);if(!c){let m=a.find(f=>f.file===`actions/${e.actionId}.yml`);return X(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=va(c,e.input);if(!l.ok)return X(l.error);let u=qp(t.contextDir),p=q(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),Co(`${e.projectId}/${r.name}`,async()=>{await rr(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=_e(e.projectId,r.name,t.baseDir),f=await Hf({cwd:m,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:g=>i(e.runId,g)});return me({runId:e.runId,status:f.status,exitCode:f.exitCode,...f.failedStep?{failedStep:f.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return X("no context repo clone on this CLI");let i=Yf(t.contextDir,e.path);return me({path:e.path,...i})}case"search_model":{if(!t.contextDir)return X("no context repo clone on this CLI");let{searchModelIndex:i}=await Promise.resolve().then(()=>(To(),Eo)),s=await i(t.contextDir,e.q,e.limit);return me({hits:s})}case"model_drift":return X("model_drift requires a local workspace (handled by the daemon)");case"model_bootstrap":return X("model_bootstrap requires a local workspace (handled by the daemon)");default:return X(`unsupported action type: ${e.type}`)}}catch(i){return X(i instanceof Error?i.message:String(i))}}function me(t){return{status:"done",result:t}}function X(t){return{status:"failed",error:t}}ut();tl();je();fe();import{existsSync as yh,readFileSync as wh}from"node:fs";import{join as kh}from"node:path";async function bh(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=Ke(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Xi(e.farmId,e.farmPublicKey);let s=q(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=kh(r,"project.yaml"),m=kh(r,"regimen.yaml");yh(d)&&yh(m)?c={projectYaml:wh(d,"utf-8"),regimenYaml:wh(m,"utf-8")}:n.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},u=Bt(e.farmPublicKey,JSON.stringify(l));Vi(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let p=await Zi(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))}}F();ut();Fe();ut();import{homedir as zS}from"node:os";import{existsSync as VS,mkdirSync as XS,readFileSync as JS,writeFileSync as ZS}from"node:fs";import{dirname as QS,join as eE}from"node:path";function ol(){return V("RUNNER_PINS")??eE(zS(),".codepipe","runner-pins.json")}function $h(){let t=ol();if(!VS(t))return{};try{return JSON.parse(JS(t,"utf-8"))}catch{return{}}}function tE(t){let e=ol();XS(QS(e),{recursive:!0}),ZS(e,JSON.stringify(t,null,2)+`
965
- `,{mode:384})}function rE(t){return $h()[t]}function il(t,e){let r=$h();r[t]=e,tE(r)}function vh(t,e){let r=Ke(e),n=rE(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 ${ol()}.`);return r}je();fe();var Sh=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function xh(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:Sh(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 nE={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Sh(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)=>xh(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>xh(t,e,r,"remove-token")},Eh={api:nE,fetchProject:se,provisionOnRunner:ih,teardownOnRunner:sh};async function Th(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(Ke(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");vh(e.runnerId,e.runnerPublicKey);let i=q(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 Ih(t,e,r,n=Eh){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 Th(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:[Fa(e.runnerId)]},c=Bt(e.runnerPublicKey,JSON.stringify(a));il(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 Rh(t,e,r,n=Eh){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 Th(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=Bt(e.runnerPublicKey,JSON.stringify(c));il(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))}}je();F();ut();fe();var Ch=16*1024;function oE(t){return Je.test(t)?Ot(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Je}`}function Ph(t,e,r,n){let o=oE(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(pn(n,r).toString("utf-8"));if(typeof s.value!="string"||s.value.length===0)return{ok:!1,detail:"payload has no value"};i=s.value}catch(s){return{ok:!1,detail:`cannot open the sealed secret (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}if(i.length>Ch)return{ok:!1,detail:`secret value too large (max ${Ch} chars)`};try{return Hd(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function Ah(t,e){try{return Wd(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)}}}nn();fe();Vt();var es=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}=lo(o,a.repoSpec);try{let u=await l.getPullRequest(c,a.number);n.push({number:a.number,url:a.url,state:u.state,merged:u.merged,ci:u.ci,mergeable:u.mergeable})}catch(u){if(u instanceof xr){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.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}=lo(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=iE(n);this.log.info(`[track] task=${e} snapshot signalled${s?` \u2192 ${s}`:""} (${n.length} PR(s))`)}};function iE(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}F();var ts=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??(()=>It({contextDir:this.options.contextDir})))();if(!r.ok){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn(`[yt-sync] tracker provider unavailable (${r.error}) \u2014 poller idle.`));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,r.provider)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let $=e.stageField?{stageField:e.stageField}:{},S=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},v=(e.backlogScope??"personal")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(v){let b=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[I,_]=await Promise.all([b.length>0?r.listIssues({projectKey:e.projectKey,columns:b,...$,...S}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...$})]),G=new Map;for(let z of[...I,..._])G.set(z.id,z);o=[...G.values()]}else{let b=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:b,...$,...S})}}catch($){let S=$ instanceof Error?$.message:String($);S.includes("stage_field")?this.log.warn(`[yt-sync] CONFIGURATION ERROR \u2014 ${S}`):this.log.warn(`[yt-sync] listIssues failed: ${S}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let $ of o){if(s.add($.id),a.has($.status))continue;let S=await Nh(r,$.id,e.sinceMs,this.log);S&&i.set($.id,S)}let c=[];for(let $ of e.offBoardIssueIds){if(s.has($))continue;let S=await Nh(r,$,e.sinceMs,this.log);if(S&&S.length>0&&i.set($,S),e.requireAssignee||S&&S.length>0){let T=await jh(r,$,e.stageField,this.log);if(T)c.push(T);else if(S&&S.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter($=>!a.has($.status)),{attachmentsByIssue:u,attachmentKeys:p}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let d=[...l,...c].map($=>({issue:$,comments:i.get($.id)??[],attachments:u.get($.id)??[]}));d.push(...await Xm(this.options.contextDir,d,$=>jh(r,$,e.stageField,this.log)));try{await qi(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let $ of p)this.shippedAttachments.add($)}catch($){let S=$ instanceof Error?$.message:String($);this.abandonTick(`context task sync failed: ${S}`);return}let m=this.options.isSelfComment??(()=>!1),f=[],g=[];for(let[$,S]of i){let T=S.filter(b=>!m(b.id));if(T.length===0)continue;f.push({issueId:$,comments:T.map(sE)});let v=T.flatMap(b=>{let I=br(b.body);return I?[{commentId:b.id,author:b.author,name:I.name,args:I.args,createdAt:b.createdAt}]:[]});v.length>0&&g.push({issueId:$,commands:v})}let k={type:"youtrack_observation",projectId:e.projectId,issues:o.map(_h),commentsBatch:f,...g.length>0?{commandsBatch:g}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(_h)}:{},observedAtMs:n};this.send(k);let h=f.reduce(($,S)=>$+S.comments.length,0),w=g.reduce(($,S)=>$+S.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${h} commands=${w} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let p=`${s.id}:${u.id}`;if(this.shippedAttachments.has(p))continue;let d;try{d=await n.downloadAttachment(u.url)}catch(f){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${f instanceof Error?f.message:String(f)}`);continue}let m=aE(u.name);l.has(m)&&(m=`${u.id}-${m}`),l.add(m),c.push({name:m,contentBase64:d.toString("base64")}),i.push(p)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}};function _h(t){let{description:e,...r}=t;return r}function sE(t){let{body:e,...r}=t;return r}function aE(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 jh(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 Nh(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 TE(t,e){let r=t.repos.filter(i=>i.mirror);if(r.length===0)return[];let{mirrorLag:n}=await Promise.resolve().then(()=>(cl(),al)),o=[];for(let i of r){let s=i.mountAs==="."?t.root:Ar(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 kl="npm i -g @code-partner/codepipe@latest";function ss(t,e={}){let r=e.log??{info:h=>console.log(h),warn:h=>console.warn(h)};r.info(`codepipe-cli v${Ve} (protocol ${ht})`);let n=h=>e.onEvent?.(h),o=e.workspace;o?.contextDir&&Vp(o.contextDir,r);let i=()=>{if(o?.contextDir)try{cn(o.contextDir,o.root,r)}catch(h){r.warn(`[skills] materialize failed (non-fatal): ${h instanceof Error?h.message:String(h)}`)}};i();let s=Xh("CLI_TRACKING_POLL_INTERVAL_SEC"),a=Xh("CLI_YOUTRACK_POLL_INTERVAL_SEC"),c=(()=>{let h=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(h)&&h>0?h*1e3:6e5})(),l=!1,u=!1,p=!1,d=new Set,m=!1,f=new Set,g=k();function k(){let h=Ji(t.hubUrl,t.cliToken),w=null,$=new es(s,L=>{h.readyState===h.OPEN&&h.send(JSON.stringify(L))},r),S=new ts(a,L=>{h.readyState===h.OPEN&&h.send(JSON.stringify(L))},r,{contextDir:o?.contextDir??null,isSelfComment:L=>f.has(L)}),T=null,v=async()=>{try{let L={trackerProvider:Qc(o?.contextDir??null)};try{let E=await se(t.hubUrl,t.cliToken,t.projectId);L={...L,repos:E.repos,contextRepo:E.contextRepo}}catch(E){r.warn(`[readiness] could not fetch project summary for push checks: ${E instanceof Error?E.message:String(E)}`)}let B=await Np(t.projectId,L),M=o?await TE(o,r):[];if(i(),h.readyState!==h.OPEN)return;let Y={type:"cli_readiness",projectId:t.projectId,ready:B.ready,checks:B.checks,creds:B.creds,secretNames:qd(t.projectId),...o?{mirrors:M}:{},checkedAt:B.checkedAt};if(h.send(JSON.stringify(Y)),B.ready)r.info("[readiness] ready");else{let E=B.checks.filter(R=>!R.ok).map(R=>`${R.name}(${R.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${E.join(", ")}`)}let W=Bp(B.creds,p);if(W==="open"){p=!0;let E=Fp(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${E}`),Tr(E)}else W==="rearm"&&(p=!1)}catch(L){r.warn(`[readiness] check failed: ${L instanceof Error?L.message:String(L)}`)}},b=()=>{v(),T=setInterval(()=>void v(),c),typeof T.unref=="function"&&T.unref()},I=()=>{T&&(clearInterval(T),T=null)},_=150,G=new Map,z=L=>{let B=G.get(L);if(!B||(B.timer&&clearTimeout(B.timer),G.delete(L),B.events.length===0||h.readyState!==h.OPEN))return;let M={type:"run_activity",projectId:t.projectId,runId:L,events:B.events};h.send(JSON.stringify(M))},A=(L,B)=>{let M=G.get(L);if(M||(M={events:[],timer:null},G.set(L,M)),M.events.push(B),B.kind==="result"){z(L);return}M.timer||(M.timer=setTimeout(()=>z(L),_),M.timer.unref?.())},y=o?.contextDir?new ki(o.contextDir,t.projectId,L=>{h.readyState===h.OPEN&&h.send(JSON.stringify(L))},r):null,U=async()=>{let L=o?.contextDir;if(!L)throw new Error("no context repo clone on this CLI");let B;try{B=(await se(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let M=await $f(L,t.projectId,B,r);return h.readyState===h.OPEN&&h.send(JSON.stringify(M)),M},j=null,H=async()=>{let L=o?.contextDir;if(L)try{let{readContextIndexHub:B,collectSearchRows:M}=await Promise.resolve().then(()=>(To(),Eo));if(B(L)!=="metadata")return;let Y=M(L);h.readyState===h.OPEN&&(h.send(JSON.stringify({type:"model_index",projectId:t.projectId,rows:Y})),r.info(`[model] tier-2 index snapshot pushed (${Y.length} rows)`))}catch(B){r.warn(`[model] tier-2 index push failed (non-fatal): ${B instanceof Error?B.message:String(B)}`)}},J=()=>{j&&clearTimeout(j),j=setTimeout(()=>void H(),5e3)},oe=null,At=async L=>{if(o?.contextDir)try{let{rebuildWorkspaceModelIfStale:B}=await Promise.resolve().then(()=>(_o(),is));(await B({root:o.root,contextDir:o.contextDir,repos:o.repos},{fetch:L,onLog:Y=>r.info(Y)})).rebuilt.length>0&&J()}catch(B){r.warn(`[model] release-path rebuild failed (non-fatal): ${B instanceof Error?B.message:String(B)}`)}},pt=L=>{oe&&clearTimeout(oe),oe=setTimeout(()=>void At(L),6e4)},Ue=setInterval(()=>void At(!0),6*36e5);return h.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let L=ep(t.projectId),B=V("ORIGIN")==="farm"?"farm":"local",M=V("FARM_ID"),Y=t.accountEmail??L.email,W;try{let R=Bf(t.projectId);R&&(W=R.publicKey,r.info(`[cred-channel] key fingerprint: ${R.fingerprint}`))}catch(R){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${R instanceof Error?R.message:String(R)}`)}let E={type:"register",projectId:t.projectId,platformVersion:Ve,protocolVersion:ht,accountId:L.accountId,accountLabel:L.label,origin:B,inFlightActionIds:[...d],...Y?{accountEmail:Y}:{},...B==="farm"&&M?{farmId:M}:{},...W?{sealPublicKey:W}:{}};h.send(JSON.stringify(E))}),h.on("message",async L=>{let B=L.toString("utf-8");if(B==="pong"||B==="ping")return;let M;try{M=JSON.parse(B)}catch{return}if(!M||typeof M!="object")return;let Y=M.type;if(Y==="registered"){let E=M;if(E.ok){if(r.info(`[ws] registered for project ${E.projectId}`),n({kind:"registered",projectId:E.projectId??t.projectId}),$.start(),y?.start(),b(),bl(t,o,r),o?.contextDir){try{let R=Ei(o.contextDir,t.projectId);h.readyState===h.OPEN&&h.send(JSON.stringify(R)),R.outdated&&(r.warn(`[ctx] context format outdated: v${R.templateVersion} \u2192 v${R.currentVersion}`+(R.missingPaths.length>0?` (missing: ${R.missingPaths.join(", ")})`:"")),u||(u=!0,U().catch(()=>{})))}catch(R){r.warn(`[ctx] context-format detect failed (non-fatal): ${R instanceof Error?R.message:String(R)}`)}H(),pt(!0)}}else r.warn(`[ws] register rejected: ${E.reason??"unknown"}`),n({kind:"register_rejected",reason:E.reason??"unknown"}),l=!0,h.close();return}if(Y==="hello"){let E=M;w=zn(E.protocolVersion);let R=w?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${E.platformVersion} (protocol ${E.protocolVersion}) \u2014 ${R}`),w||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Ve}, protocol ${ht}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${kl}`),n({kind:"incompatible",hubVersion:typeof E.platformVersion=="string"?E.platformVersion:null,hubProtocol:typeof E.protocolVersion=="number"?E.protocolVersion:null,updateCommand:kl}));return}if(Y==="tracking_targets"){$.setTargets(M.targets);return}if(Y==="youtrack_sync_request"){S.setRequest(M);return}if(Y==="youtrack_force_sync"){S.forceSync();return}if(Y==="sync_local"){await CE(M,o,h,r);return}if(Y==="provision_repo"){let E=M;r.info(`[repo] provision_repo: ${E.repo.name} (${E.repo.host}:${E.repo.owner}/${E.repo.repoName})`),await IE(t,o,E.repo,r),await bl(t,o,r);return}if(Y==="remove_repo"){let E=M;r.info(`[repo] remove_repo: ${E.repoName}${E.purge?" (purge)":""}`),await bl(t,o,r),E.purge&&RE(t,o,E.repoName,r);return}if(Y==="context_write"){await PE(M,o,h,r),i();return}if(Y==="adr_promote"){await AE(M,o,h,r),i();return}if(Y==="cred_update"){let E=M,R=q(t.projectId),Q=R?.sealKey?await Ff(t.projectId,E.kind,E.sealed,R.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},ie={type:"cred_update_result",updateId:E.updateId,projectId:t.projectId,ok:Q.ok,...Q.detail?{detail:Q.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(ie)),Q.ok?(r.info(`[cred] ${E.kind} replaced${Q.detail?` \u2014 ${Q.detail}`:""}`),v()):r.warn(`[cred] ${E.kind} replacement rejected: ${Q.detail??"unknown"}`);return}if(Y==="readiness_check"){r.info("[readiness] on-demand check requested"),v();return}if(Y==="agent_login_start"){Up(t,h,M,r,v);return}if(Y==="move_to_farm"){let E=M;r.info(`[farm-move] request to move ${t.projectId} onto farm ${E.farmName} (${E.farmId})`);let R=await bh(t,E,o?.contextDir,r);h.readyState===h.OPEN&&h.send(JSON.stringify(R)),R.ok?r.info(`[farm-move] done \u2014 farm daemon ${R.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${R.error??"unknown error"}`);return}if(Y==="gh_runner_setup"){let E=M;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${E.runnerName} (${E.runnerId})`);let R=await Ih(t,E,r);h.readyState===h.OPEN&&h.send(JSON.stringify(R)),R.ok?r.info(`[ghr] runners connected on ${E.runnerName}`):r.warn(`[ghr] setup failed: ${R.error??"see per-repo statuses"}`);return}if(Y==="gh_runner_teardown"){let E=M;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${E.runnerName} (${E.runnerId})`);let R=await Rh(t,E,r);h.readyState===h.OPEN&&h.send(JSON.stringify(R)),R.ok?r.info(`[ghr] runners disconnected from ${E.runnerName}`):r.warn(`[ghr] teardown failed: ${R.error??"unknown error"}`);return}if(Y==="tracker_fields_request"){let E=M,R={type:"tracker_fields_result",requestId:E.requestId,projectId:t.projectId,ok:!1},Q=It({contextDir:o?.contextDir??null});if(!Q.ok)R.error=Q.error;else try{R.fields=await Q.provider.fetchStateFields(E.projectKey),R.ok=!0}catch(ie){R.error=ie instanceof Error?ie.message:String(ie)}h.readyState===h.OPEN&&h.send(JSON.stringify(R)),R.ok||r.warn(`[yt-fields] listing failed: ${R.error??"unknown"}`);return}if(Y==="project_secret_update"||Y==="project_secret_delete"){let E=M,R;if(E.type==="project_secret_update"){let ie=q(t.projectId);R=ie?.sealKey?Ph(t.projectId,E.name,E.sealed,ie.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else R=Ah(t.projectId,E.name);let Q={type:"project_secret_update_result",updateId:E.updateId,projectId:t.projectId,ok:R.ok,...R.detail?{detail:R.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(Q)),R.ok?(r.info(`[secret] ${E.name} ${E.type==="project_secret_update"?"saved":"deleted"}`+(R.detail?` \u2014 ${R.detail}`:"")),v()):r.warn(`[secret] ${E.name} rejected: ${R.detail??"unknown"}`);return}if(Y==="sandbox_keys"){let E=q(t.projectId);if(!E){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let R=Qr(t.projectId),Q=Lf(M,E,R,r);for(let ie of Q)h.readyState===h.OPEN&&h.send(JSON.stringify(ie));return}if(Y!=="dispatch_action")return;let W=M;if(w===!1){let E=`refused: HUB protocol incompatible with CLI v${Ve} (protocol ${ht})`;h.send(JSON.stringify({type:"action_result",actionId:W.actionId,status:"failed",error:E})),r.warn(`[exec] ${W.actionId} (${W.action.type}) \u2192 REFUSED: ${E}`),r.warn(`[exec] update the CLI to clear this: ${kl}`),n({kind:"action",actionId:W.actionId,actionType:W.action.type,ok:!1,error:E});return}if(W.action.type==="model_drift"){d.add(W.actionId);try{let E,R=o?.repos.find(Q=>Q.name===W.action.repoName);if(!o?.contextDir||!R)E={status:"failed",error:"no local workspace/repo clone on this CLI"};else try{let{computeDriftReport:Q}=await Promise.resolve().then(()=>(Vh(),zh)),ie=R.mountAs==="."?o.root:Ar(o.root,R.mountAs);E={status:"done",result:{report:await Q(ie,o.contextDir,R.name)}}}catch(Q){E={status:"failed",error:Q instanceof Error?Q.message:String(Q)}}h.send(JSON.stringify({type:"action_result",actionId:W.actionId,...E}))}finally{d.delete(W.actionId)}return}if(W.action.type==="model_bootstrap"){d.add(W.actionId);try{let E;if(!o?.contextDir)E={status:"failed",error:"no Context Repo clone on this CLI"};else if(m)E={status:"failed",error:"model bootstrap is already running"};else{m=!0;try{let R=await se(t.hubUrl,t.cliToken,t.projectId),{bootstrapDaemonModel:Q}=await Promise.resolve().then(()=>(_o(),is)),ie=await Q(t.projectId,{root:o.root,contextDir:o.contextDir},R.repos,P=>r.info(`[model] ${P}`));r.info(`[model] bootstrap done: ${ie.repos} repos, ${ie.events} task events`),J(),E={status:"done",result:{repos:ie.repos,events:ie.events}}}catch(R){E={status:"failed",error:R instanceof Error?R.message:String(R)},r.warn(`[model] bootstrap failed: ${E.error}`)}finally{m=!1}}h.readyState===h.OPEN&&h.send(JSON.stringify({type:"action_result",actionId:W.actionId,...E}))}finally{d.delete(W.actionId)}return}d.add(W.actionId);try{let E=await rh({action:W.action,repo:W.repo,trackerIssueId:W.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:y?()=>y.reportNow():void 0,refreshContextStatus:o?.contextDir?U:void 0,onRunActivity:A}).catch(ie=>({status:"failed",error:ie instanceof Error?ie.message:String(ie)}));W.action.type==="tracker_comment"&&E.status==="done"&&"result"in E&&typeof E.result?.commentId=="string"&&f.add(E.result.commentId),h.send(JSON.stringify({type:"action_result",actionId:W.actionId,...E}));let R=E.status!=="failed",Q=!R&&"error"in E?E.error:void 0;R?r.info(`[exec] ${W.actionId} (${W.action.type}) \u2192 done`):r.warn(`[exec] ${W.actionId} (${W.action.type}) \u2192 FAILED: ${Q??"?"}`),n({kind:"action",actionId:W.actionId,actionType:W.action.type,ok:R,...Q?{error:Q}:{}}),R&&["apply_delivery","context_write","create_pr"].includes(W.action.type)&&J(),R&&["merge_pr","merge_branch"].includes(W.action.type)&&pt(!0)}finally{d.delete(W.actionId)}}),h.on("close",(L,B)=>{let M=B?.toString("utf-8")??"";if(r.info(`[ws] closed code=${L}${M?` reason=${M}`:""}`),$.stop(),S.stop(),y?.stop(),I(),clearInterval(Ue),oe&&clearTimeout(oe),j&&clearTimeout(j),M==="replaced"){l=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:L}),!l&&setTimeout(()=>{g=k()},2e3)}),h.on("error",L=>r.warn(`[ws] error: ${L.message}`)),h}return{stop(){l=!0,g.close()}}}async function bl(t,e,r){try{let n=await se(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=wo(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 IE(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?Ar(e.root,o):_e(t.projectId,r.name);if(Jh(Ar(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await EE().clone(e?Ci(r):Ac(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 RE(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?Ar(e.root,o):_e(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Jh(Ar(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{SE(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 CE(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=Ar(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Gp(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 PE(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 Re(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 AE(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 rf(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 Xh(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}je();fe();Ut();vl();it();Ai();async function lg(t={profile:void 0}){let{cfg:e,profile:r}=Zr(t.profile),n=q(e.projectId);n&&co(n),bo(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),$o(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),vo(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=jo(xl(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=ui("CLI_LOG",i,o);if(s.enabled){let d=new tn(s);di(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=Xr(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=jo(xl(),".codepipe",r?jo("profiles",r,"context"):"context");if(await nl(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await ag(()=>cs({cfg:e,secrets:n,contextDir:d,log:{info:m=>console.log(m),warn:m=>console.warn(m)}}),{log:{warn:m=>console.warn(m)}}),a||await nl(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let m=jo(xl(),".codepipe",r?jo("profiles",r,"context-config"):"context-config");bi(a.contextDir,m,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=ss(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(`
966
- [${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}_n();Ge();je();async function dw(t={profile:void 0}){let e=st(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Ji(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=Le(t.profile);o?o.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${o.sandboxId} (${o.name}), llm=${o.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${o.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}Ko();import{readFileSync as OC}from"node:fs";F();Ge();Ut();Bo();Ir();Vt();Er();je();fe();function $e(t){throw new Error(t)}function Ce(t,e){return(typeof t!="string"||t.trim().length===0)&&$e(`config: '${e}' must be a non-empty string`),t.trim()}function qo(t,e){if(t==null)return;typeof t!="string"&&$e(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function LC(t){(!t||typeof t!="object")&&$e("config: expected a JSON object");let e=t,r=Ce(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||$e("config: 'hubUrl' must start with http(s)://");let n=Ce(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&$e("config: 'project' is required");let i=o,s=Ce(i.id,"project.id");Wt.test(s)||$e("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=Ce(i.name,"project.name"),c=Ce(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&$e("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||$e("config: 'project.repos' must be an array");let u=l.map((w,$)=>{(!w||typeof w!="object")&&$e(`config: project.repos[${$}] must be an object`);let S=w,T=Ce(S.host,`project.repos[${$}].host`);T!=="github"&&T!=="bitbucket"&&T!=="gitlab"&&$e(`config: project.repos[${$}].host must be 'github', 'bitbucket' or 'gitlab'`);let v={name:Ce(S.name,`project.repos[${$}].name`),host:T,owner:Ce(S.owner,`project.repos[${$}].owner`),repoName:Ce(S.repoName,`project.repos[${$}].repoName`)},b=qo(S.defaultBranch,`project.repos[${$}].defaultBranch`);b&&(v.defaultBranch=b);let I=qo(S.mountAs,`project.repos[${$}].mountAs`);return I&&(v.mountAs=I),v}),p=i.contextRepo;(!p||typeof p!="object")&&$e("config: 'project.contextRepo' is required");let d=p,m=qo(d.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&$e("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:m,owner:Ce(d.owner,"project.contextRepo.owner"),name:qo(d.name,"project.contextRepo.name")??xt(s)},g={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:f}},k=qo(i.youtrackProjectKey,"project.youtrackProjectKey");if(k&&(g.project.youtrackProjectKey=k),i.index!==void 0&&(typeof i.index!="boolean"&&$e("config: 'project.index' must be a boolean"),g.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&$e("config: 'project.youtrackWrites' must be a boolean"),g.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let w=Ce(i.llmProvider,"project.llmProvider");w==="codex"&&$e(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),w!=="claude"&&$e("config: 'project.llmProvider' must be 'claude'"),g.project.llmProvider=w}let h=e.secrets;if(h!==void 0){(typeof h!="object"||h===null)&&$e("config: 'secrets' must be an object");let w=h,$={};if(w.github){let S=w.github;$.github={token:Ce(S.token,"secrets.github.token")}}if(w.bitbucket){let S=w.bitbucket;$.bitbucket={email:Ce(S.email,"secrets.bitbucket.email"),apiToken:Ce(S.apiToken,"secrets.bitbucket.apiToken")}}if(w.gitlab){let S=w.gitlab;$.gitlab={token:Ce(S.token,"secrets.gitlab.token")}}if(w.youtrack){let S=w.youtrack;$.youtrack={url:Ce(S.url,"secrets.youtrack.url").replace(/\/$/,""),token:Ce(S.token,"secrets.youtrack.token")}}if(w.contextWrite){let S=w.contextWrite;$.contextWrite={token:Ce(S.token,"secrets.contextWrite.token")}}g.secrets=$}return g}async function MC(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function DC(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await qt(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 Yt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await hi(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 zt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Jt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function gk(t){let e=!t.configPath||t.configPath==="-"?await MC():OC(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){$e(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=LC(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 DC(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 jn(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??en(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){$e(`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 nr(o,i,a)}catch(d){if(d instanceof K&&d.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await se(o,i,s.id);else if(d instanceof K)$e(`HUB \u2192 ${d.status} ${d.message}`);else throw d}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let p={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(ae(p),Mt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${St(s.id)}`),Qt(s.id,Tt(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,s.llmProvider??Xe),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await Ao(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();fe();import{cancel as yk,intro as wk,isCancel as kk,log as Ql,outro as UC,password as bk}from"@clack/prompts";async function BC(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function $k(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await BC(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){wk("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Ql.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await bk({message:"Claude OAuth token"});kk(i)&&(yk("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),zd({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${li()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=st(t.profile);if(!e){wk(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Ql.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await bk({message:"Claude OAuth token"});kk(i)&&(yk("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=q(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},ae(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Ql.success("Claude OAuth token saved."),UC("It will be sealed into job bundles when a SANDBOX (re)connects."))}_o();F();Ge();Ut();Bo();Ir();Ss();je();fe();import{cancel as FC,confirm as GC,intro as KC,isCancel as vk,log as Me,outro as HC,select as xk,text as dr}from"@clack/prompts";function Sk(t){FC(t),process.exit(1)}function Dn(t){return vk(t)&&Sk("aborted"),t}function Yo(t){return vk(t)&&Sk("aborted"),typeof t=="string"?t:""}async function WC(t,e){let r=Dn(await xk({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),n=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",o=Yo(await dr({message:"Context Repo owner (org / group / workspace / user)",placeholder:n||"your-org",initialValue:n,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=Yo(await dr({message:"Context Repo name",placeholder:xt(t),initialValue:xt(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function Ek(t={profile:void 0}){let e=st(t.profile);KC(`codepipe project add \u2192 ${e.hubUrl}`);let r=Dn(await dr({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>Wt.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=Dn(await dr({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=Dn(await xk({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"})),i=Dn(await dr({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Dn(await GC({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=Yo(await dr({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:h=>!h||!h.trim()||qe(h)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!d)break;let m=qe(d);Me.message(`${m.host}: ${m.owner}/${m.repoName}`);let f=Yo(await dr({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:h=>h.trim().length>0?void 0:"required"})).trim(),g=Yo(await dr({message:"default branch (optional)",placeholder:"main"})).trim(),k={name:f,host:m.host,owner:m.owner,repoName:m.repoName};g&&(k.defaultBranch=g),a.push(k)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await WC(r,a),u=q(e.projectId);Me.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await jn(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??en(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:d=>Me.message(d),warn:d=>Me.warn(d)}})}catch(d){Me.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,Me.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await nr(e.hubUrl,e.cliToken,c);Me.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),Qt(r,Tt(c,s,u?.youtrack?.url),{info:m=>Me.message(m),warn:m=>Me.warn(m)}),d.contextRepo&&(Me.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),Me.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&Me.error(` error: ${d.provisioningError}`),HC("done")}catch(d){d instanceof K?(Me.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&Me.message(JSON.stringify(d.payload,null,2))):Me.error(d instanceof Error?d.message:String(d)),process.exit(1)}}_n();Ge();je();fe();it();Ko();import{existsSync as qC,rmSync as YC}from"node:fs";import{confirm as zC,intro as VC,isCancel as XC,log as pr,outro as JC,spinner as ZC}from"@clack/prompts";function Pt(t){pr.error(t),process.exit(1)}var Tk=t=>t.trim().replace(/\/+$/,"");async function Ik(t){VC("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Ae()?.spec.projectId??void 0;e||Pt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=wt(e);r||Pt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Tk(r.hubUrl),o=r.projectId,i=Tk(t.hub);i.startsWith("http")||Pt("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&Pt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let h=ZC();h.start(`reading project ${o} from ${n}\u2026`);try{l=await se(n,r.cliToken,o),h.stop(`read project ${o} (${l.name})`)}catch(w){throw h.stop("could not read the source project",1),w instanceof K&&Pt(`source HUB ${n} \u2192 ${w.status} ${w.message}. The source HUB must be reachable with a valid token to move a project.`),w}}l.contextRepo||Pt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=q(o),p=(t.account??r.accountEmail??await Ln()).trim().toLowerCase();if(pr.message(`move project '${o}'
963
+ `;return await Ie(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 yf(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:ai.statusColumns}]}async mutateRecord(e,r,n){let o=yo(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=wo(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:Vr(e),content:Rc(i)},...Yi(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await Ie(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:so,status:r.targetStatus,links:[],created:n,updated:n},i=wo(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:Vr(e),content:Rc(o)},...Yi(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}};function Qm(t,e){let r=Se(t,`tasks/${e}/comments.jsonl`);if(!OS(r))return[];let n=[];for(let o of LS(r,"utf-8").split(`
964
+ `)){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}Ii();function el(t){if(!t)return"youtrack";try{let e=rh(t,"project.yaml");return eh(e)&&nh(th(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function Rt(t){let e=el(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=mf(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=DS(n);return i?{ok:!0,kind:e,provider:new Co(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=wp();return r?{ok:!0,kind:e,provider:new Io(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function DS(t){try{let e=rh(t,"project.yaml");if(!eh(e))return null;let r=nh(th(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var Vi=new Map;async function Po(t,e){let n=(Vi.get(t)??Promise.resolve()).catch(()=>{}).then(e);Vi.set(t,n);try{return await n}finally{Vi.get(t)===n&&Vi.delete(t)}}function Ao(t,e){return uo(t.split(":",2)[0]??"",e)}function oh(t){let{mirror:e,...r}=t;return{spec:r,host:Er(r)}}async function ih(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;rr(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return V("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Po(`${i}/${r.name}`,async()=>{let s=await nr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir),{commit:c,pushed:l,baseMoved:u}=await If(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 Xm({contextDir:t.contextDir,repoDir:a,repoName:r.name,taskKey:p,commitSha:c}).catch(d=>{rr(`[model] task event for ${p} failed: ${d instanceof Error?d.message:String(d)}`)})}return ue({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 V("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Po(`${i}/${r.name}`,async()=>{let s=await nr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir);return await Cf(s,a,{branchName:e.branchName,force:e.force}),ue({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"create_pr":{if(!r)return V("no repo spec");let{spec:i,host:s}=Ao(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 Jm({contextDir:t.contextDir,repoDir:_e(l,r.name,t.baseDir),branchName:e.branchName,baseBranch:e.baseBranch,fallbackTaskKey:c,prUrl:a.url}).catch(u=>{rr(`[model] pr link for ${c} failed: ${u instanceof Error?u.message:String(u)}`)})}return ue({url:a.url,number:a.number,host:s.name})}case"merge_pr":{if(!r)return V("no repo spec");let{spec:i,host:s}=Ao(e.taskId,r),a=await s.mergePR(i,e.prNumber,e.mergeMethod,e.deleteBranch);return ue({prNumber:e.prNumber,host:s.name,...a.mergedSha?{mergedSha:a.mergedSha}:{}})}case"close_pr":{if(!r)return V("no repo spec");let{spec:i,host:s}=Ao(e.taskId,r);return await s.closePR(i,e.prNumber,e.comment),ue({prNumber:e.prNumber,host:s.name})}case"rewrite_cluster_branch":{if(!r)return V("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Po(`${i}/${r.name}`,async()=>{let s=await nr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir),{commit:c,dropped:l}=await Pf(s,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:r.defaultBranch});return ue({branch:e.branchName,commit:c,dropped:l,pushed:l>0})})}case"merge_branch":{if(!r)return V("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Po(`${i}/${r.name}`,async()=>{let s=await nr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir),{mergedSha:c}=await Af(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ue({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return V("no repo spec");let i=t.cloneUrlOverride??Ai(r),a=(await _f(i)).filter(u=>jf(u,e.issueKey)),c=Er(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 ue({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return V("no repo spec");let{spec:i,host:s}=e.upstream?oh(r):Ao(e.taskId,r);return await s.addPRComment(i,e.prNumber,e.body),ue({prNumber:e.prNumber,host:s.name})}case"add_pr_inline_comment":{if(!r)return V("no repo spec");let{spec:i,host:s}=e.upstream?oh(r):Ao(e.taskId,r);if(s.addPRInlineComment)try{return await s.addPRInlineComment(i,e.prNumber,e.path,e.line,e.body),ue({prNumber:e.prNumber,inline:!0,host:s.name})}catch(a){rr(`[exec] inline comment ${e.path}:${e.line} failed (${a instanceof Error?a.message.split(`
965
+ `)[0]:String(a)}) \u2014 posting as a plain comment`)}return await s.addPRComment(i,e.prNumber,`\u{1F4CD} \`${e.path}:${e.line}\`
966
+
967
+ ${e.body}`),ue({prNumber:e.prNumber,inline:!1,host:s.name})}case"tracker_status":{let i=Rt({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),ue({issueId:t.trackerIssueId,newStatus:e.newStatus})):V("no tracker_issue_id provided"):V(i.error)}case"tracker_comment":{let i=Rt({contextDir:t.contextDir});if(!i.ok)return V(i.error);if(!t.trackerIssueId)return V("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return ue({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Rt({contextDir:t.contextDir});if(!i.ok)return V(i.error);if(!e.projectKey)return V("no projectKey in create_tracker_issue action");let{id:s,key:a}=await i.provider.createIssue({projectKey:e.projectKey,title:e.title,body:e.body,targetStatus:e.targetStatus});return ue({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Rt({contextDir:t.contextDir});if(!i.ok)return V(i.error);let s=0;for(let a of e.links)try{await i.provider.applyLink(a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return V(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return ue({applied:s})}case"set_project_setting":{if(!t.contextDir)return V("no context repo clone on this CLI");let i=await Xf(t.contextDir,e.edits);return ue({files:i.files})}case"set_prompt_override":{if(!t.contextDir)return V("no context repo clone on this CLI");if(!Oa(e.role))return V(`unknown prompt operation: ${e.role}`);let i=La(e.role);return await Ie(t.contextDir,[e.content===null?{path:i,content:"",deleted:!0}:{path:i,content:e.content}],e.commitMessage),t.requestConfigReport?.(),ue({path:i,reset:e.content===null})}case"tracker_edit":{let i=Rt({contextDir:t.contextDir});if(!i.ok)return V(i.error);if(!t.contextDir)return V("no context repo clone on this CLI");await i.provider.editIssue(e.issueKey,{...e.title!==void 0?{title:e.title}:{},...e.body!==void 0?{body:e.body}:{}});let s=await i.provider.getIssue(e.issueKey);return s&&await zi(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),ue({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return V("no context repo clone on this CLI");let i=await om(t.contextDir,e);return ue({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return V("no context repo clone on this CLI");let i=await rm(t.contextDir,e);return ue({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ue({reported:!0})):V("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return V("no context repo clone on this CLI");let i=await t.refreshContextStatus();return ue({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return V("no project workspace on this CLI");if(!r)return V("no repo spec");if(!t.onRunActivity)return V("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=bi(t.contextDir),c=s.find(m=>m.id===e.actionId);if(!c){let m=a.find(f=>f.file===`actions/${e.actionId}.yml`);return V(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=xa(c,e.input);if(!l.ok)return V(l.error);let u=zp(t.contextDir),p=q(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),Po(`${e.projectId}/${r.name}`,async()=>{await nr(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=_e(e.projectId,r.name,t.baseDir),f=await qf({cwd:m,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:g=>i(e.runId,g)});return ue({runId:e.runId,status:f.status,exitCode:f.exitCode,...f.failedStep?{failedStep:f.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return V("no context repo clone on this CLI");let i=Vf(t.contextDir,e.path);return ue({path:e.path,...i})}case"search_model":{if(!t.contextDir)return V("no context repo clone on this CLI");let{searchModelIndex:i}=await Promise.resolve().then(()=>(Ro(),To)),s=await i(t.contextDir,e.q,e.limit);return ue({hits:s})}case"model_drift":return V("model_drift requires a local workspace (handled by the daemon)");case"model_bootstrap":return V("model_bootstrap requires a local workspace (handled by the daemon)");default:return V(`unsupported action type: ${e.type}`)}}catch(i){return V(i instanceof Error?i.message:String(i))}}function ue(t){return{status:"done",result:t}}function V(t){return{status:"failed",error:t}}ut();rl();je();me();import{existsSync as bh,readFileSync as $h}from"node:fs";import{join as vh}from"node:path";async function xh(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=Ke(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Ji(e.farmId,e.farmPublicKey);let s=q(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=vh(r,"project.yaml"),m=vh(r,"regimen.yaml");bh(d)&&bh(m)?c={projectYaml:$h(d,"utf-8"),regimenYaml:$h(m,"utf-8")}:n.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},u=Bt(e.farmPublicKey,JSON.stringify(l));Xi(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let p=await Qi(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))}}F();ut();Fe();ut();import{homedir as XS}from"node:os";import{existsSync as JS,mkdirSync as ZS,readFileSync as QS,writeFileSync as eE}from"node:fs";import{dirname as tE,join as rE}from"node:path";function il(){return X("RUNNER_PINS")??rE(XS(),".codepipe","runner-pins.json")}function Sh(){let t=il();if(!JS(t))return{};try{return JSON.parse(QS(t,"utf-8"))}catch{return{}}}function nE(t){let e=il();ZS(tE(e),{recursive:!0}),eE(e,JSON.stringify(t,null,2)+`
968
+ `,{mode:384})}function oE(t){return Sh()[t]}function sl(t,e){let r=Sh();r[t]=e,nE(r)}function Eh(t,e){let r=Ke(e),n=oE(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 ${il()}.`);return r}je();me();var Rh=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function Th(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:Rh(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 iE={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Rh(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)=>Th(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Th(t,e,r,"remove-token")},Ih={api:iE,fetchProject:se,provisionOnRunner:ch,teardownOnRunner:lh};async function Ch(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(Ke(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Eh(e.runnerId,e.runnerPublicKey);let i=q(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 Ph(t,e,r,n=Ih){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 Ch(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:[Ga(e.runnerId)]},c=Bt(e.runnerPublicKey,JSON.stringify(a));sl(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 Ah(t,e,r,n=Ih){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 Ch(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=Bt(e.runnerPublicKey,JSON.stringify(c));sl(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))}}je();F();ut();me();var _h=16*1024;function sE(t){return Je.test(t)?Ot(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Je}`}function jh(t,e,r,n){let o=sE(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(fn(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>_h)return{ok:!1,detail:`secret value too large (max ${_h} chars)`};try{return qd(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function Nh(t,e){try{return Yd(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)}}}on();me();Vt();var ts=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}=uo(o,a.repoSpec);try{let u=await l.getPullRequest(c,a.number);n.push({number:a.number,url:a.url,state:u.state,merged:u.merged,ci:u.ci,mergeable:u.mergeable})}catch(u){if(u instanceof Sr){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.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}=uo(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=aE(n);this.log.info(`[track] task=${e} snapshot signalled${s?` \u2192 ${s}`:""} (${n.length} PR(s))`)}};function aE(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}F();var rs=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??(()=>Rt({contextDir:this.options.contextDir})))();if(!r.ok){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn(`[yt-sync] tracker provider unavailable (${r.error}) \u2014 poller idle.`));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,r.provider)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let $=e.stageField?{stageField:e.stageField}:{},S=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},v=(e.backlogScope??"personal")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(v){let b=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[R,_]=await Promise.all([b.length>0?r.listIssues({projectKey:e.projectKey,columns:b,...$,...S}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...$})]),G=new Map;for(let z of[...R,..._])G.set(z.id,z);o=[...G.values()]}else{let b=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:b,...$,...S})}}catch($){let S=$ instanceof Error?$.message:String($);S.includes("stage_field")?this.log.warn(`[yt-sync] CONFIGURATION ERROR \u2014 ${S}`):this.log.warn(`[yt-sync] listIssues failed: ${S}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let $ of o){if(s.add($.id),a.has($.status))continue;let S=await Mh(r,$.id,e.sinceMs,this.log);S&&i.set($.id,S)}let c=[];for(let $ of e.offBoardIssueIds){if(s.has($))continue;let S=await Mh(r,$,e.sinceMs,this.log);if(S&&S.length>0&&i.set($,S),e.requireAssignee||S&&S.length>0){let T=await Lh(r,$,e.stageField,this.log);if(T)c.push(T);else if(S&&S.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter($=>!a.has($.status)),{attachmentsByIssue:u,attachmentKeys:p}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let d=[...l,...c].map($=>({issue:$,comments:i.get($.id)??[],attachments:u.get($.id)??[]}));d.push(...await Zm(this.options.contextDir,d,$=>Lh(r,$,e.stageField,this.log)));try{await zi(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let $ of p)this.shippedAttachments.add($)}catch($){let S=$ instanceof Error?$.message:String($);this.abandonTick(`context task sync failed: ${S}`);return}let m=this.options.isSelfComment??(()=>!1),f=[],g=[];for(let[$,S]of i){let T=S.filter(b=>!m(b.id));if(T.length===0)continue;f.push({issueId:$,comments:T.map(cE)});let v=T.flatMap(b=>{let R=$r(b.body);return R?[{commentId:b.id,author:b.author,name:R.name,args:R.args,createdAt:b.createdAt}]:[]});v.length>0&&g.push({issueId:$,commands:v})}let k={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Oh),commentsBatch:f,...g.length>0?{commandsBatch:g}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(Oh)}:{},observedAtMs:n};this.send(k);let h=f.reduce(($,S)=>$+S.comments.length,0),w=g.reduce(($,S)=>$+S.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${h} commands=${w} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let p=`${s.id}:${u.id}`;if(this.shippedAttachments.has(p))continue;let d;try{d=await n.downloadAttachment(u.url)}catch(f){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${f instanceof Error?f.message:String(f)}`);continue}let m=lE(u.name);l.has(m)&&(m=`${u.id}-${m}`),l.add(m),c.push({name:m,contentBase64:d.toString("base64")}),i.push(p)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}};function Oh(t){let{description:e,...r}=t;return r}function cE(t){let{body:e,...r}=t;return r}function lE(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 Lh(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 Mh(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 IE(t,e){let r=t.repos.filter(i=>i.mirror);if(r.length===0)return[];let{mirrorLag:n}=await Promise.resolve().then(()=>(ll(),cl)),o=[];for(let i of r){let s=i.mountAs==="."?t.root:Ar(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 bl="npm i -g @code-partner/codepipe@latest";function as(t,e={}){let r=e.log??{info:h=>console.log(h),warn:h=>console.warn(h)};r.info(`codepipe-cli v${Ve} (protocol ${ht})`);let n=h=>e.onEvent?.(h),o=e.workspace;o?.contextDir&&Jp(o.contextDir,r);let i=()=>{if(o?.contextDir)try{ln(o.contextDir,o.root,r)}catch(h){r.warn(`[skills] materialize failed (non-fatal): ${h instanceof Error?h.message:String(h)}`)}};i();let s=Qh("CLI_TRACKING_POLL_INTERVAL_SEC"),a=Qh("CLI_YOUTRACK_POLL_INTERVAL_SEC"),c=(()=>{let h=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(h)&&h>0?h*1e3:6e5})(),l=!1,u=!1,p=!1,d=new Set,m=!1,f=new Set,g=k();function k(){let h=Zi(t.hubUrl,t.cliToken),w=null,$=new ts(s,L=>{h.readyState===h.OPEN&&h.send(JSON.stringify(L))},r),S=new rs(a,L=>{h.readyState===h.OPEN&&h.send(JSON.stringify(L))},r,{contextDir:o?.contextDir??null,isSelfComment:L=>f.has(L)}),T=null,v=async()=>{try{let L={trackerProvider:el(o?.contextDir??null)};try{let E=await se(t.hubUrl,t.cliToken,t.projectId);L={...L,repos:E.repos,contextRepo:E.contextRepo}}catch(E){r.warn(`[readiness] could not fetch project summary for push checks: ${E instanceof Error?E.message:String(E)}`)}let B=await Lp(t.projectId,L),M=o?await IE(o,r):[];if(i(),h.readyState!==h.OPEN)return;let Y={type:"cli_readiness",projectId:t.projectId,ready:B.ready,checks:B.checks,creds:B.creds,secretNames:zd(t.projectId),...o?{mirrors:M}:{},checkedAt:B.checkedAt};if(h.send(JSON.stringify(Y)),B.ready)r.info("[readiness] ready");else{let E=B.checks.filter(I=>!I.ok).map(I=>`${I.name}(${I.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${E.join(", ")}`)}let W=Gp(B.creds,p);if(W==="open"){p=!0;let E=Kp(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${E}`),Rr(E)}else W==="rearm"&&(p=!1)}catch(L){r.warn(`[readiness] check failed: ${L instanceof Error?L.message:String(L)}`)}},b=()=>{v(),T=setInterval(()=>void v(),c),typeof T.unref=="function"&&T.unref()},R=()=>{T&&(clearInterval(T),T=null)},_=150,G=new Map,z=L=>{let B=G.get(L);if(!B||(B.timer&&clearTimeout(B.timer),G.delete(L),B.events.length===0||h.readyState!==h.OPEN))return;let M={type:"run_activity",projectId:t.projectId,runId:L,events:B.events};h.send(JSON.stringify(M))},A=(L,B)=>{let M=G.get(L);if(M||(M={events:[],timer:null},G.set(L,M)),M.events.push(B),B.kind==="result"){z(L);return}M.timer||(M.timer=setTimeout(()=>z(L),_),M.timer.unref?.())},y=o?.contextDir?new $i(o.contextDir,t.projectId,L=>{h.readyState===h.OPEN&&h.send(JSON.stringify(L))},r):null,U=async()=>{let L=o?.contextDir;if(!L)throw new Error("no context repo clone on this CLI");let B;try{B=(await se(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let M=await xf(L,t.projectId,B,r);return h.readyState===h.OPEN&&h.send(JSON.stringify(M)),M},j=null,H=async()=>{let L=o?.contextDir;if(L)try{let{readContextIndexHub:B,collectSearchRows:M}=await Promise.resolve().then(()=>(Ro(),To));if(B(L)!=="metadata")return;let Y=M(L);h.readyState===h.OPEN&&(h.send(JSON.stringify({type:"model_index",projectId:t.projectId,rows:Y})),r.info(`[model] tier-2 index snapshot pushed (${Y.length} rows)`))}catch(B){r.warn(`[model] tier-2 index push failed (non-fatal): ${B instanceof Error?B.message:String(B)}`)}},J=()=>{j&&clearTimeout(j),j=setTimeout(()=>void H(),5e3)},oe=null,At=async L=>{if(o?.contextDir)try{let{rebuildWorkspaceModelIfStale:B}=await Promise.resolve().then(()=>(No(),ss));(await B({root:o.root,contextDir:o.contextDir,repos:o.repos},{fetch:L,onLog:Y=>r.info(Y)})).rebuilt.length>0&&J()}catch(B){r.warn(`[model] release-path rebuild failed (non-fatal): ${B instanceof Error?B.message:String(B)}`)}},pt=L=>{oe&&clearTimeout(oe),oe=setTimeout(()=>void At(L),6e4)},Ue=setInterval(()=>void At(!0),6*36e5);return h.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let L=rp(t.projectId),B=X("ORIGIN")==="farm"?"farm":"local",M=X("FARM_ID"),Y=t.accountEmail??L.email,W;try{let I=Gf(t.projectId);I&&(W=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 E={type:"register",projectId:t.projectId,platformVersion:Ve,protocolVersion:ht,accountId:L.accountId,accountLabel:L.label,origin:B,inFlightActionIds:[...d],...Y?{accountEmail:Y}:{},...B==="farm"&&M?{farmId:M}:{},...W?{sealPublicKey:W}:{}};h.send(JSON.stringify(E))}),h.on("message",async L=>{let B=L.toString("utf-8");if(B==="pong"||B==="ping")return;let M;try{M=JSON.parse(B)}catch{return}if(!M||typeof M!="object")return;let Y=M.type;if(Y==="registered"){let E=M;if(E.ok){if(r.info(`[ws] registered for project ${E.projectId}`),n({kind:"registered",projectId:E.projectId??t.projectId}),$.start(),y?.start(),b(),$l(t,o,r),o?.contextDir){try{let I=Ri(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(", ")})`:"")),u||(u=!0,U().catch(()=>{})))}catch(I){r.warn(`[ctx] context-format detect failed (non-fatal): ${I instanceof Error?I.message:String(I)}`)}H(),pt(!0)}}else r.warn(`[ws] register rejected: ${E.reason??"unknown"}`),n({kind:"register_rejected",reason:E.reason??"unknown"}),l=!0,h.close();return}if(Y==="hello"){let E=M;w=Vn(E.protocolVersion);let I=w?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${E.platformVersion} (protocol ${E.protocolVersion}) \u2014 ${I}`),w||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Ve}, protocol ${ht}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${bl}`),n({kind:"incompatible",hubVersion:typeof E.platformVersion=="string"?E.platformVersion:null,hubProtocol:typeof E.protocolVersion=="number"?E.protocolVersion:null,updateCommand:bl}));return}if(Y==="tracking_targets"){$.setTargets(M.targets);return}if(Y==="youtrack_sync_request"){S.setRequest(M);return}if(Y==="youtrack_force_sync"){S.forceSync();return}if(Y==="sync_local"){await AE(M,o,h,r);return}if(Y==="provision_repo"){let E=M;r.info(`[repo] provision_repo: ${E.repo.name} (${E.repo.host}:${E.repo.owner}/${E.repo.repoName})`),await CE(t,o,E.repo,r),await $l(t,o,r);return}if(Y==="remove_repo"){let E=M;r.info(`[repo] remove_repo: ${E.repoName}${E.purge?" (purge)":""}`),await $l(t,o,r),E.purge&&PE(t,o,E.repoName,r);return}if(Y==="context_write"){await _E(M,o,h,r),i();return}if(Y==="adr_promote"){await jE(M,o,h,r),i();return}if(Y==="cred_update"){let E=M,I=q(t.projectId),Q=I?.sealKey?await Kf(t.projectId,E.kind,E.sealed,I.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},ie={type:"cred_update_result",updateId:E.updateId,projectId:t.projectId,ok:Q.ok,...Q.detail?{detail:Q.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(ie)),Q.ok?(r.info(`[cred] ${E.kind} replaced${Q.detail?` \u2014 ${Q.detail}`:""}`),v()):r.warn(`[cred] ${E.kind} replacement rejected: ${Q.detail??"unknown"}`);return}if(Y==="readiness_check"){r.info("[readiness] on-demand check requested"),v();return}if(Y==="agent_login_start"){Fp(t,h,M,r,v);return}if(Y==="move_to_farm"){let E=M;r.info(`[farm-move] request to move ${t.projectId} onto farm ${E.farmName} (${E.farmId})`);let I=await xh(t,E,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(Y==="gh_runner_setup"){let E=M;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${E.runnerName} (${E.runnerId})`);let I=await Ph(t,E,r);h.readyState===h.OPEN&&h.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners connected on ${E.runnerName}`):r.warn(`[ghr] setup failed: ${I.error??"see per-repo statuses"}`);return}if(Y==="gh_runner_teardown"){let E=M;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${E.runnerName} (${E.runnerId})`);let I=await Ah(t,E,r);h.readyState===h.OPEN&&h.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners disconnected from ${E.runnerName}`):r.warn(`[ghr] teardown failed: ${I.error??"unknown error"}`);return}if(Y==="tracker_fields_request"){let E=M,I={type:"tracker_fields_result",requestId:E.requestId,projectId:t.projectId,ok:!1},Q=Rt({contextDir:o?.contextDir??null});if(!Q.ok)I.error=Q.error;else try{I.fields=await Q.provider.fetchStateFields(E.projectKey),I.ok=!0}catch(ie){I.error=ie instanceof Error?ie.message:String(ie)}h.readyState===h.OPEN&&h.send(JSON.stringify(I)),I.ok||r.warn(`[yt-fields] listing failed: ${I.error??"unknown"}`);return}if(Y==="project_secret_update"||Y==="project_secret_delete"){let E=M,I;if(E.type==="project_secret_update"){let ie=q(t.projectId);I=ie?.sealKey?jh(t.projectId,E.name,E.sealed,ie.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else I=Nh(t.projectId,E.name);let Q={type:"project_secret_update_result",updateId:E.updateId,projectId:t.projectId,ok:I.ok,...I.detail?{detail:I.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(Q)),I.ok?(r.info(`[secret] ${E.name} ${E.type==="project_secret_update"?"saved":"deleted"}`+(I.detail?` \u2014 ${I.detail}`:"")),v()):r.warn(`[secret] ${E.name} rejected: ${I.detail??"unknown"}`);return}if(Y==="sandbox_keys"){let E=q(t.projectId);if(!E){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let I=en(t.projectId),Q=Df(M,E,I,r);for(let ie of Q)h.readyState===h.OPEN&&h.send(JSON.stringify(ie));return}if(Y!=="dispatch_action")return;let W=M;if(w===!1){let E=`refused: HUB protocol incompatible with CLI v${Ve} (protocol ${ht})`;h.send(JSON.stringify({type:"action_result",actionId:W.actionId,status:"failed",error:E})),r.warn(`[exec] ${W.actionId} (${W.action.type}) \u2192 REFUSED: ${E}`),r.warn(`[exec] update the CLI to clear this: ${bl}`),n({kind:"action",actionId:W.actionId,actionType:W.action.type,ok:!1,error:E});return}if(W.action.type==="model_drift"){d.add(W.actionId);try{let E,I=o?.repos.find(Q=>Q.name===W.action.repoName);if(!o?.contextDir||!I)E={status:"failed",error:"no local workspace/repo clone on this CLI"};else try{let{computeDriftReport:Q}=await Promise.resolve().then(()=>(Zh(),Jh)),ie=I.mountAs==="."?o.root:Ar(o.root,I.mountAs);E={status:"done",result:{report:await Q(ie,o.contextDir,I.name)}}}catch(Q){E={status:"failed",error:Q instanceof Error?Q.message:String(Q)}}h.send(JSON.stringify({type:"action_result",actionId:W.actionId,...E}))}finally{d.delete(W.actionId)}return}if(W.action.type==="model_bootstrap"){d.add(W.actionId);try{let E;if(!o?.contextDir)E={status:"failed",error:"no Context Repo clone on this CLI"};else if(m)E={status:"failed",error:"model bootstrap is already running"};else{m=!0;try{let I=await se(t.hubUrl,t.cliToken,t.projectId),{bootstrapDaemonModel:Q}=await Promise.resolve().then(()=>(No(),ss)),ie=await Q(t.projectId,{root:o.root,contextDir:o.contextDir},I.repos,P=>r.info(`[model] ${P}`));r.info(`[model] bootstrap done: ${ie.repos} repos, ${ie.events} task events`),J(),E={status:"done",result:{repos:ie.repos,events:ie.events}}}catch(I){E={status:"failed",error:I instanceof Error?I.message:String(I)},r.warn(`[model] bootstrap failed: ${E.error}`)}finally{m=!1}}h.readyState===h.OPEN&&h.send(JSON.stringify({type:"action_result",actionId:W.actionId,...E}))}finally{d.delete(W.actionId)}return}d.add(W.actionId);try{let E=await ih({action:W.action,repo:W.repo,trackerIssueId:W.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:y?()=>y.reportNow():void 0,refreshContextStatus:o?.contextDir?U:void 0,onRunActivity:A}).catch(ie=>({status:"failed",error:ie instanceof Error?ie.message:String(ie)}));W.action.type==="tracker_comment"&&E.status==="done"&&"result"in E&&typeof E.result?.commentId=="string"&&f.add(E.result.commentId),h.send(JSON.stringify({type:"action_result",actionId:W.actionId,...E}));let I=E.status!=="failed",Q=!I&&"error"in E?E.error:void 0;I?r.info(`[exec] ${W.actionId} (${W.action.type}) \u2192 done`):r.warn(`[exec] ${W.actionId} (${W.action.type}) \u2192 FAILED: ${Q??"?"}`),n({kind:"action",actionId:W.actionId,actionType:W.action.type,ok:I,...Q?{error:Q}:{}}),I&&["apply_delivery","context_write","create_pr"].includes(W.action.type)&&J(),I&&["merge_pr","merge_branch"].includes(W.action.type)&&pt(!0)}finally{d.delete(W.actionId)}}),h.on("close",(L,B)=>{let M=B?.toString("utf-8")??"";if(r.info(`[ws] closed code=${L}${M?` reason=${M}`:""}`),$.stop(),S.stop(),y?.stop(),R(),clearInterval(Ue),oe&&clearTimeout(oe),j&&clearTimeout(j),M==="replaced"){l=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:L}),!l&&setTimeout(()=>{g=k()},2e3)}),h.on("error",L=>r.warn(`[ws] error: ${L.message}`)),h}return{stop(){l=!0,g.close()}}}async function $l(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 CE(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?Ar(e.root,o):_e(t.projectId,r.name);if(eg(Ar(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await RE().clone(e?Ai(r):_c(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 PE(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?Ar(e.root,o):_e(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!eg(Ar(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{TE(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 AE(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=Ar(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Hp(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 _E(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 Ie(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 jE(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 of(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 Qh(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}je();me();Ut();xl();it();ji();async function pg(t={profile:void 0}){let{cfg:e,profile:r}=Qr(t.profile),n=q(e.projectId);n&&lo(n),$o(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),vo(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),xo(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=Oo(Sl(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=pi("CLI_LOG",i,o);if(s.enabled){let d=new rn(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=Jr(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=Oo(Sl(),".codepipe",r?Oo("profiles",r,"context"):"context");if(await ol(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await ug(()=>ls({cfg:e,secrets:n,contextDir:d,log:{info:m=>console.log(m),warn:m=>console.warn(m)}}),{log:{warn:m=>console.warn(m)}}),a||await ol(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let m=Oo(Sl(),".codepipe",r?Oo("profiles",r,"context-config"):"context-config");vi(a.contextDir,m,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=as(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(`
969
+ [${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}jn();Ge();je();async function fw(t={profile:void 0}){let e=st(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Zi(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=Le(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`)")}Wo();import{readFileSync as UC}from"node:fs";F();Ge();Ut();Go();Ir();Vt();Tr();je();me();function ve(t){throw new Error(t)}function Ce(t,e){return(typeof t!="string"||t.trim().length===0)&&ve(`config: '${e}' must be a non-empty string`),t.trim()}function zo(t,e){if(t==null)return;typeof t!="string"&&ve(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function BC(t){(!t||typeof t!="object")&&ve("config: expected a JSON object");let e=t,r=Ce(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||ve("config: 'hubUrl' must start with http(s)://");let n=Ce(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&ve("config: 'project' is required");let i=o,s=Ce(i.id,"project.id");Wt.test(s)||ve("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=Ce(i.name,"project.name"),c=Ce(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&ve("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||ve("config: 'project.repos' must be an array");let u=l.map((w,$)=>{(!w||typeof w!="object")&&ve(`config: project.repos[${$}] must be an object`);let S=w,T=Ce(S.host,`project.repos[${$}].host`);T!=="github"&&T!=="bitbucket"&&T!=="gitlab"&&ve(`config: project.repos[${$}].host must be 'github', 'bitbucket' or 'gitlab'`);let v={name:Ce(S.name,`project.repos[${$}].name`),host:T,owner:Ce(S.owner,`project.repos[${$}].owner`),repoName:Ce(S.repoName,`project.repos[${$}].repoName`)},b=zo(S.defaultBranch,`project.repos[${$}].defaultBranch`);b&&(v.defaultBranch=b);let R=zo(S.mountAs,`project.repos[${$}].mountAs`);return R&&(v.mountAs=R),v}),p=i.contextRepo;(!p||typeof p!="object")&&ve("config: 'project.contextRepo' is required");let d=p,m=zo(d.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&ve("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:m,owner:Ce(d.owner,"project.contextRepo.owner"),name:zo(d.name,"project.contextRepo.name")??xt(s)},g={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:f}},k=zo(i.youtrackProjectKey,"project.youtrackProjectKey");if(k&&(g.project.youtrackProjectKey=k),i.index!==void 0&&(typeof i.index!="boolean"&&ve("config: 'project.index' must be a boolean"),g.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&ve("config: 'project.youtrackWrites' must be a boolean"),g.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let w=Ce(i.llmProvider,"project.llmProvider");w==="codex"&&ve(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),w!=="claude"&&ve("config: 'project.llmProvider' must be 'claude'"),g.project.llmProvider=w}let h=e.secrets;if(h!==void 0){(typeof h!="object"||h===null)&&ve("config: 'secrets' must be an object");let w=h,$={};if(w.github){let S=w.github;$.github={token:Ce(S.token,"secrets.github.token")}}if(w.bitbucket){let S=w.bitbucket;$.bitbucket={email:Ce(S.email,"secrets.bitbucket.email"),apiToken:Ce(S.apiToken,"secrets.bitbucket.apiToken")}}if(w.gitlab){let S=w.gitlab;$.gitlab={token:Ce(S.token,"secrets.gitlab.token")}}if(w.youtrack){let S=w.youtrack;$.youtrack={url:Ce(S.url,"secrets.youtrack.url").replace(/\/$/,""),token:Ce(S.token,"secrets.youtrack.token")}}if(w.contextWrite){let S=w.contextWrite;$.contextWrite={token:Ce(S.token,"secrets.contextWrite.token")}}g.secrets=$}return g}async function FC(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function GC(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await qt(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 Yt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await yi(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 zt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Jt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function wk(t){let e=!t.configPath||t.configPath==="-"?await FC():UC(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){ve(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=BC(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 GC(n));let a={projectId:s.id,name:s.name,automationLevel:s.automationLevel,repos:s.repos};s.youtrackProjectKey&&(a.youtrackProjectKey=s.youtrackProjectKey),console.log(`provisioning Context Repo ${s.contextRepo.owner}/${s.contextRepo.name} (${s.contextRepo.host})\u2026`);let c=n.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,l;try{l=await Nn(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??tn(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){ve(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let u;try{u=await or(o,i,a)}catch(d){if(d instanceof K&&d.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await se(o,i,s.id);else if(d instanceof K)ve(`HUB \u2192 ${d.status} ${d.message}`);else throw d}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let p={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(ae(p),Mt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${St(s.id)}`),Qt(s.id,Tt(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,s.llmProvider??Xe),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await jo(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();me();import{cancel as kk,intro as bk,isCancel as $k,log as tu,outro as KC,password as vk}from"@clack/prompts";async function HC(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function xk(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await HC(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){bk("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),tu.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await vk({message:"Claude OAuth token"});$k(i)&&(kk("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Xd({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${di()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=st(t.profile);if(!e){bk(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),tu.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await vk({message:"Claude OAuth token"});$k(i)&&(kk("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=q(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},ae(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(tu.success("Claude OAuth token saved."),KC("It will be sealed into job bundles when a SANDBOX (re)connects."))}No();F();Ge();Ut();Go();Ir();Es();je();me();import{cancel as WC,confirm as qC,intro as YC,isCancel as Sk,log as Me,outro as zC,select as Ek,text as pr}from"@clack/prompts";function Tk(t){WC(t),process.exit(1)}function Un(t){return Sk(t)&&Tk("aborted"),t}function Vo(t){return Sk(t)&&Tk("aborted"),typeof t=="string"?t:""}async function VC(t,e){let r=Un(await Ek({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=Vo(await pr({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=Vo(await pr({message:"Context Repo name",placeholder:xt(t),initialValue:xt(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function Rk(t={profile:void 0}){let e=st(t.profile);YC(`codepipe project add \u2192 ${e.hubUrl}`);let r=Un(await pr({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>Wt.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=Un(await pr({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=Un(await Ek({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=Un(await pr({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Un(await qC({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=Vo(await pr({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:h=>!h||!h.trim()||qe(h)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!d)break;let m=qe(d);Me.message(`${m.host}: ${m.owner}/${m.repoName}`);let f=Vo(await pr({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:h=>h.trim().length>0?void 0:"required"})).trim(),g=Vo(await pr({message:"default branch (optional)",placeholder:"main"})).trim(),k={name:f,host:m.host,owner:m.owner,repoName:m.repoName};g&&(k.defaultBranch=g),a.push(k)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await VC(r,a),u=q(e.projectId);Me.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await Nn(c,l,{githubToken:u?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:u?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:u?.bitbucket??tn(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:d=>Me.message(d),warn:d=>Me.warn(d)}})}catch(d){Me.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,Me.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await or(e.hubUrl,e.cliToken,c);Me.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),Qt(r,Tt(c,s,u?.youtrack?.url),{info:m=>Me.message(m),warn:m=>Me.warn(m)}),d.contextRepo&&(Me.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),Me.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&Me.error(` error: ${d.provisioningError}`),zC("done")}catch(d){d instanceof K?(Me.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&Me.message(JSON.stringify(d.payload,null,2))):Me.error(d instanceof Error?d.message:String(d)),process.exit(1)}}jn();Ge();je();me();it();Wo();import{existsSync as XC,rmSync as JC}from"node:fs";import{confirm as ZC,intro as QC,isCancel as eP,log as fr,outro as tP,spinner as rP}from"@clack/prompts";function Pt(t){fr.error(t),process.exit(1)}var Ik=t=>t.trim().replace(/\/+$/,"");async function Ck(t){QC("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Ae()?.spec.projectId??void 0;e||Pt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=wt(e);r||Pt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Ik(r.hubUrl),o=r.projectId,i=Ik(t.hub);i.startsWith("http")||Pt("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&Pt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let h=rP();h.start(`reading project ${o} from ${n}\u2026`);try{l=await se(n,r.cliToken,o),h.stop(`read project ${o} (${l.name})`)}catch(w){throw h.stop("could not read the source project",1),w instanceof K&&Pt(`source HUB ${n} \u2192 ${w.status} ${w.message}. The source HUB must be reachable with a valid token to move a project.`),w}}l.contextRepo||Pt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=q(o),p=(t.account??r.accountEmail??await Mn()).trim().toLowerCase();if(fr.message(`move project '${o}'
967
970
  from : ${n} (profile ${e})
968
971
  to : ${i} (profile ${s}, project ${a}, account ${p})
969
972
  \u2022 the source registration on the old HUB is left intact (non-destructive)
970
973
  \u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
971
- `+(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 h=await zC({message:"Continue?",initialValue:!0});(XC(h)||!h)&&Pt("aborted")}!c&&a===o&&pr.warn(`source and destination share the same project id, so they share one secrets file (${St(a)}). Running both profiles at the same time will conflict \u2014 pass --project <newId> for a parallel setup, or keep only one active.`);let{cliToken:d,accountEmail:m}=await Mn(i,p),f={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:m,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};pr.step(`registering project on ${i}\u2026`);let g;try{g=await nr(i,d,f)}catch(h){if(h instanceof K&&h.status===409){pr.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{g=await se(i,d,a)}catch(w){throw w instanceof K&&Pt(`target HUB \u2192 ${w.status} ${w.message}`),w}}else if(h instanceof K&&h.status===403)Pt(`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(h instanceof K)Pt(`target HUB \u2192 ${h.status} ${h.message}`);else throw h}pr.success(`project ${g.projectId} ready on ${i} (${g.provisioningStatus})`),Mt({hubUrl:i,cliToken:d,projectId:a,accountEmail:m},s);let k={...u??{},hubUrl:i,cliToken:d,projectId:a};if(delete k.sandboxPins,ae(k),pr.success(`profile '${s}' \u2192 ${St(a)}`),c){let h=$t(s);qC(h)&&(YC(h),pr.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}JC(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}Ge();import{existsSync as eu,rmSync as QC,statSync as eP}from"node:fs";import{join as Os,relative as tP,resolve as rP}from"node:path";import{cancel as nP,intro as Ck,isCancel as oP,log as Ee,outro as Pk,text as Or}from"@clack/prompts";import{simpleGit as Ak}from"simple-git";Ss();je();ko();fe();it();function et(t){nP(t),process.exit(1)}function Lr(t){return oP(t)&&et("aborted"),typeof t=="string"?t:""}async function Rk(t){try{let e=await Ak(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function iP(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function sP(t,e){let r=q(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(iP(r,e)){Ee.message(`reusing existing ${e} credentials`);return}if(Ee.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=Lr(await Or({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=Lr(await Or({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=Lr(await Or({message:`${e} access token (read access to the repo)`,validate:o=>o.trim()?void 0:"required"})).trim();e==="github"?r.github={token:n}:r.gitlab={token:n}}ae(r),Ee.success(`saved ${e} credentials`)}async function _k(t){let e=st(t.profile);Ck(`codepipe repo add \u2192 project ${e.projectId}`);let r=Ae()??void 0,n;try{n=(await se(e.hubUrl,e.cliToken,e.projectId)).repos}catch(w){et(`could not read project from HUB: ${w instanceof Error?w.message:String(w)}`)}let o=t.target?.trim();if(!o){let w=await Rk(process.cwd());w?(o=process.cwd(),Ee.message(`using the current directory (${w})`)):o=Lr(await Or({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:$=>$.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(eu(o)&&eP(o).isDirectory()){i=rP(o);let w=await Rk(i);w||et(`${i} is not a git repository (no origin remote)`);let $=qe(w);$||et(`origin ${w} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=$,s=w,Ee.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let w=qe(o);w||et(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=w,s=o,Ee.message(`${a}: ${c}/${l}`)}let u=Lr(await Or({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:w=>w.trim()?void 0:"required"})).trim();n.some(w=>w.name===u)&&et(`a repo named "${u}" is already registered`);let p=Lr(await Or({message:"default branch (optional)",placeholder:"main"})).trim(),d=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let w=tP(r.root,i);d=w===""?".":w}let m=Lr(await Or({message:"mount_as (directory relative to the workspace root)",placeholder:d,initialValue:d})).trim()||d;n.some(w=>(w.mountAs??w.name)===m)&&et(`mount_as "${m}" is already used by another repo`),await sP(e,a);let f={name:u,host:a,owner:c,repoName:l,mountAs:m,...p?{defaultBranch:p}:{}};if(!i){let w=r?Os(r.root,m):_e(e.projectId,u);if(eu(Os(w,".git")))Ee.message(`already cloned at ${w}`);else{Ee.info(`cloning ${s} \u2192 ${w} \u2026`);try{await Ak().clone(s,w),Ee.success(`cloned into ${w}`)}catch($){et(`clone failed: ${$ instanceof Error?$.message.trim():String($)}
972
- check that your ${a} credentials grant read access to ${c}/${l}`)}}}let g;try{g=await mh(e.hubUrl,e.cliToken,e.projectId,f)}catch(w){w instanceof K&&et(`HUB \u2192 ${w.status} ${w.message}`),et(w instanceof Error?w.message:String(w))}let{updated:k,errors:h}=wo(e.projectId,g.repos,r?.contextDir);for(let w of k)Ee.message(`updated ${w}`);for(let w of h)Ee.warn(`could not update ${w.path}: ${w.error}`);Ee.success(`added "${u}" \u2014 project now has ${g.repos.length} repo(s)`),Pk("done")}async function jk(t){let e=st(t.profile);Ck(`codepipe repo remove \u2192 project ${e.projectId}`);let r=Ae()??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 hh(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof K&&(a.status===404&&et(`no repo named "${t.name}" in this project`),et(`HUB \u2192 ${a.status} ${a.message}`)),et(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=wo(e.projectId,o.repos,r?.contextDir);for(let a of i)Ee.message(`updated ${a}`);for(let a of s)Ee.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")Ee.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?Os(r.root,n):_e(e.projectId,t.name);if(eu(Os(a,".git")))try{QC(a,{recursive:!0,force:!0}),Ee.message(`deleted local clone ${a}`)}catch(c){Ee.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else Ee.message(`no local clone found to purge (${a})`)}Ee.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),Pk("done")}async function Nk(t){let e=st(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}`)}}Ts();F();Ge();Si();je();it();it();import{existsSync as Ok}from"node:fs";import{join as tu}from"node:path";import{simpleGit as ru}from"simple-git";var aP=60;async function Lk(t){let{cfg:e}=Zr(t.profile),r=Xr(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=async()=>{let s=await gh(e.hubUrl,e.cliToken,e.projectId);if(s.length===0){console.log("[pull] nothing ready yet");return}for(let a of s)await cP(r.root,r.spec.repos,a,n);if(await pP(r.contextDir),r.contextDir)try{cn(r.contextDir,r.root,{info:a=>console.log(`[pull] ${a}`),warn:a=>console.warn(`[pull] ${a}`)})}catch(a){console.warn(`[pull] skills materialize failed \u2014 ${a instanceof Error?a.message:String(a)}`)}};if(!t.watch){await o();return}try{await o()}catch(s){console.warn(`[pull] ${s instanceof Error?s.message:String(s)}`)}let i=Math.max(10,t.intervalSec??aP)*1e3;for(console.log(`[pull] watching \u2014 every ${Math.round(i/1e3)}s, Ctrl+C to stop`);;){await new Promise(s=>setTimeout(s,i));try{await o()}catch(s){console.warn(`[pull] ${s instanceof Error?s.message:String(s)}`)}}}async function cP(t,e,r,n){for(let o of r.repos){let i=e.find(l=>l.name===o.repoName);if(!i)continue;let s=`${r.taskKey}:${i.name}:${o.branchName}`;if(!oo(o.branchName)){n.has(s)||(n.add(s),console.warn(`[pull] ${r.taskKey} ${i.mountAs}: refusing suspicious branch name`));continue}let a=tu(t,i.mountAs);if(!Ok(tu(a,".git")))continue;let c=ru(a);try{let l=await dP(c,o.branchName);await c.fetch(await lP(c,i),`refs/heads/${o.branchName}`);let u=(await c.revparse(["FETCH_HEAD"])).trim();if(l===u)continue;if(await uP(c,a,o.branchName)){n.has(s)||(n.add(s),console.log(`[pull] ${r.taskKey} \u2192 ${i.mountAs}: ${o.branchName} is checked out here \u2014 fetched ${u.slice(0,10)}; merge or pull it in that checkout yourself`));continue}await c.raw(["branch","-f",o.branchName,u]),console.log(`[pull] ${r.taskKey} \u2192 ${i.mountAs}: ${o.branchName} ${u.slice(0,10)} (checkout untouched)`)}catch(l){if(n.has(s))continue;n.add(s),console.warn(`[pull] ${r.taskKey} ${i.mountAs}: ${o.branchName} unavailable \u2014 `+(l instanceof Error?l.message.split(`
973
- `)[0]:String(l)))}}}async function lP(t,e){if(e.mirror){let r=e.mirror;return r.host==="github"?`git@github.com:${r.owner}/${r.repoName}.git`:r.host==="gitlab"?`git@gitlab.com:${r.owner}/${r.repoName}.git`:`git@bitbucket.org:${r.owner}/${r.repoName}.git`}try{if((await t.getRemotes(!0)).find(n=>n.name==="origin")?.refs?.fetch)return"origin"}catch{}return si(e)}async function uP(t,e,r){try{return(await t.raw(["worktree","list","--porcelain"])).split(`
974
- `).some(o=>o.trim()===`branch refs/heads/${r}`)}catch{try{return(await ru(e).revparse(["--abbrev-ref","HEAD"])).trim()===r}catch{return!1}}}async function dP(t,e){try{return(await t.revparse([e])).trim()}catch{return null}}async function pP(t){if(!(!t||!Ok(tu(t,".git"))))try{await ru(t).pull(["--ff-only"])}catch(e){console.warn(`[pull] context repo not updated \u2014 ${e instanceof Error?e.message.split(`
975
- `)[0]:String(e)}`)}}As();import{existsSync as Fk,mkdirSync as fP,readFileSync as mP,writeFileSync as hP}from"node:fs";import{homedir as gP}from"node:os";import{dirname as yP,join as Gk}from"node:path";import*as Bn from"node:readline";je();Ri();fe();it();Ts();As();var Ls=Gk(gP(),".codepipe","history"),Mk=["/help","/status","/tasks","/task","/sync","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Kk=500,Dk=40;async function Hk(t={}){let e=Ae();e||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let r=q(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)),co(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=Bn.createInterface({input:process.stdin,output:process.stdout,completer:wP,history:jP(),removeHistoryDuplicates:!0}),o={ws:e,secrets:r,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};Sf(i=>fr(o,i)),o.daemon=ss({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:i=>fr(o,i),warn:i=>fr(o,i)},onEvent:i=>CP(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 Rs(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=Cs({entry:s,profile:t.profile,onLine:c=>fr(o,`[worker] ${c}`)});a.on("exit",(c,l)=>{o.workerExited=!0,!iu&&Un(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.`)}ou(o),n.prompt(),n.on("line",async i=>{let s=i.trim();if(s.length>0)try{if(await kP(o,s)){Bk(o);return}}catch(a){console.error(a instanceof Error?a.message:String(a))}o.unread=0,ou(o),n.prompt()}),n.on("close",()=>{Bk(o)})}function wP(t){let e=Mk.filter(r=>r.startsWith(t));return[e.length?e:Mk,t]}async function kP(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return bP(),!1;case"/status":return await $P(t),!1;case"/tasks":return await vP(t,n),!1;case"/task":return await xP(t,n),!1;case"/sync":return await SP(t),!1;case"/logs":return PP(t,n),!1;case"/monitor":return AP(t),!1;case"/approve":return await Uk(t,n,"approve"),!1;case"/merge":return await Uk(t,n,"merge"),!1;case"/login":return EP(t,n),!1;case"/secret":return TP(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function bP(){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(`
976
- `))}async function $P(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=Fk(Gk(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function vP(t,e){let r=_P(e,"--phase");try{let n=await dh(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){su(n)}}async function xP(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await ph(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){su(n)}}async function SP(t){let e=await Go(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 Uk(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await fh(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){su(o)}}function EP(t,e){let r=e.join(" ").trim();if(!r){console.log("usage: /login <claude-oauth-token>"),console.log(" get one with `claude setup-token`, then paste it here."),console.log(" (this line is scrubbed from history; takes effect on next SANDBOX reconnect)");return}t.secrets.claude={oauthToken:r},ae(t.secrets),console.log(" Claude OAuth token saved. It will be sealed into job bundles for SANDBOXes."),console.log(" Re-seal happens when a SANDBOX (re)connects; restart it if you need it now.")}function TP(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(`
977
- `)}`:" (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}IP(t.secrets,n,i),ae(t.secrets),co(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}RP(t.secrets,n),ae(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function IP(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 RP(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 CP(t,e){switch(e.kind){case"connected":t.connection="connecting",fr(t,"[hub] connected");break;case"registered":t.connection="registered",fr(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Un(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",fr(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Un(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Un(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?fr(t,`[hub] action ${e.actionType} done`):Un(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function fr(t,e){t.logBuffer.push(e),t.logBuffer.length>Kk&&t.logBuffer.shift(),t.follow&&Un(t,e)}function PP(t,e){let r=e[0];if(r==="follow"||r==="on"){nu(t,!0);return}if(r==="off"){nu(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(Kk,Number(r)||Dk)):Dk,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 AP(t){nu(t,!t.follow)}function nu(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Un(t,e){Bn.cursorTo(process.stdout,0),Bn.clearLine(process.stdout,0),process.stdout.write(e+`
978
- `),t.unread+=1,ou(t),t.rl.prompt(!0)}function ou(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var iu=!1;function Bk(t){if(iu)return;iu=!0,NP(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
974
+ `+(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 h=await ZC({message:"Continue?",initialValue:!0});(eP(h)||!h)&&Pt("aborted")}!c&&a===o&&fr.warn(`source and destination share the same project id, so they share one secrets file (${St(a)}). Running both profiles at the same time will conflict \u2014 pass --project <newId> for a parallel setup, or keep only one active.`);let{cliToken:d,accountEmail:m}=await Dn(i,p),f={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:m,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};fr.step(`registering project on ${i}\u2026`);let g;try{g=await or(i,d,f)}catch(h){if(h instanceof K&&h.status===409){fr.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{g=await se(i,d,a)}catch(w){throw w instanceof K&&Pt(`target HUB \u2192 ${w.status} ${w.message}`),w}}else if(h instanceof K&&h.status===403)Pt(`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(h instanceof K)Pt(`target HUB \u2192 ${h.status} ${h.message}`);else throw h}fr.success(`project ${g.projectId} ready on ${i} (${g.provisioningStatus})`),Mt({hubUrl:i,cliToken:d,projectId:a,accountEmail:m},s);let k={...u??{},hubUrl:i,cliToken:d,projectId:a};if(delete k.sandboxPins,ae(k),fr.success(`profile '${s}' \u2192 ${St(a)}`),c){let h=$t(s);XC(h)&&(JC(h),fr.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}tP(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}Ge();import{existsSync as ru,rmSync as nP,statSync as oP}from"node:fs";import{join as Ls,relative as iP,resolve as sP}from"node:path";import{cancel as aP,intro as Ak,isCancel as cP,log as Ee,outro as _k,text as Lr}from"@clack/prompts";import{simpleGit as jk}from"simple-git";Es();je();bo();me();it();function et(t){aP(t),process.exit(1)}function Mr(t){return cP(t)&&et("aborted"),typeof t=="string"?t:""}async function Pk(t){try{let e=await jk(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function lP(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function uP(t,e){let r=q(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(lP(r,e)){Ee.message(`reusing existing ${e} credentials`);return}if(Ee.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=Mr(await Lr({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=Mr(await Lr({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=Mr(await Lr({message:`${e} access token (read access to the repo)`,validate:o=>o.trim()?void 0:"required"})).trim();e==="github"?r.github={token:n}:r.gitlab={token:n}}ae(r),Ee.success(`saved ${e} credentials`)}async function Nk(t){let e=st(t.profile);Ak(`codepipe repo add \u2192 project ${e.projectId}`);let r=Ae()??void 0,n;try{n=(await se(e.hubUrl,e.cliToken,e.projectId)).repos}catch(w){et(`could not read project from HUB: ${w instanceof Error?w.message:String(w)}`)}let o=t.target?.trim();if(!o){let w=await Pk(process.cwd());w?(o=process.cwd(),Ee.message(`using the current directory (${w})`)):o=Mr(await Lr({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:$=>$.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(ru(o)&&oP(o).isDirectory()){i=sP(o);let w=await Pk(i);w||et(`${i} is not a git repository (no origin remote)`);let $=qe(w);$||et(`origin ${w} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=$,s=w,Ee.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let w=qe(o);w||et(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=w,s=o,Ee.message(`${a}: ${c}/${l}`)}let u=Mr(await Lr({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:w=>w.trim()?void 0:"required"})).trim();n.some(w=>w.name===u)&&et(`a repo named "${u}" is already registered`);let p=Mr(await Lr({message:"default branch (optional)",placeholder:"main"})).trim(),d=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let w=iP(r.root,i);d=w===""?".":w}let m=Mr(await Lr({message:"mount_as (directory relative to the workspace root)",placeholder:d,initialValue:d})).trim()||d;n.some(w=>(w.mountAs??w.name)===m)&&et(`mount_as "${m}" is already used by another repo`),await uP(e,a);let f={name:u,host:a,owner:c,repoName:l,mountAs:m,...p?{defaultBranch:p}:{}};if(!i){let w=r?Ls(r.root,m):_e(e.projectId,u);if(ru(Ls(w,".git")))Ee.message(`already cloned at ${w}`);else{Ee.info(`cloning ${s} \u2192 ${w} \u2026`);try{await jk().clone(s,w),Ee.success(`cloned into ${w}`)}catch($){et(`clone failed: ${$ instanceof Error?$.message.trim():String($)}
975
+ check that your ${a} credentials grant read access to ${c}/${l}`)}}}let g;try{g=await yh(e.hubUrl,e.cliToken,e.projectId,f)}catch(w){w instanceof K&&et(`HUB \u2192 ${w.status} ${w.message}`),et(w instanceof Error?w.message:String(w))}let{updated:k,errors:h}=ko(e.projectId,g.repos,r?.contextDir);for(let w of k)Ee.message(`updated ${w}`);for(let w of h)Ee.warn(`could not update ${w.path}: ${w.error}`);Ee.success(`added "${u}" \u2014 project now has ${g.repos.length} repo(s)`),_k("done")}async function Ok(t){let e=st(t.profile);Ak(`codepipe repo remove \u2192 project ${e.projectId}`);let r=Ae()??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 wh(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof K&&(a.status===404&&et(`no repo named "${t.name}" in this project`),et(`HUB \u2192 ${a.status} ${a.message}`)),et(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=ko(e.projectId,o.repos,r?.contextDir);for(let a of i)Ee.message(`updated ${a}`);for(let a of s)Ee.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")Ee.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?Ls(r.root,n):_e(e.projectId,t.name);if(ru(Ls(a,".git")))try{nP(a,{recursive:!0,force:!0}),Ee.message(`deleted local clone ${a}`)}catch(c){Ee.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else Ee.message(`no local clone found to purge (${a})`)}Ee.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),_k("done")}async function Lk(t){let e=st(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}`)}}Rs();F();Ge();Ti();je();it();it();import{existsSync as Mk}from"node:fs";import{join as nu}from"node:path";import{simpleGit as ou}from"simple-git";var dP=60;async function Dk(t){let{cfg:e}=Qr(t.profile),r=Jr(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=async()=>{let s=await kh(e.hubUrl,e.cliToken,e.projectId);if(s.length===0){console.log("[pull] nothing ready yet");return}for(let a of s)await pP(r.root,r.spec.repos,a,n);if(await gP(r.contextDir),r.contextDir)try{ln(r.contextDir,r.root,{info:a=>console.log(`[pull] ${a}`),warn:a=>console.warn(`[pull] ${a}`)})}catch(a){console.warn(`[pull] skills materialize failed \u2014 ${a instanceof Error?a.message:String(a)}`)}};if(!t.watch){await o();return}try{await o()}catch(s){console.warn(`[pull] ${s instanceof Error?s.message:String(s)}`)}let i=Math.max(10,t.intervalSec??dP)*1e3;for(console.log(`[pull] watching \u2014 every ${Math.round(i/1e3)}s, Ctrl+C to stop`);;){await new Promise(s=>setTimeout(s,i));try{await o()}catch(s){console.warn(`[pull] ${s instanceof Error?s.message:String(s)}`)}}}async function pP(t,e,r,n){for(let o of r.repos){let i=e.find(l=>l.name===o.repoName);if(!i)continue;let s=`${r.taskKey}:${i.name}:${o.branchName}`;if(!io(o.branchName)){n.has(s)||(n.add(s),console.warn(`[pull] ${r.taskKey} ${i.mountAs}: refusing suspicious branch name`));continue}let a=nu(t,i.mountAs);if(!Mk(nu(a,".git")))continue;let c=ou(a);try{let l=await hP(c,o.branchName);await c.fetch(await fP(c,i),`refs/heads/${o.branchName}`);let u=(await c.revparse(["FETCH_HEAD"])).trim();if(l===u)continue;if(await mP(c,a,o.branchName)){n.has(s)||(n.add(s),console.log(`[pull] ${r.taskKey} \u2192 ${i.mountAs}: ${o.branchName} is checked out here \u2014 fetched ${u.slice(0,10)}; merge or pull it in that checkout yourself`));continue}await c.raw(["branch","-f",o.branchName,u]),console.log(`[pull] ${r.taskKey} \u2192 ${i.mountAs}: ${o.branchName} ${u.slice(0,10)} (checkout untouched)`)}catch(l){if(n.has(s))continue;n.add(s),console.warn(`[pull] ${r.taskKey} ${i.mountAs}: ${o.branchName} unavailable \u2014 `+(l instanceof Error?l.message.split(`
976
+ `)[0]:String(l)))}}}async function fP(t,e){if(e.mirror){let r=e.mirror;return r.host==="github"?`git@github.com:${r.owner}/${r.repoName}.git`:r.host==="gitlab"?`git@gitlab.com:${r.owner}/${r.repoName}.git`:`git@bitbucket.org:${r.owner}/${r.repoName}.git`}try{if((await t.getRemotes(!0)).find(n=>n.name==="origin")?.refs?.fetch)return"origin"}catch{}return ci(e)}async function mP(t,e,r){try{return(await t.raw(["worktree","list","--porcelain"])).split(`
977
+ `).some(o=>o.trim()===`branch refs/heads/${r}`)}catch{try{return(await ou(e).revparse(["--abbrev-ref","HEAD"])).trim()===r}catch{return!1}}}async function hP(t,e){try{return(await t.revparse([e])).trim()}catch{return null}}async function gP(t){if(!(!t||!Mk(nu(t,".git"))))try{await ou(t).pull(["--ff-only"])}catch(e){console.warn(`[pull] context repo not updated \u2014 ${e instanceof Error?e.message.split(`
978
+ `)[0]:String(e)}`)}}_s();import{existsSync as Kk,mkdirSync as yP,readFileSync as wP,writeFileSync as kP}from"node:fs";import{homedir as bP}from"node:os";import{dirname as $P,join as Hk}from"node:path";import*as Fn from"node:readline";je();Pi();me();it();Rs();_s();var Ms=Hk(bP(),".codepipe","history"),Uk=["/help","/status","/tasks","/task","/sync","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Wk=500,Bk=40;async function qk(t={}){let e=Ae();e||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let r=q(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)),lo(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=Fn.createInterface({input:process.stdin,output:process.stdout,completer:vP,history:MP(),removeHistoryDuplicates:!0}),o={ws:e,secrets:r,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};Tf(i=>mr(o,i)),o.daemon=as({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:i=>mr(o,i),warn:i=>mr(o,i)},onEvent:i=>jP(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 Cs(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=Ps({entry:s,profile:t.profile,onLine:c=>mr(o,`[worker] ${c}`)});a.on("exit",(c,l)=>{o.workerExited=!0,!au&&Bn(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.`)}su(o),n.prompt(),n.on("line",async i=>{let s=i.trim();if(s.length>0)try{if(await xP(o,s)){Gk(o);return}}catch(a){console.error(a instanceof Error?a.message:String(a))}o.unread=0,su(o),n.prompt()}),n.on("close",()=>{Gk(o)})}function vP(t){let e=Uk.filter(r=>r.startsWith(t));return[e.length?e:Uk,t]}async function xP(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return SP(),!1;case"/status":return await EP(t),!1;case"/tasks":return await TP(t,n),!1;case"/task":return await RP(t,n),!1;case"/sync":return await IP(t),!1;case"/logs":return NP(t,n),!1;case"/monitor":return OP(t),!1;case"/approve":return await Fk(t,n,"approve"),!1;case"/merge":return await Fk(t,n,"merge"),!1;case"/login":return CP(t,n),!1;case"/secret":return PP(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function SP(){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(`
979
+ `))}async function EP(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=Kk(Hk(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function TP(t,e){let r=LP(e,"--phase");try{let n=await mh(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){cu(n)}}async function RP(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await hh(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){cu(n)}}async function IP(t){let e=await Ho(t.ws.root,t.ws.spec.repos);for(let r of e)console.log(` ${r.mountAs}: ${r.status}${r.detail?` \u2014 ${r.detail}`:""}`)}async function Fk(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await gh(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){cu(o)}}function CP(t,e){let r=e.join(" ").trim();if(!r){console.log("usage: /login <claude-oauth-token>"),console.log(" get one with `claude setup-token`, then paste it here."),console.log(" (this line is scrubbed from history; takes effect on next SANDBOX reconnect)");return}t.secrets.claude={oauthToken:r},ae(t.secrets),console.log(" Claude OAuth token saved. It will be sealed into job bundles for SANDBOXes."),console.log(" Re-seal happens when a SANDBOX (re)connects; restart it if you need it now.")}function PP(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(`
980
+ `)}`:" (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}AP(t.secrets,n,i),ae(t.secrets),lo(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}_P(t.secrets,n),ae(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function AP(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 _P(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 jP(t,e){switch(e.kind){case"connected":t.connection="connecting",mr(t,"[hub] connected");break;case"registered":t.connection="registered",mr(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Bn(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",mr(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Bn(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Bn(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?mr(t,`[hub] action ${e.actionType} done`):Bn(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function mr(t,e){t.logBuffer.push(e),t.logBuffer.length>Wk&&t.logBuffer.shift(),t.follow&&Bn(t,e)}function NP(t,e){let r=e[0];if(r==="follow"||r==="on"){iu(t,!0);return}if(r==="off"){iu(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(Wk,Number(r)||Bk)):Bk,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 OP(t){iu(t,!t.follow)}function iu(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Bn(t,e){Fn.cursorTo(process.stdout,0),Fn.clearLine(process.stdout,0),process.stdout.write(e+`
981
+ `),t.unread+=1,su(t),t.rl.prompt(!0)}function su(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var au=!1;function Gk(t){if(au)return;au=!0,DP(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
979
982
  bye.`),setTimeout(()=>process.exit(0),150);return}console.log(`
980
- 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 _P(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function su(t){t instanceof K?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function jP(){if(!Fk(Ls))return[];try{return mP(Ls,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function NP(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{fP(yP(Ls),{recursive:!0}),hP(Ls,r.slice().reverse().join(`
983
+ 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 LP(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function cu(t){t instanceof K?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function MP(){if(!Kk(Ms))return[];try{return wP(Ms,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function DP(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{yP($P(Ms),{recursive:!0}),kP(Ms,r.slice().reverse().join(`
981
984
  `)+`
982
- `)}catch{}}_n();F();Fe();_n();Ge();je();Ko();import{hostname as OP}from"node:os";import{cancel as LP,confirm as Wk,intro as MP,isCancel as zk,log as Fn,multiselect as DP,outro as qk,password as UP,select as au,text as cu}from"@clack/prompts";function zo(t){LP(t),process.exit(1)}function Gn(t){return zk(t)&&zo("aborted"),t}function Ms(t){return zk(t)&&zo("aborted"),typeof t=="string"?t:""}function Ds(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Yk(t,e){try{let{secret:r}=await Qi(t,e);return r}catch(r){throw r instanceof K&&r.status===404&&zo("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 BP(t,e){if(Gn(await au({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 rl(t,e);if(o.length>0)return Gn(await DP({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}));Fn.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Fn.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return Ms(await cu({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 lu(t){MP("codepipe worker \u2014 set up this machine as a runner");let e=Le(t.profile);e&&(Fn.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Gn(await Wk({message:"re-register this worker?",initialValue:!1}))||zo("keeping the existing registration"));let r=wt(t.profile)??wt(),n=Ms(await cu({message:"HUB URL",placeholder:mt,initialValue:V("HUB_URL")??r?.hubUrl??mt,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=Gn(await au({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 Yk(n,a),Fn.success("account-issued registration token minted");else if(i==="login"){let d=await Ln();a=(await Mn(n,d)).cliToken,s=await Yk(n,a),Fn.success("account-issued registration token minted")}else s=Ms(await UP({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||zo("a registration token is required");let c=await BP(n,a),l=Ms(await cu({message:"worker name",initialValue:OP(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=Gn(await au({message:"agent backend",options:[{value:"claude-headless",label:"claude-headless \u2014 Claude Code on PATH (the real thing)"},{value:"mock",label:"mock \u2014 deterministic stub (development)"},{value:"",label:"none \u2014 this worker will not claim agent jobs"}],initialValue:"claude-headless"}));if(await _r({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Fn.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Gn(await Wk({message:"start the claim-loop now?",initialValue:!0}))){qk("registered. start later with `codepipe worker`.");return}qk("starting the claim-loop\u2026"),await Uo(t.profile?{profile:t.profile}:{})}function GP(){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 V("PROFILE")}var be=GP();Ld(be);var De=new FP;De.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Ve).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{Ds()?await Hk({profile:be}):await Ps({profile:be})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});De.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await gk({configPath:t.config,skipVerify:t.skipVerify===!0}):await ok({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","Personal CLI token (issued during `codepipe init`)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await Vd({...t,profile:be})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await ik({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});De.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await lg({profile:be})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});De.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await Fw({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("login").description("Set the Claude OAuth token (sealed into job bundles)").option("--token <token>","Provide the token non-interactively").option("--shared","Save to the machine/farm-wide ~/.codepipe/shared.json instead of this project").option("--stdin","Read the token from stdin (for scripted/ssh delivery)").action(async t=>{try{await $k({profile:be,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await dw({profile:be})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});De.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 Lk({profile:t.profile,...t.watch?{watch:!0}:{},...Number.isFinite(t.interval)?{intervalSec:t.interval}:{}})});De.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).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 Ps({profile:be,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Vk=De.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Vk.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??V("HUB_URL")??wt(be)?.hubUrl??mt,r=t.token??V("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Ds()){await lu({profile:be});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=V("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??V("WORKER_NAME"),i=t.llm??V("WORKER_LLM");await _r({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...be?{profile:be}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Vk.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!Le(be)&&Ds()){await lu({profile:be});return}await Uo(be?{profile:be}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Xk=De.command("project").description("Manage CodePipe projects");Xk.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Ek({profile:be})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Xk.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 Ik({...t,cliProfile:be})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var uu=De.command("repo").description("Manage the project's git repositories");uu.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 _k({profile:be,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});uu.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 jk({profile:be,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});uu.command("list").description("List the project's repos").action(async()=>{try{await Nk({profile:be})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Jk=De.command("model").description("Project map (model/ in the Context Repo)");Jk.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 fl({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Jk.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 ml({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.parseAsync();
985
+ `)}catch{}}jn();F();Fe();jn();Ge();je();Wo();import{hostname as UP}from"node:os";import{cancel as BP,confirm as Yk,intro as FP,isCancel as Xk,log as Gn,multiselect as GP,outro as zk,password as KP,select as lu,text as uu}from"@clack/prompts";function Xo(t){BP(t),process.exit(1)}function Kn(t){return Xk(t)&&Xo("aborted"),t}function Ds(t){return Xk(t)&&Xo("aborted"),typeof t=="string"?t:""}function Us(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Vk(t,e){try{let{secret:r}=await es(t,e);return r}catch(r){throw r instanceof K&&r.status===404&&Xo("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 HP(t,e){if(Kn(await lu({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 nl(t,e);if(o.length>0)return Kn(await GP({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}));Gn.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Gn.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return Ds(await uu({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 du(t){FP("codepipe worker \u2014 set up this machine as a runner");let e=Le(t.profile);e&&(Gn.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Kn(await Yk({message:"re-register this worker?",initialValue:!1}))||Xo("keeping the existing registration"));let r=wt(t.profile)??wt(),n=Ds(await uu({message:"HUB URL",placeholder:mt,initialValue:X("HUB_URL")??r?.hubUrl??mt,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=Kn(await lu({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 Vk(n,a),Gn.success("account-issued registration token minted");else if(i==="login"){let d=await Mn();a=(await Dn(n,d)).cliToken,s=await Vk(n,a),Gn.success("account-issued registration token minted")}else s=Ds(await KP({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||Xo("a registration token is required");let c=await HP(n,a),l=Ds(await uu({message:"worker name",initialValue:UP(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=Kn(await lu({message:"agent backend",options:[{value:"claude-headless",label:"claude-headless \u2014 Claude Code on PATH (the real thing)"},{value:"mock",label:"mock \u2014 deterministic stub (development)"},{value:"",label:"none \u2014 this worker will not claim agent jobs"}],initialValue:"claude-headless"}));if(await _r({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Gn.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Kn(await Yk({message:"start the claim-loop now?",initialValue:!0}))){zk("registered. start later with `codepipe worker`.");return}zk("starting the claim-loop\u2026"),await Fo(t.profile?{profile:t.profile}:{})}function qP(){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 X("PROFILE")}var be=qP();Dd(be);var De=new WP;De.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Ve).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{Us()?await qk({profile:be}):await As({profile:be})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});De.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await wk({configPath:t.config,skipVerify:t.skipVerify===!0}):await sk({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","Personal CLI token (issued during `codepipe init`)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await Jd({...t,profile:be})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await ak({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});De.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await pg({profile:be})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});De.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await Kw({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("login").description("Set the Claude OAuth token (sealed into job bundles)").option("--token <token>","Provide the token non-interactively").option("--shared","Save to the machine/farm-wide ~/.codepipe/shared.json instead of this project").option("--stdin","Read the token from stdin (for scripted/ssh delivery)").action(async t=>{try{await xk({profile:be,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await fw({profile:be})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});De.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 Dk({profile:t.profile,...t.watch?{watch:!0}:{},...Number.isFinite(t.interval)?{intervalSec:t.interval}:{}})});De.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).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 As({profile:be,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Jk=De.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Jk.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??X("HUB_URL")??wt(be)?.hubUrl??mt,r=t.token??X("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Us()){await du({profile:be});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=X("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??X("WORKER_NAME"),i=t.llm??X("WORKER_LLM");await _r({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...be?{profile:be}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Jk.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!Le(be)&&Us()){await du({profile:be});return}await Fo(be?{profile:be}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Zk=De.command("project").description("Manage CodePipe projects");Zk.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Rk({profile:be})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Zk.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 Ck({...t,cliProfile:be})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var pu=De.command("repo").description("Manage the project's git repositories");pu.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 Nk({profile:be,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});pu.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 Ok({profile:be,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});pu.command("list").description("List the project's repos").action(async()=>{try{await Lk({profile:be})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Qk=De.command("model").description("Project map (model/ in the Context Repo)");Qk.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 ml({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Qk.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 hl({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.parseAsync();