@code-partner/codepipe 0.11.1-dev.220.g0db591d → 0.11.1-dev.221.g686928f

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 +308 -219
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,55 +1,60 @@
1
1
  #!/usr/bin/env node
2
- var Vk=Object.defineProperty;var v=(t,e)=>()=>(t&&(e=t(t=0)),e);var Rr=(t,e)=>{for(var r in e)Vk(t,r,{get:e[r],enumerable:!0})};var Ue,ct,Is=v(()=>{"use strict";Ue="0.11.1-dev.220.g0db591d",ct="https://hub.dev.codepipe.dev"});function Ao(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=zk&&t<=lt}var lt,zk,$l=v(()=>{"use strict";Is();lt=4,zk=4});var vl=v(()=>{"use strict";Is()});function Po(t=4){return`# CodePipe Context Repo format version.
2
+ var mb=Object.defineProperty;var $=(t,e)=>()=>(t&&(e=t(t=0)),e);var Be=(t,e)=>{for(var r in e)mb(t,r,{get:e[r],enumerable:!0})};var Fe,it,Ki=$(()=>{"use strict";Fe="0.11.1-dev.221.g686928f",it="https://hub.dev.codepipe.dev"});function Vn(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Ru&&t<=at}var at,Ru,Tu=$(()=>{"use strict";Ki();at=4,Ru=4});var Iu=$(()=>{"use strict";Ki()});function zn(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 Sl(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 Tl(t,e=xl){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 El(t,e=xl){return e.filter(r=>r.version>t)}var ut,On,xl,Il=v(()=>{"use strict";ut=".codepipe-context.yaml",On=".devpipe-context.yaml",xl=[{version:1,summary:"ADR section: adr/ scaffold (README, template, derived INDEX) + the format-version stamp itself",addedPaths:["adr/README.md","adr/0000-template.md","adr/INDEX.md",ut]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[ut]},{version:3,summary:"Custom project actions (the RUN tab): actions/ scaffold with the format README",addedPaths:["actions/README.md"]},{version:4,summary:"Project map: model/ scaffold with the format README (facts/ vs derived/ layout)",addedPaths:["model/README.md"]}]});function _o(t){return`model/facts/identity/${t}.yaml`}function Pr(t){return`model/facts/events/${t}.yaml`}function Rl(t){return`model/facts/annotations/${t}.md`}function Cl(t){return`model/derived/correlates/${t}.yaml`}function Al(t){return`model/derived/touched/${t}.yaml`}function Xk(t){return t===""?"root":t.replace(/\//g,"-")}function Pl(t,e){return`model/derived/structure/${t}/${Xk(e)}.yaml`}function Ps(t){return typeof t=="string"&&Qk.test(t)}function Q(t){if(typeof t!="string")return null;let e=t.indexOf(":");if(e<=0)return null;let r=t.indexOf(":",e+1);if(r<0)return null;let n=t.slice(0,e);if(!Jk.includes(n))return null;let o=t.slice(e+1,r),i=t.slice(r+1);return o===""&&!Zk.includes(n)||i===""?null:{level:n,repo:o,path:i}}function ve(t){return`task::${t}`}function pe(t,e,r){return`${t}:${e}:${r}`}function jo(t){let e=[];return dt(t)?(No(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),typeof t.repo!="string"&&e.push("repo: missing (empty string = cross-repo)"),typeof t.builtFromCommit!="string"&&e.push("builtFromCommit: missing"),Array.isArray(t.edges)?t.edges.forEach((r,n)=>{if(!dt(r)){e.push(`edges[${n}]: not an object`);return}_l.includes(r.kind)||e.push(`edges[${n}].kind: unknown "${String(r.kind)}"`),Q(r.from)||e.push(`edges[${n}].from: malformed nodeKey`),Q(r.to)||e.push(`edges[${n}].to: malformed nodeKey`),r.weight!==void 0&&!(typeof r.weight=="number"&&Number.isFinite(r.weight))&&e.push(`edges[${n}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}):{ok:!1,errors:["edge sheet: not an object"]}}function ew(t){return{...t,edges:Cr(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function _r(t){return Nr(ew(t))}function dt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function No(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function Xe(t){return typeof t=="string"&&t.length>0}function At(t){let e=[];if(!dt(t))return{ok:!1,errors:["shard: not an object"]};No(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),Xe(t.repo)||e.push("repo: missing or empty"),Xe(t.builtFromCommit)||e.push("builtFromCommit: missing or empty");let r=typeof t.repo=="string"?t.repo:"",n=new Set;return Array.isArray(t.nodes)?t.nodes.forEach((o,i)=>{if(!dt(o)){e.push(`nodes[${i}]: not an object`);return}let s=Q(o.key);if(!s){e.push(`nodes[${i}].key: malformed nodeKey (${JSON.stringify(o.key??null)})`);return}o.level!==s.level&&e.push(`nodes[${i}]: level "${String(o.level)}" does not match key prefix "${s.level}"`),r&&s.repo!==r&&e.push(`nodes[${i}].key: repo "${s.repo}" mixed into shard of repo "${r}"`);let a=o.key;n.has(a)&&e.push(`nodes[${i}].key: duplicate "${a}"`),n.add(a),o.entityId!==void 0&&!Ps(o.entityId)&&e.push(`nodes[${i}].entityId: malformed (${JSON.stringify(o.entityId)})`)}):e.push("nodes: not an array"),Array.isArray(t.edges)?t.edges.forEach((o,i)=>{if(!dt(o)){e.push(`edges[${i}]: not an object`);return}_l.includes(o.kind)||e.push(`edges[${i}].kind: unknown "${String(o.kind)}"`),(!Xe(o.to)||!Q(o.to))&&e.push(`edges[${i}].to: malformed nodeKey`),(!Xe(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 Oo(t){let e=[];if(!dt(t))return{ok:!1,errors:["identity: not an object"]};if(No(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),Xe(t.repo)||e.push("repo: missing or empty"),t.builtFromCommit!==void 0&&!Xe(t.builtFromCommit)&&e.push("builtFromCommit: not a non-empty string"),!Array.isArray(t.entities))e.push("entities: not an array");else{let r=new Set;t.entities.forEach((n,o)=>{if(!dt(n)){e.push(`entities[${o}]: not an object`);return}Ps(n.entityId)?r.has(n.entityId)?e.push(`entities[${o}].entityId: duplicate "${n.entityId}"`):r.add(n.entityId):e.push(`entities[${o}].entityId: malformed (${JSON.stringify(n.entityId??null)})`),Q(n.currentKey)||e.push(`entities[${o}].currentKey: malformed nodeKey`),n.status!=="active"&&n.status!=="orphaned"&&e.push(`entities[${o}].status: expected active|orphaned`),Xe(n.firstSeen)||e.push(`entities[${o}].firstSeen: missing`),Xe(n.lastSeen)||e.push(`entities[${o}].lastSeen: missing`),n.aliases!==void 0&&(Array.isArray(n.aliases)?n.aliases.forEach((i,s)=>{(!dt(i)||!Q(i.key)||!Xe(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 Pt(t){let e=[];return dt(t)?(No(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),Xe(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=>!Xe(r)))&&e.push("commits: not an array of non-empty strings"),Array.isArray(t.files)?t.files.forEach((r,n)=>{if(!dt(r)||!Q(r.key)){e.push(`files[${n}].key: malformed nodeKey`);return}r.entityId!==void 0&&!Ps(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 Cr(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function tw(t){return{...t,nodes:Cr(t.nodes,e=>e.key),edges:Cr(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function rw(t){return{...t,entities:Cr(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:Cr(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function nw(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:Cr(t.files,r=>r.key),...e?{links:e}:{}}}function Ln(t){return ow.test(t)?t:JSON.stringify(t)}function Dl(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 Ml(t){return t===null||["boolean","number","string"].includes(typeof t)}function Rs(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function Ul(t,e,r){if(Array.isArray(t)){for(let n of t)if(Ml(n))r.push(`${e}- ${Dl(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=Rs(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([i,s],a)=>{let c=a===0?`${e}- `:`${e} `;Cs(i,s,c,`${e} `,r)})}}return}for(let[n,o]of Rs(t))Cs(n,o,e,e,r)}function Cs(t,e,r,n,o){if(Ml(e))o.push(`${r}${Ln(t)}: ${Dl(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${Ln(t)}: []`):(o.push(`${r}${Ln(t)}:`),Ul(e,`${n} `,o));else{let i=Rs(e);if(i.length===0)o.push(`${r}${Ln(t)}: {}`);else{o.push(`${r}${Ln(t)}:`);for(let[s,a]of i)Cs(s,a,`${n} `,`${n} `,o)}}}function Nr(t){let e=[];return Ul(t,"",e),e.join(`
5
+ `}function Hi(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 Wi(t,e=Gi){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 qi(t,e=Gi){return e.filter(r=>r.version>t)}var Cu,ct,Gr,Gi,Au=$(()=>{"use strict";Cu=6,ct=".codepipe-context.yaml",Gr=".devpipe-context.yaml",Gi=[{version:1,summary:"ADR section: adr/ scaffold (README, template, derived INDEX) + the format-version stamp itself",addedPaths:["adr/README.md","adr/0000-template.md","adr/INDEX.md",ct]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[ct]},{version:3,summary:"Custom project actions (the RUN tab): actions/ scaffold with the format README",addedPaths:["actions/README.md"]},{version:4,summary:"Project map: model/ scaffold with the format README (facts/ vs derived/ layout)",addedPaths:["model/README.md"]},{version:5,summary:"Roles: roles/ scaffold with the format README (override a bundled critic by name, or add your own)",addedPaths:["roles/README.md"]},{version:6,summary:"Skills: skills/ scaffold with the format README (procedures the agent invokes instead of improvising)",addedPaths:["skills/README.md"]}]});function Jn(t){return`model/facts/identity/${t}.yaml`}function dr(t){return`model/facts/events/${t}.yaml`}function zi(t){return`model/facts/annotations/${t}.md`}function Xi(t){return`model/derived/correlates/${t}.yaml`}function Ji(t){return`model/derived/touched/${t}.yaml`}function Pu(t){return t===""?"root":t.replace(/\//g,"-")}function Zi(t,e){return`model/derived/structure/${t}/${Pu(e)}.yaml`}function Xo(t){return typeof t=="string"&&ju.test(t)}function re(t){if(typeof t!="string")return null;let e=t.indexOf(":");if(e<=0)return null;let r=t.indexOf(":",e+1);if(r<0)return null;let n=t.slice(0,e);if(!_u.includes(n))return null;let o=t.slice(e+1,r),s=t.slice(r+1);return o===""&&!wb.includes(n)||s===""?null:{level:n,repo:o,path:s}}function ke(t){return`task::${t}`}function me(t,e,r){return`${t}:${e}:${r}`}function Zn(t){let e=[];return kt(t)?(Zo(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(!kt(r)){e.push(`edges[${n}]: not an object`);return}Qi.includes(r.kind)||e.push(`edges[${n}].kind: unknown "${String(r.kind)}"`),re(r.from)||e.push(`edges[${n}].from: malformed nodeKey`),re(r.to)||e.push(`edges[${n}].to: malformed nodeKey`),r.weight!==void 0&&!(typeof r.weight=="number"&&Number.isFinite(r.weight))&&e.push(`edges[${n}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}):{ok:!1,errors:["edge sheet: not an object"]}}function Nu(t){return{...t,edges:Hr(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function pr(t){return mr(Nu(t))}function kt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Zo(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function lt(t){return typeof t=="string"&&t.length>0}function $b(t){return t.modelFormatVersion!==2}function Ct(t){let e=[];if(!kt(t))return{ok:!1,errors:["shard: not an object"]};Zo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),lt(t.repo)||e.push("repo: missing or empty"),lt(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,s)=>{if(!kt(o)){e.push(`nodes[${s}]: not an object`);return}let i=re(o.key);if(!i){e.push(`nodes[${s}].key: malformed nodeKey (${JSON.stringify(o.key??null)})`);return}o.level!==i.level&&e.push(`nodes[${s}]: level "${String(o.level)}" does not match key prefix "${i.level}"`),r&&i.repo!==r&&e.push(`nodes[${s}].key: repo "${i.repo}" mixed into shard of repo "${r}"`);let a=o.key;n.has(a)&&e.push(`nodes[${s}].key: duplicate "${a}"`),n.add(a),o.entityId!==void 0&&!Xo(o.entityId)&&e.push(`nodes[${s}].entityId: malformed (${JSON.stringify(o.entityId)})`)}):e.push("nodes: not an array"),Array.isArray(t.edges)?t.edges.forEach((o,s)=>{if(!kt(o)){e.push(`edges[${s}]: not an object`);return}Qi.includes(o.kind)||e.push(`edges[${s}].kind: unknown "${String(o.kind)}"`),(!lt(o.to)||!re(o.to))&&e.push(`edges[${s}].to: malformed nodeKey`),(!lt(o.from)||!n.has(o.from))&&e.push(`edges[${s}].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[${s}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}}function Qn(t){let e=[];if(!kt(t))return{ok:!1,errors:["identity: not an object"]};if(Zo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),lt(t.repo)||e.push("repo: missing or empty"),t.builtFromCommit!==void 0&&!lt(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(!kt(n)){e.push(`entities[${o}]: not an object`);return}Xo(n.entityId)?r.has(n.entityId)?e.push(`entities[${o}].entityId: duplicate "${n.entityId}"`):r.add(n.entityId):e.push(`entities[${o}].entityId: malformed (${JSON.stringify(n.entityId??null)})`),re(n.currentKey)||e.push(`entities[${o}].currentKey: malformed nodeKey`),n.status!=="active"&&n.status!=="orphaned"&&e.push(`entities[${o}].status: expected active|orphaned`),lt(n.firstSeen)||e.push(`entities[${o}].firstSeen: missing`),lt(n.lastSeen)||e.push(`entities[${o}].lastSeen: missing`),n.aliases!==void 0&&(Array.isArray(n.aliases)?n.aliases.forEach((s,i)=>{(!kt(s)||!re(s.key)||!lt(s.until))&&e.push(`entities[${o}].aliases[${i}]: malformed`)}):e.push(`entities[${o}].aliases: not an array`))})}return e.length?{ok:!1,errors:e}:{ok:!0,value:t}}function At(t){let e=[];return kt(t)?(Zo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),lt(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=>!lt(r)))&&e.push("commits: not an array of non-empty strings"),Array.isArray(t.files)?t.files.forEach((r,n)=>{if(!kt(r)||!re(r.key)){e.push(`files[${n}].key: malformed nodeKey`);return}r.entityId!==void 0&&!Xo(r.entityId)&&e.push(`files[${n}].entityId: malformed`),r.churn!==void 0&&!(typeof r.churn=="number"&&r.churn>=0)&&e.push(`files[${n}].churn: not a non-negative number`)}):e.push("files: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}):{ok:!1,errors:["event: not an object"]}}function Hr(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function Ou(t){return{...t,nodes:Hr(t.nodes,e=>e.key),edges:Hr(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function Lu(t){return{...t,entities:Hr(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:Hr(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function Du(t){let e=t.links?{...t.links,...t.links.adr?{adr:[...t.links.adr].sort()}:{},...t.links.tasks?{tasks:[...t.links.tasks].sort()}:{}}:void 0;return{...t,commits:[...t.commits].sort(),files:Hr(t.files,r=>r.key),...e?{links:e}:{}}}function Xn(t){return vb.test(t)?t:JSON.stringify(t)}function Mu(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 Uu(t){return t===null||["boolean","number","string"].includes(typeof t)}function Yi(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function Bu(t,e,r){if(Array.isArray(t)){for(let n of t)if(Uu(n))r.push(`${e}- ${Mu(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=Yi(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([s,i],a)=>{let c=a===0?`${e}- `:`${e} `;Vi(s,i,c,`${e} `,r)})}}return}for(let[n,o]of Yi(t))Vi(n,o,e,e,r)}function Vi(t,e,r,n,o){if(Uu(e))o.push(`${r}${Xn(t)}: ${Mu(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${Xn(t)}: []`):(o.push(`${r}${Xn(t)}:`),Bu(e,`${n} `,o));else{let s=Yi(e);if(s.length===0)o.push(`${r}${Xn(t)}: {}`);else{o.push(`${r}${Xn(t)}:`);for(let[i,a]of s)Vi(i,a,`${n} `,`${n} `,o)}}}function mr(t){let e=[];return Bu(t,"",e),e.join(`
6
6
  `)+`
7
- `}function Bl(t){return Nr(tw(t))}function Fl(t){return Nr(rw(t))}function Dn(t){return Nr(nw(t))}var As,Ar,Jk,_l,Qk,Zk,Je,jl,Nl,Ol,_s,Ll,jr,ow,js=v(()=>{"use strict";As="model/derived/INDEX.yaml",Ar="model/derived/relates.yaml";Jk=["system","container","component","code","task","adr"],_l=["contains","touched_by","correlates","relates","references","depends_on"],Qk=/^e_[0-9a-f]{8}$/;Zk=["system","task","adr"];Je={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};jl=2,Nl=5,Ol=50,_s=2e3,Ll={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},jr={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};ow=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});var Gl=v(()=>{"use strict"});var iw,RR,Kl=v(()=>{"use strict";iw=[{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"]}],RR=iw.flatMap(t=>t.phases)});function rr(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Hl,Ns=v(()=>{"use strict";Hl=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"]});function Wl(t,e){return e.toLowerCase().includes(t.toLowerCase())}function Vl(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||lw.every(o=>e.some(i=>Wl(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 cw){let i=n.find(s=>Wl(o,s.id));if(i)return i.id}return n[0].id}var pt,ql,Be,Lo,Os,Ls,sw,aw,Yl,Ds,cw,lw,Ms=v(()=>{"use strict";Ns();pt="claude",ql=[pt],Be="opus",Lo="sonnet",Os="haiku",Ls=[Be,Lo,Os],sw="build-discovery",aw=[sw],Yl=[...Hl,...aw],Ds={analyze:Be,implement:Be,"resolve-conflict":Be,rework:Be,estimate:Lo,build:Os,"build-discovery":Be,"code-review":Be,draft:Lo,index:Be,backfill:Be,analysis:Be,chat:Be},cw=[Be,Lo,Os],lw=Array.from(new Set(Object.values(Ds)))});function _t(t){return uw.has(t)?!0:dw.some(e=>t.startsWith(e))}function Do(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function nr(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function Us(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function Zl(t,e){let r=Do(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=nr(r.id,"id")??n;if(!zl.test(o))throw new Error(`id must match ${zl} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=nr(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=Do(r.env,"env");s={};for(let[d,f]of Object.entries(p)){if(!Fe.test(d))throw new Error(`env name "${d}" must match ${Fe}`);if(typeof f!="string"&&typeof f!="number"&&typeof f!="boolean")throw new Error(`env.${d} must be a scalar`);s[d]=String(f)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>Xl)throw new Error(`too many params (max ${Xl})`);let p=new Set;a=c.map((d,f)=>pw(d,f,p))}let l=r.steps;if(!Array.isArray(l)||l.length===0)throw new Error("steps must be a non-empty list");if(l.length>Jl)throw new Error(`too many steps (max ${Jl})`);let u=l.map((p,d)=>{let f=Do(p,`steps[${d}]`),m=nr(f.run,`steps[${d}].run`);if(!m||m.trim().length===0)throw new Error(`steps[${d}].run is required`);let h=nr(f.name,`steps[${d}].name`),g=Us(f.timeout_sec,`steps[${d}].timeout_sec`);if(g!==void 0&&(!Number.isInteger(g)||g<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:m,...h?{name:h}:{},...g!==void 0?{timeout_sec:g}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function pw(t,e,r){let n=Do(t,`params[${e}]`),o=nr(n.name,`params[${e}].name`);if(!o||!Fe.test(o))throw new Error(`params[${e}].name must match ${Fe}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let f=n.enum;if(!Array.isArray(f)||f.length===0||!f.every(m=>typeof m=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=f}let a=nr(n.label,`params[${e}].label`),c=nr(n.help,`params[${e}].help`),l=n.required===!0,u=Us(n.min,`params[${e}].min`),p=Us(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 eu(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 Fe,uw,dw,Ql,zl,Xl,Jl,Bs=v(()=>{"use strict";Fe=/^[A-Z][A-Z0-9_]*$/,uw=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),dw=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];Ql=600,zl=/^[a-z0-9-]+$/,Xl=32,Jl=64});var or,tu,Mn,Fs=v(()=>{"use strict";or="auto",tu=["primary","context","tasks","docs","code_comments","chat"],Mn=["English","Russian","German","Spanish","French","Portuguese","Italian","Chinese","Japanese","Korean"]});function iu(t=gw){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...iu(r.groups));return e}function hw(t,e){let r=JSON.stringify(e);return iu().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function su(t){let e=hw(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.type==="string"&&e.mustContain&&!i.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:e.maxLength!==void 0&&i.length>e.maxLength?{ok:!1,error:`${e.id} must be \u2264 ${e.maxLength} chars`}:{ok:!0,field:e,value:i}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}case"string_map":{if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,error:`${e.id} must be a name\u2192value map`};let i=Object.entries(r);if(i.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(i.length>ru)return{ok:!1,error:`${e.id} must have \u2264 ${ru} entries`};let s={};for(let[a,c]of i){if(!Fe.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Fe}`};if(_t(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>nu)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${nu} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var fw,mw,ru,nu,ou,gw,au=v(()=>{"use strict";Bs();Ms();js();Fs();fw={primary:"Primary language",context:"Context documents",tasks:"Tracker issues",docs:"Repo documentation",code_comments:"Code comments",chat:"Agent chat"},mw={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."},ru=64,nu=2e3,ou=2e3,gw=[{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:[...ql],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:[...Ls],help:"Overrides the recommended defaults for every role not listed below."},...Yl.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Ls],help:`recommended: ${Ds[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:ou,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:ou,help:`e.g. "implementation details, bullet list of what was done, in the tracker's language". Empty \u21D2 the default PR body.`}]},{id:"apply.auto_merge",label:"Auto-merge",help:"Whether CodePipe may merge the task's pull request itself, or waits for you.",fields:[{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:"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)."}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (on by default; orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on (default), a task taken from Develop waits in the QUEUE for a single Confirm before the pipeline starts \u2014 the Confirm pulls in dependency closure and topologically orders the queue. Off \u21D2 conveyor: the task starts the pipeline immediately."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]},{id:"language",label:"Language",help:"Languages the agent writes in, per area. Empty \u21D2 auto: mirror the language of the user's material.",fields:tu.map(t=>({id:`language.${t}`,file:"project.yaml",path:["language",t],type:"string",label:fw[t],nullable:!0,maxLength:40,suggestions:t==="chat"?[or,...Mn]:[...Mn],help:mw[t]}))},{id:"context.model",label:"Project map",help:"Parameters of the project map (built from git history by the CLI). Empty fields keep the defaults.",fields:[{id:"context.model.enabled",file:"regimen.yaml",path:["context","model","enabled"],type:"boolean",label:"Enable in the pipeline",nullable:!1,help:"When on, agents are asked to record intent annotations and (once available) receive an assembled context pack. Off \u21D2 the pipeline ignores the map entirely."},{id:"context.index.hub",file:"regimen.yaml",path:["context","index","hub"],type:"enum",label:"Search index on the server",nullable:!0,suggestions:["off","metadata"],help:"off (default): search runs on your machine, nothing is uploaded. metadata: paths, labels and task texts (never code) are mirrored to the server so search and structure stay available while your machine is offline. Switching back to off deletes the mirrored rows."},{id:"context.model.issue_key_pattern",file:"regimen.yaml",path:["context","model","issue_key_pattern"],type:"string",label:"Issue-key pattern (regex)",nullable:!0,maxLength:200,help:"Regex that finds tracker issue keys in commit subjects when mining task events from history. Empty \u21D2 derived from the tracker project key (e.g. DEV-\\d+)."},{id:"context.model.cochange.window_commits",file:"regimen.yaml",path:["context","model","cochange","window_commits"],type:"number",label:"History window (commits)",nullable:!0,min:50,max:5e4,help:`How many commits back from the build commit are mined. Default ${Je.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 ${Je.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 ${Je.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 ${Je.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 ${Je.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 ${Je.topK}.`}]},{id:"context.job_logs",label:"Job transcripts",help:"Whether the raw agent transcript of each job is kept in the Context Repo.",fields:[{id:"context.job_logs.enabled",file:"regimen.yaml",path:["context","job_logs","enabled"],type:"boolean",label:"Keep transcripts in the Context Repo",nullable:!1,help:"Off (default): the transcript is discarded after the run \u2014 nothing lands in the Context Repo. On: each job's raw transcript is committed as tasks/<KEY>/logs/job-<id>.jsonl for post-mortem debugging."}]},{id:"implementation",label:"Implementation",help:"How a dependency cluster is serialized into branches and PRs.",fields:[{id:"implementation.mode",file:"regimen.yaml",path:["implementation","mode"],type:"enum",label:"Implementation mode",nullable:!0,suggestions:["cluster-pr","sequential","parallel"],help:"cluster-pr (the standard mode) \u2014 one shared branch and a single PR per dependency cluster; a lone task is a cluster of one. sequential / parallel are DEPRECATED and will be removed \u2014 migrate to cluster-pr. Clearing removes the key from regimen.yaml but keeps the mode already stored for the project (it is not reset to the default)."}]}]});var cu=v(()=>{"use strict"});var lu=v(()=>{"use strict"});var uu=v(()=>{"use strict"});function du(t){return`codepipe-host-${t}`}var pu=v(()=>{"use strict"});function fu(t){return!(!t||t.length>250||!/^[A-Za-z0-9._/-]+$/.test(t)||/^[-/.]/.test(t)||/[/.]$/.test(t)||t.endsWith(".lock")||t.includes("..")||t.includes("//")||t.includes("/."))}function $t(t){return`${t}${yw}`}var ir,yw,mu=v(()=>{"use strict";ir=/^[a-z][a-z0-9-]{1,30}$/,yw="-codepipe-ctx"});var gu=v(()=>{"use strict"});var hu=v(()=>{"use strict"});function Or(t){for(let e of kw){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var kw,yu=v(()=>{"use strict";kw=[{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 ku=v(()=>{"use strict"});var wu=v(()=>{"use strict"});var bu=v(()=>{"use strict"});function $u(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function xu(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=$u(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Lr.test(r))return r;let n=$u(t);return Lr.test(n)?n:Gs}function Su(t,e){let r=new Set([...e].map(n=>n.toUpperCase()));if(!r.has(t.toUpperCase()))return t;for(let n=1;n<1e4;n++){let o=String(n),i=t.slice(0,10-o.length)+o;if(!r.has(i.toUpperCase()))return i}return t}function Bn(t){return`tasks/${t}/issue.yaml`}var vu,Uo,Gs,Lr,Ks,qR,Bo,Un,Tu=v(()=>{"use strict";vu=["bug","feature","epic"],Uo="feature",Gs="TASK",Lr=/^[A-Z][A-Z0-9]{1,9}$/;Ks={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},qR=Ks.backlog,Bo="tracker/config.yaml",Un="tracker/counter"});var Eu=v(()=>{"use strict"});function Dr(t){let e=t.match(/^git@([^:/]+):/);if(e)return e[1]??null;let r=t.match(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)/);if(r)return r[1]??null;let n=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return n?n[1]??null:null}function Fo(t){switch(t){case Fn.gitlab:return"oauth2";case Fn.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Fn,sr,Iu=v(()=>{"use strict";Fn={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};sr="x-bitbucket-api-token-auth"});var Ru=v(()=>{"use strict"});var Cu=v(()=>{"use strict";Eu();Iu();Ru()});var Au,G=v(()=>{"use strict";$l();vl();Il();js();Gl();Kl();Ns();Ms();au();Fs();Bs();cu();lu();uu();pu();mu();gu();hu();yu();ku();wu();bu();Tu();Cu();Au=20});function V(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var _e=v(()=>{"use strict"});import{existsSync as Pu,renameSync as ww}from"node:fs";function ar(t,e,r=n=>console.error(n)){if(Pu(e)||!Pu(t))return!1;try{return ww(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(n){return r(`failed to migrate ${t} \u2192 ${e}: ${n instanceof Error?n.message:String(n)} \u2014 continuing with the legacy path untouched`),!1}}var Go=v(()=>{"use strict"});import{existsSync as Ko,readFileSync as _u,readdirSync as bw,writeFileSync as $w}from"node:fs";import{dirname as vw,join as jt}from"node:path";import{parse as xw}from"yaml";function Sw(t=process.cwd()){let e=t;for(;;){if(Ko(jt(e,ft,"project.yaml")))return e;if(Ko(jt(e,Hs,"project.yaml")))return ar(jt(e,Hs),jt(e,ft))&&Ew(e),e;let r=vw(e);if(r===e)return null;e=r}}function Tw(t){let e=jt(t,ft);return Ko(e)?e:jt(t,Hs)}function Ew(t){let e=jt(t,".gitignore");if(!Ko(e))return;let r=_u(e,"utf-8"),n=r.split(/\r?\n/).map(o=>{let i=o.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?o.replace(".devpipe",".codepipe"):o}).join(`
8
- `);n!==r&&$w(e,n)}function Se(t=process.cwd()){let e=Sw(t);if(!e)return null;let r=Tw(e),n=Iw(_u(jt(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function ju(t,e,r){return bw(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 Ho(t,e=process.cwd()){try{let r=Se(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function Iw(t){let e=xw(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),n=String(e.name??r),o=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of o){if(!s||typeof s!="object")continue;let a=s,c=String(a.repo??a.repoName??""),l=String(a.name??c);if(!l||!c)continue;let u=a.host,p=u==="bitbucket"?"bitbucket":u==="gitlab"?"gitlab":"github";i.push({name:l,host:p,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l)})}return{projectId:r,name:n,repos:i}}function Nu(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}var ft,Hs,mt=v(()=>{"use strict";Go();ft=".codepipe",Hs=".devpipe"});import{homedir as Ou}from"node:os";import{mkdirSync as Rw,readFileSync as Cw,writeFileSync as Aw,existsSync as Ws}from"node:fs";import{dirname as Du,join as Wo,resolve as Pw}from"node:path";import{fileURLToPath as _w}from"node:url";function Mu(t){let e=Wo(Lu,".env");if(Ws(e)&&process.loadEnvFile(e),t){let r=Wo(Lu,"profiles",t,".env");Ws(r)&&process.loadEnvFile(r)}}function Mr(t){let e=V("CONFIG");return e||(t?Wo(Ou(),".codepipe","profiles",t,"config.json"):Wo(Ou(),".codepipe","config.json"))}function Qe(t){let e=Mr(t);if(!Ws(e))return null;let r=Cw(e,"utf-8");return JSON.parse(r)}function vt(t,e){let r=Mr(e);Rw(Du(r),{recursive:!0}),Aw(r,JSON.stringify(t,null,2)+`
9
- `,{mode:384})}function qo(t){if(t)return{cfg:Ge(t),profile:t};let e;try{e=Se()?.spec.projectId||void 0}catch{}if(e){let r=Qe(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:Ge(void 0),profile:void 0}}function Ge(t){let e=Qe(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 ${Mr(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var Lu,De=v(()=>{"use strict";_e();mt();Lu=Pw(Du(_w(import.meta.url)),"..")});import{homedir as Gu}from"node:os";import{existsSync as Ku,mkdirSync as Hu,readFileSync as Wu,writeFileSync as qu}from"node:fs";import{dirname as Yu,join as Vu}from"node:path";function zu(t,e,r){let n=W(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},oe(n)}function Xu(t,e){let r=W(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],oe(r),!0)}function Ju(t){return Object.keys(W(t)?.secrets??{}).sort()}function Yo(t,e,r){let n=W(t);if(!n)return"mismatch";let o=n.sandboxPins??{},i=o[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(o[e]=r,n.sandboxPins=o,oe(n),"pinned")}function Qu(t,e){let r=W(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],oe(r),!0):!1}function gt(t){return Vu(Gu(),".codepipe","secrets",`${t}.json`)}function W(t){let e=gt(t);return Ku(e)?JSON.parse(Wu(e,"utf-8")):null}function oe(t){let e=gt(t.projectId);Hu(Yu(e),{recursive:!0}),qu(e,JSON.stringify(t,null,2)+`
10
- `,{mode:384})}function Vo(){return Vu(Gu(),".codepipe","shared.json")}function qs(){let t=Vo();return Ku(t)?JSON.parse(Wu(t,"utf-8")):null}function Zu(t){let e=Vo();Hu(Yu(e),{recursive:!0}),qu(e,JSON.stringify(t,null,2)+`
11
- `,{mode:384})}function Ur(t){let e=W(t)?.claude?.oauthToken;return e||qs()?.claude?.oauthToken}function Gn(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 Ys){let n=e[r];n&&!process.env[r]&&(process.env[r]=n)}}function Br(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var Ys,ue=v(()=>{"use strict";Ys=["GH_TOKEN","BITBUCKET_EMAIL","BITBUCKET_API_TOKEN","GITLAB_TOKEN","YOUTRACK_URL","YOUTRACK_TOKEN"]});import{appendFileSync as jw,existsSync as td,mkdirSync as Nw,renameSync as rd,statSync as Ow,unlinkSync as Lw}from"node:fs";import{Writable as Dw}from"node:stream";import{join as Mw}from"node:path";function zo(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=Uw(process.env[`${t}_MAX_BYTES`]??String(nd.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):nd.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function Uw(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 Xo(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(Bw(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 Bw(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:Fw(o)).join(" ");return`${r} ${t} ${n}`}function Fw(t){try{return JSON.stringify(t)}catch{return String(t)}}var nd,Fr,Vs=v(()=>{"use strict";nd={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},Fr=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&Nw(e.dir,{recursive:!0}),this.currentPath=Mw(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
7
+ `}function oa(t){return mr(Ou(t))}function sa(t){return mr(Lu(t))}function Wr(t){return mr(Du(t))}var _e,hb,gb,yb,kb,zo,ur,_u,Qi,ju,wb,Je,ea,ta,ra,Jo,bb,na,fr,vb,ia=$(()=>{"use strict";_e=2,hb="model",gb="model/README.md",yb="model/facts",kb="model/derived",zo="model/derived/INDEX.yaml",ur="model/derived/relates.yaml";_u=["system","container","component","code","task","adr"],Qi=["contains","touched_by","correlates","relates","references","depends_on"],ju=/^e_[0-9a-f]{8}$/;wb=["system","task","adr"];Je={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};ea=2,ta=5,ra=50,Jo=2e3,bb=5e4,na={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},fr={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};vb=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});function xb(t){return t==="DONE"}function Sb(t){return t==="AWAITING_EXTERNAL_FIX"?!1:aa.indexOf(t)>=aa.indexOf("IMPLEMENTING")}var aa,Fu=$(()=>{"use strict";aa=["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 Rb(t){for(let e of ca)if(e.phases.includes(t))return e.id;return null}function Tb(t){for(let e of Ku)if(e.phases.includes(t))return e.id;return null}var ca,Eb,Ku,Gu=$(()=>{"use strict";ca=[{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"]}],Eb=ca.flatMap(t=>t.phases),Ku=[{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 Ib(t){return Hu.includes(t)?"planning":"implementation"}function Bt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var la,Hu,Cb,ua=$(()=>{"use strict";la=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat","observer","council","testing"],Hu=["draft","analysis","chat","observer","council"];Cb=1});function Wu(t,e){return e.toLowerCase().includes(t.toLowerCase())}function fa(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||Xu.every(o=>e.some(s=>Wu(o,s.id))))return null;let n=[...e].sort((o,s)=>{let i=o.createdAt??"",a=s.createdAt??"";return i!==a?i<a?1:-1:o.id<s.id?1:-1});for(let o of zu){let s=n.find(i=>Wu(o,i.id));if(s)return s.id}return n[0].id}function qr(){return{default:null,roles:{}}}function Ab(t,e){let r=t?.roles?.[e];return typeof r=="string"&&r.trim().length>0?r.trim():t?.default&&t.default.trim().length>0?t.default.trim():to[e]??Vu}function Pb(t){let e=t?.provider;return typeof e=="string"&&e.trim().length>0?e.trim():Ke}function _b(t){let e=qr();if(!t||typeof t!="object")return e;let r=t.llm;if(!r||typeof r!="object")return e;let n=r.provider;typeof n=="string"&&n.trim().length>0&&(e.provider=n.trim());let o=r.models;if(!o||typeof o!="object")return e;for(let[s,i]of Object.entries(o))typeof i!="string"||i.trim().length===0||(s==="default"?e.default=i.trim():e.roles[s]=i.trim());return e}function jb(t){let e=typeof t.provider=="string"&&t.provider.trim().length>0&&t.provider.trim()!==Ke;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 Nb(t){if(!t)return qr();try{let e=JSON.parse(t);if(!e||typeof e!="object")return qr();let r=e,n=qr();typeof r.provider=="string"&&r.provider.trim().length>0&&(n.provider=r.provider.trim()),typeof r.default=="string"&&(n.default=r.default);let o=r.roles;if(o&&typeof o=="object")for(let[s,i]of Object.entries(o))typeof i=="string"&&(n.roles[s]=i);return n}catch{return qr()}}var Ke,da,Re,eo,Qo,es,qu,Yu,pa,to,Vu,zu,Xu,ma=$(()=>{"use strict";ua();Ke="claude",da=[Ke],Re="opus",eo="sonnet",Qo="haiku",es=[Re,eo,Qo],qu="build-discovery",Yu=[qu],pa=[...la,...Yu],to={analyze:Re,implement:Re,"resolve-conflict":Re,rework:Re,estimate:eo,build:Qo,"build-discovery":Re,"code-review":Re,draft:eo,index:Re,backfill:Re,analysis:Re,chat:Re,observer:Re,council:Re,testing:Re},Vu=Re,zu=[Re,eo,Qo],Xu=Array.from(new Set(Object.values(to)))});function Pt(t){return Ob.has(t)?!0:Lb.some(e=>t.startsWith(e))}function ts(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function hr(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function ga(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function ka(t,e){let r=ts(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=hr(r.id,"id")??n;if(!ha.test(o))throw new Error(`id must match ${ha} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let s=hr(r.title,"title")?.trim()||o,i;if(r.env!==void 0&&r.env!==null){let p=ts(r.env,"env");i={};for(let[d,m]of Object.entries(p)){if(!Ge.test(d))throw new Error(`env name "${d}" must match ${Ge}`);if(typeof m!="string"&&typeof m!="number"&&typeof m!="boolean")throw new Error(`env.${d} must be a scalar`);i[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>Ju)throw new Error(`too many params (max ${Ju})`);let p=new Set;a=c.map((d,m)=>Db(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>Zu)throw new Error(`too many steps (max ${Zu})`);let u=l.map((p,d)=>{let m=ts(p,`steps[${d}]`),f=hr(m.run,`steps[${d}].run`);if(!f||f.trim().length===0)throw new Error(`steps[${d}].run is required`);let g=hr(m.name,`steps[${d}].name`),h=ga(m.timeout_sec,`steps[${d}].timeout_sec`);if(h!==void 0&&(!Number.isInteger(h)||h<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:f,...g?{name:g}:{},...h!==void 0?{timeout_sec:h}:{}}});return{id:o,title:s,...i?{env:i}:{},...a?{params:a}:{},steps:u}}function Db(t,e,r){let n=ts(t,`params[${e}]`),o=hr(n.name,`params[${e}].name`);if(!o||!Ge.test(o))throw new Error(`params[${e}].name must match ${Ge}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let s=n.type;if(s!=="string"&&s!=="enum"&&s!=="number"&&s!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let i;if(s==="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`);i=m}let a=hr(n.label,`params[${e}].label`),c=hr(n.help,`params[${e}].help`),l=n.required===!0,u=ga(n.min,`params[${e}].min`),p=ga(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:s,...a?{label:a}:{},...c?{help:c}:{},...l?{required:!0}:{},...i?{enum:i}:{},...u!==void 0?{min:u}:{},...p!==void 0?{max:p}:{},...d!=null?{default:d}:{}}}function wa(t,e){let r=t.params??[],n=new Map(r.map(s=>[s.name,s]));for(let s of Object.keys(e))if(!n.has(s))return{ok:!1,error:`unknown param: ${s}`};let o={};for(let s of r){let i=e[s.name];if(i==null||typeof i=="string"&&i.trim()==="")if(s.default!==void 0)i=s.default;else{if(s.required)return{ok:!1,error:`${s.name} is required`};continue}switch(s.type){case"string":{if(typeof i!="string")return{ok:!1,error:`${s.name} must be a string`};o[s.name]=i;break}case"enum":{if(typeof i!="string"||!(s.enum??[]).includes(i))return{ok:!1,error:`${s.name} must be one of: ${(s.enum??[]).join(", ")}`};o[s.name]=i;break}case"number":{let a=typeof i=="number"?i:typeof i=="string"?Number(i):NaN;if(!Number.isFinite(a))return{ok:!1,error:`${s.name} must be a number`};if(s.min!==void 0&&a<s.min)return{ok:!1,error:`${s.name} must be \u2265 ${s.min}`};if(s.max!==void 0&&a>s.max)return{ok:!1,error:`${s.name} must be \u2264 ${s.max}`};o[s.name]=a;break}case"boolean":{let a=typeof i=="boolean"?i:i==="true"?!0:i==="false"?!1:null;if(a===null)return{ok:!1,error:`${s.name} must be a boolean`};o[s.name]=a;break}}}return{ok:!0,values:o}}var Ge,Ob,Lb,ya,ha,Ju,Zu,ba=$(()=>{"use strict";Ge=/^[A-Z][A-Z0-9_]*$/,Ob=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),Lb=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];ya=600,ha=/^[a-z0-9-]+$/,Ju=32,Zu=64});function Qu(){return{primary:we,context:we,tasks:we,docs:we,code_comments:we,chat:we}}function ed(t){return!t||t.trim().length===0||t.trim().toLowerCase()===we}function Mb(t){if(typeof t!="string")return we;let e=t.trim().replace(/\s+/g," ");return e.length===0||e.length>40||e.toLowerCase()===we?we:e}function Ub(t){let e=Qu();if(!t||typeof t!="object")return e;let r=t.language;if(!r||typeof r!="object"||Array.isArray(r))return e;let n=r;for(let o of ro)e[o]=Mb(n[o]);return e}function Bb(t){return ro.every(e=>ed(t[e]))}var we,ro,Yr,no,$a=$(()=>{"use strict";we="auto",ro=["primary","context","tasks","docs","code_comments","chat"],Yr=["English","Russian","German","Spanish","French","Portuguese","Italian","Chinese","Japanese","Korean"],no=40});function Ea(t=td){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...Ea(r.groups));return e}function rd(t,e){let r=JSON.stringify(e);return Ea().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function Ra(t){let e=rd(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 s=r.trim();return e.type==="string"&&e.mustContain&&!s.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:e.maxLength!==void 0&&s.length>e.maxLength?{ok:!1,error:`${e.id} must be \u2264 ${e.maxLength} chars`}:{ok:!0,field:e,value:s}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let s=r.trim();return e.suggestions?.includes(s)?{ok:!0,field:e,value:s}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let s=r.map(i=>typeof i=="string"?i.trim():"").filter(i=>i.length>0);return s.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:s}}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 s=Object.entries(r);if(s.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(s.length>va)return{ok:!1,error:`${e.id} must have \u2264 ${va} entries`};let i={};for(let[a,c]of s){if(!Ge.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Ge}`};if(Pt(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>xa)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${xa} chars`};i[a]=c}return{ok:!0,field:e,value:i}}}}var Fb,Kb,va,xa,Sa,td,nd=$(()=>{"use strict";ba();ma();ia();$a();Fb={primary:"Primary language",context:"Context documents",tasks:"Tracker issues",docs:"Repo documentation",code_comments:"Code comments",chat:"Agent chat"},Kb={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."},va=64,xa=2e3,Sa=2e3,td=[{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:[...da],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:[...es],help:"Overrides the recommended defaults for every role not listed below."},...pa.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...es],help:`recommended: ${to[t]}`}))]}]},{id:"apply.style",label:"Commits & PRs",help:"Instructions for the AI agent on how to write commit messages and PR descriptions. Empty \u21D2 built-in templates.",fields:[{id:"apply.commit_style",file:"project.yaml",path:["apply","commit_style"],type:"string",label:"Commit message style",nullable:!0,multiline:!0,maxLength:Sa,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:Sa,help:`e.g. "implementation details, bullet list of what was done, in the tracker's language". Empty \u21D2 the default PR body.`}]},{id:"apply.delivery",label:"Delivery & merge",help:"How a finished change reaches the repository: with or without a pull request, and who merges it.",fields:[{id:"apply.pull_request",file:"project.yaml",path:["apply","pull_request"],type:"boolean",label:"Open a pull request",nullable:!1,help:"On (default): the task branch is pushed and a pull request is opened \u2014 the change is reviewable in the git host and keeps a history of review comments. Off: no PR at all; the branch is merged into the default branch directly, and the agent's review remarks live only in the dashboard and the Context Repo."},{id:"apply.done",file:"project.yaml",path:["apply","done"],type:"enum",label:"Task is done when",nullable:!1,suggestions:["merge","branch"],help:"merge (default): the task is finished only once its change lands in the default branch. branch: the task ends at the pushed branch (plus the PR, if enabled) and nothing is merged for you."},{id:"apply.auto_merge",file:"project.yaml",path:["apply","auto_merge"],type:"enum",label:"Auto-merge pull requests",nullable:!1,suggestions:["off","on_ci_green"],help:"Applies to the pull-request path only. off (default): the merge waits for you (Approve on the task card). on_ci_green: as soon as the PR is open, conflict-free and its CI is green, CodePipe merges it \u2014 changes reach the default branch with no further review from you. Requires full automation; branch protection on the host still applies (a refused merge parks the task). Without pull requests, full automation merges the branch itself and this switch does not apply."}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{id:"testing",label:"Testing",help:"An optional phase after code review: writes the test plan you run in the morning and reports what it could verify.",fields:[{id:"testing.enabled",file:"regimen.yaml",path:["testing","enabled"],type:"boolean",nullable:!1,label:"Run the testing phase",help:"Off by default. When on, a task passing code review goes through a test pass before the PR: it derives TESTPLAN.md from the plan's requirements and reports per requirement what it could verify. A requirement it finds broken sends the change back for a fix (bounded below)."},{id:"testing.max_iterations",file:"regimen.yaml",path:["testing","max_iterations"],type:"number",nullable:!0,min:1,max:10,label:"Fix rounds before stopping",help:"How many times a failed test pass may send the change back before the task waits for you. Empty \u21D2 2."}]},{id:"skills",label:"Skills",help:"Reusable procedures the agent can invoke instead of improvising. Only their names and one-line descriptions sit in the prompt; the steps load when a skill is used.",fields:[{id:"skills.from_bundled",file:"regimen.yaml",path:["skills","from_bundled"],type:"boolean",nullable:!1,label:"Use the skills shipped with CodePipe",help:"On by default. General procedures maintained with the product."},{id:"skills.from_context_repo",file:"regimen.yaml",path:["skills","from_context_repo"],type:"boolean",nullable:!1,label:"Use this project's skills",help:"On by default. Skills the team writes in the context repository under `skills/<name>/SKILL.md`. These override a bundled skill of the same name."},{id:"skills.from_project_repo",file:"regimen.yaml",path:["skills","from_project_repo"],type:"boolean",nullable:!1,label:"Use the code repository's skills",help:"On by default. `.claude/skills/` inside the project repositories \u2014 the skills your developers already use locally. These win over both other sources."}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (on by default; orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on (default), a task taken from Develop waits in the QUEUE for a single Confirm before the pipeline starts \u2014 the Confirm pulls in dependency closure and topologically orders the queue. Off \u21D2 conveyor: the task starts the pipeline immediately."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]},{id:"language",label:"Language",help:"Languages the agent writes in, per area. Empty \u21D2 auto: mirror the language of the user's material.",fields:ro.map(t=>({id:`language.${t}`,file:"project.yaml",path:["language",t],type:"string",label:Fb[t],nullable:!0,maxLength:40,suggestions:t==="chat"?[we,...Yr]:[...Yr],help:Kb[t]}))},{id:"context.model",label:"Project map",help:"Parameters of the project map (built from git history by the CLI). Empty fields keep the defaults.",fields:[{id:"context.model.enabled",file:"regimen.yaml",path:["context","model","enabled"],type:"boolean",label:"Enable in the pipeline",nullable:!1,help:"When on, agents are asked to record intent annotations and (once available) receive an assembled context pack. Off \u21D2 the pipeline ignores the map entirely."},{id:"context.index.hub",file:"regimen.yaml",path:["context","index","hub"],type:"enum",label:"Search index on the server",nullable:!0,suggestions:["off","metadata"],help:"off (default): search runs on your machine, nothing is uploaded. metadata: paths, labels and task texts (never code) are mirrored to the server so search and structure stay available while your machine is offline. Switching back to off deletes the mirrored rows."},{id:"context.model.issue_key_pattern",file:"regimen.yaml",path:["context","model","issue_key_pattern"],type:"string",label:"Issue-key pattern (regex)",nullable:!0,maxLength:200,help:"Regex that finds tracker issue keys in commit subjects when mining task events from history. Empty \u21D2 derived from the tracker project key (e.g. DEV-\\d+)."},{id:"context.model.cochange.window_commits",file:"regimen.yaml",path:["context","model","cochange","window_commits"],type:"number",label:"History window (commits)",nullable:!0,min:50,max:5e4,help:`How many commits back from the build commit are mined. Default ${Je.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 ${Je.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 ${Je.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 ${Je.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 ${Je.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 ${Je.topK}.`}]},{id:"context.job_logs",label:"Job transcripts",help:"Whether the raw agent transcript of each job is kept in the Context Repo.",fields:[{id:"context.job_logs.enabled",file:"regimen.yaml",path:["context","job_logs","enabled"],type:"boolean",label:"Keep transcripts in the Context Repo",nullable:!1,help:"Off (default): the transcript is discarded after the run \u2014 nothing lands in the Context Repo. On: each job's raw transcript is committed as tasks/<KEY>/logs/job-<id>.jsonl for post-mortem debugging."}]}]});function od(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 Ia(t){let{name:e,body:r,origin:n}=t;if(!Ta.test(e))return{ok:!1,error:`role name must match ${Ta} (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 s=o,i=s.description;if(typeof i!="string"||i.trim().length===0)return{ok:!1,error:"description is required (one line: what this role looks for)"};if(i.length>300)return{ok:!1,error:"description must be \u2264 300 characters"};let a=od(s.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=od(s.scenarios);if(c===null)return{ok:!1,error:"scenarios must be a list"};let l=[];for(let d of c){if(!rs.includes(d))return{ok:!1,error:`unknown scenario "${d}" \u2014 one of: ${rs.join(", ")}`};l.includes(d)||l.push(d)}if(l.length===0)return{ok:!1,error:`scenarios must name at least one of: ${rs.join(", ")}`};let u=s.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=s.enabled;return p!==void 0&&typeof p!="boolean"?{ok:!1,error:"enabled must be true or false"}:{ok:!0,role:{name:e,description:i.trim(),...typeof u=="string"?{model:u.trim()}:{},refs:a,scenarios:l,enabled:p!==!1,body:r.trim(),origin:n}}}function Ca(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 Aa(t,e){return t.filter(r=>r.enabled&&r.scenarios.includes(e))}var rs,Ta,AP,PP,sd=$(()=>{"use strict";rs=["plan_review","code_review","council"],Ta=/^[a-z][a-z0-9-]{1,39}$/,AP=10,PP=300});function Pa(t){return id.includes(t)}function _a(t){return`prompts/${t}.md`}var id,ad=$(()=>{"use strict";id=["analysis","analyze","backfill","build","chat","code-review","code-review-external","code-review-fix","council","draft","estimate","implement","index","observer","resolve-conflict","rework","testing"]});function Na(t){if(!ja.test(t.name))return{ok:!1,error:`skill directory name must match ${ja}`};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 Oa(t,e,r){let n=new Map;for(let o of[...t,...e,...r])n.set(o.name,o);return[...n.values()].sort((o,s)=>o.name<s.name?-1:o.name>s.name?1:0)}function ld(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(!Gb.test(n))return{ok:!1,error:`"${t}": expected <owner>/<repo>[@<40-hex sha>]`};let s=cd.find(i=>i.repo.toLowerCase()===n.toLowerCase());return o&&!Hb.test(o)?{ok:!1,error:`"${t}": pin to a full 40-character commit sha \u2014 a branch or tag can change under you`}:!s&&!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:s?.name??n.replace("/","-").toLowerCase(),official:!!s}}}function Wb(t){let e=[],r=[],n=new Set;for(let o of t){if(!o.trim())continue;let s=ld(o);if(!s.ok){r.push(s.error);continue}n.has(s.source.name)||(n.add(s.source.name),e.push(s.source))}return{sources:e,errors:r}}function Yb(t,e){let r=new Set(e.map(s=>s.name)),n={},o=[];for(let s of t){let i=s.trim();if(i){if(!qb.test(i)||!r.has(i.slice(i.indexOf("@")+1))){o.push(i);continue}n[i]=!0}}return{enabled:n,unknown:o}}var ja,NP,cd,Gb,Hb,qb,ud=$(()=>{"use strict";ja=/^[a-z][a-z0-9-]{1,39}$/,NP=300;cd=[{repo:"anthropics/skills",name:"anthropic-agent-skills"},{repo:"anthropics/claude-plugins-official",name:"claude-plugins-official"}],Gb=/^[A-Za-z0-9][\w.-]*\/[A-Za-z0-9][\w.-]*$/,Hb=/^[0-9a-f]{40}$/;qb=/^[A-Za-z0-9][\w.-]*@[A-Za-z0-9][\w.-]*$/});function dd(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 Vb(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=dd(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 s=e.filter(f=>!o.includes(f));if(o.length>0&&s.length>0)return{ok:!1,error:`order omits ${s.join(", ")}`};let i=n.tasks,a=[];if(i!=null){if(!Array.isArray(i))return{ok:!1,error:"tasks must be a list"};for(let f of i){if(!f||typeof f!="object")return{ok:!1,error:"each task entry must be an object"};let g=f,h=typeof g.taskKey=="string"?g.taskKey.trim():"";if(!r.has(h))return{ok:!1,error:`tasks names ${h||"(empty)"}, which is not in this batch`};let w=dd(g.after,e.length);if(w===null)return{ok:!1,error:`${h}: after must be a list of task keys`};for(let x of w){if(!r.has(x))return{ok:!1,error:`${h}: after names ${x}, not in this batch`};if(x===h)return{ok:!1,error:`${h}: cannot come after itself`}}let y=typeof g.decisions=="string"?g.decisions.trim():"";a.push({taskKey:h,decisions:y.slice(0,4e3),after:w})}}let c=[],l=n.conflicts;if(Array.isArray(l))for(let f of l){if(!f||typeof f!="object")continue;let g=f,h=typeof g.taskKey=="string"?g.taskKey.trim():"",w=typeof g.adr=="string"?g.adr.trim():"",y=typeof g.detail=="string"?g.detail.trim():"";!r.has(h)||!y||c.push({taskKey:h,adr:w,detail:y.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,h=typeof g.taskKey=="string"?g.taskKey.trim():"",w=typeof g.detail=="string"?g.detail.trim():"";!h||!w||u.push({taskKey:h,detail:w.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 LP,DP,pd=$(()=>{"use strict";LP=4e3,DP=4e3});function zb(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 s=r.answers;if(!Array.isArray(s))return{ok:!1,error:"answers must be a list"};if(s.length!==e.length)return{ok:!1,error:`expected ${e.length} answer(s), got ${s.length}`};let i=[];for(let[a,c]of s.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`};i.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:i,unresolved:!1,fork:""}}}var UP,fd=$(()=>{"use strict";UP=4e3});function Zb(t){let e=t.replace(/^#+\s*/,"").trim();for(let r of Xb)if(r.re.test(e))return{kind:r.kind,letter:r.letter};return null}function La(t){let e=[],r=new Map,n="",o=null,s=null;for(let a of t.split(`
8
+ `)){let c=/^#{1,6}\s+(.*)$/.exec(a);if(c){n=c[1].trim(),o=Zb(n),s=null;continue}let l=Jb.exec(a);if(l&&o){let u=l[1];r.set(u,(r.get(u)??0)+1),s={id:u,kind:o.kind,text:l[2].trim(),section:n},e.push(s);continue}if(s&&a.trim()&&!/^#{1,6}\s/.test(a)&&!/^\s*[-*]\s/.test(a)){s.text=`${s.text}
9
+ ${a.trim()}`.trim();continue}a.trim()||(s=null)}let i=[...r.entries()].filter(([,a])=>a>1).map(([a])=>a);return{items:e,structured:e.length>=2&&i.length===0,duplicateIds:i}}function Qb(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 e$(t,e){let r=new Map(t.items.map(i=>[i.id,i])),n=e.filter(i=>!i.approved),o=e.filter(i=>i.approved).map(i=>i.id);if(n.length===0)return"";let s=["Rejected plan items:",""];for(let i of n){let a=r.get(i.id),c=a?`${i.id} \u2014 ${a.text.split(`
10
+ `)[0]}`:i.id;s.push(`- **${c}**`),i.remark?.trim()&&s.push(` ${i.remark.trim()}`)}return o.length>0&&s.push("",`Approved and settled: ${o.join(", ")}. Do not revisit these unless a`,"rejected item forces it \u2014 and say so explicitly if it does."),s.join(`
11
+ `)}function Da(t){let e=new Set;for(let r of t.items)if(r.kind==="procedure")for(let n of r.text.matchAll(t$))e.add(n[1]);return[...e]}var Xb,Jb,t$,md=$(()=>{"use strict";Xb=[{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"}],Jb=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*(.*)$/;t$=/`([a-z][a-z0-9-]{1,39})`/g});function o$(t){let e=[],r=null;for(let o of t.split(`
12
+ `)){let s=n$.exec(o);if(s){r={id:s[1],status:s[2].toLowerCase(),text:s[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 s$(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 r$,n$,hd=$(()=>{"use strict";r$=["done","deviated","partial","dropped"],n$=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*[—:-]?\s*(done|deviated|partial|dropped)\b\s*[—:-]?\s*(.*)$/i});var gd=$(()=>{"use strict"});var yd=$(()=>{"use strict"});var kd=$(()=>{"use strict"});function Ma(t){return`codepipe-host-${t}`}function i$(t){let e=t.filter(r=>r!=="self-hosted");return`runs-on: [self-hosted${e.length?", "+e.join(", "):""}]`}var wd=$(()=>{"use strict"});function a$(t,e){return(t&&t.includes("<TASK_ID>")?t:bd).replace(/<TASK_ID>/g,e.toLowerCase())}function c$(t,e){if(t)return`${t.replace(/\/+$/,"")}/issue/${encodeURIComponent(e)}`}function Ua(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 wt(t){return`${t}${$d}`}var bd,Ft,$d,vd=$(()=>{"use strict";bd="codepipe/<TASK_ID>";Ft=/^[a-z][a-z0-9-]{1,30}$/,$d="-codepipe-ctx"});function l$(t,e){return`${t}:${e}`}var xd=$(()=>{"use strict"});function Sd(t){let e=(t??"").trim();return/^pr_closed_without_merge\b/.test(e)?"blocked":/^(merge_failed|close_failed)\b/.test(e)||/^chain_base_changed\b/.test(e)?"conflict":/^(build_failed|ci_failed)\b/.test(e)?"loop_exhausted":"error"}function u$(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.to==="NEEDS_MANUAL")return r}return null}function d$(t,e){if(t==="AWAITING_ANSWER")return{kind:"question"};if(t==="NEEDS_MANUAL"){let n=u$(e)?.reason,o={kind:Sd(n)};return n&&(o.reason=n),o}}var Ed=$(()=>{"use strict"});function gr(t){for(let e of Rd){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var Rd,Td=$(()=>{"use strict";Rd=[{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 Id=$(()=>{"use strict"});function Cd(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 p$(t,e=Date.now()){return`${Cd((e-t)/1e3)} ago`}function f$(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 Ad=$(()=>{"use strict"});var Pd=$(()=>{"use strict"});function _d(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function Fa(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=_d(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(yr.test(r))return r;let n=_d(t);return yr.test(n)?n:ns}function Ka(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),s=t.slice(0,10-o.length)+o;if(!r.has(s.toUpperCase()))return s}return t}function zr(t){return`tasks/${t}/issue.yaml`}var Ba,oo,ns,yr,os,m$,so,Vr,jd=$(()=>{"use strict";Ba=["bug","feature","epic"],oo="feature",ns="TASK",yr=/^[A-Z][A-Z0-9]{1,9}$/;os={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},m$=os.backlog,so="tracker/config.yaml",Vr="tracker/counter"});var h$,Nd=$(()=>{"use strict";h$="youtrack"});function kr(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 io(t){switch(t){case Xr.gitlab:return"oauth2";case Xr.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Xr,Kt,Od=$(()=>{"use strict";Xr={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Kt="x-bitbucket-api-token-auth"});var Ld=$(()=>{"use strict"});var Dd=$(()=>{"use strict";Nd();Od();Ld()});var Md={};Be(Md,{ACTION_ID_RE:()=>ha,ACTION_STEP_DEFAULT_TIMEOUT_SEC:()=>ya,ALL_JOB_ROLES:()=>la,ALL_MODEL_ROLE_KEYS:()=>pa,ANALYSIS_MAX_DRAFTS:()=>Ga,ANNOTATION_MAX_PER_TASK:()=>ta,BACKFILL_MAX_DRAFTS:()=>g$,BITBUCKET_API_TOKEN_GIT_USER:()=>Kt,BUILD_DISCOVERY:()=>qu,COCHANGE_DEFAULTS:()=>Je,CODEPIPE_COMMANDS:()=>Rd,COMMIT_STYLE_MAX_LENGTH:()=>Sa,CONTEXT_PACK_DECAY:()=>na,CONTEXT_PACK_DEFAULTS:()=>fr,CONTEXT_REPO_SUFFIX:()=>$d,CONTEXT_STAMP_FILE:()=>ct,CONTEXT_TEMPLATE_CHANGELOG:()=>Gi,CONTEXT_TEMPLATE_VERSION:()=>Cu,COUNCIL_MAX_ANSWER:()=>UP,DEFAULT_BRANCH_PATTERN:()=>bd,DEFAULT_HUB_URL:()=>it,DEFAULT_INTERNAL_ISSUE_TYPE:()=>oo,DEFAULT_INTERNAL_TRACKER_PREFIX:()=>ns,DEFAULT_LLM_PROVIDER:()=>Ke,DEFAULT_REGIMEN_ALIASES:()=>Xu,DEFAULT_TRACKER_PROVIDER:()=>h$,ENV_NAME_RE:()=>Ge,FALLBACK_MODEL:()=>Vu,GIT_HOST_DOMAINS:()=>Xr,INTERNAL_ISSUE_TYPES:()=>Ba,INTERNAL_TRACKER_CONFIG_PATH:()=>so,INTERNAL_TRACKER_COUNTER_PATH:()=>Vr,INTERNAL_TRACKER_DEFAULT_STATUS:()=>m$,INTERNAL_TRACKER_PREFIX_RE:()=>yr,INTERNAL_TRACKER_STATUSES:()=>os,LANE_PHASES:()=>Eb,LANE_SEGMENTS:()=>ca,LANGUAGE_AUTO:()=>we,LANGUAGE_SUGGESTIONS:()=>Yr,LANGUAGE_VALUE_MAX_LENGTH:()=>no,LEGACY_CONTEXT_STAMP_FILE:()=>Gr,LLM_PROVIDER_SUGGESTIONS:()=>da,MIN_SUPPORTED_PROTOCOL:()=>Ru,MODEL_ALIAS_SUGGESTIONS:()=>es,MODEL_DERIVED_DIR:()=>kb,MODEL_DERIVED_INDEX_PATH:()=>zo,MODEL_DIR:()=>hb,MODEL_EDGE_KINDS:()=>Qi,MODEL_ENTITY_ID_RE:()=>ju,MODEL_FACTS_DIR:()=>yb,MODEL_FAMILY_PREFERENCE:()=>zu,MODEL_HAIKU:()=>Qo,MODEL_LEVELS:()=>_u,MODEL_OPUS:()=>Re,MODEL_README_PATH:()=>gb,MODEL_RELATES_PATH:()=>ur,MODEL_SEARCH_MAX_LIMIT:()=>ra,MODEL_SEARCH_MAX_ROWS:()=>bb,MODEL_SEARCH_ROW_TEXT_MAX:()=>Jo,MODEL_SONNET:()=>eo,MODEL_SUB_ROLES:()=>Yu,OBSERVER_MAX_DECISION:()=>LP,OBSERVER_MAX_SUMMARY:()=>DP,OFFICIAL_MARKETPLACES:()=>cd,PHASES:()=>aa,PIPELINE_COLUMNS:()=>Ku,PLANNING_LANE_MAX_JOBS:()=>Cb,PLANNING_ROLES:()=>Hu,PLATFORM_VERSION:()=>Fe,PROJECT_ID_RE:()=>Ft,PROJECT_LANGUAGE_SECTIONS:()=>ro,PROJECT_MODEL_FORMAT_VERSION:()=>_e,PROJECT_SETTINGS_MANIFEST:()=>td,PROMPT_ROLES:()=>id,PROTOCOL_VERSION:()=>at,RECOMMENDED_ROLE_MODELS:()=>to,RELATES_MIN_OVERLAP:()=>ea,ROLE_MAX_DESCRIPTION:()=>PP,ROLE_MAX_REFS:()=>AP,ROLE_NAME_RE:()=>Ta,ROLE_SCENARIOS:()=>rs,SKILL_MAX_DESCRIPTION:()=>NP,SKILL_NAME_RE:()=>ja,SOLUTION_STATUSES:()=>r$,STRING_MAP_MAX_ENTRIES:()=>va,STRING_MAP_MAX_VALUE_LENGTH:()=>xa,additionsSince:()=>Wi,ago:()=>p$,attentionFor:()=>d$,autoLanguageConfig:()=>Qu,autoModelDefault:()=>fa,canonicalizeModelEdgeSheet:()=>Nu,canonicalizeModelIdentityTable:()=>Lu,canonicalizeModelShard:()=>Ou,canonicalizeModelTaskEvent:()=>Du,changesSince:()=>qi,classifyAttentionReason:()=>Sd,compilePlanRework:()=>e$,contextRepoName:()=>wt,deserializeModelConfig:()=>Nb,emptyModelConfig:()=>qr,enabledPluginsSetting:()=>Yb,extractLanguageConfig:()=>Ub,findSettingField:()=>rd,firstFreeInternalTrackerPrefix:()=>Ka,flattenSettingFields:()=>Ea,fmtDuration:()=>Cd,fmtUptime:()=>f$,ghRunnerHostLabel:()=>Ma,ghRunnerRunsOnSnippet:()=>i$,gitCloneUrlDomain:()=>kr,httpsTokenUser:()=>io,internalIssueYamlPath:()=>zr,isAllAutoLanguage:()=>Bb,isAutoLanguage:()=>ed,isBodyEditFrozen:()=>Sb,isModelEntityId:()=>Xo,isPromptRole:()=>Pa,isProtocolCompatible:()=>Vn,isReservedEnvName:()=>Pt,isTerminalPhase:()=>xb,isValidBranchName:()=>Ua,jobLane:()=>Ib,laneSegmentForPhase:()=>Rb,makeTaskId:()=>l$,mergeRoles:()=>Ca,mergeSkills:()=>Oa,mismatchedIds:()=>Qb,modelAnnotationPath:()=>zi,modelComponentSlug:()=>Pu,modelCorrelatesPath:()=>Xi,modelEventPath:()=>dr,modelIdentityPath:()=>Jn,modelNodeKey:()=>me,modelShardNeedsRebuild:()=>$b,modelStructureShardPath:()=>Zi,modelTaskNodeKey:()=>ke,modelTouchedPath:()=>Ji,parseActionDefinition:()=>ka,parseCodepipeCommand:()=>gr,parseContextStamp:()=>Hi,parseMarketplaceSource:()=>ld,parseMarketplaces:()=>Wb,parseModelConfig:()=>_b,parseModelNodeKey:()=>re,parsePlanItems:()=>La,parseSolutionItems:()=>o$,pipelineColumnForPhase:()=>Tb,prescribedSkills:()=>Da,promptOverridePath:()=>_a,renderContextStamp:()=>zn,resolveBranchName:()=>a$,resolveModelForRole:()=>Ab,resolveProvider:()=>Pb,rolesForScenario:()=>Aa,serializeModelConfig:()=>jb,serializeModelEdgeSheet:()=>pr,serializeModelIdentityTable:()=>sa,serializeModelShard:()=>oa,serializeModelTaskEvent:()=>Wr,serializeModelYaml:()=>mr,solutionCoverage:()=>s$,suggestInternalTrackerPrefix:()=>Fa,validateActionInput:()=>wa,validateCouncilVerdict:()=>zb,validateModelEdgeSheet:()=>Zn,validateModelIdentityTable:()=>Qn,validateModelShard:()=>Ct,validateModelTaskEvent:()=>At,validateObserverPlan:()=>Vb,validateRoleDefinition:()=>Ia,validateSettingEdit:()=>Ra,validateSkill:()=>Na,youtrackIssueUrl:()=>c$,zeroUsage:()=>Bt});var Ga,g$,F=$(()=>{"use strict";Tu();Iu();Au();ia();Fu();Gu();ua();ma();nd();$a();ba();sd();ad();ud();pd();fd();md();hd();gd();yd();kd();wd();vd();xd();Ed();Td();Id();Ad();Pd();jd();Dd();Ga=20,g$=15});function J(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Le=$(()=>{"use strict"});import{existsSync as y$,readFileSync as k$,readdirSync as w$}from"node:fs";import{dirname as b$,join as Ha}from"node:path";import{parse as $$}from"yaml";function v$(t=process.cwd()){let e=t;for(;;){if(y$(Ha(e,_t,"project.yaml")))return e;let r=b$(e);if(r===e)return null;e=r}}function x$(t){return Ha(t,_t)}function Te(t=process.cwd()){let e=v$(t);if(!e)return null;let r=x$(e),n=S$(k$(Ha(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function Ud(t,e,r){return w$(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 ss(t,e=process.cwd()){try{let r=Te(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function S$(t){let e=$$(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:[],s=[];for(let i of o){if(!i||typeof i!="object")continue;let a=i,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";s.push({name:l,host:p,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l)})}return{projectId:r,name:n,repos:s}}function Bd(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 _t,bt=$(()=>{"use strict";_t=".codepipe"});import{homedir as Fd}from"node:os";import{mkdirSync as E$,readFileSync as R$,writeFileSync as T$,existsSync as Wa}from"node:fs";import{dirname as Gd,join as is,resolve as I$}from"node:path";import{fileURLToPath as C$}from"node:url";function Hd(t){let e=is(Kd,".env");if(Wa(e)&&process.loadEnvFile(e),t){let r=is(Kd,"profiles",t,".env");Wa(r)&&process.loadEnvFile(r)}}function Jr(t){let e=J("CONFIG");return e||(t?is(Fd(),".codepipe","profiles",t,"config.json"):is(Fd(),".codepipe","config.json"))}function ut(t){let e=Jr(t);if(!Wa(e))return null;let r=R$(e,"utf-8");return JSON.parse(r)}function jt(t,e){let r=Jr(e);E$(Gd(r),{recursive:!0}),T$(r,JSON.stringify(t,null,2)+`
14
+ `,{mode:384})}function as(t){if(t)return{cfg:Ze(t),profile:t};let e;try{e=Te()?.spec.projectId||void 0}catch{}if(e){let r=ut(e);if(r)return console.log(`[profile] ${e} \u2014 resolved from this folder's workspace`),{cfg:r,profile:e};console.error(`this folder is the workspace of project '${e}', but that CLI profile is not initialised on this machine \u2014 run \`codepipe init\` here (or pass --profile).`),process.exit(1)}return{cfg:Ze(void 0),profile:void 0}}function Ze(t){let e=ut(t);if(!e){let r=t?`codepipe init --profile ${t} --hub <url> --token <token> --project ${t}`:"codepipe init --hub <url> --token <token> --project <id>";console.error(t?`CLI profile '${t}' is not initialised. run \`${r}\` first.`:`CLI is not initialised. run \`${r}\` first.`),process.exit(1)}return e.projectId||(console.error(`config at ${Jr(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var Kd,He=$(()=>{"use strict";Le();bt();Kd=I$(Gd(C$(import.meta.url)),"..")});import{homedir as Wd}from"node:os";import{existsSync as qd,mkdirSync as Yd,readFileSync as Vd,writeFileSync as zd}from"node:fs";import{dirname as Xd,join as Jd}from"node:path";function Zd(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},ie(n)}function Qd(t,e){let r=q(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],ie(r),!0)}function ep(t){return Object.keys(q(t)?.secrets??{}).sort()}function cs(t,e,r){let n=q(t);if(!n)return"mismatch";let o=n.sandboxPins??{},s=o[e];return s&&s===r?"ok":s&&s!==r?"mismatch":(o[e]=r,n.sandboxPins=o,ie(n),"pinned")}function tp(t,e){let r=q(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],ie(r),!0):!1}function $t(t){return Jd(Wd(),".codepipe","secrets",`${t}.json`)}function q(t){let e=$t(t);return qd(e)?JSON.parse(Vd(e,"utf-8")):null}function ie(t){let e=$t(t.projectId);Yd(Xd(e),{recursive:!0}),zd(e,JSON.stringify(t,null,2)+`
15
+ `,{mode:384})}function ls(){return Jd(Wd(),".codepipe","shared.json")}function qa(){let t=ls();return qd(t)?JSON.parse(Vd(t,"utf-8")):null}function rp(t){let e=ls();Yd(Xd(e),{recursive:!0}),zd(e,JSON.stringify(t,null,2)+`
16
+ `,{mode:384})}function Zr(t){let e=q(t)?.claude?.oauthToken;return e||qa()?.claude?.oauthToken}function ao(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 Ya){let n=e[r];n&&!process.env[r]&&(process.env[r]=n)}}function Qr(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var Ya,pe=$(()=>{"use strict";Ya=["GH_TOKEN","BITBUCKET_EMAIL","BITBUCKET_API_TOKEN","GITLAB_TOKEN","YOUTRACK_URL","YOUTRACK_TOKEN"]});import{appendFileSync as A$,existsSync as op,mkdirSync as P$,renameSync as sp,statSync as _$,unlinkSync as j$}from"node:fs";import{Writable as N$}from"node:stream";import{join as O$}from"node:path";function us(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,s=L$(process.env[`${t}_MAX_BYTES`]??String(ip.maxBytes)),i=process.env[`${t}_MAX_FILES`],a=i?Math.max(1,Number(i)):ip.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:s,maxFiles:a}}function L$(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 ds(t){let e={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},r=(n,o)=>(...s)=>{n(...s);try{t.writeLine(D$(o,s))}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 D$(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:M$(o)).join(" ");return`${r} ${t} ${n}`}function M$(t){try{return JSON.stringify(t)}catch{return String(t)}}var ip,en,Va=$(()=>{"use strict";ip={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},en=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&P$(e.dir,{recursive:!0}),this.currentPath=O$(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
12
17
  `)?e:e+`
13
- `;jw(this.currentPath,r,"utf-8")}asWritable(){return new Dw({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||!td(this.currentPath)||Ow(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;td(n)&&(r>=this.cfg.maxFiles?Lw(n):rd(n,`${this.currentPath}.${r+1}`))}rd(this.currentPath,`${this.currentPath}.1`)}}}});import{createHash as Gw}from"node:crypto";import{existsSync as Kw,readFileSync as Hw}from"node:fs";import{homedir as Ww,hostname as zs}from"node:os";import{join as qw}from"node:path";function od(t){return Gw("sha256").update(t).digest("hex").slice(0,12)}function Yw(){let t=V("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=qw(Ww(),".claude","credentials.json");if(!Kw(e))return;let r=JSON.parse(Hw(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 id(t){let e=Yw(),r=V("ACCOUNT_ID")?.trim(),n=V("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=Ur(t);return o?{accountId:`acct-${od(o)}`,label:n||zs(),...e?{email:e}:{}}:{accountId:`acct-${od(`host:${zs()}`)}`,label:n||zs(),...e?{email:e}:{}}}var sd=v(()=>{"use strict";_e();ue()});function Qo(t){return t===429||t>=500}function ad(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
14
- `+t.slice(t.length-e)}async function Nt(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),Jo);try{let i;try{i=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new Ke(`cannot reach api.github.com (${l instanceof Error?l.message:String(l)})`)}if(i.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(Qo(i.status))throw new Ke(`api.github.com \u2192 ${i.status} ${i.statusText}`);if(!i.ok)throw new Error(`GitHub \u2192 ${i.status} ${i.statusText}`);let a=(await i.json()).login??"ok",c=i.headers.get("x-oauth-scopes");if(c!==null&&e&&!c.split(",").map(u=>u.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${c||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let l;try{let u=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});u.ok&&(l=(await u.json()).type)}catch{}if(l==="Organization"){let u=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});if(u.status===403)throw new Error(`token cannot access org "${e.owner}" (403) \u2014 for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens; for classic PATs: verify 'repo' or 'admin:org' scope`);if(u.status===404)throw new Error(`org "${e.owner}" not found or not visible to this token \u2014 check the org name; for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens`);if(!u.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${u.status} ${u.statusText}`)}}return a}finally{clearTimeout(o)}}async function Zo(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),Jo);try{let s;try{s=await fetch(n,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},signal:o.signal})}catch(c){throw new Ke(`cannot reach api.github.com (${c instanceof Error?c.message:String(c)})`)}if(s.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(s.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(Qo(s.status))throw new Ke(`api.github.com \u2192 ${s.status} ${s.statusText}`);if(!s.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${s.status} ${s.statusText}`);if((await s.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}finally{clearTimeout(i)}}async function Ot(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(),Jo);try{let s;try{s=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new Ke(`cannot reach api.bitbucket.org (${c instanceof Error?c.message:String(c)})`)}if(s.ok)return t;if(s.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;if(Qo(s.status))throw new Ke(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await Vw(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 Vw(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function ei(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=cd.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: ${cd.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function Lt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Jo);try{let n;try{n=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"},signal:e.signal})}catch(i){throw new Ke(`cannot reach gitlab.com (${i instanceof Error?i.message:String(i)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(Qo(n.status))throw new Ke(`gitlab.com \u2192 ${n.status} ${n.statusText}`);if(!n.ok)throw new Error(`GitLab \u2192 ${n.status} ${n.statusText}`);return(await n.json()).username??"ok"}finally{clearTimeout(r)}}async function ld(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 zw(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 Xs(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 Ze(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new Qs(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new Js(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new Zs(e)}return new ea}var cr,Ke,Jo,cd,Js,Qs,Zs,ea,Dt=v(()=>{"use strict";cr=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},Ke=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},Jo=5e3;cd=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];Js=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 cr(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){let i=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:o})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:n}})});if(!o.ok)throw new Error(`bitbucket comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},Qs=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 cr(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),a=!1,c=!1,l=!1;if(i.ok){let u=await i.json();for(let p of u.check_runs??[])l=!0,p.status!=="completed"?a=!0:p.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(p.conclusion)&&(c=!0)}if(s.ok){let u=await s.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${o}/pulls/${r}`,{headers:n});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${o}/actions/runs?head_sha=${a}&per_page=20`,{headers:n});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],u=[];for(let p of l.filter(d=>d.conclusion&&i.includes(d.conclusion))){let d=await fetch(`${o}/actions/runs/${p.id}/jobs?per_page=50`,{headers:n});if(!d.ok)continue;let f=(await d.json()).jobs??[];for(let m of f.filter(h=>h.conclusion==="failure")){let h=await fetch(`${o}/actions/jobs/${m.id}/logs`,{headers:n});if(!h.ok)continue;let g=await h.text();u.push(`### CI job: ${m.name}
15
-
16
- ${ad(g,8e3)}`)}}return u.length===0?void 0:ad(u.join(`
17
-
18
- `),16e3)}catch{return}}async mergePR(e,r,n,o){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},Zs=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 cr(`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=zw(i.head_pipeline?.status??i.pipeline?.status),a=i.merge_status==="cannot_be_merged"||i.has_conflicts===!0?"conflict":i.merge_status==="can_be_merged"&&i.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:s,mergeable:a}}async mergePR(e,r,n,o){let i=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,s,a=await fetch(i,{headers:this.headers()});if(a.ok){let u=await a.json().catch(()=>null);s=u?.sha??u?.diff_refs?.head_sha}let c=await fetch(`${i}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:n==="squash",should_remove_source_branch:o,...s?{sha:s}:{}})});if(!c.ok)throw new Error(`gitlab merge MR !${r}: ${c.status} ${await c.text()}`);let l=await c.json().catch(()=>null);return l?.merge_commit_sha?{mergedSha:l.merge_commit_sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`gitlab comment MR !${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!o.ok)throw new Error(`gitlab close MR !${r}: ${o.status} ${await o.text()}`)}};ea=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(Xs(e,r,"merge"))}async closePR(e,r,n){throw new Error(Xs(e,r,"close"))}async addPRComment(e,r,n){throw new Error(Xs(e,r,"comment"))}}});import{X509Certificate as pd}from"node:crypto";import{readFileSync as Xw}from"node:fs";import Mt from"node:tls";function Jw(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function gd(t=md){if(ud)return;ud=!0;let e=V("EXTRA_CA_FILE");if(!(!e||!fd))try{let r=Jw(Xw(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Mt.setDefaultCACertificates([...Mt.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 hd(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 Qw(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
19
- `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function Zw(t,e,r){return new Promise((n,o)=>{let i=Mt.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 pd(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function ta(t,e,r){return new Promise(n=>{let o=Mt.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 eb(t){try{let e=await fetch(t);return e.ok?new pd(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function yd(t,e=443,r=md){let n=`${t}:${e}`,o=dd.get(n);if(o)return o;let i=tb(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return dd.set(n,i),i}async function tb(t,e,r){if(!fd)return!1;let n=8e3;if(await ta(t,e,n))return!0;let o=await Zw(t,e,n),i=Mt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=Qw(o);if(!c)break;let l=await eb(c);if(!l)break;if(s.push(l.toString()),Mt.setDefaultCACertificates([...i,...s]),await ta(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 ta(t,e,n)}var fd,ud,dd,md,kd=v(()=>{"use strict";_e();fd=typeof Mt.getCACertificates=="function"&&typeof Mt.setDefaultCACertificates=="function",ud=!1,dd=new Map,md=t=>console.warn(t)});function vd(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function He(t,e,r){gd();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(hd(s)&&await yd(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function rb(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function nb(){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 ra(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=nb(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await He(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&&rb(l.status,u)){await wd(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await wd(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Ut(t){let e;try{e=await He(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 xd(t){try{let e=await He(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function ob(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=bd.get(o);if(i)return i;let s=await He(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 bd.set(o,l.id),l.id}async function Sd(t,e,r,n=Kn){let o=await ob(t,e,r,n);await ra(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 Td(t,e,r){return await(await ra(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function Ed(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await ra(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function Id(t,e){let r=$d.get(e);if(r)return r;let n=await He(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 $d.set(e,i.id),i.id}async function Rd(t,e,r,n,o,i=Kn){let s=await Id(t,e),a=await He(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 Cd(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await He(t,"/api/commands",{method:"POST",body:JSON.stringify({query:o,issues:[{idReadable:e}]})});if(!i.ok)throw new Error(`yt applyIssueLink (${o} on ${e}): ${i.status} ${await i.text()}`)}function _d(t){if(!t||t.length===0)return;let e=[];for(let r of t)!r.url||!r.name||e.push({id:r.id,name:r.name,url:r.url,...r.mimeType?{mimeType:r.mimeType}:{},...typeof r.size=="number"?{size:r.size}:{}});return e.length>0?e:void 0}async function jd(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 Nd(t,e){let r=e.stageField??Kn,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=${Pd}&$top=200`,s=await He(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>Dd(c,r))}async function Od(t,e,r=Kn){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Pd}`,o=await He(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Dd(await o.json(),r)}async function Ld(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${sb}&$top=500`,o=await He(t,n);if(!o.ok)throw new Error(`yt listComments ${e}: ${o.status} ${await o.text()}`);return(await o.json()).filter(s=>s.created>r).map(s=>{let a={id:s.id,issueId:e,author:s.author?.login??"unknown",body:s.text??"",createdAt:new Date(s.created).toISOString()},c=_d(s.attachments);return c&&(a.attachments=c),a})}function ab(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 Dd(t,e=Kn){let r=t.customFields??[],n=r.find(l=>l.name===e),o=r.find(l=>l.name==="Assignee"),i=r.find(l=>l.name==="Type"),s={id:t.id,key:t.idReadable,title:t.summary,status:n?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(s.description=t.description),o?.value?.login&&(s.assignee=o.value.login),i?.value?.name&&(s.issueType=i.value.name),t.tags&&t.tags.length>0&&(s.tags=t.tags.map(l=>l.name));let a=_d(t.attachments);a&&(s.attachments=a);let c=ab(t.links);return c&&(s.links=c),s}async function Md(t,e){let r=await cb(t,e);return r.length>0?r:lb(t,e)}async function cb(t,e){let r=await Id(t,e),n=await He(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:Ud(s.bundle)});return i}async function lb(t,e){let r=`project: ${e}`,n=await He(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:Ud(s.projectCustomField?.bundle)});return i}function Ud(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var wd,Kn,bd,$d,Ad,ib,Pd,sb,lr=v(()=>{"use strict";kd();wd=t=>new Promise(e=>setTimeout(e,t));Kn="Stage",bd=new Map;$d=new Map;Ad="attachments(id,name,url,size,mimeType)",ib="links(direction,linkType(name),issues(idReadable))",Pd=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Ad},${ib}`,sb=`id,text,created,author(login),${Ad}`});function et(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function Gr(t){return t instanceof Ke}async function Bd(t,e){let r=W(t),n=[],o=[],i=()=>Date.now();if(e?.trackerProvider==="internal")n.push({name:"tracker",ok:!0,detail:"built-in tracker"});else if(r?.youtrack?.url&&r.youtrack.token)try{let c=await Ut({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:et(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:et(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 Nt(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){Gr(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:et(c)}),o.push({kind:"github",present:!0,ok:!1,detail:et(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 Ot(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){Gr(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:et(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:et(c),checkedAt:i()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Lt(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){Gr(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:et(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:et(c),checkedAt:i()}))}}else o.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||n.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let u of e?.repos??[])if(u.host==="github")try{await Zo(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){Gr(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:et(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await Zo(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){Gr(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:et(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Zo(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){Gr(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:i()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:et(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=Ur(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 token rejected (401) \u2014 refresh via `claude setup-token`";n.push({name:"claude",ok:!1,detail:l}),o.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function Bt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});return n.status===200?"valid":n.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}async function Fd(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 Kr=v(()=>{"use strict";ue();Dt();lr()});import ub from"node:http";import na from"node:crypto";function ti(){let t=oa(na.randomBytes(32)),e=oa(na.createHash("sha256").update(t).digest()),r=oa(na.randomBytes(32));return{verifier:t,challenge:e,state:r}}function sa(t){let e=new URL(db);return e.search=new URLSearchParams({response_type:"code",client_id:Gd,redirect_uri:t.redirectUri,scope:fb,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function gb(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 Kd(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 hb(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 aa(t){let e=await fetch(pb,{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:Gd,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return hb(await e.json())}async function ca(t){let e=t.timeoutMs??mb,r=ub.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=sa({redirectUri:o,challenge:t.challenge,state:t.state}),s,a=new Promise((l,u)=>{s=setTimeout(()=>u(new Error("no-callback")),e),r.on("request",(p,d)=>{let f=new URL(p.url??"/",o);if(f.pathname!=="/callback"){d.statusCode=404,d.end();return}clearTimeout(s),d.setHeader("content-type","text/html"),d.end("<h3>Authorized \u2014 you can close this tab.</h3>");try{l(gb(f.searchParams,t.state))}catch(m){u(m)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>aa({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function Hd(t){let e=await ca(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
20
- ${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var Gd,db,pb,ia,fb,mb,oa,la=v(()=>{"use strict";Gd="9d1c250a-e61b-44d9-88ed-5944d1962f5e",db="https://platform.claude.com/oauth/authorize",pb="https://platform.claude.com/v1/oauth/token",ia="https://platform.claude.com/oauth/code/callback",fb="org:create_api_key user:profile user:inference",mb=12e4,oa=t=>Buffer.from(t).toString("base64url")});async function Wd(t,e,r,n,o){let i=c=>{e.readyState===e.OPEN&&e.send(JSON.stringify(c))},s=c=>i({type:"agent_login_url",requestId:r.requestId,projectId:t.projectId,error:c});if(V("ORIGIN")==="farm"||V("CLAUDE_AUTOLOGIN")==="0"){s("autologin_disabled");return}let a;try{a=await ca(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 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=W(t.projectId);if(!u){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"no secrets file for this project on the CLI"}),n.warn("[agent-auth] no secrets file for this project \u2014 token not saved");return}u.claude={oauthToken:c.oauthToken},oe(u),n.info(`[agent-auth] Claude token replaced (${c.oauthToken.slice(0,12)}\u2026, ${c.oauthToken.length} chars)`),i({type:"agent_login_result",projectId:t.projectId,ok:!0,...l==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}}),o()}catch(c){let l=c instanceof Error?c.message:String(c);i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:l}),n.warn(`[agent-auth] browser authorization failed: ${l}`)}finally{a.close()}}var qd=v(()=>{"use strict";_e();Kr();ue();la()});function Yd(t,e){let r=t.find(n=>n.kind==="claude");return r?.present===!0&&r.ok===!1?V("ORIGIN")==="farm"||V("CLAUDE_AUTOLOGIN")==="0"||e?"none":"open":r?.ok===!0?"rearm":"none"}function Vd(t,e){return`${t.replace(/\/$/,"")}/?project=${encodeURIComponent(e)}`}var zd=v(()=>{"use strict";_e()});import{spawn as yb}from"node:child_process";function ur(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=yb(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var ri=v(()=>{"use strict"});import{setTimeout as kb}from"node:timers/promises";import wb from"ws";function ni(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new wb(r)}async function Ft(t,e,r){return tt(t,e,"/projects",r)}async function Xd(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 oi(t,e,r,n){return tt(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function Jd(t,e,r,n){return tt(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function Qd(t,e,r,n){return tt(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function Zd(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 ii(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 ua(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 ep(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await ua(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 kb(r.delayMs??1500)}throw o}async function tp(t,e){let r=await fetch(`${t}/cli/bootstrap-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})});if(r.status===403){let n;try{n=(await r.json()).error}catch{}if(n==="registration_required")throw new Hn(e)}if(!r.ok)throw new K(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function rp(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 np(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 op(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 da(t,e,r,n){return tt(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function ip(t,e,r,n,o){return tt(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function sp(t,e,r,n,o){return tt(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function ap(t,e,r,n,o){return tt(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function Wn(t,e,r,n){return tt(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function pa(t,e,r,n){await tt(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function cp(t,e,r,n){return tt(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function lp(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 ne(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 tt(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}var K,Hn,Ie=v(()=>{"use strict";K=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};Hn=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});function dp(t){up=t}function dr(t,e="info"){up(t,e)}var up,si=v(()=>{"use strict";up=t=>console.log(t)});import{homedir as bb,tmpdir as $b}from"node:os";import{existsSync as vb,mkdirSync as xb,mkdtempSync as Sb,rmSync as Tb}from"node:fs";import{join as qn}from"node:path";import{simpleGit as ai}from"simple-git";function Te(t,e,r){let n=r??qn(bb(),".codepipe","repos");return qn(n,t,e)}async function xt(t,e,r={}){let n=Te(t,e.name,r.baseDir),o=r.cloneUrlOverride??Vn(e);if(!vb(qn(n,".git"))){xb(n,{recursive:!0});let a=ai();dr(`[git] clone ${o} \u2192 ${n}`);try{await a.clone(o,n)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${o}
21
- ${l.trim()}`)}}let i=ai(n);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
22
- ${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function pr(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function fr(t,e){let{contextRepoCloneUrl:r,deliveryRef:n,deliverySha:o,baseSha:i,commitMessage:s}=e;await t.raw(["fetch",r,`+refs/heads/${n}:refs/codepipe-delivery`]);let a=(await t.revparse(["refs/codepipe-delivery"])).trim();o&&a!==o&&dr(`[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 pr(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await pr(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([...ci,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function Yn(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await pr(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await pr(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 pp(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 Yn(t,i,()=>fr(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));p&&await t.raw(["branch","-D",a]).catch(()=>{});let f=`origin/${c}`;if(await pr(t,f)||(f=`origin/${u??c}`),(await t.revparse([f])).trim()===s)await t.raw(["branch","-f",a,d]),await t.checkout(a);else{await t.checkout(["-B",a,f]);try{await t.raw([...ci,"cherry-pick",d])}catch(w){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let y=w instanceof Error?w.message:String(w);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
23
- ${y.trim()}`)}}let h=(await t.revparse(["HEAD"])).trim(),g=r.push!==!1;if(g){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:h,pushed:g}}async function fp(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 mp(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,u=await Yn(t,i,()=>fr(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:c}));return await t.raw(["branch","-f",a,u]),l&&await t.push(["--force-with-lease","-u","origin",a]),{commit:u,pushed:l}}async function gp(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,baseRef:a,branchName:c,commitMessage:l,defaultBranch:u}=r,p=await Yn(t,i,()=>fr(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));await t.fetch().catch(()=>{});let d=`origin/${a}`;if(await pr(t,d)||(d=`origin/${u??a}`),(await t.revparse([d])).trim()===s)return await t.raw(["branch","-f",c,p]),{commit:p,branch:c};let m=Sb(qn($b(),"codepipe-apply-")),h=qn(m,"wt");try{await t.raw(["worktree","add","--detach",h,d]);let g=ai(h);try{await g.raw([...ci,"cherry-pick",p])}catch(y){await g.raw(["cherry-pick","--abort"]).catch(()=>{});let x=y instanceof Error?y.message:String(y);throw new Error(`cherry-pick of ${i.slice(0,10)} onto ${a} hit conflicts
24
- ${x.trim()}`)}let w=(await g.revparse(["HEAD"])).trim();return await t.raw(["branch","-f",c,w]),{commit:w,branch:c}}finally{await t.raw(["worktree","remove","--force",h]).catch(()=>{}),Tb(m,{recursive:!0,force:!0}),await t.raw(["worktree","prune"]).catch(()=>{})}}async function hp(t,e,r){let{branchName:n,dropTaskKeys:o}=r,i=`origin/${n}`;if(!await pr(t,i))throw new Error(`rewrite_cluster_branch: ${i} not found upstream`);let s=`origin/${r.defaultBranch??"main"}`,a=(await t.raw(["merge-base",i,s])).trim(),c=(await t.raw(["rev-list","--reverse",`${a}..${i}`])).split(`
25
- `).map(f=>f.trim()).filter(f=>f.length>0),l=new Set(o.map(f=>f.toUpperCase())),u=[],p=0;for(let f of c)(await t.raw(["show","-s","--format=%(trailers:key=CodePipe-Task,valueonly)",f])).split(`
26
- `).map(g=>g.trim().toUpperCase()).filter(g=>g.length>0).some(g=>l.has(g))?p++:u.push(f);if(p===0)return{commit:(await t.revparse([i])).trim(),dropped:0};await t.checkout(["-B",n,a]);for(let f of u)try{await t.raw([...ci,"cherry-pick","--allow-empty","--keep-redundant-commits",f])}catch(m){await t.raw(["cherry-pick","--abort"]).catch(()=>{}),await t.checkout(["-B",n,i]).catch(()=>{});let h=m instanceof Error?m.message:String(m);throw new Error(`rewrite_cluster_branch: replaying ${f.slice(0,10)} after dropping ${o.join(", ")} hit conflicts
27
- ${h.trim()}`)}let d=(await t.revparse(["HEAD"])).trim();return await t.push(["--force-with-lease","-u","origin",n]),{commit:d,dropped:p}}async function yp(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 Vn(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 kp(t){return(await ai().listRemote(["--heads",t])).split(`
28
- `).map(r=>r.trim()).filter(r=>r.length>0).map(r=>r.split(/\s+/)[1]??"").filter(r=>r.startsWith("refs/heads/")).map(r=>r.slice(11))}function wp(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}var ci,mr=v(()=>{"use strict";si();ci=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{existsSync as ui,readFileSync as Eb,writeFileSync as Ib}from"node:fs";import{join as hr}from"node:path";import{simpleGit as li}from"simple-git";function $p(t){return hr(t,Rb)}function yr(t){let e=$p(t);if(!ui(e))return{};try{return JSON.parse(Eb(e,"utf-8"))}catch{return{}}}function ma(t,e){Ib($p(t),JSON.stringify(e,null,2)+`
29
- `)}async function vp(t,e,r,n,o){let i;try{i=await da(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(d){return{ok:!1,message:`claim failed: ${d instanceof Error?d.message:String(d)}`}}let s=[];for(let d of i.repos){let f=t.spec.repos.find(w=>w.name===d.repoName);if(!f)return{ok:!1,message:`repo "${d.repoName}" not in project.yaml \u2014 run /sync`};let m=hr(t.root,f.mountAs);if(!ui(hr(m,".git")))return{ok:!1,message:`${f.mountAs}/ not cloned \u2014 run /sync first`};if(!(await li(m).status()).isClean())return{ok:!1,message:`${f.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:d,spec:f,dir:m})}let a=[];for(let d of s){let f=li(d.dir),m=await Cb(f),h=d.claimRepo;try{await f.fetch()}catch(y){return await fa(a,o),{ok:!1,message:`fetch failed in ${d.spec.mountAs}: ${gr(y)}`}}let g=`origin/${h.baseRef}`,w;try{w=await fr(f,{contextRepoCloneUrl:h.contextRepoCloneUrl,deliveryRef:h.deliveryRef,deliverySha:h.deliverySha,baseSha:h.baseSha,commitMessage:h.commitMessage})}catch(y){return await fa(a,o),{ok:!1,message:`fetch delivery failed in ${d.spec.mountAs}: ${gr(y)}`}}a.push({git:f,dir:d.dir,mountAs:d.spec.mountAs,originalRef:m,branch:h.branchName,baseSha:g,deliveryCommit:w,startPoint:g})}let c=[];for(let d of a)try{if(n==="apply"){await d.git.checkout(["-B",d.branch,d.startPoint]),await d.git.raw([...bp,"cherry-pick",d.deliveryCommit]);let f=(await d.git.revparse(["HEAD"])).trim();c.push({mountAs:d.mountAs,branch:d.branch,baseSha:d.baseSha,appliedSha:f})}else await d.git.checkout(["--detach",d.startPoint]),await d.git.raw([...bp,"cherry-pick","--no-commit",d.deliveryCommit]),await d.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:d.mountAs,branch:d.branch,baseSha:d.baseSha})}catch(f){return await d.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await fa(a,o),{ok:!1,message:`apply failed in ${d.mountAs}: ${gr(f)} (rolled back all repos)`}}let l=yr(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},ma(t.contextDir,l);let u=c.map(d=>d.mountAs).join(", "),p=n==="apply"?`review, push branch '${i.repos[0]?.branchName}', then: /applied ${r} --pr <url>`:`review with 'git diff', commit & push yourself, then: /applied ${r} --pr <url>`;return{ok:!0,message:`${n==="apply"?"applied":"unstashed"} ${r} in ${u}
18
+ `;A$(this.currentPath,r,"utf-8")}asWritable(){return new N$({write:(e,r,n)=>{try{let o=typeof e=="string"?e:e.toString("utf-8");for(let s of o.split(/\r?\n/))s&&this.writeLine(s);n()}catch(o){n(o)}}})}rotateIfNeeded(){if(!(this.cfg.maxBytes<=0||!op(this.currentPath)||_$(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;op(n)&&(r>=this.cfg.maxFiles?j$(n):sp(n,`${this.currentPath}.${r+1}`))}sp(this.currentPath,`${this.currentPath}.1`)}}}});import{createHash as U$}from"node:crypto";import{existsSync as B$,readFileSync as F$}from"node:fs";import{homedir as K$,hostname as za}from"node:os";import{join as G$}from"node:path";function ap(t){return U$("sha256").update(t).digest("hex").slice(0,12)}function H$(){let t=J("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=G$(K$(),".claude","credentials.json");if(!B$(e))return;let r=JSON.parse(F$(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 cp(t){let e=H$(),r=J("ACCOUNT_ID")?.trim(),n=J("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=Zr(t);return o?{accountId:`acct-${ap(o)}`,label:n||za(),...e?{email:e}:{}}:{accountId:`acct-${ap(`host:${za()}`)}`,label:n||za(),...e?{email:e}:{}}}var lp=$(()=>{"use strict";Le();pe()});function fs(t){return t===429||t>=500}function up(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
19
+ `+t.slice(t.length-e)}async function Gt(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),ps);try{let s;try{s=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new Qe(`cannot reach api.github.com (${l instanceof Error?l.message:String(l)})`)}if(s.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(fs(s.status))throw new Qe(`api.github.com \u2192 ${s.status} ${s.statusText}`);if(!s.ok)throw new Error(`GitHub \u2192 ${s.status} ${s.statusText}`);let a=(await s.json()).login??"ok",c=s.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 ms(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,s=setTimeout(()=>o.abort(),ps);try{let i;try{i=await fetch(n,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},signal:o.signal})}catch(c){throw new Qe(`cannot reach api.github.com (${c instanceof Error?c.message:String(c)})`)}if(i.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(i.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(fs(i.status))throw new Qe(`api.github.com \u2192 ${i.status} ${i.statusText}`);if(!i.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${i.status} ${i.statusText}`);if((await i.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}finally{clearTimeout(s)}}async function Ht(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,s=setTimeout(()=>o.abort(),ps);try{let i;try{i=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new Qe(`cannot reach api.bitbucket.org (${c instanceof Error?c.message:String(c)})`)}if(i.ok)return t;if(i.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;if(fs(i.status))throw new Qe(`api.bitbucket.org \u2192 ${i.status} ${i.statusText}`);let a=await W$(i);throw i.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${a})`):i.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${a})`):i.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${a})`):new Error(`Bitbucket \u2192 ${i.status} ${i.statusText}${a}`)}finally{clearTimeout(s)}}async function W$(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function hs(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 s={};try{s=await o.json()}catch{}let i=s.error?.detail?.granted;if(Array.isArray(i)){let c=dp.filter(l=>!i.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: ${dp.join(", ")}`}let a=s.error?.message?`: ${s.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function Wt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),ps);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(s){throw new Qe(`cannot reach gitlab.com (${s instanceof Error?s.message:String(s)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(fs(n.status))throw new Qe(`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 pp(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 q$(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 Xa(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 dt(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new Za(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new Ja(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new Qa(e)}return new ec}var wr,Qe,ps,dp,Ja,Za,Qa,ec,qt=$(()=>{"use strict";wr=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},Qe=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},ps=5e3;dp=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];Ja=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 i=(await o.json()).values?.[0];return i?{url:i.links?.html?.href??"",number:i.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 wr(`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 s=await o.json();return s.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:s.state==="DECLINED"||s.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 s=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",i=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:s,close_source_branch:o})});if(!i.ok)throw new Error(`bitbucket merge PR #${r}: ${i.status} ${await i.text()}`);let a=await i.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:n}})});if(!o.ok)throw new Error(`bitbucket comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},Za=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 s=(await n.json())[0];return s?{url:s.html_url,number:s.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 wr(`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 s=await o.json();if(s.state==="closed"&&s.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(s.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let i=s.mergeable===!1||s.mergeable_state==="dirty"?"conflict":s.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:s.head?.sha?await this.fetchCiStatus(e,s.head.sha):"none",mergeable:i}}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[s,i]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),a=!1,c=!1,l=!1;if(s.ok){let u=await s.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(i.ok){let u=await i.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}`,s=["failure","timed_out","cancelled","action_required","startup_failure"];try{let i=await fetch(`${o}/pulls/${r}`,{headers:n});if(!i.ok)return;let a=(await i.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&&s.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 h=await g.text();u.push(`### CI job: ${f.name}
20
+
21
+ ${up(h,8e3)}`)}}return u.length===0?void 0:up(u.join(`
22
+
23
+ `),16e3)}catch{return}}async mergePR(e,r,n,o){let s=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(!s.ok)throw new Error(`github merge PR #${r}: ${s.status} ${await s.text()}`);let i=await s.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 i?.sha?{mergedSha:i.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},Qa=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 s=(await n.json())[0];return s?{url:s.web_url??"",number:s.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 wr(`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 s=await o.json();if(s.state==="merged")return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(s.state==="closed"||s.state==="locked")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let i=q$(s.head_pipeline?.status??s.pipeline?.status),a=s.merge_status==="cannot_be_merged"||s.has_conflicts===!0?"conflict":s.merge_status==="can_be_merged"&&s.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:i,mergeable:a}}async mergePR(e,r,n,o){let s=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,i,a=await fetch(s,{headers:this.headers()});if(a.ok){let u=await a.json().catch(()=>null);i=u?.sha??u?.diff_refs?.head_sha}let c=await fetch(`${s}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:n==="squash",should_remove_source_branch:o,...i?{sha:i}:{}})});if(!c.ok)throw new Error(`gitlab merge MR !${r}: ${c.status} ${await c.text()}`);let l=await c.json().catch(()=>null);return l?.merge_commit_sha?{mergedSha:l.merge_commit_sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`gitlab comment MR !${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!o.ok)throw new Error(`gitlab close MR !${r}: ${o.status} ${await o.text()}`)}};ec=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(Xa(e,r,"merge"))}async closePR(e,r,n){throw new Error(Xa(e,r,"close"))}async addPRComment(e,r,n){throw new Error(Xa(e,r,"comment"))}}});import{X509Certificate as hp}from"node:crypto";import{readFileSync as Y$}from"node:fs";import Yt from"node:tls";function V$(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function kp(t=yp){if(fp)return;fp=!0;let e=J("EXTRA_CA_FILE");if(!(!e||!gp))try{let r=V$(Y$(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Yt.setDefaultCACertificates([...Yt.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 wp(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 z$(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
24
+ `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function X$(t,e,r){return new Promise((n,o)=>{let s=Yt.connect({host:t,port:e,servername:t,rejectUnauthorized:!1},()=>{let i=s.getPeerCertificate(!0),a=new Set;for(;i?.issuerCertificate&&i.issuerCertificate!==i&&i.fingerprint256&&!a.has(i.fingerprint256);)a.add(i.fingerprint256),i=i.issuerCertificate;let c=i?.raw?new hp(i.raw):null;s.end(),n(c)});s.on("error",o),s.setTimeout(r,()=>{s.destroy(),o(new Error("tls connect timeout"))})})}function tc(t,e,r){return new Promise(n=>{let o=Yt.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 J$(t){try{let e=await fetch(t);return e.ok?new hp(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function bp(t,e=443,r=yp){let n=`${t}:${e}`,o=mp.get(n);if(o)return o;let s=Z$(t,e,r).catch(i=>(r(`[tls] chain repair for ${t} failed: ${i instanceof Error?i.message:String(i)}`),!1));return mp.set(n,s),s}async function Z$(t,e,r){if(!gp)return!1;let n=8e3;if(await tc(t,e,n))return!0;let o=await X$(t,e,n),s=Yt.getCACertificates(),i=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=z$(o);if(!c)break;let l=await J$(c);if(!l)break;if(i.push(l.toString()),Yt.setDefaultCACertificates([...s,...i]),await tc(t,e,n))return r(`[tls] completed certificate chain for ${t} via AIA (+${i.length} intermediate cert(s))`),!0;if(l.subject===l.issuer)break;o=l}return tc(t,e,n)}var gp,fp,mp,yp,$p=$(()=>{"use strict";Le();gp=typeof Yt.getCACertificates=="function"&&typeof Yt.setDefaultCACertificates=="function",fp=!1,mp=new Map,yp=t=>console.warn(t)});function Ep(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function et(t,e,r){kp();let n={Authorization:`Bearer ${t.token}`,Accept:"application/json"};r?.body&&(n["Content-Type"]="application/json");let o=t.baseUrl+e,s={...r,headers:{...n,...r?.headers??{}}};try{return await fetch(o,s)}catch(i){if(wp(i)&&await bp(new URL(t.baseUrl).host))return await fetch(o,s);throw i}}function Q$(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function ev(){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 rc(t,e,r,n){let{attempts:o,baseMs:s,capMs:i}=ev(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await et(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&&Q$(l.status,u)){await vp(Math.min(i,s*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await vp(Math.min(i,s*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Vt(t){let e;try{e=await et(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 Rp(t){try{let e=await et(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function tv(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,s=xp.get(o);if(s)return s;let i=await et(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!i.ok)throw new Error(`yt resolveStateId ${e}: ${i.status} ${await i.text()}`);let c=(await i.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 xp.set(o,l.id),l.id}async function Tp(t,e,r,n=co){let o=await tv(t,e,r,n);await rc(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 Ip(t,e,r){return await(await rc(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function Cp(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await rc(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function Ap(t,e){let r=Sp.get(e);if(r)return r;let n=await et(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!n.ok)throw new Error(`yt resolveProjectId: ${n.status} ${await n.text()}`);let s=(await n.json()).find(i=>i.shortName===e);if(!s)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return Sp.set(e,s.id),s.id}async function Pp(t,e,r,n,o,s=co){let i=await Ap(t,e),a=await et(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:i},summary:r,description:n,customFields:[{name:s,$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 _p(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,s=await et(t,"/api/commands",{method:"POST",body:JSON.stringify({query:o,issues:[{idReadable:e}]})});if(!s.ok)throw new Error(`yt applyIssueLink (${o} on ${e}): ${s.status} ${await s.text()}`)}function Op(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 Lp(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 Dp(t,e){let r=e.stageField??co,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(" "),s=`/api/issues?query=${encodeURIComponent(o)}&fields=${Np}&$top=200`,i=await et(t,s);if(!i.ok)throw new Error(`yt listIssues: ${i.status} ${await i.text()}`);return(await i.json()).map(c=>Bp(c,r))}async function Mp(t,e,r=co){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Np}`,o=await et(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Bp(await o.json(),r)}async function Up(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${nv}&$top=500`,o=await et(t,n);if(!o.ok)throw new Error(`yt listComments ${e}: ${o.status} ${await o.text()}`);return(await o.json()).filter(i=>i.created>r).map(i=>{let a={id:i.id,issueId:e,author:i.author?.login??"unknown",body:i.text??"",createdAt:new Date(i.created).toISOString()},c=Op(i.attachments);return c&&(a.attachments=c),a})}function ov(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 Bp(t,e=co){let r=t.customFields??[],n=r.find(l=>l.name===e),o=r.find(l=>l.name==="Assignee"),s=r.find(l=>l.name==="Type"),i={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&&(i.description=t.description),o?.value?.login&&(i.assignee=o.value.login),s?.value?.name&&(i.issueType=s.value.name),t.tags&&t.tags.length>0&&(i.tags=t.tags.map(l=>l.name));let a=Op(t.attachments);a&&(i.attachments=a);let c=ov(t.links);return c&&(i.links=c),i}async function Fp(t,e){let r=await sv(t,e);return r.length>0?r:iv(t,e)}async function sv(t,e){let r=await Ap(t,e),n=await et(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(),s=[];for(let i of o)i.$type==="StateProjectCustomField"&&i.field?.name&&s.push({name:i.field.name,values:Kp(i.bundle)});return s}async function iv(t,e){let r=`project: ${e}`,n=await et(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(),s=[];for(let i of o[0]?.customFields??[])i.$type==="StateIssueCustomField"&&i.name&&s.push({name:i.name,values:Kp(i.projectCustomField?.bundle)});return s}function Kp(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var vp,co,xp,Sp,jp,rv,Np,nv,br=$(()=>{"use strict";$p();vp=t=>new Promise(e=>setTimeout(e,t));co="Stage",xp=new Map;Sp=new Map;jp="attachments(id,name,url,size,mimeType)",rv="links(direction,linkType(name),issues(idReadable))",Np=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${jp},${rv}`,nv=`id,text,created,author(login),${jp}`});function pt(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function tn(t){return t instanceof Qe}async function Gp(t,e){let r=q(t),n=[],o=[],s=()=>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 Vt({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:s()})}catch(c){n.push({name:"youtrack",ok:!1,detail:pt(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:pt(c),checkedAt:s()})}else n.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),o.push({kind:"youtrack",present:!1,checkedAt:s()});let i=!1;if(r?.github?.token){i=!0;try{let c=await Gt(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:s()})}catch(c){tn(c)?(n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,detail:"check inconclusive",checkedAt:s()})):(n.push({name:"github",ok:!1,detail:pt(c)}),o.push({kind:"github",present:!0,ok:!1,detail:pt(c),checkedAt:s()}))}}else o.push({kind:"github",present:!1,checkedAt:s()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){i=!0;try{let c=await Ht(r.bitbucket.email,r.bitbucket.apiToken);n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:s()})}catch(c){tn(c)?(n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,detail:"check inconclusive",checkedAt:s()})):(n.push({name:"bitbucket",ok:!1,detail:pt(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:pt(c),checkedAt:s()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:s()});if(r?.gitlab?.token){i=!0;try{let c=await Wt(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:s()})}catch(c){tn(c)?(n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,detail:"check inconclusive",checkedAt:s()})):(n.push({name:"gitlab",ok:!1,detail:pt(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:pt(c),checkedAt:s()}))}}else o.push({kind:"gitlab",present:!1,checkedAt:s()});if(i||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 ms(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){tn(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:pt(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await ms(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){tn(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:pt(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await ms(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:s()})}catch(l){tn(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:s()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:pt(l),checkedAt:s()})}else o.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:s()})}else o.push({kind:"contextWrite",present:!1,checkedAt:s()});let a=Zr(t);if(!a)n.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),o.push({kind:"claude",present:!1,checkedAt:s()});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:s()});else{let c=await zt(a);if(c==="invalid"){let l="Claude token rejected (401) \u2014 refresh via `claude setup-token`";n.push({name:"claude",ok:!1,detail:l}),o.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:s()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:s()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function zt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});return n.status===200?"valid":n.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}async function Hp(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 s=(await n.json())?.data;if(!Array.isArray(s))return null;let i=[];for(let a of s){let c=a?.id;if(typeof c!="string"||c.trim().length===0)continue;let l=a?.created_at;i.push({id:c,...typeof l=="string"?{createdAt:l}:{}})}return i}catch{return null}finally{clearTimeout(r)}}var rn=$(()=>{"use strict";pe();qt();br()});import av from"node:http";import nc from"node:crypto";function gs(){let t=oc(nc.randomBytes(32)),e=oc(nc.createHash("sha256").update(t).digest()),r=oc(nc.randomBytes(32));return{verifier:t,challenge:e,state:r}}function ic(t){let e=new URL(cv);return e.search=new URLSearchParams({response_type:"code",client_id:Wp,redirect_uri:t.redirectUri,scope:uv,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function pv(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 qp(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 fv(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 ac(t){let e=await fetch(lv,{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:Wp,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return fv(await e.json())}async function cc(t){let e=t.timeoutMs??dv,r=av.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,s=ic({redirectUri:o,challenge:t.challenge,state:t.state}),i,a=new Promise((l,u)=>{i=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(i),d.setHeader("content-type","text/html"),d.end("<h3>Authorized \u2014 you can close this tab.</h3>");try{l(pv(m.searchParams,t.state))}catch(f){u(f)}})});a.catch(()=>{});let c;return{authUrl:s,redirectUri:o,waitForToken(){return c||(c=a.then(l=>ac({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(i),r.close()}}}async function Yp(t){let e=await cc(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
25
+ ${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var Wp,cv,lv,sc,uv,dv,oc,lc=$(()=>{"use strict";Wp="9d1c250a-e61b-44d9-88ed-5944d1962f5e",cv="https://platform.claude.com/oauth/authorize",lv="https://platform.claude.com/v1/oauth/token",sc="https://platform.claude.com/oauth/code/callback",uv="org:create_api_key user:profile user:inference",dv=12e4,oc=t=>Buffer.from(t).toString("base64url")});async function Vp(t,e,r,n,o){let s=c=>{e.readyState===e.OPEN&&e.send(JSON.stringify(c))},i=c=>s({type:"agent_login_url",requestId:r.requestId,projectId:t.projectId,error:c});if(J("ORIGIN")==="farm"||J("CLAUDE_AUTOLOGIN")==="0"){i("autologin_disabled");return}let a;try{a=await cc(gs())}catch(c){i(`listener failed: ${c instanceof Error?c.message:String(c)}`);return}s({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 zt(c.oauthToken);if(l==="invalid"){s({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){s({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"no secrets file for this project on the CLI"}),n.warn("[agent-auth] no secrets file for this project \u2014 token not saved");return}u.claude={oauthToken:c.oauthToken},ie(u),n.info(`[agent-auth] Claude token replaced (${c.oauthToken.slice(0,12)}\u2026, ${c.oauthToken.length} chars)`),s({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);s({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:l}),n.warn(`[agent-auth] browser authorization failed: ${l}`)}finally{a.close()}}var zp=$(()=>{"use strict";Le();rn();pe();lc()});function Xp(t,e){let r=t.find(n=>n.kind==="claude");return r?.present===!0&&r.ok===!1?J("ORIGIN")==="farm"||J("CLAUDE_AUTOLOGIN")==="0"||e?"none":"open":r?.ok===!0?"rearm":"none"}function Jp(t,e){return`${t.replace(/\/$/,"")}/?project=${encodeURIComponent(e)}`}var Zp=$(()=>{"use strict";Le()});import{spawn as mv}from"node:child_process";function $r(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=mv(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var ys=$(()=>{"use strict"});import{setTimeout as hv}from"node:timers/promises";import gv from"ws";function ks(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new gv(r)}async function Xt(t,e,r){return ft(t,e,"/projects",r)}async function Qp(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new H(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function ws(t,e,r,n){return ft(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function ef(t,e,r,n){return ft(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function tf(t,e,r,n){return ft(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function rf(t,e){let r=await fetch(`${t}/sandbox/me`,{headers:{Authorization:`Bearer ${e}`}});if(r.ok)return"ok";if(r.status===401)return"unknown";if(r.status===404)return"unsupported";throw new H(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function bs(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new H(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function uc(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new H(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function nf(t,e,r={}){let n=r.attempts??3,o;for(let s=0;s<n;s++)try{let i=await uc(t,e),a=new Set;for(let c of i)c.id!==r.excludeProjectId&&c.trackerProvider==="internal"&&c.youtrackProjectKey&&a.add(c.youtrackProjectKey.toUpperCase());return a}catch(i){o=i,s<n-1&&await hv(r.delayMs??1500)}throw o}async function of(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 lo(e)}if(!r.ok)throw new H(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function sf(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new H(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function af(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new H(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function cf(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new H(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function dc(t,e,r,n){return ft(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function lf(t,e,r,n,o){return ft(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function uf(t,e,r,n,o){return ft(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function df(t,e,r,n,o){return ft(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function uo(t,e,r,n){return ft(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function pc(t,e,r,n){await ft(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function pf(t,e,r,n){return ft(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function ff(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/repos/${encodeURIComponent(n)}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}}),s=await o.text(),i=s?JSON.parse(s):null;if(!o.ok){let a=i&&typeof i=="object"&&"error"in i?String(i.error):`HTTP ${o.status}`;throw new H(o.status,i,a)}return i}async function oe(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new H(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function ft(t,e,r,n){let o=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}),s=await o.text(),i=s?JSON.parse(s):null;if(!o.ok){let a=i&&typeof i=="object"&&"error"in i?String(i.error):`HTTP ${o.status}`;throw new H(o.status,i,a)}return i}var H,lo,Ae=$(()=>{"use strict";H=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};lo=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});function hf(t){mf=t}function vr(t,e="info"){mf(t,e)}var mf,$s=$(()=>{"use strict";mf=t=>console.log(t)});import{homedir as yv,tmpdir as kv}from"node:os";import{existsSync as wv,mkdirSync as bv,mkdtempSync as $v,rmSync as vv}from"node:fs";import{join as po}from"node:path";import{simpleGit as vs}from"simple-git";function Ie(t,e,r){let n=r??po(yv(),".codepipe","repos");return po(n,t,e)}async function Nt(t,e,r={}){let n=Ie(t,e.name,r.baseDir),o=r.cloneUrlOverride??mo(e);if(!wv(po(n,".git"))){bv(n,{recursive:!0});let a=vs();vr(`[git] clone ${o} \u2192 ${n}`);try{await a.clone(o,n)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${o}
26
+ ${l.trim()}`)}}let s=vs(n);try{await s.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
27
+ ${c.trim()}`)}let i=e.defaultBranch??"main";return await s.checkout(["-B",i,`origin/${i}`]).catch(()=>{}),s}async function xr(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function Sr(t,e){let{contextRepoCloneUrl:r,deliveryRef:n,deliverySha:o,baseSha:s,commitMessage:i}=e;await t.raw(["fetch",r,`+refs/heads/${n}:refs/codepipe-delivery`]);let a=(await t.revparse(["refs/codepipe-delivery"])).trim();o&&a!==o&&vr(`[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 xr(t,s)||await t.fetch(["origin",s]).catch(()=>{}),!await xr(t,s))throw new Error(`apply_delivery: base commit ${s.slice(0,10)} unavailable \u2014 cannot re-parent the delivery`);let l=(await t.raw([...xs,"commit-tree",c,"-p",s,"-m",i])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function fo(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await xr(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await xr(t,o)){let i=(await t.revparse([o])).trim();return await t.raw(["update-ref",n,i]).catch(()=>{}),i}let s=await r();return await t.raw(["update-ref",n,s]).catch(()=>{}),s}async function gf(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:s,baseSha:i,branchName:a,baseRef:c,commitMessage:l,defaultBranch:u,force:p}=r,d=await fo(t,s,()=>Sr(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:s,baseSha:i,commitMessage:l}));p&&await t.raw(["branch","-D",a]).catch(()=>{});let m=`origin/${c}`;if(await xr(t,m)||(m=`origin/${u??c}`),(await t.revparse([m])).trim()===i)await t.raw(["branch","-f",a,d]),await t.checkout(a);else{await t.checkout(["-B",a,m]);try{await t.raw([...xs,"cherry-pick",d])}catch(w){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let y=w instanceof Error?w.message:String(w);throw new Error(`apply_delivery: cherry-pick of ${s.slice(0,10)} onto ${c} hit conflicts
28
+ ${y.trim()}`)}}let g=(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:g,pushed:h}}async function yf(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 kf(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:s,baseSha:i,branchName:a,commitMessage:c,push:l}=r,u=await fo(t,s,()=>Sr(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:s,baseSha:i,commitMessage:c}));return await t.raw(["branch","-f",a,u]),l&&await t.push(["--force-with-lease","-u","origin",a]),{commit:u,pushed:l}}async function wf(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:s,baseSha:i,baseRef:a,branchName:c,commitMessage:l,defaultBranch:u}=r,p=await fo(t,s,()=>Sr(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:s,baseSha:i,commitMessage:l}));await t.fetch().catch(()=>{});let d=`origin/${a}`;if(await xr(t,d)||(d=`origin/${u??a}`),(await t.revparse([d])).trim()===i)return await t.raw(["branch","-f",c,p]),{commit:p,branch:c};let f=$v(po(kv(),"codepipe-apply-")),g=po(f,"wt");try{await t.raw(["worktree","add","--detach",g,d]);let h=vs(g);try{await h.raw([...xs,"cherry-pick",p])}catch(y){await h.raw(["cherry-pick","--abort"]).catch(()=>{});let x=y instanceof Error?y.message:String(y);throw new Error(`cherry-pick of ${s.slice(0,10)} onto ${a} hit conflicts
29
+ ${x.trim()}`)}let w=(await h.revparse(["HEAD"])).trim();return await t.raw(["branch","-f",c,w]),{commit:w,branch:c}}finally{await t.raw(["worktree","remove","--force",g]).catch(()=>{}),vv(f,{recursive:!0,force:!0}),await t.raw(["worktree","prune"]).catch(()=>{})}}async function bf(t,e,r){let{branchName:n,dropTaskKeys:o}=r,s=`origin/${n}`;if(!await xr(t,s))throw new Error(`rewrite_cluster_branch: ${s} not found upstream`);let i=`origin/${r.defaultBranch??"main"}`,a=(await t.raw(["merge-base",s,i])).trim(),c=(await t.raw(["rev-list","--reverse",`${a}..${s}`])).split(`
30
+ `).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(`
31
+ `).map(h=>h.trim().toUpperCase()).filter(h=>h.length>0).some(h=>l.has(h))?p++:u.push(m);if(p===0)return{commit:(await t.revparse([s])).trim(),dropped:0};await t.checkout(["-B",n,a]);for(let m of u)try{await t.raw([...xs,"cherry-pick","--allow-empty","--keep-redundant-commits",m])}catch(f){await t.raw(["cherry-pick","--abort"]).catch(()=>{}),await t.checkout(["-B",n,s]).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
32
+ ${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 $f(t,e,r){let{branchName:n,baseBranch:o,mergeMethod:s,deleteBranch:i}=r,a=`origin/${n}`;return s==="squash"?(await t.raw(["merge","--squash",a]),await t.commit(`Merge branch '${n}'`)):s==="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]),i&&await t.push(["origin","--delete",n]).catch(()=>{}),{mergedSha:(await t.revparse(["HEAD"])).trim()}}function mo(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 vf(t){return(await vs().listRemote(["--heads",t])).split(`
33
+ `).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 xf(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}var xs,Er=$(()=>{"use strict";$s();xs=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{existsSync as Es,readFileSync as xv,writeFileSync as Sv}from"node:fs";import{join as Tr}from"node:path";import{simpleGit as Ss}from"simple-git";function Ef(t){return Tr(t,Ev)}function Ir(t){let e=Ef(t);if(!Es(e))return{};try{return JSON.parse(xv(e,"utf-8"))}catch{return{}}}function mc(t,e){Sv(Ef(t),JSON.stringify(e,null,2)+`
34
+ `)}async function Rf(t,e,r,n,o){let s;try{s=await dc(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(d){return{ok:!1,message:`claim failed: ${d instanceof Error?d.message:String(d)}`}}let i=[];for(let d of s.repos){let m=t.spec.repos.find(w=>w.name===d.repoName);if(!m)return{ok:!1,message:`repo "${d.repoName}" not in project.yaml \u2014 run /sync`};let f=Tr(t.root,m.mountAs);if(!Es(Tr(f,".git")))return{ok:!1,message:`${m.mountAs}/ not cloned \u2014 run /sync first`};if(!(await Ss(f).status()).isClean())return{ok:!1,message:`${m.mountAs}/ has uncommitted changes \u2014 commit or stash first`};i.push({claimRepo:d,spec:m,dir:f})}let a=[];for(let d of i){let m=Ss(d.dir),f=await Rv(m),g=d.claimRepo;try{await m.fetch()}catch(y){return await fc(a,o),{ok:!1,message:`fetch failed in ${d.spec.mountAs}: ${Rr(y)}`}}let h=`origin/${g.baseRef}`,w;try{w=await Sr(m,{contextRepoCloneUrl:g.contextRepoCloneUrl,deliveryRef:g.deliveryRef,deliverySha:g.deliverySha,baseSha:g.baseSha,commitMessage:g.commitMessage})}catch(y){return await fc(a,o),{ok:!1,message:`fetch delivery failed in ${d.spec.mountAs}: ${Rr(y)}`}}a.push({git:m,dir:d.dir,mountAs:d.spec.mountAs,originalRef:f,branch:g.branchName,baseSha:h,deliveryCommit:w,startPoint:h})}let c=[];for(let d of a)try{if(n==="apply"){await d.git.checkout(["-B",d.branch,d.startPoint]),await d.git.raw([...Sf,"cherry-pick",d.deliveryCommit]);let m=(await d.git.revparse(["HEAD"])).trim();c.push({mountAs:d.mountAs,branch:d.branch,baseSha:d.baseSha,appliedSha:m})}else await d.git.checkout(["--detach",d.startPoint]),await d.git.raw([...Sf,"cherry-pick","--no-commit",d.deliveryCommit]),await d.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:d.mountAs,branch:d.branch,baseSha:d.baseSha})}catch(m){return await d.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await fc(a,o),{ok:!1,message:`apply failed in ${d.mountAs}: ${Rr(m)} (rolled back all repos)`}}let l=Ir(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},mc(t.contextDir,l);let u=c.map(d=>d.mountAs).join(", "),p=n==="apply"?`review, push branch '${s.repos[0]?.branchName}', then: /applied ${r} --pr <url>`:`review with 'git diff', commit & push yourself, then: /applied ${r} --pr <url>`;return{ok:!0,message:`${n==="apply"?"applied":"unstashed"} ${r} in ${u}
30
35
  ${p}
31
- or: /abort ${r} --reason "..."`}}async function xp(t,e,r){let n=[];for(let c of e.repos){let l=t.repos.find(p=>p.name===c.repoName);if(!l)return{ok:!1,message:`repo "${c.repoName}" not in project.yaml \u2014 run /sync`};let u=hr(t.root,l.mountAs);if(!ui(hr(u,".git")))return{ok:!1,message:`${l.mountAs}/ not cloned \u2014 run /sync first`};n.push({git:li(u),dir:u,spec:l,cr:c})}let o=[],i=[];for(let c of n)try{let{commit:l}=await gp(c.git,c.dir,{contextRepoCloneUrl:c.cr.contextRepoCloneUrl,deliveryRef:c.cr.deliveryRef,deliverySha:c.cr.deliverySha,baseSha:c.cr.baseSha,baseRef:c.cr.baseRef,branchName:c.cr.branchName,commitMessage:c.cr.commitMessage,defaultBranch:c.spec.defaultBranch});r.info(`[apply] ${e.taskKey}: ${c.cr.branchName} \u2192 ${c.spec.mountAs} (${l.slice(0,10)})`),o.push({git:c.git,branch:c.cr.branchName}),i.push({mountAs:c.spec.mountAs,branch:c.cr.branchName,baseSha:`origin/${c.cr.baseRef}`,appliedSha:l})}catch(l){for(let u of o)await u.git.raw(["branch","-D",u.branch]).catch(()=>{});return{ok:!1,message:`auto-apply failed in ${c.spec.mountAs}: ${gr(l)}`}}try{await da(t.hubUrl,t.cliToken,t.projectId,e.taskKey)}catch(c){return{ok:!1,message:`branch created but claim failed: ${gr(c)} \u2014 retried on the next reconnect`,branches:o.map(l=>l.branch)}}let s=yr(t.contextDir);s[e.taskKey]={mode:"apply",claimedAt:new Date().toISOString(),repos:i},ma(t.contextDir,s);let a=i.map(c=>`${c.branch} (${c.mountAs})`).join(", ");return{ok:!0,branches:i.map(c=>c.branch),message:`branch created locally without touching your checkout: ${a}
36
+ or: /abort ${r} --reason "..."`}}async function Tf(t,e,r){let n=[];for(let c of e.repos){let l=t.repos.find(p=>p.name===c.repoName);if(!l)return{ok:!1,message:`repo "${c.repoName}" not in project.yaml \u2014 run /sync`};let u=Tr(t.root,l.mountAs);if(!Es(Tr(u,".git")))return{ok:!1,message:`${l.mountAs}/ not cloned \u2014 run /sync first`};n.push({git:Ss(u),dir:u,spec:l,cr:c})}let o=[],s=[];for(let c of n)try{let{commit:l}=await wf(c.git,c.dir,{contextRepoCloneUrl:c.cr.contextRepoCloneUrl,deliveryRef:c.cr.deliveryRef,deliverySha:c.cr.deliverySha,baseSha:c.cr.baseSha,baseRef:c.cr.baseRef,branchName:c.cr.branchName,commitMessage:c.cr.commitMessage,defaultBranch:c.spec.defaultBranch});r.info(`[apply] ${e.taskKey}: ${c.cr.branchName} \u2192 ${c.spec.mountAs} (${l.slice(0,10)})`),o.push({git:c.git,branch:c.cr.branchName}),s.push({mountAs:c.spec.mountAs,branch:c.cr.branchName,baseSha:`origin/${c.cr.baseRef}`,appliedSha:l})}catch(l){for(let u of o)await u.git.raw(["branch","-D",u.branch]).catch(()=>{});return{ok:!1,message:`auto-apply failed in ${c.spec.mountAs}: ${Rr(l)}`}}try{await dc(t.hubUrl,t.cliToken,t.projectId,e.taskKey)}catch(c){return{ok:!1,message:`branch created but claim failed: ${Rr(c)} \u2014 retried on the next reconnect`,branches:o.map(l=>l.branch)}}let i=Ir(t.contextDir);i[e.taskKey]={mode:"apply",claimedAt:new Date().toISOString(),repos:s},mc(t.contextDir,i);let a=s.map(c=>`${c.branch} (${c.mountAs})`).join(", ");return{ok:!0,branches:s.map(c=>c.branch),message:`branch created locally without touching your checkout: ${a}
32
37
  review, push, then: /applied ${e.taskKey} --pr <url>
33
- or: /abort ${e.taskKey} --reason "..."`}}function ga(t,e){let r=yr(t);r[e]&&(delete r[e],ma(t,r))}async function fa(t,e){for(let r of t)try{await r.git.raw(["cherry-pick","--quit"]).catch(()=>{}),await r.git.checkout(["-f",r.originalRef]),await r.git.reset(["--hard",r.originalRef]),await r.git.raw(["branch","-D",r.branch]).catch(()=>{})}catch(n){e.warn(`rollback failed in ${r.mountAs}: ${gr(n)} \u2014 check manually`)}}async function Sp(t,e,r){let o=yr(t.contextDir)[e];if(o){for(let i of o.repos){let s=hr(t.root,i.mountAs);if(!ui(hr(s,".git")))continue;let a=li(s),c=t.spec.repos.find(u=>u.mountAs===i.mountAs),l=c?`origin/${c.defaultBranch}`:i.baseSha;try{await a.checkout(["-f",l]),await a.reset(["--hard",l]),await a.raw(["branch","-D",i.branch]).catch(()=>{})}catch(u){r.warn(`rollback failed in ${i.mountAs}: ${gr(u)} \u2014 check manually`)}}ga(t.contextDir,e)}}async function Cb(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function gr(t){return t instanceof Error?t.message.trim():String(t)}var bp,Rb,ha=v(()=>{"use strict";Ie();mr();bp=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],Rb="apply-queue.json"});import{existsSync as Ab}from"node:fs";import{join as Pb}from"node:path";import{simpleGit as _b}from"simple-git";async function Tp(t,e){if(!Ab(Pb(t,".git")))return{status:"skipped"};let r=_b(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${jb(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 jb(t){return t instanceof Error?t.message.trim():String(t)}var Ep=v(()=>{"use strict"});import{existsSync as Ip,readFileSync as Rp,readdirSync as Nb,statSync as Ob}from"node:fs";import{join as ya}from"node:path";import{parse as Cp}from"yaml";function di(t){let e=ya(t,"actions"),r=[],n=[];if(!Ip(e))return{defs:r,errors:n};let o;try{o=Nb(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=ya(e,s);try{if(!Ob(a).isFile())continue;let c=Zl(s,Cp(Rp(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 Ap(t){let e={},r=ya(t,"project.yaml");if(!Ip(r))return e;let n;try{n=Cp(Rp(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))!Fe.test(i)||_t(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var ka=v(()=>{"use strict";G()});import{existsSync as wa,readFileSync as Pp,readdirSync as Lb,watch as Db}from"node:fs";import{join as zn}from"node:path";var pi,_p=v(()=>{"use strict";ka();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,zn(this.contextDir,"prompts"),zn(this.contextDir,"actions")];for(let n of r)if(wa(n))try{let o=Db(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=di(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=zn(this.contextDir,e);if(!wa(r))return null;try{return Pp(r,"utf-8")}catch{return null}}readPrompts(){let e=zn(this.contextDir,"prompts"),r={};if(!wa(e))return r;let n;try{n=Lb(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=Pp(zn(e,o),"utf-8")}catch{}}return r}}});import{existsSync as Gt,mkdirSync as jp,readFileSync as ba,writeFileSync as Hr}from"node:fs";import{homedir as Mb}from"node:os";import{join as ht}from"node:path";import{simpleGit as Ub}from"simple-git";function Xn(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=ht(t,o);Gt(s)||(Hr(s,i),r.push(o))}return r}function kr(t,e,r){let n=ht(Mb(),".codepipe","profiles",t,"context-config");return jp(n,{recursive:!0}),Hr(ht(n,"project.yaml"),e.projectYaml),Hr(ht(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function fi(t,e,r){if(Gt(e))for(let n of Wr){let o=ht(e,n),i=ht(t,n);if(!(!Gt(o)||Gt(i)))try{Hr(i,ba(o)),r.info(`[config] seeded local ${n} from the provisioning bundle`)}catch(s){r.warn(`[config] could not seed ${n}: ${s instanceof Error?s.message:String(s)}`)}}}function qr(t){let e=ht(t,".gitignore"),r=Gt(e)?ba(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(Wr.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
38
+ or: /abort ${e.taskKey} --reason "..."`}}function hc(t,e){let r=Ir(t);r[e]&&(delete r[e],mc(t,r))}async function fc(t,e){for(let r of t)try{await r.git.raw(["cherry-pick","--quit"]).catch(()=>{}),await r.git.checkout(["-f",r.originalRef]),await r.git.reset(["--hard",r.originalRef]),await r.git.raw(["branch","-D",r.branch]).catch(()=>{})}catch(n){e.warn(`rollback failed in ${r.mountAs}: ${Rr(n)} \u2014 check manually`)}}async function If(t,e,r){let o=Ir(t.contextDir)[e];if(o){for(let s of o.repos){let i=Tr(t.root,s.mountAs);if(!Es(Tr(i,".git")))continue;let a=Ss(i),c=t.spec.repos.find(u=>u.mountAs===s.mountAs),l=c?`origin/${c.defaultBranch}`:s.baseSha;try{await a.checkout(["-f",l]),await a.reset(["--hard",l]),await a.raw(["branch","-D",s.branch]).catch(()=>{})}catch(u){r.warn(`rollback failed in ${s.mountAs}: ${Rr(u)} \u2014 check manually`)}}hc(t.contextDir,e)}}async function Rv(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function Rr(t){return t instanceof Error?t.message.trim():String(t)}var Sf,Ev,gc=$(()=>{"use strict";Ae();Er();Sf=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],Ev="apply-queue.json"});import{existsSync as Tv}from"node:fs";import{join as Iv}from"node:path";import{simpleGit as Cv}from"simple-git";async function Cf(t,e){if(!Tv(Iv(t,".git")))return{status:"skipped"};let r=Cv(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${Av(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 Av(t){return t instanceof Error?t.message.trim():String(t)}var Af=$(()=>{"use strict"});import{existsSync as Pf,readFileSync as _f,readdirSync as Pv,statSync as _v}from"node:fs";import{join as yc}from"node:path";import{parse as jf}from"yaml";function Rs(t){let e=yc(t,"actions"),r=[],n=[];if(!Pf(e))return{defs:r,errors:n};let o;try{o=Pv(e).sort()}catch{return{defs:r,errors:n}}let s=new Set;for(let i of o){if(!/\.(yml|yaml)$/i.test(i))continue;let a=yc(e,i);try{if(!_v(a).isFile())continue;let c=ka(i,jf(_f(a,"utf-8")));if(s.has(c.id))throw new Error(`duplicate action id "${c.id}"`);s.add(c.id),r.push(c)}catch(c){n.push({file:`actions/${i}`,error:c instanceof Error?c.message:String(c)})}}return{defs:r,errors:n}}function Nf(t){let e={},r=yc(t,"project.yaml");if(!Pf(r))return e;let n;try{n=jf(_f(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[s,i]of Object.entries(o))!Ge.test(s)||Pt(s)||(typeof i=="string"?e[s]=i:(typeof i=="number"||typeof i=="boolean")&&(e[s]=String(i)));return e}var kc=$(()=>{"use strict";F()});import{existsSync as wc,readFileSync as Of,readdirSync as jv,watch as Nv}from"node:fs";import{join as ho}from"node:path";var Ts,Lf=$(()=>{"use strict";kc();Ts=class{constructor(e,r,n,o,s=6e4){this.contextDir=e;this.projectId=r;this.send=n;this.log=o;this.intervalMs=s}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(wc(n))try{let o=Nv(n,e);o.on("error",s=>{this.log.warn(`[config] fs.watch failed on ${n} \u2014 falling back to periodic reporting: ${s instanceof Error?s.message:String(s)}`);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=Rs(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(!wc(r))return null;try{return Of(r,"utf-8")}catch{return null}}readPrompts(){let e=ho(this.contextDir,"prompts"),r={};if(!wc(e))return r;let n;try{n=jv(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let s=o.slice(0,-3);try{r[s]=Of(ho(e,o),"utf-8")}catch{}}return r}}});import{existsSync as Jt,mkdirSync as Df,readFileSync as bc,writeFileSync as nn}from"node:fs";import{homedir as Ov}from"node:os";import{join as vt}from"node:path";import{simpleGit as Lv}from"simple-git";function go(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,s]of n){let i=vt(t,o);Jt(i)||(nn(i,s),r.push(o))}return r}function Cr(t,e,r){let n=vt(Ov(),".codepipe","profiles",t,"context-config");return Df(n,{recursive:!0}),nn(vt(n,"project.yaml"),e.projectYaml),nn(vt(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function Is(t,e,r){if(Jt(e))for(let n of on){let o=vt(e,n),s=vt(t,n);if(!(!Jt(o)||Jt(s)))try{nn(s,bc(o)),r.info(`[config] seeded local ${n} from the provisioning bundle`)}catch(i){r.warn(`[config] could not seed ${n}: ${i instanceof Error?i.message:String(i)}`)}}}function sn(t){let e=vt(t,".gitignore"),r=Jt(e)?bc(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(i=>i.trim()));if(on.filter(i=>!n.has(i)&&!n.has(`/${i}`)).length===0)return!1;let s=r.length===0||r.endsWith(`
34
39
  `)?"":`
35
- `;return Hr(e,r+i+Bb.join(`
40
+ `;return nn(e,r+s+Dv.join(`
36
41
  `)+`
37
- `),!0}async function Np(t,e){try{if(!Gt(ht(t,".git")))return;let r=Ub(t),n=(await r.raw(["ls-files","--",...Wr])).split(`
38
- `).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;qr(t),await r.raw(["rm","--cached","--quiet","--",...n]),await r.add([".gitignore"]),await r.commit("chore(context): move project config out of the Context Repo"),await xa(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 $a(t){let e=new Map;for(let r of Wr){let n=ht(t,r);Gt(n)&&e.set(r,ba(n))}return e}function va(t,e){jp(t,{recursive:!0});for(let[r,n]of e){let o=ht(t,r);Gt(o)||Hr(o,n)}}var Wr,Bb,St=v(()=>{"use strict";rt();Wr=["project.yaml","regimen.yaml"];Bb=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as Fb,mkdirSync as Gb,rmSync as Kb,writeFileSync as Sa}from"node:fs";import{dirname as Hb,isAbsolute as Wb,join as Dp,normalize as hi}from"node:path";import{simpleGit as Mp}from"simple-git";async function Ta(t,e){let r=hi(t),o=(gi.get(r)??Promise.resolve()).catch(()=>{}).then(e);gi.set(r,o);try{return await o}finally{gi.get(r)===o&&gi.delete(r)}}async function Re(t,e,r){return Ta(t,()=>Ea(t,e,r))}async function Ea(t,e,r){if(!Fb(Dp(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=he(t,a.path);if(a.deleted){Kb(c,{force:!0});continue}Gb(Hb(c),{recursive:!0}),a.encoding==="base64"?Sa(c,Buffer.from(a.content,"base64")):Sa(c,a.content)}let n=Mp(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+=mi)await n.raw(["add","-A","-f","--",...o.slice(a,a+mi)]);for(let a=0;a<i.length;a+=mi)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...i.slice(a,a+mi)]);await n.raw(["reset","-q","--",...Wr]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await xa(t))}async function xa(t){let e=Mp(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=Op;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 zb(e);if(i.length>0&&i.every(a=>qb.has(a)||Lp.test(a)||Yb.test(a))){for(let a of i)Lp.test(a)?await Vb(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 ${Op} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function Vb(t,e,r){let n=async s=>await t.raw(["show",`:${s}:${r}`]).catch(()=>""),o=new Map;for(let s of[await n(2),await n(3)])for(let a of s.split(`
39
- `)){let c=a.trim();if(c)try{let l=JSON.parse(c);if(typeof l.id!="string")continue;o.has(l.id)||o.set(l.id,{raw:c,createdAt:typeof l.createdAt=="string"?l.createdAt:""})}catch{}}let i=[...o.values()].sort((s,a)=>s.createdAt.localeCompare(a.createdAt)).map(s=>s.raw);Sa(he(e,r),i.join(`
40
- `)+(i.length>0?`
41
- `:""))}async function zb(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
42
- `).map(r=>r.trim()).filter(Boolean)}function he(t,e){if(Wb(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=hi(Dp(t,e)),n=hi(t+"/");if(r!==hi(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var Op,qb,Yb,Lp,mi,gi,rt=v(()=>{"use strict";St();Op=3,qb=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),Yb=/^model\/derived\//,Lp=/^tasks\/[^/]+\/comments\.jsonl$/,mi=500,gi=new Map});import{existsSync as Ia,readFileSync as Up,readdirSync as Xb}from"node:fs";import{join as Bp}from"node:path";import{simpleGit as Jb}from"simple-git";function e$(t){let e=t.split(`
43
- `),r=e.find(i=>i.startsWith("# ")),n=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",o=i=>{let s=new RegExp(`^-\\s*\\*\\*${i}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=s.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:n,status:o("Status"),date:o("Date")}}function t$(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
44
- `),a=s.findIndex(w=>w.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),u=[],p="",d=null,f=a>=0?a+1:0;for(let w=f;w<s.length;w++){let y=(s[w]??"").trim();if(y===""){f=w+1;continue}let x=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(y);if(!x)break;let T=(x[1]??"").trim().toLowerCase(),I=(x[2]??"").trim(),E=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(y);E&&(d=parseInt(E[1]??"",10)),T==="tasks"&&(p=I),l.has(T)||u.push(y),f=w+1}let m=p?p.includes(n)?p:`${p}, ${n}`:n,h=s.slice(f).join(`
45
- `).replace(/^\n+/,""),g=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${m}`,...u,"",h].join(`
46
- `);return{content:g.endsWith(`
47
- `)?g:g+`
48
- `,supersedes:d}}function r$(t,e){let r=String(e).padStart(4,"0"),n=t.replace(/^(-\s*\*\*Status:\*\*).*$/im,`$1 superseded by ADR-${r}`);return n===t?t.replace(/^(# .*)$/m,`$1
49
-
50
- - **Status:** superseded by ADR-${r}`):n}function n$(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(`
42
+ `),!0}async function Mf(t,e){try{if(!Jt(vt(t,".git")))return;let r=Lv(t),n=(await r.raw(["ls-files","--",...on])).split(`
43
+ `).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;sn(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 xc(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 $c(t){let e=new Map;for(let r of on){let n=vt(t,r);Jt(n)&&e.set(r,bc(n))}return e}function vc(t,e){Df(t,{recursive:!0});for(let[r,n]of e){let o=vt(t,r);Jt(o)||nn(o,n)}}var on,Dv,Ot=$(()=>{"use strict";tt();on=["project.yaml","regimen.yaml"];Dv=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as Mv,mkdirSync as Uv,rmSync as Bv,writeFileSync as Sc}from"node:fs";import{dirname as Fv,isAbsolute as Kv,join as Ff,normalize as Ps}from"node:path";import{simpleGit as Kf}from"simple-git";async function Ec(t,e){let r=Ps(t),o=(As.get(r)??Promise.resolve()).catch(()=>{}).then(e);As.set(r,o);try{return await o}finally{As.get(r)===o&&As.delete(r)}}async function Se(t,e,r){return Ec(t,()=>Rc(t,e,r))}async function Rc(t,e,r){if(!Mv(Ff(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=be(t,a.path);if(a.deleted){Bv(c,{force:!0});continue}Uv(Fv(c),{recursive:!0}),a.encoding==="base64"?Sc(c,Buffer.from(a.content,"base64")):Sc(c,a.content)}let n=Kf(t),o=e.filter(a=>!a.deleted).map(a=>a.path),s=e.filter(a=>a.deleted).map(a=>a.path);for(let a=0;a<o.length;a+=Cs)await n.raw(["add","-A","-f","--",...o.slice(a,a+Cs)]);for(let a=0;a<s.length;a+=Cs)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...s.slice(a,a+Cs)]);await n.raw(["reset","-q","--",...on]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await xc(t))}async function xc(t){let e=Kf(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=Uf;n++){try{await e.push();return}catch(s){r=s}await e.fetch().catch(()=>{});let o=(await e.revparse(["--abbrev-ref","HEAD"])).trim();try{await e.rebase([`origin/${o}`])}catch{let s=await qv(e);if(s.length>0&&s.every(a=>Gv.has(a)||Bf.test(a)||Hv.test(a))){for(let a of s)Bf.test(a)?await Wv(e,t,a):await e.raw(["checkout","--theirs","--",a]);await e.add(s),await e.raw(["-c","core.editor=true","rebase","--continue"])}else throw await e.rebase(["--abort"]).catch(()=>{}),new Error(`context push: rebase conflict in ${s.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 Wv(t,e,r){let n=async i=>await t.raw(["show",`:${i}:${r}`]).catch(()=>""),o=new Map;for(let i of[await n(2),await n(3)])for(let a of i.split(`
44
+ `)){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 s=[...o.values()].sort((i,a)=>i.createdAt.localeCompare(a.createdAt)).map(i=>i.raw);Sc(be(e,r),s.join(`
45
+ `)+(s.length>0?`
46
+ `:""))}async function qv(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
47
+ `).map(r=>r.trim()).filter(Boolean)}function be(t,e){if(Kv(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=Ps(Ff(t,e)),n=Ps(t+"/");if(r!==Ps(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var Uf,Gv,Hv,Bf,Cs,As,tt=$(()=>{"use strict";Ot();Uf=3,Gv=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),Hv=/^model\/derived\//,Bf=/^tasks\/[^/]+\/comments\.jsonl$/,Cs=500,As=new Map});import{existsSync as Tc,readFileSync as Gf,readdirSync as Yv}from"node:fs";import{join as Hf}from"node:path";import{simpleGit as Vv}from"simple-git";function Jv(t){let e=t.split(`
48
+ `),r=e.find(s=>s.startsWith("# ")),n=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",o=s=>{let i=new RegExp(`^-\\s*\\*\\*${s}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=i.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:n,status:o("Status"),date:o("Date")}}function Zv(t,e,r,n,o){let s=String(e).padStart(4,"0"),i=t.split(`
49
+ `),a=i.findIndex(w=>w.startsWith("# ")),c=a>=0&&(i[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 w=m;w<i.length;w++){let y=(i[w]??"").trim();if(y===""){m=w+1;continue}let x=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(y);if(!x)break;let S=(x[1]??"").trim().toLowerCase(),T=(x[2]??"").trim(),R=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(y);R&&(d=parseInt(R[1]??"",10)),S==="tasks"&&(p=T),l.has(S)||u.push(y),m=w+1}let f=p?p.includes(n)?p:`${p}, ${n}`:n,g=i.slice(m).join(`
50
+ `).replace(/^\n+/,""),h=[`# ADR-${s}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${f}`,...u,"",g].join(`
51
+ `);return{content:h.endsWith(`
52
+ `)?h:h+`
53
+ `,supersedes:d}}function Qv(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
54
+
55
+ - **Status:** superseded by ADR-${r}`):n}function ex(t){let e=["# ADR index","","<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->",""];if(t.length===0)e.push("(no accepted ADRs yet)");else for(let r of[...t].sort((n,o)=>n.num-o.num)){let n=String(r.num).padStart(4,"0"),o=[r.header.status||"accepted",r.header.date].filter(Boolean).join(", ");e.push(`- [ADR-${n} \u2014 ${r.header.title||r.file}](${r.file}) \u2014 ${o}`)}return e.join(`
51
56
  `)+`
52
- `}async function Fp(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await Jb(t).pull(void 0,void 0,["--rebase"])}catch{}let i=g=>o==="staging"?`adr/DRAFT-${g}.md`:`tasks/${e}/adr/DRAFT-${g}.md`,s=[],a=[];for(let g of r){let w=he(t,i(g));if(!Ia(w)){a.push(g);continue}s.push({slug:g,content:Up(w,"utf-8")})}let c=Bp(t,"adr"),l=new Map;if(Ia(c))for(let g of Xb(c)){let w=Qb.exec(g);!w||g===Zb||l.set(g,{num:parseInt(w[1]??"",10),slug:w[2]??"",content:Up(Bp(c,g),"utf-8")})}let u=Math.max(0,...[...l.values()].map(g=>g.num))+1,p=new Map,d=[],f=[];for(let g of s){if([...l.entries()].find(([,E])=>E.slug===g.slug&&E.content.includes(e))){f.push(g.slug);continue}let y=u++,x=`${String(y).padStart(4,"0")}-${g.slug}.md`,{content:T,supersedes:I}=t$(g.content,y,g.slug,e,n);if(p.set(x,T),l.set(x,{num:y,slug:g.slug,content:T}),d.push(`adr/${x}`),I!==null){let E=[...l.keys()].find(b=>b.startsWith(`${String(I).padStart(4,"0")}-`));if(E&&E!==x){let b=r$(p.get(E)??l.get(E).content,y);p.set(E,b),l.set(E,{...l.get(E),content:b})}}}let m=[];if(o==="staging")for(let g of s)Ia(he(t,`adr/DRAFT-${g.slug}.md`))&&m.push({path:`adr/DRAFT-${g.slug}.md`,content:"",deleted:!0});if(d.length===0&&m.length===0)return{promoted:d,skipped:f,missing:a};if(d.length>0){let g=[...l.entries()].map(([w,y])=>({num:y.num,file:w,header:e$(y.content)}));p.set("INDEX.md",n$(g))}for(let[g,w]of p.entries())m.push({path:`adr/${g}`,content:w});let h=d.length>0?`adr(${e}): promote ${s.map(g=>g.slug).join(", ")}`:`adr(${e}): drop stale staged ${f.join(", ")}`;return await Re(t,m,h),{promoted:d,skipped:f,missing:a}}var Qb,Zb,Gp=v(()=>{"use strict";rt();Qb=/^(\d{4})-(.+)\.md$/,Zb="0000-template.md"});import{existsSync as Kp,readFileSync as i$}from"node:fs";import{join as Hp}from"node:path";function s$(t){for(let e of[ut,On]){let r=Hp(t,e);if(Kp(r))try{return Sl(i$(r,"utf-8"))}catch{return 0}}return 0}function a$(t,e,r,n=4){let o=e<n,i=o?Tl(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function yi(t,e){return a$(e,s$(t),r=>Kp(Hp(t,r)))}var Ra=v(()=>{"use strict";G()});import{existsSync as Kt,readFileSync as Yr,readdirSync as qp}from"node:fs";import{join as Ca}from"node:path";import{simpleGit as Yp}from"simple-git";import{parse as Vp}from"yaml";function zp(t){try{let e=he(t,Bo);if(!Kt(e))return null;let r=Vp(Yr(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!Lr.test(n)?null:{prefix:n}}catch{return null}}function Xp(t){return`# Built-in tracker configuration \u2014 shared by every team member.
57
+ `}async function Wf(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await Vv(t).pull(void 0,void 0,["--rebase"])}catch{}let s=h=>o==="staging"?`adr/DRAFT-${h}.md`:`tasks/${e}/adr/DRAFT-${h}.md`,i=[],a=[];for(let h of r){let w=be(t,s(h));if(!Tc(w)){a.push(h);continue}i.push({slug:h,content:Gf(w,"utf-8")})}let c=Hf(t,"adr"),l=new Map;if(Tc(c))for(let h of Yv(c)){let w=zv.exec(h);!w||h===Xv||l.set(h,{num:parseInt(w[1]??"",10),slug:w[2]??"",content:Gf(Hf(c,h),"utf-8")})}let u=Math.max(0,...[...l.values()].map(h=>h.num))+1,p=new Map,d=[],m=[];for(let h of i){if([...l.entries()].find(([,R])=>R.slug===h.slug&&R.content.includes(e))){m.push(h.slug);continue}let y=u++,x=`${String(y).padStart(4,"0")}-${h.slug}.md`,{content:S,supersedes:T}=Zv(h.content,y,h.slug,e,n);if(p.set(x,S),l.set(x,{num:y,slug:h.slug,content:S}),d.push(`adr/${x}`),T!==null){let R=[...l.keys()].find(b=>b.startsWith(`${String(T).padStart(4,"0")}-`));if(R&&R!==x){let b=Qv(p.get(R)??l.get(R).content,y);p.set(R,b),l.set(R,{...l.get(R),content:b})}}}let f=[];if(o==="staging")for(let h of i)Tc(be(t,`adr/DRAFT-${h.slug}.md`))&&f.push({path:`adr/DRAFT-${h.slug}.md`,content:"",deleted:!0});if(d.length===0&&f.length===0)return{promoted:d,skipped:m,missing:a};if(d.length>0){let h=[...l.entries()].map(([w,y])=>({num:y.num,file:w,header:Jv(y.content)}));p.set("INDEX.md",ex(h))}for(let[h,w]of p.entries())f.push({path:`adr/${h}`,content:w});let g=d.length>0?`adr(${e}): promote ${i.map(h=>h.slug).join(", ")}`:`adr(${e}): drop stale staged ${m.join(", ")}`;return await Se(t,f,g),{promoted:d,skipped:m,missing:a}}var zv,Xv,qf=$(()=>{"use strict";tt();zv=/^(\d{4})-(.+)\.md$/,Xv="0000-template.md"});import{existsSync as Yf,readFileSync as tx}from"node:fs";import{join as Vf}from"node:path";function rx(t){for(let e of[ct,Gr]){let r=Vf(t,e);if(Yf(r))try{return Hi(tx(r,"utf-8"))}catch{return 0}}return 0}function nx(t,e,r,n=6){let o=e<n,s=o?Wi(e).filter(i=>!r(i)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:s}}function _s(t,e){return nx(e,rx(t),r=>Yf(Vf(t,r)))}var Ic=$(()=>{"use strict";F()});import{existsSync as Zt,readFileSync as an,readdirSync as Xf}from"node:fs";import{join as Cc}from"node:path";import{simpleGit as Jf}from"simple-git";import{parse as Zf}from"yaml";function Qf(t){try{let e=be(t,so);if(!Zt(e))return null;let r=Zf(an(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!yr.test(n)?null:{prefix:n}}catch{return null}}function em(t){return`# Built-in tracker configuration \u2014 shared by every team member.
53
58
  # The issue-key prefix (<PREFIX>-<N>). Fixed at project init: changing it
54
59
  # later would orphan existing tasks/<KEY>/ directories.
55
60
  prefix: ${t}
@@ -57,15 +62,15 @@ prefix: ${t}
57
62
  # Statuses are the built-in default set for now:
58
63
  # Backlog | To Do | In Progress | Review | Done | Rejected
59
64
  # A configurable status set / pipeline mapping is a planned extension.
60
- `}function Aa(t=0){return`${t}
61
- `}function c$(t){return t==="depends_on"||t==="subtask"}function l$(t){let e;try{e=Vp(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=vu.includes(r.type)?r.type:Uo,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;c$(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 Pa(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(`
65
+ `}function Ac(t=0){return`${t}
66
+ `}function ox(t){return t==="depends_on"||t==="subtask"}function sx(t){let e;try{e=Zf(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=Ba.includes(r.type)?r.type:oo,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;ox(l.type)&&typeof l.target=="string"&&l.target&&o.push({type:l.type,targetKey:l.target})}let s=typeof r.created=="string"?r.created:new Date(0).toISOString(),i=typeof r.updated=="string"?r.updated:s,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:s,updated:i}}function Pc(t){let e=[`key: ${t.key}`,`title: ${JSON.stringify(t.title)}`,`type: ${t.type}`,`status: ${JSON.stringify(t.status)}`];if(t.assignee&&e.push(`assignee: ${JSON.stringify(t.assignee)}`),t.links.length>0){e.push("links:");for(let r of t.links)e.push(` - type: ${r.type}`,` target: ${r.targetKey}`)}return e.push(`created: ${t.created}`,`updated: ${t.updated}`),e.join(`
62
67
  `)+`
63
- `}function Qn(t,e){let r=he(t,Bn(e));return Kt(r)?l$(Yr(r,"utf-8")):null}function Jp(t){let e=Ca(t,"tasks");if(!Kt(e))return[];let r=[];for(let n of qp(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=Qn(t,n.name);o&&r.push(o)}return r}function u$(t,e){let r=he(t,`tasks/${e}/task.md`);if(!Kt(r))return;let n=Yr(r,"utf-8").split(`
64
- `),o=n.indexOf("---");if(o<0)return;let i=n.slice(o+1),s=i.lastIndexOf("## Attachments");s>=0&&i.slice(s+1).every(u=>u.trim()===""||/^- \[[^\]]*\]\(attachments\/[^)]*\)$/.test(u.trim()))&&(i=i.slice(0,s));let a=i.join(`
65
- `).trim();if(!(!a||a==="_(no description)_"))return a}function Zn(t,e,r={}){let n=r.withDescription?u$(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:d$(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function d$(t){return t.charAt(0).toUpperCase()+t.slice(1)}function p$(t){let e=he(t,Un);if(!Kt(e))return 0;let r=Number.parseInt(Yr(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function f$(t,e){let r=Ca(t,"tasks");if(!Kt(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of qp(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 m$(t,e){return Math.max(p$(t),f$(t,e))+1}async function Qp(t,e,r,n){return Ta(t,()=>g$(t,e,r,n))}async function g$(t,e,r,n){if(!Kt(Ca(t,".git")))throw new Error(`context repo clone not found at ${t}`);await Jn(t);let o=null;for(let i=0;i<Wp;i++){let s=m$(t,e),a=`${e}-${s}`,c=[...r(a),{path:Un,content:Aa(s)}];try{return await Ea(t,c,n(a)),a}catch(l){if(o=l,await y$(t,n(a)),await Jn(t),h$(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${Wp} attempts: ${o instanceof Error?o.message:String(o)}`)}function h$(t,e){for(let r of e){let n=he(t,r.path);if(!Kt(n)||(r.encoding==="base64"?Yr(n).toString("base64"):Yr(n,"utf-8"))!==r.content)return!1}return!0}async function Jn(t){let e=Yp(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 y$(t,e){let r=Yp(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
68
+ `}function ko(t,e){let r=be(t,zr(e));return Zt(r)?sx(an(r,"utf-8")):null}function tm(t){let e=Cc(t,"tasks");if(!Zt(e))return[];let r=[];for(let n of Xf(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=ko(t,n.name);o&&r.push(o)}return r}function ix(t,e){let r=be(t,`tasks/${e}/task.md`);if(!Zt(r))return;let n=an(r,"utf-8").split(`
69
+ `),o=n.indexOf("---");if(o<0)return;let s=n.slice(o+1),i=s.lastIndexOf("## Attachments");i>=0&&s.slice(i+1).every(u=>u.trim()===""||/^- \[[^\]]*\]\(attachments\/[^)]*\)$/.test(u.trim()))&&(s=s.slice(0,i));let a=s.join(`
70
+ `).trim();if(!(!a||a==="_(no description)_"))return a}function wo(t,e,r={}){let n=r.withDescription?ix(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:ax(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function ax(t){return t.charAt(0).toUpperCase()+t.slice(1)}function cx(t){let e=be(t,Vr);if(!Zt(e))return 0;let r=Number.parseInt(an(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function lx(t,e){let r=Cc(t,"tasks");if(!Zt(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let s of Xf(r,{withFileTypes:!0})){if(!s.isDirectory())continue;let i=n.exec(s.name);if(!i)continue;let a=Number.parseInt(i[1],10);Number.isFinite(a)&&a>o&&(o=a)}return o}function ux(t,e){return Math.max(cx(t),lx(t,e))+1}async function rm(t,e,r,n){return Ec(t,()=>dx(t,e,r,n))}async function dx(t,e,r,n){if(!Zt(Cc(t,".git")))throw new Error(`context repo clone not found at ${t}`);await yo(t);let o=null;for(let s=0;s<zf;s++){let i=ux(t,e),a=`${e}-${i}`,c=[...r(a),{path:Vr,content:Ac(i)}];try{return await Rc(t,c,n(a)),a}catch(l){if(o=l,await fx(t,n(a)),await yo(t),px(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${zf} attempts: ${o instanceof Error?o.message:String(o)}`)}function px(t,e){for(let r of e){let n=be(t,r.path);if(!Zt(n)||(r.encoding==="base64"?an(n).toString("base64"):an(n,"utf-8"))!==r.content)return!1}return!0}async function yo(t){let e=Jf(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 fx(t,e){let r=Jf(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
66
71
  `)[0]||!(await r.raw(["log","@{u}..HEAD","--pretty=%s"]).catch(()=>"")).trim().split(`
67
- `).some(i=>i.trim()===e.split(`
68
- `)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var Wp,ki=v(()=>{"use strict";G();rt();Wp=5});function Vr(t,e,r,n){return[{path:"README.md",content:C$(t,e)},{path:".gitignore",content:x$()},{path:"CLAUDE.md",content:T$(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:S$()},{path:"knowledge/README.md",content:E$()},{path:"knowledge/build.yaml",content:R$()},{path:"actions/README.md",content:I$()},{path:"model/README.md",content:k$()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:v$()},{path:"adr/README.md",content:w$()},{path:"adr/0000-template.md",content:b$()},{path:"adr/INDEX.md",content:$$()},{path:ut,content:Po()},...t.trackerProvider==="internal"?[{path:Bo,content:Xp(t.youtrackProjectKey??Gs)},{path:Un,content:Aa()}]:[]]}function k$(){return`# model/ \u2014 the project map
72
+ `).some(s=>s.trim()===e.split(`
73
+ `)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var zf,js=$(()=>{"use strict";F();tt();zf=5});function cn(t,e,r,n){return[{path:"README.md",content:Tx(t,e)},{path:".gitignore",content:wx()},{path:"CLAUDE.md",content:$x(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:bx()},{path:"knowledge/README.md",content:vx()},{path:"knowledge/build.yaml",content:Rx()},{path:"actions/README.md",content:xx()},{path:"roles/README.md",content:Sx()},{path:"skills/README.md",content:Ex()},{path:"model/README.md",content:mx()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:kx()},{path:"adr/README.md",content:hx()},{path:"adr/0000-template.md",content:gx()},{path:"adr/INDEX.md",content:yx()},{path:ct,content:zn()},...t.trackerProvider==="internal"?[{path:so,content:em(t.youtrackProjectKey??ns)},{path:Vr,content:Ac()}]:[]]}function mx(){return`# model/ \u2014 the project map
69
74
 
70
75
  A graph of the project built from **git history and task artifacts**: files
71
76
  and directories connected by the fact of changing together and the fact of
@@ -92,7 +97,7 @@ asset \u2014 treat it like \`knowledge/\`.
92
97
 
93
98
  Every YAML file carries \`modelFormatVersion\`; a reader that meets a
94
99
  different version treats it as "rebuild needed", not as an error.
95
- `}function w$(){return`# ADR \u2014 architecture decision records
100
+ `}function hx(){return`# ADR \u2014 architecture decision records
96
101
 
97
102
  Accepted architectural decisions of this project \u2014 its **framework**. The
98
103
  agent reads this section (start with \`INDEX.md\`) at the beginning of every
@@ -120,7 +125,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
120
125
  canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
121
126
  is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
122
127
  open a PR to this repository.
123
- `}function b$(){return`# ADR-NNNN: <title>
128
+ `}function gx(){return`# ADR-NNNN: <title>
124
129
 
125
130
  - **Status:** accepted | superseded by ADR-NNNN
126
131
  - **Date:** YYYY-MM-DD
@@ -142,12 +147,12 @@ What becomes easier, what becomes harder, what future tasks must keep doing.
142
147
  ## Alternatives considered
143
148
 
144
149
  - **<alternative>** \u2014 why it was rejected.
145
- `}function $$(){return`# ADR index
150
+ `}function yx(){return`# ADR index
146
151
 
147
152
  <!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->
148
153
 
149
154
  (no accepted ADRs yet)
150
- `}function v$(){return`# Audit
155
+ `}function kx(){return`# Audit
151
156
 
152
157
  Pipeline event logs. Naming is per-writer: each codepipe
153
158
  project appends only to its own file \u2014
@@ -156,14 +161,14 @@ project appends only to its own file \u2014
156
161
 
157
162
  \u2014 so several team members' CLIs never contend on one file. Do not create a
158
163
  shared aggregate here.
159
- `}function yt(t,e,r,n,o="auto",i=pt,s){let a=t.trackerProvider==="internal";return{projectYaml:a?A$(t,o):P$(t,r,n,o),regimenYaml:_$(t.automationLevel,a?!0:e,a,i,s)}}function x$(){return`# codepipe project config is local to each member's workspace
164
+ `}function xt(t,e,r,n,o="auto",s=Ke,i){let a=t.trackerProvider==="internal";return{projectYaml:a?Ix(t,o):Cx(t,r,n,o),regimenYaml:Ax(t.automationLevel,a?!0:e,a,s,i)}}function wx(){return`# codepipe project config is local to each member's workspace
160
165
  project.yaml
161
166
  regimen.yaml
162
167
 
163
168
  # codepipe runtime
164
169
  session.log
165
170
  apply-queue.json
166
- `}function S$(){return`# Index prompt
171
+ `}function bx(){return`# Index prompt
167
172
 
168
173
  You are the **Indexer** agent on the CodePipe pipeline. Your one job is to build a
169
174
  navigation map of this project's repositories and save it to the Context Repo, so
@@ -220,7 +225,7 @@ current working directory; write nothing else under the Context Repo.
220
225
  Keep both durable and skimmable \u2014 they are read at the start of every future
221
226
  task. Prefer structure (headings, bullet lists) over prose. If a repository is
222
227
  empty or unavailable, say so briefly rather than inventing content.
223
- `}function T$(t){return`# Project context for the CodePipe agent
228
+ `}function $x(t){return`# Project context for the CodePipe agent
224
229
 
225
230
  Instructions for AI agents working on **${t.name}** tasks. Claude Code
226
231
  auto-loads this file when the Context Repo is mounted. Keep it short and
@@ -238,7 +243,7 @@ the relevant notes there; when you learn something durable (an architectural
238
243
  decision, a domain rule, a gotcha), record it as a short Markdown note under
239
244
  \`knowledge/\` so future tasks benefit. Refine existing notes rather than
240
245
  duplicating. Don't put task-specific narration here \u2014 that goes in the task's
241
- \`PLAN.md\` / \`diff-summary.md\`.
246
+ \`PLAN.md\` / \`SOLUTION.md\`.
242
247
 
243
248
  ## ADRs \u2014 the project's framework
244
249
 
@@ -248,7 +253,7 @@ project's architectural invariants: read them at the start of a task and treat
248
253
  them as binding. New or changed decisions do **not** go here directly \u2014 during
249
254
  analysis you draft them as task artifacts, and they are promoted into \`adr/\`
250
255
  only after the analysis is approved.
251
- `}function E$(){return`# Knowledge
256
+ `}function vx(){return`# Knowledge
252
257
 
253
258
  Durable, reusable notes about this project \u2014 the CodePipe agent's long-lived
254
259
  **memory** across tasks. Architectural decisions, domain rules,
@@ -265,7 +270,7 @@ Keep each note in its own file \u2014 never grow one shared aggregate \u2014 so
265
270
  concurrent commits touch different files and rebase cleanly. \`INDEX.md\` is
266
271
  REGENERATED from the entries by the index job: don't hand-edit it, and treat
267
272
  any merge conflict in it as noise (either side converges on the next run).
268
- `}function I$(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
273
+ `}function xx(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
269
274
 
270
275
  One \`<id>.yml\` per action. Every file here appears as a button on the
271
276
  project's **RUN** tab; an action with \`params\` opens a small wizard first.
@@ -304,7 +309,94 @@ steps:
304
309
  Parameter values are passed to the commands **only as env vars** \u2014 reference
305
310
  them as \`$INPUT_<NAME>\` in \`run\`; they are never substituted into the
306
311
  command text itself.
307
- `}function R$(){return`# BUILD phase config. Discovered & maintained by the agent.
312
+ `}function Sx(){return`# roles/ \u2014 who reviews your work
313
+
314
+ A **role** is a critic with a narrow view and its own curated context: one
315
+ \`<name>.md\` per role. Roles review a plan before the work starts, review the
316
+ change before it ships, and are consulted when a question comes up mid-task.
317
+
318
+ A set of roles ships with CodePipe (architecture, scope, testability,
319
+ refactoring). A file here with the same name **replaces** the built-in one; a
320
+ file with a new name adds a role of your own. Delete the file to go back to
321
+ the built-in behaviour.
322
+
323
+ Example \u2014 \`roles/security.md\`:
324
+
325
+ \`\`\`markdown
326
+ ---
327
+ description: Security \u2014 authz, input handling, secrets in logs
328
+ model: opus # optional; otherwise the project's per-role model applies
329
+ refs: # optional: what this role reads first (max 10 files)
330
+ - knowledge/threat-model.md
331
+ - adr/INDEX.md
332
+ scenarios: [plan_review, code_review, council]
333
+ enabled: true # optional; set false to keep the file but stop running it
334
+ ---
335
+ You are the security critic. \u2026the body is the role's prompt\u2026
336
+ \`\`\`
337
+
338
+ Keep \`refs\` short and specific: the value of a role is a NARROW view, and
339
+ "give it everything" is exactly the failure this design avoids.
340
+ `}function Ex(){return`# skills/ \u2014 procedures the agent can invoke
341
+
342
+ A **skill** is a directory with a \`SKILL.md\`: a description of when to use it,
343
+ a body with the steps, and any files the steps need beside it (scripts,
344
+ templates, checklists).
345
+
346
+ \`\`\`
347
+ skills/
348
+ \u2514\u2500\u2500 run-integration-tests/
349
+ \u251C\u2500\u2500 SKILL.md
350
+ \u2514\u2500\u2500 seed.sh
351
+ \`\`\`
352
+
353
+ \`SKILL.md\`:
354
+
355
+ \`\`\`markdown
356
+ ---
357
+ description: Run the integration suite \u2014 use before touching anything under api/checkout
358
+ ---
359
+ 1. \`docker compose -f ops/it.yml up -d\`
360
+ 2. \`./seed.sh\` (idempotent; safe to re-run)
361
+ 3. \`pnpm test:it -- --shard=$SHARD\`
362
+
363
+ The suite fails on a cold database with a misleading auth error \u2014 that means
364
+ step 2 did not run, not that credentials are wrong.
365
+ \`\`\`
366
+
367
+ **Why a skill and not more prompt text.** Only the name and the description sit
368
+ in the agent's context; the body loads at the moment the skill is used. A prompt
369
+ pays its full length on every step of every job \u2014 a skill pays it once, when it
370
+ is actually needed. So a procedure that applies to one kind of work belongs
371
+ here, and instructions that apply to *everything* belong in \`CLAUDE.md\`.
372
+
373
+ **Write the description for the decision, not the topic.** "Run the integration
374
+ suite \u2014 use before touching anything under api/checkout" fires at the right
375
+ moment; "Integration testing" does not.
376
+
377
+ Three sources are merged for each job: the set bundled with CodePipe, this
378
+ directory, and \`.claude/skills/\` inside your code repositories. Same name \u21D2 the
379
+ one closest to the code wins (repository, then here, then bundled) \u2014 so a skill
380
+ your developers already use by hand stays authoritative. Any of the three can be
381
+ switched off in the project's settings.
382
+
383
+ Skill marketplaces are a fourth source, configured in \`regimen.yaml\`:
384
+
385
+ \`\`\`yaml
386
+ skills:
387
+ marketplaces:
388
+ - anthropics/skills # Anthropic's own \u2014 on by default
389
+ - anthropics/claude-plugins-official
390
+ # - someone/their-skills@<40-hex sha> # third-party: must be pinned
391
+ plugins:
392
+ - document-skills@anthropic-agent-skills
393
+ \`\`\`
394
+
395
+ A third-party marketplace **must** name a full commit sha: its skills run beside
396
+ your checked-out code with the agent's credentials, and a branch would let that
397
+ code change between two runs of the same task. Nothing from a marketplace is
398
+ active until it is listed in \`plugins\`.
399
+ `}function Rx(){return`# BUILD phase config. Discovered & maintained by the agent.
308
400
  # Steps run in a rootless Podman container in the SANDBOX, before the PR.
309
401
  # Success = every step exits 0. Credentials are NOT available inside the container.
310
402
  #
@@ -320,7 +412,7 @@ command text itself.
320
412
  # - name: test
321
413
  # run: npm test
322
414
  # timeout_sec: 600 # per-step timeout (optional, default 600)
323
- `}function C$(t,e){return`# ${e.name}
415
+ `}function Tx(t,e){return`# ${e.name}
324
416
 
325
417
  Context Repo for the **${t.name}** project (CodePipe).
326
418
 
@@ -346,7 +438,7 @@ PRs to this repository (and the agent also writes to \`knowledge/\` and
346
438
  pipeline \u2014 don't edit them by hand.
347
439
 
348
440
  Automation level: **${t.automationLevel}**.
349
- `}function A$(t,e="auto"){return`# Project description for CodePipe.
441
+ `}function Ix(t,e="auto"){return`# Project description for CodePipe.
350
442
  id: ${t.projectId}
351
443
  name: ${t.name}
352
444
 
@@ -373,28 +465,28 @@ apply:
373
465
  # Branch (must keep the <TASK_ID> placeholder).
374
466
  branch:
375
467
  pattern: codepipe/<TASK_ID>
376
- ${Zp(t)}
468
+ ${nm(t)}
377
469
  repos:
378
- ${ef(t)}
379
- `}function Zp(t){let e=t.language;return!e||Object.keys(e).length===0?"":`
470
+ ${om(t)}
471
+ `}function nm(t){let e=t.language;return!e||Object.keys(e).length===0?"":`
380
472
  # Languages the agent writes in, per area. \`auto\` = mirror the language of
381
473
  # the user's material. Also editable from the dashboard: project card \u2192
382
474
  # Settings \u2192 Language.
383
475
  language:
384
476
  ${Object.entries(e).map(([n,o])=>` ${n}: ${o}`).join(`
385
477
  `)}
386
- `}function ef(t){return t.repos.length===0?` [] # add repos here
478
+ `}function om(t){return t.repos.length===0?` [] # add repos here
387
479
  `:t.repos.map(e=>` - name: ${e.name}
388
480
  host: ${e.host}
389
481
  owner: ${e.owner}
390
482
  repo: ${e.repoName}
391
483
  mount_as: ${e.mountAs??e.name}`+(e.defaultBranch?`
392
484
  default_branch: ${e.defaultBranch}`:"")).join(`
393
- `)}function P$(t,e,r,n="auto"){let o=e?`
485
+ `)}function Cx(t,e,r,n="auto"){let o=e?`
394
486
  tracker_url: ${e}`:`
395
- # tracker_url: https://your.youtrack.cloud`,i=r?`require_assignee: true
487
+ # tracker_url: https://your.youtrack.cloud`,s=r?`require_assignee: true
396
488
  assignee: ${r}`:`require_assignee: false
397
- # assignee: your.youtrack.login`,s=t.youtrackProjectKey?` project_key: ${t.youtrackProjectKey}${o}
489
+ # assignee: your.youtrack.login`,i=t.youtrackProjectKey?` project_key: ${t.youtrackProjectKey}${o}
398
490
  poll_interval_sec: 60
399
491
  # Name of the YT workflow field the board is driven by. Default: Stage
400
492
  # (custom field); YouTrack's standard configuration uses State.
@@ -436,14 +528,14 @@ ${Object.entries(e).map(([n,o])=>` ${n}: ${o}`).join(`
436
528
  # behavior unchanged. When true, CodePipe only pulls tasks of the given
437
529
  # assignee (YT login) into the pipeline; without assignee \u2014 any task with a
438
530
  # non-empty assignee. assignee only takes effect when require_assignee=true.
439
- ${i}`:` # project_key: \u2026
531
+ ${s}`:` # project_key: \u2026
440
532
  # tracker_url: https://your.youtrack.cloud
441
- poll_interval_sec: 60`,a=ef(t);return`# Project description for CodePipe.
533
+ poll_interval_sec: 60`,a=om(t);return`# Project description for CodePipe.
442
534
  id: ${t.projectId}
443
535
  name: ${t.name}
444
536
 
445
537
  youtrack:
446
- ${s}
538
+ ${i}
447
539
 
448
540
  adapters:
449
541
  tracker: youtrack
@@ -472,10 +564,10 @@ apply:
472
564
  # Branch (must keep the <TASK_ID> placeholder).
473
565
  branch:
474
566
  pattern: codepipe/<TASK_ID>
475
- ${Zp(t)}
567
+ ${nm(t)}
476
568
  repos:
477
569
  ${a}
478
- `}function _$(t,e,r=!1,n=pt,o){let i=t==="full",s=e?"true":"false",a=o?` # Model selection. This project's Claude subscription did not include every
570
+ `}function Ax(t,e,r=!1,n=Ke,o){let s=t==="full",i=e?"true":"false",a=o?` # Model selection. This project's Claude subscription did not include every
479
571
  # model in the recommended per-role split, so CodePipe set a single default
480
572
  # your subscription can serve for all roles. Tune per role later from the
481
573
  # dashboard (Project Settings \u2192 llm.models) or by editing this file.
@@ -519,11 +611,11 @@ ${r?` # The built-in tracker is CodePipe's own \u2014 these switches stay on (t
519
611
  # These flags are set from a dedicated 'codepipe init' question and do
520
612
  # NOT depend on automation.level \u2014 the two are orthogonal axes (writes vs gates).`}
521
613
  writes:
522
- enabled: ${s}
523
- status_changes: ${s}
524
- pr_comment: ${s}
614
+ enabled: ${i}
615
+ status_changes: ${i}
616
+ pr_comment: ${i}
525
617
  # Mirror dashboard comments back into YouTrack. Off without enabled.
526
- dashboard_mirror: ${s}
618
+ dashboard_mirror: ${i}
527
619
  # YT column (Stage) for new drafts published from PLAN.
528
620
  # Backlog by default \u2192 the task shows up in the TODO section, not straight in WORK.
529
621
  draft_target_status: Backlog
@@ -538,10 +630,10 @@ gates:
538
630
  # 'assisted' requires a manual Run/Approve at each. Names and modes mirror
539
631
  # docs/PIPELINE.md so a future per-gate parser stays config-compatible.
540
632
  # Modes: always | auto_below_hours | never.
541
- G1_estimate: { mode: ${i?"never":"always"} }
542
- G2_solution: { mode: ${i?"never":"always"} }
543
- G3_implementation: { mode: ${i?"never":"always"} }
544
- G4_apply: { mode: ${i?"never":"always"} }
633
+ G1_estimate: { mode: ${s?"never":"always"} }
634
+ G2_solution: { mode: ${s?"never":"always"} }
635
+ G3_implementation: { mode: ${s?"never":"always"} }
636
+ G4_apply: { mode: ${s?"never":"always"} }
545
637
  # The first ACTUALLY consumed key of the gates block. When true (the
546
638
  # default), a task taken from a source stage lands in the QUEUE section
547
639
  # (QUEUED) and waits for a single Confirm; the Confirm pulls in the
@@ -617,63 +709,47 @@ ${a}
617
709
  # sandbox quota (how many runners the account may occupy), enforced by the HUB
618
710
  # and sized on the farm. A solo 'codepipe up' runs one worker. (ADR-0030)
619
711
 
620
- # implementation:
621
- # # How IMPLEMENTING is ordered across tasks. Default: cluster-pr.
622
- # # cluster-pr \u2014 the whole linked scope (dependency cluster) is developed on
623
- # # one shared branch: tasks commit in chain order, each review
624
- # # sees the accumulated state, and the cluster ships as a
625
- # # single pull request merged once. A standalone task is a
626
- # # cluster of one.
627
- # # parallel \u2014 DEPRECATED (will be removed): tasks branch independently
628
- # # off the base; conflicts are resolved reactively via
629
- # # \`@codepipe rebase\`. No head-of-line blocking between tasks.
630
- # # sequential \u2014 DEPRECATED (will be removed): one task at a time in
631
- # # creation order; each branch stacks on the previous task's
632
- # # branch (auto-merge without reworking the tail of the chain).
633
- # # While this key stays commented out, the project keeps its current mode \u2014
634
- # # only new projects start on cluster-pr. Uncomment and set a value to switch.
635
- # mode: cluster-pr
636
- `}var wr=v(()=>{"use strict";G();ki()});import{existsSync as tf,mkdirSync as j$,mkdtempSync as N$,rmSync as rf,writeFileSync as nf}from"node:fs";import{tmpdir as O$}from"node:os";import{dirname as L$,join as wi}from"node:path";import{simpleGit as _a}from"simple-git";function D$(t){return`codepipe/context-migration-v${t}`}function M$(t){let e=El(t.templateVersion),r=[`CodePipe context format migration: **v${t.templateVersion} \u2192 v${t.currentVersion}**.`,"","Additive only \u2014 this PR creates files your context is missing and updates",`the \`${ut}\` stamp (renamed from \`${On}\``,"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(`
637
- `)}async function of(t,e,r,n){let o=_a(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=yi(t,e);if(!i.outdated)return i;let s=D$(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 U$(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=Ze(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:M$(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 U$(t,e,r,n,o,i,s){let a=_a(t),c=N$(wi(O$(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",o,c,`origin/${i}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},u={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},p=new Map(Vr(l,u).map(h=>[h.path,h.content])),d=0;for(let h of n.missingPaths){if(h===ut)continue;let g=p.get(h);if(g==null){s.warn(`[ctx] migration: no template for ${h} \u2014 skipped`);continue}let w=wi(c,h);tf(w)||(j$(L$(w),{recursive:!0}),nf(w,g),d++)}nf(wi(c,ut),Po(n.currentVersion)),d++;let f=wi(c,On);tf(f)&&(rf(f,{force:!0}),d++);let m=_a(c);await m.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await m.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await m.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${d} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),rf(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}var sf=v(()=>{"use strict";G();Dt();Ra();wr()});import{existsSync as B$,readFileSync as F$,writeFileSync as G$}from"node:fs";import{homedir as K$}from"node:os";import{join as af}from"node:path";import{parseDocument as H$}from"yaml";function W$(t){let e={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(e.default_branch=t.defaultBranch),e}function q$(t,e){let r=H$(t);return r.set("repos",e.map(W$)),r.toString()}function Y$(t,e){let r=[af(K$(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(af(e,"project.yaml")),r}function eo(t,e,r){let n=[],o=[];for(let i of Y$(t,r))if(B$(i))try{let s=F$(i,"utf-8"),a=q$(s,e);a!==s&&(G$(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}var ja=v(()=>{"use strict"});import{createCipheriv as V$,createDecipheriv as z$,createHash as X$,createPrivateKey as J$,createPublicKey as Na,diffieHellman as cf,generateKeyPairSync as lf,hkdfSync as uf,randomBytes as Q$}from"node:crypto";function bi(){let{publicKey:t,privateKey:e}=lf("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function je(t){let e=Buffer.from(t,"base64");return(X$("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function Tt(t,e){let r=Na({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=lf("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=cf({privateKey:o,publicKey:r}),c=Buffer.from(uf("sha256",a,Buffer.concat([i,s]),df,32)),l=Q$(12),u=V$("aes-256-gcm",c,l),p=typeof e=="string"?Buffer.from(e,"utf-8"):e,d=Buffer.concat([u.update(p),u.final()]),f=u.getAuthTag(),m={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:f.toString("base64"),ct:d.toString("base64")};return Buffer.from(JSON.stringify(m),"utf-8").toString("base64")}function zr(t,e){let r=JSON.parse(Buffer.from(e,"base64").toString("utf-8"));if(r.v!==1)throw new Error(`sealedbox: unsupported envelope version ${r.v}`);let n=J$({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=Na({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=Na(n).export({type:"spki",format:"der"}),a=cf({privateKey:n,publicKey:o}),c=Buffer.from(uf("sha256",a,Buffer.concat([i,s]),df,32)),l=z$("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 df,We=v(()=>{"use strict";df=Buffer.from("devpipe-sealedbox-v1","utf-8")});function Z$(t,e){let r={};t.github?.token&&(r.github={token:t.github.token}),t.bitbucket?.apiToken&&(r.bitbucket={apiToken:t.bitbucket.apiToken}),t.gitlab?.token&&(r.gitlab={token:t.gitlab.token});let n=e??t.claude?.oauthToken;return n&&(r.claudeOauthToken=n),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),r}function pf(t,e,r,n){let o=Z$(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=Yo(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=Tt(a.publicKey,i)}catch(u){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}var ff=v(()=>{"use strict";We();ue()});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 ro(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 no(t,e=process.env){if(!t)return!1;let r=`https://${sr}:${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 Oa(t,e,r,n){let o=Number.parseInt(n.GIT_CONFIG_COUNT??"0",10)||0,i=!1;for(let s=0;s<o;s++){let a=n[`GIT_CONFIG_KEY_${s}`];a&&t.test(a)&&(n[`GIT_CONFIG_KEY_${s}`]=`url.${e}.insteadOf`,i=!0)}return i||r()}function mf(t,e=process.env){return Oa(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>to(t,e),e)}function gf(t,e=process.env){return Oa(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>ro(t,e),e)}function hf(t,e=process.env){return Oa(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${sr}:${encodeURIComponent(t)}@bitbucket.org/`,()=>no(t,e),e)}var $i=v(()=>{"use strict";G()});function yf(t){let e=W(t);if(!e)return null;if(!e.sealKey){let r=bi();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},oe(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:je(e.sealKey.publicKey)}}async function kf(t,e,r,n){let o;try{o=JSON.parse(zr(n,r).toString("utf-8"))}catch(s){return{ok:!1,detail:`cannot open the sealed credential (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}let i=W(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Nt(o.token);return i.github={token:o.token},Xr(i,()=>{process.env.GH_TOKEN=o.token,mf(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Lt(o.token);return i.gitlab={token:o.token},Xr(i,()=>{process.env.GITLAB_TOKEN=o.token,gf(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 Ot(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},Xr(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,hf(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 Ut({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},Xr(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},Xr(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},Xr(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 Xr(t,e){oe(t),e()}var wf=v(()=>{"use strict";We();ue();Dt();lr();Kr();$i()});import{spawn as ev}from"node:child_process";function rv(t,e,r,n,o,i){let s={...t},a=(c,l)=>{_t(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 vf(t){let{def:e,onEvent:r}=t,n=rv(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
638
- `,o.length>bf&&(o=o.slice(o.length-bf))},s=(a,c)=>{let l=c.length>$f?c.slice(0,$f)+"\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 nv(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 nv(t,e,r,n,o){return new Promise(i=>{let s=ev("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??Ql)*1e3,l=setTimeout(()=>{a=!0,o("stderr",`step timed out after ${c/1e3}s \u2014 killing`),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},c);l.unref?.();let u=f=>{let m="";return{data:h=>{m+=h.toString("utf-8");let g;for(;(g=m.indexOf(`
639
- `))!==-1;)o(f,m.slice(0,g).replace(/\r$/,"")),m=m.slice(g+1)},flush:()=>{m.length>0&&o(f,m.replace(/\r$/,"")),m=""}}},p=u("stdout"),d=u("stderr");s.stdout?.on("data",p.data),s.stderr?.on("data",d.data),s.on("error",f=>{clearTimeout(l),o("stderr",`spawn failed: ${f.message}`),i(127)}),s.on("close",(f,m)=>{clearTimeout(l),p.flush(),d.flush(),i(a?tv:f??(m?1:0))})})}var tv,bf,$f,xf=v(()=>{"use strict";G();tv=124,bf=16*1024,$f=4e3});import{existsSync as ov,readFileSync as iv,statSync as Sf}from"node:fs";function sv(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function Ef(t,e){let r=he(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!ov(r)||!Sf(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=Sf(r);if(n>Tf)throw new Error(`file too large: ${e} is ${n} bytes (limit ${Tf})`);let o=iv(r);return sv(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}var Tf,If=v(()=>{"use strict";rt();Tf=2*1024*1024});import{existsSync as av,readFileSync as cv,writeFileSync as lv}from"node:fs";import{join as uv}from"node:path";import{parseDocument as dv}from"yaml";async function Rf(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=su(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=uv(t,o);if(!av(s))throw new Error(`${o} not found in context repo (${t})`);let a=dv(cv(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);lv(s,a.toString()),n.push(o)}return{files:n}}var Cf=v(()=>{"use strict";G()});import{existsSync as pv,readFileSync as fv,writeFileSync as mv}from"node:fs";import{join as gv}from"node:path";import{isMap as Af,parseDocument as hv}from"yaml";async function Pf(t,e){let r=e.repoName?.trim(),n=e.defaultBranch?.trim();if(!r)throw new Error("repoName must be a non-empty string");if(!n||!fu(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=gv(t,"project.yaml");if(!pv(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=hv(fv(o,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>Af(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!Af(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),mv(o,i.toString()),{repoName:r,defaultBranch:n}}var _f=v(()=>{"use strict";G()});import{existsSync as La,readFileSync as Da,writeFileSync as yv}from"node:fs";import{join as vi}from"node:path";import{parseDocument as Ma}from"yaml";async function jf(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=vi(t,"project.yaml");if(!La(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=Ma(Da(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=vi(t,"regimen.yaml");if(!La(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=Ma(Da(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)yv(vi(t,i.path),i.content);return{files:r.map(i=>i.path)}}function xi(t){if(!t)return"Stage";try{let e=vi(t,"project.yaml");if(!La(e))return"Stage";let n=Ma(Da(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}var Ua=v(()=>{"use strict"});import{existsSync as Nf,readFileSync as Of,readdirSync as kv}from"node:fs";import{join as Ba}from"node:path";import{simpleGit as wv}from"simple-git";function bv(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(`
640
- `)){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 $v(t,e){let r=Ba(t,`tasks/${e}/annotations`);if(!Nf(r))return[];let n=[];for(let o of kv(r).sort())if(o.endsWith(".md")){try{let i=bv(o,Of(Ba(r,o),"utf-8"));i&&n.push(i)}catch{}if(n.length>=Nl)break}return n}async function Lf(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=wv(o),p=[];for(let d of $v(e,r)){if(d.repo!==n)continue;let f=pe("code",n,d.path);if(!a.has(f))continue;let m=l.get(f);if(!m)continue;let h=(await u.raw(["rev-parse",`${i}:${d.path}`]).catch(()=>"")).trim().slice(0,vv),g=Rl(m),w=Ba(e,g),y=p.find(R=>R.path===g),x=y?.content??(Nf(w)?Of(w,"utf-8"):null),T=`<!-- ${r}${h?`:${h}`:""} -->`;if(x?.includes(T))continue;let I=x??`---
641
- entityId: ${m}
712
+ `}var Ar=$(()=>{"use strict";F();js()});import{existsSync as sm,mkdirSync as Px,mkdtempSync as _x,rmSync as im,writeFileSync as am}from"node:fs";import{tmpdir as jx}from"node:os";import{dirname as Nx,join as Ns}from"node:path";import{simpleGit as _c}from"simple-git";function Ox(t){return`codepipe/context-migration-v${t}`}function Lx(t){let e=qi(t.templateVersion),r=[`CodePipe context format migration: **v${t.templateVersion} \u2192 v${t.currentVersion}**.`,"","Additive only \u2014 this PR creates files your context is missing and updates",`the \`${ct}\` stamp (renamed from \`${Gr}\``,"when the legacy file is present). Hand-edited files are never touched.","","## Format changes",""];for(let n of e){r.push(`- **v${n.version}** \u2014 ${n.summary}`);for(let o of n.addedPaths)r.push(` - \`${o}\``)}return r.push("","Merge to apply. CodePipe re-checks the stamp on the next daemon start and","clears the \u201Ccontext outdated\u201D badge.","","_Opened automatically by the CodePipe CLI._"),r.join(`
713
+ `)}async function cm(t,e,r,n){let o=_c(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let s=_s(t,e);if(!s.outdated)return s;let i=Ox(s.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",i]).catch(()=>"")).trim().length===0?await Dx(t,e,r,s,i,a,n):n.info(`[ctx] migration branch ${i} 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)}`),s}if(!r)return s;let c={name:r.name,host:r.host,owner:r.owner,repoName:r.name};try{let l=dt(c),u=await l.findOpenPrByBranch?.(c,i)??null;if(u)return n.info(`[ctx] migration PR already open: ${u.url}`),{...s,migrationPrUrl:u.url};let p=await l.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:i,baseBranch:a,title:`CodePipe: context format v${s.templateVersion} \u2192 v${s.currentVersion}`,body:Lx(s)});return n.info(`[ctx] migration PR opened: ${p.url}`),{...s,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)}`),s}}async function Dx(t,e,r,n,o,s,i){let a=_c(t),c=_x(Ns(jx(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",o,c,`origin/${s}`]);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(cn(l,u).map(g=>[g.path,g.content])),d=0;for(let g of n.missingPaths){if(g===ct)continue;let h=p.get(g);if(h==null){i.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let w=Ns(c,g);sm(w)||(Px(Nx(w),{recursive:!0}),am(w,h),d++)}am(Ns(c,ct),zn(n.currentVersion)),d++;let m=Ns(c,Gr);sm(m)&&(im(m,{force:!0}),d++);let f=_c(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]),i.info(`[ctx] migration branch ${o} pushed (${d} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),im(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}var lm=$(()=>{"use strict";F();qt();Ic();Ar()});import{existsSync as Mx,readFileSync as Ux,writeFileSync as Bx}from"node:fs";import{homedir as Fx}from"node:os";import{join as um}from"node:path";import{parseDocument as Kx}from"yaml";function Gx(t){let e={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(e.default_branch=t.defaultBranch),e}function Hx(t,e){let r=Kx(t);return r.set("repos",e.map(Gx)),r.toString()}function Wx(t,e){let r=[um(Fx(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(um(e,"project.yaml")),r}function bo(t,e,r){let n=[],o=[];for(let s of Wx(t,r))if(Mx(s))try{let i=Ux(s,"utf-8"),a=Hx(i,e);a!==i&&(Bx(s,a),n.push(s))}catch(i){o.push({path:s,error:i instanceof Error?i.message:String(i)})}return{updated:n,errors:o}}var jc=$(()=>{"use strict"});import{createCipheriv as qx,createDecipheriv as Yx,createHash as Vx,createPrivateKey as zx,createPublicKey as Nc,diffieHellman as dm,generateKeyPairSync as pm,hkdfSync as fm,randomBytes as Xx}from"node:crypto";function Os(){let{publicKey:t,privateKey:e}=pm("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function De(t){let e=Buffer.from(t,"base64");return(Vx("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function Lt(t,e){let r=Nc({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=pm("x25519"),s=n.export({type:"spki",format:"der"}),i=r.export({type:"spki",format:"der"}),a=dm({privateKey:o,publicKey:r}),c=Buffer.from(fm("sha256",a,Buffer.concat([s,i]),mm,32)),l=Xx(12),u=qx("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:s.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 ln(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=zx({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=Nc({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),s=o.export({type:"spki",format:"der"}),i=Nc(n).export({type:"spki",format:"der"}),a=dm({privateKey:n,publicKey:o}),c=Buffer.from(fm("sha256",a,Buffer.concat([s,i]),mm,32)),l=Yx("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 mm,rt=$(()=>{"use strict";mm=Buffer.from("devpipe-sealedbox-v1","utf-8")});function Jx(t,e){let r={};t.github?.token&&(r.github={token:t.github.token}),t.bitbucket?.apiToken&&(r.bitbucket={apiToken:t.bitbucket.apiToken}),t.gitlab?.token&&(r.gitlab={token:t.gitlab.token});let n=e??t.claude?.oauthToken;return n&&(r.claudeOauthToken=n),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),r}function hm(t,e,r,n){let o=Jx(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 s=JSON.stringify(o),i=[];for(let a of t.sandboxes){let c=cs(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=Lt(a.publicKey,s)}catch(u){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}i.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return i}var gm=$(()=>{"use strict";rt();pe()});function $o(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(s,i)=>{e[`GIT_CONFIG_KEY_${n+s}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+s}`]=i};return o(0,"git@github.com:"),o(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function vo(t,e=process.env){if(!t)return!1;let r=`https://oauth2:${t}@gitlab.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(s,i)=>{e[`GIT_CONFIG_KEY_${n+s}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+s}`]=i};return o(0,"git@gitlab.com:"),o(1,"ssh://git@gitlab.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function xo(t,e=process.env){if(!t)return!1;let r=`https://${Kt}:${encodeURIComponent(t)}@bitbucket.org/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(s,i)=>{e[`GIT_CONFIG_KEY_${n+s}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+s}`]=i};return o(0,"git@bitbucket.org:"),o(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function Oc(t,e,r,n){let o=Number.parseInt(n.GIT_CONFIG_COUNT??"0",10)||0,s=!1;for(let i=0;i<o;i++){let a=n[`GIT_CONFIG_KEY_${i}`];a&&t.test(a)&&(n[`GIT_CONFIG_KEY_${i}`]=`url.${e}.insteadOf`,s=!0)}return s||r()}function ym(t,e=process.env){return Oc(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>$o(t,e),e)}function km(t,e=process.env){return Oc(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>vo(t,e),e)}function wm(t,e=process.env){return Oc(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Kt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>xo(t,e),e)}var Ls=$(()=>{"use strict";F()});function bm(t){let e=q(t);if(!e)return null;if(!e.sealKey){let r=Os();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},ie(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:De(e.sealKey.publicKey)}}async function $m(t,e,r,n){let o;try{o=JSON.parse(ln(n,r).toString("utf-8"))}catch(i){return{ok:!1,detail:`cannot open the sealed credential (${i instanceof Error?i.message:String(i)}) \u2014 wrong channel key?`}}let s=q(t);if(!s)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 i=await Gt(o.token);return s.github={token:o.token},un(s,()=>{process.env.GH_TOKEN=o.token,ym(o.token)}),{ok:!0,detail:`authenticated as ${i}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let i=await Wt(o.token);return s.gitlab={token:o.token},un(s,()=>{process.env.GITLAB_TOKEN=o.token,km(o.token)}),{ok:!0,detail:`authenticated as ${i}`}}case"bitbucket":{if(!o.email||!o.apiToken)return{ok:!1,detail:"payload needs email + apiToken"};let i=await Ht(o.email,o.apiToken);return s.bitbucket={email:o.email,apiToken:o.apiToken},un(s,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,wm(o.apiToken)}),{ok:!0,detail:`authenticated as ${i}`}}case"youtrack":{if(!o.token)return{ok:!1,detail:"payload has no token"};let i=o.url?.trim().replace(/\/$/,"")||s.youtrack?.url;if(!i)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await Vt({baseUrl:i,token:o.token});return s.youtrack={url:i,token:o.token},un(s,()=>{process.env.YOUTRACK_URL=i,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 i=await zt(o.token);return i==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(s.claude={oauthToken:o.token},un(s,()=>{}),{ok:!0,...i==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(s.contextWrite={token:o.token},un(s,()=>{}),{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(i){return{ok:!1,detail:`${i instanceof Error?i.message:String(i)} \u2014 previous credential kept`}}}function un(t,e){ie(t),e()}var vm=$(()=>{"use strict";rt();pe();qt();br();rn();Ls()});import{spawn as Zx}from"node:child_process";function eS(t,e,r,n,o,s){let i={...t},a=(c,l)=>{Pt(c)||(i[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))i[c]=l;for(let[c,l]of Object.entries(s))i[`INPUT_${c}`]=String(l);return i}async function Em(t){let{def:e,onEvent:r}=t,n=eS(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",s=a=>{o+=a+`
714
+ `,o.length>xm&&(o=o.slice(o.length-xm))},i=(a,c)=>{let l=c.length>Sm?c.slice(0,Sm)+"\u2026":c;s(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 tS(c.run,c.timeout_sec,t.cwd,n,i);if(u!==0)return s(`[${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 tS(t,e,r,n,o){return new Promise(s=>{let i=Zx("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??ya)*1e3,l=setTimeout(()=>{a=!0,o("stderr",`step timed out after ${c/1e3}s \u2014 killing`),i.kill("SIGTERM"),setTimeout(()=>i.kill("SIGKILL"),5e3).unref()},c);l.unref?.();let u=m=>{let f="";return{data:g=>{f+=g.toString("utf-8");let h;for(;(h=f.indexOf(`
715
+ `))!==-1;)o(m,f.slice(0,h).replace(/\r$/,"")),f=f.slice(h+1)},flush:()=>{f.length>0&&o(m,f.replace(/\r$/,"")),f=""}}},p=u("stdout"),d=u("stderr");i.stdout?.on("data",p.data),i.stderr?.on("data",d.data),i.on("error",m=>{clearTimeout(l),o("stderr",`spawn failed: ${m.message}`),s(127)}),i.on("close",(m,f)=>{clearTimeout(l),p.flush(),d.flush(),s(a?Qx:m??(f?1:0))})})}var Qx,xm,Sm,Rm=$(()=>{"use strict";F();Qx=124,xm=16*1024,Sm=4e3});import{existsSync as rS,readFileSync as nS,statSync as Tm}from"node:fs";function oS(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function Cm(t,e){let r=be(t,e);if(e.split("/").some(s=>s===".git"))throw new Error(`not a context file: ${e}`);if(!rS(r)||!Tm(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=Tm(r);if(n>Im)throw new Error(`file too large: ${e} is ${n} bytes (limit ${Im})`);let o=nS(r);return oS(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}var Im,Am=$(()=>{"use strict";tt();Im=2*1024*1024});import{existsSync as sS,readFileSync as iS,writeFileSync as aS}from"node:fs";import{join as cS}from"node:path";import{parseDocument as lS}from"yaml";async function Pm(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let s=Ra(o);if(!s.ok)throw new Error(s.error);let i=r.get(o.file)??[];i.push({path:s.field.path,value:s.value}),r.set(o.file,i)}let n=[];for(let[o,s]of r){let i=cS(t,o);if(!sS(i))throw new Error(`${o} not found in context repo (${t})`);let a=lS(iS(i,"utf-8"));for(let c of s)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);aS(i,a.toString()),n.push(o)}return{files:n}}var _m=$(()=>{"use strict";F()});import{existsSync as uS,readFileSync as dS,writeFileSync as pS}from"node:fs";import{join as fS}from"node:path";import{isMap as jm,parseDocument as mS}from"yaml";async function Nm(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||!Ua(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=fS(t,"project.yaml");if(!uS(o))throw new Error(`project.yaml not found in context repo (${t})`);let s=mS(dS(o,"utf-8")),i=s.get("repos"),c=(i&&typeof i=="object"&&"items"in i?i.items:[]).find(l=>jm(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!jm(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),pS(o,s.toString()),{repoName:r,defaultBranch:n}}var Om=$(()=>{"use strict";F()});import{existsSync as Lc,readFileSync as Dc,writeFileSync as hS}from"node:fs";import{join as Ds}from"node:path";import{parseDocument as Mc}from"yaml";async function Lm(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 s=Ds(t,"project.yaml");if(!Lc(s))throw new Error(`project.yaml not found in context repo (${t})`);let i=Mc(Dc(s,"utf-8"));if(e.stageField!==void 0){let a=typeof e.stageField=="string"?e.stageField.trim():"";a&&a!=="Stage"?i.setIn(["youtrack","stage_field"],a):i.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?i.setIn(["youtrack","reject_columns"],a):i.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?i.setIn(["youtrack","done_columns"],a):i.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?i.setIn(["youtrack","review_columns"],a):i.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?i.setIn(["youtrack","status_columns"],a):i.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");i.setIn(["youtrack","source_columns"],a)}if(e.backlogColumn!==void 0){let a=typeof e.backlogColumn=="string"?e.backlogColumn.trim():"";a?i.setIn(["youtrack","backlog_column"],a):i.deleteIn(["youtrack","backlog_column"])}if(e.assignee!==void 0){let a=typeof e.assignee=="string"?e.assignee.trim():"";a?i.setIn(["youtrack","assignee"],a):i.deleteIn(["youtrack","assignee"])}e.requireAssignee!==void 0&&i.setIn(["youtrack","require_assignee"],e.requireAssignee===!0),e.backlogScope!==void 0&&(e.backlogScope==="personal"?i.setIn(["youtrack","backlog_scope"],"personal"):e.backlogScope==="shared"?i.setIn(["youtrack","backlog_scope"],"shared"):i.deleteIn(["youtrack","backlog_scope"])),r.push({path:"project.yaml",content:i.toString()})}if(e.reviewStatus!==void 0||e.writes!==void 0){let s=Ds(t,"regimen.yaml");if(!Lc(s))throw new Error(`regimen.yaml not found in context repo (${t})`);let i=Mc(Dc(s,"utf-8"));if(e.reviewStatus!==void 0){let a=e.reviewStatus.trim();a&&i.setIn(["youtrack","review_status"],a)}if(e.writes!==void 0){let a=e.writes;i.setIn(["youtrack","writes","enabled"],a.enabled===!0),i.setIn(["youtrack","writes","status_changes"],a.statusChanges===!0),i.setIn(["youtrack","writes","pr_comment"],a.prComment===!0),i.setIn(["youtrack","writes","dashboard_mirror"],a.dashboardMirror===!0)}r.push({path:"regimen.yaml",content:i.toString()})}if(r.length===0)return{files:[]};for(let s of r)hS(Ds(t,s.path),s.content);return{files:r.map(s=>s.path)}}function Ms(t){if(!t)return"Stage";try{let e=Ds(t,"project.yaml");if(!Lc(e))return"Stage";let n=Mc(Dc(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}var Uc=$(()=>{"use strict"});import{existsSync as Dm,readFileSync as Mm,readdirSync as gS}from"node:fs";import{join as Bc}from"node:path";import{simpleGit as yS}from"simple-git";function kS(t,e){let r=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/.exec(e);if(!r)return null;let n="",o="";for(let i of r[1].split(`
716
+ `)){let a=/^(\w+):\s*(.+)$/.exec(i.trim());a&&(a[1]==="repo"&&(n=a[2].trim()),a[1]==="path"&&(o=a[2].trim().replace(/^\.\//,"")))}let s=r[2].trim();return!n||!o||!s||o.includes("..")||o.startsWith("/")?null:{repo:n,path:o,body:s,source:t}}function wS(t,e){let r=Bc(t,`tasks/${e}/annotations`);if(!Dm(r))return[];let n=[];for(let o of gS(r).sort())if(o.endsWith(".md")){try{let s=kS(o,Mm(Bc(r,o),"utf-8"));s&&n.push(s)}catch{}if(n.length>=ta)break}return n}async function Um(t){let{contextDir:e,taskKey:r,repoName:n,repoDir:o,commitSha:s,date:i,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=yS(o),p=[];for(let d of wS(e,r)){if(d.repo!==n)continue;let m=me("code",n,d.path);if(!a.has(m))continue;let f=l.get(m);if(!f)continue;let g=(await u.raw(["rev-parse",`${s}:${d.path}`]).catch(()=>"")).trim().slice(0,bS),h=zi(f),w=Bc(e,h),y=p.find(I=>I.path===h),x=y?.content??(Dm(w)?Mm(w,"utf-8"):null),S=`<!-- ${r}${g?`:${g}`:""} -->`;if(x?.includes(S))continue;let T=x??`---
717
+ entityId: ${f}
642
718
  ---
643
719
 
644
720
  # Intent log
645
721
 
646
722
  Append-only. Keyed by entityId \u2014 never by path; entries survive renames.
647
- `,E=["",`## ${s} \u2014 ${r}`,T,"",d.body,""].join(`
648
- `),b=I+E;y?y.content=b:p.push({path:g,content:b})}return p}var vv,Df=v(()=>{"use strict";G();vv=12});import{existsSync as Fa,readFileSync as Ga}from"node:fs";import{join as Ka}from"node:path";import{simpleGit as Uf}from"simple-git";import{parse as Ha}from"yaml";function Ff(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(xv.source,"g")}function Gf(t){let e=Ka(t,"project.yaml");if(Fa(e))try{let o=Ha(Ga(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=Ka(t,"tracker","config.yaml");if(Fa(r))try{let o=Ha(Ga(r,"utf-8"))?.prefix;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return null}function Kf(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 Sv(t,e,r){let o=await Uf(t).raw(["log","--numstat","--format=@@@ %H %ct %P %x09%s","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
649
- `))if(a.startsWith("@@@ ")){let c=a.indexOf(" "),l=(c>=0?a.slice(4,c):a.slice(4)).trim().split(/\s+/),u=c>=0?a.slice(c+1):"",p=l[0]??"",d=Number(l[1]??0),f=l.slice(2),m=Wa.exec(u)??Bf.exec(u);s={sha:p,timeSec:d,subject:u,files:[],prNumber:m?Number(m[1]):null,isMerge:f.length>1},i.push(s)}else if(a.trim()&&s){let c=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(a);if(!c)continue;let l=c[1]==="-"?0:Number(c[1]),u=c[2]==="-"?0:Number(c[2]);s.files.push({path:Kf(c[3]),churn:l+u})}return i}async function Tv(t,e){let n=await Uf(t).raw(["diff","--numstat",`${e}^1`,e]).catch(()=>""),o=[];for(let i of n.split(`
650
- `)){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:Kf(s[3]),churn:a+c})}return o}function Ev(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(Wa,"").trim();else if(c.prNumber!==null){if((t.trackerProjectKey??"").toUpperCase()==="PR")continue;u=`PR-${c.prNumber}`,p=c.subject.replace(Wa,"").replace(Bf,"").replace(/^from\s+/,"").trim()||c.subject}else continue;if(!/^[A-Za-z0-9._-]+$/.test(u))continue;let f=new Map;for(let g of c.files){let w=o.get(g.path)??g.path;s(w)||f.set(w,(f.get(w)??0)+g.churn)}if(f.size===0)continue;let h=a.get(u)??{modelFormatVersion:2,taskKey:u,origin:"bootstrap",title:"",commits:[],files:[]};p&&(h.title=p),c.timeSec>0&&(h.date=new Date(c.timeSec*1e3).toISOString().slice(0,10)),h.commits.push(c.sha);for(let[g,w]of f){let y=pe("code",e,g),x=h.files.find(T=>T.key===y);if(x)x.churn=(x.churn??0)+w;else{let T=i.get(y);h.files.push({key:y,...T?{entityId:T}:{},churn:w})}}if(d.length>0){let g=new Set([...h.links?.tasks??[],...d]);g.delete(u),h.links={...h.links??{},tasks:[...g].sort()}}a.set(u,h)}return a}function Mf(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 Hf(t){let e=await Sv(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 Tv(t.repoDir,r.sha))}return Ev({repo:t.repo,issueKeyRe:t.issueKeyRe,commits:e,pathToCurrent:t.pathToCurrent,entityByKey:t.entityByKey,ignored:t.ignored,trackerProjectKey:t.trackerProjectKey??null})}function Wf(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?Mf(c,a)??c:a)}let n=[],o=0;for(let[i,s]of[...r.entries()].sort(([a],[c])=>a<c?-1:1)){let a=Mf(Si(t,i),s);if(!a){o++;continue}n.push({path:Pr(i),content:Dn(a)})}return{files:n,skippedPipeline:o}}function Si(t,e){let r=Ka(t,Pr(e));if(!Fa(r))return null;try{let n=Pt(Ha(Ga(r,"utf-8")));return n.ok?n.value:null}catch{return null}}var xv,Wa,Bf,qa=v(()=>{"use strict";G();xv=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g,Wa=/\(#(\d+)\)\s*$/,Bf=/^Merge pull request #(\d+)\b/});import{simpleGit as Iv}from"simple-git";async function Yf(t,e,r){let o=await Iv(t).raw(["log","--no-merges","--name-only","--format=@@@ %H %ct","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
651
- `))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 Ti(t){let e=new Map;for(let r of t.entities){if(r.status!=="active"||!r.aliases)continue;let n=Q(r.currentKey);if(n?.level==="code")for(let o of r.aliases){let i=Q(o.key);i?.level==="code"&&e.set(i.path,n.path)}}return e}function Vf(t){let{repo:e,headTimeSec:r,filesets:n,pathToCurrent:o,currentPaths:i,ignored:s,settings:a}=t,c=a.halfLifeDays*86400,l=new Map,u=new Map,p=new Map;for(let w of n){let y=new Set;for(let E of w.files){let b=o.get(E)??E;!i.has(b)||s(b)||y.add(b)}if(y.size<2||y.size>a.commitFileCap)continue;let x=Math.max(0,r-w.timeSec),T=Math.pow(.5,x/c),I=[...y].sort();for(let E of I)l.set(E,(l.get(E)??0)+T);for(let E=0;E<I.length;E++)for(let b=E+1;b<I.length;b++){let R=`${I[E]}\0${I[b]}`;u.set(R,(u.get(R)??0)+T),p.set(R,(p.get(R)??0)+1)}}let d=[],f=a.jaccardMinPct/100;for(let[w,y]of u){if((p.get(w)??0)<a.supportMin)continue;let[x,T]=w.split("\0"),I=(l.get(x)??0)+(l.get(T)??0)-y,E=I>0?y/I:0;E<f||d.push({a:x,b:T,weight:Math.round(E*qf)/qf})}let m=new Map;for(let w of d)for(let y of[w.a,w.b])m.has(y)||m.set(y,[]),m.get(y).push(w);let h=new Map;for(let[,w]of m)w.sort((y,x)=>x.weight-y.weight||(y.a<x.a?-1:y.a>x.a?1:y.b<x.b?-1:1)).slice(0,a.topK).forEach(y=>h.set(y,(h.get(y)??0)+1));return[...h.entries()].filter(([,w])=>w===2).map(([w])=>w).map(w=>({kind:"correlates",from:pe("code",e,w.a),to:pe("code",e,w.b),weight:w.weight})).sort((w,y)=>w.from<y.from?-1:w.from>y.from?1:w.to<y.to?-1:1)}var Jr,qf,Ei=v(()=>{"use strict";G();Jr=["package-lock.json","pnpm-lock.yaml","yarn.lock"];qf=1e4});import{createHash as Rv}from"node:crypto";function Av(t,e,r,n){for(let o=0;;o++){let s=`e_${Rv("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(s))return s}}function zf(t){let{repo:e,headCommit:r,headDate:n,prev:o,renameChains:i,prevBlobByPath:s,headBlobByPath:a}=t,c=[...t.currentKeys].sort(),l=new Set(c),u=o?.entities??[],p=new Set(u.map(b=>b.entityId)),d=new Set,f=[],m=new Map,h=(b,R)=>{d.add(R),m.set(R,b.entityId),f.push(b)},g=[];for(let b of u)l.has(b.currentKey)&&!d.has(b.currentKey)?h({...b,status:"active",lastSeen:r},b.currentKey):g.push(b);let w=[],y=[];for(let b of g){let R=Q(b.currentKey),N=R?i.get(R.path):void 0;if(R&&N){let F=pe(R.level,e,N.finalPath);if(l.has(F)&&!d.has(F)){w.push({entity:b,newKey:F,untilCommit:N.commit}),d.add(F);continue}}y.push(b)}let x=[];if(s){let b=new Map;for(let N of c){if(d.has(N))continue;let F=Q(N);if(F?.level!=="code")continue;let C=a.get(F.path);C&&b.set(C,b.has(C)?null:N)}let R=new Map;for(let N of y){let F=Q(N.currentKey);if(F?.level!=="code")continue;let C=s.get(F.path);C&&R.set(C,R.has(C)?null:N)}for(let N of y){let F=Q(N.currentKey),C=F?.level==="code"?s.get(F.path):void 0,k=C?b.get(C):void 0;C&&k&&R.get(C)===N&&!d.has(k)?(w.push({entity:N,newKey:k,untilCommit:r}),d.add(k)):x.push(N)}}else x.push(...y);let T=new Map;for(let b of w){let R=Q(b.entity.currentKey),N=Q(b.newKey);if(R?.level!=="code"||!N)continue;let F=R.path,C=N.path;for(let k=F.lastIndexOf("/");k>0;k=F.lastIndexOf("/",k-1)){let L=F.slice(0,k),A=F.slice(k+1);if(!C.endsWith(`/${A}`))continue;let H=C.slice(0,C.length-A.length-1);if(H===L)continue;let q=`${L}\0${H}`,Z=T.get(q);T.set(q,{count:(Z?.count??0)+1,commit:Z&&Z.commit>b.untilCommit?Z.commit:b.untilCommit})}}let I=[...T.entries()].filter(([,b])=>b.count>=Cv).map(([b,R])=>{let[N,F]=b.split("\0");return{from:N,to:F,commit:R.commit}}).sort((b,R)=>R.from.length-b.from.length||(b.from<R.from?-1:1)),E=[];for(let b of x){let R=Q(b.currentKey),N=!1;if(R?.level==="component")for(let F of I){let C=null;if(R.path===F.from?C=F.to:R.path.startsWith(`${F.from}/`)&&(C=F.to+R.path.slice(F.from.length)),C===null)continue;let k=pe("component",e,C);l.has(k)&&!d.has(k)&&(w.push({entity:b,newKey:k,untilCommit:F.commit}),d.add(k),N=!0);break}N||E.push(b)}for(let b of w.sort((R,N)=>R.newKey<N.newKey?-1:1))h({...b.entity,currentKey:b.newKey,aliases:[...b.entity.aliases??[],{key:b.entity.currentKey,until:b.untilCommit}],status:"active",lastSeen:r},b.newKey);for(let b of E)f.push({...b,status:"orphaned"});for(let b of c){if(d.has(b))continue;let R=Av(e,b,r,p);p.add(R),h({entityId:R,currentKey:b,firstSeen:n,lastSeen:r,status:"active"},b)}return{table:{modelFormatVersion:2,repo:e,builtFromCommit:r,entities:f},byKey:m}}var Cv,Xf=v(()=>{"use strict";G();Cv=5});import{simpleGit as Pv}from"simple-git";async function Jf(t,e,r){let n=Pv(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
652
- `).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 Qf(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 Zf=v(()=>{"use strict"});function Ii(t){return pe("container",t,_v)}function em(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function tm(t,e,r,n){let o=[],i=u=>{let p=pe("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:em(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,jv)}},s=(u,p)=>{let d=pe("component",t,u),f=n.get(d);return{key:d,level:"component",label:em(u),...f?{entityId:f}:{},...p?{aggregate:!0}:{}}},a=(u,p,d)=>{let f=r.filesByDir.get(d)??[],m=r.childDirs.get(d)??[],h=[p,...f.map(i)],g=[...f.map(w=>({kind:"contains",from:p.key,to:pe("code",t,w.path)})),...m.map(w=>({kind:"contains",from:p.key,to:pe("component",t,w)}))];c(u,h,g)},c=(u,p,d)=>{let f={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},m=At(f);if(!m.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${m.errors.join("; ")}`);o.push({path:Pl(t,u),content:Bl(f)})},l={key:Ii(t),level:"container",label:t,...n.get(Ii(t))?{entityId:n.get(Ii(t))}:{}};a("",l,"");for(let u of r.components)r.collapsed.has(u)?c(u,[s(u,!0)],[]):a(u,s(u,!1),u);return o.sort((u,p)=>u.path<p.path?-1:u.path>p.path?1:0),{files:o,counts:r.counts}}function rm(t,e){let r=[Ii(t)];for(let n of e.components)r.push(pe("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(pe("code",t,o.path));return r.sort()}var _v,jv,nm=v(()=>{"use strict";G();_v=".";jv=12});import{simpleGit as im}from"simple-git";function br(t){let e=new Set,r=[],n=new Set;for(let o of t){let i=o.trim();if(i)if(i.endsWith("/"))e.add(i.slice(0,-1));else if(i.includes("*")){let s=i.replace(/[.*+?^${}()|[\]\\]/g,a=>a==="*"?"\0":`\\${a}`).replace(/\0/g,".*");r.push(new RegExp(`^${s}$`))}else n.add(i)}return o=>{let i=o.split("/"),s=i[i.length-1]??o;if(n.has(o))return!0;for(let a of i)if(e.has(a)||n.has(a))return!0;return r.some(a=>a.test(s))}}async function am(t,e="HEAD"){let r=im(t),n=(await r.revparse([e])).trim(),[o,i]=(await r.raw(["show","-s","--format=%cs %ct",n])).trim().split(/\s+/);return{commit:n,commitDate:o??"",commitTimeSec:Number(i??0),files:await oo(t,n)}}async function oo(t,e){let n=await im(t).raw(["ls-tree","-r","-z",e]),o=[];for(let i of n.split("\0")){if(!i)continue;let s=i.indexOf(" ");if(s<0)continue;let[,a,c]=i.slice(0,s).split(/\s+/);a!=="blob"||!c||o.push({path:i.slice(s+1),blobHash:c})}return o.sort((i,s)=>i.path<s.path?-1:i.path>s.path?1:0),o}function om(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function cm(t,e){let r=[...t].sort((m,h)=>m.path<h.path?-1:m.path>h.path?1:0),n=new Map,o=new Map;for(let m of r){let h=om(m.path);n.has(h)||n.set(h,[]),n.get(h).push(m);let g=h;for(;g!=="";){let w=om(g);o.has(w)||o.set(w,new Set),o.get(w).add(g),g=w}}let i=m=>[...o.get(m)??[]].sort(),s=Math.max(e,1)-1,a=new Set,c=new Set,l=[""];for(;l.length>0;){let m=l.shift(),h=(n.get(m)??[]).length+i(m).length;if(h<=s)s-=h,c.add(m),l.push(...i(m));else{if(m==="")return{components:[],collapsed:new Set,filesByDir:new Map,childDirs:new Map,counts:{component:0,code:0}};a.add(m)}}let u=[],p=new Map,d=new Map,f=0;for(let m of[...c].sort()){let h=n.get(m)??[];p.set(m,h),d.set(m,i(m)),f+=h.length,m!==""&&u.push(m)}for(let m of a)u.push(m);return u.sort(),{components:u,collapsed:a,filesByDir:p,childDirs:d,counts:{component:u.length,code:f}}}var sm,io=v(()=>{"use strict";sm=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as lm,readFileSync as um}from"node:fs";import{join as dm}from"node:path";import{simpleGit as Nv}from"simple-git";import{parse as pm}from"yaml";function Qr(t){let e={ignore:sm,containerNodeCap:Ov,cochange:{...Je},issueKeyPattern:null,enabled:!1},r=dm(t,"regimen.yaml");if(!lm(r))return e;let n;try{n=pm(um(r,"utf-8"))}catch{return e}let o=n?.context,i=o&&typeof o=="object"?o.model:void 0;if(!i||typeof i!="object")return e;let s=i,a=Array.isArray(s.ignore)?s.ignore.filter(f=>typeof f=="string"&&f.trim().length>0):e.ignore,c=(f,m)=>typeof f=="number"&&Number.isInteger(f)&&f>0?f:m,l=c(s.container_node_cap,e.containerNodeCap),u=s.cochange&&typeof s.cochange=="object"?s.cochange:{},p={windowCommits:c(u.window_commits,e.cochange.windowCommits),commitFileCap:c(u.commit_file_cap,e.cochange.commitFileCap),supportMin:c(u.support_min,e.cochange.supportMin),jaccardMinPct:typeof u.jaccard_min_pct=="number"&&Number.isInteger(u.jaccard_min_pct)&&u.jaccard_min_pct>=0&&u.jaccard_min_pct<=100?u.jaccard_min_pct:e.cochange.jaccardMinPct,halfLifeDays:c(u.half_life_days,e.cochange.halfLifeDays),topK:c(u.top_k,e.cochange.topK)},d=typeof s.issue_key_pattern=="string"&&s.issue_key_pattern.trim().length>0?s.issue_key_pattern.trim():null;return{ignore:a,containerNodeCap:l,cochange:p,issueKeyPattern:d,enabled:s.enabled===!0}}function Ya(t,e){let r=dm(t,_o(e));if(!lm(r))return null;let n=pm(um(r,"utf-8")),o=Oo(n);if(!o.ok)throw new Error(`model: ${_o(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function Va(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await am(r,t.ref??"HEAD"),s=br(o.ignore),a=i.files.filter(y=>!s(y.path)),c=cm(a,o.containerNodeCap),l=Ya(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await Nv(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=Qf(await Jf(r,l.builtFromCommit,i.commit)),p=new Map((await oo(r,l.builtFromCommit)).map(T=>[T.path,T.blobHash]))):l?.builtFromCommit===i.commit&&(p=new Map(a.map(y=>[y.path,y.blobHash])));let d=new Map(a.map(y=>[y.path,y.blobHash])),f=zf({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:rm(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),m=tm(e,i.commit,c,f.byKey),h=br([...o.ignore,...Jr]),g=Vf({repo:e,headTimeSec:i.commitTimeSec,filesets:await Yf(r,i.commit,o.cochange.windowCommits),pathToCurrent:Ti(f.table),currentPaths:new Set(a.map(y=>y.path)),ignored:h,settings:o.cochange}),w=[{path:_o(e),content:Fl(f.table)},...m.files.map(y=>({path:y.path,content:y.content})),{path:Cl(e),content:_r({modelFormatVersion:2,repo:e,builtFromCommit:i.commit,edges:g})}];return{repo:e,headCommit:i.commit,files:w,emittedShardPaths:new Set(m.files.map(y=>y.path)),counts:{...m.counts,correlates:g.length},identityTable:f.table,entityByKey:f.byKey}}var Ov,za=v(()=>{"use strict";G();Ei();Xf();Zf();nm();io();Ov=1500});import{existsSync as mm,readFileSync as gm,readdirSync as Lv}from"node:fs";import{join as Xa}from"node:path";import{parse as hm}from"yaml";function Dv(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 ym(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<jl)return null;let s=i/Math.min(n.size,o.size),a=Dv(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(s*c*fm)/fm;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[ve(t.taskKey),ve(e.taskKey)]:[ve(e.taskKey),ve(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function km(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=ym(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 wm(t,e,r,n){let o=ve(r),i=t.filter(a=>a.from!==o&&a.to!==o),s=e.find(a=>a.taskKey===r);if(s){let a=new Set(s.files.map(c=>c.key));for(let c of e){if(c.taskKey===r||!c.files.some(u=>a.has(u.key)))continue;let l=ym(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 Ri(t){let e=Xa(t,"model/facts/events");if(!mm(e))return[];let r=[];for(let n of Lv(e).sort())if(n.endsWith(".yaml"))try{let o=Pt(hm(gm(Xa(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function bm(t){let e=Xa(t,Ar);if(!mm(e))return[];try{let r=jo(hm(gm(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function Ci(t){return _r({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var fm,Ja=v(()=>{"use strict";G();fm=1e4});var so={};Rr(so,{collectSearchRows:()=>vm,readContextIndexHub:()=>Mv,rebuildSearchIndex:()=>xm,searchIndexPath:()=>ji,searchModelIndex:()=>Uv,toFtsQuery:()=>Sm});import{existsSync as en,readFileSync as Zr,readdirSync as Pi}from"node:fs";import{join as nt}from"node:path";import{parse as _i}from"yaml";function ji(t){return nt(t,".git","codepipe-model-index.sqlite")}function Mv(t){let e=nt(t,"regimen.yaml");if(!en(e))return"off";try{let n=_i(Zr(e,"utf-8"))?.context,o=n&&typeof n=="object"?n.index:null;return(o&&typeof o=="object"?o.hub:null)==="metadata"?"metadata":"off"}catch{return"off"}}async function $m(){try{let{createRequire:t}=await import("node:module");return t(import.meta.url)("node:sqlite")}catch{return null}}function Ai(t){return t.length>_s?t.slice(0,_s):t}function Qa(t){if(!en(t))return[];let e=[];for(let r of Pi(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=nt(t,r.name);r.isDirectory()?e.push(...Qa(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function vm(t){let e=[];for(let i of Qa(nt(t,"model/derived/structure"))){let s;try{s=_i(Zr(i,"utf-8"))}catch{continue}let a=At(s);if(a.ok)for(let c of a.value.nodes){let l=Q(c.key);l&&e.push({nodeId:c.key,kind:l.level,text:Ai(`${l.path} ${c.label??""}`.trim())})}}let r=nt(t,"model/facts/events");if(en(r)){for(let i of Pi(r).sort())if(i.endsWith(".yaml"))try{let s=Pt(_i(Zr(nt(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:Ai(`${a.taskKey} ${a.title??""} ${c}`.trim())})}catch{}}let n=nt(t,"model/facts/annotations");if(en(n)){let i=new Map;for(let s of Qa(nt(t,"model/facts/identity")))try{let a=_i(Zr(s,"utf-8"));for(let c of a?.entities??[])c.status==="active"&&c.entityId&&c.currentKey&&i.set(c.entityId,c.currentKey)}catch{}for(let s of Pi(n).sort())if(s.endsWith(".md"))try{let a=Zr(nt(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:Ai(c[2].trim())})}catch{}}let o=nt(t,"adr");if(en(o))for(let i of Pi(o).sort()){let s=/^(\d{4})-/.exec(i)?.[1];if(!(!s||!i.endsWith(".md")))try{let a=Zr(nt(o,i),"utf-8").split(`
653
- `).slice(0,6);e.push({nodeId:`adr::ADR-${s}`,kind:"adr",text:Ai(a.filter(c=>c.trim()).join(" "))})}catch{}}return e}async function xm(t){let e=vm(t),r=await $m();if(!r)return{rows:e,indexed:!1};let n=new r.DatabaseSync(ji(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 Sm(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 Uv(t,e,r){let n=await $m();if(!n)throw new Error("model search needs Node with built-in sqlite (>= 22.13) on this CLI");en(ji(t))||await xm(t);let o=Sm(e);if(!o)return[];let i=Math.min(Math.max(r??20,1),Ol),s=new n.DatabaseSync(ji(t));try{return s.prepare(`SELECT node_id AS nodeId, kind, snippet(model_fts, 2, '[', ']', '\u2026', 10) AS snippet,
723
+ `,R=["",`## ${i} \u2014 ${r}`,S,"",d.body,""].join(`
724
+ `),b=T+R;y?y.content=b:p.push({path:h,content:b})}return p}var bS,Bm=$(()=>{"use strict";F();bS=12});import{existsSync as Fc,readFileSync as Kc}from"node:fs";import{join as Gc}from"node:path";import{simpleGit as Km}from"simple-git";import{parse as Hc}from"yaml";function Hm(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 Wm(t){let e=Gc(t,"project.yaml");if(Fc(e))try{let o=Hc(Kc(e,"utf-8"))?.youtrack,s=o&&typeof o=="object"?o.project_key:null;if(typeof s=="string"&&s.trim())return s.trim()}catch{}let r=Gc(t,"tracker","config.yaml");if(Fc(r))try{let o=Hc(Kc(r,"utf-8"))?.prefix;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return null}function qm(t){if(t.includes("=>")){let r=t.replace(/\{([^{}]*) => ([^{}]*)\}/g,(o,s,i)=>i).replace(/\/\//g,"/");if(!r.includes("=>"))return r;let n=r.split("=>");return(n[n.length-1]??r).trim()}return t}async function vS(t,e,r){let o=await Km(t).raw(["log","--numstat","--format=@@@ %H %ct %P %x09%s","-n",String(r),e]),s=[],i=null;for(let a of o.split(`
725
+ `))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=Wc.exec(u)??Gm.exec(u);i={sha:p,timeSec:d,subject:u,files:[],prNumber:f?Number(f[1]):null,isMerge:m.length>1},s.push(i)}else if(a.trim()&&i){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]);i.files.push({path:qm(c[3]),churn:l+u})}return s}async function xS(t,e){let n=await Km(t).raw(["diff","--numstat",`${e}^1`,e]).catch(()=>""),o=[];for(let s of n.split(`
726
+ `)){let i=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(s);if(!i)continue;let a=i[1]==="-"?0:Number(i[1]),c=i[2]==="-"?0:Number(i[2]);o.push({path:qm(i[3]),churn:a+c})}return o}function SS(t){let{repo:e,issueKeyRe:r,commits:n,pathToCurrent:o,entityByKey:s,ignored:i}=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(Wc,"").trim();else if(c.prNumber!==null){if((t.trackerProjectKey??"").toUpperCase()==="PR")continue;u=`PR-${c.prNumber}`,p=c.subject.replace(Wc,"").replace(Gm,"").replace(/^from\s+/,"").trim()||c.subject}else continue;if(!/^[A-Za-z0-9._-]+$/.test(u))continue;let m=new Map;for(let h of c.files){let w=o.get(h.path)??h.path;i(w)||m.set(w,(m.get(w)??0)+h.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[h,w]of m){let y=me("code",e,h),x=g.files.find(S=>S.key===y);if(x)x.churn=(x.churn??0)+w;else{let S=s.get(y);g.files.push({key:y,...S?{entityId:S}:{},churn:w})}}if(d.length>0){let h=new Set([...g.links?.tasks??[],...d]);h.delete(u),g.links={...g.links??{},tasks:[...h].sort()}}a.set(u,g)}return a}function Fm(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(s=>[s.key,s]));for(let s of e.files)n.has(s.key)||n.set(s.key,s);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 Ym(t){let e=await vS(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 xS(t.repoDir,r.sha))}return SS({repo:t.repo,issueKeyRe:t.issueKeyRe,commits:e,pathToCurrent:t.pathToCurrent,entityByKey:t.entityByKey,ignored:t.ignored,trackerProjectKey:t.trackerProjectKey??null})}function Vm(t,e){let r=new Map;for(let s of e)for(let[i,a]of s){let c=r.get(i);r.set(i,c?Fm(c,a)??c:a)}let n=[],o=0;for(let[s,i]of[...r.entries()].sort(([a],[c])=>a<c?-1:1)){let a=Fm(Us(t,s),i);if(!a){o++;continue}n.push({path:dr(s),content:Wr(a)})}return{files:n,skippedPipeline:o}}function Us(t,e){let r=Gc(t,dr(e));if(!Fc(r))return null;try{let n=At(Hc(Kc(r,"utf-8")));return n.ok?n.value:null}catch{return null}}var $S,Wc,Gm,qc=$(()=>{"use strict";F();$S=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g,Wc=/\(#(\d+)\)\s*$/,Gm=/^Merge pull request #(\d+)\b/});import{simpleGit as ES}from"simple-git";async function Xm(t,e,r){let o=await ES(t).raw(["log","--no-merges","--name-only","--format=@@@ %H %ct","-n",String(r),e]),s=[],i=null;for(let a of o.split(`
727
+ `))if(a.startsWith("@@@ ")){let[c,l]=a.slice(4).trim().split(/\s+/);i={sha:c??"",timeSec:Number(l??0),files:[]},s.push(i)}else a.trim()&&i&&i.files.push(a.trim());return s}function Bs(t){let e=new Map;for(let r of t.entities){if(r.status!=="active"||!r.aliases)continue;let n=re(r.currentKey);if(n?.level==="code")for(let o of r.aliases){let s=re(o.key);s?.level==="code"&&e.set(s.path,n.path)}}return e}function Jm(t){let{repo:e,headTimeSec:r,filesets:n,pathToCurrent:o,currentPaths:s,ignored:i,settings:a}=t,c=a.halfLifeDays*86400,l=new Map,u=new Map,p=new Map;for(let w of n){let y=new Set;for(let R of w.files){let b=o.get(R)??R;!s.has(b)||i(b)||y.add(b)}if(y.size<2||y.size>a.commitFileCap)continue;let x=Math.max(0,r-w.timeSec),S=Math.pow(.5,x/c),T=[...y].sort();for(let R of T)l.set(R,(l.get(R)??0)+S);for(let R=0;R<T.length;R++)for(let b=R+1;b<T.length;b++){let I=`${T[R]}\0${T[b]}`;u.set(I,(u.get(I)??0)+S),p.set(I,(p.get(I)??0)+1)}}let d=[],m=a.jaccardMinPct/100;for(let[w,y]of u){if((p.get(w)??0)<a.supportMin)continue;let[x,S]=w.split("\0"),T=(l.get(x)??0)+(l.get(S)??0)-y,R=T>0?y/T:0;R<m||d.push({a:x,b:S,weight:Math.round(R*zm)/zm})}let f=new Map;for(let w of d)for(let y of[w.a,w.b])f.has(y)||f.set(y,[]),f.get(y).push(w);let g=new Map;for(let[,w]of f)w.sort((y,x)=>x.weight-y.weight||(y.a<x.a?-1:y.a>x.a?1:y.b<x.b?-1:1)).slice(0,a.topK).forEach(y=>g.set(y,(g.get(y)??0)+1));return[...g.entries()].filter(([,w])=>w===2).map(([w])=>w).map(w=>({kind:"correlates",from:me("code",e,w.a),to:me("code",e,w.b),weight:w.weight})).sort((w,y)=>w.from<y.from?-1:w.from>y.from?1:w.to<y.to?-1:1)}var dn,zm,Fs=$(()=>{"use strict";F();dn=["package-lock.json","pnpm-lock.yaml","yarn.lock"];zm=1e4});import{createHash as RS}from"node:crypto";function IS(t,e,r,n){for(let o=0;;o++){let i=`e_${RS("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(i))return i}}function Zm(t){let{repo:e,headCommit:r,headDate:n,prev:o,renameChains:s,prevBlobByPath:i,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)},h=[];for(let b of u)l.has(b.currentKey)&&!d.has(b.currentKey)?g({...b,status:"active",lastSeen:r},b.currentKey):h.push(b);let w=[],y=[];for(let b of h){let I=re(b.currentKey),D=I?s.get(I.path):void 0;if(I&&D){let K=me(I.level,e,D.finalPath);if(l.has(K)&&!d.has(K)){w.push({entity:b,newKey:K,untilCommit:D.commit}),d.add(K);continue}}y.push(b)}let x=[];if(i){let b=new Map;for(let D of c){if(d.has(D))continue;let K=re(D);if(K?.level!=="code")continue;let ee=a.get(K.path);ee&&b.set(ee,b.has(ee)?null:D)}let I=new Map;for(let D of y){let K=re(D.currentKey);if(K?.level!=="code")continue;let ee=i.get(K.path);ee&&I.set(ee,I.has(ee)?null:D)}for(let D of y){let K=re(D.currentKey),ee=K?.level==="code"?i.get(K.path):void 0,C=ee?b.get(ee):void 0;ee&&C&&I.get(ee)===D&&!d.has(C)?(w.push({entity:D,newKey:C,untilCommit:r}),d.add(C)):x.push(D)}}else x.push(...y);let S=new Map;for(let b of w){let I=re(b.entity.currentKey),D=re(b.newKey);if(I?.level!=="code"||!D)continue;let K=I.path,ee=D.path;for(let C=K.lastIndexOf("/");C>0;C=K.lastIndexOf("/",C-1)){let k=K.slice(0,C),U=K.slice(C+1);if(!ee.endsWith(`/${U}`))continue;let P=ee.slice(0,ee.length-U.length-1);if(P===k)continue;let G=`${k}\0${P}`,Y=S.get(G);S.set(G,{count:(Y?.count??0)+1,commit:Y&&Y.commit>b.untilCommit?Y.commit:b.untilCommit})}}let T=[...S.entries()].filter(([,b])=>b.count>=TS).map(([b,I])=>{let[D,K]=b.split("\0");return{from:D,to:K,commit:I.commit}}).sort((b,I)=>I.from.length-b.from.length||(b.from<I.from?-1:1)),R=[];for(let b of x){let I=re(b.currentKey),D=!1;if(I?.level==="component")for(let K of T){let ee=null;if(I.path===K.from?ee=K.to:I.path.startsWith(`${K.from}/`)&&(ee=K.to+I.path.slice(K.from.length)),ee===null)continue;let C=me("component",e,ee);l.has(C)&&!d.has(C)&&(w.push({entity:b,newKey:C,untilCommit:K.commit}),d.add(C),D=!0);break}D||R.push(b)}for(let b of w.sort((I,D)=>I.newKey<D.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 R)m.push({...b,status:"orphaned"});for(let b of c){if(d.has(b))continue;let I=IS(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 TS,Qm=$(()=>{"use strict";F();TS=5});import{simpleGit as CS}from"simple-git";async function eh(t,e,r){let n=CS(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
728
+ `).map(i=>i.trim()).filter(Boolean),s=[];for(let i of o){let c=(await n.raw(["diff","-M","-C","-z","--name-status","--diff-filter=R",`${i}^`,i]).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&&s.push({fromPath:p,toPath:d,commit:i}),l+=3}}return s}function th(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 rh=$(()=>{"use strict"});function Ks(t){return me("container",t,AS)}function nh(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function oh(t,e,r,n){let o=[],s=u=>{let p=me("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:nh(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,PS)}},i=(u,p)=>{let d=me("component",t,u),m=n.get(d);return{key:d,level:"component",label:nh(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(s)],h=[...m.map(w=>({kind:"contains",from:p.key,to:me("code",t,w.path)})),...f.map(w=>({kind:"contains",from:p.key,to:me("component",t,w)}))];c(u,g,h)},c=(u,p,d)=>{let m={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},f=Ct(m);if(!f.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${f.errors.join("; ")}`);o.push({path:Zi(t,u),content:oa(m)})},l={key:Ks(t),level:"container",label:t,...n.get(Ks(t))?{entityId:n.get(Ks(t))}:{}};a("",l,"");for(let u of r.components)r.collapsed.has(u)?c(u,[i(u,!0)],[]):a(u,i(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 sh(t,e){let r=[Ks(t)];for(let n of e.components)r.push(me("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(me("code",t,o.path));return r.sort()}var AS,PS,ih=$(()=>{"use strict";F();AS=".";PS=12});import{simpleGit as ch}from"simple-git";function Pr(t){let e=new Set,r=[],n=new Set;for(let o of t){let s=o.trim();if(s)if(s.endsWith("/"))e.add(s.slice(0,-1));else if(s.includes("*")){let i=s.replace(/[.*+?^${}()|[\]\\]/g,a=>a==="*"?"\0":`\\${a}`).replace(/\0/g,".*");r.push(new RegExp(`^${i}$`))}else n.add(s)}return o=>{let s=o.split("/"),i=s[s.length-1]??o;if(n.has(o))return!0;for(let a of s)if(e.has(a)||n.has(a))return!0;return r.some(a=>a.test(i))}}async function uh(t,e="HEAD"){let r=ch(t),n=(await r.revparse([e])).trim(),[o,s]=(await r.raw(["show","-s","--format=%cs %ct",n])).trim().split(/\s+/);return{commit:n,commitDate:o??"",commitTimeSec:Number(s??0),files:await So(t,n)}}async function So(t,e){let n=await ch(t).raw(["ls-tree","-r","-z",e]),o=[];for(let s of n.split("\0")){if(!s)continue;let i=s.indexOf(" ");if(i<0)continue;let[,a,c]=s.slice(0,i).split(/\s+/);a!=="blob"||!c||o.push({path:s.slice(i+1),blobHash:c})}return o.sort((s,i)=>s.path<i.path?-1:s.path>i.path?1:0),o}function ah(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function dh(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=ah(f.path);n.has(g)||n.set(g,[]),n.get(g).push(f);let h=g;for(;h!=="";){let w=ah(h);o.has(w)||o.set(w,new Set),o.get(w).add(h),h=w}}let s=f=>[...o.get(f)??[]].sort(),i=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+s(f).length;if(g<=i)i-=g,c.add(f),l.push(...s(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,s(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 lh,Eo=$(()=>{"use strict";lh=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as ph,readFileSync as fh}from"node:fs";import{join as mh}from"node:path";import{simpleGit as _S}from"simple-git";import{parse as hh}from"yaml";function pn(t){let e={ignore:lh,containerNodeCap:jS,cochange:{...Je},issueKeyPattern:null,enabled:!1},r=mh(t,"regimen.yaml");if(!ph(r))return e;let n;try{n=hh(fh(r,"utf-8"))}catch{return e}let o=n?.context,s=o&&typeof o=="object"?o.model:void 0;if(!s||typeof s!="object")return e;let i=s,a=Array.isArray(i.ignore)?i.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(i.container_node_cap,e.containerNodeCap),u=i.cochange&&typeof i.cochange=="object"?i.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 i.issue_key_pattern=="string"&&i.issue_key_pattern.trim().length>0?i.issue_key_pattern.trim():null;return{ignore:a,containerNodeCap:l,cochange:p,issueKeyPattern:d,enabled:i.enabled===!0}}function Yc(t,e){let r=mh(t,Jn(e));if(!ph(r))return null;let n=hh(fh(r,"utf-8")),o=Qn(n);if(!o.ok)throw new Error(`model: ${Jn(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function Vc(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,s=await uh(r,t.ref??"HEAD"),i=Pr(o.ignore),a=s.files.filter(y=>!i(y.path)),c=dh(a,o.containerNodeCap),l=Yc(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==s.commit?await _S(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=th(await eh(r,l.builtFromCommit,s.commit)),p=new Map((await So(r,l.builtFromCommit)).map(S=>[S.path,S.blobHash]))):l?.builtFromCommit===s.commit&&(p=new Map(a.map(y=>[y.path,y.blobHash])));let d=new Map(a.map(y=>[y.path,y.blobHash])),m=Zm({repo:e,headCommit:s.commit,headDate:s.commitDate,prev:l,currentKeys:sh(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),f=oh(e,s.commit,c,m.byKey),g=Pr([...o.ignore,...dn]),h=Jm({repo:e,headTimeSec:s.commitTimeSec,filesets:await Xm(r,s.commit,o.cochange.windowCommits),pathToCurrent:Bs(m.table),currentPaths:new Set(a.map(y=>y.path)),ignored:g,settings:o.cochange}),w=[{path:Jn(e),content:sa(m.table)},...f.files.map(y=>({path:y.path,content:y.content})),{path:Xi(e),content:pr({modelFormatVersion:2,repo:e,builtFromCommit:s.commit,edges:h})}];return{repo:e,headCommit:s.commit,files:w,emittedShardPaths:new Set(f.files.map(y=>y.path)),counts:{...f.counts,correlates:h.length},identityTable:m.table,entityByKey:m.byKey}}var jS,zc=$(()=>{"use strict";F();Fs();Qm();rh();ih();Eo();jS=1500});import{existsSync as yh,readFileSync as kh,readdirSync as NS}from"node:fs";import{join as Xc}from"node:path";import{parse as wh}from"yaml";function OS(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 bh(t,e,r){let n=new Set(t.files.map(d=>d.key)),o=new Set(e.files.map(d=>d.key)),s=0;for(let d of n)o.has(d)&&s++;if(s<ea)return null;let i=s/Math.min(n.size,o.size),a=OS(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(i*c*gh)/gh;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[ke(t.taskKey),ke(e.taskKey)]:[ke(e.taskKey),ke(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function $h(t,e){let r=new Map(t.map(i=>[i.taskKey,i])),n=new Map;for(let i of t)for(let a of i.files)n.has(a.key)||n.set(a.key,[]),n.get(a.key).push(i.taskKey);let o=new Set,s=[];for(let i of n.values())if(!(i.length<2))for(let a=0;a<i.length;a++)for(let c=a+1;c<i.length;c++){let[l,u]=i[a]<i[c]?[i[a],i[c]]:[i[c],i[a]],p=`${l}\0${u}`;if(o.has(p))continue;o.add(p);let d=bh(r.get(l),r.get(u),e);d&&s.push(d)}return s.sort((i,a)=>i.from<a.from?-1:i.from>a.from?1:i.to<a.to?-1:1)}function vh(t,e,r,n){let o=ke(r),s=t.filter(a=>a.from!==o&&a.to!==o),i=e.find(a=>a.taskKey===r);if(i){let a=new Set(i.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=bh(i,c,n);l&&s.push(l)}}return s.sort((a,c)=>a.from<c.from?-1:a.from>c.from?1:a.to<c.to?-1:1)}function Gs(t){let e=Xc(t,"model/facts/events");if(!yh(e))return[];let r=[];for(let n of NS(e).sort())if(n.endsWith(".yaml"))try{let o=At(wh(kh(Xc(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function xh(t){let e=Xc(t,ur);if(!yh(e))return[];try{let r=Zn(wh(kh(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function Hs(t){return pr({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var gh,Jc=$(()=>{"use strict";F();gh=1e4});var Ro={};Be(Ro,{collectSearchRows:()=>Eh,readContextIndexHub:()=>LS,rebuildSearchIndex:()=>Rh,searchIndexPath:()=>Vs,searchModelIndex:()=>DS,toFtsQuery:()=>Th});import{existsSync as mn,readFileSync as fn,readdirSync as qs}from"node:fs";import{join as mt}from"node:path";import{parse as Ys}from"yaml";function Vs(t){return mt(t,".git","codepipe-model-index.sqlite")}function LS(t){let e=mt(t,"regimen.yaml");if(!mn(e))return"off";try{let n=Ys(fn(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 Sh(){try{let{createRequire:t}=await import("node:module");return t(import.meta.url)("node:sqlite")}catch{return null}}function Ws(t){return t.length>Jo?t.slice(0,Jo):t}function Zc(t){if(!mn(t))return[];let e=[];for(let r of qs(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=mt(t,r.name);r.isDirectory()?e.push(...Zc(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function Eh(t){let e=[];for(let s of Zc(mt(t,"model/derived/structure"))){let i;try{i=Ys(fn(s,"utf-8"))}catch{continue}let a=Ct(i);if(a.ok)for(let c of a.value.nodes){let l=re(c.key);l&&e.push({nodeId:c.key,kind:l.level,text:Ws(`${l.path} ${c.label??""}`.trim())})}}let r=mt(t,"model/facts/events");if(mn(r)){for(let s of qs(r).sort())if(s.endsWith(".yaml"))try{let i=At(Ys(fn(mt(r,s),"utf-8")));if(!i.ok)continue;let a=i.value,c=[...a.links?.adr??[],...a.links?.tasks??[]].join(" ");e.push({nodeId:`task::${a.taskKey}`,kind:"task",text:Ws(`${a.taskKey} ${a.title??""} ${c}`.trim())})}catch{}}let n=mt(t,"model/facts/annotations");if(mn(n)){let s=new Map;for(let i of Zc(mt(t,"model/facts/identity")))try{let a=Ys(fn(i,"utf-8"));for(let c of a?.entities??[])c.status==="active"&&c.entityId&&c.currentKey&&s.set(c.entityId,c.currentKey)}catch{}for(let i of qs(n).sort())if(i.endsWith(".md"))try{let a=fn(mt(n,i),"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:s.get(c[1])??c[1],kind:"annotation",text:Ws(c[2].trim())})}catch{}}let o=mt(t,"adr");if(mn(o))for(let s of qs(o).sort()){let i=/^(\d{4})-/.exec(s)?.[1];if(!(!i||!s.endsWith(".md")))try{let a=fn(mt(o,s),"utf-8").split(`
729
+ `).slice(0,6);e.push({nodeId:`adr::ADR-${i}`,kind:"adr",text:Ws(a.filter(c=>c.trim()).join(" "))})}catch{}}return e}async function Rh(t){let e=Eh(t),r=await Sh();if(!r)return{rows:e,indexed:!1};let n=new r.DatabaseSync(Vs(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 s of e)o.run(s.nodeId,s.kind,s.text)}finally{n.close()}return{rows:e,indexed:!0}}function Th(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 DS(t,e,r){let n=await Sh();if(!n)throw new Error("model search needs Node with built-in sqlite (>= 22.13) on this CLI");mn(Vs(t))||await Rh(t);let o=Th(e);if(!o)return[];let s=Math.min(Math.max(r??20,1),ra),i=new n.DatabaseSync(Vs(t));try{return i.prepare(`SELECT node_id AS nodeId, kind, snippet(model_fts, 2, '[', ']', '\u2026', 10) AS snippet,
654
730
  bm25(model_fts) AS rank
655
- 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 ao=v(()=>{"use strict";G()});var Im={};Rr(Im,{attachPrToBranchTasks:()=>tc,attachPrToEvent:()=>Em,recordPipelineEvent:()=>ec});import{existsSync as Bv,readFileSync as Fv}from"node:fs";import{join as Tm}from"node:path";import{simpleGit as Za}from"simple-git";async function Gv(t,e){let n=await Za(t).raw(["diff","--numstat",`${e}^`,e]).catch(()=>""),o=[];for(let i of n.split(`
656
- `)){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 Kv(t,e){let n=[`tasks/${e}/PLAN.md`,`tasks/${e}/SOLUTION.md`].find(i=>Bv(Tm(t,i)));if(!n)return{};let o=Tm(t,n);try{let i=Fv(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 ec(t){let{contextDir:e,repoDir:r,repoName:n,taskKey:o,commitSha:i}=t,s=Qr(e),a=br([...s.ignore,...Jr]),c=await Gv(r,i),l=(await Za(r).raw(["show","-s","--format=%cs",i])).trim(),u=null,p=new Map;try{u=Ya(e,n),u&&(p=new Map(u.entities.filter(I=>I.status==="active").map(I=>[I.currentKey,I.entityId])))}catch{}let d=[];for(let I of c){if(a(I.path))continue;let E=pe("code",n,I.path),b=p.get(E);d.push({key:E,...b?{entityId:b}:{},churn:I.churn})}if(d.length===0)return{recorded:!1};let f=Kv(e,o),m=Si(e,o),h=m?.origin==="pipeline"?m.files.filter(I=>Q(I.key)?.repo!==n):[],g=m?.origin==="pipeline"?m.commits:[],w={modelFormatVersion:2,taskKey:o,origin:"pipeline",...m?.title?{title:m.title}:{},...l?{date:l}:{},commits:[...new Set([...g,i])],files:[...h,...d],links:{...m?.origin==="pipeline"?m.links:{},...f}};w.links&&Object.keys(w.links).length===0&&delete w.links;let y=[...Ri(e).filter(I=>I.taskKey!==o),w],x=wm(bm(e),y,o,s.cochange.halfLifeDays),T=await Lf({contextDir:e,taskKey:o,repoName:n,repoDir:r,commitSha:i,date:l,touchedKeys:new Set(d.map(I=>I.key)),identity:u}).catch(()=>[]);await Re(e,[{path:Pr(o),content:Dn(w)},{path:Ar,content:Ci(x)},...T],`model: task event ${o}`);{let{rebuildSearchIndex:I}=await Promise.resolve().then(()=>(ao(),so));await I(e).catch(()=>{})}return{recorded:!0}}async function tc(t){let e=new Set([t.fallbackTaskKey]);try{let r=Za(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(`
657
- `)){let s=i.trim();s&&e.add(s)}}catch{}for(let r of[...e].sort())await Em(t.contextDir,r,t.prUrl)}async function Em(t,e,r){let n=Si(t,e);if(!n||n.origin!=="pipeline"||n.links?.pr===r)return;let o={...n,links:{...n.links??{},pr:r}};await Re(t,[{path:Pr(e),content:Dn(o)}],`model: pr link for ${e}`)}var rc=v(()=>{"use strict";G();rt();Df();qa();za();Ei();Ja();io()});var co,nc=v(()=>{"use strict";Ua();lr();co=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return Nd(this.cfg,e)}getIssue(e,r){return Od(this.cfg,e,r??xi(this.contextDir))}listComments(e,r){return Ld(this.cfg,e,r)}downloadAttachment(e){return jd(this.cfg,e)}updateStatus(e,r){return Sd(this.cfg,e,r,xi(this.contextDir))}addComment(e,r,n){return Td(this.cfg,e,r)}createIssue(e){return Rd(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,xi(this.contextDir))}editIssue(e,r){return Ed(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return Cd(this.cfg,e,r,n)}fetchStateFields(e){return Md(this.cfg,e)}}});import{existsSync as oc,readFileSync as Hv,readdirSync as Wv}from"node:fs";function Ni(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=zv(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:qv(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:Vv(Yv(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 Rm(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),oc(he(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 Oi(t,e,r){if(r.length===0)return;let n=Ni(t,e,r),o=r.map(i=>i.issue.key);await Re(t,n,`sync(${o.join(", ")}): task data`)}function qv(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(`
658
- `)}function Yv(t,e,r){let n=new Map,o=he(t,`tasks/${e}/comments.jsonl`);if(oc(o))for(let i of Hv(o,"utf-8").split(`
659
- `)){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=Or(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function Vv(t){return t.map(e=>JSON.stringify(e)).join(`
731
+ FROM model_fts WHERE model_fts MATCH ? ORDER BY bm25(model_fts), node_id LIMIT ?`).all(o,s).map(c=>({nodeId:c.nodeId,kind:c.kind,score:-c.rank,snippet:c.snippet}))}finally{i.close()}}var To=$(()=>{"use strict";F()});var Ah={};Be(Ah,{attachPrToBranchTasks:()=>tl,attachPrToEvent:()=>Ch,recordPipelineEvent:()=>el});import{existsSync as MS,readFileSync as US}from"node:fs";import{join as Ih}from"node:path";import{simpleGit as Qc}from"simple-git";async function BS(t,e){let n=await Qc(t).raw(["diff","--numstat",`${e}^`,e]).catch(()=>""),o=[];for(let s of n.split(`
732
+ `)){let i=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(s);if(!i)continue;let a=i[1]==="-"?0:Number(i[1]),c=i[2]==="-"?0:Number(i[2]);o.push({path:i[3],churn:a+c})}return o}function FS(t,e){let n=[`tasks/${e}/PLAN.md`,`tasks/${e}/SOLUTION.md`].find(s=>MS(Ih(t,s)));if(!n)return{};let o=Ih(t,n);try{let s=US(o,"utf-8"),i=[...new Set(s.match(/\bADR-\d{3,4}\b/g)??[])].sort();return{solution:n,...i.length>0?{adr:i}:{}}}catch{return{solution:n}}}async function el(t){let{contextDir:e,repoDir:r,repoName:n,taskKey:o,commitSha:s}=t,i=pn(e),a=Pr([...i.ignore,...dn]),c=await BS(r,s),l=(await Qc(r).raw(["show","-s","--format=%cs",s])).trim(),u=null,p=new Map;try{u=Yc(e,n),u&&(p=new Map(u.entities.filter(T=>T.status==="active").map(T=>[T.currentKey,T.entityId])))}catch{}let d=[];for(let T of c){if(a(T.path))continue;let R=me("code",n,T.path),b=p.get(R);d.push({key:R,...b?{entityId:b}:{},churn:T.churn})}if(d.length===0)return{recorded:!1};let m=FS(e,o),f=Us(e,o),g=f?.origin==="pipeline"?f.files.filter(T=>re(T.key)?.repo!==n):[],h=f?.origin==="pipeline"?f.commits:[],w={modelFormatVersion:2,taskKey:o,origin:"pipeline",...f?.title?{title:f.title}:{},...l?{date:l}:{},commits:[...new Set([...h,s])],files:[...g,...d],links:{...f?.origin==="pipeline"?f.links:{},...m}};w.links&&Object.keys(w.links).length===0&&delete w.links;let y=[...Gs(e).filter(T=>T.taskKey!==o),w],x=vh(xh(e),y,o,i.cochange.halfLifeDays),S=await Um({contextDir:e,taskKey:o,repoName:n,repoDir:r,commitSha:s,date:l,touchedKeys:new Set(d.map(T=>T.key)),identity:u}).catch(()=>[]);await Se(e,[{path:dr(o),content:Wr(w)},{path:ur,content:Hs(x)},...S],`model: task event ${o}`);{let{rebuildSearchIndex:T}=await Promise.resolve().then(()=>(To(),Ro));await T(e).catch(()=>{})}return{recorded:!0}}async function tl(t){let e=new Set([t.fallbackTaskKey]);try{let r=Qc(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 s of o.split(`
733
+ `)){let i=s.trim();i&&e.add(i)}}catch{}for(let r of[...e].sort())await Ch(t.contextDir,r,t.prUrl)}async function Ch(t,e,r){let n=Us(t,e);if(!n||n.origin!=="pipeline"||n.links?.pr===r)return;let o={...n,links:{...n.links??{},pr:r}};await Se(t,[{path:dr(e),content:Wr(o)}],`model: pr link for ${e}`)}var rl=$(()=>{"use strict";F();tt();Bm();qc();zc();Fs();Jc();Eo()});var Io,nl=$(()=>{"use strict";Uc();br();Io=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return Dp(this.cfg,e)}getIssue(e,r){return Mp(this.cfg,e,r??Ms(this.contextDir))}listComments(e,r){return Up(this.cfg,e,r)}downloadAttachment(e){return Lp(this.cfg,e)}updateStatus(e,r){return Tp(this.cfg,e,r,Ms(this.contextDir))}addComment(e,r,n){return Ip(this.cfg,e,r)}createIssue(e){return Pp(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,Ms(this.contextDir))}editIssue(e,r){return Cp(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return _p(this.cfg,e,r,n)}fetchStateFields(e){return Fp(this.cfg,e)}}});import{existsSync as ol,readFileSync as KS,readdirSync as GS}from"node:fs";function zs(t,e,r){let n=[];for(let o of r){let s=o.issue.key,i=YS(t,s,o.attachments);n.push({path:`tasks/${s}/task.md`,content:HS(o.issue,e,i)}),n.push({path:`tasks/${s}/comments.jsonl`,content:qS(WS(t,s,o.comments))});for(let a of o.attachments)n.push({path:`tasks/${s}/attachments/${a.name}`,content:a.contentBase64,encoding:"base64"})}return n}async function Ph(t,e,r,n=10){let o=new Set(e.map(c=>c.issue.key)),s=[],i=c=>(c.links??[]).filter(l=>l.type==="subtask").map(l=>l.targetKey);for(let c of e)s.push(...i(c.issue));let a=[];for(;s.length>0&&a.length<n;){let c=s.shift();if(o.has(c)||(o.add(c),ol(be(t,`tasks/${c}/task.md`))))continue;let l=null;try{l=await r(c)}catch{continue}l&&(a.push({issue:l,comments:[],attachments:[]}),s.push(...i(l)))}return a}async function Xs(t,e,r){if(r.length===0)return;let n=zs(t,e,r),o=r.map(s=>s.issue.key);await Se(t,n,`sync(${o.join(", ")}): task data`)}function HS(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 s of r)o.push(`- [${s}](attachments/${encodeURI(s)})`);o.push("")}return o.join(`
734
+ `)}function WS(t,e,r){let n=new Map,o=be(t,`tasks/${e}/comments.jsonl`);if(ol(o))for(let s of KS(o,"utf-8").split(`
735
+ `)){let i=s.trim();if(i)try{let a=JSON.parse(i);a&&typeof a.id=="string"&&n.set(a.id,a)}catch{}}for(let s of r){if(n.has(s.id))continue;let i={id:s.id,author:s.author,origin:"youtrack",body:s.body,createdAt:new Date(s.createdAt).toISOString()},a=gr(s.body);a&&(i.parsedCommand=a),n.set(s.id,i)}return[...n.values()].sort((s,i)=>s.createdAt.localeCompare(i.createdAt))}function qS(t){return t.map(e=>JSON.stringify(e)).join(`
660
736
  `)+(t.length>0?`
661
- `:"")}function zv(t,e,r){let n=[],o=he(t,`tasks/${e}/attachments`);if(oc(o))for(let i of Wv(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}var Li=v(()=>{"use strict";G();rt()});import{existsSync as Xv,readFileSync as Jv}from"node:fs";import{randomBytes as Qv}from"node:crypto";function Cm(t,e){let r=he(t,`tasks/${e}/comments.jsonl`);if(!Xv(r))return[];let n=[];for(let o of Jv(r,"utf-8").split(`
662
- `)){let i=o.trim();if(i)try{let s=JSON.parse(i);s&&typeof s.id=="string"&&typeof s.body=="string"&&n.push(s)}catch{}}return n}var lo,ic=v(()=>{"use strict";G();rt();Li();ki();lo=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await Jn(this.contextDir);let r=e.columns??[];return Jp(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>Zn(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=Qn(this.contextDir,e);return r?Zn(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return Cm(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 Jn(this.contextDir),!Qn(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${Qv(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=Or(r);s&&(i.parsedCommand=s);let c=[...Cm(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
737
+ `:"")}function YS(t,e,r){let n=[],o=be(t,`tasks/${e}/attachments`);if(ol(o))for(let s of GS(o))n.push(s);for(let s of r)n.includes(s.name)||n.push(s.name);return n}var Js=$(()=>{"use strict";F();tt()});import{existsSync as VS,readFileSync as zS}from"node:fs";import{randomBytes as XS}from"node:crypto";function _h(t,e){let r=be(t,`tasks/${e}/comments.jsonl`);if(!VS(r))return[];let n=[];for(let o of zS(r,"utf-8").split(`
738
+ `)){let s=o.trim();if(s)try{let i=JSON.parse(s);i&&typeof i.id=="string"&&typeof i.body=="string"&&n.push(i)}catch{}}return n}var Co,sl=$(()=>{"use strict";F();tt();Js();js();Co=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await yo(this.contextDir);let r=e.columns??[];return tm(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>wo(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=ko(this.contextDir,e);return r?wo(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return _h(this.contextDir,e).map(n=>({id:n.id,issueId:e,author:n.author,body:n.body,createdAt:n.createdAt}))}async downloadAttachment(e){throw new Error(`internal tracker: no remote attachments (${e})`)}async updateStatus(e,r){await this.mutateRecord(e,n=>({...n,status:r}))}async addComment(e,r,n){if(await yo(this.contextDir),!ko(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let s={id:`int-${Date.now().toString(36)}-${XS(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},i=gr(r);i&&(s.parsedCommand=i);let c=[..._h(this.contextDir,e),s].map(l=>JSON.stringify(l)).join(`
663
739
  `)+`
664
- `;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 Qp(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:Ks.statusColumns}]}async mutateRecord(e,r,n){let o=Qn(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=Zn(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:Bn(e),content:Pa(i)},...Ni(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:Uo,status:r.targetStatus,links:[],created:n,updated:n},i=Zn(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:Bn(e),content:Pa(o)},...Ni(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}}});import{existsSync as Am,readFileSync as Pm}from"node:fs";import{join as _m}from"node:path";import{parseDocument as jm}from"yaml";function sc(t){if(!t)return"youtrack";try{let e=_m(t,"project.yaml");return Am(e)&&jm(Pm(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function kt(t){let e=sc(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=zp(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=Zv(n);return i?{ok:!0,kind:e,provider:new lo(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=vd();return r?{ok:!0,kind:e,provider:new co(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function Zv(t){try{let e=_m(t,"project.yaml");if(!Am(e))return null;let r=jm(Pm(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var Di=v(()=>{"use strict";lr();nc();ic();ki();nc();ic()});async function tn(t,e){let n=(Mi.get(t)??Promise.resolve()).catch(()=>{}).then(e);Mi.set(t,n);try{return await n}finally{Mi.get(t)===n&&Mi.delete(t)}}async function Nm(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;dr(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return X("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return tn(`${i}/${r.name}`,async()=>{let s=await xt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Te(i,r.name,t.baseDir),{commit:c,pushed:l}=await pp(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force,push:e.push});if(t.contextDir){let u=e.taskId.split(":")[1]??"";u&&await ec({contextDir:t.contextDir,repoDir:a,repoName:r.name,taskKey:u,commitSha:c}).catch(p=>{dr(`[model] task event for ${u} failed: ${p instanceof Error?p.message:String(p)}`)})}return ce({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,pushed:l,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"push_branch":{if(!r)return X("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return tn(`${i}/${r.name}`,async()=>{let s=await xt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Te(i,r.name,t.baseDir);return await fp(s,a,{branchName:e.branchName,force:e.force}),ce({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"early_branch":{if(!r)return X("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return tn(`${i}/${r.name}`,async()=>{let s=await xt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Te(i,r.name,t.baseDir),{commit:c,pushed:l}=await mp(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return ce({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return X("no repo spec");let i=Ze(r),s=await i.createPullRequest(r,e);if(t.contextDir){let a=e.taskId.split(":")[1]??"",c=e.taskId.split(":",2)[0]??"?";a&&await tc({contextDir:t.contextDir,repoDir:Te(c,r.name,t.baseDir),branchName:e.branchName,baseBranch:e.baseBranch,fallbackTaskKey:a,prUrl:s.url}).catch(l=>{dr(`[model] pr link for ${a} failed: ${l instanceof Error?l.message:String(l)}`)})}return ce({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return X("no repo spec");let i=Ze(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ce({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return X("no repo spec");let i=Ze(r);return await i.closePR(r,e.prNumber,e.comment),ce({prNumber:e.prNumber,host:i.name})}case"rewrite_cluster_branch":{if(!r)return X("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return tn(`${i}/${r.name}`,async()=>{let s=await xt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Te(i,r.name,t.baseDir),{commit:c,dropped:l}=await hp(s,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:r.defaultBranch});return ce({branch:e.branchName,commit:c,dropped:l,pushed:l>0})})}case"merge_branch":{if(!r)return X("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return tn(`${i}/${r.name}`,async()=>{let s=await xt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Te(i,r.name,t.baseDir),{mergedSha:c}=await yp(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ce({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return X("no repo spec");let i=t.cloneUrlOverride??Vn(r),a=(await kp(i)).filter(u=>wp(u,e.issueKey)),c=Ze(r),l=null;if(c.findOpenPrByBranch)for(let u of a){let p=await c.findOpenPrByBranch(r,u).catch(()=>null);if(p){l={number:p.number,url:p.url};break}}return ce({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return X("no repo spec");let i=Ze(r);return await i.addPRComment(r,e.prNumber,e.body),ce({prNumber:e.prNumber,host:i.name})}case"tracker_status":{let i=kt({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),ce({issueId:t.trackerIssueId,newStatus:e.newStatus})):X("no tracker_issue_id provided"):X(i.error)}case"tracker_comment":{let i=kt({contextDir:t.contextDir});if(!i.ok)return X(i.error);if(!t.trackerIssueId)return X("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return ce({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=kt({contextDir:t.contextDir});if(!i.ok)return X(i.error);if(!e.projectKey)return X("no projectKey in create_tracker_issue action");let{id:s,key:a}=await i.provider.createIssue({projectKey:e.projectKey,title:e.title,body:e.body,targetStatus:e.targetStatus});return ce({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=kt({contextDir:t.contextDir});if(!i.ok)return X(i.error);let s=0;for(let a of e.links)try{await i.provider.applyLink(a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return X(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return ce({applied:s})}case"set_project_setting":{if(!t.contextDir)return X("no context repo clone on this CLI");let i=await Rf(t.contextDir,e.edits);return ce({files:i.files})}case"tracker_edit":{let i=kt({contextDir:t.contextDir});if(!i.ok)return X(i.error);if(!t.contextDir)return X("no context repo clone on this CLI");await i.provider.editIssue(e.issueKey,{...e.title!==void 0?{title:e.title}:{},...e.body!==void 0?{body:e.body}:{}});let s=await i.provider.getIssue(e.issueKey);return s&&await Oi(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),ce({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return X("no context repo clone on this CLI");let i=await jf(t.contextDir,e);return ce({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return X("no context repo clone on this CLI");let i=await Pf(t.contextDir,e);return ce({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ce({reported:!0})):X("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return X("no context repo clone on this CLI");let i=await t.refreshContextStatus();return ce({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return X("no project workspace on this CLI");if(!r)return X("no repo spec");if(!t.onRunActivity)return X("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=di(t.contextDir),c=s.find(f=>f.id===e.actionId);if(!c){let f=a.find(m=>m.file===`actions/${e.actionId}.yml`);return X(f?`action "${e.actionId}" failed to parse: ${f.error}`:`unknown action "${e.actionId}"`)}let l=eu(c,e.input);if(!l.ok)return X(l.error);let u=Ap(t.contextDir),p=W(e.projectId),d={};return p?.github?.token&&(d.GH_TOKEN=p.github.token),p?.gitlab?.token&&(d.GITLAB_TOKEN=p.gitlab.token),p?.bitbucket&&(d.BITBUCKET_EMAIL=p.bitbucket.email,d.BITBUCKET_API_TOKEN=p.bitbucket.apiToken),p?.youtrack&&(d.YOUTRACK_URL=p.youtrack.url,d.YOUTRACK_TOKEN=p.youtrack.token),tn(`${e.projectId}/${r.name}`,async()=>{await xt(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let f=Te(e.projectId,r.name,t.baseDir),m=await vf({cwd:f,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:h=>i(e.runId,h)});return ce({runId:e.runId,status:m.status,exitCode:m.exitCode,...m.failedStep?{failedStep:m.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return X("no context repo clone on this CLI");let i=Ef(t.contextDir,e.path);return ce({path:e.path,...i})}case"search_model":{if(!t.contextDir)return X("no context repo clone on this CLI");let{searchModelIndex:i}=await Promise.resolve().then(()=>(ao(),so)),s=await i(t.contextDir,e.q,e.limit);return ce({hits:s})}case"model_drift":return X("model_drift requires a local workspace (handled by the daemon)");case"model_bootstrap":return X("model_bootstrap requires a local workspace (handled by the daemon)");case"local_apply":return X("local_apply requires a local workspace (handled by the daemon)");default:return X(`unsupported action type: ${e.type}`)}}catch(i){return X(i instanceof Error?i.message:String(i))}}function ce(t){return{status:"done",result:t}}function X(t){return{status:"failed",error:t}}var Mi,Om=v(()=>{"use strict";G();ka();xf();If();ue();Cf();_f();Ua();Dt();si();mr();rc();Di();Li();Mi=new Map});import{existsSync as ex,mkdtempSync as tx,rmSync as rx}from"node:fs";import{tmpdir as nx}from"node:os";import{join as ac}from"node:path";import{simpleGit as Lm}from"simple-git";async function Dm(t,e,r){let n=[];for(let a of e){let c=t.repos.find(u=>u.name===a.repoName);if(!c)return{ok:!1,error:`repo "${a.repoName}" not in project.yaml \u2014 run /sync`};let l=ac(t.root,c.mountAs);if(!ex(ac(l,".git")))return{ok:!1,error:`${c.mountAs}/ not cloned \u2014 run /sync first`};n.push({payload:a,dir:l,mountAs:c.mountAs,defaultBranch:c.defaultBranch})}let o=[];for(let a of n){let c=Lm(a.dir),l=a.payload;try{await c.fetch()}catch(f){return{ok:!1,error:`fetch failed in ${a.mountAs}: ${uo(f)}`}}let u=`origin/${l.baseRef}`;await ax(c,u)||(u=`origin/${a.defaultBranch}`);let p;try{p=(await c.revparse([u])).trim()}catch(f){return{ok:!1,error:`base ${u} unavailable in ${a.mountAs}: ${uo(f)}`}}let d;try{d=await Yn(c,l.deliverySha,()=>fr(c,{contextRepoCloneUrl:l.contextRepoCloneUrl,deliveryRef:l.deliveryRef,deliverySha:l.deliverySha,baseSha:l.baseSha,commitMessage:l.commitMessage}))}catch(f){return{ok:!1,error:`fetch delivery failed in ${a.mountAs}: ${uo(f)}`}}o.push({repoName:l.repoName,mountAs:a.mountAs,git:c,branch:l.branchName,startPoint:p,deliveryCommit:d})}let i=[],s=[];for(let a of o){let c=await cx(a.git,`refs/heads/${a.branch}`);try{let u=(await a.git.revparse([`${a.deliveryCommit}^`])).trim()===a.startPoint?a.deliveryCommit:await ix(a);await a.git.raw(["branch","-f",a.branch,u]),i.push({git:a.git,mountAs:a.mountAs,branch:a.branch,priorSha:c}),s.push({repoName:a.repoName,branch:a.branch,commit:u}),r.info(`[local-apply] ${a.mountAs}: branch ${a.branch} \u2192 ${u.slice(0,10)} (no checkout)`)}catch(l){return await sx(i,r),{ok:!1,error:`apply failed in ${a.mountAs}: ${uo(l)} (rolled back all repos)`}}}return{ok:!0,repos:s}}async function ix(t){let e=tx(ac(nx(),"codepipe-local-apply-"));try{await t.git.raw(["worktree","add","--detach",e,t.startPoint]);let r=Lm(e);try{await r.raw([...ox,"cherry-pick",t.deliveryCommit])}catch(n){throw await r.raw(["cherry-pick","--abort"]).catch(()=>{}),n}return(await r.revparse(["HEAD"])).trim()}finally{await t.git.raw(["worktree","remove","--force",e]).catch(()=>{}),rx(e,{recursive:!0,force:!0}),await t.git.raw(["worktree","prune"]).catch(()=>{})}}async function sx(t,e){for(let r of t)try{r.priorSha?await r.git.raw(["branch","-f",r.branch,r.priorSha]):await r.git.raw(["branch","-D",r.branch])}catch(n){e.warn(`[local-apply] rollback of ${r.mountAs}#${r.branch} failed: ${uo(n)} \u2014 check manually`)}}async function ax(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function cx(t,e){try{return(await t.raw(["rev-parse","--verify","--quiet",e])).trim()||null}catch{return null}}function uo(t){return t instanceof Error?t.message.trim():String(t)}var ox,Mm=v(()=>{"use strict";mr();ox=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{homedir as lx}from"node:os";import{existsSync as ux,mkdirSync as dx,readFileSync as px,writeFileSync as fx}from"node:fs";import{dirname as mx,join as gx}from"node:path";function cc(){return V("FARM_PINS")??gx(lx(),".codepipe","farm-pins.json")}function Um(){let t=cc();if(!ux(t))return{};try{return JSON.parse(px(t,"utf-8"))}catch{return{}}}function hx(t){let e=cc();dx(mx(e),{recursive:!0}),fx(e,JSON.stringify(t,null,2)+`
665
- `,{mode:384})}function yx(t){return Um()[t]}function Ui(t,e){let r=Um();r[t]=e,hx(r)}function Bi(t,e){let r=je(e),n=yx(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 ${cc()}.`);return r}var lc=v(()=>{"use strict";_e();We()});import{existsSync as Bm,readFileSync as Fm}from"node:fs";import{join as Gm}from"node:path";async function Km(t,e,r,n){let o=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return o(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=je(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Bi(e.farmId,e.farmPublicKey);let s=W(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await ne(t.hubUrl,t.cliToken,t.projectId),c;if(r){let d=Gm(r,"project.yaml"),f=Gm(r,"regimen.yaml");Bm(d)&&Bm(f)?c={projectYaml:Fm(d,"utf-8"),regimenYaml:Fm(f,"utf-8")}:n.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},u=Tt(e.farmPublicKey,JSON.stringify(l));Ui(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let p=await oi(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:u});return p.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...p.daemonStatus?{daemonStatus:p.daemonStatus}:{}}:o(p.error??"farm provisioning failed")}catch(i){return o(i instanceof Error?i.message:String(i))}}var Hm=v(()=>{"use strict";We();lc();Ie();ue()});import{homedir as kx}from"node:os";import{existsSync as wx,mkdirSync as bx,readFileSync as $x,writeFileSync as vx}from"node:fs";import{dirname as xx,join as Sx}from"node:path";function uc(){return V("RUNNER_PINS")??Sx(kx(),".codepipe","runner-pins.json")}function Wm(){let t=uc();if(!wx(t))return{};try{return JSON.parse($x(t,"utf-8"))}catch{return{}}}function Tx(t){let e=uc();bx(xx(e),{recursive:!0}),vx(e,JSON.stringify(t,null,2)+`
666
- `,{mode:384})}function Ex(t){return Wm()[t]}function dc(t,e){let r=Wm();r[t]=e,Tx(r)}function qm(t,e){let r=je(e),n=Ex(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 ${uc()}.`);return r}var Ym=v(()=>{"use strict";_e();We()});async function Vm(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:zm(t)});if(!o.ok)throw new Error(`github ${n} for ${e}/${r}: HTTP ${o.status}`);let i=await o.json();if(!i.token)throw new Error(`github ${n} for ${e}/${r}: no token in response`);return i.token}async function Jm(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(je(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");qm(e.runnerId,e.runnerPublicKey);let i=W(t.projectId)?.github?.token;if(!i)throw new Error("no GitHub token stored for this project on this CLI");let a=((await r.fetchProject(t.hubUrl,t.cliToken,t.projectId)).repos??[]).find(c=>c.host==="github"&&c.owner===e.owner&&c.repoName===e.repo);if(!a)throw new Error(`${e.owner}/${e.repo} is not a GitHub repository of this project`);return{githubToken:i,repo:a}}async function Qm(t,e,r,n=Xm){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 Jm(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:[du(e.runnerId)]},c=Tt(e.runnerPublicKey,JSON.stringify(a));dc(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 Zm(t,e,r,n=Xm){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 Jm(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=Tt(e.runnerPublicKey,JSON.stringify(c));dc(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle for ${s.owner}/${s.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let u=await n.teardownOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:l,owner:s.owner,repo:s.repoName});return{type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:u.ok,...u.error?{error:u.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}var zm,Ix,Xm,eg=v(()=>{"use strict";G();We();Ym();Ie();ue();zm=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});Ix={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:zm(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)=>Vm(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Vm(t,e,r,"remove-token")},Xm={api:Ix,fetchProject:ne,provisionOnRunner:Jd,teardownOnRunner:Qd}});function Rx(t){return Fe.test(t)?_t(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Fe}`}function rg(t,e,r,n){let o=Rx(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(zr(n,r).toString("utf-8"));if(typeof s.value!="string"||s.value.length===0)return{ok:!1,detail:"payload has no value"};i=s.value}catch(s){return{ok:!1,detail:`cannot open the sealed secret (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}if(i.length>tg)return{ok:!1,detail:`secret value too large (max ${tg} chars)`};try{return zu(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function ng(t,e){try{return Xu(t,e)?{ok:!0}:{ok:!0,detail:"no such secret (already absent)"}}catch(r){return{ok:!1,detail:r instanceof Error?r.message:String(r)}}}var tg,og=v(()=>{"use strict";G();We();ue();tg=16*1024});function Cx(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var Fi,ig=v(()=>{"use strict";Dt();Fi=class{constructor(e,r,n){this.intervalMs=e;this.send=r;this.log=n}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let n=[];for(let s of r.prs){let a=Ze(s.repoSpec);try{let c=await a.getPullRequest(s.repoSpec,s.number);n.push({number:s.number,url:s.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof cr){this.log.warn(`[track] task=${e} pr=${s.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${s.url} fetch failed: ${c instanceof Error?c.message:String(c)}`);return}}let o=n.map(s=>`${s.number}:${s.state}:${s.merged?1:0}:${s.ci}:${s.mergeable}`).join("|");if(this.lastSig.get(e)===o)return;for(let s=0;s<n.length;s++){let a=n[s];if(a.ci!=="failed")continue;let c=Ze(r.prs[s].repoSpec);if(c.getCiFailureLog)try{let l=await c.getCiFailureLog(r.prs[s].repoSpec,a.number);l&&(a.ciFailureLog=l)}catch(l){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${l instanceof Error?l.message:String(l)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:n}),this.lastSig.set(e,o);let i=Cx(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}}});function sg(t){let{description:e,...r}=t;return r}function Ax(t){let{body:e,...r}=t;return r}function Px(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 ag(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 cg(t,e,r,n){try{return await t.listComments(e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}var Gi,lg=v(()=>{"use strict";G();Li();Di();Gi=class t{constructor(e,r,n,o={contextDir:null}){this.intervalMs=e;this.send=r;this.log=n;this.options=o}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;abandonedTicks=0;static MAX_ABANDONED_TICKS=3;setRequest(e){let r=this.request?.projectId;this.request=e,this.log.info(`[yt-sync] request updated: project=${e.projectKey} columns=[${e.sourceColumns.join(",")}] sinceMs=${e.sinceMs} offBoard=${e.offBoardIssueIds.length}`),this.timer||this.start(),r&&r!==e.projectId&&this.log.info(`[yt-sync] project switch ${r} \u2192 ${e.projectId}`)}start(){if(this.timer)return;this.log.info(`[yt-sync] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[yt-sync] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[yt-sync] poller stopped"))}async tickOnce(){await this.tick()}async forceSync(){if(!this.request){this.log.info("[yt-sync] force requested but no sync_request yet \u2014 ignored");return}this.log.info("[yt-sync] force sync requested (manual)"),await this.tick()}async tick(){if(this.running||!this.request)return;let r=(this.options.resolveProvider??(()=>kt({contextDir:this.options.contextDir})))();if(!r.ok){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn(`[yt-sync] tracker provider unavailable (${r.error}) \u2014 poller idle.`));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,r.provider)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let x=e.stageField?{stageField:e.stageField}:{},T=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},E=(e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(E){let b=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[R,N]=await Promise.all([b.length>0?r.listIssues({projectKey:e.projectKey,columns:b,...x,...T}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...x})]),F=new Map;for(let C of[...R,...N])F.set(C.id,C);o=[...F.values()]}else{let b=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:b,...x,...T})}}catch(x){this.log.warn(`[yt-sync] listIssues failed: ${x instanceof Error?x.message:String(x)}`);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 T=await cg(r,x.id,e.sinceMs,this.log);T&&i.set(x.id,T)}let c=[];for(let x of e.offBoardIssueIds){if(s.has(x))continue;let T=await cg(r,x,e.sinceMs,this.log);if(T&&T.length>0&&i.set(x,T),e.requireAssignee||T&&T.length>0){let I=await ag(r,x,e.stageField,this.log);if(I)c.push(I);else if(T&&T.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 Rm(this.options.contextDir,d,x=>ag(r,x,e.stageField,this.log)));try{await Oi(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let x of p)this.shippedAttachments.add(x)}catch(x){let T=x instanceof Error?x.message:String(x);this.abandonTick(`context task sync failed: ${T}`);return}let f=this.options.isSelfComment??(()=>!1),m=[],h=[];for(let[x,T]of i){let I=T.filter(b=>!f(b.id));if(I.length===0)continue;m.push({issueId:x,comments:I.map(Ax)});let E=I.flatMap(b=>{let R=Or(b.body);return R?[{commentId:b.id,author:b.author,name:R.name,args:R.args,createdAt:b.createdAt}]:[]});E.length>0&&h.push({issueId:x,commands:E})}let g={type:"youtrack_observation",projectId:e.projectId,issues:o.map(sg),commentsBatch:m,...h.length>0?{commandsBatch:h}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(sg)}:{},observedAtMs:n};this.send(g);let w=m.reduce((x,T)=>x+T.comments.length,0),y=h.reduce((x,T)=>x+T.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${w} commands=${y} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let p=`${s.id}:${u.id}`;if(this.shippedAttachments.has(p))continue;let d;try{d=await n.downloadAttachment(u.url)}catch(m){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${m instanceof Error?m.message:String(m)}`);continue}let f=Px(u.name);l.has(f)&&(f=`${u.id}-${f}`),l.add(f),c.push({name:f,contentBase64:d.toString("base64")}),i.push(p)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}}});import{existsSync as ug,readFileSync as _x,readdirSync as jx}from"node:fs";import{join as dg}from"node:path";import{simpleGit as Nx}from"simple-git";import{parse as Ox}from"yaml";function pc(t){let e=new Map,r=dg(t,As);if(!ug(r))return e;let n;try{n=Ox(_x(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 Lx(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return Nr({modelFormatVersion:2,repos:e})}function pg(t,e){let r=dg(t,e);if(!ug(r))return[];let n=[];for(let o of jx(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...pg(t,i)):n.push(i)}return n}async function Ki(t,e,r={}){let n=[],o=0;for(let d of e){n.push(...d.files);let f=`model/derived/structure/${d.repo}`;for(let m of pg(t,f))d.emittedShardPaths.has(m)||(n.push({path:m,content:"",deleted:!0}),o++)}let i=pc(t);for(let d of e)i.set(d.repo,{builtFromCommit:d.headCommit,counts:d.counts});n.push({path:As,content:Lx(i)});let s=Ri(t),a=km(s,r.halfLifeDays??Je.halfLifeDays);n.push({path:Ar,content:Ci(a)});for(let d of e){let f=[];for(let m of s)for(let h of m.files)Q(h.key)?.repo===d.repo&&f.push({kind:"touched_by",from:ve(m.taskKey),to:h.key,...h.churn!==void 0?{weight:h.churn}:{}});n.push({path:Al(d.repo),content:_r({modelFormatVersion:2,repo:d.repo,builtFromCommit:d.headCommit,edges:f})})}let c=Nx(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(()=>(ao(),so));await d(t).catch(()=>{})}return{committed:p!==l,filesWritten:n.filter(d=>!d.deleted).length,filesDeleted:o}}var fg=v(()=>{"use strict";G();Ja();rt()});var Wi={};Rr(Wi,{bootstrapDaemonModel:()=>Mx,bootstrapModelForTargets:()=>wc,bootstrapWorkspaceModel:()=>kg,modelBootstrapCommand:()=>kc,modelBuildCommand:()=>yc,rebuildWorkspaceModelIfStale:()=>Ux});import{existsSync as gc}from"node:fs";import{join as rn}from"node:path";import{cancel as Dx,intro as mg,log as fc,outro as mc}from"@clack/prompts";import{simpleGit as hc}from"simple-git";function Hi(t){Dx(t),process.exit(1)}function gg(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:rn(t.root,i.mountAs);if(!gc(rn(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 hg(t){let e=hc(t.dir),r=`origin/${t.defaultBranch}`;return await e.raw(["rev-parse","--verify",r]).then(()=>!0).catch(()=>!1)?r:"HEAD"}async function yg(t,e,r,n){let o=[];for(let i of e)try{let s=await Va({repo:i.name,repoDir:i.dir,contextDir:t,settings:r,ref:await hg(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 yc(t){mg("codepipe model build");let e=Se();e||Hi("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{let r=Qr(e.contextDir),n=gg(e,t.repo,s=>fc.warn(s)),o=await yg(e.contextDir,n,r,s=>fc.info(s)),i=await Ki(e.contextDir,o,{halfLifeDays:r.cochange.halfLifeDays});i.committed?mc(`model updated: ${i.filesWritten} files written, ${i.filesDeleted} stale removed`):mc("model already up to date (no changes)")}catch(r){Hi(r instanceof Error?r.message:String(r))}}async function kc(t){mg("codepipe model bootstrap");let e=Se();e||Hi("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{await kg(e,t.repo,{onLog:r=>fc.info(r)})}catch(r){Hi(r instanceof Error?r.message:String(r))}mc("bootstrap complete")}async function kg(t,e,r){let n=gg(t,e,r.onLog);return wc(t.contextDir,n,r)}async function wc(t,e,r){let n=Qr(t),o=await yg(t,e,n,r.onLog),i=Gf(t),s=Ff(n.issueKeyPattern,i),a=br([...n.ignore,...Jr]),c=[];for(let p of o){let d=e.find(m=>m.name===p.repo),f=await Hf({repo:p.repo,repoDir:d.dir,headCommit:p.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:s,pathToCurrent:Ti(p.identityTable),entityByKey:p.entityByKey,ignored:a,trackerProjectKey:i});c.push(f),r.onLog(`${p.repo}: ${f.size} task events mined from history`)}let{files:l,skippedPipeline:u}=Wf(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 Ki(t,o,{halfLifeDays:n.cochange.halfLifeDays}),{events:l.length}}async function Mx(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:rn(e.root,a),l=s.defaultBranch||"main";c!==e.contextDir&&gc(rn(c,".git"))?(await hc(c).fetch(["origin",l]).catch(()=>{}),o.push({name:s.name,dir:c,defaultBranch:l})):(n(`${s.name}: materializing clone in the daemon layout`),await xt(t,s),o.push({name:s.name,dir:Te(t,s.name),defaultBranch:l}))}let i=await wc(e.contextDir,o,{onLog:n});return{repos:o.length,events:i.events}}async function Ux(t,e={}){let r=e.onLog??(()=>{}),n=Qr(t.contextDir);if(!n.enabled)return{rebuilt:[],skipped:[]};let o=[],i=[],s=pc(t.contextDir),a=[];for(let c of t.repos){let l=c.mountAs==="."?t.root:rn(t.root,c.mountAs);if(!gc(rn(l,".git")))continue;let u=hc(l),p=c.defaultBranch||"main";e.fetch&&await u.fetch(["origin",p]).catch(()=>{});let d=await hg({name:c.name,dir:l,defaultBranch:p}),f=(await u.revparse([d]).catch(()=>"")).trim();if(f){if(s.get(c.name)?.builtFromCommit===f){i.push(c.name);continue}try{a.push(await Va({repo:c.name,repoDir:l,contextDir:t.contextDir,settings:n,ref:f})),o.push(c.name)}catch(m){r(`[model] rebuild of ${c.name} failed: ${m instanceof Error?m.message:String(m)}`)}}}return a.length>0&&(await Ki(t.contextDir,a,{halfLifeDays:n.cochange.halfLifeDays}),r(`[model] release-path rebuild: ${o.join(", ")} (skipped up-to-date: ${i.join(", ")||"\u2014"})`)),{rebuilt:o,skipped:i}}var po=v(()=>{"use strict";rt();fg();za();qa();Ei();io();mr();mt()});var bg={};Rr(bg,{computeDriftReport:()=>Hx,supersededAdrIds:()=>wg});import{existsSync as bc,readFileSync as $c,readdirSync as vc}from"node:fs";import{join as nn}from"node:path";import{parse as Bx}from"yaml";import{simpleGit as Fx}from"simple-git";function Kx(t,e){let r=nn(t,`model/derived/structure/${e}`),n=[],o="";if(!bc(r))return{nodes:n,builtFromCommit:o};for(let i of vc(r).sort()){if(!i.endsWith(".yaml"))continue;let s;try{let a=At(Bx($c(nn(r,i),"utf-8")));if(!a.ok)continue;s=a.value}catch{continue}o=s.builtFromCommit;for(let a of s.nodes){let c=Q(a.key);!c||c.level!=="code"&&c.level!=="component"||n.push({key:a.key,path:c.path,level:c.level,contentHash:a.contentHash,entityId:a.entityId})}}return{nodes:n,builtFromCommit:o}}function wg(t){let e=new Set,r=nn(t,"adr");if(!bc(r))return e;for(let n of vc(r).sort()){let o=/^(\d{4})-/.exec(n)?.[1];if(!(!o||!n.endsWith(".md")))try{let i=$c(nn(r,n),"utf-8").slice(0,600).toLowerCase();/status[^\n]*superseded/.test(i)&&e.add(`ADR-${o}`)}catch{}}return e}async function Hx(t,e,r){let{nodes:n,builtFromCommit:o}=Kx(e,r),i=(await Fx(t).revparse(["HEAD"])).trim(),s=await oo(t,i),a=new Map(s.map(y=>[y.path,y.blobHash])),c=[],l=[],u=new Set,p=[];for(let y of n){if(y.level==="component"){p.push(y);continue}u.add(y.path);let x=a.get(y.path);x?y.contentHash&&x.slice(0,Gx)!==y.contentHash&&c.push(y.key):l.push(y.key)}let d=0,f=new Map,m=new Set;for(let y of s){let x=y.path.lastIndexOf("/"),T=x<0?"":y.path.slice(0,x);f.has(T)||f.set(T,new Set),f.get(T).add(y.path),u.has(y.path)||d++;let I=T;for(;I!==""&&!m.has(I);)m.add(I),I=I.includes("/")?I.slice(0,I.lastIndexOf("/")):""}let h=new Map;for(let y of u){let x=y.lastIndexOf("/"),T=x<0?"":y.slice(0,x);h.has(T)||h.set(T,new Set),h.get(T).add(y)}for(let y of p){if(!m.has(y.path)){l.push(y.key);continue}let x=h.get(y.path)??new Set,T=f.get(y.path)??new Set;(x.size!==T.size||[...x].some(E=>!T.has(E)))&&c.push(y.key)}let g=[],w=wg(e);if(w.size>0){let y=nn(e,"model/facts/annotations"),x=new Map(n.filter(T=>T.entityId).map(T=>[T.entityId,T.key]));if(bc(y))for(let T of vc(y).sort()){if(!T.endsWith(".md"))continue;let I=T.replace(/\.md$/,""),E=x.get(I);if(E)try{($c(nn(y,T),"utf-8").match(/\bADR-(\d{3,4})\b/g)??[]).map(N=>`ADR-${N.slice(4).padStart(4,"0")}`).some(N=>w.has(N))&&g.push(E)}catch{}}}return{repo:r,builtFromCommit:o,headCommit:i,stale:[...new Set(c)].sort(),orphaned:[...new Set(l)].sort(),superseded:[...new Set(g)].sort(),newFiles:d}}var Gx,$g=v(()=>{"use strict";G();io();Gx=12});import{existsSync as xg,rmSync as Wx}from"node:fs";import{join as $r}from"node:path";import{simpleGit as qx}from"simple-git";import"ws";function qi(t,e={}){let r=e.log??{info:g=>console.log(g),warn:g=>console.warn(g)};r.info(`codepipe-cli v${Ue} (protocol ${lt})`);let n=g=>e.onEvent?.(g),o=e.workspace;o?.contextDir&&Np(o.contextDir,r);let i=vg("CLI_TRACKING_POLL_INTERVAL_SEC"),s=vg("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let g=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(g)&&g>0?g*1e3:6e5})(),c=!1,l=!1,u=!1,p=new Set,d=!1,f=new Set,m=h();function h(){let g=ni(t.hubUrl,t.cliToken),w=null,y=new Fi(i,_=>{g.readyState===g.OPEN&&g.send(JSON.stringify(_))},r),x=new Gi(s,_=>{g.readyState===g.OPEN&&g.send(JSON.stringify(_))},r,{contextDir:o?.contextDir??null,isSelfComment:_=>f.has(_)}),T=null,I=async()=>{try{let _={trackerProvider:sc(o?.contextDir??null)};try{let O=await ne(t.hubUrl,t.cliToken,t.projectId);_={..._,repos:O.repos,contextRepo:O.contextRepo}}catch(O){r.warn(`[readiness] could not fetch project summary for push checks: ${O instanceof Error?O.message:String(O)}`)}let M=await Bd(t.projectId,_);if(g.readyState!==g.OPEN)return;let D={type:"cli_readiness",projectId:t.projectId,ready:M.ready,checks:M.checks,creds:M.creds,secretNames:Ju(t.projectId),checkedAt:M.checkedAt};if(g.send(JSON.stringify(D)),M.ready)r.info("[readiness] ready");else{let O=M.checks.filter(S=>!S.ok).map(S=>`${S.name}(${S.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${O.join(", ")}`)}let z=Yd(M.creds,u);if(z==="open"){u=!0;let O=Vd(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${O}`),ur(O)}else z==="rearm"&&(u=!1)}catch(_){r.warn(`[readiness] check failed: ${_ instanceof Error?_.message:String(_)}`)}},E=()=>{I(),T=setInterval(()=>void I(),a),typeof T.unref=="function"&&T.unref()},b=()=>{T&&(clearInterval(T),T=null)},R=150,N=new Map,F=_=>{let M=N.get(_);if(!M||(M.timer&&clearTimeout(M.timer),N.delete(_),M.events.length===0||g.readyState!==g.OPEN))return;let D={type:"run_activity",projectId:t.projectId,runId:_,events:M.events};g.send(JSON.stringify(D))},C=(_,M)=>{let D=N.get(_);if(D||(D={events:[],timer:null},N.set(_,D)),D.events.push(M),M.kind==="result"){F(_);return}D.timer||(D.timer=setTimeout(()=>F(_),R),D.timer.unref?.())},k=o?.contextDir?new pi(o.contextDir,t.projectId,_=>{g.readyState===g.OPEN&&g.send(JSON.stringify(_))},r):null,L=async()=>{let _=o?.contextDir;if(!_)throw new Error("no context repo clone on this CLI");let M;try{M=(await ne(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let D=await of(_,t.projectId,M,r);return g.readyState===g.OPEN&&g.send(JSON.stringify(D)),D},A=null,H=async()=>{let _=o?.contextDir;if(_)try{let{readContextIndexHub:M,collectSearchRows:D}=await Promise.resolve().then(()=>(ao(),so));if(M(_)!=="metadata")return;let z=D(_);g.readyState===g.OPEN&&(g.send(JSON.stringify({type:"model_index",projectId:t.projectId,rows:z})),r.info(`[model] tier-2 index snapshot pushed (${z.length} rows)`))}catch(M){r.warn(`[model] tier-2 index push failed (non-fatal): ${M instanceof Error?M.message:String(M)}`)}},q=()=>{A&&clearTimeout(A),A=setTimeout(()=>void H(),5e3)},Z=null,Ye=async _=>{if(o?.contextDir)try{let{rebuildWorkspaceModelIfStale:M}=await Promise.resolve().then(()=>(po(),Wi));(await M({root:o.root,contextDir:o.contextDir,repos:o.repos},{fetch:_,onLog:z=>r.info(z)})).rebuilt.length>0&&q()}catch(M){r.warn(`[model] release-path rebuild failed (non-fatal): ${M instanceof Error?M.message:String(M)}`)}},Ve=_=>{Z&&clearTimeout(Z),Z=setTimeout(()=>void Ye(_),6e4)},ge=setInterval(()=>void Ye(!0),6*36e5);return g.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let _=id(t.projectId),M=V("ORIGIN")==="farm"?"farm":"local",D=V("FARM_ID"),z=t.accountEmail??_.email,O;try{let $=yf(t.projectId);$&&(O=$.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 S={type:"register",projectId:t.projectId,platformVersion:Ue,protocolVersion:lt,accountId:_.accountId,accountLabel:_.label,origin:M,inFlightActionIds:[...p],...z?{accountEmail:z}:{},...M==="farm"&&D?{farmId:D}:{},...O?{sealPublicKey:O}:{}};g.send(JSON.stringify(S))}),g.on("message",async _=>{let M=_.toString("utf-8");if(M==="pong"||M==="ping")return;let D;try{D=JSON.parse(M)}catch{return}if(!D||typeof D!="object")return;let z=D.type;if(z==="registered"){let S=D;if(S.ok){if(r.info(`[ws] registered for project ${S.projectId}`),n({kind:"registered",projectId:S.projectId??t.projectId}),y.start(),k?.start(),E(),Sc(t,o,r),o?.contextDir){try{let $=yi(o.contextDir,t.projectId);g.readyState===g.OPEN&&g.send(JSON.stringify($)),$.outdated&&(r.warn(`[ctx] context format outdated: v${$.templateVersion} \u2192 v${$.currentVersion}`+($.missingPaths.length>0?` (missing: ${$.missingPaths.join(", ")})`:"")),l||(l=!0,L().catch(()=>{})))}catch($){r.warn(`[ctx] context-format detect failed (non-fatal): ${$ instanceof Error?$.message:String($)}`)}H(),Ve(!0)}}else r.warn(`[ws] register rejected: ${S.reason??"unknown"}`),n({kind:"register_rejected",reason:S.reason??"unknown"}),c=!0,g.close();return}if(z==="hello"){let S=D;w=Ao(S.protocolVersion);let $=w?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${S.platformVersion} (protocol ${S.protocolVersion}) \u2014 ${$}`),w||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Ue}, protocol ${lt}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${xc}`),n({kind:"incompatible",hubVersion:typeof S.platformVersion=="string"?S.platformVersion:null,hubProtocol:typeof S.protocolVersion=="number"?S.protocolVersion:null,updateCommand:xc}));return}if(z==="tracking_targets"){y.setTargets(D.targets);return}if(z==="youtrack_sync_request"){x.setRequest(D);return}if(z==="youtrack_force_sync"){x.forceSync();return}if(z==="sync_local"){await zx(D,o,g,r);return}if(z==="provision_repo"){let S=D;r.info(`[repo] provision_repo: ${S.repo.name} (${S.repo.host}:${S.repo.owner}/${S.repo.repoName})`),await Yx(t,o,S.repo,r),await Sc(t,o,r);return}if(z==="remove_repo"){let S=D;r.info(`[repo] remove_repo: ${S.repoName}${S.purge?" (purge)":""}`),await Sc(t,o,r),S.purge&&Vx(t,o,S.repoName,r);return}if(z==="context_write"){await Xx(D,o,g,r);return}if(z==="adr_promote"){await Jx(D,o,g,r);return}if(z==="cred_update"){let S=D,$=W(t.projectId),j=$?.sealKey?await kf(t.projectId,S.kind,S.sealed,$.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},Y={type:"cred_update_result",updateId:S.updateId,projectId:t.projectId,ok:j.ok,...j.detail?{detail:j.detail}:{}};g.readyState===g.OPEN&&g.send(JSON.stringify(Y)),j.ok?(r.info(`[cred] ${S.kind} replaced${j.detail?` \u2014 ${j.detail}`:""}`),I()):r.warn(`[cred] ${S.kind} replacement rejected: ${j.detail??"unknown"}`);return}if(z==="readiness_check"){r.info("[readiness] on-demand check requested"),I();return}if(z==="agent_login_start"){Wd(t,g,D,r,I);return}if(z==="move_to_farm"){let S=D;r.info(`[farm-move] request to move ${t.projectId} onto farm ${S.farmName} (${S.farmId})`);let $=await Km(t,S,o?.contextDir,r);g.readyState===g.OPEN&&g.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(z==="gh_runner_setup"){let S=D;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${S.runnerName} (${S.runnerId})`);let $=await Qm(t,S,r);g.readyState===g.OPEN&&g.send(JSON.stringify($)),$.ok?r.info(`[ghr] runners connected on ${S.runnerName}`):r.warn(`[ghr] setup failed: ${$.error??"see per-repo statuses"}`);return}if(z==="gh_runner_teardown"){let S=D;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${S.runnerName} (${S.runnerId})`);let $=await Zm(t,S,r);g.readyState===g.OPEN&&g.send(JSON.stringify($)),$.ok?r.info(`[ghr] runners disconnected from ${S.runnerName}`):r.warn(`[ghr] teardown failed: ${$.error??"unknown error"}`);return}if(z==="tracker_fields_request"){let S=D,$={type:"tracker_fields_result",requestId:S.requestId,projectId:t.projectId,ok:!1},j=kt({contextDir:o?.contextDir??null});if(!j.ok)$.error=j.error;else try{$.fields=await j.provider.fetchStateFields(S.projectKey),$.ok=!0}catch(Y){$.error=Y instanceof Error?Y.message:String(Y)}g.readyState===g.OPEN&&g.send(JSON.stringify($)),$.ok||r.warn(`[yt-fields] listing failed: ${$.error??"unknown"}`);return}if(z==="project_secret_update"||z==="project_secret_delete"){let S=D,$;if(S.type==="project_secret_update"){let Y=W(t.projectId);$=Y?.sealKey?rg(t.projectId,S.name,S.sealed,Y.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else $=ng(t.projectId,S.name);let j={type:"project_secret_update_result",updateId:S.updateId,projectId:t.projectId,ok:$.ok,...$.detail?{detail:$.detail}:{}};g.readyState===g.OPEN&&g.send(JSON.stringify(j)),$.ok?(r.info(`[secret] ${S.name} ${S.type==="project_secret_update"?"saved":"deleted"}`+($.detail?` \u2014 ${$.detail}`:"")),I()):r.warn(`[secret] ${S.name} rejected: ${$.detail??"unknown"}`);return}if(z==="auto_apply_local"){let S=D;if(!o?.contextDir){r.warn(`[apply] auto_apply_local for ${S.claim.taskKey} \u2014 no workspace (headless), skipped; task stays in READY_TO_APPLY`);return}let $=await xp({hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId,root:o.root,contextDir:o.contextDir,repos:o.repos},S.claim,r).catch(j=>({ok:!1,message:j instanceof Error?j.message:String(j)}));$.ok?r.info(`[apply] ${S.claim.taskKey}: ${$.message}`):r.warn(`[apply] ${S.claim.taskKey}: ${$.message} \u2014 task stays in READY_TO_APPLY`),n({kind:"local_applied",taskKey:S.claim.taskKey,ok:$.ok,...$.ok?{branches:$.branches??[]}:{error:$.message}});return}if(z==="sandbox_keys"){let S=W(t.projectId);if(!S){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let $=Ur(t.projectId),j=pf(D,S,$,r);for(let Y of j)g.readyState===g.OPEN&&g.send(JSON.stringify(Y));return}if(z!=="dispatch_action")return;let O=D;if(w===!1){let S=`refused: HUB protocol incompatible with CLI v${Ue} (protocol ${lt})`;g.send(JSON.stringify({type:"action_result",actionId:O.actionId,status:"failed",error:S})),r.warn(`[exec] ${O.actionId} (${O.action.type}) \u2192 REFUSED: ${S}`),r.warn(`[exec] update the CLI to clear this: ${xc}`),n({kind:"action",actionId:O.actionId,actionType:O.action.type,ok:!1,error:S});return}if(O.action.type==="model_drift"){p.add(O.actionId);try{let S,$=o?.repos.find(j=>j.name===O.action.repoName);if(!o?.contextDir||!$)S={status:"failed",error:"no local workspace/repo clone on this CLI"};else try{let{computeDriftReport:j}=await Promise.resolve().then(()=>($g(),bg)),Y=$.mountAs==="."?o.root:$r(o.root,$.mountAs);S={status:"done",result:{report:await j(Y,o.contextDir,$.name)}}}catch(j){S={status:"failed",error:j instanceof Error?j.message:String(j)}}g.send(JSON.stringify({type:"action_result",actionId:O.actionId,...S}))}finally{p.delete(O.actionId)}return}if(O.action.type==="model_bootstrap"){p.add(O.actionId);try{let S;if(!o?.contextDir)S={status:"failed",error:"no Context Repo clone on this CLI"};else if(d)S={status:"failed",error:"model bootstrap is already running"};else{d=!0;try{let $=await ne(t.hubUrl,t.cliToken,t.projectId),{bootstrapDaemonModel:j}=await Promise.resolve().then(()=>(po(),Wi)),Y=await j(t.projectId,{root:o.root,contextDir:o.contextDir},$.repos,ke=>r.info(`[model] ${ke}`));r.info(`[model] bootstrap done: ${Y.repos} repos, ${Y.events} task events`),q(),S={status:"done",result:{repos:Y.repos,events:Y.events}}}catch($){S={status:"failed",error:$ instanceof Error?$.message:String($)},r.warn(`[model] bootstrap failed: ${S.error}`)}finally{d=!1}}g.readyState===g.OPEN&&g.send(JSON.stringify({type:"action_result",actionId:O.actionId,...S}))}finally{p.delete(O.actionId)}return}if(O.action.type==="local_apply"){p.add(O.actionId);try{let S;if(!o)S={status:"failed",error:"no local workspace on this CLI"};else{let j=await Dm(o,O.action.repos,r);if(S=j.ok?{status:"done",result:{repos:j.repos}}:{status:"failed",error:j.error},j.ok&&o.contextDir){let Y=O.action.taskId.split(":")[1]??"";for(let ke of Y?j.repos:[]){let J=o.repos.find(te=>te.name===ke.repoName);if(!J)continue;let{recordPipelineEvent:we}=await Promise.resolve().then(()=>(rc(),Im));await we({contextDir:o.contextDir,repoDir:$r(o.root,J.mountAs),repoName:ke.repoName,taskKey:Y,commitSha:ke.commit}).catch(te=>r.warn(`[model] task event for ${Y} failed: ${te instanceof Error?te.message:String(te)}`))}q()}}g.send(JSON.stringify({type:"action_result",actionId:O.actionId,...S}));let $=S.status!=="failed";$?r.info(`[exec] ${O.actionId} (local_apply) \u2192 done`):r.warn(`[exec] ${O.actionId} (local_apply) \u2192 FAILED: ${S.status==="failed"?S.error:"?"}`),n({kind:"action",actionId:O.actionId,actionType:"local_apply",ok:$,...S.status==="failed"?{error:S.error}:{}})}finally{p.delete(O.actionId)}return}p.add(O.actionId);try{let S=await Nm({action:O.action,repo:O.repo,trackerIssueId:O.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:k?()=>k.reportNow():void 0,refreshContextStatus:o?.contextDir?L:void 0,onRunActivity:C}).catch(Y=>({status:"failed",error:Y instanceof Error?Y.message:String(Y)}));O.action.type==="tracker_comment"&&S.status==="done"&&"result"in S&&typeof S.result?.commentId=="string"&&f.add(S.result.commentId),g.send(JSON.stringify({type:"action_result",actionId:O.actionId,...S}));let $=S.status!=="failed",j=!$&&"error"in S?S.error:void 0;$?r.info(`[exec] ${O.actionId} (${O.action.type}) \u2192 done`):r.warn(`[exec] ${O.actionId} (${O.action.type}) \u2192 FAILED: ${j??"?"}`),n({kind:"action",actionId:O.actionId,actionType:O.action.type,ok:$,...j?{error:j}:{}}),$&&["apply_delivery","context_write","create_pr"].includes(O.action.type)&&q(),$&&["merge_pr","merge_branch"].includes(O.action.type)&&Ve(!0)}finally{p.delete(O.actionId)}}),g.on("close",(_,M)=>{let D=M?.toString("utf-8")??"";if(r.info(`[ws] closed code=${_}${D?` reason=${D}`:""}`),y.stop(),x.stop(),k?.stop(),b(),clearInterval(ge),Z&&clearTimeout(Z),A&&clearTimeout(A),D==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:_}),!c&&setTimeout(()=>{m=h()},2e3)}),g.on("error",_=>r.warn(`[ws] error: ${_.message}`)),g}return{stop(){c=!0,m.close()}}}async function Sc(t,e,r){try{let n=await ne(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=eo(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 Yx(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?$r(e.root,o):Te(t.projectId,r.name);if(xg($r(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await qx().clone(Vn(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 Vx(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?$r(e.root,o):Te(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!xg($r(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{Wx(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 zx(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=$r(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Tp(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 Xx(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 Jx(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 Fp(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 vg(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}var xc,Tc=v(()=>{"use strict";_e();G();sd();qd();zd();ri();ha();Ep();_p();Gp();rt();St();Ra();sf();ja();mr();ff();wf();Om();Mm();Hm();eg();Ie();og();Kr();ue();ig();lg();Di();xc="npm i -g @code-partner/codepipe@latest"});import{execFileSync as Qx}from"node:child_process";import{mkdtempSync as Zx,mkdirSync as eS,readFileSync as Sg,rmSync as tS,writeFileSync as rS}from"node:fs";import{tmpdir as nS}from"node:os";import{dirname as oS,join as Tg}from"node:path";function Eg(t="codepipe-context"){let e=Zx(Tg(nS(),"codepipe-ssh-")),r=Tg(e,"id_ed25519");try{return Qx("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Sg(r,"utf-8"),publicKey:Sg(`${r}.pub`,"utf-8").trim()}}finally{tS(e,{recursive:!0,force:!0})}}async function Ig(t,e,r,n="codepipe-context"){let o=await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/keys`,{method:"POST",headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({title:n,key:r,read_only:!1})});if(o.ok)return;let i=await o.text();if(!(o.status===422&&/already in use/i.test(i)))throw new Error(`add deploy key failed: ${o.status} ${i}`)}function Rg(t){if(/^git@[^:]+:.+/.test(t))return t;let e=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(e)return`git@${e[1]}:${e[2]}`;let r=t.match(/^https:\/\/(?:[^@/]+@)?([^/]+)\/(.+)$/);return r?`git@${r[1]}:${r[2]}`:t}function Cg(t,e){eS(oS(t),{recursive:!0});let r=e.endsWith(`
740
+ `;return await Se(this.contextDir,[{path:`tasks/${e}/comments.jsonl`,content:c}],`tracker(${e}): comment`),{id:s.id}}async createIssue(e){let r=new Date().toISOString(),n=await rm(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,s=>{let i=s.links.filter(a=>!(a.type===o&&a.targetKey===n));return i.push({type:o,targetKey:n}),{...s,links:i}})}async fetchStateFields(e){return[{name:"Status",values:os.statusColumns}]}async mutateRecord(e,r,n){let o=ko(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let s={...r(o),updated:new Date().toISOString()},i=wo(this.contextDir,s,{withDescription:!0});n!==void 0&&(n.trim().length>0?i.description=n:delete i.description);let a=[{path:zr(e),content:Pc(s)},...zs(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])];await Se(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:oo,status:r.targetStatus,links:[],created:n,updated:n},s=wo(this.contextDir,o);return r.body.trim().length>0&&(s.description=r.body),[{path:zr(e),content:Pc(o)},...zs(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])]}}});import{existsSync as jh,readFileSync as Nh}from"node:fs";import{join as Oh}from"node:path";import{parseDocument as Lh}from"yaml";function il(t){if(!t)return"youtrack";try{let e=Oh(t,"project.yaml");return jh(e)&&Lh(Nh(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function St(t){let e=il(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=Qf(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let s=JS(n);return s?{ok:!0,kind:e,provider:new Co(n,s,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=Ep();return r?{ok:!0,kind:e,provider:new Io(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function JS(t){try{let e=Oh(t,"project.yaml");if(!jh(e))return null;let r=Lh(Nh(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var Zs=$(()=>{"use strict";br();nl();sl();js();nl();sl()});async function hn(t,e){let n=(Qs.get(t)??Promise.resolve()).catch(()=>{}).then(e);Qs.set(t,n);try{return await n}finally{Qs.get(t)===n&&Qs.delete(t)}}async function Dh(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;vr(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return V("no repo spec");let s=e.taskId.split(":",2)[0]??"?";return hn(`${s}/${r.name}`,async()=>{let i=await Nt(s,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(s,r.name,t.baseDir),{commit:c,pushed:l}=await gf(i,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force,push:e.push});if(t.contextDir){let u=e.taskId.split(":")[1]??"";u&&await el({contextDir:t.contextDir,repoDir:a,repoName:r.name,taskKey:u,commitSha:c}).catch(p=>{vr(`[model] task event for ${u} failed: ${p instanceof Error?p.message:String(p)}`)})}return ue({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,pushed:l,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"push_branch":{if(!r)return V("no repo spec");let s=e.taskId.split(":",2)[0]??"?";return hn(`${s}/${r.name}`,async()=>{let i=await Nt(s,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(s,r.name,t.baseDir);return await yf(i,a,{branchName:e.branchName,force:e.force}),ue({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"early_branch":{if(!r)return V("no repo spec");let s=e.taskId.split(":",2)[0]??"?";return hn(`${s}/${r.name}`,async()=>{let i=await Nt(s,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(s,r.name,t.baseDir),{commit:c,pushed:l}=await kf(i,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return ue({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return V("no repo spec");let s=dt(r),i=await s.createPullRequest(r,e);if(t.contextDir){let a=e.taskId.split(":")[1]??"",c=e.taskId.split(":",2)[0]??"?";a&&await tl({contextDir:t.contextDir,repoDir:Ie(c,r.name,t.baseDir),branchName:e.branchName,baseBranch:e.baseBranch,fallbackTaskKey:a,prUrl:i.url}).catch(l=>{vr(`[model] pr link for ${a} failed: ${l instanceof Error?l.message:String(l)}`)})}return ue({url:i.url,number:i.number,host:s.name})}case"merge_pr":{if(!r)return V("no repo spec");let s=dt(r),i=await s.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ue({prNumber:e.prNumber,host:s.name,...i.mergedSha?{mergedSha:i.mergedSha}:{}})}case"close_pr":{if(!r)return V("no repo spec");let s=dt(r);return await s.closePR(r,e.prNumber,e.comment),ue({prNumber:e.prNumber,host:s.name})}case"rewrite_cluster_branch":{if(!r)return V("no repo spec");let s=e.taskId.split(":",2)[0]??"?";return hn(`${s}/${r.name}`,async()=>{let i=await Nt(s,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(s,r.name,t.baseDir),{commit:c,dropped:l}=await bf(i,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:r.defaultBranch});return ue({branch:e.branchName,commit:c,dropped:l,pushed:l>0})})}case"merge_branch":{if(!r)return V("no repo spec");let s=e.taskId.split(":",2)[0]??"?";return hn(`${s}/${r.name}`,async()=>{let i=await Nt(s,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(s,r.name,t.baseDir),{mergedSha:c}=await $f(i,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ue({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return V("no repo spec");let s=t.cloneUrlOverride??mo(r),a=(await vf(s)).filter(u=>xf(u,e.issueKey)),c=dt(r),l=null;if(c.findOpenPrByBranch)for(let u of a){let p=await c.findOpenPrByBranch(r,u).catch(()=>null);if(p){l={number:p.number,url:p.url};break}}return ue({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return V("no repo spec");let s=dt(r);return await s.addPRComment(r,e.prNumber,e.body),ue({prNumber:e.prNumber,host:s.name})}case"tracker_status":{let s=St({contextDir:t.contextDir});return s.ok?t.trackerIssueId?(await s.provider.updateStatus(t.trackerIssueId,e.newStatus),ue({issueId:t.trackerIssueId,newStatus:e.newStatus})):V("no tracker_issue_id provided"):V(s.error)}case"tracker_comment":{let s=St({contextDir:t.contextDir});if(!s.ok)return V(s.error);if(!t.trackerIssueId)return V("no tracker_issue_id provided");let i=await s.provider.addComment(t.trackerIssueId,e.body,e.author);return ue({issueId:t.trackerIssueId,commentId:i.id})}case"create_tracker_issue":{let s=St({contextDir:t.contextDir});if(!s.ok)return V(s.error);if(!e.projectKey)return V("no projectKey in create_tracker_issue action");let{id:i,key:a}=await s.provider.createIssue({projectKey:e.projectKey,title:e.title,body:e.body,targetStatus:e.targetStatus});return ue({issueKey:a,issueId:i})}case"apply_tracker_links":{let s=St({contextDir:t.contextDir});if(!s.ok)return V(s.error);let i=0;for(let a of e.links)try{await s.provider.applyLink(a.sourceIssueKey,a.rel,a.targetIssueKey),i++}catch(c){return V(`${c instanceof Error?c.message:String(c)} (applied ${i}/${e.links.length})`)}return ue({applied:i})}case"set_project_setting":{if(!t.contextDir)return V("no context repo clone on this CLI");let s=await Pm(t.contextDir,e.edits);return ue({files:s.files})}case"set_prompt_override":{if(!t.contextDir)return V("no context repo clone on this CLI");if(!Pa(e.role))return V(`unknown prompt operation: ${e.role}`);let s=_a(e.role);return await Se(t.contextDir,[e.content===null?{path:s,content:"",deleted:!0}:{path:s,content:e.content}],e.commitMessage),t.requestConfigReport?.(),ue({path:s,reset:e.content===null})}case"tracker_edit":{let s=St({contextDir:t.contextDir});if(!s.ok)return V(s.error);if(!t.contextDir)return V("no context repo clone on this CLI");await s.provider.editIssue(e.issueKey,{...e.title!==void 0?{title:e.title}:{},...e.body!==void 0?{body:e.body}:{}});let i=await s.provider.getIssue(e.issueKey);return i&&await Xs(t.contextDir,e.projectId,[{issue:i,comments:[],attachments:[]}]),ue({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return V("no context repo clone on this CLI");let s=await Lm(t.contextDir,e);return ue({files:s.files})}case"set_repo_default_branch":{if(!t.contextDir)return V("no context repo clone on this CLI");let s=await Nm(t.contextDir,e);return ue({repoName:s.repoName,defaultBranch:s.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ue({reported:!0})):V("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return V("no context repo clone on this CLI");let s=await t.refreshContextStatus();return ue({outdated:s.outdated,templateVersion:s.templateVersion})}case"run_action":{if(!t.contextDir)return V("no project workspace on this CLI");if(!r)return V("no repo spec");if(!t.onRunActivity)return V("no run-activity stream on this CLI");let s=t.onRunActivity,{defs:i,errors:a}=Rs(t.contextDir),c=i.find(m=>m.id===e.actionId);if(!c){let m=a.find(f=>f.file===`actions/${e.actionId}.yml`);return V(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=wa(c,e.input);if(!l.ok)return V(l.error);let u=Nf(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),hn(`${e.projectId}/${r.name}`,async()=>{await Nt(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=Ie(e.projectId,r.name,t.baseDir),f=await Em({cwd:m,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:g=>s(e.runId,g)});return ue({runId:e.runId,status:f.status,exitCode:f.exitCode,...f.failedStep?{failedStep:f.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return V("no context repo clone on this CLI");let s=Cm(t.contextDir,e.path);return ue({path:e.path,...s})}case"search_model":{if(!t.contextDir)return V("no context repo clone on this CLI");let{searchModelIndex:s}=await Promise.resolve().then(()=>(To(),Ro)),i=await s(t.contextDir,e.q,e.limit);return ue({hits:i})}case"model_drift":return V("model_drift requires a local workspace (handled by the daemon)");case"model_bootstrap":return V("model_bootstrap requires a local workspace (handled by the daemon)");case"local_apply":return V("local_apply requires a local workspace (handled by the daemon)");default:return V(`unsupported action type: ${e.type}`)}}catch(s){return V(s instanceof Error?s.message:String(s))}}function ue(t){return{status:"done",result:t}}function V(t){return{status:"failed",error:t}}var Qs,Mh=$(()=>{"use strict";F();kc();Rm();tt();Am();pe();_m();Om();Uc();qt();$s();Er();rl();Zs();Js();Qs=new Map});import{existsSync as ZS,mkdtempSync as QS,rmSync as eE}from"node:fs";import{tmpdir as tE}from"node:os";import{join as al}from"node:path";import{simpleGit as Uh}from"simple-git";async function Bh(t,e,r){let n=[];for(let a of e){let c=t.repos.find(u=>u.name===a.repoName);if(!c)return{ok:!1,error:`repo "${a.repoName}" not in project.yaml \u2014 run /sync`};let l=al(t.root,c.mountAs);if(!ZS(al(l,".git")))return{ok:!1,error:`${c.mountAs}/ not cloned \u2014 run /sync first`};n.push({payload:a,dir:l,mountAs:c.mountAs,defaultBranch:c.defaultBranch})}let o=[];for(let a of n){let c=Uh(a.dir),l=a.payload;try{await c.fetch()}catch(m){return{ok:!1,error:`fetch failed in ${a.mountAs}: ${Ao(m)}`}}let u=`origin/${l.baseRef}`;await sE(c,u)||(u=`origin/${a.defaultBranch}`);let p;try{p=(await c.revparse([u])).trim()}catch(m){return{ok:!1,error:`base ${u} unavailable in ${a.mountAs}: ${Ao(m)}`}}let d;try{d=await fo(c,l.deliverySha,()=>Sr(c,{contextRepoCloneUrl:l.contextRepoCloneUrl,deliveryRef:l.deliveryRef,deliverySha:l.deliverySha,baseSha:l.baseSha,commitMessage:l.commitMessage}))}catch(m){return{ok:!1,error:`fetch delivery failed in ${a.mountAs}: ${Ao(m)}`}}o.push({repoName:l.repoName,mountAs:a.mountAs,git:c,branch:l.branchName,startPoint:p,deliveryCommit:d})}let s=[],i=[];for(let a of o){let c=await iE(a.git,`refs/heads/${a.branch}`);try{let u=(await a.git.revparse([`${a.deliveryCommit}^`])).trim()===a.startPoint?a.deliveryCommit:await nE(a);await a.git.raw(["branch","-f",a.branch,u]),s.push({git:a.git,mountAs:a.mountAs,branch:a.branch,priorSha:c}),i.push({repoName:a.repoName,branch:a.branch,commit:u}),r.info(`[local-apply] ${a.mountAs}: branch ${a.branch} \u2192 ${u.slice(0,10)} (no checkout)`)}catch(l){return await oE(s,r),{ok:!1,error:`apply failed in ${a.mountAs}: ${Ao(l)} (rolled back all repos)`}}}return{ok:!0,repos:i}}async function nE(t){let e=QS(al(tE(),"codepipe-local-apply-"));try{await t.git.raw(["worktree","add","--detach",e,t.startPoint]);let r=Uh(e);try{await r.raw([...rE,"cherry-pick",t.deliveryCommit])}catch(n){throw await r.raw(["cherry-pick","--abort"]).catch(()=>{}),n}return(await r.revparse(["HEAD"])).trim()}finally{await t.git.raw(["worktree","remove","--force",e]).catch(()=>{}),eE(e,{recursive:!0,force:!0}),await t.git.raw(["worktree","prune"]).catch(()=>{})}}async function oE(t,e){for(let r of t)try{r.priorSha?await r.git.raw(["branch","-f",r.branch,r.priorSha]):await r.git.raw(["branch","-D",r.branch])}catch(n){e.warn(`[local-apply] rollback of ${r.mountAs}#${r.branch} failed: ${Ao(n)} \u2014 check manually`)}}async function sE(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function iE(t,e){try{return(await t.raw(["rev-parse","--verify","--quiet",e])).trim()||null}catch{return null}}function Ao(t){return t instanceof Error?t.message.trim():String(t)}var rE,Fh=$(()=>{"use strict";Er();rE=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{homedir as aE}from"node:os";import{existsSync as cE,mkdirSync as lE,readFileSync as uE,writeFileSync as dE}from"node:fs";import{dirname as pE,join as fE}from"node:path";function cl(){return J("FARM_PINS")??fE(aE(),".codepipe","farm-pins.json")}function Kh(){let t=cl();if(!cE(t))return{};try{return JSON.parse(uE(t,"utf-8"))}catch{return{}}}function mE(t){let e=cl();lE(pE(e),{recursive:!0}),dE(e,JSON.stringify(t,null,2)+`
741
+ `,{mode:384})}function hE(t){return Kh()[t]}function ei(t,e){let r=Kh();r[t]=e,mE(r)}function ti(t,e){let r=De(e),n=hE(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 ${cl()}.`);return r}var ll=$(()=>{"use strict";Le();rt()});import{existsSync as Gh,readFileSync as Hh}from"node:fs";import{join as Wh}from"node:path";async function qh(t,e,r,n){let o=s=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:s});try{if(e.projectId!==t.projectId)return o(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let s=De(e.farmPublicKey);if(s!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");ti(e.farmId,e.farmPublicKey);let i=q(t.projectId);if(!i)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await oe(t.hubUrl,t.cliToken,t.projectId),c;if(r){let d=Wh(r,"project.yaml"),m=Wh(r,"regimen.yaml");Gh(d)&&Gh(m)?c={projectYaml:Hh(d,"utf-8"),regimenYaml:Hh(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:{...i.github?{github:i.github}:{},...i.bitbucket?{bitbucket:i.bitbucket}:{},...i.gitlab?{gitlab:i.gitlab}:{},...i.youtrack?{youtrack:i.youtrack}:{},...i.claude?{claude:i.claude}:{},...i.contextWrite?{contextWrite:i.contextWrite}:{},...i.contextSsh?{contextSsh:i.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},u=Lt(e.farmPublicKey,JSON.stringify(l));ei(e.farmId,s),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${s}) \u2014 handing off`);let p=await ws(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(s){return o(s instanceof Error?s.message:String(s))}}var Yh=$(()=>{"use strict";rt();ll();Ae();pe()});import{homedir as gE}from"node:os";import{existsSync as yE,mkdirSync as kE,readFileSync as wE,writeFileSync as bE}from"node:fs";import{dirname as $E,join as vE}from"node:path";function ul(){return J("RUNNER_PINS")??vE(gE(),".codepipe","runner-pins.json")}function Vh(){let t=ul();if(!yE(t))return{};try{return JSON.parse(wE(t,"utf-8"))}catch{return{}}}function xE(t){let e=ul();kE($E(e),{recursive:!0}),bE(e,JSON.stringify(t,null,2)+`
742
+ `,{mode:384})}function SE(t){return Vh()[t]}function dl(t,e){let r=Vh();r[t]=e,xE(r)}function zh(t,e){let r=De(e),n=SE(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 ${ul()}.`);return r}var Xh=$(()=>{"use strict";Le();rt()});async function Jh(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:Zh(t)});if(!o.ok)throw new Error(`github ${n} for ${e}/${r}: HTTP ${o.status}`);let s=await o.json();if(!s.token)throw new Error(`github ${n} for ${e}/${r}: no token in response`);return s.token}async function eg(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(De(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");zh(e.runnerId,e.runnerPublicKey);let s=q(t.projectId)?.github?.token;if(!s)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:s,repo:a}}async function tg(t,e,r,n=Qh){let o=s=>({type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:s});try{let{githubToken:s,repo:i}=await eg(t,e,n);if(!await n.api.repoHasAdmin(s,i.owner,i.repoName))return o(`the GitHub token lacks admin access on ${i.owner}/${i.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:i.owner,repo:i.repoName,regToken:await n.api.mintRegistrationToken(s,i.owner,i.repoName)}],labels:[Ma(e.runnerId)]},c=Lt(e.runnerPublicKey,JSON.stringify(a));dl(e.runnerId,e.fingerprint),r.info(`[ghr] registration token for ${i.owner}/${i.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(s){return o(s instanceof Error?s.message:String(s))}}async function rg(t,e,r,n=Qh){let o=s=>({type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:s});try{let{githubToken:s,repo:i}=await eg(t,e,n),a={owner:i.owner,repo:i.repoName};try{a.removeToken=await n.api.mintRemoveToken(s,i.owner,i.repoName)}catch(p){r.warn(`[ghr] remove-token for ${i.owner}/${i.repoName} failed (${p instanceof Error?p.message:p}) \u2014 the runner host will force-remove`)}let c={projectId:t.projectId,runners:[a]},l=Lt(e.runnerPublicKey,JSON.stringify(c));dl(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle for ${i.owner}/${i.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:i.owner,repo:i.repoName});return{type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:u.ok,...u.error?{error:u.error}:{}}}catch(s){return o(s instanceof Error?s.message:String(s))}}var Zh,EE,Qh,ng=$(()=>{"use strict";F();rt();Xh();Ae();pe();Zh=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});EE={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Zh(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)=>Jh(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Jh(t,e,r,"remove-token")},Qh={api:EE,fetchProject:oe,provisionOnRunner:ef,teardownOnRunner:tf}});function RE(t){return Ge.test(t)?Pt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Ge}`}function sg(t,e,r,n){let o=RE(e);if(o)return{ok:!1,detail:o};let s;try{let i=JSON.parse(ln(n,r).toString("utf-8"));if(typeof i.value!="string"||i.value.length===0)return{ok:!1,detail:"payload has no value"};s=i.value}catch(i){return{ok:!1,detail:`cannot open the sealed secret (${i instanceof Error?i.message:String(i)}) \u2014 wrong channel key?`}}if(s.length>og)return{ok:!1,detail:`secret value too large (max ${og} chars)`};try{return Zd(t,e,s),{ok:!0}}catch(i){return{ok:!1,detail:i instanceof Error?i.message:String(i)}}}function ig(t,e){try{return Qd(t,e)?{ok:!0}:{ok:!0,detail:"no such secret (already absent)"}}catch(r){return{ok:!1,detail:r instanceof Error?r.message:String(r)}}}var og,ag=$(()=>{"use strict";F();rt();pe();og=16*1024});function TE(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var ri,cg=$(()=>{"use strict";qt();ri=class{constructor(e,r,n){this.intervalMs=e;this.send=r;this.log=n}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let n=[];for(let i of r.prs){let a=dt(i.repoSpec);try{let c=await a.getPullRequest(i.repoSpec,i.number);n.push({number:i.number,url:i.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof wr){this.log.warn(`[track] task=${e} pr=${i.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${i.url} fetch failed: ${c instanceof Error?c.message:String(c)}`);return}}let o=n.map(i=>`${i.number}:${i.state}:${i.merged?1:0}:${i.ci}:${i.mergeable}`).join("|");if(this.lastSig.get(e)===o)return;for(let i=0;i<n.length;i++){let a=n[i];if(a.ci!=="failed")continue;let c=dt(r.prs[i].repoSpec);if(c.getCiFailureLog)try{let l=await c.getCiFailureLog(r.prs[i].repoSpec,a.number);l&&(a.ciFailureLog=l)}catch(l){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${l instanceof Error?l.message:String(l)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:n}),this.lastSig.set(e,o);let s=TE(n);this.log.info(`[track] task=${e} snapshot signalled${s?` \u2192 ${s}`:""} (${n.length} PR(s))`)}}});function lg(t){let{description:e,...r}=t;return r}function IE(t){let{body:e,...r}=t;return r}function CE(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 ug(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 dg(t,e,r,n){try{return await t.listComments(e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}var ni,pg=$(()=>{"use strict";F();Js();Zs();ni=class t{constructor(e,r,n,o={contextDir:null}){this.intervalMs=e;this.send=r;this.log=n;this.options=o}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;abandonedTicks=0;static MAX_ABANDONED_TICKS=3;setRequest(e){let r=this.request?.projectId;this.request=e,this.log.info(`[yt-sync] request updated: project=${e.projectKey} columns=[${e.sourceColumns.join(",")}] sinceMs=${e.sinceMs} offBoard=${e.offBoardIssueIds.length}`),this.timer||this.start(),r&&r!==e.projectId&&this.log.info(`[yt-sync] project switch ${r} \u2192 ${e.projectId}`)}start(){if(this.timer)return;this.log.info(`[yt-sync] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[yt-sync] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[yt-sync] poller stopped"))}async tickOnce(){await this.tick()}async forceSync(){if(!this.request){this.log.info("[yt-sync] force requested but no sync_request yet \u2014 ignored");return}this.log.info("[yt-sync] force sync requested (manual)"),await this.tick()}async tick(){if(this.running||!this.request)return;let r=(this.options.resolveProvider??(()=>St({contextDir:this.options.contextDir})))();if(!r.ok){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn(`[yt-sync] tracker provider unavailable (${r.error}) \u2014 poller idle.`));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,r.provider)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let x=e.stageField?{stageField:e.stageField}:{},S=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},R=(e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(R){let b=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[I,D]=await Promise.all([b.length>0?r.listIssues({projectKey:e.projectKey,columns:b,...x,...S}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...x})]),K=new Map;for(let ee of[...I,...D])K.set(ee.id,ee);o=[...K.values()]}else{let b=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:b,...x,...S})}}catch(x){this.log.warn(`[yt-sync] listIssues failed: ${x instanceof Error?x.message:String(x)}`);return}let s=new Map,i=new Set,a=new Set(e.doneColumns??[]);for(let x of o){if(i.add(x.id),a.has(x.status))continue;let S=await dg(r,x.id,e.sinceMs,this.log);S&&s.set(x.id,S)}let c=[];for(let x of e.offBoardIssueIds){if(i.has(x))continue;let S=await dg(r,x,e.sinceMs,this.log);if(S&&S.length>0&&s.set(x,S),e.requireAssignee||S&&S.length>0){let T=await ug(r,x,e.stageField,this.log);if(T)c.push(T);else if(S&&S.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(x=>!a.has(x.status)),{attachmentsByIssue:u,attachmentKeys:p}=await this.collectAttachments(l,s,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:s.get(x.id)??[],attachments:u.get(x.id)??[]}));d.push(...await Ph(this.options.contextDir,d,x=>ug(r,x,e.stageField,this.log)));try{await Xs(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let x of p)this.shippedAttachments.add(x)}catch(x){let S=x instanceof Error?x.message:String(x);this.abandonTick(`context task sync failed: ${S}`);return}let m=this.options.isSelfComment??(()=>!1),f=[],g=[];for(let[x,S]of s){let T=S.filter(b=>!m(b.id));if(T.length===0)continue;f.push({issueId:x,comments:T.map(IE)});let R=T.flatMap(b=>{let I=gr(b.body);return I?[{commentId:b.id,author:b.author,name:I.name,args:I.args,createdAt:b.createdAt}]:[]});R.length>0&&g.push({issueId:x,commands:R})}let h={type:"youtrack_observation",projectId:e.projectId,issues:o.map(lg),commentsBatch:f,...g.length>0?{commandsBatch:g}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(lg)}:{},observedAtMs:n};this.send(h);let w=f.reduce((x,S)=>x+S.comments.length,0),y=g.reduce((x,S)=>x+S.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${w} commands=${y} (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,s=[];for(let i of e){let a=[...i.attachments??[]];for(let u of r.get(i.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let p=`${i.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} (${i.id}) download failed: ${f instanceof Error?f.message:String(f)}`);continue}let m=CE(u.name);l.has(m)&&(m=`${u.id}-${m}`),l.add(m),c.push({name:m,contentBase64:d.toString("base64")}),s.push(p)}c.length>0&&o.set(i.id,c)}return{attachmentsByIssue:o,attachmentKeys:s}}}});import{existsSync as fg,readFileSync as AE,readdirSync as PE}from"node:fs";import{join as mg}from"node:path";import{simpleGit as _E}from"simple-git";import{parse as jE}from"yaml";function pl(t){let e=new Map,r=mg(t,zo);if(!fg(r))return e;let n;try{n=jE(AE(r,"utf-8"))}catch{return e}let o=n?.repos;if(!o||typeof o!="object")return e;for(let[s,i]of Object.entries(o)){if(!i||typeof i!="object")continue;let a=i,c=a.counts??{};typeof a.builtFromCommit=="string"&&e.set(s,{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 NE(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return mr({modelFormatVersion:2,repos:e})}function hg(t,e){let r=mg(t,e);if(!fg(r))return[];let n=[];for(let o of PE(r,{withFileTypes:!0})){let s=`${e}/${o.name}`;o.isDirectory()?n.push(...hg(t,s)):n.push(s)}return n}async function oi(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 hg(t,m))d.emittedShardPaths.has(f)||(n.push({path:f,content:"",deleted:!0}),o++)}let s=pl(t);for(let d of e)s.set(d.repo,{builtFromCommit:d.headCommit,counts:d.counts});n.push({path:zo,content:NE(s)});let i=Gs(t),a=$h(i,r.halfLifeDays??Je.halfLifeDays);n.push({path:ur,content:Hs(a)});for(let d of e){let m=[];for(let f of i)for(let g of f.files)re(g.key)?.repo===d.repo&&m.push({kind:"touched_by",from:ke(f.taskKey),to:g.key,...g.churn!==void 0?{weight:g.churn}:{}});n.push({path:Ji(d.repo),content:pr({modelFormatVersion:2,repo:d.repo,builtFromCommit:d.headCommit,edges:m})})}let c=_E(t),l=(await c.revparse(["HEAD"]).catch(()=>"")).trim(),u=`model: build ${e.map(d=>`${d.repo}@${d.headCommit.slice(0,10)}`).join(", ")}`;await Se(t,n,u);let p=(await c.revparse(["HEAD"]).catch(()=>"")).trim();if(p!==l){let{rebuildSearchIndex:d}=await Promise.resolve().then(()=>(To(),Ro));await d(t).catch(()=>{})}return{committed:p!==l,filesWritten:n.filter(d=>!d.deleted).length,filesDeleted:o}}var gg=$(()=>{"use strict";F();Jc();tt()});var ii={};Be(ii,{bootstrapDaemonModel:()=>LE,bootstrapModelForTargets:()=>wl,bootstrapWorkspaceModel:()=>$g,modelBootstrapCommand:()=>kl,modelBuildCommand:()=>yl,rebuildWorkspaceModelIfStale:()=>DE});import{existsSync as hl}from"node:fs";import{join as gn}from"node:path";import{cancel as OE,intro as yg,log as fl,outro as ml}from"@clack/prompts";import{simpleGit as gl}from"simple-git";function si(t){OE(t),process.exit(1)}function kg(t,e,r){let n=t.spec.repos.filter(s=>!e||s.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 s of n){let i=s.mountAs==="."?t.root:gn(t.root,s.mountAs);if(!hl(gn(i,".git"))){r(`${s.name}: no local clone at ${i} \u2014 skipped (run \`codepipe clone\` first)`);continue}o.push({name:s.name,dir:i,defaultBranch:s.defaultBranch||"main"})}if(o.length===0)throw new Error("nothing to do \u2014 no repo clones found");return o}async function wg(t){let e=gl(t.dir),r=`origin/${t.defaultBranch}`;return await e.raw(["rev-parse","--verify",r]).then(()=>!0).catch(()=>!1)?r:"HEAD"}async function bg(t,e,r,n){let o=[];for(let s of e)try{let i=await Vc({repo:s.name,repoDir:s.dir,contextDir:t,settings:r,ref:await wg(s)});o.push(i),n(`${s.name}: ${i.counts.code} files, ${i.counts.component} components, ${i.counts.correlates} co-change edges @ ${i.headCommit.slice(0,10)}`)}catch(i){throw new Error(`${s.name}: ${i instanceof Error?i.message:String(i)}`)}return o}async function yl(t){yg("codepipe model build");let e=Te();e||si("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{let r=pn(e.contextDir),n=kg(e,t.repo,i=>fl.warn(i)),o=await bg(e.contextDir,n,r,i=>fl.info(i)),s=await oi(e.contextDir,o,{halfLifeDays:r.cochange.halfLifeDays});s.committed?ml(`model updated: ${s.filesWritten} files written, ${s.filesDeleted} stale removed`):ml("model already up to date (no changes)")}catch(r){si(r instanceof Error?r.message:String(r))}}async function kl(t){yg("codepipe model bootstrap");let e=Te();e||si("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{await $g(e,t.repo,{onLog:r=>fl.info(r)})}catch(r){si(r instanceof Error?r.message:String(r))}ml("bootstrap complete")}async function $g(t,e,r){let n=kg(t,e,r.onLog);return wl(t.contextDir,n,r)}async function wl(t,e,r){let n=pn(t),o=await bg(t,e,n,r.onLog),s=Wm(t),i=Hm(n.issueKeyPattern,s),a=Pr([...n.ignore,...dn]),c=[];for(let p of o){let d=e.find(f=>f.name===p.repo),m=await Ym({repo:p.repo,repoDir:d.dir,headCommit:p.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:i,pathToCurrent:Bs(p.identityTable),entityByKey:p.entityByKey,ignored:a,trackerProjectKey:s});c.push(m),r.onLog(`${p.repo}: ${m.size} task events mined from history`)}let{files:l,skippedPipeline:u}=Vm(t,c);return u>0&&r.onLog(`${u} events already recorded by the live pipeline \u2014 left untouched`),l.length>0&&await Se(t,l,`model: bootstrap ${l.length} task events from history`),await oi(t,o,{halfLifeDays:n.cochange.halfLifeDays}),{events:l.length}}async function LE(t,e,r,n){if(r.length===0)throw new Error("the project has no repos configured");let o=[];for(let i of r){let a=i.mountAs??i.name,c=a==="."?e.root:gn(e.root,a),l=i.defaultBranch||"main";c!==e.contextDir&&hl(gn(c,".git"))?(await gl(c).fetch(["origin",l]).catch(()=>{}),o.push({name:i.name,dir:c,defaultBranch:l})):(n(`${i.name}: materializing clone in the daemon layout`),await Nt(t,i),o.push({name:i.name,dir:Ie(t,i.name),defaultBranch:l}))}let s=await wl(e.contextDir,o,{onLog:n});return{repos:o.length,events:s.events}}async function DE(t,e={}){let r=e.onLog??(()=>{}),n=pn(t.contextDir);if(!n.enabled)return{rebuilt:[],skipped:[]};let o=[],s=[],i=pl(t.contextDir),a=[];for(let c of t.repos){let l=c.mountAs==="."?t.root:gn(t.root,c.mountAs);if(!hl(gn(l,".git")))continue;let u=gl(l),p=c.defaultBranch||"main";e.fetch&&await u.fetch(["origin",p]).catch(()=>{});let d=await wg({name:c.name,dir:l,defaultBranch:p}),m=(await u.revparse([d]).catch(()=>"")).trim();if(m){if(i.get(c.name)?.builtFromCommit===m){s.push(c.name);continue}try{a.push(await Vc({repo:c.name,repoDir:l,contextDir:t.contextDir,settings:n,ref:m})),o.push(c.name)}catch(f){r(`[model] rebuild of ${c.name} failed: ${f instanceof Error?f.message:String(f)}`)}}}return a.length>0&&(await oi(t.contextDir,a,{halfLifeDays:n.cochange.halfLifeDays}),r(`[model] release-path rebuild: ${o.join(", ")} (skipped up-to-date: ${s.join(", ")||"\u2014"})`)),{rebuilt:o,skipped:s}}var Po=$(()=>{"use strict";tt();gg();zc();qc();Fs();Eo();Er();bt()});var xg={};Be(xg,{computeDriftReport:()=>KE,supersededAdrIds:()=>vg});import{existsSync as bl,readFileSync as $l,readdirSync as vl}from"node:fs";import{join as yn}from"node:path";import{parse as ME}from"yaml";import{simpleGit as UE}from"simple-git";function FE(t,e){let r=yn(t,`model/derived/structure/${e}`),n=[],o="";if(!bl(r))return{nodes:n,builtFromCommit:o};for(let s of vl(r).sort()){if(!s.endsWith(".yaml"))continue;let i;try{let a=Ct(ME($l(yn(r,s),"utf-8")));if(!a.ok)continue;i=a.value}catch{continue}o=i.builtFromCommit;for(let a of i.nodes){let c=re(a.key);!c||c.level!=="code"&&c.level!=="component"||n.push({key:a.key,path:c.path,level:c.level,contentHash:a.contentHash,entityId:a.entityId})}}return{nodes:n,builtFromCommit:o}}function vg(t){let e=new Set,r=yn(t,"adr");if(!bl(r))return e;for(let n of vl(r).sort()){let o=/^(\d{4})-/.exec(n)?.[1];if(!(!o||!n.endsWith(".md")))try{let s=$l(yn(r,n),"utf-8").slice(0,600).toLowerCase();/status[^\n]*superseded/.test(s)&&e.add(`ADR-${o}`)}catch{}}return e}async function KE(t,e,r){let{nodes:n,builtFromCommit:o}=FE(e,r),s=(await UE(t).revparse(["HEAD"])).trim(),i=await So(t,s),a=new Map(i.map(y=>[y.path,y.blobHash])),c=[],l=[],u=new Set,p=[];for(let y of n){if(y.level==="component"){p.push(y);continue}u.add(y.path);let x=a.get(y.path);x?y.contentHash&&x.slice(0,BE)!==y.contentHash&&c.push(y.key):l.push(y.key)}let d=0,m=new Map,f=new Set;for(let y of i){let x=y.path.lastIndexOf("/"),S=x<0?"":y.path.slice(0,x);m.has(S)||m.set(S,new Set),m.get(S).add(y.path),u.has(y.path)||d++;let T=S;for(;T!==""&&!f.has(T);)f.add(T),T=T.includes("/")?T.slice(0,T.lastIndexOf("/")):""}let g=new Map;for(let y of u){let x=y.lastIndexOf("/"),S=x<0?"":y.slice(0,x);g.has(S)||g.set(S,new Set),g.get(S).add(y)}for(let y of p){if(!f.has(y.path)){l.push(y.key);continue}let x=g.get(y.path)??new Set,S=m.get(y.path)??new Set;(x.size!==S.size||[...x].some(R=>!S.has(R)))&&c.push(y.key)}let h=[],w=vg(e);if(w.size>0){let y=yn(e,"model/facts/annotations"),x=new Map(n.filter(S=>S.entityId).map(S=>[S.entityId,S.key]));if(bl(y))for(let S of vl(y).sort()){if(!S.endsWith(".md"))continue;let T=S.replace(/\.md$/,""),R=x.get(T);if(R)try{($l(yn(y,S),"utf-8").match(/\bADR-(\d{3,4})\b/g)??[]).map(D=>`ADR-${D.slice(4).padStart(4,"0")}`).some(D=>w.has(D))&&h.push(R)}catch{}}}return{repo:r,builtFromCommit:o,headCommit:s,stale:[...new Set(c)].sort(),orphaned:[...new Set(l)].sort(),superseded:[...new Set(h)].sort(),newFiles:d}}var BE,Sg=$(()=>{"use strict";F();Eo();BE=12});import{existsSync as Rg,rmSync as GE}from"node:fs";import{join as _r}from"node:path";import{simpleGit as HE}from"simple-git";import"ws";function ai(t,e={}){let r=e.log??{info:h=>console.log(h),warn:h=>console.warn(h)};r.info(`codepipe-cli v${Fe} (protocol ${at})`);let n=h=>e.onEvent?.(h),o=e.workspace;o?.contextDir&&Mf(o.contextDir,r);let s=Eg("CLI_TRACKING_POLL_INTERVAL_SEC"),i=Eg("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let h=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(h)&&h>0?h*1e3:6e5})(),c=!1,l=!1,u=!1,p=new Set,d=!1,m=new Set,f=g();function g(){let h=ks(t.hubUrl,t.cliToken),w=null,y=new ri(s,_=>{h.readyState===h.OPEN&&h.send(JSON.stringify(_))},r),x=new ni(i,_=>{h.readyState===h.OPEN&&h.send(JSON.stringify(_))},r,{contextDir:o?.contextDir??null,isSelfComment:_=>m.has(_)}),S=null,T=async()=>{try{let _={trackerProvider:il(o?.contextDir??null)};try{let L=await oe(t.hubUrl,t.cliToken,t.projectId);_={..._,repos:L.repos,contextRepo:L.contextRepo}}catch(L){r.warn(`[readiness] could not fetch project summary for push checks: ${L instanceof Error?L.message:String(L)}`)}let B=await Gp(t.projectId,_);if(h.readyState!==h.OPEN)return;let O={type:"cli_readiness",projectId:t.projectId,ready:B.ready,checks:B.checks,creds:B.creds,secretNames:ep(t.projectId),checkedAt:B.checkedAt};if(h.send(JSON.stringify(O)),B.ready)r.info("[readiness] ready");else{let L=B.checks.filter(E=>!E.ok).map(E=>`${E.name}(${E.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${L.join(", ")}`)}let X=Xp(B.creds,u);if(X==="open"){u=!0;let L=Jp(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${L}`),$r(L)}else X==="rearm"&&(u=!1)}catch(_){r.warn(`[readiness] check failed: ${_ instanceof Error?_.message:String(_)}`)}},R=()=>{T(),S=setInterval(()=>void T(),a),typeof S.unref=="function"&&S.unref()},b=()=>{S&&(clearInterval(S),S=null)},I=150,D=new Map,K=_=>{let B=D.get(_);if(!B||(B.timer&&clearTimeout(B.timer),D.delete(_),B.events.length===0||h.readyState!==h.OPEN))return;let O={type:"run_activity",projectId:t.projectId,runId:_,events:B.events};h.send(JSON.stringify(O))},ee=(_,B)=>{let O=D.get(_);if(O||(O={events:[],timer:null},D.set(_,O)),O.events.push(B),B.kind==="result"){K(_);return}O.timer||(O.timer=setTimeout(()=>K(_),I),O.timer.unref?.())},C=o?.contextDir?new Ts(o.contextDir,t.projectId,_=>{h.readyState===h.OPEN&&h.send(JSON.stringify(_))},r):null,k=async()=>{let _=o?.contextDir;if(!_)throw new Error("no context repo clone on this CLI");let B;try{B=(await oe(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let O=await cm(_,t.projectId,B,r);return h.readyState===h.OPEN&&h.send(JSON.stringify(O)),O},U=null,P=async()=>{let _=o?.contextDir;if(_)try{let{readContextIndexHub:B,collectSearchRows:O}=await Promise.resolve().then(()=>(To(),Ro));if(B(_)!=="metadata")return;let X=O(_);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)}`)}},G=()=>{U&&clearTimeout(U),U=setTimeout(()=>void P(),5e3)},Y=null,se=async _=>{if(o?.contextDir)try{let{rebuildWorkspaceModelIfStale:B}=await Promise.resolve().then(()=>(Po(),ii));(await B({root:o.root,contextDir:o.contextDir,repos:o.repos},{fetch:_,onLog:X=>r.info(X)})).rebuilt.length>0&&G()}catch(B){r.warn(`[model] release-path rebuild failed (non-fatal): ${B instanceof Error?B.message:String(B)}`)}},qe=_=>{Y&&clearTimeout(Y),Y=setTimeout(()=>void se(_),6e4)},Ye=setInterval(()=>void se(!0),6*36e5);return h.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let _=cp(t.projectId),B=J("ORIGIN")==="farm"?"farm":"local",O=J("FARM_ID"),X=t.accountEmail??_.email,L;try{let v=bm(t.projectId);v&&(L=v.publicKey,r.info(`[cred-channel] key fingerprint: ${v.fingerprint}`))}catch(v){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${v instanceof Error?v.message:String(v)}`)}let E={type:"register",projectId:t.projectId,platformVersion:Fe,protocolVersion:at,accountId:_.accountId,accountLabel:_.label,origin:B,inFlightActionIds:[...p],...X?{accountEmail:X}:{},...B==="farm"&&O?{farmId:O}:{},...L?{sealPublicKey:L}:{}};h.send(JSON.stringify(E))}),h.on("message",async _=>{let B=_.toString("utf-8");if(B==="pong"||B==="ping")return;let O;try{O=JSON.parse(B)}catch{return}if(!O||typeof O!="object")return;let X=O.type;if(X==="registered"){let E=O;if(E.ok){if(r.info(`[ws] registered for project ${E.projectId}`),n({kind:"registered",projectId:E.projectId??t.projectId}),y.start(),C?.start(),R(),Sl(t,o,r),o?.contextDir){try{let v=_s(o.contextDir,t.projectId);h.readyState===h.OPEN&&h.send(JSON.stringify(v)),v.outdated&&(r.warn(`[ctx] context format outdated: v${v.templateVersion} \u2192 v${v.currentVersion}`+(v.missingPaths.length>0?` (missing: ${v.missingPaths.join(", ")})`:"")),l||(l=!0,k().catch(()=>{})))}catch(v){r.warn(`[ctx] context-format detect failed (non-fatal): ${v instanceof Error?v.message:String(v)}`)}P(),qe(!0)}}else r.warn(`[ws] register rejected: ${E.reason??"unknown"}`),n({kind:"register_rejected",reason:E.reason??"unknown"}),c=!0,h.close();return}if(X==="hello"){let E=O;w=Vn(E.protocolVersion);let v=w?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${E.platformVersion} (protocol ${E.protocolVersion}) \u2014 ${v}`),w||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Fe}, protocol ${at}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${xl}`),n({kind:"incompatible",hubVersion:typeof E.platformVersion=="string"?E.platformVersion:null,hubProtocol:typeof E.protocolVersion=="number"?E.protocolVersion:null,updateCommand:xl}));return}if(X==="tracking_targets"){y.setTargets(O.targets);return}if(X==="youtrack_sync_request"){x.setRequest(O);return}if(X==="youtrack_force_sync"){x.forceSync();return}if(X==="sync_local"){await YE(O,o,h,r);return}if(X==="provision_repo"){let E=O;r.info(`[repo] provision_repo: ${E.repo.name} (${E.repo.host}:${E.repo.owner}/${E.repo.repoName})`),await WE(t,o,E.repo,r),await Sl(t,o,r);return}if(X==="remove_repo"){let E=O;r.info(`[repo] remove_repo: ${E.repoName}${E.purge?" (purge)":""}`),await Sl(t,o,r),E.purge&&qE(t,o,E.repoName,r);return}if(X==="context_write"){await VE(O,o,h,r);return}if(X==="adr_promote"){await zE(O,o,h,r);return}if(X==="cred_update"){let E=O,v=q(t.projectId),N=v?.sealKey?await $m(t.projectId,E.kind,E.sealed,v.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},z={type:"cred_update_result",updateId:E.updateId,projectId:t.projectId,ok:N.ok,...N.detail?{detail:N.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(z)),N.ok?(r.info(`[cred] ${E.kind} replaced${N.detail?` \u2014 ${N.detail}`:""}`),T()):r.warn(`[cred] ${E.kind} replacement rejected: ${N.detail??"unknown"}`);return}if(X==="readiness_check"){r.info("[readiness] on-demand check requested"),T();return}if(X==="agent_login_start"){Vp(t,h,O,r,T);return}if(X==="move_to_farm"){let E=O;r.info(`[farm-move] request to move ${t.projectId} onto farm ${E.farmName} (${E.farmId})`);let v=await qh(t,E,o?.contextDir,r);h.readyState===h.OPEN&&h.send(JSON.stringify(v)),v.ok?r.info(`[farm-move] done \u2014 farm daemon ${v.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${v.error??"unknown error"}`);return}if(X==="gh_runner_setup"){let E=O;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${E.runnerName} (${E.runnerId})`);let v=await tg(t,E,r);h.readyState===h.OPEN&&h.send(JSON.stringify(v)),v.ok?r.info(`[ghr] runners connected on ${E.runnerName}`):r.warn(`[ghr] setup failed: ${v.error??"see per-repo statuses"}`);return}if(X==="gh_runner_teardown"){let E=O;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${E.runnerName} (${E.runnerId})`);let v=await rg(t,E,r);h.readyState===h.OPEN&&h.send(JSON.stringify(v)),v.ok?r.info(`[ghr] runners disconnected from ${E.runnerName}`):r.warn(`[ghr] teardown failed: ${v.error??"unknown error"}`);return}if(X==="tracker_fields_request"){let E=O,v={type:"tracker_fields_result",requestId:E.requestId,projectId:t.projectId,ok:!1},N=St({contextDir:o?.contextDir??null});if(!N.ok)v.error=N.error;else try{v.fields=await N.provider.fetchStateFields(E.projectKey),v.ok=!0}catch(z){v.error=z instanceof Error?z.message:String(z)}h.readyState===h.OPEN&&h.send(JSON.stringify(v)),v.ok||r.warn(`[yt-fields] listing failed: ${v.error??"unknown"}`);return}if(X==="project_secret_update"||X==="project_secret_delete"){let E=O,v;if(E.type==="project_secret_update"){let z=q(t.projectId);v=z?.sealKey?sg(t.projectId,E.name,E.sealed,z.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else v=ig(t.projectId,E.name);let N={type:"project_secret_update_result",updateId:E.updateId,projectId:t.projectId,ok:v.ok,...v.detail?{detail:v.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(N)),v.ok?(r.info(`[secret] ${E.name} ${E.type==="project_secret_update"?"saved":"deleted"}`+(v.detail?` \u2014 ${v.detail}`:"")),T()):r.warn(`[secret] ${E.name} rejected: ${v.detail??"unknown"}`);return}if(X==="auto_apply_local"){let E=O;if(!o?.contextDir){r.warn(`[apply] auto_apply_local for ${E.claim.taskKey} \u2014 no workspace (headless), skipped; task stays in READY_TO_APPLY`);return}let v=await Tf({hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId,root:o.root,contextDir:o.contextDir,repos:o.repos},E.claim,r).catch(N=>({ok:!1,message:N instanceof Error?N.message:String(N)}));v.ok?r.info(`[apply] ${E.claim.taskKey}: ${v.message}`):r.warn(`[apply] ${E.claim.taskKey}: ${v.message} \u2014 task stays in READY_TO_APPLY`),n({kind:"local_applied",taskKey:E.claim.taskKey,ok:v.ok,...v.ok?{branches:v.branches??[]}:{error:v.message}});return}if(X==="sandbox_keys"){let E=q(t.projectId);if(!E){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let v=Zr(t.projectId),N=hm(O,E,v,r);for(let z of N)h.readyState===h.OPEN&&h.send(JSON.stringify(z));return}if(X!=="dispatch_action")return;let L=O;if(w===!1){let E=`refused: HUB protocol incompatible with CLI v${Fe} (protocol ${at})`;h.send(JSON.stringify({type:"action_result",actionId:L.actionId,status:"failed",error:E})),r.warn(`[exec] ${L.actionId} (${L.action.type}) \u2192 REFUSED: ${E}`),r.warn(`[exec] update the CLI to clear this: ${xl}`),n({kind:"action",actionId:L.actionId,actionType:L.action.type,ok:!1,error:E});return}if(L.action.type==="model_drift"){p.add(L.actionId);try{let E,v=o?.repos.find(N=>N.name===L.action.repoName);if(!o?.contextDir||!v)E={status:"failed",error:"no local workspace/repo clone on this CLI"};else try{let{computeDriftReport:N}=await Promise.resolve().then(()=>(Sg(),xg)),z=v.mountAs==="."?o.root:_r(o.root,v.mountAs);E={status:"done",result:{report:await N(z,o.contextDir,v.name)}}}catch(N){E={status:"failed",error:N instanceof Error?N.message:String(N)}}h.send(JSON.stringify({type:"action_result",actionId:L.actionId,...E}))}finally{p.delete(L.actionId)}return}if(L.action.type==="model_bootstrap"){p.add(L.actionId);try{let E;if(!o?.contextDir)E={status:"failed",error:"no Context Repo clone on this CLI"};else if(d)E={status:"failed",error:"model bootstrap is already running"};else{d=!0;try{let v=await oe(t.hubUrl,t.cliToken,t.projectId),{bootstrapDaemonModel:N}=await Promise.resolve().then(()=>(Po(),ii)),z=await N(t.projectId,{root:o.root,contextDir:o.contextDir},v.repos,ve=>r.info(`[model] ${ve}`));r.info(`[model] bootstrap done: ${z.repos} repos, ${z.events} task events`),G(),E={status:"done",result:{repos:z.repos,events:z.events}}}catch(v){E={status:"failed",error:v instanceof Error?v.message:String(v)},r.warn(`[model] bootstrap failed: ${E.error}`)}finally{d=!1}}h.readyState===h.OPEN&&h.send(JSON.stringify({type:"action_result",actionId:L.actionId,...E}))}finally{p.delete(L.actionId)}return}if(L.action.type==="local_apply"){p.add(L.actionId);try{let E;if(!o)E={status:"failed",error:"no local workspace on this CLI"};else{let N=await Bh(o,L.action.repos,r);if(E=N.ok?{status:"done",result:{repos:N.repos}}:{status:"failed",error:N.error},N.ok&&o.contextDir){let z=L.action.taskId.split(":")[1]??"";for(let ve of z?N.repos:[]){let ot=o.repos.find(ne=>ne.name===ve.repoName);if(!ot)continue;let{recordPipelineEvent:W}=await Promise.resolve().then(()=>(rl(),Ah));await W({contextDir:o.contextDir,repoDir:_r(o.root,ot.mountAs),repoName:ve.repoName,taskKey:z,commitSha:ve.commit}).catch(ne=>r.warn(`[model] task event for ${z} failed: ${ne instanceof Error?ne.message:String(ne)}`))}G()}}h.send(JSON.stringify({type:"action_result",actionId:L.actionId,...E}));let v=E.status!=="failed";v?r.info(`[exec] ${L.actionId} (local_apply) \u2192 done`):r.warn(`[exec] ${L.actionId} (local_apply) \u2192 FAILED: ${E.status==="failed"?E.error:"?"}`),n({kind:"action",actionId:L.actionId,actionType:"local_apply",ok:v,...E.status==="failed"?{error:E.error}:{}})}finally{p.delete(L.actionId)}return}p.add(L.actionId);try{let E=await Dh({action:L.action,repo:L.repo,trackerIssueId:L.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:C?()=>C.reportNow():void 0,refreshContextStatus:o?.contextDir?k:void 0,onRunActivity:ee}).catch(z=>({status:"failed",error:z instanceof Error?z.message:String(z)}));L.action.type==="tracker_comment"&&E.status==="done"&&"result"in E&&typeof E.result?.commentId=="string"&&m.add(E.result.commentId),h.send(JSON.stringify({type:"action_result",actionId:L.actionId,...E}));let v=E.status!=="failed",N=!v&&"error"in E?E.error:void 0;v?r.info(`[exec] ${L.actionId} (${L.action.type}) \u2192 done`):r.warn(`[exec] ${L.actionId} (${L.action.type}) \u2192 FAILED: ${N??"?"}`),n({kind:"action",actionId:L.actionId,actionType:L.action.type,ok:v,...N?{error:N}:{}}),v&&["apply_delivery","context_write","create_pr"].includes(L.action.type)&&G(),v&&["merge_pr","merge_branch"].includes(L.action.type)&&qe(!0)}finally{p.delete(L.actionId)}}),h.on("close",(_,B)=>{let O=B?.toString("utf-8")??"";if(r.info(`[ws] closed code=${_}${O?` reason=${O}`:""}`),y.stop(),x.stop(),C?.stop(),b(),clearInterval(Ye),Y&&clearTimeout(Y),U&&clearTimeout(U),O==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:_}),!c&&setTimeout(()=>{f=g()},2e3)}),h.on("error",_=>r.warn(`[ws] error: ${_.message}`)),h}return{stop(){c=!0,f.close()}}}async function Sl(t,e,r){try{let n=await oe(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:s}=bo(t.projectId,n.repos,e?.contextDir);for(let i of o)r.info(`[repo] restaged repo set in ${i}`);for(let i of s)r.warn(`[repo] could not restage ${i.path}: ${i.error}`)}catch(n){r.warn(`[repo] repo-set reconcile skipped: ${n instanceof Error?n.message:String(n)}`)}}async function WE(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 s=e?_r(e.root,o):Ie(t.projectId,r.name);if(Rg(_r(s,".git"))){n.info(`[repo] ${r.name} already present at ${s}`);return}try{await HE().clone(mo(r),s),n.info(`[repo] cloned ${r.name} \u2192 ${s}`)}catch(i){n.warn(`[repo] clone of ${r.name} failed (will retry lazily): ${i instanceof Error?i.message.trim():String(i)}`)}}function qE(t,e,r,n){let o=e?.repos.find(i=>i.name===r)?.mountAs??r,s=e?_r(e.root,o):Ie(t.projectId,r);if(e&&s===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Rg(_r(s,".git"))){n.info(`[repo] no local clone to purge for ${r} (${s})`);return}try{GE(s,{recursive:!0,force:!0}),n.info(`[repo] purged local clone ${s}`)}catch(i){n.warn(`[repo] purge of ${s} failed: ${i instanceof Error?i.message:String(i)}`)}}async function YE(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 s=e.repos.find(l=>l.name===o.repoName),i=_r(e.root,s?.mountAs??o.repoName),a=s?.defaultBranch??o.defaultBranch,c=await Cf(i,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 VE(t,e,r,n){let o=(s,i)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:s};i&&(a.error=i),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{await Se(e.contextDir,t.files,t.message),n.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),o("done")}catch(s){let i=s instanceof Error?s.message:String(s);n.warn(`[ctx] context_write ${t.id} failed: ${i}`),o("failed",i)}}async function zE(t,e,r,n){let o=(s,i)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:s};i&&(a.error=i),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 s=t.source??"task",i=await Wf(e.contextDir,t.taskKey,t.slugs,void 0,s);if(n.info(`[adr] adr_promote ${t.id}: promoted ${i.promoted.length}, skipped ${i.skipped.length}`+(i.promoted.length>0?` (${i.promoted.join(", ")})`:"")),i.missing.length>0){let a=l=>s==="staging"?`adr/DRAFT-${l}.md`:`tasks/${t.taskKey}/adr/DRAFT-${l}.md`,c=`draft file(s) missing in clone: ${i.missing.map(a).join(", ")}`;n.warn(`[adr] adr_promote ${t.id}: ${c}`),o("failed",c);return}o("done")}catch(s){let i=s instanceof Error?s.message:String(s);n.warn(`[adr] adr_promote ${t.id} failed: ${i}`),o("failed",i)}}function Eg(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}var xl,El=$(()=>{"use strict";Le();F();lp();zp();Zp();ys();gc();Af();Lf();qf();tt();Ot();Ic();lm();jc();Er();gm();vm();Mh();Fh();Yh();ng();Ae();ag();rn();pe();cg();pg();Zs();xl="npm i -g @code-partner/codepipe@latest"});import{execFileSync as XE}from"node:child_process";import{mkdtempSync as JE,mkdirSync as ZE,readFileSync as Tg,rmSync as QE,writeFileSync as eR}from"node:fs";import{tmpdir as tR}from"node:os";import{dirname as rR,join as Ig}from"node:path";function Cg(t="codepipe-context"){let e=JE(Ig(tR(),"codepipe-ssh-")),r=Ig(e,"id_ed25519");try{return XE("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Tg(r,"utf-8"),publicKey:Tg(`${r}.pub`,"utf-8").trim()}}finally{QE(e,{recursive:!0,force:!0})}}async function Ag(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 s=await o.text();if(!(o.status===422&&/already in use/i.test(s)))throw new Error(`add deploy key failed: ${o.status} ${s}`)}function Pg(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 _g(t,e){ZE(rR(t),{recursive:!0});let r=e.endsWith(`
667
743
  `)?e:e+`
668
- `;return rS(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var Ec=v(()=>{"use strict"});import{existsSync as Ag,mkdirSync as Pg}from"node:fs";import{dirname as _g}from"node:path";import{simpleGit as on}from"simple-git";function iS(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 sS(t,e){return e?.contextWrite?.token?{user:Fo(t),secret:e.contextWrite.token}:t===Fn.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Fn.bitbucket?e?.bitbucket?.apiToken?{user:sr,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function jg(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 Yi))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 Vi(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await ne(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new Yi(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=sS(Dr(s.cloneUrl),r);if(a){let c=await aS({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 cS({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 aS(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=iS(e.cloneUrl,n.secret,n.user),s=e.branch,a=encodeURIComponent(n.secret),c=l=>l.split(n.secret).join("***").split(a).join("***");try{if(Ag(`${r}/.git`)){let l=on(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=$a(r);await l.reset(["--hard",`origin/${s}`]),va(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Pg(_g(r),{recursive:!0}),await on().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await Ng(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 cS(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=Cg(i,n),a=Rg(e.cloneUrl),c=e.branch;try{if(Ag(`${r}/.git`)){let l=on(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=$a(r);await l.reset(["--hard",`origin/${c}`]),va(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Pg(_g(r),{recursive:!0}),await on().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await on(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await Ng(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 Ng(t){let e=on(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 Yi,Ic=v(()=>{"use strict";G();Ie();St();Ec();Yi=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as lS}from"node:child_process";function uS(){try{return lS("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function Lg(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:uS(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var Dg=v(()=>{"use strict"});import{homedir as sn}from"node:os";import{mkdirSync as dS,readFileSync as Mg,writeFileSync as pS,existsSync as Cc}from"node:fs";import{dirname as fS,join as Ht}from"node:path";function mS(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function ot(t){let e=V("SANDBOX_CONFIG");if(e)return e;let r=Ht(sn(),".codepipe","worker");return t?Ht(r,"profiles",t,"config.json"):Ht(r,"config.json")}function Ug(){return Ht(sn(),".devpipe-sandbox","config.json")}function zi(){ar(Ht(sn(),".devpipe"),Ht(sn(),".codepipe")),V("SANDBOX_CONFIG")||ar(Ht(sn(),".devpipe-sandbox"),Ht(sn(),".codepipe-sandbox"))}function Bg(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function Ae(t){let e=ot(t),r=null;return Cc(e)?r=JSON.parse(Mg(e,"utf-8")):!t&&!V("SANDBOX_CONFIG")&&Cc(Ug())&&(r=JSON.parse(Mg(Ug(),"utf-8"))),r?(r.planningLane=mS(),r):null}function Fg(t,e){let r=ot(e);dS(fS(r),{recursive:!0}),pS(r,JSON.stringify(t,null,2)+`
669
- `,{mode:384})}var Xi=v(()=>{"use strict";_e();Go();Cc(".env")&&process.loadEnvFile(".env")});import gS from"ws";var an,Ac=v(()=>{"use strict";an=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 gS(e)}}});import{hostname as hS}from"node:os";async function vr(t){zi();let e=Ae(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${ot(t.profile)}.`),process.exit(1));let r=t.name??hS(),n=Lg({projects:t.projects??[],llm:t.llm??null}),o=new an(t.hub.replace(/\/$/,"")),i=bi(),s=je(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});Fg({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 ${ot(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 Gg=v(()=>{"use strict";We();Dg();Xi();Ac()});function Kg(t){return t?`Write ALL user-visible text \u2014 full replies and the brief status notes you emit between tool calls alike \u2014 in ${t}, regardless of the language the user writes in (the project pinned ${t} for the chat).`:"Write ALL user-visible text \u2014 full replies and the brief status notes you emit between tool calls alike \u2014 in the language of the user's most recent chat message. When the user switches language mid-conversation, switch with them. Judge the language by the human prose only: ignore code snippets, file paths and identifiers. If a message is too short to tell (a bare keyword, pure code), keep the language of the conversation so far."}function Ji(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 Hg(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 cn(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 Qi=v(()=>{"use strict"});import{spawn as yS}from"node:child_process";function Pc(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function wS(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 bS(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function xr(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function _c(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}})+`
670
- `}async function Vg(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Et;let r=cn(e.metadata),n=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",Kg(r)];e.model&&e.model.trim().length>0&&n.push("--model",e.model.trim());for(let l of e.addDirs??[])n.push("--add-dir",l);let o=e.onActivity,i=l=>{if(o)try{o(l)}catch{}},s=[],a=null,c=l=>{let u=Date.now(),p=l.type;if(p==="assistant"){let d=l.message;for(let f of d?.content??[]){let m=f.type;if(m==="text"){let h=String(f.text??"").trim();h&&i({ts:u,kind:"text",author:"agent",text:Pc(h,Wg)})}else if(m==="tool_use"){let h=String(f.name??""),g=f.input?.file_path??f.input?.path,w=wS(g,e.workspaceDir);i({ts:u,kind:"tool",author:"agent",tool:h,...w?{file:w}:{}})}}return}if(p==="user"){let d=l.message;for(let f of d?.content??[])if(f.type==="tool_result"){let m=f.is_error===!0,h=m?Pc(bS(f.content),200):"";i({ts:u,kind:"tool_result",author:"agent",isError:m,...h?{text:h}:{}})}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=yS(t,n,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});p.stdout.setEncoding("utf-8"),p.stderr.setEncoding("utf-8");let d=!1,f=!1,m=null,h=()=>{d=!0,p.kill("SIGTERM"),m=setTimeout(()=>p.kill("SIGKILL"),qg)};e.signal?.addEventListener("abort",h,{once:!0});let g=null,w=()=>{g&&clearTimeout(g),g=setTimeout(()=>{f=!0,console.warn(`[claude:chat] idle for ${Yg}ms \u2014 ending session`),p.kill("SIGTERM"),m=setTimeout(()=>p.kill("SIGKILL"),qg)},Yg)},y=()=>{m&&clearTimeout(m),g&&clearTimeout(g),e.signal?.removeEventListener("abort",h)},x=!0,T=b=>{if(!(!x||p.stdin.destroyed))try{p.stdin.write(b)}catch{}};T(_c(e.prompt)),w(),(async()=>{try{for await(let b of e.interactive.inbox){if(d||!x)break;if(w(),b.kind==="user")i({ts:Date.now(),kind:"text",author:"user",text:Pc(b.text,Wg)}),T(_c(b.text,Hg(r)));else{T(_c(kS)),x=!1;try{p.stdin.end()}catch{}break}}}catch{}})();let I="",E=b=>{let R;try{R=JSON.parse(b)}catch{return}c(R)};p.stdout.on("data",b=>{s.push(b),w(),I+=b;let R;for(;(R=I.indexOf(`
671
- `))!==-1;){let N=I.slice(0,R).trim();I=I.slice(R+1),N&&E(N)}}),p.stderr.on("data",b=>{s.push(b);for(let R of b.split(`
672
- `)){let N=R.trim();N&&console.warn(`[claude:chat:stderr] ${N}`)}}),p.on("error",b=>{y(),u(b)}),p.on("close",b=>{if(y(),d){u(new Et);return}if(f){u(new Error("chat session ended: idle for too long without a reply"));return}I.trim()&&E(I.trim()),console.log(`[claude:chat] exit code=${b}`),l({artifactPaths:[],log:s.join(""),usage:$S(a)})})})}function $S(t){let e=rr();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=xr(r.input_tokens),e.outputTokens=xr(r.output_tokens),e.cacheReadInputTokens=xr(r.cache_read_input_tokens),e.cacheCreationInputTokens=xr(r.cache_creation_input_tokens)),e.totalCostUsd=xr(t.total_cost_usd),e.numTurns=xr(t.num_turns),e.durationMs=xr(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var Wg,qg,Yg,kS,zg=v(()=>{"use strict";G();ln();Qi();Wg=16e3,qg=5e3,Yg=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),kS="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 vS}from"node:child_process";import{existsSync as xS}from"node:fs";function TS(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function Xg(t){let e;try{e=JSON.parse(t)}catch{return console.log(`[claude] ${t.slice(0,200)}`),null}let r=e.type;if(r==="system"){let n=e.subtype??"";return console.log(`[claude] system ${n}`),e}if(r==="assistant"){let n=e.message;for(let o of n?.content??[]){let i=o.type;if(i==="text"){let s=String(o.text??"").trim();s&&console.log(`[claude] text: ${Wt(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=RS(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=Qg(o.content);console.log(`[claude] tool_result (error)${i?`: ${Wt(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)} ${Wt(JSON.stringify(e),200)}`),e}function ES(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(Wt(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(Wt(r.trim().split(`
744
+ `;return eR(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var Rl=$(()=>{"use strict"});import{existsSync as jg,mkdirSync as Ng}from"node:fs";import{dirname as Og}from"node:path";import{simpleGit as kn}from"simple-git";function nR(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 s=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(s)return`https://${n}@${s[1]}/${s[2]}`;let i=t.match(/^https:\/\/(?:[^@/]+@)?(.+)$/);return i?`https://${n}@${i[1]}`:t}function oR(t,e){return e?.contextWrite?.token?{user:io(t),secret:e.contextWrite.token}:t===Xr.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Xr.bitbucket?e?.bitbucket?.apiToken?{user:Kt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function Lg(t,e){let r=e.sleep??(s=>new Promise(i=>setTimeout(i,s))),n=e.initialDelayMs??5e3,o=e.maxDelayMs??6e4;for(;;)try{return await t()}catch(s){if(!(s instanceof ci))throw s;e.log.warn(`[ctx] ${s.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 li(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,s;try{s=await oe(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new ci(c)}let i=s.contextRepo;if(!i)return o.warn("[ctx] project has no Context Repo on HUB \u2014 daemon stays headless (no config report)"),null;let a=oR(kr(i.cloneUrl),r);if(a){let c=await sR({ctx:i,contextDir:n,cred:a,log:o});if(c)return c;o.warn("[ctx] token clone/update failed")}if(r?.contextSsh?.privateKey){let c=await iR({ctx:i,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 sR(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,s=nR(e.cloneUrl,n.secret,n.user),i=e.branch,a=encodeURIComponent(n.secret),c=l=>l.split(n.secret).join("***").split(a).join("***");try{if(jg(`${r}/.git`)){let l=kn(r);await l.remote(["set-url","origin",s]),await l.fetch("origin",i),await l.checkout(i);let u=$c(r);await l.reset(["--hard",`origin/${i}`]),vc(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${i}`)}else Ng(Og(r),{recursive:!0}),await kn().clone(s,r,["--branch",i]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${i} \u2192 ${r}`);await Dg(r)}catch(l){return o.warn(`[ctx] Context Repo clone/update failed: ${c(l instanceof Error?l.message:String(l))}`),null}return{root:r,contextDir:r,repos:[]}}async function iR(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,s=`${r}.deploy-key`,i=_g(s,n),a=Pg(e.cloneUrl),c=e.branch;try{if(jg(`${r}/.git`)){let l=kn(r);await l.addConfig("core.sshCommand",i,!1,"local"),await l.remote(["set-url","origin",a]),await l.fetch("origin",c),await l.checkout(c);let u=$c(r);await l.reset(["--hard",`origin/${c}`]),vc(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Ng(Og(r),{recursive:!0}),await kn().env({...process.env,GIT_SSH_COMMAND:i}).clone(a,r,["--branch",c]),await kn(r).addConfig("core.sshCommand",i,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await Dg(r),{root:r,contextDir:r,repos:[]}}catch(l){return o.warn(`[ctx] Context Repo ssh clone/update failed: ${l instanceof Error?l.message:String(l)}`),null}}async function Dg(t){let e=kn(t);await e.raw(["config","user.email"]).then(n=>n.trim()).catch(()=>"")||(await e.addConfig("user.email","farm@codepipe.local",!1,"local"),await e.addConfig("user.name","CodePipe Farm CLI",!1,"local"))}var ci,Tl=$(()=>{"use strict";F();Ae();Ot();Rl();ci=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as aR}from"node:child_process";function cR(){try{return aR("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function Ug(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:cR(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var Bg=$(()=>{"use strict"});import{homedir as lR}from"node:os";import{mkdirSync as uR,readFileSync as dR,writeFileSync as pR,existsSync as Fg}from"node:fs";import{dirname as fR,join as Cl}from"node:path";function mR(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function ht(t){let e=J("SANDBOX_CONFIG");if(e)return e;let r=Cl(lR(),".codepipe","worker");return t?Cl(r,"profiles",t,"config.json"):Cl(r,"config.json")}function Kg(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function je(t){let e=ht(t),r=null;return Fg(e)&&(r=JSON.parse(dR(e,"utf-8"))),r?(r.planningLane=mR(),r):null}function Gg(t,e){let r=ht(e);uR(fR(r),{recursive:!0}),pR(r,JSON.stringify(t,null,2)+`
745
+ `,{mode:384})}var ui=$(()=>{"use strict";Le();Fg(".env")&&process.loadEnvFile(".env")});import hR from"ws";var wn,Al=$(()=>{"use strict";wn=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 s=await fetch(`${this.hubUrl}/jobs/release`,o);if(!s.ok&&s.status!==409&&s.status!==404)throw new Error(`release failed: ${s.status} ${await s.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 hR(e)}}});import{hostname as gR}from"node:os";async function jr(t){let e=je(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${ht(t.profile)}.`),process.exit(1));let r=t.name??gR(),n=Ug({projects:t.projects??[],llm:t.llm??null}),o=new wn(t.hub.replace(/\/$/,"")),s=Os(),i=De(s.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:s.publicKey});Gg({hubUrl:t.hub.replace(/\/$/,""),sandboxId:a,token:c,name:r,llm:t.llm??null,sealPublicKey:s.publicKey,sealPrivateKey:s.privateKey},t.profile),console.log(`registered as ${a} (${r}) at ${t.hub}`),console.log(`config saved to ${ht(t.profile)}`),console.log(""),console.log(" cred-channel key fingerprint (confirm this on the CLI \u2014 pin-on-register):"),console.log(` ${i}`),console.log("")}var Hg=$(()=>{"use strict";rt();Bg();ui();Al()});function Wg(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 di(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 qg(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 bn(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 pi=$(()=>{"use strict"});import{spawn as yR}from"node:child_process";function Pl(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function wR(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 bR(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Nr(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function _l(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}})+`
746
+ `}async function Xg(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Dt;let r=bn(e.metadata),n=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",Wg(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,s=l=>{if(o)try{o(l)}catch{}},i=[],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&&s({ts:u,kind:"text",author:"agent",text:Pl(g,Yg)})}else if(f==="tool_use"){let g=String(m.name??""),h=m.input?.file_path??m.input?.path,w=wR(h,e.workspaceDir);s({ts:u,kind:"tool",author:"agent",tool:g,...w?{file:w}:{}})}}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?Pl(bR(m.content),200):"";s({ts:u,kind:"tool_result",author:"agent",isError:f,...g?{text:g}:{}})}return}if(p==="result"){a=l;let d=String(l.subtype??"").trim();s({ts:u,kind:"result",author:"agent",...d?{text:d}:{}});return}if(p==="system"){let d=String(l.subtype??"").trim();d&&s({ts:u,kind:"system",author:"agent",text:d})}};return s({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((l,u)=>{let p=yR(t,n,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});p.stdout.setEncoding("utf-8"),p.stderr.setEncoding("utf-8");let d=!1,m=!1,f=null,g=()=>{d=!0,p.kill("SIGTERM"),f=setTimeout(()=>p.kill("SIGKILL"),Vg)};e.signal?.addEventListener("abort",g,{once:!0});let h=null,w=()=>{h&&clearTimeout(h),h=setTimeout(()=>{m=!0,console.warn(`[claude:chat] idle for ${zg}ms \u2014 ending session`),p.kill("SIGTERM"),f=setTimeout(()=>p.kill("SIGKILL"),Vg)},zg)},y=()=>{f&&clearTimeout(f),h&&clearTimeout(h),e.signal?.removeEventListener("abort",g)},x=!0,S=b=>{if(!(!x||p.stdin.destroyed))try{p.stdin.write(b)}catch{}};S(_l(e.prompt)),w(),(async()=>{try{for await(let b of e.interactive.inbox){if(d||!x)break;if(w(),b.kind==="user")s({ts:Date.now(),kind:"text",author:"user",text:Pl(b.text,Yg)}),S(_l(b.text,qg(r)));else{S(_l(kR)),x=!1;try{p.stdin.end()}catch{}break}}}catch{}})();let T="",R=b=>{let I;try{I=JSON.parse(b)}catch{return}c(I)};p.stdout.on("data",b=>{i.push(b),w(),T+=b;let I;for(;(I=T.indexOf(`
747
+ `))!==-1;){let D=T.slice(0,I).trim();T=T.slice(I+1),D&&R(D)}}),p.stderr.on("data",b=>{i.push(b);for(let I of b.split(`
748
+ `)){let D=I.trim();D&&console.warn(`[claude:chat:stderr] ${D}`)}}),p.on("error",b=>{y(),u(b)}),p.on("close",b=>{if(y(),d){u(new Dt);return}if(m){u(new Error("chat session ended: idle for too long without a reply"));return}T.trim()&&R(T.trim()),console.log(`[claude:chat] exit code=${b}`),l({artifactPaths:[],log:i.join(""),usage:$R(a)})})})}function $R(t){let e=Bt();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=Nr(r.input_tokens),e.outputTokens=Nr(r.output_tokens),e.cacheReadInputTokens=Nr(r.cache_read_input_tokens),e.cacheCreationInputTokens=Nr(r.cache_creation_input_tokens)),e.totalCostUsd=Nr(t.total_cost_usd),e.numTurns=Nr(t.num_turns),e.durationMs=Nr(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var Yg,Vg,zg,kR,Jg=$(()=>{"use strict";F();$n();pi();Yg=16e3,Vg=5e3,zg=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),kR="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 vR}from"node:child_process";import{existsSync as xR}from"node:fs";function ER(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function Zg(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 s=o.type;if(s==="text"){let i=String(o.text??"").trim();i&&console.log(`[claude] text: ${Qt(i,200)}`)}else if(s==="tool_use"){let i=String(o.name??""),a=o.input,c=IR(i,a);console.log(`[claude] tool_use ${i}${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 s=ey(o.content);console.log(`[claude] tool_result (error)${s?`: ${Qt(s,200)}`:""}`)}else console.log("[claude] tool_result");return e}if(r==="result"){let n=e.subtype??"",o=e.num_turns,s=e.total_cost_usd;return console.log(`[claude] result ${n} turns=${o} cost=$${s}`),e}return console.log(`[claude] ${String(r)} ${Qt(JSON.stringify(e),200)}`),e}function RR(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():"",s=e.api_error_status,i=e.subtype;o?n.push(Qt(o,500)):typeof i=="string"&&i!=="success"&&n.push(i),typeof s=="number"&&n.push(`(api_status=${s})`)}return n.length===1&&r.trim()&&n.push(Qt(r.trim().split(`
673
749
  `).slice(-5).join(`
674
- `),500)),n.join(" \u2014 ")}function IS(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 Qg(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function RS(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=${Wt(r,80)}`}return""}function Wt(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function Oe(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function CS(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=Oe(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:Oe(e.resetsAt),rateLimitType:typeof e.rateLimitType=="string"?e.rateLimitType:"",utilization:n,isUsingOverage:e.isUsingOverage===!0};return typeof e.surpassedThreshold=="number"&&(o.surpassedThreshold=e.surpassedThreshold),o}function AS(t,e,r,n){let o=rr(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=Oe(i.input_tokens),o.outputTokens=Oe(i.output_tokens),o.cacheReadInputTokens=Oe(i.cache_read_input_tokens),o.cacheCreationInputTokens=Oe(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=Oe(t?.total_cost_usd),o.numTurns=t&&Oe(t.num_turns)>0?Oe(t.num_turns):r,o.durationMs=Oe(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}function PS(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:Wt(c,Jg)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,p=_S(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?Wt(Qg(s.content),Jg):"";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 _S(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 un,Et,SS,mo,Jg,ln=v(()=>{"use strict";G();zg();Qi();un=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Et=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},SS=5e3;mo=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return Vg(this.binary,e);if(e.signal?.aborted)throw new Et;let r=["-p",TS(e.prompt),"--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",Ji(cn(e.metadata))];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let m of e.addDirs??[])r.push("--add-dir",m);let n=[],o=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,u=m=>{if(m){if(m.type==="result"){i=m;return}if(m.type==="rate_limit_event"){let h=CS(m.rate_limit_info);h&&(!l||h.utilization>l.utilization)&&(l=h);return}if(m.type==="assistant"){let h=m.message;typeof h?.model=="string"&&(c=h.model);let g=h?.usage;g&&(a+=1,s.input+=Oe(g.input_tokens),s.output+=Oe(g.output_tokens),s.cacheRead+=Oe(g.cache_read_input_tokens),s.cacheCreate+=Oe(g.cache_creation_input_tokens))}}},p=e.role,d=e.onActivity,f=m=>{if(d)for(let h of PS(m,e.workspaceDir))try{d(h)}catch{}};return d?.({ts:Date.now(),kind:"start",text:`${p} job started`}),console.log(`[claude] spawn ${this.binary} role=${p}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((m,h)=>{let g=vS(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"}});g.stdout.setEncoding("utf-8"),g.stderr.setEncoding("utf-8");let w=!1,y=null,x=()=>{w=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${p}`),g.kill("SIGTERM"),y=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),g.kill("SIGKILL")},SS)};e.signal?.addEventListener("abort",x,{once:!0});let T=()=>{y&&clearTimeout(y),e.signal?.removeEventListener("abort",x)},I="";g.stdout.on("data",E=>{n.push(E),I+=E;let b;for(;(b=I.indexOf(`
675
- `))!==-1;){let R=I.slice(0,b).trim();if(I=I.slice(b+1),R){let N=Xg(R);u(N),N&&f(N)}}}),g.stderr.on("data",E=>{n.push(E),o.push(E);for(let b of E.split(`
676
- `)){let R=b.trim();R&&console.warn(`[claude:stderr] ${R}`)}}),g.on("error",E=>{T(),h(E)}),g.on("close",E=>{if(T(),w){h(new Et);return}if(I.trim()){let R=Xg(I.trim());u(R),R&&f(R)}let b=i?.is_error===!0;if(E!==0||b){let R=typeof i?.api_error_status=="number"?i.api_error_status:void 0,N=typeof i?.subtype=="string"?i.subtype:void 0,F=typeof i?.result=="string"?i.result:void 0;h(new un(ES(E,i,o.join("")),{code:E,apiErrorStatus:R,subtype:N,resultText:F,retryAfterMs:IS(i)}));return}console.log("[claude] exit code=0"),m({artifactPaths:[],log:n.join(""),usage:AS(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("/")&&xS(n))}};Jg=200});import{mkdirSync as jS,writeFileSync as dn}from"node:fs";import{dirname as NS,join as pn}from"node:path";function Zg(t,e,r){let n=pn(t,e);jS(NS(n),{recursive:!0}),dn(n,r)}function OS(t,e,r){return`# ${t} \u2014 Estimate
750
+ `),500)),n.join(" \u2014 ")}function TR(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 ey(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function IR(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=${Qt(r,80)}`}return""}function Qt(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function Me(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function CR(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=Me(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:Me(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 AR(t,e,r,n){let o=Bt(),s=t&&typeof t.usage=="object"?t.usage:null;s?(o.inputTokens=Me(s.input_tokens),o.outputTokens=Me(s.output_tokens),o.cacheReadInputTokens=Me(s.cache_read_input_tokens),o.cacheCreationInputTokens=Me(s.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=Me(t?.total_cost_usd),o.numTurns=t&&Me(t.num_turns)>0?Me(t.num_turns):r,o.durationMs=Me(t?.duration_ms);let i=typeof t?.model=="string"?t.model:"";return o.model=i||n,o}function PR(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,s=[];for(let i of o?.content??[]){let a=i.type;if(a==="text"){let c=String(i.text??"").trim();c&&s.push({ts:r,kind:"text",text:Qt(c,Qg)})}else if(a==="tool_use"){let c=String(i.name??""),l=i.input,u=l?.file_path??l?.path??l?.notebook_path,p=_R(u,e);s.push({ts:r,kind:"tool",tool:c,...p?{file:p}:{}})}}return s}if(n==="user"){let o=t.message,s=[];for(let i of o?.content??[])if(i.type==="tool_result"){let a=i.is_error===!0,c=a?Qt(ey(i.content),Qg):"";s.push({ts:r,kind:"tool_result",isError:a,...c?{text:c}:{}})}return s}if(n==="result"){let o=String(t.subtype??"").trim(),s=typeof t.num_turns=="number"?t.num_turns:void 0,i=typeof t.total_cost_usd=="number"?t.total_cost_usd:void 0;return[{ts:r,kind:"result",...o?{text:o}:{},...s!==void 0?{turns:s}:{},...i!==void 0?{costUsd:i}:{}}]}return[]}function _R(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 vn,Dt,SR,jo,Qg,$n=$(()=>{"use strict";F();Jg();pi();vn=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Dt=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},SR=5e3;jo=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return Xg(this.binary,e);if(e.signal?.aborted)throw new Dt;let r=["-p",ER(e.prompt),"--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",di(bn(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=[],s=null,i={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,u=f=>{if(f){if(f.type==="result"){s=f;return}if(f.type==="rate_limit_event"){let g=CR(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 h=g?.usage;h&&(a+=1,i.input+=Me(h.input_tokens),i.output+=Me(h.output_tokens),i.cacheRead+=Me(h.cache_read_input_tokens),i.cacheCreate+=Me(h.cache_creation_input_tokens))}}},p=e.role,d=e.onActivity,m=f=>{if(d)for(let g of PR(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 h=vR(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"}});h.stdout.setEncoding("utf-8"),h.stderr.setEncoding("utf-8");let w=!1,y=null,x=()=>{w=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${p}`),h.kill("SIGTERM"),y=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),h.kill("SIGKILL")},SR)};e.signal?.addEventListener("abort",x,{once:!0});let S=()=>{y&&clearTimeout(y),e.signal?.removeEventListener("abort",x)},T="";h.stdout.on("data",R=>{n.push(R),T+=R;let b;for(;(b=T.indexOf(`
751
+ `))!==-1;){let I=T.slice(0,b).trim();if(T=T.slice(b+1),I){let D=Zg(I);u(D),D&&m(D)}}}),h.stderr.on("data",R=>{n.push(R),o.push(R);for(let b of R.split(`
752
+ `)){let I=b.trim();I&&console.warn(`[claude:stderr] ${I}`)}}),h.on("error",R=>{S(),g(R)}),h.on("close",R=>{if(S(),w){g(new Dt);return}if(T.trim()){let I=Zg(T.trim());u(I),I&&m(I)}let b=s?.is_error===!0;if(R!==0||b){let I=typeof s?.api_error_status=="number"?s.api_error_status:void 0,D=typeof s?.subtype=="string"?s.subtype:void 0,K=typeof s?.result=="string"?s.result:void 0;g(new vn(RR(R,s,o.join("")),{code:R,apiErrorStatus:I,subtype:D,resultText:K,retryAfterMs:TR(s)}));return}console.log("[claude] exit code=0"),f({artifactPaths:[],log:n.join(""),usage:AR(s,i,a,c),...l?{rateLimit:l}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(n=>n.includes("/")&&xR(n))}};Qg=200});import{mkdirSync as jR,writeFileSync as xn}from"node:fs";import{dirname as NR,join as Sn}from"node:path";function ty(t,e,r){let n=Sn(t,e);jR(NR(n),{recursive:!0}),xn(n,r)}function OR(t,e,r){return`# ${t} \u2014 Estimate
677
753
 
678
754
  **Title:** ${e}
679
755
 
@@ -694,7 +770,7 @@ production-grade estimates.)
694
770
  ${r.split(`
695
771
  `).slice(0,8).join(`
696
772
  `).trim()||"(empty)"}
697
- `}function LS(t,e,r,n){let o=n?`
773
+ `}function LR(t,e,r,n){let o=n?`
698
774
  ## Reviewer rework instruction
699
775
 
700
776
  > ${n.split(`
@@ -723,10 +799,10 @@ TBD (mock runner does not yet inspect project code).
723
799
  ${r.split(`
724
800
  `).slice(0,8).join(`
725
801
  `).trim()||"(empty)"}
726
- `}function DS(t){return`# ${t} \u2014 Open questions
802
+ `}function DR(t){return`# ${t} \u2014 Open questions
727
803
 
728
804
  (none \u2014 mock runner did not surface ambiguities.)
729
- `}function MS(t,e,r){let n=r?` (rework: ${r.split(`
805
+ `}function MR(t,e,r){let n=r?` (rework: ${r.split(`
730
806
  `)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
731
807
  index 0000000..1111111 100644
732
808
  --- a/CHANGELOG.md
@@ -737,7 +813,7 @@ index 0000000..1111111 100644
737
813
  +- mock-runner placeholder change for slice 5 testing.
738
814
  +
739
815
  # Changelog
740
- `}function US(t,e,r){return`# ${t} \u2014 Diff summary
816
+ `}function UR(t,e,r){return`# ${t} \u2014 Diff summary
741
817
 
742
818
  **Title:** ${e}
743
819
  ${r?`
@@ -748,144 +824,157 @@ ${r?`
748
824
  - \`CHANGELOG.md\` \u2014 added entry for ${t}.
749
825
 
750
826
  (Mock-runner output. Replace with claude-headless for production patches.)
751
- `}var go,jc=v(()=>{"use strict";G();ln();go=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=OS(n,o,i);dn(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;dn(pn(e.workspaceDir,"PLAN.md"),LS(n,o,i,a)),s.push("PLAN.md"),dn(pn(e.workspaceDir,"QUESTIONS.md"),DS(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Zg(e.workspaceDir,"changes/sample.patch",MS(n,o,a)),s.push("changes/sample.patch"),Zg(e.workspaceDir,"diff-summary.md",US(n,o,a)),s.push("diff-summary.md")}else e.role==="rework"&&(dn(pn(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
752
- `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:rr()}}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 Et;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 dn(pn(e.workspaceDir,"DRAFT.md"),`${o}
827
+ `}var No,jl=$(()=>{"use strict";F();$n();No=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)",s=r.taskDescription??"",i=[];if(e.role==="estimate"){let a=OR(n,o,s);xn(Sn(e.workspaceDir,"ESTIMATE.md"),a),i.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;xn(Sn(e.workspaceDir,"PLAN.md"),LR(n,o,s,a)),i.push("PLAN.md"),xn(Sn(e.workspaceDir,"QUESTIONS.md"),DR(n)),i.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;ty(e.workspaceDir,"changes/sample.patch",MR(n,o,a)),i.push("changes/sample.patch"),ty(e.workspaceDir,"SOLUTION.md",UR(n,o,a)),i.push("SOLUTION.md")}else e.role==="rework"&&(xn(Sn(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
828
+ `),i.push("NOTE.md"));return{artifactPaths:i,log:`mock runner produced ${i.length} artifact(s) for role=${e.role}`,usage:Bt()}}async runInteractive(e){let r=e.onActivity,n=s=>{r?.({ts:Date.now(),kind:"text",author:"agent",text:s}),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 s of e.interactive.inbox){if(e.signal?.aborted)throw new Dt;if(s.kind==="user")r?.({ts:Date.now(),kind:"text",author:"user",text:s.text}),s.text.trim()&&(o=s.text.trim().slice(0,80)),n(`Got it: **${s.text.trim()}**. Anything else to clarify?`);else break}return xn(Sn(e.workspaceDir,"DRAFT.md"),`${o}
753
829
 
754
830
  Produced by the interactive chat (mock runner).
755
- `),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:rr()}}}});function eh(t){switch(t){case"mock":return new go;case"claude-headless":return new mo;default:return null}}function th(t,e){let r=e&&e.trim().length>0?e.trim():pt;return t==="mock"?!0:t==="claude-headless"?r==="claude":!1}var rh=v(()=>{"use strict";G();ln();jc();ln();jc()});function ih(t=process.env){return{maxAttempts:Zi(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:Zi(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:Zi(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:Zi(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function KS(t){if(t instanceof un){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return FS.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&GS.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:BS.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:nh.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 nh.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function sh(t){if(t instanceof un){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&oh.test(n)}let e=t instanceof Error?t.message:String(t);return oh.test(e)}function HS(t,e,r){if(typeof r=="number"&&r>0)return Math.min(r,e.maxDelayMs);let n=e.baseDelayMs*2**(t-1),o=Math.min(n,e.maxDelayMs);return Math.round(o/2+Math.random()*(o/2))}async function ah(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=KS(a),l=s>=r.policy.maxAttempts;if(!c.retryable||l||r.aborted())throw s>1?new Error(`agent failed after ${s} attempts: ${i}`):a;let u=HS(s,r.policy,c.retryAfterMs);if(Date.now()+u>o)throw new Error(`agent failed after ${s} attempts (retry budget exhausted): ${i}`);console.warn(`[job] ${r.jobId} agent attempt ${s}/${r.policy.maxAttempts} failed (retryable: ${c.reason}) \u2014 cleaning workspace, backoff ${u}ms`),await r.onBeforeRetry(),await n(u)}}function Zi(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}var BS,nh,FS,GS,oh,ch=v(()=>{"use strict";ln();BS=new Set([429,500,502,503,529]),nh=/(\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,FS=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,GS=new Set(["error_max_turns"]);oh=/(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 WS,writeFileSync as qS}from"node:fs";import{homedir as YS}from"node:os";import{join as lh}from"node:path";function dh(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 ph(t,e,r,n){try{let o=lh(YS(),".codepipe","debug",uh(t));WS(o,{recursive:!0});let i=new Date().toISOString().replace(/[:.]/g,"-"),s=lh(o,`${i}-${uh(e)}-${r}.md`);return qS(s,n),s}catch{return null}}var uh,fh=v(()=>{"use strict";uh=t=>t.replace(/[^A-Za-z0-9._-]/g,"_")});import{mkdtempSync as VS,rmSync as zS,writeFileSync as mh}from"node:fs";import{tmpdir as XS}from"node:os";import{join as Nc}from"node:path";function es(t){return`[url "https://${t}/"]
831
+ `),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:Bt()}}}});function ry(t){switch(t){case"mock":return new No;case"claude-headless":return new jo;default:return null}}function ny(t,e){let r=e&&e.trim().length>0?e.trim():Ke;return t==="mock"?!0:t==="claude-headless"?r==="claude":!1}var oy=$(()=>{"use strict";F();$n();jl();$n();jl()});function ay(t=process.env){return{maxAttempts:fi(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:fi(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:fi(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:fi(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function GR(t){if(t instanceof vn){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:s}=t.details,i=o??"";return FR.test(i)?{retryable:!1,reason:"out_of_credits"}:n&&KR.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:s}:BR.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:sy.test(i)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:n??`exit ${t.details.code}`}}let e=t instanceof Error?t.message:String(t);return sy.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function cy(t){if(t instanceof vn){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&iy.test(n)}let e=t instanceof Error?t.message:String(t);return iy.test(e)}function HR(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 ly(t,e,r){let n=r.sleep??(i=>new Promise(a=>setTimeout(a,i))),o=Date.now()+r.policy.totalBudgetMs,s="";for(let i=1;;i++)try{return await t.run(e)}catch(a){s=a instanceof Error?a.message:String(a);let c=GR(a),l=i>=r.policy.maxAttempts;if(!c.retryable||l||r.aborted())throw i>1?new Error(`agent failed after ${i} attempts: ${s}`):a;let u=HR(i,r.policy,c.retryAfterMs);if(Date.now()+u>o)throw new Error(`agent failed after ${i} attempts (retry budget exhausted): ${s}`);console.warn(`[job] ${r.jobId} agent attempt ${i}/${r.policy.maxAttempts} failed (retryable: ${c.reason}) \u2014 cleaning workspace, backoff ${u}ms`),await r.onBeforeRetry(),await n(u)}}function fi(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}var BR,sy,FR,KR,iy,uy=$(()=>{"use strict";$n();BR=new Set([429,500,502,503,529]),sy=/(\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,FR=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,KR=new Set(["error_max_turns"]);iy=/(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 WR,writeFileSync as qR}from"node:fs";import{homedir as YR}from"node:os";import{join as dy}from"node:path";function fy(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 my(t,e,r,n){try{let o=dy(YR(),".codepipe","debug",py(t));WR(o,{recursive:!0});let s=new Date().toISOString().replace(/[:.]/g,"-"),i=dy(o,`${s}-${py(e)}-${r}.md`);return qR(i,n),i}catch{return null}}var py,hy=$(()=>{"use strict";py=t=>t.replace(/[^A-Za-z0-9._-]/g,"_")});import{mkdtempSync as VR,rmSync as zR,writeFileSync as gy}from"node:fs";import{tmpdir as XR}from"node:os";import{join as Nl}from"node:path";function mi(t){return`[url "https://${t}/"]
756
832
  insteadOf = git@${t}:
757
833
  insteadOf = ssh://git@${t}/
758
- `}function gh(t,e){if(t.length===0)return null;let r=VS(Nc(XS(),"devpipe-gitcreds-")),n=Nc(r,"credentials"),o=Nc(r,"gitconfig");return mh(n,t.join(`
834
+ `}function yy(t,e){if(t.length===0)return null;let r=VR(Nl(XR(),"devpipe-gitcreds-")),n=Nl(r,"credentials"),o=Nl(r,"gitconfig");return gy(n,t.join(`
759
835
  `)+`
760
- `,{mode:384}),mh(o,`[credential]
836
+ `,{mode:384}),gy(o,`[credential]
761
837
  helper = store --file=${n}
762
- `+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{zS(r,{recursive:!0,force:!0})}catch{}}}}function Oc(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(JS)),t.bitbucket?.apiToken&&(e.push(`https://${sr}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(QS)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(ZS)),gh(e,r)}function hh(t,e){if(t.contextWrite?.token){let r=Dr(e)??"github.com",n=Fo(r);return gh([`https://${n}:${t.contextWrite.token}@${r}`],[es(r)])}return Oc(t)}var JS,QS,ZS,yh=v(()=>{"use strict";G();JS=es("github.com"),QS=es("bitbucket.org"),ZS=es("gitlab.com")});import{spawn as wh}from"node:child_process";import{existsSync as ts,mkdirSync as ho,readFileSync as eT,rmSync as Lc,symlinkSync as tT}from"node:fs";import{homedir as rT}from"node:os";import{dirname as mn,join as qt}from"node:path";function bh(t){let e=qt(rT(),".codepipe-sandbox","repos");return t?qt(e,t):e}function $h(t,e){let n=(fn.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{fn.get(t)===o&&fn.delete(t)},()=>{fn.get(t)===o&&fn.delete(t)});return fn.set(t,o),n}function kh(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 nT(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 vh(t,e,r,n,o){let i=async c=>{await ie(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await ie(t,["reset","--hard",`origin/${c}`],o),await ie(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!kh(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{ts(t)&&Lc(t,{recursive:!0,force:!0}),ho(mn(t),{recursive:!0});try{return await ie(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!kh(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),ts(t)&&Lc(t,{recursive:!0,force:!0}),ho(mn(t),{recursive:!0}),await ie(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(ts(qt(t,".git")))try{return await s()}catch(c){if(!nT(c))throw c;let l=c instanceof Error?c.message:String(c);console.warn(`[git] cache at ${t} looks corrupt (${l}) \u2014 discarding and re-cloning`)}return a()}async function xh(t){await ie(t.workspacePath,["reset","--hard",t.baseSha]),await ie(t.workspacePath,["clean","-fdx"])}async function Sh(t,e){let r=t.workspacePath;await ie(r,["add","-A"]);let n=(await Ce(r,["write-tree"])).trim(),o=(await Ce(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:gn,GIT_AUTHOR_EMAIL:hn,GIT_COMMITTER_NAME:gn,GIT_COMMITTER_EMAIL:hn};return(await Ce(r,["commit-tree",n,"-m",e],i)).trim()}async function Th(t,e,r,n,o){try{await ie(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw Dr(n)==="github.com"&&/without `?workflow`? scope|workflow.*scope/i.test(s)?new Error("delivery push rejected: the Context-Repo push token needs the `workflow` scope (the delivery includes .github/workflows/*). Set secrets.contextWrite.token to a fine-grained PAT on the Context Repo with Contents: write + Workflows: write (or add `workflow` to the project token).\n"+s):i}}async function Eh(t,e){return Ce(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Ih(t,e,r,n,o){await ie(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await ie(t.workspacePath,["checkout","--force",r])}async function Rh(t,e,r,n,o,i){let s=t.workspacePath;await ie(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await Ce(s,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=m=>Ce(s,["rev-parse","-q","--verify",`${m}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await Ce(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ie(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(h=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(h)}`)}),await c(n)||await ie(s,["fetch","origin",n],i).catch(()=>{}),!await c(n)))throw new Error(`moved-base apply: delivery base ${n.slice(0,10)} is unreachable \u2014 cannot re-apply the previous iteration onto the fresh ${t.ref}`);let l={...i??process.env,GIT_AUTHOR_NAME:gn,GIT_AUTHOR_EMAIL:hn,GIT_COMMITTER_NAME:gn,GIT_COMMITTER_EMAIL:hn},u=(await Ce(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),p=(await Ce(s,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await ie(s,["cherry-pick","--quit"],l).catch(()=>{});let d=null;try{await ie(s,["cherry-pick","--no-commit",p],l)}catch(m){d=m instanceof Error?m.message:String(m)}let f=(await Ce(s,["diff","--name-only","--diff-filter=U"])).split(`
763
- `).map(m=>m.trim()).filter(m=>m.length>0);if(d&&f.length===0)throw await ie(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${d}`);return f}async function Dc(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:gn,GIT_AUTHOR_EMAIL:hn,GIT_COMMITTER_NAME:gn,GIT_COMMITTER_EMAIL:hn};(await Ce(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ie(n,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),await ie(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await ie(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await Ce(n,["diff","--name-only","--diff-filter=U"])).split(`
764
- `).map(l=>l.trim()).filter(l=>l.length>0),c=await Ce(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}function ie(t,e,r){return new Promise((n,o)=>{let i=wh("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}):
765
- ${s.join("").trim()||"(no stderr)"}`))})})}function Ce(t,e,r){return new Promise((n,o)=>{let i=wh("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}):
766
- ${a.join("").trim()||"(no stderr)"}`))})})}function Ch(t,e){ts(t)&&Lc(t,{recursive:!0,force:!0}),ho(mn(t),{recursive:!0}),tT(e,t,"dir")}async function Ah(t,e,r){await ie(t,["worktree","prune"]).catch(()=>{}),ho(mn(r),{recursive:!0}),await ie(t,["worktree","add","--detach",r,`origin/${e}`])}async function oT(t,e,r){ho(mn(r),{recursive:!0}),await ie(mn(r),["clone","--quiet","--no-checkout",t,r]),await ie(r,["checkout","--force","--detach",e])}async function Ph(t,e,r,n="worktree",o,i){return r.length===0?[]:$h(e,async()=>{let s=[];for(let a of r){let c=qt(bh(i),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await vh(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 Ce(c,["rev-parse","HEAD"])).trim(),p=qt(t,"code",a.name);n==="direct"?(Ch(p,c),console.log(`[git] code: linked ${p} \u2192 ${c} @ ${u.slice(0,10)}`)):n==="clone"?(await oT(c,u,p),console.log(`[git] code: clone ${p} \u2190 ${c} @ ${u.slice(0,10)}`)):(await Ah(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 _h(t,e,r,n="worktree",o,i){if(!r||!r.cloneUrl)return null;let s=r;return $h(e,async()=>{let a=qt(bh(i),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);try{await vh(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=qt(t,"context");n==="direct"?(Ch(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await Ah(a,s.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await Ce(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function jh(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await ie(r,["add","-A",...n]).catch(()=>{});let o;try{o=await Ce(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
767
- `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=eT(qt(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var fn,gn,hn,Nh=v(()=>{"use strict";G();fn=new Map;gn="CodePipe Agent",hn="codepipe@codepartner.ee"});import{existsSync as iT,readFileSync as sT}from"node:fs";import{join as aT}from"node:path";import{parse as cT}from"yaml";function Oh(t){if(!t)return!1;let e=aT(t,Mc);if(!iT(e))return!1;try{let r=cT(sT(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 Mc,Lh=v(()=>{"use strict";Mc="knowledge/build.yaml"});import{readFileSync as lT}from"node:fs";import{join as uT}from"node:path";function Dh(t){let e=uT(t,yo),r;try{r=lT(e,"utf-8")}catch{throw new Yt(`BUILD produced no ${yo} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new Yt(`${yo} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new Yt(`${yo} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new Yt(`${yo}: "ok" must be a boolean`);let i=o.ok,a=(Array.isArray(o.steps)?o.steps:[]).flatMap(u=>{if(!u||typeof u!="object")return[];let p=u,d=typeof p.name=="string"?p.name:null,f=typeof p.exitCode=="number"?p.exitCode:null;if(d===null||f===null)return[];let m={name:d,exitCode:f};return typeof p.durationMs=="number"&&(m.durationMs=p.durationMs),[m]}),c=typeof o.logTail=="string"?dT(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 dT(t){let e=Buffer.from(t,"utf-8");return e.length<=Uc?t:`\u2026 [${e.length-Uc} bytes elided] \u2026
768
- `+e.subarray(e.length-Uc).toString("utf-8")}var Uc,Yt,yo,Mh=v(()=>{"use strict";Uc=8*1024,Yt=class extends Error{},yo="meta/build-result.json"});import{readFileSync as pT}from"node:fs";import{join as fT}from"node:path";function Bh(t){let e=fT(t,yn),r;try{r=pT(e,"utf-8")}catch{throw new It(`code review produced no ${yn} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(c){throw new It(`${yn} is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(!n||typeof n!="object")throw new It(`${yn} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new It(`${yn}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?Uh(o.remarks,mT):"";if(!i&&s.trim().length===0)throw new It(`${yn}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?Uh(o.summary,gT):"";return{approved:i,remarks:s,summary:a}}function Uh(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
769
- \u2026 [${r.length-e} bytes elided]`}var mT,gT,It,yn,Fh=v(()=>{"use strict";mT=16*1024,gT=4*1024,It=class extends Error{},yn="meta/review-result.json"});import{readFileSync as hT,statSync as yT}from"node:fs";import{join as Gh}from"node:path";function ST(t){return t.startsWith("meta/")||xT.has(t)}function TT(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 ET(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function Kh(t,e,r){let n=r?.maxBytes??kT,o=r?.totalBytes??wT,i=r?.maxCount??bT,s=e.map((m,h)=>{let g=null;try{g=yT(Gh(t,m)).size}catch{}return{path:m,index:h,size:g}}),a=[...s].sort((m,h)=>{let g=w=>ST(w.path)?0:1;return g(m)!==g(h)?g(m)-g(h):(m.size??0)-(h.size??0)}),c=a.slice(0,i),l=a.slice(i).sort((m,h)=>m.index-h.index).map(m=>m.path),u=new Array(s.length),p=[],d=0;for(let m of c){let h=null;if(m.size!==null&&m.size<=n&&d+m.size<=o)try{h=hT(Gh(t,m.path))}catch{}if(h!==null){d+=h.length,u[m.index]={path:m.path,contentBase64:h.toString("base64")};continue}let g=m.size===null?ET(m.path):TT(m.path,m.size,n,o),w=Buffer.from(g,"utf-8");d+=w.length,u[m.index]={path:m.path,contentBase64:w.toString("base64")},p.push({path:m.path,bytes:m.size??0})}let f=u.filter(m=>m!==void 0);if(l.length>0){let m=l.slice(0,vT),h=`# Artifacts omitted from upload
770
-
771
- ${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.
772
-
773
- `+m.map(g=>`- ${g}
774
- `).join("")+(l.length>m.length?`
775
- \u2026and ${l.length-m.length} more.
776
- `:"");f.push({path:$T,contentBase64:Buffer.from(h,"utf-8").toString("base64")})}return{artifacts:f,omitted:p,dropped:l}}var kT,wT,bT,$T,vT,xT,Hh=v(()=>{"use strict";kT=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),wT=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),bT=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),$T="artifacts-omitted.md",vT=500,xT=new Set(["QUESTIONS.md","PLAN.md","SOLUTION.md","DRAFT.md","ESTIMATE.md","diff-summary.md","review-result.md","commit-message.txt","pr-description.md"])});import{lstatSync as IT,mkdtempSync as RT,readFileSync as CT,readdirSync as qh,rmSync as Wh}from"node:fs";import{tmpdir as AT}from"node:os";import{join as rs,relative as PT}from"node:path";function Yh(t){let e=RT(rs(AT(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Wh(e,{recursive:!0,force:!0}),listFiles:()=>Vh(e,e),readFile:r=>CT(rs(e,r),"utf-8"),clean:()=>{for(let r of qh(e))jT.has(r)||Wh(rs(e,r),{recursive:!0,force:!0})}}}function Vh(t,e){let r=[];for(let n of qh(e)){let o=rs(e,n),i=IT(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&_T.has(n))continue;r.push(...Vh(t,o))}else r.push(PT(t,o))}return r}var _T,jT,zh=v(()=>{"use strict";_T=new Set(["code","context","scratch"]),jT=new Set(["code","context"])});import{existsSync as os,readFileSync as Xh,readdirSync as Bc}from"node:fs";import{join as Rt}from"node:path";import{parse as NT}from"yaml";function is(t){if(!os(t))return[];let e=[];for(let r of Bc(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=Rt(t,r.name);r.isDirectory()?e.push(...is(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function ns(t){try{return NT(Xh(t,"utf-8"))}catch{return null}}function Jh(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 is(Rt(t,"model/derived/structure"))){let s=At(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[...is(Rt(t,"model/derived/correlates")),Rt(t,"model/derived/relates.yaml")]){if(!os(i))continue;let s=jo(ns(i));if(s.ok)for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}let n=Rt(t,"model/facts/events");if(os(n))for(let i of Bc(n).sort()){if(!i.endsWith(".yaml"))continue;let s=Pt(ns(Rt(n,i)));if(!s.ok)continue;let a=s.value;e.events.set(a.taskKey,a);let c=ve(a.taskKey);for(let l of a.files)r(c,l.key,"touched_by",1);for(let l of a.links?.adr??[])r(c,`adr::${l}`,"references",1);for(let l of a.links?.tasks??[])r(c,ve(l),"references",1)}for(let i of is(Rt(t,"model/facts/identity"))){let s=Oo(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=Rt(t,"model/facts/annotations");if(os(o)){for(let i of Bc(o).sort())if(i.endsWith(".md"))try{let s=Xh(Rt(o,i),"utf-8"),a=/^---\n[\s\S]*?entityId:\s*(e_[0-9a-f]{8})[\s\S]*?\n---\n?([\s\S]*)$/.exec(s);a&&e.annotations.set(a[1],a[2].trim())}catch{}}return e.empty=e.nodes.size===0&&e.events.size===0,e}var Qh=v(()=>{"use strict";G()});function ey(t){return new Set((t.toLowerCase().match(/[a-zа-я0-9_]{4,}/g)??[]).filter(e=>!/^\d+$/.test(e)))}function FT(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 ty(t){let{taskKey:e,title:r,text:n,model:o}=t,i=new Map,s=(f,m)=>{(i.get(f)??0)<m&&i.set(f,m)};(o.events.has(e)||o.adjacency.has(ve(e)))&&s(ve(e),Zh);for(let f of`${r}
777
- ${n}`.match(BT)??[]){if(f===e)continue;let m=ve(f);(o.events.has(f)||o.adjacency.has(m))&&s(m,Zh)}let a=new Map;for(let f of o.nodes.keys()){let m=Q(f);if(m?.level!=="code")continue;let h=m.path.slice(m.path.lastIndexOf("/")+1);for(let g of[m.path,h])a.has(g)||a.set(g,[]),a.get(g).push(f)}let c=`${r}
778
- ${n}`.split(/[\s,;()[\]{}<>"'!?]+/);for(let f of c){let m=f.replace(/^[`*_]+|[`*_.:]+$/g,"");if(!m||!m.includes("/")&&!m.includes("."))continue;let h=a.get(m)??[];h.length===1&&s(h[0],OT)}let l=new Map,u=(f,m)=>{let h=f.toLowerCase();!h||h.length<4||l.set(h,l.has(h)&&l.get(h)!==m?null:m)};for(let f of o.nodes.keys()){let m=Q(f);if(!m)continue;let h=m.path.slice(m.path.lastIndexOf("/")+1);m.level==="code"&&u(h.replace(/\.[a-z0-9]+$/i,""),f),m.level==="component"&&u(h,f)}for(let f of`${r}
779
- ${n}`.match(/[A-Za-z][A-Za-z0-9_-]{3,}/g)??[]){let m=l.get(f.toLowerCase());m&&s(m,LT)}let p=ey(`${r}
780
- ${n}`),d=[];for(let[f,m]of o.events){if(f===e||!m.title)continue;let h=FT(p,ey(m.title));h>=MT&&d.push({key:ve(f),score:h})}return d.sort((f,m)=>m.score-f.score||(f.key<m.key?-1:1)).slice(0,UT).forEach(f=>s(f.key,DT)),i}var Zh,OT,LT,DT,MT,UT,BT,ry=v(()=>{"use strict";G();Zh=1,OT=.9,LT=.7,DT=.5,MT=.15,UT=3,BT=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g});function ny(t,e,r={}){let n=r.cutoff??jr.activationCutoff,o=r.topK??jr.topKPerNode,i=r.nodeCap??jr.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=Ll[p.kind]??.3,f=l.activation*d*Math.min(p.weight,1);if(f<n)continue;let m=s.get(p.to);(!m||m.activation<f)&&(s.set(p.to,{activation:f,via:{from:l.key,kind:p.kind}}),a.push({key:p.to,activation:f}))}}return s}var oy=v(()=>{"use strict";G()});import{existsSync as Gc,readFileSync as iy,readdirSync as GT}from"node:fs";import{join as cs}from"node:path";function Fc(t){return Math.ceil(t.length/4)}function ss(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 Vt(t){let e=Q(t);return e?(e.level==="task"||e.level==="adr",e.path):t}function as(t){if(!t.via)return"matched from the task text";let e=Vt(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 qT(t,e){let r=/^ADR-(\d{3,4})$/.exec(e)?.[1];if(!r)return null;let n=cs(t,"adr");if(!Gc(n))return null;let o=r.padStart(4,"0");for(let i of GT(n).sort())if(!(!i.startsWith(`${o}-`)||!i.endsWith(".md")))try{return{file:`adr/${i}`,content:iy(cs(n,i),"utf-8").trim()}}catch{return null}return null}function sy(t){let{taskKey:e,title:r,contextDir:n,model:o,activated:i}=t,s=t.budgetTokens??jr.budgetTokens,a=[],c=0,l=E=>{let b=Fc(E);return c+b>s?!1:(a.push(E),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(`
781
- `));let u=ss(i,E=>E.startsWith("adr::")),p=!1;for(let E of u){let b=qT(n,Vt(E.key));if(!b)continue;let R=`${p?"":`
838
+ `+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{zR(r,{recursive:!0,force:!0})}catch{}}}}function Ol(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(JR)),t.bitbucket?.apiToken&&(e.push(`https://${Kt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(ZR)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(QR)),yy(e,r)}function ky(t,e){if(t.contextWrite?.token){let r=kr(e)??"github.com",n=io(r);return yy([`https://${n}:${t.contextWrite.token}@${r}`],[mi(r)])}return Ol(t)}var JR,ZR,QR,wy=$(()=>{"use strict";F();JR=mi("github.com"),ZR=mi("bitbucket.org"),QR=mi("gitlab.com")});import{spawn as $y}from"node:child_process";import{existsSync as hi,mkdirSync as Oo,readFileSync as eT,rmSync as Ll,symlinkSync as tT}from"node:fs";import{homedir as rT}from"node:os";import{dirname as Rn,join as er}from"node:path";function vy(t){let e=er(rT(),".codepipe-sandbox","repos");return t?er(e,t):e}function xy(t,e){let n=(En.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{En.get(t)===o&&En.delete(t)},()=>{En.get(t)===o&&En.delete(t)});return En.set(t,o),n}function by(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 nT(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 Sy(t,e,r,n,o){let s=async c=>{await ce(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await ce(t,["reset","--hard",`origin/${c}`],o),await ce(t,["clean","-fdx"],o)},i=async()=>{try{return await s(r),r}catch(c){if(!n||n===r||!by(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await s(n),n}},a=async()=>{hi(t)&&Ll(t,{recursive:!0,force:!0}),Oo(Rn(t),{recursive:!0});try{return await ce(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!by(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),hi(t)&&Ll(t,{recursive:!0,force:!0}),Oo(Rn(t),{recursive:!0}),await ce(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(hi(er(t,".git")))try{return await i()}catch(c){if(!nT(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 Ey(t){await ce(t.workspacePath,["reset","--hard",t.baseSha]),await ce(t.workspacePath,["clean","-fdx"])}async function Ry(t,e){let r=t.workspacePath;await ce(r,["add","-A"]);let n=(await Pe(r,["write-tree"])).trim(),o=(await Pe(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let s={...process.env,GIT_AUTHOR_NAME:Tn,GIT_AUTHOR_EMAIL:In,GIT_COMMITTER_NAME:Tn,GIT_COMMITTER_EMAIL:In};return(await Pe(r,["commit-tree",n,"-m",e],s)).trim()}async function Ty(t,e,r,n,o){try{await ce(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(s){let i=s instanceof Error?s.message:String(s);throw kr(n)==="github.com"&&/without `?workflow`? scope|workflow.*scope/i.test(i)?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"+i):s}}async function Iy(t,e){return Pe(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Cy(t,e,r,n,o){await ce(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await ce(t.workspacePath,["checkout","--force",r])}async function Ay(t,e,r,n,o,s){let i=t.workspacePath;await ce(i,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],s);let a=(await Pe(i,["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=>Pe(i,["rev-parse","-q","--verify",`${f}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await Pe(i,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ce(i,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],s).catch(g=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(g)}`)}),await c(n)||await ce(i,["fetch","origin",n],s).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={...s??process.env,GIT_AUTHOR_NAME:Tn,GIT_AUTHOR_EMAIL:In,GIT_COMMITTER_NAME:Tn,GIT_COMMITTER_EMAIL:In},u=(await Pe(i,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),p=(await Pe(i,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await ce(i,["cherry-pick","--quit"],l).catch(()=>{});let d=null;try{await ce(i,["cherry-pick","--no-commit",p],l)}catch(f){d=f instanceof Error?f.message:String(f)}let m=(await Pe(i,["diff","--name-only","--diff-filter=U"])).split(`
839
+ `).map(f=>f.trim()).filter(f=>f.length>0);if(d&&m.length===0)throw await ce(i,["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 Dl(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:Tn,GIT_AUTHOR_EMAIL:In,GIT_COMMITTER_NAME:Tn,GIT_COMMITTER_EMAIL:In};(await Pe(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ce(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 ce(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let i=null;try{await ce(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){i=l instanceof Error?l.message:String(l)}let a=(await Pe(n,["diff","--name-only","--diff-filter=U"])).split(`
840
+ `).map(l=>l.trim()).filter(l=>l.length>0),c=await Pe(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(i&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${i}`);return a}function ce(t,e,r){return new Promise((n,o)=>{let s=$y("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),i=[];s.stderr.setEncoding("utf-8"),s.stderr.on("data",a=>i.push(a)),s.on("error",o),s.on("close",a=>{if(a===0)return n();o(new Error(`git ${e[0]} failed (exit ${a}):
841
+ ${i.join("").trim()||"(no stderr)"}`))})})}function Pe(t,e,r){return new Promise((n,o)=>{let s=$y("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),i=[],a=[];s.stdout.setEncoding("utf-8"),s.stderr.setEncoding("utf-8"),s.stdout.on("data",c=>i.push(c)),s.stderr.on("data",c=>a.push(c)),s.on("error",o),s.on("close",c=>{if(c===0)return n(i.join(""));o(new Error(`git ${e[0]} failed (exit ${c}):
842
+ ${a.join("").trim()||"(no stderr)"}`))})})}function Py(t,e){hi(t)&&Ll(t,{recursive:!0,force:!0}),Oo(Rn(t),{recursive:!0}),tT(e,t,"dir")}async function _y(t,e,r){await ce(t,["worktree","prune"]).catch(()=>{}),Oo(Rn(r),{recursive:!0}),await ce(t,["worktree","add","--detach",r,`origin/${e}`])}async function oT(t,e,r){Oo(Rn(r),{recursive:!0}),await ce(Rn(r),["clone","--quiet","--no-checkout",t,r]),await ce(r,["checkout","--force","--detach",e])}async function jy(t,e,r,n="worktree",o,s){return r.length===0?[]:xy(e,async()=>{let i=[];for(let a of r){let c=er(vy(s),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await Sy(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 Pe(c,["rev-parse","HEAD"])).trim(),p=er(t,"code",a.name);n==="direct"?(Py(p,c),console.log(`[git] code: linked ${p} \u2192 ${c} @ ${u.slice(0,10)}`)):n==="clone"?(await oT(c,u,p),console.log(`[git] code: clone ${p} \u2190 ${c} @ ${u.slice(0,10)}`)):(await _y(c,l,p),console.log(`[git] code: worktree ${p} \u2190 ${c} @ ${u.slice(0,10)}`)),i.push({name:a.name,workspacePath:p,cachePath:c,ref:l,baseSha:u})}return i})}async function Ny(t,e,r,n="worktree",o,s){if(!r||!r.cloneUrl)return null;let i=r;return xy(e,async()=>{let a=er(vy(s),e,"_context");console.log(`[git] context: ensure ${i.cloneUrl} @ ${i.ref} \u2192 ${a}`);try{await Sy(a,i.cloneUrl,i.ref,void 0,o)}catch(u){throw new Error(`failed to materialize context repo (${i.cloneUrl}): `+(u instanceof Error?u.message:String(u)))}let c=er(t,"context");n==="direct"?(Py(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await _y(a,i.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await Pe(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function Oy(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await ce(r,["add","-A",...n]).catch(()=>{});let o;try{o=await Pe(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let s=o.split(`
843
+ `).map(a=>a.trim()).filter(a=>a.length>0),i=[];for(let a of s)try{let c=eT(er(r,a)).toString("base64");i.push({path:a,contentBase64:c})}catch{}return i}var En,Tn,In,Ly=$(()=>{"use strict";F();En=new Map;Tn="CodePipe Agent",In="codepipe@codepartner.ee"});import{existsSync as sT,readFileSync as iT}from"node:fs";import{join as aT}from"node:path";import{parse as cT}from"yaml";function Dy(t){if(!t)return!1;let e=aT(t,Ml);if(!sT(e))return!1;try{let r=cT(iT(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 Ml,My=$(()=>{"use strict";Ml="knowledge/build.yaml"});import{readFileSync as lT}from"node:fs";import{join as uT}from"node:path";function Uy(t){let e=uT(t,Lo),r;try{r=lT(e,"utf-8")}catch{throw new tr(`BUILD produced no ${Lo} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new tr(`${Lo} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new tr(`${Lo} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new tr(`${Lo}: "ok" must be a boolean`);let s=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"?dT(o.logTail):"",l={ok:s,steps:a,logTail:c};if(typeof o.failedStep=="string"&&o.failedStep)l.failedStep=o.failedStep;else if(!s){let u=a.find(p=>p.exitCode!==0);u&&(l.failedStep=u.name)}return l}function dT(t){let e=Buffer.from(t,"utf-8");return e.length<=Ul?t:`\u2026 [${e.length-Ul} bytes elided] \u2026
844
+ `+e.subarray(e.length-Ul).toString("utf-8")}var Ul,tr,Lo,By=$(()=>{"use strict";Ul=8*1024,tr=class extends Error{},Lo="meta/build-result.json"});import{readFileSync as pT}from"node:fs";import{join as fT}from"node:path";function Ky(t){let e=fT(t,Cn),r;try{r=pT(e,"utf-8")}catch{throw new Mt(`code review produced no ${Cn} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(c){throw new Mt(`${Cn} is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(!n||typeof n!="object")throw new Mt(`${Cn} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new Mt(`${Cn}: "approved" must be a boolean`);let s=o.approved,i=typeof o.remarks=="string"?Fy(o.remarks,mT):"";if(!s&&i.trim().length===0)throw new Mt(`${Cn}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?Fy(o.summary,hT):"";return{approved:s,remarks:i,summary:a}}function Fy(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
845
+ \u2026 [${r.length-e} bytes elided]`}var mT,hT,Mt,Cn,Gy=$(()=>{"use strict";mT=16*1024,hT=4*1024,Mt=class extends Error{},Cn="meta/review-result.json"});import{readFileSync as gT,statSync as yT}from"node:fs";import{join as Hy}from"node:path";function ST(t){return t.startsWith("meta/")||xT.has(t)}function ET(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 RT(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function Wy(t,e,r){let n=r?.maxBytes??kT,o=r?.totalBytes??wT,s=r?.maxCount??bT,i=e.map((f,g)=>{let h=null;try{h=yT(Hy(t,f)).size}catch{}return{path:f,index:g,size:h}}),a=[...i].sort((f,g)=>{let h=w=>ST(w.path)?0:1;return h(f)!==h(g)?h(f)-h(g):(f.size??0)-(g.size??0)}),c=a.slice(0,s),l=a.slice(s).sort((f,g)=>f.index-g.index).map(f=>f.path),u=new Array(i.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=gT(Hy(t,f.path))}catch{}if(g!==null){d+=g.length,u[f.index]={path:f.path,contentBase64:g.toString("base64")};continue}let h=f.size===null?RT(f.path):ET(f.path,f.size,n,o),w=Buffer.from(h,"utf-8");d+=w.length,u[f.index]={path:f.path,contentBase64:w.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,vT),g=`# Artifacts omitted from upload
846
+
847
+ ${l.length} file(s) exceeded the SANDBOX artifact count budget (${s}) 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.
848
+
849
+ `+f.map(h=>`- ${h}
850
+ `).join("")+(l.length>f.length?`
851
+ \u2026and ${l.length-f.length} more.
852
+ `:"");m.push({path:$T,contentBase64:Buffer.from(g,"utf-8").toString("base64")})}return{artifacts:m,omitted:p,dropped:l}}var kT,wT,bT,$T,vT,xT,qy=$(()=>{"use strict";kT=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),wT=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),bT=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),$T="artifacts-omitted.md",vT=500,xT=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 TT,mkdtempSync as IT,readFileSync as CT,readdirSync as Vy,rmSync as Yy}from"node:fs";import{tmpdir as AT}from"node:os";import{join as gi,relative as PT}from"node:path";function zy(t){let e=IT(gi(AT(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Yy(e,{recursive:!0,force:!0}),listFiles:()=>Xy(e,e),readFile:r=>CT(gi(e,r),"utf-8"),clean:()=>{for(let r of Vy(e))jT.has(r)||Yy(gi(e,r),{recursive:!0,force:!0})}}}function Xy(t,e){let r=[];for(let n of Vy(e)){let o=gi(e,n),s=TT(o);if(!s.isSymbolicLink())if(s.isDirectory()){if(e===t&&_T.has(n))continue;r.push(...Xy(t,o))}else r.push(PT(t,o))}return r}var _T,jT,Jy=$(()=>{"use strict";_T=new Set(["code","context","scratch",".claude"]),jT=new Set(["code","context"])});import{existsSync as ki,readFileSync as Zy,readdirSync as Bl}from"node:fs";import{join as Ut}from"node:path";import{parse as NT}from"yaml";function wi(t){if(!ki(t))return[];let e=[];for(let r of Bl(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=Ut(t,r.name);r.isDirectory()?e.push(...wi(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function yi(t){try{return NT(Zy(t,"utf-8"))}catch{return null}}function Qy(t){let e={nodes:new Map,adjacency:new Map,events:new Map,annotations:new Map,keyByEntity:new Map,orphanedEntities:new Set,empty:!0},r=(s,i,a,c)=>{e.adjacency.has(s)||e.adjacency.set(s,[]),e.adjacency.has(i)||e.adjacency.set(i,[]),e.adjacency.get(s).push({to:i,kind:a,weight:c}),e.adjacency.get(i).push({to:s,kind:a,weight:c})};for(let s of wi(Ut(t,"model/derived/structure"))){let i=Ct(yi(s));if(i.ok){for(let a of i.value.nodes)e.nodes.set(a.key,a);for(let a of i.value.edges)r(a.from,a.to,a.kind,a.weight??1)}}for(let s of[...wi(Ut(t,"model/derived/correlates")),Ut(t,"model/derived/relates.yaml")]){if(!ki(s))continue;let i=Zn(yi(s));if(i.ok)for(let a of i.value.edges)r(a.from,a.to,a.kind,a.weight??1)}let n=Ut(t,"model/facts/events");if(ki(n))for(let s of Bl(n).sort()){if(!s.endsWith(".yaml"))continue;let i=At(yi(Ut(n,s)));if(!i.ok)continue;let a=i.value;e.events.set(a.taskKey,a);let c=ke(a.taskKey);for(let l of a.files)r(c,l.key,"touched_by",1);for(let l of a.links?.adr??[])r(c,`adr::${l}`,"references",1);for(let l of a.links?.tasks??[])r(c,ke(l),"references",1)}for(let s of wi(Ut(t,"model/facts/identity"))){let i=Qn(yi(s));if(i.ok)for(let a of i.value.entities)a.status==="orphaned"?e.orphanedEntities.add(a.entityId):e.keyByEntity.set(a.entityId,a.currentKey)}let o=Ut(t,"model/facts/annotations");if(ki(o)){for(let s of Bl(o).sort())if(s.endsWith(".md"))try{let i=Zy(Ut(o,s),"utf-8"),a=/^---\n[\s\S]*?entityId:\s*(e_[0-9a-f]{8})[\s\S]*?\n---\n?([\s\S]*)$/.exec(i);a&&e.annotations.set(a[1],a[2].trim())}catch{}}return e.empty=e.nodes.size===0&&e.events.size===0,e}var ek=$(()=>{"use strict";F()});function rk(t){return new Set((t.toLowerCase().match(/[a-zа-я0-9_]{4,}/g)??[]).filter(e=>!/^\d+$/.test(e)))}function FT(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 nk(t){let{taskKey:e,title:r,text:n,model:o}=t,s=new Map,i=(m,f)=>{(s.get(m)??0)<f&&s.set(m,f)};(o.events.has(e)||o.adjacency.has(ke(e)))&&i(ke(e),tk);for(let m of`${r}
853
+ ${n}`.match(BT)??[]){if(m===e)continue;let f=ke(m);(o.events.has(m)||o.adjacency.has(f))&&i(f,tk)}let a=new Map;for(let m of o.nodes.keys()){let f=re(m);if(f?.level!=="code")continue;let g=f.path.slice(f.path.lastIndexOf("/")+1);for(let h of[f.path,g])a.has(h)||a.set(h,[]),a.get(h).push(m)}let c=`${r}
854
+ ${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&&i(g[0],OT)}let l=new Map,u=(m,f)=>{let g=m.toLowerCase();!g||g.length<4||l.set(g,l.has(g)&&l.get(g)!==f?null:f)};for(let m of o.nodes.keys()){let f=re(m);if(!f)continue;let g=f.path.slice(f.path.lastIndexOf("/")+1);f.level==="code"&&u(g.replace(/\.[a-z0-9]+$/i,""),m),f.level==="component"&&u(g,m)}for(let m of`${r}
855
+ ${n}`.match(/[A-Za-z][A-Za-z0-9_-]{3,}/g)??[]){let f=l.get(m.toLowerCase());f&&i(f,LT)}let p=rk(`${r}
856
+ ${n}`),d=[];for(let[m,f]of o.events){if(m===e||!f.title)continue;let g=FT(p,rk(f.title));g>=MT&&d.push({key:ke(m),score:g})}return d.sort((m,f)=>f.score-m.score||(m.key<f.key?-1:1)).slice(0,UT).forEach(m=>i(m.key,DT)),s}var tk,OT,LT,DT,MT,UT,BT,ok=$(()=>{"use strict";F();tk=1,OT=.9,LT=.7,DT=.5,MT=.15,UT=3,BT=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g});function sk(t,e,r={}){let n=r.cutoff??fr.activationCutoff,o=r.topK??fr.topKPerNode,s=r.nodeCap??fr.nodeCap,i=new Map;for(let[l,u]of e)i.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)||(i.get(l.key)?.activation??0)>l.activation)continue;if(c.add(l.key),c.size>s)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=na[p.kind]??.3,m=l.activation*d*Math.min(p.weight,1);if(m<n)continue;let f=i.get(p.to);(!f||f.activation<m)&&(i.set(p.to,{activation:m,via:{from:l.key,kind:p.kind}}),a.push({key:p.to,activation:m}))}}return i}var ik=$(()=>{"use strict";F()});import{existsSync as Kl,readFileSync as ak,readdirSync as KT}from"node:fs";import{join as vi}from"node:path";function Fl(t){return Math.ceil(t.length/4)}function bi(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 rr(t){let e=re(t);return e?(e.level==="task"||e.level==="adr",e.path):t}function $i(t){if(!t.via)return"matched from the task text";let e=rr(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 qT(t,e){let r=/^ADR-(\d{3,4})$/.exec(e)?.[1];if(!r)return null;let n=vi(t,"adr");if(!Kl(n))return null;let o=r.padStart(4,"0");for(let s of KT(n).sort())if(!(!s.startsWith(`${o}-`)||!s.endsWith(".md")))try{return{file:`adr/${s}`,content:ak(vi(n,s),"utf-8").trim()}}catch{return null}return null}function ck(t){let{taskKey:e,title:r,contextDir:n,model:o,activated:s}=t,i=t.budgetTokens??fr.budgetTokens,a=[],c=0,l=R=>{let b=Fl(R);return c+b>i?!1:(a.push(R),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(`
857
+ `));let u=bi(s,R=>R.startsWith("adr::")),p=!1;for(let R of u){let b=qT(n,rr(R.key));if(!b)continue;let I=`${p?"":`
782
858
  ## Governing decisions
783
859
  `}
784
- ### ${Vt(E.key)} (\`${b.file}\`, ${as(E)})
860
+ ### ${rr(R.key)} (\`${b.file}\`, ${$i(R)})
785
861
 
786
862
  ${b.content}
787
- `;if(!l(R))break;p=!0}let d=ss(i,E=>o.nodes.get(E)?.entityId!==void 0).filter(E=>o.annotations.has(o.nodes.get(E.key).entityId)),f=t.staleKeys??new Set,m=!1;for(let E of d){let b=o.nodes.get(E.key).entityId,R=o.annotations.get(b),N=f.has(E.key)?" \u2014 \u26A0 the file changed since the map was built":o.orphanedEntities.has(b)?" \u2014 \u26A0 the file no longer exists":"",F=`${m?"":`
863
+ `;if(!l(I))break;p=!0}let d=bi(s,R=>o.nodes.get(R)?.entityId!==void 0).filter(R=>o.annotations.has(o.nodes.get(R.key).entityId)),m=t.staleKeys??new Set,f=!1;for(let R of d){let b=o.nodes.get(R.key).entityId,I=o.annotations.get(b),D=m.has(R.key)?" \u2014 \u26A0 the file changed since the map was built":o.orphanedEntities.has(b)?" \u2014 \u26A0 the file no longer exists":"",K=`${f?"":`
788
864
  ## Why the code is shaped this way (intent notes)
789
865
  `}
790
- ### \`${Vt(E.key)}\`${N}
866
+ ### \`${rr(R.key)}\`${D}
791
867
 
792
- ${R}
793
- `;if(!l(F))break;m=!0}let h=ve(e),g=ss(i,E=>E.startsWith("task::")&&E!==h).slice(0,KT),w=!1;for(let E of g){let b=o.events.get(Vt(E.key));if(!b)continue;let R=[...b.files].filter(L=>!f.has(L.key)&&(!L.entityId||!o.orphanedEntities.has(L.entityId))).sort((L,A)=>(A.churn??0)-(L.churn??0)||(L.key<A.key?-1:1)).slice(0,3).map(L=>`\`${Vt(L.key)}\``).join(", "),N="",F=b.links?.solution??[`tasks/${b.taskKey}/PLAN.md`,`tasks/${b.taskKey}/SOLUTION.md`].find(L=>Gc(cs(n,L)))??`tasks/${b.taskKey}/PLAN.md`,C=cs(n,F);if(Gc(C))try{N=`
794
- > ${iy(C,"utf-8").trim().slice(0,WT).replace(/\n+/g," ").trim()}\u2026
795
- > _(full text: \`${F}\`)_`}catch{}let k=`${w?"":`
868
+ ${I}
869
+ `;if(!l(K))break;f=!0}let g=ke(e),h=bi(s,R=>R.startsWith("task::")&&R!==g).slice(0,GT),w=!1;for(let R of h){let b=o.events.get(rr(R.key));if(!b)continue;let I=[...b.files].filter(k=>!m.has(k.key)&&(!k.entityId||!o.orphanedEntities.has(k.entityId))).sort((k,U)=>(U.churn??0)-(k.churn??0)||(k.key<U.key?-1:1)).slice(0,3).map(k=>`\`${rr(k.key)}\``).join(", "),D="",K=b.links?.solution??[`tasks/${b.taskKey}/PLAN.md`,`tasks/${b.taskKey}/SOLUTION.md`].find(k=>Kl(vi(n,k)))??`tasks/${b.taskKey}/PLAN.md`,ee=vi(n,K);if(Kl(ee))try{D=`
870
+ > ${ak(ee,"utf-8").trim().slice(0,WT).replace(/\n+/g," ").trim()}\u2026
871
+ > _(full text: \`${K}\`)_`}catch{}let C=`${w?"":`
796
872
  ## Related past tasks
797
873
  `}
798
- - **${b.taskKey}**${b.title?` \u2014 ${b.title}`:""}${b.date?` (${b.date})`:""}, ${as(E)}. Files: ${R||"\u2014"}.${N}`;if(!l(k))break;w=!0}let y=E=>{if(f.has(E.key))return!1;let b=o.nodes.get(E.key)?.entityId;return!b||!o.orphanedEntities.has(b)},x=ss(i,E=>E.startsWith("code:")),T=x.filter(y).slice(0,HT);if(T.length>0){let E=["","## Files likely involved",""];for(let b of T){let R=`- \`${Vt(b.key)}\` \u2014 ${as(b)}`;if(c+Fc(E.join(`
799
- `))+Fc(R)>s)break;E.push(R)}E.length>3&&l(E.join(`
800
- `))}let I=x.filter(E=>!y(E)).slice(0,10);if(I.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.","",...I.map(b=>`- \`${Vt(b.key)}\` \u2014 ${as(b)}${f.has(b.key)?" (changed since the map was built)":" (file gone)"}`)];l(E.join(`
874
+ - **${b.taskKey}**${b.title?` \u2014 ${b.title}`:""}${b.date?` (${b.date})`:""}, ${$i(R)}. Files: ${I||"\u2014"}.${D}`;if(!l(C))break;w=!0}let y=R=>{if(m.has(R.key))return!1;let b=o.nodes.get(R.key)?.entityId;return!b||!o.orphanedEntities.has(b)},x=bi(s,R=>R.startsWith("code:")),S=x.filter(y).slice(0,HT);if(S.length>0){let R=["","## Files likely involved",""];for(let b of S){let I=`- \`${rr(b.key)}\` \u2014 ${$i(b)}`;if(c+Fl(R.join(`
875
+ `))+Fl(I)>i)break;R.push(I)}R.length>3&&l(R.join(`
876
+ `))}let T=x.filter(R=>!y(R)).slice(0,10);if(T.length>0){let R=["","## Possibly stale (verify before trusting)","","These entries reference files that changed after the map was built or","no longer exist at their recorded location. Useful as history, wrong","as current fact.","",...T.map(b=>`- \`${rr(b.key)}\` \u2014 ${$i(b)}${m.has(b.key)?" (changed since the map was built)":" (file gone)"}`)];l(R.join(`
801
877
  `))}return a.length<=1?null:a.join(`
802
878
  `)+`
803
- `}var KT,HT,WT,ay=v(()=>{"use strict";G();KT=5,HT=300,WT=400});var dy={};Rr(dy,{assembleContextPack:()=>XT});import{createHash as YT}from"node:crypto";import{existsSync as cy,readFileSync as ly}from"node:fs";import{join as uy}from"node:path";function VT(t){return YT("sha1").update(`blob ${t.length}\0`).update(t).digest("hex")}function zT(t,e,r){let n=new Set;for(let o of e.keys()){let i=Q(o);if(i?.level!=="code")continue;let s=t.nodes.get(o);if(!s?.contentHash)continue;let a=r.get(i.repo);if(!a)continue;let c=uy(a,i.path);try{if(!cy(c)){n.add(o);continue}VT(ly(c)).startsWith(s.contentHash)||n.add(o)}catch{}}return n}function XT(t){let e=Jh(t.contextDir);if(e.empty)return null;let r="",n=uy(t.contextDir,`tasks/${t.taskKey}/task.md`);if(cy(n))try{r=ly(n,"utf-8")}catch{r=""}let o=ty({taskKey:t.taskKey,title:t.title,text:r,model:e});if(o.size===0)return null;let i=ny(e,o),s=t.repoDirs?zT(e,i,t.repoDirs):new Set;return sy({taskKey:t.taskKey,title:t.title,contextDir:t.contextDir,model:e,activated:i,staleKeys:s,...t.budgetTokens!==void 0?{budgetTokens:t.budgetTokens}:{}})}var py=v(()=>{"use strict";G();Qh();ry();oy();ay()});import{mkdirSync as fy,readFileSync as my,readdirSync as JT,writeFileSync as gy}from"node:fs";import{homedir as QT}from"node:os";import{dirname as ZT,join as zt}from"node:path";function tE(t){let e=Buffer.from(t,"utf-8");if(e.length<=ls)return t;let r=Math.floor(ls/4),n=ls-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}
804
-
805
- \u2026 [${s} bytes elided \u2014 log capped at ${ls} bytes for upload] \u2026
806
-
807
- ${i}`}function rE(){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={}){zi();let e=Ae(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=Bg(t.profile,e.sandboxId,!!V("SANDBOX_CONFIG")),s=zt(QT(),".codepipe","logs"),a=zo("SANDBOX_LOG",i,s);if(a.enabled){let C=new Fr(a);Xo(C),console.log(`[log] file logging \u2192 ${C.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${Ue} (protocol ${lt})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=eh(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=ih();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let u=new an(e.hubUrl,e.token),p=!1,d=new AbortController,f=new Map,m=null,h=null,g=!1,w=()=>{let C=u.openControlSocket();return m=C,C.on("open",()=>{console.log("[ws] connected");let k={type:"sandbox_hello",platformVersion:Ue,protocolVersion:lt};C.send(JSON.stringify(k))}),C.on("message",k=>{let L=k.toString("utf-8"),A=null;try{let H=JSON.parse(L);H&&typeof H=="object"&&(A=H)}catch{}if(A&&A.type==="hello"){let H=A;h=Ao(H.protocolVersion);let q=h?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${H.platformVersion} (protocol ${H.protocolVersion}) \u2014 ${q}`),h&&(g=!1);return}if(A&&A.type==="pause_job"){let H=typeof A.jobId=="string"?A.jobId:"",q=H?f.get(H):void 0;q?(console.warn(`[ws] pause_job ${H} \u2014 aborting agent`),q.paused=!0,q.abort.abort()):console.log(`[ws] pause_job ${H} \u2014 not a running job, ignoring`),H&&C.send(JSON.stringify({type:"job_paused",jobId:H}));return}if(A&&(A.type==="chat_user_message"||A.type==="chat_finalize")){let H=typeof A.jobId=="string"?A.jobId:"",q=H?f.get(H):void 0;if(q?.chatInbox)if(A.type==="chat_user_message"){let Z=typeof A.text=="string"?A.text:"";Z.trim()&&q.chatInbox.push({kind:"user",text:Z})}else q.chatInbox.finalize();else console.log(`[ws] ${String(A.type)} ${H} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${L}`)}),C.on("close",(k,L)=>{console.log(`[ws] closed code=${k} reason=${L?.toString()||""}`),m===C&&(m=null),!p&&setTimeout(w,2e3)}),C.on("error",k=>console.warn(`[ws] error: ${k.message}`)),C},y=w(),x=async C=>{for(;!p;){if(h===!1){g||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${Ue}, protocol ${lt}) \u2014 not claiming jobs until versions align.`),g=!0),await new Promise(k=>setTimeout(k,5e3));continue}try{let k=await u.claim(d.signal,C);if(k.status===204)continue;if(k.status===401){console.error("[claim] 401 unauthorized \u2014 the HUB does not know this worker registration. It was removed; re-register with `codepipe up --reregister` (or `codepipe worker register --force`). exiting."),process.exitCode=1,p=!0;break}if(!k.ok){console.warn(`[claim:${C}] ${k.status} \u2014 backoff 5s`),await new Promise(A=>setTimeout(A,5e3));continue}let L=await k.json();await T(u,L)}catch(k){if(d.signal.aborted)break;let L=k instanceof Error?k.message:String(k);console.warn(`[claim:${C}] error: ${L} \u2014 backoff 5s`),await new Promise(A=>setTimeout(A,5e3))}}};async function T(C,k){let L={abort:new AbortController,paused:!1};k.role==="chat"&&(L.chatInbox=rE()),f.set(k.jobId,L);let A=!1,H=null,q=null,Z=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),Ye=async()=>{try{await C.heartbeat(k.jobId)==="claim_lost"&&(A=!0,console.warn(`[job] ${k.jobId} claim lost \u2014 HUB sweeper took it`))}catch(J){let we=J instanceof Error?J.message:String(J);console.warn(`[job] ${k.jobId} heartbeat error: ${we}`)}};Ye();let Ve=setInterval(()=>{Ye()},Z),ge=new Date().toISOString();console.log(`[job] ${k.jobId} claimed \u2014 role=${k.role} task=${k.taskId} phase=${k.phase}`),console.log(`[job] ${k.jobId} prompt (${k.prompt.length} chars):`),console.log(E(k.prompt," \u2502 "));let _=[],M=null,D=400,z=25,O=500,S=()=>{if(M&&(clearTimeout(M),M=null),_.length===0)return;let J=_.splice(0,_.length),we=m;if(!we||we.readyState!==we.OPEN)return;let te={type:"agent_activity",jobId:k.jobId,taskId:k.taskId,projectId:k.projectId,role:k.role,phase:k.phase,events:J};try{we.send(JSON.stringify(te))}catch{}},$=J=>{_.push(J),_.length>O&&_.shift(),_.length>=z?S():M||(M=setTimeout(S,D))},j=k.role==="analysis"&&k.taskId.startsWith("draft::")?k.taskId.slice(7):null,Y=new Set,ke=null;try{if(!c){A||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:ge,finishedAt:new Date().toISOString()});return}if(!th(o,k.provider??null)){A||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${k.provider??"claude"}"`},startedAt:ge,finishedAt:new Date().toISOString()});return}let J=Yh(k.jobId);console.log(`[job] ${k.jobId} workspace=${J.dir}`);let we=I(k,r);H=we.gitCreds,q=we.contextGitCreds;let te=H?.env,fl=we.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:we.claudeOauthToken}:void 0,at=[],Ct=null,$s=null;try{let B=k.role==="build"?"clone":"worktree";at=await Ph(J.dir,k.projectId,k.projectRepos,B,te,n);let U=await _h(J.dir,k.projectId,k.contextRepo,"worktree",te,n);$s=U,Ct=U?.workspacePath??null}catch(B){let U=B instanceof Error?B.message:String(B);console.warn(`[job] ${k.jobId} materialize failed: ${U}`),A||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${U}`},startedAt:ge,finishedAt:new Date().toISOString()}),J.dispose();return}let An=k.model;k.role==="build"&&k.modelDiscovery&&!Oh(Ct)&&(An=k.modelDiscovery,console.log(`[job] ${k.jobId} BUILD discovery (no steps in ${Mc}) \u2014 model=${An}`));let ml=async()=>{if(!k.deliveries||k.deliveries.length===0)return[];let B=k.contextRepo?.cloneUrl;if(!B||!te)throw new Error(B?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let U=[];for(let ee of k.deliveries){let re=at.find(be=>be.name===ee.name);if(re){if(k.role==="implement"&&ee.baseSha&&ee.baseSha!==re.baseSha){let be=await Rh(re,ee.deliveryRef,ee.deliverySha,ee.baseSha,B,te);console.log(`[job] ${k.jobId} ${re.name}: base moved ${ee.baseSha.slice(0,10)} \u2192 ${re.baseSha.slice(0,10)} \u2014 re-applied delivery ${ee.deliverySha.slice(0,10)} (${be.length} conflicted file(s))`),be.length>0&&U.push(`- **${re.name}**:`,...be.map(_n=>` - \`${_n}\``));continue}await Ih(re,ee.deliveryRef,ee.deliverySha,B,te),console.log(`[job] ${k.jobId} ${re.name}: checked out delivery ${ee.deliverySha.slice(0,10)} for ${k.role}`)}}return U},vs=[];if(k.role==="build"||k.role==="implement"||k.role==="code-review")try{vs=await ml()}catch(B){let U=B instanceof Error?B.message:String(B);console.warn(`[job] ${k.jobId} delivery checkout failed: ${U}`),A||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${U}`},startedAt:ge,finishedAt:new Date().toISOString()}),J.dispose();return}let xs=k.role==="resolve-conflict"?k.metadata?.taskBranchByRepo??{}:{},gl="";if(k.role==="resolve-conflict"){if(!at.some(B=>xs[B.name])){let B="resolve-conflict job carries no task branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${k.jobId} ${B}`),A||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:B},startedAt:ge,finishedAt:new Date().toISOString()}),J.dispose();return}try{let B=[];for(let U of at){let ee=xs[U.name];if(!ee)continue;let re=await Dc(U,ee,te);console.log(`[job] ${k.jobId} ${U.name}: merged ${ee} into ${U.ref} \u2014 ${re.length} conflicted file(s)`),re.length>0?B.push(`- **${U.name}**:`,...re.map(be=>` - \`${be}\``)):B.push(`- **${U.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}gl=`
879
+ `}var GT,HT,WT,lk=$(()=>{"use strict";F();GT=5,HT=300,WT=400});var fk={};Be(fk,{assembleContextPack:()=>XT});import{createHash as YT}from"node:crypto";import{existsSync as uk,readFileSync as dk}from"node:fs";import{join as pk}from"node:path";function VT(t){return YT("sha1").update(`blob ${t.length}\0`).update(t).digest("hex")}function zT(t,e,r){let n=new Set;for(let o of e.keys()){let s=re(o);if(s?.level!=="code")continue;let i=t.nodes.get(o);if(!i?.contentHash)continue;let a=r.get(s.repo);if(!a)continue;let c=pk(a,s.path);try{if(!uk(c)){n.add(o);continue}VT(dk(c)).startsWith(i.contentHash)||n.add(o)}catch{}}return n}function XT(t){let e=Qy(t.contextDir);if(e.empty)return null;let r="",n=pk(t.contextDir,`tasks/${t.taskKey}/task.md`);if(uk(n))try{r=dk(n,"utf-8")}catch{r=""}let o=nk({taskKey:t.taskKey,title:t.title,text:r,model:e});if(o.size===0)return null;let s=sk(e,o),i=t.repoDirs?zT(e,s,t.repoDirs):new Set;return ck({taskKey:t.taskKey,title:t.title,contextDir:t.contextDir,model:e,activated:s,staleKeys:i,...t.budgetTokens!==void 0?{budgetTokens:t.budgetTokens}:{}})}var mk=$(()=>{"use strict";F();ek();ok();ik();lk()});var hk={};Be(hk,{SKILLS_DIR:()=>Gl,loadSkills:()=>cI,materializeSkills:()=>lI,renderSkillsBlock:()=>uI});import{cpSync as JT,existsSync as ZT,mkdirSync as QT,readFileSync as eI,readdirSync as tI}from"node:fs";import{dirname as rI,join as An}from"node:path";import{fileURLToPath as nI}from"node:url";import{parse as oI}from"yaml";function iI(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
880
+ ---`,3);return r===-1?null:{yaml:e.slice(e.indexOf(`
881
+ `,3)+1,r),body:e.slice(e.indexOf(`
882
+ `,r+1)+1)}}function aI(t,e,r){let n=[],o=[];if(!ZT(t))return{skills:n,errors:o};let s;try{s=tI(t,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>i.name).sort()}catch(i){return{skills:n,errors:[{source:r,error:`cannot read: ${String(i)}`}]}}for(let i of s){let a=An(t,i),c=`${r}/${i}`,l;try{l=eI(An(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=oI(u.yaml)}catch(m){o.push({source:c,error:`frontmatter is not valid YAML: ${String(m)}`});continue}let d=Na({name:i,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 cI(t){let e=[],r=(i,a,c)=>{let l=aI(i,a,c);return e.push(...l.errors),l.skills},n=t.sources.bundled?r(sI,"bundled","bundled"):[],o=t.sources.context&&t.contextDir?r(An(t.contextDir,"skills"),"context","skills"):[],s=t.sources.repo?t.repoDirs.flatMap(i=>r(An(i,".claude","skills"),"repo","repo")):[];return{skills:Oa(n,o,s),errors:e}}function lI(t,e){if(e.length===0)return[];let r=An(t,Gl);QT(r,{recursive:!0});let n=[];for(let o of e)JT(o.dir,An(r,o.name),{recursive:!0}),n.push(`${Gl}/${o.name}`);return n}function uI(t,e=[]){let r=new Set(t.map(i=>i.name)),n=e.filter(i=>!r.has(i));if(t.length===0&&n.length===0)return"";let o=[];t.length>0&&o.push("## Skills available to you","",...t.map(i=>`- **${i.name}** \u2014 ${i.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 s=e.filter(i=>r.has(i));return s.length>0&&o.push("**The approved plan requires this task to follow: "+s.map(i=>`\`${i}\``).join(", ")+".**","This is not a suggestion \u2014 a reviewer approved it as a requirement.",""),n.length>0&&o.push("**The plan prescribes "+n.map(i=>`\`${i}\``).join(", ")+", which is not available here.**","Proceed without it and say so in your result \u2014 do not invent the procedure.",""),o.join(`
883
+ `)}var Gl,sI,gk=$(()=>{"use strict";F();Gl=".claude/skills",sI=rI(nI(import.meta.url))});var bk={};Be(bk,{seedMarketplaces:()=>bI});import{spawn as dI}from"node:child_process";import{cpSync as pI,existsSync as yk,mkdirSync as kk,rmSync as Hl,symlinkSync as fI,writeFileSync as mI}from"node:fs";import{homedir as hI}from"node:os";import{join as nr}from"node:path";function wk(){return nr(hI(),".codepipe-sandbox","plugins")}function kI(t){return nr(wk(),"src",`${t.name}@${t.sha||"head"}`)}function Do(t,e){return new Promise((r,n)=>{let o=dI("git",t,{cwd:e,stdio:["ignore","ignore","pipe"],env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"}}),s=[];o.stderr.setEncoding("utf-8"),o.stderr.on("data",i=>s.push(i)),o.on("error",n),o.on("close",i=>{if(i===0)return r();n(new Error(`git ${t[0]} failed (exit ${i}): ${s.join("").trim().slice(0,400)}`))})})}async function wI(t){let e=kI(t);if(yk(nr(e,".claude-plugin","marketplace.json")))return e;Hl(e,{recursive:!0,force:!0}),kk(e,{recursive:!0});let r=`https://github.com/${t.repo}.git`;if(t.sha?(await Do(["init","--quiet"],e),await Do(["remote","add","origin",r],e),await Do(["fetch","--quiet","--depth","1","origin",t.sha],e),await Do(["checkout","--quiet","FETCH_HEAD"],e)):await Do(["clone","--quiet","--depth","1",r,e]),!yk(nr(e,".claude-plugin","marketplace.json")))throw Hl(e,{recursive:!0,force:!0}),new Error("no .claude-plugin/marketplace.json \u2014 this repository is not a marketplace");return e}async function bI(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 wI(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=nr(wk(),"seed",r.map(a=>`${a.name}@${a.sha||"head"}`).sort().join("_")),s=nr(o,gI);kk(s,{recursive:!0});let i={};for(let a of r){let c=nr(s,a.name);Hl(c,{recursive:!0,force:!0}),$I(n.get(a.name),c),i[a.name]={source:{source:"github",repo:a.repo},installLocation:c,...a.sha?{commit:a.sha}:{}}}return mI(nr(o,yI),`${JSON.stringify(i,null,2)}
884
+ `),{dir:o,ready:r,errors:e}}function $I(t,e){try{fI(t,e,"dir")}catch{pI(t,e,{recursive:!0,filter:r=>!/(^|\/)\.git(\/|$)/.test(r)})}}var gI,yI,$k=$(()=>{"use strict";gI="marketplaces",yI="known_marketplaces.json"});var Sk={};Be(Sk,{loadRoles:()=>AI});import{existsSync as vI,readFileSync as xI,readdirSync as SI}from"node:fs";import{dirname as EI,join as xk}from"node:path";import{fileURLToPath as RI}from"node:url";import{parse as TI}from"yaml";function CI(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
885
+ ---`,3);if(r===-1)return null;let n=e.slice(e.indexOf(`
886
+ `,3)+1,r),o=e.indexOf(`
887
+ `,r+1);return{yaml:n,body:o===-1?"":e.slice(o+1)}}function vk(t,e,r){let n=[],o=[];if(!vI(t))return{roles:n,errors:o};let s;try{s=SI(t).sort()}catch(i){return{roles:n,errors:[{file:r,error:`cannot read: ${String(i)}`}]}}for(let i of s){if(!i.endsWith(".md"))continue;let a=`${r}/${i}`,c;try{c=xI(xk(t,i),"utf-8")}catch(d){o.push({file:a,error:`cannot read: ${String(d)}`});continue}let l=CI(c);if(!l){o.push({file:a,error:"missing frontmatter block (--- \u2026 ---) at the top of the file"});continue}let u;try{u=TI(l.yaml)}catch(d){o.push({file:a,error:`frontmatter is not valid YAML: ${String(d)}`});continue}let p=Ia({name:i.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 AI(t){let e=vk(II,"bundled","bundled"),r=t?vk(xk(t,"roles"),"project","roles"):{roles:[],errors:[]};return{roles:Ca(e.roles,r.roles),errors:[...e.errors,...r.errors]}}var II,Ek=$(()=>{"use strict";F();II=EI(RI(import.meta.url))});var Rk={};Be(Rk,{ROLE_AGENTS_DIR:()=>ql,materializeRoleAgents:()=>NI,renderRolesBlock:()=>OI});import{mkdirSync as PI,writeFileSync as _I}from"node:fs";import{join as Wl}from"node:path";function jI(t,e){let r=["---",`name: ${t.name}`,`description: ${t.description}`,...t.model?[`model: ${t.model}`]:[],"---",""].join(`
888
+ `),n=t.refs.length>0&&e?["","## Read these first","",...t.refs.map(o=>`- \`${Wl(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(`
889
+ `):"";return`${r}${t.body}
890
+ ${n}`}function NI(t,e,r,n){let o=Aa(e,r);if(o.length===0)return{roles:[],files:[]};let s=Wl(t,ql);PI(s,{recursive:!0});let i=[];for(let a of o)_I(Wl(s,`${a.name}.md`),jI(a,n)),i.push(`${ql}/${a.name}.md`);return{roles:o,files:i}}function OI(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(`
891
+ `),"","Delegate to **every** role above, one at a time, giving each the change under","review. 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(`
892
+ `)}var ql,Tk=$(()=>{"use strict";F();ql=".claude/agents"});var Ck={};Be(Ck,{COUNCIL_ANSWER_PATH:()=>Ik,readCouncilVerdict:()=>MI});import{readFileSync as LI}from"node:fs";import{join as DI}from"node:path";function MI(t){let e;try{e=LI(DI(t,Ik),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var Ik,Ak=$(()=>{"use strict";Ik="meta/council-answer.json"});var _k={};Be(_k,{QUEUE_PLAN_PATH:()=>Pk,readQueuePlan:()=>FI});import{readFileSync as UI}from"node:fs";import{join as BI}from"node:path";function FI(t){let e;try{e=UI(BI(t,Pk),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var Pk,jk=$(()=>{"use strict";Pk="meta/queue-plan.json"});import{mkdirSync as Nk,readFileSync as xi,readdirSync as KI,writeFileSync as Ok}from"node:fs";import{homedir as GI}from"node:os";import{dirname as HI,join as Et}from"node:path";function qI(t){let e=Buffer.from(t,"utf-8");if(e.length<=Si)return t;let r=Math.floor(Si/4),n=Si-r,o=e.subarray(0,r).toString("utf-8"),s=e.subarray(e.length-n).toString("utf-8"),i=e.length-r-n;return`${o}
893
+
894
+ \u2026 [${i} bytes elided \u2014 log capped at ${Si} bytes for upload] \u2026
895
+
896
+ ${s}`}function YI(){let t=[],e=!1,r=null,n=s=>{if(r){let i=r;r=null,i({value:s,done:!1})}else t.push(s)},o=()=>{if(r){let s=r;r=null,s({value:void 0,done:!0})}};return{push(s){e||n(s)},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(s=>{r=s})}}}}}}async function Mo(t={}){let e=je(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,s=Kg(t.profile,e.sandboxId,!!J("SANDBOX_CONFIG")),i=Et(GI(),".codepipe","logs"),a=us("SANDBOX_LOG",s,i);if(a.enabled){let C=new en(a);ds(C),console.log(`[log] file logging \u2192 ${C.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${Fe} (protocol ${at})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=ry(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=ay();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let u=new wn(e.hubUrl,e.token),p=!1,d=new AbortController,m=new Map,f=null,g=null,h=!1,w=()=>{let C=u.openControlSocket();return f=C,C.on("open",()=>{console.log("[ws] connected");let k={type:"sandbox_hello",platformVersion:Fe,protocolVersion:at};C.send(JSON.stringify(k))}),C.on("message",k=>{let U=k.toString("utf-8"),P=null;try{let G=JSON.parse(U);G&&typeof G=="object"&&(P=G)}catch{}if(P&&P.type==="hello"){let G=P;g=Vn(G.protocolVersion);let Y=g?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${G.platformVersion} (protocol ${G.protocolVersion}) \u2014 ${Y}`),g&&(h=!1);return}if(P&&P.type==="pause_job"){let G=typeof P.jobId=="string"?P.jobId:"",Y=G?m.get(G):void 0;Y?(console.warn(`[ws] pause_job ${G} \u2014 aborting agent`),Y.paused=!0,Y.abort.abort()):console.log(`[ws] pause_job ${G} \u2014 not a running job, ignoring`),G&&C.send(JSON.stringify({type:"job_paused",jobId:G}));return}if(P&&(P.type==="chat_user_message"||P.type==="chat_finalize")){let G=typeof P.jobId=="string"?P.jobId:"",Y=G?m.get(G):void 0;if(Y?.chatInbox)if(P.type==="chat_user_message"){let se=typeof P.text=="string"?P.text:"";se.trim()&&Y.chatInbox.push({kind:"user",text:se})}else Y.chatInbox.finalize();else console.log(`[ws] ${String(P.type)} ${G} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${U}`)}),C.on("close",(k,U)=>{console.log(`[ws] closed code=${k} reason=${U?.toString()||""}`),f===C&&(f=null),!p&&setTimeout(w,2e3)}),C.on("error",k=>console.warn(`[ws] error: ${k.message}`)),C},y=w(),x=async C=>{for(;!p;){if(g===!1){h||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${Fe}, protocol ${at}) \u2014 not claiming jobs until versions align.`),h=!0),await new Promise(k=>setTimeout(k,5e3));continue}try{let k=await u.claim(d.signal,C);if(k.status===204)continue;if(k.status===401){console.error("[claim] 401 unauthorized \u2014 the HUB does not know this worker registration. It was removed; re-register with `codepipe up --reregister` (or `codepipe worker register --force`). exiting."),process.exitCode=1,p=!0;break}if(!k.ok){console.warn(`[claim:${C}] ${k.status} \u2014 backoff 5s`),await new Promise(P=>setTimeout(P,5e3));continue}let U=await k.json();await S(u,U)}catch(k){if(d.signal.aborted)break;let U=k instanceof Error?k.message:String(k);console.warn(`[claim:${C}] error: ${U} \u2014 backoff 5s`),await new Promise(P=>setTimeout(P,5e3))}}};async function S(C,k){let U={abort:new AbortController,paused:!1};k.role==="chat"&&(U.chatInbox=YI()),m.set(k.jobId,U);let P=!1,G=null,Y=null,se=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),qe=async()=>{try{await C.heartbeat(k.jobId)==="claim_lost"&&(P=!0,console.warn(`[job] ${k.jobId} claim lost \u2014 HUB sweeper took it`))}catch(W){let ne=W instanceof Error?W.message:String(W);console.warn(`[job] ${k.jobId} heartbeat error: ${ne}`)}};qe();let Ye=setInterval(()=>{qe()},se),_=new Date().toISOString();console.log(`[job] ${k.jobId} claimed \u2014 role=${k.role} task=${k.taskId} phase=${k.phase}`),console.log(`[job] ${k.jobId} prompt (${k.prompt.length} chars):`),console.log(R(k.prompt," \u2502 "));let B=[],O=null,X=400,L=25,E=500,v=()=>{if(O&&(clearTimeout(O),O=null),B.length===0)return;let W=B.splice(0,B.length),ne=f;if(!ne||ne.readyState!==ne.OPEN)return;let Tt={type:"agent_activity",jobId:k.jobId,taskId:k.taskId,projectId:k.projectId,role:k.role,phase:k.phase,events:W};try{ne.send(JSON.stringify(Tt))}catch{}},N=W=>{B.push(W),B.length>E&&B.shift(),B.length>=L?v():O||(O=setTimeout(v,X))},z=k.role==="analysis"&&k.taskId.startsWith("draft::")?k.taskId.slice(7):null,ve=new Set,ot=null;try{if(!c){P||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:_,finishedAt:new Date().toISOString()});return}if(!ny(o,k.provider??null)){P||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${k.provider??"claude"}"`},startedAt:_,finishedAt:new Date().toISOString()});return}let W=zy(k.jobId);console.log(`[job] ${k.jobId} workspace=${W.dir}`);let ne=T(k,r);G=ne.gitCreds,Y=ne.contextGitCreds;let Tt=G?.env,yu=ne.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:ne.claudeOauthToken}:void 0,st=[],Ve=null,Li=null;try{let j=k.role==="build"?"clone":"worktree";st=await jy(W.dir,k.projectId,k.projectRepos,j,Tt,n);let M=await Ny(W.dir,k.projectId,k.contextRepo,"worktree",Tt,n);Li=M,Ve=M?.workspacePath??null}catch(j){let M=j instanceof Error?j.message:String(j);console.warn(`[job] ${k.jobId} materialize failed: ${M}`),P||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${M}`},startedAt:_,finishedAt:new Date().toISOString()}),W.dispose();return}let Gn=k.model;k.role==="build"&&k.modelDiscovery&&!Dy(Ve)&&(Gn=k.modelDiscovery,console.log(`[job] ${k.jobId} BUILD discovery (no steps in ${Ml}) \u2014 model=${Gn}`));let ku=async()=>{if(!k.deliveries||k.deliveries.length===0)return[];let j=k.contextRepo?.cloneUrl;if(!j||!Tt)throw new Error(j?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let M=[];for(let Q of k.deliveries){let Z=st.find(ae=>ae.name===Q.name);if(Z){if(k.role==="implement"&&Q.baseSha&&Q.baseSha!==Z.baseSha){let ae=await Ay(Z,Q.deliveryRef,Q.deliverySha,Q.baseSha,j,Tt);console.log(`[job] ${k.jobId} ${Z.name}: base moved ${Q.baseSha.slice(0,10)} \u2192 ${Z.baseSha.slice(0,10)} \u2014 re-applied delivery ${Q.deliverySha.slice(0,10)} (${ae.length} conflicted file(s))`),ae.length>0&&M.push(`- **${Z.name}**:`,...ae.map(ze=>` - \`${ze}\``));continue}await Cy(Z,Q.deliveryRef,Q.deliverySha,j,Tt),console.log(`[job] ${k.jobId} ${Z.name}: checked out delivery ${Q.deliverySha.slice(0,10)} for ${k.role}`)}}return M},Di=[];if(k.role==="build"||k.role==="implement"||k.role==="code-review")try{Di=await ku()}catch(j){let M=j instanceof Error?j.message:String(j);console.warn(`[job] ${k.jobId} delivery checkout failed: ${M}`),P||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${M}`},startedAt:_,finishedAt:new Date().toISOString()}),W.dispose();return}let Mi=k.role==="resolve-conflict"?k.metadata?.taskBranchByRepo??{}:{},wu="";if(k.role==="resolve-conflict"){if(!st.some(j=>Mi[j.name])){let j="resolve-conflict job carries no task branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${k.jobId} ${j}`),P||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:j},startedAt:_,finishedAt:new Date().toISOString()}),W.dispose();return}try{let j=[];for(let M of st){let Q=Mi[M.name];if(!Q)continue;let Z=await Dl(M,Q,Tt);console.log(`[job] ${k.jobId} ${M.name}: merged ${Q} into ${M.ref} \u2014 ${Z.length} conflicted file(s)`),Z.length>0?j.push(`- **${M.name}**:`,...Z.map(ae=>` - \`${ae}\``)):j.push(`- **${M.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}wu=`
808
897
 
809
898
  ## Conflicts to resolve
810
899
 
811
- `+(B.length>0?B.join(`
900
+ `+(j.length>0?j.join(`
812
901
  `):"(no task branches to merge)")+`
813
- `}catch(B){let U=B instanceof Error?B.message:String(B);console.warn(`[job] ${k.jobId} conflict merge failed: ${U}`),A||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${U}`},startedAt:ge,finishedAt:new Date().toISOString()}),J.dispose();return}}let Ss=null;if(k.contextPack&&Ct)try{let{assembleContextPack:B}=await Promise.resolve().then(()=>(py(),dy)),U=B({contextDir:Ct,taskKey:String(k.metadata?.trackerIssueKey??k.taskId.split(":")[1]??""),title:String(k.metadata?.taskTitle??""),repoDirs:new Map(at.map(ee=>[ee.name,ee.workspacePath]))});U?(fy(zt(J.dir,"meta"),{recursive:!0}),gy(zt(J.dir,"meta","context-pack.md"),U),Ss=U,console.log(`[job] ${k.jobId} context pack: ${U.length} chars \u2192 meta/context-pack.md`)):console.log(`[job] ${k.jobId} context pack: model empty or no signal \u2014 skipped`)}catch(B){let U=B instanceof Error?B.message:String(B);console.warn(`[job] ${k.jobId} context pack failed (non-fatal): ${U}`)}let Wk=vs.length>0?`
902
+ `}catch(j){let M=j instanceof Error?j.message:String(j);console.warn(`[job] ${k.jobId} conflict merge failed: ${M}`),P||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${M}`},startedAt:_,finishedAt:new Date().toISOString()}),W.dispose();return}}let Ui=null;if(k.contextPack&&Ve)try{let{assembleContextPack:j}=await Promise.resolve().then(()=>(mk(),fk)),M=j({contextDir:Ve,taskKey:String(k.metadata?.trackerIssueKey??k.taskId.split(":")[1]??""),title:String(k.metadata?.taskTitle??""),repoDirs:new Map(st.map(Q=>[Q.name,Q.workspacePath]))});M?(Nk(Et(W.dir,"meta"),{recursive:!0}),Ok(Et(W.dir,"meta","context-pack.md"),M),Ui=M,console.log(`[job] ${k.jobId} context pack: ${M.length} chars \u2192 meta/context-pack.md`)):console.log(`[job] ${k.jobId} context pack: model empty or no signal \u2014 skipped`)}catch(j){let M=j instanceof Error?j.message:String(j);console.warn(`[job] ${k.jobId} context pack failed (non-fatal): ${M}`)}let bu="",Vo=null,Bi=null;try{let{loadSkills:j,materializeSkills:M,renderSkillsBlock:Q}=await Promise.resolve().then(()=>(gk(),hk)),Z=k.skills??{bundled:!0,context:!0,repo:!0},ae=j({contextDir:Ve,repoDirs:st.map(Xe=>Xe.workspacePath),sources:Z});for(let Xe of ae.errors)console.warn(`[job] ${k.jobId} skill ${Xe.source}: ${Xe.error}`);let ze=M(W.dir,ae.skills),fe=["implement","rework","testing"].includes(k.role)?Da(La(I(Ve,k.taskId))):[];bu=Q(ae.skills,fe),ze.length>0&&console.log(`[job] ${k.jobId} skills: ${ae.skills.map(Xe=>Xe.name).join(", ")}`);let{parseMarketplaces:Oe,enabledPluginsSetting:Mr}=await Promise.resolve().then(()=>(F(),Md)),{sources:Ur,errors:Wn}=Oe(Z.marketplaces??[]);for(let Xe of Wn)console.warn(`[job] ${k.jobId} marketplace ${Xe}`);if(Ur.length>0&&(Z.plugins??[]).length>0){let{seedMarketplaces:Xe}=await Promise.resolve().then(()=>($k(),bk)),Br=await Xe(Ur);for(let te of Br.errors)console.warn(`[job] ${k.jobId} marketplace ${te.repo}: ${te.error}`);let{enabled:Fr,unknown:Kr}=Mr(Z.plugins??[],Br.ready);for(let te of Kr)console.warn(`[job] ${k.jobId} plugin ${te}: no such marketplace in this project`);Br.dir&&Object.keys(Fr).length>0&&(Vo=Br.dir,Bi={enabledPlugins:Fr},console.log(`[job] ${k.jobId} plugins: ${Object.keys(Fr).join(", ")}`))}}catch(j){let M=j instanceof Error?j.message:String(j);console.warn(`[job] ${k.jobId} skills unavailable (non-fatal): ${M}`)}let $u="";if(["code-review","council","analyze","testing"].includes(k.role))try{let{loadRoles:j}=await Promise.resolve().then(()=>(Ek(),Sk)),{materializeRoleAgents:M,renderRolesBlock:Q}=await Promise.resolve().then(()=>(Tk(),Rk)),Z=j(Ve);for(let Oe of Z.errors)console.warn(`[job] ${k.jobId} role ${Oe.file}: ${Oe.error}`);let ae=k.role==="council"?"council":k.role==="analyze"?"plan_review":"code_review",ze=k.role==="council"?"council":k.role==="analyze"?"plan-review":k.role==="testing"?"testing":"code-review",fe=M(W.dir,Z.roles,ae,Ve);$u=Q(fe,ze),console.log(`[job] ${k.jobId} review panel: ${fe.roles.length>0?fe.roles.map(Oe=>Oe.name).join(", "):"(no roles)"}`)}catch(j){let M=j instanceof Error?j.message:String(j);console.warn(`[job] ${k.jobId} review panel unavailable (non-fatal): ${M}`)}let db=Di.length>0?`
814
903
 
815
904
  ## Base branch moved \u2014 conflicts to resolve
816
905
 
817
906
  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:
818
907
 
819
- `+vs.join(`
908
+ `+Di.join(`
820
909
  `)+`
821
- `:"",hl=R(b(k.prompt,at,Ct),Ct,k.taskId)+gl+Wk,Pn=[...at.map(B=>B.workspacePath),...Ct?[Ct]:[]];if(Pn.length>0&&console.log(`[job] ${k.jobId} --add-dir: ${Pn.join(", ")}`),dh("agent-request")){let B=Ji(cn(k.metadata??{})),U=ph(k.projectId,k.jobId,"agent-request",[`# Agent request \u2014 job ${k.jobId}`,"",`- project: ${k.projectId}`,`- task: ${k.taskId}`,`- role: ${k.role}`,`- model: ${An??"(backend default)"}`,`- add-dirs:${Pn.length>0?"":" (none)"}`,...Pn.map(ee=>` - ${ee}`),"","## Append-system-prompt (language directive)","","```",B,"```","","## Prompt","",hl,"",...Ss?["## Context pack (meta/context-pack.md)","",Ss]:["## Context pack","","(not generated for this job)"],""].join(`
822
- `));U&&console.log(`[debug] ${k.jobId} agent request \u2192 ${U}`)}j&&(ke=setInterval(()=>{let U=m;if(!U||U.readyState!==U.OPEN)return;let ee;try{ee=JT(zt(J.dir,"drafts")).filter(re=>re.endsWith(".json")).sort()}catch{return}for(let re of ee){if(Y.has(re))continue;if(Y.size>=Au)break;let be;try{let ze=JSON.parse(my(zt(J.dir,"drafts",re),"utf-8")),Ir=typeof ze.localRef=="string"?ze.localRef:"",Ro=typeof ze.title=="string"?ze.title:"",Ts=typeof ze.body=="string"?ze.body:"";if(!Ir||!Ro)continue;be={localRef:Ir,title:Ro,body:Ts,...ze.isEpic===!0?{isEpic:!0}:{},...Array.isArray(ze.links)?{links:ze.links}:{}}}catch{continue}Y.add(re);let _n={type:"child_draft",jobId:k.jobId,projectId:k.projectId,draftId:j,child:be};try{U.send(JSON.stringify(_n))}catch{}}},1500));try{let B={workspaceDir:J.dir,role:k.role,prompt:hl,addDirs:Pn,metadata:k.metadata??{},...An?{model:An}:{},...fl?{env:fl}:{},signal:L.abort.signal,onActivity:$},U=L.chatInbox?await c.run({...B,interactive:{inbox:L.chatInbox.iterable}}):await ah(c,B,{jobId:k.jobId,policy:l,onBeforeRetry:async()=>{J.clean();for(let ae of at)try{await xh(ae);let $e=xs[ae.name];k.role==="resolve-conflict"&&$e&&await Dc(ae,$e,te)}catch($e){let jn=$e instanceof Error?$e.message:String($e);console.warn(`[job] ${k.jobId} worktree reset failed (${ae.name}): ${jn}`)}try{await ml()}catch(ae){let $e=ae instanceof Error?ae.message:String(ae);console.warn(`[job] ${k.jobId} delivery re-checkout failed: ${$e}`)}},aborted:()=>A||L.paused}),ee=[];if(eE.has(k.role)&&at.length>0){let ae=k.metadata??{},$e=typeof ae.commitMessage=="string"?ae.commitMessage:`${k.taskId}: changes`,jn=k.contextRepo?.cloneUrl,kl=q?.env;if(!jn||!kl)throw new Error("delivery requested but "+(jn?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let qk=k.taskId.includes(":")?k.taskId.slice(k.taskId.indexOf(":")+1):k.taskId;for(let bt of at){let Nn=await Sh(bt,$e);if(!Nn){console.log(`[job] ${k.jobId} ${bt.name}: no changes \u2014 no delivery`);continue}let Es=`codepipe/deliveries/${qk}/${k.jobId}/${bt.name}`;await Th(bt,Nn,Es,jn,kl),ee.push({name:bt.name,deliveryRef:Es,deliverySha:Nn,baseSha:bt.baseSha}),console.log(`[job] ${k.jobId} ${bt.name}: delivered ${Nn.slice(0,10)} \u2192 ${Es}`);let wl=await Eh(bt,Nn);if(wl.trim().length>0){let Yk=zt("display",`${bt.name}.diff`),bl=zt(J.dir,Yk);fy(ZT(bl),{recursive:!0}),gy(bl,wl)}}}if(k.role==="resolve-conflict"&&ee.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's diff-summary.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let re;k.role==="build"&&(re=Dh(J.dir),console.log(`[job] ${k.jobId} build verdict: ok=${re.ok}`+(re.failedStep?` failedStep=${re.failedStep}`:"")));let be;k.role==="code-review"&&(be=Bh(J.dir),console.log(`[job] ${k.jobId} review verdict: approved=${be.approved}`));let _n=U.artifactPaths.length>0?U.artifactPaths:J.listFiles(),ze=Array.from(new Set(_n)),Ir;if($s)try{let ae=k.role==="index"?["adr/SOURCES.md"]:k.role==="backfill"?["adr"]:[],$e=await jh($s,ae);$e.length>0&&(Ir=$e,console.log(`[job] ${k.jobId} captured ${$e.length} knowledge file(s) for Context Repo`))}catch(ae){let $e=ae instanceof Error?ae.message:String(ae);console.warn(`[job] ${k.jobId} knowledge capture failed (non-fatal): ${$e}`)}let{artifacts:Ro,omitted:Ts,dropped:yl}=Kh(J.dir,ze);for(let ae of Ts)console.warn(`[job] ${k.jobId} artifact ${ae.path} (${ae.bytes} bytes) exceeded upload budget \u2014 content omitted`);yl.length>0&&console.warn(`[job] ${k.jobId} artifact listing truncated: ${yl.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let Co={jobId:k.jobId,status:"succeeded",artifacts:Ro,...Ir?{contextWrites:Ir}:{},...ee.length>0?{deliveries:ee}:{},log:tE(U.log),startedAt:ge,finishedAt:new Date().toISOString(),usage:U.usage,...U.rateLimit?{rateLimit:U.rateLimit}:{},...re?{build:re}:{},...be?{review:be}:{}};if(A||L.paused)console.warn(`[job] ${k.jobId} skipping result upload \u2014 ${L.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await C.submitResult(Co),console.log(`[job] ${k.jobId} done \u2014 uploaded ${Co.artifacts.length} artifact(s):`);for(let ae of Co.artifacts){let $e=Buffer.from(ae.contentBase64,"base64").length;console.log(` \xB7 ${ae.path} (${$e} bytes)`)}Co.artifacts.length===0&&console.warn(`[job] ${k.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(B){let U=B instanceof Error?B.message:String(B);if(L.paused)console.log(`[job] ${k.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(A)console.warn(`[job] ${k.jobId} failed after claim lost (${U}) \u2014 skipping result upload`);else{let ee=sh(B),re=B instanceof Yt,be=B instanceof It;console.warn(ee?`[job] ${k.jobId} failed: ${U} (Claude auth \u2014 token invalid/expired)`:re?`[job] ${k.jobId} failed: ${U} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:be?`[job] ${k.jobId} failed: ${U} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${k.jobId} failed: ${U}`),await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:U},startedAt:ge,finishedAt:new Date().toISOString(),...ee?{authError:!0}:{},...re?{buildInconclusive:!0}:{},...be?{reviewInconclusive:!0}:{}})}}finally{J.dispose()}}finally{clearInterval(Ve),ke&&clearInterval(ke),S(),L.chatInbox?.close(),f.delete(k.jobId),H?.cleanup(),q?.cleanup()}}function I(C,k){if(!C.credBundle)return{gitCreds:null,contextGitCreds:null};if(!k)return console.warn(`[job] ${C.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let L;try{L=JSON.parse(zr(k,C.credBundle).toString("utf-8"))}catch(Z){return console.warn(`[job] ${C.jobId} failed to open credBundle: ${Z instanceof Error?Z.message:String(Z)}`),{gitCreds:null,contextGitCreds:null}}let A=Oc(L);A&&console.log(`[job] ${C.jobId} cred bundle opened \u2014 git creds configured`);let H=hh(L,C.contextRepo.cloneUrl),q={gitCreds:A,contextGitCreds:H};return L.claudeOauthToken&&(q.claudeOauthToken=L.claudeOauthToken),q}function E(C,k){return C.split(`
823
- `).map(L=>k+L).join(`
824
- `)}function b(C,k,L){let A=k[0]?.workspacePath??"";return C.replace(/\{\{codeDir\}\}/g,A).replace(/\{\{codeRoot\}\}/g,A?A.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,L??"")}function R(C,k,L){let A=C,H=L.includes("::")?"":L.split(":",2)[1]??"",q=Z=>{if(!k||!H)return"";try{return my(zt(k,"tasks",H,Z),"utf-8").trim()}catch{return""}};if(A.includes("{{planMd}}")||A.includes("{{solutionMd}}")){let Z=q("PLAN.md")||q("SOLUTION.md")||"(PLAN.md missing \u2014 proceed from the task description)";A=A.replace(/\{\{planMd\}\}/g,()=>Z),A=A.replace(/\{\{solutionMd\}\}/g,()=>Z)}if(A.includes("{{taskDescription}}")){let Z=q("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";A=A.replace(/\{\{taskDescription\}\}/g,()=>Z)}return A}let N=C=>{if(p)return;p=!0,console.log(`
825
- [${C}] shutting down`),d.abort();let k=[...f.keys()];for(let H of f.values())H.abort.abort();let L=new AbortController,A=setTimeout(()=>L.abort(),3e3);(async()=>(await Promise.all(k.map(async H=>{try{await u.releaseJob(H,`sandbox ${C}`,L.signal),console.log(`[${C}] released job ${H}`)}catch(q){let Z=q instanceof Error?q.message:String(q);console.warn(`[${C}] release failed: ${Z} (sweeper will reclaim)`)}})),clearTimeout(A),y.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>N("SIGINT")),process.on("SIGTERM",()=>N("SIGTERM"));let F=[x("implementation")];e.planningLane!==!1?F.push(x("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(F)}var ls,eE,hy=v(()=>{"use strict";G();We();Vs();rh();Qi();ch();fh();_e();Xi();yh();Ac();Nh();Lh();Mh();Fh();Hh();zh();ls=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),eE=new Set(["implement","resolve-conflict"])});var kn=v(()=>{"use strict";Gg();hy();Xi()});import{cancel as nE,isCancel as ky,log as it,password as oE,text as iE}from"@clack/prompts";function sE(t){return ky(t)&&(nE("aborted"),process.exit(1)),typeof t=="string"?t:""}function aE(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function cE(t){let e=sa({redirectUri:ia,challenge:t.challenge,state:t.state});it.message(`Open this URL, approve the access, and paste the code shown:
826
- ${e}`);let r=await iE({message:"Authorization code \u2014 blank to skip"});if(ky(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=Kd(r,t.state);return await aa({code:n,verifier:t.verifier,state:t.state,redirectUri:ia})}catch(n){return it.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function lE(t){if(qs()?.claude?.oauthToken&&!t.farm)return it.message("Claude: this machine already has a shared OAuth token \u2014 the project will use it (set a project-specific one later with `codepipe login`)."),"";if(process.env.CODEPIPE_CLAUDE_AUTOLOGIN==="0"||!process.stdout.isTTY)return null;it.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=ti(),n;try{n=await Hd({...r,openUrl:ur,log:i=>it.message(i)})}catch(i){it.warn(`Browser sign-in didn't complete (${i instanceof Error?i.message:String(i)}) \u2014 trying the code-paste fallback.`);let s=await cE(r);if(s===null)return null;n=s}let o=await Bt(n.oauthToken);return o==="invalid"?(it.warn("Claude rejected the obtained token (401) \u2014 falling back to manual entry."),null):(it.success(`Claude: logged in \u2014 ${aE(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function uE(t){it.message("Claude login \u2014 pipeline agents run on your Claude subscription.\n Get a token: install Claude Code (https://claude.com/claude-code), run\n `claude setup-token` in a terminal and paste the result here."+(t.farm?`
827
- Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=sE(await oE({message:"Claude OAuth token \u2014 blank to skip"})).trim();return e?(e.startsWith("sk-ant-")||it.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`."),e):(it.warn(t.farm?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"")}var wy,by=v(()=>{"use strict";ri();Kr();ue();la();wy={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:lE,promptManual:uE,validate:Bt}});function $y(t){return wy}async function vy(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var xy=v(()=>{"use strict";by()});async function bn(t,e,r){return e.host==="github"?pE(t,e,r):e.host==="gitlab"?wE(t,e,r):$E(t,e,r)}async function Sy(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 Jt(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Ty(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 Xt(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Ey(e.gitlabToken,t):o}}return e.bitbucket?(await wn(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Iy(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 Ty(t,e){let r=!1;try{r=(await Jt(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 Ey(t,e){let r=!1;try{r=(await Xt(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 Iy(t,e){let r=!1;try{r=(await wn(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 Jt(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(dE+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 pE(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 fE(n,e,r),i=await gE(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=Vr(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await hE(n,o.owner,o.name,a.path,i)||await yE(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 fE(t,e,r){let n=await Jt(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 Ty(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await mE(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 Jt(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 mE(t,e){let{status:r,data:n}=await Jt(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function gE(t,e,r){let{data:n}=await Jt(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function hE(t,e,r,n,o){let{status:i,data:s}=await Jt(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function yE(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 Jt(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Xt(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(kE+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 wE(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 Xt(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 Ey(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await Xt(n,"GET","/user"),d={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(p.data?.username!==e.owner){let m=await Xt(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(m.status===404||!m.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);d.namespace_id=m.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let f=await Xt(n,"POST","/projects",d);if(!f.data)throw new Error("GitLab create project: empty response");i=f.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Vr(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let f=(await Xt(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let m of f)l.add(m.path);if(f.length<100)break}let u=c.filter(p=>!l.has(p.path)).map(p=>({action:"create",file_path:p.path,content:p.content}));return u.length>0?await Xt(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 wn(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(bE+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 $E(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 wn(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 Iy(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 wn(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(p.status===404||!p.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);i=p.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Vr(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await wn(n,"GET",`${o}/src/${encodeURIComponent(a)}/${p.path}?format=meta`)).status===404&&l.push(p);if(l.length>0){let p=new URLSearchParams;p.set("message","chore(codepipe): scaffold context repo files"),p.set("branch",a);for(let f of l)p.set(f.path,f.content);if((await wn(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 dE,kE,bE,us=v(()=>{"use strict";wr();dE="https://api.github.com";kE="https://gitlab.com/api/v4";bE="https://api.bitbucket.org/2.0"});function qe(t){let e=t.trim();if(!e)return null;let r,n;if(e.includes("://")){let a;try{a=new URL(e)}catch{return null}r=a.hostname.toLowerCase(),n=a.pathname}else{let a=/^(?:[\w.-]+@)?([\w.-]+):(.+)$/.exec(e);if(!a)return null;r=a[1].toLowerCase(),n=a[2]}let o=vE[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 vE,ds=v(()=>{"use strict";vE={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as xE}from"node:crypto";import{existsSync as Ry,mkdirSync as SE,readFileSync as Cy,readdirSync as TE,rmSync as ps,writeFileSync as EE}from"node:fs";import{homedir as IE}from"node:os";import{dirname as RE,join as Kc}from"node:path";function Ay(){return Kc(IE(),".codepipe","init-drafts")}function Hc(t){let e=xE("sha256").update(t).digest("hex").slice(0,16);return Kc(Ay(),`${e}.json`)}function Py(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=CE)}function _y(t){let e=Hc(t);if(!Ry(e))return null;try{let r=JSON.parse(Cy(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Py(r.savedAt)?(ps(e,{force:!0}),null):r}catch{return null}}function Wc(t){ps(Hc(t),{force:!0})}function jy(){let t=Ay();if(Ry(t))for(let e of TE(t)){let r=Kc(t,e);try{let n=JSON.parse(Cy(r,"utf-8"));Py(n.savedAt)&&ps(r,{force:!0})}catch{ps(r,{force:!0})}}}var CE,$n,Ny=v(()=>{"use strict";CE=24*60*60*1e3;$n=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(){Wc(this.cwd)}persist(){let e=Hc(this.cwd);SE(RE(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};EE(e,JSON.stringify(r,null,2)+`
828
- `,{mode:384})}}});function Oy(t){let e=[],r=[];return t.localClones&&(e.push({value:"map",label:"Project map from git history",hint:"local, a few seconds \u2014 a graph of files, tasks and their connections for the AI agent"}),r.push("map")),e.push(t.indexExists?{value:"index",label:"Re-index the context (an index already exists)",hint:"background job; keeps nothing if skipped"}:{value:"index",label:"Context index \u2014 knowledge and docs map",hint:"background job, recommended on first run"}),t.indexExists||r.push("index"),!t.indexExists&&t.reposNonEmpty&&(e.push({value:"backfill",label:"Reconstruct architecture decisions from the existing code",hint:"deep one-off AI analysis \u2014 proposes decision drafts you review before they become canonical"}),r.push("backfill")),{message:"Analyze the project? Pick what to run (space to toggle, enter to confirm):",options:e,initialValues:r,reindex:t.indexExists}}async function Ly(t,e){if(t.host!=="github"||!e)return!1;try{return(await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/contents/knowledge/INDEX.md?ref=${encodeURIComponent(t.branch)}`,{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}})).status===200}catch{return!1}}var Dy=v(()=>{"use strict"});import{existsSync as AE}from"node:fs";import{join as PE}from"node:path";import{simpleGit as _E}from"simple-git";function LE(t){let e=t.split("/");return e[e.length-1]??t}function My(t){if(t.filter(r=>!NE.test(LE(r))).length>jE)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(OE.has(n))return!0}return!1}async function DE(t){try{let r=(await _E(t).raw(["ls-files"])).split(`
829
- `).map(n=>n.trim()).filter(Boolean);return My(r)}catch{return!1}}async function ME(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)?My(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function Uy(t,e){for(let r of t)try{let n=e.localRoot!=null?PE(e.localRoot,r.mountAs??r.name):null;if(n&&AE(n)?await DE(n):await ME(r,e.tokens))return!0}catch{}return!1}var jE,NE,OE,By=v(()=>{"use strict";jE=3,NE=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,OE=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as Fy}from"node:fs";import{join as Gy}from"node:path";import{simpleGit as Ky}from"simple-git";async function bo(t,e,r={}){let n=r.log??UE,o=[];for(let i of e){let s=Gy(t,i.mountAs),a=Nu(i);if(!Fy(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 Ky().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(!Fy(Gy(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=Ky(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!BE(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 BE(t,e){return Hy(t)===Hy(e)}function Hy(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function wo(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function Wy(t={}){let e=Se();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 bo(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 UE,fs=v(()=>{"use strict";mt();UE={info:t=>console.log(t),warn:t=>console.warn(t)}});import{spawn as Yy}from"node:child_process";import{existsSync as qy}from"node:fs";import{homedir as FE,hostname as GE}from"node:os";import{join as ms}from"node:path";async function KE(t,e,r){let n=Ae(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${ot(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 Zd(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 ${ot(e)} still holds its token.
830
- 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`),Qu(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function HE(t,e,r){let n=Ae(e)!==null;if(!await KE(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 ii(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 vr({hub:t.hubUrl,token:o,name:r.name??`${GE()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function WE(t,e){let r=Ae(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=je(r.sealPublicKey);if(!W(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=Yo(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 qc(t,e,r){await HE(t,e,r),WE(t.projectId,e)}function qE(t){return[...t?["--profile",t]:[],"worker","start"]}function YE(t){let e={...t};for(let r of Ys)delete e[r];return e}function Yc(t){let e=Yy(process.execPath,[t.entry,...qE(t.profile)],{stdio:["ignore","pipe","pipe"],env:YE(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
831
- `))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function VE(t,e){let r=process.cwd(),n=ms(r,ft);if(Ho(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(qy(n)){console.warn(`[up] ${n} exists but is not this project's workspace \u2014 the context stays under ~/.codepipe/profiles`);return}let o;try{o=await ne(t.hubUrl,t.cliToken,t.projectId)}catch(u){console.warn(`[up] could not fetch the project summary (${u instanceof Error?u.message:String(u)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await Xc(r);if(!ju(r,i?.parsed??null,o.repos)){console.log(`[up] this folder is neither empty nor a repo of ${t.projectId} \u2014 the context stays under ~/.codepipe/profiles`);return}let s=W(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await Vi({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=ms(FE(),".codepipe",e?ms("profiles",e,"context-config"):"context-config");if(fi(c.contextDir,l,a),!qy(ms(c.contextDir,"project.yaml"))){qr(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};Xn(c.contextDir,yt(u,!0,s?.youtrack?.url)),console.log("[up] local project config seeded with defaults \u2014 review .codepipe/project.yaml")}console.log(`[up] project context materialized \u2192 ${n}`)}async function Vc(t){let{cfg:e,profile:r}=qo(t.profile);if(t.debug){let f=typeof t.debug=="string"&&t.debug.trim()?t.debug.trim():"agent-request";process.env.CODEPIPE_DEBUG=f,console.log(`[up] debug logging on (${f}) \u2192 ~/.codepipe/debug/${e.projectId}/`)}await VE(e,r),await qc(e,r,t);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(f,m)=>{let h=g=>w=>{for(let y of w.toString("utf-8").split(`
832
- `))y.length>0&&g.write(`${m} ${y}
833
- `)};f.stdout?.on("data",h(process.stdout)),f.stderr?.on("data",h(process.stderr))},i=(f,m)=>{let h=Yy(process.execPath,[n,...m],{stdio:["ignore","pipe","pipe"],env:process.env});return o(h,f),h};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=Yc({entry:n,profile:r,onLine:f=>process.stdout.write(`[worker] ${f}
834
- `)}),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,u=f=>{if(!l){l=!0,console.log(`
835
- [up] ${f} \u2014 stopping both roles`);for(let{child:m}of c)m.exitCode===null&&m.kill(f);setTimeout(()=>{for(let{name:m,child:h}of c)h.exitCode===null&&(console.warn(`[up] ${m} did not stop \u2014 SIGKILL`),h.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:f,child:m})=>new Promise(h=>{m.on("exit",(g,w)=>h({name:f,code:g??(w?1:0)}))})),d=await Promise.race(p);l||(console.log(`[up] ${d.name} exited (code ${d.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(p),process.exit(d.code)}var zc=v(()=>{"use strict";We();kn();De();St();Ic();wr();Ie();ue();mt();$o()});var rk={};Rr(rk,{replCommand:()=>el});import{existsSync as Zy,mkdirSync as zE,readFileSync as XE,writeFileSync as JE}from"node:fs";import{homedir as QE}from"node:os";import{dirname as ZE,join as ek}from"node:path";import*as vn from"node:readline";async function el(t={}){let e=Se();e||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let r=W(e.spec.projectId);r||(console.error(`no secrets for project ${e.spec.projectId} at ~/.codepipe/secrets/${e.spec.projectId}.json. run \`codepipe init\` or \`codepipe clone\` to set them up.`),process.exit(1)),Gn(r),console.log(`connected to ${r.hubUrl} as project ${e.spec.projectId}`),console.log("the CLI daemon and an embedded agent worker run in this session; /logs and /monitor show their output."),console.log("type /help to list commands. Ctrl+D or /quit to exit.");let n=yr(e.contextDir),o=Object.keys(n);o.length>0&&console.log(`
910
+ `:"",vu=D(b(k.prompt,st,Ve),Ve,k.taskId).replace(/\{\{rolesBlock\}\}/g,$u).replace(/\{\{skillsBlock\}\}/g,bu)+wu+db,Hn=[...st.map(j=>j.workspacePath),...Ve?[Ve]:[]];if(Hn.length>0&&console.log(`[job] ${k.jobId} --add-dir: ${Hn.join(", ")}`),fy("agent-request")){let j=di(bn(k.metadata??{})),M=my(k.projectId,k.jobId,"agent-request",[`# Agent request \u2014 job ${k.jobId}`,"",`- project: ${k.projectId}`,`- task: ${k.taskId}`,`- role: ${k.role}`,`- model: ${Gn??"(backend default)"}`,`- add-dirs:${Hn.length>0?"":" (none)"}`,...Hn.map(Q=>` - ${Q}`),"","## Append-system-prompt (language directive)","","```",j,"```","","## Prompt","",vu,"",...Ui?["## Context pack (meta/context-pack.md)","",Ui]:["## Context pack","","(not generated for this job)"],""].join(`
911
+ `));M&&console.log(`[debug] ${k.jobId} agent request \u2192 ${M}`)}z&&(ot=setInterval(()=>{let M=f;if(!M||M.readyState!==M.OPEN)return;let Q;try{Q=KI(Et(W.dir,"drafts")).filter(Z=>Z.endsWith(".json")).sort()}catch{return}for(let Z of Q){if(ve.has(Z))continue;if(ve.size>=Ga)break;let ae;try{let fe=JSON.parse(xi(Et(W.dir,"drafts",Z),"utf-8")),Oe=typeof fe.localRef=="string"?fe.localRef:"",Mr=typeof fe.title=="string"?fe.title:"",Ur=typeof fe.body=="string"?fe.body:"";if(!Oe||!Mr)continue;ae={localRef:Oe,title:Mr,body:Ur,...fe.isEpic===!0?{isEpic:!0}:{},...Array.isArray(fe.links)?{links:fe.links}:{}}}catch{continue}ve.add(Z);let ze={type:"child_draft",jobId:k.jobId,projectId:k.projectId,draftId:z,child:ae};try{M.send(JSON.stringify(ze))}catch{}}},1500));try{let j={workspaceDir:W.dir,role:k.role,prompt:vu,addDirs:Hn,metadata:k.metadata??{},...Gn?{model:Gn}:{},...yu||Vo?{env:{...yu??{},...Vo?{CLAUDE_CODE_PLUGIN_SEED_DIR:Vo}:{}}}:{},...Bi?{settings:Bi}:{},signal:U.abort.signal,onActivity:N},M=U.chatInbox?await c.run({...j,interactive:{inbox:U.chatInbox.iterable}}):await ly(c,j,{jobId:k.jobId,policy:l,onBeforeRetry:async()=>{W.clean();for(let te of st)try{await Ey(te);let xe=Mi[te.name];k.role==="resolve-conflict"&&xe&&await Dl(te,xe,Tt)}catch(xe){let qn=xe instanceof Error?xe.message:String(xe);console.warn(`[job] ${k.jobId} worktree reset failed (${te.name}): ${qn}`)}try{await ku()}catch(te){let xe=te instanceof Error?te.message:String(te);console.warn(`[job] ${k.jobId} delivery re-checkout failed: ${xe}`)}},aborted:()=>P||U.paused}),Q=[];if(WI.has(k.role)&&st.length>0){let te=k.metadata??{},xe=typeof te.commitMessage=="string"?te.commitMessage:`${k.taskId}: changes`,qn=k.contextRepo?.cloneUrl,xu=Y?.env;if(!qn||!xu)throw new Error("delivery requested but "+(qn?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let pb=k.taskId.includes(":")?k.taskId.slice(k.taskId.indexOf(":")+1):k.taskId;for(let It of st){let Yn=await Ry(It,xe);if(!Yn){console.log(`[job] ${k.jobId} ${It.name}: no changes \u2014 no delivery`);continue}let Fi=`codepipe/deliveries/${pb}/${k.jobId}/${It.name}`;await Ty(It,Yn,Fi,qn,xu),Q.push({name:It.name,deliveryRef:Fi,deliverySha:Yn,baseSha:It.baseSha}),console.log(`[job] ${k.jobId} ${It.name}: delivered ${Yn.slice(0,10)} \u2192 ${Fi}`);let Su=await Iy(It,Yn);if(Su.trim().length>0){let fb=Et("display",`${It.name}.diff`),Eu=Et(W.dir,fb);Nk(HI(Eu),{recursive:!0}),Ok(Eu,Su)}}}if(k.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 Z;k.role==="build"&&(Z=Uy(W.dir),console.log(`[job] ${k.jobId} build verdict: ok=${Z.ok}`+(Z.failedStep?` failedStep=${Z.failedStep}`:"")));let ae;k.role==="code-review"&&(ae=Ky(W.dir),console.log(`[job] ${k.jobId} review verdict: approved=${ae.approved}`));let ze;if(k.role==="council"){let{readCouncilVerdict:te}=await Promise.resolve().then(()=>(Ak(),Ck));ze=te(W.dir)??void 0,console.log(`[job] ${k.jobId} council: ${ze?"answered":"no verdict \u2014 task stops for a human"}`)}let fe;if(k.role==="testing"){try{let te=xi(Et(W.dir,"meta","test-result.json"),"utf-8");fe=JSON.parse(te)}catch{fe=void 0}console.log(`[job] ${k.jobId} test verdict: ${fe?"written":"none \u2014 proceeding to the PR"}`)}let Oe;if(k.role==="observer"){let{readQueuePlan:te}=await Promise.resolve().then(()=>(jk(),_k));Oe=te(W.dir)??void 0,console.log(`[job] ${k.jobId} queue plan: ${Oe?"produced":"none \u2014 batch keeps the staged order"}`)}let Mr=M.artifactPaths.length>0?M.artifactPaths:W.listFiles(),Ur=Array.from(new Set(Mr)),Wn;if(Li)try{let te=k.role==="index"?["adr/SOURCES.md"]:k.role==="backfill"?["adr"]:[],xe=await Oy(Li,te);xe.length>0&&(Wn=xe,console.log(`[job] ${k.jobId} captured ${xe.length} knowledge file(s) for Context Repo`))}catch(te){let xe=te instanceof Error?te.message:String(te);console.warn(`[job] ${k.jobId} knowledge capture failed (non-fatal): ${xe}`)}let{artifacts:Xe,omitted:Br,dropped:Fr}=Wy(W.dir,Ur);for(let te of Br)console.warn(`[job] ${k.jobId} artifact ${te.path} (${te.bytes} bytes) exceeded upload budget \u2014 content omitted`);Fr.length>0&&console.warn(`[job] ${k.jobId} artifact listing truncated: ${Fr.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let Kr={jobId:k.jobId,status:"succeeded",artifacts:Xe,...Wn?{contextWrites:Wn}:{},...Q.length>0?{deliveries:Q}:{},log:qI(M.log),startedAt:_,finishedAt:new Date().toISOString(),usage:M.usage,...M.rateLimit?{rateLimit:M.rateLimit}:{},...Z?{build:Z}:{},...ae?{review:ae}:{},...Oe!==void 0?{queuePlan:Oe}:{},...ze!==void 0?{council:ze}:{},...fe!==void 0?{test:fe}:{}};if(P||U.paused)console.warn(`[job] ${k.jobId} skipping result upload \u2014 ${U.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await C.submitResult(Kr),console.log(`[job] ${k.jobId} done \u2014 uploaded ${Kr.artifacts.length} artifact(s):`);for(let te of Kr.artifacts){let xe=Buffer.from(te.contentBase64,"base64").length;console.log(` \xB7 ${te.path} (${xe} bytes)`)}Kr.artifacts.length===0&&console.warn(`[job] ${k.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(j){let M=j instanceof Error?j.message:String(j);if(U.paused)console.log(`[job] ${k.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(P)console.warn(`[job] ${k.jobId} failed after claim lost (${M}) \u2014 skipping result upload`);else{let Q=cy(j),Z=j instanceof tr,ae=j instanceof Mt;console.warn(Q?`[job] ${k.jobId} failed: ${M} (Claude auth \u2014 token invalid/expired)`:Z?`[job] ${k.jobId} failed: ${M} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:ae?`[job] ${k.jobId} failed: ${M} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${k.jobId} failed: ${M}`),await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:M},startedAt:_,finishedAt:new Date().toISOString(),...Q?{authError:!0}:{},...Z?{buildInconclusive:!0}:{},...ae?{reviewInconclusive:!0}:{}})}}finally{W.dispose()}}finally{clearInterval(Ye),ot&&clearInterval(ot),v(),U.chatInbox?.close(),m.delete(k.jobId),G?.cleanup(),Y?.cleanup()}}function T(C,k){if(!C.credBundle)return{gitCreds:null,contextGitCreds:null};if(!k)return console.warn(`[job] ${C.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let U;try{U=JSON.parse(ln(k,C.credBundle).toString("utf-8"))}catch(se){return console.warn(`[job] ${C.jobId} failed to open credBundle: ${se instanceof Error?se.message:String(se)}`),{gitCreds:null,contextGitCreds:null}}let P=Ol(U);P&&console.log(`[job] ${C.jobId} cred bundle opened \u2014 git creds configured`);let G=ky(U,C.contextRepo.cloneUrl),Y={gitCreds:P,contextGitCreds:G};return U.claudeOauthToken&&(Y.claudeOauthToken=U.claudeOauthToken),Y}function R(C,k){return C.split(`
912
+ `).map(U=>k+U).join(`
913
+ `)}function b(C,k,U){let P=k[0]?.workspacePath??"";return C.replace(/\{\{codeDir\}\}/g,P).replace(/\{\{codeRoot\}\}/g,P?P.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,U??"")}function I(C,k){let U=k.includes("::")?"":k.split(":",2)[1]??"";if(!C||!U)return"";for(let P of["PLAN.md","SOLUTION.md"])try{return xi(Et(C,"tasks",U,P),"utf-8")}catch{}return""}function D(C,k,U){let P=C,G=U.includes("::")?"":U.split(":",2)[1]??"",Y=se=>{if(!k||!G)return"";try{return xi(Et(k,"tasks",G,se),"utf-8").trim()}catch{return""}};if(P.includes("{{planMd}}")||P.includes("{{solutionMd}}")){let se=Y("PLAN.md")||Y("SOLUTION.md")||"(PLAN.md missing \u2014 proceed from the task description)";P=P.replace(/\{\{planMd\}\}/g,()=>se),P=P.replace(/\{\{solutionMd\}\}/g,()=>se)}if(P.includes("{{taskDescription}}")){let se=Y("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";P=P.replace(/\{\{taskDescription\}\}/g,()=>se)}return P}let K=C=>{if(p)return;p=!0,console.log(`
914
+ [${C}] shutting down`),d.abort();let k=[...m.keys()];for(let G of m.values())G.abort.abort();let U=new AbortController,P=setTimeout(()=>U.abort(),3e3);(async()=>(await Promise.all(k.map(async G=>{try{await u.releaseJob(G,`sandbox ${C}`,U.signal),console.log(`[${C}] released job ${G}`)}catch(Y){let se=Y instanceof Error?Y.message:String(Y);console.warn(`[${C}] release failed: ${se} (sweeper will reclaim)`)}})),clearTimeout(P),y.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>K("SIGINT")),process.on("SIGTERM",()=>K("SIGTERM"));let ee=[x("implementation")];e.planningLane!==!1?ee.push(x("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(ee)}var Si,WI,Lk=$(()=>{"use strict";F();rt();Va();oy();pi();uy();hy();Le();ui();wy();Al();Ly();My();By();Gy();qy();Jy();Si=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),WI=new Set(["implement","resolve-conflict"])});var Pn=$(()=>{"use strict";Hg();Lk();ui()});import{cancel as VI,isCancel as Mk,log as gt,password as zI,text as XI}from"@clack/prompts";function JI(t){return Mk(t)&&(VI("aborted"),process.exit(1)),typeof t=="string"?t:""}function ZI(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function QI(t){let e=ic({redirectUri:sc,challenge:t.challenge,state:t.state});gt.message(`Open this URL, approve the access, and paste the code shown:
915
+ ${e}`);let r=await XI({message:"Authorization code \u2014 blank to skip"});if(Mk(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=qp(r,t.state);return await ac({code:n,verifier:t.verifier,state:t.state,redirectUri:sc})}catch(n){return gt.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function eC(t){if(qa()?.claude?.oauthToken&&!t.farm)return gt.message("Claude: this machine already has a shared OAuth token \u2014 the project will use it (set a project-specific one later with `codepipe login`)."),"";if(process.env.CODEPIPE_CLAUDE_AUTOLOGIN==="0"||!process.stdout.isTTY)return null;gt.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=gs(),n;try{n=await Yp({...r,openUrl:$r,log:s=>gt.message(s)})}catch(s){gt.warn(`Browser sign-in didn't complete (${s instanceof Error?s.message:String(s)}) \u2014 trying the code-paste fallback.`);let i=await QI(r);if(i===null)return null;n=i}let o=await zt(n.oauthToken);return o==="invalid"?(gt.warn("Claude rejected the obtained token (401) \u2014 falling back to manual entry."),null):(gt.success(`Claude: logged in \u2014 ${ZI(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function tC(t){gt.message("Claude login \u2014 pipeline agents run on your Claude subscription.\n Get a token: install Claude Code (https://claude.com/claude-code), run\n `claude setup-token` in a terminal and paste the result here."+(t.farm?`
916
+ Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=JI(await zI({message:"Claude OAuth token \u2014 blank to skip"})).trim();return e?(e.startsWith("sk-ant-")||gt.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`."),e):(gt.warn(t.farm?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"")}var Uk,Bk=$(()=>{"use strict";ys();rn();pe();lc();Uk={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:eC,promptManual:tC,validate:zt}});function Fk(t){return Uk}async function Kk(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var Gk=$(()=>{"use strict";Bk()});async function jn(t,e,r){return e.host==="github"?nC(t,e,r):e.host==="gitlab"?uC(t,e,r):pC(t,e,r)}async function Hk(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 sr(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Wk(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 i=encodeURIComponent(`${t.owner}/${t.name}`);return(await or(e.gitlabToken,"GET",`/projects/${i}`)).status!==404?{found:!0}:{found:!1,detail:n?await qk(e.gitlabToken,t):o}}return e.bitbucket?(await _n(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Yk(e.bitbucket,t):o}:{found:"unknown",detail:"no Bitbucket credentials \u2014 existence not checked"}}catch(s){return{found:"unknown",detail:s instanceof Error?s.message:String(s)}}}async function Wk(t,e){let r=!1;try{r=(await sr(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 qk(t,e){let r=!1;try{r=(await or(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 Yk(t,e){let r=!1;try{r=(await _n(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 sr(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 s=await fetch(rC+r,o),i=await s.text(),a=i?JSON.parse(i):null;if(s.status>=400&&s.status!==404){let c=typeof a=="object"&&a&&"message"in a?a.message:i;throw new Error(`GitHub ${e} ${r} \u2192 ${s.status} ${c}`)}return{status:s.status,data:a}}async function nC(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 oC(n,e,r),s=await iC(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${s}`);let i=cn(t,e,r.youtrackWrites,r.trackerUrl);for(let a of i)await aC(n,o.owner,o.name,a.path,s)||await cC(n,o.owner,o.name,a.path,a.content,`chore(codepipe): scaffold ${a.path}`,s);return{host:"github",owner:o.owner,name:o.name,cloneUrl:o.sshUrl,branch:s}}async function oC(t,e,r){let n=await sr(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 Wk(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await sC(t,e.owner),s=o?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${o?"org":"user"})`);let i=await sr(t,"POST",s,{name:e.name,private:!0,auto_init:!0,description:`CodePipe Context Repo for project ${e.name}`});if(!i.data)throw new Error("GitHub createRepo: empty response");return{owner:i.data.owner.login,name:i.data.name,sshUrl:i.data.ssh_url}}async function sC(t,e){let{status:r,data:n}=await sr(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function iC(t,e,r){let{data:n}=await sr(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function aC(t,e,r,n,o){let{status:s,data:i}=await sr(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return s===404||!i?null:i.sha}async function cC(t,e,r,n,o,s,i,a){let c={message:s,content:Buffer.from(o,"utf-8").toString("base64"),branch:i};a&&(c.sha=a),await sr(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function or(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 s=await fetch(lC+r,o),i=await s.text(),a=i?JSON.parse(i):null;if(s.status>=400&&s.status!==404){let c=typeof a=="object"&&a&&"message"in a?JSON.stringify(a.message):i;throw new Error(`GitLab ${e} ${r} \u2192 ${s.status} ${c}`)}return{status:s.status,data:a}}async function uC(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}`),s,i=await or(n,"GET",`/projects/${o}`);if(i.status===200&&i.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),s=i.data;else{if(r.mode==="attach")throw new Error(`attach: ${await qk(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await or(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 or(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 or(n,"POST","/projects",d);if(!m.data)throw new Error("GitLab create project: empty response");s=m.data}let a=s.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=cn(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let m=(await or(n,"GET",`/projects/${s.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 or(n,"POST",`/projects/${s.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:s.path,cloneUrl:s.ssh_url_to_repo,branch:a}}async function _n(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 s=await fetch(dC+r,o),i=await s.text(),a=null;try{a=i?JSON.parse(i):null}catch{}if(s.status>=400&&s.status!==404)throw new Error(`Bitbucket ${e} ${r} \u2192 ${s.status} ${i}`);return{status:s.status,data:a}}async function pC(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)}`,s,i=await _n(n,"GET",o);if(i.status===200&&i.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),s=i.data;else{if(r.mode==="attach")throw new Error(`attach: ${await Yk(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 _n(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`);s=p.data}let a=s.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=cn(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await _n(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 _n(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=s.links?.clone?.find(p=>p.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:s.slug??e.name,cloneUrl:u??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var rC,lC,dC,Ei=$(()=>{"use strict";Ar();rC="https://api.github.com";lC="https://gitlab.com/api/v4";dC="https://api.bitbucket.org/2.0"});function nt(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=fC[r];if(!o)return null;let s=n.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(s.length<2)return null;let i=s[s.length-1].replace(/\.git$/,"");return i?{host:o,owner:s.slice(0,-1).join("/"),repoName:i}:null}var fC,Ri=$(()=>{"use strict";fC={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as mC}from"node:crypto";import{existsSync as Vk,mkdirSync as hC,readFileSync as zk,readdirSync as gC,rmSync as Ti,writeFileSync as yC}from"node:fs";import{homedir as kC}from"node:os";import{dirname as wC,join as Yl}from"node:path";function Xk(){return Yl(kC(),".codepipe","init-drafts")}function Vl(t){let e=mC("sha256").update(t).digest("hex").slice(0,16);return Yl(Xk(),`${e}.json`)}function Jk(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=bC)}function Zk(t){let e=Vl(t);if(!Vk(e))return null;try{let r=JSON.parse(zk(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Jk(r.savedAt)?(Ti(e,{force:!0}),null):r}catch{return null}}function zl(t){Ti(Vl(t),{force:!0})}function Qk(){let t=Xk();if(Vk(t))for(let e of gC(t)){let r=Yl(t,e);try{let n=JSON.parse(zk(r,"utf-8"));Jk(n.savedAt)&&Ti(r,{force:!0})}catch{Ti(r,{force:!0})}}}var bC,Nn,ew=$(()=>{"use strict";bC=24*60*60*1e3;Nn=class{constructor(e,r){this.cwd=e;this.answers=r?.answers?{...r.answers}:{}}answers;get(e){return this.answers[e]}set(e,r){this.answers[e]=r,this.persist()}delete(e){delete this.answers[e],this.persist()}async ask(e,r){if(e in this.answers)return this.answers[e];let n=await r();return this.set(e,n),n}clear(){zl(this.cwd)}persist(){let e=Vl(this.cwd);hC(wC(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};yC(e,JSON.stringify(r,null,2)+`
917
+ `,{mode:384})}}});function tw(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 rw(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 nw=$(()=>{"use strict"});import{existsSync as $C}from"node:fs";import{join as vC}from"node:path";import{simpleGit as xC}from"simple-git";function TC(t){let e=t.split("/");return e[e.length-1]??t}function ow(t){if(t.filter(r=>!EC.test(TC(r))).length>SC)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(RC.has(n))return!0}return!1}async function IC(t){try{let r=(await xC(t).raw(["ls-files"])).split(`
918
+ `).map(n=>n.trim()).filter(Boolean);return ow(r)}catch{return!1}}async function CC(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 s=await o.json();return Array.isArray(s)?ow(s.map(i=>i.name??"").filter(Boolean)):!1}catch{return!1}}async function sw(t,e){for(let r of t)try{let n=e.localRoot!=null?vC(e.localRoot,r.mountAs??r.name):null;if(n&&$C(n)?await IC(n):await CC(r,e.tokens))return!0}catch{}return!1}var SC,EC,RC,iw=$(()=>{"use strict";SC=3,EC=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,RC=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as aw}from"node:fs";import{join as cw}from"node:path";import{simpleGit as lw}from"simple-git";async function Bo(t,e,r={}){let n=r.log??AC,o=[];for(let s of e){let i=cw(t,s.mountAs),a=Bd(s);if(!aw(i)){if(r.dryRun){n.info(`would clone ${a} \u2192 ${s.mountAs}/`),o.push({mountAs:s.mountAs,status:"cloned",detail:"(dry-run)"});continue}try{n.info(`cloning ${a} \u2192 ${s.mountAs}/`),await lw().clone(a,i),o.push({mountAs:s.mountAs,status:"cloned"})}catch(u){let p=Uo(u instanceof Error?u.message:String(u));n.warn(`clone failed for ${s.mountAs}: ${p}`),o.push({mountAs:s.mountAs,status:"error",detail:p})}continue}if(!aw(cw(i,".git"))){n.warn(`${s.mountAs}/ exists but is not a git repo \u2014 skipping`),o.push({mountAs:s.mountAs,status:"skipped-not-git"});continue}let c=lw(i),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!PC(l,a)){n.warn(`${s.mountAs}/ origin (${Uo(l)||"none"}) != expected (${Uo(a)}) \u2014 skipping`),o.push({mountAs:s.mountAs,status:"skipped-origin-mismatch",detail:Uo(l)});continue}if(r.dryRun){n.info(`would fetch ${s.mountAs}/`),o.push({mountAs:s.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),o.push({mountAs:s.mountAs,status:"fetched"})}catch(u){let p=Uo(u instanceof Error?u.message:String(u));n.warn(`fetch failed for ${s.mountAs}: ${p}`),o.push({mountAs:s.mountAs,status:"error",detail:p})}}return o}function PC(t,e){return uw(t)===uw(e)}function uw(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function Uo(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function dw(t={}){let e=Te();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 Bo(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 AC,Ii=$(()=>{"use strict";bt();AC={info:t=>console.log(t),warn:t=>console.warn(t)}});import{spawn as fw}from"node:child_process";import{existsSync as pw}from"node:fs";import{homedir as _C,hostname as jC}from"node:os";import{join as Ci}from"node:path";async function NC(t,e,r){let n=je(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${ht(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 rf(t.hubUrl.replace(/\/$/,""),n.token)}catch(s){return console.warn(`[up] could not verify the worker registration (${s instanceof Error?s.message:String(s)}) \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 ${ht(e)} still holds its token.
919
+ 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`),tp(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function OC(t,e,r){let n=je(e)!==null;if(!await NC(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 bs(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(s){throw s instanceof H&&s.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):s instanceof H&&s.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"):s instanceof H?s:new Error(`cannot reach the HUB at ${t.hubUrl} (${s instanceof Error?s.message:String(s)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await jr({hub:t.hubUrl,token:o,name:r.name??`${jC()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function LC(t,e){let r=je(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=De(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=cs(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 Xl(t,e,r){await OC(t,e,r),LC(t.projectId,e)}function DC(t){return[...t?["--profile",t]:[],"worker","start"]}function MC(t){let e={...t};for(let r of Ya)delete e[r];return e}function Jl(t){let e=fw(process.execPath,[t.entry,...DC(t.profile)],{stdio:["ignore","pipe","pipe"],env:MC(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
920
+ `))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function UC(t,e){let r=process.cwd(),n=Ci(r,_t);if(ss(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(pw(n)){console.warn(`[up] ${n} exists but is not this project's workspace \u2014 the context stays under ~/.codepipe/profiles`);return}let o;try{o=await oe(t.hubUrl,t.cliToken,t.projectId)}catch(u){console.warn(`[up] could not fetch the project summary (${u instanceof Error?u.message:String(u)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let s=await eu(r);if(!Ud(r,s?.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 i=q(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await li({cfg:t,secrets:i,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=Ci(_C(),".codepipe",e?Ci("profiles",e,"context-config"):"context-config");if(Is(c.contextDir,l,a),!pw(Ci(c.contextDir,"project.yaml"))){sn(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};go(c.contextDir,xt(u,!0,i?.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 Zl(t){let{cfg:e,profile:r}=as(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 UC(e,r),await Xl(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=h=>w=>{for(let y of w.toString("utf-8").split(`
921
+ `))y.length>0&&h.write(`${f} ${y}
922
+ `)};m.stdout?.on("data",g(process.stdout)),m.stderr?.on("data",g(process.stderr))},s=(m,f)=>{let g=fw(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 i=s("[cli]",[...r?["--profile",r]:[],"daemon"]),a=Jl({entry:n,profile:r,onLine:m=>process.stdout.write(`[worker] ${m}
923
+ `)}),c=[{name:"daemon",child:i},{name:"worker",child:a}],l=!1,u=m=>{if(!l){l=!0,console.log(`
924
+ [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",(h,w)=>g({name:m,code:h??(w?1:0)}))})),d=await Promise.race(p);l||(console.log(`[up] ${d.name} exited (code ${d.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(p),process.exit(d.code)}var Ql=$(()=>{"use strict";rt();Pn();He();Ot();Tl();Ar();Ae();pe();bt();Fo()});var vw={};Be(vw,{replCommand:()=>ou});import{existsSync as ww,mkdirSync as BC,readFileSync as FC,writeFileSync as KC}from"node:fs";import{homedir as GC}from"node:os";import{dirname as HC,join as bw}from"node:path";import*as On from"node:readline";async function ou(t={}){let e=Te();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)),ao(r),console.log(`connected to ${r.hubUrl} as project ${e.spec.projectId}`),console.log("the CLI daemon and an embedded agent worker run in this session; /logs and /monitor show their output."),console.log("type /help to list commands. Ctrl+D or /quit to exit.");let n=Ir(e.contextDir),o=Object.keys(n);o.length>0&&console.log(`
836
925
  \u26A0 unfinished local apply: ${o.map(a=>`${a} (${n[a].repos.map(c=>c.mountAs).join(", ")})`).join("; ")}
837
- finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let i=vn.createInterface({input:process.stdin,output:process.stdout,completer:eI,history:bI(),removeHistoryDuplicates:!0}),s={ws:e,secrets:r,connection:"connecting",rl:i,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};dp(a=>Zt(s,a)),s.daemon=qi({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:a=>Zt(s,a),warn:a=>Zt(s,a)},onEvent:a=>mI(s,a),workspace:{root:e.root,contextDir:e.contextDir,repos:e.spec.repos.map(a=>({name:a.name,mountAs:a.mountAs,defaultBranch:a.defaultBranch}))}});try{let a={hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId};await qc(a,t.profile,{profile:t.profile});let c=process.argv[1];if(!c)throw new Error("cannot resolve the codepipe entry script for the worker process");let l=Yc({entry:c,profile:t.profile,onLine:u=>Zt(s,`[worker] ${u}`)});l.on("exit",(u,p)=>{s.workerExited=!0,!Zc&&Qt(s,`[worker] exited (code ${u??(p?1:0)}) \u2014 agent jobs will NOT run; /quit and restart codepipe to bring it back`)}),s.workerChild=l,console.log("embedded agent worker started \u2014 agent jobs run on this machine.")}catch(a){console.warn(`[worker] could not start the embedded worker (${a instanceof Error?a.message:String(a)}). REPL commands still work; run \`codepipe up --reregister\` if the registration was removed.`)}Qc(s),i.prompt(),i.on("line",async a=>{let c=a.trim();if(c.length>0)try{if(await tI(s,c)){Qy(s);return}}catch(l){console.error(l instanceof Error?l.message:String(l))}s.unread=0,Qc(s),i.prompt()}),i.on("close",()=>{Qy(s)})}function eI(t){let e=Vy.filter(r=>r.startsWith(t));return[e.length?e:Vy,t]}async function tI(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return rI(),!1;case"/status":return await nI(t),!1;case"/tasks":return await oI(t,n),!1;case"/task":return await iI(t,n),!1;case"/sync":return await sI(t),!1;case"/logs":return gI(t,n),!1;case"/monitor":return hI(t),!1;case"/apply":return await Xy(t,n,"apply"),!1;case"/unstash":return await Xy(t,n,"unstash"),!1;case"/applied":return await aI(t,n),!1;case"/abort":return await cI(t,n),!1;case"/approve":return await Jy(t,n,"approve"),!1;case"/merge":return await Jy(t,n,"merge"),!1;case"/login":return uI(t,n),!1;case"/secret":return dI(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function rI(){console.log(["/help show this list","/status connection, project, embedded worker, siblings","/tasks [--phase P] list tasks (optionally filtered by phase)","/task <key> task detail (phase + artifacts)","/sync clone/fetch project repos per project.yaml","/logs [n|follow|clear] tail last n daemon/worker logs / toggle live / clear buffer","/monitor toggle live daemon/worker log streaming (alias /logs follow)","/apply <key> apply task patch on a new branch + commit (local mode)","/unstash <key> apply task patch uncommitted on base commit","/applied <key> --pr U mark applied; --pr repo=URL for multi-repo","/abort <key> --reason roll back local apply, send task back to agent","/approve <key> merge the task's PR(s) (TRACKING, PR mode)","/merge <key> direct-merge the branch to main (TRACKING, no-PR mode)","/login <token> set the Claude OAuth token (not stored in history)","/secret set <k> <v> set a secret (not stored in history)","/secret list list secret keys (no values)","/secret unset <k> remove a secret","/quit stop the daemon and the worker, exit"].join(`
838
- `))}async function nI(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=Zy(ek(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function oI(t,e){let r=yI(e,"--phase");try{let n=await np(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){vo(n)}}async function iI(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await op(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){vo(n)}}async function sI(t){let e=await bo(t.ws.root,t.ws.spec.repos);for(let r of e)console.log(` ${r.mountAs}: ${r.status}${r.detail?` \u2014 ${r.detail}`:""}`)}async function Xy(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await vp(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function aI(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=yr(t.ws.contextDir)[r],i=kI(e,"--pr");if(i.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let s=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of i){let l=c.indexOf("="),u,p;if(l>0?(u=c.slice(0,l),p=c.slice(l+1)):(p=c,u=o?.repos.length===1?lI(t,o.repos[0].mountAs):s.length===1?s[0]:""),!u){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${p}`);return}let d=p.match(/(?:pull|pull-requests)\/(\d+)/);if(!d){console.log(` cannot parse PR number from ${p}`);return}a.push({repoName:u,url:p,number:Number(d[1])})}try{let c=await ip(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);ga(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){vo(c)}}async function Jy(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await ap(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){vo(o)}}async function cI(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=wI(e,"--reason")||"local apply aborted";await Sp(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await sp(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){vo(o)}}function lI(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function uI(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},oe(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 dI(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(`
839
- `)}`:" (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}pI(t.secrets,n,i),oe(t.secrets),Gn(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}fI(t.secrets,n),oe(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function pI(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 fI(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 mI(t,e){switch(e.kind){case"connected":t.connection="connecting",Zt(t,"[hub] connected");break;case"registered":t.connection="registered",Zt(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Qt(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",Zt(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Qt(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Qt(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?Zt(t,`[hub] action ${e.actionType} done`):Qt(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break;case"local_applied":e.ok?Qt(t,`[apply] ${e.taskKey}: branch ${(e.branches??[]).join(", ")} created locally (your checkout is untouched) \u2014 review, push, then: /applied ${e.taskKey} --pr <url>`):Qt(t,`[apply] ${e.taskKey}: auto-apply failed \u2014 task stays in READY_TO_APPLY: ${e.error??"?"}`);break}}function Zt(t,e){t.logBuffer.push(e),t.logBuffer.length>tk&&t.logBuffer.shift(),t.follow&&Qt(t,e)}function gI(t,e){let r=e[0];if(r==="follow"||r==="on"){Jc(t,!0);return}if(r==="off"){Jc(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(tk,Number(r)||zy)):zy,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 hI(t){Jc(t,!t.follow)}function Jc(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Qt(t,e){vn.cursorTo(process.stdout,0),vn.clearLine(process.stdout,0),process.stdout.write(e+`
840
- `),t.unread+=1,Qc(t),t.rl.prompt(!0)}function Qc(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}function Qy(t){if(Zc)return;Zc=!0,$I(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
926
+ finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let s=On.createInterface({input:process.stdin,output:process.stdout,completer:WC,history:dA(),removeHistoryDuplicates:!0}),i={ws:e,secrets:r,connection:"connecting",rl:s,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};hf(a=>ar(i,a)),i.daemon=ai({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:a=>ar(i,a),warn:a=>ar(i,a)},onEvent:a=>sA(i,a),workspace:{root:e.root,contextDir:e.contextDir,repos:e.spec.repos.map(a=>({name:a.name,mountAs:a.mountAs,defaultBranch:a.defaultBranch}))}});try{let a={hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId};await Xl(a,t.profile,{profile:t.profile});let c=process.argv[1];if(!c)throw new Error("cannot resolve the codepipe entry script for the worker process");let l=Jl({entry:c,profile:t.profile,onLine:u=>ar(i,`[worker] ${u}`)});l.on("exit",(u,p)=>{i.workerExited=!0,!nu&&ir(i,`[worker] exited (code ${u??(p?1:0)}) \u2014 agent jobs will NOT run; /quit and restart codepipe to bring it back`)}),i.workerChild=l,console.log("embedded agent worker started \u2014 agent jobs run on this machine.")}catch(a){console.warn(`[worker] could not start the embedded worker (${a instanceof Error?a.message:String(a)}). REPL commands still work; run \`codepipe up --reregister\` if the registration was removed.`)}ru(i),s.prompt(),s.on("line",async a=>{let c=a.trim();if(c.length>0)try{if(await qC(i,c)){kw(i);return}}catch(l){console.error(l instanceof Error?l.message:String(l))}i.unread=0,ru(i),s.prompt()}),s.on("close",()=>{kw(i)})}function WC(t){let e=mw.filter(r=>r.startsWith(t));return[e.length?e:mw,t]}async function qC(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return YC(),!1;case"/status":return await VC(t),!1;case"/tasks":return await zC(t,n),!1;case"/task":return await XC(t,n),!1;case"/sync":return await JC(t),!1;case"/logs":return iA(t,n),!1;case"/monitor":return aA(t),!1;case"/apply":return await gw(t,n,"apply"),!1;case"/unstash":return await gw(t,n,"unstash"),!1;case"/applied":return await ZC(t,n),!1;case"/abort":return await QC(t,n),!1;case"/approve":return await yw(t,n,"approve"),!1;case"/merge":return await yw(t,n,"merge"),!1;case"/login":return tA(t,n),!1;case"/secret":return rA(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function YC(){console.log(["/help show this list","/status connection, project, embedded worker, siblings","/tasks [--phase P] list tasks (optionally filtered by phase)","/task <key> task detail (phase + artifacts)","/sync clone/fetch project repos per project.yaml","/logs [n|follow|clear] tail last n daemon/worker logs / toggle live / clear buffer","/monitor toggle live daemon/worker log streaming (alias /logs follow)","/apply <key> apply task patch on a new branch + commit (local mode)","/unstash <key> apply task patch uncommitted on base commit","/applied <key> --pr U mark applied; --pr repo=URL for multi-repo","/abort <key> --reason roll back local apply, send task back to agent","/approve <key> merge the task's PR(s) (TRACKING, PR mode)","/merge <key> direct-merge the branch to main (TRACKING, no-PR mode)","/login <token> set the Claude OAuth token (not stored in history)","/secret set <k> <v> set a secret (not stored in history)","/secret list list secret keys (no values)","/secret unset <k> remove a secret","/quit stop the daemon and the worker, exit"].join(`
927
+ `))}async function VC(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=ww(bw(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function zC(t,e){let r=cA(e,"--phase");try{let n=await af(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId),o=r?n.filter(s=>s.phase.toLowerCase()===r.toLowerCase()):n;if(o.length===0){console.log(" (no tasks)");return}for(let s of o)console.log(` ${s.key.padEnd(10)} ${s.phase.padEnd(16)} ${s.title}`)}catch(n){Ko(n)}}async function XC(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await cf(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){Ko(n)}}async function JC(t){let e=await Bo(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 gw(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await Rf(t.ws,t.secrets,n,r,{info:s=>console.log(s),warn:s=>console.warn(s)});console.log(` ${o.message}`)}async function ZC(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=Ir(t.ws.contextDir)[r],s=lA(e,"--pr");if(s.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let i=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of s){let l=c.indexOf("="),u,p;if(l>0?(u=c.slice(0,l),p=c.slice(l+1)):(p=c,u=o?.repos.length===1?eA(t,o.repos[0].mountAs):i.length===1?i[0]:""),!u){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${p}`);return}let d=p.match(/(?:pull|pull-requests)\/(\d+)/);if(!d){console.log(` cannot parse PR number from ${p}`);return}a.push({repoName:u,url:p,number:Number(d[1])})}try{let c=await lf(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);hc(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){Ko(c)}}async function yw(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await df(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){Ko(o)}}async function QC(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=uA(e,"--reason")||"local apply aborted";await If(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await uf(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){Ko(o)}}function eA(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function tA(t,e){let r=e.join(" ").trim();if(!r){console.log("usage: /login <claude-oauth-token>"),console.log(" get one with `claude setup-token`, then paste it here."),console.log(" (this line is scrubbed from history; takes effect on next SANDBOX reconnect)");return}t.secrets.claude={oauthToken:r},ie(t.secrets),console.log(" Claude OAuth token saved. It will be sealed into job bundles for SANDBOXes."),console.log(" Re-seal happens when a SANDBOX (re)connects; restart it if you need it now.")}function rA(t,e){let[r,n,...o]=e;if(r==="list"){let s=[];t.secrets.github&&s.push("github.token"),t.secrets.bitbucket&&s.push("bitbucket.email","bitbucket.apiToken"),t.secrets.youtrack&&s.push("youtrack.url","youtrack.token"),console.log(s.length?` ${s.join(`
928
+ `)}`:" (none)");return}if(r==="set"){let s=o.join(" ");if(!n||!s){console.log("usage: /secret set <key> <value> (keys: GH_TOKEN, YOUTRACK_URL, YOUTRACK_TOKEN, BITBUCKET_EMAIL, BITBUCKET_API_TOKEN)");return}nA(t.secrets,n,s),ie(t.secrets),ao(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}oA(t.secrets,n),ie(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function nA(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 oA(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 sA(t,e){switch(e.kind){case"connected":t.connection="connecting",ar(t,"[hub] connected");break;case"registered":t.connection="registered",ar(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",ir(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",ar(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",ir(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":ir(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?ar(t,`[hub] action ${e.actionType} done`):ir(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break;case"local_applied":e.ok?ir(t,`[apply] ${e.taskKey}: branch ${(e.branches??[]).join(", ")} created locally (your checkout is untouched) \u2014 review, push, then: /applied ${e.taskKey} --pr <url>`):ir(t,`[apply] ${e.taskKey}: auto-apply failed \u2014 task stays in READY_TO_APPLY: ${e.error??"?"}`);break}}function ar(t,e){t.logBuffer.push(e),t.logBuffer.length>$w&&t.logBuffer.shift(),t.follow&&ir(t,e)}function iA(t,e){let r=e[0];if(r==="follow"||r==="on"){tu(t,!0);return}if(r==="off"){tu(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min($w,Number(r)||hw)):hw,o=t.logBuffer.slice(-n);if(o.length===0){console.log(" (no daemon logs buffered yet)");return}for(let s of o)console.log(` ${s}`);console.log(` \u2014 ${o.length} line(s); /monitor for live stream`)}function aA(t){tu(t,!t.follow)}function tu(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function ir(t,e){On.cursorTo(process.stdout,0),On.clearLine(process.stdout,0),process.stdout.write(e+`
929
+ `),t.unread+=1,ru(t),t.rl.prompt(!0)}function ru(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}function kw(t){if(nu)return;nu=!0,pA(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
841
930
  bye.`),setTimeout(()=>process.exit(0),150);return}console.log(`
842
- 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 yI(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function kI(t,e){let r=[];for(let n=0;n<t.length;n++)t[n]===e&&t[n+1]&&r.push(t[n+1]);return r}function wI(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function vo(t){t instanceof K?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function bI(){if(!Zy(gs))return[];try{return XE(gs,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function $I(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{zE(ZE(gs),{recursive:!0}),JE(gs,r.slice().reverse().join(`
931
+ 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 cA(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function lA(t,e){let r=[];for(let n=0;n<t.length;n++)t[n]===e&&t[n+1]&&r.push(t[n+1]);return r}function uA(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function Ko(t){t instanceof H?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function dA(){if(!ww(Ai))return[];try{return FC(Ai,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function pA(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{BC(HC(Ai),{recursive:!0}),KC(Ai,r.slice().reverse().join(`
843
932
  `)+`
844
- `)}catch{}}var gs,Vy,tk,zy,Zc,tl=v(()=>{"use strict";Tc();Ie();si();ue();mt();fs();zc();ha();gs=ek(QE(),".codepipe","history"),Vy=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],tk=500,zy=40;Zc=!1});import{existsSync as xn,mkdirSync as ok,readFileSync as ik,readdirSync as vI,writeFileSync as sk}from"node:fs";import{join as Sr,resolve as ak}from"node:path";import{setTimeout as rl}from"node:timers/promises";import{cancel as xI,confirm as Sn,intro as ck,isCancel as il,log as P,multiselect as SI,outro as nl,password as xo,select as st,spinner as sl,text as fe}from"@clack/prompts";import{simpleGit as ys}from"simple-git";function le(t){xI(t),process.exit(1)}function Ee(t){return il(t)&&le("aborted"),t}function se(t){return il(t)&&le("aborted"),typeof t=="string"?t:""}async function lk(t={}){ck("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();jy();let r=_y(e),n,o=!1;r&&Object.keys(r.answers).length>0?Ee(await Sn({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 $n(e,r),o=!0):(Wc(e),n=new $n(e)):n=new $n(e);let i=t.force===!0?null:await Xc(e),s=await n.ask("target",async()=>Ee(await st({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i,a?P.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):o&&n.get("contextRepo")!==void 0||dk(e,t.force===!0));let c=await n.ask("hubUrl",async()=>se(await fe({message:"HUB URL",placeholder:ct,initialValue:V("HUB_URL")??ct,validate:$=>$.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>Tn()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>En(c,l)),d=null;s==="farm"&&(d=await TI(c,u));let f=a?II(a.parsed.repoName):"",m=await n.ask("projectId",async()=>se(await fe({message:"project id (slug)",placeholder:f||"acme",...f?{initialValue:f}:{},validate:$=>ir.test($.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),h=await n.ask("projectName",async()=>se(await fe({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:$=>$.trim().length>0?void 0:"required"})).trim()),g=await n.ask("language",()=>LI()),w=await n.ask("automationLevel",async()=>Ee(await st({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),y=s==="farm"?"auto":await n.ask("applyMode",async()=>Ee(await st({message:"how do approved changes reach your repo?",options:[{value:"auto",label:"auto \u2014 CodePipe pushes the branch and opens a PR"},{value:"local",label:"local \u2014 changes wait; you pull them into your checkout via the CLI REPL (/apply or /unstash), no push/PR"}],initialValue:"auto"}))),x=await n.ask("trackerProvider",async()=>Ee(await st({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=x==="internal",I=null,E,b=!0;if(T){let $,j=sl();j.start("checking task-key prefixes on your account\u2026");try{$=await ep(c,u,{excludeProjectId:m}),j.stop("prefixes checked")}catch{j.stop("could not reach the HUB",1),le("Could not verify the task-key prefix against your account \u2014 the HUB is unreachable right now. Prefix uniqueness is required, so init can't continue. Check your connection and re-run `codepipe init` later.")}let Y=Su(xu(h),$);E=await n.ask("trackerPrefix",async()=>se(await fe({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:Y,initialValue:Y,validate:ke=>{let J=ke.trim();if(!Lr.test(J))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if($.has(J.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else I=await n.ask("youtrack",()=>kk()),E=await n.ask("youtrackProjectKey",async()=>se(await fe({message:"YouTrack project key",placeholder:"DEV",validate:$=>$.trim().length>0?void 0:"required"})).trim()),b=await n.ask("youtrackWrites",async()=>Ee(await Sn({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let R=n.get("tokens")??{},N=()=>n.set("tokens",R),F=await n.ask("repos",()=>AI(R,l,a,{onCred:N,initial:n.get("reposPartial")??[],onProgress:$=>n.set("reposPartial",$)}));n.delete("reposPartial");let C=await PI(await n.ask("contextRepo",()=>gk(m,F,R,l)),m,F,R,l,N,$=>n.set("contextRepo",$)),{spec:k,mode:L}=C,A;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)."),A=await n.ask("assigneeLogin",async()=>se(await fe({message:"your YouTrack login (the assignee value)",...I?.login?{initialValue:I.login}:{},validate:$=>$.trim().length>0?void 0:"required"})).trim()));let H=await n.ask("llmProvider",async()=>{for(;;){if(Ee(await st({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.")}}),q=H==="claude"?await n.ask("claudeToken",()=>vy($y("claude"),{farm:s==="farm"})):"",Z;if(q){let $=await Fd(q);if($){let j=Vl($);j&&(Z=j,P.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${j} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let Ye={projectId:m,name:h,automationLevel:w,repos:F,trackerProvider:x,youtrackProjectKey:E,language:g};P.step(`${L==="attach"?"attaching to":"provisioning"} Context Repo ${k.owner}/${k.name} (${k.host})\u2026`);let Ve;try{Ve=await bn(Ye,k,{...hk(R),youtrackWrites:b,...I?{trackerUrl:I.url}:{},mode:L,log:{info:$=>P.message($),warn:$=>P.warn($)}})}catch($){le(`Context Repo provisioning failed: ${$ instanceof Error?$.message:String($)}`)}Ye.contextRepo=Ve,P.success(`Context Repo ready: ${Ve.owner}/${Ve.name}@${Ve.branch}`),P.step(`registering project on ${c}\u2026`);let ge;try{ge=await Ft(c,u,Ye)}catch($){if($ instanceof K&&$.status===409){P.warn(`project ${m} already exists on HUB \u2014 reusing it`);try{ge=await ne(c,u,m)}catch(j){throw j instanceof K&&le(`HUB \u2192 ${j.status} ${j.message}`),j}}else if($ instanceof K&&$.status===401)n.delete("cliToken"),le("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if($ instanceof K)le(`HUB \u2192 ${$.status} ${$.message}`);else throw $}let _=ge.contextRepo??Ve;P.success(`project ${ge.projectId} ready (${ge.provisioningStatus})`);let M=await DI(_),D=I?{url:I.url,token:I.token}:void 0;if(s==="farm"){let $=d,j={...R,...M?{contextWrite:M}:{},...q?{claude:{oauthToken:q}}:{},...D?{youtrack:D}:{}},Y=R.github?.token;if(_.host==="github"&&Y)try{let te=Eg(`devpipe-${m}`);await Ig(_,Y,te.publicKey,`devpipe-${m}`),j.contextSsh={privateKey:te.privateKey},P.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(te){P.warn(`could not set up Context Repo SSH deploy key (${te instanceof Error?te.message:String(te)}); the farm will fall back to the token path.`)}let ke={projectId:m,config:{hubUrl:c,cliToken:u,projectId:m},secrets:j,contextRepo:_,projectConfig:yt(Ye,b,I?.url,A||void 0,"auto",H,Z)},J=Tt($.farm.publicKey,JSON.stringify(ke));P.step(`handing project ${m} to farm ${$.farm.name}\u2026`);let we;try{we=await oi(c,u,$.farm.farmId,{projectId:m,sealedBundle:J})}catch(te){throw te instanceof K&&le(te.status===409?`farm ${$.farm.name} is offline \u2014 start it and re-run.`:te.status===504?`farm ${$.farm.name} did not respond in time.`:`HUB \u2192 ${te.status} ${te.message}`),te}we.ok||le(`farm rejected provisioning: ${we.error??"unknown error"}`),await ol(c,u,m,_,Y,ge.repos,null,R),n.clear(),nl(`done. project ${m} is now hosted on farm ${$.farm.name} (daemon ${we.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}yk(R),await pk(e,_.cloneUrl,_.branch),mk(e),a&&await CI(e);{let $=Sr(e,ft);qr($);let j=yt(Ye,b,I?.url,A||void 0,y,H,Z),Y=Xn($,j);Y.length>0&&P.success(`local project config \u2192 .codepipe/{${Y.join(", ")}}`),kr(m,j,{info:ke=>P.message(ke),warn:ke=>P.warn(ke)})}await fk(e,ge.repos);let z={hubUrl:c,cliToken:u,projectId:m,...R,...M?{contextWrite:M}:{},...q?{claude:{oauthToken:q}}:{},...D?{youtrack:D}:{}};oe(z),vt({hubUrl:c,cliToken:u,projectId:m,accountEmail:p},m),P.success(`secrets \u2192 ${gt(m)}`),await ol(c,u,m,_,R.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,ge.repos,e,R),n.clear();let O=`${c}/?project=${encodeURIComponent(m)}`;ur(O),nl(`done. your project on the dashboard (sign in there to work with it):
845
- ${O}
846
- starting codepipe \u2014 the CLI daemon, an agent worker, and a command line. type /help for commands; Ctrl+D or /quit to exit (restart anytime with \`codepipe\` from this folder).`);let{replCommand:S}=await Promise.resolve().then(()=>(tl(),rk));await S({})}async function ol(t,e,r,n,o,i=[],s=null,a={}){let c=await Ly(n,o),l=!1;if(!c)try{l=await Uy(i,{localRoot:s,tokens:a})}catch{l=!1}let u=Oy({indexExists:c,localClones:s!==null,reposNonEmpty:l}),p=await SI({message:u.message,options:u.options,initialValues:u.initialValues,required:!1});if(il(p))return;let d=new Set(p);if(d.has("map")&&s!==null)try{let f=Se(s);if(!f)throw new Error("workspace not found");let{bootstrapWorkspaceModel:m}=await Promise.resolve().then(()=>(po(),Wi)),h=await m(f,void 0,{onLog:g=>P.message(g)});P.success(`project map ready: ${h.events} task events mined from history`)}catch(f){P.warn(`could not build the project map: ${f instanceof Error?f.message:String(f)}. Registration is not affected \u2014 run \`codepipe model bootstrap\` later.`)}if(d.has("backfill"))try{let{jobId:f}=await Wn(t,e,r,{reindex:!1,backfill:!0});P.success(`retrospective architecture analysis queued (job ${f}); decision drafts will appear on the project card for review once a SANDBOX picks up the job.`)}catch(f){P.warn(`could not start the retrospective analysis: ${f instanceof Error?f.message:String(f)}. Registration is not affected.`)}if(d.has("index"))try{let{jobId:f}=await Wn(t,e,r,{reindex:u.reindex});P.success(`indexing queued (job ${f}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(f){P.warn(`could not start indexing: ${f instanceof Error?f.message:String(f)}. You can retry later \u2014 registration is not affected.`)}}async function TI(t,e){let r;try{r=await Xd(t,e)}catch(c){throw c instanceof K&&le(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&le("no farm is available to this account. Farms are assigned by the operator \u2014 ask them to assign one to you (or, if you run your own farm host: `codepipe-farm register --hub <url> --token <token>` and `codepipe-farm start`, then have the operator assign it).");let o=Ee(await st({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=Bi(i.farmId,i.publicKey)}catch(c){le(c instanceof Error?c.message:String(c))}return Ee(await Sn({message:`confirm farm ${i.name} cred-channel fingerprint:
847
- ${s}
848
- (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||le("farm fingerprint not confirmed \u2014 aborting."),Ui(i.farmId,s),{farm:i,fingerprint:s}}async function uk(t){ck(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();dk(e,t.force===!0);let r=se(await fe({message:"HUB URL",initialValue:V("HUB_URL")??ct,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await Tn(),{cliToken:o,accountEmail:i}=await En(r,n);P.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await ne(r,o,t.projectId)}catch(d){throw d instanceof K&&le(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||le(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await kk(),l={},u=new Set(s.repos.map(d=>d.host));u.add(s.contextRepo.host);for(let d of u){let f=s.repos.find(m=>m.host===d);await hs(d,l,f?.owner??s.contextRepo.owner,n,f?.repoName)}yk(l),await pk(e,s.contextRepo.cloneUrl,s.contextRepo.branch),mk(e);{let d=Sr(e,ft);qr(d);let f={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.trackerProvider?{trackerProvider:s.trackerProvider}:{},...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{},...s.language?{language:s.language}:{}},m=yt(f,!0,c?.url,void 0,"auto",s.llmProvider??pt),h=Xn(d,m);h.length>0&&P.success(`local project config \u2192 .codepipe/{${h.join(", ")}} (defaults \u2014 review and adjust)`),kr(t.projectId,m,{info:g=>P.message(g),warn:g=>P.warn(g)})}await fk(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};oe(p),vt({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),P.success(`secrets \u2192 ${gt(t.projectId)}`),await ol(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),nl("done.")}function dk(t,e){if(!xn(t)){ok(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=vI(t).filter(o=>!r.has(o));n.length!==0&&(e||le(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function Xc(t){if(!xn(Sr(t,".git")))return null;try{let r=(await ys(t).remote(["get-url","origin"])||"").toString().trim(),n=r?qe(r):null;return n?{parsed:n,defaultBranch:await EI(t)}:null}catch{return null}}async function EI(t){let e=ys(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 II(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return ir.test(e)?e:""}function RI(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function CI(t){let e=Sr(t,".gitignore"),r=xn(e)?ik(e,"utf-8"):"";if(RI(r))return;if(!Ee(await Sn({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(`
933
+ `)}catch{}}var Ai,mw,$w,hw,nu,su=$(()=>{"use strict";El();Ae();$s();pe();bt();Ii();Ql();gc();Ai=bw(GC(),".codepipe","history"),mw=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],$w=500,hw=40;nu=!1});import{existsSync as Ln,mkdirSync as Sw,readFileSync as Ew,readdirSync as fA,writeFileSync as Rw}from"node:fs";import{join as Or,resolve as Tw}from"node:path";import{setTimeout as iu}from"node:timers/promises";import{cancel as mA,confirm as Dn,intro as Iw,isCancel as lu,log as A,multiselect as hA,outro as au,password as Go,select as yt,spinner as uu,text as ge}from"@clack/prompts";import{simpleGit as _i}from"simple-git";function de(t){mA(t),process.exit(1)}function Ce(t){return lu(t)&&de("aborted"),t}function le(t){return lu(t)&&de("aborted"),typeof t=="string"?t:""}async function Cw(t={}){Iw("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Qk();let r=Zk(e),n,o=!1;r&&Object.keys(r.answers).length>0?Ce(await Dn({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 Nn(e,r),o=!0):(zl(e),n=new Nn(e)):n=new Nn(e);let s=t.force===!0?null:await eu(e),i=await n.ask("target",async()=>Ce(await yt({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;i==="local"&&(a=s,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||Pw(e,t.force===!0));let c=await n.ask("hubUrl",async()=>le(await ge({message:"HUB URL",placeholder:it,initialValue:J("HUB_URL")??it,validate:v=>v.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>Mn()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>Un(c,l)),d=null;i==="farm"&&(d=await gA(c,u));let m=a?kA(a.parsed.repoName):"",f=await n.ask("projectId",async()=>le(await ge({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:v=>Ft.test(v.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await n.ask("projectName",async()=>le(await ge({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:v=>v.trim().length>0?void 0:"required"})).trim()),h=await n.ask("language",()=>TA()),w=await n.ask("automationLevel",async()=>Ce(await yt({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),y=i==="farm"?"auto":await n.ask("applyMode",async()=>Ce(await yt({message:"how do approved changes reach your repo?",options:[{value:"auto",label:"auto \u2014 CodePipe pushes the branch and opens a PR"},{value:"local",label:"local \u2014 changes wait; you pull them into your checkout via the CLI REPL (/apply or /unstash), no push/PR"}],initialValue:"auto"}))),x=await n.ask("trackerProvider",async()=>Ce(await yt({message:"task tracker",options:[{value:"internal",label:"built-in \u2014 CodePipe tracks tasks itself (no external tracker needed)"},{value:"youtrack",label:"YouTrack \u2014 connect an existing YouTrack project"}],initialValue:"internal"}))),S=x==="internal",T=null,R,b=!0;if(S){let v,N=uu();N.start("checking task-key prefixes on your account\u2026");try{v=await nf(c,u,{excludeProjectId:f}),N.stop("prefixes checked")}catch{N.stop("could not reach the HUB",1),de("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 z=Ka(Fa(g),v);R=await n.ask("trackerPrefix",async()=>le(await ge({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:z,initialValue:z,validate:ve=>{let ot=ve.trim();if(!yr.test(ot))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(v.has(ot.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else T=await n.ask("youtrack",()=>Mw()),R=await n.ask("youtrackProjectKey",async()=>le(await ge({message:"YouTrack project key",placeholder:"DEV",validate:v=>v.trim().length>0?void 0:"required"})).trim()),b=await n.ask("youtrackWrites",async()=>Ce(await Dn({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let I=n.get("tokens")??{},D=()=>n.set("tokens",I),K=await n.ask("repos",()=>$A(I,l,a,{onCred:D,initial:n.get("reposPartial")??[],onProgress:v=>n.set("reposPartial",v)}));n.delete("reposPartial");let ee=await vA(await n.ask("contextRepo",()=>Ow(f,K,I,l)),f,K,I,l,D,v=>n.set("contextRepo",v)),{spec:C,mode:k}=ee,U;S||(A.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),U=await n.ask("assigneeLogin",async()=>le(await ge({message:"your YouTrack login (the assignee value)",...T?.login?{initialValue:T.login}:{},validate:v=>v.trim().length>0?void 0:"required"})).trim()));let P=await n.ask("llmProvider",async()=>{for(;;){if(Ce(await yt({message:"LLM provider",options:[{value:"claude",label:"Claude",hint:"recommended"},{value:"codex",label:"Codex",hint:"coming soon"}],initialValue:"claude"}))==="claude")return"claude";A.warn("Codex support is coming soon \u2014 pick Claude for now.")}}),G=P==="claude"?await n.ask("claudeToken",()=>Kk(Fk("claude"),{farm:i==="farm"})):"",Y;if(G){let v=await Hp(G);if(v){let N=fa(v);N&&(Y=N,A.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${N} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let se={projectId:f,name:g,automationLevel:w,repos:K,trackerProvider:x,youtrackProjectKey:R,language:h};A.step(`${k==="attach"?"attaching to":"provisioning"} Context Repo ${C.owner}/${C.name} (${C.host})\u2026`);let qe;try{qe=await jn(se,C,{...Lw(I),youtrackWrites:b,...T?{trackerUrl:T.url}:{},mode:k,log:{info:v=>A.message(v),warn:v=>A.warn(v)}})}catch(v){de(`Context Repo provisioning failed: ${v instanceof Error?v.message:String(v)}`)}se.contextRepo=qe,A.success(`Context Repo ready: ${qe.owner}/${qe.name}@${qe.branch}`),A.step(`registering project on ${c}\u2026`);let Ye;try{Ye=await Xt(c,u,se)}catch(v){if(v instanceof H&&v.status===409){A.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{Ye=await oe(c,u,f)}catch(N){throw N instanceof H&&de(`HUB \u2192 ${N.status} ${N.message}`),N}}else if(v instanceof H&&v.status===401)n.delete("cliToken"),de("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(v instanceof H)de(`HUB \u2192 ${v.status} ${v.message}`);else throw v}let _=Ye.contextRepo??qe;A.success(`project ${Ye.projectId} ready (${Ye.provisioningStatus})`);let B=await IA(_),O=T?{url:T.url,token:T.token}:void 0;if(i==="farm"){let v=d,N={...I,...B?{contextWrite:B}:{},...G?{claude:{oauthToken:G}}:{},...O?{youtrack:O}:{}},z=I.github?.token;if(_.host==="github"&&z)try{let ne=Cg(`devpipe-${f}`);await Ag(_,z,ne.publicKey,`devpipe-${f}`),N.contextSsh={privateKey:ne.privateKey},A.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(ne){A.warn(`could not set up Context Repo SSH deploy key (${ne instanceof Error?ne.message:String(ne)}); the farm will fall back to the token path.`)}let ve={projectId:f,config:{hubUrl:c,cliToken:u,projectId:f},secrets:N,contextRepo:_,projectConfig:xt(se,b,T?.url,U||void 0,"auto",P,Y)},ot=Lt(v.farm.publicKey,JSON.stringify(ve));A.step(`handing project ${f} to farm ${v.farm.name}\u2026`);let W;try{W=await ws(c,u,v.farm.farmId,{projectId:f,sealedBundle:ot})}catch(ne){throw ne instanceof H&&de(ne.status===409?`farm ${v.farm.name} is offline \u2014 start it and re-run.`:ne.status===504?`farm ${v.farm.name} did not respond in time.`:`HUB \u2192 ${ne.status} ${ne.message}`),ne}W.ok||de(`farm rejected provisioning: ${W.error??"unknown error"}`),await cu(c,u,f,_,z,Ye.repos,null,I),n.clear(),au(`done. project ${f} is now hosted on farm ${v.farm.name} (daemon ${W.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}Dw(I),await _w(e,_.cloneUrl,_.branch),Nw(e),a&&await bA(e);{let v=Or(e,_t);sn(v);let N=xt(se,b,T?.url,U||void 0,y,P,Y),z=go(v,N);z.length>0&&A.success(`local project config \u2192 .codepipe/{${z.join(", ")}}`),Cr(f,N,{info:ve=>A.message(ve),warn:ve=>A.warn(ve)})}await jw(e,Ye.repos);let X={hubUrl:c,cliToken:u,projectId:f,...I,...B?{contextWrite:B}:{},...G?{claude:{oauthToken:G}}:{},...O?{youtrack:O}:{}};ie(X),jt({hubUrl:c,cliToken:u,projectId:f,accountEmail:p},f),A.success(`secrets \u2192 ${$t(f)}`),await cu(c,u,f,_,I.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,Ye.repos,e,I),n.clear();let L=`${c}/?project=${encodeURIComponent(f)}`;$r(L),au(`done. your project on the dashboard (sign in there to work with it):
934
+ ${L}
935
+ starting codepipe \u2014 the CLI daemon, an agent worker, and a command line. type /help for commands; Ctrl+D or /quit to exit (restart anytime with \`codepipe\` from this folder).`);let{replCommand:E}=await Promise.resolve().then(()=>(su(),vw));await E({})}async function cu(t,e,r,n,o,s=[],i=null,a={}){let c=await rw(n,o),l=!1;if(!c)try{l=await sw(s,{localRoot:i,tokens:a})}catch{l=!1}let u=tw({indexExists:c,localClones:i!==null,reposNonEmpty:l}),p=await hA({message:u.message,options:u.options,initialValues:u.initialValues,required:!1});if(lu(p))return;let d=new Set(p);if(d.has("map")&&i!==null)try{let m=Te(i);if(!m)throw new Error("workspace not found");let{bootstrapWorkspaceModel:f}=await Promise.resolve().then(()=>(Po(),ii)),g=await f(m,void 0,{onLog:h=>A.message(h)});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 uo(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 uo(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 gA(t,e){let r;try{r=await Qp(t,e)}catch(c){throw c instanceof H&&de(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&de("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=Ce(await yt({message:"target farm",options:n.map(c=>({value:c.farmId,label:`${c.name}${c.online?"":" (offline)"} \u2014 ${c.keyFingerprint??"no fingerprint"}`}))})),s=n.find(c=>c.farmId===o),i;try{i=ti(s.farmId,s.publicKey)}catch(c){de(c instanceof Error?c.message:String(c))}return Ce(await Dn({message:`confirm farm ${s.name} cred-channel fingerprint:
936
+ ${i}
937
+ (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||de("farm fingerprint not confirmed \u2014 aborting."),ei(s.farmId,i),{farm:s,fingerprint:i}}async function Aw(t){Iw(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();Pw(e,t.force===!0);let r=le(await ge({message:"HUB URL",initialValue:J("HUB_URL")??it,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await Mn(),{cliToken:o,accountEmail:s}=await Un(r,n);A.step(`fetching project ${t.projectId} from HUB\u2026`);let i;try{i=await oe(r,o,t.projectId)}catch(d){throw d instanceof H&&de(`HUB \u2192 ${d.status} ${d.message}`),d}i.contextRepo||de(`project ${t.projectId} has no Context Repo on HUB`);let c=i.trackerProvider==="internal"?null:await Mw(),l={},u=new Set(i.repos.map(d=>d.host));u.add(i.contextRepo.host);for(let d of u){let m=i.repos.find(f=>f.host===d);await Pi(d,l,m?.owner??i.contextRepo.owner,n,m?.repoName)}Dw(l),await _w(e,i.contextRepo.cloneUrl,i.contextRepo.branch),Nw(e);{let d=Or(e,_t);sn(d);let m={projectId:t.projectId,name:i.name,automationLevel:i.automationLevel,repos:i.repos,...i.trackerProvider?{trackerProvider:i.trackerProvider}:{},...i.youtrackProjectKey?{youtrackProjectKey:i.youtrackProjectKey}:{},...i.language?{language:i.language}:{}},f=xt(m,!0,c?.url,void 0,"auto",i.llmProvider??Ke),g=go(d,f);g.length>0&&A.success(`local project config \u2192 .codepipe/{${g.join(", ")}} (defaults \u2014 review and adjust)`),Cr(t.projectId,f,{info:h=>A.message(h),warn:h=>A.warn(h)})}await jw(e,i.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};ie(p),jt({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:s},t.projectId),A.success(`secrets \u2192 ${$t(t.projectId)}`),await cu(r,o,t.projectId,i.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,i.repos,e,l),au("done.")}function Pw(t,e){if(!Ln(t)){Sw(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=fA(t).filter(o=>!r.has(o));n.length!==0&&(e||de(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function eu(t){if(!Ln(Or(t,".git")))return null;try{let r=(await _i(t).remote(["get-url","origin"])||"").toString().trim(),n=r?nt(r):null;return n?{parsed:n,defaultBranch:await yA(t)}:null}catch{return null}}async function yA(t){let e=_i(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 kA(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Ft.test(e)?e:""}function wA(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function bA(t){let e=Or(t,".gitignore"),r=Ln(e)?Ew(e,"utf-8"):"";if(wA(r))return;if(!Ce(await Dn({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(`
849
938
  `)?"":`
850
- `;sk(e,r+o+`
939
+ `;Rw(e,r+o+`
851
940
  # codepipe workspace (added by \`codepipe init\`)
852
941
  .codepipe/
853
- `),P.success(`.codepipe/ added to ${ak(e)}`)}async function Tn(){let t="";try{t=(await ys().raw(["config","--global","user.email"])||"").trim()}catch{}return se(await fe({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function En(t,e){P.step(`connecting account ${e}`);let r;try{r=await tp(t,e)}catch(s){throw s instanceof Hn&&le(`${e} is not authorized on this HUB yet.
942
+ `),A.success(`.codepipe/ added to ${Tw(e)}`)}async function Mn(){let t="";try{t=(await _i().raw(["config","--global","user.email"])||"").trim()}catch{}return le(await ge({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function Un(t,e){A.step(`connecting account ${e}`);let r;try{r=await of(t,e)}catch(i){throw i instanceof lo&&de(`${e} is not authorized on this HUB yet.
854
943
  Sign up at ${t} (registration form on the login screen),
855
944
  wait for the operator to approve it by email, then re-run
856
- \`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&&(ur(r.authorizeUrl),P.message(`a browser tab was opened to confirm this CLI:
945
+ \`codepipe init\` with the same email.`),i}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&&($r(r.authorizeUrl),A.message(`a browser tab was opened to confirm this CLI:
857
946
  ${r.authorizeUrl}
858
947
  `+(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
859
- 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 rp(t,r.requestId)}catch(a){P.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await rl(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&P.message(`connected as ${a} (the account confirmed in the browser).`),P.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&le("the HUB rejected this account"),s.status==="expired"&&le("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,P.message(`email confirmed. waiting for the operator to approve your account\u2026
860
- (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await rl(5e3);continue}await rl(2e3)}le("bootstrap timed out")}async function pk(t,e,r){let n=Sr(t,ft);if(xn(Sr(n,".git"))){P.message(`${n} already cloned \u2014 skipping`);return}xn(n)&&le(`${n} exists but is not a git repo \u2014 remove it and re-run`),ok(n,{recursive:!0}),P.step(`cloning Context Repo \u2192 ${n}`);try{await ys().clone(e,n,["--branch",r]),P.success(`cloned ${e}`)}catch(o){le(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function fk(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 bo(t,r,{log:{info:o=>P.message(o),warn:o=>P.warn(o)}});for(let o of n)P.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function mk(t){let e=Sr(t,ft,".gitignore"),r="";if(xn(e)&&(r=ik(e,"utf-8")),nk.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
948
+ 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(),s=o+15*6e4;for(;Date.now()<s;){let i;try{i=await sf(t,r.requestId)}catch(a){A.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await iu(5e3);continue}if(i.status==="confirmed"&&i.cliToken){let a=i.email??e;return a!==e&&A.message(`connected as ${a} (the account confirmed in the browser).`),A.success("confirmed"),{cliToken:i.cliToken,accountEmail:a}}if(i.status==="rejected"&&de("the HUB rejected this account"),i.status==="expired"&&de("the request expired \u2014 re-run init"),i.status==="waiting_approval"||i.status==="email_confirmed"){n||(n=!0,s=o+24*60*6e4,A.message(`email confirmed. waiting for the operator to approve your account\u2026
949
+ (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await iu(5e3);continue}await iu(2e3)}de("bootstrap timed out")}async function _w(t,e,r){let n=Or(t,_t);if(Ln(Or(n,".git"))){A.message(`${n} already cloned \u2014 skipping`);return}Ln(n)&&de(`${n} exists but is not a git repo \u2014 remove it and re-run`),Sw(n,{recursive:!0}),A.step(`cloning Context Repo \u2192 ${n}`);try{await _i().clone(e,n,["--branch",r]),A.success(`cloned ${e}`)}catch(o){de(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function jw(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 Bo(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 Nw(t){let e=Or(t,_t,".gitignore"),r="";if(Ln(e)&&(r=Ew(e,"utf-8")),xw.filter(i=>i.startsWith("#")?!1:!r.split(/\r?\n/).includes(i)).length===0)return;let o=r.endsWith(`
861
950
  `)||r.length===0?"":`
862
- `,i=nk.join(`
951
+ `,s=xw.join(`
863
952
  `)+`
864
- `;sk(e,r+o+(r?`
865
- `:"")+i),P.message(`appended runtime entries to ${ak(e)}`)}async function AI(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;P.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await hs(s.host,t,s.owner,e,s.repoName),i?.();let c=se(await fe({message:"repo logical name (used inside Context Repo paths)",placeholder:s.repoName,initialValue:s.repoName,validate:u=>u.trim().length>0?void 0:"required"})).trim(),l=se(await fe({message:"default branch",placeholder:a,initialValue:a,validate:u=>u.trim().length>0?void 0:"required"})).trim();o.push({name:c,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:l,mountAs:"."}),n.onProgress?.(o)}for(;Ee(await Sn({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=se(await fe({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:f=>!f||!f.trim()||qe(f)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!a)continue;let c=qe(a);P.message(`${c.host}: ${c.owner}/${c.repoName}`),await hs(c.host,t,c.owner,e,c.repoName),i?.();let l=se(await fe({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=se(await fe({message:"default branch (optional)",placeholder:"main"})).trim(),p=se(await fe({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),d={name:l,host:c.host,owner:c.owner,repoName:c.repoName};u&&(d.defaultBranch=u),p&&p!==l&&(d.mountAs=p),o.push(d),n.onProgress?.(o)}return o}async function gk(t,e,r,n){P.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let o=Ee(await st({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));o==="attach"&&P.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let i=e[0]?.host,s=e[0]?.owner,a;if(i&&s){let c=se(await fe({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:$t(t),validate:u=>{let p=(u??"").trim();if(!p)return"required";if(!qe(p)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(p))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),l=qe(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await _I(),l=se(await fe({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=se(await fe({message:"Context Repo name",placeholder:$t(t),initialValue:$t(t),validate:p=>p.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:o}}function hk(t){return{githubToken:t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:t.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:t.bitbucket??Br()}}async function PI(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await hs(c.host,n,c.owner,o),i?.();let u=sl();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let p=await Sy(c,hk(n),{explain:l==="attach"});if(p.found===!0)return u.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(p.found==="unknown")return u.stop(`could not check ${c.owner}/${c.name} (${p.detail}) \u2014 continuing`,1),a;if(l==="create")return u.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;u.stop(p.detail,1);let d=Ee(await st({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(d==="abort"&&le("aborted"),d==="create")return a={spec:c,mode:"create"},s(a),a;a=await gk(e,r,n,o),s(a)}}async function _I(){return Ee(await st({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function So(t,e){let r=sl();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 yk(t){to(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),ro(t.gitlab?.token??process.env.GITLAB_TOKEN),no(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function hs(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await jI(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 NI(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 OI();i?e.gitlab=i:P.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function jI(t){for(;;){let e=se(await xo({message:`GitHub PAT \u2014 blank to skip
953
+ `;Rw(e,r+o+(r?`
954
+ `:"")+s),A.message(`appended runtime entries to ${Tw(e)}`)}async function $A(t,e,r,n={}){let o=[...n.initial??[]],s=n.onCred;if(r&&o.length===0){let{parsed:i,defaultBranch:a}=r;A.message(`this repo: ${i.host}: ${i.owner}/${i.repoName} (mounted in place)`),await Pi(i.host,t,i.owner,e,i.repoName),s?.();let c=le(await ge({message:"repo logical name (used inside Context Repo paths)",placeholder:i.repoName,initialValue:i.repoName,validate:u=>u.trim().length>0?void 0:"required"})).trim(),l=le(await ge({message:"default branch",placeholder:a,initialValue:a,validate:u=>u.trim().length>0?void 0:"required"})).trim();o.push({name:c,host:i.host,owner:i.owner,repoName:i.repoName,defaultBranch:l,mountAs:"."}),n.onProgress?.(o)}for(;Ce(await Dn({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=le(await ge({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:m=>!m||!m.trim()||nt(m)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!a)continue;let c=nt(a);A.message(`${c.host}: ${c.owner}/${c.repoName}`),await Pi(c.host,t,c.owner,e,c.repoName),s?.();let l=le(await ge({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:m=>m.trim().length>0?void 0:"required"})).trim(),u=le(await ge({message:"default branch (optional)",placeholder:"main"})).trim(),p=le(await ge({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),d={name:l,host:c.host,owner:c.owner,repoName:c.repoName};u&&(d.defaultBranch=u),p&&p!==l&&(d.mountAs=p),o.push(d),n.onProgress?.(o)}return o}async function Ow(t,e,r,n){A.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let o=Ce(await yt({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));o==="attach"&&A.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let s=e[0]?.host,i=e[0]?.owner,a;if(s&&i){let c=le(await ge({message:`Context Repo \u2014 a name (hosted at ${s}: ${i}/<name>) or a full clone URL`,initialValue:wt(t),validate:u=>{let p=(u??"").trim();if(!p)return"required";if(!nt(p)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(p))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),l=nt(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:s,owner:i,name:c}}else{let c=await xA(),l=le(await ge({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=le(await ge({message:"Context Repo name",placeholder:wt(t),initialValue:wt(t),validate:p=>p.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:o}}function Lw(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??Qr()}}async function vA(t,e,r,n,o,s,i){let a=t;for(;;){let{spec:c,mode:l}=a;await Pi(c.host,n,c.owner,o),s?.();let u=uu();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let p=await Hk(c,Lw(n),{explain:l==="attach"});if(p.found===!0)return u.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(p.found==="unknown")return u.stop(`could not check ${c.owner}/${c.name} (${p.detail}) \u2014 continuing`,1),a;if(l==="create")return u.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;u.stop(p.detail,1);let d=Ce(await yt({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(d==="abort"&&de("aborted"),d==="create")return a={spec:c,mode:"create"},i(a),a;a=await Ow(e,r,n,o),i(a)}}async function xA(){return Ce(await yt({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Ho(t,e){let r=uu();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 Dw(t){$o(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),vo(t.gitlab?.token??process.env.GITLAB_TOKEN),xo(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Pi(t,e,r,n,o){if(!e[t])if(t==="github"){let s=await SA(r);s?e.github=s:A.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let s=await EA(r,n,o);s?e.bitbucket=s: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 s=await RA();s?e.gitlab=s:A.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function SA(t){for(;;){let e=le(await Go({message:`GitHub PAT \u2014 blank to skip
866
955
  classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
867
956
  fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
868
957
  if org: approve token in org Settings \u2192 Personal access tokens.
869
958
  (Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo;
870
- set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await So("GitHub",()=>Nt(e,t?{owner:t}:void 0)))return{token:e};P.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function NI(t,e,r){for(P.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
959
+ set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await Ho("GitHub",()=>Gt(e,t?{owner:t}:void 0)))return{token:e};A.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function EA(t,e,r){for(A.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
871
960
  How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
872
961
  'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes:
873
962
  read:repository:bitbucket + write:repository:bitbucket +
874
963
  read:pullrequest:bitbucket + write:pullrequest:bitbucket
875
964
  \u2014 write scopes do NOT include read: pick BOTH scopes of each pair
876
965
  (+ admin:repository:bitbucket if this token will provision the Context Repo).
877
- The token is shown ONCE \u2014 copy it right away.`);;){let n=se(await fe({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:i=>!i||!i.trim()||i.includes("@")?void 0:"must be an email"})).trim();if(!n)return;let o=se(await xo({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 So("Bitbucket",async()=>{let i=await Ot(n,o,t);if(t&&r){let s=await ei(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 OI(){for(;;){let t=se(await xo({message:`GitLab PAT \u2014 blank to skip
878
- scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await So("GitLab",()=>Lt(t))){let e=await ld(t);return e&&P.warn(e),{token:t}}P.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function LI(){let t="__other__",e=async()=>se(await fe({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=Ee(await st({message:"project language",options:[...Mn.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:or};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:or}],i={primary:n};for(let s of o){let a=new Set,c=[s.initial,n,"English",or].filter(u=>a.has(u)?!1:(a.add(u),!0)).map(u=>({value:u,label:u===or?"auto \u2014 mirror the language of the user's material":u}));c.push({value:t,label:"other\u2026"});let l=Ee(await st({message:`language for ${s.label}`,options:c,initialValue:s.initial}));i[s.key]=l===t?await e():l}return i}async function DI(t){if(Ee(await Sn({message:`Issue a separate context-write token (scoped to the Context Repo only)?
966
+ The token is shown ONCE \u2014 copy it right away.`);;){let n=le(await ge({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:s=>!s||!s.trim()||s.includes("@")?void 0:"must be an email"})).trim();if(!n)return;let o=le(await Go({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 Ho("Bitbucket",async()=>{let s=await Ht(n,o,t);if(t&&r){let i=await hs(n,o,t,r);if(i)throw new Error(i)}return s}))return{email:n,apiToken:o};A.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function RA(){for(;;){let t=le(await Go({message:`GitLab PAT \u2014 blank to skip
967
+ scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Ho("GitLab",()=>Wt(t))){let e=await pp(t);return e&&A.warn(e),{token:t}}A.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function TA(){let t="__other__",e=async()=>le(await ge({message:"language name (in English, e.g. Ukrainian)",validate:i=>{let a=i.trim();if(a.length===0)return"required";if(a.length>40)return`\u2264 ${40} chars`}})).trim(),r=Ce(await yt({message:"project language",options:[...Yr.map(i=>({value:i,label:i==="English"?"English (default)":i})),{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:we};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:we}],s={primary:n};for(let i of o){let a=new Set,c=[i.initial,n,"English",we].filter(u=>a.has(u)?!1:(a.add(u),!0)).map(u=>({value:u,label:u===we?"auto \u2014 mirror the language of the user's material":u}));c.push({value:t,label:"other\u2026"});let l=Ce(await yt({message:`language for ${i.label}`,options:c,initialValue:i.initial}));s[i.key]=l===t?await e():l}return s}async function IA(t){if(Ce(await Dn({message:`Issue a separate context-write token (scoped to the Context Repo only)?
879
968
  Without it the SANDBOX pushes delivery commits with the project ${t.host}
880
969
  credential. A scoped token hardens setups where the SANDBOX runs outside
881
- your trusted network.`,initialValue:!1})))for(t.host==="github"?P.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
970
+ your trusted network.`,initialValue:!1})))for(t.host==="github"?A.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
882
971
  permissions Contents: Read and write + Workflows: Read and write (Workflows is
883
- required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):P.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
884
- (${t.host==="gitlab"?"project access token, 'write_repository' scope":"Bitbucket repository access token, Repositories: Read & write \u2014 the only Bitbucket credential scopeable to a single repo; an account-wide API token would defeat the scoping"}).`);;){let r=se(await xo({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await So("contextWrite",()=>MI(r,t)))return{token:r};P.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function MI(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n;try{n=await fetch(`https://api.github.com/repos/${e.owner}/${e.name}`,{headers:r})}catch(i){throw new Error(`cannot reach api.github.com (${i instanceof Error?i.message:String(i)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the PAT)");if(n.status===404)throw new Error(`token cannot see ${e.owner}/${e.name} (404) \u2014 scope the fine-grained PAT to that repo and approve it in the org, or use a classic PAT with 'repo'`);if(!n.ok)throw new Error(`GitHub \u2192 ${n.status} ${n.statusText}`);let o=await n.json();if(o.permissions&&o.permissions.push===!1)throw new Error(`token has no write access to ${e.owner}/${e.name} \u2014 needs Contents: write`);return o.full_name??`${e.owner}/${e.name}`}async function kk(){for(;;){let t=se(await fe({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let n=r.trim();if(!n)return"required";if(!n.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=se(await xo({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await So("YouTrack",()=>Ut({baseUrl:t,token:e}))){let r=await xd({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}P.warn("re-enter the YouTrack URL / token.")}}var nk,$o=v(()=>{"use strict";_e();G();We();xy();ri();De();St();wr();Kr();us();Ec();ds();Dt();lr();Ny();Ie();Dy();By();lc();$i();ue();fs();mt();nk=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});G();_e();De();import{Command as yR}from"commander";Go();import{homedir as Uu}from"node:os";import{join as Bu}from"node:path";function Fu(){ar(Bu(Uu(),".devpipe"),Bu(Uu(),".codepipe"))}De();ue();async function ed(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=Qe(e);r&&!t.force&&(console.error(`already configured at ${Mr(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");vt({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...W(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};oe(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${Mr(e)}`)}Vs();De();Tc();Ie();ue();St();Ic();mt();$i();import{homedir as Rc}from"node:os";import{join as fo}from"node:path";async function Og(t={profile:void 0}){let{cfg:e,profile:r}=qo(t.profile),n=W(e.projectId);n&&Gn(n),to(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),ro(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),no(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=fo(Rc(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=zo("CLI_LOG",i,o);if(s.enabled){let d=new Fr(s);Xo(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=Ho(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(Rc(),".codepipe",r?fo("profiles",r,"context"):"context");if(await pa(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await jg(()=>Vi({cfg:e,secrets:n,contextDir:d,log:{info:f=>console.log(f),warn:f=>console.warn(f)}}),{log:{warn:f=>console.warn(f)}}),a||await pa(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let f=fo(Rc(),".codepipe",r?fo("profiles",r,"context-config"):"context-config");fi(a.contextDir,f,{info:m=>console.log(m),warn:m=>console.warn(m)})}}let l=qi(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(`
885
- [${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}kn();De();Ie();async function yy(t={profile:void 0}){let e=Ge(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=ni(e.hubUrl,e.cliToken),n=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let u=l.toString("utf-8");if(s.push(`msg:${u}`),u!=="pong")try{let p=JSON.parse(u);p.type==="registered"?(a=!!p.ok,clearTimeout(c),r.send("ping")):p.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,u)=>{s.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of n.events)console.log(` ${i}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await ne(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=Ae(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`)")}$o();import{readFileSync as UI}from"node:fs";G();De();St();us();wr();Dt();lr();Ie();ue();function me(t){throw new Error(t)}function xe(t,e){return(typeof t!="string"||t.trim().length===0)&&me(`config: '${e}' must be a non-empty string`),t.trim()}function To(t,e){if(t==null)return;typeof t!="string"&&me(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function BI(t){(!t||typeof t!="object")&&me("config: expected a JSON object");let e=t,r=xe(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||me("config: 'hubUrl' must start with http(s)://");let n=xe(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&me("config: 'project' is required");let i=o,s=xe(i.id,"project.id");ir.test(s)||me("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=xe(i.name,"project.name"),c=xe(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&me("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||me("config: 'project.repos' must be an array");let u=l.map((y,x)=>{(!y||typeof y!="object")&&me(`config: project.repos[${x}] must be an object`);let T=y,I=xe(T.host,`project.repos[${x}].host`);I!=="github"&&I!=="bitbucket"&&I!=="gitlab"&&me(`config: project.repos[${x}].host must be 'github', 'bitbucket' or 'gitlab'`);let E={name:xe(T.name,`project.repos[${x}].name`),host:I,owner:xe(T.owner,`project.repos[${x}].owner`),repoName:xe(T.repoName,`project.repos[${x}].repoName`)},b=To(T.defaultBranch,`project.repos[${x}].defaultBranch`);b&&(E.defaultBranch=b);let R=To(T.mountAs,`project.repos[${x}].mountAs`);return R&&(E.mountAs=R),E}),p=i.contextRepo;(!p||typeof p!="object")&&me("config: 'project.contextRepo' is required");let d=p,f=To(d.host,"project.contextRepo.host")??"github";f!=="github"&&f!=="bitbucket"&&f!=="gitlab"&&me("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let m={host:f,owner:xe(d.owner,"project.contextRepo.owner"),name:To(d.name,"project.contextRepo.name")??$t(s)},h={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:m}},g=To(i.youtrackProjectKey,"project.youtrackProjectKey");if(g&&(h.project.youtrackProjectKey=g),i.index!==void 0&&(typeof i.index!="boolean"&&me("config: 'project.index' must be a boolean"),h.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&me("config: 'project.youtrackWrites' must be a boolean"),h.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let y=xe(i.llmProvider,"project.llmProvider");y==="codex"&&me(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),y!=="claude"&&me("config: 'project.llmProvider' must be 'claude'"),h.project.llmProvider=y}let w=e.secrets;if(w!==void 0){(typeof w!="object"||w===null)&&me("config: 'secrets' must be an object");let y=w,x={};if(y.github){let T=y.github;x.github={token:xe(T.token,"secrets.github.token")}}if(y.bitbucket){let T=y.bitbucket;x.bitbucket={email:xe(T.email,"secrets.bitbucket.email"),apiToken:xe(T.apiToken,"secrets.bitbucket.apiToken")}}if(y.gitlab){let T=y.gitlab;x.gitlab={token:xe(T.token,"secrets.gitlab.token")}}if(y.youtrack){let T=y.youtrack;x.youtrack={url:xe(T.url,"secrets.youtrack.url").replace(/\/$/,""),token:xe(T.token,"secrets.youtrack.token")}}if(y.contextWrite){let T=y.contextWrite;x.contextWrite={token:xe(T.token,"secrets.contextWrite.token")}}h.secrets=x}return h}async function FI(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function GI(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await Nt(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 Ot(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await ei(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 Lt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Ut({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function wk(t){let e=!t.configPath||t.configPath==="-"?await FI():UI(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){me(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=BI(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 GI(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 bn(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??Br(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){me(`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 Ft(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 ne(o,i,s.id);else if(d instanceof K)me(`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(oe(p),vt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${gt(s.id)}`),kr(s.id,yt(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,"auto",s.llmProvider??pt),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await Wn(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`)}De();ue();import{cancel as bk,intro as $k,isCancel as vk,log as al,outro as KI,password as xk}from"@clack/prompts";async function HI(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Sk(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await HI(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){$k("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),al.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await xk({message:"Claude OAuth token"});vk(i)&&(bk("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Zu({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Vo()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Ge(t.profile);if(!e){$k(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),al.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await xk({message:"Claude OAuth token"});vk(i)&&(bk("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=W(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},oe(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(al.success("Claude OAuth token saved."),KI("It will be sealed into job bundles when a SANDBOX (re)connects."))}po();G();De();St();us();wr();ds();Ie();ue();import{cancel as WI,confirm as qI,intro as YI,isCancel as Tk,log as Pe,outro as VI,select as Ek,text as er}from"@clack/prompts";function Ik(t){WI(t),process.exit(1)}function In(t){return Tk(t)&&Ik("aborted"),t}function Eo(t){return Tk(t)&&Ik("aborted"),typeof t=="string"?t:""}async function zI(t,e){let r=In(await Ek({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),n=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",o=Eo(await er({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=Eo(await er({message:"Context Repo name",placeholder:$t(t),initialValue:$t(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function Rk(t={profile:void 0}){let e=Ge(t.profile);YI(`codepipe project add \u2192 ${e.hubUrl}`);let r=In(await er({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>ir.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=In(await er({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=In(await Ek({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"})),i=In(await er({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=In(await qI({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=Eo(await er({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:w=>!w||!w.trim()||qe(w)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!d)break;let f=qe(d);Pe.message(`${f.host}: ${f.owner}/${f.repoName}`);let m=Eo(await er({message:"repo logical name (used inside Context Repo paths)",placeholder:f.repoName,initialValue:f.repoName,validate:w=>w.trim().length>0?void 0:"required"})).trim(),h=Eo(await er({message:"default branch (optional)",placeholder:"main"})).trim(),g={name:m,host:f.host,owner:f.owner,repoName:f.repoName};h&&(g.defaultBranch=h),a.push(g)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await zI(r,a),u=W(e.projectId);Pe.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await bn(c,l,{githubToken:u?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:u?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:u?.bitbucket??Br(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:d=>Pe.message(d),warn:d=>Pe.warn(d)}})}catch(d){Pe.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,Pe.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await Ft(e.hubUrl,e.cliToken,c);Pe.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),kr(r,yt(c,s,u?.youtrack?.url),{info:f=>Pe.message(f),warn:f=>Pe.warn(f)}),d.contextRepo&&(Pe.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),Pe.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&Pe.error(` error: ${d.provisioningError}`),VI("done")}catch(d){d instanceof K?(Pe.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&Pe.message(JSON.stringify(d.payload,null,2))):Pe.error(d instanceof Error?d.message:String(d)),process.exit(1)}}kn();De();Ie();ue();mt();$o();import{existsSync as XI,rmSync as JI}from"node:fs";import{confirm as QI,intro as ZI,isCancel as eR,log as tr,outro as tR,spinner as rR}from"@clack/prompts";function wt(t){tr.error(t),process.exit(1)}var Ck=t=>t.trim().replace(/\/+$/,"");async function Ak(t){ZI("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Se()?.spec.projectId??void 0;e||wt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=Qe(e);r||wt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Ck(r.hubUrl),o=r.projectId,i=Ck(t.hub);i.startsWith("http")||wt("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&wt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let w=rR();w.start(`reading project ${o} from ${n}\u2026`);try{l=await ne(n,r.cliToken,o),w.stop(`read project ${o} (${l.name})`)}catch(y){throw w.stop("could not read the source project",1),y instanceof K&&wt(`source HUB ${n} \u2192 ${y.status} ${y.message}. The source HUB must be reachable with a valid token to move a project.`),y}}l.contextRepo||wt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=W(o),p=(t.account??r.accountEmail??await Tn()).trim().toLowerCase();if(tr.message(`move project '${o}'
972
+ required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):A.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
973
+ (${t.host==="gitlab"?"project access token, 'write_repository' scope":"Bitbucket repository access token, Repositories: Read & write \u2014 the only Bitbucket credential scopeable to a single repo; an account-wide API token would defeat the scoping"}).`);;){let r=le(await Go({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await Ho("contextWrite",()=>CA(r,t)))return{token:r};A.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function CA(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n;try{n=await fetch(`https://api.github.com/repos/${e.owner}/${e.name}`,{headers:r})}catch(s){throw new Error(`cannot reach api.github.com (${s instanceof Error?s.message:String(s)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the PAT)");if(n.status===404)throw new Error(`token cannot see ${e.owner}/${e.name} (404) \u2014 scope the fine-grained PAT to that repo and approve it in the org, or use a classic PAT with 'repo'`);if(!n.ok)throw new Error(`GitHub \u2192 ${n.status} ${n.statusText}`);let o=await n.json();if(o.permissions&&o.permissions.push===!1)throw new Error(`token has no write access to ${e.owner}/${e.name} \u2014 needs Contents: write`);return o.full_name??`${e.owner}/${e.name}`}async function Mw(){for(;;){let t=le(await ge({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=le(await Go({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Ho("YouTrack",()=>Vt({baseUrl:t,token:e}))){let r=await Rp({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}A.warn("re-enter the YouTrack URL / token.")}}var xw,Fo=$(()=>{"use strict";Le();F();rt();Gk();ys();He();Ot();Ar();rn();Ei();Rl();Ri();qt();br();ew();Ae();nw();iw();ll();Ls();pe();Ii();bt();xw=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});F();Le();He();import{Command as cP}from"commander";He();pe();async function np(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=ut(e);r&&!t.force&&(console.error(`already configured at ${Jr(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");jt({hubUrl:n,cliToken:t.token,projectId:t.project},e);let s={...q(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};ie(s),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${Jr(e)}`)}Va();He();El();Ae();pe();Ot();Tl();bt();Ls();import{homedir as Il}from"node:os";import{join as _o}from"node:path";async function Mg(t={profile:void 0}){let{cfg:e,profile:r}=as(t.profile),n=q(e.projectId);n&&ao(n),$o(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),vo(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),xo(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=_o(Il(),".codepipe","logs"),s=r?`cli-daemon-${r}`:"cli-daemon",i=us("CLI_LOG",s,o);if(i.enabled){let d=new en(i);ds(d),console.log(`[log] file logging \u2192 ${d.path} (rotate at ${i.maxBytes}B, keep ${i.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let a=null,c=ss(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=_o(Il(),".codepipe",r?_o("profiles",r,"context"):"context");if(await pc(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await Lg(()=>li({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 pc(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=_o(Il(),".codepipe",r?_o("profiles",r,"context-config"):"context-config");Is(a.contextDir,m,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=ai(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(`
974
+ [${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}Pn();He();Ae();async function Dk(t={profile:void 0}){let e=Ze(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=ks(e.hubUrl,e.cliToken),n=await new Promise(s=>{let i=[],a=!1,c=setTimeout(()=>{i.push("timeout"),r.close(),s({ok:!1,events:i})},5e3);r.on("open",()=>{i.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(i.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=>i.push(`error:${l.message}`)),r.on("close",(l,u)=>{i.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),s({ok:a,events:i})}),setTimeout(()=>r.close(),1500)});for(let s of n.events)console.log(` ${s}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let s=await oe(e.hubUrl,e.cliToken,e.projectId);if(s.duplicateIntake){let i=s.duplicateIntake;console.warn(`warning: project \xAB${i.withProjectId}\xBB watches the same YouTrack columns (${i.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=je(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`)")}Fo();import{readFileSync as AA}from"node:fs";F();He();Ot();Ei();Ar();qt();br();Ae();pe();function ye(t){throw new Error(t)}function Ee(t,e){return(typeof t!="string"||t.trim().length===0)&&ye(`config: '${e}' must be a non-empty string`),t.trim()}function Wo(t,e){if(t==null)return;typeof t!="string"&&ye(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function PA(t){(!t||typeof t!="object")&&ye("config: expected a JSON object");let e=t,r=Ee(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||ye("config: 'hubUrl' must start with http(s)://");let n=Ee(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&ye("config: 'project' is required");let s=o,i=Ee(s.id,"project.id");Ft.test(i)||ye("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=Ee(s.name,"project.name"),c=Ee(s.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&ye("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=s.repos;Array.isArray(l)||ye("config: 'project.repos' must be an array");let u=l.map((y,x)=>{(!y||typeof y!="object")&&ye(`config: project.repos[${x}] must be an object`);let S=y,T=Ee(S.host,`project.repos[${x}].host`);T!=="github"&&T!=="bitbucket"&&T!=="gitlab"&&ye(`config: project.repos[${x}].host must be 'github', 'bitbucket' or 'gitlab'`);let R={name:Ee(S.name,`project.repos[${x}].name`),host:T,owner:Ee(S.owner,`project.repos[${x}].owner`),repoName:Ee(S.repoName,`project.repos[${x}].repoName`)},b=Wo(S.defaultBranch,`project.repos[${x}].defaultBranch`);b&&(R.defaultBranch=b);let I=Wo(S.mountAs,`project.repos[${x}].mountAs`);return I&&(R.mountAs=I),R}),p=s.contextRepo;(!p||typeof p!="object")&&ye("config: 'project.contextRepo' is required");let d=p,m=Wo(d.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&ye("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:m,owner:Ee(d.owner,"project.contextRepo.owner"),name:Wo(d.name,"project.contextRepo.name")??wt(i)},g={hubUrl:r,cliToken:n,project:{id:i,name:a,automationLevel:c,repos:u,contextRepo:f}},h=Wo(s.youtrackProjectKey,"project.youtrackProjectKey");if(h&&(g.project.youtrackProjectKey=h),s.index!==void 0&&(typeof s.index!="boolean"&&ye("config: 'project.index' must be a boolean"),g.project.index=s.index),s.youtrackWrites!==void 0&&(typeof s.youtrackWrites!="boolean"&&ye("config: 'project.youtrackWrites' must be a boolean"),g.project.youtrackWrites=s.youtrackWrites),s.llmProvider!==void 0){let y=Ee(s.llmProvider,"project.llmProvider");y==="codex"&&ye(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),y!=="claude"&&ye("config: 'project.llmProvider' must be 'claude'"),g.project.llmProvider=y}let w=e.secrets;if(w!==void 0){(typeof w!="object"||w===null)&&ye("config: 'secrets' must be an object");let y=w,x={};if(y.github){let S=y.github;x.github={token:Ee(S.token,"secrets.github.token")}}if(y.bitbucket){let S=y.bitbucket;x.bitbucket={email:Ee(S.email,"secrets.bitbucket.email"),apiToken:Ee(S.apiToken,"secrets.bitbucket.apiToken")}}if(y.gitlab){let S=y.gitlab;x.gitlab={token:Ee(S.token,"secrets.gitlab.token")}}if(y.youtrack){let S=y.youtrack;x.youtrack={url:Ee(S.url,"secrets.youtrack.url").replace(/\/$/,""),token:Ee(S.token,"secrets.youtrack.token")}}if(y.contextWrite){let S=y.contextWrite;x.contextWrite={token:Ee(S.token,"secrets.contextWrite.token")}}g.secrets=x}return g}async function _A(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function jA(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await Gt(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(s=>s.host==="bitbucket"),n=r?.owner??(t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:void 0),o=await Ht(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let s=await hs(e.bitbucket.email,e.bitbucket.apiToken,r.owner,r.repoName);if(s)throw new Error(`Bitbucket: ${s}`)}console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await Wt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Vt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Uw(t){let e=!t.configPath||t.configPath==="-"?await _A():AA(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){ye(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=PA(r),{hubUrl:o,cliToken:s,project:i}=n;console.log(`codepipe init --headless \u2192 ${o} (project=${i.id})`),t.skipVerify||(console.log("verifying credentials\u2026"),await jA(n));let a={projectId:i.id,name:i.name,automationLevel:i.automationLevel,repos:i.repos};i.youtrackProjectKey&&(a.youtrackProjectKey=i.youtrackProjectKey),console.log(`provisioning Context Repo ${i.contextRepo.owner}/${i.contextRepo.name} (${i.contextRepo.host})\u2026`);let c=n.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,l;try{l=await jn(a,i.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??Qr(),youtrackWrites:i.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){ye(`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 Xt(o,s,a)}catch(d){if(d instanceof H&&d.status===409)console.log(`project ${i.id} already exists on HUB \u2014 reusing it`),u=await oe(o,s,i.id);else if(d instanceof H)ye(`HUB \u2192 ${d.status} ${d.message}`);else throw d}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let p={hubUrl:o,cliToken:s,projectId:i.id,...n.secrets??{}};if(ie(p),jt({hubUrl:o,cliToken:s,projectId:i.id},i.id),console.log(`config + secrets written (profile ${i.id}) \u2192 ${$t(i.id)}`),Cr(i.id,xt(a,i.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,"auto",i.llmProvider??Ke),{info:d=>console.log(d),warn:d=>console.warn(d)}),i.index)try{let{jobId:d}=await uo(o,s,i.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 ${i.id} daemon`)}He();pe();import{cancel as Bw,intro as Fw,isCancel as Kw,log as du,outro as NA,password as Gw}from"@clack/prompts";async function OA(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Hw(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await OA(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Fw("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),du.message("Run `claude setup-token` and paste the token below (input hidden).");let s=await Gw({message:"Claude OAuth token"});Kw(s)&&(Bw("aborted"),process.exit(1)),e=s.trim()}e||(console.error("login: no token provided"),process.exit(1)),rp({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${ls()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Ze(t.profile);if(!e){Fw(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),du.message("Run `claude setup-token` and paste the token below (input hidden).");let s=await Gw({message:"Claude OAuth token"});Kw(s)&&(Bw("aborted"),process.exit(1)),e=s.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},ie(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(du.success("Claude OAuth token saved."),NA("It will be sealed into job bundles when a SANDBOX (re)connects."))}Po();F();He();Ot();Ei();Ar();Ri();Ae();pe();import{cancel as LA,confirm as DA,intro as MA,isCancel as Ww,log as Ne,outro as UA,select as qw,text as cr}from"@clack/prompts";function Yw(t){LA(t),process.exit(1)}function Bn(t){return Ww(t)&&Yw("aborted"),t}function qo(t){return Ww(t)&&Yw("aborted"),typeof t=="string"?t:""}async function BA(t,e){let r=Bn(await qw({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(i=>i.host===r)?.owner??e[0]?.owner??"",o=qo(await cr({message:"Context Repo owner (org / group / workspace / user)",placeholder:n||"your-org",initialValue:n,validate:i=>i.trim().length>0?void 0:"required"})).trim(),s=qo(await cr({message:"Context Repo name",placeholder:wt(t),initialValue:wt(t),validate:i=>i.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:s}}async function Vw(t={profile:void 0}){let e=Ze(t.profile);MA(`codepipe project add \u2192 ${e.hubUrl}`);let r=Bn(await cr({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>Ft.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=Bn(await cr({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=Bn(await qw({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"})),s=Bn(await cr({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),i=Bn(await DA({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=qo(await cr({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:w=>!w||!w.trim()||nt(w)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!d)break;let m=nt(d);Ne.message(`${m.host}: ${m.owner}/${m.repoName}`);let f=qo(await cr({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:w=>w.trim().length>0?void 0:"required"})).trim(),g=qo(await cr({message:"default branch (optional)",placeholder:"main"})).trim(),h={name:f,host:m.host,owner:m.owner,repoName:m.repoName};g&&(h.defaultBranch=g),a.push(h)}let c={projectId:r,name:n,automationLevel:o,repos:a};s&&(c.youtrackProjectKey=s);let l=await BA(r,a),u=q(e.projectId);Ne.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await jn(c,l,{githubToken:u?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:u?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:u?.bitbucket??Qr(),youtrackWrites:i,trackerUrl:u?.youtrack?.url,log:{info:d=>Ne.message(d),warn:d=>Ne.warn(d)}})}catch(d){Ne.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,Ne.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await Xt(e.hubUrl,e.cliToken,c);Ne.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),Cr(r,xt(c,i,u?.youtrack?.url),{info:m=>Ne.message(m),warn:m=>Ne.warn(m)}),d.contextRepo&&(Ne.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),Ne.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&Ne.error(` error: ${d.provisioningError}`),UA("done")}catch(d){d instanceof H?(Ne.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&Ne.message(JSON.stringify(d.payload,null,2))):Ne.error(d instanceof Error?d.message:String(d)),process.exit(1)}}Pn();He();Ae();pe();bt();Fo();import{existsSync as FA,rmSync as KA}from"node:fs";import{confirm as GA,intro as HA,isCancel as WA,log as lr,outro as qA,spinner as YA}from"@clack/prompts";function Rt(t){lr.error(t),process.exit(1)}var zw=t=>t.trim().replace(/\/+$/,"");async function Xw(t){HA("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Te()?.spec.projectId??void 0;e||Rt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=ut(e);r||Rt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=zw(r.hubUrl),o=r.projectId,s=zw(t.hub);s.startsWith("http")||Rt("--hub must be an http(s):// URL");let i=t.toProfile??e,a=t.project??o,c=i===e;c&&a===o&&s===n&&Rt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let w=YA();w.start(`reading project ${o} from ${n}\u2026`);try{l=await oe(n,r.cliToken,o),w.stop(`read project ${o} (${l.name})`)}catch(y){throw w.stop("could not read the source project",1),y instanceof H&&Rt(`source HUB ${n} \u2192 ${y.status} ${y.message}. The source HUB must be reachable with a valid token to move a project.`),y}}l.contextRepo||Rt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=q(o),p=(t.account??r.accountEmail??await Mn()).trim().toLowerCase();if(lr.message(`move project '${o}'
886
975
  from : ${n} (profile ${e})
887
- to : ${i} (profile ${s}, project ${a}, account ${p})
976
+ to : ${s} (profile ${i}, project ${a}, account ${p})
888
977
  \u2022 the source registration on the old HUB is left intact (non-destructive)
889
978
  \u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
890
- `+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let w=await QI({message:"Continue?",initialValue:!0});(eR(w)||!w)&&wt("aborted")}!c&&a===o&&tr.warn(`source and destination share the same project id, so they share one secrets file (${gt(a)}). Running both profiles at the same time will conflict \u2014 pass --project <newId> for a parallel setup, or keep only one active.`);let{cliToken:d,accountEmail:f}=await En(i,p),m={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:f,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};tr.step(`registering project on ${i}\u2026`);let h;try{h=await Ft(i,d,m)}catch(w){if(w instanceof K&&w.status===409){tr.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{h=await ne(i,d,a)}catch(y){throw y instanceof K&&wt(`target HUB \u2192 ${y.status} ${y.message}`),y}}else if(w instanceof K&&w.status===403)wt(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(w instanceof K)wt(`target HUB \u2192 ${w.status} ${w.message}`);else throw w}tr.success(`project ${h.projectId} ready on ${i} (${h.provisioningStatus})`),vt({hubUrl:i,cliToken:d,projectId:a,accountEmail:f},s);let g={...u??{},hubUrl:i,cliToken:d,projectId:a};if(delete g.sandboxPins,oe(g),tr.success(`profile '${s}' \u2192 ${gt(a)}`),c){let w=ot(s);XI(w)&&(JI(w),tr.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}tR(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}De();ja();ds();Ie();mr();ue();mt();import{existsSync as cl,rmSync as nR,statSync as oR}from"node:fs";import{join as ks,relative as iR,resolve as sR}from"node:path";import{cancel as aR,intro as _k,isCancel as cR,log as ye,outro as jk,text as Tr}from"@clack/prompts";import{simpleGit as Nk}from"simple-git";function Me(t){aR(t),process.exit(1)}function Er(t){return cR(t)&&Me("aborted"),typeof t=="string"?t:""}async function Pk(t){try{let e=await Nk(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function lR(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function uR(t,e){let r=W(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(lR(r,e)){ye.message(`reusing existing ${e} credentials`);return}if(ye.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=Er(await Tr({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=Er(await Tr({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=Er(await Tr({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}}oe(r),ye.success(`saved ${e} credentials`)}async function Ok(t){let e=Ge(t.profile);_k(`codepipe repo add \u2192 project ${e.projectId}`);let r=Se()??void 0,n;try{n=(await ne(e.hubUrl,e.cliToken,e.projectId)).repos}catch(y){Me(`could not read project from HUB: ${y instanceof Error?y.message:String(y)}`)}let o=t.target?.trim();if(!o){let y=await Pk(process.cwd());y?(o=process.cwd(),ye.message(`using the current directory (${y})`)):o=Er(await Tr({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:x=>x.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(cl(o)&&oR(o).isDirectory()){i=sR(o);let y=await Pk(i);y||Me(`${i} is not a git repository (no origin remote)`);let x=qe(y);x||Me(`origin ${y} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=x,s=y,ye.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let y=qe(o);y||Me(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=y,s=o,ye.message(`${a}: ${c}/${l}`)}let u=Er(await Tr({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:y=>y.trim()?void 0:"required"})).trim();n.some(y=>y.name===u)&&Me(`a repo named "${u}" is already registered`);let p=Er(await Tr({message:"default branch (optional)",placeholder:"main"})).trim(),d=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let y=iR(r.root,i);d=y===""?".":y}let f=Er(await Tr({message:"mount_as (directory relative to the workspace root)",placeholder:d,initialValue:d})).trim()||d;n.some(y=>(y.mountAs??y.name)===f)&&Me(`mount_as "${f}" is already used by another repo`),await uR(e,a);let m={name:u,host:a,owner:c,repoName:l,mountAs:f,...p?{defaultBranch:p}:{}};if(!i){let y=r?ks(r.root,f):Te(e.projectId,u);if(cl(ks(y,".git")))ye.message(`already cloned at ${y}`);else{ye.info(`cloning ${s} \u2192 ${y} \u2026`);try{await Nk().clone(s,y),ye.success(`cloned into ${y}`)}catch(x){Me(`clone failed: ${x instanceof Error?x.message.trim():String(x)}
891
- check that your ${a} credentials grant read access to ${c}/${l}`)}}}let h;try{h=await cp(e.hubUrl,e.cliToken,e.projectId,m)}catch(y){y instanceof K&&Me(`HUB \u2192 ${y.status} ${y.message}`),Me(y instanceof Error?y.message:String(y))}let{updated:g,errors:w}=eo(e.projectId,h.repos,r?.contextDir);for(let y of g)ye.message(`updated ${y}`);for(let y of w)ye.warn(`could not update ${y.path}: ${y.error}`);ye.success(`added "${u}" \u2014 project now has ${h.repos.length} repo(s)`),jk("done")}async function Lk(t){let e=Ge(t.profile);_k(`codepipe repo remove \u2192 project ${e.projectId}`);let r=Se()??void 0,n;try{let c=(await ne(e.hubUrl,e.cliToken,e.projectId)).repos.find(l=>l.name===t.name);n=c?c.mountAs??c.name:void 0}catch{}let o;try{o=await lp(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof K&&(a.status===404&&Me(`no repo named "${t.name}" in this project`),Me(`HUB \u2192 ${a.status} ${a.message}`)),Me(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=eo(e.projectId,o.repos,r?.contextDir);for(let a of i)ye.message(`updated ${a}`);for(let a of s)ye.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")ye.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?ks(r.root,n):Te(e.projectId,t.name);if(cl(ks(a,".git")))try{nR(a,{recursive:!0,force:!0}),ye.message(`deleted local clone ${a}`)}catch(c){ye.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else ye.message(`no local clone found to purge (${a})`)}ye.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),jk("done")}async function Dk(t){let e=Ge(t.profile),r;try{r=(await ne(e.hubUrl,e.cliToken,e.projectId)).repos}catch(n){console.error(`could not read project from HUB: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(r.length===0){console.log(`project ${e.projectId} has no repos yet \u2014 add one with \`codepipe repo add\``);return}console.log(`project ${e.projectId} \u2014 ${r.length} repo(s):`);for(let n of r){let o=n.mountAs??n.name,i=n.defaultBranch?` @${n.defaultBranch}`:"";console.log(` ${n.name} ${n.host}:${n.owner}/${n.repoName}${i} \u2192 ${o}`)}}fs();zc();tl();kn();G();_e();kn();De();Ie();$o();import{hostname as dR}from"node:os";import{cancel as pR,confirm as Mk,intro as fR,isCancel as Fk,log as Rn,multiselect as mR,outro as Uk,password as gR,select as ll,text as ul}from"@clack/prompts";function Io(t){pR(t),process.exit(1)}function Cn(t){return Fk(t)&&Io("aborted"),t}function ws(t){return Fk(t)&&Io("aborted"),typeof t=="string"?t:""}function bs(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Bk(t,e){try{let{secret:r}=await ii(t,e);return r}catch(r){throw r instanceof K&&r.status===404&&Io("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 hR(t,e){if(Cn(await ll({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 ua(t,e);if(o.length>0)return Cn(await mR({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}));Rn.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Rn.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return ws(await ul({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 dl(t){fR("codepipe worker \u2014 set up this machine as a runner");let e=Ae(t.profile);e&&(Rn.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Cn(await Mk({message:"re-register this worker?",initialValue:!1}))||Io("keeping the existing registration"));let r=Qe(t.profile)??Qe(),n=ws(await ul({message:"HUB URL",placeholder:ct,initialValue:V("HUB_URL")??r?.hubUrl??ct,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=Cn(await ll({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 Bk(n,a),Rn.success("account-issued registration token minted");else if(i==="login"){let d=await Tn();a=(await En(n,d)).cliToken,s=await Bk(n,a),Rn.success("account-issued registration token minted")}else s=ws(await gR({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||Io("a registration token is required");let c=await hR(n,a),l=ws(await ul({message:"worker name",initialValue:dR(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=Cn(await ll({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 vr({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Rn.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Cn(await Mk({message:"start the claim-loop now?",initialValue:!0}))){Uk("registered. start later with `codepipe worker`.");return}Uk("starting the claim-loop\u2026"),await ko(t.profile?{profile:t.profile}:{})}function kR(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return V("PROFILE")}var de=kR();Mu(de);Fu();var Le=new yR;Le.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Ue).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{bs()?await el({profile:de}):await Vc({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Le.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await wk({configPath:t.config,skipVerify:t.skipVerify===!0}):await lk({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Le.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 ed({...t,profile:de})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Le.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 uk({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Le.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await Og({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Le.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 Wy({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Le.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 Sk({profile:de,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Le.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await yy({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Le.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 Vc({profile:de,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Gk=Le.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Gk.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??V("HUB_URL")??Qe(de)?.hubUrl??ct,r=t.token??V("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&bs()){await dl({profile:de});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let n=V("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??V("WORKER_NAME"),i=t.llm??V("WORKER_LLM");await vr({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...de?{profile:de}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Gk.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!Ae(de)&&bs()){await dl({profile:de});return}await ko(de?{profile:de}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Kk=Le.command("project").description("Manage CodePipe projects");Kk.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Rk({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Kk.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 Ak({...t,cliProfile:de})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var pl=Le.command("repo").description("Manage the project's git repositories");pl.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 Ok({profile:de,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});pl.command("remove").description("Remove a repo from this project by its logical name").argument("<name>","Logical name of the repo (as shown by `codepipe repo list`)").option("--purge","Also delete the local clone",!1).action(async(t,e)=>{try{await Lk({profile:de,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});pl.command("list").description("List the project's repos").action(async()=>{try{await Dk({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Hk=Le.command("model").description("Project map (model/ in the Context Repo)");Hk.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 yc({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Hk.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 kc({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Le.parseAsync();
979
+ `+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${i}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let w=await GA({message:"Continue?",initialValue:!0});(WA(w)||!w)&&Rt("aborted")}!c&&a===o&&lr.warn(`source and destination share the same project id, so they share one secrets file (${$t(a)}). Running both profiles at the same time will conflict \u2014 pass --project <newId> for a parallel setup, or keep only one active.`);let{cliToken:d,accountEmail:m}=await Un(s,p),f={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:m,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};lr.step(`registering project on ${s}\u2026`);let g;try{g=await Xt(s,d,f)}catch(w){if(w instanceof H&&w.status===409){lr.warn(`project ${a} already exists on ${s} \u2014 reusing it`);try{g=await oe(s,d,a)}catch(y){throw y instanceof H&&Rt(`target HUB \u2192 ${y.status} ${y.message}`),y}}else if(w instanceof H&&w.status===403)Rt(`project ${a} already exists on ${s} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(w instanceof H)Rt(`target HUB \u2192 ${w.status} ${w.message}`);else throw w}lr.success(`project ${g.projectId} ready on ${s} (${g.provisioningStatus})`),jt({hubUrl:s,cliToken:d,projectId:a,accountEmail:m},i);let h={...u??{},hubUrl:s,cliToken:d,projectId:a};if(delete h.sandboxPins,ie(h),lr.success(`profile '${i}' \u2192 ${$t(a)}`),c){let w=ht(i);FA(w)&&(KA(w),lr.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}qA(`done. next: \`codepipe up --profile ${i}\` \u2014 starts the daemon and a worker on ${s}.`)}He();jc();Ri();Ae();Er();pe();bt();import{existsSync as pu,rmSync as VA,statSync as zA}from"node:fs";import{join as ji,relative as XA,resolve as JA}from"node:path";import{cancel as ZA,intro as Zw,isCancel as QA,log as $e,outro as Qw,text as Lr}from"@clack/prompts";import{simpleGit as eb}from"simple-git";function We(t){ZA(t),process.exit(1)}function Dr(t){return QA(t)&&We("aborted"),typeof t=="string"?t:""}async function Jw(t){try{let e=await eb(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function eP(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function tP(t,e){let r=q(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(eP(r,e)){$e.message(`reusing existing ${e} credentials`);return}if($e.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=Dr(await Lr({message:"Atlassian account email (Bitbucket)",validate:s=>s.trim()?void 0:"required"})).trim(),o=Dr(await Lr({message:"Bitbucket API token (scoped)",validate:s=>s.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=Dr(await Lr({message:`${e} access token (read access to the repo)`,validate:o=>o.trim()?void 0:"required"})).trim();e==="github"?r.github={token:n}:r.gitlab={token:n}}ie(r),$e.success(`saved ${e} credentials`)}async function tb(t){let e=Ze(t.profile);Zw(`codepipe repo add \u2192 project ${e.projectId}`);let r=Te()??void 0,n;try{n=(await oe(e.hubUrl,e.cliToken,e.projectId)).repos}catch(y){We(`could not read project from HUB: ${y instanceof Error?y.message:String(y)}`)}let o=t.target?.trim();if(!o){let y=await Jw(process.cwd());y?(o=process.cwd(),$e.message(`using the current directory (${y})`)):o=Dr(await Lr({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:x=>x.trim()?void 0:"required"})).trim()}let s=null,i,a,c,l;if(pu(o)&&zA(o).isDirectory()){s=JA(o);let y=await Jw(s);y||We(`${s} is not a git repository (no origin remote)`);let x=nt(y);x||We(`origin ${y} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=x,i=y,$e.message(`${a}: ${c}/${l} (already cloned at ${s})`)}else{let y=nt(o);y||We(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=y,i=o,$e.message(`${a}: ${c}/${l}`)}let u=Dr(await Lr({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:y=>y.trim()?void 0:"required"})).trim();n.some(y=>y.name===u)&&We(`a repo named "${u}" is already registered`);let p=Dr(await Lr({message:"default branch (optional)",placeholder:"main"})).trim(),d=u;if(s&&r&&(s===r.root||s.startsWith(r.root+"/"))){let y=XA(r.root,s);d=y===""?".":y}let m=Dr(await Lr({message:"mount_as (directory relative to the workspace root)",placeholder:d,initialValue:d})).trim()||d;n.some(y=>(y.mountAs??y.name)===m)&&We(`mount_as "${m}" is already used by another repo`),await tP(e,a);let f={name:u,host:a,owner:c,repoName:l,mountAs:m,...p?{defaultBranch:p}:{}};if(!s){let y=r?ji(r.root,m):Ie(e.projectId,u);if(pu(ji(y,".git")))$e.message(`already cloned at ${y}`);else{$e.info(`cloning ${i} \u2192 ${y} \u2026`);try{await eb().clone(i,y),$e.success(`cloned into ${y}`)}catch(x){We(`clone failed: ${x instanceof Error?x.message.trim():String(x)}
980
+ check that your ${a} credentials grant read access to ${c}/${l}`)}}}let g;try{g=await pf(e.hubUrl,e.cliToken,e.projectId,f)}catch(y){y instanceof H&&We(`HUB \u2192 ${y.status} ${y.message}`),We(y instanceof Error?y.message:String(y))}let{updated:h,errors:w}=bo(e.projectId,g.repos,r?.contextDir);for(let y of h)$e.message(`updated ${y}`);for(let y of w)$e.warn(`could not update ${y.path}: ${y.error}`);$e.success(`added "${u}" \u2014 project now has ${g.repos.length} repo(s)`),Qw("done")}async function rb(t){let e=Ze(t.profile);Zw(`codepipe repo remove \u2192 project ${e.projectId}`);let r=Te()??void 0,n;try{let c=(await oe(e.hubUrl,e.cliToken,e.projectId)).repos.find(l=>l.name===t.name);n=c?c.mountAs??c.name:void 0}catch{}let o;try{o=await ff(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof H&&(a.status===404&&We(`no repo named "${t.name}" in this project`),We(`HUB \u2192 ${a.status} ${a.message}`)),We(a instanceof Error?a.message:String(a))}let{updated:s,errors:i}=bo(e.projectId,o.repos,r?.contextDir);for(let a of s)$e.message(`updated ${a}`);for(let a of i)$e.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")$e.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?ji(r.root,n):Ie(e.projectId,t.name);if(pu(ji(a,".git")))try{VA(a,{recursive:!0,force:!0}),$e.message(`deleted local clone ${a}`)}catch(c){$e.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else $e.message(`no local clone found to purge (${a})`)}$e.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),Qw("done")}async function nb(t){let e=Ze(t.profile),r;try{r=(await oe(e.hubUrl,e.cliToken,e.projectId)).repos}catch(n){console.error(`could not read project from HUB: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(r.length===0){console.log(`project ${e.projectId} has no repos yet \u2014 add one with \`codepipe repo add\``);return}console.log(`project ${e.projectId} \u2014 ${r.length} repo(s):`);for(let n of r){let o=n.mountAs??n.name,s=n.defaultBranch?` @${n.defaultBranch}`:"";console.log(` ${n.name} ${n.host}:${n.owner}/${n.repoName}${s} \u2192 ${o}`)}}Ii();Ql();su();Pn();F();Le();Pn();He();Ae();Fo();import{hostname as rP}from"node:os";import{cancel as nP,confirm as ob,intro as oP,isCancel as ab,log as Fn,multiselect as sP,outro as sb,password as iP,select as fu,text as mu}from"@clack/prompts";function Yo(t){nP(t),process.exit(1)}function Kn(t){return ab(t)&&Yo("aborted"),t}function Ni(t){return ab(t)&&Yo("aborted"),typeof t=="string"?t:""}function Oi(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function ib(t,e){try{let{secret:r}=await bs(t,e);return r}catch(r){throw r instanceof H&&r.status===404&&Yo("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 aP(t,e){if(Kn(await fu({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 uc(t,e);if(o.length>0)return Kn(await sP({message:"pick the projects (space to toggle, enter to confirm)",options:o.map(s=>({value:s.id,label:`${s.id} \u2014 ${s.name}`})),required:!0}));Fn.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Fn.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return Ni(await mu({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 hu(t){oP("codepipe worker \u2014 set up this machine as a runner");let e=je(t.profile);e&&(Fn.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Kn(await ob({message:"re-register this worker?",initialValue:!1}))||Yo("keeping the existing registration"));let r=ut(t.profile)??ut(),n=Ni(await mu({message:"HUB URL",placeholder:it,initialValue:J("HUB_URL")??r?.hubUrl??it,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,s=Kn(await fu({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"})),i,a=null;if(s==="local")a=r.cliToken,i=await ib(n,a),Fn.success("account-issued registration token minted");else if(s==="login"){let d=await Mn();a=(await Un(n,d)).cliToken,i=await ib(n,a),Fn.success("account-issued registration token minted")}else i=Ni(await iP({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),i||Yo("a registration token is required");let c=await aP(n,a),l=Ni(await mu({message:"worker name",initialValue:rP(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=Kn(await fu({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 jr({hub:n,token:i,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Fn.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Kn(await ob({message:"start the claim-loop now?",initialValue:!0}))){sb("registered. start later with `codepipe worker`.");return}sb("starting the claim-loop\u2026"),await Mo(t.profile?{profile:t.profile}:{})}function lP(){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 J("PROFILE")}var he=lP();Hd(he);var Ue=new cP;Ue.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Fe).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{Oi()?await ou({profile:he}):await Zl({profile:he})}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 Uw({configPath:t.config,skipVerify:t.skipVerify===!0}):await Cw({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 np({...t,profile:he})}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 Aw({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 Mg({profile:he})}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 dw({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 Hw({profile:he,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 Dk({profile:he})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});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 Zl({profile:he,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var cb=Ue.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");cb.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??J("HUB_URL")??ut(he)?.hubUrl??it,r=t.token??J("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Oi()){await hu({profile:he});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=J("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??J("WORKER_NAME"),s=t.llm??J("WORKER_LLM");await jr({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...s?{llm:s}:{},...he?{profile:he}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});cb.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!je(he)&&Oi()){await hu({profile:he});return}await Mo(he?{profile:he}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var lb=Ue.command("project").description("Manage CodePipe projects");lb.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Vw({profile:he})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});lb.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 Xw({...t,cliProfile:he})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var gu=Ue.command("repo").description("Manage the project's git repositories");gu.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 tb({profile:he,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});gu.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 rb({profile:he,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});gu.command("list").description("List the project's repos").action(async()=>{try{await nb({profile:he})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var ub=Ue.command("model").description("Project map (model/ in the Context Repo)");ub.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 yl({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ub.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 kl({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ue.parseAsync();