@code-partner/codepipe 0.14.1-dev.285.g30f288c9 → 0.14.1-dev.288.g0848b8d6

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 +213 -191
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,40 +1,40 @@
1
1
  #!/usr/bin/env node
2
- var Rb=Object.defineProperty;var x=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ge=(t,e)=>{for(var r in e)Rb(t,r,{get:e[r],enumerable:!0})};var Xe,mt,ta=x(()=>{"use strict";Xe="0.14.1-dev.285.g30f288c9",mt="https://hub.dev.codepipe.dev"});function Jn(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Cu&&t<=ht}var ht,Cu,Au=x(()=>{"use strict";ta();ht=4,Cu=4});var Pu=x(()=>{"use strict";ta()});function Zn(t=6){return`# CodePipe Context Repo format version.
2
+ var lv=Object.defineProperty;var S=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ge=(t,e)=>{for(var r in e)lv(t,r,{get:e[r],enumerable:!0})};var Xe,mt,ua=S(()=>{"use strict";Xe="0.14.1-dev.288.g0848b8d6",mt="https://hub.dev.codepipe.dev"});function ro(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=zu&&t<=ht}var ht,zu,Xu=S(()=>{"use strict";ua();ht=4,zu=4});var Ju=S(()=>{"use strict";ua()});function no(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 na(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 oa(t,e=ra){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 ia(t,e=ra){return e.filter(r=>r.version>t)}var _u,gt,zr,ra,ju=x(()=>{"use strict";_u=6,gt=".codepipe-context.yaml",zr=".devpipe-context.yaml",ra=[{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 eo(t){return`model/facts/identity/${t}.yaml`}function kr(t){return`model/facts/events/${t}.yaml`}function ca(t){return`model/facts/annotations/${t}.md`}function la(t){return`model/derived/correlates/${t}.yaml`}function ua(t){return`model/derived/touched/${t}.yaml`}function Nu(t){return t===""?"root":t.replace(/\//g,"-")}function da(t,e){return`model/derived/structure/${t}/${Nu(e)}.yaml`}function ti(t){return typeof t=="string"&&Lu.test(t)}function te(t){if(typeof t!="string")return null;let e=t.indexOf(":");if(e<=0)return null;let r=t.indexOf(":",e+1);if(r<0)return null;let n=t.slice(0,e);if(!Ou.includes(n))return null;let o=t.slice(e+1,r),i=t.slice(r+1);return o===""&&!_b.includes(n)||i===""?null:{level:n,repo:o,path:i}}function Se(t){return`task::${t}`}function ge(t,e,r){return`${t}:${e}:${r}`}function to(t){let e=[];return St(t)?(ni(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),typeof t.repo!="string"&&e.push("repo: missing (empty string = cross-repo)"),typeof t.builtFromCommit!="string"&&e.push("builtFromCommit: missing"),Array.isArray(t.edges)?t.edges.forEach((r,n)=>{if(!St(r)){e.push(`edges[${n}]: not an object`);return}pa.includes(r.kind)||e.push(`edges[${n}].kind: unknown "${String(r.kind)}"`),te(r.from)||e.push(`edges[${n}].from: malformed nodeKey`),te(r.to)||e.push(`edges[${n}].to: malformed nodeKey`),r.weight!==void 0&&!(typeof r.weight=="number"&&Number.isFinite(r.weight))&&e.push(`edges[${n}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}):{ok:!1,errors:["edge sheet: not an object"]}}function Mu(t){return{...t,edges:Vr(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function br(t){return $r(Mu(t))}function St(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ni(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function yt(t){return typeof t=="string"&&t.length>0}function Nb(t){return t.modelFormatVersion!==2}function Ot(t){let e=[];if(!St(t))return{ok:!1,errors:["shard: not an object"]};ni(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(!St(o)){e.push(`nodes[${i}]: not an object`);return}let s=te(o.key);if(!s){e.push(`nodes[${i}].key: malformed nodeKey (${JSON.stringify(o.key??null)})`);return}o.level!==s.level&&e.push(`nodes[${i}]: level "${String(o.level)}" does not match key prefix "${s.level}"`),r&&s.repo!==r&&e.push(`nodes[${i}].key: repo "${s.repo}" mixed into shard of repo "${r}"`);let a=o.key;n.has(a)&&e.push(`nodes[${i}].key: duplicate "${a}"`),n.add(a),o.entityId!==void 0&&!ti(o.entityId)&&e.push(`nodes[${i}].entityId: malformed (${JSON.stringify(o.entityId)})`)}):e.push("nodes: not an array"),Array.isArray(t.edges)?t.edges.forEach((o,i)=>{if(!St(o)){e.push(`edges[${i}]: not an object`);return}pa.includes(o.kind)||e.push(`edges[${i}].kind: unknown "${String(o.kind)}"`),(!yt(o.to)||!te(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 ro(t){let e=[];if(!St(t))return{ok:!1,errors:["identity: not an object"]};if(ni(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(!St(n)){e.push(`entities[${o}]: not an object`);return}ti(n.entityId)?r.has(n.entityId)?e.push(`entities[${o}].entityId: duplicate "${n.entityId}"`):r.add(n.entityId):e.push(`entities[${o}].entityId: malformed (${JSON.stringify(n.entityId??null)})`),te(n.currentKey)||e.push(`entities[${o}].currentKey: malformed nodeKey`),n.status!=="active"&&n.status!=="orphaned"&&e.push(`entities[${o}].status: expected active|orphaned`),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)=>{(!St(i)||!te(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 Lt(t){let e=[];return St(t)?(ni(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(!St(r)||!te(r.key)){e.push(`files[${n}].key: malformed nodeKey`);return}r.entityId!==void 0&&!ti(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 Vr(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function Du(t){return{...t,nodes:Vr(t.nodes,e=>e.key),edges:Vr(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function Uu(t){return{...t,entities:Vr(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:Vr(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function Bu(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:Vr(t.files,r=>r.key),...e?{links:e}:{}}}function Qn(t){return Ob.test(t)?t:JSON.stringify(t)}function Fu(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 Gu(t){return t===null||["boolean","number","string"].includes(typeof t)}function sa(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function Ku(t,e,r){if(Array.isArray(t)){for(let n of t)if(Gu(n))r.push(`${e}- ${Fu(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=sa(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([i,s],a)=>{let c=a===0?`${e}- `:`${e} `;aa(i,s,c,`${e} `,r)})}}return}for(let[n,o]of sa(t))aa(n,o,e,e,r)}function aa(t,e,r,n,o){if(Gu(e))o.push(`${r}${Qn(t)}: ${Fu(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${Qn(t)}: []`):(o.push(`${r}${Qn(t)}:`),Ku(e,`${n} `,o));else{let i=sa(e);if(i.length===0)o.push(`${r}${Qn(t)}: {}`);else{o.push(`${r}${Qn(t)}:`);for(let[s,a]of i)aa(s,a,`${n} `,`${n} `,o)}}}function $r(t){let e=[];return Ku(t,"",e),e.join(`
5
+ `}function pa(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 fa(t,e=da){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 ma(t,e=da){return e.filter(r=>r.version>t)}var Zu,gt,Jr,da,Qu=S(()=>{"use strict";Zu=6,gt=".codepipe-context.yaml",Jr=".devpipe-context.yaml",da=[{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 io(t){return`model/facts/identity/${t}.yaml`}function kr(t){return`model/facts/events/${t}.yaml`}function ya(t){return`model/facts/annotations/${t}.md`}function wa(t){return`model/derived/correlates/${t}.yaml`}function ba(t){return`model/derived/touched/${t}.yaml`}function ed(t){return t===""?"root":t.replace(/\//g,"-")}function ka(t,e){return`model/derived/structure/${t}/${ed(e)}.yaml`}function ai(t){return typeof t=="string"&&rd.test(t)}function te(t){if(typeof t!="string")return null;let e=t.indexOf(":");if(e<=0)return null;let r=t.indexOf(":",e+1);if(r<0)return null;let n=t.slice(0,e);if(!td.includes(n))return null;let o=t.slice(e+1,r),i=t.slice(r+1);return o===""&&!mv.includes(n)||i===""?null:{level:n,repo:o,path:i}}function Se(t){return`task::${t}`}function he(t,e,r){return`${t}:${e}:${r}`}function so(t){let e=[];return Et(t)?(li(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(!Et(r)){e.push(`edges[${n}]: not an object`);return}va.includes(r.kind)||e.push(`edges[${n}].kind: unknown "${String(r.kind)}"`),te(r.from)||e.push(`edges[${n}].from: malformed nodeKey`),te(r.to)||e.push(`edges[${n}].to: malformed nodeKey`),r.weight!==void 0&&!(typeof r.weight=="number"&&Number.isFinite(r.weight))&&e.push(`edges[${n}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}):{ok:!1,errors:["edge sheet: not an object"]}}function nd(t){return{...t,edges:Zr(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function vr(t){return xr(nd(t))}function Et(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function li(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function yt(t){return typeof t=="string"&&t.length>0}function gv(t){return t.modelFormatVersion!==2}function Ot(t){let e=[];if(!Et(t))return{ok:!1,errors:["shard: not an object"]};li(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(!Et(o)){e.push(`nodes[${i}]: not an object`);return}let s=te(o.key);if(!s){e.push(`nodes[${i}].key: malformed nodeKey (${JSON.stringify(o.key??null)})`);return}o.level!==s.level&&e.push(`nodes[${i}]: level "${String(o.level)}" does not match key prefix "${s.level}"`),r&&s.repo!==r&&e.push(`nodes[${i}].key: repo "${s.repo}" mixed into shard of repo "${r}"`);let a=o.key;n.has(a)&&e.push(`nodes[${i}].key: duplicate "${a}"`),n.add(a),o.entityId!==void 0&&!ai(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(!Et(o)){e.push(`edges[${i}]: not an object`);return}va.includes(o.kind)||e.push(`edges[${i}].kind: unknown "${String(o.kind)}"`),(!yt(o.to)||!te(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 ao(t){let e=[];if(!Et(t))return{ok:!1,errors:["identity: not an object"]};if(li(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(!Et(n)){e.push(`entities[${o}]: not an object`);return}ai(n.entityId)?r.has(n.entityId)?e.push(`entities[${o}].entityId: duplicate "${n.entityId}"`):r.add(n.entityId):e.push(`entities[${o}].entityId: malformed (${JSON.stringify(n.entityId??null)})`),te(n.currentKey)||e.push(`entities[${o}].currentKey: malformed nodeKey`),n.status!=="active"&&n.status!=="orphaned"&&e.push(`entities[${o}].status: expected active|orphaned`),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)=>{(!Et(i)||!te(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 Lt(t){let e=[];return Et(t)?(li(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(!Et(r)||!te(r.key)){e.push(`files[${n}].key: malformed nodeKey`);return}r.entityId!==void 0&&!ai(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 Zr(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function od(t){return{...t,nodes:Zr(t.nodes,e=>e.key),edges:Zr(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function id(t){return{...t,entities:Zr(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:Zr(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function sd(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:Zr(t.files,r=>r.key),...e?{links:e}:{}}}function oo(t){return yv.test(t)?t:JSON.stringify(t)}function ad(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 cd(t){return t===null||["boolean","number","string"].includes(typeof t)}function ha(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function ld(t,e,r){if(Array.isArray(t)){for(let n of t)if(cd(n))r.push(`${e}- ${ad(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=ha(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([i,s],a)=>{let c=a===0?`${e}- `:`${e} `;ga(i,s,c,`${e} `,r)})}}return}for(let[n,o]of ha(t))ga(n,o,e,e,r)}function ga(t,e,r,n,o){if(cd(e))o.push(`${r}${oo(t)}: ${ad(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${oo(t)}: []`):(o.push(`${r}${oo(t)}:`),ld(e,`${n} `,o));else{let i=ha(e);if(i.length===0)o.push(`${r}${oo(t)}: {}`);else{o.push(`${r}${oo(t)}:`);for(let[s,a]of i)ga(s,a,`${n} `,`${n} `,o)}}}function xr(t){let e=[];return ld(t,"",e),e.join(`
6
6
  `)+`
7
- `}function ya(t){return $r(Du(t))}function wa(t){return $r(Uu(t))}function Xr(t){return $r(Bu(t))}var Oe,Ib,Cb,Ab,Pb,ei,wr,Ou,pa,Lu,_b,ot,fa,ma,ha,ri,jb,ga,vr,Ob,ka=x(()=>{"use strict";Oe=2,Ib="model",Cb="model/README.md",Ab="model/facts",Pb="model/derived",ei="model/derived/INDEX.yaml",wr="model/derived/relates.yaml";Ou=["system","container","component","code","task","adr"],pa=["contains","touched_by","correlates","relates","references","depends_on"],Lu=/^e_[0-9a-f]{8}$/;_b=["system","task","adr"];ot={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};fa=2,ma=5,ha=50,ri=2e3,jb=5e4,ga={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},vr={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};Ob=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});function Lb(t){return t==="DONE"}function Mb(t){return t==="AWAITING_EXTERNAL_FIX"?!1:ba.indexOf(t)>=ba.indexOf("IMPLEMENTING")}var ba,Hu=x(()=>{"use strict";ba=["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 Ub(t){for(let e of va)if(e.phases.includes(t))return e.id;return null}function Bb(t){for(let e of Wu)if(e.phases.includes(t))return e.id;return null}var va,Db,Wu,qu=x(()=>{"use strict";va=[{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"]}],Db=va.flatMap(t=>t.phases),Wu=[{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 Fb(t){return Yu.includes(t)?"planning":"implementation"}function qt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var $a,Yu,Gb,xa=x(()=>{"use strict";$a=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat","observer","council","testing"],Yu=["draft","analysis","chat","observer","council"];Gb=1});function zu(t,e){return e.toLowerCase().includes(t.toLowerCase())}function Ta(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||ed.every(o=>e.some(i=>zu(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 Qu){let i=n.find(s=>zu(o,s.id));if(i)return i.id}return n[0].id}function Jr(){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():no[e]??Zu}function Hb(t){let e=t?.provider;return typeof e=="string"&&e.trim().length>0?e.trim():Je}function Wb(t){let e=Jr();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 qb(t){let e=typeof t.provider=="string"&&t.provider.trim().length>0&&t.provider.trim()!==Je;if(t.default===null&&Object.keys(t.roles).length===0&&!e)return null;let{provider:r,...n}=t;return JSON.stringify(e?{provider:r.trim(),...n}:n)}function Yb(t){if(!t)return Jr();try{let e=JSON.parse(t);if(!e||typeof e!="object")return Jr();let r=e,n=Jr();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 Jr()}}var Je,Sa,Ce,Zr,oi,ii,Vu,Xu,Ju,Ea,no,Zu,Qu,ed,Ra=x(()=>{"use strict";xa();Je="claude",Sa=[Je],Ce="opus",Zr="sonnet",oi="haiku",ii=[Ce,Zr,oi],Vu="build-discovery",Xu="code-review-verify",Ju=[Vu,Xu],Ea=[...$a,...Ju],no={analyze:Ce,implement:Ce,"resolve-conflict":Ce,rework:Ce,estimate:Zr,build:oi,"build-discovery":Ce,"code-review":Ce,"code-review-verify":Zr,draft:Zr,index:Ce,backfill:Ce,analysis:Ce,chat:Ce,observer:Ce,council:Ce,testing:Ce},Zu=Ce,Qu=[Ce,Zr,oi],ed=Array.from(new Set(Object.values(no)))});function Mt(t){return zb.has(t)?!0:Vb.some(e=>t.startsWith(e))}function si(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function xr(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function Ca(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function Pa(t,e){let r=si(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=xr(r.id,"id")??n;if(!Ia.test(o))throw new Error(`id must match ${Ia} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=xr(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=si(r.env,"env");s={};for(let[d,m]of Object.entries(p)){if(!Ze.test(d))throw new Error(`env name "${d}" must match ${Ze}`);if(typeof m!="string"&&typeof m!="number"&&typeof m!="boolean")throw new Error(`env.${d} must be a scalar`);s[d]=String(m)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>td)throw new Error(`too many params (max ${td})`);let p=new Set;a=c.map((d,m)=>Xb(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>rd)throw new Error(`too many steps (max ${rd})`);let u=l.map((p,d)=>{let m=si(p,`steps[${d}]`),f=xr(m.run,`steps[${d}].run`);if(!f||f.trim().length===0)throw new Error(`steps[${d}].run is required`);let g=xr(m.name,`steps[${d}].name`),k=Ca(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 Xb(t,e,r){let n=si(t,`params[${e}]`),o=xr(n.name,`params[${e}].name`);if(!o||!Ze.test(o))throw new Error(`params[${e}].name must match ${Ze}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let m=n.enum;if(!Array.isArray(m)||m.length===0||!m.every(f=>typeof f=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=m}let a=xr(n.label,`params[${e}].label`),c=xr(n.help,`params[${e}].help`),l=n.required===!0,u=Ca(n.min,`params[${e}].min`),p=Ca(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 _a(t,e){let r=t.params??[],n=new Map(r.map(i=>[i.name,i]));for(let i of Object.keys(e))if(!n.has(i))return{ok:!1,error:`unknown param: ${i}`};let o={};for(let i of r){let s=e[i.name];if(s==null||typeof s=="string"&&s.trim()==="")if(i.default!==void 0)s=i.default;else{if(i.required)return{ok:!1,error:`${i.name} is required`};continue}switch(i.type){case"string":{if(typeof s!="string")return{ok:!1,error:`${i.name} must be a string`};o[i.name]=s;break}case"enum":{if(typeof s!="string"||!(i.enum??[]).includes(s))return{ok:!1,error:`${i.name} must be one of: ${(i.enum??[]).join(", ")}`};o[i.name]=s;break}case"number":{let a=typeof s=="number"?s:typeof s=="string"?Number(s):NaN;if(!Number.isFinite(a))return{ok:!1,error:`${i.name} must be a number`};if(i.min!==void 0&&a<i.min)return{ok:!1,error:`${i.name} must be \u2265 ${i.min}`};if(i.max!==void 0&&a>i.max)return{ok:!1,error:`${i.name} must be \u2264 ${i.max}`};o[i.name]=a;break}case"boolean":{let a=typeof s=="boolean"?s:s==="true"?!0:s==="false"?!1:null;if(a===null)return{ok:!1,error:`${i.name} must be a boolean`};o[i.name]=a;break}}}return{ok:!0,values:o}}var Ze,zb,Vb,Aa,Ia,td,rd,ja=x(()=>{"use strict";Ze=/^[A-Z][A-Z0-9_]*$/,zb=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),Vb=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];Aa=600,Ia=/^[a-z0-9-]+$/,td=32,rd=64});function nd(){return{primary:ve,context:ve,tasks:ve,docs:ve,code_comments:ve,chat:ve,code_review:ve}}function od(t){return!t||t.trim().length===0||t.trim().toLowerCase()===ve}function Jb(t){if(typeof t!="string")return ve;let e=t.trim().replace(/\s+/g," ");return e.length===0||e.length>40||e.toLowerCase()===ve?ve:e}function Zb(t){let e=nd();if(!t||typeof t!="object")return e;let r=t.language;if(!r||typeof r!="object"||Array.isArray(r))return e;let n=r;for(let o of oo)e[o]=Jb(n[o]);return e}function Qb(t){return oo.every(e=>od(t[e]))}var ve,oo,Qr,io,Na=x(()=>{"use strict";ve="auto",oo=["primary","context","tasks","docs","code_comments","chat","code_review"],Qr=["English","Russian","German","Spanish","French","Portuguese","Italian","Chinese","Japanese","Korean"],io=40});function Da(t=id){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...Da(r.groups));return e}function sd(t,e){let r=JSON.stringify(e);return Da().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function Ua(t){let e=sd(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.type==="string"&&e.mustContain&&!i.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:e.maxLength!==void 0&&i.length>e.maxLength?{ok:!1,error:`${e.id} must be \u2264 ${e.maxLength} chars`}:{ok:!0,field:e,value:i}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)?{ok:!1,error:`${e.id} must be a number`}:!e.float&&!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}case"string_map":{if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,error:`${e.id} must be a name\u2192value map`};let i=Object.entries(r);if(i.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(i.length>Oa)return{ok:!1,error:`${e.id} must have \u2264 ${Oa} entries`};let s={};for(let[a,c]of i){if(!Ze.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Ze}`};if(Mt(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>La)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${La} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var ev,tv,Oa,La,Ma,id,ad=x(()=>{"use strict";ja();Ra();ka();Na();ev={primary:"Primary language",context:"Context documents",tasks:"Tracker issues",docs:"Repo documentation",code_comments:"Code comments",chat:"Agent chat",code_review:"Code review comments"},tv={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."},Oa=64,La=2e3,Ma=2e3,id=[{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:[...Sa],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:[...ii],help:"Overrides the recommended defaults for every role not listed below."},...Ea.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...ii],help:`recommended: ${no[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:Ma,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:Ma,help:`e.g. "implementation details, bullet list of what was done, in the tracker's language". Empty \u21D2 the default PR body.`}]},{id:"apply.delivery",label:"Delivery & merge",help:"How a finished change reaches the repository: with or without a pull request, and who merges it.",fields:[{id:"apply.pull_request",file:"project.yaml",path:["apply","pull_request"],type:"boolean",label:"Open a pull request",nullable:!1,help:"On (default): the task branch is pushed and a pull request is opened \u2014 the change is reviewable in the git host and keeps a history of review comments. Off: no PR at all; the branch is merged into the default branch directly, and the agent's review remarks live only in the dashboard and the Context Repo."},{id:"apply.done",file:"project.yaml",path:["apply","done"],type:"enum",label:"Task is done when",nullable:!1,suggestions:["merge","branch"],help:"merge (default): the task is finished only once its change lands in the default branch. branch: the task ends at the pushed branch (plus the PR, if enabled) and nothing is merged for you."},{id:"apply.auto_merge",file:"project.yaml",path:["apply","auto_merge"],type:"enum",label:"Auto-merge pull requests",nullable:!1,suggestions:["off","on_ci_green"],help:"Applies to the pull-request path only. off (default): the merge waits for you (Approve on the task card). on_ci_green: as soon as the PR is open, conflict-free and its CI is green, CodePipe merges it \u2014 changes reach the default branch with no further review from you. Requires full automation; branch protection on the host still applies (a refused merge parks the task). Without pull requests, full automation merges the branch itself and this switch does not apply."}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{id:"testing",label:"Testing",help:"An optional phase after code review: writes the test plan you run in the morning and reports what it could verify.",fields:[{id:"testing.enabled",file:"regimen.yaml",path:["testing","enabled"],type:"boolean",nullable:!1,label:"Run the testing phase",help:"Off by default. When on, a task passing code review goes through a test pass before the PR: it derives TESTPLAN.md from the plan's requirements and reports per requirement what it could verify. A requirement it finds broken sends the change back for a fix (bounded below)."},{id:"testing.max_iterations",file:"regimen.yaml",path:["testing","max_iterations"],type:"number",nullable:!0,min:1,max:10,label:"Fix rounds before stopping",help:"How many times a failed test pass may send the change back before the task waits for you. Empty \u21D2 2."}]},{id:"code_review",label:"Code review",help:"One review mechanism for the pipeline's own changes and for developers' branches (the review column); they differ only in where the findings go.",fields:[{id:"code_review.verify_pass",file:"regimen.yaml",path:["code_review","verify_pass"],type:"boolean",nullable:!1,label:"Verifier pass (precision)",help:"On by default, paired with the critics panel. A second, narrow agent checks every finding against the code (real? re-grade) before it costs a rework round or reaches a developer; the findings threshold below keeps small rounds cheap."},{id:"code_review.panel",file:"regimen.yaml",path:["code_review","panel"],type:"boolean",nullable:!1,label:"Critics panel",help:"On by default. The reviewer delegates to the project's critic roles (roles/ in the Context Repo, or the bundled set) as parallel subagents before its own pass. Cost grows with the number of roles."},{id:"code_review.verify_min_findings",file:"regimen.yaml",path:["code_review","verify_min_findings"],type:"number",nullable:!0,min:1,label:"Verifier threshold (findings)",help:"The verifier runs only when a round carries at least this many actionable findings \u2014 1-2 are cheap to absorb, noise scales with volume. Empty = 3; 1 = verify every round."},{id:"code_review.max_blocking",file:"regimen.yaml",path:["code_review","max_blocking"],type:"number",nullable:!0,label:"Blocking budget (internal)",help:"Max blocker findings that keep their power in the pipeline's own review; the rest are demoted to major, weakest confidence first. Empty = 5."},{id:"code_review.external.max_blocking",file:"regimen.yaml",path:["code_review","external","max_blocking"],type:"number",nullable:!0,label:"Blocking budget (external)",help:"The same budget for a developer's branch review \u2014 tighter by default because a human reads these. Empty = 3."}]},{id:"skills",label:"Skills",help:"Reusable procedures the agent can invoke instead of improvising. Only their names and one-line descriptions sit in the prompt; the steps load when a skill is used.",fields:[{id:"skills.from_bundled",file:"regimen.yaml",path:["skills","from_bundled"],type:"boolean",nullable:!1,label:"Use the skills shipped with CodePipe",help:"On by default. General procedures maintained with the product."},{id:"skills.from_context_repo",file:"regimen.yaml",path:["skills","from_context_repo"],type:"boolean",nullable:!1,label:"Use this project's skills",help:"On by default. Skills the team writes in the context repository under `skills/<name>/SKILL.md`. These override a bundled skill of the same name."},{id:"skills.from_project_repo",file:"regimen.yaml",path:["skills","from_project_repo"],type:"boolean",nullable:!1,label:"Use the code repository's skills",help:"On by default. `.claude/skills/` inside the project repositories \u2014 the skills your developers already use locally. These win over both other sources."}]},{id:"quality",label:"Quality block",help:"Skip the whole quality block (build + code review) when a change touches only safe paths.",fields:[{id:"quality.skip_paths",file:"regimen.yaml",path:["quality","skip_paths"],type:"string_list",nullable:!0,label:"Skip paths (gitignore-style)",help:"When every changed file across all repos matches these globs, build and code review are skipped and the change goes straight to apply. One file outside the list runs both as usual. Use ! to re-include (e.g. !schema/**/*.md). Empty = never skip."}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (on by default; orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on (default), a task taken from Develop waits in the QUEUE for a single Confirm before the pipeline starts \u2014 the Confirm pulls in dependency closure and topologically orders the queue. Off \u21D2 conveyor: the task starts the pipeline immediately."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]},{id:"language",label:"Language",help:"Languages the agent writes in, per area. Empty \u21D2 auto: mirror the language of the user's material.",fields:oo.map(t=>({id:`language.${t}`,file:"project.yaml",path:["language",t],type:"string",label:ev[t],nullable:!0,maxLength:40,suggestions:t==="chat"?[ve,...Qr]:[...Qr],help:tv[t]}))},{id:"context.model",label:"Project map",help:"Parameters of the project map (built from git history by the CLI). Empty fields keep the defaults.",fields:[{id:"context.model.enabled",file:"regimen.yaml",path:["context","model","enabled"],type:"boolean",label:"Enable in the pipeline",nullable:!1,help:"On by default. Agents are asked to record intent annotations and receive an assembled context pack built from the project map. Off \u21D2 the pipeline ignores the map entirely and behaves exactly as if the feature were absent."},{id:"context.model.prompt.pack",file:"regimen.yaml",path:["context","model","prompt","pack"],type:"boolean",nullable:!1,label:"Give agents the context pack",help:"On by default. The assembled pack costs up to ~4000 tokens on every task of the analyze / estimate / implement / rework roles. Turning it off keeps the map building and stops the spend \u2014 the way to see what the pack is actually worth on this project."},{id:"context.model.prompt.annotations",file:"regimen.yaml",path:["context","model","prompt","annotations"],type:"boolean",nullable:!1,label:"Ask agents for intent annotations",help:"On by default. Adds the annotations block to the implement and rework prompts \u2014 the layer that records WHY the code is shaped this way. Cheap, and worth accumulating even while the pack is off."},{id:"context.index.hub",file:"regimen.yaml",path:["context","index","hub"],type:"enum",label:"Search index on the server",nullable:!0,suggestions:["off","metadata"],help:"off (default): search runs on your machine, nothing is uploaded. metadata: paths, labels and task texts (never code) are mirrored to the server so search and structure stay available while your machine is offline. Switching back to off deletes the mirrored rows."},{id:"context.model.issue_key_pattern",file:"regimen.yaml",path:["context","model","issue_key_pattern"],type:"string",label:"Issue-key pattern (regex)",nullable:!0,maxLength:200,help:"Regex that finds tracker issue keys in commit subjects when mining task events from history. Empty \u21D2 derived from the tracker project key (e.g. DEV-\\d+)."},{id:"context.model.cochange.window_commits",file:"regimen.yaml",path:["context","model","cochange","window_commits"],type:"number",label:"History window (commits)",nullable:!0,min:50,max:5e4,help:`How many commits back from the build commit are mined. Default ${ot.windowCommits}.`},{id:"context.model.cochange.commit_file_cap",file:"regimen.yaml",path:["context","model","cochange","commit_file_cap"],type:"number",label:"Commit size cap (files)",nullable:!0,min:2,max:500,help:`Commits touching more files are ignored as noise. Default ${ot.commitFileCap}.`},{id:"context.model.cochange.support_min",file:"regimen.yaml",path:["context","model","cochange","support_min"],type:"number",label:"Minimum co-occurrences",nullable:!0,min:1,max:100,help:`A pair of files must change together at least this many times. Default ${ot.supportMin}.`},{id:"context.model.cochange.jaccard_min_pct",file:"regimen.yaml",path:["context","model","cochange","jaccard_min_pct"],type:"number",label:"Minimum Jaccard (%)",nullable:!0,min:0,max:100,help:`Overlap threshold: |A\u2229B| / |A\u222AB| of the files' commit sets, in percent. Default ${ot.jaccardMinPct}.`},{id:"context.model.cochange.half_life_days",file:"regimen.yaml",path:["context","model","cochange","half_life_days"],type:"number",label:"Time-decay half-life (days)",nullable:!0,min:1,max:3650,help:`A commit this old counts half as much. Default ${ot.halfLifeDays} (~9 months).`},{id:"context.model.cochange.top_k",file:"regimen.yaml",path:["context","model","cochange","top_k"],type:"number",label:"Edges per file (top-k)",nullable:!0,min:1,max:64,help:`Only the k strongest co-change edges of a file survive \u2014 bounds graph density whatever the thresholds. Default ${ot.topK}.`}]},{id:"rate_limit",label:"Rate limit",help:"Automatic project pause as the LLM usage window fills up.",fields:[{id:"rate_limit.auto_pause.enabled",file:"project.yaml",path:["rate_limit","auto_pause","enabled"],type:"boolean",nullable:!1,label:"Pause the project near the limit",help:"On (default): when window utilization reaches the threshold, the project is paused (same pause as the manual one) and you get an email \u2014 the remaining window stays available for your own work. Off: agents keep working until the provider actually runs out."},{id:"rate_limit.auto_pause.threshold",file:"project.yaml",path:["rate_limit","auto_pause","threshold"],type:"number",float:!0,nullable:!0,min:.05,max:1,label:"Pause threshold (share of the window)",help:"Fraction of the usage window at which the pause fires; the rest (1 \u2212 threshold) is your manual-work reserve. Empty \u21D2 0.75."}]},{id:"context.job_logs",label:"Job transcripts",help:"Whether the raw agent transcript of each job is kept in the Context Repo.",fields:[{id:"context.job_logs.enabled",file:"regimen.yaml",path:["context","job_logs","enabled"],type:"boolean",label:"Keep transcripts in the Context Repo",nullable:!1,help:"Off (default): the transcript is discarded after the run \u2014 nothing lands in the Context Repo. On: each job's raw transcript is committed as tasks/<KEY>/logs/job-<id>.jsonl for post-mortem debugging."}]}]});function cd(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 Fa(t){let{name:e,body:r,origin:n}=t;if(!Ba.test(e))return{ok:!1,error:`role name must match ${Ba} (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=cd(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=cd(i.scenarios);if(c===null)return{ok:!1,error:"scenarios must be a list"};let l=[];for(let d of c){if(!ai.includes(d))return{ok:!1,error:`unknown scenario "${d}" \u2014 one of: ${ai.join(", ")}`};l.includes(d)||l.push(d)}if(l.length===0)return{ok:!1,error:`scenarios must name at least one of: ${ai.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 Ga(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 Ka(t,e){return t.filter(r=>r.enabled&&r.scenarios.includes(e))}var ai,Ba,ZP,QP,ld=x(()=>{"use strict";ai=["plan_review","code_review","council"],Ba=/^[a-z][a-z0-9-]{1,39}$/,ZP=10,QP=300});function Ha(t){return ud.includes(t)}function Wa(t){return`prompts/${t}.md`}var ud,dd=x(()=>{"use strict";ud=["analysis","analyze","backfill","build","chat","code-review","code-review-external","code-review-fix","code-review-verify","council","draft","estimate","implement","index","observer","resolve-conflict","review-comment","rework","testing"]});function Ya(t){if(!qa.test(t.name))return{ok:!1,error:`skill directory name must match ${qa}`};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 za(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 fd(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(!rv.test(n))return{ok:!1,error:`"${t}": expected <owner>/<repo>[@<40-hex sha>]`};let i=pd.find(s=>s.repo.toLowerCase()===n.toLowerCase());return o&&!nv.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 ov(t){let e=[],r=[],n=new Set;for(let o of t){if(!o.trim())continue;let i=fd(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 sv(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(!iv.test(s)||!r.has(s.slice(s.indexOf("@")+1))){o.push(s);continue}n[s]=!0}}return{enabled:n,unknown:o}}var qa,r_,pd,rv,nv,iv,md=x(()=>{"use strict";qa=/^[a-z][a-z0-9-]{1,39}$/,r_=300;pd=[{repo:"anthropics/skills",name:"anthropic-agent-skills"},{repo:"anthropics/claude-plugins-official",name:"claude-plugins-official"}],rv=/^[A-Za-z0-9][\w.-]*\/[A-Za-z0-9][\w.-]*$/,nv=/^[0-9a-f]{40}$/;iv=/^[A-Za-z0-9][\w.-]*@[A-Za-z0-9][\w.-]*$/});function hd(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 av(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=hd(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=hd(g.after,e.length);if(h===null)return{ok:!1,error:`${k}: after must be a list of task keys`};for(let v of h){if(!r.has(v))return{ok:!1,error:`${k}: after names ${v}, not in this batch`};if(v===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 o_,i_,gd=x(()=>{"use strict";o_=4e3,i_=4e3});function cv(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 a_,yd=x(()=>{"use strict";a_=4e3});function dv(t){let e=t.replace(/^#+\s*/,"").trim();for(let r of lv)if(r.re.test(e))return{kind:r.kind,letter:r.letter};return null}function Va(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=dv(n),i=null;continue}let l=uv.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 pv(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 fv(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 Ra(t){return xr(od(t))}function Ta(t){return xr(id(t))}function Qr(t){return xr(sd(t))}var Le,uv,dv,pv,fv,si,br,td,va,rd,mv,ot,$a,xa,Sa,ci,hv,Ea,$r,yv,Ia=S(()=>{"use strict";Le=2,uv="model",dv="model/README.md",pv="model/facts",fv="model/derived",si="model/derived/INDEX.yaml",br="model/derived/relates.yaml";td=["system","container","component","code","task","adr"],va=["contains","touched_by","correlates","relates","references","depends_on"],rd=/^e_[0-9a-f]{8}$/;mv=["system","task","adr"];ot={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};$a=2,xa=5,Sa=50,ci=2e3,hv=5e4,Ea={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},$r={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};yv=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});function wv(t){return t==="DONE"}function bv(t){return t==="AWAITING_EXTERNAL_FIX"?!1:Ca.indexOf(t)>=Ca.indexOf("IMPLEMENTING")}var Ca,ud=S(()=>{"use strict";Ca=["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 vv(t){for(let e of Pa)if(e.phases.includes(t))return e.id;return null}function $v(t){for(let e of dd)if(e.phases.includes(t))return e.id;return null}var Pa,kv,dd,pd=S(()=>{"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"]}],kv=Pa.flatMap(t=>t.phases),dd=[{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 _a(t){return md.includes(t)}function xv(t){return fd.includes(t)?"planning":"implementation"}function Mt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Aa,fd,md,Sv,ja=S(()=>{"use strict";Aa=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat","config","observer","council","testing"],fd=["draft","analysis","chat","config","observer","council"],md=["chat","config"];Sv=1});function hd(t,e){return e.toLowerCase().includes(t.toLowerCase())}function La(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||vd.every(o=>e.some(i=>hd(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 kd){let i=n.find(s=>hd(o,s.id));if(i)return i.id}return n[0].id}function en(){return{default:null,roles:{}}}function Ev(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():co[e]??bd}function Rv(t){let e=t?.provider;return typeof e=="string"&&e.trim().length>0?e.trim():Je}function Tv(t){let e=en();if(!t||typeof t!="object")return e;let r=t.llm;if(!r||typeof r!="object")return e;let n=r.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 Iv(t){let e=typeof t.provider=="string"&&t.provider.trim().length>0&&t.provider.trim()!==Je;if(t.default===null&&Object.keys(t.roles).length===0&&!e)return null;let{provider:r,...n}=t;return JSON.stringify(e?{provider:r.trim(),...n}:n)}function Cv(t){if(!t)return en();try{let e=JSON.parse(t);if(!e||typeof e!="object")return en();let r=e,n=en();typeof r.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 en()}}var Je,Na,Te,tn,ui,di,gd,yd,wd,Oa,co,bd,kd,vd,Ma=S(()=>{"use strict";ja();Je="claude",Na=[Je],Te="opus",tn="sonnet",ui="haiku",di=[Te,tn,ui],gd="build-discovery",yd="code-review-verify",wd=[gd,yd],Oa=[...Aa,...wd],co={analyze:Te,implement:Te,"resolve-conflict":Te,rework:Te,estimate:tn,build:ui,"build-discovery":Te,"code-review":Te,"code-review-verify":tn,draft:tn,index:Te,backfill:Te,analysis:Te,chat:Te,config:Te,observer:Te,council:Te,testing:Te},bd=Te,kd=[Te,tn,ui],vd=Array.from(new Set(Object.values(co)))});function Dt(t){return Pv.has(t)?!0:Av.some(e=>t.startsWith(e))}function pi(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Sr(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function Ua(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function Fa(t,e){let r=pi(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=Sr(r.id,"id")??n;if(!Da.test(o))throw new Error(`id must match ${Da} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=Sr(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=pi(r.env,"env");s={};for(let[d,m]of Object.entries(p)){if(!Ze.test(d))throw new Error(`env name "${d}" must match ${Ze}`);if(typeof m!="string"&&typeof m!="number"&&typeof m!="boolean")throw new Error(`env.${d} must be a scalar`);s[d]=String(m)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>$d)throw new Error(`too many params (max ${$d})`);let p=new Set;a=c.map((d,m)=>_v(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>xd)throw new Error(`too many steps (max ${xd})`);let u=l.map((p,d)=>{let m=pi(p,`steps[${d}]`),f=Sr(m.run,`steps[${d}].run`);if(!f||f.trim().length===0)throw new Error(`steps[${d}].run is required`);let g=Sr(m.name,`steps[${d}].name`),w=Ua(m.timeout_sec,`steps[${d}].timeout_sec`);if(w!==void 0&&(!Number.isInteger(w)||w<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:f,...g?{name:g}:{},...w!==void 0?{timeout_sec:w}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function _v(t,e,r){let n=pi(t,`params[${e}]`),o=Sr(n.name,`params[${e}].name`);if(!o||!Ze.test(o))throw new Error(`params[${e}].name must match ${Ze}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let m=n.enum;if(!Array.isArray(m)||m.length===0||!m.every(f=>typeof f=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=m}let a=Sr(n.label,`params[${e}].label`),c=Sr(n.help,`params[${e}].help`),l=n.required===!0,u=Ua(n.min,`params[${e}].min`),p=Ua(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 Ga(t,e){let r=t.params??[],n=new Map(r.map(i=>[i.name,i]));for(let i of Object.keys(e))if(!n.has(i))return{ok:!1,error:`unknown param: ${i}`};let o={};for(let i of r){let s=e[i.name];if(s==null||typeof s=="string"&&s.trim()==="")if(i.default!==void 0)s=i.default;else{if(i.required)return{ok:!1,error:`${i.name} is required`};continue}switch(i.type){case"string":{if(typeof s!="string")return{ok:!1,error:`${i.name} must be a string`};o[i.name]=s;break}case"enum":{if(typeof s!="string"||!(i.enum??[]).includes(s))return{ok:!1,error:`${i.name} must be one of: ${(i.enum??[]).join(", ")}`};o[i.name]=s;break}case"number":{let a=typeof s=="number"?s:typeof s=="string"?Number(s):NaN;if(!Number.isFinite(a))return{ok:!1,error:`${i.name} must be a number`};if(i.min!==void 0&&a<i.min)return{ok:!1,error:`${i.name} must be \u2265 ${i.min}`};if(i.max!==void 0&&a>i.max)return{ok:!1,error:`${i.name} must be \u2264 ${i.max}`};o[i.name]=a;break}case"boolean":{let a=typeof s=="boolean"?s:s==="true"?!0:s==="false"?!1:null;if(a===null)return{ok:!1,error:`${i.name} must be a boolean`};o[i.name]=a;break}}}return{ok:!0,values:o}}var Ze,Pv,Av,Ba,Da,$d,xd,Ka=S(()=>{"use strict";Ze=/^[A-Z][A-Z0-9_]*$/,Pv=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),Av=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];Ba=600,Da=/^[a-z0-9-]+$/,$d=32,xd=64});function Sd(){return{primary:ge,context:ge,tasks:ge,docs:ge,code_comments:ge,chat:ge,code_review:ge,commits:ge}}function Ed(t){return!t||t.trim().length===0||t.trim().toLowerCase()===ge}function jv(t){if(typeof t!="string")return ge;let e=t.trim().replace(/\s+/g," ");return e.length===0||e.length>40||e.toLowerCase()===ge?ge:e}function Nv(t){let e=Sd();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 lo)e[o]=jv(n[o]);return e}function Ov(t){return lo.every(e=>Ed(t[e]))}var ge,lo,rn,uo,Ha=S(()=>{"use strict";ge="auto",lo=["primary","context","tasks","docs","code_comments","chat","code_review","commits"],rn=["English","Russian","German","Spanish","French","Portuguese","Italian","Chinese","Japanese","Korean"],uo=40});function Va(t=Rd){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...Va(r.groups));return e}function Td(t,e){let r=JSON.stringify(e);return Va().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function za(t){let e=Td(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.type==="string"&&e.mustContain&&!i.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:e.maxLength!==void 0&&i.length>e.maxLength?{ok:!1,error:`${e.id} must be \u2264 ${e.maxLength} chars`}:{ok:!0,field:e,value:i}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)?{ok:!1,error:`${e.id} must be a number`}:!e.float&&!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}case"string_map":{if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,error:`${e.id} must be a name\u2192value map`};let i=Object.entries(r);if(i.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(i.length>Wa)return{ok:!1,error:`${e.id} must have \u2264 ${Wa} entries`};let s={};for(let[a,c]of i){if(!Ze.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Ze}`};if(Dt(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>qa)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${qa} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var Lv,Mv,Wa,qa,Ya,Rd,Id=S(()=>{"use strict";Ka();Ma();Ia();Ha();Lv={primary:"Primary language",context:"Context documents",tasks:"Tracker issues",docs:"Repo documentation",code_comments:"Code comments",chat:"Agent chat",code_review:"Code review comments",commits:"Commits & branches"},Mv={primary:"The project's main language (agent status notes ride it). Empty \u21D2 auto.",context:"Knowledge, ADRs and task artifacts in the Context Repo. Empty \u21D2 auto.",tasks:"Issue titles/bodies the agent drafts. Empty \u21D2 auto.",docs:"Documentation changes in the project repos. Empty \u21D2 auto.",code_comments:"New code comments the agent writes. Empty \u21D2 auto.",chat:"The interactive task-drafting chat. Empty/auto \u21D2 mirror the user's messages.",code_review:"Review findings and PR comments. Empty \u21D2 follows the tracker-issues language.",commits:"Commit/PR subject & branch slug. Empty \u21D2 follows the tracker-issues language."},Wa=64,qa=2e3,Ya=2e3,Rd=[{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:[...Na],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:[...di],help:"Overrides the recommended defaults for every role not listed below."},...Oa.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...di],help:`recommended: ${co[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:Ya,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:Ya,help:`e.g. "implementation details, bullet list of what was done, in the tracker's language". Empty \u21D2 the default PR body.`}]},{id:"apply.delivery",label:"Delivery & merge",help:"How a finished change reaches the repository: with or without a pull request, and who merges it.",fields:[{id:"apply.pull_request",file:"project.yaml",path:["apply","pull_request"],type:"boolean",label:"Open a pull request",nullable:!1,help:"On (default): the task branch is pushed and a pull request is opened \u2014 the change is reviewable in the git host and keeps a history of review comments. Off: no PR at all; the branch is merged into the default branch directly, and the agent's review remarks live only in the dashboard and the Context Repo."},{id:"apply.done",file:"project.yaml",path:["apply","done"],type:"enum",label:"Task is done when",nullable:!1,suggestions:["merge","branch"],help:"merge (default): the task is finished only once its change lands in the default branch. branch: the task ends at the pushed branch (plus the PR, if enabled) and nothing is merged for you."},{id:"apply.auto_merge",file:"project.yaml",path:["apply","auto_merge"],type:"enum",label:"Auto-merge pull requests",nullable:!1,suggestions:["off","on_ci_green"],help:"Applies to the pull-request path only. off (default): the merge waits for you (Approve on the task card). on_ci_green: as soon as the PR is open, conflict-free and its CI is green, CodePipe merges it \u2014 changes reach the default branch with no further review from you. Requires full automation; branch protection on the host still applies (a refused merge parks the task). Without pull requests, full automation merges the branch itself and this switch does not apply."}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{id:"testing",label:"Testing",help:"An optional phase after code review: writes the test plan you run in the morning and reports what it could verify.",fields:[{id:"testing.enabled",file:"regimen.yaml",path:["testing","enabled"],type:"boolean",nullable:!1,label:"Run the testing phase",help:"Off by default. When on, a task passing code review goes through a test pass before the PR: it derives TESTPLAN.md from the plan's requirements and reports per requirement what it could verify. A requirement it finds broken sends the change back for a fix (bounded below)."},{id:"testing.max_iterations",file:"regimen.yaml",path:["testing","max_iterations"],type:"number",nullable:!0,min:1,max:10,label:"Fix rounds before stopping",help:"How many times a failed test pass may send the change back before the task waits for you. Empty \u21D2 2."}]},{id:"code_review",label:"Code review",help:"One review mechanism for the pipeline's own changes and for developers' branches (the review column); they differ only in where the findings go.",fields:[{id:"code_review.verify_pass",file:"regimen.yaml",path:["code_review","verify_pass"],type:"boolean",nullable:!1,label:"Verifier pass (precision)",help:"On by default, paired with the critics panel. A second, narrow agent checks every finding against the code (real? re-grade) before it costs a rework round or reaches a developer; the findings threshold below keeps small rounds cheap."},{id:"code_review.panel",file:"regimen.yaml",path:["code_review","panel"],type:"boolean",nullable:!1,label:"Critics panel",help:"On by default. The reviewer delegates to the project's critic roles (roles/ in the Context Repo, or the bundled set) as parallel subagents before its own pass. Cost grows with the number of roles."},{id:"code_review.verify_min_findings",file:"regimen.yaml",path:["code_review","verify_min_findings"],type:"number",nullable:!0,min:1,label:"Verifier threshold (findings)",help:"The verifier runs only when a round carries at least this many actionable findings \u2014 1-2 are cheap to absorb, noise scales with volume. Empty = 3; 1 = verify every round."},{id:"code_review.max_blocking",file:"regimen.yaml",path:["code_review","max_blocking"],type:"number",nullable:!0,label:"Blocking budget (internal)",help:"Max blocker findings that keep their power in the pipeline's own review; the rest are demoted to major, weakest confidence first. Empty = 5."},{id:"code_review.external.max_blocking",file:"regimen.yaml",path:["code_review","external","max_blocking"],type:"number",nullable:!0,label:"Blocking budget (external)",help:"The same budget for a developer's branch review \u2014 tighter by default because a human reads these. Empty = 3."}]},{id:"skills",label:"Skills",help:"Reusable procedures the agent can invoke instead of improvising. Only their names and one-line descriptions sit in the prompt; the steps load when a skill is used.",fields:[{id:"skills.from_bundled",file:"regimen.yaml",path:["skills","from_bundled"],type:"boolean",nullable:!1,label:"Use the skills shipped with CodePipe",help:"On by default. General procedures maintained with the product."},{id:"skills.from_context_repo",file:"regimen.yaml",path:["skills","from_context_repo"],type:"boolean",nullable:!1,label:"Use this project's skills",help:"On by default. Skills the team writes in the context repository under `skills/<name>/SKILL.md`. These override a bundled skill of the same name."},{id:"skills.from_project_repo",file:"regimen.yaml",path:["skills","from_project_repo"],type:"boolean",nullable:!1,label:"Use the code repository's skills",help:"On by default. `.claude/skills/` inside the project repositories \u2014 the skills your developers already use locally. These win over both other sources."}]},{id:"quality",label:"Quality block",help:"Skip the whole quality block (build + code review) when a change touches only safe paths.",fields:[{id:"quality.skip_paths",file:"regimen.yaml",path:["quality","skip_paths"],type:"string_list",nullable:!0,label:"Skip paths (gitignore-style)",help:"When every changed file across all repos matches these globs, build and code review are skipped and the change goes straight to apply. One file outside the list runs both as usual. Use ! to re-include (e.g. !schema/**/*.md). Empty = never skip."}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (on by default; orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on (default), a task taken from Develop waits in the QUEUE for a single Confirm before the pipeline starts \u2014 the Confirm pulls in dependency closure and topologically orders the queue. Off \u21D2 conveyor: the task starts the pipeline immediately."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]},{id:"language",label:"Language",help:"Languages the agent writes in, per area. Empty \u21D2 auto: mirror the language of the user's material.",fields:lo.map(t=>({id:`language.${t}`,file:"project.yaml",path:["language",t],type:"string",label:Lv[t],nullable:!0,maxLength:40,suggestions:t==="chat"?[ge,...rn]:[...rn],help:Mv[t]}))},{id:"context.model",label:"Project map",help:"Parameters of the project map (built from git history by the CLI). Empty fields keep the defaults.",fields:[{id:"context.model.enabled",file:"regimen.yaml",path:["context","model","enabled"],type:"boolean",label:"Enable in the pipeline",nullable:!1,help:"On by default. Agents are asked to record intent annotations and receive an assembled context pack built from the project map. Off \u21D2 the pipeline ignores the map entirely and behaves exactly as if the feature were absent."},{id:"context.model.prompt.pack",file:"regimen.yaml",path:["context","model","prompt","pack"],type:"boolean",nullable:!1,label:"Give agents the context pack",help:"On by default. The assembled pack costs up to ~4000 tokens on every task of the analyze / estimate / implement / rework roles. Turning it off keeps the map building and stops the spend \u2014 the way to see what the pack is actually worth on this project."},{id:"context.model.prompt.annotations",file:"regimen.yaml",path:["context","model","prompt","annotations"],type:"boolean",nullable:!1,label:"Ask agents for intent annotations",help:"On by default. Adds the annotations block to the implement and rework prompts \u2014 the layer that records WHY the code is shaped this way. Cheap, and worth accumulating even while the pack is off."},{id:"context.index.hub",file:"regimen.yaml",path:["context","index","hub"],type:"enum",label:"Search index on the server",nullable:!0,suggestions:["off","metadata"],help:"off (default): search runs on your machine, nothing is uploaded. metadata: paths, labels and task texts (never code) are mirrored to the server so search and structure stay available while your machine is offline. Switching back to off deletes the mirrored rows."},{id:"context.model.issue_key_pattern",file:"regimen.yaml",path:["context","model","issue_key_pattern"],type:"string",label:"Issue-key pattern (regex)",nullable:!0,maxLength:200,help:"Regex that finds tracker issue keys in commit subjects when mining task events from history. Empty \u21D2 derived from the tracker project key (e.g. DEV-\\d+)."},{id:"context.model.cochange.window_commits",file:"regimen.yaml",path:["context","model","cochange","window_commits"],type:"number",label:"History window (commits)",nullable:!0,min:50,max:5e4,help:`How many commits back from the build commit are mined. Default ${ot.windowCommits}.`},{id:"context.model.cochange.commit_file_cap",file:"regimen.yaml",path:["context","model","cochange","commit_file_cap"],type:"number",label:"Commit size cap (files)",nullable:!0,min:2,max:500,help:`Commits touching more files are ignored as noise. Default ${ot.commitFileCap}.`},{id:"context.model.cochange.support_min",file:"regimen.yaml",path:["context","model","cochange","support_min"],type:"number",label:"Minimum co-occurrences",nullable:!0,min:1,max:100,help:`A pair of files must change together at least this many times. Default ${ot.supportMin}.`},{id:"context.model.cochange.jaccard_min_pct",file:"regimen.yaml",path:["context","model","cochange","jaccard_min_pct"],type:"number",label:"Minimum Jaccard (%)",nullable:!0,min:0,max:100,help:`Overlap threshold: |A\u2229B| / |A\u222AB| of the files' commit sets, in percent. Default ${ot.jaccardMinPct}.`},{id:"context.model.cochange.half_life_days",file:"regimen.yaml",path:["context","model","cochange","half_life_days"],type:"number",label:"Time-decay half-life (days)",nullable:!0,min:1,max:3650,help:`A commit this old counts half as much. Default ${ot.halfLifeDays} (~9 months).`},{id:"context.model.cochange.top_k",file:"regimen.yaml",path:["context","model","cochange","top_k"],type:"number",label:"Edges per file (top-k)",nullable:!0,min:1,max:64,help:`Only the k strongest co-change edges of a file survive \u2014 bounds graph density whatever the thresholds. Default ${ot.topK}.`}]},{id:"rate_limit",label:"Rate limit",help:"Automatic project pause as the LLM usage window fills up.",fields:[{id:"rate_limit.auto_pause.enabled",file:"project.yaml",path:["rate_limit","auto_pause","enabled"],type:"boolean",nullable:!1,label:"Pause the project near the limit",help:"On (default): when window utilization reaches the threshold, the project is paused (same pause as the manual one) and you get an email \u2014 the remaining window stays available for your own work. Off: agents keep working until the provider actually runs out."},{id:"rate_limit.auto_pause.threshold",file:"project.yaml",path:["rate_limit","auto_pause","threshold"],type:"number",float:!0,nullable:!0,min:.05,max:1,label:"Pause threshold (share of the window)",help:"Fraction of the usage window at which the pause fires; the rest (1 \u2212 threshold) is your manual-work reserve. Empty \u21D2 0.75."}]},{id:"context.job_logs",label:"Job transcripts",help:"Whether the raw agent transcript of each job is kept in the Context Repo.",fields:[{id:"context.job_logs.enabled",file:"regimen.yaml",path:["context","job_logs","enabled"],type:"boolean",label:"Keep transcripts in the Context Repo",nullable:!1,help:"Off (default): the transcript is discarded after the run \u2014 nothing lands in the Context Repo. On: each job's raw transcript is committed as tasks/<KEY>/logs/job-<id>.jsonl for post-mortem debugging."}]}]});var Cd=S(()=>{"use strict"});function Pd(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 Ja(t){let{name:e,body:r,origin:n}=t;if(!Xa.test(e))return{ok:!1,error:`role name must match ${Xa} (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=Pd(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=Pd(i.scenarios);if(c===null)return{ok:!1,error:"scenarios must be a list"};let l=[];for(let d of c){if(!fi.includes(d))return{ok:!1,error:`unknown scenario "${d}" \u2014 one of: ${fi.join(", ")}`};l.includes(d)||l.push(d)}if(l.length===0)return{ok:!1,error:`scenarios must name at least one of: ${fi.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 Za(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 Qa(t,e){return t.filter(r=>r.enabled&&r.scenarios.includes(e))}var fi,Xa,z_,X_,Ad=S(()=>{"use strict";fi=["plan_review","code_review","council"],Xa=/^[a-z][a-z0-9-]{1,39}$/,z_=10,X_=300});function ec(t){return _d.includes(t)}function tc(t){return`prompts/${t}.md`}var _d,jd=S(()=>{"use strict";_d=["analysis","analyze","backfill","build","chat","code-review","code-review-external","code-review-fix","code-review-verify","config","council","draft","estimate","implement","index","observer","resolve-conflict","review-comment","rework","testing"]});function nc(t){if(!rc.test(t.name))return{ok:!1,error:`skill directory name must match ${rc}`};if(t.body.trim().length===0)return{ok:!1,error:"SKILL.md has no body \u2014 the body IS the procedure"};let e=t.frontmatter;if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"SKILL.md has no frontmatter block"};let r=e.description;return typeof r!="string"||r.trim().length===0?{ok:!1,error:"description is required \u2014 it is what decides when the skill fires"}:r.length>300?{ok:!1,error:"description must be \u2264 300 characters"}:{ok:!0,skill:{name:t.name,description:r.trim()}}}function oc(t,e,r){let n=new Map;for(let o of[...t,...e,...r])n.set(o.name,o);return[...n.values()].sort((o,i)=>o.name<i.name?-1:o.name>i.name?1:0)}function 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(!Dv.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&&!Uv.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 Bv(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 Gv(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(!Fv.test(s)||!r.has(s.slice(s.indexOf("@")+1))){o.push(s);continue}n[s]=!0}}return{enabled:n,unknown:o}}var rc,Q_,Nd,Dv,Uv,Fv,Ld=S(()=>{"use strict";rc=/^[a-z][a-z0-9-]{1,39}$/,Q_=300;Nd=[{repo:"anthropics/skills",name:"anthropic-agent-skills"},{repo:"anthropics/claude-plugins-official",name:"claude-plugins-official"}],Dv=/^[A-Za-z0-9][\w.-]*\/[A-Za-z0-9][\w.-]*$/,Uv=/^[0-9a-f]{40}$/;Fv=/^[A-Za-z0-9][\w.-]*@[A-Za-z0-9][\w.-]*$/});function Md(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 Kv(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=Md(n.order,e.length);if(o===null)return{ok:!1,error:"order must be a list of task keys"};for(let f of o)if(!r.has(f))return{ok:!1,error:`order names ${f}, which is not in this batch`};if(new Set(o).size!==o.length)return{ok:!1,error:"order repeats a task key"};let i=e.filter(f=>!o.includes(f));if(o.length>0&&i.length>0)return{ok:!1,error:`order omits ${i.join(", ")}`};let s=n.tasks,a=[];if(s!=null){if(!Array.isArray(s))return{ok:!1,error:"tasks must be a list"};for(let f of s){if(!f||typeof f!="object")return{ok:!1,error:"each task entry must be an object"};let g=f,w=typeof g.taskKey=="string"?g.taskKey.trim():"";if(!r.has(w))return{ok:!1,error:`tasks names ${w||"(empty)"}, which is not in this batch`};let h=Md(g.after,e.length);if(h===null)return{ok:!1,error:`${w}: after must be a list of task keys`};for(let x of h){if(!r.has(x))return{ok:!1,error:`${w}: after names ${x}, not in this batch`};if(x===w)return{ok:!1,error:`${w}: cannot come after itself`}}let k=typeof g.decisions=="string"?g.decisions.trim():"";a.push({taskKey:w,decisions:k.slice(0,4e3),after:h})}}let c=[],l=n.conflicts;if(Array.isArray(l))for(let f of l){if(!f||typeof f!="object")continue;let g=f,w=typeof g.taskKey=="string"?g.taskKey.trim():"",h=typeof g.adr=="string"?g.adr.trim():"",k=typeof g.detail=="string"?g.detail.trim():"";!r.has(w)||!k||c.push({taskKey:w,adr:h,detail:k.slice(0,4e3)})}let u=[],p=n.related;if(Array.isArray(p))for(let f of p){if(!f||typeof f!="object")continue;let g=f,w=typeof g.taskKey=="string"?g.taskKey.trim():"",h=typeof g.detail=="string"?g.detail.trim():"";!w||!h||u.push({taskKey:w,detail:h.slice(0,4e3)})}let d=typeof n.summary=="string"?n.summary.trim().slice(0,4e3):"",m=n.deferBehind===!0;return{ok:!0,plan:{order:o,tasks:a,conflicts:c,related:u,summary:d,deferBehind:m}}}var tj,rj,Dd=S(()=>{"use strict";tj=4e3,rj=4e3});function Hv(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 oj,Ud=S(()=>{"use strict";oj=4e3});function Yv(t){let e=t.replace(/^#+\s*/,"").trim();for(let r of Wv)if(r.re.test(e))return{kind:r.kind,letter:r.letter};return null}function ic(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=Yv(n),i=null;continue}let l=qv.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 Vv(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 zv(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 Xa(t){let e=new Set;for(let r of t.items)if(r.kind==="procedure")for(let n of r.text.matchAll(mv))e.add(n[1]);return[...e]}var lv,uv,mv,wd=x(()=>{"use strict";lv=[{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"}],uv=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*(.*)$/;mv=/`([a-z][a-z0-9-]{1,39})`/g});function yv(t){let e=[],r=null;for(let o of t.split(`
12
- `)){let i=gv.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 wv(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 hv,gv,kd=x(()=>{"use strict";hv=["done","deviated","partial","dropped"],gv=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*[—:-]?\s*(done|deviated|partial|dropped)\b\s*[—:-]?\s*(.*)$/i});var bd=x(()=>{"use strict"});var vd=x(()=>{"use strict"});var $d=x(()=>{"use strict"});function Ja(t){return`codepipe-host-${t}`}function kv(t){let e=t.filter(r=>r!=="self-hosted");return`runs-on: [self-hosted${e.length?", "+e.join(", "):""}]`}var xd=x(()=>{"use strict"});function bv(t,e){return(t&&t.includes("<TASK_ID>")?t:Sd).replace(/<TASK_ID>/g,e.toLowerCase())}function vv(t,e){if(t)return`${t.replace(/\/+$/,"")}/issue/${encodeURIComponent(e)}`}function so(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 Za(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 Qa(t){if(!t.mirror)return t;let{mirror:e,...r}=t;return{...r,host:e.host,owner:e.owner,repoName:e.repoName}}function Et(t){return`${t}${Ed}`}var Sd,Yt,Ed,Td=x(()=>{"use strict";Sd="codepipe/<TASK_ID>";Yt=/^[a-z][a-z0-9-]{1,30}$/,Ed="-codepipe-ctx"});function $v(t,e){return`${t}:${e}`}var Rd=x(()=>{"use strict"});function Id(t){let e=(t??"").trim();return/^pr_closed_without_merge\b/.test(e)?"blocked":/^(merge_failed|close_failed)\b/.test(e)||/^chain_base_changed\b/.test(e)||/^write action apply_delivery failed: .*hit conflicts/.test(e)?"conflict":/^(build_failed|ci_failed)\b/.test(e)?"loop_exhausted":"error"}function xv(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.to==="NEEDS_MANUAL")return r}return null}function Sv(t,e){if(t==="AWAITING_ANSWER")return{kind:"question"};if(t==="NEEDS_MANUAL"){let n=xv(e)?.reason,o={kind:Id(n)};return n&&(o.reason=n),o}}var Cd=x(()=>{"use strict"});function Sr(t){for(let e of Ad){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var Ad,Pd=x(()=>{"use strict";Ad=[{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 jd(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 Ev(t,e=Date.now()){return`${jd((e-t)/1e3)} ago`}function Tv(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 Nd=x(()=>{"use strict"});var Od=x(()=>{"use strict"});function Ld(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function tc(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=Ld(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Er.test(r))return r;let n=Ld(t);return Er.test(n)?n:ci}function rc(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 tn(t){return`tasks/${t}/issue.yaml`}var ec,ao,ci,Er,li,Rv,co,en,Md=x(()=>{"use strict";ec=["bug","feature","epic"],ao="feature",ci="TASK",Er=/^[A-Z][A-Z0-9]{1,9}$/;li={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},Rv=li.backlog,co="tracker/config.yaml",en="tracker/counter"});function lo(t){let e=t.split(`
11
+ `)}function sc(t){let e=new Set;for(let r of t.items)if(r.kind==="procedure")for(let n of r.text.matchAll(Xv))e.add(n[1]);return[...e]}var Wv,qv,Xv,Bd=S(()=>{"use strict";Wv=[{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"}],qv=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*(.*)$/;Xv=/`([a-z][a-z0-9-]{1,39})`/g});function Qv(t){let e=[],r=null;for(let o of t.split(`
12
+ `)){let i=Zv.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 e$(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 Jv,Zv,Fd=S(()=>{"use strict";Jv=["done","deviated","partial","dropped"],Zv=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*[—:-]?\s*(done|deviated|partial|dropped)\b\s*[—:-]?\s*(.*)$/i});var Gd=S(()=>{"use strict"});var Kd=S(()=>{"use strict"});var Hd=S(()=>{"use strict"});function ac(t){return`codepipe-host-${t}`}function t$(t){let e=t.filter(r=>r!=="self-hosted");return`runs-on: [self-hosted${e.length?", "+e.join(", "):""}]`}var Wd=S(()=>{"use strict"});function r$(t){let e=t.toLowerCase(),r="";for(let o of e)r+=Object.prototype.hasOwnProperty.call(qd,o)?qd[o]:o;return r.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,50).replace(/-+$/g,"")}function n$(t,e,r){let o=(t&&t.includes("<TASK_ID>")?t:Yd).replace(/<TASK_ID>/g,e.toLowerCase()).replace(/<SLUG>/g,r??"");return o=o.replace(/-{2,}/g,"-").replace(/\/{2,}/g,"/").replace(/-\//g,"/").replace(/\/-/g,"/").replace(/^[-/]+|[-/]+$/g,""),o}function o$(t,e){if(t)return`${t.replace(/\/+$/,"")}/issue/${encodeURIComponent(e)}`}function Yt(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 cc(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 lc(t){if(!t.mirror)return t;let{mirror:e,...r}=t;return{...r,host:e.host,owner:e.owner,repoName:e.repoName}}function Rt(t){return`${t}${Vd}`}var Yd,lj,qd,Vt,Vd,uc=S(()=>{"use strict";Yd="codepipe/<TASK_ID>",lj=50,qd={\u0430:"a",\u0431:"b",\u0432:"v",\u0433:"g",\u0434:"d",\u0435:"e",\u0451:"e",\u0436:"zh",\u0437:"z",\u0438:"i",\u0439:"y",\u043A:"k",\u043B:"l",\u043C:"m",\u043D:"n",\u043E:"o",\u043F:"p",\u0440:"r",\u0441:"s",\u0442:"t",\u0443:"u",\u0444:"f",\u0445:"h",\u0446:"c",\u0447:"ch",\u0448:"sh",\u0449:"sch",\u044A:"",\u044B:"y",\u044C:"",\u044D:"e",\u044E:"yu",\u044F:"ya"};Vt=/^[a-z][a-z0-9-]{1,30}$/,Vd="-codepipe-ctx"});function i$(t){return t==="simple"||t==="gitflow"||t==="release"}function dc(t){return t==="integration"||t==="stable"||t==="release_pattern"}function s$(t){let e=t.endsWith("/*")?t.slice(0,-2):t;return Yt(e)}function a$(t){let e=new Set(pc[t.flow].roles);for(let r of Object.keys(t.branchTypes??{}))dc(r)&&e.add(r);return e}function nn(t){if(t==null)return{config:null,errors:[]};let e=[];if(typeof t!="object"||Array.isArray(t))return{config:null,errors:["git: must be a mapping"]};let r=t,n=r.flow;if(!i$(n))return e.push(`git.flow must be one of simple | gitflow | release (got ${JSON.stringify(n)})`),{config:null,errors:e};let o=n,i={},s=r.branch_types??r.branchTypes;if(s!==void 0)if(typeof s!="object"||s===null||Array.isArray(s))e.push("git.branch_types must be a mapping of role \u2192 name/pattern");else for(let[d,m]of Object.entries(s)){if(!dc(d)){e.push(`git.branch_types: unknown role "${d}"`);continue}if(typeof m!="string"||!zd(d,m)){e.push(`git.branch_types.${d}: invalid branch name/pattern ${JSON.stringify(m)}`);continue}i[d]=m}let a=new Set(pc[o].roles);for(let d of Object.keys(i))a.add(d);let c={},l=r.branches;if(l!==void 0)if(typeof l!="object"||l===null||Array.isArray(l))e.push("git.branches must be a mapping of role \u2192 branch name");else for(let[d,m]of Object.entries(l)){if(!dc(d)){e.push(`git.branches: unknown role "${d}"`);continue}if(!a.has(d)){e.push(`git.branches.${d}: role not part of flow "${o}"`);continue}if(typeof m!="string"||!zd(d,m)){e.push(`git.branches.${d}: invalid branch name/pattern ${JSON.stringify(m)}`);continue}c[d]=m}let u,p=r.commit;if(p!==void 0)if(typeof p!="object"||p===null||Array.isArray(p))e.push("git.commit must be a mapping");else{let d=p.subject;d!==void 0&&typeof d!="string"?e.push("git.commit.subject must be a string"):typeof d=="string"?u={subject:d}:u={}}return e.length>0?{config:null,errors:e}:{config:{flow:o,branches:c,...Object.keys(i).length>0?{branchTypes:i}:{},...u?{commit:u}:{}},errors:[]}}function zd(t,e){return t==="release_pattern"?s$(e):Yt(e)}function c$(t,e,r){let n=r??"main",o=e??t;if(!o)return{flow:"simple",integration:n};let i=a$(o),s=u=>o.branches[u]??o.branchTypes?.[u],a=s("integration")??n,c=i.has("stable")?s("stable"):void 0,l=i.has("release_pattern")?s("release_pattern"):void 0;return{flow:o.flow,integration:a,...c?{stable:c}:{},...l?{releasePattern:l}:{}}}function mi(t){return t.gitFlow?.integration??t.defaultBranch??"main"}function l$(t,e){return e??mi(t)}function Xd(t,e){if(e.endsWith("/*")){let r=e.slice(0,-1);return t.startsWith(r)&&t.length>r.length}return t===e}function fc(t,e){return e.flow==="simple"?!1:!!(t===e.integration||e.stable&&t===e.stable||e.releasePattern&&Xd(t,e.releasePattern))}function po(t){let e=t.branches??[],r=e.some(s=>/^release\//.test(s)),n=e.includes("develop")||e.includes("dev"),o=r?"release":n?"gitflow":"simple",i={integration:u$(o,t)};if(o!=="simple"){let s=d$(t,i.integration??"");s&&(i.stable=s)}return o==="release"&&(i.release_pattern="release/*"),{flow:o,branches:i}}function u$(t,e){let r=e.branches??[];if(t!=="simple"){if(r.includes("develop"))return"develop";if(r.includes("dev"))return"dev"}return e.defaultBranch??r[0]??""}function d$(t,e){let r=t.branches??[],n=t.defaultBranch;if(n&&(n==="main"||n==="master")&&n!==e)return n;if(r.includes("main")&&e!=="main")return"main";if(r.includes("master")&&e!=="master")return"master"}function mc(t,e){if(t.flow==="simple")return!1;if(t.flow!==e.flow)return!0;let r=t.branches,n=e.branches;return(r.integration??"")!==(n.integration??"")||(r.stable??"")!==(n.stable??"")||(r.release_pattern??"")!==(n.release_pattern??"")}var pc,Jd=S(()=>{"use strict";uc();pc={simple:{roles:["integration"]},gitflow:{roles:["integration","stable"]},release:{roles:["integration","stable","release_pattern"]}}});function p$(t,e,r=72){let n=(t||Zd).replace(/\{key\}/g,e.key).replace(/\{summary\}/g,e.summary).replace(/\s+/g," ").trim(),o=Number.isFinite(r)&&r>0?Math.floor(r):72;if(n.length<=o)return n;let i=n.slice(0,o),s=i.lastIndexOf(" ");return s>=Math.floor(o/2)?i.slice(0,s).trimEnd():i.trimEnd()}var Zd,fj,Qd=S(()=>{"use strict";Zd="{key}: {summary}",fj=72});function f$(t,e){return`${t}:${e}`}var ep=S(()=>{"use strict"});function tp(t){let e=(t??"").trim();return/^pr_closed_without_merge\b/.test(e)?"blocked":/^(merge_failed|close_failed)\b/.test(e)||/^chain_base_changed\b/.test(e)||/^write action apply_delivery failed: .*hit conflicts/.test(e)?"conflict":/^(build_failed|ci_failed)\b/.test(e)?"loop_exhausted":"error"}function m$(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.to==="NEEDS_MANUAL")return r}return null}function h$(t,e){if(t==="AWAITING_ANSWER")return{kind:"question"};if(t==="NEEDS_MANUAL"){let n=m$(e)?.reason,o={kind:tp(n)};return n&&(o.reason=n),o}}var rp=S(()=>{"use strict"});function Er(t){for(let e of np){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var np,op=S(()=>{"use strict";np=[{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 ip=S(()=>{"use strict"});function sp(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 g$(t,e=Date.now()){return`${sp((e-t)/1e3)} ago`}function y$(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 ap=S(()=>{"use strict"});var cp=S(()=>{"use strict"});function lp(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function gc(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=lp(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Rr.test(r))return r;let n=lp(t);return Rr.test(n)?n:hi}function yc(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 sn(t){return`tasks/${t}/issue.yaml`}var hc,fo,hi,Rr,gi,w$,mo,on,up=S(()=>{"use strict";hc=["bug","feature","epic"],fo="feature",hi="TASK",Rr=/^[A-Z][A-Z0-9]{1,9}$/;gi={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},w$=gi.backlog,mo="tracker/config.yaml",on="tracker/counter"});function ho(t){let e=t.split(`
14
14
  `),r=e.indexOf("---");if(r<0)return;let n=e.slice(r+1),o=n.lastIndexOf("## Attachments");o>=0&&n.slice(o+1).every(c=>c.trim()===""||/^- \[[^\]]*\]\(attachments\/[^)]*\)$/.test(c.trim()))&&(n=n.slice(0,o));let i=n.join(`
15
- `).trim();if(!(!i||i==="_(no description)_"))return i}function Iv(t){return`{{ancestorExcerpt:${t}}}`}var ui,Dd=x(()=>{"use strict";ui=/\{\{ancestorExcerpt:([^}]+)\}\}/g});var Cv,Ud=x(()=>{"use strict";Cv="youtrack"});function Tr(t){let e=t.match(/^git@([^:/]+):/);if(e)return e[1]??null;let r=t.match(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)/);if(r)return r[1]??null;let n=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return n?n[1]??null:null}function uo(t){switch(t){case rn.gitlab:return"oauth2";case rn.bitbucket:return"x-token-auth";default:return"x-access-token"}}var rn,Dt,Bd=x(()=>{"use strict";rn={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Dt="x-bitbucket-api-token-auth"});var Fd=x(()=>{"use strict"});var Gd=x(()=>{"use strict";Ud();Bd();Fd()});var Kd={};Ge(Kd,{ACTION_ID_RE:()=>Ia,ACTION_STEP_DEFAULT_TIMEOUT_SEC:()=>Aa,ALL_JOB_ROLES:()=>$a,ALL_MODEL_ROLE_KEYS:()=>Ea,ANALYSIS_MAX_DRAFTS:()=>nc,ANCESTOR_EXCERPT_RE:()=>ui,ANCESTOR_EXCERPT_TOKEN:()=>Iv,ANNOTATION_MAX_PER_TASK:()=>ma,BACKFILL_MAX_DRAFTS:()=>Av,BITBUCKET_API_TOKEN_GIT_USER:()=>Dt,BUILD_DISCOVERY:()=>Vu,COCHANGE_DEFAULTS:()=>ot,CODEPIPE_COMMANDS:()=>Ad,CODE_REVIEW_VERIFY:()=>Xu,COMMIT_STYLE_MAX_LENGTH:()=>Ma,CONTEXT_PACK_DECAY:()=>ga,CONTEXT_PACK_DEFAULTS:()=>vr,CONTEXT_REPO_SUFFIX:()=>Ed,CONTEXT_STAMP_FILE:()=>gt,CONTEXT_TEMPLATE_CHANGELOG:()=>ra,CONTEXT_TEMPLATE_VERSION:()=>_u,COUNCIL_MAX_ANSWER:()=>a_,DEFAULT_BRANCH_PATTERN:()=>Sd,DEFAULT_HUB_URL:()=>mt,DEFAULT_INTERNAL_ISSUE_TYPE:()=>ao,DEFAULT_INTERNAL_TRACKER_PREFIX:()=>ci,DEFAULT_LLM_PROVIDER:()=>Je,DEFAULT_REGIMEN_ALIASES:()=>ed,DEFAULT_TRACKER_PROVIDER:()=>Cv,ENV_NAME_RE:()=>Ze,FALLBACK_MODEL:()=>Zu,GIT_HOST_DOMAINS:()=>rn,INTERNAL_ISSUE_TYPES:()=>ec,INTERNAL_TRACKER_CONFIG_PATH:()=>co,INTERNAL_TRACKER_COUNTER_PATH:()=>en,INTERNAL_TRACKER_DEFAULT_STATUS:()=>Rv,INTERNAL_TRACKER_PREFIX_RE:()=>Er,INTERNAL_TRACKER_STATUSES:()=>li,LANE_PHASES:()=>Db,LANE_SEGMENTS:()=>va,LANGUAGE_AUTO:()=>ve,LANGUAGE_SUGGESTIONS:()=>Qr,LANGUAGE_VALUE_MAX_LENGTH:()=>io,LEGACY_CONTEXT_STAMP_FILE:()=>zr,LLM_PROVIDER_SUGGESTIONS:()=>Sa,MIN_SUPPORTED_PROTOCOL:()=>Cu,MODEL_ALIAS_SUGGESTIONS:()=>ii,MODEL_DERIVED_DIR:()=>Pb,MODEL_DERIVED_INDEX_PATH:()=>ei,MODEL_DIR:()=>Ib,MODEL_EDGE_KINDS:()=>pa,MODEL_ENTITY_ID_RE:()=>Lu,MODEL_FACTS_DIR:()=>Ab,MODEL_FAMILY_PREFERENCE:()=>Qu,MODEL_HAIKU:()=>oi,MODEL_LEVELS:()=>Ou,MODEL_OPUS:()=>Ce,MODEL_README_PATH:()=>Cb,MODEL_RELATES_PATH:()=>wr,MODEL_SEARCH_MAX_LIMIT:()=>ha,MODEL_SEARCH_MAX_ROWS:()=>jb,MODEL_SEARCH_ROW_TEXT_MAX:()=>ri,MODEL_SONNET:()=>Zr,MODEL_SUB_ROLES:()=>Ju,OBSERVER_MAX_DECISION:()=>o_,OBSERVER_MAX_SUMMARY:()=>i_,OFFICIAL_MARKETPLACES:()=>pd,PHASES:()=>ba,PIPELINE_COLUMNS:()=>Wu,PLANNING_LANE_MAX_JOBS:()=>Gb,PLANNING_ROLES:()=>Yu,PLATFORM_VERSION:()=>Xe,PROJECT_ID_RE:()=>Yt,PROJECT_LANGUAGE_SECTIONS:()=>oo,PROJECT_MODEL_FORMAT_VERSION:()=>Oe,PROJECT_SETTINGS_MANIFEST:()=>id,PROMPT_ROLES:()=>ud,PROTOCOL_VERSION:()=>ht,RECOMMENDED_ROLE_MODELS:()=>no,RELATES_MIN_OVERLAP:()=>fa,ROLE_MAX_DESCRIPTION:()=>QP,ROLE_MAX_REFS:()=>ZP,ROLE_NAME_RE:()=>Ba,ROLE_SCENARIOS:()=>ai,SKILL_MAX_DESCRIPTION:()=>r_,SKILL_NAME_RE:()=>qa,SOLUTION_STATUSES:()=>hv,STRING_MAP_MAX_ENTRIES:()=>Oa,STRING_MAP_MAX_VALUE_LENGTH:()=>La,additionsSince:()=>oa,ago:()=>Ev,attentionFor:()=>Sv,autoLanguageConfig:()=>nd,autoModelDefault:()=>Ta,canonicalizeModelEdgeSheet:()=>Mu,canonicalizeModelIdentityTable:()=>Uu,canonicalizeModelShard:()=>Du,canonicalizeModelTaskEvent:()=>Bu,changesSince:()=>ia,classifyAttentionReason:()=>Id,compilePlanRework:()=>fv,contextRepoName:()=>Et,deserializeModelConfig:()=>Yb,emptyModelConfig:()=>Jr,enabledPluginsSetting:()=>sv,extractLanguageConfig:()=>Zb,extractTaskMdBody:()=>lo,findSettingField:()=>sd,firstFreeInternalTrackerPrefix:()=>rc,flattenSettingFields:()=>Da,fmtDuration:()=>jd,fmtUptime:()=>Tv,ghRunnerHostLabel:()=>Ja,ghRunnerRunsOnSnippet:()=>kv,gitCloneUrlDomain:()=>Tr,httpsTokenUser:()=>uo,internalIssueYamlPath:()=>tn,isAllAutoLanguage:()=>Qb,isAutoLanguage:()=>od,isBodyEditFrozen:()=>Mb,isModelEntityId:()=>ti,isPromptRole:()=>Ha,isProtocolCompatible:()=>Jn,isReservedEnvName:()=>Mt,isTerminalPhase:()=>Lb,isValidBranchName:()=>so,jobLane:()=>Fb,laneSegmentForPhase:()=>Ub,makeTaskId:()=>$v,mergeRoles:()=>Ga,mergeSkills:()=>za,mismatchedIds:()=>pv,modelAnnotationPath:()=>ca,modelComponentSlug:()=>Nu,modelCorrelatesPath:()=>la,modelEventPath:()=>kr,modelIdentityPath:()=>eo,modelNodeKey:()=>ge,modelShardNeedsRebuild:()=>Nb,modelStructureShardPath:()=>da,modelTaskNodeKey:()=>Se,modelTouchedPath:()=>ua,parseActionDefinition:()=>Pa,parseCodepipeCommand:()=>Sr,parseContextStamp:()=>na,parseMarketplaceSource:()=>fd,parseMarketplaces:()=>ov,parseModelConfig:()=>Wb,parseModelNodeKey:()=>te,parsePlanItems:()=>Va,parseRepoMirror:()=>Za,parseSolutionItems:()=>yv,pipelineColumnForPhase:()=>Bb,pipelineRepoSpec:()=>Qa,prescribedSkills:()=>Xa,promptOverridePath:()=>Wa,renderContextStamp:()=>Zn,resolveBranchName:()=>bv,resolveModelForRole:()=>Kb,resolveProvider:()=>Hb,rolesForScenario:()=>Ka,serializeModelConfig:()=>qb,serializeModelEdgeSheet:()=>br,serializeModelIdentityTable:()=>wa,serializeModelShard:()=>ya,serializeModelTaskEvent:()=>Xr,serializeModelYaml:()=>$r,solutionCoverage:()=>wv,suggestInternalTrackerPrefix:()=>tc,validateActionInput:()=>_a,validateCouncilVerdict:()=>cv,validateModelEdgeSheet:()=>to,validateModelIdentityTable:()=>ro,validateModelShard:()=>Ot,validateModelTaskEvent:()=>Lt,validateObserverPlan:()=>av,validateRoleDefinition:()=>Fa,validateSettingEdit:()=>Ua,validateSkill:()=>Ya,youtrackIssueUrl:()=>vv,zeroUsage:()=>qt});var nc,Av,F=x(()=>{"use strict";Au();Pu();ju();ka();Hu();qu();xa();Ra();ad();Na();ja();ld();dd();md();gd();yd();wd();kd();bd();vd();$d();xd();Td();Rd();Cd();Pd();_d();Nd();Od();Md();Dd();Gd();nc=20,Av=15});function Q(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Ke=x(()=>{"use strict"});import{existsSync as Pv,readFileSync as _v,readdirSync as jv}from"node:fs";import{dirname as Nv,join as oc}from"node:path";import{parse as Ov}from"yaml";function Lv(t=process.cwd()){let e=t;for(;;){if(Pv(oc(e,it,"project.yaml")))return e;let r=Nv(e);if(r===e)return null;e=r}}function Mv(t){return oc(t,it)}function Ae(t=process.cwd()){let e=Lv(t);if(!e)return null;let r=Mv(e),n=Dv(_v(oc(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function Hd(t,e,r){return jv(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 nn(t,e=process.cwd()){try{let r=Ae(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function Dv(t){let e=Ov(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=Za(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 Wd(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 it,wt=x(()=>{"use strict";F();it=".codepipe"});import{homedir as qd}from"node:os";import{mkdirSync as Uv,readFileSync as Bv,writeFileSync as Fv,existsSync as ic}from"node:fs";import{dirname as zd,join as di,resolve as Gv}from"node:path";import{fileURLToPath as Kv}from"node:url";function Vd(t){let e=di(Yd,".env");if(ic(e)&&process.loadEnvFile(e),t){let r=di(Yd,"profiles",t,".env");ic(r)&&process.loadEnvFile(r)}}function on(t){let e=Q("CONFIG");return e||(t?di(qd(),".codepipe","profiles",t,"config.json"):di(qd(),".codepipe","config.json"))}function kt(t){let e=on(t);if(!ic(e))return null;let r=Bv(e,"utf-8");return JSON.parse(r)}function Ut(t,e){let r=on(e);Uv(zd(r),{recursive:!0}),Fv(r,JSON.stringify(t,null,2)+`
16
- `,{mode:384})}function sn(t){if(t)return{cfg:st(t),profile:t};let e;try{e=Ae()?.spec.projectId||void 0}catch{}if(e){let r=kt(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=kt(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 ${on(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var Yd,He=x(()=>{"use strict";Ke();wt();Yd=Gv(zd(Kv(import.meta.url)),"..")});import{homedir as Xd}from"node:os";import{existsSync as Jd,mkdirSync as Zd,readFileSync as Qd,writeFileSync as ep}from"node:fs";import{dirname as tp,join as rp}from"node:path";function np(t,e,r){let n=Y(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},ae(n)}function op(t,e){let r=Y(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],ae(r),!0)}function ip(t){return Object.keys(Y(t)?.secrets??{}).sort()}function pi(t,e,r){let n=Y(t);if(!n)return"mismatch";let o=n.sandboxPins??{},i=o[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(o[e]=r,n.sandboxPins=o,ae(n),"pinned")}function sp(t,e){let r=Y(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],ae(r),!0):!1}function Tt(t){return rp(Xd(),".codepipe","secrets",`${t}.json`)}function Y(t){let e=Tt(t);return Jd(e)?JSON.parse(Qd(e,"utf-8")):null}function ae(t){let e=Tt(t.projectId);Zd(tp(e),{recursive:!0}),ep(e,JSON.stringify(t,null,2)+`
17
- `,{mode:384})}function fi(){return rp(Xd(),".codepipe","shared.json")}function sc(){let t=fi();return Jd(t)?JSON.parse(Qd(t,"utf-8")):null}function ap(t){let e=fi();Zd(tp(e),{recursive:!0}),ep(e,JSON.stringify(t,null,2)+`
18
- `,{mode:384})}function an(t){let e=Y(t)?.claude?.oauthToken;return e||sc()?.claude?.oauthToken}function po(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 ac){let n=e[r];n&&!process.env[r]&&(process.env[r]=n)}}function cn(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var ac,pe=x(()=>{"use strict";ac=["GH_TOKEN","BITBUCKET_EMAIL","BITBUCKET_API_TOKEN","GITLAB_TOKEN","YOUTRACK_URL","YOUTRACK_TOKEN"]});import{appendFileSync as Hv,existsSync as lp,mkdirSync as Wv,renameSync as up,statSync as qv,unlinkSync as Yv}from"node:fs";import{Writable as zv}from"node:stream";import{join as Vv}from"node:path";function mi(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=Xv(process.env[`${t}_MAX_BYTES`]??String(dp.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):dp.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function Xv(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 hi(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(Jv(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 Jv(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:Zv(o)).join(" ");return`${r} ${t} ${n}`}function Zv(t){try{return JSON.stringify(t)}catch{return String(t)}}var dp,ln,cc=x(()=>{"use strict";dp={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},ln=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&Wv(e.dir,{recursive:!0}),this.currentPath=Vv(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
15
+ `).trim();if(!(!i||i==="_(no description)_"))return i}function b$(t){return`{{ancestorExcerpt:${t}}}`}var yi,dp=S(()=>{"use strict";yi=/\{\{ancestorExcerpt:([^}]+)\}\}/g});var k$,pp=S(()=>{"use strict";k$="youtrack"});function Tr(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 go(t){switch(t){case an.gitlab:return"oauth2";case an.bitbucket:return"x-token-auth";default:return"x-access-token"}}var an,Ut,fp=S(()=>{"use strict";an={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Ut="x-bitbucket-api-token-auth"});var mp=S(()=>{"use strict"});var hp=S(()=>{"use strict";pp();fp();mp()});var gp={};Ge(gp,{ACTION_ID_RE:()=>Da,ACTION_STEP_DEFAULT_TIMEOUT_SEC:()=>Ba,ALL_JOB_ROLES:()=>Aa,ALL_MODEL_ROLE_KEYS:()=>Oa,ANALYSIS_MAX_DRAFTS:()=>wc,ANCESTOR_EXCERPT_RE:()=>yi,ANCESTOR_EXCERPT_TOKEN:()=>b$,ANNOTATION_MAX_PER_TASK:()=>xa,BACKFILL_MAX_DRAFTS:()=>v$,BITBUCKET_API_TOKEN_GIT_USER:()=>Ut,BRANCH_SLUG_MAX_LENGTH:()=>lj,BUILD_DISCOVERY:()=>gd,COCHANGE_DEFAULTS:()=>ot,CODEPIPE_COMMANDS:()=>np,CODE_REVIEW_VERIFY:()=>yd,COMMIT_STYLE_MAX_LENGTH:()=>Ya,CONTEXT_PACK_DECAY:()=>Ea,CONTEXT_PACK_DEFAULTS:()=>$r,CONTEXT_REPO_SUFFIX:()=>Vd,CONTEXT_STAMP_FILE:()=>gt,CONTEXT_TEMPLATE_CHANGELOG:()=>da,CONTEXT_TEMPLATE_VERSION:()=>Zu,COUNCIL_MAX_ANSWER:()=>oj,DEFAULT_BRANCH_PATTERN:()=>Yd,DEFAULT_COMMIT_SUBJECT:()=>Zd,DEFAULT_HUB_URL:()=>mt,DEFAULT_INTERNAL_ISSUE_TYPE:()=>fo,DEFAULT_INTERNAL_TRACKER_PREFIX:()=>hi,DEFAULT_LLM_PROVIDER:()=>Je,DEFAULT_REGIMEN_ALIASES:()=>vd,DEFAULT_SUBJECT_MAX:()=>fj,DEFAULT_TRACKER_PROVIDER:()=>k$,ENV_NAME_RE:()=>Ze,FALLBACK_MODEL:()=>bd,GIT_FLOW_PRESETS:()=>pc,GIT_HOST_DOMAINS:()=>an,INTERACTIVE_ROLES:()=>md,INTERNAL_ISSUE_TYPES:()=>hc,INTERNAL_TRACKER_CONFIG_PATH:()=>mo,INTERNAL_TRACKER_COUNTER_PATH:()=>on,INTERNAL_TRACKER_DEFAULT_STATUS:()=>w$,INTERNAL_TRACKER_PREFIX_RE:()=>Rr,INTERNAL_TRACKER_STATUSES:()=>gi,LANE_PHASES:()=>kv,LANE_SEGMENTS:()=>Pa,LANGUAGE_AUTO:()=>ge,LANGUAGE_SUGGESTIONS:()=>rn,LANGUAGE_VALUE_MAX_LENGTH:()=>uo,LEGACY_CONTEXT_STAMP_FILE:()=>Jr,LLM_PROVIDER_SUGGESTIONS:()=>Na,MIN_SUPPORTED_PROTOCOL:()=>zu,MODEL_ALIAS_SUGGESTIONS:()=>di,MODEL_DERIVED_DIR:()=>fv,MODEL_DERIVED_INDEX_PATH:()=>si,MODEL_DIR:()=>uv,MODEL_EDGE_KINDS:()=>va,MODEL_ENTITY_ID_RE:()=>rd,MODEL_FACTS_DIR:()=>pv,MODEL_FAMILY_PREFERENCE:()=>kd,MODEL_HAIKU:()=>ui,MODEL_LEVELS:()=>td,MODEL_OPUS:()=>Te,MODEL_README_PATH:()=>dv,MODEL_RELATES_PATH:()=>br,MODEL_SEARCH_MAX_LIMIT:()=>Sa,MODEL_SEARCH_MAX_ROWS:()=>hv,MODEL_SEARCH_ROW_TEXT_MAX:()=>ci,MODEL_SONNET:()=>tn,MODEL_SUB_ROLES:()=>wd,OBSERVER_MAX_DECISION:()=>tj,OBSERVER_MAX_SUMMARY:()=>rj,OFFICIAL_MARKETPLACES:()=>Nd,PHASES:()=>Ca,PIPELINE_COLUMNS:()=>dd,PLANNING_LANE_MAX_JOBS:()=>Sv,PLANNING_ROLES:()=>fd,PLATFORM_VERSION:()=>Xe,PROJECT_ID_RE:()=>Vt,PROJECT_LANGUAGE_SECTIONS:()=>lo,PROJECT_MODEL_FORMAT_VERSION:()=>Le,PROJECT_SETTINGS_MANIFEST:()=>Rd,PROMPT_ROLES:()=>_d,PROTOCOL_VERSION:()=>ht,RECOMMENDED_ROLE_MODELS:()=>co,RELATES_MIN_OVERLAP:()=>$a,ROLE_MAX_DESCRIPTION:()=>X_,ROLE_MAX_REFS:()=>z_,ROLE_NAME_RE:()=>Xa,ROLE_SCENARIOS:()=>fi,SKILL_MAX_DESCRIPTION:()=>Q_,SKILL_NAME_RE:()=>rc,SOLUTION_STATUSES:()=>Jv,STRING_MAP_MAX_ENTRIES:()=>Wa,STRING_MAP_MAX_VALUE_LENGTH:()=>qa,additionsSince:()=>fa,ago:()=>g$,attentionFor:()=>h$,autoLanguageConfig:()=>Sd,autoModelDefault:()=>La,branchMatchesFlow:()=>fc,canonicalizeModelEdgeSheet:()=>nd,canonicalizeModelIdentityTable:()=>id,canonicalizeModelShard:()=>od,canonicalizeModelTaskEvent:()=>sd,changesSince:()=>ma,classifyAttentionReason:()=>tp,compilePlanRework:()=>zv,contextRepoName:()=>Rt,deserializeModelConfig:()=>Cv,detectGitFlowPreset:()=>po,effectiveClusterBase:()=>l$,emptyModelConfig:()=>en,enabledPluginsSetting:()=>Gv,extractLanguageConfig:()=>Nv,extractTaskMdBody:()=>ho,findSettingField:()=>Td,firstFreeInternalTrackerPrefix:()=>yc,flattenSettingFields:()=>Va,fmtDuration:()=>sp,fmtUptime:()=>y$,ghRunnerHostLabel:()=>ac,ghRunnerRunsOnSnippet:()=>t$,gitCloneUrlDomain:()=>Tr,gitFlowDiverges:()=>mc,httpsTokenUser:()=>go,internalIssueYamlPath:()=>sn,isAllAutoLanguage:()=>Ov,isAutoLanguage:()=>Ed,isBodyEditFrozen:()=>bv,isInteractiveRole:()=>_a,isModelEntityId:()=>ai,isPromptRole:()=>ec,isProtocolCompatible:()=>ro,isReservedEnvName:()=>Dt,isTerminalPhase:()=>wv,isValidBranchName:()=>Yt,jobLane:()=>xv,laneSegmentForPhase:()=>vv,makeTaskId:()=>f$,matchesReleasePattern:()=>Xd,mergeRoles:()=>Za,mergeSkills:()=>oc,mismatchedIds:()=>Vv,modelAnnotationPath:()=>ya,modelComponentSlug:()=>ed,modelCorrelatesPath:()=>wa,modelEventPath:()=>kr,modelIdentityPath:()=>io,modelNodeKey:()=>he,modelShardNeedsRebuild:()=>gv,modelStructureShardPath:()=>ka,modelTaskNodeKey:()=>Se,modelTouchedPath:()=>ba,parseActionDefinition:()=>Fa,parseCodepipeCommand:()=>Er,parseContextStamp:()=>pa,parseGitConfig:()=>nn,parseMarketplaceSource:()=>Od,parseMarketplaces:()=>Bv,parseModelConfig:()=>Tv,parseModelNodeKey:()=>te,parsePlanItems:()=>ic,parseRepoMirror:()=>cc,parseSolutionItems:()=>Qv,pipelineColumnForPhase:()=>$v,pipelineRepoSpec:()=>lc,prescribedSkills:()=>sc,promptOverridePath:()=>tc,renderCommitSubject:()=>p$,renderContextStamp:()=>no,repoBaseBranch:()=>mi,resolveBranchName:()=>n$,resolveModelForRole:()=>Ev,resolveProvider:()=>Rv,resolveRepoFlow:()=>c$,rolesForScenario:()=>Qa,serializeModelConfig:()=>Iv,serializeModelEdgeSheet:()=>vr,serializeModelIdentityTable:()=>Ta,serializeModelShard:()=>Ra,serializeModelTaskEvent:()=>Qr,serializeModelYaml:()=>xr,slugify:()=>r$,solutionCoverage:()=>e$,suggestInternalTrackerPrefix:()=>gc,validateActionInput:()=>Ga,validateCouncilVerdict:()=>Hv,validateModelEdgeSheet:()=>so,validateModelIdentityTable:()=>ao,validateModelShard:()=>Ot,validateModelTaskEvent:()=>Lt,validateObserverPlan:()=>Kv,validateRoleDefinition:()=>Ja,validateSettingEdit:()=>za,validateSkill:()=>nc,youtrackIssueUrl:()=>o$,zeroUsage:()=>Mt});var wc,v$,D=S(()=>{"use strict";Xu();Ju();Qu();Ia();ud();pd();ja();Ma();Id();Cd();Ha();Ka();Ad();jd();Ld();Dd();Ud();Bd();Fd();Gd();Kd();Hd();Wd();uc();Jd();Qd();ep();rp();op();ip();ap();cp();up();dp();hp();wc=20,v$=15});function Q(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Ke=S(()=>{"use strict"});import{existsSync as $$,readFileSync as x$,readdirSync as S$}from"node:fs";import{dirname as E$,join as bc}from"node:path";import{parse as R$}from"yaml";function T$(t=process.cwd()){let e=t;for(;;){if($$(bc(e,Qe,"project.yaml")))return e;let r=E$(e);if(r===e)return null;e=r}}function I$(t){return bc(t,Qe)}function Pe(t=process.cwd()){let e=T$(t);if(!e)return null;let r=I$(e),n=C$(x$(bc(r,"project.yaml"),"utf-8"));for(let o of n.gitConfigErrors??[])console.warn(`project.yaml: invalid git config \u2014 ${o}`);return{root:e,contextDir:r,spec:n}}function yp(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 cn(t,e=process.cwd()){try{let r=Pe(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function C$(t){let e=R$(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),n=String(e.name??r),o=Array.isArray(e.repos)?e.repos:[],i=[],s=[];s.push(...nn(e.git).errors.map(a=>`git: ${a}`));for(let a of o){if(!a||typeof a!="object")continue;let c=a,l=String(c.repo??c.repoName??""),u=String(c.name??l);if(!u||!l)continue;let p=c.host,d=p==="bitbucket"?"bitbucket":p==="gitlab"?"gitlab":"github",m=cc(c.mirror);c.git!==void 0&&c.git!==null&&s.push(...nn(c.git).errors.map(f=>`repos[${u}].git: ${f}`)),i.push({name:u,host:d,owner:String(c.owner??""),repoName:l,defaultBranch:String(c.default_branch??c.defaultBranch??"main"),mountAs:String(c.mount_as??c.mountAs??u),...m?{mirror:m}:{}})}return{projectId:r,name:n,repos:i,...s.length>0?{gitConfigErrors:s}:{}}}function wp(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}var Qe,wt=S(()=>{"use strict";D();Qe=".codepipe"});import{homedir as bp}from"node:os";import{mkdirSync as P$,readFileSync as A$,writeFileSync as _$,existsSync as kc}from"node:fs";import{dirname as vp,join as wi,resolve as j$}from"node:path";import{fileURLToPath as N$}from"node:url";function $p(t){let e=wi(kp,".env");if(kc(e)&&process.loadEnvFile(e),t){let r=wi(kp,"profiles",t,".env");kc(r)&&process.loadEnvFile(r)}}function ln(t){let e=Q("CONFIG");return e||(t?wi(bp(),".codepipe","profiles",t,"config.json"):wi(bp(),".codepipe","config.json"))}function bt(t){let e=ln(t);if(!kc(e))return null;let r=A$(e,"utf-8");return JSON.parse(r)}function Bt(t,e){let r=ln(e);P$(vp(r),{recursive:!0}),_$(r,JSON.stringify(t,null,2)+`
16
+ `,{mode:384})}function un(t){if(t)return{cfg:it(t),profile:t};let e;try{e=Pe()?.spec.projectId||void 0}catch{}if(e){let r=bt(e);if(r)return console.log(`[profile] ${e} \u2014 resolved from this folder's workspace`),{cfg:r,profile:e};console.error(`this folder is the workspace of project '${e}', but that CLI profile is not initialised on this machine \u2014 run \`codepipe init\` here (or pass --profile).`),process.exit(1)}return{cfg:it(void 0),profile:void 0}}function it(t){let e=bt(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 ${ln(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var kp,He=S(()=>{"use strict";Ke();wt();kp=j$(vp(N$(import.meta.url)),"..")});import{homedir as xp}from"node:os";import{existsSync as Sp,mkdirSync as Ep,readFileSync as Rp,writeFileSync as Tp}from"node:fs";import{dirname as Ip,join as Cp}from"node:path";function Pp(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 Ap(t,e){let r=q(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],ae(r),!0)}function _p(t){return Object.keys(q(t)?.secrets??{}).sort()}function bi(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 jp(t,e){let r=q(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],ae(r),!0):!1}function Tt(t){return Cp(xp(),".codepipe","secrets",`${t}.json`)}function q(t){let e=Tt(t);return Sp(e)?JSON.parse(Rp(e,"utf-8")):null}function ae(t){let e=Tt(t.projectId);Ep(Ip(e),{recursive:!0}),Tp(e,JSON.stringify(t,null,2)+`
17
+ `,{mode:384})}function ki(){return Cp(xp(),".codepipe","shared.json")}function vc(){let t=ki();return Sp(t)?JSON.parse(Rp(t,"utf-8")):null}function Np(t){let e=ki();Ep(Ip(e),{recursive:!0}),Tp(e,JSON.stringify(t,null,2)+`
18
+ `,{mode:384})}function dn(t){let e=q(t)?.claude?.oauthToken;return e||vc()?.claude?.oauthToken}function yo(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 $c){let n=e[r];n&&!process.env[r]&&(process.env[r]=n)}}function pn(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var $c,de=S(()=>{"use strict";$c=["GH_TOKEN","BITBUCKET_EMAIL","BITBUCKET_API_TOKEN","GITLAB_TOKEN","YOUTRACK_URL","YOUTRACK_TOKEN"]});import{appendFileSync as O$,existsSync as Lp,mkdirSync as L$,renameSync as Mp,statSync as M$,unlinkSync as D$}from"node:fs";import{Writable as U$}from"node:stream";import{join as B$}from"node:path";function vi(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=F$(process.env[`${t}_MAX_BYTES`]??String(Dp.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):Dp.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function F$(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 $i(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(G$(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 G$(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:K$(o)).join(" ");return`${r} ${t} ${n}`}function K$(t){try{return JSON.stringify(t)}catch{return String(t)}}var Dp,fn,xc=S(()=>{"use strict";Dp={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},fn=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&L$(e.dir,{recursive:!0}),this.currentPath=B$(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
19
19
  `)?e:e+`
20
- `;Hv(this.currentPath,r,"utf-8")}asWritable(){return new zv({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||!lp(this.currentPath)||qv(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;lp(n)&&(r>=this.cfg.maxFiles?Yv(n):up(n,`${this.currentPath}.${r+1}`))}up(this.currentPath,`${this.currentPath}.1`)}}}});function yi(t){return t===429||t>=500}function mp(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
21
- `+t.slice(t.length-e)}async function zt(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),gi);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(yi(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 wi(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),gi);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(yi(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 Vt(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(),gi);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(yi(s.status))throw new at(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await i$(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 i$(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function ki(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=hp.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: ${hp.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function Xt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),gi);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(yi(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 gp(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 s$(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 uc(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 fo(t,e){let r=Qa(e);if(!e.mirror)return{spec:r,host:Ir(r)};let n=t?Y(t)?.mirrorWrite:void 0;return{spec:r,host:Ir(r,n?.token?{token:n.token,...n.email?{bitbucketEmail:n.email}:{}}:void 0)}}function Ir(t,e){if(t.host==="github"){let r=e?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(r)return new pc(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 dc(r,n)}if(t.host==="gitlab"){let r=e?.token??process.env.GITLAB_TOKEN;if(r)return new fc(r)}return new mc}var Rr,at,gi,hp,dc,pc,fc,mc,Jt=x(()=>{"use strict";F();pe();Rr=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},at=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},gi=5e3;hp=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];dc=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 Rr(`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()}`)}},pc=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 Rr(`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
+ `;O$(this.currentPath,r,"utf-8")}asWritable(){return new U$({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||!Lp(this.currentPath)||M$(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;Lp(n)&&(r>=this.cfg.maxFiles?D$(n):Mp(n,`${this.currentPath}.${r+1}`))}Mp(this.currentPath,`${this.currentPath}.1`)}}}});function Si(t){return t===429||t>=500}function Fp(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
21
+ `+t.slice(t.length-e)}async function zt(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),xi);try{let i;try{i=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new st(`cannot reach api.github.com (${l instanceof Error?l.message:String(l)})`)}if(i.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(Si(i.status))throw new st(`api.github.com \u2192 ${i.status} ${i.statusText}`);if(!i.ok)throw new Error(`GitHub \u2192 ${i.status} ${i.statusText}`);let a=(await i.json()).login??"ok",c=i.headers.get("x-oauth-scopes");if(c!==null&&e&&!c.split(",").map(u=>u.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${c||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let l;try{let u=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});u.ok&&(l=(await u.json()).type)}catch{}if(l==="Organization"){let u=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});if(u.status===403)throw new Error(`token cannot access org "${e.owner}" (403) \u2014 for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens; for classic PATs: verify 'repo' or 'admin:org' scope`);if(u.status===404)throw new Error(`org "${e.owner}" not found or not visible to this token \u2014 check the org name; for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens`);if(!u.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${u.status} ${u.statusText}`)}}return a}finally{clearTimeout(o)}}async function Ei(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),xi);try{let s;try{s=await fetch(n,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},signal:o.signal})}catch(c){throw new st(`cannot reach api.github.com (${c instanceof Error?c.message:String(c)})`)}if(s.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(s.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(Si(s.status))throw new st(`api.github.com \u2192 ${s.status} ${s.statusText}`);if(!s.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${s.status} ${s.statusText}`);if((await s.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}finally{clearTimeout(i)}}async function Xt(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(),xi);try{let s;try{s=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new st(`cannot reach api.bitbucket.org (${c instanceof Error?c.message:String(c)})`)}if(s.ok)return t;if(s.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;if(Si(s.status))throw new st(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await X$(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 X$(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function Ri(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=Gp.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: ${Gp.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function Jt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),xi);try{let n;try{n=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"},signal:e.signal})}catch(i){throw new st(`cannot reach gitlab.com (${i instanceof Error?i.message:String(i)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(Si(n.status))throw new st(`gitlab.com \u2192 ${n.status} ${n.statusText}`);if(!n.ok)throw new Error(`GitLab \u2192 ${n.status} ${n.statusText}`);return(await n.json()).username??"ok"}finally{clearTimeout(r)}}async function Kp(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 wo(t,e){let r=lc(e);if(!e.mirror)return{spec:r,host:Cr(r)};let n=t?q(t)?.mirrorWrite:void 0;return{spec:r,host:Cr(r,n?.token?{token:n.token,...n.email?{bitbucketEmail:n.email}:{}}:void 0)}}function Cr(t,e){if(t.host==="github"){let r=e?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(r)return new Tc(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 Ic(r)}return new Cc}var Ir,st,xi,Gp,Rc,Tc,Ic,Cc,Zt=S(()=>{"use strict";D();de();Ir=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},st=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},xi=5e3;Gp=["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 Ir(`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()}`)}},Tc=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 Ir(`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 w=await g.text();u.push(`### CI job: ${f.name}
22
22
 
23
- ${mp(k,8e3)}`)}}return u.length===0?void 0:mp(u.join(`
23
+ ${Fp(w,8e3)}`)}}return u.length===0?void 0:Fp(u.join(`
24
24
 
25
- `),16e3)}catch{return}}async mergePR(e,r,n,o){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async addPRInlineComment(e,r,n,o,i){let s={Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:s});if(!a.ok)throw new Error(`github PR #${r}: ${a.status} ${await a.text()}`);let c=(await a.json()).head?.sha;if(!c)throw new Error(`github PR #${r}: no head sha`);let l=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/comments`,{method:"POST",headers:{...s,"Content-Type":"application/json"},body:JSON.stringify({body:i,commit_id:c,path:n,line:o,side:"RIGHT"})});if(!l.ok)throw new Error(`github inline comment PR #${r} ${n}:${o}: ${l.status} ${await l.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},fc=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 Rr(`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=s$(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()}`)}};mc=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(uc(e,r,"merge"))}async closePR(e,r,n){throw new Error(uc(e,r,"close"))}async addPRComment(e,r,n){throw new Error(uc(e,r,"comment"))}}});import{X509Certificate as kp}from"node:crypto";import{readFileSync as a$}from"node:fs";import Zt from"node:tls";function c$(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function $p(t=vp){if(yp)return;yp=!0;let e=Q("EXTRA_CA_FILE");if(!(!e||!bp))try{let r=c$(a$(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Zt.setDefaultCACertificates([...Zt.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 xp(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(`
26
- `)){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=Zt.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 kp(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function hc(t,e,r){return new Promise(n=>{let o=Zt.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 kp(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Sp(t,e=443,r=vp){let n=`${t}:${e}`,o=wp.get(n);if(o)return o;let i=p$(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return wp.set(n,i),i}async function p$(t,e,r){if(!bp)return!1;let n=8e3;if(await hc(t,e,n))return!0;let o=await u$(t,e,n),i=Zt.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()),Zt.setDefaultCACertificates([...i,...s]),await hc(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 hc(t,e,n)}var bp,yp,wp,vp,Ep=x(()=>{"use strict";Ke();bp=typeof Zt.getCACertificates=="function"&&typeof Zt.setDefaultCACertificates=="function",yp=!1,wp=new Map,vp=t=>console.warn(t)});function Cp(){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){$p();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(xp(s)&&await Sp(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function f$(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function m$(){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 gc(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=m$(),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&&f$(l.status,u)){await Tp(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await Tp(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Qt(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 Ap(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=Rp.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 Rp.set(o,l.id),l.id}async function Pp(t,e,r,n=mo){let o=await h$(t,e,r,n);await gc(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 gc(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function jp(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await gc(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function Np(t,e){let r=Ip.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 Ip.set(e,i.id),i.id}async function Op(t,e,r,n,o,i=mo){let s=await Np(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 Lp(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 Up(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 Bp(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 Fp(t,e){let r=e.stageField??mo,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=${Dp}&$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=>Hp(c,r))}async function Gp(t,e,r=mo){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Dp}`,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 Hp(await o.json(),r)}async function Kp(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${y$}&$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=Up(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 Hp(t,e=mo){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=Up(t.attachments);a&&(s.attachments=a);let c=w$(t.links);return c&&(s.links=c),s}async function Wp(t,e){let r=await k$(t,e);return r.length>0?r:b$(t,e)}async function k$(t,e){let r=await Np(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:qp(s.bundle)});return i}async function b$(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:qp(s.projectCustomField?.bundle)});return i}function qp(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var Tp,mo,Rp,Ip,Mp,g$,Dp,y$,Cr=x(()=>{"use strict";Ep();Tp=t=>new Promise(e=>setTimeout(e,t));mo="Stage",Rp=new Map;Ip=new Map;Mp="attachments(id,name,url,size,mimeType)",g$="links(direction,linkType(name),issues(idReadable))",Dp=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Mp},${g$}`,y$=`id,text,created,author(login),${Mp}`});function bt(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function un(t){return t instanceof at}async function Yp(t,e){let r=Y(t),n=[],o=[],i=()=>Date.now();if(e?.trackerProvider==="internal")n.push({name:"tracker",ok:!0,detail:"built-in tracker"});else if(r?.youtrack?.url&&r.youtrack.token)try{let c=await Qt({baseUrl:r.youtrack.url,token:r.youtrack.token});n.push({name:"youtrack",ok:!0}),o.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"youtrack",ok:!1,detail:bt(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:bt(c),checkedAt:i()})}else n.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),o.push({kind:"youtrack",present:!1,checkedAt:i()});let s=!1;if(r?.github?.token){s=!0;try{let c=await zt(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){un(c)?(n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"github",ok:!1,detail:bt(c)}),o.push({kind:"github",present:!0,ok:!1,detail:bt(c),checkedAt:i()}))}}else o.push({kind:"github",present:!1,checkedAt:i()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){s=!0;try{let c=await Vt(r.bitbucket.email,r.bitbucket.apiToken);n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){un(c)?(n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"bitbucket",ok:!1,detail:bt(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:bt(c),checkedAt:i()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Xt(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){un(c)?(n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"gitlab",ok:!1,detail:bt(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:bt(c),checkedAt:i()}))}}else o.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||n.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let u of e?.repos??[])if(u.host==="github")try{await wi(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){un(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:bt(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await wi(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){un(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:bt(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await wi(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){un(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:i()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:bt(l),checkedAt:i()})}else o.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:i()})}else o.push({kind:"contextWrite",present:!1,checkedAt:i()});let a=an(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 Bt(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 Bt(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:v$,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 zp(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 v$,dn=x(()=>{"use strict";pe();Jt();Cr();v$="claude-haiku-4-5-20251001"});import $$ from"node:http";import yc from"node:crypto";function bi(){let t=wc(yc.randomBytes(32)),e=wc(yc.createHash("sha256").update(t).digest()),r=wc(yc.randomBytes(32));return{verifier:t,challenge:e,state:r}}function bc(t){let e=new URL(x$);return e.search=new URLSearchParams({response_type:"code",client_id:Vp,redirect_uri:t.redirectUri,scope:E$,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function R$(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 Xp(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 I$(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 vc(t){let e=await fetch(S$,{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:Vp,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return I$(await e.json())}async function $c(t){let e=t.timeoutMs??T$,r=$$.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=bc({redirectUri:o,challenge:t.challenge,state:t.state}),s,a=new Promise((l,u)=>{s=setTimeout(()=>u(new Error("no-callback")),e),r.on("request",(p,d)=>{let m=new URL(p.url??"/",o);if(m.pathname!=="/callback"){d.statusCode=404,d.end();return}clearTimeout(s),d.setHeader("content-type","text/html"),d.end("<h3>Authorized \u2014 you can close this tab.</h3>");try{l(R$(m.searchParams,t.state))}catch(f){u(f)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>vc({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function Jp(t){let e=await $c(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
27
- ${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var Vp,x$,S$,kc,E$,T$,wc,xc=x(()=>{"use strict";Vp="9d1c250a-e61b-44d9-88ed-5944d1962f5e",x$="https://platform.claude.com/oauth/authorize",S$="https://platform.claude.com/v1/oauth/token",kc="https://platform.claude.com/oauth/code/callback",E$="org:create_api_key user:profile user:inference",T$=12e4,wc=t=>Buffer.from(t).toString("base64url")});import{spawn as C$}from"node:child_process";function Ar(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=C$(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var vi=x(()=>{"use strict"});import{existsSync as er,mkdirSync as cf,readFileSync as Tc,writeFileSync as pn}from"node:fs";import{homedir as D$}from"node:os";import{join as Rt}from"node:path";import{simpleGit as U$}from"simple-git";function go(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=Rt(t,o);er(s)||(pn(s,i),r.push(o))}return r}function tr(t,e,r){let n=Rt(D$(),".codepipe","profiles",t,"context-config");return cf(n,{recursive:!0}),pn(Rt(n,"project.yaml"),e.projectYaml),pn(Rt(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function Si(t,e,r){if(er(e))for(let n of fn){let o=Rt(e,n),i=Rt(t,n);if(!(!er(o)||er(i)))try{pn(i,Tc(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 mn(t){let e=Rt(t,".gitignore"),r=er(e)?Tc(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(fn.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
25
+ `),16e3)}catch{return}}async mergePR(e,r,n,o){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async addPRInlineComment(e,r,n,o,i){let s={Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:s});if(!a.ok)throw new Error(`github PR #${r}: ${a.status} ${await a.text()}`);let c=(await a.json()).head?.sha;if(!c)throw new Error(`github PR #${r}: no head sha`);let l=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/comments`,{method:"POST",headers:{...s,"Content-Type":"application/json"},body:JSON.stringify({body:i,commit_id:c,path:n,line:o,side:"RIGHT"})});if(!l.ok)throw new Error(`github inline comment PR #${r} ${n}:${o}: ${l.status} ${await l.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},Ic=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 Ir(`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 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()}`)}};Cc=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 qp}from"node:crypto";import{readFileSync as Z$}from"node:fs";import Qt from"node:tls";function Q$(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function zp(t=Vp){if(Hp)return;Hp=!0;let e=Q("EXTRA_CA_FILE");if(!(!e||!Yp))try{let r=Q$(Z$(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Qt.setDefaultCACertificates([...Qt.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 Xp(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 ex(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
26
+ `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function tx(t,e,r){return new Promise((n,o)=>{let i=Qt.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 qp(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function Pc(t,e,r){return new Promise(n=>{let o=Qt.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 rx(t){try{let e=await fetch(t);return e.ok?new qp(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Jp(t,e=443,r=Vp){let n=`${t}:${e}`,o=Wp.get(n);if(o)return o;let i=nx(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Wp.set(n,i),i}async function nx(t,e,r){if(!Yp)return!1;let n=8e3;if(await Pc(t,e,n))return!0;let o=await tx(t,e,n),i=Qt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=ex(o);if(!c)break;let l=await rx(c);if(!l)break;if(s.push(l.toString()),Qt.setDefaultCACertificates([...i,...s]),await Pc(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 Pc(t,e,n)}var Yp,Hp,Wp,Vp,Zp=S(()=>{"use strict";Ke();Yp=typeof Qt.getCACertificates=="function"&&typeof Qt.setDefaultCACertificates=="function",Hp=!1,Wp=new Map,Vp=t=>console.warn(t)});function rf(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function at(t,e,r){zp();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(Xp(s)&&await Jp(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function ox(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function ix(){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}=ix(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await at(t,r,n)}catch(u){a=new Error(`${e}: ${u instanceof Error?u.message:String(u)}`)}if(l){if(l.ok)return l;let u=await l.text();if(c<o&&ox(l.status,u)){await Qp(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await Qp(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function er(t){let e;try{e=await at(t,"/api/users/me?fields=login,fullName")}catch(n){throw new Error(`cannot reach ${t.baseUrl} (${n instanceof Error?n.message:String(n)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the YouTrack PAT)");if(!e.ok)throw new Error(`YouTrack \u2192 ${e.status} ${e.statusText}`);let r=await e.json();return r.login??r.fullName??"ok"}async function nf(t){try{let e=await at(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function sx(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=ef.get(o);if(i)return i;let s=await at(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!s.ok)throw new Error(`yt resolveStateId ${e}: ${s.status} ${await s.text()}`);let c=(await s.json()).customFields.find(u=>u.name===n);if(!c)throw new Error(`yt: issue ${e} has no ${n} custom field`);let l=c.projectCustomField.bundle.values.find(u=>u.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${n} bundle for ${e}`);return ef.set(o,l.id),l.id}async function of(t,e,r,n=bo){let o=await sx(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 sf(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 af(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 cf(t,e){let r=tf.get(e);if(r)return r;let n=await at(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!n.ok)throw new Error(`yt resolveProjectId: ${n.status} ${await n.text()}`);let i=(await n.json()).find(s=>s.shortName===e);if(!i)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return tf.set(e,i.id),i.id}async function lf(t,e,r,n,o,i=bo){let s=await cf(t,e),a=await at(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:s},summary:r,description:n,customFields:[{name:i,$type:"StateIssueCustomField",value:{name:o,$type:"StateBundleElement"}}]})});if(!a.ok)throw new Error(`yt createIssue: ${a.status} ${await a.text()}`);let c=await a.json();return{id:c.id,key:c.idReadable}}async function uf(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await at(t,"/api/commands",{method:"POST",body:JSON.stringify({query:o,issues:[{idReadable:e}]})});if(!i.ok)throw new Error(`yt applyIssueLink (${o} on ${e}): ${i.status} ${await i.text()}`)}function ff(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 mf(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 hf(t,e){let r=e.stageField??bo,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=${pf}&$top=200`,s=await at(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);let a=await s.json();if(e.columns&&e.columns.length>0&&a.length>0&&!a.some(l=>(l.customFields??[]).some(u=>u.name===r))){let l=[...new Set((a[0]?.customFields??[]).map(u=>u.name).filter(u=>!!u))];throw new Error(`youtrack.stage_field "${r}" does not exist in project ${e.projectKey} \u2014 YouTrack ignored the status filter and would have returned unrelated issues. `+(l.length>0?`Fields on the issues: ${l.join(", ")}.`:"The issues carry no custom fields at all."))}return a.map(c=>wf(c,r))}async function gf(t,e,r=bo){let n=`/api/issues/${encodeURIComponent(e)}?fields=${pf}`,o=await at(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return wf(await o.json(),r)}async function yf(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${cx}&$top=500`,o=await at(t,n);if(!o.ok)throw new Error(`yt listComments ${e}: ${o.status} ${await o.text()}`);return(await o.json()).filter(s=>s.created>r).map(s=>{let a={id:s.id,issueId:e,author:s.author?.login??"unknown",body:s.text??"",createdAt:new Date(s.created).toISOString()},c=ff(s.attachments);return c&&(a.attachments=c),a})}function lx(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 wf(t,e=bo){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=ff(t.attachments);a&&(s.attachments=a);let c=lx(t.links);return c&&(s.links=c),s}async function bf(t,e){let r=await ux(t,e);return r.length>0?r:dx(t,e)}async function ux(t,e){let r=await cf(t,e),n=await at(t,`/api/admin/projects/${encodeURIComponent(r)}/customFields?fields=$type,field(name),bundle(values(name,archived))&$top=100`);if(!n.ok)return[];let o=await n.json(),i=[];for(let s of o)s.$type==="StateProjectCustomField"&&s.field?.name&&i.push({name:s.field.name,values:kf(s.bundle)});return i}async function dx(t,e){let r=`project: ${e}`,n=await at(t,`/api/issues?query=${encodeURIComponent(r)}&fields=customFields(name,$type,projectCustomField(bundle(values(name,archived))))&$top=1`);if(!n.ok)throw new Error(`yt fetchProjectStateFields ${e}: ${n.status} ${await n.text()}`);let o=await n.json(),i=[];for(let s of o[0]?.customFields??[])s.$type==="StateIssueCustomField"&&s.name&&i.push({name:s.name,values:kf(s.projectCustomField?.bundle)});return i}function kf(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var Qp,bo,ef,tf,df,ax,pf,cx,Pr=S(()=>{"use strict";Zp();Qp=t=>new Promise(e=>setTimeout(e,t));bo="Stage",ef=new Map;tf=new Map;df="attachments(id,name,url,size,mimeType)",ax="links(direction,linkType(name),issues(idReadable))",pf=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${df},${ax}`,cx=`id,text,created,author(login),${df}`});function kt(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function mn(t){return t instanceof st}async function vf(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 er({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 zt(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){mn(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 Xt(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){mn(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 Jt(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){mn(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 Ei(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){mn(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 Ei(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){mn(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 Ei(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){mn(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=dn(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 Ft(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 Ft(t){let e=new AbortController,r=setTimeout(()=>e.abort(),8e3);try{let n=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20","content-type":"application/json"},body:JSON.stringify({model:px,max_tokens:1,messages:[{role:"user",content:"hi"}]}),signal:e.signal});return n.status===200?"valid":n.status===401||n.status===403?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}async function $f(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1000",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});if(n.status!==200)return null;let i=(await n.json())?.data;if(!Array.isArray(i))return null;let s=[];for(let a of i){let c=a?.id;if(typeof c!="string"||c.trim().length===0)continue;let l=a?.created_at;s.push({id:c,...typeof l=="string"?{createdAt:l}:{}})}return s}catch{return null}finally{clearTimeout(r)}}var px,hn=S(()=>{"use strict";de();Zt();Pr();px="claude-haiku-4-5-20251001"});import fx from"node:http";import _c from"node:crypto";function Ti(){let t=jc(_c.randomBytes(32)),e=jc(_c.createHash("sha256").update(t).digest()),r=jc(_c.randomBytes(32));return{verifier:t,challenge:e,state:r}}function Oc(t){let e=new URL(mx);return e.search=new URLSearchParams({response_type:"code",client_id:xf,redirect_uri:t.redirectUri,scope:gx,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function wx(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 Sf(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 bx(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 Lc(t){let e=await fetch(hx,{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:xf,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return bx(await e.json())}async function Mc(t){let e=t.timeoutMs??yx,r=fx.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=Oc({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(wx(m.searchParams,t.state))}catch(f){u(f)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>Lc({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function Ef(t){let e=await Mc(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
27
+ ${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var xf,mx,hx,Nc,gx,yx,jc,Dc=S(()=>{"use strict";xf="9d1c250a-e61b-44d9-88ed-5944d1962f5e",mx="https://platform.claude.com/oauth/authorize",hx="https://platform.claude.com/v1/oauth/token",Nc="https://platform.claude.com/oauth/code/callback",gx="org:create_api_key user:profile user:inference",yx=12e4,jc=t=>Buffer.from(t).toString("base64url")});import{spawn as kx}from"node:child_process";function Ar(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=kx(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var Ii=S(()=>{"use strict"});import{existsSync as tr,mkdirSync as Of,readFileSync as Fc,writeFileSync as gn}from"node:fs";import{homedir as Cx}from"node:os";import{join as It}from"node:path";import{simpleGit as Px}from"simple-git";function vo(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=It(t,o);tr(s)||(gn(s,i),r.push(o))}return r}function rr(t,e,r){let n=It(Cx(),".codepipe","profiles",t,"context-config");return Of(n,{recursive:!0}),gn(It(n,"project.yaml"),e.projectYaml),gn(It(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function Ai(t,e,r){if(tr(e))for(let n of yn){let o=It(e,n),i=It(t,n);if(!(!tr(o)||tr(i)))try{gn(i,Fc(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 wn(t){let e=It(t,".gitignore"),r=tr(e)?Fc(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(yn.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
28
28
  `)?"":`
29
- `;return pn(e,r+i+B$.join(`
29
+ `;return gn(e,r+i+Ax.join(`
30
30
  `)+`
31
- `),!0}async function lf(t,e){try{if(!er(Rt(t,".git")))return;let r=U$(t),n=(await r.raw(["ls-files","--",...fn])).split(`
32
- `).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;mn(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 Cc(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 Rc(t){let e=new Map;for(let r of fn){let n=Rt(t,r);er(n)&&e.set(r,Tc(n))}return e}function Ic(t,e){cf(t,{recursive:!0});for(let[r,n]of e){let o=Rt(t,r);er(o)||pn(o,n)}}var fn,B$,Ft=x(()=>{"use strict";lt();fn=["project.yaml","regimen.yaml"];B$=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as F$,mkdirSync as G$,rmSync as K$,writeFileSync as Ac}from"node:fs";import{dirname as H$,isAbsolute as W$,join as pf,normalize as Ri}from"node:path";import{simpleGit as ff}from"simple-git";async function Pc(t,e){let r=Ri(t),o=(Ti.get(r)??Promise.resolve()).catch(()=>{}).then(e);Ti.set(r,o);try{return await o}finally{Ti.get(r)===o&&Ti.delete(r)}}async function Re(t,e,r){return Pc(t,()=>_c(t,e,r))}async function _c(t,e,r){if(!F$(pf(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=Ee(t,a.path);if(a.deleted){K$(c,{force:!0});continue}G$(H$(c),{recursive:!0}),a.encoding==="base64"?Ac(c,Buffer.from(a.content,"base64")):Ac(c,a.content)}let n=ff(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+=Ei)await n.raw(["add","-A","-f","--",...o.slice(a,a+Ei)]);for(let a=0;a<i.length;a+=Ei)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...i.slice(a,a+Ei)]);await n.raw(["reset","-q","--",...fn]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await Cc(t))}async function Cc(t){let e=ff(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=uf;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 V$(e);if(i.length>0&&i.every(a=>q$.has(a)||df.test(a)||Y$.test(a))){for(let a of i)df.test(a)?await z$(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 ${uf} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function z$(t,e,r){let n=async s=>await t.raw(["show",`:${s}:${r}`]).catch(()=>""),o=new Map;for(let s of[await n(2),await n(3)])for(let a of s.split(`
33
- `)){let c=a.trim();if(c)try{let l=JSON.parse(c);if(typeof l.id!="string")continue;o.has(l.id)||o.set(l.id,{raw:c,createdAt:typeof l.createdAt=="string"?l.createdAt:""})}catch{}}let i=[...o.values()].sort((s,a)=>s.createdAt.localeCompare(a.createdAt)).map(s=>s.raw);Ac(Ee(e,r),i.join(`
31
+ `),!0}async function Lf(t,e){try{if(!tr(It(t,".git")))return;let r=Px(t),n=(await r.raw(["ls-files","--",...yn])).split(`
32
+ `).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;wn(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 Hc(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 Gc(t){let e=new Map;for(let r of yn){let n=It(t,r);tr(n)&&e.set(r,Fc(n))}return e}function Kc(t,e){Of(t,{recursive:!0});for(let[r,n]of e){let o=It(t,r);tr(o)||gn(o,n)}}var yn,Ax,Gt=S(()=>{"use strict";ct();yn=["project.yaml","regimen.yaml"];Ax=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as _x,mkdirSync as jx,rmSync as Nx,writeFileSync as Wc}from"node:fs";import{dirname as Ox,isAbsolute as Lx,join as Uf,normalize as Ni}from"node:path";import{simpleGit as Bf}from"simple-git";async function qc(t,e){let r=Ni(t),o=(ji.get(r)??Promise.resolve()).catch(()=>{}).then(e);ji.set(r,o);try{return await o}finally{ji.get(r)===o&&ji.delete(r)}}async function Ie(t,e,r){return qc(t,()=>Yc(t,e,r))}async function Yc(t,e,r){if(!_x(Uf(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=Ee(t,a.path);if(a.deleted){Nx(c,{force:!0});continue}jx(Ox(c),{recursive:!0}),a.encoding==="base64"?Wc(c,Buffer.from(a.content,"base64")):Wc(c,a.content)}let n=Bf(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","--",...yn]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await Hc(t))}async function Hc(t){let e=Bf(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=Mf;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 Bx(e);if(i.length>0&&i.every(a=>Mx.has(a)||Df.test(a)||Dx.test(a))){for(let a of i)Df.test(a)?await Ux(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 ${Mf} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function Ux(t,e,r){let n=async s=>await t.raw(["show",`:${s}:${r}`]).catch(()=>""),o=new Map;for(let s of[await n(2),await n(3)])for(let a of s.split(`
33
+ `)){let c=a.trim();if(c)try{let l=JSON.parse(c);if(typeof l.id!="string")continue;o.has(l.id)||o.set(l.id,{raw:c,createdAt:typeof l.createdAt=="string"?l.createdAt:""})}catch{}}let i=[...o.values()].sort((s,a)=>s.createdAt.localeCompare(a.createdAt)).map(s=>s.raw);Wc(Ee(e,r),i.join(`
34
34
  `)+(i.length>0?`
35
- `:""))}async function V$(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
36
- `).map(r=>r.trim()).filter(Boolean)}function Ee(t,e){if(W$(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=Ri(pf(t,e)),n=Ri(t+"/");if(r!==Ri(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var uf,q$,Y$,df,Ei,Ti,lt=x(()=>{"use strict";Ft();uf=3,q$=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),Y$=/^model\/derived\//,df=/^tasks\/[^/]+\/comments\.jsonl$/,Ei=500,Ti=new Map});import{cpSync as ox,existsSync as yo,mkdirSync as yf,readFileSync as ix,readdirSync as sx,rmSync as wf,statSync as ax,writeFileSync as cx}from"node:fs";import{join as rr}from"node:path";function hn(t,e,r){let n=rr(t,"skills"),o=rr(e,".claude","skills"),i=rr(o,lx),s=ux(i),a={written:[],removed:[],skipped:[]},c=dx(n);for(let u of s)c.includes(u)||(wf(rr(o,u),{recursive:!0,force:!0}),a.removed.push(u));let l=[];for(let u of c){let p=rr(o,u);if(yo(p)&&!s.includes(u)){a.skipped.push(u);continue}yf(o,{recursive:!0}),wf(p,{recursive:!0,force:!0}),ox(rr(n,u),p,{recursive:!0}),l.push(u),a.written.push(u)}(l.length>0||a.removed.length>0||yo(i))&&(yf(o,{recursive:!0}),cx(i,JSON.stringify({managed:l.sort()},null,2)+`
37
- `)),(a.written.length>0||a.removed.length>0)&&r.info(`[skills] context \u2192 .claude/skills: ${a.written.length} written`+(a.removed.length>0?`, ${a.removed.length} removed`:""));for(let u of a.skipped)r.warn(`[skills] "${u}" exists in .claude/skills but is not managed by CodePipe \u2014 your copy wins; rename one of them to get the context version`);return a}function ux(t){if(!yo(t))return[];try{let e=JSON.parse(ix(t,"utf-8"));return Array.isArray(e.managed)?e.managed.filter(r=>typeof r=="string"):[]}catch{return[]}}function dx(t){return yo(t)?sx(t).filter(e=>{if(e.startsWith("."))return!1;let r=rr(t,e);try{return ax(r).isDirectory()&&yo(rr(r,"SKILL.md"))}catch{return!1}}):[]}var lx,Ii=x(()=>{"use strict";lx=".codepipe-managed.json"});import{existsSync as nr,readFileSync as gn,readdirSync as $f}from"node:fs";import{join as Nc}from"node:path";import{simpleGit as xf}from"simple-git";import{parse as Sf}from"yaml";function Ef(t){try{let e=Ee(t,co);if(!nr(e))return null;let r=Sf(gn(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!Er.test(n)?null:{prefix:n}}catch{return null}}function Tf(t){return`# Built-in tracker configuration \u2014 shared by every team member.
35
+ `:""))}async function Bx(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
36
+ `).map(r=>r.trim()).filter(Boolean)}function Ee(t,e){if(Lx(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=Ni(Uf(t,e)),n=Ni(t+"/");if(r!==Ni(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var Mf,Mx,Dx,Df,_i,ji,ct=S(()=>{"use strict";Gt();Mf=3,Mx=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),Dx=/^model\/derived\//,Df=/^tasks\/[^/]+\/comments\.jsonl$/,_i=500,ji=new Map});import{cpSync as zx,existsSync as $o,mkdirSync as Hf,readFileSync as Xx,readdirSync as Jx,rmSync as Wf,statSync as Zx,writeFileSync as Qx}from"node:fs";import{join as nr}from"node:path";function bn(t,e,r){let n=nr(t,"skills"),o=nr(e,".claude","skills"),i=nr(o,eS),s=tS(i),a={written:[],removed:[],skipped:[]},c=rS(n);for(let u of s)c.includes(u)||(Wf(nr(o,u),{recursive:!0,force:!0}),a.removed.push(u));let l=[];for(let u of c){let p=nr(o,u);if($o(p)&&!s.includes(u)){a.skipped.push(u);continue}Hf(o,{recursive:!0}),Wf(p,{recursive:!0,force:!0}),zx(nr(n,u),p,{recursive:!0}),l.push(u),a.written.push(u)}(l.length>0||a.removed.length>0||$o(i))&&(Hf(o,{recursive:!0}),Qx(i,JSON.stringify({managed:l.sort()},null,2)+`
37
+ `)),(a.written.length>0||a.removed.length>0)&&r.info(`[skills] context \u2192 .claude/skills: ${a.written.length} written`+(a.removed.length>0?`, ${a.removed.length} removed`:""));for(let u of a.skipped)r.warn(`[skills] "${u}" exists in .claude/skills but is not managed by CodePipe \u2014 your copy wins; rename one of them to get the context version`);return a}function tS(t){if(!$o(t))return[];try{let e=JSON.parse(Xx(t,"utf-8"));return Array.isArray(e.managed)?e.managed.filter(r=>typeof r=="string"):[]}catch{return[]}}function rS(t){return $o(t)?Jx(t).filter(e=>{if(e.startsWith("."))return!1;let r=nr(t,e);try{return Zx(r).isDirectory()&&$o(nr(r,"SKILL.md"))}catch{return!1}}):[]}var eS,Oi=S(()=>{"use strict";eS=".codepipe-managed.json"});import{existsSync as or,readFileSync as kn,readdirSync as zf}from"node:fs";import{join as zc}from"node:path";import{simpleGit as Xf}from"simple-git";import{parse as Jf}from"yaml";function Zf(t){try{let e=Ee(t,mo);if(!or(e))return null;let r=Jf(kn(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!Rr.test(n)?null:{prefix:n}}catch{return null}}function Qf(t){return`# Built-in tracker configuration \u2014 shared by every team member.
38
38
  # The issue-key prefix (<PREFIX>-<N>). Fixed at project init: changing it
39
39
  # later would orphan existing tasks/<KEY>/ directories.
40
40
  prefix: ${t}
@@ -42,13 +42,13 @@ prefix: ${t}
42
42
  # Statuses are the built-in default set for now:
43
43
  # Backlog | To Do | In Progress | Review | Done | Rejected
44
44
  # A configurable status set / pipeline mapping is a planned extension.
45
- `}function Oc(t=0){return`${t}
46
- `}function hx(t){return t==="depends_on"||t==="subtask"}function gx(t){let e;try{e=Sf(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=ec.includes(r.type)?r.type:ao,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;hx(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 Lc(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
+ `}function Xc(t=0){return`${t}
46
+ `}function sS(t){return t==="depends_on"||t==="subtask"}function aS(t){let e;try{e=Jf(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=hc.includes(r.type)?r.type:fo,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;sS(l.type)&&typeof l.target=="string"&&l.target&&o.push({type:l.type,targetKey:l.target})}let i=typeof r.created=="string"?r.created:new Date(0).toISOString(),s=typeof r.updated=="string"?r.updated:i,a=typeof r.assignee=="string"&&r.assignee.trim().length>0?r.assignee.trim():void 0;return{key:r.key,title:r.title,type:n,status:typeof r.status=="string"&&r.status?r.status:"Backlog",...a?{assignee:a}:{},links:o,created:i,updated:s}}function Jc(t){let e=[`key: ${t.key}`,`title: ${JSON.stringify(t.title)}`,`type: ${t.type}`,`status: ${JSON.stringify(t.status)}`];if(t.assignee&&e.push(`assignee: ${JSON.stringify(t.assignee)}`),t.links.length>0){e.push("links:");for(let r of t.links)e.push(` - type: ${r.type}`,` target: ${r.targetKey}`)}return e.push(`created: ${t.created}`,`updated: ${t.updated}`),e.join(`
47
47
  `)+`
48
- `}function ko(t,e){let r=Ee(t,tn(e));return nr(r)?gx(gn(r,"utf-8")):null}function Rf(t){let e=Nc(t,"tasks");if(!nr(e))return[];let r=[];for(let n of $f(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=ko(t,n.name);o&&r.push(o)}return r}function yx(t,e){let r=Ee(t,`tasks/${e}/task.md`);if(nr(r))return lo(gn(r,"utf-8"))}function bo(t,e,r={}){let n=r.withDescription?yx(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:wx(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function wx(t){return t.charAt(0).toUpperCase()+t.slice(1)}function kx(t){let e=Ee(t,en);if(!nr(e))return 0;let r=Number.parseInt(gn(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function bx(t,e){let r=Nc(t,"tasks");if(!nr(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of $f(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 vx(t,e){return Math.max(kx(t),bx(t,e))+1}async function If(t,e,r,n){return Pc(t,()=>$x(t,e,r,n))}async function $x(t,e,r,n){if(!nr(Nc(t,".git")))throw new Error(`context repo clone not found at ${t}`);await wo(t);let o=null;for(let i=0;i<vf;i++){let s=vx(t,e),a=`${e}-${s}`,c=[...r(a),{path:en,content:Oc(s)}];try{return await _c(t,c,n(a)),a}catch(l){if(o=l,await Sx(t,n(a)),await wo(t),xx(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${vf} attempts: ${o instanceof Error?o.message:String(o)}`)}function xx(t,e){for(let r of e){let n=Ee(t,r.path);if(!nr(n)||(r.encoding==="base64"?gn(n).toString("base64"):gn(n,"utf-8"))!==r.content)return!1}return!0}async function wo(t){let e=xf(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 Sx(t,e){let r=xf(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
48
+ `}function So(t,e){let r=Ee(t,sn(e));return or(r)?aS(kn(r,"utf-8")):null}function em(t){let e=zc(t,"tasks");if(!or(e))return[];let r=[];for(let n of zf(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=So(t,n.name);o&&r.push(o)}return r}function cS(t,e){let r=Ee(t,`tasks/${e}/task.md`);if(or(r))return ho(kn(r,"utf-8"))}function Eo(t,e,r={}){let n=r.withDescription?cS(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:lS(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function lS(t){return t.charAt(0).toUpperCase()+t.slice(1)}function uS(t){let e=Ee(t,on);if(!or(e))return 0;let r=Number.parseInt(kn(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function dS(t,e){let r=zc(t,"tasks");if(!or(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of zf(r,{withFileTypes:!0})){if(!i.isDirectory())continue;let s=n.exec(i.name);if(!s)continue;let a=Number.parseInt(s[1],10);Number.isFinite(a)&&a>o&&(o=a)}return o}function pS(t,e){return Math.max(uS(t),dS(t,e))+1}async function tm(t,e,r,n){return qc(t,()=>fS(t,e,r,n))}async function fS(t,e,r,n){if(!or(zc(t,".git")))throw new Error(`context repo clone not found at ${t}`);await xo(t);let o=null;for(let i=0;i<Vf;i++){let s=pS(t,e),a=`${e}-${s}`,c=[...r(a),{path:on,content:Xc(s)}];try{return await Yc(t,c,n(a)),a}catch(l){if(o=l,await hS(t,n(a)),await xo(t),mS(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${Vf} attempts: ${o instanceof Error?o.message:String(o)}`)}function mS(t,e){for(let r of e){let n=Ee(t,r.path);if(!or(n)||(r.encoding==="base64"?kn(n).toString("base64"):kn(n,"utf-8"))!==r.content)return!1}return!0}async function xo(t){let e=Xf(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 hS(t,e){let r=Xf(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 vf,Ai=x(()=>{"use strict";F();lt();vf=5});function yn(t,e,r,n){return[{path:"README.md",content:Dx(t,e)},{path:".gitignore",content:Ax()},{path:"CLAUDE.md",content:_x(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:Px()},{path:"knowledge/README.md",content:jx()},{path:"knowledge/build.yaml",content:Mx()},{path:"actions/README.md",content:Nx()},{path:"roles/README.md",content:Ox()},{path:"skills/README.md",content:Lx()},{path:"model/README.md",content:Ex()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:Cx()},{path:"adr/README.md",content:Tx()},{path:"adr/0000-template.md",content:Rx()},{path:"adr/INDEX.md",content:Ix()},{path:gt,content:Zn()},...t.trackerProvider==="internal"?[{path:co,content:Tf(t.youtrackProjectKey??ci)},{path:en,content:Oc()}]:[]]}function Ex(){return`# model/ \u2014 the project map
51
+ `)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var Vf,Mi=S(()=>{"use strict";D();ct();Vf=5});function vn(t,e,r,n){return[{path:"README.md",content:CS(t,e)},{path:".gitignore",content:vS()},{path:"CLAUDE.md",content:xS(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:$S()},{path:"knowledge/README.md",content:SS()},{path:"knowledge/build.yaml",content:IS()},{path:"actions/README.md",content:ES()},{path:"roles/README.md",content:RS()},{path:"skills/README.md",content:TS()},{path:"model/README.md",content:gS()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:kS()},{path:"adr/README.md",content:yS()},{path:"adr/0000-template.md",content:wS()},{path:"adr/INDEX.md",content:bS()},{path:gt,content:no()},...t.trackerProvider==="internal"?[{path:mo,content:Qf(t.youtrackProjectKey??hi)},{path:on,content:Xc()}]:[]]}function gS(){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 Tx(){return`# ADR \u2014 architecture decision records
78
+ `}function yS(){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 Rx(){return`# ADR-NNNN: <title>
106
+ `}function wS(){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 Ix(){return`# ADR index
128
+ `}function bS(){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 Cx(){return`# Audit
133
+ `}function kS(){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 It(t,e,r,n,o=Je,i){let s=t.trackerProvider==="internal";return{projectYaml:s?Ux(t):Bx(t,r,n),regimenYaml:Fx(t.automationLevel,s?!0:e,s,o,i)}}function Ax(){return`# codepipe project config is local to each member's workspace
142
+ `}function Ct(t,e,r,n,o=Je,i){let s=t.trackerProvider==="internal";return{projectYaml:s?PS(t):AS(t,r,n),regimenYaml:_S(t.automationLevel,s?!0:e,s,o,i)}}function vS(){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 Px(){return`# Index prompt
149
+ `}function $S(){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 _x(t){return`# Project context for the CodePipe agent
206
+ `}function xS(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 jx(){return`# Knowledge
234
+ `}function SS(){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 Nx(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
251
+ `}function ES(){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 Ox(){return`# roles/ \u2014 who reviews your work
290
+ `}function RS(){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 TS(){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 Mx(){return`# BUILD phase config. Discovered & maintained by the agent.
377
+ `}function IS(){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 CS(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 Ux(t){return`# Project description for CodePipe.
419
+ `}function PS(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
- ${Cf(t)}
444
+ ${rm()}${nm(t)}
445
445
  repos:
446
- ${Af(t)}
446
+ ${om(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,36 @@ ${Af(t)}
453
453
  # host: github
454
454
  # owner: your-org
455
455
  # repo: <project>-api-mirror
456
- `}function Cf(t){let e=t.language;return!e||Object.keys(e).length===0?"":`
456
+ `}function rm(){return`
457
+ # Git workflow. Omit this whole section for the default single-branch flow
458
+ # (\`simple\`) \u2014 nothing changes from today. Presets bind branch ROLES to your
459
+ # real branch names (names differ across projects: develop vs dev, main vs a
460
+ # stale master), so CodePipe targets the right base/target per repo.
461
+ # simple \u2014 one branch (integration); the default.
462
+ # gitflow \u2014 integration (e.g. develop) + stable (e.g. master).
463
+ # release \u2014 gitflow + a release_pattern (e.g. release/*).
464
+ # A single repo can override the whole section under \`repos[].git\`.
465
+ # git:
466
+ # flow: gitflow
467
+ # branches:
468
+ # integration: develop
469
+ # stable: master
470
+ # # release_pattern: "release/*" # with flow: release
471
+ `}function nm(t){let e=t.language;return!e||Object.keys(e).length===0?"":`
457
472
  # Languages the agent writes in, per area. \`auto\` = mirror the language of
458
473
  # the user's material. Also editable from the dashboard: project card \u2192
459
474
  # Settings \u2192 Language.
460
475
  language:
461
476
  ${Object.entries(e).map(([n,o])=>` ${n}: ${o}`).join(`
462
477
  `)}
463
- `}function Af(t){return t.repos.length===0?` [] # add repos here
478
+ `}function om(t){return t.repos.length===0?` [] # add repos here
464
479
  `:t.repos.map(e=>` - name: ${e.name}
465
480
  host: ${e.host}
466
481
  owner: ${e.owner}
467
482
  repo: ${e.repoName}
468
483
  mount_as: ${e.mountAs??e.name}`+(e.defaultBranch?`
469
484
  default_branch: ${e.defaultBranch}`:"")).join(`
470
- `)}function Bx(t,e,r){let n=e?`
485
+ `)}function AS(t,e,r){let n=e?`
471
486
  tracker_url: ${e}`:`
472
487
  # tracker_url: https://your.youtrack.cloud`,o=r?`require_assignee: true
473
488
  assignee: ${r}`:`require_assignee: false
@@ -515,7 +530,7 @@ ${Object.entries(e).map(([n,o])=>` ${n}: ${o}`).join(`
515
530
  # non-empty assignee. assignee only takes effect when require_assignee=true.
516
531
  ${o}`:` # project_key: \u2026
517
532
  # tracker_url: https://your.youtrack.cloud
518
- poll_interval_sec: 60`,s=Af(t);return`# Project description for CodePipe.
533
+ poll_interval_sec: 60`,s=om(t);return`# Project description for CodePipe.
519
534
  id: ${t.projectId}
520
535
  name: ${t.name}
521
536
 
@@ -547,10 +562,10 @@ adapters:
547
562
  # Branch (must keep the <TASK_ID> placeholder).
548
563
  branch:
549
564
  pattern: codepipe/<TASK_ID>
550
- ${Cf(t)}
565
+ ${rm()}${nm(t)}
551
566
  repos:
552
567
  ${s}
553
- `}function Fx(t,e,r=!1,n=Je,o){let i=t==="full",s=e?"true":"false",a=o?` # Model selection. This project's Claude subscription did not include every
568
+ `}function _S(t,e,r=!1,n=Je,o){let i=t==="full",s=e?"true":"false",a=o?` # Model selection. This project's Claude subscription did not include every
554
569
  # model in the recommended per-role split, so CodePipe set a single default
555
570
  # your subscription can serve for all roles. Tune per role later from the
556
571
  # dashboard (Project Settings \u2192 llm.models) or by editing this file.
@@ -597,6 +612,8 @@ ${s}
597
612
  analysis: opus
598
613
  # The interactive draft chat reasons about the project and holds a dialogue.
599
614
  chat: opus
615
+ # The project-configuration chat shapes a validated ConfigProposal in a dialogue.
616
+ config: opus
600
617
  # The observer reads a whole batch against accepted decisions \u2014 runs once per batch.
601
618
  observer: opus
602
619
  # The council unblocks a task; a wrong answer is paid for by every later phase.
@@ -729,35 +746,35 @@ ${a}
729
746
  # sandbox quota (how many runners the account may occupy), enforced by the HUB
730
747
  # and sized on the farm. A solo 'codepipe up' runs one worker. (ADR-0030)
731
748
 
732
- `}var Pr=x(()=>{"use strict";F();Ai()});function Mf(t){Lf=t}function ut(t,e="info"){Lf(t,e)}var Lf,_i=x(()=>{"use strict";Lf=t=>console.log(t)});import{homedir as nS,tmpdir as mN}from"node:os";import{existsSync as oS,mkdirSync as iS,mkdtempSync as gN,rmSync as yN}from"node:fs";import{join as Dc}from"node:path";import{simpleGit as Uc}from"simple-git";function _e(t,e,r){let n=r??Dc(nS(),".codepipe","repos");return Dc(n,t,e)}async function or(t,e,r={}){let n=_e(t,e.name,r.baseDir),o=r.cloneUrlOverride??Fc(e);if(!oS(Dc(n,".git"))){iS(n,{recursive:!0});let c=Uc();ut(`[git] clone ${o} \u2192 ${n}`);try{await c.clone(o,n)}catch(l){let u=l instanceof Error?l.message:String(l);throw new Error(`git clone failed: ${o}
733
- ${u.trim()}`)}}let i=Uc(n),s=(await i.remote(["get-url","origin"]).catch(()=>"")||"").toString().trim();s&&s!==o&&(ut(`[git] ${e.name}: origin ${s} \u2192 ${o} (spec changed)`),await i.remote(["set-url","origin",o]));try{await i.fetch()}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git fetch failed in ${n}
734
- ${l.trim()}`)}let a=e.defaultBranch??"main";return await i.checkout(["-B",a,`origin/${a}`]).catch(()=>{}),i}async function wn(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function sS(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&&ut(`[git] delivery ${n} resolved ${a.slice(0,10)} (expected ${o.slice(0,10)})`);let c=(await t.raw(["rev-parse","refs/codepipe-delivery^{tree}"])).trim();if(await wn(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await wn(t,i))throw new Error(`apply_delivery: base commit ${i.slice(0,10)} unavailable \u2014 cannot re-parent the delivery`);let l=(await t.raw([...Bc,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function aS(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await wn(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await wn(t,o)){let s=(await t.revparse([o])).trim();return await t.raw(["update-ref",n,s]).catch(()=>{}),s}let i=await r();return await t.raw(["update-ref",n,i]).catch(()=>{}),i}async function Uf(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 aS(t,i,()=>sS(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));p&&await t.raw(["branch","-D",a]).catch(()=>{});let m=`origin/${c}`;await wn(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([...Bc,"cherry-pick",d])}catch(w){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let v=w instanceof Error?w.message:String(w);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
735
- ${v.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 Bf(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 Ff(t,e,r){let{branchName:n,dropTaskKeys:o}=r,i=`origin/${n}`;if(!await wn(t,i))throw new Error(`rewrite_cluster_branch: ${i} not found upstream`);let s=`origin/${r.defaultBranch??"main"}`,a=(await t.raw(["merge-base",i,s])).trim(),c=(await t.raw(["rev-list","--reverse",`${a}..${i}`])).split(`
749
+ `}var _r=S(()=>{"use strict";D();Mi()});function dm(t){um=t}function lt(t,e="info"){um(t,e)}var um,Ui=S(()=>{"use strict";um=t=>console.log(t)});import{homedir as VS,tmpdir as bO}from"node:os";import{existsSync as zS,mkdirSync as XS,mkdtempSync as vO,rmSync as $O}from"node:fs";import{join as Qc}from"node:path";import{simpleGit as el}from"simple-git";function _e(t,e,r){let n=r??Qc(VS(),".codepipe","repos");return Qc(n,t,e)}async function ir(t,e,r={}){let n=_e(t,e.name,r.baseDir),o=r.cloneUrlOverride??rl(e);if(!zS(Qc(n,".git"))){XS(n,{recursive:!0});let c=el();lt(`[git] clone ${o} \u2192 ${n}`);try{await c.clone(o,n)}catch(l){let u=l instanceof Error?l.message:String(l);throw new Error(`git clone failed: ${o}
750
+ ${u.trim()}`)}}let i=el(n),s=(await i.remote(["get-url","origin"]).catch(()=>"")||"").toString().trim();s&&s!==o&&(lt(`[git] ${e.name}: origin ${s} \u2192 ${o} (spec changed)`),await i.remote(["set-url","origin",o]));try{await i.fetch()}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git fetch failed in ${n}
751
+ ${l.trim()}`)}let a=e.defaultBranch??"main";return await i.checkout(["-B",a,`origin/${a}`]).catch(()=>{}),i}async function $n(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function JS(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&&lt(`[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 $n(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await $n(t,i))throw new Error(`apply_delivery: base commit ${i.slice(0,10)} unavailable \u2014 cannot re-parent the delivery`);let l=(await t.raw([...tl,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function ZS(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await $n(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await $n(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 fm(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 ZS(t,i,()=>JS(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));p&&await t.raw(["branch","-D",a]).catch(()=>{});let m=`origin/${c}`;await $n(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([...tl,"cherry-pick",d])}catch(k){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let x=k instanceof Error?k.message:String(k);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
752
+ ${x.trim()}`)}}let w=(await t.revparse(["HEAD"])).trim(),h=r.push!==!1;if(h){let k=p?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push(k)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:w,pushed:h,...g>0?{baseMoved:g}:{}}}async function mm(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 hm(t,e,r){let{branchName:n,dropTaskKeys:o}=r,i=`origin/${n}`;if(!await $n(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(`
736
753
  `).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(`
737
- `).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([...Bc,"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
738
- ${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 Gf(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 Fc(t){return t.mirror?Df(t.mirror.host,t.mirror.owner,t.mirror.repoName):Df(t.host,t.owner,t.repoName)}function Df(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 ji(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 Kf(t){return(await Uc().listRemote(["--heads",t])).split(`
739
- `).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 Hf(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}var Bc,$o=x(()=>{"use strict";_i();Bc=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{createCipheriv as cS,createDecipheriv as lS,createHash as uS,createPrivateKey as dS,createPublicKey as Gc,diffieHellman as Wf,generateKeyPairSync as qf,hkdfSync as Yf,randomBytes as pS}from"node:crypto";function Ni(){let{publicKey:t,privateKey:e}=qf("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function We(t){let e=Buffer.from(t,"base64");return(uS("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function Gt(t,e){let r=Gc({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=qf("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=Wf({privateKey:o,publicKey:r}),c=Buffer.from(Yf("sha256",a,Buffer.concat([i,s]),zf,32)),l=pS(12),u=cS("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 kn(t,e){let r=JSON.parse(Buffer.from(e,"base64").toString("utf-8"));if(r.v!==1)throw new Error(`sealedbox: unsupported envelope version ${r.v}`);let n=dS({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=Gc({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=Gc(n).export({type:"spki",format:"der"}),a=Wf({privateKey:n,publicKey:o}),c=Buffer.from(Yf("sha256",a,Buffer.concat([i,s]),zf,32)),l=lS("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 zf,dt=x(()=>{"use strict";zf=Buffer.from("devpipe-sealedbox-v1","utf-8")});function xo(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 So(t,e=process.env){if(!t)return!1;let r=`https://oauth2:${t}@gitlab.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@gitlab.com:"),o(1,"ssh://git@gitlab.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function Eo(t,e=process.env){if(!t)return!1;let r=`https://${Dt}:${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 Kc(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 Xf(t,e=process.env){return Kc(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>xo(t,e),e)}function Jf(t,e=process.env){return Kc(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>So(t,e),e)}function Zf(t,e=process.env){return Kc(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Dt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>Eo(t,e),e)}var Oi=x(()=>{"use strict";F()});import{existsSync as cm,readFileSync as lm,writeFileSync as um}from"node:fs";import{join as dm}from"node:path";import{isMap as Li,parseDocument as pm}from"yaml";async function fm(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||!so(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=dm(t,"project.yaml");if(!cm(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=pm(lm(o,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>Li(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!Li(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),um(o,i.toString()),{repoName:r,defaultBranch:n}}function mm(t,e,r){let n=dm(t,"project.yaml");if(!cm(n))throw new Error(`project.yaml not found in context repo (${t})`);let o=pm(lm(n,"utf-8")),i=o.get("repos"),a=(i&&typeof i=="object"&&"items"in i?i.items:[]).find(c=>Li(c)&&String(c.get("name")??c.get("repo")??"")===e);if(!Li(a))throw new Error(`repo "${e}" not found in project.yaml repos[]`);a.set("mirror",{host:r.host,owner:r.owner,repo:r.repoName}),um(n,o.toString())}var Hc=x(()=>{"use strict";F()});import{existsSync as Vc,readFileSync as Xc}from"node:fs";import{join as Jc}from"node:path";import{simpleGit as bm}from"simple-git";import{parse as Zc}from"yaml";function $m(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(_S.source,"g")}function xm(t){let e=Jc(t,"project.yaml");if(Vc(e))try{let o=Zc(Xc(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=Jc(t,"tracker","config.yaml");if(Vc(r))try{let o=Zc(Xc(r,"utf-8"))?.prefix;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return null}function Sm(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 jS(t,e,r){let o=await bm(t).raw(["log","--numstat","--format=@@@ %H %ct %P %x09%s","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
740
- `))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=Qc.exec(u)??vm.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:Sm(c[3]),churn:l+u})}return i}async function NS(t,e){let n=await bm(t).raw(["diff","--numstat",`${e}^1`,e]).catch(()=>""),o=[];for(let i of n.split(`
741
- `)){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:Sm(s[3]),churn:a+c})}return o}function OS(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(Qc,"").trim();else if(c.prNumber!==null){if((t.trackerProjectKey??"").toUpperCase()==="PR")continue;u=`PR-${c.prNumber}`,p=c.subject.replace(Qc,"").replace(vm,"").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=ge("code",e,k),v=g.files.find(S=>S.key===w);if(v)v.churn=(v.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 km(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 Em(t){let e=await jS(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 NS(t.repoDir,r.sha))}return OS({repo:t.repo,issueKeyRe:t.issueKeyRe,commits:e,pathToCurrent:t.pathToCurrent,entityByKey:t.entityByKey,ignored:t.ignored,trackerProjectKey:t.trackerProjectKey??null})}function Tm(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?km(c,a)??c:a)}let n=[],o=0;for(let[i,s]of[...r.entries()].sort(([a],[c])=>a<c?-1:1)){let a=km(Ui(t,i),s);if(!a){o++;continue}n.push({path:kr(i),content:Xr(a)})}return{files:n,skippedPipeline:o}}function Ui(t,e){let r=Jc(t,kr(e));if(!Vc(r))return null;try{let n=Lt(Zc(Xc(r,"utf-8")));return n.ok?n.value:null}catch{return null}}var _S,Qc,vm,el=x(()=>{"use strict";F();_S=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g,Qc=/\(#(\d+)\)\s*$/,vm=/^Merge pull request #(\d+)\b/});import{simpleGit as LS}from"simple-git";async function Im(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(`
742
- `))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 Bi(t){let e=new Map;for(let r of t.entities){if(r.status!=="active"||!r.aliases)continue;let n=te(r.currentKey);if(n?.level==="code")for(let o of r.aliases){let i=te(o.key);i?.level==="code"&&e.set(i.path,n.path)}}return e}function Cm(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 $ of h.files){let b=o.get($)??$;!i.has(b)||s(b)||w.add(b)}if(w.size<2||w.size>a.commitFileCap)continue;let v=Math.max(0,r-h.timeSec),S=Math.pow(.5,v/c),R=[...w].sort();for(let $ of R)l.set($,(l.get($)??0)+S);for(let $=0;$<R.length;$++)for(let b=$+1;b<R.length;b++){let I=`${R[$]}\0${R[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[v,S]=h.split("\0"),R=(l.get(v)??0)+(l.get(S)??0)-w,$=R>0?w/R:0;$<m||d.push({a:v,b:S,weight:Math.round($*Rm)/Rm})}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,v)=>v.weight-w.weight||(w.a<v.a?-1:w.a>v.a?1:w.b<v.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:ge("code",e,h.a),to:ge("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 vn,Rm,Fi=x(()=>{"use strict";F();vn=["package-lock.json","pnpm-lock.yaml","yarn.lock"];Rm=1e4});import{createHash as MS}from"node:crypto";function US(t,e,r,n){for(let o=0;;o++){let s=`e_${MS("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(s))return s}}function Am(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=te(b.currentKey),N=I?i.get(I.path):void 0;if(I&&N){let H=ge(I.level,e,N.finalPath);if(l.has(H)&&!d.has(H)){h.push({entity:b,newKey:H,untilCommit:N.commit}),d.add(H);continue}}w.push(b)}let v=[];if(s){let b=new Map;for(let N of c){if(d.has(N))continue;let H=te(N);if(H?.level!=="code")continue;let z=a.get(H.path);z&&b.set(z,b.has(z)?null:N)}let I=new Map;for(let N of w){let H=te(N.currentKey);if(H?.level!=="code")continue;let z=s.get(H.path);z&&I.set(z,I.has(z)?null:N)}for(let N of w){let H=te(N.currentKey),z=H?.level==="code"?s.get(H.path):void 0,_=z?b.get(z):void 0;z&&_&&I.get(z)===N&&!d.has(_)?(h.push({entity:N,newKey:_,untilCommit:r}),d.add(_)):v.push(N)}}else v.push(...w);let S=new Map;for(let b of h){let I=te(b.entity.currentKey),N=te(b.newKey);if(I?.level!=="code"||!N)continue;let H=I.path,z=N.path;for(let _=H.lastIndexOf("/");_>0;_=H.lastIndexOf("/",_-1)){let y=H.slice(0,_),U=H.slice(_+1);if(!z.endsWith(`/${U}`))continue;let O=z.slice(0,z.length-U.length-1);if(O===y)continue;let K=`${y}\0${O}`,ee=S.get(K);S.set(K,{count:(ee?.count??0)+1,commit:ee&&ee.commit>b.untilCommit?ee.commit:b.untilCommit})}}let R=[...S.entries()].filter(([,b])=>b.count>=DS).map(([b,I])=>{let[N,H]=b.split("\0");return{from:N,to:H,commit:I.commit}}).sort((b,I)=>I.from.length-b.from.length||(b.from<I.from?-1:1)),$=[];for(let b of v){let I=te(b.currentKey),N=!1;if(I?.level==="component")for(let H of R){let z=null;if(I.path===H.from?z=H.to:I.path.startsWith(`${H.from}/`)&&(z=H.to+I.path.slice(H.from.length)),z===null)continue;let _=ge("component",e,z);l.has(_)&&!d.has(_)&&(h.push({entity:b,newKey:_,untilCommit:H.commit}),d.add(_),N=!0);break}N||$.push(b)}for(let b of h.sort((I,N)=>I.newKey<N.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 $)m.push({...b,status:"orphaned"});for(let b of c){if(d.has(b))continue;let I=US(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,Pm=x(()=>{"use strict";F();DS=5});import{simpleGit as BS}from"simple-git";async function _m(t,e,r){let n=BS(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
743
- `).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 jm(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 Nm=x(()=>{"use strict"});function Gi(t){return ge("container",t,FS)}function Om(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function Lm(t,e,r,n){let o=[],i=u=>{let p=ge("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:Om(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,GS)}},s=(u,p)=>{let d=ge("component",t,u),m=n.get(d);return{key:d,level:"component",label:Om(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:ge("code",t,h.path)})),...f.map(h=>({kind:"contains",from:p.key,to:ge("component",t,h)}))];c(u,g,k)},c=(u,p,d)=>{let m={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},f=Ot(m);if(!f.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${f.errors.join("; ")}`);o.push({path:da(t,u),content:ya(m)})},l={key:Gi(t),level:"container",label:t,...n.get(Gi(t))?{entityId:n.get(Gi(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 Mm(t,e){let r=[Gi(t)];for(let n of e.components)r.push(ge("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(ge("code",t,o.path));return r.sort()}var FS,GS,Dm=x(()=>{"use strict";F();FS=".";GS=12});import{simpleGit as Bm}from"simple-git";function _r(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 Gm(t,e="HEAD"){let r=Bm(t),n=(await r.revparse([e])).trim(),[o,i]=(await r.raw(["show","-s","--format=%cs %ct",n])).trim().split(/\s+/);return{commit:n,commitDate:o??"",commitTimeSec:Number(i??0),files:await To(t,n)}}async function To(t,e){let n=await Bm(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 Um(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function Km(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=Um(f.path);n.has(g)||n.set(g,[]),n.get(g).push(f);let k=g;for(;k!=="";){let h=Um(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 Fm,Ro=x(()=>{"use strict";Fm=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as Hm,readFileSync as Wm}from"node:fs";import{join as qm}from"node:path";import{simpleGit as KS}from"simple-git";import{parse as Ym}from"yaml";function jr(t){let e={ignore:Fm,containerNodeCap:HS,cochange:{...ot},issueKeyPattern:null,enabled:!0},r=qm(t,"regimen.yaml");if(!Hm(r))return e;let n;try{n=Ym(Wm(r,"utf-8"))}catch{return e}let o=n?.context,i=o&&typeof o=="object"?o.model:void 0;if(!i||typeof i!="object")return e;let s=i,a=Array.isArray(s.ignore)?s.ignore.filter(m=>typeof m=="string"&&m.trim().length>0):e.ignore,c=(m,f)=>typeof m=="number"&&Number.isInteger(m)&&m>0?m:f,l=c(s.container_node_cap,e.containerNodeCap),u=s.cochange&&typeof s.cochange=="object"?s.cochange:{},p={windowCommits:c(u.window_commits,e.cochange.windowCommits),commitFileCap:c(u.commit_file_cap,e.cochange.commitFileCap),supportMin:c(u.support_min,e.cochange.supportMin),jaccardMinPct:typeof u.jaccard_min_pct=="number"&&Number.isInteger(u.jaccard_min_pct)&&u.jaccard_min_pct>=0&&u.jaccard_min_pct<=100?u.jaccard_min_pct:e.cochange.jaccardMinPct,halfLifeDays:c(u.half_life_days,e.cochange.halfLifeDays),topK:c(u.top_k,e.cochange.topK)},d=typeof s.issue_key_pattern=="string"&&s.issue_key_pattern.trim().length>0?s.issue_key_pattern.trim():null;return{ignore:a,containerNodeCap:l,cochange:p,issueKeyPattern:d,enabled:s.enabled!==!1}}function tl(t,e){let r=qm(t,eo(e));if(!Hm(r))return null;let n=Ym(Wm(r,"utf-8")),o=ro(n);if(!o.ok)throw new Error(`model: ${eo(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function rl(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await Gm(r,t.ref??"HEAD"),s=_r(o.ignore),a=i.files.filter(w=>!s(w.path)),c=Km(a,o.containerNodeCap),l=tl(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await KS(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=jm(await _m(r,l.builtFromCommit,i.commit)),p=new Map((await To(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=Am({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:Mm(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),f=Lm(e,i.commit,c,m.byKey),g=_r([...o.ignore,...vn]),k=Cm({repo:e,headTimeSec:i.commitTimeSec,filesets:await Im(r,i.commit,o.cochange.windowCommits),pathToCurrent:Bi(m.table),currentPaths:new Set(a.map(w=>w.path)),ignored:g,settings:o.cochange}),h=[{path:eo(e),content:wa(m.table)},...f.files.map(w=>({path:w.path,content:w.content})),{path:la(e),content:br({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 HS,nl=x(()=>{"use strict";F();Fi();Pm();Nm();Dm();Ro();HS=1500});import{existsSync as Vm,readFileSync as Xm,readdirSync as WS}from"node:fs";import{join as ol}from"node:path";import{parse as Jm}from"yaml";function qS(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 Zm(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<fa)return null;let s=i/Math.min(n.size,o.size),a=qS(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(s*c*zm)/zm;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[Se(t.taskKey),Se(e.taskKey)]:[Se(e.taskKey),Se(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function Qm(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=Zm(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 eh(t,e,r,n){let o=Se(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=Zm(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 Ki(t){let e=ol(t,"model/facts/events");if(!Vm(e))return[];let r=[];for(let n of WS(e).sort())if(n.endsWith(".yaml"))try{let o=Lt(Jm(Xm(ol(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function th(t){let e=ol(t,wr);if(!Vm(e))return[];try{let r=to(Jm(Xm(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function Hi(t){return br({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var zm,il=x(()=>{"use strict";F();zm=1e4});var Io={};Ge(Io,{collectSearchRows:()=>nh,readContextIndexHub:()=>YS,rebuildSearchIndex:()=>oh,searchIndexPath:()=>zi,searchModelIndex:()=>zS,toFtsQuery:()=>ih});import{existsSync as xn,readFileSync as $n,readdirSync as qi}from"node:fs";import{join as vt}from"node:path";import{parse as Yi}from"yaml";function zi(t){return vt(t,".git","codepipe-model-index.sqlite")}function YS(t){let e=vt(t,"regimen.yaml");if(!xn(e))return"off";try{let n=Yi($n(e,"utf-8"))?.context,o=n&&typeof n=="object"?n.index:null;return(o&&typeof o=="object"?o.hub:null)==="metadata"?"metadata":"off"}catch{return"off"}}async function rh(){try{let{createRequire:t}=await import("node:module");return t(import.meta.url)("node:sqlite")}catch{return null}}function Wi(t){return t.length>ri?t.slice(0,ri):t}function sl(t){if(!xn(t))return[];let e=[];for(let r of qi(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=vt(t,r.name);r.isDirectory()?e.push(...sl(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function nh(t){let e=[];for(let i of sl(vt(t,"model/derived/structure"))){let s;try{s=Yi($n(i,"utf-8"))}catch{continue}let a=Ot(s);if(a.ok)for(let c of a.value.nodes){let l=te(c.key);l&&e.push({nodeId:c.key,kind:l.level,text:Wi(`${l.path} ${c.label??""}`.trim())})}}let r=vt(t,"model/facts/events");if(xn(r)){for(let i of qi(r).sort())if(i.endsWith(".yaml"))try{let s=Lt(Yi($n(vt(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:Wi(`${a.taskKey} ${a.title??""} ${c}`.trim())})}catch{}}let n=vt(t,"model/facts/annotations");if(xn(n)){let i=new Map;for(let s of sl(vt(t,"model/facts/identity")))try{let a=Yi($n(s,"utf-8"));for(let c of a?.entities??[])c.status==="active"&&c.entityId&&c.currentKey&&i.set(c.entityId,c.currentKey)}catch{}for(let s of qi(n).sort())if(s.endsWith(".md"))try{let a=$n(vt(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:Wi(c[2].trim())})}catch{}}let o=vt(t,"adr");if(xn(o))for(let i of qi(o).sort()){let s=/^(\d{4})-/.exec(i)?.[1];if(!(!s||!i.endsWith(".md")))try{let a=$n(vt(o,i),"utf-8").split(`
744
- `).slice(0,6);e.push({nodeId:`adr::ADR-${s}`,kind:"adr",text:Wi(a.filter(c=>c.trim()).join(" "))})}catch{}}return e}async function oh(t){let e=nh(t),r=await rh();if(!r)return{rows:e,indexed:!1};let n=new r.DatabaseSync(zi(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 ih(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 zS(t,e,r){let n=await rh();if(!n)throw new Error("model search needs Node with built-in sqlite (>= 22.13) on this CLI");xn(zi(t))||await oh(t);let o=ih(e);if(!o)return[];let i=Math.min(Math.max(r??20,1),ha),s=new n.DatabaseSync(zi(t));try{return s.prepare(`SELECT node_id AS nodeId, kind, snippet(model_fts, 2, '[', ']', '\u2026', 10) AS snippet,
754
+ `).map(w=>w.trim().toUpperCase()).filter(w=>w.length>0).some(w=>l.has(w))?p++:u.push(m);if(p===0)return{commit:(await t.revparse([i])).trim(),dropped:0};await t.checkout(["-B",n,a]);for(let m of u)try{await t.raw([...tl,"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
755
+ ${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 gm(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 rl(t){return t.mirror?pm(t.mirror.host,t.mirror.owner,t.mirror.repoName):pm(t.host,t.owner,t.repoName)}function pm(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 xn(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 Bi(t){return(await el().listRemote(["--heads",t])).split(`
756
+ `).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 ym(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}var tl,Sn=S(()=>{"use strict";Ui();tl=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{createCipheriv as QS,createDecipheriv as eE,createHash as tE,createPrivateKey as rE,createPublicKey as nl,diffieHellman as wm,generateKeyPairSync as bm,hkdfSync as km,randomBytes as nE}from"node:crypto";function Fi(){let{publicKey:t,privateKey:e}=bm("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function We(t){let e=Buffer.from(t,"base64");return(tE("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function Kt(t,e){let r=nl({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=bm("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=wm({privateKey:o,publicKey:r}),c=Buffer.from(km("sha256",a,Buffer.concat([i,s]),vm,32)),l=nE(12),u=QS("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 En(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=rE({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=nl({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=nl(n).export({type:"spki",format:"der"}),a=wm({privateKey:n,publicKey:o}),c=Buffer.from(km("sha256",a,Buffer.concat([i,s]),vm,32)),l=eE("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 vm,ut=S(()=>{"use strict";vm=Buffer.from("devpipe-sealedbox-v1","utf-8")});function To(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 Io(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 Co(t,e=process.env){if(!t)return!1;let r=`https://${Ut}:${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 ol(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 xm(t,e=process.env){return ol(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>To(t,e),e)}function Sm(t,e=process.env){return ol(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>Io(t,e),e)}function Em(t,e=process.env){return ol(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Ut}:${encodeURIComponent(t)}@bitbucket.org/`,()=>Co(t,e),e)}var Gi=S(()=>{"use strict";D()});import{existsSync as Lm,readFileSync as Mm,writeFileSync as Dm}from"node:fs";import{join as Um}from"node:path";import{isMap as Om,parseDocument as Bm}from"yaml";async function Fm(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||!Yt(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=Um(t,"project.yaml");if(!Lm(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=Bm(Mm(o,"utf-8"));return Ki(i,r).set("default_branch",n),Dm(o,i.toString()),{repoName:r,defaultBranch:n}}function Gm(t,e,r){let n=Um(t,"project.yaml");if(!Lm(n))throw new Error(`project.yaml not found in context repo (${t})`);let o=Bm(Mm(n,"utf-8"));Ki(o,e).set("mirror",{host:r.host,owner:r.owner,repo:r.repoName}),Dm(n,o.toString())}function Ki(t,e){let r=t.get("repos"),o=(r&&typeof r=="object"&&"items"in r?r.items:[]).find(i=>Om(i)&&String(i.get("name")??i.get("repo")??"")===e);if(!Om(o))throw new Error(`repo "${e}" not found in project.yaml repos[]`);return o}var Hi=S(()=>{"use strict";D()});import{existsSync as ll,readFileSync as ul}from"node:fs";import{join as dl}from"node:path";import{simpleGit as Vm}from"simple-git";import{parse as pl}from"yaml";function Xm(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(xE.source,"g")}function Jm(t){let e=dl(t,"project.yaml");if(ll(e))try{let o=pl(ul(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=dl(t,"tracker","config.yaml");if(ll(r))try{let o=pl(ul(r,"utf-8"))?.prefix;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return null}function Zm(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 SE(t,e,r){let o=await Vm(t).raw(["log","--numstat","--format=@@@ %H %ct %P %x09%s","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
757
+ `))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=fl.exec(u)??zm.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:Zm(c[3]),churn:l+u})}return i}async function EE(t,e){let n=await Vm(t).raw(["diff","--numstat",`${e}^1`,e]).catch(()=>""),o=[];for(let i of n.split(`
758
+ `)){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:Zm(s[3]),churn:a+c})}return o}function RE(t){let{repo:e,issueKeyRe:r,commits:n,pathToCurrent:o,entityByKey:i,ignored:s}=t,a=new Map;for(let c of[...n].reverse()){let l=[...new Set(c.subject.match(r)??[])],u,p,d=l.slice(1);if(l.length>0)u=l[0],p=c.subject.replace(new RegExp(`^\\s*${u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[:\u2014-]\\s*`),"").replace(fl,"").trim();else if(c.prNumber!==null){if((t.trackerProjectKey??"").toUpperCase()==="PR")continue;u=`PR-${c.prNumber}`,p=c.subject.replace(fl,"").replace(zm,"").replace(/^from\s+/,"").trim()||c.subject}else continue;if(!/^[A-Za-z0-9._-]+$/.test(u))continue;let m=new Map;for(let w of c.files){let h=o.get(w.path)??w.path;s(h)||m.set(h,(m.get(h)??0)+w.churn)}if(m.size===0)continue;let g=a.get(u)??{modelFormatVersion:2,taskKey:u,origin:"bootstrap",title:"",commits:[],files:[]};p&&(g.title=p),c.timeSec>0&&(g.date=new Date(c.timeSec*1e3).toISOString().slice(0,10)),g.commits.push(c.sha);for(let[w,h]of m){let k=he("code",e,w),x=g.files.find(b=>b.key===k);if(x)x.churn=(x.churn??0)+h;else{let b=i.get(k);g.files.push({key:k,...b?{entityId:b}:{},churn:h})}}if(d.length>0){let w=new Set([...g.links?.tasks??[],...d]);w.delete(u),g.links={...g.links??{},tasks:[...w].sort()}}a.set(u,g)}return a}function Ym(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 Qm(t){let e=await SE(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 EE(t.repoDir,r.sha))}return RE({repo:t.repo,issueKeyRe:t.issueKeyRe,commits:e,pathToCurrent:t.pathToCurrent,entityByKey:t.entityByKey,ignored:t.ignored,trackerProjectKey:t.trackerProjectKey??null})}function eh(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?Ym(c,a)??c:a)}let n=[],o=0;for(let[i,s]of[...r.entries()].sort(([a],[c])=>a<c?-1:1)){let a=Ym(Yi(t,i),s);if(!a){o++;continue}n.push({path:kr(i),content:Qr(a)})}return{files:n,skippedPipeline:o}}function Yi(t,e){let r=dl(t,kr(e));if(!ll(r))return null;try{let n=Lt(pl(ul(r,"utf-8")));return n.ok?n.value:null}catch{return null}}var xE,fl,zm,ml=S(()=>{"use strict";D();xE=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g,fl=/\(#(\d+)\)\s*$/,zm=/^Merge pull request #(\d+)\b/});import{simpleGit as TE}from"simple-git";async function rh(t,e,r){let o=await TE(t).raw(["log","--no-merges","--name-only","--format=@@@ %H %ct","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
759
+ `))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 Vi(t){let e=new Map;for(let r of t.entities){if(r.status!=="active"||!r.aliases)continue;let n=te(r.currentKey);if(n?.level==="code")for(let o of r.aliases){let i=te(o.key);i?.level==="code"&&e.set(i.path,n.path)}}return e}function nh(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 k=new Set;for(let E of h.files){let v=o.get(E)??E;!i.has(v)||s(v)||k.add(v)}if(k.size<2||k.size>a.commitFileCap)continue;let x=Math.max(0,r-h.timeSec),b=Math.pow(.5,x/c),T=[...k].sort();for(let E of T)l.set(E,(l.get(E)??0)+b);for(let E=0;E<T.length;E++)for(let v=E+1;v<T.length;v++){let I=`${T[E]}\0${T[v]}`;u.set(I,(u.get(I)??0)+b),p.set(I,(p.get(I)??0)+1)}}let d=[],m=a.jaccardMinPct/100;for(let[h,k]of u){if((p.get(h)??0)<a.supportMin)continue;let[x,b]=h.split("\0"),T=(l.get(x)??0)+(l.get(b)??0)-k,E=T>0?k/T:0;E<m||d.push({a:x,b,weight:Math.round(E*th)/th})}let f=new Map;for(let h of d)for(let k of[h.a,h.b])f.has(k)||f.set(k,[]),f.get(k).push(h);let g=new Map;for(let[,h]of f)h.sort((k,x)=>x.weight-k.weight||(k.a<x.a?-1:k.a>x.a?1:k.b<x.b?-1:1)).slice(0,a.topK).forEach(k=>g.set(k,(g.get(k)??0)+1));return[...g.entries()].filter(([,h])=>h===2).map(([h])=>h).map(h=>({kind:"correlates",from:he("code",e,h.a),to:he("code",e,h.b),weight:h.weight})).sort((h,k)=>h.from<k.from?-1:h.from>k.from?1:h.to<k.to?-1:1)}var Tn,th,zi=S(()=>{"use strict";D();Tn=["package-lock.json","pnpm-lock.yaml","yarn.lock"];th=1e4});import{createHash as IE}from"node:crypto";function PE(t,e,r,n){for(let o=0;;o++){let s=`e_${IE("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(s))return s}}function oh(t){let{repo:e,headCommit:r,headDate:n,prev:o,renameChains:i,prevBlobByPath:s,headBlobByPath:a}=t,c=[...t.currentKeys].sort(),l=new Set(c),u=o?.entities??[],p=new Set(u.map(v=>v.entityId)),d=new Set,m=[],f=new Map,g=(v,I)=>{d.add(I),f.set(I,v.entityId),m.push(v)},w=[];for(let v of u)l.has(v.currentKey)&&!d.has(v.currentKey)?g({...v,status:"active",lastSeen:r},v.currentKey):w.push(v);let h=[],k=[];for(let v of w){let I=te(v.currentKey),j=I?i.get(I.path):void 0;if(I&&j){let G=he(I.level,e,j.finalPath);if(l.has(G)&&!d.has(G)){h.push({entity:v,newKey:G,untilCommit:j.commit}),d.add(G);continue}}k.push(v)}let x=[];if(s){let v=new Map;for(let j of c){if(d.has(j))continue;let G=te(j);if(G?.level!=="code")continue;let z=a.get(G.path);z&&v.set(z,v.has(z)?null:j)}let I=new Map;for(let j of k){let G=te(j.currentKey);if(G?.level!=="code")continue;let z=s.get(G.path);z&&I.set(z,I.has(z)?null:j)}for(let j of k){let G=te(j.currentKey),z=G?.level==="code"?s.get(G.path):void 0,A=z?v.get(z):void 0;z&&A&&I.get(z)===j&&!d.has(A)?(h.push({entity:j,newKey:A,untilCommit:r}),d.add(A)):x.push(j)}}else x.push(...k);let b=new Map;for(let v of h){let I=te(v.entity.currentKey),j=te(v.newKey);if(I?.level!=="code"||!j)continue;let G=I.path,z=j.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 N=z.slice(0,z.length-U.length-1);if(N===y)continue;let H=`${y}\0${N}`,X=b.get(H);b.set(H,{count:(X?.count??0)+1,commit:X&&X.commit>v.untilCommit?X.commit:v.untilCommit})}}let T=[...b.entries()].filter(([,v])=>v.count>=CE).map(([v,I])=>{let[j,G]=v.split("\0");return{from:j,to:G,commit:I.commit}}).sort((v,I)=>I.from.length-v.from.length||(v.from<I.from?-1:1)),E=[];for(let v of x){let I=te(v.currentKey),j=!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=he("component",e,z);l.has(A)&&!d.has(A)&&(h.push({entity:v,newKey:A,untilCommit:G.commit}),d.add(A),j=!0);break}j||E.push(v)}for(let v of h.sort((I,j)=>I.newKey<j.newKey?-1:1))g({...v.entity,currentKey:v.newKey,aliases:[...v.entity.aliases??[],{key:v.entity.currentKey,until:v.untilCommit}],status:"active",lastSeen:r},v.newKey);for(let v of E)m.push({...v,status:"orphaned"});for(let v of c){if(d.has(v))continue;let I=PE(e,v,r,p);p.add(I),g({entityId:I,currentKey:v,firstSeen:n,lastSeen:r,status:"active"},v)}return{table:{modelFormatVersion:2,repo:e,builtFromCommit:r,entities:m},byKey:f}}var CE,ih=S(()=>{"use strict";D();CE=5});import{simpleGit as AE}from"simple-git";async function sh(t,e,r){let n=AE(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
760
+ `).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 ah(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 ch=S(()=>{"use strict"});function Xi(t){return he("container",t,_E)}function lh(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function uh(t,e,r,n){let o=[],i=u=>{let p=he("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:lh(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,jE)}},s=(u,p)=>{let d=he("component",t,u),m=n.get(d);return{key:d,level:"component",label:lh(u),...m?{entityId:m}:{},...p?{aggregate:!0}:{}}},a=(u,p,d)=>{let m=r.filesByDir.get(d)??[],f=r.childDirs.get(d)??[],g=[p,...m.map(i)],w=[...m.map(h=>({kind:"contains",from:p.key,to:he("code",t,h.path)})),...f.map(h=>({kind:"contains",from:p.key,to:he("component",t,h)}))];c(u,g,w)},c=(u,p,d)=>{let m={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},f=Ot(m);if(!f.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${f.errors.join("; ")}`);o.push({path:ka(t,u),content:Ra(m)})},l={key:Xi(t),level:"container",label:t,...n.get(Xi(t))?{entityId:n.get(Xi(t))}:{}};a("",l,"");for(let u of r.components)r.collapsed.has(u)?c(u,[s(u,!0)],[]):a(u,s(u,!1),u);return o.sort((u,p)=>u.path<p.path?-1:u.path>p.path?1:0),{files:o,counts:r.counts}}function dh(t,e){let r=[Xi(t)];for(let n of e.components)r.push(he("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(he("code",t,o.path));return r.sort()}var _E,jE,ph=S(()=>{"use strict";D();_E=".";jE=12});import{simpleGit as mh}from"simple-git";function jr(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 gh(t,e="HEAD"){let r=mh(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 Po(t,n)}}async function Po(t,e){let n=await mh(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 fh(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function yh(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=fh(f.path);n.has(g)||n.set(g,[]),n.get(g).push(f);let w=g;for(;w!=="";){let h=fh(w);o.has(h)||o.set(h,new Set),o.get(h).add(w),w=h}}let i=f=>[...o.get(f)??[]].sort(),s=Math.max(e,1)-1,a=new Set,c=new Set,l=[""];for(;l.length>0;){let f=l.shift(),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 hh,Ao=S(()=>{"use strict";hh=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as wh,readFileSync as bh}from"node:fs";import{join as kh}from"node:path";import{simpleGit as NE}from"simple-git";import{parse as vh}from"yaml";function Nr(t){let e={ignore:hh,containerNodeCap:OE,cochange:{...ot},issueKeyPattern:null,enabled:!0},r=kh(t,"regimen.yaml");if(!wh(r))return e;let n;try{n=vh(bh(r,"utf-8"))}catch{return e}let o=n?.context,i=o&&typeof o=="object"?o.model:void 0;if(!i||typeof i!="object")return e;let s=i,a=Array.isArray(s.ignore)?s.ignore.filter(m=>typeof m=="string"&&m.trim().length>0):e.ignore,c=(m,f)=>typeof m=="number"&&Number.isInteger(m)&&m>0?m:f,l=c(s.container_node_cap,e.containerNodeCap),u=s.cochange&&typeof s.cochange=="object"?s.cochange:{},p={windowCommits:c(u.window_commits,e.cochange.windowCommits),commitFileCap:c(u.commit_file_cap,e.cochange.commitFileCap),supportMin:c(u.support_min,e.cochange.supportMin),jaccardMinPct:typeof u.jaccard_min_pct=="number"&&Number.isInteger(u.jaccard_min_pct)&&u.jaccard_min_pct>=0&&u.jaccard_min_pct<=100?u.jaccard_min_pct:e.cochange.jaccardMinPct,halfLifeDays:c(u.half_life_days,e.cochange.halfLifeDays),topK:c(u.top_k,e.cochange.topK)},d=typeof s.issue_key_pattern=="string"&&s.issue_key_pattern.trim().length>0?s.issue_key_pattern.trim():null;return{ignore:a,containerNodeCap:l,cochange:p,issueKeyPattern:d,enabled:s.enabled!==!1}}function hl(t,e){let r=kh(t,io(e));if(!wh(r))return null;let n=vh(bh(r,"utf-8")),o=ao(n);if(!o.ok)throw new Error(`model: ${io(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function gl(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await gh(r,t.ref??"HEAD"),s=jr(o.ignore),a=i.files.filter(k=>!s(k.path)),c=yh(a,o.containerNodeCap),l=hl(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await NE(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=ah(await sh(r,l.builtFromCommit,i.commit)),p=new Map((await Po(r,l.builtFromCommit)).map(b=>[b.path,b.blobHash]))):l?.builtFromCommit===i.commit&&(p=new Map(a.map(k=>[k.path,k.blobHash])));let d=new Map(a.map(k=>[k.path,k.blobHash])),m=oh({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:dh(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),f=uh(e,i.commit,c,m.byKey),g=jr([...o.ignore,...Tn]),w=nh({repo:e,headTimeSec:i.commitTimeSec,filesets:await rh(r,i.commit,o.cochange.windowCommits),pathToCurrent:Vi(m.table),currentPaths:new Set(a.map(k=>k.path)),ignored:g,settings:o.cochange}),h=[{path:io(e),content:Ta(m.table)},...f.files.map(k=>({path:k.path,content:k.content})),{path:wa(e),content:vr({modelFormatVersion:2,repo:e,builtFromCommit:i.commit,edges:w})}];return{repo:e,headCommit:i.commit,files:h,emittedShardPaths:new Set(f.files.map(k=>k.path)),counts:{...f.counts,correlates:w.length},identityTable:m.table,entityByKey:m.byKey}}var OE,yl=S(()=>{"use strict";D();zi();ih();ch();ph();Ao();OE=1500});import{existsSync as xh,readFileSync as Sh,readdirSync as LE}from"node:fs";import{join as wl}from"node:path";import{parse as Eh}from"yaml";function ME(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 Rh(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<$a)return null;let s=i/Math.min(n.size,o.size),a=ME(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(s*c*$h)/$h;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[Se(t.taskKey),Se(e.taskKey)]:[Se(e.taskKey),Se(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function Th(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=Rh(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 Ih(t,e,r,n){let o=Se(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=Rh(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 Ji(t){let e=wl(t,"model/facts/events");if(!xh(e))return[];let r=[];for(let n of LE(e).sort())if(n.endsWith(".yaml"))try{let o=Lt(Eh(Sh(wl(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function Ch(t){let e=wl(t,br);if(!xh(e))return[];try{let r=so(Eh(Sh(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function Zi(t){return vr({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var $h,bl=S(()=>{"use strict";D();$h=1e4});var _o={};Ge(_o,{collectSearchRows:()=>Ah,readContextIndexHub:()=>DE,rebuildSearchIndex:()=>_h,searchIndexPath:()=>rs,searchModelIndex:()=>UE,toFtsQuery:()=>jh});import{existsSync as Cn,readFileSync as In,readdirSync as es}from"node:fs";import{join as vt}from"node:path";import{parse as ts}from"yaml";function rs(t){return vt(t,".git","codepipe-model-index.sqlite")}function DE(t){let e=vt(t,"regimen.yaml");if(!Cn(e))return"off";try{let n=ts(In(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 Ph(){try{let{createRequire:t}=await import("node:module");return t(import.meta.url)("node:sqlite")}catch{return null}}function Qi(t){return t.length>ci?t.slice(0,ci):t}function kl(t){if(!Cn(t))return[];let e=[];for(let r of es(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=vt(t,r.name);r.isDirectory()?e.push(...kl(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function Ah(t){let e=[];for(let i of kl(vt(t,"model/derived/structure"))){let s;try{s=ts(In(i,"utf-8"))}catch{continue}let a=Ot(s);if(a.ok)for(let c of a.value.nodes){let l=te(c.key);l&&e.push({nodeId:c.key,kind:l.level,text:Qi(`${l.path} ${c.label??""}`.trim())})}}let r=vt(t,"model/facts/events");if(Cn(r)){for(let i of es(r).sort())if(i.endsWith(".yaml"))try{let s=Lt(ts(In(vt(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:Qi(`${a.taskKey} ${a.title??""} ${c}`.trim())})}catch{}}let n=vt(t,"model/facts/annotations");if(Cn(n)){let i=new Map;for(let s of kl(vt(t,"model/facts/identity")))try{let a=ts(In(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 es(n).sort())if(s.endsWith(".md"))try{let a=In(vt(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:Qi(c[2].trim())})}catch{}}let o=vt(t,"adr");if(Cn(o))for(let i of es(o).sort()){let s=/^(\d{4})-/.exec(i)?.[1];if(!(!s||!i.endsWith(".md")))try{let a=In(vt(o,i),"utf-8").split(`
761
+ `).slice(0,6);e.push({nodeId:`adr::ADR-${s}`,kind:"adr",text:Qi(a.filter(c=>c.trim()).join(" "))})}catch{}}return e}async function _h(t){let e=Ah(t),r=await Ph();if(!r)return{rows:e,indexed:!1};let n=new r.DatabaseSync(rs(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 jh(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 UE(t,e,r){let n=await Ph();if(!n)throw new Error("model search needs Node with built-in sqlite (>= 22.13) on this CLI");Cn(rs(t))||await _h(t);let o=jh(e);if(!o)return[];let i=Math.min(Math.max(r??20,1),Sa),s=new n.DatabaseSync(rs(t));try{return s.prepare(`SELECT node_id AS nodeId, kind, snippet(model_fts, 2, '[', ']', '\u2026', 10) AS snippet,
745
762
  bm25(model_fts) AS rank
746
- 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 Co=x(()=>{"use strict";F()});var Ji={};Ge(Ji,{mirrorLag:()=>dE,syncUpstream:()=>uE});import{simpleGit as hh}from"simple-git";async function uE(t,e,r,n){let o=hh(e),i=t.defaultBranch??"main",s=n?.upstream??gh(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/*:${Nr}/*`,["--prune"]);let a=(await o.revparse([`${Nr}/${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?yh(t.mirror):null);if(!c)return{repo:t.name,upstreamHead:a,updated:!1};let l=await pE(o),u=await ul(o,c),p=[];for(let d of l){if(d==="codepipe"||d.startsWith("codepipe/"))continue;let m=(await o.revparse([`${Nr}/${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(`
747
- `)[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?yh(t.mirror):null);if(!n)return null;let o=r?.upstream??gh(t);if(!o)return null;let i=hh(e),s=t.defaultBranch??"main";try{let a=(await ul(i,n,s)).get(s);if(!a)return null;let c=(await ul(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}:${Nr}/${s}`),await l())}catch{return null}}function gh(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 yh(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",Nr,"--format=%(refname)"]).catch(()=>"")).split(`
748
- `).map(r=>r.trim()).filter(r=>r.startsWith(`${Nr}/`)).map(r=>r.slice(Nr.length+1))}async function ul(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(`
749
- `)){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 Nr,Zi=x(()=>{"use strict";Nr="refs/codepipe/upstream"});import{homedir as fE}from"node:os";import{existsSync as mE,mkdirSync as hE,readFileSync as gE,writeFileSync as yE}from"node:fs";import{dirname as wE,join as kE}from"node:path";function dl(){return Q("FARM_PINS")??kE(fE(),".codepipe","farm-pins.json")}function bh(){let t=dl();if(!mE(t))return{};try{return JSON.parse(gE(t,"utf-8"))}catch{return{}}}function bE(t){let e=dl();hE(wE(e),{recursive:!0}),yE(e,JSON.stringify(t,null,2)+`
750
- `,{mode:384})}function vE(t){return bh()[t]}function es(t,e){let r=bh();r[t]=e,bE(r)}function ts(t,e){let r=We(e),n=vE(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 ${dl()}.`);return r}var pl=x(()=>{"use strict";Ke();dt()});import{setTimeout as $E}from"node:timers/promises";import xE from"ws";function rs(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new xE(r)}async function ir(t,e,r){return sr(t,e,"/projects",r)}async function vh(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new W(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function ns(t,e,r,n){return sr(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function $h(t,e,r,n){return sr(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function xh(t,e,r,n){return sr(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function Sh(t,e){let r=await fetch(`${t}/sandbox/me`,{headers:{Authorization:`Bearer ${e}`}});if(r.ok)return"ok";if(r.status===401)return"unknown";if(r.status===404)return"unsupported";throw new W(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function os(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new W(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function fl(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new W(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function Eh(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await fl(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 $E(r.delayMs??1500)}throw o}async function Th(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 No(e)}if(!r.ok)throw new W(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function Rh(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new W(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function Ih(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new W(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function Ch(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new W(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function Ah(t,e,r,n,o){return sr(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function Oo(t,e,r,n){return sr(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function ml(t,e,r,n){await sr(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function Ph(t,e,r,n){return sr(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function _h(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/repos/${encodeURIComponent(n)}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new W(o.status,s,a)}return s}async function se(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new W(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function sr(t,e,r,n){let o=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new W(o.status,s,a)}return s}async function is(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/deliverables`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new W(n.status,null,`GET /deliverables HTTP ${n.status}`);return(await n.json()).deliverables}var W,No,je=x(()=>{"use strict";W=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};No=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});import{existsSync as eg,readFileSync as GE,readdirSync as KE}from"node:fs";import{join as tg}from"node:path";import{simpleGit as HE}from"simple-git";import{parse as WE}from"yaml";function ls(t){let e=new Map,r=tg(t,ei);if(!eg(r))return e;let n;try{n=WE(GE(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 qE(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return $r({modelFormatVersion:2,repos:e})}function rg(t,e){let r=tg(t,e);if(!eg(r))return[];let n=[];for(let o of KE(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...rg(t,i)):n.push(i)}return n}async function us(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 rg(t,m))d.emittedShardPaths.has(f)||(n.push({path:f,content:"",deleted:!0}),o++)}let i=ls(t);for(let d of e)i.set(d.repo,{builtFromCommit:d.headCommit,counts:d.counts});n.push({path:ei,content:qE(i)});let s=Ki(t),a=Qm(s,r.halfLifeDays??ot.halfLifeDays);n.push({path:wr,content:Hi(a)});for(let d of e){let m=[];for(let f of s)for(let g of f.files)te(g.key)?.repo===d.repo&&m.push({kind:"touched_by",from:Se(f.taskKey),to:g.key,...g.churn!==void 0?{weight:g.churn}:{}});n.push({path:ua(d.repo),content:br({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 Re(t,n,u);let p=(await c.revparse(["HEAD"]).catch(()=>"")).trim();if(p!==l){let{rebuildSearchIndex:d}=await Promise.resolve().then(()=>(Co(),Io));await d(t).catch(()=>{})}return{committed:p!==l,filesWritten:n.filter(d=>!d.deleted).length,filesDeleted:o}}var ng=x(()=>{"use strict";F();il();lt()});var fs={};Ge(fs,{bootstrapDaemonModel:()=>zE,bootstrapModelForTargets:()=>xl,bootstrapWorkspaceModel:()=>cg,modelBootstrapCommand:()=>$l,modelBuildCommand:()=>vl,modelIndexExists:()=>ug,rebuildWorkspaceModelIfStale:()=>XE,shouldAutoBootstrapModel:()=>VE,syncWorkspaceMirrors:()=>lg});import{existsSync as ps}from"node:fs";import{join as ar}from"node:path";import{cancel as YE,intro as og,log as wl,outro as kl}from"@clack/prompts";import{simpleGit as bl}from"simple-git";function ds(t){YE(t),process.exit(1)}function ig(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:ar(t.root,i.mountAs);if(!ps(ar(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 sg(t){let e=bl(t.dir),r=`origin/${t.defaultBranch}`;return await e.raw(["rev-parse","--verify",r]).then(()=>!0).catch(()=>!1)?r:"HEAD"}async function ag(t,e,r,n){let o=[];for(let i of e)try{let s=await rl({repo:i.name,repoDir:i.dir,contextDir:t,settings:r,ref:await sg(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 vl(t){og("codepipe model build");let e=Ae();e||ds("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{let r=jr(e.contextDir),n=ig(e,t.repo,s=>wl.warn(s)),o=await ag(e.contextDir,n,r,s=>wl.info(s)),i=await us(e.contextDir,o,{halfLifeDays:r.cochange.halfLifeDays});i.committed?kl(`model updated: ${i.filesWritten} files written, ${i.filesDeleted} stale removed`):kl("model already up to date (no changes)")}catch(r){ds(r instanceof Error?r.message:String(r))}}async function $l(t){og("codepipe model bootstrap");let e=Ae();e||ds("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{await cg(e,t.repo,{onLog:r=>wl.info(r)})}catch(r){ds(r instanceof Error?r.message:String(r))}kl("bootstrap complete")}async function cg(t,e,r){let n=ig(t,e,r.onLog);return xl(t.contextDir,n,r)}async function xl(t,e,r){let n=jr(t),o=await ag(t,e,n,r.onLog),i=xm(t),s=$m(n.issueKeyPattern,i),a=_r([...n.ignore,...vn]),c=[];for(let p of o){let d=e.find(f=>f.name===p.repo),m=await Em({repo:p.repo,repoDir:d.dir,headCommit:p.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:s,pathToCurrent:Bi(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}=Tm(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 us(t,o,{halfLifeDays:n.cochange.halfLifeDays}),{events:l.length}}async function zE(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:ar(e.root,a),l=s.defaultBranch||"main";c!==e.contextDir&&ps(ar(c,".git"))?(await bl(c).fetch(["origin",l]).catch(()=>{}),o.push({name:s.name,dir:c,defaultBranch:l})):(n(`${s.name}: materializing clone in the daemon layout`),await or(t,s),o.push({name:s.name,dir:_e(t,s.name),defaultBranch:l}))}let i=await xl(e.contextDir,o,{onLog:n});return{repos:o.length,events:i.events}}async function lg(t,e){let r=new Map;for(let n of t.repos){if(!n.mirror)continue;let o=n.mountAs==="."?t.root:ar(t.root,n.mountAs);if(!ps(ar(o,".git")))continue;let{syncUpstream:i}=await Promise.resolve().then(()=>(Zi(),Ji)),s=await i(n,o,{info:a=>e(`[mirror] ${a}`),warn:a=>e(`[mirror] ${a}`)});if(s.error||!s.upstreamHead){e(`[mirror] ${n.name}: sync failed (${s.error??"no upstream head"})`);continue}r.set(n.name,s.upstreamHead)}return r}function ug(t){return ls(t).size>0}function VE(t){return jr(t).enabled&&!ug(t)}async function XE(t,e={}){let r=e.onLog??(()=>{}),n=jr(t.contextDir),o=await lg(t,r);if(!n.enabled)return{rebuilt:[],skipped:[]};let i=[],s=[],a=ls(t.contextDir),c=[];for(let l of t.repos){let u=l.mountAs==="."?t.root:ar(t.root,l.mountAs);if(!ps(ar(u,".git")))continue;let p=bl(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 sg({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 rl({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 us(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 Lo=x(()=>{"use strict";lt();ng();nl();el();Fi();Ro();$o();wt()});var pg={};Ge(pg,{computeDriftReport:()=>tT,supersededAdrIds:()=>dg});import{existsSync as Sl,readFileSync as El,readdirSync as Tl}from"node:fs";import{join as Sn}from"node:path";import{parse as JE}from"yaml";import{simpleGit as ZE}from"simple-git";function eT(t,e){let r=Sn(t,`model/derived/structure/${e}`),n=[],o="";if(!Sl(r))return{nodes:n,builtFromCommit:o};for(let i of Tl(r).sort()){if(!i.endsWith(".yaml"))continue;let s;try{let a=Ot(JE(El(Sn(r,i),"utf-8")));if(!a.ok)continue;s=a.value}catch{continue}o=s.builtFromCommit;for(let a of s.nodes){let c=te(a.key);!c||c.level!=="code"&&c.level!=="component"||n.push({key:a.key,path:c.path,level:c.level,contentHash:a.contentHash,entityId:a.entityId})}}return{nodes:n,builtFromCommit:o}}function dg(t){let e=new Set,r=Sn(t,"adr");if(!Sl(r))return e;for(let n of Tl(r).sort()){let o=/^(\d{4})-/.exec(n)?.[1];if(!(!o||!n.endsWith(".md")))try{let i=El(Sn(r,n),"utf-8").slice(0,600).toLowerCase();/status[^\n]*superseded/.test(i)&&e.add(`ADR-${o}`)}catch{}}return e}async function tT(t,e,r){let{nodes:n,builtFromCommit:o}=eT(e,r),i=(await ZE(t).revparse(["HEAD"])).trim(),s=await To(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 v=a.get(w.path);v?w.contentHash&&v.slice(0,QE)!==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 v=w.path.lastIndexOf("/"),S=v<0?"":w.path.slice(0,v);m.has(S)||m.set(S,new Set),m.get(S).add(w.path),u.has(w.path)||d++;let R=S;for(;R!==""&&!f.has(R);)f.add(R),R=R.includes("/")?R.slice(0,R.lastIndexOf("/")):""}let g=new Map;for(let w of u){let v=w.lastIndexOf("/"),S=v<0?"":w.slice(0,v);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 v=g.get(w.path)??new Set,S=m.get(w.path)??new Set;(v.size!==S.size||[...v].some($=>!S.has($)))&&c.push(w.key)}let k=[],h=dg(e);if(h.size>0){let w=Sn(e,"model/facts/annotations"),v=new Map(n.filter(S=>S.entityId).map(S=>[S.entityId,S.key]));if(Sl(w))for(let S of Tl(w).sort()){if(!S.endsWith(".md"))continue;let R=S.replace(/\.md$/,""),$=v.get(R);if($)try{(El(Sn(w,S),"utf-8").match(/\bADR-(\d{3,4})\b/g)??[]).map(N=>`ADR-${N.slice(4).padStart(4,"0")}`).some(N=>h.has(N))&&k.push($)}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 QE,fg=x(()=>{"use strict";F();Ro();QE=12});import{execFileSync as uT}from"node:child_process";import{mkdtempSync as dT,mkdirSync as pT,readFileSync as hg,rmSync as fT,writeFileSync as mT}from"node:fs";import{tmpdir as hT}from"node:os";import{dirname as gT,join as gg}from"node:path";function yg(t="codepipe-context"){let e=dT(gg(hT(),"codepipe-ssh-")),r=gg(e,"id_ed25519");try{return uT("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:hg(r,"utf-8"),publicKey:hg(`${r}.pub`,"utf-8").trim()}}finally{fT(e,{recursive:!0,force:!0})}}async function wg(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 kg(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 bg(t,e){pT(gT(t),{recursive:!0});let r=e.endsWith(`
763
+ 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 jo=S(()=>{"use strict";D()});var is={};Ge(is,{mirrorLag:()=>rR,syncUpstream:()=>tR});import{simpleGit as Kh}from"simple-git";async function tR(t,e,r,n){let o=Kh(e),i=t.defaultBranch??"main",s=n?.upstream??Hh(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/*:${Or}/*`,["--prune"]);let a=(await o.revparse([`${Or}/${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?Wh(t.mirror):null);if(!c)return{repo:t.name,upstreamHead:a,updated:!1};let l=await nR(o),u=await Sl(o,c),p=[];for(let d of l){if(d==="codepipe"||d.startsWith("codepipe/"))continue;let m=(await o.revparse([`${Or}/${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(`
764
+ `)[0]:String(a);return{repo:t.name,upstreamHead:null,updated:!1,error:c}}}async function rR(t,e,r){let n=r?.mirror??(t.mirror?Wh(t.mirror):null);if(!n)return null;let o=r?.upstream??Hh(t);if(!o)return null;let i=Kh(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}:${Or}/${s}`),await l())}catch{return null}}function Hh(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 Wh(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 nR(t){return(await t.raw(["for-each-ref",Or,"--format=%(refname)"]).catch(()=>"")).split(`
765
+ `).map(r=>r.trim()).filter(r=>r.startsWith(`${Or}/`)).map(r=>r.slice(Or.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(`
766
+ `)){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 Or,ss=S(()=>{"use strict";Or="refs/codepipe/upstream"});import{homedir as oR}from"node:os";import{existsSync as iR,mkdirSync as sR,readFileSync as aR,writeFileSync as cR}from"node:fs";import{dirname as lR,join as uR}from"node:path";function El(){return Q("FARM_PINS")??uR(oR(),".codepipe","farm-pins.json")}function Vh(){let t=El();if(!iR(t))return{};try{return JSON.parse(aR(t,"utf-8"))}catch{return{}}}function dR(t){let e=El();sR(lR(e),{recursive:!0}),cR(e,JSON.stringify(t,null,2)+`
767
+ `,{mode:384})}function pR(t){return Vh()[t]}function cs(t,e){let r=Vh();r[t]=e,dR(r)}function ls(t,e){let r=We(e),n=pR(t);if(n&&n!==r)throw new Error(`farm ${t} key fingerprint changed (pinned ${n}, now ${r}) \u2014 refusing to seal. If the farm was re-registered intentionally, remove its entry from ${El()}.`);return r}var Rl=S(()=>{"use strict";Ke();ut()});import{setTimeout as fR}from"node:timers/promises";import mR from"ws";function us(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new mR(r)}async function sr(t,e,r){return ar(t,e,"/projects",r)}async function zh(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 ds(t,e,r,n){return ar(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function Xh(t,e,r,n){return ar(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function Jh(t,e,r,n){return ar(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function Zh(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 ps(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 Tl(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 Qh(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await Tl(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 fR(r.delayMs??1500)}throw o}async function eg(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 Do(e)}if(!r.ok)throw new K(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function tg(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 rg(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 ng(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 og(t,e,r,n,o){return ar(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function Uo(t,e,r,n){return ar(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function Il(t,e,r,n){await ar(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function ig(t,e,r,n){return ar(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function sg(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 ar(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 fs(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,Do,je=S(()=>{"use strict";K=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};Do=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});import{existsSync as Ig,readFileSync as jR,readdirSync as NR}from"node:fs";import{join as Cg}from"node:path";import{simpleGit as OR}from"simple-git";import{parse as LR}from"yaml";function ws(t){let e=new Map,r=Cg(t,si);if(!Ig(r))return e;let n;try{n=LR(jR(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 MR(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return xr({modelFormatVersion:2,repos:e})}function Pg(t,e){let r=Cg(t,e);if(!Ig(r))return[];let n=[];for(let o of NR(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...Pg(t,i)):n.push(i)}return n}async function bs(t,e,r={}){let n=[],o=0;for(let d of e){n.push(...d.files);let m=`model/derived/structure/${d.repo}`;for(let f of Pg(t,m))d.emittedShardPaths.has(f)||(n.push({path:f,content:"",deleted:!0}),o++)}let i=ws(t);for(let d of e)i.set(d.repo,{builtFromCommit:d.headCommit,counts:d.counts});n.push({path:si,content:MR(i)});let s=Ji(t),a=Th(s,r.halfLifeDays??ot.halfLifeDays);n.push({path:br,content:Zi(a)});for(let d of e){let m=[];for(let f of s)for(let g of f.files)te(g.key)?.repo===d.repo&&m.push({kind:"touched_by",from:Se(f.taskKey),to:g.key,...g.churn!==void 0?{weight:g.churn}:{}});n.push({path:ba(d.repo),content:vr({modelFormatVersion:2,repo:d.repo,builtFromCommit:d.headCommit,edges:m})})}let c=OR(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(()=>(jo(),_o));await d(t).catch(()=>{})}return{committed:p!==l,filesWritten:n.filter(d=>!d.deleted).length,filesDeleted:o}}var Ag=S(()=>{"use strict";D();bl();ct()});var $s={};Ge($s,{bootstrapDaemonModel:()=>UR,bootstrapModelForTargets:()=>Ml,bootstrapWorkspaceModel:()=>Lg,modelBootstrapCommand:()=>Ll,modelBuildCommand:()=>Ol,modelIndexExists:()=>Dg,rebuildWorkspaceModelIfStale:()=>FR,shouldAutoBootstrapModel:()=>BR,syncWorkspaceMirrors:()=>Mg});import{existsSync as vs}from"node:fs";import{join as cr}from"node:path";import{cancel as DR,intro as _g,log as _l,outro as jl}from"@clack/prompts";import{simpleGit as Nl}from"simple-git";function ks(t){DR(t),process.exit(1)}function jg(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:cr(t.root,i.mountAs);if(!vs(cr(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 Ng(t){let e=Nl(t.dir),r=`origin/${t.defaultBranch}`;return await e.raw(["rev-parse","--verify",r]).then(()=>!0).catch(()=>!1)?r:"HEAD"}async function Og(t,e,r,n){let o=[];for(let i of e)try{let s=await gl({repo:i.name,repoDir:i.dir,contextDir:t,settings:r,ref:await Ng(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 Ol(t){_g("codepipe model build");let e=Pe();e||ks("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{let r=Nr(e.contextDir),n=jg(e,t.repo,s=>_l.warn(s)),o=await Og(e.contextDir,n,r,s=>_l.info(s)),i=await bs(e.contextDir,o,{halfLifeDays:r.cochange.halfLifeDays});i.committed?jl(`model updated: ${i.filesWritten} files written, ${i.filesDeleted} stale removed`):jl("model already up to date (no changes)")}catch(r){ks(r instanceof Error?r.message:String(r))}}async function Ll(t){_g("codepipe model bootstrap");let e=Pe();e||ks("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{await Lg(e,t.repo,{onLog:r=>_l.info(r)})}catch(r){ks(r instanceof Error?r.message:String(r))}jl("bootstrap complete")}async function Lg(t,e,r){let n=jg(t,e,r.onLog);return Ml(t.contextDir,n,r)}async function Ml(t,e,r){let n=Nr(t),o=await Og(t,e,n,r.onLog),i=Jm(t),s=Xm(n.issueKeyPattern,i),a=jr([...n.ignore,...Tn]),c=[];for(let p of o){let d=e.find(f=>f.name===p.repo),m=await Qm({repo:p.repo,repoDir:d.dir,headCommit:p.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:s,pathToCurrent:Vi(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}=eh(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 bs(t,o,{halfLifeDays:n.cochange.halfLifeDays}),{events:l.length}}async function UR(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:cr(e.root,a),l=s.defaultBranch||"main";c!==e.contextDir&&vs(cr(c,".git"))?(await Nl(c).fetch(["origin",l]).catch(()=>{}),o.push({name:s.name,dir:c,defaultBranch:l})):(n(`${s.name}: materializing clone in the daemon layout`),await ir(t,s),o.push({name:s.name,dir:_e(t,s.name),defaultBranch:l}))}let i=await Ml(e.contextDir,o,{onLog:n});return{repos:o.length,events:i.events}}async function Mg(t,e){let r=new Map;for(let n of t.repos){if(!n.mirror)continue;let o=n.mountAs==="."?t.root:cr(t.root,n.mountAs);if(!vs(cr(o,".git")))continue;let{syncUpstream:i}=await Promise.resolve().then(()=>(ss(),is)),s=await i(n,o,{info:a=>e(`[mirror] ${a}`),warn:a=>e(`[mirror] ${a}`)});if(s.error||!s.upstreamHead){e(`[mirror] ${n.name}: sync failed (${s.error??"no upstream head"})`);continue}r.set(n.name,s.upstreamHead)}return r}function Dg(t){return ws(t).size>0}function BR(t){return Nr(t).enabled&&!Dg(t)}async function FR(t,e={}){let r=e.onLog??(()=>{}),n=Nr(t.contextDir),o=await Mg(t,r);if(!n.enabled)return{rebuilt:[],skipped:[]};let i=[],s=[],a=ws(t.contextDir),c=[];for(let l of t.repos){let u=l.mountAs==="."?t.root:cr(t.root,l.mountAs);if(!vs(cr(u,".git")))continue;let p=Nl(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 Ng({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 gl({repo:l.name,repoDir:u,contextDir:t.contextDir,settings:n,ref:g})),i.push(l.name)}catch(w){r(`[model] rebuild of ${l.name} failed: ${w instanceof Error?w.message:String(w)}`)}}}return c.length>0&&(await bs(t.contextDir,c,{halfLifeDays:n.cochange.halfLifeDays}),r(`[model] release-path rebuild: ${i.join(", ")} (skipped up-to-date: ${s.join(", ")||"\u2014"})`)),{rebuilt:i,skipped:s}}var Bo=S(()=>{"use strict";ct();Ag();yl();ml();zi();Ao();Sn();wt()});var Bg={};Ge(Bg,{computeDriftReport:()=>qR,supersededAdrIds:()=>Ug});import{existsSync as Dl,readFileSync as Ul,readdirSync as Bl}from"node:fs";import{join as Pn}from"node:path";import{parse as GR}from"yaml";import{simpleGit as KR}from"simple-git";function WR(t,e){let r=Pn(t,`model/derived/structure/${e}`),n=[],o="";if(!Dl(r))return{nodes:n,builtFromCommit:o};for(let i of Bl(r).sort()){if(!i.endsWith(".yaml"))continue;let s;try{let a=Ot(GR(Ul(Pn(r,i),"utf-8")));if(!a.ok)continue;s=a.value}catch{continue}o=s.builtFromCommit;for(let a of s.nodes){let c=te(a.key);!c||c.level!=="code"&&c.level!=="component"||n.push({key:a.key,path:c.path,level:c.level,contentHash:a.contentHash,entityId:a.entityId})}}return{nodes:n,builtFromCommit:o}}function Ug(t){let e=new Set,r=Pn(t,"adr");if(!Dl(r))return e;for(let n of Bl(r).sort()){let o=/^(\d{4})-/.exec(n)?.[1];if(!(!o||!n.endsWith(".md")))try{let i=Ul(Pn(r,n),"utf-8").slice(0,600).toLowerCase();/status[^\n]*superseded/.test(i)&&e.add(`ADR-${o}`)}catch{}}return e}async function qR(t,e,r){let{nodes:n,builtFromCommit:o}=WR(e,r),i=(await KR(t).revparse(["HEAD"])).trim(),s=await Po(t,i),a=new Map(s.map(k=>[k.path,k.blobHash])),c=[],l=[],u=new Set,p=[];for(let k of n){if(k.level==="component"){p.push(k);continue}u.add(k.path);let x=a.get(k.path);x?k.contentHash&&x.slice(0,HR)!==k.contentHash&&c.push(k.key):l.push(k.key)}let d=0,m=new Map,f=new Set;for(let k of s){let x=k.path.lastIndexOf("/"),b=x<0?"":k.path.slice(0,x);m.has(b)||m.set(b,new Set),m.get(b).add(k.path),u.has(k.path)||d++;let T=b;for(;T!==""&&!f.has(T);)f.add(T),T=T.includes("/")?T.slice(0,T.lastIndexOf("/")):""}let g=new Map;for(let k of u){let x=k.lastIndexOf("/"),b=x<0?"":k.slice(0,x);g.has(b)||g.set(b,new Set),g.get(b).add(k)}for(let k of p){if(!f.has(k.path)){l.push(k.key);continue}let x=g.get(k.path)??new Set,b=m.get(k.path)??new Set;(x.size!==b.size||[...x].some(E=>!b.has(E)))&&c.push(k.key)}let w=[],h=Ug(e);if(h.size>0){let k=Pn(e,"model/facts/annotations"),x=new Map(n.filter(b=>b.entityId).map(b=>[b.entityId,b.key]));if(Dl(k))for(let b of Bl(k).sort()){if(!b.endsWith(".md"))continue;let T=b.replace(/\.md$/,""),E=x.get(T);if(E)try{(Ul(Pn(k,b),"utf-8").match(/\bADR-(\d{3,4})\b/g)??[]).map(j=>`ADR-${j.slice(4).padStart(4,"0")}`).some(j=>h.has(j))&&w.push(E)}catch{}}}return{repo:r,builtFromCommit:o,headCommit:i,stale:[...new Set(c)].sort(),orphaned:[...new Set(l)].sort(),superseded:[...new Set(w)].sort(),newFiles:d}}var HR,Fg=S(()=>{"use strict";D();Ao();HR=12});import{execFileSync as tT}from"node:child_process";import{mkdtempSync as rT,mkdirSync as nT,readFileSync as Kg,rmSync as oT,writeFileSync as iT}from"node:fs";import{tmpdir as sT}from"node:os";import{dirname as aT,join as Hg}from"node:path";function Wg(t="codepipe-context"){let e=rT(Hg(sT(),"codepipe-ssh-")),r=Hg(e,"id_ed25519");try{return tT("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Kg(r,"utf-8"),publicKey:Kg(`${r}.pub`,"utf-8").trim()}}finally{oT(e,{recursive:!0,force:!0})}}async function qg(t,e,r,n="codepipe-context"){let o=await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/keys`,{method:"POST",headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({title:n,key:r,read_only:!1})});if(o.ok)return;let i=await o.text();if(!(o.status===422&&/already in use/i.test(i)))throw new Error(`add deploy key failed: ${o.status} ${i}`)}function Yg(t){if(/^git@[^:]+:.+/.test(t))return t;let e=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(e)return`git@${e[1]}:${e[2]}`;let r=t.match(/^https:\/\/(?:[^@/]+@)?([^/]+)\/(.+)$/);return r?`git@${r[1]}:${r[2]}`:t}function Vg(t,e){nT(aT(t),{recursive:!0});let r=e.endsWith(`
751
768
  `)?e:e+`
752
- `;return mT(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var Al=x(()=>{"use strict"});import{existsSync as vg,mkdirSync as $g}from"node:fs";import{dirname as xg}from"node:path";import{simpleGit as En}from"simple-git";function yT(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 wT(t,e){return e?.contextWrite?.token?{user:uo(t),secret:e.contextWrite.token}:t===rn.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===rn.bitbucket?e?.bitbucket?.apiToken?{user:Dt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function Sg(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 hs))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 gs(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 hs(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=wT(Tr(s.cloneUrl),r);if(a){let c=await kT({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 bT({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 kT(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=yT(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(vg(`${r}/.git`)){let l=En(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=Rc(r);await l.reset(["--hard",`origin/${s}`]),Ic(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else $g(xg(r),{recursive:!0}),await En().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await Eg(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 bT(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=bg(i,n),a=kg(e.cloneUrl),c=e.branch;try{if(vg(`${r}/.git`)){let l=En(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=Rc(r);await l.reset(["--hard",`origin/${c}`]),Ic(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else $g(xg(r),{recursive:!0}),await En().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await En(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await Eg(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 Eg(t){let e=En(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 hs,Pl=x(()=>{"use strict";F();je();Ft();Al();hs=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as vT}from"node:child_process";function $T(){try{return vT("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function Rg(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:$T(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var Ig=x(()=>{"use strict"});import{homedir as xT}from"node:os";import{mkdirSync as ST,readFileSync as ET,writeFileSync as TT,existsSync as Cg}from"node:fs";import{dirname as RT,join as jl}from"node:path";function IT(){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=Q("SANDBOX_CONFIG");if(e)return e;let r=jl(xT(),".codepipe","worker");return t?jl(r,"profiles",t,"config.json"):jl(r,"config.json")}function Ag(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function Le(t){let e=$t(t),r=null;return Cg(e)&&(r=JSON.parse(ET(e,"utf-8"))),r?(r.planningLane=IT(),r):null}function Pg(t,e){let r=$t(e);ST(RT(r),{recursive:!0}),TT(r,JSON.stringify(t,null,2)+`
753
- `,{mode:384})}var ys=x(()=>{"use strict";Ke();Cg(".env")&&process.loadEnvFile(".env")});import CT from"ws";var Tn,Nl=x(()=>{"use strict";Tn=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 CT(e)}}});import{hostname as AT}from"node:os";async function Lr(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??AT(),n=Rg({projects:t.projects??[],llm:t.llm??null}),o=new Tn(t.hub.replace(/\/$/,"")),i=Ni(),s=We(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});Pg({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 _g=x(()=>{"use strict";dt();Ig();ys();Nl()});function jg(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 ws(t){return t?`Write ALL user-facing prose \u2014 brief status notes between tool calls, questions, summaries and the bodies of Markdown artifacts you produce for humans \u2014 in ${t} (the project's configured language), unless your prompt pins a different language for a specific output. In-repo content (code, code comments, commit messages) follows the project's existing conventions and any explicit instructions in your prompt.`:"Write ALL user-facing prose \u2014 brief status notes between tool calls, questions, summaries and the bodies of Markdown artifacts you produce for humans \u2014 in the language of the task description and user input embedded in your prompt, NOT the language the surrounding instructions are written in. Judge that language by the human prose only, ignoring code snippets, file paths and identifiers. In-repo content (code, code comments, commit messages) follows the project's existing conventions instead."}function Ng(t){return t?`[Session note: the instructions from the start of this conversation remain in force. Reply in ${t} \u2014 including the brief status notes between tool calls.]`:"[Session note: the instructions from the start of this conversation remain in force. Reply in the language of the user's message above \u2014 including the brief status notes between tool calls. Judge the language by the human prose, ignoring code snippets and identifiers.]"}function Rn(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 ks=x(()=>{"use strict"});import{spawn as PT}from"node:child_process";function Ol(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function jT(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 NT(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Mr(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Ll(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}})+`
754
- `}async function Dg(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Kt;let r=Rn(e.metadata),n=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",jg(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:Ol(g,Og)})}else if(f==="tool_use"){let g=String(m.name??""),k=m.input?.file_path??m.input?.path,h=jT(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?Ol(NT(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=PT(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"),Lg)};e.signal?.addEventListener("abort",g,{once:!0});let k=null,h=()=>{k&&clearTimeout(k),k=setTimeout(()=>{m=!0,console.warn(`[claude:chat] idle for ${Mg}ms \u2014 ending session`),p.kill("SIGTERM"),f=setTimeout(()=>p.kill("SIGKILL"),Lg)},Mg)},w=()=>{f&&clearTimeout(f),k&&clearTimeout(k),e.signal?.removeEventListener("abort",g)},v=!0,S=b=>{if(!(!v||p.stdin.destroyed))try{p.stdin.write(b)}catch{}};S(Ll(e.prompt)),h(),(async()=>{try{for await(let b of e.interactive.inbox){if(d||!v)break;if(h(),b.kind==="user")i({ts:Date.now(),kind:"text",author:"user",text:Ol(b.text,Og)}),S(Ll(b.text,Ng(r)));else{S(Ll(_T)),v=!1;try{p.stdin.end()}catch{}break}}}catch{}})();let R="",$=b=>{let I;try{I=JSON.parse(b)}catch{return}c(I)};p.stdout.on("data",b=>{s.push(b),h(),R+=b;let I;for(;(I=R.indexOf(`
755
- `))!==-1;){let N=R.slice(0,I).trim();R=R.slice(I+1),N&&$(N)}}),p.stderr.on("data",b=>{s.push(b);for(let I of b.split(`
756
- `)){let N=I.trim();N&&console.warn(`[claude:chat:stderr] ${N}`)}}),p.on("error",b=>{w(),u(b)}),p.on("close",b=>{if(w(),d){u(new Kt);return}if(m){u(new Error("chat session ended: idle for too long without a reply"));return}R.trim()&&$(R.trim()),console.log(`[claude:chat] exit code=${b}`),l({artifactPaths:[],log:s.join(""),usage:OT(a)})})})}function OT(t){let e=qt();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=Mr(r.input_tokens),e.outputTokens=Mr(r.output_tokens),e.cacheReadInputTokens=Mr(r.cache_read_input_tokens),e.cacheCreationInputTokens=Mr(r.cache_creation_input_tokens)),e.totalCostUsd=Mr(t.total_cost_usd),e.numTurns=Mr(t.num_turns),e.durationMs=Mr(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var Og,Lg,Mg,_T,Ug=x(()=>{"use strict";F();In();ks();Og=16e3,Lg=5e3,Mg=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),_T="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 LT}from"node:child_process";import{existsSync as MT}from"node:fs";function UT(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function Bg(t){let e;try{e=JSON.parse(t)}catch{return console.log(`[claude] ${t.slice(0,200)}`),null}let r=e.type;if(r==="system"){let n=e.subtype??"";return console.log(`[claude] system ${n}`),e}if(r==="assistant"){let n=e.message;for(let o of n?.content??[]){let i=o.type;if(i==="text"){let s=String(o.text??"").trim();s&&console.log(`[claude] text: ${cr(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=GT(s,a);console.log(`[claude] tool_use ${s}${c?` ${c}`:""}`)}}return e}if(r==="user"){let n=e.message;for(let o of n?.content??[])if(o.type==="tool_result")if(o.is_error===!0){let i=Gg(o.content);console.log(`[claude] tool_result (error)${i?`: ${cr(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)} ${cr(JSON.stringify(e),200)}`),e}function BT(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(cr(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(cr(r.trim().split(`
769
+ `;return iT(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var Hl=S(()=>{"use strict"});import{existsSync as zg,mkdirSync as Xg}from"node:fs";import{dirname as Jg}from"node:path";import{simpleGit as An}from"simple-git";function cT(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 lT(t,e){return e?.contextWrite?.token?{user:go(t),secret:e.contextWrite.token}:t===an.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===an.bitbucket?e?.bitbucket?.apiToken?{user:Ut,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function Zg(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 Ss))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 Es(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 Ss(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=lT(Tr(s.cloneUrl),r);if(a){let c=await uT({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 dT({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 uT(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=cT(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(zg(`${r}/.git`)){let l=An(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=Gc(r);await l.reset(["--hard",`origin/${s}`]),Kc(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Xg(Jg(r),{recursive:!0}),await An().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await Qg(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 dT(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=Vg(i,n),a=Yg(e.cloneUrl),c=e.branch;try{if(zg(`${r}/.git`)){let l=An(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=Gc(r);await l.reset(["--hard",`origin/${c}`]),Kc(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Xg(Jg(r),{recursive:!0}),await An().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await An(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await Qg(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 Qg(t){let e=An(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 Ss,Wl=S(()=>{"use strict";D();je();Gt();Hl();Ss=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as pT}from"node:child_process";function fT(){try{return pT("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function ty(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:fT(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var ry=S(()=>{"use strict"});import{homedir as mT}from"node:os";import{mkdirSync as hT,readFileSync as gT,writeFileSync as yT,existsSync as ny}from"node:fs";import{dirname as wT,join as Yl}from"node:path";function bT(){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=Q("SANDBOX_CONFIG");if(e)return e;let r=Yl(mT(),".codepipe","worker");return t?Yl(r,"profiles",t,"config.json"):Yl(r,"config.json")}function oy(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function Me(t){let e=$t(t),r=null;return ny(e)&&(r=JSON.parse(gT(e,"utf-8"))),r?(r.planningLane=bT(),r):null}function iy(t,e){let r=$t(e);hT(wT(r),{recursive:!0}),yT(r,JSON.stringify(t,null,2)+`
770
+ `,{mode:384})}var Rs=S(()=>{"use strict";Ke();ny(".env")&&process.loadEnvFile(".env")});import kT from"ws";var _n,Vl=S(()=>{"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 kT(e)}}});import{hostname as vT}from"node:os";async function Mr(t){let e=Me(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${$t(t.profile)}.`),process.exit(1));let r=t.name??vT(),n=ty({projects:t.projects??[],llm:t.llm??null}),o=new _n(t.hub.replace(/\/$/,"")),i=Fi(),s=We(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});iy({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 sy=S(()=>{"use strict";ut();ry();Rs();Vl()});function ay(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 Ts(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 cy(t){return t?`[Session note: the instructions from the start of this conversation remain in force. Reply in ${t} \u2014 including the brief status notes between tool calls.]`:"[Session note: the instructions from the start of this conversation remain in force. Reply in the language of the user's message above \u2014 including the brief status notes between tool calls. Judge the language by the human prose, ignoring code snippets and identifiers.]"}function jn(t){let e=t?.responseLanguage;if(typeof e!="string")return;let r=e.trim();return r.length>0&&r.toLowerCase()!=="auto"?r:void 0}var Is=S(()=>{"use strict"});import{spawn as $T}from"node:child_process";function zl(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function ST(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 ET(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Dr(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Xl(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}})+`
771
+ `}async function py(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Ht;let r=jn(e.metadata),n=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",ay(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:zl(g,ly)})}else if(f==="tool_use"){let g=String(m.name??""),w=m.input?.file_path??m.input?.path,h=ST(w,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?zl(ET(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=$T(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"),uy)};e.signal?.addEventListener("abort",g,{once:!0});let w=null,h=()=>{w&&clearTimeout(w),w=setTimeout(()=>{m=!0,console.warn(`[claude:chat] idle for ${dy}ms \u2014 ending session`),p.kill("SIGTERM"),f=setTimeout(()=>p.kill("SIGKILL"),uy)},dy)},k=()=>{f&&clearTimeout(f),w&&clearTimeout(w),e.signal?.removeEventListener("abort",g)},x=!0,b=v=>{if(!(!x||p.stdin.destroyed))try{p.stdin.write(v)}catch{}};b(Xl(e.prompt)),h(),(async()=>{try{for await(let v of e.interactive.inbox){if(d||!x)break;if(h(),v.kind==="user")i({ts:Date.now(),kind:"text",author:"user",text:zl(v.text,ly)}),b(Xl(v.text,cy(r)));else{b(Xl(xT)),x=!1;try{p.stdin.end()}catch{}break}}}catch{}})();let T="",E=v=>{let I;try{I=JSON.parse(v)}catch{return}c(I)};p.stdout.on("data",v=>{s.push(v),h(),T+=v;let I;for(;(I=T.indexOf(`
772
+ `))!==-1;){let j=T.slice(0,I).trim();T=T.slice(I+1),j&&E(j)}}),p.stderr.on("data",v=>{s.push(v);for(let I of v.split(`
773
+ `)){let j=I.trim();j&&console.warn(`[claude:chat:stderr] ${j}`)}}),p.on("error",v=>{k(),u(v)}),p.on("close",v=>{if(k(),d){u(new Ht);return}if(m){u(new Error("chat session ended: idle for too long without a reply"));return}T.trim()&&E(T.trim()),console.log(`[claude:chat] exit code=${v}`),l({artifactPaths:[],log:s.join(""),usage:RT(a)})})})}function RT(t){let e=Mt();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=Dr(r.input_tokens),e.outputTokens=Dr(r.output_tokens),e.cacheReadInputTokens=Dr(r.cache_read_input_tokens),e.cacheCreationInputTokens=Dr(r.cache_creation_input_tokens)),e.totalCostUsd=Dr(t.total_cost_usd),e.numTurns=Dr(t.num_turns),e.durationMs=Dr(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var ly,uy,dy,xT,fy=S(()=>{"use strict";D();Nn();Is();ly=16e3,uy=5e3,dy=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),xT="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 TT}from"node:child_process";import{existsSync as IT}from"node:fs";function PT(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function my(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: ${lr(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=jT(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=gy(o.content);console.log(`[claude] tool_result (error)${i?`: ${lr(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)} ${lr(JSON.stringify(e),200)}`),e}function AT(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(lr(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(lr(r.trim().split(`
757
774
  `).slice(-5).join(`
758
- `),500)),n.join(" \u2014 ")}function FT(t){if(!t)return;let e=t.retry_after;if(typeof e=="number"&&e>0)return Math.round(e*1e3);let r=typeof t.result=="string"?t.result:"",n=/retry[\s-]*after[:\s]*(\d+)|reset[s]?\s+in[:\s]*(\d+)/i.exec(r),o=n?Number(n[1]??n[2]):NaN;return Number.isFinite(o)&&o>0?o*1e3:void 0}function Gg(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function GT(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=${cr(r,80)}`}return""}function cr(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function qe(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function KT(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=qe(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:qe(e.resetsAt),rateLimitType:typeof e.rateLimitType=="string"?e.rateLimitType:"",utilization:n,isUsingOverage:e.isUsingOverage===!0};return typeof e.surpassedThreshold=="number"&&(o.surpassedThreshold=e.surpassedThreshold),o}function HT(t,e,r,n){let o=qt(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=qe(i.input_tokens),o.outputTokens=qe(i.output_tokens),o.cacheReadInputTokens=qe(i.cache_read_input_tokens),o.cacheCreationInputTokens=qe(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=qe(t?.total_cost_usd),o.numTurns=t&&qe(t.num_turns)>0?qe(t.num_turns):r,o.durationMs=qe(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}function WT(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:cr(c,Fg)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,p=qT(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?cr(Gg(s.content),Fg):"";i.push({ts:r,kind:"tool_result",isError:a,...c?{text:c}:{}})}return i}if(n==="result"){let o=String(t.subtype??"").trim(),i=typeof t.num_turns=="number"?t.num_turns:void 0,s=typeof t.total_cost_usd=="number"?t.total_cost_usd:void 0;return[{ts:r,kind:"result",...o?{text:o}:{},...i!==void 0?{turns:i}:{},...s!==void 0?{costUsd:s}:{}}]}return[]}function qT(t,e){if(!(typeof t!="string"||!t))return t.startsWith(e)?t.slice(e.length).replace(/^\/+/,"")||t.split("/").pop()||void 0:t.startsWith("/")?t.split("/").pop()||void 0:t}var Cn,Kt,DT,Do,Fg,In=x(()=>{"use strict";F();Ug();ks();Cn=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Kt=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},DT=5e3;Do=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return Dg(this.binary,e);if(e.signal?.aborted)throw new Kt;let r=["-p",UT(e.prompt),"--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",ws(Rn(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=KT(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+=qe(k.input_tokens),s.output+=qe(k.output_tokens),s.cacheRead+=qe(k.cache_read_input_tokens),s.cacheCreate+=qe(k.cache_creation_input_tokens))}}},p=e.role,d=e.onActivity,m=f=>{if(d)for(let g of WT(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=LT(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,v=()=>{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")},DT)};e.signal?.addEventListener("abort",v,{once:!0});let S=()=>{w&&clearTimeout(w),e.signal?.removeEventListener("abort",v)},R="";k.stdout.on("data",$=>{n.push($),R+=$;let b;for(;(b=R.indexOf(`
759
- `))!==-1;){let I=R.slice(0,b).trim();if(R=R.slice(b+1),I){let N=Bg(I);u(N),N&&m(N)}}}),k.stderr.on("data",$=>{n.push($),o.push($);for(let b of $.split(`
760
- `)){let I=b.trim();I&&console.warn(`[claude:stderr] ${I}`)}}),k.on("error",$=>{S(),g($)}),k.on("close",$=>{if(S(),h){g(new Kt);return}if(R.trim()){let I=Bg(R.trim());u(I),I&&m(I)}let b=i?.is_error===!0;if($!==0||b){let I=typeof i?.api_error_status=="number"?i.api_error_status:void 0,N=typeof i?.subtype=="string"?i.subtype:void 0,H=typeof i?.result=="string"?i.result:void 0;g(new Cn(BT($,i,o.join("")),{code:$,apiErrorStatus:I,subtype:N,resultText:H,retryAfterMs:FT(i)}));return}console.log("[claude] exit code=0"),f({artifactPaths:[],log:n.join(""),usage:HT(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("/")&&MT(n))}};Fg=200});import{mkdirSync as YT,writeFileSync as An}from"node:fs";import{dirname as zT,join as Pn}from"node:path";function Kg(t,e,r){let n=Pn(t,e);YT(zT(n),{recursive:!0}),An(n,r)}function VT(t,e,r){return`# ${t} \u2014 Estimate
775
+ `),500)),n.join(" \u2014 ")}function _T(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 gy(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function jT(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=${lr(r,80)}`}return""}function lr(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function qe(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function NT(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=qe(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:qe(e.resetsAt),rateLimitType:typeof e.rateLimitType=="string"?e.rateLimitType:"",utilization:n,isUsingOverage:e.isUsingOverage===!0};return typeof e.surpassedThreshold=="number"&&(o.surpassedThreshold=e.surpassedThreshold),o}function OT(t,e,r,n){let o=Mt(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=qe(i.input_tokens),o.outputTokens=qe(i.output_tokens),o.cacheReadInputTokens=qe(i.cache_read_input_tokens),o.cacheCreationInputTokens=qe(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=qe(t?.total_cost_usd),o.numTurns=t&&qe(t.num_turns)>0?qe(t.num_turns):r,o.durationMs=qe(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}function LT(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:lr(c,hy)})}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?lr(gy(s.content),hy):"";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 On,Ht,CT,Go,hy,Nn=S(()=>{"use strict";D();fy();Is();On=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Ht=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},CT=5e3;Go=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return py(this.binary,e);if(e.signal?.aborted)throw new Ht;let r=["-p",PT(e.prompt),"--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",Ts(jn(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=NT(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 w=g?.usage;w&&(a+=1,s.input+=qe(w.input_tokens),s.output+=qe(w.output_tokens),s.cacheRead+=qe(w.cache_read_input_tokens),s.cacheCreate+=qe(w.cache_creation_input_tokens))}}},p=e.role,d=e.onActivity,m=f=>{if(d)for(let g of LT(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 w=TT(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{},CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:"1800000"}});w.stdout.setEncoding("utf-8"),w.stderr.setEncoding("utf-8");let h=!1,k=null,x=()=>{h=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${p}`),w.kill("SIGTERM"),k=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),w.kill("SIGKILL")},CT)};e.signal?.addEventListener("abort",x,{once:!0});let b=()=>{k&&clearTimeout(k),e.signal?.removeEventListener("abort",x)},T="";w.stdout.on("data",E=>{n.push(E),T+=E;let v;for(;(v=T.indexOf(`
776
+ `))!==-1;){let I=T.slice(0,v).trim();if(T=T.slice(v+1),I){let j=my(I);u(j),j&&m(j)}}}),w.stderr.on("data",E=>{n.push(E),o.push(E);for(let v of E.split(`
777
+ `)){let I=v.trim();I&&console.warn(`[claude:stderr] ${I}`)}}),w.on("error",E=>{b(),g(E)}),w.on("close",E=>{if(b(),h){g(new Ht);return}if(T.trim()){let I=my(T.trim());u(I),I&&m(I)}let v=i?.is_error===!0;if(E!==0||v){let I=typeof i?.api_error_status=="number"?i.api_error_status:void 0,j=typeof i?.subtype=="string"?i.subtype:void 0,G=typeof i?.result=="string"?i.result:void 0;g(new On(AT(E,i,o.join("")),{code:E,apiErrorStatus:I,subtype:j,resultText:G,retryAfterMs:_T(i)}));return}console.log("[claude] exit code=0"),f({artifactPaths:[],log:n.join(""),usage:OT(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))}};hy=200});import{mkdirSync as DT,writeFileSync as Ur}from"node:fs";import{dirname as UT,join as Br}from"node:path";function yy(t,e,r){let n=Br(t,e);DT(UT(n),{recursive:!0}),Ur(n,r)}function BT(t,e,r){return`# ${t} \u2014 Estimate
761
778
 
762
779
  **Title:** ${e}
763
780
 
@@ -778,7 +795,7 @@ production-grade estimates.)
778
795
  ${r.split(`
779
796
  `).slice(0,8).join(`
780
797
  `).trim()||"(empty)"}
781
- `}function XT(t,e,r,n){let o=n?`
798
+ `}function FT(t,e,r,n){let o=n?`
782
799
  ## Reviewer rework instruction
783
800
 
784
801
  > ${n.split(`
@@ -807,10 +824,10 @@ TBD (mock runner does not yet inspect project code).
807
824
  ${r.split(`
808
825
  `).slice(0,8).join(`
809
826
  `).trim()||"(empty)"}
810
- `}function JT(t){return`# ${t} \u2014 Open questions
827
+ `}function GT(t){return`# ${t} \u2014 Open questions
811
828
 
812
829
  (none \u2014 mock runner did not surface ambiguities.)
813
- `}function ZT(t,e,r){let n=r?` (rework: ${r.split(`
830
+ `}function KT(t,e,r){let n=r?` (rework: ${r.split(`
814
831
  `)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
815
832
  index 0000000..1111111 100644
816
833
  --- a/CHANGELOG.md
@@ -821,7 +838,7 @@ index 0000000..1111111 100644
821
838
  +- mock-runner placeholder change for slice 5 testing.
822
839
  +
823
840
  # Changelog
824
- `}function QT(t,e,r){return`# ${t} \u2014 Diff summary
841
+ `}function HT(t,e,r){return`# ${t} \u2014 Diff summary
825
842
 
826
843
  **Title:** ${e}
827
844
  ${r?`
@@ -832,200 +849,205 @@ ${r?`
832
849
  - \`CHANGELOG.md\` \u2014 added entry for ${t}.
833
850
 
834
851
  (Mock-runner output. Replace with claude-headless for production patches.)
835
- `}var Uo,Ml=x(()=>{"use strict";F();In();Uo=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=VT(n,o,i);An(Pn(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;An(Pn(e.workspaceDir,"PLAN.md"),XT(n,o,i,a)),s.push("PLAN.md"),An(Pn(e.workspaceDir,"QUESTIONS.md"),JT(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Kg(e.workspaceDir,"changes/sample.patch",ZT(n,o,a)),s.push("changes/sample.patch"),Kg(e.workspaceDir,"SOLUTION.md",QT(n,o,a)),s.push("SOLUTION.md")}else e.role==="rework"&&(An(Pn(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
836
- `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:qt()}}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 Kt;if(i.kind==="user")r?.({ts:Date.now(),kind:"text",author:"user",text:i.text}),i.text.trim()&&(o=i.text.trim().slice(0,80)),n(`Got it: **${i.text.trim()}**. Anything else to clarify?`);else break}return An(Pn(e.workspaceDir,"DRAFT.md"),`${o}
852
+ `}var Ko,Jl=S(()=>{"use strict";D();Nn();Ko=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=BT(n,o,i);Ur(Br(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Ur(Br(e.workspaceDir,"PLAN.md"),FT(n,o,i,a)),s.push("PLAN.md"),Ur(Br(e.workspaceDir,"QUESTIONS.md"),GT(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;yy(e.workspaceDir,"changes/sample.patch",KT(n,o,a)),s.push("changes/sample.patch"),yy(e.workspaceDir,"SOLUTION.md",HT(n,o,a)),s.push("SOLUTION.md")}else e.role==="rework"&&(Ur(Br(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
853
+ `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:Mt()}}async runInteractive(e){let r=e.role==="config",n=e.onActivity,o=s=>{n?.({ts:Date.now(),kind:"text",author:"agent",text:s}),n?.({ts:Date.now(),kind:"result",author:"agent",text:"success"})};n?.({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),o(r?"Hi! Describe the configuration change you'd like to make.":"Hi! Describe the task you'd like to formulate.");let i=r?"Config from chat":"Draft from chat";for await(let s of e.interactive.inbox){if(e.signal?.aborted)throw new Ht;if(s.kind==="user")n?.({ts:Date.now(),kind:"text",author:"user",text:s.text}),s.text.trim()&&(i=s.text.trim().slice(0,80)),o(`Got it: **${s.text.trim()}**. Anything else to clarify?`);else break}if(r){let s={file:"project.yaml",section:["branch"],edits:[{file:"project.yaml",path:["branch","pattern"],value:"codepipe/<TASK_ID>"}],explanation:`Proposed by the interactive config chat (mock runner): ${i}`,diff:[{path:"branch",before:`branch:
854
+ pattern: <TASK_ID>
855
+ `,after:`branch:
856
+ pattern: codepipe/<TASK_ID>
857
+ `}]};return Ur(Br(e.workspaceDir,"PROPOSAL.json"),JSON.stringify(s,null,2)),{artifactPaths:["PROPOSAL.json"],log:"mock config session finalized PROPOSAL.json",usage:Mt()}}return Ur(Br(e.workspaceDir,"DRAFT.md"),`${i}
837
858
 
838
859
  Produced by the interactive chat (mock runner).
839
- `),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:qt()}}}});function Hg(t){switch(t){case"mock":return new Uo;case"claude-headless":return new Do;default:return null}}function Wg(t,e){let r=e&&e.trim().length>0?e.trim():Je;return t==="mock"?!0:t==="claude-headless"?r==="claude":!1}var qg=x(()=>{"use strict";F();In();Ml();In();Ml()});function Vg(t=process.env){return{maxAttempts:bs(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:bs(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:bs(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:bs(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function nR(t){if(t instanceof Cn){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return tR.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&rR.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:eR.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:Yg.test(s)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:n??`exit ${t.details.code}`}}let e=t instanceof Error?t.message:String(t);return Yg.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function Xg(t){if(t instanceof Cn){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&zg.test(n)}let e=t instanceof Error?t.message:String(t);return zg.test(e)}function oR(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 Jg(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=nR(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=oR(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 bs(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}var eR,Yg,tR,rR,zg,Zg=x(()=>{"use strict";In();eR=new Set([429,500,502,503,529]),Yg=/(\bETIMEDOUT\b|\bECONNRESET\b|\bECONNREFUSED\b|\bEAI_AGAIN\b|\bEPIPE\b|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,tR=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,rR=new Set(["error_max_turns"]);zg=/(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 iR,writeFileSync as sR}from"node:fs";import{homedir as aR}from"node:os";import{join as Qg}from"node:path";function ty(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 ry(t,e,r,n){try{let o=Qg(aR(),".codepipe","debug",ey(t));iR(o,{recursive:!0});let i=new Date().toISOString().replace(/[:.]/g,"-"),s=Qg(o,`${i}-${ey(e)}-${r}.md`);return sR(s,n),s}catch{return null}}var ey,ny=x(()=>{"use strict";ey=t=>t.replace(/[^A-Za-z0-9._-]/g,"_")});import{mkdtempSync as cR,rmSync as lR,writeFileSync as oy}from"node:fs";import{tmpdir as uR}from"node:os";import{join as Dl}from"node:path";function vs(t){return`[url "https://${t}/"]
860
+ `),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:Mt()}}}});function wy(t){switch(t){case"mock":return new Ko;case"claude-headless":return new Go;default:return null}}function by(t,e){let r=e&&e.trim().length>0?e.trim():Je;return t==="mock"?!0:t==="claude-headless"?r==="claude":!1}var ky=S(()=>{"use strict";D();Nn();Jl();Nn();Jl()});function xy(t=process.env){return{maxAttempts:Cs(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:Cs(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:Cs(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:Cs(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function VT(t){if(t instanceof On){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return qT.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&YT.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:WT.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:vy.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 vy.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function Sy(t){if(t instanceof On){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&$y.test(n)}let e=t instanceof Error?t.message:String(t);return $y.test(e)}function zT(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 Ey(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=VT(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=zT(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 Cs(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}var WT,vy,qT,YT,$y,Ry=S(()=>{"use strict";Nn();WT=new Set([429,500,502,503,529]),vy=/(\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,qT=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,YT=new Set(["error_max_turns"]);$y=/(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 XT,writeFileSync as JT}from"node:fs";import{homedir as ZT}from"node:os";import{join as Ty}from"node:path";function Cy(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 Py(t,e,r,n){try{let o=Ty(ZT(),".codepipe","debug",Iy(t));XT(o,{recursive:!0});let i=new Date().toISOString().replace(/[:.]/g,"-"),s=Ty(o,`${i}-${Iy(e)}-${r}.md`);return JT(s,n),s}catch{return null}}var Iy,Ay=S(()=>{"use strict";Iy=t=>t.replace(/[^A-Za-z0-9._-]/g,"_")});import{mkdtempSync as QT,rmSync as eI,writeFileSync as _y}from"node:fs";import{tmpdir as tI}from"node:os";import{join as Zl}from"node:path";function Ps(t){return`[url "https://${t}/"]
840
861
  insteadOf = git@${t}:
841
862
  insteadOf = ssh://git@${t}/
842
- `}function cy(t,e){if(t.length===0)return null;let r=cR(Dl(uR(),"devpipe-gitcreds-")),n=Dl(r,"credentials"),o=Dl(r,"gitconfig");return oy(n,t.join(`
863
+ `}function Ly(t,e){if(t.length===0)return null;let r=QT(Zl(tI(),"devpipe-gitcreds-")),n=Zl(r,"credentials"),o=Zl(r,"gitconfig");return _y(n,t.join(`
843
864
  `)+`
844
- `,{mode:384}),oy(o,`[credential]
865
+ `,{mode:384}),_y(o,`[credential]
845
866
  helper = store --file=${n}
846
- `+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{lR(r,{recursive:!0,force:!0})}catch{}}}}function Ul(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(iy)),(!n||n==="gitlab")&&(e.push(`https://oauth2:${t.mirrorWrite.token}@gitlab.com`),r.push(ay)),(!n||n==="bitbucket")&&(e.push(`https://${Dt}:${encodeURIComponent(t.mirrorWrite.token)}@bitbucket.org`),r.push(sy))}return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(iy)),t.bitbucket?.apiToken&&(e.push(`https://${Dt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(sy)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(ay)),cy(e,r)}function ly(t,e){if(t.contextWrite?.token){let r=Tr(e)??"github.com",n=uo(r);return cy([`https://${n}:${t.contextWrite.token}@${r}`],[vs(r)])}return Ul(t)}var iy,sy,ay,uy=x(()=>{"use strict";F();iy=vs("github.com"),sy=vs("bitbucket.org"),ay=vs("gitlab.com")});import{spawn as py}from"node:child_process";import{existsSync as $s,mkdirSync as Bo,readFileSync as dR,rmSync as Bl,symlinkSync as pR}from"node:fs";import{homedir as fR}from"node:os";import{dirname as jn,join as lr}from"node:path";function fy(t){let e=lr(fR(),".codepipe-sandbox","repos");return t?lr(e,t):e}function my(t,e){let n=(_n.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{_n.get(t)===o&&_n.delete(t)},()=>{_n.get(t)===o&&_n.delete(t)});return _n.set(t,o),n}function dy(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 mR(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 hy(t,e,r,n,o){let i=async c=>{await ne(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await ne(t,["reset","--hard",`origin/${c}`],o),await ne(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!dy(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{$s(t)&&Bl(t,{recursive:!0,force:!0}),Bo(jn(t),{recursive:!0});try{return await ne(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!dy(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),$s(t)&&Bl(t,{recursive:!0,force:!0}),Bo(jn(t),{recursive:!0}),await ne(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if($s(lr(t,".git")))try{return await s()}catch(c){if(!mR(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 gy(t){await ne(t.workspacePath,["reset","--hard",t.baseSha]),await ne(t.workspacePath,["clean","-fdx"])}async function yy(t,e){let r=t.workspacePath;await ne(r,["add","-A"]);let n=(await $e(r,["write-tree"])).trim(),o=(await $e(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:Nn,GIT_AUTHOR_EMAIL:On,GIT_COMMITTER_NAME:Nn,GIT_COMMITTER_EMAIL:On};return(await $e(r,["commit-tree",n,"-m",e],i)).trim()}async function wy(t,e,r,n,o){try{await ne(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw Tr(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 ky(t,e){return $e(t.workspacePath,["diff","--binary",t.baseSha,e])}async function by(t,e){return(await $e(t.workspacePath,["diff","--name-only",t.baseSha,e])).split(`
847
- `).map(n=>n.trim()).filter(n=>n.length>0)}async function vy(t,e,r,n,o){await ne(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await ne(t.workspacePath,["checkout","--force",r])}async function $y(t,e,r,n,o,i){let s=t.workspacePath;await ne(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await $e(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=>$e(s,["rev-parse","-q","--verify",`${f}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await $e(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ne(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(g=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(g)}`)}),await c(n)||await ne(s,["fetch","origin",n],i).catch(()=>{}),!await c(n)))throw new Error(`moved-base apply: delivery base ${n.slice(0,10)} is unreachable \u2014 cannot re-apply the previous iteration onto the fresh ${t.ref}`);let l={...i??process.env,GIT_AUTHOR_NAME:Nn,GIT_AUTHOR_EMAIL:On,GIT_COMMITTER_NAME:Nn,GIT_COMMITTER_EMAIL:On},u=(await $e(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),p=(await $e(s,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await ne(s,["cherry-pick","--quit"],l).catch(()=>{});let d=null;try{await ne(s,["cherry-pick","--no-commit",p],l)}catch(f){d=f instanceof Error?f.message:String(f)}let m=(await $e(s,["diff","--name-only","--diff-filter=U"])).split(`
848
- `).map(f=>f.trim()).filter(f=>f.length>0);if(d&&m.length===0)throw await ne(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${d}`);return m}async function Fl(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:Nn,GIT_AUTHOR_EMAIL:On,GIT_COMMITTER_NAME:Nn,GIT_COMMITTER_EMAIL:On};(await $e(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ne(n,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),await ne(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await ne(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await $e(n,["diff","--name-only","--diff-filter=U"])).split(`
849
- `).map(l=>l.trim()).filter(l=>l.length>0),c=await $e(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}async function Sy(t,e){return $e(t.workspacePath,["diff","--unified=0",`${xy}..HEAD`],e)}async function Gl(t,e,r){await ne(t.workspacePath,["update-ref",xy,e],r)}async function Ey(t,e,r){let n=t.workspacePath,o=[`+refs/heads/${e}:refs/remotes/origin/${e}`,...t.ref!==e?[`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`]:[]];await ne(n,["fetch","--depth=1","origin",...o],r).catch(a=>{console.warn(`[git] review-base ${t.name}: base fetch failed: ${String(a)}`)});let i=()=>$e(n,["merge-base",`origin/${e}`,"HEAD"],r).then(a=>a.trim()||null).catch(()=>null),s=await i();for(let a of[64,256,1024]){if(s)break;await ne(n,["fetch",`--deepen=${a}`,"origin",...o],r).catch(c=>{console.warn(`[git] review-base ${t.name}: --deepen=${a} failed: ${String(c)}`)}),s=await i()}return s||(await $e(n,["rev-parse","--is-shallow-repository"],r)).trim()==="true"&&(await ne(n,["fetch","--unshallow","origin",...o],r).catch(c=>{console.warn(`[git] review-base ${t.name}: --unshallow failed: ${String(c)}`)}),s=await i()),s&&await Gl(t,s,r),s}function ne(t,e,r){return new Promise((n,o)=>{let i=py("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}):
850
- ${s.join("").trim()||"(no stderr)"}`))})})}function $e(t,e,r){return new Promise((n,o)=>{let i=py("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}):
851
- ${a.join("").trim()||"(no stderr)"}`))})})}function Ty(t,e){$s(t)&&Bl(t,{recursive:!0,force:!0}),Bo(jn(t),{recursive:!0}),pR(e,t,"dir")}async function Ry(t,e,r){await ne(t,["worktree","prune"]).catch(()=>{}),Bo(jn(r),{recursive:!0}),await ne(t,["worktree","add","--detach",r,`origin/${e}`])}async function hR(t,e,r){Bo(jn(r),{recursive:!0}),await ne(jn(r),["clone","--quiet","--no-checkout",t,r]),await ne(r,["checkout","--force","--detach",e])}async function Iy(t,e,r,n="worktree",o,i){return r.length===0?[]:my(e,async()=>{let s=[];for(let a of r){let c=lr(fy(i),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await hy(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 $e(c,["rev-parse","HEAD"])).trim(),p=lr(t,"code",a.name);n==="direct"?(Ty(p,c),console.log(`[git] code: linked ${p} \u2192 ${c} @ ${u.slice(0,10)}`)):n==="clone"?(await hR(c,u,p),console.log(`[git] code: clone ${p} \u2190 ${c} @ ${u.slice(0,10)}`)):(await Ry(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 my(e,async()=>{let a=lr(fy(i),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);try{await hy(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=lr(t,"context");n==="direct"?(Ty(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await Ry(a,s.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await $e(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function Ay(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await ne(r,["add","-A",...n]).catch(()=>{});let o;try{o=await $e(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
852
- `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=dR(lr(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var _n,Nn,On,xy,Py=x(()=>{"use strict";F();_n=new Map;Nn="CodePipe Agent",On="codepipe@codepartner.ee";xy="refs/worktree/codepipe/review-base"});import{existsSync as gR,readFileSync as yR}from"node:fs";import{join as wR}from"node:path";import{parse as kR}from"yaml";function _y(t){if(!t)return!1;let e=wR(t,Kl);if(!gR(e))return!1;try{let r=kR(yR(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 Kl,jy=x(()=>{"use strict";Kl="knowledge/build.yaml"});import{readFileSync as bR}from"node:fs";import{join as vR}from"node:path";function Ny(t){let e=vR(t,Fo),r;try{r=bR(e,"utf-8")}catch{throw new ur(`BUILD produced no ${Fo} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new ur(`${Fo} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new ur(`${Fo} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new ur(`${Fo}: "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"?$R(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 $R(t){let e=Buffer.from(t,"utf-8");return e.length<=Hl?t:`\u2026 [${e.length-Hl} bytes elided] \u2026
853
- `+e.subarray(e.length-Hl).toString("utf-8")}var Hl,ur,Fo,Oy=x(()=>{"use strict";Hl=8*1024,ur=class extends Error{},Fo="meta/build-result.json"});var Ly={};Ge(Ly,{REVIEW_RESULT_PATH:()=>Dr,ReviewVerdictError:()=>At,markFindingScope:()=>AR,parseChangedRanges:()=>CR,readCodeReviewResult:()=>Wl});import{readFileSync as xR}from"node:fs";import{join as SR}from"node:path";function Wl(t){let e=SR(t,Dr),r;try{r=xR(e,"utf-8")}catch{throw new At(`code review produced no ${Dr} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(l){throw new At(`${Dr} is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}if(!n||typeof n!="object")throw new At(`${Dr} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new At(`${Dr}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?dr(o.remarks,ER):"";if(!i&&s.trim().length===0)throw new At(`${Dr}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?dr(o.summary,TR):"",c=IR(o.findings);return{approved:i,remarks:s,summary:a,...c.length>0?{findings:c}:{}}}function IR(t){if(!Array.isArray(t))return[];let e=[];for(let r of t.slice(0,RR)){if(!r||typeof r!="object")continue;let n=r,o=typeof n.title=="string"?dr(n.title,512).trim():"",i=typeof n.problem=="string"?dr(n.problem,xs).trim():"";if(!o||!i)continue;let s=typeof n.line=="number"&&Number.isInteger(n.line)&&n.line>0?n.line:void 0,a=n.severity==="blocker"||n.severity==="major"||n.severity==="minor"?n.severity:"other",c=typeof n.scenario=="string"&&n.scenario.trim()?dr(n.scenario,xs):void 0;a==="blocker"&&!c&&(console.warn(`[review] blocker "${o.slice(0,80)}" carries no scenario \u2014 demoted to major`),a="major"),e.push({severity:a,title:o,problem:i,...typeof n.repo=="string"&&n.repo?{repo:n.repo}:{},...typeof n.file=="string"&&n.file?{file:dr(n.file,1024)}:{},...s!==void 0?{line:s}:{},...c?{scenario:c}:{},...typeof n.suggestion=="string"&&n.suggestion.trim()?{suggestion:dr(n.suggestion,xs)}:{},...n.confidence==="high"||n.confidence==="medium"||n.confidence==="low"?{confidence:n.confidence}:{},...n.rule_source==="adr"||n.rule_source==="convention"||n.rule_source==="build"||n.rule_source==="judgment"?{ruleSource:n.rule_source}:{},...typeof n.out_of_diff_reason=="string"&&n.out_of_diff_reason.trim()?{outOfDiffReason:dr(n.out_of_diff_reason,xs)}:{}})}return e}function dr(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
854
- \u2026 [${r.length-e} bytes elided]`}function CR(t){let e=new Map,r=null;for(let n of t.split(`
855
- `)){if(n.startsWith("+++ ")){let o=n.slice(4).trim();r=o==="/dev/null"?null:o.replace(/^b\//,""),r&&!e.has(r)&&e.set(r,[]);continue}if(r&&n.startsWith("@@")){let o=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(n);if(!o)continue;let i=Number(o[1]),s=o[2]!==void 0?Number(o[2]):1,a=s===0?Math.max(1,i):i,c=s===0?Math.max(1,i):i+s-1;e.get(r).push([a,c])}}return e}function AR(t,e,r){for(let n of t.findings??[]){if(!n.file)continue;let o=n.repo??r;if(!o)continue;let i=e.get(o);if(!i)continue;let s=i.get(n.file);if(!s){n.scope="outside";continue}if(n.line===void 0||s.length===0){n.scope="diff";continue}let a=n.line;n.scope=s.some(([c,l])=>a>=c&&a<=l)?"diff":"file"}}var ER,TR,At,Dr,xs,RR,ql=x(()=>{"use strict";ER=16*1024,TR=4*1024,At=class extends Error{},Dr="meta/review-result.json";xs=8*1024,RR=50});import{readFileSync as PR,statSync as _R}from"node:fs";import{join as My}from"node:path";function UR(t){return t.startsWith("meta/")||DR.has(t)}function BR(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 FR(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function Dy(t,e,r){let n=r?.maxBytes??jR,o=r?.totalBytes??NR,i=r?.maxCount??OR,s=e.map((f,g)=>{let k=null;try{k=_R(My(t,f)).size}catch{}return{path:f,index:g,size:k}}),a=[...s].sort((f,g)=>{let k=h=>UR(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=PR(My(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?FR(f.path):BR(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,MR),g=`# Artifacts omitted from upload
867
+ `+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{eI(r,{recursive:!0,force:!0})}catch{}}}}function Ql(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(jy)),(!n||n==="gitlab")&&(e.push(`https://oauth2:${t.mirrorWrite.token}@gitlab.com`),r.push(Oy)),(!n||n==="bitbucket")&&(e.push(`https://${Ut}:${encodeURIComponent(t.mirrorWrite.token)}@bitbucket.org`),r.push(Ny))}return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(jy)),t.bitbucket?.apiToken&&(e.push(`https://${Ut}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(Ny)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(Oy)),Ly(e,r)}function My(t,e){if(t.contextWrite?.token){let r=Tr(e)??"github.com",n=go(r);return Ly([`https://${n}:${t.contextWrite.token}@${r}`],[Ps(r)])}return Ql(t)}var jy,Ny,Oy,Dy=S(()=>{"use strict";D();jy=Ps("github.com"),Ny=Ps("bitbucket.org"),Oy=Ps("gitlab.com")});import{spawn as By}from"node:child_process";import{existsSync as As,mkdirSync as Ho,readFileSync as rI,rmSync as eu,symlinkSync as nI}from"node:fs";import{homedir as oI}from"node:os";import{dirname as Mn,join as ur}from"node:path";function Fy(t){let e=ur(oI(),".codepipe-sandbox","repos");return t?ur(e,t):e}function Gy(t,e){let n=(Ln.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{Ln.get(t)===o&&Ln.delete(t)},()=>{Ln.get(t)===o&&Ln.delete(t)});return Ln.set(t,o),n}function Uy(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 iI(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 Ky(t,e,r,n,o){let i=async c=>{await ne(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await ne(t,["reset","--hard",`origin/${c}`],o),await ne(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!Uy(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{As(t)&&eu(t,{recursive:!0,force:!0}),Ho(Mn(t),{recursive:!0});try{return await ne(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!Uy(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),As(t)&&eu(t,{recursive:!0,force:!0}),Ho(Mn(t),{recursive:!0}),await ne(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(As(ur(t,".git")))try{return await s()}catch(c){if(!iI(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 Hy(t){await ne(t.workspacePath,["reset","--hard",t.baseSha]),await ne(t.workspacePath,["clean","-fdx"])}async function Wy(t,e){let r=t.workspacePath;await ne(r,["add","-A"]);let n=(await $e(r,["write-tree"])).trim(),o=(await $e(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:Dn,GIT_AUTHOR_EMAIL:Un,GIT_COMMITTER_NAME:Dn,GIT_COMMITTER_EMAIL:Un};return(await $e(r,["commit-tree",n,"-m",e],i)).trim()}async function qy(t,e,r,n,o){try{await ne(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw Tr(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 Yy(t,e){return $e(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Vy(t,e){return(await $e(t.workspacePath,["diff","--name-only",t.baseSha,e])).split(`
868
+ `).map(n=>n.trim()).filter(n=>n.length>0)}async function zy(t,e,r,n,o){await ne(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await ne(t.workspacePath,["checkout","--force",r])}async function Xy(t,e,r,n,o,i){let s=t.workspacePath;await ne(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await $e(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=>$e(s,["rev-parse","-q","--verify",`${f}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await $e(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ne(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(g=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(g)}`)}),await c(n)||await ne(s,["fetch","origin",n],i).catch(()=>{}),!await c(n)))throw new Error(`moved-base apply: delivery base ${n.slice(0,10)} is unreachable \u2014 cannot re-apply the previous iteration onto the fresh ${t.ref}`);let l={...i??process.env,GIT_AUTHOR_NAME:Dn,GIT_AUTHOR_EMAIL:Un,GIT_COMMITTER_NAME:Dn,GIT_COMMITTER_EMAIL:Un},u=(await $e(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),p=(await $e(s,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await ne(s,["cherry-pick","--quit"],l).catch(()=>{});let d=null;try{await ne(s,["cherry-pick","--no-commit",p],l)}catch(f){d=f instanceof Error?f.message:String(f)}let m=(await $e(s,["diff","--name-only","--diff-filter=U"])).split(`
869
+ `).map(f=>f.trim()).filter(f=>f.length>0);if(d&&m.length===0)throw await ne(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${d}`);return m}async function tu(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:Dn,GIT_AUTHOR_EMAIL:Un,GIT_COMMITTER_NAME:Dn,GIT_COMMITTER_EMAIL:Un};(await $e(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ne(n,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),await ne(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await ne(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await $e(n,["diff","--name-only","--diff-filter=U"])).split(`
870
+ `).map(l=>l.trim()).filter(l=>l.length>0),c=await $e(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}async function Zy(t,e){return $e(t.workspacePath,["diff","--unified=0",`${Jy}..HEAD`],e)}async function ru(t,e,r){await ne(t.workspacePath,["update-ref",Jy,e],r)}async function Qy(t,e,r){let n=t.workspacePath,o=[`+refs/heads/${e}:refs/remotes/origin/${e}`,...t.ref!==e?[`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`]:[]];await ne(n,["fetch","--depth=1","origin",...o],r).catch(a=>{console.warn(`[git] review-base ${t.name}: base fetch failed: ${String(a)}`)});let i=()=>$e(n,["merge-base",`origin/${e}`,"HEAD"],r).then(a=>a.trim()||null).catch(()=>null),s=await i();for(let a of[64,256,1024]){if(s)break;await ne(n,["fetch",`--deepen=${a}`,"origin",...o],r).catch(c=>{console.warn(`[git] review-base ${t.name}: --deepen=${a} failed: ${String(c)}`)}),s=await i()}return s||(await $e(n,["rev-parse","--is-shallow-repository"],r)).trim()==="true"&&(await ne(n,["fetch","--unshallow","origin",...o],r).catch(c=>{console.warn(`[git] review-base ${t.name}: --unshallow failed: ${String(c)}`)}),s=await i()),s&&await ru(t,s,r),s}function ne(t,e,r){return new Promise((n,o)=>{let i=By("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}):
871
+ ${s.join("").trim()||"(no stderr)"}`))})})}function $e(t,e,r){return new Promise((n,o)=>{let i=By("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}):
872
+ ${a.join("").trim()||"(no stderr)"}`))})})}function ew(t,e){As(t)&&eu(t,{recursive:!0,force:!0}),Ho(Mn(t),{recursive:!0}),nI(e,t,"dir")}async function tw(t,e,r){await ne(t,["worktree","prune"]).catch(()=>{}),Ho(Mn(r),{recursive:!0}),await ne(t,["worktree","add","--detach",r,`origin/${e}`])}async function sI(t,e,r){Ho(Mn(r),{recursive:!0}),await ne(Mn(r),["clone","--quiet","--no-checkout",t,r]),await ne(r,["checkout","--force","--detach",e])}async function rw(t,e,r,n="worktree",o,i){return r.length===0?[]:Gy(e,async()=>{let s=[];for(let a of r){let c=ur(Fy(i),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await Ky(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 $e(c,["rev-parse","HEAD"])).trim(),p=ur(t,"code",a.name);n==="direct"?(ew(p,c),console.log(`[git] code: linked ${p} \u2192 ${c} @ ${u.slice(0,10)}`)):n==="clone"?(await sI(c,u,p),console.log(`[git] code: clone ${p} \u2190 ${c} @ ${u.slice(0,10)}`)):(await tw(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 nw(t,e,r,n="worktree",o,i){if(!r||!r.cloneUrl)return null;let s=r;return Gy(e,async()=>{let a=ur(Fy(i),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);try{await Ky(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=ur(t,"context");n==="direct"?(ew(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await tw(a,s.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await $e(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function ow(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await ne(r,["add","-A",...n]).catch(()=>{});let o;try{o=await $e(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
873
+ `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=rI(ur(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var Ln,Dn,Un,Jy,iw=S(()=>{"use strict";D();Ln=new Map;Dn="CodePipe Agent",Un="codepipe@codepartner.ee";Jy="refs/worktree/codepipe/review-base"});import{existsSync as aI,readFileSync as cI}from"node:fs";import{join as lI}from"node:path";import{parse as uI}from"yaml";function sw(t){if(!t)return!1;let e=lI(t,nu);if(!aI(e))return!1;try{let r=uI(cI(e,"utf-8"));if(!r||typeof r!="object")return!1;let n=r.steps;return!Array.isArray(n)||n.length===0?!1:n.some(o=>o!=null&&typeof o=="object"&&typeof o.run=="string"&&o.run.trim().length>0)}catch{return!1}}var nu,aw=S(()=>{"use strict";nu="knowledge/build.yaml"});import{readFileSync as dI}from"node:fs";import{join as pI}from"node:path";function cw(t){let e=pI(t,Wo),r;try{r=dI(e,"utf-8")}catch{throw new dr(`BUILD produced no ${Wo} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new dr(`${Wo} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new dr(`${Wo} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new dr(`${Wo}: "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"?fI(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 fI(t){let e=Buffer.from(t,"utf-8");return e.length<=ou?t:`\u2026 [${e.length-ou} bytes elided] \u2026
874
+ `+e.subarray(e.length-ou).toString("utf-8")}var ou,dr,Wo,lw=S(()=>{"use strict";ou=8*1024,dr=class extends Error{},Wo="meta/build-result.json"});var uw={};Ge(uw,{REVIEW_RESULT_PATH:()=>Fr,ReviewVerdictError:()=>At,markFindingScope:()=>vI,parseChangedRanges:()=>kI,readCodeReviewResult:()=>iu});import{readFileSync as mI}from"node:fs";import{join as hI}from"node:path";function iu(t){let e=hI(t,Fr),r;try{r=mI(e,"utf-8")}catch{throw new At(`code review produced no ${Fr} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(l){throw new At(`${Fr} is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}if(!n||typeof n!="object")throw new At(`${Fr} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new At(`${Fr}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?pr(o.remarks,gI):"";if(!i&&s.trim().length===0)throw new At(`${Fr}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?pr(o.summary,yI):"",c=bI(o.findings);return{approved:i,remarks:s,summary:a,...c.length>0?{findings:c}:{}}}function bI(t){if(!Array.isArray(t))return[];let e=[];for(let r of t.slice(0,wI)){if(!r||typeof r!="object")continue;let n=r,o=typeof n.title=="string"?pr(n.title,512).trim():"",i=typeof n.problem=="string"?pr(n.problem,_s).trim():"";if(!o||!i)continue;let s=typeof n.line=="number"&&Number.isInteger(n.line)&&n.line>0?n.line:void 0,a=n.severity==="blocker"||n.severity==="major"||n.severity==="minor"?n.severity:"other",c=typeof n.scenario=="string"&&n.scenario.trim()?pr(n.scenario,_s):void 0;a==="blocker"&&!c&&(console.warn(`[review] blocker "${o.slice(0,80)}" carries no scenario \u2014 demoted to major`),a="major"),e.push({severity:a,title:o,problem:i,...typeof n.repo=="string"&&n.repo?{repo:n.repo}:{},...typeof n.file=="string"&&n.file?{file:pr(n.file,1024)}:{},...s!==void 0?{line:s}:{},...c?{scenario:c}:{},...typeof n.suggestion=="string"&&n.suggestion.trim()?{suggestion:pr(n.suggestion,_s)}:{},...n.confidence==="high"||n.confidence==="medium"||n.confidence==="low"?{confidence:n.confidence}:{},...n.rule_source==="adr"||n.rule_source==="convention"||n.rule_source==="build"||n.rule_source==="judgment"?{ruleSource:n.rule_source}:{},...typeof n.out_of_diff_reason=="string"&&n.out_of_diff_reason.trim()?{outOfDiffReason:pr(n.out_of_diff_reason,_s)}:{}})}return e}function pr(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
875
+ \u2026 [${r.length-e} bytes elided]`}function kI(t){let e=new Map,r=null;for(let n of t.split(`
876
+ `)){if(n.startsWith("+++ ")){let o=n.slice(4).trim();r=o==="/dev/null"?null:o.replace(/^b\//,""),r&&!e.has(r)&&e.set(r,[]);continue}if(r&&n.startsWith("@@")){let o=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(n);if(!o)continue;let i=Number(o[1]),s=o[2]!==void 0?Number(o[2]):1,a=s===0?Math.max(1,i):i,c=s===0?Math.max(1,i):i+s-1;e.get(r).push([a,c])}}return e}function vI(t,e,r){for(let n of t.findings??[]){if(!n.file)continue;let o=n.repo??r;if(!o)continue;let i=e.get(o);if(!i)continue;let s=i.get(n.file);if(!s){n.scope="outside";continue}if(n.line===void 0||s.length===0){n.scope="diff";continue}let a=n.line;n.scope=s.some(([c,l])=>a>=c&&a<=l)?"diff":"file"}}var gI,yI,At,Fr,_s,wI,su=S(()=>{"use strict";gI=16*1024,yI=4*1024,At=class extends Error{},Fr="meta/review-result.json";_s=8*1024,wI=50});import{readFileSync as $I,statSync as xI}from"node:fs";import{join as dw}from"node:path";function PI(t){return t.startsWith("meta/")||CI.has(t)}function AI(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 _I(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function pw(t,e,r){let n=r?.maxBytes??SI,o=r?.totalBytes??EI,i=r?.maxCount??RI,s=e.map((f,g)=>{let w=null;try{w=xI(dw(t,f)).size}catch{}return{path:f,index:g,size:w}}),a=[...s].sort((f,g)=>{let w=h=>PI(h.path)?0:1;return w(f)!==w(g)?w(f)-w(g):(f.size??0)-(g.size??0)}),c=a.slice(0,i),l=a.slice(i).sort((f,g)=>f.index-g.index).map(f=>f.path),u=new Array(s.length),p=[],d=0;for(let f of c){let g=null;if(f.size!==null&&f.size<=n&&d+f.size<=o)try{g=$I(dw(t,f.path))}catch{}if(g!==null){d+=g.length,u[f.index]={path:f.path,contentBase64:g.toString("base64")};continue}let w=f.size===null?_I(f.path):AI(f.path,f.size,n,o),h=Buffer.from(w,"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,II),g=`# Artifacts omitted from upload
856
877
 
857
878
  ${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.
858
879
 
859
- `+f.map(k=>`- ${k}
880
+ `+f.map(w=>`- ${w}
860
881
  `).join("")+(l.length>f.length?`
861
882
  \u2026and ${l.length-f.length} more.
862
- `:"");m.push({path:LR,contentBase64:Buffer.from(g,"utf-8").toString("base64")})}return{artifacts:m,omitted:p,dropped:l}}var jR,NR,OR,LR,MR,DR,Uy=x(()=>{"use strict";jR=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),NR=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),OR=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),LR="artifacts-omitted.md",MR=500,DR=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 GR,mkdtempSync as KR,readFileSync as HR,readdirSync as Fy,rmSync as By}from"node:fs";import{tmpdir as WR}from"node:os";import{join as Ss,relative as qR}from"node:path";function Gy(t){let e=KR(Ss(WR(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>By(e,{recursive:!0,force:!0}),listFiles:()=>Ky(e,e),readFile:r=>HR(Ss(e,r),"utf-8"),clean:()=>{for(let r of Fy(e))zR.has(r)||By(Ss(e,r),{recursive:!0,force:!0})}}}function Ky(t,e){let r=[];for(let n of Fy(e)){let o=Ss(e,n),i=GR(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&YR.has(n))continue;r.push(...Ky(t,o))}else r.push(qR(t,o))}return r}var YR,zR,Hy=x(()=>{"use strict";YR=new Set(["code","context","scratch",".claude"]),zR=new Set(["code","context"])});import{readFileSync as VR}from"node:fs";import{join as XR}from"node:path";function tI(t,e){let r=lo(t);return r?qy(rI(r),e):""}function Wy(t,e,r={}){let n=r.perAncestorBudget??JR,o=r.totalBudget??ZR,i=[...t.matchAll(ui)];if(i.length===0)return t;let s=i.map(l=>{let u=l[1],p=nI(e,u),d=p!=null?tI(p,n):"";return{key:u,text:d||`(\u0442\u0435\u043B\u043E \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u043E \u2014 \u0441\u043C. tasks/${u}/task.md)`}}),a=o,c=new Map;for(let l of s){let u=Math.max(0,Math.min(l.text.length,a));c.set(l.key,qy(l.text,u)),a-=u}return t.replace(ui,(l,u)=>c.get(u)??"")}function rI(t){let e=t.split(`
863
- `),r=e.findIndex(a=>eI.test(a));if(r<0)return t;let n=e.slice(0,r).join(`
883
+ `:"");m.push({path:TI,contentBase64:Buffer.from(g,"utf-8").toString("base64")})}return{artifacts:m,omitted:p,dropped:l}}var SI,EI,RI,TI,II,CI,fw=S(()=>{"use strict";SI=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),EI=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),RI=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),TI="artifacts-omitted.md",II=500,CI=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 jI,mkdtempSync as NI,readFileSync as OI,readdirSync as hw,rmSync as mw}from"node:fs";import{tmpdir as LI}from"node:os";import{join as js,relative as MI}from"node:path";function gw(t){let e=NI(js(LI(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>mw(e,{recursive:!0,force:!0}),listFiles:()=>yw(e,e),readFile:r=>OI(js(e,r),"utf-8"),clean:()=>{for(let r of hw(e))UI.has(r)||mw(js(e,r),{recursive:!0,force:!0})}}}function yw(t,e){let r=[];for(let n of hw(e)){let o=js(e,n),i=jI(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&DI.has(n))continue;r.push(...yw(t,o))}else r.push(MI(t,o))}return r}var DI,UI,ww=S(()=>{"use strict";DI=new Set(["code","context","scratch",".claude"]),UI=new Set(["code","context"])});import{readFileSync as BI}from"node:fs";import{join as FI}from"node:path";function qI(t,e){let r=ho(t);return r?kw(YI(r),e):""}function bw(t,e,r={}){let n=r.perAncestorBudget??GI,o=r.totalBudget??KI,i=[...t.matchAll(yi)];if(i.length===0)return t;let s=i.map(l=>{let u=l[1],p=VI(e,u),d=p!=null?qI(p,n):"";return{key:u,text:d||`(\u0442\u0435\u043B\u043E \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u043E \u2014 \u0441\u043C. tasks/${u}/task.md)`}}),a=o,c=new Map;for(let l of s){let u=Math.max(0,Math.min(l.text.length,a));c.set(l.key,kw(l.text,u)),a-=u}return t.replace(yi,(l,u)=>c.get(u)??"")}function YI(t){let e=t.split(`
884
+ `),r=e.findIndex(a=>WI.test(a));if(r<0)return t;let n=e.slice(0,r).join(`
864
885
  `).trim(),o=(e[r]??"").match(/^#+/)?.[0].length??1,i=e.length;for(let a=r+1;a<e.length;a++){let c=(e[a]??"").match(/^(#{1,6})\s/);if(c&&(c[1]?.length??0)<=o){i=a;break}}let s=e.slice(r,i).join(`
865
886
  `).trim();return[n,s].filter(Boolean).join(`
866
887
 
867
- `)}function qy(t,e){return t.length<=e?t:t.slice(0,e).trimEnd()+QR}function nI(t,e){if(!t)return null;try{return VR(XR(t,"tasks",e,"task.md"),"utf-8")}catch{return null}}var JR,ZR,QR,eI,Yy=x(()=>{"use strict";F();JR=1200,ZR=3e3,QR=`
888
+ `)}function kw(t,e){return t.length<=e?t:t.slice(0,e).trimEnd()+HI}function VI(t,e){if(!t)return null;try{return BI(FI(t,"tasks",e,"task.md"),"utf-8")}catch{return null}}var GI,KI,HI,WI,vw=S(()=>{"use strict";D();GI=1200,KI=3e3,HI=`
868
889
 
869
- \u2026(\u043E\u0431\u0440\u0435\u0437\u0430\u043D\u043E)`,eI=/^#{1,6}\s.*(приёмк|acceptance|критери)/i});import{existsSync as Ts,readFileSync as zy,readdirSync as Yl}from"node:fs";import{join as Ht}from"node:path";import{parse as oI}from"yaml";function Rs(t){if(!Ts(t))return[];let e=[];for(let r of Yl(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=Ht(t,r.name);r.isDirectory()?e.push(...Rs(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function Es(t){try{return oI(zy(t,"utf-8"))}catch{return null}}function Vy(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 Rs(Ht(t,"model/derived/structure"))){let s=Ot(Es(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[...Rs(Ht(t,"model/derived/correlates")),Ht(t,"model/derived/relates.yaml")]){if(!Ts(i))continue;let s=to(Es(i));if(s.ok)for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}let n=Ht(t,"model/facts/events");if(Ts(n))for(let i of Yl(n).sort()){if(!i.endsWith(".yaml"))continue;let s=Lt(Es(Ht(n,i)));if(!s.ok)continue;let a=s.value;e.events.set(a.taskKey,a);let c=Se(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,Se(l),"references",1)}for(let i of Rs(Ht(t,"model/facts/identity"))){let s=ro(Es(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=Ht(t,"model/facts/annotations");if(Ts(o)){for(let i of Yl(o).sort())if(i.endsWith(".md"))try{let s=zy(Ht(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 Xy=x(()=>{"use strict";F()});function Zy(t){return new Set((t.toLowerCase().match(/[a-zа-я0-9_]{4,}/g)??[]).filter(e=>!/^\d+$/.test(e)))}function dI(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 Qy(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(Se(e)))&&s(Se(e),Jy);for(let m of`${r}
870
- ${n}`.match(uI)??[]){if(m===e)continue;let f=Se(m);(o.events.has(m)||o.adjacency.has(f))&&s(f,Jy)}let a=new Map;for(let m of o.nodes.keys()){let f=te(m);if(f?.level!=="code")continue;let g=f.path.slice(f.path.lastIndexOf("/")+1);for(let k of[f.path,g])a.has(k)||a.set(k,[]),a.get(k).push(m)}let c=`${r}
871
- ${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],iI)}let l=new Map,u=(m,f)=>{let g=m.toLowerCase();!g||g.length<4||l.set(g,l.has(g)&&l.get(g)!==f?null:f)};for(let m of o.nodes.keys()){let f=te(m);if(!f)continue;let g=f.path.slice(f.path.lastIndexOf("/")+1);f.level==="code"&&u(g.replace(/\.[a-z0-9]+$/i,""),m),f.level==="component"&&u(g,m)}for(let m of`${r}
872
- ${n}`.match(/[A-Za-z][A-Za-z0-9_-]{3,}/g)??[]){let f=l.get(m.toLowerCase());f&&s(f,sI)}let p=Zy(`${r}
873
- ${n}`),d=[];for(let[m,f]of o.events){if(m===e||!f.title)continue;let g=dI(p,Zy(f.title));g>=cI&&d.push({key:Se(m),score:g})}return d.sort((m,f)=>f.score-m.score||(m.key<f.key?-1:1)).slice(0,lI).forEach(m=>s(m.key,aI)),i}var Jy,iI,sI,aI,cI,lI,uI,ew=x(()=>{"use strict";F();Jy=1,iI=.9,sI=.7,aI=.5,cI=.15,lI=3,uI=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g});function tw(t,e,r={}){let n=r.cutoff??vr.activationCutoff,o=r.topK??vr.topKPerNode,i=r.nodeCap??vr.nodeCap,s=new Map;for(let[l,u]of e)s.set(l,{activation:u});let a=[...e].map(([l,u])=>({key:l,activation:u})).sort((l,u)=>u.activation-l.activation||(l.key<u.key?-1:1)),c=new Set;for(;a.length>0;){a.sort((p,d)=>d.activation-p.activation||(p.key<d.key?-1:1));let l=a.shift();if(c.has(l.key)||(s.get(l.key)?.activation??0)>l.activation)continue;if(c.add(l.key),c.size>i)break;let u=[...t.adjacency.get(l.key)??[]].sort((p,d)=>d.weight-p.weight||(p.to<d.to?-1:1)).slice(0,o);for(let p of u){let d=ga[p.kind]??.3,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 rw=x(()=>{"use strict";F()});import{existsSync as Vl,readFileSync as nw,readdirSync as pI}from"node:fs";import{join as As}from"node:path";function zl(t){return Math.ceil(t.length/4)}function Is(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 pr(t){let e=te(t);return e?(e.level==="task"||e.level==="adr",e.path):t}function Cs(t){if(!t.via)return"matched from the task text";let e=pr(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 gI(t,e){let r=/^ADR-(\d{3,4})$/.exec(e)?.[1];if(!r)return null;let n=As(t,"adr");if(!Vl(n))return null;let o=r.padStart(4,"0");for(let i of pI(n).sort())if(!(!i.startsWith(`${o}-`)||!i.endsWith(".md")))try{return{file:`adr/${i}`,content:nw(As(n,i),"utf-8").trim()}}catch{return null}return null}function ow(t){let{taskKey:e,title:r,contextDir:n,model:o,activated:i}=t,s=t.budgetTokens??vr.budgetTokens,a=[],c=0,l=$=>{let b=zl($);return c+b>s?!1:(a.push($),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(`
874
- `));let u=Is(i,$=>$.startsWith("adr::")),p=!1;for(let $ of u){let b=gI(n,pr($.key));if(!b)continue;let I=`${p?"":`
890
+ \u2026(\u043E\u0431\u0440\u0435\u0437\u0430\u043D\u043E)`,WI=/^#{1,6}\s.*(приёмк|acceptance|критери)/i});import{existsSync as Os,readFileSync as $w,readdirSync as au}from"node:fs";import{join as Wt}from"node:path";import{parse as zI}from"yaml";function Ls(t){if(!Os(t))return[];let e=[];for(let r of au(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=Wt(t,r.name);r.isDirectory()?e.push(...Ls(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function Ns(t){try{return zI($w(t,"utf-8"))}catch{return null}}function xw(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 Ls(Wt(t,"model/derived/structure"))){let s=Ot(Ns(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[...Ls(Wt(t,"model/derived/correlates")),Wt(t,"model/derived/relates.yaml")]){if(!Os(i))continue;let s=so(Ns(i));if(s.ok)for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}let n=Wt(t,"model/facts/events");if(Os(n))for(let i of au(n).sort()){if(!i.endsWith(".yaml"))continue;let s=Lt(Ns(Wt(n,i)));if(!s.ok)continue;let a=s.value;e.events.set(a.taskKey,a);let c=Se(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,Se(l),"references",1)}for(let i of Ls(Wt(t,"model/facts/identity"))){let s=ao(Ns(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=Wt(t,"model/facts/annotations");if(Os(o)){for(let i of au(o).sort())if(i.endsWith(".md"))try{let s=$w(Wt(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 Sw=S(()=>{"use strict";D()});function Rw(t){return new Set((t.toLowerCase().match(/[a-zа-я0-9_]{4,}/g)??[]).filter(e=>!/^\d+$/.test(e)))}function rC(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 Tw(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(Se(e)))&&s(Se(e),Ew);for(let m of`${r}
891
+ ${n}`.match(tC)??[]){if(m===e)continue;let f=Se(m);(o.events.has(m)||o.adjacency.has(f))&&s(f,Ew)}let a=new Map;for(let m of o.nodes.keys()){let f=te(m);if(f?.level!=="code")continue;let g=f.path.slice(f.path.lastIndexOf("/")+1);for(let w of[f.path,g])a.has(w)||a.set(w,[]),a.get(w).push(m)}let c=`${r}
892
+ ${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],XI)}let l=new Map,u=(m,f)=>{let g=m.toLowerCase();!g||g.length<4||l.set(g,l.has(g)&&l.get(g)!==f?null:f)};for(let m of o.nodes.keys()){let f=te(m);if(!f)continue;let g=f.path.slice(f.path.lastIndexOf("/")+1);f.level==="code"&&u(g.replace(/\.[a-z0-9]+$/i,""),m),f.level==="component"&&u(g,m)}for(let m of`${r}
893
+ ${n}`.match(/[A-Za-z][A-Za-z0-9_-]{3,}/g)??[]){let f=l.get(m.toLowerCase());f&&s(f,JI)}let p=Rw(`${r}
894
+ ${n}`),d=[];for(let[m,f]of o.events){if(m===e||!f.title)continue;let g=rC(p,Rw(f.title));g>=QI&&d.push({key:Se(m),score:g})}return d.sort((m,f)=>f.score-m.score||(m.key<f.key?-1:1)).slice(0,eC).forEach(m=>s(m.key,ZI)),i}var Ew,XI,JI,ZI,QI,eC,tC,Iw=S(()=>{"use strict";D();Ew=1,XI=.9,JI=.7,ZI=.5,QI=.15,eC=3,tC=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g});function Cw(t,e,r={}){let n=r.cutoff??$r.activationCutoff,o=r.topK??$r.topKPerNode,i=r.nodeCap??$r.nodeCap,s=new Map;for(let[l,u]of e)s.set(l,{activation:u});let a=[...e].map(([l,u])=>({key:l,activation:u})).sort((l,u)=>u.activation-l.activation||(l.key<u.key?-1:1)),c=new Set;for(;a.length>0;){a.sort((p,d)=>d.activation-p.activation||(p.key<d.key?-1:1));let l=a.shift();if(c.has(l.key)||(s.get(l.key)?.activation??0)>l.activation)continue;if(c.add(l.key),c.size>i)break;let u=[...t.adjacency.get(l.key)??[]].sort((p,d)=>d.weight-p.weight||(p.to<d.to?-1:1)).slice(0,o);for(let p of u){let d=Ea[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 Pw=S(()=>{"use strict";D()});import{existsSync as lu,readFileSync as Aw,readdirSync as nC}from"node:fs";import{join as Us}from"node:path";function cu(t){return Math.ceil(t.length/4)}function Ms(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 fr(t){let e=te(t);return e?(e.level==="task"||e.level==="adr",e.path):t}function Ds(t){if(!t.via)return"matched from the task text";let e=fr(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 aC(t,e){let r=/^ADR-(\d{3,4})$/.exec(e)?.[1];if(!r)return null;let n=Us(t,"adr");if(!lu(n))return null;let o=r.padStart(4,"0");for(let i of nC(n).sort())if(!(!i.startsWith(`${o}-`)||!i.endsWith(".md")))try{return{file:`adr/${i}`,content:Aw(Us(n,i),"utf-8").trim()}}catch{return null}return null}function _w(t){let{taskKey:e,title:r,contextDir:n,model:o,activated:i}=t,s=t.budgetTokens??$r.budgetTokens,a=[],c=0,l=E=>{let v=cu(E);return c+v>s?!1:(a.push(E),c+=v,!0)};l([`# Context pack \u2014 ${e}: ${r}`,"","Assembled deterministically from the project map (git history, past","tasks, decisions). No file bodies here \u2014 the paths are ENTRY POINTS","into the repositories; each line says why it made the list."].join(`
895
+ `));let u=Ms(i,E=>E.startsWith("adr::")),p=!1;for(let E of u){let v=aC(n,fr(E.key));if(!v)continue;let I=`${p?"":`
875
896
  ## Governing decisions
876
897
  `}
877
- ### ${pr($.key)} (\`${b.file}\`, ${Cs($)})
898
+ ### ${fr(E.key)} (\`${v.file}\`, ${Ds(E)})
878
899
 
879
- ${b.content}
880
- `;if(!l(I))break;p=!0}let d=Is(i,$=>o.nodes.get($)?.entityId!==void 0).filter($=>o.annotations.has(o.nodes.get($.key).entityId)),m=t.staleKeys??new Set,f=!1;for(let $ of d){let b=o.nodes.get($.key).entityId,I=o.annotations.get(b),N=m.has($.key)?" \u2014 \u26A0 the file changed since the map was built":o.orphanedEntities.has(b)?" \u2014 \u26A0 the file no longer exists":"",H=`${f?"":`
900
+ ${v.content}
901
+ `;if(!l(I))break;p=!0}let d=Ms(i,E=>o.nodes.get(E)?.entityId!==void 0).filter(E=>o.annotations.has(o.nodes.get(E.key).entityId)),m=t.staleKeys??new Set,f=!1;for(let E of d){let v=o.nodes.get(E.key).entityId,I=o.annotations.get(v),j=m.has(E.key)?" \u2014 \u26A0 the file changed since the map was built":o.orphanedEntities.has(v)?" \u2014 \u26A0 the file no longer exists":"",G=`${f?"":`
881
902
  ## Why the code is shaped this way (intent notes)
882
903
  `}
883
- ### \`${pr($.key)}\`${N}
904
+ ### \`${fr(E.key)}\`${j}
884
905
 
885
906
  ${I}
886
- `;if(!l(H))break;f=!0}let g=Se(e),k=Is(i,$=>$.startsWith("task::")&&$!==g).slice(0,fI),h=!1;for(let $ of k){let b=o.events.get(pr($.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=>`\`${pr(y.key)}\``).join(", "),N="",H=b.links?.solution??[`tasks/${b.taskKey}/PLAN.md`,`tasks/${b.taskKey}/SOLUTION.md`].find(y=>Vl(As(n,y)))??`tasks/${b.taskKey}/PLAN.md`,z=As(n,H);if(Vl(z))try{N=`
887
- > ${nw(z,"utf-8").trim().slice(0,hI).replace(/\n+/g," ").trim()}\u2026
888
- > _(full text: \`${H}\`)_`}catch{}let _=`${h?"":`
907
+ `;if(!l(G))break;f=!0}let g=Se(e),w=Ms(i,E=>E.startsWith("task::")&&E!==g).slice(0,oC),h=!1;for(let E of w){let v=o.events.get(fr(E.key));if(!v)continue;let I=[...v.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=>`\`${fr(y.key)}\``).join(", "),j="",G=v.links?.solution??[`tasks/${v.taskKey}/PLAN.md`,`tasks/${v.taskKey}/SOLUTION.md`].find(y=>lu(Us(n,y)))??`tasks/${v.taskKey}/PLAN.md`,z=Us(n,G);if(lu(z))try{j=`
908
+ > ${Aw(z,"utf-8").trim().slice(0,sC).replace(/\n+/g," ").trim()}\u2026
909
+ > _(full text: \`${G}\`)_`}catch{}let A=`${h?"":`
889
910
  ## Related past tasks
890
911
  `}
891
- - **${b.taskKey}**${b.title?` \u2014 ${b.title}`:""}${b.date?` (${b.date})`:""}, ${Cs($)}. Files: ${I||"\u2014"}.${N}`;if(!l(_))break;h=!0}let w=$=>{if(m.has($.key))return!1;let b=o.nodes.get($.key)?.entityId;return!b||!o.orphanedEntities.has(b)},v=Is(i,$=>$.startsWith("code:")),S=v.filter(w).slice(0,mI);if(S.length>0){let $=["","## Files likely involved",""];for(let b of S){let I=`- \`${pr(b.key)}\` \u2014 ${Cs(b)}`;if(c+zl($.join(`
892
- `))+zl(I)>s)break;$.push(I)}$.length>3&&l($.join(`
893
- `))}let R=v.filter($=>!w($)).slice(0,10);if(R.length>0){let $=["","## Possibly stale (verify before trusting)","","These entries reference files that changed after the map was built or","no longer exist at their recorded location. Useful as history, wrong","as current fact.","",...R.map(b=>`- \`${pr(b.key)}\` \u2014 ${Cs(b)}${m.has(b.key)?" (changed since the map was built)":" (file gone)"}`)];l($.join(`
912
+ - **${v.taskKey}**${v.title?` \u2014 ${v.title}`:""}${v.date?` (${v.date})`:""}, ${Ds(E)}. Files: ${I||"\u2014"}.${j}`;if(!l(A))break;h=!0}let k=E=>{if(m.has(E.key))return!1;let v=o.nodes.get(E.key)?.entityId;return!v||!o.orphanedEntities.has(v)},x=Ms(i,E=>E.startsWith("code:")),b=x.filter(k).slice(0,iC);if(b.length>0){let E=["","## Files likely involved",""];for(let v of b){let I=`- \`${fr(v.key)}\` \u2014 ${Ds(v)}`;if(c+cu(E.join(`
913
+ `))+cu(I)>s)break;E.push(I)}E.length>3&&l(E.join(`
914
+ `))}let T=x.filter(E=>!k(E)).slice(0,10);if(T.length>0){let E=["","## Possibly stale (verify before trusting)","","These entries reference files that changed after the map was built or","no longer exist at their recorded location. Useful as history, wrong","as current fact.","",...T.map(v=>`- \`${fr(v.key)}\` \u2014 ${Ds(v)}${m.has(v.key)?" (changed since the map was built)":" (file gone)"}`)];l(E.join(`
894
915
  `))}return a.length<=1?null:a.join(`
895
916
  `)+`
896
- `}var fI,mI,hI,iw=x(()=>{"use strict";F();fI=5,mI=300,hI=400});var lw={};Ge(lw,{assembleContextPack:()=>bI});import{createHash as yI}from"node:crypto";import{existsSync as sw,readFileSync as aw}from"node:fs";import{join as cw}from"node:path";function wI(t){return yI("sha1").update(`blob ${t.length}\0`).update(t).digest("hex")}function kI(t,e,r){let n=new Set;for(let o of e.keys()){let i=te(o);if(i?.level!=="code")continue;let s=t.nodes.get(o);if(!s?.contentHash)continue;let a=r.get(i.repo);if(!a)continue;let c=cw(a,i.path);try{if(!sw(c)){n.add(o);continue}wI(aw(c)).startsWith(s.contentHash)||n.add(o)}catch{}}return n}function bI(t){let e=Vy(t.contextDir);if(e.empty)return null;let r="",n=cw(t.contextDir,`tasks/${t.taskKey}/task.md`);if(sw(n))try{r=aw(n,"utf-8")}catch{r=""}let o=Qy({taskKey:t.taskKey,title:t.title,text:r,model:e});if(o.size===0)return null;let i=tw(e,o),s=t.repoDirs?kI(e,i,t.repoDirs):new Set;return ow({taskKey:t.taskKey,title:t.title,contextDir:t.contextDir,model:e,activated:i,staleKeys:s,...t.budgetTokens!==void 0?{budgetTokens:t.budgetTokens}:{}})}var uw=x(()=>{"use strict";F();Xy();ew();rw();iw()});var mw={};Ge(mw,{SKILLS_DIR:()=>Xl,loadSkills:()=>AI,materializeSkills:()=>PI,renderSkillsBlock:()=>_I,resolveBundledSkillsDir:()=>fw});import{cpSync as vI,existsSync as dw,mkdirSync as $I,readFileSync as xI,readdirSync as pw}from"node:fs";import{dirname as SI,join as fr}from"node:path";import{fileURLToPath as EI}from"node:url";import{parse as TI}from"yaml";function fw(t){for(let e of[t,fr(t,"skills")])try{if(pw(e,{withFileTypes:!0}).some(n=>n.isDirectory()&&dw(fr(e,n.name,"SKILL.md"))))return e}catch{}return t}function II(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
917
+ `}var oC,iC,sC,jw=S(()=>{"use strict";D();oC=5,iC=300,sC=400});var Mw={};Ge(Mw,{assembleContextPack:()=>dC});import{createHash as cC}from"node:crypto";import{existsSync as Nw,readFileSync as Ow}from"node:fs";import{join as Lw}from"node:path";function lC(t){return cC("sha1").update(`blob ${t.length}\0`).update(t).digest("hex")}function uC(t,e,r){let n=new Set;for(let o of e.keys()){let i=te(o);if(i?.level!=="code")continue;let s=t.nodes.get(o);if(!s?.contentHash)continue;let a=r.get(i.repo);if(!a)continue;let c=Lw(a,i.path);try{if(!Nw(c)){n.add(o);continue}lC(Ow(c)).startsWith(s.contentHash)||n.add(o)}catch{}}return n}function dC(t){let e=xw(t.contextDir);if(e.empty)return null;let r="",n=Lw(t.contextDir,`tasks/${t.taskKey}/task.md`);if(Nw(n))try{r=Ow(n,"utf-8")}catch{r=""}let o=Tw({taskKey:t.taskKey,title:t.title,text:r,model:e});if(o.size===0)return null;let i=Cw(e,o),s=t.repoDirs?uC(e,i,t.repoDirs):new Set;return _w({taskKey:t.taskKey,title:t.title,contextDir:t.contextDir,model:e,activated:i,staleKeys:s,...t.budgetTokens!==void 0?{budgetTokens:t.budgetTokens}:{}})}var Dw=S(()=>{"use strict";D();Sw();Iw();Pw();jw()});var Gw={};Ge(Gw,{SKILLS_DIR:()=>uu,loadSkills:()=>vC,materializeSkills:()=>$C,renderSkillsBlock:()=>xC,resolveBundledSkillsDir:()=>Fw});import{cpSync as pC,existsSync as Uw,mkdirSync as fC,readFileSync as mC,readdirSync as Bw}from"node:fs";import{dirname as hC,join as mr}from"node:path";import{fileURLToPath as gC}from"node:url";import{parse as yC}from"yaml";function Fw(t){for(let e of[t,mr(t,"skills")])try{if(Bw(e,{withFileTypes:!0}).some(n=>n.isDirectory()&&Uw(mr(e,n.name,"SKILL.md"))))return e}catch{}return t}function bC(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
897
918
  ---`,3);return r===-1?null:{yaml:e.slice(e.indexOf(`
898
919
  `,3)+1,r),body:e.slice(e.indexOf(`
899
- `,r+1)+1)}}function CI(t,e,r){let n=[],o=[];if(!dw(t))return{skills:n,errors:o};let i;try{i=pw(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=fr(t,s),c=`${r}/${s}`,l;try{l=xI(fr(a,"SKILL.md"),"utf-8")}catch{o.push({source:c,error:"no SKILL.md in the directory"});continue}let u=II(l);if(!u){o.push({source:c,error:"SKILL.md has no frontmatter block"});continue}let p;try{p=TI(u.yaml)}catch(m){o.push({source:c,error:`frontmatter is not valid YAML: ${String(m)}`});continue}let d=Ya({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 AI(t){let e=[],r=(s,a,c)=>{let l=CI(s,a,c);return e.push(...l.errors),l.skills},n=t.sources.bundled?r(RI,"bundled","bundled"):[],o=t.sources.context&&t.contextDir?r(fr(t.contextDir,"skills"),"context","skills"):[],i=t.sources.repo?t.repoDirs.flatMap(s=>r(fr(s,".claude","skills"),"repo","repo")):[];return{skills:za(n,o,i),errors:e}}function PI(t,e){if(e.length===0)return[];let r=fr(t,Xl);$I(r,{recursive:!0});let n=[];for(let o of e)vI(o.dir,fr(r,o.name),{recursive:!0}),n.push(`${Xl}/${o.name}`);return n}function _I(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(`
900
- `)}var Xl,RI,hw=x(()=>{"use strict";F();Xl=".claude/skills";RI=fw(SI(EI(import.meta.url)))});var kw={};Ge(kw,{seedMarketplaces:()=>GI});import{spawn as jI}from"node:child_process";import{cpSync as NI,existsSync as gw,mkdirSync as yw,rmSync as Jl,symlinkSync as OI,writeFileSync as LI}from"node:fs";import{homedir as MI}from"node:os";import{join as mr}from"node:path";function ww(){return mr(MI(),".codepipe-sandbox","plugins")}function BI(t){return mr(ww(),"src",`${t.name}@${t.sha||"head"}`)}function Go(t,e){return new Promise((r,n)=>{let o=jI("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 FI(t){let e=BI(t);if(gw(mr(e,".claude-plugin","marketplace.json")))return e;Jl(e,{recursive:!0,force:!0}),yw(e,{recursive:!0});let r=`https://github.com/${t.repo}.git`;if(t.sha?(await Go(["init","--quiet"],e),await Go(["remote","add","origin",r],e),await Go(["fetch","--quiet","--depth","1","origin",t.sha],e),await Go(["checkout","--quiet","FETCH_HEAD"],e)):await Go(["clone","--quiet","--depth","1",r,e]),!gw(mr(e,".claude-plugin","marketplace.json")))throw Jl(e,{recursive:!0,force:!0}),new Error("no .claude-plugin/marketplace.json \u2014 this repository is not a marketplace");return e}async function GI(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 FI(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=mr(ww(),"seed",r.map(a=>`${a.name}@${a.sha||"head"}`).sort().join("_")),i=mr(o,DI);yw(i,{recursive:!0});let s={};for(let a of r){let c=mr(i,a.name);Jl(c,{recursive:!0,force:!0}),KI(n.get(a.name),c),s[a.name]={source:{source:"github",repo:a.repo},installLocation:c,...a.sha?{commit:a.sha}:{}}}return LI(mr(o,UI),`${JSON.stringify(s,null,2)}
901
- `),{dir:o,ready:r,errors:e}}function KI(t,e){try{OI(t,e,"dir")}catch{NI(t,e,{recursive:!0,filter:r=>!/(^|\/)\.git(\/|$)/.test(r)})}}var DI,UI,bw=x(()=>{"use strict";DI="marketplaces",UI="known_marketplaces.json"});var Sw={};Ge(Sw,{loadRoles:()=>JI,resolveBundledRolesDir:()=>xw});import{existsSync as HI,readFileSync as WI,readdirSync as $w}from"node:fs";import{dirname as qI,join as Zl}from"node:path";import{fileURLToPath as YI}from"node:url";import{parse as zI}from"yaml";function xw(t){for(let e of[t,Zl(t,"roles")])try{if($w(e).some(r=>r.endsWith(".md")))return e}catch{}return t}function XI(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
920
+ `,r+1)+1)}}function kC(t,e,r){let n=[],o=[];if(!Uw(t))return{skills:n,errors:o};let i;try{i=Bw(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=mr(t,s),c=`${r}/${s}`,l;try{l=mC(mr(a,"SKILL.md"),"utf-8")}catch{o.push({source:c,error:"no SKILL.md in the directory"});continue}let u=bC(l);if(!u){o.push({source:c,error:"SKILL.md has no frontmatter block"});continue}let p;try{p=yC(u.yaml)}catch(m){o.push({source:c,error:`frontmatter is not valid YAML: ${String(m)}`});continue}let d=nc({name:s,frontmatter:p,body:u.body});d.ok?n.push({...d.skill,dir:a,origin:e}):o.push({source:c,error:d.error})}return{skills:n,errors:o}}function vC(t){let e=[],r=(s,a,c)=>{let l=kC(s,a,c);return e.push(...l.errors),l.skills},n=t.sources.bundled?r(wC,"bundled","bundled"):[],o=t.sources.context&&t.contextDir?r(mr(t.contextDir,"skills"),"context","skills"):[],i=t.sources.repo?t.repoDirs.flatMap(s=>r(mr(s,".claude","skills"),"repo","repo")):[];return{skills:oc(n,o,i),errors:e}}function $C(t,e){if(e.length===0)return[];let r=mr(t,uu);fC(r,{recursive:!0});let n=[];for(let o of e)pC(o.dir,mr(r,o.name),{recursive:!0}),n.push(`${uu}/${o.name}`);return n}function xC(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(`
921
+ `)}var uu,wC,Kw=S(()=>{"use strict";D();uu=".claude/skills";wC=Fw(hC(gC(import.meta.url)))});var Yw={};Ge(Yw,{seedMarketplaces:()=>jC});import{spawn as SC}from"node:child_process";import{cpSync as EC,existsSync as Hw,mkdirSync as Ww,rmSync as du,symlinkSync as RC,writeFileSync as TC}from"node:fs";import{homedir as IC}from"node:os";import{join as hr}from"node:path";function qw(){return hr(IC(),".codepipe-sandbox","plugins")}function AC(t){return hr(qw(),"src",`${t.name}@${t.sha||"head"}`)}function qo(t,e){return new Promise((r,n)=>{let o=SC("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 _C(t){let e=AC(t);if(Hw(hr(e,".claude-plugin","marketplace.json")))return e;du(e,{recursive:!0,force:!0}),Ww(e,{recursive:!0});let r=`https://github.com/${t.repo}.git`;if(t.sha?(await qo(["init","--quiet"],e),await qo(["remote","add","origin",r],e),await qo(["fetch","--quiet","--depth","1","origin",t.sha],e),await qo(["checkout","--quiet","FETCH_HEAD"],e)):await qo(["clone","--quiet","--depth","1",r,e]),!Hw(hr(e,".claude-plugin","marketplace.json")))throw du(e,{recursive:!0,force:!0}),new Error("no .claude-plugin/marketplace.json \u2014 this repository is not a marketplace");return e}async function jC(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 _C(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=hr(qw(),"seed",r.map(a=>`${a.name}@${a.sha||"head"}`).sort().join("_")),i=hr(o,CC);Ww(i,{recursive:!0});let s={};for(let a of r){let c=hr(i,a.name);du(c,{recursive:!0,force:!0}),NC(n.get(a.name),c),s[a.name]={source:{source:"github",repo:a.repo},installLocation:c,...a.sha?{commit:a.sha}:{}}}return TC(hr(o,PC),`${JSON.stringify(s,null,2)}
922
+ `),{dir:o,ready:r,errors:e}}function NC(t,e){try{RC(t,e,"dir")}catch{EC(t,e,{recursive:!0,filter:r=>!/(^|\/)\.git(\/|$)/.test(r)})}}var CC,PC,Vw=S(()=>{"use strict";CC="marketplaces",PC="known_marketplaces.json"});var Zw={};Ge(Zw,{loadRoles:()=>GC,resolveBundledRolesDir:()=>Jw});import{existsSync as OC,readFileSync as LC,readdirSync as Xw}from"node:fs";import{dirname as MC,join as pu}from"node:path";import{fileURLToPath as DC}from"node:url";import{parse as UC}from"yaml";function Jw(t){for(let e of[t,pu(t,"roles")])try{if(Xw(e).some(r=>r.endsWith(".md")))return e}catch{}return t}function FC(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
902
923
  ---`,3);if(r===-1)return null;let n=e.slice(e.indexOf(`
903
924
  `,3)+1,r),o=e.indexOf(`
904
- `,r+1);return{yaml:n,body:o===-1?"":e.slice(o+1)}}function vw(t,e,r){let n=[],o=[];if(!HI(t))return{roles:n,errors:o};let i;try{i=$w(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=WI(Zl(t,s),"utf-8")}catch(d){o.push({file:a,error:`cannot read: ${String(d)}`});continue}let l=XI(c);if(!l){o.push({file:a,error:"missing frontmatter block (--- \u2026 ---) at the top of the file"});continue}let u;try{u=zI(l.yaml)}catch(d){o.push({file:a,error:`frontmatter is not valid YAML: ${String(d)}`});continue}let p=Fa({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 JI(t){let e=vw(VI,"bundled","bundled"),r=t?vw(Zl(t,"roles"),"project","roles"):{roles:[],errors:[]};return{roles:Ga(e.roles,r.roles),errors:[...e.errors,...r.errors]}}var VI,Ew=x(()=>{"use strict";F();VI=xw(qI(YI(import.meta.url)))});var Tw={};Ge(Tw,{ROLE_AGENTS_DIR:()=>eu,materializeRoleAgents:()=>tC,renderRolesBlock:()=>rC});import{mkdirSync as ZI,writeFileSync as QI}from"node:fs";import{join as Ql}from"node:path";function eC(t,e){let r=["---",`name: ${t.name}`,`description: ${t.description}`,...t.model?[`model: ${t.model}`]:[],"---",""].join(`
905
- `),n=t.refs.length>0&&e?["","## Read these first","",...t.refs.map(o=>`- \`${Ql(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(`
925
+ `,r+1);return{yaml:n,body:o===-1?"":e.slice(o+1)}}function zw(t,e,r){let n=[],o=[];if(!OC(t))return{roles:n,errors:o};let i;try{i=Xw(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=LC(pu(t,s),"utf-8")}catch(d){o.push({file:a,error:`cannot read: ${String(d)}`});continue}let l=FC(c);if(!l){o.push({file:a,error:"missing frontmatter block (--- \u2026 ---) at the top of the file"});continue}let u;try{u=UC(l.yaml)}catch(d){o.push({file:a,error:`frontmatter is not valid YAML: ${String(d)}`});continue}let p=Ja({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 GC(t){let e=zw(BC,"bundled","bundled"),r=t?zw(pu(t,"roles"),"project","roles"):{roles:[],errors:[]};return{roles:Za(e.roles,r.roles),errors:[...e.errors,...r.errors]}}var BC,Qw=S(()=>{"use strict";D();BC=Jw(MC(DC(import.meta.url)))});var eb={};Ge(eb,{ROLE_AGENTS_DIR:()=>mu,materializeRoleAgents:()=>qC,renderRolesBlock:()=>YC});import{mkdirSync as KC,writeFileSync as HC}from"node:fs";import{join as fu}from"node:path";function WC(t,e){let r=["---",`name: ${t.name}`,`description: ${t.description}`,...t.model?[`model: ${t.model}`]:[],"---",""].join(`
926
+ `),n=t.refs.length>0&&e?["","## Read these first","",...t.refs.map(o=>`- \`${fu(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(`
906
927
  `):"";return`${r}${t.body}
907
- ${n}`}function tC(t,e,r,n){let o=Ka(e,r);if(o.length===0)return{roles:[],files:[]};let i=Ql(t,eu);ZI(i,{recursive:!0});let s=[];for(let a of o)QI(Ql(i,`${a.name}.md`),eC(a,n)),s.push(`${eu}/${a.name}.md`);return{roles:o,files:s}}function rC(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(`
928
+ ${n}`}function qC(t,e,r,n){let o=Qa(e,r);if(o.length===0)return{roles:[],files:[]};let i=fu(t,mu);KC(i,{recursive:!0});let s=[];for(let a of o)HC(fu(i,`${a.name}.md`),WC(a,n)),s.push(`${mu}/${a.name}.md`);return{roles:o,files:s}}function YC(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(`
908
929
  `),"","Delegate to **every** role above \u2014 **in parallel**, all Task calls in one","turn. Give each role the SAME briefing (DEV-651 \u2014 the panel's quality is","the briefing's quality, not the coordinator's mood):","","- the review subject: `git diff refs/worktree/codepipe/review-base..HEAD`"," in each repo under `code/` \u2014 the base ref is pinned, do not diff against"," a branch tip;","- the finding contract: every finding names file + line, the concrete"," failing scenario, and stays within the diff \u2014 or states explicitly how"," the change broke an untouched place;","- established facts the role must not re-derive (the BUILD verdict when"," your prompt carries one).","","The roles are independent read-only views that never wait on each other,","so the panel costs the time of its slowest member, not the sum. Then do","your own job on what comes back:","",`1. Save each role's findings verbatim as \`${e}/<role>.md\`.`,"2. **Deduplicate.** Two roles reporting the same defect is one finding, not two.","3. **Filter.** A finding earns a round-trip only if it is a real defect, a"," regression or a convention the project actually enforces. Taste-level notes"," go in the summary, never in the remarks.","4. **Decide.** The verdict is yours, not a vote: a role can be wrong, and you"," are the one who read the code. When you overrule a role, say why in the"," summary.","","A role that returns nothing is a normal outcome \u2014 do not manufacture findings","to justify the panel.",""].join(`
909
- `)}var eu,Rw=x(()=>{"use strict";F();eu=".claude/agents"});var Cw={};Ge(Cw,{COUNCIL_ANSWER_PATH:()=>Iw,readCouncilVerdict:()=>iC});import{readFileSync as nC}from"node:fs";import{join as oC}from"node:path";function iC(t){let e;try{e=nC(oC(t,Iw),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var Iw,Aw=x(()=>{"use strict";Iw="meta/council-answer.json"});var _w={};Ge(_w,{QUEUE_PLAN_PATH:()=>Pw,readQueuePlan:()=>cC});import{readFileSync as sC}from"node:fs";import{join as aC}from"node:path";function cC(t){let e;try{e=sC(aC(t,Pw),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var Pw,jw=x(()=>{"use strict";Pw="meta/queue-plan.json"});import{mkdirSync as Nw,readFileSync as Ps,readdirSync as lC,writeFileSync as Ow}from"node:fs";import{homedir as uC}from"node:os";import{dirname as dC,join as Pt}from"node:path";function fC(t){let e=Buffer.from(t,"utf-8");if(e.length<=_s)return t;let r=Math.floor(_s/4),n=_s-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}
930
+ `)}var mu,tb=S(()=>{"use strict";D();mu=".claude/agents"});var nb={};Ge(nb,{COUNCIL_ANSWER_PATH:()=>rb,readCouncilVerdict:()=>XC});import{readFileSync as VC}from"node:fs";import{join as zC}from"node:path";function XC(t){let e;try{e=VC(zC(t,rb),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var rb,ob=S(()=>{"use strict";rb="meta/council-answer.json"});var sb={};Ge(sb,{QUEUE_PLAN_PATH:()=>ib,readQueuePlan:()=>QC});import{readFileSync as JC}from"node:fs";import{join as ZC}from"node:path";function QC(t){let e;try{e=JC(ZC(t,ib),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var ib,ab=S(()=>{"use strict";ib="meta/queue-plan.json"});import{mkdirSync as cb,readFileSync as Bs,readdirSync as eP,writeFileSync as lb}from"node:fs";import{homedir as tP}from"node:os";import{dirname as rP,join as _t}from"node:path";function oP(t){let e=Buffer.from(t,"utf-8");if(e.length<=Fs)return t;let r=Math.floor(Fs/4),n=Fs-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}
910
931
 
911
- \u2026 [${s} bytes elided \u2014 log capped at ${_s} bytes for upload] \u2026
932
+ \u2026 [${s} bytes elided \u2014 log capped at ${Fs} bytes for upload] \u2026
912
933
 
913
- ${i}`}function mC(){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 Ko(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=Ag(t.profile,e.sandboxId,!!Q("SANDBOX_CONFIG")),s=Pt(uC(),".codepipe","logs"),a=mi("SANDBOX_LOG",i,s);if(a.enabled){let _=new ln(a);hi(_),console.log(`[log] file logging \u2192 ${_.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${Xe} (protocol ${ht})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=Hg(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=Vg();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let u=new Tn(e.hubUrl,e.token),p=!1,d=new AbortController,m=new Map,f=null,g=null,k=!1,h=()=>{let _=u.openControlSocket();return f=_,_.on("open",()=>{console.log("[ws] connected");let y={type:"sandbox_hello",platformVersion:Xe,protocolVersion:ht};_.send(JSON.stringify(y))}),_.on("message",y=>{let U=y.toString("utf-8"),O=null;try{let K=JSON.parse(U);K&&typeof K=="object"&&(O=K)}catch{}if(O&&O.type==="hello"){let K=O;g=Jn(K.protocolVersion);let ee=g?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${K.platformVersion} (protocol ${K.protocolVersion}) \u2014 ${ee}`),g&&(k=!1);return}if(O&&O.type==="pause_job"){let K=typeof O.jobId=="string"?O.jobId:"",ee=K?m.get(K):void 0;ee?(console.warn(`[ws] pause_job ${K} \u2014 aborting agent`),ee.paused=!0,ee.abort.abort()):console.log(`[ws] pause_job ${K} \u2014 not a running job, ignoring`),K&&_.send(JSON.stringify({type:"job_paused",jobId:K}));return}if(O&&(O.type==="chat_user_message"||O.type==="chat_finalize")){let K=typeof O.jobId=="string"?O.jobId:"",ee=K?m.get(K):void 0;if(ee?.chatInbox)if(O.type==="chat_user_message"){let le=typeof O.text=="string"?O.text:"";le.trim()&&ee.chatInbox.push({kind:"user",text:le})}else ee.chatInbox.finalize();else console.log(`[ws] ${String(O.type)} ${K} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${U}`)}),_.on("close",(y,U)=>{console.log(`[ws] closed code=${y} reason=${U?.toString()||""}`),f===_&&(f=null),!p&&setTimeout(h,2e3)}),_.on("error",y=>console.warn(`[ws] error: ${y.message}`)),_},w=h(),v=async _=>{for(;!p;){if(g===!1){k||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${Xe}, 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,_);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:${_}] ${y.status} \u2014 backoff 5s`),await new Promise(O=>setTimeout(O,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:${_}] error: ${U} \u2014 backoff 5s`),await new Promise(O=>setTimeout(O,5e3))}}};async function S(_,y){let U={abort:new AbortController,paused:!1};y.role==="chat"&&(U.chatInbox=mC()),m.set(y.jobId,U);let O=!1,K=null,ee=null,le=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),Nt=async()=>{try{await _.heartbeat(y.jobId)==="claim_lost"&&(O=!0,console.warn(`[job] ${y.jobId} claim lost \u2014 HUB sweeper took it`))}catch(P){let ue=P instanceof Error?P.message:String(P);console.warn(`[job] ${y.jobId} heartbeat error: ${ue}`)}};Nt();let Ue=setInterval(()=>{Nt()},le),Ne=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($(y.prompt," \u2502 "));let Pe=[],Be=null,M=400,B=25,D=500,X=()=>{if(Be&&(clearTimeout(Be),Be=null),Pe.length===0)return;let P=Pe.splice(0,Pe.length),ue=f;if(!ue||ue.readyState!==ue.OPEN)return;let me={type:"agent_activity",jobId:y.jobId,taskId:y.taskId,projectId:y.projectId,role:y.role,phase:y.phase,events:P};try{ue.send(JSON.stringify(me))}catch{}},G=P=>{Pe.push(P),Pe.length>D&&Pe.shift(),Pe.length>=B?X():Be||(Be=setTimeout(X,M))},E=y.role==="analysis"&&y.taskId.startsWith("draft::")?y.taskId.slice(7):null,C=new Set,T=null;try{if(!c){O||await _.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:Ne,finishedAt:new Date().toISOString()});return}if(!Wg(o,y.provider??null)){O||await _.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${y.provider??"claude"}"`},startedAt:Ne,finishedAt:new Date().toISOString()});return}let P=Gy(y.jobId);console.log(`[job] ${y.jobId} workspace=${P.dir}`);let ue=R(y,r);K=ue.gitCreds,ee=ue.contextGitCreds;let me=K?.env,ft=ue.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:ue.claudeOauthToken}:void 0,ie=[],re=null,zs=null;try{let L=y.role==="build"?"clone":"worktree";ie=await Iy(P.dir,y.projectId,y.projectRepos,L,me,n);let j=await Cy(P.dir,y.projectId,y.contextRepo,"worktree",me,n);zs=j,re=j?.workspacePath??null}catch(L){let j=L instanceof Error?L.message:String(L);console.warn(`[job] ${y.jobId} materialize failed: ${j}`),O||await _.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${j}`},startedAt:Ne,finishedAt:new Date().toISOString()}),P.dispose();return}let Yn=y.model;y.role==="build"&&y.modelDiscovery&&!_y(re)&&(Yn=y.modelDiscovery,console.log(`[job] ${y.jobId} BUILD discovery (no steps in ${Kl}) \u2014 model=${Yn}`));let $u=async()=>{if(!y.deliveries||y.deliveries.length===0)return[];let L=y.contextRepo?.cloneUrl;if(!L||!me)throw new Error(L?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let j=[];for(let q of y.deliveries){let V=ie.find(oe=>oe.name===q.name);if(V){if(y.role==="implement"&&q.baseSha&&q.baseSha!==V.baseSha){let oe=await $y(V,q.deliveryRef,q.deliverySha,q.baseSha,L,me);console.log(`[job] ${y.jobId} ${V.name}: base moved ${q.baseSha.slice(0,10)} \u2192 ${V.baseSha.slice(0,10)} \u2014 re-applied delivery ${q.deliverySha.slice(0,10)} (${oe.length} conflicted file(s))`),oe.length>0&&j.push(`- **${V.name}**:`,...oe.map(rt=>` - \`${rt}\``));continue}await vy(V,q.deliveryRef,q.deliverySha,L,me),console.log(`[job] ${y.jobId} ${V.name}: checked out delivery ${q.deliverySha.slice(0,10)} for ${y.role}`)}}return j},Vs=[];if(y.role==="build"||y.role==="implement"||y.role==="code-review")try{Vs=await $u()}catch(L){let j=L instanceof Error?L.message:String(L);console.warn(`[job] ${y.jobId} delivery checkout failed: ${j}`),O||await _.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${j}`},startedAt:Ne,finishedAt:new Date().toISOString()}),P.dispose();return}if(y.role==="code-review"){let L=y.metadata?.externalReview===!0;for(let j of ie)try{if(L){let q=y.projectRepos.find(oe=>oe.name===j.name)?.defaultBranch??j.ref,V=await Ey(j,q,me);V?console.log(`[job] ${y.jobId} ${j.name}: review base ${V.slice(0,10)} (merge-base with ${q})`):console.warn(`[job] ${y.jobId} ${j.name}: no merge-base with ${q} \u2014 review base not pinned (agent falls back to manual deepen)`)}else await Gl(j,j.baseSha,me),console.log(`[job] ${y.jobId} ${j.name}: review base ${j.baseSha.slice(0,10)} (pre-delivery)`)}catch(q){let V=q instanceof Error?q.message:String(q);console.warn(`[job] ${y.jobId} ${j.name}: review-base pin failed: ${V}`)}}let Xs=y.role==="resolve-conflict"?y.metadata?.mergeBranchByRepo??y.metadata?.taskBranchByRepo??{}:{},xu="";if(y.role==="resolve-conflict"){if(!ie.some(L=>Xs[L.name])){let L="resolve-conflict job carries no branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${y.jobId} ${L}`),O||await _.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:L},startedAt:Ne,finishedAt:new Date().toISOString()}),P.dispose();return}try{let L=[];for(let j of ie){let q=Xs[j.name];if(!q)continue;let V=await Fl(j,q,me);console.log(`[job] ${y.jobId} ${j.name}: merged ${q} into ${j.ref} \u2014 ${V.length} conflicted file(s)`),V.length>0?L.push(`- **${j.name}**:`,...V.map(oe=>` - \`${oe}\``)):L.push(`- **${j.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}xu=`
934
+ ${i}`}function iP(){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 Yo(t={}){let e=Me(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,n=e.sandboxId,o=e.llm,i=oy(t.profile,e.sandboxId,!!Q("SANDBOX_CONFIG")),s=_t(tP(),".codepipe","logs"),a=vi("SANDBOX_LOG",i,s);if(a.enabled){let A=new fn(a);$i(A),console.log(`[log] file logging \u2192 ${A.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${Xe} (protocol ${ht})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=wy(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=xy();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,w=!1,h=()=>{let A=u.openControlSocket();return f=A,A.on("open",()=>{console.log("[ws] connected");let y={type:"sandbox_hello",platformVersion:Xe,protocolVersion:ht};A.send(JSON.stringify(y))}),A.on("message",y=>{let U=y.toString("utf-8"),N=null;try{let H=JSON.parse(U);H&&typeof H=="object"&&(N=H)}catch{}if(N&&N.type==="hello"){let H=N;g=ro(H.protocolVersion);let X=g?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${H.platformVersion} (protocol ${H.protocolVersion}) \u2014 ${X}`),g&&(w=!1);return}if(N&&N.type==="pause_job"){let H=typeof N.jobId=="string"?N.jobId:"",X=H?m.get(H):void 0;X?(console.warn(`[ws] pause_job ${H} \u2014 aborting agent`),X.paused=!0,X.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(N&&(N.type==="chat_user_message"||N.type==="chat_finalize")){let H=typeof N.jobId=="string"?N.jobId:"",X=H?m.get(H):void 0;if(X?.chatInbox)if(N.type==="chat_user_message"){let ue=typeof N.text=="string"?N.text:"";ue.trim()&&X.chatInbox.push({kind:"user",text:ue})}else X.chatInbox.finalize();else console.log(`[ws] ${String(N.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},k=h(),x=async A=>{for(;!p;){if(g===!1){w||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${Xe}, protocol ${ht}) \u2014 not claiming jobs until versions align.`),w=!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(N=>setTimeout(N,5e3));continue}let U=await y.json();await b(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(N=>setTimeout(N,5e3))}}};async function b(A,y){let U={abort:new AbortController,paused:!1};_a(y.role)&&(U.chatInbox=iP()),m.set(y.jobId,U);let N=!1,H=null,X=null,ue=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),xt=async()=>{try{await A.heartbeat(y.jobId)==="claim_lost"&&(N=!0,console.warn(`[job] ${y.jobId} claim lost \u2014 HUB sweeper took it`))}catch(C){let Y=C instanceof Error?C.message:String(C);console.warn(`[job] ${y.jobId} heartbeat error: ${Y}`)}};xt();let pt=setInterval(()=>{xt()},ue),Re=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(E(y.prompt," \u2502 "));let Ae=[],Oe=null,Be=400,M=25,B=500,L=()=>{if(Oe&&(clearTimeout(Oe),Oe=null),Ae.length===0)return;let C=Ae.splice(0,Ae.length),Y=f;if(!Y||Y.readyState!==Y.OPEN)return;let fe={type:"agent_activity",jobId:y.jobId,taskId:y.taskId,projectId:y.projectId,role:y.role,phase:y.phase,events:C};try{Y.send(JSON.stringify(fe))}catch{}},ee=C=>{Ae.push(C),Ae.length>B&&Ae.shift(),Ae.length>=M?L():Oe||(Oe=setTimeout(L,Be))},F=y.role==="analysis"&&y.taskId.startsWith("draft::")?y.taskId.slice(7):null,R=new Set,$=null;try{if(!c){N||await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:Re,finishedAt:new Date().toISOString()});return}if(!by(o,y.provider??null)){N||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:Re,finishedAt:new Date().toISOString()});return}let C=gw(y.jobId);console.log(`[job] ${y.jobId} workspace=${C.dir}`);let Y=T(y,r);H=Y.gitCreds,X=Y.contextGitCreds;let fe=H?.env,ft=Y.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:Y.claudeOauthToken}:void 0,ie=[],re=null,na=null;try{let O=y.role==="build"?"clone":"worktree";ie=await rw(C.dir,y.projectId,y.projectRepos,O,fe,n);let _=await nw(C.dir,y.projectId,y.contextRepo,"worktree",fe,n);na=_,re=_?.workspacePath??null}catch(O){let _=O instanceof Error?O.message:String(O);console.warn(`[job] ${y.jobId} materialize failed: ${_}`),N||await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${_}`},startedAt:Re,finishedAt:new Date().toISOString()}),C.dispose();return}let Zn=y.model;y.role==="build"&&y.modelDiscovery&&!sw(re)&&(Zn=y.modelDiscovery,console.log(`[job] ${y.jobId} BUILD discovery (no steps in ${nu}) \u2014 model=${Zn}`));let Gu=async()=>{if(!y.deliveries||y.deliveries.length===0)return[];let O=y.contextRepo?.cloneUrl;if(!O||!fe)throw new Error(O?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let _=[];for(let W of y.deliveries){let V=ie.find(oe=>oe.name===W.name);if(V){if(y.role==="implement"&&W.baseSha&&W.baseSha!==V.baseSha){let oe=await Xy(V,W.deliveryRef,W.deliverySha,W.baseSha,O,fe);console.log(`[job] ${y.jobId} ${V.name}: base moved ${W.baseSha.slice(0,10)} \u2192 ${V.baseSha.slice(0,10)} \u2014 re-applied delivery ${W.deliverySha.slice(0,10)} (${oe.length} conflicted file(s))`),oe.length>0&&_.push(`- **${V.name}**:`,...oe.map(rt=>` - \`${rt}\``));continue}await zy(V,W.deliveryRef,W.deliverySha,O,fe),console.log(`[job] ${y.jobId} ${V.name}: checked out delivery ${W.deliverySha.slice(0,10)} for ${y.role}`)}}return _},oa=[];if(y.role==="build"||y.role==="implement"||y.role==="code-review")try{oa=await Gu()}catch(O){let _=O instanceof Error?O.message:String(O);console.warn(`[job] ${y.jobId} delivery checkout failed: ${_}`),N||await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${_}`},startedAt:Re,finishedAt:new Date().toISOString()}),C.dispose();return}if(y.role==="code-review"){let O=y.metadata?.externalReview===!0;for(let _ of ie)try{if(O){let W=y.projectRepos.find(oe=>oe.name===_.name)?.defaultBranch??_.ref,V=await Qy(_,W,fe);V?console.log(`[job] ${y.jobId} ${_.name}: review base ${V.slice(0,10)} (merge-base with ${W})`):console.warn(`[job] ${y.jobId} ${_.name}: no merge-base with ${W} \u2014 review base not pinned (agent falls back to manual deepen)`)}else await ru(_,_.baseSha,fe),console.log(`[job] ${y.jobId} ${_.name}: review base ${_.baseSha.slice(0,10)} (pre-delivery)`)}catch(W){let V=W instanceof Error?W.message:String(W);console.warn(`[job] ${y.jobId} ${_.name}: review-base pin failed: ${V}`)}}let ia=y.role==="resolve-conflict"?y.metadata?.mergeBranchByRepo??y.metadata?.taskBranchByRepo??{}:{},Ku="";if(y.role==="resolve-conflict"){if(!ie.some(O=>ia[O.name])){let O="resolve-conflict job carries no branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${y.jobId} ${O}`),N||await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:O},startedAt:Re,finishedAt:new Date().toISOString()}),C.dispose();return}try{let O=[];for(let _ of ie){let W=ia[_.name];if(!W)continue;let V=await tu(_,W,fe);console.log(`[job] ${y.jobId} ${_.name}: merged ${W} into ${_.ref} \u2014 ${V.length} conflicted file(s)`),V.length>0?O.push(`- **${_.name}**:`,...V.map(oe=>` - \`${oe}\``)):O.push(`- **${_.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}Ku=`
914
935
 
915
936
  ## Conflicts to resolve
916
937
 
917
- `+(L.length>0?L.join(`
938
+ `+(O.length>0?O.join(`
918
939
  `):"(no task branches to merge)")+`
919
- `}catch(L){let j=L instanceof Error?L.message:String(L);console.warn(`[job] ${y.jobId} conflict merge failed: ${j}`),O||await _.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${j}`},startedAt:Ne,finishedAt:new Date().toISOString()}),P.dispose();return}}let Js=null;if(y.contextPack&&re)try{let{assembleContextPack:L}=await Promise.resolve().then(()=>(uw(),lw)),j=L({contextDir:re,taskKey:String(y.metadata?.trackerIssueKey??y.taskId.split(":")[1]??""),title:String(y.metadata?.taskTitle??""),repoDirs:new Map(ie.map(q=>[q.name,q.workspacePath]))});j?(Nw(Pt(P.dir,"meta"),{recursive:!0}),Ow(Pt(P.dir,"meta","context-pack.md"),j),Js=j,console.log(`[job] ${y.jobId} context pack: ${j.length} chars \u2192 meta/context-pack.md`)):console.log(`[job] ${y.jobId} context pack: model empty or no signal \u2014 skipped`)}catch(L){let j=L instanceof Error?L.message:String(L);console.warn(`[job] ${y.jobId} context pack failed (non-fatal): ${j}`)}let Su="",Qo=null,Zs=null;try{let{loadSkills:L,materializeSkills:j,renderSkillsBlock:q}=await Promise.resolve().then(()=>(hw(),mw)),V=y.skills??{bundled:!0,context:!0,repo:!0},oe=L({contextDir:re,repoDirs:ie.map(nt=>nt.workspacePath),sources:V});for(let nt of oe.errors)console.warn(`[job] ${y.jobId} skill ${nt.source}: ${nt.error}`);let rt=j(P.dir,oe.skills),he=["implement","rework","testing"].includes(y.role)?Xa(Va(I(re,y.taskId))):[];Su=q(oe.skills,he),rt.length>0&&console.log(`[job] ${y.jobId} skills: ${oe.skills.map(nt=>nt.name).join(", ")}`);let{parseMarketplaces:Fe,enabledPluginsSetting:Gr}=await Promise.resolve().then(()=>(F(),Kd)),{sources:Kr,errors:Vn}=Fe(V.marketplaces??[]);for(let nt of Vn)console.warn(`[job] ${y.jobId} marketplace ${nt}`);if(Kr.length>0&&(V.plugins??[]).length>0){let{seedMarketplaces:nt}=await Promise.resolve().then(()=>(bw(),kw)),Hr=await nt(Kr);for(let J of Hr.errors)console.warn(`[job] ${y.jobId} marketplace ${J.repo}: ${J.error}`);let{enabled:Wr,unknown:qr}=Gr(V.plugins??[],Hr.ready);for(let J of qr)console.warn(`[job] ${y.jobId} plugin ${J}: no such marketplace in this project`);Hr.dir&&Object.keys(Wr).length>0&&(Qo=Hr.dir,Zs={enabledPlugins:Wr},console.log(`[job] ${y.jobId} plugins: ${Object.keys(Wr).join(", ")}`))}}catch(L){let j=L instanceof Error?L.message:String(L);console.warn(`[job] ${y.jobId} skills unavailable (non-fatal): ${j}`)}let Eu="",xb=y.role==="code-review"&&y.metadata?.reviewPanel===!1;if(["code-review","council","analyze","testing"].includes(y.role)&&!xb)try{let{loadRoles:L}=await Promise.resolve().then(()=>(Ew(),Sw)),{materializeRoleAgents:j,renderRolesBlock:q}=await Promise.resolve().then(()=>(Rw(),Tw)),V=L(re);for(let Fe of V.errors)console.warn(`[job] ${y.jobId} role ${Fe.file}: ${Fe.error}`);let oe=y.role==="council"?"council":y.role==="analyze"?"plan_review":"code_review",rt=y.role==="council"?"council":y.role==="analyze"?"plan-review":y.role==="testing"?"testing":"code-review",he=j(P.dir,V.roles,oe,re);Eu=q(he,rt),console.log(`[job] ${y.jobId} review panel: ${he.roles.length>0?he.roles.map(Fe=>Fe.name).join(", "):"(no roles)"}`)}catch(L){let j=L instanceof Error?L.message:String(L);console.warn(`[job] ${y.jobId} review panel unavailable (non-fatal): ${j}`)}let Sb=Vs.length>0?`
940
+ `}catch(O){let _=O instanceof Error?O.message:String(O);console.warn(`[job] ${y.jobId} conflict merge failed: ${_}`),N||await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${_}`},startedAt:Re,finishedAt:new Date().toISOString()}),C.dispose();return}}let sa=null;if(y.contextPack&&re)try{let{assembleContextPack:O}=await Promise.resolve().then(()=>(Dw(),Mw)),_=O({contextDir:re,taskKey:String(y.metadata?.trackerIssueKey??y.taskId.split(":")[1]??""),title:String(y.metadata?.taskTitle??""),repoDirs:new Map(ie.map(W=>[W.name,W.workspacePath]))});_?(cb(_t(C.dir,"meta"),{recursive:!0}),lb(_t(C.dir,"meta","context-pack.md"),_),sa=_,console.log(`[job] ${y.jobId} context pack: ${_.length} chars \u2192 meta/context-pack.md`)):console.log(`[job] ${y.jobId} context pack: model empty or no signal \u2014 skipped`)}catch(O){let _=O instanceof Error?O.message:String(O);console.warn(`[job] ${y.jobId} context pack failed (non-fatal): ${_}`)}let Hu="",ii=null,aa=null;try{let{loadSkills:O,materializeSkills:_,renderSkillsBlock:W}=await Promise.resolve().then(()=>(Kw(),Gw)),V=y.skills??{bundled:!0,context:!0,repo:!0},oe=O({contextDir:re,repoDirs:ie.map(nt=>nt.workspacePath),sources:V});for(let nt of oe.errors)console.warn(`[job] ${y.jobId} skill ${nt.source}: ${nt.error}`);let rt=_(C.dir,oe.skills),me=["implement","rework","testing"].includes(y.role)?sc(ic(I(re,y.taskId))):[];Hu=W(oe.skills,me),rt.length>0&&console.log(`[job] ${y.jobId} skills: ${oe.skills.map(nt=>nt.name).join(", ")}`);let{parseMarketplaces:Fe,enabledPluginsSetting:Wr}=await Promise.resolve().then(()=>(D(),gp)),{sources:qr,errors:eo}=Fe(V.marketplaces??[]);for(let nt of eo)console.warn(`[job] ${y.jobId} marketplace ${nt}`);if(qr.length>0&&(V.plugins??[]).length>0){let{seedMarketplaces:nt}=await Promise.resolve().then(()=>(Vw(),Yw)),Yr=await nt(qr);for(let J of Yr.errors)console.warn(`[job] ${y.jobId} marketplace ${J.repo}: ${J.error}`);let{enabled:Vr,unknown:zr}=Wr(V.plugins??[],Yr.ready);for(let J of zr)console.warn(`[job] ${y.jobId} plugin ${J}: no such marketplace in this project`);Yr.dir&&Object.keys(Vr).length>0&&(ii=Yr.dir,aa={enabledPlugins:Vr},console.log(`[job] ${y.jobId} plugins: ${Object.keys(Vr).join(", ")}`))}}catch(O){let _=O instanceof Error?O.message:String(O);console.warn(`[job] ${y.jobId} skills unavailable (non-fatal): ${_}`)}let Wu="",iv=y.role==="code-review"&&y.metadata?.reviewPanel===!1;if(["code-review","council","analyze","testing"].includes(y.role)&&!iv)try{let{loadRoles:O}=await Promise.resolve().then(()=>(Qw(),Zw)),{materializeRoleAgents:_,renderRolesBlock:W}=await Promise.resolve().then(()=>(tb(),eb)),V=O(re);for(let Fe of V.errors)console.warn(`[job] ${y.jobId} role ${Fe.file}: ${Fe.error}`);let oe=y.role==="council"?"council":y.role==="analyze"?"plan_review":"code_review",rt=y.role==="council"?"council":y.role==="analyze"?"plan-review":y.role==="testing"?"testing":"code-review",me=_(C.dir,V.roles,oe,re);Wu=W(me,rt),console.log(`[job] ${y.jobId} review panel: ${me.roles.length>0?me.roles.map(Fe=>Fe.name).join(", "):"(no roles)"}`)}catch(O){let _=O instanceof Error?O.message:String(O);console.warn(`[job] ${y.jobId} review panel unavailable (non-fatal): ${_}`)}let sv=oa.length>0?`
920
941
 
921
942
  ## Base branch moved \u2014 conflicts to resolve
922
943
 
923
944
  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:
924
945
 
925
- `+Vs.join(`
946
+ `+oa.join(`
926
947
  `)+`
927
- `:"",Tu=N(b(y.prompt,ie,re),re,y.taskId).replace(/\{\{rolesBlock\}\}/g,Eu).replace(/\{\{skillsBlock\}\}/g,Su)+xu+Sb,zn=[...ie.map(L=>L.workspacePath),...re?[re]:[]];if(zn.length>0&&console.log(`[job] ${y.jobId} --add-dir: ${zn.join(", ")}`),ty("agent-request")){let L=ws(Rn(y.metadata??{})),j=ry(y.projectId,y.jobId,"agent-request",[`# Agent request \u2014 job ${y.jobId}`,"",`- project: ${y.projectId}`,`- task: ${y.taskId}`,`- role: ${y.role}`,`- model: ${Yn??"(backend default)"}`,`- add-dirs:${zn.length>0?"":" (none)"}`,...zn.map(q=>` - ${q}`),"","## Append-system-prompt (language directive)","","```",L,"```","","## Prompt","",Tu,"",...Js?["## Context pack (meta/context-pack.md)","",Js]:["## Context pack","","(not generated for this job)"],""].join(`
928
- `));j&&console.log(`[debug] ${y.jobId} agent request \u2192 ${j}`)}E&&(T=setInterval(()=>{let j=f;if(!j||j.readyState!==j.OPEN)return;let q;try{q=lC(Pt(P.dir,"drafts")).filter(V=>V.endsWith(".json")).sort()}catch{return}for(let V of q){if(C.has(V))continue;if(C.size>=nc)break;let oe;try{let he=JSON.parse(Ps(Pt(P.dir,"drafts",V),"utf-8")),Fe=typeof he.localRef=="string"?he.localRef:"",Gr=typeof he.title=="string"?he.title:"",Kr=typeof he.body=="string"?he.body:"";if(!Fe||!Gr)continue;oe={localRef:Fe,title:Gr,body:Kr,...he.isEpic===!0?{isEpic:!0}:{},...Array.isArray(he.links)?{links:he.links}:{}}}catch{continue}C.add(V);let rt={type:"child_draft",jobId:y.jobId,projectId:y.projectId,draftId:E,child:oe};try{j.send(JSON.stringify(rt))}catch{}}},1500));try{let L={workspaceDir:P.dir,role:y.role,prompt:Tu,addDirs:zn,metadata:y.metadata??{},...Yn?{model:Yn}:{},...ft||Qo?{env:{...ft??{},...Qo?{CLAUDE_CODE_PLUGIN_SEED_DIR:Qo}:{}}}:{},...Zs?{settings:Zs}:{},signal:U.abort.signal,onActivity:G},j=U.chatInbox?await c.run({...L,interactive:{inbox:U.chatInbox.iterable}}):await Jg(c,L,{jobId:y.jobId,policy:l,onBeforeRetry:async()=>{P.clean();for(let J of ie)try{await gy(J);let be=Xs[J.name];y.role==="resolve-conflict"&&be&&await Fl(J,be,me)}catch(be){let Wt=be instanceof Error?be.message:String(be);console.warn(`[job] ${y.jobId} worktree reset failed (${J.name}): ${Wt}`)}try{await $u()}catch(J){let be=J instanceof Error?J.message:String(J);console.warn(`[job] ${y.jobId} delivery re-checkout failed: ${be}`)}},aborted:()=>O||U.paused}),q=[];if(pC.has(y.role)&&ie.length>0){let J=y.metadata??{},be=typeof J.commitMessage=="string"?J.commitMessage:`${y.taskId}: changes`,Wt=y.contextRepo?.cloneUrl,Xn=ee?.env;if(!Wt||!Xn)throw new Error("delivery requested but "+(Wt?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let Qs=y.taskId.includes(":")?y.taskId.slice(y.taskId.indexOf(":")+1):y.taskId;for(let xt of ie){let Yr=await yy(xt,be);if(!Yr){console.log(`[job] ${y.jobId} ${xt.name}: no changes \u2014 no delivery`);continue}let ea=`codepipe/deliveries/${Qs}/${y.jobId}/${xt.name}`;await wy(xt,Yr,ea,Wt,Xn);let Eb=await by(xt,Yr);q.push({name:xt.name,deliveryRef:ea,deliverySha:Yr,baseSha:xt.baseSha,changedFiles:Eb}),console.log(`[job] ${y.jobId} ${xt.name}: delivered ${Yr.slice(0,10)} \u2192 ${ea}`);let Ru=await ky(xt,Yr);if(Ru.trim().length>0){let Tb=Pt("display",`${xt.name}.diff`),Iu=Pt(P.dir,Tb);Nw(dC(Iu),{recursive:!0}),Ow(Iu,Ru)}}}if(y.role==="resolve-conflict"&&q.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 V;y.role==="build"&&(V=Ny(P.dir),console.log(`[job] ${y.jobId} build verdict: ok=${V.ok}`+(V.failedStep?` failedStep=${V.failedStep}`:"")));let oe;if(y.role==="code-review"){oe=Wl(P.dir),console.log(`[job] ${y.jobId} review verdict: approved=${oe.approved}`);try{let{parseChangedRanges:J,markFindingScope:be}=await Promise.resolve().then(()=>(ql(),Ly)),Wt=new Map;for(let Xn of ie)try{let Qs=await Sy(Xn,me);Wt.set(Xn.name,J(Qs))}catch{}be(oe,Wt,ie.length===1?ie[0].name:void 0)}catch(J){console.warn(`[job] ${y.jobId} finding scope marking failed (non-fatal): ${String(J)}`)}}let rt;if(y.role==="council"){let{readCouncilVerdict:J}=await Promise.resolve().then(()=>(Aw(),Cw));rt=J(P.dir)??void 0,console.log(`[job] ${y.jobId} council: ${rt?"answered":"no verdict \u2014 task stops for a human"}`)}let he;if(y.role==="testing"){try{let J=Ps(Pt(P.dir,"meta","test-result.json"),"utf-8");he=JSON.parse(J)}catch{he=void 0}console.log(`[job] ${y.jobId} test verdict: ${he?"written":"none \u2014 proceeding to the PR"}`)}let Fe;if(y.role==="observer"){let{readQueuePlan:J}=await Promise.resolve().then(()=>(jw(),_w));Fe=J(P.dir)??void 0,console.log(`[job] ${y.jobId} queue plan: ${Fe?"produced":"none \u2014 batch keeps the staged order"}`)}let Gr=j.artifactPaths.length>0?j.artifactPaths:P.listFiles(),Kr=Array.from(new Set(Gr)),Vn;if(zs)try{let J=y.role==="index"?["adr/SOURCES.md"]:y.role==="backfill"?["adr"]:[],be=await Ay(zs,J);be.length>0&&(Vn=be,console.log(`[job] ${y.jobId} captured ${be.length} knowledge file(s) for Context Repo`))}catch(J){let be=J instanceof Error?J.message:String(J);console.warn(`[job] ${y.jobId} knowledge capture failed (non-fatal): ${be}`)}let{artifacts:nt,omitted:Hr,dropped:Wr}=Dy(P.dir,Kr);for(let J of Hr)console.warn(`[job] ${y.jobId} artifact ${J.path} (${J.bytes} bytes) exceeded upload budget \u2014 content omitted`);Wr.length>0&&console.warn(`[job] ${y.jobId} artifact listing truncated: ${Wr.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let qr={jobId:y.jobId,status:"succeeded",artifacts:nt,...Vn?{contextWrites:Vn}:{},...q.length>0?{deliveries:q}:{},log:fC(j.log),startedAt:Ne,finishedAt:new Date().toISOString(),usage:j.usage,...j.rateLimit?{rateLimit:j.rateLimit}:{},...V?{build:V}:{},...oe?{review:oe}:{},...Fe!==void 0?{queuePlan:Fe}:{},...rt!==void 0?{council:rt}:{},...he!==void 0?{test:he}:{}};if(O||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 _.submitResult(qr),console.log(`[job] ${y.jobId} done \u2014 uploaded ${qr.artifacts.length} artifact(s):`);for(let J of qr.artifacts){let be=Buffer.from(J.contentBase64,"base64").length;console.log(` \xB7 ${J.path} (${be} bytes)`)}qr.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(L){let j=L instanceof Error?L.message:String(L);if(U.paused)console.log(`[job] ${y.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(O)console.warn(`[job] ${y.jobId} failed after claim lost (${j}) \u2014 skipping result upload`);else{let q=Xg(L),V=L instanceof ur,oe=L instanceof At;console.warn(q?`[job] ${y.jobId} failed: ${j} (Claude auth \u2014 token invalid/expired)`:V?`[job] ${y.jobId} failed: ${j} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:oe?`[job] ${y.jobId} failed: ${j} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${y.jobId} failed: ${j}`),await _.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:j},startedAt:Ne,finishedAt:new Date().toISOString(),...q?{authError:!0}:{},...V?{buildInconclusive:!0}:{},...oe?{reviewInconclusive:!0}:{}})}}finally{P.dispose()}}finally{clearInterval(Ue),T&&clearInterval(T),X(),U.chatInbox?.close(),m.delete(y.jobId),K?.cleanup(),ee?.cleanup()}}function R(_,y){if(!_.credBundle)return{gitCreds:null,contextGitCreds:null};if(!y)return console.warn(`[job] ${_.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let U;try{U=JSON.parse(kn(y,_.credBundle).toString("utf-8"))}catch(le){return console.warn(`[job] ${_.jobId} failed to open credBundle: ${le instanceof Error?le.message:String(le)}`),{gitCreds:null,contextGitCreds:null}}let O=Ul(U);O&&console.log(`[job] ${_.jobId} cred bundle opened \u2014 git creds configured`);let K=ly(U,_.contextRepo.cloneUrl),ee={gitCreds:O,contextGitCreds:K};return U.claudeOauthToken&&(ee.claudeOauthToken=U.claudeOauthToken),ee}function $(_,y){return _.split(`
948
+ `:"",qu=j(v(y.prompt,ie,re),re,y.taskId).replace(/\{\{rolesBlock\}\}/g,Wu).replace(/\{\{skillsBlock\}\}/g,Hu)+Ku+sv,Qn=[...ie.map(O=>O.workspacePath),...re?[re]:[]];if(Qn.length>0&&console.log(`[job] ${y.jobId} --add-dir: ${Qn.join(", ")}`),Cy("agent-request")){let O=Ts(jn(y.metadata??{})),_=Py(y.projectId,y.jobId,"agent-request",[`# Agent request \u2014 job ${y.jobId}`,"",`- project: ${y.projectId}`,`- task: ${y.taskId}`,`- role: ${y.role}`,`- model: ${Zn??"(backend default)"}`,`- add-dirs:${Qn.length>0?"":" (none)"}`,...Qn.map(W=>` - ${W}`),"","## Append-system-prompt (language directive)","","```",O,"```","","## Prompt","",qu,"",...sa?["## Context pack (meta/context-pack.md)","",sa]:["## Context pack","","(not generated for this job)"],""].join(`
949
+ `));_&&console.log(`[debug] ${y.jobId} agent request \u2192 ${_}`)}F&&($=setInterval(()=>{let _=f;if(!_||_.readyState!==_.OPEN)return;let W;try{W=eP(_t(C.dir,"drafts")).filter(V=>V.endsWith(".json")).sort()}catch{return}for(let V of W){if(R.has(V))continue;if(R.size>=wc)break;let oe;try{let me=JSON.parse(Bs(_t(C.dir,"drafts",V),"utf-8")),Fe=typeof me.localRef=="string"?me.localRef:"",Wr=typeof me.title=="string"?me.title:"",qr=typeof me.body=="string"?me.body:"";if(!Fe||!Wr)continue;oe={localRef:Fe,title:Wr,body:qr,...me.isEpic===!0?{isEpic:!0}:{},...Array.isArray(me.links)?{links:me.links}:{}}}catch{continue}R.add(V);let rt={type:"child_draft",jobId:y.jobId,projectId:y.projectId,draftId:F,child:oe};try{_.send(JSON.stringify(rt))}catch{}}},1500));try{let O={workspaceDir:C.dir,role:y.role,prompt:qu,addDirs:Qn,metadata:y.metadata??{},...Zn?{model:Zn}:{},...ft||ii?{env:{...ft??{},...ii?{CLAUDE_CODE_PLUGIN_SEED_DIR:ii}:{}}}:{},...aa?{settings:aa}:{},signal:U.abort.signal,onActivity:ee},_=U.chatInbox?await c.run({...O,interactive:{inbox:U.chatInbox.iterable}}):await Ey(c,O,{jobId:y.jobId,policy:l,onBeforeRetry:async()=>{C.clean();for(let J of ie)try{await Hy(J);let ve=ia[J.name];y.role==="resolve-conflict"&&ve&&await tu(J,ve,fe)}catch(ve){let qt=ve instanceof Error?ve.message:String(ve);console.warn(`[job] ${y.jobId} worktree reset failed (${J.name}): ${qt}`)}try{await Gu()}catch(J){let ve=J instanceof Error?J.message:String(J);console.warn(`[job] ${y.jobId} delivery re-checkout failed: ${ve}`)}},aborted:()=>N||U.paused}),W=[];if(nP.has(y.role)&&ie.length>0){let J=y.metadata??{},ve=typeof J.commitMessage=="string"?J.commitMessage:`${y.taskId}: changes`,qt=y.contextRepo?.cloneUrl,to=X?.env;if(!qt||!to)throw new Error("delivery requested but "+(qt?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let ca=y.taskId.includes(":")?y.taskId.slice(y.taskId.indexOf(":")+1):y.taskId;for(let St of ie){let Xr=await Wy(St,ve);if(!Xr){console.log(`[job] ${y.jobId} ${St.name}: no changes \u2014 no delivery`);continue}let la=`codepipe/deliveries/${ca}/${y.jobId}/${St.name}`;await qy(St,Xr,la,qt,to);let av=await Vy(St,Xr);W.push({name:St.name,deliveryRef:la,deliverySha:Xr,baseSha:St.baseSha,changedFiles:av}),console.log(`[job] ${y.jobId} ${St.name}: delivered ${Xr.slice(0,10)} \u2192 ${la}`);let Yu=await Yy(St,Xr);if(Yu.trim().length>0){let cv=_t("display",`${St.name}.diff`),Vu=_t(C.dir,cv);cb(rP(Vu),{recursive:!0}),lb(Vu,Yu)}}}if(y.role==="resolve-conflict"&&W.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 V;y.role==="build"&&(V=cw(C.dir),console.log(`[job] ${y.jobId} build verdict: ok=${V.ok}`+(V.failedStep?` failedStep=${V.failedStep}`:"")));let oe;if(y.role==="code-review"){oe=iu(C.dir),console.log(`[job] ${y.jobId} review verdict: approved=${oe.approved}`);try{let{parseChangedRanges:J,markFindingScope:ve}=await Promise.resolve().then(()=>(su(),uw)),qt=new Map;for(let to of ie)try{let ca=await Zy(to,fe);qt.set(to.name,J(ca))}catch{}ve(oe,qt,ie.length===1?ie[0].name:void 0)}catch(J){console.warn(`[job] ${y.jobId} finding scope marking failed (non-fatal): ${String(J)}`)}}let rt;if(y.role==="council"){let{readCouncilVerdict:J}=await Promise.resolve().then(()=>(ob(),nb));rt=J(C.dir)??void 0,console.log(`[job] ${y.jobId} council: ${rt?"answered":"no verdict \u2014 task stops for a human"}`)}let me;if(y.role==="testing"){try{let J=Bs(_t(C.dir,"meta","test-result.json"),"utf-8");me=JSON.parse(J)}catch{me=void 0}console.log(`[job] ${y.jobId} test verdict: ${me?"written":"none \u2014 proceeding to the PR"}`)}let Fe;if(y.role==="observer"){let{readQueuePlan:J}=await Promise.resolve().then(()=>(ab(),sb));Fe=J(C.dir)??void 0,console.log(`[job] ${y.jobId} queue plan: ${Fe?"produced":"none \u2014 batch keeps the staged order"}`)}let Wr=_.artifactPaths.length>0?_.artifactPaths:C.listFiles(),qr=Array.from(new Set(Wr)),eo;if(na)try{let J=y.role==="index"?["adr/SOURCES.md"]:y.role==="backfill"?["adr"]:[],ve=await ow(na,J);ve.length>0&&(eo=ve,console.log(`[job] ${y.jobId} captured ${ve.length} knowledge file(s) for Context Repo`))}catch(J){let ve=J instanceof Error?J.message:String(J);console.warn(`[job] ${y.jobId} knowledge capture failed (non-fatal): ${ve}`)}let{artifacts:nt,omitted:Yr,dropped:Vr}=pw(C.dir,qr);for(let J of Yr)console.warn(`[job] ${y.jobId} artifact ${J.path} (${J.bytes} bytes) exceeded upload budget \u2014 content omitted`);Vr.length>0&&console.warn(`[job] ${y.jobId} artifact listing truncated: ${Vr.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let zr={jobId:y.jobId,status:"succeeded",artifacts:nt,...eo?{contextWrites:eo}:{},...W.length>0?{deliveries:W}:{},log:oP(_.log),startedAt:Re,finishedAt:new Date().toISOString(),usage:_.usage,..._.rateLimit?{rateLimit:_.rateLimit}:{},...V?{build:V}:{},...oe?{review:oe}:{},...Fe!==void 0?{queuePlan:Fe}:{},...rt!==void 0?{council:rt}:{},...me!==void 0?{test:me}:{}};if(N||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(zr),console.log(`[job] ${y.jobId} done \u2014 uploaded ${zr.artifacts.length} artifact(s):`);for(let J of zr.artifacts){let ve=Buffer.from(J.contentBase64,"base64").length;console.log(` \xB7 ${J.path} (${ve} bytes)`)}zr.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 _=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(N)console.warn(`[job] ${y.jobId} failed after claim lost (${_}) \u2014 skipping result upload`);else{let W=Sy(O),V=O instanceof dr,oe=O instanceof At;console.warn(W?`[job] ${y.jobId} failed: ${_} (Claude auth \u2014 token invalid/expired)`:V?`[job] ${y.jobId} failed: ${_} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:oe?`[job] ${y.jobId} failed: ${_} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${y.jobId} failed: ${_}`),await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:_},startedAt:Re,finishedAt:new Date().toISOString(),...W?{authError:!0}:{},...V?{buildInconclusive:!0}:{},...oe?{reviewInconclusive:!0}:{}})}}finally{C.dispose()}}finally{clearInterval(pt),$&&clearInterval($),L(),U.chatInbox?.close(),m.delete(y.jobId),H?.cleanup(),X?.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(En(y,A.credBundle).toString("utf-8"))}catch(ue){return console.warn(`[job] ${A.jobId} failed to open credBundle: ${ue instanceof Error?ue.message:String(ue)}`),{gitCreds:null,contextGitCreds:null}}let N=Ql(U);N&&console.log(`[job] ${A.jobId} cred bundle opened \u2014 git creds configured`);let H=My(U,A.contextRepo.cloneUrl),X={gitCreds:N,contextGitCreds:H};return U.claudeOauthToken&&(X.claudeOauthToken=U.claudeOauthToken),X}function E(A,y){return A.split(`
929
950
  `).map(U=>y+U).join(`
930
- `)}function b(_,y,U){let O=y[0]?.workspacePath??"";return _.replace(/\{\{codeDir\}\}/g,O).replace(/\{\{codeRoot\}\}/g,O?O.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,U??"")}function I(_,y){let U=y.includes("::")?"":y.split(":",2)[1]??"";if(!_||!U)return"";for(let O of["PLAN.md","SOLUTION.md"])try{return Ps(Pt(_,"tasks",U,O),"utf-8")}catch{}return""}function N(_,y,U){let O=_,K=U.includes("::")?"":U.split(":",2)[1]??"",ee=le=>{if(!y||!K)return"";try{return Ps(Pt(y,"tasks",K,le),"utf-8").trim()}catch{return""}};if(O.includes("{{planMd}}")||O.includes("{{solutionMd}}")){let le=ee("PLAN.md")||ee("SOLUTION.md")||"(PLAN.md missing \u2014 proceed from the task description)";O=O.replace(/\{\{planMd\}\}/g,()=>le),O=O.replace(/\{\{solutionMd\}\}/g,()=>le)}if(O.includes("{{taskDescription}}")){let le=ee("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";O=O.replace(/\{\{taskDescription\}\}/g,()=>le)}return O=Wy(O,y),O}let H=_=>{if(p)return;p=!0,console.log(`
931
- [${_}] shutting down`),d.abort();let y=[...m.keys()];for(let K of m.values())K.abort.abort();let U=new AbortController,O=setTimeout(()=>U.abort(),3e3);(async()=>(await Promise.all(y.map(async K=>{try{await u.releaseJob(K,`sandbox ${_}`,U.signal),console.log(`[${_}] released job ${K}`)}catch(ee){let le=ee instanceof Error?ee.message:String(ee);console.warn(`[${_}] release failed: ${le} (sweeper will reclaim)`)}})),clearTimeout(O),w.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>H("SIGINT")),process.on("SIGTERM",()=>H("SIGTERM"));let z=[v("implementation")];e.planningLane!==!1?z.push(v("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(z)}var _s,pC,Lw=x(()=>{"use strict";F();dt();cc();qg();ks();Zg();ny();Ke();ys();uy();Nl();Py();jy();Oy();ql();Uy();Hy();Yy();_s=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),pC=new Set(["implement","resolve-conflict"])});var Ln=x(()=>{"use strict";_g();Lw();ys()});import{cancel as hC,isCancel as Dw,log as Qe,password as gC,text as yC}from"@clack/prompts";function wC(t){return Dw(t)&&(hC("aborted"),process.exit(1)),typeof t=="string"?t:""}function Uw(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function kC(t){let e=bc({redirectUri:kc,challenge:t.challenge,state:t.state});Qe.message(`Open this URL, approve the access, and paste the code shown:
932
- ${e}`);let r=await yC({message:"Authorization code \u2014 blank to skip"});if(Dw(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=Xp(r,t.state);return await vc({code:n,verifier:t.verifier,state:t.state,redirectUri:kc})}catch(n){return Qe.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function bC(t){if(sc()?.claude?.oauthToken&&!t.farm)return Qe.message("Claude: this machine already has a shared OAuth token \u2014 the project will use it (set a project-specific one later with `codepipe login`)."),"";if(process.env.CODEPIPE_CLAUDE_AUTOLOGIN!=="1"||!process.stdout.isTTY)return null;Qe.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=bi(),n;try{n=await Jp({...r,openUrl:Ar,log:i=>Qe.message(i)})}catch(i){Qe.warn(`Browser sign-in didn't complete (${i instanceof Error?i.message:String(i)}) \u2014 trying the code-paste fallback.`);let s=await kC(r);if(s===null)return null;n=s}let o=await Bt(n.oauthToken);return o==="invalid"?(Qe.warn("Claude rejected the obtained token (401) \u2014 falling back to manual entry."),null):(Qe.success(`Claude: logged in \u2014 ${Uw(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function Bw(t){Qe.message(`Claude \u2014 the pipeline's agents run on your Claude subscription.
951
+ `)}function v(A,y,U){let N=y[0]?.workspacePath??"";return A.replace(/\{\{codeDir\}\}/g,N).replace(/\{\{codeRoot\}\}/g,N?N.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,U??"")}function I(A,y){let U=y.includes("::")?"":y.split(":",2)[1]??"";if(!A||!U)return"";for(let N of["PLAN.md","SOLUTION.md"])try{return Bs(_t(A,"tasks",U,N),"utf-8")}catch{}return""}function j(A,y,U){let N=A,H=U.includes("::")?"":U.split(":",2)[1]??"",X=ue=>{if(!y||!H)return"";try{return Bs(_t(y,"tasks",H,ue),"utf-8").trim()}catch{return""}};if(N.includes("{{planMd}}")||N.includes("{{solutionMd}}")){let ue=X("PLAN.md")||X("SOLUTION.md")||"(PLAN.md missing \u2014 proceed from the task description)";N=N.replace(/\{\{planMd\}\}/g,()=>ue),N=N.replace(/\{\{solutionMd\}\}/g,()=>ue)}if(N.includes("{{taskDescription}}")){let ue=X("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";N=N.replace(/\{\{taskDescription\}\}/g,()=>ue)}return N=bw(N,y),N}let G=A=>{if(p)return;p=!0,console.log(`
952
+ [${A}] shutting down`),d.abort();let y=[...m.keys()];for(let H of m.values())H.abort.abort();let U=new AbortController,N=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(X){let ue=X instanceof Error?X.message:String(X);console.warn(`[${A}] release failed: ${ue} (sweeper will reclaim)`)}})),clearTimeout(N),k.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>G("SIGINT")),process.on("SIGTERM",()=>G("SIGTERM"));let z=[x("implementation")];e.planningLane!==!1?z.push(x("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(z)}var Fs,nP,ub=S(()=>{"use strict";D();ut();xc();ky();Is();Ry();Ay();Ke();Rs();Dy();Vl();iw();aw();lw();su();fw();ww();vw();Fs=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),nP=new Set(["implement","resolve-conflict"])});var Bn=S(()=>{"use strict";sy();ub();Rs()});import{cancel as sP,isCancel as pb,log as et,password as aP,text as cP}from"@clack/prompts";function lP(t){return pb(t)&&(sP("aborted"),process.exit(1)),typeof t=="string"?t:""}function fb(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function uP(t){let e=Oc({redirectUri:Nc,challenge:t.challenge,state:t.state});et.message(`Open this URL, approve the access, and paste the code shown:
953
+ ${e}`);let r=await cP({message:"Authorization code \u2014 blank to skip"});if(pb(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=Sf(r,t.state);return await Lc({code:n,verifier:t.verifier,state:t.state,redirectUri:Nc})}catch(n){return et.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function dP(t){if(vc()?.claude?.oauthToken&&!t.farm)return et.message("Claude: this machine already has a shared OAuth token \u2014 the project will use it (set a project-specific one later with `codepipe login`)."),"";if(process.env.CODEPIPE_CLAUDE_AUTOLOGIN!=="1"||!process.stdout.isTTY)return null;et.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=Ti(),n;try{n=await Ef({...r,openUrl:Ar,log:i=>et.message(i)})}catch(i){et.warn(`Browser sign-in didn't complete (${i instanceof Error?i.message:String(i)}) \u2014 trying the code-paste fallback.`);let s=await uP(r);if(s===null)return null;n=s}let o=await Ft(n.oauthToken);return o==="invalid"?(et.warn("Claude rejected the obtained token (401) \u2014 falling back to manual entry."),null):(et.success(`Claude: logged in \u2014 ${fb(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function mb(t){et.message(`Claude \u2014 the pipeline's agents run on your Claude subscription.
933
954
  In another terminal:
934
955
  1. install Claude Code \u2014 https://claude.com/claude-code
935
956
  2. run \`claude setup-token\`
936
957
  3. paste the token it prints (starts with sk-ant-) below`+(t.farm?`
937
- Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=wC(await gC({message:"Claude OAuth token \u2014 blank to skip"})).trim();if(!e)return Qe.warn(t.farm?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"";e.startsWith("sk-ant-")||Qe.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`.");let r=await Bt(e);return r==="invalid"?(Qe.warn("Claude refused this token. Run `claude setup-token` again and paste the new one."),Bw(t)):(Qe.success(`Claude: ${Uw(e)} \u2014 ${r==="valid"?"verified":"check inconclusive, saved"}.`),e)}var Fw,Gw=x(()=>{"use strict";vi();dn();pe();xc();Fw={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:bC,promptManual:Bw,validate:Bt}});function Kw(t){return Fw}async function Hw(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var Ww=x(()=>{"use strict";Gw()});async function Mn(t,e,r){return e.host==="github"?$C(t,e,r):e.host==="gitlab"?IC(t,e,r):AC(t,e,r)}async function qw(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 et(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Yw(e.githubToken,t):o}:{found:"unknown",detail:"no GitHub token \u2014 existence not checked"};if(t.host==="gitlab"){if(!e.gitlabToken)return{found:"unknown",detail:"no GitLab token \u2014 existence not checked"};let s=encodeURIComponent(`${t.owner}/${t.name}`);return(await Ye(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await zw(e.gitlabToken,t):o}}return e.bitbucket?(await _t(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Vw(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 Yw(t,e){let r=!1;try{r=(await et(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 zw(t,e){let r=!1;try{r=(await Ye(t,"GET",`/namespaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitLab project ${e.owner}/${e.name} does not exist (the namespace "${e.owner}" is visible to the token) \u2014 check the project name, or the token has no access to this specific project`:`GitLab namespace "${e.owner}" is not visible to this token \u2014 check the group/username spelling; a private group answers 404 until the token's owner is a member`}async function Vw(t,e){let r=!1;try{r=(await _t(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 et(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(vC+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 $C(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 xC(n,e,r),i=await SC(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=yn(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await EC(n,o.owner,o.name,a.path,i)||await TC(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 xC(t,e,r){let n=await et(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 Yw(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await tu(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 et(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 tu(t,e){let{status:r,data:n}=await et(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function SC(t,e,r){let{data:n}=await et(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function EC(t,e,r,n,o){let{status:i,data:s}=await et(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function TC(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 et(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Ye(t,e,r,n){let o={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...n!==void 0?{"Content-Type":"application/json"}:{}}};n!==void 0&&(o.body=JSON.stringify(n));let i=await fetch(RC+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 IC(t,e,r){let n=r.gitlabToken;if(!n)throw new Error("GitLab PAT required to provision a gitlab-hosted Context Repo \u2014 set GITLAB_TOKEN or provide it during `codepipe init`");let o=encodeURIComponent(`${e.owner}/${e.name}`),i,s=await Ye(n,"GET",`/projects/${o}`);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await zw(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await Ye(n,"GET","/user"),d={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(p.data?.username!==e.owner){let f=await Ye(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(f.status===404||!f.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);d.namespace_id=f.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let m=await Ye(n,"POST","/projects",d);if(!m.data)throw new Error("GitLab create project: empty response");i=m.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=yn(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let m=(await Ye(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let f of m)l.add(f.path);if(m.length<100)break}let u=c.filter(p=>!l.has(p.path)).map(p=>({action:"create",file_path:p.path,content:p.content}));return u.length>0?await Ye(n,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:u}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}async function _t(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(CC+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 AC(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 _t(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 Vw(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 _t(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=yn(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await _t(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 _t(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 vC,RC,CC,Ho=x(()=>{"use strict";Pr();vC="https://api.github.com";RC="https://gitlab.com/api/v4";CC="https://api.bitbucket.org/2.0"});function ze(t){let e=t.trim();if(!e)return null;let r,n;if(e.includes("://")){let a;try{a=new URL(e)}catch{return null}r=a.hostname.toLowerCase(),n=a.pathname}else{let a=/^(?:[\w.-]+@)?([\w.-]+):(.+)$/.exec(e);if(!a)return null;r=a[1].toLowerCase(),n=a[2]}let o=PC[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 PC,js=x(()=>{"use strict";PC={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as _C}from"node:crypto";import{existsSync as Xw,mkdirSync as jC,readFileSync as Jw,readdirSync as NC,rmSync as Ns,writeFileSync as OC}from"node:fs";import{homedir as LC}from"node:os";import{dirname as MC,join as ru}from"node:path";function Zw(){return ru(LC(),".codepipe","init-drafts")}function nu(t){let e=_C("sha256").update(t).digest("hex").slice(0,16);return ru(Zw(),`${e}.json`)}function Qw(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=DC)}function ek(t){let e=nu(t);if(!Xw(e))return null;try{let r=JSON.parse(Jw(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Qw(r.savedAt)?(Ns(e,{force:!0}),null):r}catch{return null}}function ou(t){Ns(nu(t),{force:!0})}function tk(){let t=Zw();if(Xw(t))for(let e of NC(t)){let r=ru(t,e);try{let n=JSON.parse(Jw(r,"utf-8"));Qw(n.savedAt)&&Ns(r,{force:!0})}catch{Ns(r,{force:!0})}}}var DC,Dn,rk=x(()=>{"use strict";DC=24*60*60*1e3;Dn=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(){ou(this.cwd)}persist(){let e=nu(this.cwd);jC(MC(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};OC(e,JSON.stringify(r,null,2)+`
938
- `,{mode:384})}}});function nk(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 ok(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 ik=x(()=>{"use strict"});import{existsSync as UC}from"node:fs";import{join as BC}from"node:path";import{simpleGit as FC}from"simple-git";function WC(t){let e=t.split("/");return e[e.length-1]??t}function sk(t){if(t.filter(r=>!KC.test(WC(r))).length>GC)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(HC.has(n))return!0}return!1}async function qC(t){try{let r=(await FC(t).raw(["ls-files"])).split(`
939
- `).map(n=>n.trim()).filter(Boolean);return sk(r)}catch{return!1}}async function YC(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)?sk(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function ak(t,e){for(let r of t)try{let n=e.localRoot!=null?BC(e.localRoot,r.mountAs??r.name):null;if(n&&UC(n)?await qC(n):await YC(r,e.tokens))return!0}catch{}return!1}var GC,KC,HC,ck=x(()=>{"use strict";GC=3,KC=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,HC=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as lk}from"node:fs";import{join as uk}from"node:path";import{simpleGit as dk}from"simple-git";async function qo(t,e,r={}){let n=r.log??zC,o=[];for(let i of e){let s=uk(t,i.mountAs),a=Wd(i);if(!lk(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 dk().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let p=Wo(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(!lk(uk(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=dk(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!VC(l,a)){n.warn(`${i.mountAs}/ origin (${Wo(l)||"none"}) != expected (${Wo(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:Wo(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=Wo(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 VC(t,e){return pk(t)===pk(e)}function pk(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function Wo(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function fk(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 qo(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 zC,Os=x(()=>{"use strict";wt();zC={info:t=>console.log(t),warn:t=>console.warn(t)}});import{simpleGit as XC}from"simple-git";async function mk(t,e,r){return t.host==="github"?JC(t,e,r):t.host==="gitlab"?ZC(t,e,r):QC(t,e,r)}function iu(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 JC(t,e,r){let n=e.githubToken;if(!n)throw new Error("GitHub token required to create a github-hosted mirror");let o=await et(n,"GET",`/repos/${t.owner}/${encodeURIComponent(t.repoName)}`);if(o.status===200&&o.data){if(o.data.private!==!0)throw iu(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 et(n,"GET","/user")).data?.login??"",s=i.toLowerCase()===t.owner.toLowerCase(),a=!s&&await tu(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 et(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 hk(t,e,r){try{return t==="github"?(await et(e,"GET","/user")).data?.login??null:t==="gitlab"?(await Ye(e,"GET","/user")).data?.username??null:r?(await _t({email:r,apiToken:e},"GET","/workspaces?role=contributor&pagelen=1")).data?.values?.[0]?.slug??null:null}catch{return null}}async function ZC(t,e,r){let n=e.gitlabToken;if(!n)throw new Error("GitLab PAT required to create a gitlab-hosted mirror");let o=encodeURIComponent(`${t.owner}/${t.repoName}`),i=await Ye(n,"GET",`/projects/${o}`);if(i.status===200&&i.data){if(i.data.visibility!=="private")throw iu(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:i.data.ssh_url_to_repo,created:!1}}let s={name:t.repoName,path:t.repoName,visibility:"private",initialize_with_readme:!1,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"};if((await Ye(n,"GET","/user")).data?.username!==t.owner){let l=await Ye(n,"GET",`/namespaces/${encodeURIComponent(t.owner)}`);if(l.status===404||!l.data)throw new Error(`GitLab namespace "${t.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);s.namespace_id=l.data.id}r.info(`creating mirror ${t.owner}/${t.repoName} (gitlab)`);let c=await Ye(n,"POST","/projects",s);if(!c.data)throw new Error(`GitLab: could not create ${t.owner}/${t.repoName}`);return{spec:t,sshUrl:c.data.ssh_url_to_repo,created:!0}}async function QC(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 _t(n,"GET",o);if(s.status===200&&s.data){if(s.data.is_private!==!0)throw iu(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 _t(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 gk(t,e,r){let n=XC(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(`
940
- `).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 eA(t,e){let r=e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-");return`${t}-${r}-mirror`.replace(/-{2,}/g,"-").replace(/^[-.]+|[-.]+$/g,"")}function tA(t,e,r){return e.mirror?{host:e.mirror.host,owner:e.mirror.owner,repoName:e.mirror.repoName}:{host:r.host,owner:r.owner,repoName:eA(t,e.repoName)}}function yk(t,e,r){let n=new Map,o=[];for(let i of e){let s=tA(t,i,r),a=`${s.host}:${s.owner.toLowerCase()}/${s.repoName.toLowerCase()}`,c=n.get(a);if(c)throw new Error(`repositories "${c}" and "${i.name}" both map to the mirror ${s.owner}/${s.repoName} \u2014 mirroring them into one repository would merge their histories. Give one an explicit mirror name (mirror.repo in project.yaml) and re-run`);n.set(a,i.name),o.push({repo:i,spec:s})}return o}var wk=x(()=>{"use strict";Ho()});var xk={};Ge(xk,{ensureEmbeddedWorker:()=>Ms,spawnWorkerProcess:()=>Ds,upCommand:()=>Us,workerChildEnv:()=>$k,workerStartArgs:()=>vk});import{spawn as bk}from"node:child_process";import{existsSync as kk}from"node:fs";import{homedir as rA,hostname as nA}from"node:os";import{join as Ls}from"node:path";async function oA(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 Sh(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.
941
- 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`),sp(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function iA(t,e,r){let n=Le(e)!==null;if(!await oA(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 os(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof W&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof W&&i.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):i instanceof W?i:new Error(`cannot reach the HUB at ${t.hubUrl} (${i instanceof Error?i.message:String(i)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await Lr({hub:t.hubUrl,token:o,name:r.name??`${nA()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function sA(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=We(r.sealPublicKey);if(!Y(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=pi(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 Ms(t,e,r){await iA(t,e,r),sA(t.projectId,e)}function vk(t){return[...t?["--profile",t]:[],"worker","start"]}function $k(t){let e={...t};for(let r of ac)delete e[r];return e}function Ds(t){let e=bk(process.execPath,[t.entry,...vk(t.profile)],{stdio:["ignore","pipe","pipe"],env:$k(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
942
- `))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function aA(t,e){let r=process.cwd(),n=Ls(r,it);if(nn(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(kk(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 su(r);if(!Hd(r,i?.parsed??null,o.repos)){console.log(`[up] this folder is neither empty nor a repo of ${t.projectId} \u2014 the context stays under ~/.codepipe/profiles`);return}let s=Y(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await gs({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=Ls(rA(),".codepipe",e?Ls("profiles",e,"context-config"):"context-config");if(Si(c.contextDir,l,a),!kk(Ls(c.contextDir,"project.yaml"))){mn(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};go(c.contextDir,It(u,!0,s?.youtrack?.url)),console.log("[up] local project config seeded with defaults \u2014 review .codepipe/project.yaml")}console.log(`[up] project context materialized \u2192 ${n}`)}async function Us(t){let{cfg:e,profile:r}=sn(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 aA(e,r),await Ms(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(`
943
- `))w.length>0&&k.write(`${f} ${w}
944
- `)};m.stdout?.on("data",g(process.stdout)),m.stderr?.on("data",g(process.stderr))},i=(m,f)=>{let g=bk(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=Ds({entry:n,profile:r,onLine:m=>process.stdout.write(`[worker] ${m}
958
+ Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=lP(await aP({message:"Claude OAuth token \u2014 blank to skip"})).trim();if(!e)return et.warn(t.farm?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"";e.startsWith("sk-ant-")||et.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`.");let r=await Ft(e);return r==="invalid"?(et.warn("Claude refused this token. Run `claude setup-token` again and paste the new one."),mb(t)):(et.success(`Claude: ${fb(e)} \u2014 ${r==="valid"?"verified":"check inconclusive, saved"}.`),e)}var hb,gb=S(()=>{"use strict";Ii();hn();de();Dc();hb={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:dP,promptManual:mb,validate:Ft}});function yb(t){return hb}async function wb(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var bb=S(()=>{"use strict";gb()});async function Fn(t,e,r){return e.host==="github"?fP(t,e,r):e.host==="gitlab"?bP(t,e,r):vP(t,e,r)}async function kb(t,e,r={}){let n=r.explain??!0,o=`${t.owner}/${t.name} not found on ${t.host}`;try{if(t.host==="github")return e.githubToken?(await tt(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await vb(e.githubToken,t):o}:{found:"unknown",detail:"no GitHub token \u2014 existence not checked"};if(t.host==="gitlab"){if(!e.gitlabToken)return{found:"unknown",detail:"no GitLab token \u2014 existence not checked"};let s=encodeURIComponent(`${t.owner}/${t.name}`);return(await Ye(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await $b(e.gitlabToken,t):o}}return e.bitbucket?(await jt(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await xb(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 vb(t,e){let r=!1;try{r=(await tt(t,"GET",`/users/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitHub repo ${e.owner}/${e.name} does not exist, or the token cannot see it \u2014 check the name; a fine-grained PAT must be scoped to this repo (and approved in the org)`:`GitHub owner "${e.owner}" not found \u2014 check the org/user spelling`}async function $b(t,e){let r=!1;try{r=(await Ye(t,"GET",`/namespaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitLab project ${e.owner}/${e.name} does not exist (the namespace "${e.owner}" is visible to the token) \u2014 check the project name, or the token has no access to this specific project`:`GitLab namespace "${e.owner}" is not visible to this token \u2014 check the group/username spelling; a private group answers 404 until the token's owner is a member`}async function xb(t,e){let r=!1;try{r=(await jt(t,"GET",`/workspaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`Bitbucket repo ${e.owner}/${e.name} does not exist in workspace "${e.owner}" (which the credential can see) \u2014 check the repo name, or the API token lacks access to it`:`Bitbucket workspace "${e.owner}" is not visible to this credential \u2014 check the workspace name and the token's read:repository:bitbucket scope`}async function tt(t,e,r,n){let o={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};n!==void 0&&(o.body=JSON.stringify(n),o.headers["Content-Type"]="application/json");let i=await fetch(pP+r,o),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?a.message:s;throw new Error(`GitHub ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function fP(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 mP(n,e,r),i=await hP(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=vn(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await gP(n,o.owner,o.name,a.path,i)||await yP(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 mP(t,e,r){let n=await tt(t,"GET",`/repos/${e.owner}/${encodeURIComponent(e.name)}`);if(n.status===200&&n.data)return r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),{owner:n.data.owner.login,name:n.data.name,sshUrl:n.data.ssh_url};if(r.mode==="attach")throw new Error(`attach: ${await vb(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await hu(t,e.owner),i=o?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${o?"org":"user"})`);let s=await tt(t,"POST",i,{name:e.name,private:!0,auto_init:!0,description:`CodePipe Context Repo for project ${e.name}`});if(!s.data)throw new Error("GitHub createRepo: empty response");return{owner:s.data.owner.login,name:s.data.name,sshUrl:s.data.ssh_url}}async function hu(t,e){let{status:r,data:n}=await tt(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function hP(t,e,r){let{data:n}=await tt(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function gP(t,e,r,n,o){let{status:i,data:s}=await tt(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function yP(t,e,r,n,o,i,s,a){let c={message:i,content:Buffer.from(o,"utf-8").toString("base64"),branch:s};a&&(c.sha=a),await tt(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Ye(t,e,r,n){let o={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...n!==void 0?{"Content-Type":"application/json"}:{}}};n!==void 0&&(o.body=JSON.stringify(n));let i=await fetch(wP+r,o),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?JSON.stringify(a.message):s;throw new Error(`GitLab ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function bP(t,e,r){let n=r.gitlabToken;if(!n)throw new Error("GitLab PAT required to provision a gitlab-hosted Context Repo \u2014 set GITLAB_TOKEN or provide it during `codepipe init`");let o=encodeURIComponent(`${e.owner}/${e.name}`),i,s=await Ye(n,"GET",`/projects/${o}`);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await $b(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await Ye(n,"GET","/user"),d={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(p.data?.username!==e.owner){let f=await Ye(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(f.status===404||!f.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);d.namespace_id=f.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let m=await Ye(n,"POST","/projects",d);if(!m.data)throw new Error("GitLab create project: empty response");i=m.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=vn(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let m=(await Ye(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let f of m)l.add(f.path);if(m.length<100)break}let u=c.filter(p=>!l.has(p.path)).map(p=>({action:"create",file_path:p.path,content:p.content}));return u.length>0?await Ye(n,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:u}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}async function jt(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(kP+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 vP(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 jt(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 xb(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 jt(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=vn(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await jt(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 jt(n,"POST",`${o}/src`,{form:p})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let u=i.links?.clone?.find(p=>p.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:u??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var pP,wP,kP,Vo=S(()=>{"use strict";_r();pP="https://api.github.com";wP="https://gitlab.com/api/v4";kP="https://api.bitbucket.org/2.0"});function Ve(t){let e=t.trim();if(!e)return null;let r,n;if(e.includes("://")){let a;try{a=new URL(e)}catch{return null}r=a.hostname.toLowerCase(),n=a.pathname}else{let a=/^(?:[\w.-]+@)?([\w.-]+):(.+)$/.exec(e);if(!a)return null;r=a[1].toLowerCase(),n=a[2]}let o=$P[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 $P,Gs=S(()=>{"use strict";$P={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as xP}from"node:crypto";import{existsSync as Sb,mkdirSync as SP,readFileSync as Eb,readdirSync as EP,rmSync as Ks,writeFileSync as RP}from"node:fs";import{homedir as TP}from"node:os";import{dirname as IP,join as gu}from"node:path";function Rb(){return gu(TP(),".codepipe","init-drafts")}function yu(t){let e=xP("sha256").update(t).digest("hex").slice(0,16);return gu(Rb(),`${e}.json`)}function Tb(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=CP)}function Ib(t){let e=yu(t);if(!Sb(e))return null;try{let r=JSON.parse(Eb(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Tb(r.savedAt)?(Ks(e,{force:!0}),null):r}catch{return null}}function wu(t){Ks(yu(t),{force:!0})}function Cb(){let t=Rb();if(Sb(t))for(let e of EP(t)){let r=gu(t,e);try{let n=JSON.parse(Eb(r,"utf-8"));Tb(n.savedAt)&&Ks(r,{force:!0})}catch{Ks(r,{force:!0})}}}var CP,Gn,Pb=S(()=>{"use strict";CP=24*60*60*1e3;Gn=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(){wu(this.cwd)}persist(){let e=yu(this.cwd);SP(IP(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};RP(e,JSON.stringify(r,null,2)+`
959
+ `,{mode:384})}}});function Ab(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 _b(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 jb=S(()=>{"use strict"});import{existsSync as PP}from"node:fs";import{join as AP}from"node:path";import{simpleGit as _P}from"simple-git";function LP(t){let e=t.split("/");return e[e.length-1]??t}function Nb(t){if(t.filter(r=>!NP.test(LP(r))).length>jP)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(OP.has(n))return!0}return!1}async function MP(t){try{let r=(await _P(t).raw(["ls-files"])).split(`
960
+ `).map(n=>n.trim()).filter(Boolean);return Nb(r)}catch{return!1}}async function DP(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)?Nb(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function Ob(t,e){for(let r of t)try{let n=e.localRoot!=null?AP(e.localRoot,r.mountAs??r.name):null;if(n&&PP(n)?await MP(n):await DP(r,e.tokens))return!0}catch{}return!1}var jP,NP,OP,Lb=S(()=>{"use strict";jP=3,NP=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,OP=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as Mb}from"node:fs";import{join as Db}from"node:path";import{simpleGit as Ub}from"simple-git";async function Xo(t,e,r={}){let n=r.log??UP,o=[];for(let i of e){let s=Db(t,i.mountAs),a=wp(i);if(!Mb(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 Ub().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let p=zo(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(!Mb(Db(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=Ub(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!BP(l,a)){n.warn(`${i.mountAs}/ origin (${zo(l)||"none"}) != expected (${zo(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:zo(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=zo(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 BP(t,e){return Bb(t)===Bb(e)}function Bb(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function zo(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function Fb(t={}){let e=Pe();e||(console.error("no .codepipe/ workspace found in this directory or any parent. run `codepipe init` first."),process.exit(1)),console.log(`codepipe sync \u2014 project ${e.spec.projectId} (${e.spec.repos.length} repos)`);let r=await Xo(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 UP,Hs=S(()=>{"use strict";wt();UP={info:t=>console.log(t),warn:t=>console.warn(t)}});import{existsSync as bu,readFileSync as ku,writeFileSync as Gb}from"node:fs";import{join as vu}from"node:path";import{parseDocument as $u}from"yaml";function Kb(t){let e={};return t.branches.integration&&(e.integration=t.branches.integration),t.branches.stable!==void 0&&(e.stable=t.branches.stable),t.branches.release_pattern!==void 0&&(e.release_pattern=t.branches.release_pattern),{flow:t.flow,branches:e}}function Hb(t){let{errors:e}=nn(t);if(e.length>0)throw new Error(`invalid git config: ${e.join("; ")}`)}async function Wb(t,e){let r=Kb(e);Hb(r);let n=vu(t,"project.yaml");if(!bu(n))throw new Error(`project.yaml not found in context repo (${t})`);let o=$u(ku(n,"utf-8"));o.set("git",r),Gb(n,o.toString())}async function qb(t,e,r){let n=Kb(r);Hb(n);let o=vu(t,"project.yaml");if(!bu(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=$u(ku(o,"utf-8"));Ki(i,e).set("git",n),Gb(o,i.toString())}function Yb(t){let e=vu(t,"project.yaml");if(!bu(e))return null;try{let r=$u(ku(e,"utf-8")).toJS();return FP(r?.git)}catch{return null}}function FP(t){if(!t||typeof t!="object")return null;let e=t,r=e.flow;if(r!=="simple"&&r!=="gitflow"&&r!=="release")return null;let n=e.branches;if(!n||typeof n!="object")return null;let o=n,i=o.integration;if(typeof i!="string"||!i)return null;let s={flow:r,branches:{integration:i}};return typeof o.stable=="string"&&(s.branches.stable=o.stable),typeof o.release_pattern=="string"&&(s.branches.release_pattern=o.release_pattern),s}var Vb=S(()=>{"use strict";D();Hi()});import{confirm as GP,isCancel as KP}from"@clack/prompts";async function Ws(t){let e=po(t.facts),r=t.confirm??HP,n=t.log??(()=>{}),o=t.readProject??Yb,i=t.writeProject??Wb,s=t.writeOverride??qb;if(!t.contextDir)return e.flow!=="simple"&&n(`git-flow: detected ${Kn(e)} (no context repo to persist)`),{outcome:"no-context",detected:e};let a=t.contextDir,c=o(a);return c===null?e.flow==="simple"?(n("git-flow: simple (single branch)"),{outcome:"silent-simple",detected:e}):await r(`Detected git-flow: ${Kn(e)}. Use it?`)?(await i(a,e),n(`git-flow: ${Kn(e)} (project default)`),{outcome:"wrote-project",detected:e}):(n("git-flow: keeping simple (detection declined)"),{outcome:"declined",detected:e}):mc(e,c)?await r(`This repo's git-flow (${Kn(e)}) differs from the project (${Kn(c)}). Record a per-repo override?`)?(await s(a,t.repoName,e),n(`git-flow: ${Kn(e)} (per-repo override for "${t.repoName}")`),{outcome:"wrote-override",detected:e}):(n(`git-flow: using the project flow for "${t.repoName}" (override declined)`),{outcome:"declined",detected:e}):{outcome:"match",detected:e}}function Kn(t){if(t.flow==="simple")return"simple (single branch)";let e=[`integration=${t.branches.integration}`];return t.branches.stable&&e.push(`stable=${t.branches.stable}`),t.branches.release_pattern&&e.push(`release=${t.branches.release_pattern}`),`${t.flow} (${e.join(", ")})`}async function HP(t){let e=await GP({message:t,initialValue:!0});return KP(e)?!1:e===!0}var xu=S(()=>{"use strict";D();Vb()});import{simpleGit as zb}from"simple-git";async function Jo(t,e){let r=zb(t),n=null;try{n=(await r.raw(["symbolic-ref","--short","refs/remotes/origin/HEAD"])).trim().replace(/^origin\//,"")||null}catch{}!n&&e&&(n=await WP(e));let o=[];try{o=(await r.raw(["for-each-ref","--format=%(refname:short)","refs/remotes/origin"])).split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).map(s=>s.replace(/^origin\//,"")).filter(s=>s!=="HEAD"&&s!=="origin")}catch{o=[]}return{defaultBranch:n,branches:o}}async function WP(t){try{let e=await zb().listRemote(["--symref",t,"HEAD"]);return/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m.exec(e)?.[1]??null}catch{return null}}var Su=S(()=>{"use strict"});import{simpleGit as qP}from"simple-git";async function Xb(t,e,r){return t.host==="github"?YP(t,e,r):t.host==="gitlab"?VP(t,e,r):zP(t,e,r)}function Eu(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 YP(t,e,r){let n=e.githubToken;if(!n)throw new Error("GitHub token required to create a github-hosted mirror");let o=await tt(n,"GET",`/repos/${t.owner}/${encodeURIComponent(t.repoName)}`);if(o.status===200&&o.data){if(o.data.private!==!0)throw Eu(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:o.data.ssh_url,created:!1}}let i=(await tt(n,"GET","/user")).data?.login??"",s=i.toLowerCase()===t.owner.toLowerCase(),a=!s&&await hu(n,t.owner);if(!s&&!a)throw new Error(`"${t.owner}" is neither the token's account ("${i}") nor an organization it can see \u2014 nothing was created. Use a GitHub username or organization (not an email)`);r.info(`creating mirror ${t.owner}/${t.repoName} (github, ${a?"org":"user"})`);let c=await tt(n,"POST",a?`/orgs/${t.owner}/repos`:"/user/repos",{name:t.repoName,private:!0,auto_init:!1,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"});if(!c.data)throw new Error(`GitHub: could not create ${t.owner}/${t.repoName}`);return{spec:t,sshUrl:c.data.ssh_url,created:!0}}async function Jb(t,e,r){try{return t==="github"?(await tt(e,"GET","/user")).data?.login??null:t==="gitlab"?(await Ye(e,"GET","/user")).data?.username??null:r?(await jt({email:r,apiToken:e},"GET","/workspaces?role=contributor&pagelen=1")).data?.values?.[0]?.slug??null:null}catch{return null}}async function VP(t,e,r){let n=e.gitlabToken;if(!n)throw new Error("GitLab PAT required to create a gitlab-hosted mirror");let o=encodeURIComponent(`${t.owner}/${t.repoName}`),i=await Ye(n,"GET",`/projects/${o}`);if(i.status===200&&i.data){if(i.data.visibility!=="private")throw Eu(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:i.data.ssh_url_to_repo,created:!1}}let s={name:t.repoName,path:t.repoName,visibility:"private",initialize_with_readme:!1,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"};if((await Ye(n,"GET","/user")).data?.username!==t.owner){let l=await Ye(n,"GET",`/namespaces/${encodeURIComponent(t.owner)}`);if(l.status===404||!l.data)throw new Error(`GitLab namespace "${t.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);s.namespace_id=l.data.id}r.info(`creating mirror ${t.owner}/${t.repoName} (gitlab)`);let c=await Ye(n,"POST","/projects",s);if(!c.data)throw new Error(`GitLab: could not create ${t.owner}/${t.repoName}`);return{spec:t,sshUrl:c.data.ssh_url_to_repo,created:!0}}async function zP(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 jt(n,"GET",o);if(s.status===200&&s.data){if(s.data.is_private!==!0)throw Eu(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 jt(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 Zb(t,e,r){let n=qP(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(`
961
+ `).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 XP(t,e){let r=e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-");return`${t}-${r}-mirror`.replace(/-{2,}/g,"-").replace(/^[-.]+|[-.]+$/g,"")}function JP(t,e,r){return e.mirror?{host:e.mirror.host,owner:e.mirror.owner,repoName:e.mirror.repoName}:{host:r.host,owner:r.owner,repoName:XP(t,e.repoName)}}function Qb(t,e,r){let n=new Map,o=[];for(let i of e){let s=JP(t,i,r),a=`${s.host}:${s.owner.toLowerCase()}/${s.repoName.toLowerCase()}`,c=n.get(a);if(c)throw new Error(`repositories "${c}" and "${i.name}" both map to the mirror ${s.owner}/${s.repoName} \u2014 mirroring them into one repository would merge their histories. Give one an explicit mirror name (mirror.repo in project.yaml) and re-run`);n.set(a,i.name),o.push({repo:i,spec:s})}return o}var ek=S(()=>{"use strict";Vo()});var ik={};Ge(ik,{ensureEmbeddedWorker:()=>Ys,spawnWorkerProcess:()=>Vs,upCommand:()=>zs,workerChildEnv:()=>ok,workerStartArgs:()=>nk});import{spawn as rk}from"node:child_process";import{existsSync as tk}from"node:fs";import{homedir as ZP,hostname as QP}from"node:os";import{join as qs}from"node:path";async function eA(t,e,r){let n=Me(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 Zh(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.
962
+ 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`),jp(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function tA(t,e,r){let n=Me(e)!==null;if(!await eA(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 ps(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 Mr({hub:t.hubUrl,token:o,name:r.name??`${QP()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function rA(t,e){let r=Me(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=We(r.sealPublicKey);if(!q(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=bi(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 Ys(t,e,r){await tA(t,e,r),rA(t.projectId,e)}function nk(t){return[...t?["--profile",t]:[],"worker","start"]}function ok(t){let e={...t};for(let r of $c)delete e[r];return e}function Vs(t){let e=rk(process.execPath,[t.entry,...nk(t.profile)],{stdio:["ignore","pipe","pipe"],env:ok(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
963
+ `))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function nA(t,e){let r=process.cwd(),n=qs(r,Qe);if(cn(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(tk(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 Ru(r);if(!yp(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 Es({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=qs(ZP(),".codepipe",e?qs("profiles",e,"context-config"):"context-config");if(Ai(c.contextDir,l,a),!tk(qs(c.contextDir,"project.yaml"))){wn(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};vo(c.contextDir,Ct(u,!0,s?.youtrack?.url)),console.log("[up] local project config seeded with defaults \u2014 review .codepipe/project.yaml")}console.log(`[up] project context materialized \u2192 ${n}`)}async function zs(t){let{cfg:e,profile:r}=un(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 nA(e,r),await Ys(e,r,t);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(m,f)=>{let g=w=>h=>{for(let k of h.toString("utf-8").split(`
964
+ `))k.length>0&&w.write(`${f} ${k}
965
+ `)};m.stdout?.on("data",g(process.stdout)),m.stderr?.on("data",g(process.stderr))},i=(m,f)=>{let g=rk(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=Vs({entry:n,profile:r,onLine:m=>process.stdout.write(`[worker] ${m}
945
966
  `)}),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,u=m=>{if(!l){l=!0,console.log(`
946
- [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 Bs=x(()=>{"use strict";dt();Ln();He();Ft();Pl();Pr();je();pe();wt();Yo()});import{existsSync as Ur,mkdirSync as Ek,readFileSync as Fs,readdirSync as cA,writeFileSync as Tk}from"node:fs";import{join as Ve,resolve as Rk}from"node:path";import{setTimeout as au}from"node:timers/promises";import{cancel as Ik,confirm as zo,intro as Ck,isCancel as uu,log as A,multiselect as lA,outro as cu,password as Vo,select as pt,spinner as du,text as we}from"@clack/prompts";import{simpleGit as Un}from"simple-git";function fe(t){Ik(t),process.exit(1)}function ye(t){return uu(t)&&fe("aborted"),t}function ce(t){return uu(t)&&fe("aborted"),typeof t=="string"?t:""}async function Ak(t={}){Ck("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();tk();let r=ek(e),n,o=!1;r&&Object.keys(r.answers).length>0?ye(await zo({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(A.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new Dn(e,r),o=!0):(ou(e),n=new Dn(e)):n=new Dn(e);let i=t.force===!0?null:await su(e),s=await n.ask("target",async()=>ye(await pt({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i??(t.force===!0?null:await dA(e,n)),a?A.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):o&&n.get("contextRepo")!==void 0||_k(e,t.force===!0));let c=await n.ask("hubUrl",async()=>ce(await we({message:"HUB URL",placeholder:mt,initialValue:Q("HUB_URL")??mt,validate:T=>T.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>Bn()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>Fn(c,l)),d=null;s==="farm"&&(d=await uA(c,u));let m=a?mA(a.parsed.repoName):"",f=await n.ask("projectId",async()=>ce(await we({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:T=>Yt.test(T.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await n.ask("projectName",async()=>ce(await we({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:T=>T.trim().length>0?void 0:"required"})).trim()),k=await n.ask("language",()=>SA()),h=await n.ask("automationLevel",async()=>ye(await pt({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),v=(s==="farm"?"no":await n.ask("mirrorChoice",async()=>ye(await pt({message:"how much access should CodePipe have to your repositories?",options:[{value:"no",label:"read and write \u2014 branches and pull requests go into your repositories"},{value:"yes",label:"read only \u2014 CodePipe mirrors them and works in the mirrors",hint:"a mirror is a full copy of the history, in the account you choose next"}],initialValue:"no"}))))==="yes";v&&A.message("read-only token tip: if you want CodePipe to review pull requests people open in your repositories, the token also needs PR-comment permission (GitHub: Pull requests write; Bitbucket: pullrequest:write). Code stays read-only either way.");let S=await n.ask("trackerProvider",async()=>ye(await pt({message:"task tracker",options:[{value:"internal",label:"built-in \u2014 CodePipe tracks tasks itself (no external tracker needed)"},{value:"youtrack",label:"YouTrack \u2014 connect an existing YouTrack project"}],initialValue:"internal"}))),R=S==="internal",$=null,b,I=!0;if(R){let T,P=du();P.start("checking task-key prefixes on your account\u2026");try{T=await Eh(c,u,{excludeProjectId:f}),P.stop("prefixes checked")}catch{P.stop("could not reach the HUB",1),fe("Could not verify the task-key prefix against your account \u2014 the HUB is unreachable right now. Prefix uniqueness is required, so init can't continue. Check your connection and re-run `codepipe init` later.")}let ue=rc(tc(g),T);b=await n.ask("trackerPrefix",async()=>ce(await we({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:ue,initialValue:ue,validate:me=>{let ft=me.trim();if(!Er.test(ft))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(T.has(ft.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else $=await n.ask("youtrack",()=>Fk()),b=await n.ask("youtrackProjectKey",async()=>ce(await we({message:"YouTrack project key",placeholder:"DEV",validate:T=>T.trim().length>0?void 0:"required"})).trim()),I=await n.ask("youtrackWrites",async()=>ye(await zo({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let N=n.get("tokens")??{},H=()=>n.set("tokens",N),z=await n.ask("repos",()=>wA(N,l,a,{onCred:H,initial:n.get("reposPartial")??[],onProgress:T=>n.set("reposPartial",T)}));n.delete("reposPartial");let _=null,y="",U="";if(v){let T=ye(await n.ask("mirrorHost",async()=>ye(await pt({message:"where should the mirrors live? (your Context Repo will default there too)",options:["github","gitlab","bitbucket"].map(ie=>({value:ie,label:ie===z[0]?.host?`${ie} (same as your repositories)`:ie})),initialValue:z[0]?.host??"github"}))));y=ce(await n.ask("mirrorToken",async()=>ye(await Vo({message:`token that may CREATE and PUSH repositories on ${T}`})))).trim(),T==="bitbucket"&&(U=ce(await n.ask("mirrorEmail",async()=>ye(await we({message:"Atlassian account email for that token",...N.bitbucket?.email?{placeholder:N.bitbucket.email,defaultValue:N.bitbucket.email}:{}})))).trim());let P=await hk(T,y,U||void 0),ue=T==="bitbucket"?"workspace slug":"username or organization (not an email)",ft=ce(await n.ask("mirrorOwnerLogin",async()=>ye(await we({message:`account for the mirrors \u2014 ${T} ${ue}`,...P?{placeholder:P,defaultValue:P}:{},validate:ie=>{let re=(ie??"").trim();if(!re&&!P)return"required";if(re.includes("@"))return`that looks like an email \u2014 a ${T} ${ue} is expected`;if(/\s/.test(re))return"no spaces"}})))).trim()||P||"";if(!ft||ft.includes("@")){Ik("mirrors need a host account to live in (a username/organization, not an email)");return}_={host:T,owner:ft}}let O=await kA(await n.ask("contextRepo",()=>Dk(f,z,N,l,_??void 0)),f,z,N,l,H,T=>n.set("contextRepo",T),_??void 0),{spec:K,mode:ee}=O,le;R||(A.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),le=await n.ask("assigneeLogin",async()=>ce(await we({message:"your YouTrack login (the assignee value)",...$?.login?{initialValue:$.login}:{},validate:T=>T.trim().length>0?void 0:"required"})).trim()));let Nt=await n.ask("llmProvider",async()=>{for(;;){if(ye(await pt({message:"LLM provider",options:[{value:"claude",label:"Claude",hint:"recommended"},{value:"codex",label:"Codex",hint:"coming soon"}],initialValue:"claude"}))==="claude")return"claude";A.warn("Codex support is coming soon \u2014 pick Claude for now.")}}),Ue=Nt==="claude"?await n.ask("claudeToken",()=>Hw(Kw("claude"),{farm:s==="farm"})):"",Ne;if(Ue){let T=await zp(Ue);if(T){let P=Ta(T);P&&(Ne=P,A.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${P} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let Pe={projectId:f,name:g,automationLevel:h,repos:z,trackerProvider:S,youtrackProjectKey:b,language:k};A.step(`${ee==="attach"?"attaching to":"provisioning"} Context Repo ${K.owner}/${K.name} (${K.host})\u2026`);let Be;try{Be=await Mn(Pe,K,{...Uk(N),youtrackWrites:I,...$?{trackerUrl:$.url}:{},mode:ee,log:{info:T=>A.message(T),warn:T=>A.warn(T)}})}catch(T){fe(`Context Repo provisioning failed: ${T instanceof Error?T.message:String(T)}`)}Pe.contextRepo=Be,A.success(`Context Repo ready: ${Be.owner}/${Be.name}@${Be.branch}`),A.step(`registering project on ${c}\u2026`);let M;try{M=await ir(c,u,Pe)}catch(T){if(T instanceof W&&T.status===409){A.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{M=await se(c,u,f)}catch(P){throw P instanceof W&&fe(`HUB \u2192 ${P.status} ${P.message}`),P}}else if(T instanceof W&&T.status===401)n.delete("cliToken"),fe("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(T instanceof W)fe(`HUB \u2192 ${T.status} ${T.message}`);else throw T}let B=M.contextRepo??Be;A.success(`project ${M.projectId} ready (${M.provisioningStatus})`);let D=$?{url:$.url,token:$.token}:void 0;if(s==="farm"){let T=d,P={...N,...Ue?{claude:{oauthToken:Ue}}:{},...D?{youtrack:D}:{}},ue=N.github?.token;if(B.host==="github"&&ue)try{let re=yg(`devpipe-${f}`);await wg(B,ue,re.publicKey,`devpipe-${f}`),P.contextSsh={privateKey:re.privateKey},A.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(re){A.warn(`could not set up Context Repo SSH deploy key (${re instanceof Error?re.message:String(re)}); the farm will fall back to the token path.`)}let me={projectId:f,config:{hubUrl:c,cliToken:u,projectId:f},secrets:P,contextRepo:B,projectConfig:It(Pe,I,$?.url,le||void 0,Nt,Ne)},ft=Gt(T.farm.publicKey,JSON.stringify(me));A.step(`handing project ${f} to farm ${T.farm.name}\u2026`);let ie;try{ie=await ns(c,u,T.farm.farmId,{projectId:f,sealedBundle:ft})}catch(re){throw re instanceof W&&fe(re.status===409?`farm ${T.farm.name} is offline \u2014 start it and re-run.`:re.status===504?`farm ${T.farm.name} did not respond in time.`:`HUB \u2192 ${re.status} ${re.message}`),re}ie.ok||fe(`farm rejected provisioning: ${ie.error??"unknown error"}`),await lu(c,u,f,B,ue,M.repos,null,N),n.clear(),cu(`done. project ${f} is now hosted on farm ${T.farm.name} (daemon ${ie.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}Bk(N),await Ok(e,B.cloneUrl,B.branch),Mk(e);try{hn(Ve(e,it),e,{info:T=>A.message(T),warn:T=>A.warn(T)})}catch(T){A.warn(`skills materialize failed \u2014 ${T instanceof Error?T.message:String(T)}`)}a&&await gA(e);{let T=Ve(e,it);mn(T);let P=It(Pe,I,$?.url,le||void 0,Nt,Ne),ue=go(T,P);ue.length>0&&A.success(`local project config \u2192 .codepipe/{${ue.join(", ")}}`),tr(f,P,{info:me=>A.message(me),warn:me=>A.warn(me)})}await Lk(e,M.repos);let X=!1;if(v&&_&&(X=await yA(e,Ve(e,it),f,M.repos,{host:_.host,owner:_.owner,token:y,...U?{email:U}:{}}),X)){let T=Ve(e,it);tr(f,{projectYaml:Fs(Ve(T,"project.yaml"),"utf-8"),regimenYaml:Fs(Ve(T,"regimen.yaml"),"utf-8")},{info:P=>A.message(P),warn:P=>A.warn(P)})}let G={hubUrl:c,cliToken:u,projectId:f,...N,...Ue?{claude:{oauthToken:Ue}}:{},...D?{youtrack:D}:{},...X?{mirrorWrite:{token:y,host:_.host,...U?{email:U}:{}}}:{}};ae(G),Ut({hubUrl:c,cliToken:u,projectId:f,accountEmail:p},f),A.success(`secrets \u2192 ${Tt(f)}`),await lu(c,u,f,B,N.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,M.repos,e,N),n.clear();let E=`${c}/?project=${encodeURIComponent(f)}`;Ar(E),cu(`done. your project on the dashboard (sign in there to work with it):
947
- ${E}
948
- 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:C}=await Promise.resolve().then(()=>(Bs(),xk));await C({profile:void 0})}async function lu(t,e,r,n,o,i=[],s=null,a={}){let c=await ok(n,o),l=!1;if(!c)try{l=await ak(i,{localRoot:s,tokens:a})}catch{l=!1}let u=nk({indexExists:c,localClones:s!==null,reposNonEmpty:l}),p=await lA({message:u.message,options:u.options,initialValues:u.initialValues,required:!1});if(uu(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(()=>(Lo(),fs)),g=await f(m,void 0,{onLog:k=>A.message(k)});A.success(`project map ready: ${g.events} task events mined from history`)}catch(m){A.warn(`could not build the project map: ${m instanceof Error?m.message:String(m)}. Registration is not affected \u2014 run \`codepipe model bootstrap\` later.`)}if(d.has("backfill"))try{let{jobId:m}=await Oo(t,e,r,{reindex:!1,backfill:!0});A.success(`retrospective architecture analysis queued (job ${m}); decision drafts will appear on the project card for review once a SANDBOX picks up the job.`)}catch(m){A.warn(`could not start the retrospective analysis: ${m instanceof Error?m.message:String(m)}. Registration is not affected.`)}if(d.has("index"))try{let{jobId:m}=await Oo(t,e,r,{reindex:u.reindex});A.success(`indexing queued (job ${m}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(m){A.warn(`could not start indexing: ${m instanceof Error?m.message:String(m)}. You can retry later \u2014 registration is not affected.`)}}async function uA(t,e){let r;try{r=await vh(t,e)}catch(c){throw c instanceof W&&fe(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&fe("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=ye(await pt({message:"target farm",options:n.map(c=>({value:c.farmId,label:`${c.name}${c.online?"":" (offline)"} \u2014 ${c.keyFingerprint??"no fingerprint"}`}))})),i=n.find(c=>c.farmId===o),s;try{s=ts(i.farmId,i.publicKey)}catch(c){fe(c instanceof Error?c.message:String(c))}return ye(await zo({message:`confirm farm ${i.name} cred-channel fingerprint:
967
+ [up] ${m} \u2014 stopping both roles`);for(let{child:f}of c)f.exitCode===null&&f.kill(m);setTimeout(()=>{for(let{name:f,child:g}of c)g.exitCode===null&&(console.warn(`[up] ${f} did not stop \u2014 SIGKILL`),g.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:m,child:f})=>new Promise(g=>{f.on("exit",(w,h)=>g({name:m,code:w??(h?1:0)}))})),d=await Promise.race(p);l||(console.log(`[up] ${d.name} exited (code ${d.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(p),process.exit(d.code)}var Xs=S(()=>{"use strict";ut();Bn();He();Gt();Wl();_r();je();de();wt();Zo()});import{existsSync as Gr,mkdirSync as ak,readFileSync as Js,readdirSync as oA,writeFileSync as ck}from"node:fs";import{join as Ne,resolve as lk}from"node:path";import{setTimeout as Tu}from"node:timers/promises";import{cancel as uk,confirm as Qo,intro as dk,isCancel as Pu,log as P,multiselect as iA,outro as Iu,password as ei,select as dt,spinner as Au,text as we}from"@clack/prompts";import{simpleGit as Hn}from"simple-git";function pe(t){uk(t),process.exit(1)}function ye(t){return Pu(t)&&pe("aborted"),t}function ce(t){return Pu(t)&&pe("aborted"),typeof t=="string"?t:""}async function pk(t={}){dk("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Cb();let r=Ib(e),n,o=!1;r&&Object.keys(r.answers).length>0?ye(await Qo({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(P.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new Gn(e,r),o=!0):(wu(e),n=new Gn(e)):n=new Gn(e);let i=t.force===!0?null:await Ru(e),s=await n.ask("target",async()=>ye(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 aA(e,n)),a?P.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):o&&n.get("contextRepo")!==void 0||mk(e,t.force===!0));let c=await n.ask("hubUrl",async()=>ce(await we({message:"HUB URL",placeholder:mt,initialValue:Q("HUB_URL")??mt,validate:$=>$.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>Wn()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>qn(c,l)),d=null;s==="farm"&&(d=await sA(c,u));let m=a?uA(a.parsed.repoName):"",f=await n.ask("projectId",async()=>ce(await we({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:$=>Vt.test($.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await n.ask("projectName",async()=>ce(await we({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:$=>$.trim().length>0?void 0:"required"})).trim()),w=await n.ask("language",()=>vA()),h=await n.ask("automationLevel",async()=>ye(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"}))),x=(s==="farm"?"no":await n.ask("mirrorChoice",async()=>ye(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";x&&P.message("read-only token tip: if you want CodePipe to review pull requests people open in your repositories, the token also needs PR-comment permission (GitHub: Pull requests write; Bitbucket: pullrequest:write). Code stays read-only either way.");let b=await n.ask("trackerProvider",async()=>ye(await 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=b==="internal",E=null,v,I=!0;if(T){let $,C=Au();C.start("checking task-key prefixes on your account\u2026");try{$=await Qh(c,u,{excludeProjectId:f}),C.stop("prefixes checked")}catch{C.stop("could not reach the HUB",1),pe("Could not verify the task-key prefix against your account \u2014 the HUB is unreachable right now. Prefix uniqueness is required, so init can't continue. Check your connection and re-run `codepipe init` later.")}let Y=yc(gc(g),$);v=await n.ask("trackerPrefix",async()=>ce(await we({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:Y,initialValue:Y,validate:fe=>{let ft=fe.trim();if(!Rr.test(ft))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if($.has(ft.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else E=await n.ask("youtrack",()=>xk()),v=await n.ask("youtrackProjectKey",async()=>ce(await we({message:"YouTrack project key",placeholder:"DEV",validate:$=>$.trim().length>0?void 0:"required"})).trim()),I=await n.ask("youtrackWrites",async()=>ye(await Qo({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let j=n.get("tokens")??{},G=()=>n.set("tokens",j),z=await n.ask("repos",()=>hA(j,l,a,{onCred:G,initial:n.get("reposPartial")??[],onProgress:$=>n.set("reposPartial",$)}));n.delete("reposPartial");let A=null,y="",U="";if(x){let $=ye(await n.ask("mirrorHost",async()=>ye(await dt({message:"where should the mirrors live? (your Context Repo will default there too)",options:["github","gitlab","bitbucket"].map(ie=>({value:ie,label:ie===z[0]?.host?`${ie} (same as your repositories)`:ie})),initialValue:z[0]?.host??"github"}))));y=ce(await n.ask("mirrorToken",async()=>ye(await ei({message:`token that may CREATE and PUSH repositories on ${$}`})))).trim(),$==="bitbucket"&&(U=ce(await n.ask("mirrorEmail",async()=>ye(await we({message:"Atlassian account email for that token",...j.bitbucket?.email?{placeholder:j.bitbucket.email,defaultValue:j.bitbucket.email}:{}})))).trim());let C=await Jb($,y,U||void 0),Y=$==="bitbucket"?"workspace slug":"username or organization (not an email)",ft=ce(await n.ask("mirrorOwnerLogin",async()=>ye(await we({message:`account for the mirrors \u2014 ${$} ${Y}`,...C?{placeholder:C,defaultValue:C}:{},validate:ie=>{let re=(ie??"").trim();if(!re&&!C)return"required";if(re.includes("@"))return`that looks like an email \u2014 a ${$} ${Y} is expected`;if(/\s/.test(re))return"no spaces"}})))).trim()||C||"";if(!ft||ft.includes("@")){uk("mirrors need a host account to live in (a username/organization, not an email)");return}A={host:$,owner:ft}}let N=await gA(await n.ask("contextRepo",()=>kk(f,z,j,l,A??void 0)),f,z,j,l,G,$=>n.set("contextRepo",$),A??void 0),{spec:H,mode:X}=N,ue;T||(P.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),ue=await n.ask("assigneeLogin",async()=>ce(await we({message:"your YouTrack login (the assignee value)",...E?.login?{initialValue:E.login}:{},validate:$=>$.trim().length>0?void 0:"required"})).trim()));let xt=await n.ask("llmProvider",async()=>{for(;;){if(ye(await dt({message:"LLM provider",options:[{value:"claude",label:"Claude",hint:"recommended"},{value:"codex",label:"Codex",hint:"coming soon"}],initialValue:"claude"}))==="claude")return"claude";P.warn("Codex support is coming soon \u2014 pick Claude for now.")}}),pt=xt==="claude"?await n.ask("claudeToken",()=>wb(yb("claude"),{farm:s==="farm"})):"",Re;if(pt){let $=await $f(pt);if($){let C=La($);C&&(Re=C,P.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${C} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let Ae={projectId:f,name:g,automationLevel:h,repos:z,trackerProvider:b,youtrackProjectKey:v,language:w};P.step(`${X==="attach"?"attaching to":"provisioning"} Context Repo ${H.owner}/${H.name} (${H.host})\u2026`);let Oe;try{Oe=await Fn(Ae,H,{...vk(j),youtrackWrites:I,...E?{trackerUrl:E.url}:{},mode:X,log:{info:$=>P.message($),warn:$=>P.warn($)}})}catch($){pe(`Context Repo provisioning failed: ${$ instanceof Error?$.message:String($)}`)}Ae.contextRepo=Oe,P.success(`Context Repo ready: ${Oe.owner}/${Oe.name}@${Oe.branch}`),P.step(`registering project on ${c}\u2026`);let Be;try{Be=await sr(c,u,Ae)}catch($){if($ instanceof K&&$.status===409){P.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{Be=await se(c,u,f)}catch(C){throw C instanceof K&&pe(`HUB \u2192 ${C.status} ${C.message}`),C}}else if($ instanceof K&&$.status===401)n.delete("cliToken"),pe("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if($ instanceof K)pe(`HUB \u2192 ${$.status} ${$.message}`);else throw $}let M=Be.contextRepo??Oe;P.success(`project ${Be.projectId} ready (${Be.provisioningStatus})`);let B=E?{url:E.url,token:E.token}:void 0;if(s==="farm"){let $=d,C={...j,...pt?{claude:{oauthToken:pt}}:{},...B?{youtrack:B}:{}},Y=j.github?.token;if(M.host==="github"&&Y)try{let re=Wg(`devpipe-${f}`);await qg(M,Y,re.publicKey,`devpipe-${f}`),C.contextSsh={privateKey:re.privateKey},P.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(re){P.warn(`could not set up Context Repo SSH deploy key (${re instanceof Error?re.message:String(re)}); the farm will fall back to the token path.`)}let fe={projectId:f,config:{hubUrl:c,cliToken:u,projectId:f},secrets:C,contextRepo:M,projectConfig:Ct(Ae,I,E?.url,ue||void 0,xt,Re)},ft=Kt($.farm.publicKey,JSON.stringify(fe));P.step(`handing project ${f} to farm ${$.farm.name}\u2026`);let ie;try{ie=await ds(c,u,$.farm.farmId,{projectId:f,sealedBundle:ft})}catch(re){throw re instanceof K&&pe(re.status===409?`farm ${$.farm.name} is offline \u2014 start it and re-run.`:re.status===504?`farm ${$.farm.name} did not respond in time.`:`HUB \u2192 ${re.status} ${re.message}`),re}ie.ok||pe(`farm rejected provisioning: ${ie.error??"unknown error"}`),await Cu(c,u,f,M,Y,Be.repos,null,j),n.clear(),Iu(`done. project ${f} is now hosted on farm ${$.farm.name} (daemon ${ie.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}$k(j),await yk(e,M.cloneUrl,M.branch),bk(e);try{bn(Ne(e,Qe),e,{info:$=>P.message($),warn:$=>P.warn($)})}catch($){P.warn(`skills materialize failed \u2014 ${$ instanceof Error?$.message:String($)}`)}a&&await pA(e);{let $=Ne(e,Qe);wn($);let C=Ct(Ae,I,E?.url,ue||void 0,xt,Re),Y=vo($,C);Y.length>0&&P.success(`local project config \u2192 .codepipe/{${Y.join(", ")}}`),rr(f,C,{info:fe=>P.message(fe),warn:fe=>P.warn(fe)})}await wk(e,Be.repos),await mA(e,Be.repos);let L=!1;if(x&&A&&(L=await fA(e,Ne(e,Qe),f,Be.repos,{host:A.host,owner:A.owner,token:y,...U?{email:U}:{}}),L)){let $=Ne(e,Qe);rr(f,{projectYaml:Js(Ne($,"project.yaml"),"utf-8"),regimenYaml:Js(Ne($,"regimen.yaml"),"utf-8")},{info:C=>P.message(C),warn:C=>P.warn(C)})}let ee={hubUrl:c,cliToken:u,projectId:f,...j,...pt?{claude:{oauthToken:pt}}:{},...B?{youtrack:B}:{},...L?{mirrorWrite:{token:y,host:A.host,...U?{email:U}:{}}}:{}};ae(ee),Bt({hubUrl:c,cliToken:u,projectId:f,accountEmail:p},f),P.success(`secrets \u2192 ${Tt(f)}`),await Cu(c,u,f,M,j.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,Be.repos,e,j),n.clear();let F=`${c}/?project=${encodeURIComponent(f)}`;Ar(F),Iu(`done. your project on the dashboard (sign in there to work with it):
968
+ ${F}
969
+ 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:R}=await Promise.resolve().then(()=>(Xs(),ik));await R({profile:void 0})}async function Cu(t,e,r,n,o,i=[],s=null,a={}){let c=await _b(n,o),l=!1;if(!c)try{l=await Ob(i,{localRoot:s,tokens:a})}catch{l=!1}let u=Ab({indexExists:c,localClones:s!==null,reposNonEmpty:l}),p=await iA({message:u.message,options:u.options,initialValues:u.initialValues,required:!1});if(Pu(p))return;let d=new Set(p);if(d.has("map")&&s!==null)try{let m=Pe(s);if(!m)throw new Error("workspace not found");let{bootstrapWorkspaceModel:f}=await Promise.resolve().then(()=>(Bo(),$s)),g=await f(m,void 0,{onLog:w=>P.message(w)});P.success(`project map ready: ${g.events} task events mined from history`)}catch(m){P.warn(`could not build the project map: ${m instanceof Error?m.message:String(m)}. Registration is not affected \u2014 run \`codepipe model bootstrap\` later.`)}if(d.has("backfill"))try{let{jobId:m}=await Uo(t,e,r,{reindex:!1,backfill:!0});P.success(`retrospective architecture analysis queued (job ${m}); decision drafts will appear on the project card for review once a SANDBOX picks up the job.`)}catch(m){P.warn(`could not start the retrospective analysis: ${m instanceof Error?m.message:String(m)}. Registration is not affected.`)}if(d.has("index"))try{let{jobId:m}=await Uo(t,e,r,{reindex:u.reindex});P.success(`indexing queued (job ${m}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(m){P.warn(`could not start indexing: ${m instanceof Error?m.message:String(m)}. You can retry later \u2014 registration is not affected.`)}}async function sA(t,e){let r;try{r=await zh(t,e)}catch(c){throw c instanceof K&&pe(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&pe("no farm is available to this account. Farms are assigned by the operator \u2014 ask them to assign one to you (or, if you run your own farm host: `codepipe-farm register --hub <url> --token <token>` and `codepipe-farm start`, then have the operator assign it).");let o=ye(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=ls(i.farmId,i.publicKey)}catch(c){pe(c instanceof Error?c.message:String(c))}return ye(await Qo({message:`confirm farm ${i.name} cred-channel fingerprint:
949
970
  ${s}
950
- (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||fe("farm fingerprint not confirmed \u2014 aborting."),es(i.farmId,s),{farm:i,fingerprint:s}}async function Pk(t){Ck(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();_k(e,t.force===!0);let r=ce(await we({message:"HUB URL",initialValue:Q("HUB_URL")??mt,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await Bn(),{cliToken:o,accountEmail:i}=await Fn(r,n);A.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await se(r,o,t.projectId)}catch(d){throw d instanceof W&&fe(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||fe(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await Fk(),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 Gs(d,l,m?.owner??s.contextRepo.owner,n,m?.repoName)}Bk(l),await Ok(e,s.contextRepo.cloneUrl,s.contextRepo.branch),Mk(e);{let d=Ve(e,it);mn(d);let m={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.trackerProvider?{trackerProvider:s.trackerProvider}:{},...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{},...s.language?{language:s.language}:{}},f=It(m,!0,c?.url,void 0,s.llmProvider??Je),g=go(d,f);g.length>0&&A.success(`local project config \u2192 .codepipe/{${g.join(", ")}} (defaults \u2014 review and adjust)`),tr(t.projectId,f,{info:k=>A.message(k),warn:k=>A.warn(k)})}await Lk(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};ae(p),Ut({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),A.success(`secrets \u2192 ${Tt(t.projectId)}`),await lu(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),cu("done.")}function _k(t,e){if(!Ur(t)){Ek(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=cA(t).filter(o=>!r.has(o));n.length!==0&&(e||fe(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function su(t){if(!Ur(Ve(t,".git")))return null;try{let e=ze(await jk(t));return e?{parsed:e,defaultBranch:await Nk(t)}:null}catch{return null}}async function jk(t){try{return(await Un(t).remote(["get-url","origin"])||"").toString().trim()}catch{return""}}async function dA(t,e){if(!Ur(Ve(t,".git")))return null;let r=await e.ask("inPlaceOrigin",async()=>{let o=await jk(t);return A.warn(o?`this folder is a git checkout, but its origin (${o}) is not a github.com / gitlab.com / bitbucket.org URL`:"this folder is a git checkout without an `origin` remote"),ce(await we({message:"clone URL of this repository \u2014 blank if this folder is not the project repo",placeholder:"git@github.com:acme/api.git",validate:i=>!i||!i.trim()||ze(i)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim()}),n=r?ze(r):null;return n?{parsed:n,defaultBranch:await Nk(t)}:null}async function pA(t){try{let e=await Un().listRemote(["--symref",t,"HEAD"]);return/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m.exec(e)?.[1]??null}catch{return null}}async function fA(t,e){try{return(await Un().listRemote([t,`refs/heads/${e}`])).trim().length>0}catch{return!0}}async function Nk(t){let e=Un(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 mA(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Yt.test(e)?e:""}function hA(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function gA(t){let e=Ve(t,".gitignore"),r=Ur(e)?Fs(e,"utf-8"):"";if(hA(r))return;if(!ye(await zo({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){A.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
971
+ (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||pe("farm fingerprint not confirmed \u2014 aborting."),cs(i.farmId,s),{farm:i,fingerprint:s}}async function fk(t){dk(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();mk(e,t.force===!0);let r=ce(await we({message:"HUB URL",initialValue:Q("HUB_URL")??mt,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await Wn(),{cliToken:o,accountEmail:i}=await qn(r,n);P.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await se(r,o,t.projectId)}catch(d){throw d instanceof K&&pe(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||pe(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await xk(),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 Zs(d,l,m?.owner??s.contextRepo.owner,n,m?.repoName)}$k(l),await yk(e,s.contextRepo.cloneUrl,s.contextRepo.branch),bk(e);{let d=Ne(e,Qe);wn(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=Ct(m,!0,c?.url,void 0,s.llmProvider??Je),g=vo(d,f);g.length>0&&P.success(`local project config \u2192 .codepipe/{${g.join(", ")}} (defaults \u2014 review and adjust)`),rr(t.projectId,f,{info:w=>P.message(w),warn:w=>P.warn(w)})}await wk(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};ae(p),Bt({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),P.success(`secrets \u2192 ${Tt(t.projectId)}`),await Cu(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),Iu("done.")}function mk(t,e){if(!Gr(t)){ak(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=oA(t).filter(o=>!r.has(o));n.length!==0&&(e||pe(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function Ru(t){if(!Gr(Ne(t,".git")))return null;try{let e=Ve(await hk(t));return e?{parsed:e,defaultBranch:await gk(t)}:null}catch{return null}}async function hk(t){try{return(await Hn(t).remote(["get-url","origin"])||"").toString().trim()}catch{return""}}async function aA(t,e){if(!Gr(Ne(t,".git")))return null;let r=await e.ask("inPlaceOrigin",async()=>{let o=await hk(t);return P.warn(o?`this folder is a git checkout, but its origin (${o}) is not a github.com / gitlab.com / bitbucket.org URL`:"this folder is a git checkout without an `origin` remote"),ce(await we({message:"clone URL of this repository \u2014 blank if this folder is not the project repo",placeholder:"git@github.com:acme/api.git",validate:i=>!i||!i.trim()||Ve(i)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim()}),n=r?Ve(r):null;return n?{parsed:n,defaultBranch:await gk(t)}:null}async function cA(t){try{let e=await Hn().listRemote(["--symref",t,"HEAD"]);return/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m.exec(e)?.[1]??null}catch{return null}}async function lA(t,e){try{return(await Hn().listRemote([t,`refs/heads/${e}`])).trim().length>0}catch{return!0}}async function gk(t){let e=Hn(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 uA(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Vt.test(e)?e:""}function dA(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function pA(t){let e=Ne(t,".gitignore"),r=Gr(e)?Js(e,"utf-8"):"";if(dA(r))return;if(!ye(await Qo({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){P.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
951
972
  `)?"":`
952
- `;Tk(e,r+o+`
973
+ `;ck(e,r+o+`
953
974
  # codepipe workspace (added by \`codepipe init\`)
954
975
  .codepipe/
955
- `),A.success(`.codepipe/ added to ${Rk(e)}`)}async function Bn(){let t="";try{t=(await Un().raw(["config","--global","user.email"])||"").trim()}catch{}return ce(await we({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function Fn(t,e){A.step(`connecting account ${e}`);let r;try{r=await Th(t,e)}catch(s){throw s instanceof No&&fe(`${e} is not authorized on this HUB yet.
976
+ `),P.success(`.codepipe/ added to ${lk(e)}`)}async function Wn(){let t="";try{t=(await Hn().raw(["config","--global","user.email"])||"").trim()}catch{}return ce(await we({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function qn(t,e){P.step(`connecting account ${e}`);let r;try{r=await eg(t,e)}catch(s){throw s instanceof Do&&pe(`${e} is not authorized on this HUB yet.
956
977
  Sign up at ${t} (registration form on the login screen),
957
978
  wait for the operator to approve it by email, then re-run
958
- \`codepipe init\` with the same email.`),s}r.accountCreated&&A.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&A.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(Ar(r.authorizeUrl),A.message(`a browser tab was opened to confirm this CLI:
979
+ \`codepipe init\` with the same email.`),s}r.accountCreated&&P.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&P.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(Ar(r.authorizeUrl),P.message(`a browser tab was opened to confirm this CLI:
959
980
  ${r.authorizeUrl}
960
981
  `+(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
961
- otherwise use the emailed link the page offers.`))),r.approvalRequired&&A.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),A.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let n=!1,o=Date.now(),i=o+15*6e4;for(;Date.now()<i;){let s;try{s=await Rh(t,r.requestId)}catch(a){A.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await au(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&A.message(`connected as ${a} (the account confirmed in the browser).`),A.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&fe("the HUB rejected this account"),s.status==="expired"&&fe("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,A.message(`email confirmed. waiting for the operator to approve your account\u2026
962
- (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await au(5e3);continue}await au(2e3)}fe("bootstrap timed out")}async function Ok(t,e,r){let n=Ve(t,it);if(Ur(Ve(n,".git"))){A.message(`${n} already cloned \u2014 skipping`);return}Ur(n)&&fe(`${n} exists but is not a git repo \u2014 remove it and re-run`),Ek(n,{recursive:!0}),A.step(`cloning Context Repo \u2192 ${n}`);try{await Un().clone(e,n,["--branch",r]),A.success(`cloned ${e}`)}catch(o){fe(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function yA(t,e,r,n,o){if(n.length===0)return!1;A.step(`setting up ${n.length} mirror(s) \u2014 your repositories stay read-only`);let i={info:l=>A.message(` ${l}`),warn:l=>A.warn(` ${l}`)},s={...o.host==="github"?{githubToken:o.token}:{},...o.host==="gitlab"?{gitlabToken:o.token}:{},...o.host==="bitbucket"&&o.email?{bitbucket:{email:o.email,apiToken:o.token}}:{}},a;try{a=yk(r,n,o)}catch(l){return A.warn(` ${l instanceof Error?l.message:String(l)}`),A.warn("mirroring is all-or-nothing: NO mirrors were recorded and the project keeps working against its own repositories. Fix the cause and re-run `codepipe init`"),!1}let c=[];for(let{repo:l,spec:u}of a)try{let p=await mk(u,s,i);await gk(Ve(t,l.mountAs??l.name),p.sshUrl,i),c.push({repoName:l.name,spec:u})}catch(p){return A.warn(` ${l.name}: mirror not set up \u2014 ${p instanceof Error?p.message:String(p)}`),A.warn("mirroring is all-or-nothing: NO mirrors were recorded and the project keeps working against its own repositories. Fix the cause and re-run `codepipe init`"),!1}for(let l of c)mm(e,l.repoName,l.spec);for(let l of c)A.success(` ${l.repoName} \u2192 ${l.spec.owner}/${l.spec.repoName}`);return!0}async function Lk(t,e){if(e.length===0)return;A.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(o=>({name:o.name,host:o.host,owner:o.owner,repoName:o.repoName,defaultBranch:o.defaultBranch??"main",mountAs:o.mountAs??o.name})),n=await qo(t,r,{log:{info:o=>A.message(o),warn:o=>A.warn(o)}});for(let o of n)A.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function Mk(t){let e=Ve(t,it,".gitignore"),r="";if(Ur(e)&&(r=Fs(e,"utf-8")),Sk.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
982
+ otherwise use the emailed link the page offers.`))),r.approvalRequired&&P.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),P.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let n=!1,o=Date.now(),i=o+15*6e4;for(;Date.now()<i;){let s;try{s=await tg(t,r.requestId)}catch(a){P.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await Tu(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&P.message(`connected as ${a} (the account confirmed in the browser).`),P.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&pe("the HUB rejected this account"),s.status==="expired"&&pe("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,P.message(`email confirmed. waiting for the operator to approve your account\u2026
983
+ (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await Tu(5e3);continue}await Tu(2e3)}pe("bootstrap timed out")}async function yk(t,e,r){let n=Ne(t,Qe);if(Gr(Ne(n,".git"))){P.message(`${n} already cloned \u2014 skipping`);return}Gr(n)&&pe(`${n} exists but is not a git repo \u2014 remove it and re-run`),ak(n,{recursive:!0}),P.step(`cloning Context Repo \u2192 ${n}`);try{await Hn().clone(e,n,["--branch",r]),P.success(`cloned ${e}`)}catch(o){pe(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function fA(t,e,r,n,o){if(n.length===0)return!1;P.step(`setting up ${n.length} mirror(s) \u2014 your repositories stay read-only`);let i={info:l=>P.message(` ${l}`),warn:l=>P.warn(` ${l}`)},s={...o.host==="github"?{githubToken:o.token}:{},...o.host==="gitlab"?{gitlabToken:o.token}:{},...o.host==="bitbucket"&&o.email?{bitbucket:{email:o.email,apiToken:o.token}}:{}},a;try{a=Qb(r,n,o)}catch(l){return P.warn(` ${l instanceof Error?l.message:String(l)}`),P.warn("mirroring is all-or-nothing: NO mirrors were recorded and the project keeps working against its own repositories. Fix the cause and re-run `codepipe init`"),!1}let c=[];for(let{repo:l,spec:u}of a)try{let p=await Xb(u,s,i);await Zb(Ne(t,l.mountAs??l.name),p.sshUrl,i),c.push({repoName:l.name,spec:u})}catch(p){return P.warn(` ${l.name}: mirror not set up \u2014 ${p instanceof Error?p.message:String(p)}`),P.warn("mirroring is all-or-nothing: NO mirrors were recorded and the project keeps working against its own repositories. Fix the cause and re-run `codepipe init`"),!1}for(let l of c)Gm(e,l.repoName,l.spec);for(let l of c)P.success(` ${l.repoName} \u2192 ${l.spec.owner}/${l.spec.repoName}`);return!0}async function wk(t,e){if(e.length===0)return;P.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(o=>({name:o.name,host:o.host,owner:o.owner,repoName:o.repoName,defaultBranch:o.defaultBranch??"main",mountAs:o.mountAs??o.name})),n=await Xo(t,r,{log:{info:o=>P.message(o),warn:o=>P.warn(o)}});for(let o of n)P.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}async function mA(t,e){let r=Ne(t,Qe);for(let n of e){let o=Ne(t,n.mountAs??n.name),i;try{i=await Jo(o)}catch(s){P.warn(`git-flow detection skipped for "${n.name}": ${s instanceof Error?s.message:String(s)}`);continue}try{await Ws({contextDir:r,repoName:n.name,facts:i,log:s=>P.message(s)})}catch(s){throw P.error(`git-flow for "${n.name}" was NOT saved: ${s instanceof Error?s.message:String(s)}`),s}}}function bk(t){let e=Ne(t,Qe,".gitignore"),r="";if(Gr(e)&&(r=Js(e,"utf-8")),sk.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
963
984
  `)||r.length===0?"":`
964
- `,i=Sk.join(`
985
+ `,i=sk.join(`
965
986
  `)+`
966
- `;Tk(e,r+o+(r?`
967
- `:"")+i),A.message(`appended runtime entries to ${Rk(e)}`)}async function wA(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;await Gs(s.host,t,s.owner,e,s.repoName),i?.(),o.push({name:s.repoName,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:a,mountAs:"."}),n.onProgress?.(o),A.success(`added this repository: ${s.host}: ${s.owner}/${s.repoName} (this folder, default branch ${a})`)}for(;ye(await zo({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 we({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:f=>!f||!f.trim()||ze(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=ze(a);A.message(`${c.host}: ${c.owner}/${c.repoName}`),await Gs(c.host,t,c.owner,e,c.repoName),i?.();let l=ce(await we({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 pA(a),p="";for(;p=ce(await we({message:"default branch",placeholder:u??"main",...u?{initialValue:u}:{}})).trim(),!(!p||!u||p===u||await fA(a,p));)A.warn(`branch "${p}" does not exist in ${c.owner}/${c.repoName} (the repository's default is "${u}")`);let d=ce(await we({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 Dk(t,e,r,n,o){A.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let i=ye(await pt({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));i==="attach"&&A.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let s=o?.host??e[0]?.host,a=o?.owner??e[0]?.owner,c;if(s&&a){let l=ce(await we({message:`Context Repo \u2014 a name (hosted at ${s}: ${a}/<name>) or a full clone URL`,initialValue:Et(t),validate:p=>{let d=(p??"").trim();if(!d)return"required";if(!ze(d)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(d))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),u=ze(l);c=u?{host:u.host,owner:u.owner,name:u.repoName}:{host:s,owner:a,name:l}}else{let l=await bA(),u=ce(await we({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:d=>d.trim().length>0?void 0:"required"})).trim(),p=ce(await we({message:"Context Repo name",placeholder:Et(t),initialValue:Et(t),validate:d=>d.trim().length>0?void 0:"required"})).trim();c={host:l,owner:u,name:p}}return{spec:c,mode:i}}function Uk(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??cn()}}async function kA(t,e,r,n,o,i,s,a){let c=t;for(;;){let{spec:l,mode:u}=c;await Gs(l.host,n,l.owner,o),i?.();let p=du();p.start(`checking ${l.owner}/${l.name} on ${l.host}\u2026`);let d=await qw(l,Uk(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=ye(await pt({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(m==="abort"&&fe("aborted"),m==="create")return c={spec:l,mode:"create"},s(c),c;c=await Dk(e,r,n,o,a),s(c)}}async function bA(){return ye(await pt({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Ks(t,e){let r=du();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 Bk(t){xo(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),So(t.gitlab?.token??process.env.GITLAB_TOKEN),Eo(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Gs(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await vA(r);i?e.github=i:A.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let i=await $A(r,n,o);i?e.bitbucket=i:A.warn("no Bitbucket API token \u2014 git falls back to this machine's SSH keys / BITBUCKET_* env; private repos won't clone over HTTPS and PRs won't open.")}else{let i=await xA();i?e.gitlab=i:A.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function vA(t){for(;;){let e=ce(await Vo({message:`GitHub PAT \u2014 blank to skip
987
+ `;ck(e,r+o+(r?`
988
+ `:"")+i),P.message(`appended runtime entries to ${lk(e)}`)}async function hA(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;await Zs(s.host,t,s.owner,e,s.repoName),i?.(),o.push({name:s.repoName,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:a,mountAs:"."}),n.onProgress?.(o),P.success(`added this repository: ${s.host}: ${s.owner}/${s.repoName} (this folder, default branch ${a})`)}for(;ye(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 we({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:f=>!f||!f.trim()||Ve(f)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!a)continue;let c=Ve(a);P.message(`${c.host}: ${c.owner}/${c.repoName}`),await Zs(c.host,t,c.owner,e,c.repoName),i?.();let l=ce(await we({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 cA(a),p="";for(;p=ce(await we({message:"default branch",placeholder:u??"main",...u?{initialValue:u}:{}})).trim(),!(!p||!u||p===u||await lA(a,p));)P.warn(`branch "${p}" does not exist in ${c.owner}/${c.repoName} (the repository's default is "${u}")`);let d=ce(await we({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 kk(t,e,r,n,o){P.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let i=ye(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"&&P.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let s=o?.host??e[0]?.host,a=o?.owner??e[0]?.owner,c;if(s&&a){let l=ce(await we({message:`Context Repo \u2014 a name (hosted at ${s}: ${a}/<name>) or a full clone URL`,initialValue:Rt(t),validate:p=>{let d=(p??"").trim();if(!d)return"required";if(!Ve(d)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(d))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),u=Ve(l);c=u?{host:u.host,owner:u.owner,name:u.repoName}:{host:s,owner:a,name:l}}else{let l=await yA(),u=ce(await we({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:d=>d.trim().length>0?void 0:"required"})).trim(),p=ce(await we({message:"Context Repo name",placeholder:Rt(t),initialValue:Rt(t),validate:d=>d.trim().length>0?void 0:"required"})).trim();c={host:l,owner:u,name:p}}return{spec:c,mode:i}}function vk(t){return{githubToken:t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:t.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:t.bitbucket??pn()}}async function gA(t,e,r,n,o,i,s,a){let c=t;for(;;){let{spec:l,mode:u}=c;await Zs(l.host,n,l.owner,o),i?.();let p=Au();p.start(`checking ${l.owner}/${l.name} on ${l.host}\u2026`);let d=await kb(l,vk(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=ye(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"&&pe("aborted"),m==="create")return c={spec:l,mode:"create"},s(c),c;c=await kk(e,r,n,o,a),s(c)}}async function yA(){return ye(await dt({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Qs(t,e){let r=Au();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 $k(t){To(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Io(t.gitlab?.token??process.env.GITLAB_TOKEN),Co(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Zs(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await wA(r);i?e.github=i:P.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let i=await bA(r,n,o);i?e.bitbucket=i:P.warn("no Bitbucket API token \u2014 git falls back to this machine's SSH keys / BITBUCKET_* env; private repos won't clone over HTTPS and PRs won't open.")}else{let i=await kA();i?e.gitlab=i:P.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function wA(t){for(;;){let e=ce(await ei({message:`GitHub PAT \u2014 blank to skip
968
989
  classic PAT: 'repo' + 'workflow'
969
990
  fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
970
991
  if org: approve token in org Settings \u2192 Personal access tokens.
971
- (Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo.)`})).trim();if(!e)return;if(await Ks("GitHub",()=>zt(e,t?{owner:t}:void 0)))return{token:e};A.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function $A(t,e,r){for(A.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
992
+ (Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo.)`})).trim();if(!e)return;if(await Qs("GitHub",()=>zt(e,t?{owner:t}:void 0)))return{token:e};P.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function bA(t,e,r){for(P.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
972
993
  How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
973
994
  'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes:
974
995
  read:repository:bitbucket + write:repository:bitbucket +
975
996
  read:pullrequest:bitbucket + write:pullrequest:bitbucket
976
997
  \u2014 write scopes do NOT include read: pick BOTH scopes of each pair
977
998
  (+ admin:repository:bitbucket if this token will provision the Context Repo).
978
- The token is shown ONCE \u2014 copy it right away.`);;){let n=ce(await we({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 Vo({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){A.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await Ks("Bitbucket",async()=>{let i=await Vt(n,o,t);if(t&&r){let s=await ki(n,o,t,r);if(s)throw new Error(s)}return i}))return{email:n,apiToken:o};A.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function xA(){for(;;){let t=ce(await Vo({message:`GitLab PAT \u2014 blank to skip
979
- scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Ks("GitLab",()=>Xt(t))){let e=await gp(t);return e&&A.warn(e),{token:t}}A.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function SA(){let t="__other__",e=async()=>ce(await we({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=ye(await pt({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:ve};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:ve}],i={primary:n};for(let s of o){let a=new Set,c=[s.initial,n,"English",ve].filter(u=>a.has(u)?!1:(a.add(u),!0)).map(u=>({value:u,label:u===ve?"auto \u2014 mirror the language of the user's material":u}));c.push({value:t,label:"other\u2026"});let l=ye(await pt({message:`language for ${s.label}`,options:c,initialValue:s.initial}));i[s.key]=l===t?await e():l}return i}async function Fk(){for(;;){let t=ce(await we({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 Vo({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Ks("YouTrack",()=>Qt({baseUrl:t,token:e}))){let r=await Ap({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}A.warn("re-enter the YouTrack URL / token.")}}var Sk,Yo=x(()=>{"use strict";Ke();F();dt();Ww();vi();He();Ft();Pr();dn();Ho();Al();js();Jt();Cr();rk();je();ik();ck();pl();Oi();pe();Os();Hc();wk();Ii();wt();Sk=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});F();Ke();He();import{Command as AP}from"commander";He();pe();async function cp(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=kt(e);r&&!t.force&&(console.error(`already configured at ${on(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");Ut({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...Y(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};ae(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${on(e)}`)}cc();He();import{homedir as _l}from"node:os";import{join as Mo}from"node:path";Ke();F();import{existsSync as mg,rmSync as rT}from"node:fs";import{join as Or}from"node:path";import{simpleGit as nT}from"simple-git";import"ws";Ke();pe();import{createHash as Qv}from"node:crypto";import{existsSync as e$,readFileSync as t$}from"node:fs";import{homedir as r$,hostname as lc}from"node:os";import{join as n$}from"node:path";function pp(t){return Qv("sha256").update(t).digest("hex").slice(0,12)}function o$(){let t=Q("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=n$(r$(),".claude","credentials.json");if(!e$(e))return;let r=JSON.parse(t$(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 fp(t){let e=o$(),r=Q("ACCOUNT_ID")?.trim(),n=Q("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=an(t);return o?{accountId:`acct-${pp(o)}`,label:n||lc(),...e?{email:e}:{}}:{accountId:`acct-${pp(`host:${lc()}`)}`,label:n||lc(),...e?{email:e}:{}}}Ke();dn();pe();xc();async function Zp(t,e,r,n,o){let i=c=>{e.readyState===e.OPEN&&e.send(JSON.stringify(c))},s=c=>i({type:"agent_login_url",requestId:r.requestId,projectId:t.projectId,error:c});if(Q("ORIGIN")==="farm"||Q("CLAUDE_AUTOLOGIN")!=="1"){s("autologin_disabled");return}let a;try{a=await $c(bi())}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 Bt(c.oauthToken);if(l==="invalid"){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"token rejected (401) \u2014 previous token kept"}),n.warn("[agent-auth] new Claude token rejected (401) \u2014 previous token kept");return}let u=Y(t.projectId);if(!u){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"no secrets file for this project on the CLI"}),n.warn("[agent-auth] no secrets file for this project \u2014 token not saved");return}u.claude={oauthToken:c.oauthToken},ae(u),n.info(`[agent-auth] Claude token replaced (${c.oauthToken.slice(0,12)}\u2026, ${c.oauthToken.length} chars)`),i({type:"agent_login_result",projectId:t.projectId,ok:!0,...l==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}}),o()}catch(c){let l=c instanceof Error?c.message:String(c);i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:l}),n.warn(`[agent-auth] browser authorization failed: ${l}`)}finally{a.close()}}Ke();function Qp(t,e){let r=t.find(n=>n.kind==="claude");return r?.present===!0&&r.ok===!1?Q("ORIGIN")==="farm"||Q("CLAUDE_AUTOLOGIN")!=="1"||e?"none":"open":r?.ok===!0?"rearm":"none"}function ef(t,e){return`${t.replace(/\/$/,"")}/?project=${encodeURIComponent(e)}`}vi();import{existsSync as A$}from"node:fs";import{join as P$}from"node:path";import{simpleGit as _$}from"simple-git";async function tf(t,e){if(!A$(P$(t,".git")))return{status:"skipped"};let r=_$(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${j$(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 j$(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as Ec,readFileSync as af,readdirSync as L$,watch as M$}from"node:fs";import{join as ho}from"node:path";F();import{existsSync as rf,readFileSync as nf,readdirSync as N$,statSync as O$}from"node:fs";import{join as Sc}from"node:path";import{parse as of}from"yaml";function $i(t){let e=Sc(t,"actions"),r=[],n=[];if(!rf(e))return{defs:r,errors:n};let o;try{o=N$(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=Sc(e,s);try{if(!O$(a).isFile())continue;let c=Pa(s,of(nf(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 sf(t){let e={},r=Sc(t,"project.yaml");if(!rf(r))return e;let n;try{n=of(nf(r,"utf-8"))}catch{return e}if(!n||typeof n!="object")return e;let o=n.variables;if(!o||typeof o!="object"||Array.isArray(o))return e;for(let[i,s]of Object.entries(o))!Ze.test(i)||Mt(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var xi=class{constructor(e,r,n,o,i=6e4){this.contextDir=e;this.projectId=r;this.send=n;this.log=o;this.intervalMs=i}timer=null;watchers=[];debounce=null;started=!1;start(){this.started||(this.started=!0,this.report(),this.timer=setInterval(()=>this.report(),this.intervalMs),this.timer.unref?.(),this.installWatcher())}stop(){this.started=!1,this.timer&&clearInterval(this.timer),this.timer=null,this.debounce&&clearTimeout(this.debounce),this.debounce=null;for(let e of this.watchers)try{e.close()}catch{}this.watchers=[]}installWatcher(){let e=()=>{this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>this.report(),500),this.debounce.unref?.()},r=[this.contextDir,ho(this.contextDir,"prompts"),ho(this.contextDir,"actions")];for(let n of r)if(Ec(n))try{let o=M$(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=$i(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=ho(this.contextDir,e);if(!Ec(r))return null;try{return af(r,"utf-8")}catch{return null}}readPrompts(){let e=ho(this.contextDir,"prompts"),r={};if(!Ec(e))return r;let n;try{n=L$(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=af(ho(e,o),"utf-8")}catch{}}return r}};lt();import{existsSync as jc,readFileSync as mf,readdirSync as X$}from"node:fs";import{join as hf}from"node:path";import{simpleGit as J$}from"simple-git";var Z$=/^(\d{4})-(.+)\.md$/,Q$="0000-template.md";function ex(t){let e=t.split(`
980
- `),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 tx(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
981
- `),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 v=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(w);if(!v)break;let S=(v[1]??"").trim().toLowerCase(),R=(v[2]??"").trim(),$=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(w);$&&(d=parseInt($[1]??"",10)),S==="tasks"&&(p=R),l.has(S)||u.push(w),m=h+1}let f=p?p.includes(n)?p:`${p}, ${n}`:n,g=s.slice(m).join(`
982
- `).replace(/^\n+/,""),k=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${f}`,...u,"",g].join(`
983
- `);return{content:k.endsWith(`
984
- `)?k:k+`
985
- `,supersedes:d}}function rx(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
986
-
987
- - **Status:** superseded by ADR-${r}`):n}function nx(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(`
999
+ The token is shown ONCE \u2014 copy it right away.`);;){let n=ce(await we({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 ei({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){P.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await Qs("Bitbucket",async()=>{let i=await Xt(n,o,t);if(t&&r){let s=await Ri(n,o,t,r);if(s)throw new Error(s)}return i}))return{email:n,apiToken:o};P.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function kA(){for(;;){let t=ce(await ei({message:`GitLab PAT \u2014 blank to skip
1000
+ scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Qs("GitLab",()=>Jt(t))){let e=await Kp(t);return e&&P.warn(e),{token:t}}P.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function vA(){let t="__other__",e=async()=>ce(await we({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=ye(await dt({message:"project language",options:[...rn.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:ge};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:ge}],i={primary:n};for(let s of o){let a=new Set,c=[s.initial,n,"English",ge].filter(u=>a.has(u)?!1:(a.add(u),!0)).map(u=>({value:u,label:u===ge?"auto \u2014 mirror the language of the user's material":u}));c.push({value:t,label:"other\u2026"});let l=ye(await dt({message:`language for ${s.label}`,options:c,initialValue:s.initial}));i[s.key]=l===t?await e():l}return i}async function xk(){for(;;){let t=ce(await we({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 ei({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Qs("YouTrack",()=>er({baseUrl:t,token:e}))){let r=await nf({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}P.warn("re-enter the YouTrack URL / token.")}}var sk,Zo=S(()=>{"use strict";Ke();D();ut();bb();Ii();He();Gt();_r();hn();Vo();Hl();Gs();Zt();Pr();Pb();je();jb();Lb();Rl();Gi();de();Hs();Hi();xu();Su();ek();Oi();wt();sk=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});D();Ke();He();import{Command as T_}from"commander";He();de();async function Op(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=bt(e);r&&!t.force&&(console.error(`already configured at ${ln(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");Bt({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=${ln(e)}`)}xc();He();import{homedir as ql}from"node:os";import{join as Fo}from"node:path";Ke();D();import{existsSync as Gg,rmSync as YR}from"node:fs";import{join as Lr}from"node:path";import{simpleGit as VR}from"simple-git";import"ws";Ke();de();import{createHash as H$}from"node:crypto";import{existsSync as W$,readFileSync as q$}from"node:fs";import{homedir as Y$,hostname as Sc}from"node:os";import{join as V$}from"node:path";function Up(t){return H$("sha256").update(t).digest("hex").slice(0,12)}function z$(){let t=Q("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=V$(Y$(),".claude","credentials.json");if(!W$(e))return;let r=JSON.parse(q$(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 Bp(t){let e=z$(),r=Q("ACCOUNT_ID")?.trim(),n=Q("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=dn(t);return o?{accountId:`acct-${Up(o)}`,label:n||Sc(),...e?{email:e}:{}}:{accountId:`acct-${Up(`host:${Sc()}`)}`,label:n||Sc(),...e?{email:e}:{}}}Ke();hn();de();Dc();async function Rf(t,e,r,n,o){let i=c=>{e.readyState===e.OPEN&&e.send(JSON.stringify(c))},s=c=>i({type:"agent_login_url",requestId:r.requestId,projectId:t.projectId,error:c});if(Q("ORIGIN")==="farm"||Q("CLAUDE_AUTOLOGIN")!=="1"){s("autologin_disabled");return}let a;try{a=await Mc(Ti())}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 Ft(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()}}Ke();function Tf(t,e){let r=t.find(n=>n.kind==="claude");return r?.present===!0&&r.ok===!1?Q("ORIGIN")==="farm"||Q("CLAUDE_AUTOLOGIN")!=="1"||e?"none":"open":r?.ok===!0?"rearm":"none"}function If(t,e){return`${t.replace(/\/$/,"")}/?project=${encodeURIComponent(e)}`}Ii();import{existsSync as vx}from"node:fs";import{join as $x}from"node:path";import{simpleGit as xx}from"simple-git";async function Cf(t,e){if(!vx($x(t,".git")))return{status:"skipped"};let r=xx(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${Sx(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 Sx(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as Bc,readFileSync as Nf,readdirSync as Tx,watch as Ix}from"node:fs";import{join as ko}from"node:path";D();import{existsSync as Pf,readFileSync as Af,readdirSync as Ex,statSync as Rx}from"node:fs";import{join as Uc}from"node:path";import{parse as _f}from"yaml";function Ci(t){let e=Uc(t,"actions"),r=[],n=[];if(!Pf(e))return{defs:r,errors:n};let o;try{o=Ex(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=Uc(e,s);try{if(!Rx(a).isFile())continue;let c=Fa(s,_f(Af(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 jf(t){let e={},r=Uc(t,"project.yaml");if(!Pf(r))return e;let n;try{n=_f(Af(r,"utf-8"))}catch{return e}if(!n||typeof n!="object")return e;let o=n.variables;if(!o||typeof o!="object"||Array.isArray(o))return e;for(let[i,s]of Object.entries(o))!Ze.test(i)||Dt(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var Pi=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,ko(this.contextDir,"prompts"),ko(this.contextDir,"actions")];for(let n of r)if(Bc(n))try{let o=Ix(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=Ci(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=ko(this.contextDir,e);if(!Bc(r))return null;try{return Nf(r,"utf-8")}catch{return null}}readPrompts(){let e=ko(this.contextDir,"prompts"),r={};if(!Bc(e))return r;let n;try{n=Tx(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=Nf(ko(e,o),"utf-8")}catch{}}return r}};ct();import{existsSync as Vc,readFileSync as Ff,readdirSync as Fx}from"node:fs";import{join as Gf}from"node:path";import{simpleGit as Gx}from"simple-git";var Kx=/^(\d{4})-(.+)\.md$/,Hx="0000-template.md";function Wx(t){let e=t.split(`
1001
+ `),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 qx(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
1002
+ `),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 k=(s[h]??"").trim();if(k===""){m=h+1;continue}let x=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(k);if(!x)break;let b=(x[1]??"").trim().toLowerCase(),T=(x[2]??"").trim(),E=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(k);E&&(d=parseInt(E[1]??"",10)),b==="tasks"&&(p=T),l.has(b)||u.push(k),m=h+1}let f=p?p.includes(n)?p:`${p}, ${n}`:n,g=s.slice(m).join(`
1003
+ `).replace(/^\n+/,""),w=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${f}`,...u,"",g].join(`
1004
+ `);return{content:w.endsWith(`
1005
+ `)?w:w+`
1006
+ `,supersedes:d}}function Yx(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
1007
+
1008
+ - **Status:** superseded by ADR-${r}`):n}function Vx(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(`
988
1009
  `)+`
989
- `}async function gf(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await J$(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=Ee(t,i(k));if(!jc(h)){a.push(k);continue}s.push({slug:k,content:mf(h,"utf-8")})}let c=hf(t,"adr"),l=new Map;if(jc(c))for(let k of X$(c)){let h=Z$.exec(k);!h||k===Q$||l.set(k,{num:parseInt(h[1]??"",10),slug:h[2]??"",content:mf(hf(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(([,$])=>$.slug===k.slug&&$.content.includes(e))){m.push(k.slug);continue}let w=u++,v=`${String(w).padStart(4,"0")}-${k.slug}.md`,{content:S,supersedes:R}=tx(k.content,w,k.slug,e,n);if(p.set(v,S),l.set(v,{num:w,slug:k.slug,content:S}),d.push(`adr/${v}`),R!==null){let $=[...l.keys()].find(b=>b.startsWith(`${String(R).padStart(4,"0")}-`));if($&&$!==v){let b=rx(p.get($)??l.get($).content,w);p.set($,b),l.set($,{...l.get($),content:b})}}}let f=[];if(o==="staging")for(let k of s)jc(Ee(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:ex(w.content)}));p.set("INDEX.md",nx(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();Ii();Ft();F();import{existsSync as kf,readFileSync as px}from"node:fs";import{join as bf}from"node:path";function fx(t){for(let e of[gt,zr]){let r=bf(t,e);if(kf(r))try{return na(px(r,"utf-8"))}catch{return 0}}return 0}function mx(t,e,r,n=6){let o=e<n,i=o?oa(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function Ci(t,e){return mx(e,fx(t),r=>kf(bf(t,r)))}F();Jt();import{existsSync as Pf,mkdirSync as Gx,mkdtempSync as Kx,rmSync as _f,writeFileSync as jf}from"node:fs";import{tmpdir as Hx}from"node:os";import{dirname as Wx,join as Pi}from"node:path";import{simpleGit as Mc}from"simple-git";Pr();function qx(t){return`codepipe/context-migration-v${t}`}function Yx(t){let e=ia(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 \`${zr}\``,"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(`
990
- `)}async function Nf(t,e,r,n){let o=Mc(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Ci(t,e);if(!i.outdated)return i;let s=qx(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 zx(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=Ir(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:Yx(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 zx(t,e,r,n,o,i,s){let a=Mc(t),c=Kx(Pi(Hx(),"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(yn(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=Pi(c,g);Pf(h)||(Gx(Wx(h),{recursive:!0}),jf(h,k),d++)}jf(Pi(c,gt),Zn(n.currentVersion)),d++;let m=Pi(c,zr);Pf(m)&&(_f(m,{force:!0}),d++);let f=Mc(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 Vx,readFileSync as Xx,writeFileSync as Jx}from"node:fs";import{homedir as Zx}from"node:os";import{join as Of}from"node:path";import{parseDocument as Qx}from"yaml";function eS(t,e){let r={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(r.default_branch=t.defaultBranch),e!==void 0&&(r.mirror=e),r}function tS(t,e){let r=Qx(t),n=new Map,o=r.toJS();for(let i of o?.repos??[]){if(!i||typeof i!="object")continue;let s=typeof i.name=="string"?i.name:String(i.repo??"");s&&i.mirror!==void 0&&i.mirror!==null&&n.set(s,i.mirror)}return r.set("repos",e.map(i=>eS(i,n.get(i.name)))),r.toString()}function rS(t,e){let r=[Of(Zx(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(Of(e,"project.yaml")),r}function vo(t,e,r){let n=[],o=[];for(let i of rS(t,r))if(Vx(i))try{let s=Xx(i,"utf-8"),a=tS(s,e);a!==s&&(Jx(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}$o();dt();pe();function fS(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 Vf(t,e,r,n){let o=fS(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=pi(t.projectId,a.sandboxId,a.fingerprint);if(c==="mismatch"){n.warn(`[cred] SANDBOX ${a.name} (${a.sandboxId}) key fingerprint CHANGED \u2014 refusing to seal creds. Expected the pinned key; got ${a.fingerprint}. If this is intentional, clear the pin in the secrets file and re-run.`);continue}c==="pinned"&&n.info(`[cred] pinned SANDBOX ${a.name} (${a.sandboxId}) fingerprint ${a.fingerprint}`);let l;try{l=Gt(a.publicKey,i)}catch(u){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}dt();pe();Jt();Cr();dn();Oi();function Qf(t){let e=Y(t);if(!e)return null;if(!e.sealKey){let r=Ni();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},ae(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:We(e.sealKey.publicKey)}}async function em(t,e,r,n){let o;try{o=JSON.parse(kn(n,r).toString("utf-8"))}catch(s){return{ok:!1,detail:`cannot open the sealed credential (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}let i=Y(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await zt(o.token);return i.github={token:o.token},bn(i,()=>{process.env.GH_TOKEN=o.token,Xf(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Xt(o.token);return i.gitlab={token:o.token},bn(i,()=>{process.env.GITLAB_TOKEN=o.token,Jf(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 Vt(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},bn(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,Zf(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 Qt({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},bn(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 Bt(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},bn(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},bn(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 bn(t,e){ae(t),e()}F();F();import{spawn as mS}from"node:child_process";var hS=124,tm=16*1024,rm=4e3;function gS(t,e,r,n,o,i){let s={...t},a=(c,l)=>{Mt(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 nm(t){let{def:e,onEvent:r}=t,n=gS(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
991
- `,o.length>tm&&(o=o.slice(o.length-tm))},s=(a,c)=>{let l=c.length>rm?c.slice(0,rm)+"\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 yS(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 yS(t,e,r,n,o){return new Promise(i=>{let s=mS("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??Aa)*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(`
992
- `))!==-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?hS:m??(f?1:0))})})}lt();lt();import{existsSync as wS,readFileSync as kS,statSync as om}from"node:fs";var im=2*1024*1024;function bS(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function sm(t,e){let r=Ee(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!wS(r)||!om(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=om(r);if(n>im)throw new Error(`file too large: ${e} is ${n} bytes (limit ${im})`);let o=kS(r);return bS(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}pe();F();import{existsSync as vS,readFileSync as $S,writeFileSync as xS}from"node:fs";import{join as SS}from"node:path";import{parseDocument as ES}from"yaml";async function am(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=Ua(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=SS(t,o);if(!vS(s))throw new Error(`${o} not found in context repo (${t})`);let a=ES($S(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);xS(s,a.toString()),n.push(o)}return{files:n}}Hc();import{existsSync as Wc,readFileSync as qc,writeFileSync as TS}from"node:fs";import{join as Mi}from"node:path";import{parseDocument as Yc}from"yaml";async function hm(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=Mi(t,"project.yaml");if(!Wc(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=Yc(qc(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=Mi(t,"regimen.yaml");if(!Wc(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=Yc(qc(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(Mi(t,i.path),i.content);return{files:r.map(i=>i.path)}}function Di(t){if(!t)return"Stage";try{let e=Mi(t,"project.yaml");if(!Wc(e))return"Stage";let n=Yc(qc(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}Jt();_i();$o();F();lt();import{existsSync as VS,readFileSync as XS}from"node:fs";import{join as sh}from"node:path";import{simpleGit as al}from"simple-git";F();import{existsSync as gm,readFileSync as ym,readdirSync as RS}from"node:fs";import{join as zc}from"node:path";import{simpleGit as IS}from"simple-git";function CS(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(`
993
- `)){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 AS(t,e){let r=zc(t,`tasks/${e}/annotations`);if(!gm(r))return[];let n=[];for(let o of RS(r).sort())if(o.endsWith(".md")){try{let i=CS(o,ym(zc(r,o),"utf-8"));i&&n.push(i)}catch{}if(n.length>=ma)break}return n}var PS=12;async function wm(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=IS(o),p=[];for(let d of AS(e,r)){if(d.repo!==n)continue;let m=ge("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,PS),k=ca(f),h=zc(e,k),w=p.find(I=>I.path===k),v=w?.content??(gm(h)?ym(h,"utf-8"):null),S=`<!-- ${r}${g?`:${g}`:""} -->`;if(v?.includes(S))continue;let R=v??`---
1010
+ `}async function Kf(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await Gx(t).pull(void 0,void 0,["--rebase"])}catch{}let i=w=>o==="staging"?`adr/DRAFT-${w}.md`:`tasks/${e}/adr/DRAFT-${w}.md`,s=[],a=[];for(let w of r){let h=Ee(t,i(w));if(!Vc(h)){a.push(w);continue}s.push({slug:w,content:Ff(h,"utf-8")})}let c=Gf(t,"adr"),l=new Map;if(Vc(c))for(let w of Fx(c)){let h=Kx.exec(w);!h||w===Hx||l.set(w,{num:parseInt(h[1]??"",10),slug:h[2]??"",content:Ff(Gf(c,w),"utf-8")})}let u=Math.max(0,...[...l.values()].map(w=>w.num))+1,p=new Map,d=[],m=[];for(let w of s){if([...l.entries()].find(([,E])=>E.slug===w.slug&&E.content.includes(e))){m.push(w.slug);continue}let k=u++,x=`${String(k).padStart(4,"0")}-${w.slug}.md`,{content:b,supersedes:T}=qx(w.content,k,w.slug,e,n);if(p.set(x,b),l.set(x,{num:k,slug:w.slug,content:b}),d.push(`adr/${x}`),T!==null){let E=[...l.keys()].find(v=>v.startsWith(`${String(T).padStart(4,"0")}-`));if(E&&E!==x){let v=Yx(p.get(E)??l.get(E).content,k);p.set(E,v),l.set(E,{...l.get(E),content:v})}}}let f=[];if(o==="staging")for(let w of s)Vc(Ee(t,`adr/DRAFT-${w.slug}.md`))&&f.push({path:`adr/DRAFT-${w.slug}.md`,content:"",deleted:!0});if(d.length===0&&f.length===0)return{promoted:d,skipped:m,missing:a};if(d.length>0){let w=[...l.entries()].map(([h,k])=>({num:k.num,file:h,header:Wx(k.content)}));p.set("INDEX.md",Vx(w))}for(let[w,h]of p.entries())f.push({path:`adr/${w}`,content:h});let g=d.length>0?`adr(${e}): promote ${s.map(w=>w.slug).join(", ")}`:`adr(${e}): drop stale staged ${m.join(", ")}`;return await Ie(t,f,g),{promoted:d,skipped:m,missing:a}}ct();Oi();Gt();D();import{existsSync as qf,readFileSync as nS}from"node:fs";import{join as Yf}from"node:path";function oS(t){for(let e of[gt,Jr]){let r=Yf(t,e);if(qf(r))try{return pa(nS(r,"utf-8"))}catch{return 0}}return 0}function iS(t,e,r,n=6){let o=e<n,i=o?fa(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function Li(t,e){return iS(e,oS(t),r=>qf(Yf(t,r)))}D();Zt();import{existsSync as im,mkdirSync as jS,mkdtempSync as NS,rmSync as sm,writeFileSync as am}from"node:fs";import{tmpdir as OS}from"node:os";import{dirname as LS,join as Di}from"node:path";import{simpleGit as Zc}from"simple-git";_r();function MS(t){return`codepipe/context-migration-v${t}`}function DS(t){let e=ma(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 \`${Jr}\``,"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(`
1011
+ `)}async function cm(t,e,r,n){let o=Zc(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Li(t,e);if(!i.outdated)return i;let s=MS(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 US(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=Cr(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:DS(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 US(t,e,r,n,o,i,s){let a=Zc(t),c=NS(Di(OS(),"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(vn(l,u).map(g=>[g.path,g.content])),d=0;for(let g of n.missingPaths){if(g===gt)continue;let w=p.get(g);if(w==null){s.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let h=Di(c,g);im(h)||(jS(LS(h),{recursive:!0}),am(h,w),d++)}am(Di(c,gt),no(n.currentVersion)),d++;let m=Di(c,Jr);im(m)&&(sm(m,{force:!0}),d++);let f=Zc(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(()=>{}),sm(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{existsSync as BS,readFileSync as FS,writeFileSync as GS}from"node:fs";import{homedir as KS}from"node:os";import{join as lm}from"node:path";import{parseDocument as HS}from"yaml";function WS(t,e,r){let n={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(n.default_branch=t.defaultBranch),e!==void 0&&(n.mirror=e),r!==void 0&&(n.git=r),n}function qS(t,e){let r=HS(t),n=new Map,o=new Map,i=r.toJS();for(let s of i?.repos??[]){if(!s||typeof s!="object")continue;let a=typeof s.name=="string"?s.name:String(s.repo??"");a&&(s.mirror!==void 0&&s.mirror!==null&&n.set(a,s.mirror),s.git!==void 0&&s.git!==null&&o.set(a,s.git))}return r.set("repos",e.map(s=>WS(s,n.get(s.name),o.get(s.name)))),r.toString()}function YS(t,e){let r=[lm(KS(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(lm(e,"project.yaml")),r}function Ro(t,e,r){let n=[],o=[];for(let i of YS(t,r))if(BS(i))try{let s=FS(i,"utf-8"),a=qS(s,e);a!==s&&(GS(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}Sn();ut();de();function oE(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 $m(t,e,r,n){let o=oE(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=bi(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=Kt(a.publicKey,i)}catch(u){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}ut();de();Zt();Pr();hn();Gi();function Rm(t){let e=q(t);if(!e)return null;if(!e.sealKey){let r=Fi();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},ae(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:We(e.sealKey.publicKey)}}async function Tm(t,e,r,n){let o;try{o=JSON.parse(En(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 zt(o.token);return i.github={token:o.token},Rn(i,()=>{process.env.GH_TOKEN=o.token,xm(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Jt(o.token);return i.gitlab={token:o.token},Rn(i,()=>{process.env.GITLAB_TOKEN=o.token,Sm(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 Xt(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},Rn(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,Em(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 er({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},Rn(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 Ft(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},Rn(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},Rn(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 Rn(t,e){ae(t),e()}D();D();import{spawn as iE}from"node:child_process";var sE=124,Im=16*1024,Cm=4e3;function aE(t,e,r,n,o,i){let s={...t},a=(c,l)=>{Dt(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 Pm(t){let{def:e,onEvent:r}=t,n=aE(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
1012
+ `,o.length>Im&&(o=o.slice(o.length-Im))},s=(a,c)=>{let l=c.length>Cm?c.slice(0,Cm)+"\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 cE(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 cE(t,e,r,n,o){return new Promise(i=>{let s=iE("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 w;for(;(w=f.indexOf(`
1013
+ `))!==-1;)o(m,f.slice(0,w).replace(/\r$/,"")),f=f.slice(w+1)},flush:()=>{f.length>0&&o(m,f.replace(/\r$/,"")),f=""}}},p=u("stdout"),d=u("stderr");s.stdout?.on("data",p.data),s.stderr?.on("data",d.data),s.on("error",m=>{clearTimeout(l),o("stderr",`spawn failed: ${m.message}`),i(127)}),s.on("close",(m,f)=>{clearTimeout(l),p.flush(),d.flush(),i(a?sE:m??(f?1:0))})})}ct();ct();import{existsSync as lE,readFileSync as uE,statSync as Am}from"node:fs";var _m=2*1024*1024;function dE(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function jm(t,e){let r=Ee(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!lE(r)||!Am(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=Am(r);if(n>_m)throw new Error(`file too large: ${e} is ${n} bytes (limit ${_m})`);let o=uE(r);return dE(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}de();D();import{existsSync as pE,readFileSync as fE,writeFileSync as mE}from"node:fs";import{join as hE}from"node:path";import{parseDocument as gE}from"yaml";async function Nm(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=za(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=hE(t,o);if(!pE(s))throw new Error(`${o} not found in context repo (${t})`);let a=gE(fE(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);mE(s,a.toString()),n.push(o)}return{files:n}}Hi();import{existsSync as il,readFileSync as sl,writeFileSync as yE}from"node:fs";import{join as Wi}from"node:path";import{parseDocument as al}from"yaml";async function Km(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=Wi(t,"project.yaml");if(!il(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=al(sl(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=Wi(t,"regimen.yaml");if(!il(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=al(sl(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)yE(Wi(t,i.path),i.content);return{files:r.map(i=>i.path)}}function qi(t){if(!t)return"Stage";try{let e=Wi(t,"project.yaml");if(!il(e))return"Stage";let n=al(sl(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}Zt();Ui();Sn();D();ct();import{existsSync as BE,readFileSync as FE}from"node:fs";import{join as Nh}from"node:path";import{simpleGit as vl}from"simple-git";D();import{existsSync as Hm,readFileSync as Wm,readdirSync as wE}from"node:fs";import{join as cl}from"node:path";import{simpleGit as bE}from"simple-git";function kE(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(`
1014
+ `)){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 vE(t,e){let r=cl(t,`tasks/${e}/annotations`);if(!Hm(r))return[];let n=[];for(let o of wE(r).sort())if(o.endsWith(".md")){try{let i=kE(o,Wm(cl(r,o),"utf-8"));i&&n.push(i)}catch{}if(n.length>=xa)break}return n}var $E=12;async function qm(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=bE(o),p=[];for(let d of vE(e,r)){if(d.repo!==n)continue;let m=he("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,$E),w=ya(f),h=cl(e,w),k=p.find(I=>I.path===w),x=k?.content??(Hm(h)?Wm(h,"utf-8"):null),b=`<!-- ${r}${g?`:${g}`:""} -->`;if(x?.includes(b))continue;let T=x??`---
994
1015
  entityId: ${f}
995
1016
  ---
996
1017
 
997
1018
  # Intent log
998
1019
 
999
1020
  Append-only. Keyed by entityId \u2014 never by path; entries survive renames.
1000
- `,$=["",`## ${s} \u2014 ${r}`,S,"",d.body,""].join(`
1001
- `),b=R+$;w?w.content=b:p.push({path:k,content:b})}return p}el();nl();Fi();il();Ro();async function JS(t,e){let n=await al(t).raw(["diff","--numstat",`${e}^`,e]).catch(()=>""),o=[];for(let i of n.split(`
1002
- `)){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 ZS(t,e){let n=[`tasks/${e}/PLAN.md`,`tasks/${e}/SOLUTION.md`].find(i=>VS(sh(t,i)));if(!n)return{};let o=sh(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 ah(t){let{contextDir:e,repoDir:r,repoName:n,taskKey:o,commitSha:i}=t,s=jr(e),a=_r([...s.ignore,...vn]),c=await JS(r,i),l=(await al(r).raw(["show","-s","--format=%cs",i])).trim(),u=null,p=new Map;try{u=tl(e,n),u&&(p=new Map(u.entities.filter(R=>R.status==="active").map(R=>[R.currentKey,R.entityId])))}catch{}let d=[];for(let R of c){if(a(R.path))continue;let $=ge("code",n,R.path),b=p.get($);d.push({key:$,...b?{entityId:b}:{},churn:R.churn})}if(d.length===0)return{recorded:!1};let m=ZS(e,o),f=Ui(e,o),g=f?.origin==="pipeline"?f.files.filter(R=>te(R.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=[...Ki(e).filter(R=>R.taskKey!==o),h],v=eh(th(e),w,o,s.cochange.halfLifeDays),S=await wm({contextDir:e,taskKey:o,repoName:n,repoDir:r,commitSha:i,date:l,touchedKeys:new Set(d.map(R=>R.key)),identity:u}).catch(()=>[]);await Re(e,[{path:kr(o),content:Xr(h)},{path:wr,content:Hi(v)},...S],`model: task event ${o}`);{let{rebuildSearchIndex:R}=await Promise.resolve().then(()=>(Co(),Io));await R(e).catch(()=>{})}return{recorded:!0}}async function ch(t){let e=new Set([t.fallbackTaskKey]);try{let r=al(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(`
1003
- `)){let s=i.trim();s&&e.add(s)}}catch{}for(let r of[...e].sort())await QS(t.contextDir,r,t.prUrl)}async function QS(t,e,r){let n=Ui(t,e);if(!n||n.origin!=="pipeline"||n.links?.pr===r)return;let o={...n,links:{...n.links??{},pr:r}};await Re(t,[{path:kr(e),content:Xr(o)}],`model: pr link for ${e}`)}Cr();import{existsSync as dh,readFileSync as ph}from"node:fs";import{join as fh}from"node:path";import{parseDocument as mh}from"yaml";Cr();var Ao=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return Fp(this.cfg,e)}getIssue(e,r){return Gp(this.cfg,e,r??Di(this.contextDir))}listComments(e,r){return Kp(this.cfg,e,r)}downloadAttachment(e){return Bp(this.cfg,e)}updateStatus(e,r){return Pp(this.cfg,e,r,Di(this.contextDir))}addComment(e,r,n){return _p(this.cfg,e,r)}createIssue(e){return Op(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,Di(this.contextDir))}editIssue(e,r){return jp(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return Lp(this.cfg,e,r,n)}fetchStateFields(e){return Wp(this.cfg,e)}};F();lt();import{existsSync as sE,readFileSync as aE}from"node:fs";import{randomBytes as cE}from"node:crypto";import{existsSync as cl,readFileSync as eE,readdirSync as tE}from"node:fs";F();lt();function Vi(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=iE(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:rE(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:oE(nE(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 lh(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),cl(Ee(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 Xi(t,e,r){if(r.length===0)return;let n=Vi(t,e,r),o=r.map(i=>i.issue.key);await Re(t,n,`sync(${o.join(", ")}): task data`)}function rE(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(`
1004
- `)}function nE(t,e,r){let n=new Map,o=Ee(t,`tasks/${e}/comments.jsonl`);if(cl(o))for(let i of eE(o,"utf-8").split(`
1005
- `)){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=Sr(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function oE(t){return t.map(e=>JSON.stringify(e)).join(`
1021
+ `,E=["",`## ${s} \u2014 ${r}`,b,"",d.body,""].join(`
1022
+ `),v=T+E;k?k.content=v:p.push({path:w,content:v})}return p}ml();yl();zi();bl();Ao();async function GE(t,e){let n=await vl(t).raw(["diff","--numstat",`${e}^`,e]).catch(()=>""),o=[];for(let i of n.split(`
1023
+ `)){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 KE(t,e){let n=[`tasks/${e}/PLAN.md`,`tasks/${e}/SOLUTION.md`].find(i=>BE(Nh(t,i)));if(!n)return{};let o=Nh(t,n);try{let i=FE(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 Oh(t){let{contextDir:e,repoDir:r,repoName:n,taskKey:o,commitSha:i}=t,s=Nr(e),a=jr([...s.ignore,...Tn]),c=await GE(r,i),l=(await vl(r).raw(["show","-s","--format=%cs",i])).trim(),u=null,p=new Map;try{u=hl(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 E=he("code",n,T.path),v=p.get(E);d.push({key:E,...v?{entityId:v}:{},churn:T.churn})}if(d.length===0)return{recorded:!1};let m=KE(e,o),f=Yi(e,o),g=f?.origin==="pipeline"?f.files.filter(T=>te(T.key)?.repo!==n):[],w=f?.origin==="pipeline"?f.commits:[],h={modelFormatVersion:2,taskKey:o,origin:"pipeline",...f?.title?{title:f.title}:{},...l?{date:l}:{},commits:[...new Set([...w,i])],files:[...g,...d],links:{...f?.origin==="pipeline"?f.links:{},...m}};h.links&&Object.keys(h.links).length===0&&delete h.links;let k=[...Ji(e).filter(T=>T.taskKey!==o),h],x=Ih(Ch(e),k,o,s.cochange.halfLifeDays),b=await qm({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:kr(o),content:Qr(h)},{path:br,content:Zi(x)},...b],`model: task event ${o}`);{let{rebuildSearchIndex:T}=await Promise.resolve().then(()=>(jo(),_o));await T(e).catch(()=>{})}return{recorded:!0}}async function Lh(t){let e=new Set([t.fallbackTaskKey]);try{let r=vl(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(`
1024
+ `)){let s=i.trim();s&&e.add(s)}}catch{}for(let r of[...e].sort())await HE(t.contextDir,r,t.prUrl)}async function HE(t,e,r){let n=Yi(t,e);if(!n||n.origin!=="pipeline"||n.links?.pr===r)return;let o={...n,links:{...n.links??{},pr:r}};await Ie(t,[{path:kr(e),content:Qr(o)}],`model: pr link for ${e}`)}Pr();import{existsSync as Uh,readFileSync as Bh}from"node:fs";import{join as Fh}from"node:path";import{parseDocument as Gh}from"yaml";Pr();var No=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return hf(this.cfg,e)}getIssue(e,r){return gf(this.cfg,e,r??qi(this.contextDir))}listComments(e,r){return yf(this.cfg,e,r)}downloadAttachment(e){return mf(this.cfg,e)}updateStatus(e,r){return of(this.cfg,e,r,qi(this.contextDir))}addComment(e,r,n){return sf(this.cfg,e,r)}createIssue(e){return lf(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,qi(this.contextDir))}editIssue(e,r){return af(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return uf(this.cfg,e,r,n)}fetchStateFields(e){return bf(this.cfg,e)}};D();ct();import{existsSync as JE,readFileSync as ZE}from"node:fs";import{randomBytes as QE}from"node:crypto";import{existsSync as $l,readFileSync as WE,readdirSync as qE}from"node:fs";D();ct();function ns(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=XE(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:YE(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:zE(VE(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 Mh(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),$l(Ee(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 os(t,e,r){if(r.length===0)return;let n=ns(t,e,r),o=r.map(i=>i.issue.key);await Ie(t,n,`sync(${o.join(", ")}): task data`)}function YE(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(`
1025
+ `)}function VE(t,e,r){let n=new Map,o=Ee(t,`tasks/${e}/comments.jsonl`);if($l(o))for(let i of WE(o,"utf-8").split(`
1026
+ `)){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=Er(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function zE(t){return t.map(e=>JSON.stringify(e)).join(`
1006
1027
  `)+(t.length>0?`
1007
- `:"")}function iE(t,e,r){let n=[],o=Ee(t,`tasks/${e}/attachments`);if(cl(o))for(let i of tE(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}Ai();var Po=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await wo(this.contextDir);let r=e.columns??[];return Rf(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>bo(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=ko(this.contextDir,e);return r?bo(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return uh(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 wo(this.contextDir),!ko(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${cE(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=Sr(r);s&&(i.parsedCommand=s);let c=[...uh(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
1028
+ `:"")}function XE(t,e,r){let n=[],o=Ee(t,`tasks/${e}/attachments`);if($l(o))for(let i of qE(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}Mi();var Oo=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await xo(this.contextDir);let r=e.columns??[];return em(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>Eo(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=So(this.contextDir,e);return r?Eo(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return Dh(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 xo(this.contextDir),!So(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${QE(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=Er(r);s&&(i.parsedCommand=s);let c=[...Dh(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
1008
1029
  `)+`
1009
- `;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 If(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:li.statusColumns}]}async mutateRecord(e,r,n){let o=ko(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=bo(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:tn(e),content:Lc(i)},...Vi(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:ao,status:r.targetStatus,links:[],created:n,updated:n},i=bo(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:tn(e),content:Lc(o)},...Vi(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}};function uh(t,e){let r=Ee(t,`tasks/${e}/comments.jsonl`);if(!sE(r))return[];let n=[];for(let o of aE(r,"utf-8").split(`
1010
- `)){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}Ai();function ll(t){if(!t)return"youtrack";try{let e=fh(t,"project.yaml");return dh(e)&&mh(ph(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function Ct(t){let e=ll(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=Ef(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=lE(n);return i?{ok:!0,kind:e,provider:new Po(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=Cp();return r?{ok:!0,kind:e,provider:new Ao(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function lE(t){try{let e=fh(t,"project.yaml");if(!dh(e))return null;let r=mh(ph(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var Qi=new Map;async function _o(t,e){let n=(Qi.get(t)??Promise.resolve()).catch(()=>{}).then(e);Qi.set(t,n);try{return await n}finally{Qi.get(t)===n&&Qi.delete(t)}}function jo(t,e){return fo(t.split(":",2)[0]??"",e)}function wh(t){let{mirror:e,...r}=t;return{spec:r,host:Ir(r)}}async function kh(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;ut(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return Z("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return _o(`${i}/${r.name}`,async()=>{let s=await or(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir);if(r.mirror){let{syncUpstream:p}=await Promise.resolve().then(()=>(Zi(),Ji)),d=await p(r,a,{info:m=>ut(`[mirror] ${m}`),warn:m=>ut(`[mirror] WARN ${m}`)});d.error&&ut(`[mirror] ${r.name}: pre-apply sync failed \u2014 ${d.error}`)}let{commit:c,pushed:l,baseMoved:u}=await Uf(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 ah({contextDir:t.contextDir,repoDir:a,repoName:r.name,taskKey:p,commitSha:c}).catch(d=>{ut(`[model] task event for ${p} failed: ${d instanceof Error?d.message:String(d)}`)})}return de({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,pushed:l,...typeof u=="number"&&u>0?{baseMoved:u}:{},...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"push_branch":{if(!r)return Z("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return _o(`${i}/${r.name}`,async()=>{let s=await or(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir);return await Bf(s,a,{branchName:e.branchName,force:e.force}),de({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"create_pr":{if(!r)return Z("no repo spec");let{spec:i,host:s}=jo(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 ch({contextDir:t.contextDir,repoDir:_e(l,r.name,t.baseDir),branchName:e.branchName,baseBranch:e.baseBranch,fallbackTaskKey:c,prUrl:a.url}).catch(u=>{ut(`[model] pr link for ${c} failed: ${u instanceof Error?u.message:String(u)}`)})}return de({url:a.url,number:a.number,host:s.name})}case"merge_pr":{if(!r)return Z("no repo spec");let{spec:i,host:s}=jo(e.taskId,r),a=await s.mergePR(i,e.prNumber,e.mergeMethod,e.deleteBranch);return de({prNumber:e.prNumber,host:s.name,...a.mergedSha?{mergedSha:a.mergedSha}:{}})}case"close_pr":{if(!r)return Z("no repo spec");let{spec:i,host:s}=jo(e.taskId,r);return await s.closePR(i,e.prNumber,e.comment),de({prNumber:e.prNumber,host:s.name})}case"rewrite_cluster_branch":{if(!r)return Z("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return _o(`${i}/${r.name}`,async()=>{let s=await or(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir),{commit:c,dropped:l}=await Ff(s,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:r.defaultBranch});return de({branch:e.branchName,commit:c,dropped:l,pushed:l>0})})}case"merge_branch":{if(!r)return Z("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return _o(`${i}/${r.name}`,async()=>{let s=await or(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir),{mergedSha:c}=await Gf(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return de({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return Z("no repo spec");let i=t.cloneUrlOverride??ji(r),a=(await Kf(i)).filter(u=>Hf(u,e.issueKey)),c=Ir(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 de({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return Z("no repo spec");let{spec:i,host:s}=e.upstream?wh(r):jo(e.taskId,r);return await s.addPRComment(i,e.prNumber,e.body),de({prNumber:e.prNumber,host:s.name})}case"add_pr_inline_comment":{if(!r)return Z("no repo spec");let{spec:i,host:s}=e.upstream?wh(r):jo(e.taskId,r);if(s.addPRInlineComment)try{return await s.addPRInlineComment(i,e.prNumber,e.path,e.line,e.body),de({prNumber:e.prNumber,inline:!0,host:s.name})}catch(a){ut(`[exec] inline comment ${e.path}:${e.line} failed (${a instanceof Error?a.message.split(`
1030
+ `;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 tm(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:gi.statusColumns}]}async mutateRecord(e,r,n){let o=So(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=Eo(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:sn(e),content:Jc(i)},...ns(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:fo,status:r.targetStatus,links:[],created:n,updated:n},i=Eo(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:sn(e),content:Jc(o)},...ns(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}};function Dh(t,e){let r=Ee(t,`tasks/${e}/comments.jsonl`);if(!JE(r))return[];let n=[];for(let o of ZE(r,"utf-8").split(`
1031
+ `)){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}Mi();function xl(t){if(!t)return"youtrack";try{let e=Fh(t,"project.yaml");return Uh(e)&&Gh(Bh(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function Pt(t){let e=xl(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=Zf(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=eR(n);return i?{ok:!0,kind:e,provider:new Oo(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=rf();return r?{ok:!0,kind:e,provider:new No(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function eR(t){try{let e=Fh(t,"project.yaml");if(!Uh(e))return null;let r=Gh(Bh(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var as=new Map;async function Lo(t,e){let n=(as.get(t)??Promise.resolve()).catch(()=>{}).then(e);as.set(t,n);try{return await n}finally{as.get(t)===n&&as.delete(t)}}function Mo(t,e){return wo(t.split(":",2)[0]??"",e)}function qh(t){let{mirror:e,...r}=t;return{spec:r,host:Cr(r)}}async function Yh(t){let{action:e,repo:r}=t,n="repoName"in e?e.repoName:"-",o="taskId"in e?e.taskId:"draftId"in e?e.draftId:e.projectId;lt(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return Z("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Lo(`${i}/${r.name}`,async()=>{let s=await ir(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir);if(r.mirror){let{syncUpstream:p}=await Promise.resolve().then(()=>(ss(),is)),d=await p(r,a,{info:m=>lt(`[mirror] ${m}`),warn:m=>lt(`[mirror] WARN ${m}`)});d.error&&lt(`[mirror] ${r.name}: pre-apply sync failed \u2014 ${d.error}`)}let{commit:c,pushed:l,baseMoved:u}=await fm(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 Oh({contextDir:t.contextDir,repoDir:a,repoName:r.name,taskKey:p,commitSha:c}).catch(d=>{lt(`[model] task event for ${p} failed: ${d instanceof Error?d.message:String(d)}`)})}return le({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,pushed:l,...typeof u=="number"&&u>0?{baseMoved:u}:{},...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"push_branch":{if(!r)return Z("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Lo(`${i}/${r.name}`,async()=>{let s=await ir(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir);return await mm(s,a,{branchName:e.branchName,force:e.force}),le({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"create_pr":{if(!r)return Z("no repo spec");let{spec:i,host:s}=Mo(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 Lh({contextDir:t.contextDir,repoDir:_e(l,r.name,t.baseDir),branchName:e.branchName,baseBranch:e.baseBranch,fallbackTaskKey:c,prUrl:a.url}).catch(u=>{lt(`[model] pr link for ${c} failed: ${u instanceof Error?u.message:String(u)}`)})}return le({url:a.url,number:a.number,host:s.name})}case"merge_pr":{if(!r)return Z("no repo spec");let{spec:i,host:s}=Mo(e.taskId,r),a=await s.mergePR(i,e.prNumber,e.mergeMethod,e.deleteBranch);return le({prNumber:e.prNumber,host:s.name,...a.mergedSha?{mergedSha:a.mergedSha}:{}})}case"close_pr":{if(!r)return Z("no repo spec");let{spec:i,host:s}=Mo(e.taskId,r);return await s.closePR(i,e.prNumber,e.comment),le({prNumber:e.prNumber,host:s.name})}case"rewrite_cluster_branch":{if(!r)return Z("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Lo(`${i}/${r.name}`,async()=>{let s=await ir(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir),{commit:c,dropped:l}=await hm(s,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:mi(r)});return le({branch:e.branchName,commit:c,dropped:l,pushed:l>0})})}case"merge_branch":{if(!r)return Z("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Lo(`${i}/${r.name}`,async()=>{let s=await ir(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir),{mergedSha:c}=await gm(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return le({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return Z("no repo spec");let i=t.cloneUrlOverride??xn(r),a=(await Bi(i)).filter(u=>ym(u,e.issueKey)),c=Cr(r),l=null;if(c.findOpenPrByBranch)for(let u of a){let p=await c.findOpenPrByBranch(r,u).catch(()=>null);if(p){l={number:p.number,url:p.url};break}}return le({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return Z("no repo spec");let{spec:i,host:s}=e.upstream?qh(r):Mo(e.taskId,r);return await s.addPRComment(i,e.prNumber,e.body),le({prNumber:e.prNumber,host:s.name})}case"add_pr_inline_comment":{if(!r)return Z("no repo spec");let{spec:i,host:s}=e.upstream?qh(r):Mo(e.taskId,r);if(s.addPRInlineComment)try{return await s.addPRInlineComment(i,e.prNumber,e.path,e.line,e.body),le({prNumber:e.prNumber,inline:!0,host:s.name})}catch(a){lt(`[exec] inline comment ${e.path}:${e.line} failed (${a instanceof Error?a.message.split(`
1011
1032
  `)[0]:String(a)}) \u2014 posting as a plain comment`)}return await s.addPRComment(i,e.prNumber,`\u{1F4CD} \`${e.path}:${e.line}\`
1012
1033
 
1013
- ${e.body}`),de({prNumber:e.prNumber,inline:!1,host:s.name})}case"tracker_status":{let i=Ct({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),de({issueId:t.trackerIssueId,newStatus:e.newStatus})):Z("no tracker_issue_id provided"):Z(i.error)}case"tracker_comment":{let i=Ct({contextDir:t.contextDir});if(!i.ok)return Z(i.error);if(!t.trackerIssueId)return Z("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return de({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Ct({contextDir:t.contextDir});if(!i.ok)return Z(i.error);if(!e.projectKey)return Z("no projectKey in create_tracker_issue action");let{id:s,key:a}=await i.provider.createIssue({projectKey:e.projectKey,title:e.title,body:e.body,targetStatus:e.targetStatus});return de({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Ct({contextDir:t.contextDir});if(!i.ok)return Z(i.error);let s=0;for(let a of e.links)try{await i.provider.applyLink(a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return Z(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return de({applied:s})}case"set_project_setting":{if(!t.contextDir)return Z("no context repo clone on this CLI");let i=await am(t.contextDir,e.edits);return de({files:i.files})}case"set_prompt_override":{if(!t.contextDir)return Z("no context repo clone on this CLI");if(!Ha(e.role))return Z(`unknown prompt operation: ${e.role}`);let i=Wa(e.role);return await Re(t.contextDir,[e.content===null?{path:i,content:"",deleted:!0}:{path:i,content:e.content}],e.commitMessage),t.requestConfigReport?.(),de({path:i,reset:e.content===null})}case"tracker_edit":{let i=Ct({contextDir:t.contextDir});if(!i.ok)return Z(i.error);if(!t.contextDir)return Z("no context repo clone on this CLI");await i.provider.editIssue(e.issueKey,{...e.title!==void 0?{title:e.title}:{},...e.body!==void 0?{body:e.body}:{}});let s=await i.provider.getIssue(e.issueKey);return s&&await Xi(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),de({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return Z("no context repo clone on this CLI");let i=await hm(t.contextDir,e);return de({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return Z("no context repo clone on this CLI");let i=await fm(t.contextDir,e);return de({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),de({reported:!0})):Z("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return Z("no context repo clone on this CLI");let i=await t.refreshContextStatus();return de({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return Z("no project workspace on this CLI");if(!r)return Z("no repo spec");if(!t.onRunActivity)return Z("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=$i(t.contextDir),c=s.find(m=>m.id===e.actionId);if(!c){let m=a.find(f=>f.file===`actions/${e.actionId}.yml`);return Z(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=_a(c,e.input);if(!l.ok)return Z(l.error);let u=sf(t.contextDir),p=Y(e.projectId),d={};return p?.github?.token&&(d.GH_TOKEN=p.github.token),p?.gitlab?.token&&(d.GITLAB_TOKEN=p.gitlab.token),p?.bitbucket&&(d.BITBUCKET_EMAIL=p.bitbucket.email,d.BITBUCKET_API_TOKEN=p.bitbucket.apiToken),p?.youtrack&&(d.YOUTRACK_URL=p.youtrack.url,d.YOUTRACK_TOKEN=p.youtrack.token),_o(`${e.projectId}/${r.name}`,async()=>{await or(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=_e(e.projectId,r.name,t.baseDir),f=await nm({cwd:m,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:g=>i(e.runId,g)});return de({runId:e.runId,status:f.status,exitCode:f.exitCode,...f.failedStep?{failedStep:f.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return Z("no context repo clone on this CLI");let i=sm(t.contextDir,e.path);return de({path:e.path,...i})}case"search_model":{if(!t.contextDir)return Z("no context repo clone on this CLI");let{searchModelIndex:i}=await Promise.resolve().then(()=>(Co(),Io)),s=await i(t.contextDir,e.q,e.limit);return de({hits:s})}case"model_drift":return Z("model_drift requires a local workspace (handled by the daemon)");case"model_bootstrap":return Z("model_bootstrap requires a local workspace (handled by the daemon)");default:return Z(`unsupported action type: ${e.type}`)}}catch(i){return Z(i instanceof Error?i.message:String(i))}}function de(t){return{status:"done",result:t}}function Z(t){return{status:"failed",error:t}}dt();pl();je();pe();import{existsSync as jh,readFileSync as Nh}from"node:fs";import{join as Oh}from"node:path";async function Lh(t,e,r,n){let o=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return o(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=We(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");ts(e.farmId,e.farmPublicKey);let s=Y(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await se(t.hubUrl,t.cliToken,t.projectId),c;if(r){let d=Oh(r,"project.yaml"),m=Oh(r,"regimen.yaml");jh(d)&&jh(m)?c={projectYaml:Nh(d,"utf-8"),regimenYaml:Nh(m,"utf-8")}:n.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},u=Gt(e.farmPublicKey,JSON.stringify(l));es(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let p=await ns(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();dt();Ke();dt();import{homedir as SE}from"node:os";import{existsSync as EE,mkdirSync as TE,readFileSync as RE,writeFileSync as IE}from"node:fs";import{dirname as CE,join as AE}from"node:path";function hl(){return Q("RUNNER_PINS")??AE(SE(),".codepipe","runner-pins.json")}function Mh(){let t=hl();if(!EE(t))return{};try{return JSON.parse(RE(t,"utf-8"))}catch{return{}}}function PE(t){let e=hl();TE(CE(e),{recursive:!0}),IE(e,JSON.stringify(t,null,2)+`
1014
- `,{mode:384})}function _E(t){return Mh()[t]}function gl(t,e){let r=Mh();r[t]=e,PE(r)}function Dh(t,e){let r=We(e),n=_E(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 ${hl()}.`);return r}je();pe();var Bh=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function Uh(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:Bh(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 jE={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Bh(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)=>Uh(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Uh(t,e,r,"remove-token")},Fh={api:jE,fetchProject:se,provisionOnRunner:$h,teardownOnRunner:xh};async function Gh(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(We(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Dh(e.runnerId,e.runnerPublicKey);let i=Y(t.projectId)?.github?.token;if(!i)throw new Error("no GitHub token stored for this project on this CLI");let a=((await r.fetchProject(t.hubUrl,t.cliToken,t.projectId)).repos??[]).find(c=>c.host==="github"&&c.owner===e.owner&&c.repoName===e.repo);if(!a)throw new Error(`${e.owner}/${e.repo} is not a GitHub repository of this project`);return{githubToken:i,repo:a}}async function Kh(t,e,r,n=Fh){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 Gh(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:[Ja(e.runnerId)]},c=Gt(e.runnerPublicKey,JSON.stringify(a));gl(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 Hh(t,e,r,n=Fh){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 Gh(t,e,n),a={owner:s.owner,repo:s.repoName};try{a.removeToken=await n.api.mintRemoveToken(i,s.owner,s.repoName)}catch(p){r.warn(`[ghr] remove-token for ${s.owner}/${s.repoName} failed (${p instanceof Error?p.message:p}) \u2014 the runner host will force-remove`)}let c={projectId:t.projectId,runners:[a]},l=Gt(e.runnerPublicKey,JSON.stringify(c));gl(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();import{existsSync as NE}from"node:fs";import{join as Wh}from"node:path";import{simpleGit as Yh}from"simple-git";async function yl(t,e,r,n,o){for(let i of r.repos){let s=e.find(u=>u.name===i.repoName);if(!s)continue;let a=`${r.taskKey}:${s.name}:${i.branchName}`;if(!so(i.branchName)){n.has(a)||(n.add(a),o.warn(`[pull] ${r.taskKey} ${s.mountAs}: refusing suspicious branch name`));continue}let c=Wh(t,s.mountAs);if(!NE(Wh(c,".git")))continue;let l=Yh(c);try{let u=await ME(l,i.branchName);await l.fetch(await OE(l,s),`refs/heads/${i.branchName}`);let p=(await l.revparse(["FETCH_HEAD"])).trim();if(u===p)continue;if(await LE(l,c,i.branchName)){n.has(a)||(n.add(a),o.info(`[pull] ${r.taskKey} \u2192 ${s.mountAs}: ${i.branchName} is checked out here \u2014 fetched ${p.slice(0,10)}; merge or pull it in that checkout yourself`));continue}await l.raw(["branch","-f",i.branchName,p]),o.info(`[pull] ${r.taskKey} \u2192 ${s.mountAs}: ${i.branchName} ${p.slice(0,10)} (checkout untouched)`)}catch(u){if(n.has(a))continue;n.add(a),o.warn(`[pull] ${r.taskKey} ${s.mountAs}: ${i.branchName} unavailable \u2014 `+(u instanceof Error?u.message.split(`
1015
- `)[0]:String(u)))}}}async function OE(t,e){if(e.mirror)return qh(e.mirror);try{if((await t.getRemotes(!0)).find(n=>n.name==="origin")?.refs?.fetch)return"origin"}catch{}return e.host&&e.owner&&e.repoName?qh({host:e.host,owner:e.owner,repoName:e.repoName}):"origin"}function qh(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 LE(t,e,r){try{return(await t.raw(["worktree","list","--porcelain"])).split(`
1016
- `).some(o=>o.trim()===`branch refs/heads/${r}`)}catch{try{return(await Yh(e).revparse(["--abbrev-ref","HEAD"])).trim()===r}catch{return!1}}}async function ME(t,e){try{return(await t.revparse([e])).trim()}catch{return null}}var ss=class{constructor(e,r,n,o){this.intervalMs=e;this.fetchDeliverables=r;this.workspace=n;this.log=o}timer=null;running=!1;caughtUp=!1;warned=new Set;start(){if(this.timer)return;this.log.info(`[pull] local delivery started (interval=${this.intervalMs}ms)`);let e=()=>void this.runOnce();e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[pull] local delivery stopped"))}poke(){this.runOnce()}async runOnce(){if(!this.running){this.running=!0;try{let e=await this.fetchDeliverables(),r=this.caughtUp?e.filter(n=>n.phase==="TRACKING"||n.phase==="AWAITING_CLUSTER"):e;for(let n of r)await yl(this.workspace.root,this.workspace.repos,n,this.warned,this.log);this.caughtUp=!0}catch(e){this.log.warn(`[pull] pass failed: ${e instanceof Error?e.message:String(e)}`)}finally{this.running=!1}}}};F();dt();pe();var zh=16*1024;function DE(t){return Ze.test(t)?Mt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Ze}`}function Vh(t,e,r,n){let o=DE(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(kn(n,r).toString("utf-8"));if(typeof s.value!="string"||s.value.length===0)return{ok:!1,detail:"payload has no value"};i=s.value}catch(s){return{ok:!1,detail:`cannot open the sealed secret (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}if(i.length>zh)return{ok:!1,detail:`secret value too large (max ${zh} chars)`};try{return np(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function Xh(t,e){try{return op(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)}}}dn();pe();Jt();var as=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}=fo(o,a.repoSpec);try{let u=await l.getPullRequest(c,a.number);n.push({number:a.number,repoName:a.repoSpec.name,url:a.url,state:u.state,merged:u.merged,ci:u.ci,mergeable:u.mergeable})}catch(u){if(u instanceof Rr){this.log.warn(`[track] task=${e} pr=${a.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${a.url} fetch failed: ${u instanceof Error?u.message:String(u)}`);return}}let i=n.map(a=>`${a.repoName??""}#${a.number}:${a.state}:${a.merged?1:0}:${a.ci}:${a.mergeable}`).join("|");if(this.lastSig.get(e)===i)return;for(let a=0;a<n.length;a++){let c=n[a];if(c.ci!=="failed")continue;let{spec:l,host:u}=fo(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=UE(n);this.log.info(`[track] task=${e} snapshot signalled${s?` \u2192 ${s}`:""} (${n.length} PR(s))`)}};function UE(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 cs=class t{constructor(e,r,n,o={contextDir:null}){this.intervalMs=e;this.send=r;this.log=n;this.options=o}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;abandonedTicks=0;static MAX_ABANDONED_TICKS=3;setRequest(e){let r=this.request?.projectId;this.request=e,this.log.info(`[yt-sync] request updated: project=${e.projectKey} columns=[${e.sourceColumns.join(",")}] sinceMs=${e.sinceMs} offBoard=${e.offBoardIssueIds.length}`),this.timer||this.start(),r&&r!==e.projectId&&this.log.info(`[yt-sync] project switch ${r} \u2192 ${e.projectId}`)}start(){if(this.timer)return;this.log.info(`[yt-sync] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[yt-sync] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[yt-sync] poller stopped"))}async tickOnce(){await this.tick()}async forceSync(){if(!this.request){this.log.info("[yt-sync] force requested but no sync_request yet \u2014 ignored");return}this.log.info("[yt-sync] force sync requested (manual)"),await this.tick()}async tick(){if(this.running||!this.request)return;let r=(this.options.resolveProvider??(()=>Ct({contextDir:this.options.contextDir})))();if(!r.ok){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn(`[yt-sync] tracker provider unavailable (${r.error}) \u2014 poller idle.`));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,r.provider)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let v=e.stageField?{stageField:e.stageField}:{},S=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},$=(e.backlogScope??"personal")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if($){let b=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[I,N]=await Promise.all([b.length>0?r.listIssues({projectKey:e.projectKey,columns:b,...v,...S}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...v})]),H=new Map;for(let z of[...I,...N])H.set(z.id,z);o=[...H.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,...v,...S})}}catch(v){let S=v instanceof Error?v.message:String(v);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 v of o){if(s.add(v.id),a.has(v.status))continue;let S=await Qh(r,v.id,e.sinceMs,this.log);S&&i.set(v.id,S)}let c=[];for(let v of e.offBoardIssueIds){if(s.has(v))continue;let S=await Qh(r,v,e.sinceMs,this.log);S&&S.length>0&&i.set(v,S);let R=await Zh(r,v,e.stageField,this.log);if(R)c.push(R);else if(S&&S.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}let l=o.filter(v=>!a.has(v.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(v=>({issue:v,comments:i.get(v.id)??[],attachments:u.get(v.id)??[]}));d.push(...await lh(this.options.contextDir,d,v=>Zh(r,v,e.stageField,this.log)));try{await Xi(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let v of p)this.shippedAttachments.add(v)}catch(v){let S=v instanceof Error?v.message:String(v);this.abandonTick(`context task sync failed: ${S}`);return}let m=this.options.isSelfComment??(()=>!1),f=[],g=[];for(let[v,S]of i){let R=S.filter(b=>!m(b.id));if(R.length===0)continue;f.push({issueId:v,comments:R.map(BE)});let $=R.flatMap(b=>{let I=Sr(b.body);return I?[{commentId:b.id,author:b.author,name:I.name,args:I.args,createdAt:b.createdAt}]:[]});$.length>0&&g.push({issueId:v,commands:$})}let k={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Jh),commentsBatch:f,...g.length>0?{commandsBatch:g}:{},...c.length>0?{offBoardIssues:c.map(Jh)}:{},observedAtMs:n};this.send(k);let h=f.reduce((v,S)=>v+S.comments.length,0),w=g.reduce((v,S)=>v+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=FE(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 Jh(t){let{description:e,...r}=t;return r}function BE(t){let{body:e,...r}=t;return r}function FE(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 Zh(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 Qh(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 oT(t,e){let r=t.repos.filter(i=>i.mirror);if(r.length===0)return[];let{mirrorLag:n}=await Promise.resolve().then(()=>(Zi(),Ji)),o=[];for(let i of r){let s=i.mountAs==="."?t.root:Or(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 Rl="npm i -g @code-partner/codepipe@latest";function ms(t,e={}){let r=e.log??{info:h=>console.log(h),warn:h=>console.warn(h)};r.info(`codepipe-cli v${Xe} (protocol ${ht})`);let n=h=>e.onEvent?.(h),o=e.workspace;o?.contextDir&&lf(o.contextDir,r);let i=()=>{if(o?.contextDir)try{hn(o.contextDir,o.root,r)}catch(h){r.warn(`[skills] materialize failed (non-fatal): ${h instanceof Error?h.message:String(h)}`)}};i();let s=Cl("CLI_TRACKING_POLL_INTERVAL_SEC"),a=Cl("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=rs(t.hubUrl,t.cliToken),w=null,v=new as(s,M=>{h.readyState===h.OPEN&&h.send(JSON.stringify(M))},r),S=o&&o.repos.length>0?new ss(Cl("CLI_LOCAL_PULL_INTERVAL_SEC"),()=>is(t.hubUrl,t.cliToken,t.projectId),{root:o.root,repos:o.repos},r):null,R=new cs(a,M=>{h.readyState===h.OPEN&&h.send(JSON.stringify(M))},r,{contextDir:o?.contextDir??null,isSelfComment:M=>f.has(M)}),$=null,b=async()=>{try{let M={trackerProvider:ll(o?.contextDir??null)};try{let E=await se(t.hubUrl,t.cliToken,t.projectId);M={...M,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 Yp(t.projectId,M),D=o?await oT(o,r):[];if(i(),h.readyState!==h.OPEN)return;let X={type:"cli_readiness",projectId:t.projectId,ready:B.ready,checks:B.checks,creds:B.creds,secretNames:ip(t.projectId),...o?{mirrors:D}:{},checkedAt:B.checkedAt};if(h.send(JSON.stringify(X)),B.ready)r.info("[readiness] ready");else{let E=B.checks.filter(C=>!C.ok).map(C=>`${C.name}(${C.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${E.join(", ")}`)}let G=Qp(B.creds,p);if(G==="open"){p=!0;let E=ef(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${E}`),Ar(E)}else G==="rearm"&&(p=!1)}catch(M){r.warn(`[readiness] check failed: ${M instanceof Error?M.message:String(M)}`)}},I=()=>{b(),$=setInterval(()=>void b(),c),typeof $.unref=="function"&&$.unref()},N=()=>{$&&(clearInterval($),$=null)},H=150,z=new Map,_=M=>{let B=z.get(M);if(!B||(B.timer&&clearTimeout(B.timer),z.delete(M),B.events.length===0||h.readyState!==h.OPEN))return;let D={type:"run_activity",projectId:t.projectId,runId:M,events:B.events};h.send(JSON.stringify(D))},y=(M,B)=>{let D=z.get(M);if(D||(D={events:[],timer:null},z.set(M,D)),D.events.push(B),B.kind==="result"){_(M);return}D.timer||(D.timer=setTimeout(()=>_(M),H),D.timer.unref?.())},U=o?.contextDir?new xi(o.contextDir,t.projectId,M=>{h.readyState===h.OPEN&&h.send(JSON.stringify(M))},r):null,O=async()=>{let M=o?.contextDir;if(!M)throw new Error("no context repo clone on this CLI");let B;try{B=(await se(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let D=await Nf(M,t.projectId,B,r);return h.readyState===h.OPEN&&h.send(JSON.stringify(D)),D},K=null,ee=async()=>{let M=o?.contextDir;if(M)try{let{readContextIndexHub:B,collectSearchRows:D}=await Promise.resolve().then(()=>(Co(),Io));if(B(M)!=="metadata")return;let X=D(M);h.readyState===h.OPEN&&(h.send(JSON.stringify({type:"model_index",projectId:t.projectId,rows:X})),r.info(`[model] tier-2 index snapshot pushed (${X.length} rows)`))}catch(B){r.warn(`[model] tier-2 index push failed (non-fatal): ${B instanceof Error?B.message:String(B)}`)}},le=()=>{K&&clearTimeout(K),K=setTimeout(()=>void ee(),5e3)},Nt=async()=>{if(!o?.contextDir)throw new Error("no Context Repo clone on this CLI");if(m)throw new Error("model bootstrap is already running");m=!0;try{let M=await se(t.hubUrl,t.cliToken,t.projectId),{bootstrapDaemonModel:B}=await Promise.resolve().then(()=>(Lo(),fs)),D=await B(t.projectId,{root:o.root,contextDir:o.contextDir},M.repos,X=>r.info(`[model] ${X}`));return r.info(`[model] bootstrap done: ${D.repos} repos, ${D.events} task events`),le(),D}finally{m=!1}},Ue=null,Ne=async M=>{if(o?.contextDir)try{let B=await Promise.resolve().then(()=>(Lo(),fs)),D={root:o.root,contextDir:o.contextDir,repos:o.repos};if(B.shouldAutoBootstrapModel(o.contextDir)){await B.syncWorkspaceMirrors(D,G=>r.info(G));try{await Nt()}catch(G){r.warn(`[model] auto-bootstrap failed (non-fatal): ${G instanceof Error?G.message:String(G)}`)}return}(await B.rebuildWorkspaceModelIfStale(D,{fetch:M,onLog:G=>r.info(G)})).rebuilt.length>0&&le()}catch(B){r.warn(`[model] release-path rebuild failed (non-fatal): ${B instanceof Error?B.message:String(B)}`)}},Pe=M=>{Ue&&clearTimeout(Ue),Ue=setTimeout(()=>void Ne(M),6e4)},Be=setInterval(()=>void Ne(!0),6*36e5);return h.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let M=fp(t.projectId),B=Q("ORIGIN")==="farm"?"farm":"local",D=Q("FARM_ID"),X=t.accountEmail??M.email,G;try{let C=Qf(t.projectId);C&&(G=C.publicKey,r.info(`[cred-channel] key fingerprint: ${C.fingerprint}`))}catch(C){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${C instanceof Error?C.message:String(C)}`)}let E={type:"register",projectId:t.projectId,platformVersion:Xe,protocolVersion:ht,accountId:M.accountId,accountLabel:M.label,origin:B,inFlightActionIds:[...d],...X?{accountEmail:X}:{},...B==="farm"&&D?{farmId:D}:{},...G?{sealPublicKey:G}:{}};h.send(JSON.stringify(E))}),h.on("message",async M=>{let B=M.toString("utf-8");if(B==="pong"||B==="ping")return;let D;try{D=JSON.parse(B)}catch{return}if(!D||typeof D!="object")return;let X=D.type;if(X==="registered"){let E=D;if(E.ok){if(r.info(`[ws] registered for project ${E.projectId}`),n({kind:"registered",projectId:E.projectId??t.projectId}),v.start(),S?.start(),U?.start(),I(),Il(t,o,r),o?.contextDir){try{let C=Ci(o.contextDir,t.projectId);h.readyState===h.OPEN&&h.send(JSON.stringify(C)),C.outdated&&(r.warn(`[ctx] context format outdated: v${C.templateVersion} \u2192 v${C.currentVersion}`+(C.missingPaths.length>0?` (missing: ${C.missingPaths.join(", ")})`:"")),u||(u=!0,O().catch(()=>{})))}catch(C){r.warn(`[ctx] context-format detect failed (non-fatal): ${C instanceof Error?C.message:String(C)}`)}ee(),Pe(!0)}}else r.warn(`[ws] register rejected: ${E.reason??"unknown"}`),n({kind:"register_rejected",reason:E.reason??"unknown"}),l=!0,h.close();return}if(X==="hello"){let E=D;w=Jn(E.protocolVersion);let C=w?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${E.platformVersion} (protocol ${E.protocolVersion}) \u2014 ${C}`),w||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Xe}, protocol ${ht}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Rl}`),n({kind:"incompatible",hubVersion:typeof E.platformVersion=="string"?E.platformVersion:null,hubProtocol:typeof E.protocolVersion=="number"?E.protocolVersion:null,updateCommand:Rl}));return}if(X==="tracking_targets"){v.setTargets(D.targets),S?.poke();return}if(X==="youtrack_sync_request"){R.setRequest(D);return}if(X==="youtrack_force_sync"){R.forceSync();return}if(X==="sync_local"){await aT(D,o,h,r);return}if(X==="provision_repo"){let E=D;r.info(`[repo] provision_repo: ${E.repo.name} (${E.repo.host}:${E.repo.owner}/${E.repo.repoName})`),await iT(t,o,E.repo,r),await Il(t,o,r);return}if(X==="remove_repo"){let E=D;r.info(`[repo] remove_repo: ${E.repoName}${E.purge?" (purge)":""}`),await Il(t,o,r),E.purge&&sT(t,o,E.repoName,r);return}if(X==="context_write"){await cT(D,o,h,r),i();return}if(X==="adr_promote"){await lT(D,o,h,r),i();return}if(X==="cred_update"){let E=D,C=Y(t.projectId),T=C?.sealKey?await em(t.projectId,E.kind,E.sealed,C.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},P={type:"cred_update_result",updateId:E.updateId,projectId:t.projectId,ok:T.ok,...T.detail?{detail:T.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(P)),T.ok?(r.info(`[cred] ${E.kind} replaced${T.detail?` \u2014 ${T.detail}`:""}`),b()):r.warn(`[cred] ${E.kind} replacement rejected: ${T.detail??"unknown"}`);return}if(X==="readiness_check"){r.info("[readiness] on-demand check requested"),b();return}if(X==="agent_login_start"){Zp(t,h,D,r,b);return}if(X==="move_to_farm"){let E=D;r.info(`[farm-move] request to move ${t.projectId} onto farm ${E.farmName} (${E.farmId})`);let C=await Lh(t,E,o?.contextDir,r);h.readyState===h.OPEN&&h.send(JSON.stringify(C)),C.ok?r.info(`[farm-move] done \u2014 farm daemon ${C.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${C.error??"unknown error"}`);return}if(X==="gh_runner_setup"){let E=D;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${E.runnerName} (${E.runnerId})`);let C=await Kh(t,E,r);h.readyState===h.OPEN&&h.send(JSON.stringify(C)),C.ok?r.info(`[ghr] runners connected on ${E.runnerName}`):r.warn(`[ghr] setup failed: ${C.error??"see per-repo statuses"}`);return}if(X==="gh_runner_teardown"){let E=D;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${E.runnerName} (${E.runnerId})`);let C=await Hh(t,E,r);h.readyState===h.OPEN&&h.send(JSON.stringify(C)),C.ok?r.info(`[ghr] runners disconnected from ${E.runnerName}`):r.warn(`[ghr] teardown failed: ${C.error??"unknown error"}`);return}if(X==="tracker_fields_request"){let E=D,C={type:"tracker_fields_result",requestId:E.requestId,projectId:t.projectId,ok:!1},T=Ct({contextDir:o?.contextDir??null});if(!T.ok)C.error=T.error;else try{C.fields=await T.provider.fetchStateFields(E.projectKey),C.ok=!0}catch(P){C.error=P instanceof Error?P.message:String(P)}h.readyState===h.OPEN&&h.send(JSON.stringify(C)),C.ok||r.warn(`[yt-fields] listing failed: ${C.error??"unknown"}`);return}if(X==="project_secret_update"||X==="project_secret_delete"){let E=D,C;if(E.type==="project_secret_update"){let P=Y(t.projectId);C=P?.sealKey?Vh(t.projectId,E.name,E.sealed,P.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else C=Xh(t.projectId,E.name);let T={type:"project_secret_update_result",updateId:E.updateId,projectId:t.projectId,ok:C.ok,...C.detail?{detail:C.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(T)),C.ok?(r.info(`[secret] ${E.name} ${E.type==="project_secret_update"?"saved":"deleted"}`+(C.detail?` \u2014 ${C.detail}`:"")),b()):r.warn(`[secret] ${E.name} rejected: ${C.detail??"unknown"}`);return}if(X==="sandbox_keys"){let E=Y(t.projectId);if(!E){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let C=an(t.projectId),T=Vf(D,E,C,r);for(let P of T)h.readyState===h.OPEN&&h.send(JSON.stringify(P));return}if(X!=="dispatch_action")return;let G=D;if(w===!1){let E=`refused: HUB protocol incompatible with CLI v${Xe} (protocol ${ht})`;h.send(JSON.stringify({type:"action_result",actionId:G.actionId,status:"failed",error:E})),r.warn(`[exec] ${G.actionId} (${G.action.type}) \u2192 REFUSED: ${E}`),r.warn(`[exec] update the CLI to clear this: ${Rl}`),n({kind:"action",actionId:G.actionId,actionType:G.action.type,ok:!1,error:E});return}if(G.action.type==="model_drift"){d.add(G.actionId);try{let E,C=o?.repos.find(T=>T.name===G.action.repoName);if(!o?.contextDir||!C)E={status:"failed",error:"no local workspace/repo clone on this CLI"};else try{let{computeDriftReport:T}=await Promise.resolve().then(()=>(fg(),pg)),P=C.mountAs==="."?o.root:Or(o.root,C.mountAs);E={status:"done",result:{report:await T(P,o.contextDir,C.name)}}}catch(T){E={status:"failed",error:T instanceof Error?T.message:String(T)}}h.send(JSON.stringify({type:"action_result",actionId:G.actionId,...E}))}finally{d.delete(G.actionId)}return}if(G.action.type==="model_bootstrap"){d.add(G.actionId);try{let E;try{let C=await Nt();E={status:"done",result:{repos:C.repos,events:C.events}}}catch(C){E={status:"failed",error:C instanceof Error?C.message:String(C)},r.warn(`[model] bootstrap failed: ${E.error}`)}h.readyState===h.OPEN&&h.send(JSON.stringify({type:"action_result",actionId:G.actionId,...E}))}finally{d.delete(G.actionId)}return}d.add(G.actionId);try{let E=await kh({action:G.action,repo:G.repo,trackerIssueId:G.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:U?()=>U.reportNow():void 0,refreshContextStatus:o?.contextDir?O:void 0,onRunActivity:y}).catch(P=>({status:"failed",error:P instanceof Error?P.message:String(P)}));G.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:G.actionId,...E}));let C=E.status!=="failed",T=!C&&"error"in E?E.error:void 0;C?r.info(`[exec] ${G.actionId} (${G.action.type}) \u2192 done`):r.warn(`[exec] ${G.actionId} (${G.action.type}) \u2192 FAILED: ${T??"?"}`),n({kind:"action",actionId:G.actionId,actionType:G.action.type,ok:C,...T?{error:T}:{}}),C&&["apply_delivery","context_write","create_pr"].includes(G.action.type)&&le(),C&&["merge_pr","merge_branch"].includes(G.action.type)&&Pe(!0)}finally{d.delete(G.actionId)}}),h.on("close",(M,B)=>{let D=B?.toString("utf-8")??"";if(r.info(`[ws] closed code=${M}${D?` reason=${D}`:""}`),v.stop(),S?.stop(),R.stop(),U?.stop(),N(),clearInterval(Be),Ue&&clearTimeout(Ue),K&&clearTimeout(K),D==="replaced"){l=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:M}),!l&&setTimeout(()=>{g=k()},2e3)}),h.on("error",M=>r.warn(`[ws] error: ${M.message}`)),h}return{stop(){l=!0,g.close()}}}async function Il(t,e,r){try{let n=await se(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=vo(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 iT(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?Or(e.root,o):_e(t.projectId,r.name);if(mg(Or(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await nT().clone(e?ji(r):Fc(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 sT(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?Or(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(!mg(Or(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{rT(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 aT(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=Or(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await tf(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 cT(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 lT(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 gf(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 Cl(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}je();pe();Ft();Pl();wt();Oi();async function Tg(t={profile:void 0}){let{cfg:e,profile:r}=sn(t.profile),n=Y(e.projectId);n&&po(n),xo(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),So(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),Eo(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=Mo(_l(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=mi("CLI_LOG",i,o);if(s.enabled){let d=new ln(s);hi(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=nn(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=Mo(_l(),".codepipe",r?Mo("profiles",r,"context"):"context");if(await ml(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await Sg(()=>gs({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 ml(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=Mo(_l(),".codepipe",r?Mo("profiles",r,"context-config"):"context-config");Si(a.contextDir,m,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=ms(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(`
1017
- [${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}Ln();He();je();async function Mw(t={profile:void 0}){let e=st(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=rs(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`)")}Yo();import{readFileSync as EA}from"node:fs";F();He();Ft();Ho();Pr();Jt();Cr();je();pe();function xe(t){throw new Error(t)}function Ie(t,e){return(typeof t!="string"||t.trim().length===0)&&xe(`config: '${e}' must be a non-empty string`),t.trim()}function Xo(t,e){if(t==null)return;typeof t!="string"&&xe(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function TA(t){(!t||typeof t!="object")&&xe("config: expected a JSON object");let e=t,r=Ie(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||xe("config: 'hubUrl' must start with http(s)://");let n=Ie(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&xe("config: 'project' is required");let i=o,s=Ie(i.id,"project.id");Yt.test(s)||xe("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=Ie(i.name,"project.name"),c=Ie(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&xe("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||xe("config: 'project.repos' must be an array");let u=l.map((w,v)=>{(!w||typeof w!="object")&&xe(`config: project.repos[${v}] must be an object`);let S=w,R=Ie(S.host,`project.repos[${v}].host`);R!=="github"&&R!=="bitbucket"&&R!=="gitlab"&&xe(`config: project.repos[${v}].host must be 'github', 'bitbucket' or 'gitlab'`);let $={name:Ie(S.name,`project.repos[${v}].name`),host:R,owner:Ie(S.owner,`project.repos[${v}].owner`),repoName:Ie(S.repoName,`project.repos[${v}].repoName`)},b=Xo(S.defaultBranch,`project.repos[${v}].defaultBranch`);b&&($.defaultBranch=b);let I=Xo(S.mountAs,`project.repos[${v}].mountAs`);return I&&($.mountAs=I),$}),p=i.contextRepo;(!p||typeof p!="object")&&xe("config: 'project.contextRepo' is required");let d=p,m=Xo(d.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&xe("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:m,owner:Ie(d.owner,"project.contextRepo.owner"),name:Xo(d.name,"project.contextRepo.name")??Et(s)},g={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:f}},k=Xo(i.youtrackProjectKey,"project.youtrackProjectKey");if(k&&(g.project.youtrackProjectKey=k),i.index!==void 0&&(typeof i.index!="boolean"&&xe("config: 'project.index' must be a boolean"),g.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&xe("config: 'project.youtrackWrites' must be a boolean"),g.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let w=Ie(i.llmProvider,"project.llmProvider");w==="codex"&&xe(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),w!=="claude"&&xe("config: 'project.llmProvider' must be 'claude'"),g.project.llmProvider=w}let h=e.secrets;if(h!==void 0){(typeof h!="object"||h===null)&&xe("config: 'secrets' must be an object");let w=h,v={};if(w.github){let S=w.github;v.github={token:Ie(S.token,"secrets.github.token")}}if(w.bitbucket){let S=w.bitbucket;v.bitbucket={email:Ie(S.email,"secrets.bitbucket.email"),apiToken:Ie(S.apiToken,"secrets.bitbucket.apiToken")}}if(w.gitlab){let S=w.gitlab;v.gitlab={token:Ie(S.token,"secrets.gitlab.token")}}if(w.youtrack){let S=w.youtrack;v.youtrack={url:Ie(S.url,"secrets.youtrack.url").replace(/\/$/,""),token:Ie(S.token,"secrets.youtrack.token")}}if(w.contextWrite){let S=w.contextWrite;v.contextWrite={token:Ie(S.token,"secrets.contextWrite.token")}}g.secrets=v}return g}async function RA(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function IA(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await zt(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${n}`)}if(e.bitbucket){let r=t.project.repos.find(i=>i.host==="bitbucket"),n=r?.owner??(t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:void 0),o=await Vt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await ki(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 Xt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Qt({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 RA():EA(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){xe(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=TA(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 IA(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 Mn(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??cn(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){xe(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let u;try{u=await ir(o,i,a)}catch(d){if(d instanceof W&&d.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await se(o,i,s.id);else if(d instanceof W)xe(`HUB \u2192 ${d.status} ${d.message}`);else throw d}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let p={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(ae(p),Ut({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Tt(s.id)}`),tr(s.id,It(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,s.llmProvider??Je),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await Oo(o,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${d}); runs once a SANDBOX claims it.`)}catch(d){console.warn(`could not enqueue index job: ${d instanceof Error?d.message:String(d)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}He();pe();import{cancel as Kk,intro as Hk,isCancel as Wk,log as pu,outro as CA,password as qk}from"@clack/prompts";async function AA(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Yk(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await AA(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Hk("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),pu.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await qk({message:"Claude OAuth token"});Wk(i)&&(Kk("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),ap({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${fi()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=st(t.profile);if(!e){Hk(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),pu.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await qk({message:"Claude OAuth token"});Wk(i)&&(Kk("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=Y(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},ae(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(pu.success("Claude OAuth token saved."),CA("It will be sealed into job bundles when a SANDBOX (re)connects."))}Lo();F();He();Ft();Ho();Pr();js();je();pe();import{cancel as PA,confirm as _A,intro as jA,isCancel as zk,log as Me,outro as NA,select as Vk,text as hr}from"@clack/prompts";function Xk(t){PA(t),process.exit(1)}function Gn(t){return zk(t)&&Xk("aborted"),t}function Jo(t){return zk(t)&&Xk("aborted"),typeof t=="string"?t:""}async function OA(t,e){let r=Gn(await Vk({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=Jo(await hr({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=Jo(await hr({message:"Context Repo name",placeholder:Et(t),initialValue:Et(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function Jk(t={profile:void 0}){let e=st(t.profile);jA(`codepipe project add \u2192 ${e.hubUrl}`);let r=Gn(await hr({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>Yt.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=Gn(await hr({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=Gn(await Vk({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=Gn(await hr({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Gn(await _A({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=Jo(await hr({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:h=>!h||!h.trim()||ze(h)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!d)break;let m=ze(d);Me.message(`${m.host}: ${m.owner}/${m.repoName}`);let f=Jo(await hr({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=Jo(await hr({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 OA(r,a),u=Y(e.projectId);Me.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await Mn(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??cn(),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 ir(e.hubUrl,e.cliToken,c);Me.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),tr(r,It(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}`),NA("done")}catch(d){d instanceof W?(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)}}Ln();He();je();pe();wt();Yo();import{existsSync as LA,rmSync as MA}from"node:fs";import{confirm as DA,intro as UA,isCancel as BA,log as gr,outro as FA,spinner as GA}from"@clack/prompts";function jt(t){gr.error(t),process.exit(1)}var Zk=t=>t.trim().replace(/\/+$/,"");async function Qk(t){UA("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Ae()?.spec.projectId??void 0;e||jt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=kt(e);r||jt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Zk(r.hubUrl),o=r.projectId,i=Zk(t.hub);i.startsWith("http")||jt("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&jt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let h=GA();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 W&&jt(`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||jt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=Y(o),p=(t.account??r.accountEmail??await Bn()).trim().toLowerCase();if(gr.message(`move project '${o}'
1034
+ ${e.body}`),le({prNumber:e.prNumber,inline:!1,host:s.name})}case"tracker_status":{let i=Pt({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),le({issueId:t.trackerIssueId,newStatus:e.newStatus})):Z("no tracker_issue_id provided"):Z(i.error)}case"tracker_comment":{let i=Pt({contextDir:t.contextDir});if(!i.ok)return Z(i.error);if(!t.trackerIssueId)return Z("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return le({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Pt({contextDir:t.contextDir});if(!i.ok)return Z(i.error);if(!e.projectKey)return Z("no projectKey in create_tracker_issue action");let{id:s,key:a}=await i.provider.createIssue({projectKey:e.projectKey,title:e.title,body:e.body,targetStatus:e.targetStatus});return le({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Pt({contextDir:t.contextDir});if(!i.ok)return Z(i.error);let s=0;for(let a of e.links)try{await i.provider.applyLink(a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return Z(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return le({applied:s})}case"set_project_setting":{if(!t.contextDir)return Z("no context repo clone on this CLI");let i=await Nm(t.contextDir,e.edits);return le({files:i.files})}case"set_prompt_override":{if(!t.contextDir)return Z("no context repo clone on this CLI");if(!ec(e.role))return Z(`unknown prompt operation: ${e.role}`);let i=tc(e.role);return await Ie(t.contextDir,[e.content===null?{path:i,content:"",deleted:!0}:{path:i,content:e.content}],e.commitMessage),t.requestConfigReport?.(),le({path:i,reset:e.content===null})}case"tracker_edit":{let i=Pt({contextDir:t.contextDir});if(!i.ok)return Z(i.error);if(!t.contextDir)return Z("no context repo clone on this CLI");await i.provider.editIssue(e.issueKey,{...e.title!==void 0?{title:e.title}:{},...e.body!==void 0?{body:e.body}:{}});let s=await i.provider.getIssue(e.issueKey);return s&&await os(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),le({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return Z("no context repo clone on this CLI");let i=await Km(t.contextDir,e);return le({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return Z("no context repo clone on this CLI");let i=await Fm(t.contextDir,e);return le({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),le({reported:!0})):Z("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return Z("no context repo clone on this CLI");let i=await t.refreshContextStatus();return le({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return Z("no project workspace on this CLI");if(!r)return Z("no repo spec");if(!t.onRunActivity)return Z("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=Ci(t.contextDir),c=s.find(m=>m.id===e.actionId);if(!c){let m=a.find(f=>f.file===`actions/${e.actionId}.yml`);return Z(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=Ga(c,e.input);if(!l.ok)return Z(l.error);let u=jf(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),Lo(`${e.projectId}/${r.name}`,async()=>{await ir(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=_e(e.projectId,r.name,t.baseDir),f=await Pm({cwd:m,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:g=>i(e.runId,g)});return le({runId:e.runId,status:f.status,exitCode:f.exitCode,...f.failedStep?{failedStep:f.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return Z("no context repo clone on this CLI");let i=jm(t.contextDir,e.path);return le({path:e.path,...i})}case"search_model":{if(!t.contextDir)return Z("no context repo clone on this CLI");let{searchModelIndex:i}=await Promise.resolve().then(()=>(jo(),_o)),s=await i(t.contextDir,e.q,e.limit);return le({hits:s})}case"model_drift":return Z("model_drift requires a local workspace (handled by the daemon)");case"model_bootstrap":return Z("model_bootstrap requires a local workspace (handled by the daemon)");default:return Z(`unsupported action type: ${e.type}`)}}catch(i){return Z(i instanceof Error?i.message:String(i))}}function le(t){return{status:"done",result:t}}function Z(t){return{status:"failed",error:t}}ut();Rl();je();de();import{existsSync as ag,readFileSync as cg}from"node:fs";import{join as lg}from"node:path";async function ug(t,e,r,n){let o=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return o(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=We(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");ls(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=lg(r,"project.yaml"),m=lg(r,"regimen.yaml");ag(d)&&ag(m)?c={projectYaml:cg(d,"utf-8"),regimenYaml:cg(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=Kt(e.farmPublicKey,JSON.stringify(l));cs(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let p=await ds(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:u});return p.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...p.daemonStatus?{daemonStatus:p.daemonStatus}:{}}:o(p.error??"farm provisioning failed")}catch(i){return o(i instanceof Error?i.message:String(i))}}D();ut();Ke();ut();import{homedir as hR}from"node:os";import{existsSync as gR,mkdirSync as yR,readFileSync as wR,writeFileSync as bR}from"node:fs";import{dirname as kR,join as vR}from"node:path";function Cl(){return Q("RUNNER_PINS")??vR(hR(),".codepipe","runner-pins.json")}function dg(){let t=Cl();if(!gR(t))return{};try{return JSON.parse(wR(t,"utf-8"))}catch{return{}}}function $R(t){let e=Cl();yR(kR(e),{recursive:!0}),bR(e,JSON.stringify(t,null,2)+`
1035
+ `,{mode:384})}function xR(t){return dg()[t]}function Pl(t,e){let r=dg();r[t]=e,$R(r)}function pg(t,e){let r=We(e),n=xR(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 ${Cl()}.`);return r}je();de();var mg=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function fg(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:mg(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 SR={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:mg(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)=>fg(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>fg(t,e,r,"remove-token")},hg={api:SR,fetchProject:se,provisionOnRunner:Xh,teardownOnRunner:Jh};async function gg(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(We(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");pg(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 yg(t,e,r,n=hg){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 gg(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:[ac(e.runnerId)]},c=Kt(e.runnerPublicKey,JSON.stringify(a));Pl(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 wg(t,e,r,n=hg){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 gg(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=Kt(e.runnerPublicKey,JSON.stringify(c));Pl(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();D();import{existsSync as ER}from"node:fs";import{join as bg}from"node:path";import{simpleGit as vg}from"simple-git";async function Al(t,e,r,n,o){for(let i of r.repos){let s=e.find(u=>u.name===i.repoName);if(!s)continue;let a=`${r.taskKey}:${s.name}:${i.branchName}`;if(!Yt(i.branchName)){n.has(a)||(n.add(a),o.warn(`[pull] ${r.taskKey} ${s.mountAs}: refusing suspicious branch name`));continue}let c=bg(t,s.mountAs);if(!ER(bg(c,".git")))continue;let l=vg(c);try{let u=await IR(l,i.branchName);await l.fetch(await RR(l,s),`refs/heads/${i.branchName}`);let p=(await l.revparse(["FETCH_HEAD"])).trim();if(u===p)continue;if(await TR(l,c,i.branchName)){n.has(a)||(n.add(a),o.info(`[pull] ${r.taskKey} \u2192 ${s.mountAs}: ${i.branchName} is checked out here \u2014 fetched ${p.slice(0,10)}; merge or pull it in that checkout yourself`));continue}await l.raw(["branch","-f",i.branchName,p]),o.info(`[pull] ${r.taskKey} \u2192 ${s.mountAs}: ${i.branchName} ${p.slice(0,10)} (checkout untouched)`)}catch(u){if(n.has(a))continue;n.add(a),o.warn(`[pull] ${r.taskKey} ${s.mountAs}: ${i.branchName} unavailable \u2014 `+(u instanceof Error?u.message.split(`
1036
+ `)[0]:String(u)))}}}async function RR(t,e){if(e.mirror)return kg(e.mirror);try{if((await t.getRemotes(!0)).find(n=>n.name==="origin")?.refs?.fetch)return"origin"}catch{}return e.host&&e.owner&&e.repoName?kg({host:e.host,owner:e.owner,repoName:e.repoName}):"origin"}function kg(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 TR(t,e,r){try{return(await t.raw(["worktree","list","--porcelain"])).split(`
1037
+ `).some(o=>o.trim()===`branch refs/heads/${r}`)}catch{try{return(await vg(e).revparse(["--abbrev-ref","HEAD"])).trim()===r}catch{return!1}}}async function IR(t,e){try{return(await t.revparse([e])).trim()}catch{return null}}var ms=class{constructor(e,r,n,o){this.intervalMs=e;this.fetchDeliverables=r;this.workspace=n;this.log=o}timer=null;running=!1;caughtUp=!1;warned=new Set;start(){if(this.timer)return;this.log.info(`[pull] local delivery started (interval=${this.intervalMs}ms)`);let e=()=>void this.runOnce();e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[pull] local delivery stopped"))}poke(){this.runOnce()}async runOnce(){if(!this.running){this.running=!0;try{let e=await this.fetchDeliverables(),r=this.caughtUp?e.filter(n=>n.phase==="TRACKING"||n.phase==="AWAITING_CLUSTER"):e;for(let n of r)await Al(this.workspace.root,this.workspace.repos,n,this.warned,this.log);this.caughtUp=!0}catch(e){this.log.warn(`[pull] pass failed: ${e instanceof Error?e.message:String(e)}`)}finally{this.running=!1}}}};D();ut();de();var $g=16*1024;function CR(t){return Ze.test(t)?Dt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Ze}`}function xg(t,e,r,n){let o=CR(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(En(n,r).toString("utf-8"));if(typeof s.value!="string"||s.value.length===0)return{ok:!1,detail:"payload has no value"};i=s.value}catch(s){return{ok:!1,detail:`cannot open the sealed secret (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}if(i.length>$g)return{ok:!1,detail:`secret value too large (max ${$g} chars)`};try{return Pp(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function Sg(t,e){try{return Ap(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)}}}hn();de();Zt();var hs=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}=wo(o,a.repoSpec);try{let u=await l.getPullRequest(c,a.number);n.push({number:a.number,repoName:a.repoSpec.name,url:a.url,state:u.state,merged:u.merged,ci:u.ci,mergeable:u.mergeable})}catch(u){if(u instanceof Ir){this.log.warn(`[track] task=${e} pr=${a.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${a.url} fetch failed: ${u instanceof Error?u.message:String(u)}`);return}}let i=n.map(a=>`${a.repoName??""}#${a.number}:${a.state}:${a.merged?1:0}:${a.ci}:${a.mergeable}`).join("|");if(this.lastSig.get(e)===i)return;for(let a=0;a<n.length;a++){let c=n[a];if(c.ci!=="failed")continue;let{spec:l,host:u}=wo(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=PR(n);this.log.info(`[track] task=${e} snapshot signalled${s?` \u2192 ${s}`:""} (${n.length} PR(s))`)}};function PR(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}D();Sn();var gs=class{constructor(e,r,n,o=i=>Bi(xn(i))){this.intervalMs=e;this.send=r;this.log=n;this.listBranches=o}projectId="";repos=[];lastSig=new Map;timer=null;running=!1;setRepos(e,r){this.projectId=e,this.repos=r,this.lastSig.clear()}start(){if(this.timer)return;this.log.info(`[branches] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[branches] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs),typeof this.timer.unref=="function"&&this.timer.unref()}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[branches] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let e of this.repos)await this.processRepo(e)}finally{this.running=!1}}}async processRepo(e){let r=e.gitFlow;if(!r||r.flow==="simple")return;let n;try{n=await this.listBranches(e)}catch(s){this.log.warn(`[branches] repo=${e.name} ls-remote failed: ${s instanceof Error?s.message:String(s)}`);return}let o=n.filter(s=>fc(s,r)).sort(),i=o.join("|");this.lastSig.get(e.name)!==i&&(this.send({type:"branches_observation",projectId:this.projectId,repoName:e.name,branches:o}),this.lastSig.set(e.name,i),this.log.info(`[branches] repo=${e.name} reported ${o.length} base candidate(s)`))}};D();var ys=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??(()=>Pt({contextDir:this.options.contextDir})))();if(!r.ok){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn(`[yt-sync] tracker provider unavailable (${r.error}) \u2014 poller idle.`));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,r.provider)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let x=e.stageField?{stageField:e.stageField}:{},b=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},E=(e.backlogScope??"personal")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(E){let v=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[I,j]=await Promise.all([v.length>0?r.listIssues({projectKey:e.projectKey,columns:v,...x,...b}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...x})]),G=new Map;for(let z of[...I,...j])G.set(z.id,z);o=[...G.values()]}else{let v=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:v,...x,...b})}}catch(x){let b=x instanceof Error?x.message:String(x);b.includes("stage_field")?this.log.warn(`[yt-sync] CONFIGURATION ERROR \u2014 ${b}`):this.log.warn(`[yt-sync] listIssues failed: ${b}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let x of o){if(s.add(x.id),a.has(x.status))continue;let b=await Tg(r,x.id,e.sinceMs,this.log);b&&i.set(x.id,b)}let c=[];for(let x of e.offBoardIssueIds){if(s.has(x))continue;let b=await Tg(r,x,e.sinceMs,this.log);b&&b.length>0&&i.set(x,b);let T=await Rg(r,x,e.stageField,this.log);if(T)c.push(T);else if(b&&b.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}let l=o.filter(x=>!a.has(x.status)),{attachmentsByIssue:u,attachmentKeys:p}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let d=[...l,...c].map(x=>({issue:x,comments:i.get(x.id)??[],attachments:u.get(x.id)??[]}));d.push(...await Mh(this.options.contextDir,d,x=>Rg(r,x,e.stageField,this.log)));try{await os(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let x of p)this.shippedAttachments.add(x)}catch(x){let b=x instanceof Error?x.message:String(x);this.abandonTick(`context task sync failed: ${b}`);return}let m=this.options.isSelfComment??(()=>!1),f=[],g=[];for(let[x,b]of i){let T=b.filter(v=>!m(v.id));if(T.length===0)continue;f.push({issueId:x,comments:T.map(AR)});let E=T.flatMap(v=>{let I=Er(v.body);return I?[{commentId:v.id,author:v.author,name:I.name,args:I.args,createdAt:v.createdAt}]:[]});E.length>0&&g.push({issueId:x,commands:E})}let w={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Eg),commentsBatch:f,...g.length>0?{commandsBatch:g}:{},...c.length>0?{offBoardIssues:c.map(Eg)}:{},observedAtMs:n};this.send(w);let h=f.reduce((x,b)=>x+b.comments.length,0),k=g.reduce((x,b)=>x+b.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${h} commands=${k} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let p=`${s.id}:${u.id}`;if(this.shippedAttachments.has(p))continue;let d;try{d=await n.downloadAttachment(u.url)}catch(f){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${f instanceof Error?f.message:String(f)}`);continue}let m=_R(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 Eg(t){let{description:e,...r}=t;return r}function AR(t){let{body:e,...r}=t;return r}function _R(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 Rg(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 Tg(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 zR(t,e){let r=t.repos.filter(i=>i.mirror);if(r.length===0)return[];let{mirrorLag:n}=await Promise.resolve().then(()=>(ss(),is)),o=[];for(let i of r){let s=i.mountAs==="."?t.root:Lr(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 Fl="npm i -g @code-partner/codepipe@latest";function xs(t,e={}){let r=e.log??{info:h=>console.log(h),warn:h=>console.warn(h)};r.info(`codepipe-cli v${Xe} (protocol ${ht})`);let n=h=>e.onEvent?.(h),o=e.workspace;o?.contextDir&&Lf(o.contextDir,r);let i=()=>{if(o?.contextDir)try{bn(o.contextDir,o.root,r)}catch(h){r.warn(`[skills] materialize failed (non-fatal): ${h instanceof Error?h.message:String(h)}`)}};i();let s=Kl("CLI_TRACKING_POLL_INTERVAL_SEC"),a=Kl("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=w();function w(){let h=us(t.hubUrl,t.cliToken),k=null,x=new hs(s,M=>{h.readyState===h.OPEN&&h.send(JSON.stringify(M))},r),b=new gs(s,M=>{h.readyState===h.OPEN&&h.send(JSON.stringify(M))},r),T=o&&o.repos.length>0?new ms(Kl("CLI_LOCAL_PULL_INTERVAL_SEC"),()=>fs(t.hubUrl,t.cliToken,t.projectId),{root:o.root,repos:o.repos},r):null,E=new ys(a,M=>{h.readyState===h.OPEN&&h.send(JSON.stringify(M))},r,{contextDir:o?.contextDir??null,isSelfComment:M=>f.has(M)}),v=null,I=async()=>{try{let M={trackerProvider:xl(o?.contextDir??null)};try{let R=await se(t.hubUrl,t.cliToken,t.projectId);M={...M,repos:R.repos,contextRepo:R.contextRepo},b.setRepos(t.projectId,R.repos)}catch(R){r.warn(`[readiness] could not fetch project summary for push checks: ${R instanceof Error?R.message:String(R)}`)}let B=await vf(t.projectId,M),L=o?await zR(o,r):[];if(i(),h.readyState!==h.OPEN)return;let ee={type:"cli_readiness",projectId:t.projectId,ready:B.ready,checks:B.checks,creds:B.creds,secretNames:_p(t.projectId),...o?{mirrors:L}:{},checkedAt:B.checkedAt};if(h.send(JSON.stringify(ee)),B.ready)r.info("[readiness] ready");else{let R=B.checks.filter($=>!$.ok).map($=>`${$.name}(${$.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${R.join(", ")}`)}let F=Tf(B.creds,p);if(F==="open"){p=!0;let R=If(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${R}`),Ar(R)}else F==="rearm"&&(p=!1)}catch(M){r.warn(`[readiness] check failed: ${M instanceof Error?M.message:String(M)}`)}},j=()=>{I(),v=setInterval(()=>void I(),c),typeof v.unref=="function"&&v.unref()},G=()=>{v&&(clearInterval(v),v=null)},z=150,A=new Map,y=M=>{let B=A.get(M);if(!B||(B.timer&&clearTimeout(B.timer),A.delete(M),B.events.length===0||h.readyState!==h.OPEN))return;let L={type:"run_activity",projectId:t.projectId,runId:M,events:B.events};h.send(JSON.stringify(L))},U=(M,B)=>{let L=A.get(M);if(L||(L={events:[],timer:null},A.set(M,L)),L.events.push(B),B.kind==="result"){y(M);return}L.timer||(L.timer=setTimeout(()=>y(M),z),L.timer.unref?.())},N=o?.contextDir?new Pi(o.contextDir,t.projectId,M=>{h.readyState===h.OPEN&&h.send(JSON.stringify(M))},r):null,H=async()=>{let M=o?.contextDir;if(!M)throw new Error("no context repo clone on this CLI");let B;try{B=(await se(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let L=await cm(M,t.projectId,B,r);return h.readyState===h.OPEN&&h.send(JSON.stringify(L)),L},X=null,ue=async()=>{let M=o?.contextDir;if(M)try{let{readContextIndexHub:B,collectSearchRows:L}=await Promise.resolve().then(()=>(jo(),_o));if(B(M)!=="metadata")return;let ee=L(M);h.readyState===h.OPEN&&(h.send(JSON.stringify({type:"model_index",projectId:t.projectId,rows:ee})),r.info(`[model] tier-2 index snapshot pushed (${ee.length} rows)`))}catch(B){r.warn(`[model] tier-2 index push failed (non-fatal): ${B instanceof Error?B.message:String(B)}`)}},xt=()=>{X&&clearTimeout(X),X=setTimeout(()=>void ue(),5e3)},pt=async()=>{if(!o?.contextDir)throw new Error("no Context Repo clone on this CLI");if(m)throw new Error("model bootstrap is already running");m=!0;try{let M=await se(t.hubUrl,t.cliToken,t.projectId),{bootstrapDaemonModel:B}=await Promise.resolve().then(()=>(Bo(),$s)),L=await B(t.projectId,{root:o.root,contextDir:o.contextDir},M.repos,ee=>r.info(`[model] ${ee}`));return r.info(`[model] bootstrap done: ${L.repos} repos, ${L.events} task events`),xt(),L}finally{m=!1}},Re=null,Ae=async M=>{if(o?.contextDir)try{let B=await Promise.resolve().then(()=>(Bo(),$s)),L={root:o.root,contextDir:o.contextDir,repos:o.repos};if(B.shouldAutoBootstrapModel(o.contextDir)){await B.syncWorkspaceMirrors(L,F=>r.info(F));try{await pt()}catch(F){r.warn(`[model] auto-bootstrap failed (non-fatal): ${F instanceof Error?F.message:String(F)}`)}return}(await B.rebuildWorkspaceModelIfStale(L,{fetch:M,onLog:F=>r.info(F)})).rebuilt.length>0&&xt()}catch(B){r.warn(`[model] release-path rebuild failed (non-fatal): ${B instanceof Error?B.message:String(B)}`)}},Oe=M=>{Re&&clearTimeout(Re),Re=setTimeout(()=>void Ae(M),6e4)},Be=setInterval(()=>void Ae(!0),6*36e5);return h.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let M=Bp(t.projectId),B=Q("ORIGIN")==="farm"?"farm":"local",L=Q("FARM_ID"),ee=t.accountEmail??M.email,F;try{let $=Rm(t.projectId);$&&(F=$.publicKey,r.info(`[cred-channel] key fingerprint: ${$.fingerprint}`))}catch($){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${$ instanceof Error?$.message:String($)}`)}let R={type:"register",projectId:t.projectId,platformVersion:Xe,protocolVersion:ht,accountId:M.accountId,accountLabel:M.label,origin:B,inFlightActionIds:[...d],...ee?{accountEmail:ee}:{},...B==="farm"&&L?{farmId:L}:{},...F?{sealPublicKey:F}:{}};h.send(JSON.stringify(R))}),h.on("message",async M=>{let B=M.toString("utf-8");if(B==="pong"||B==="ping")return;let L;try{L=JSON.parse(B)}catch{return}if(!L||typeof L!="object")return;let ee=L.type;if(ee==="registered"){let R=L;if(R.ok){if(r.info(`[ws] registered for project ${R.projectId}`),n({kind:"registered",projectId:R.projectId??t.projectId}),x.start(),b.start(),T?.start(),N?.start(),j(),Gl(t,o,r),o?.contextDir){try{let $=Li(o.contextDir,t.projectId);h.readyState===h.OPEN&&h.send(JSON.stringify($)),$.outdated&&(r.warn(`[ctx] context format outdated: v${$.templateVersion} \u2192 v${$.currentVersion}`+($.missingPaths.length>0?` (missing: ${$.missingPaths.join(", ")})`:"")),u||(u=!0,H().catch(()=>{})))}catch($){r.warn(`[ctx] context-format detect failed (non-fatal): ${$ instanceof Error?$.message:String($)}`)}ue(),Oe(!0)}}else r.warn(`[ws] register rejected: ${R.reason??"unknown"}`),n({kind:"register_rejected",reason:R.reason??"unknown"}),l=!0,h.close();return}if(ee==="hello"){let R=L;k=ro(R.protocolVersion);let $=k?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${R.platformVersion} (protocol ${R.protocolVersion}) \u2014 ${$}`),k||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Xe}, protocol ${ht}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Fl}`),n({kind:"incompatible",hubVersion:typeof R.platformVersion=="string"?R.platformVersion:null,hubProtocol:typeof R.protocolVersion=="number"?R.protocolVersion:null,updateCommand:Fl}));return}if(ee==="tracking_targets"){x.setTargets(L.targets),T?.poke();return}if(ee==="youtrack_sync_request"){E.setRequest(L);return}if(ee==="youtrack_force_sync"){E.forceSync();return}if(ee==="sync_local"){await ZR(L,o,h,r);return}if(ee==="provision_repo"){let R=L;r.info(`[repo] provision_repo: ${R.repo.name} (${R.repo.host}:${R.repo.owner}/${R.repo.repoName})`),await XR(t,o,R.repo,r),await Gl(t,o,r);return}if(ee==="remove_repo"){let R=L;r.info(`[repo] remove_repo: ${R.repoName}${R.purge?" (purge)":""}`),await Gl(t,o,r),R.purge&&JR(t,o,R.repoName,r);return}if(ee==="context_write"){await QR(L,o,h,r),i();return}if(ee==="adr_promote"){await eT(L,o,h,r),i();return}if(ee==="cred_update"){let R=L,$=q(t.projectId),C=$?.sealKey?await Tm(t.projectId,R.kind,R.sealed,$.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},Y={type:"cred_update_result",updateId:R.updateId,projectId:t.projectId,ok:C.ok,...C.detail?{detail:C.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(Y)),C.ok?(r.info(`[cred] ${R.kind} replaced${C.detail?` \u2014 ${C.detail}`:""}`),I()):r.warn(`[cred] ${R.kind} replacement rejected: ${C.detail??"unknown"}`);return}if(ee==="readiness_check"){r.info("[readiness] on-demand check requested"),I();return}if(ee==="agent_login_start"){Rf(t,h,L,r,I);return}if(ee==="move_to_farm"){let R=L;r.info(`[farm-move] request to move ${t.projectId} onto farm ${R.farmName} (${R.farmId})`);let $=await ug(t,R,o?.contextDir,r);h.readyState===h.OPEN&&h.send(JSON.stringify($)),$.ok?r.info(`[farm-move] done \u2014 farm daemon ${$.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${$.error??"unknown error"}`);return}if(ee==="gh_runner_setup"){let R=L;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${R.runnerName} (${R.runnerId})`);let $=await yg(t,R,r);h.readyState===h.OPEN&&h.send(JSON.stringify($)),$.ok?r.info(`[ghr] runners connected on ${R.runnerName}`):r.warn(`[ghr] setup failed: ${$.error??"see per-repo statuses"}`);return}if(ee==="gh_runner_teardown"){let R=L;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${R.runnerName} (${R.runnerId})`);let $=await wg(t,R,r);h.readyState===h.OPEN&&h.send(JSON.stringify($)),$.ok?r.info(`[ghr] runners disconnected from ${R.runnerName}`):r.warn(`[ghr] teardown failed: ${$.error??"unknown error"}`);return}if(ee==="tracker_fields_request"){let R=L,$={type:"tracker_fields_result",requestId:R.requestId,projectId:t.projectId,ok:!1},C=Pt({contextDir:o?.contextDir??null});if(!C.ok)$.error=C.error;else try{$.fields=await C.provider.fetchStateFields(R.projectKey),$.ok=!0}catch(Y){$.error=Y instanceof Error?Y.message:String(Y)}h.readyState===h.OPEN&&h.send(JSON.stringify($)),$.ok||r.warn(`[yt-fields] listing failed: ${$.error??"unknown"}`);return}if(ee==="project_secret_update"||ee==="project_secret_delete"){let R=L,$;if(R.type==="project_secret_update"){let Y=q(t.projectId);$=Y?.sealKey?xg(t.projectId,R.name,R.sealed,Y.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else $=Sg(t.projectId,R.name);let C={type:"project_secret_update_result",updateId:R.updateId,projectId:t.projectId,ok:$.ok,...$.detail?{detail:$.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(C)),$.ok?(r.info(`[secret] ${R.name} ${R.type==="project_secret_update"?"saved":"deleted"}`+($.detail?` \u2014 ${$.detail}`:"")),I()):r.warn(`[secret] ${R.name} rejected: ${$.detail??"unknown"}`);return}if(ee==="sandbox_keys"){let R=q(t.projectId);if(!R){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let $=dn(t.projectId),C=$m(L,R,$,r);for(let Y of C)h.readyState===h.OPEN&&h.send(JSON.stringify(Y));return}if(ee!=="dispatch_action")return;let F=L;if(k===!1){let R=`refused: HUB protocol incompatible with CLI v${Xe} (protocol ${ht})`;h.send(JSON.stringify({type:"action_result",actionId:F.actionId,status:"failed",error:R})),r.warn(`[exec] ${F.actionId} (${F.action.type}) \u2192 REFUSED: ${R}`),r.warn(`[exec] update the CLI to clear this: ${Fl}`),n({kind:"action",actionId:F.actionId,actionType:F.action.type,ok:!1,error:R});return}if(F.action.type==="model_drift"){d.add(F.actionId);try{let R,$=o?.repos.find(C=>C.name===F.action.repoName);if(!o?.contextDir||!$)R={status:"failed",error:"no local workspace/repo clone on this CLI"};else try{let{computeDriftReport:C}=await Promise.resolve().then(()=>(Fg(),Bg)),Y=$.mountAs==="."?o.root:Lr(o.root,$.mountAs);R={status:"done",result:{report:await C(Y,o.contextDir,$.name)}}}catch(C){R={status:"failed",error:C instanceof Error?C.message:String(C)}}h.send(JSON.stringify({type:"action_result",actionId:F.actionId,...R}))}finally{d.delete(F.actionId)}return}if(F.action.type==="model_bootstrap"){d.add(F.actionId);try{let R;try{let $=await pt();R={status:"done",result:{repos:$.repos,events:$.events}}}catch($){R={status:"failed",error:$ instanceof Error?$.message:String($)},r.warn(`[model] bootstrap failed: ${R.error}`)}h.readyState===h.OPEN&&h.send(JSON.stringify({type:"action_result",actionId:F.actionId,...R}))}finally{d.delete(F.actionId)}return}d.add(F.actionId);try{let R=await Yh({action:F.action,repo:F.repo,trackerIssueId:F.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:N?()=>N.reportNow():void 0,refreshContextStatus:o?.contextDir?H:void 0,onRunActivity:U}).catch(Y=>({status:"failed",error:Y instanceof Error?Y.message:String(Y)}));F.action.type==="tracker_comment"&&R.status==="done"&&"result"in R&&typeof R.result?.commentId=="string"&&f.add(R.result.commentId),h.send(JSON.stringify({type:"action_result",actionId:F.actionId,...R}));let $=R.status!=="failed",C=!$&&"error"in R?R.error:void 0;$?r.info(`[exec] ${F.actionId} (${F.action.type}) \u2192 done`):r.warn(`[exec] ${F.actionId} (${F.action.type}) \u2192 FAILED: ${C??"?"}`),n({kind:"action",actionId:F.actionId,actionType:F.action.type,ok:$,...C?{error:C}:{}}),$&&["apply_delivery","context_write","create_pr"].includes(F.action.type)&&xt(),$&&["merge_pr","merge_branch"].includes(F.action.type)&&Oe(!0)}finally{d.delete(F.actionId)}}),h.on("close",(M,B)=>{let L=B?.toString("utf-8")??"";if(r.info(`[ws] closed code=${M}${L?` reason=${L}`:""}`),x.stop(),b.stop(),T?.stop(),E.stop(),N?.stop(),G(),clearInterval(Be),Re&&clearTimeout(Re),X&&clearTimeout(X),L==="replaced"){l=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:M}),!l&&setTimeout(()=>{g=w()},2e3)}),h.on("error",M=>r.warn(`[ws] error: ${M.message}`)),h}return{stop(){l=!0,g.close()}}}async function Gl(t,e,r){try{let n=await se(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=Ro(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 XR(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?Lr(e.root,o):_e(t.projectId,r.name);if(Gg(Lr(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await VR().clone(e?xn(r):rl(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 JR(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?Lr(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(!Gg(Lr(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{YR(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 ZR(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=Lr(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Cf(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 QR(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 eT(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 Kf(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 Kl(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}je();de();Gt();Wl();wt();Gi();async function ey(t={profile:void 0}){let{cfg:e,profile:r}=un(t.profile),n=q(e.projectId);n&&yo(n),To(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Io(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),Co(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=Fo(ql(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=vi("CLI_LOG",i,o);if(s.enabled){let d=new fn(s);$i(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=cn(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=Fo(ql(),".codepipe",r?Fo("profiles",r,"context"):"context");if(await Il(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await Zg(()=>Es({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 Il(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=Fo(ql(),".codepipe",r?Fo("profiles",r,"context-config"):"context-config");Ai(a.contextDir,m,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=xs(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(`
1038
+ [${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}Bn();He();je();async function db(t={profile:void 0}){let e=it(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=us(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=Me(t.profile);o?o.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${o.sandboxId} (${o.name}), llm=${o.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${o.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}Zo();import{readFileSync as $A}from"node:fs";D();He();Gt();Vo();_r();Zt();Pr();je();de();function xe(t){throw new Error(t)}function Ce(t,e){return(typeof t!="string"||t.trim().length===0)&&xe(`config: '${e}' must be a non-empty string`),t.trim()}function ti(t,e){if(t==null)return;typeof t!="string"&&xe(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function xA(t){(!t||typeof t!="object")&&xe("config: expected a JSON object");let e=t,r=Ce(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||xe("config: 'hubUrl' must start with http(s)://");let n=Ce(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&xe("config: 'project' is required");let i=o,s=Ce(i.id,"project.id");Vt.test(s)||xe("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"&&xe("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||xe("config: 'project.repos' must be an array");let u=l.map((k,x)=>{(!k||typeof k!="object")&&xe(`config: project.repos[${x}] must be an object`);let b=k,T=Ce(b.host,`project.repos[${x}].host`);T!=="github"&&T!=="bitbucket"&&T!=="gitlab"&&xe(`config: project.repos[${x}].host must be 'github', 'bitbucket' or 'gitlab'`);let E={name:Ce(b.name,`project.repos[${x}].name`),host:T,owner:Ce(b.owner,`project.repos[${x}].owner`),repoName:Ce(b.repoName,`project.repos[${x}].repoName`)},v=ti(b.defaultBranch,`project.repos[${x}].defaultBranch`);v&&(E.defaultBranch=v);let I=ti(b.mountAs,`project.repos[${x}].mountAs`);return I&&(E.mountAs=I),E}),p=i.contextRepo;(!p||typeof p!="object")&&xe("config: 'project.contextRepo' is required");let d=p,m=ti(d.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&xe("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:m,owner:Ce(d.owner,"project.contextRepo.owner"),name:ti(d.name,"project.contextRepo.name")??Rt(s)},g={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:f}},w=ti(i.youtrackProjectKey,"project.youtrackProjectKey");if(w&&(g.project.youtrackProjectKey=w),i.index!==void 0&&(typeof i.index!="boolean"&&xe("config: 'project.index' must be a boolean"),g.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&xe("config: 'project.youtrackWrites' must be a boolean"),g.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let k=Ce(i.llmProvider,"project.llmProvider");k==="codex"&&xe(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),k!=="claude"&&xe("config: 'project.llmProvider' must be 'claude'"),g.project.llmProvider=k}let h=e.secrets;if(h!==void 0){(typeof h!="object"||h===null)&&xe("config: 'secrets' must be an object");let k=h,x={};if(k.github){let b=k.github;x.github={token:Ce(b.token,"secrets.github.token")}}if(k.bitbucket){let b=k.bitbucket;x.bitbucket={email:Ce(b.email,"secrets.bitbucket.email"),apiToken:Ce(b.apiToken,"secrets.bitbucket.apiToken")}}if(k.gitlab){let b=k.gitlab;x.gitlab={token:Ce(b.token,"secrets.gitlab.token")}}if(k.youtrack){let b=k.youtrack;x.youtrack={url:Ce(b.url,"secrets.youtrack.url").replace(/\/$/,""),token:Ce(b.token,"secrets.youtrack.token")}}if(k.contextWrite){let b=k.contextWrite;x.contextWrite={token:Ce(b.token,"secrets.contextWrite.token")}}g.secrets=x}return g}async function SA(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function EA(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await zt(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${n}`)}if(e.bitbucket){let r=t.project.repos.find(i=>i.host==="bitbucket"),n=r?.owner??(t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:void 0),o=await Xt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await Ri(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 Jt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await er({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Sk(t){let e=!t.configPath||t.configPath==="-"?await SA():$A(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){xe(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=xA(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 EA(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 Fn(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??pn(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){xe(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let u;try{u=await sr(o,i,a)}catch(d){if(d instanceof K&&d.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await se(o,i,s.id);else if(d instanceof K)xe(`HUB \u2192 ${d.status} ${d.message}`);else throw d}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let p={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(ae(p),Bt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Tt(s.id)}`),rr(s.id,Ct(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,s.llmProvider??Je),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await Uo(o,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${d}); runs once a SANDBOX claims it.`)}catch(d){console.warn(`could not enqueue index job: ${d instanceof Error?d.message:String(d)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}He();de();import{cancel as Ek,intro as Rk,isCancel as Tk,log as _u,outro as RA,password as Ik}from"@clack/prompts";async function TA(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Ck(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await TA(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Rk("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),_u.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Ik({message:"Claude OAuth token"});Tk(i)&&(Ek("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Np({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${ki()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=it(t.profile);if(!e){Rk(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),_u.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Ik({message:"Claude OAuth token"});Tk(i)&&(Ek("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}.`):(_u.success("Claude OAuth token saved."),RA("It will be sealed into job bundles when a SANDBOX (re)connects."))}Bo();D();He();Gt();Vo();_r();Gs();je();de();import{cancel as IA,confirm as CA,intro as PA,isCancel as Pk,log as De,outro as AA,select as Ak,text as gr}from"@clack/prompts";function _k(t){IA(t),process.exit(1)}function Yn(t){return Pk(t)&&_k("aborted"),t}function ri(t){return Pk(t)&&_k("aborted"),typeof t=="string"?t:""}async function _A(t,e){let r=Yn(await Ak({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=ri(await gr({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=ri(await gr({message:"Context Repo name",placeholder:Rt(t),initialValue:Rt(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function jk(t={profile:void 0}){let e=it(t.profile);PA(`codepipe project add \u2192 ${e.hubUrl}`);let r=Yn(await gr({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>Vt.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=Yn(await gr({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=Yn(await Ak({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=Yn(await gr({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Yn(await CA({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=ri(await gr({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()||Ve(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=Ve(d);De.message(`${m.host}: ${m.owner}/${m.repoName}`);let f=ri(await gr({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=ri(await gr({message:"default branch (optional)",placeholder:"main"})).trim(),w={name:f,host:m.host,owner:m.owner,repoName:m.repoName};g&&(w.defaultBranch=g),a.push(w)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await _A(r,a),u=q(e.projectId);De.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await Fn(c,l,{githubToken:u?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:u?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:u?.bitbucket??pn(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:d=>De.message(d),warn:d=>De.warn(d)}})}catch(d){De.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,De.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await sr(e.hubUrl,e.cliToken,c);De.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),rr(r,Ct(c,s,u?.youtrack?.url),{info:m=>De.message(m),warn:m=>De.warn(m)}),d.contextRepo&&(De.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),De.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&De.error(` error: ${d.provisioningError}`),AA("done")}catch(d){d instanceof K?(De.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&De.message(JSON.stringify(d.payload,null,2))):De.error(d instanceof Error?d.message:String(d)),process.exit(1)}}Bn();He();je();de();wt();Zo();import{existsSync as jA,rmSync as NA}from"node:fs";import{confirm as OA,intro as LA,isCancel as MA,log as yr,outro as DA,spinner as UA}from"@clack/prompts";function Nt(t){yr.error(t),process.exit(1)}var Nk=t=>t.trim().replace(/\/+$/,"");async function Ok(t){LA("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Pe()?.spec.projectId??void 0;e||Nt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=bt(e);r||Nt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Nk(r.hubUrl),o=r.projectId,i=Nk(t.hub);i.startsWith("http")||Nt("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&Nt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let h=UA();h.start(`reading project ${o} from ${n}\u2026`);try{l=await se(n,r.cliToken,o),h.stop(`read project ${o} (${l.name})`)}catch(k){throw h.stop("could not read the source project",1),k instanceof K&&Nt(`source HUB ${n} \u2192 ${k.status} ${k.message}. The source HUB must be reachable with a valid token to move a project.`),k}}l.contextRepo||Nt(`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 Wn()).trim().toLowerCase();if(yr.message(`move project '${o}'
1018
1039
  from : ${n} (profile ${e})
1019
1040
  to : ${i} (profile ${s}, project ${a}, account ${p})
1020
1041
  \u2022 the source registration on the old HUB is left intact (non-destructive)
1021
1042
  \u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
1022
- `+(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 DA({message:"Continue?",initialValue:!0});(BA(h)||!h)&&jt("aborted")}!c&&a===o&&gr.warn(`source and destination share the same project id, so they share one secrets file (${Tt(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 Fn(i,p),f={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:m,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};gr.step(`registering project on ${i}\u2026`);let g;try{g=await ir(i,d,f)}catch(h){if(h instanceof W&&h.status===409){gr.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{g=await se(i,d,a)}catch(w){throw w instanceof W&&jt(`target HUB \u2192 ${w.status} ${w.message}`),w}}else if(h instanceof W&&h.status===403)jt(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(h instanceof W)jt(`target HUB \u2192 ${h.status} ${h.message}`);else throw h}gr.success(`project ${g.projectId} ready on ${i} (${g.provisioningStatus})`),Ut({hubUrl:i,cliToken:d,projectId:a,accountEmail:m},s);let k={...u??{},hubUrl:i,cliToken:d,projectId:a};if(delete k.sandboxPins,ae(k),gr.success(`profile '${s}' \u2192 ${Tt(a)}`),c){let h=$t(s);LA(h)&&(MA(h),gr.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}FA(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}He();import{existsSync as fu,rmSync as KA,statSync as HA}from"node:fs";import{join as Hs,relative as WA,resolve as qA}from"node:path";import{cancel as YA,intro as tb,isCancel as zA,log as Te,outro as rb,text as Br}from"@clack/prompts";import{simpleGit as nb}from"simple-git";js();je();$o();pe();wt();function tt(t){YA(t),process.exit(1)}function Fr(t){return zA(t)&&tt("aborted"),typeof t=="string"?t:""}async function eb(t){try{let e=await nb(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function VA(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function XA(t,e){let r=Y(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(VA(r,e)){Te.message(`reusing existing ${e} credentials`);return}if(Te.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=Fr(await Br({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=Fr(await Br({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=Fr(await Br({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),Te.success(`saved ${e} credentials`)}async function ob(t){let e=st(t.profile);tb(`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){tt(`could not read project from HUB: ${w instanceof Error?w.message:String(w)}`)}let o=t.target?.trim();if(!o){let w=await eb(process.cwd());w?(o=process.cwd(),Te.message(`using the current directory (${w})`)):o=Fr(await Br({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:v=>v.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(fu(o)&&HA(o).isDirectory()){i=qA(o);let w=await eb(i);w||tt(`${i} is not a git repository (no origin remote)`);let v=ze(w);v||tt(`origin ${w} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=v,s=w,Te.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let w=ze(o);w||tt(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=w,s=o,Te.message(`${a}: ${c}/${l}`)}let u=Fr(await Br({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)&&tt(`a repo named "${u}" is already registered`);let p=Fr(await Br({message:"default branch (optional)",placeholder:"main"})).trim(),d=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let w=WA(r.root,i);d=w===""?".":w}let m=Fr(await Br({message:"mount_as (directory relative to the workspace root)",placeholder:d,initialValue:d})).trim()||d;n.some(w=>(w.mountAs??w.name)===m)&&tt(`mount_as "${m}" is already used by another repo`),await XA(e,a);let f={name:u,host:a,owner:c,repoName:l,mountAs:m,...p?{defaultBranch:p}:{}};if(!i){let w=r?Hs(r.root,m):_e(e.projectId,u);if(fu(Hs(w,".git")))Te.message(`already cloned at ${w}`);else{Te.info(`cloning ${s} \u2192 ${w} \u2026`);try{await nb().clone(s,w),Te.success(`cloned into ${w}`)}catch(v){tt(`clone failed: ${v instanceof Error?v.message.trim():String(v)}
1023
- check that your ${a} credentials grant read access to ${c}/${l}`)}}}let g;try{g=await Ph(e.hubUrl,e.cliToken,e.projectId,f)}catch(w){w instanceof W&&tt(`HUB \u2192 ${w.status} ${w.message}`),tt(w instanceof Error?w.message:String(w))}let{updated:k,errors:h}=vo(e.projectId,g.repos,r?.contextDir);for(let w of k)Te.message(`updated ${w}`);for(let w of h)Te.warn(`could not update ${w.path}: ${w.error}`);Te.success(`added "${u}" \u2014 project now has ${g.repos.length} repo(s)`),rb("done")}async function ib(t){let e=st(t.profile);tb(`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 _h(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof W&&(a.status===404&&tt(`no repo named "${t.name}" in this project`),tt(`HUB \u2192 ${a.status} ${a.message}`)),tt(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=vo(e.projectId,o.repos,r?.contextDir);for(let a of i)Te.message(`updated ${a}`);for(let a of s)Te.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")Te.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?Hs(r.root,n):_e(e.projectId,t.name);if(fu(Hs(a,".git")))try{KA(a,{recursive:!0,force:!0}),Te.message(`deleted local clone ${a}`)}catch(c){Te.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else Te.message(`no local clone found to purge (${a})`)}Te.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),rb("done")}async function sb(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}`)}}Os();He();Ii();je();import{existsSync as JA}from"node:fs";import{join as ZA}from"node:path";import{simpleGit as QA}from"simple-git";wt();var eP=60;async function ab(t){let{cfg:e}=sn(t.profile),r=nn(e.projectId);if(!r)throw new Error(`no workspace for ${e.projectId} here \u2014 run this from the project folder (the one with .codepipe/)`);let n=new Set,o={info:a=>console.log(a),warn:a=>console.warn(a)},i=async()=>{let a=await is(e.hubUrl,e.cliToken,e.projectId);if(a.length===0){console.log("[pull] nothing ready yet");return}for(let c of a)await yl(r.root,r.spec.repos,c,n,o);if(await tP(r.contextDir),r.contextDir)try{hn(r.contextDir,r.root,{info:c=>console.log(`[pull] ${c}`),warn:c=>console.warn(`[pull] ${c}`)})}catch(c){console.warn(`[pull] skills materialize failed \u2014 ${c instanceof Error?c.message:String(c)}`)}};if(!t.watch){await i();return}try{await i()}catch(a){console.warn(`[pull] ${a instanceof Error?a.message:String(a)}`)}let s=Math.max(10,t.intervalSec??eP)*1e3;for(console.log(`[pull] watching \u2014 every ${Math.round(s/1e3)}s, Ctrl+C to stop`);;){await new Promise(a=>setTimeout(a,s));try{await i()}catch(a){console.warn(`[pull] ${a instanceof Error?a.message:String(a)}`)}}}async function tP(t){if(!(!t||!JA(ZA(t,".git"))))try{await QA(t).pull(["--ff-only"])}catch(e){console.warn(`[pull] context repo not updated \u2014 ${e instanceof Error?e.message.split(`
1024
- `)[0]:String(e)}`)}}Bs();import{existsSync as pb,mkdirSync as rP,readFileSync as nP,writeFileSync as oP}from"node:fs";import{homedir as iP}from"node:os";import{dirname as sP,join as fb}from"node:path";import*as Hn from"node:readline";je();_i();pe();wt();Os();Bs();var Ws=fb(iP(),".codepipe","history"),cb=["/help","/status","/tasks","/task","/sync","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],mb=500,lb=40;async function hb(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=Y(e.spec.projectId);r||(console.error(`no secrets for project ${e.spec.projectId} at ~/.codepipe/secrets/${e.spec.projectId}.json. run \`codepipe init\` or \`codepipe clone\` to set them up.`),process.exit(1)),po(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=Hn.createInterface({input:process.stdin,output:process.stdout,completer:aP,history:$P(),removeHistoryDuplicates:!0}),o={ws:e,secrets:r,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};Mf(i=>yr(o,i)),o.daemon=ms({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:i=>yr(o,i),warn:i=>yr(o,i)},onEvent:i=>wP(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 Ms(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=Ds({entry:s,profile:t.profile,onLine:c=>yr(o,`[worker] ${c}`)});a.on("exit",(c,l)=>{o.workerExited=!0,!gu&&Kn(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.`)}hu(o),n.prompt(),n.on("line",async i=>{let s=i.trim();if(s.length>0)try{if(await cP(o,s)){db(o);return}}catch(a){console.error(a instanceof Error?a.message:String(a))}o.unread=0,hu(o),n.prompt()}),n.on("close",()=>{db(o)})}function aP(t){let e=cb.filter(r=>r.startsWith(t));return[e.length?e:cb,t]}async function cP(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return lP(),!1;case"/status":return await uP(t),!1;case"/tasks":return await dP(t,n),!1;case"/task":return await pP(t,n),!1;case"/sync":return await fP(t),!1;case"/logs":return kP(t,n),!1;case"/monitor":return bP(t),!1;case"/approve":return await ub(t,n,"approve"),!1;case"/merge":return await ub(t,n,"merge"),!1;case"/login":return mP(t,n),!1;case"/secret":return hP(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function lP(){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(`
1025
- `))}async function uP(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=pb(fb(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function dP(t,e){let r=vP(e,"--phase");try{let n=await Ih(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){yu(n)}}async function pP(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await Ch(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){yu(n)}}async function fP(t){let e=await qo(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 ub(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await Ah(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){yu(o)}}function mP(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 hP(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(`
1026
- `)}`:" (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}gP(t.secrets,n,i),ae(t.secrets),po(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}yP(t.secrets,n),ae(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function gP(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 yP(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 wP(t,e){switch(e.kind){case"connected":t.connection="connecting",yr(t,"[hub] connected");break;case"registered":t.connection="registered",yr(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Kn(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",yr(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Kn(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Kn(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?yr(t,`[hub] action ${e.actionType} done`):Kn(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function yr(t,e){t.logBuffer.push(e),t.logBuffer.length>mb&&t.logBuffer.shift(),t.follow&&Kn(t,e)}function kP(t,e){let r=e[0];if(r==="follow"||r==="on"){mu(t,!0);return}if(r==="off"){mu(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(mb,Number(r)||lb)):lb,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 bP(t){mu(t,!t.follow)}function mu(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Kn(t,e){Hn.cursorTo(process.stdout,0),Hn.clearLine(process.stdout,0),process.stdout.write(e+`
1027
- `),t.unread+=1,hu(t),t.rl.prompt(!0)}function hu(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var gu=!1;function db(t){if(gu)return;gu=!0,xP(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
1043
+ `+(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 OA({message:"Continue?",initialValue:!0});(MA(h)||!h)&&Nt("aborted")}!c&&a===o&&yr.warn(`source and destination share the same project id, so they share one secrets file (${Tt(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 qn(i,p),f={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:m,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};yr.step(`registering project on ${i}\u2026`);let g;try{g=await sr(i,d,f)}catch(h){if(h instanceof K&&h.status===409){yr.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{g=await se(i,d,a)}catch(k){throw k instanceof K&&Nt(`target HUB \u2192 ${k.status} ${k.message}`),k}}else if(h instanceof K&&h.status===403)Nt(`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)Nt(`target HUB \u2192 ${h.status} ${h.message}`);else throw h}yr.success(`project ${g.projectId} ready on ${i} (${g.provisioningStatus})`),Bt({hubUrl:i,cliToken:d,projectId:a,accountEmail:m},s);let w={...u??{},hubUrl:i,cliToken:d,projectId:a};if(delete w.sandboxPins,ae(w),yr.success(`profile '${s}' \u2192 ${Tt(a)}`),c){let h=$t(s);jA(h)&&(NA(h),yr.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}DA(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}D();He();import{existsSync as ju,rmSync as BA,statSync as FA}from"node:fs";import{join as ni,relative as GA,resolve as KA}from"node:path";import{cancel as HA,intro as Mk,isCancel as WA,log as be,outro as Dk,text as Kr}from"@clack/prompts";import{simpleGit as Uk}from"simple-git";xu();Su();Gs();je();Sn();de();wt();function ze(t){HA(t),process.exit(1)}function Hr(t){return WA(t)&&ze("aborted"),typeof t=="string"?t:""}async function Lk(t){try{let e=await Uk(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function qA(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function YA(t,e){let r=q(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(qA(r,e)){be.message(`reusing existing ${e} credentials`);return}if(be.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=Hr(await Kr({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=Hr(await Kr({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=Hr(await Kr({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),be.success(`saved ${e} credentials`)}async function Bk(t){let e=it(t.profile);Mk(`codepipe repo add \u2192 project ${e.projectId}`);let r=Pe()??void 0,n;try{n=(await se(e.hubUrl,e.cliToken,e.projectId)).repos}catch(b){ze(`could not read project from HUB: ${b instanceof Error?b.message:String(b)}`)}let o=t.target?.trim();if(!o){let b=await Lk(process.cwd());b?(o=process.cwd(),be.message(`using the current directory (${b})`)):o=Hr(await Kr({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:T=>T.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(ju(o)&&FA(o).isDirectory()){i=KA(o);let b=await Lk(i);b||ze(`${i} is not a git repository (no origin remote)`);let T=Ve(b);T||ze(`origin ${b} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=T,s=b,be.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let b=Ve(o);b||ze(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=b,s=o,be.message(`${a}: ${c}/${l}`)}let u=Hr(await Kr({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:b=>b.trim()?void 0:"required"})).trim();n.some(b=>b.name===u)&&ze(`a repo named "${u}" is already registered`);let p;i&&(p=await Jo(i,s));let d=p?po(p).branches.integration:"",m=Hr(await Kr({message:"default branch (optional)",placeholder:d||"main",...d?{initialValue:d}:{}})).trim(),f=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let b=GA(r.root,i);f=b===""?".":b}let g=Hr(await Kr({message:"mount_as (directory relative to the workspace root)",placeholder:f,initialValue:f})).trim()||f;n.some(b=>(b.mountAs??b.name)===g)&&ze(`mount_as "${g}" is already used by another repo`),await YA(e,a);let w={name:u,host:a,owner:c,repoName:l,mountAs:g,...m?{defaultBranch:m}:{}};if(!i){let b=r?ni(r.root,g):_e(e.projectId,u);if(ju(ni(b,".git")))be.message(`already cloned at ${b}`);else{be.info(`cloning ${s} \u2192 ${b} \u2026`);try{await Uk().clone(s,b),be.success(`cloned into ${b}`)}catch(T){ze(`clone failed: ${T instanceof Error?T.message.trim():String(T)}
1044
+ check that your ${a} credentials grant read access to ${c}/${l}`)}}}let h;try{h=await ig(e.hubUrl,e.cliToken,e.projectId,w)}catch(b){b instanceof K&&ze(`HUB \u2192 ${b.status} ${b.message}`),ze(b instanceof Error?b.message:String(b))}let{updated:k,errors:x}=Ro(e.projectId,h.repos,r?.contextDir);for(let b of k)be.message(`updated ${b}`);for(let b of x)be.warn(`could not update ${b.path}: ${b.error}`);if(r?.contextDir){if(!p)try{let b=i??ni(r.root,g);p=await Jo(b,s)}catch(b){be.warn(`git-flow detection skipped: ${b instanceof Error?b.message:String(b)}`),p={defaultBranch:null,branches:[]}}try{await Ws({contextDir:r.contextDir,repoName:u,facts:p,log:b=>be.message(b)})}catch(b){ze(`"${u}" was added, but its git-flow choice was NOT saved: ${b instanceof Error?b.message.trim():String(b)}
1045
+ re-run the command or set the git-flow manually in project.yaml`)}}be.success(`added "${u}" \u2014 project now has ${h.repos.length} repo(s)`),Dk("done")}async function Fk(t){let e=it(t.profile);Mk(`codepipe repo remove \u2192 project ${e.projectId}`);let r=Pe()??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 sg(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof K&&(a.status===404&&ze(`no repo named "${t.name}" in this project`),ze(`HUB \u2192 ${a.status} ${a.message}`)),ze(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=Ro(e.projectId,o.repos,r?.contextDir);for(let a of i)be.message(`updated ${a}`);for(let a of s)be.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")be.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?ni(r.root,n):_e(e.projectId,t.name);if(ju(ni(a,".git")))try{BA(a,{recursive:!0,force:!0}),be.message(`deleted local clone ${a}`)}catch(c){be.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else be.message(`no local clone found to purge (${a})`)}be.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),Dk("done")}async function Gk(t){let e=it(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}`)}}Hs();He();Oi();je();import{existsSync as VA}from"node:fs";import{join as zA}from"node:path";import{simpleGit as XA}from"simple-git";wt();var JA=60;async function Kk(t){let{cfg:e}=un(t.profile),r=cn(e.projectId);if(!r)throw new Error(`no workspace for ${e.projectId} here \u2014 run this from the project folder (the one with .codepipe/)`);let n=new Set,o={info:a=>console.log(a),warn:a=>console.warn(a)},i=async()=>{let a=await fs(e.hubUrl,e.cliToken,e.projectId);if(a.length===0){console.log("[pull] nothing ready yet");return}for(let c of a)await Al(r.root,r.spec.repos,c,n,o);if(await ZA(r.contextDir),r.contextDir)try{bn(r.contextDir,r.root,{info:c=>console.log(`[pull] ${c}`),warn:c=>console.warn(`[pull] ${c}`)})}catch(c){console.warn(`[pull] skills materialize failed \u2014 ${c instanceof Error?c.message:String(c)}`)}};if(!t.watch){await i();return}try{await i()}catch(a){console.warn(`[pull] ${a instanceof Error?a.message:String(a)}`)}let s=Math.max(10,t.intervalSec??JA)*1e3;for(console.log(`[pull] watching \u2014 every ${Math.round(s/1e3)}s, Ctrl+C to stop`);;){await new Promise(a=>setTimeout(a,s));try{await i()}catch(a){console.warn(`[pull] ${a instanceof Error?a.message:String(a)}`)}}}async function ZA(t){if(!(!t||!VA(zA(t,".git"))))try{await XA(t).pull(["--ff-only"])}catch(e){console.warn(`[pull] context repo not updated \u2014 ${e instanceof Error?e.message.split(`
1046
+ `)[0]:String(e)}`)}}Xs();import{existsSync as Vk,mkdirSync as QA,readFileSync as e_,writeFileSync as t_}from"node:fs";import{homedir as r_}from"node:os";import{dirname as n_,join as zk}from"node:path";import*as zn from"node:readline";je();Ui();de();wt();Hs();Xs();var ea=zk(r_(),".codepipe","history"),Hk=["/help","/status","/tasks","/task","/sync","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Xk=500,Wk=40;async function Jk(t={}){let e=Pe();e||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let r=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)),yo(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=zn.createInterface({input:process.stdin,output:process.stdout,completer:o_,history:b_(),removeHistoryDuplicates:!0}),o={ws:e,secrets:r,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};dm(i=>wr(o,i)),o.daemon=xs({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:i=>wr(o,i),warn:i=>wr(o,i)},onEvent:i=>h_(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 Ys(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=Vs({entry:s,profile:t.profile,onLine:c=>wr(o,`[worker] ${c}`)});a.on("exit",(c,l)=>{o.workerExited=!0,!Lu&&Vn(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 i_(o,s)){Yk(o);return}}catch(a){console.error(a instanceof Error?a.message:String(a))}o.unread=0,Ou(o),n.prompt()}),n.on("close",()=>{Yk(o)})}function o_(t){let e=Hk.filter(r=>r.startsWith(t));return[e.length?e:Hk,t]}async function i_(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return s_(),!1;case"/status":return await a_(t),!1;case"/tasks":return await c_(t,n),!1;case"/task":return await l_(t,n),!1;case"/sync":return await u_(t),!1;case"/logs":return g_(t,n),!1;case"/monitor":return y_(t),!1;case"/approve":return await qk(t,n,"approve"),!1;case"/merge":return await qk(t,n,"merge"),!1;case"/login":return d_(t,n),!1;case"/secret":return p_(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function s_(){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(`
1047
+ `))}async function a_(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=Vk(zk(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function c_(t,e){let r=w_(e,"--phase");try{let n=await rg(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){Mu(n)}}async function l_(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await ng(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){Mu(n)}}async function u_(t){let e=await Xo(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 qk(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await og(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){Mu(o)}}function d_(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 p_(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(`
1048
+ `)}`:" (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}f_(t.secrets,n,i),ae(t.secrets),yo(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}m_(t.secrets,n),ae(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function f_(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 m_(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 h_(t,e){switch(e.kind){case"connected":t.connection="connecting",wr(t,"[hub] connected");break;case"registered":t.connection="registered",wr(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Vn(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",wr(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Vn(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Vn(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?wr(t,`[hub] action ${e.actionType} done`):Vn(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function wr(t,e){t.logBuffer.push(e),t.logBuffer.length>Xk&&t.logBuffer.shift(),t.follow&&Vn(t,e)}function g_(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(Xk,Number(r)||Wk)):Wk,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 y_(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 Vn(t,e){zn.cursorTo(process.stdout,0),zn.clearLine(process.stdout,0),process.stdout.write(e+`
1049
+ `),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 Lu=!1;function Yk(t){if(Lu)return;Lu=!0,k_(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
1028
1050
  bye.`),setTimeout(()=>process.exit(0),150);return}console.log(`
1029
- 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 vP(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function yu(t){t instanceof W?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function $P(){if(!pb(Ws))return[];try{return nP(Ws,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function xP(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{rP(sP(Ws),{recursive:!0}),oP(Ws,r.slice().reverse().join(`
1051
+ 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 w_(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function Mu(t){t instanceof K?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function b_(){if(!Vk(ea))return[];try{return e_(ea,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function k_(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{QA(n_(ea),{recursive:!0}),t_(ea,r.slice().reverse().join(`
1030
1052
  `)+`
1031
- `)}catch{}}Ln();F();Ke();Ln();He();je();Yo();import{hostname as SP}from"node:os";import{cancel as EP,confirm as gb,intro as TP,isCancel as kb,log as Wn,multiselect as RP,outro as yb,password as IP,select as wu,text as ku}from"@clack/prompts";function Zo(t){EP(t),process.exit(1)}function qn(t){return kb(t)&&Zo("aborted"),t}function qs(t){return kb(t)&&Zo("aborted"),typeof t=="string"?t:""}function Ys(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function wb(t,e){try{let{secret:r}=await os(t,e);return r}catch(r){throw r instanceof W&&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 CP(t,e){if(qn(await wu({message:"which projects should this worker serve?",options:[{value:"all",label:"all my projects (recommended \u2014 new projects included automatically)"},{value:"selected",label:"only selected projects"}],initialValue:"all"}))==="all")return[];if(e)try{let o=await fl(t,e);if(o.length>0)return qn(await RP({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}));Wn.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Wn.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return qs(await ku({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 bu(t){TP("codepipe worker \u2014 set up this machine as a runner");let e=Le(t.profile);e&&(Wn.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),qn(await gb({message:"re-register this worker?",initialValue:!1}))||Zo("keeping the existing registration"));let r=kt(t.profile)??kt(),n=qs(await ku({message:"HUB URL",placeholder:mt,initialValue:Q("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=qn(await wu({message:"how to authorize the registration?",options:[...o?[{value:"local",label:"this machine's CLI account (recommended \u2014 no token hand-off)"}]:[],{value:"login",label:"log in by email (magic-link, like codepipe init)"},{value:"paste",label:"paste a registration token from the dashboard"}],initialValue:o?"local":"login"})),s,a=null;if(i==="local")a=r.cliToken,s=await wb(n,a),Wn.success("account-issued registration token minted");else if(i==="login"){let d=await Bn();a=(await Fn(n,d)).cliToken,s=await wb(n,a),Wn.success("account-issued registration token minted")}else s=qs(await IP({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||Zo("a registration token is required");let c=await CP(n,a),l=qs(await ku({message:"worker name",initialValue:SP(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=qn(await wu({message:"agent backend",options:[{value:"claude-headless",label:"claude-headless \u2014 Claude Code on PATH (the real thing)"},{value:"mock",label:"mock \u2014 deterministic stub (development)"},{value:"",label:"none \u2014 this worker will not claim agent jobs"}],initialValue:"claude-headless"}));if(await Lr({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Wn.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!qn(await gb({message:"start the claim-loop now?",initialValue:!0}))){yb("registered. start later with `codepipe worker`.");return}yb("starting the claim-loop\u2026"),await Ko(t.profile?{profile:t.profile}:{})}function PP(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return Q("PROFILE")}var ke=PP();Vd(ke);var De=new AP;De.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Xe).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{Ys()?await hb({profile:ke}):await Us({profile:ke})}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 Ak({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 cp({...t,profile:ke})}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 Pk({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 Tg({profile:ke})}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 fk({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 Yk({profile:ke,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 Mw({profile:ke})}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 ab({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 Us({profile:ke,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var bb=De.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");bb.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??Q("HUB_URL")??kt(ke)?.hubUrl??mt,r=t.token??Q("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Ys()){await bu({profile:ke});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let n=Q("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??Q("WORKER_NAME"),i=t.llm??Q("WORKER_LLM");await Lr({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...ke?{profile:ke}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});bb.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!Le(ke)&&Ys()){await bu({profile:ke});return}await Ko(ke?{profile:ke}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var vb=De.command("project").description("Manage CodePipe projects");vb.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Jk({profile:ke})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});vb.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 Qk({...t,cliProfile:ke})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var vu=De.command("repo").description("Manage the project's git repositories");vu.command("add").description("Add a repo to this project (a path to an existing clone, or a clone URL)").argument("[target]","Path to an already-cloned repo, or a repo clone URL").action(async t=>{try{await ob({profile:ke,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});vu.command("remove").description("Remove a repo from this project by its logical name").argument("<name>","Logical name of the repo (as shown by `codepipe repo list`)").option("--purge","Also delete the local clone",!1).action(async(t,e)=>{try{await ib({profile:ke,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});vu.command("list").description("List the project's repos").action(async()=>{try{await sb({profile:ke})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var $b=De.command("model").description("Project map (model/ in the Context Repo)");$b.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 vl({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});$b.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 $l({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.parseAsync();
1053
+ `)}catch{}}Bn();D();Ke();Bn();He();je();Zo();import{hostname as v_}from"node:os";import{cancel as $_,confirm as Zk,intro as x_,isCancel as tv,log as Xn,multiselect as S_,outro as Qk,password as E_,select as Du,text as Uu}from"@clack/prompts";function oi(t){$_(t),process.exit(1)}function Jn(t){return tv(t)&&oi("aborted"),t}function ta(t){return tv(t)&&oi("aborted"),typeof t=="string"?t:""}function ra(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function ev(t,e){try{let{secret:r}=await ps(t,e);return r}catch(r){throw r instanceof K&&r.status===404&&oi("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 R_(t,e){if(Jn(await Du({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 Tl(t,e);if(o.length>0)return Jn(await S_({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}));Xn.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Xn.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return ta(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 Bu(t){x_("codepipe worker \u2014 set up this machine as a runner");let e=Me(t.profile);e&&(Xn.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Jn(await Zk({message:"re-register this worker?",initialValue:!1}))||oi("keeping the existing registration"));let r=bt(t.profile)??bt(),n=ta(await Uu({message:"HUB URL",placeholder:mt,initialValue:Q("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=Jn(await Du({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 ev(n,a),Xn.success("account-issued registration token minted");else if(i==="login"){let d=await Wn();a=(await qn(n,d)).cliToken,s=await ev(n,a),Xn.success("account-issued registration token minted")}else s=ta(await E_({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||oi("a registration token is required");let c=await R_(n,a),l=ta(await Uu({message:"worker name",initialValue:v_(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=Jn(await Du({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 Mr({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Xn.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Jn(await Zk({message:"start the claim-loop now?",initialValue:!0}))){Qk("registered. start later with `codepipe worker`.");return}Qk("starting the claim-loop\u2026"),await Yo(t.profile?{profile:t.profile}:{})}function I_(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return Q("PROFILE")}var ke=I_();$p(ke);var Ue=new T_;Ue.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Xe).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{ra()?await Jk({profile:ke}):await zs({profile:ke})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ue.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await Sk({configPath:t.config,skipVerify:t.skipVerify===!0}):await pk({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ue.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","Personal CLI token (issued during `codepipe init`)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await Op({...t,profile:ke})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ue.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await fk({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Ue.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await ey({profile:ke})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ue.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await Fb({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ue.command("login").description("Set the Claude OAuth token (sealed into job bundles)").option("--token <token>","Provide the token non-interactively").option("--shared","Save to the machine/farm-wide ~/.codepipe/shared.json instead of this project").option("--stdin","Read the token from stdin (for scripted/ssh delivery)").action(async t=>{try{await Ck({profile:ke,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ue.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await db({profile:ke})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ue.command("pull").description("Fetch finished task branches into your local clones (no checkout switch)").option("--profile <name>","Config profile").option("--watch","Keep pulling instead of exiting after one pass").option("--interval <sec>","Watch interval in seconds (default 60, minimum 10)",t=>parseInt(t,10)).action(async t=>{if(t.interval!==void 0&&!Number.isFinite(t.interval))throw new Error("--interval expects a number of seconds");await Kk({profile:t.profile,...t.watch?{watch:!0}:{},...Number.isFinite(t.interval)?{intervalSec:t.interval}:{}})});Ue.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).option("--debug [categories]","Write local debug logs (comma-separated categories; default: agent-request \u2014 the full prompt and context each agent job receives, under ~/.codepipe/debug/)").action(async t=>{try{await zs({profile:ke,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var rv=Ue.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");rv.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??Q("HUB_URL")??bt(ke)?.hubUrl??mt,r=t.token??Q("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&ra()){await Bu({profile:ke});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let n=Q("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??Q("WORKER_NAME"),i=t.llm??Q("WORKER_LLM");await Mr({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...ke?{profile:ke}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});rv.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!Me(ke)&&ra()){await Bu({profile:ke});return}await Yo(ke?{profile:ke}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var nv=Ue.command("project").description("Manage CodePipe projects");nv.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await jk({profile:ke})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});nv.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 Ok({...t,cliProfile:ke})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Fu=Ue.command("repo").description("Manage the project's git repositories");Fu.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 Bk({profile:ke,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Fu.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 Fk({profile:ke,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Fu.command("list").description("List the project's repos").action(async()=>{try{await Gk({profile:ke})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var ov=Ue.command("model").description("Project map (model/ in the Context Repo)");ov.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 Ol({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ov.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 Ll({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ue.parseAsync();