@code-partner/codepipe 0.13.1-dev.279.g10ce2c9 → 0.13.1-dev.280.g1d860ba

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 +183 -183
  2. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -1,40 +1,40 @@
1
1
  #!/usr/bin/env node
2
- var $b=Object.defineProperty;var x=(t,e)=>()=>(t&&(e=t(t=0)),e);var Fe=(t,e)=>{for(var r in e)$b(t,r,{get:e[r],enumerable:!0})};var Ve,ht,Qs=x(()=>{"use strict";Ve="0.13.1-dev.279.g10ce2c9",ht="https://hub.dev.codepipe.dev"});function Jn(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Iu&&t<=gt}var gt,Iu,Cu=x(()=>{"use strict";Qs();gt=4,Iu=4});var Pu=x(()=>{"use strict";Qs()});function Zn(t=6){return`# CodePipe Context Repo format version.
2
+ var xb=Object.defineProperty;var x=(t,e)=>()=>(t&&(e=t(t=0)),e);var Fe=(t,e)=>{for(var r in e)xb(t,r,{get:e[r],enumerable:!0})};var Ve,ht,ea=x(()=>{"use strict";Ve="0.13.1-dev.280.g1d860ba",ht="https://hub.dev.codepipe.dev"});function Jn(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Cu&&t<=gt}var gt,Cu,Pu=x(()=>{"use strict";ea();gt=4,Cu=4});var Au=x(()=>{"use strict";ea()});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 ta(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 ra(t,e=ea){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 na(t,e=ea){return e.filter(r=>r.version>t)}var Au,yt,qr,ea,_u=x(()=>{"use strict";Au=6,yt=".codepipe-context.yaml",qr=".devpipe-context.yaml",ea=[{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",yt]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[yt]},{version:3,summary:"Custom project actions (the RUN tab): actions/ scaffold with the format README",addedPaths:["actions/README.md"]},{version:4,summary:"Project map: model/ scaffold with the format README (facts/ vs derived/ layout)",addedPaths:["model/README.md"]},{version:5,summary:"Roles: roles/ scaffold with the format README (override a bundled critic by name, or add your own)",addedPaths:["roles/README.md"]},{version:6,summary:"Skills: skills/ scaffold with the format README (procedures the agent invokes instead of improvising)",addedPaths:["skills/README.md"]}]});function eo(t){return`model/facts/identity/${t}.yaml`}function kr(t){return`model/facts/events/${t}.yaml`}function sa(t){return`model/facts/annotations/${t}.md`}function aa(t){return`model/derived/correlates/${t}.yaml`}function ca(t){return`model/derived/touched/${t}.yaml`}function ju(t){return t===""?"root":t.replace(/\//g,"-")}function la(t,e){return`model/derived/structure/${t}/${ju(e)}.yaml`}function ti(t){return typeof t=="string"&&Ou.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(!Nu.includes(n))return null;let o=t.slice(e+1,r),i=t.slice(r+1);return o===""&&!Tb.includes(n)||i===""?null:{level:n,repo:o,path:i}}function Ee(t){return`task::${t}`}function we(t,e,r){return`${t}:${e}:${r}`}function to(t){let e=[];return xt(t)?(ni(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),typeof t.repo!="string"&&e.push("repo: missing (empty string = cross-repo)"),typeof t.builtFromCommit!="string"&&e.push("builtFromCommit: missing"),Array.isArray(t.edges)?t.edges.forEach((r,n)=>{if(!xt(r)){e.push(`edges[${n}]: not an object`);return}ua.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 Lu(t){return{...t,edges:Yr(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function br(t){return vr(Lu(t))}function xt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ni(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function wt(t){return typeof t=="string"&&t.length>0}function Ib(t){return t.modelFormatVersion!==2}function Ot(t){let e=[];if(!xt(t))return{ok:!1,errors:["shard: not an object"]};ni(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),wt(t.repo)||e.push("repo: missing or empty"),wt(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(!xt(o)){e.push(`nodes[${i}]: not an object`);return}let s=re(o.key);if(!s){e.push(`nodes[${i}].key: malformed nodeKey (${JSON.stringify(o.key??null)})`);return}o.level!==s.level&&e.push(`nodes[${i}]: level "${String(o.level)}" does not match key prefix "${s.level}"`),r&&s.repo!==r&&e.push(`nodes[${i}].key: repo "${s.repo}" mixed into shard of repo "${r}"`);let a=o.key;n.has(a)&&e.push(`nodes[${i}].key: duplicate "${a}"`),n.add(a),o.entityId!==void 0&&!ti(o.entityId)&&e.push(`nodes[${i}].entityId: malformed (${JSON.stringify(o.entityId)})`)}):e.push("nodes: not an array"),Array.isArray(t.edges)?t.edges.forEach((o,i)=>{if(!xt(o)){e.push(`edges[${i}]: not an object`);return}ua.includes(o.kind)||e.push(`edges[${i}].kind: unknown "${String(o.kind)}"`),(!wt(o.to)||!re(o.to))&&e.push(`edges[${i}].to: malformed nodeKey`),(!wt(o.from)||!n.has(o.from))&&e.push(`edges[${i}].from: "${String(o.from)}" is not a node of this shard`),o.weight!==void 0&&!(typeof o.weight=="number"&&Number.isFinite(o.weight))&&e.push(`edges[${i}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}}function ro(t){let e=[];if(!xt(t))return{ok:!1,errors:["identity: not an object"]};if(ni(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),wt(t.repo)||e.push("repo: missing or empty"),t.builtFromCommit!==void 0&&!wt(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(!xt(n)){e.push(`entities[${o}]: not an object`);return}ti(n.entityId)?r.has(n.entityId)?e.push(`entities[${o}].entityId: duplicate "${n.entityId}"`):r.add(n.entityId):e.push(`entities[${o}].entityId: malformed (${JSON.stringify(n.entityId??null)})`),re(n.currentKey)||e.push(`entities[${o}].currentKey: malformed nodeKey`),n.status!=="active"&&n.status!=="orphaned"&&e.push(`entities[${o}].status: expected active|orphaned`),wt(n.firstSeen)||e.push(`entities[${o}].firstSeen: missing`),wt(n.lastSeen)||e.push(`entities[${o}].lastSeen: missing`),n.aliases!==void 0&&(Array.isArray(n.aliases)?n.aliases.forEach((i,s)=>{(!xt(i)||!re(i.key)||!wt(i.until))&&e.push(`entities[${o}].aliases[${s}]: malformed`)}):e.push(`entities[${o}].aliases: not an array`))})}return e.length?{ok:!1,errors:e}:{ok:!0,value:t}}function Lt(t){let e=[];return xt(t)?(ni(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),wt(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=>!wt(r)))&&e.push("commits: not an array of non-empty strings"),Array.isArray(t.files)?t.files.forEach((r,n)=>{if(!xt(r)||!re(r.key)){e.push(`files[${n}].key: malformed nodeKey`);return}r.entityId!==void 0&&!ti(r.entityId)&&e.push(`files[${n}].entityId: malformed`),r.churn!==void 0&&!(typeof r.churn=="number"&&r.churn>=0)&&e.push(`files[${n}].churn: not a non-negative number`)}):e.push("files: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}):{ok:!1,errors:["event: not an object"]}}function Yr(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function Mu(t){return{...t,nodes:Yr(t.nodes,e=>e.key),edges:Yr(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function Du(t){return{...t,entities:Yr(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:Yr(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function Uu(t){let e=t.links?{...t.links,...t.links.adr?{adr:[...t.links.adr].sort()}:{},...t.links.tasks?{tasks:[...t.links.tasks].sort()}:{}}:void 0;return{...t,commits:[...t.commits].sort(),files:Yr(t.files,r=>r.key),...e?{links:e}:{}}}function Qn(t){return Cb.test(t)?t:JSON.stringify(t)}function Bu(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 Fu(t){return t===null||["boolean","number","string"].includes(typeof t)}function oa(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function Gu(t,e,r){if(Array.isArray(t)){for(let n of t)if(Fu(n))r.push(`${e}- ${Bu(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=oa(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([i,s],a)=>{let c=a===0?`${e}- `:`${e} `;ia(i,s,c,`${e} `,r)})}}return}for(let[n,o]of oa(t))ia(n,o,e,e,r)}function ia(t,e,r,n,o){if(Fu(e))o.push(`${r}${Qn(t)}: ${Bu(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${Qn(t)}: []`):(o.push(`${r}${Qn(t)}:`),Gu(e,`${n} `,o));else{let i=oa(e);if(i.length===0)o.push(`${r}${Qn(t)}: {}`);else{o.push(`${r}${Qn(t)}:`);for(let[s,a]of i)ia(s,a,`${n} `,`${n} `,o)}}}function vr(t){let e=[];return Gu(t,"",e),e.join(`
5
+ `}function ra(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 na(t,e=ta){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 oa(t,e=ta){return e.filter(r=>r.version>t)}var _u,yt,qr,ta,ju=x(()=>{"use strict";_u=6,yt=".codepipe-context.yaml",qr=".devpipe-context.yaml",ta=[{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",yt]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[yt]},{version:3,summary:"Custom project actions (the RUN tab): actions/ scaffold with the format README",addedPaths:["actions/README.md"]},{version:4,summary:"Project map: model/ scaffold with the format README (facts/ vs derived/ layout)",addedPaths:["model/README.md"]},{version:5,summary:"Roles: roles/ scaffold with the format README (override a bundled critic by name, or add your own)",addedPaths:["roles/README.md"]},{version:6,summary:"Skills: skills/ scaffold with the format README (procedures the agent invokes instead of improvising)",addedPaths:["skills/README.md"]}]});function eo(t){return`model/facts/identity/${t}.yaml`}function kr(t){return`model/facts/events/${t}.yaml`}function aa(t){return`model/facts/annotations/${t}.md`}function ca(t){return`model/derived/correlates/${t}.yaml`}function la(t){return`model/derived/touched/${t}.yaml`}function Nu(t){return t===""?"root":t.replace(/\//g,"-")}function ua(t,e){return`model/derived/structure/${t}/${Nu(e)}.yaml`}function ti(t){return typeof t=="string"&&Lu.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(!Ou.includes(n))return null;let o=t.slice(e+1,r),i=t.slice(r+1);return o===""&&!Ib.includes(n)||i===""?null:{level:n,repo:o,path:i}}function Se(t){return`task::${t}`}function ye(t,e,r){return`${t}:${e}:${r}`}function to(t){let e=[];return St(t)?(ni(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),typeof t.repo!="string"&&e.push("repo: missing (empty string = cross-repo)"),typeof t.builtFromCommit!="string"&&e.push("builtFromCommit: missing"),Array.isArray(t.edges)?t.edges.forEach((r,n)=>{if(!St(r)){e.push(`edges[${n}]: not an object`);return}da.includes(r.kind)||e.push(`edges[${n}].kind: unknown "${String(r.kind)}"`),re(r.from)||e.push(`edges[${n}].from: malformed nodeKey`),re(r.to)||e.push(`edges[${n}].to: malformed nodeKey`),r.weight!==void 0&&!(typeof r.weight=="number"&&Number.isFinite(r.weight))&&e.push(`edges[${n}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}):{ok:!1,errors:["edge sheet: not an object"]}}function Mu(t){return{...t,edges:Yr(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function br(t){return vr(Mu(t))}function St(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ni(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function wt(t){return typeof t=="string"&&t.length>0}function Pb(t){return t.modelFormatVersion!==2}function Ot(t){let e=[];if(!St(t))return{ok:!1,errors:["shard: not an object"]};ni(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),wt(t.repo)||e.push("repo: missing or empty"),wt(t.builtFromCommit)||e.push("builtFromCommit: missing or empty");let r=typeof t.repo=="string"?t.repo:"",n=new Set;return Array.isArray(t.nodes)?t.nodes.forEach((o,i)=>{if(!St(o)){e.push(`nodes[${i}]: not an object`);return}let s=re(o.key);if(!s){e.push(`nodes[${i}].key: malformed nodeKey (${JSON.stringify(o.key??null)})`);return}o.level!==s.level&&e.push(`nodes[${i}]: level "${String(o.level)}" does not match key prefix "${s.level}"`),r&&s.repo!==r&&e.push(`nodes[${i}].key: repo "${s.repo}" mixed into shard of repo "${r}"`);let a=o.key;n.has(a)&&e.push(`nodes[${i}].key: duplicate "${a}"`),n.add(a),o.entityId!==void 0&&!ti(o.entityId)&&e.push(`nodes[${i}].entityId: malformed (${JSON.stringify(o.entityId)})`)}):e.push("nodes: not an array"),Array.isArray(t.edges)?t.edges.forEach((o,i)=>{if(!St(o)){e.push(`edges[${i}]: not an object`);return}da.includes(o.kind)||e.push(`edges[${i}].kind: unknown "${String(o.kind)}"`),(!wt(o.to)||!re(o.to))&&e.push(`edges[${i}].to: malformed nodeKey`),(!wt(o.from)||!n.has(o.from))&&e.push(`edges[${i}].from: "${String(o.from)}" is not a node of this shard`),o.weight!==void 0&&!(typeof o.weight=="number"&&Number.isFinite(o.weight))&&e.push(`edges[${i}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}}function ro(t){let e=[];if(!St(t))return{ok:!1,errors:["identity: not an object"]};if(ni(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),wt(t.repo)||e.push("repo: missing or empty"),t.builtFromCommit!==void 0&&!wt(t.builtFromCommit)&&e.push("builtFromCommit: not a non-empty string"),!Array.isArray(t.entities))e.push("entities: not an array");else{let r=new Set;t.entities.forEach((n,o)=>{if(!St(n)){e.push(`entities[${o}]: not an object`);return}ti(n.entityId)?r.has(n.entityId)?e.push(`entities[${o}].entityId: duplicate "${n.entityId}"`):r.add(n.entityId):e.push(`entities[${o}].entityId: malformed (${JSON.stringify(n.entityId??null)})`),re(n.currentKey)||e.push(`entities[${o}].currentKey: malformed nodeKey`),n.status!=="active"&&n.status!=="orphaned"&&e.push(`entities[${o}].status: expected active|orphaned`),wt(n.firstSeen)||e.push(`entities[${o}].firstSeen: missing`),wt(n.lastSeen)||e.push(`entities[${o}].lastSeen: missing`),n.aliases!==void 0&&(Array.isArray(n.aliases)?n.aliases.forEach((i,s)=>{(!St(i)||!re(i.key)||!wt(i.until))&&e.push(`entities[${o}].aliases[${s}]: malformed`)}):e.push(`entities[${o}].aliases: not an array`))})}return e.length?{ok:!1,errors:e}:{ok:!0,value:t}}function Lt(t){let e=[];return St(t)?(ni(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),wt(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=>!wt(r)))&&e.push("commits: not an array of non-empty strings"),Array.isArray(t.files)?t.files.forEach((r,n)=>{if(!St(r)||!re(r.key)){e.push(`files[${n}].key: malformed nodeKey`);return}r.entityId!==void 0&&!ti(r.entityId)&&e.push(`files[${n}].entityId: malformed`),r.churn!==void 0&&!(typeof r.churn=="number"&&r.churn>=0)&&e.push(`files[${n}].churn: not a non-negative number`)}):e.push("files: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}):{ok:!1,errors:["event: not an object"]}}function Yr(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function Du(t){return{...t,nodes:Yr(t.nodes,e=>e.key),edges:Yr(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function Uu(t){return{...t,entities:Yr(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:Yr(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function Bu(t){let e=t.links?{...t.links,...t.links.adr?{adr:[...t.links.adr].sort()}:{},...t.links.tasks?{tasks:[...t.links.tasks].sort()}:{}}:void 0;return{...t,commits:[...t.commits].sort(),files:Yr(t.files,r=>r.key),...e?{links:e}:{}}}function Qn(t){return Ab.test(t)?t:JSON.stringify(t)}function Fu(t){if(t===null)return"null";if(typeof t=="boolean")return t?"true":"false";if(typeof t=="number"){if(!Number.isFinite(t))throw new Error(`model yaml: non-finite number ${t}`);return JSON.stringify(t)}if(typeof t=="string")return JSON.stringify(t);throw new Error(`model yaml: unsupported scalar ${typeof t}`)}function Gu(t){return t===null||["boolean","number","string"].includes(typeof t)}function ia(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function Ku(t,e,r){if(Array.isArray(t)){for(let n of t)if(Gu(n))r.push(`${e}- ${Fu(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=ia(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([i,s],a)=>{let c=a===0?`${e}- `:`${e} `;sa(i,s,c,`${e} `,r)})}}return}for(let[n,o]of ia(t))sa(n,o,e,e,r)}function sa(t,e,r,n,o){if(Gu(e))o.push(`${r}${Qn(t)}: ${Fu(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${Qn(t)}: []`):(o.push(`${r}${Qn(t)}:`),Ku(e,`${n} `,o));else{let i=ia(e);if(i.length===0)o.push(`${r}${Qn(t)}: {}`);else{o.push(`${r}${Qn(t)}:`);for(let[s,a]of i)sa(s,a,`${n} `,`${n} `,o)}}}function vr(t){let e=[];return Ku(t,"",e),e.join(`
6
6
  `)+`
7
- `}function ha(t){return vr(Mu(t))}function ga(t){return vr(Du(t))}function zr(t){return vr(Uu(t))}var Oe,vb,xb,Sb,Eb,ei,wr,Nu,ua,Ou,Tb,nt,da,pa,fa,ri,Rb,ma,$r,Cb,ya=x(()=>{"use strict";Oe=2,vb="model",xb="model/README.md",Sb="model/facts",Eb="model/derived",ei="model/derived/INDEX.yaml",wr="model/derived/relates.yaml";Nu=["system","container","component","code","task","adr"],ua=["contains","touched_by","correlates","relates","references","depends_on"],Ou=/^e_[0-9a-f]{8}$/;Tb=["system","task","adr"];nt={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};da=2,pa=5,fa=50,ri=2e3,Rb=5e4,ma={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},$r={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};Cb=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});function Pb(t){return t==="DONE"}function Ab(t){return t==="AWAITING_EXTERNAL_FIX"?!1:wa.indexOf(t)>=wa.indexOf("IMPLEMENTING")}var wa,Ku=x(()=>{"use strict";wa=["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 jb(t){for(let e of ka)if(e.phases.includes(t))return e.id;return null}function Nb(t){for(let e of Hu)if(e.phases.includes(t))return e.id;return null}var ka,_b,Hu,Wu=x(()=>{"use strict";ka=[{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"]}],_b=ka.flatMap(t=>t.phases),Hu=[{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 Ob(t){return qu.includes(t)?"planning":"implementation"}function qt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var ba,qu,Lb,$a=x(()=>{"use strict";ba=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat","observer","council","testing"],qu=["draft","analysis","chat","observer","council"];Lb=1});function Yu(t,e){return e.toLowerCase().includes(t.toLowerCase())}function Sa(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||Qu.every(o=>e.some(i=>Yu(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 Zu){let i=n.find(s=>Yu(o,s.id));if(i)return i.id}return n[0].id}function Vr(){return{default:null,roles:{}}}function Mb(t,e){let r=t?.roles?.[e];return typeof r=="string"&&r.trim().length>0?r.trim():t?.default&&t.default.trim().length>0?t.default.trim():no[e]??Ju}function Db(t){let e=t?.provider;return typeof e=="string"&&e.trim().length>0?e.trim():Xe}function Ub(t){let e=Vr();if(!t||typeof t!="object")return e;let r=t.llm;if(!r||typeof r!="object")return e;let n=r.provider;typeof n=="string"&&n.trim().length>0&&(e.provider=n.trim());let o=r.models;if(!o||typeof o!="object")return e;for(let[i,s]of Object.entries(o))typeof s!="string"||s.trim().length===0||(i==="default"?e.default=s.trim():e.roles[i]=s.trim());return e}function Bb(t){let e=typeof t.provider=="string"&&t.provider.trim().length>0&&t.provider.trim()!==Xe;if(t.default===null&&Object.keys(t.roles).length===0&&!e)return null;let{provider:r,...n}=t;return JSON.stringify(e?{provider:r.trim(),...n}:n)}function Fb(t){if(!t)return Vr();try{let e=JSON.parse(t);if(!e||typeof e!="object")return Vr();let r=e,n=Vr();typeof r.provider=="string"&&r.provider.trim().length>0&&(n.provider=r.provider.trim()),typeof r.default=="string"&&(n.default=r.default);let o=r.roles;if(o&&typeof o=="object")for(let[i,s]of Object.entries(o))typeof s=="string"&&(n.roles[i]=s);return n}catch{return Vr()}}var Xe,va,Ae,Xr,oi,ii,zu,Vu,Xu,xa,no,Ju,Zu,Qu,Ea=x(()=>{"use strict";$a();Xe="claude",va=[Xe],Ae="opus",Xr="sonnet",oi="haiku",ii=[Ae,Xr,oi],zu="build-discovery",Vu="code-review-verify",Xu=[zu,Vu],xa=[...ba,...Xu],no={analyze:Ae,implement:Ae,"resolve-conflict":Ae,rework:Ae,estimate:Xr,build:oi,"build-discovery":Ae,"code-review":Ae,"code-review-verify":Xr,draft:Xr,index:Ae,backfill:Ae,analysis:Ae,chat:Ae,observer:Ae,council:Ae,testing:Ae},Ju=Ae,Zu=[Ae,Xr,oi],Qu=Array.from(new Set(Object.values(no)))});function Mt(t){return Gb.has(t)?!0:Kb.some(e=>t.startsWith(e))}function si(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function xr(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function Ra(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function Ca(t,e){let r=si(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=xr(r.id,"id")??n;if(!Ta.test(o))throw new Error(`id must match ${Ta} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=xr(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=si(r.env,"env");s={};for(let[d,m]of Object.entries(p)){if(!Je.test(d))throw new Error(`env name "${d}" must match ${Je}`);if(typeof m!="string"&&typeof m!="number"&&typeof m!="boolean")throw new Error(`env.${d} must be a scalar`);s[d]=String(m)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>ed)throw new Error(`too many params (max ${ed})`);let p=new Set;a=c.map((d,m)=>Hb(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>td)throw new Error(`too many steps (max ${td})`);let u=l.map((p,d)=>{let m=si(p,`steps[${d}]`),f=xr(m.run,`steps[${d}].run`);if(!f||f.trim().length===0)throw new Error(`steps[${d}].run is required`);let y=xr(m.name,`steps[${d}].name`),k=Ra(m.timeout_sec,`steps[${d}].timeout_sec`);if(k!==void 0&&(!Number.isInteger(k)||k<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:f,...y?{name:y}:{},...k!==void 0?{timeout_sec:k}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function Hb(t,e,r){let n=si(t,`params[${e}]`),o=xr(n.name,`params[${e}].name`);if(!o||!Je.test(o))throw new Error(`params[${e}].name must match ${Je}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let m=n.enum;if(!Array.isArray(m)||m.length===0||!m.every(f=>typeof f=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=m}let a=xr(n.label,`params[${e}].label`),c=xr(n.help,`params[${e}].help`),l=n.required===!0,u=Ra(n.min,`params[${e}].min`),p=Ra(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 Pa(t,e){let r=t.params??[],n=new Map(r.map(i=>[i.name,i]));for(let i of Object.keys(e))if(!n.has(i))return{ok:!1,error:`unknown param: ${i}`};let o={};for(let i of r){let s=e[i.name];if(s==null||typeof s=="string"&&s.trim()==="")if(i.default!==void 0)s=i.default;else{if(i.required)return{ok:!1,error:`${i.name} is required`};continue}switch(i.type){case"string":{if(typeof s!="string")return{ok:!1,error:`${i.name} must be a string`};o[i.name]=s;break}case"enum":{if(typeof s!="string"||!(i.enum??[]).includes(s))return{ok:!1,error:`${i.name} must be one of: ${(i.enum??[]).join(", ")}`};o[i.name]=s;break}case"number":{let a=typeof s=="number"?s:typeof s=="string"?Number(s):NaN;if(!Number.isFinite(a))return{ok:!1,error:`${i.name} must be a number`};if(i.min!==void 0&&a<i.min)return{ok:!1,error:`${i.name} must be \u2265 ${i.min}`};if(i.max!==void 0&&a>i.max)return{ok:!1,error:`${i.name} must be \u2264 ${i.max}`};o[i.name]=a;break}case"boolean":{let a=typeof s=="boolean"?s:s==="true"?!0:s==="false"?!1:null;if(a===null)return{ok:!1,error:`${i.name} must be a boolean`};o[i.name]=a;break}}}return{ok:!0,values:o}}var Je,Gb,Kb,Ia,Ta,ed,td,Aa=x(()=>{"use strict";Je=/^[A-Z][A-Z0-9_]*$/,Gb=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),Kb=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];Ia=600,Ta=/^[a-z0-9-]+$/,ed=32,td=64});function rd(){return{primary:xe,context:xe,tasks:xe,docs:xe,code_comments:xe,chat:xe,code_review:xe}}function nd(t){return!t||t.trim().length===0||t.trim().toLowerCase()===xe}function Wb(t){if(typeof t!="string")return xe;let e=t.trim().replace(/\s+/g," ");return e.length===0||e.length>40||e.toLowerCase()===xe?xe:e}function qb(t){let e=rd();if(!t||typeof t!="object")return e;let r=t.language;if(!r||typeof r!="object"||Array.isArray(r))return e;let n=r;for(let o of oo)e[o]=Wb(n[o]);return e}function Yb(t){return oo.every(e=>nd(t[e]))}var xe,oo,Jr,io,_a=x(()=>{"use strict";xe="auto",oo=["primary","context","tasks","docs","code_comments","chat","code_review"],Jr=["English","Russian","German","Spanish","French","Portuguese","Italian","Chinese","Japanese","Korean"],io=40});function La(t=od){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...La(r.groups));return e}function id(t,e){let r=JSON.stringify(e);return La().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function Ma(t){let e=id(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.type==="string"&&e.mustContain&&!i.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:e.maxLength!==void 0&&i.length>e.maxLength?{ok:!1,error:`${e.id} must be \u2264 ${e.maxLength} chars`}:{ok:!0,field:e,value:i}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)?{ok:!1,error:`${e.id} must be a number`}:!e.float&&!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}case"string_map":{if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,error:`${e.id} must be a name\u2192value map`};let i=Object.entries(r);if(i.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(i.length>ja)return{ok:!1,error:`${e.id} must have \u2264 ${ja} entries`};let s={};for(let[a,c]of i){if(!Je.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Je}`};if(Mt(a))return{ok:!1,error:`${e.id}: name "${a}" is reserved`};if(typeof c!="string")return{ok:!1,error:`${e.id}: value of "${a}" must be a string`};if(c.length>Na)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${Na} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var zb,Vb,ja,Na,Oa,od,sd=x(()=>{"use strict";Aa();Ea();ya();_a();zb={primary:"Primary language",context:"Context documents",tasks:"Tracker issues",docs:"Repo documentation",code_comments:"Code comments",chat:"Agent chat",code_review:"Code review comments"},Vb={primary:"The project's main language (agent status notes ride it). Empty \u21D2 auto.",context:"Knowledge, ADRs and task artifacts in the Context Repo. Empty \u21D2 auto.",tasks:"Issue titles/bodies the agent drafts. Empty \u21D2 auto.",docs:"Documentation changes in the project repos. Empty \u21D2 auto.",code_comments:"New code comments the agent writes. Empty \u21D2 auto.",chat:"The interactive task-drafting chat. Empty/auto \u21D2 mirror the user's messages.",code_review:"Review findings and PR comments. Empty \u21D2 follows the tracker-issues language."},ja=64,Na=2e3,Oa=2e3,od=[{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:[...va],help:"LLM backend for this project. Currently only claude is available."}],groups:[{id:"llm.models",label:"Models by role",help:"Model per pipeline stage. Empty \u21D2 the role's recommended default applies.",fields:[{id:"llm.models.default",file:"regimen.yaml",path:["llm","models","default"],type:"model",label:"default (catch-all)",nullable:!0,suggestions:[...ii],help:"Overrides the recommended defaults for every role not listed below."},...xa.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...ii],help:`recommended: ${no[t]}`}))]}]},{id:"apply.style",label:"Commits & PRs",help:"Instructions for the AI agent on how to write commit messages and PR descriptions. Empty \u21D2 built-in templates.",fields:[{id:"apply.commit_style",file:"project.yaml",path:["apply","commit_style"],type:"string",label:"Commit message style",nullable:!0,multiline:!0,maxLength:Oa,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:Oa,help:`e.g. "implementation details, bullet list of what was done, in the tracker's language". Empty \u21D2 the default PR body.`}]},{id:"apply.delivery",label:"Delivery & merge",help:"How a finished change reaches the repository: with or without a pull request, and who merges it.",fields:[{id:"apply.pull_request",file:"project.yaml",path:["apply","pull_request"],type:"boolean",label:"Open a pull request",nullable:!1,help:"On (default): the task branch is pushed and a pull request is opened \u2014 the change is reviewable in the git host and keeps a history of review comments. Off: no PR at all; the branch is merged into the default branch directly, and the agent's review remarks live only in the dashboard and the Context Repo."},{id:"apply.done",file:"project.yaml",path:["apply","done"],type:"enum",label:"Task is done when",nullable:!1,suggestions:["merge","branch"],help:"merge (default): the task is finished only once its change lands in the default branch. branch: the task ends at the pushed branch (plus the PR, if enabled) and nothing is merged for you."},{id:"apply.auto_merge",file:"project.yaml",path:["apply","auto_merge"],type:"enum",label:"Auto-merge pull requests",nullable:!1,suggestions:["off","on_ci_green"],help:"Applies to the pull-request path only. off (default): the merge waits for you (Approve on the task card). on_ci_green: as soon as the PR is open, conflict-free and its CI is green, CodePipe merges it \u2014 changes reach the default branch with no further review from you. Requires full automation; branch protection on the host still applies (a refused merge parks the task). Without pull requests, full automation merges the branch itself and this switch does not apply."}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{id:"testing",label:"Testing",help:"An optional phase after code review: writes the test plan you run in the morning and reports what it could verify.",fields:[{id:"testing.enabled",file:"regimen.yaml",path:["testing","enabled"],type:"boolean",nullable:!1,label:"Run the testing phase",help:"Off by default. When on, a task passing code review goes through a test pass before the PR: it derives TESTPLAN.md from the plan's requirements and reports per requirement what it could verify. A requirement it finds broken sends the change back for a fix (bounded below)."},{id:"testing.max_iterations",file:"regimen.yaml",path:["testing","max_iterations"],type:"number",nullable:!0,min:1,max:10,label:"Fix rounds before stopping",help:"How many times a failed test pass may send the change back before the task waits for you. Empty \u21D2 2."}]},{id:"code_review",label:"Code review",help:"One review mechanism for the pipeline's own changes and for developers' branches (the review column); they differ only in where the findings go.",fields:[{id:"code_review.verify_pass",file:"regimen.yaml",path:["code_review","verify_pass"],type:"boolean",nullable:!1,label:"Verifier pass (precision)",help:"On by default, paired with the critics panel. A second, narrow agent checks every finding against the code (real? re-grade) before it costs a rework round or reaches a developer; the findings threshold below keeps small rounds cheap."},{id:"code_review.panel",file:"regimen.yaml",path:["code_review","panel"],type:"boolean",nullable:!1,label:"Critics panel",help:"On by default. The reviewer delegates to the project's critic roles (roles/ in the Context Repo, or the bundled set) as parallel subagents before its own pass. Cost grows with the number of roles."},{id:"code_review.verify_min_findings",file:"regimen.yaml",path:["code_review","verify_min_findings"],type:"number",nullable:!0,min:1,label:"Verifier threshold (findings)",help:"The verifier runs only when a round carries at least this many actionable findings \u2014 1-2 are cheap to absorb, noise scales with volume. Empty = 3; 1 = verify every round."},{id:"code_review.max_blocking",file:"regimen.yaml",path:["code_review","max_blocking"],type:"number",nullable:!0,label:"Blocking budget (internal)",help:"Max blocker findings that keep their power in the pipeline's own review; the rest are demoted to major, weakest confidence first. Empty = 5."},{id:"code_review.external.max_blocking",file:"regimen.yaml",path:["code_review","external","max_blocking"],type:"number",nullable:!0,label:"Blocking budget (external)",help:"The same budget for a developer's branch review \u2014 tighter by default because a human reads these. Empty = 3."}]},{id:"skills",label:"Skills",help:"Reusable procedures the agent can invoke instead of improvising. Only their names and one-line descriptions sit in the prompt; the steps load when a skill is used.",fields:[{id:"skills.from_bundled",file:"regimen.yaml",path:["skills","from_bundled"],type:"boolean",nullable:!1,label:"Use the skills shipped with CodePipe",help:"On by default. General procedures maintained with the product."},{id:"skills.from_context_repo",file:"regimen.yaml",path:["skills","from_context_repo"],type:"boolean",nullable:!1,label:"Use this project's skills",help:"On by default. Skills the team writes in the context repository under `skills/<name>/SKILL.md`. These override a bundled skill of the same name."},{id:"skills.from_project_repo",file:"regimen.yaml",path:["skills","from_project_repo"],type:"boolean",nullable:!1,label:"Use the code repository's skills",help:"On by default. `.claude/skills/` inside the project repositories \u2014 the skills your developers already use locally. These win over both other sources."}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (on by default; orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on (default), a task taken from Develop waits in the QUEUE for a single Confirm before the pipeline starts \u2014 the Confirm pulls in dependency closure and topologically orders the queue. Off \u21D2 conveyor: the task starts the pipeline immediately."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]},{id:"language",label:"Language",help:"Languages the agent writes in, per area. Empty \u21D2 auto: mirror the language of the user's material.",fields:oo.map(t=>({id:`language.${t}`,file:"project.yaml",path:["language",t],type:"string",label:zb[t],nullable:!0,maxLength:40,suggestions:t==="chat"?[xe,...Jr]:[...Jr],help:Vb[t]}))},{id:"context.model",label:"Project map",help:"Parameters of the project map (built from git history by the CLI). Empty fields keep the defaults.",fields:[{id:"context.model.enabled",file:"regimen.yaml",path:["context","model","enabled"],type:"boolean",label:"Enable in the pipeline",nullable:!1,help:"When on, agents are asked to record intent annotations and (once available) receive an assembled context pack. Off \u21D2 the pipeline ignores the map entirely."},{id:"context.model.prompt.pack",file:"regimen.yaml",path:["context","model","prompt","pack"],type:"boolean",nullable:!1,label:"Give agents the context pack",help:"On by default. The assembled pack costs up to ~4000 tokens on every task of the analyze / estimate / implement / rework roles. Turning it off keeps the map building and stops the spend \u2014 the way to see what the pack is actually worth on this project."},{id:"context.model.prompt.annotations",file:"regimen.yaml",path:["context","model","prompt","annotations"],type:"boolean",nullable:!1,label:"Ask agents for intent annotations",help:"On by default. Adds the annotations block to the implement and rework prompts \u2014 the layer that records WHY the code is shaped this way. Cheap, and worth accumulating even while the pack is off."},{id:"context.index.hub",file:"regimen.yaml",path:["context","index","hub"],type:"enum",label:"Search index on the server",nullable:!0,suggestions:["off","metadata"],help:"off (default): search runs on your machine, nothing is uploaded. metadata: paths, labels and task texts (never code) are mirrored to the server so search and structure stay available while your machine is offline. Switching back to off deletes the mirrored rows."},{id:"context.model.issue_key_pattern",file:"regimen.yaml",path:["context","model","issue_key_pattern"],type:"string",label:"Issue-key pattern (regex)",nullable:!0,maxLength:200,help:"Regex that finds tracker issue keys in commit subjects when mining task events from history. Empty \u21D2 derived from the tracker project key (e.g. DEV-\\d+)."},{id:"context.model.cochange.window_commits",file:"regimen.yaml",path:["context","model","cochange","window_commits"],type:"number",label:"History window (commits)",nullable:!0,min:50,max:5e4,help:`How many commits back from the build commit are mined. Default ${nt.windowCommits}.`},{id:"context.model.cochange.commit_file_cap",file:"regimen.yaml",path:["context","model","cochange","commit_file_cap"],type:"number",label:"Commit size cap (files)",nullable:!0,min:2,max:500,help:`Commits touching more files are ignored as noise. Default ${nt.commitFileCap}.`},{id:"context.model.cochange.support_min",file:"regimen.yaml",path:["context","model","cochange","support_min"],type:"number",label:"Minimum co-occurrences",nullable:!0,min:1,max:100,help:`A pair of files must change together at least this many times. Default ${nt.supportMin}.`},{id:"context.model.cochange.jaccard_min_pct",file:"regimen.yaml",path:["context","model","cochange","jaccard_min_pct"],type:"number",label:"Minimum Jaccard (%)",nullable:!0,min:0,max:100,help:`Overlap threshold: |A\u2229B| / |A\u222AB| of the files' commit sets, in percent. Default ${nt.jaccardMinPct}.`},{id:"context.model.cochange.half_life_days",file:"regimen.yaml",path:["context","model","cochange","half_life_days"],type:"number",label:"Time-decay half-life (days)",nullable:!0,min:1,max:3650,help:`A commit this old counts half as much. Default ${nt.halfLifeDays} (~9 months).`},{id:"context.model.cochange.top_k",file:"regimen.yaml",path:["context","model","cochange","top_k"],type:"number",label:"Edges per file (top-k)",nullable:!0,min:1,max:64,help:`Only the k strongest co-change edges of a file survive \u2014 bounds graph density whatever the thresholds. Default ${nt.topK}.`}]},{id:"rate_limit",label:"Rate limit",help:"Automatic project pause as the LLM usage window fills up.",fields:[{id:"rate_limit.auto_pause.enabled",file:"project.yaml",path:["rate_limit","auto_pause","enabled"],type:"boolean",nullable:!1,label:"Pause the project near the limit",help:"On (default): when window utilization reaches the threshold, the project is paused (same pause as the manual one) and you get an email \u2014 the remaining window stays available for your own work. Off: agents keep working until the provider actually runs out."},{id:"rate_limit.auto_pause.threshold",file:"project.yaml",path:["rate_limit","auto_pause","threshold"],type:"number",float:!0,nullable:!0,min:.05,max:1,label:"Pause threshold (share of the window)",help:"Fraction of the usage window at which the pause fires; the rest (1 \u2212 threshold) is your manual-work reserve. Empty \u21D2 0.75."}]},{id:"context.job_logs",label:"Job transcripts",help:"Whether the raw agent transcript of each job is kept in the Context Repo.",fields:[{id:"context.job_logs.enabled",file:"regimen.yaml",path:["context","job_logs","enabled"],type:"boolean",label:"Keep transcripts in the Context Repo",nullable:!1,help:"Off (default): the transcript is discarded after the run \u2014 nothing lands in the Context Repo. On: each job's raw transcript is committed as tasks/<KEY>/logs/job-<id>.jsonl for post-mortem debugging."}]}]});function ad(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 Ua(t){let{name:e,body:r,origin:n}=t;if(!Da.test(e))return{ok:!1,error:`role name must match ${Da} (got "${e}")`};if(r.trim().length===0)return{ok:!1,error:"role body is empty \u2014 the body IS the role's prompt"};let o=t.frontmatter;if(o==null||typeof o!="object"||Array.isArray(o))return{ok:!1,error:"missing or malformed frontmatter block"};let i=o,s=i.description;if(typeof s!="string"||s.trim().length===0)return{ok:!1,error:"description is required (one line: what this role looks for)"};if(s.length>300)return{ok:!1,error:"description must be \u2264 300 characters"};let a=ad(i.refs);if(a===null)return{ok:!1,error:"refs must be a list of non-empty paths"};if(a.length>10)return{ok:!1,error:"refs must list at most 10 files \u2014 a role is a narrow view"};for(let d of a)if(d.startsWith("/")||d.includes(".."))return{ok:!1,error:`ref "${d}" must be a path inside the Context Repo`};let c=ad(i.scenarios);if(c===null)return{ok:!1,error:"scenarios must be a list"};let l=[];for(let d of c){if(!ai.includes(d))return{ok:!1,error:`unknown scenario "${d}" \u2014 one of: ${ai.join(", ")}`};l.includes(d)||l.push(d)}if(l.length===0)return{ok:!1,error:`scenarios must name at least one of: ${ai.join(", ")}`};let u=i.model;if(u!==void 0&&(typeof u!="string"||u.trim().length===0))return{ok:!1,error:"model must be a non-empty string when set"};let p=i.enabled;return p!==void 0&&typeof p!="boolean"?{ok:!1,error:"enabled must be true or false"}:{ok:!0,role:{name:e,description:s.trim(),...typeof u=="string"?{model:u.trim()}:{},refs:a,scenarios:l,enabled:p!==!1,body:r.trim(),origin:n}}}function Ba(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 Fa(t,e){return t.filter(r=>r.enabled&&r.scenarios.includes(e))}var ai,Da,BA,FA,cd=x(()=>{"use strict";ai=["plan_review","code_review","council"],Da=/^[a-z][a-z0-9-]{1,39}$/,BA=10,FA=300});function Ga(t){return ld.includes(t)}function Ka(t){return`prompts/${t}.md`}var ld,ud=x(()=>{"use strict";ld=["analysis","analyze","backfill","build","chat","code-review","code-review-external","code-review-fix","code-review-verify","council","draft","estimate","implement","index","observer","resolve-conflict","review-comment","rework","testing"]});function Wa(t){if(!Ha.test(t.name))return{ok:!1,error:`skill directory name must match ${Ha}`};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 qa(t,e,r){let n=new Map;for(let o of[...t,...e,...r])n.set(o.name,o);return[...n.values()].sort((o,i)=>o.name<i.name?-1:o.name>i.name?1:0)}function pd(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(!Xb.test(n))return{ok:!1,error:`"${t}": expected <owner>/<repo>[@<40-hex sha>]`};let i=dd.find(s=>s.repo.toLowerCase()===n.toLowerCase());return o&&!Jb.test(o)?{ok:!1,error:`"${t}": pin to a full 40-character commit sha \u2014 a branch or tag can change under you`}:!i&&!o?{ok:!1,error:`"${t}": a third-party marketplace must be pinned to a commit (<owner>/<repo>@<sha>). Its skills run beside your code with the agent's token.`}:{ok:!0,source:{repo:n,sha:o,name:i?.name??n.replace("/","-").toLowerCase(),official:!!i}}}function Zb(t){let e=[],r=[],n=new Set;for(let o of t){if(!o.trim())continue;let i=pd(o);if(!i.ok){r.push(i.error);continue}n.has(i.source.name)||(n.add(i.source.name),e.push(i.source))}return{sources:e,errors:r}}function e$(t,e){let r=new Set(e.map(i=>i.name)),n={},o=[];for(let i of t){let s=i.trim();if(s){if(!Qb.test(s)||!r.has(s.slice(s.indexOf("@")+1))){o.push(s);continue}n[s]=!0}}return{enabled:n,unknown:o}}var Ha,HA,dd,Xb,Jb,Qb,fd=x(()=>{"use strict";Ha=/^[a-z][a-z0-9-]{1,39}$/,HA=300;dd=[{repo:"anthropics/skills",name:"anthropic-agent-skills"},{repo:"anthropics/claude-plugins-official",name:"claude-plugins-official"}],Xb=/^[A-Za-z0-9][\w.-]*\/[A-Za-z0-9][\w.-]*$/,Jb=/^[0-9a-f]{40}$/;Qb=/^[A-Za-z0-9][\w.-]*@[A-Za-z0-9][\w.-]*$/});function md(t,e){if(t==null)return[];if(!Array.isArray(t)||t.length>e)return null;let r=[];for(let n of t){if(typeof n!="string"||n.trim().length===0)return null;r.push(n.trim())}return r}function t$(t,e){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:"queue plan must be a JSON object"};let r=new Set(e),n=t,o=md(n.order,e.length);if(o===null)return{ok:!1,error:"order must be a list of task keys"};for(let f of o)if(!r.has(f))return{ok:!1,error:`order names ${f}, which is not in this batch`};if(new Set(o).size!==o.length)return{ok:!1,error:"order repeats a task key"};let i=e.filter(f=>!o.includes(f));if(o.length>0&&i.length>0)return{ok:!1,error:`order omits ${i.join(", ")}`};let s=n.tasks,a=[];if(s!=null){if(!Array.isArray(s))return{ok:!1,error:"tasks must be a list"};for(let f of s){if(!f||typeof f!="object")return{ok:!1,error:"each task entry must be an object"};let y=f,k=typeof y.taskKey=="string"?y.taskKey.trim():"";if(!r.has(k))return{ok:!1,error:`tasks names ${k||"(empty)"}, which is not in this batch`};let h=md(y.after,e.length);if(h===null)return{ok:!1,error:`${k}: after must be a list of task keys`};for(let $ of h){if(!r.has($))return{ok:!1,error:`${k}: after names ${$}, not in this batch`};if($===k)return{ok:!1,error:`${k}: cannot come after itself`}}let w=typeof y.decisions=="string"?y.decisions.trim():"";a.push({taskKey:k,decisions:w.slice(0,4e3),after:h})}}let c=[],l=n.conflicts;if(Array.isArray(l))for(let f of l){if(!f||typeof f!="object")continue;let y=f,k=typeof y.taskKey=="string"?y.taskKey.trim():"",h=typeof y.adr=="string"?y.adr.trim():"",w=typeof y.detail=="string"?y.detail.trim():"";!r.has(k)||!w||c.push({taskKey:k,adr:h,detail:w.slice(0,4e3)})}let u=[],p=n.related;if(Array.isArray(p))for(let f of p){if(!f||typeof f!="object")continue;let y=f,k=typeof y.taskKey=="string"?y.taskKey.trim():"",h=typeof y.detail=="string"?y.detail.trim():"";!k||!h||u.push({taskKey:k,detail:h.slice(0,4e3)})}let d=typeof n.summary=="string"?n.summary.trim().slice(0,4e3):"",m=n.deferBehind===!0;return{ok:!0,plan:{order:o,tasks:a,conflicts:c,related:u,summary:d,deferBehind:m}}}var qA,YA,hd=x(()=>{"use strict";qA=4e3,YA=4e3});function r$(t,e){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:"council verdict must be a JSON object"};let r=t,n=r.unresolved===!0,o=typeof r.fork=="string"?r.fork.trim().slice(0,4e3):"";if(n)return o?{ok:!0,verdict:{answers:[],unresolved:!0,fork:o}}:{ok:!1,error:"an unresolved verdict must describe the fork"};let i=r.answers;if(!Array.isArray(i))return{ok:!1,error:"answers must be a list"};if(i.length!==e.length)return{ok:!1,error:`expected ${e.length} answer(s), got ${i.length}`};let s=[];for(let[a,c]of i.entries()){if(!c||typeof c!="object")return{ok:!1,error:`answer ${a+1} must be an object`};let l=c,u=typeof l.answer=="string"?l.answer.trim():"";if(!u)return{ok:!1,error:`answer ${a+1} is empty`};s.push({question:typeof l.question=="string"?l.question.trim():e[a],answer:u.slice(0,4e3),rationale:typeof l.rationale=="string"?l.rationale.trim().slice(0,4e3):""})}return{ok:!0,verdict:{answers:s,unresolved:!1,fork:""}}}var VA,gd=x(()=>{"use strict";VA=4e3});function i$(t){let e=t.replace(/^#+\s*/,"").trim();for(let r of n$)if(r.re.test(e))return{kind:r.kind,letter:r.letter};return null}function Ya(t){let e=[],r=new Map,n="",o=null,i=null;for(let a of t.split(`
8
- `)){let c=/^#{1,6}\s+(.*)$/.exec(a);if(c){n=c[1].trim(),o=i$(n),i=null;continue}let l=o$.exec(a);if(l&&o){let u=l[1];r.set(u,(r.get(u)??0)+1),i={id:u,kind:o.kind,text:l[2].trim(),section:n},e.push(i);continue}if(i&&a.trim()&&!/^#{1,6}\s/.test(a)&&!/^\s*[-*]\s/.test(a)){i.text=`${i.text}
9
- ${a.trim()}`.trim();continue}a.trim()||(i=null)}let s=[...r.entries()].filter(([,a])=>a>1).map(([a])=>a);return{items:e,structured:e.length>=2&&s.length===0,duplicateIds:s}}function s$(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 a$(t,e){let r=new Map(t.items.map(s=>[s.id,s])),n=e.filter(s=>!s.approved),o=e.filter(s=>s.approved).map(s=>s.id);if(n.length===0)return"";let i=["Rejected plan items:",""];for(let s of n){let a=r.get(s.id),c=a?`${s.id} \u2014 ${a.text.split(`
7
+ `}function ga(t){return vr(Du(t))}function ya(t){return vr(Uu(t))}function zr(t){return vr(Bu(t))}var Le,Sb,Eb,Tb,Rb,ei,wr,Ou,da,Lu,Ib,ot,pa,fa,ma,ri,Cb,ha,$r,Ab,wa=x(()=>{"use strict";Le=2,Sb="model",Eb="model/README.md",Tb="model/facts",Rb="model/derived",ei="model/derived/INDEX.yaml",wr="model/derived/relates.yaml";Ou=["system","container","component","code","task","adr"],da=["contains","touched_by","correlates","relates","references","depends_on"],Lu=/^e_[0-9a-f]{8}$/;Ib=["system","task","adr"];ot={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};pa=2,fa=5,ma=50,ri=2e3,Cb=5e4,ha={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},$r={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};Ab=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});function _b(t){return t==="DONE"}function jb(t){return t==="AWAITING_EXTERNAL_FIX"?!1:ka.indexOf(t)>=ka.indexOf("IMPLEMENTING")}var ka,Hu=x(()=>{"use strict";ka=["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 Ob(t){for(let e of ba)if(e.phases.includes(t))return e.id;return null}function Lb(t){for(let e of Wu)if(e.phases.includes(t))return e.id;return null}var ba,Nb,Wu,qu=x(()=>{"use strict";ba=[{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"]}],Nb=ba.flatMap(t=>t.phases),Wu=[{id:"review",label:"Review / tracking",phases:["CODE_REVIEW","TESTING","TRACKING"]},{id:"attention",label:"Need your attention",phases:["NEEDS_MANUAL","AWAITING_APPROVAL","AWAITING_EXTERNAL_FIX","AWAITING_ANSWER","REVIEW"]},{id:"backlog",label:"Backlog / queue",phases:["BACKLOG","QUEUED"]}]});function Mb(t){return Yu.includes(t)?"planning":"implementation"}function qt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var $a,Yu,Db,va=x(()=>{"use strict";$a=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat","observer","council","testing"],Yu=["draft","analysis","chat","observer","council"];Db=1});function zu(t,e){return e.toLowerCase().includes(t.toLowerCase())}function Ea(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||ed.every(o=>e.some(i=>zu(o,i.id))))return null;let n=[...e].sort((o,i)=>{let s=o.createdAt??"",a=i.createdAt??"";return s!==a?s<a?1:-1:o.id<i.id?1:-1});for(let o of Qu){let i=n.find(s=>zu(o,s.id));if(i)return i.id}return n[0].id}function Vr(){return{default:null,roles:{}}}function Ub(t,e){let r=t?.roles?.[e];return typeof r=="string"&&r.trim().length>0?r.trim():t?.default&&t.default.trim().length>0?t.default.trim():no[e]??Zu}function Bb(t){let e=t?.provider;return typeof e=="string"&&e.trim().length>0?e.trim():Xe}function Fb(t){let e=Vr();if(!t||typeof t!="object")return e;let r=t.llm;if(!r||typeof r!="object")return e;let n=r.provider;typeof n=="string"&&n.trim().length>0&&(e.provider=n.trim());let o=r.models;if(!o||typeof o!="object")return e;for(let[i,s]of Object.entries(o))typeof s!="string"||s.trim().length===0||(i==="default"?e.default=s.trim():e.roles[i]=s.trim());return e}function Gb(t){let e=typeof t.provider=="string"&&t.provider.trim().length>0&&t.provider.trim()!==Xe;if(t.default===null&&Object.keys(t.roles).length===0&&!e)return null;let{provider:r,...n}=t;return JSON.stringify(e?{provider:r.trim(),...n}:n)}function Kb(t){if(!t)return Vr();try{let e=JSON.parse(t);if(!e||typeof e!="object")return Vr();let r=e,n=Vr();typeof r.provider=="string"&&r.provider.trim().length>0&&(n.provider=r.provider.trim()),typeof r.default=="string"&&(n.default=r.default);let o=r.roles;if(o&&typeof o=="object")for(let[i,s]of Object.entries(o))typeof s=="string"&&(n.roles[i]=s);return n}catch{return Vr()}}var Xe,xa,Pe,Xr,oi,ii,Vu,Xu,Ju,Sa,no,Zu,Qu,ed,Ta=x(()=>{"use strict";va();Xe="claude",xa=[Xe],Pe="opus",Xr="sonnet",oi="haiku",ii=[Pe,Xr,oi],Vu="build-discovery",Xu="code-review-verify",Ju=[Vu,Xu],Sa=[...$a,...Ju],no={analyze:Pe,implement:Pe,"resolve-conflict":Pe,rework:Pe,estimate:Xr,build:oi,"build-discovery":Pe,"code-review":Pe,"code-review-verify":Xr,draft:Xr,index:Pe,backfill:Pe,analysis:Pe,chat:Pe,observer:Pe,council:Pe,testing:Pe},Zu=Pe,Qu=[Pe,Xr,oi],ed=Array.from(new Set(Object.values(no)))});function Mt(t){return Hb.has(t)?!0:Wb.some(e=>t.startsWith(e))}function si(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function xr(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function Ia(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function Pa(t,e){let r=si(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=xr(r.id,"id")??n;if(!Ra.test(o))throw new Error(`id must match ${Ra} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=xr(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=si(r.env,"env");s={};for(let[d,m]of Object.entries(p)){if(!Je.test(d))throw new Error(`env name "${d}" must match ${Je}`);if(typeof m!="string"&&typeof m!="number"&&typeof m!="boolean")throw new Error(`env.${d} must be a scalar`);s[d]=String(m)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>td)throw new Error(`too many params (max ${td})`);let p=new Set;a=c.map((d,m)=>qb(d,m,p))}let l=r.steps;if(!Array.isArray(l)||l.length===0)throw new Error("steps must be a non-empty list");if(l.length>rd)throw new Error(`too many steps (max ${rd})`);let u=l.map((p,d)=>{let m=si(p,`steps[${d}]`),f=xr(m.run,`steps[${d}].run`);if(!f||f.trim().length===0)throw new Error(`steps[${d}].run is required`);let g=xr(m.name,`steps[${d}].name`),k=Ia(m.timeout_sec,`steps[${d}].timeout_sec`);if(k!==void 0&&(!Number.isInteger(k)||k<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:f,...g?{name:g}:{},...k!==void 0?{timeout_sec:k}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function qb(t,e,r){let n=si(t,`params[${e}]`),o=xr(n.name,`params[${e}].name`);if(!o||!Je.test(o))throw new Error(`params[${e}].name must match ${Je}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let m=n.enum;if(!Array.isArray(m)||m.length===0||!m.every(f=>typeof f=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=m}let a=xr(n.label,`params[${e}].label`),c=xr(n.help,`params[${e}].help`),l=n.required===!0,u=Ia(n.min,`params[${e}].min`),p=Ia(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 Aa(t,e){let r=t.params??[],n=new Map(r.map(i=>[i.name,i]));for(let i of Object.keys(e))if(!n.has(i))return{ok:!1,error:`unknown param: ${i}`};let o={};for(let i of r){let s=e[i.name];if(s==null||typeof s=="string"&&s.trim()==="")if(i.default!==void 0)s=i.default;else{if(i.required)return{ok:!1,error:`${i.name} is required`};continue}switch(i.type){case"string":{if(typeof s!="string")return{ok:!1,error:`${i.name} must be a string`};o[i.name]=s;break}case"enum":{if(typeof s!="string"||!(i.enum??[]).includes(s))return{ok:!1,error:`${i.name} must be one of: ${(i.enum??[]).join(", ")}`};o[i.name]=s;break}case"number":{let a=typeof s=="number"?s:typeof s=="string"?Number(s):NaN;if(!Number.isFinite(a))return{ok:!1,error:`${i.name} must be a number`};if(i.min!==void 0&&a<i.min)return{ok:!1,error:`${i.name} must be \u2265 ${i.min}`};if(i.max!==void 0&&a>i.max)return{ok:!1,error:`${i.name} must be \u2264 ${i.max}`};o[i.name]=a;break}case"boolean":{let a=typeof s=="boolean"?s:s==="true"?!0:s==="false"?!1:null;if(a===null)return{ok:!1,error:`${i.name} must be a boolean`};o[i.name]=a;break}}}return{ok:!0,values:o}}var Je,Hb,Wb,Ca,Ra,td,rd,_a=x(()=>{"use strict";Je=/^[A-Z][A-Z0-9_]*$/,Hb=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),Wb=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];Ca=600,Ra=/^[a-z0-9-]+$/,td=32,rd=64});function nd(){return{primary:ve,context:ve,tasks:ve,docs:ve,code_comments:ve,chat:ve,code_review:ve}}function od(t){return!t||t.trim().length===0||t.trim().toLowerCase()===ve}function Yb(t){if(typeof t!="string")return ve;let e=t.trim().replace(/\s+/g," ");return e.length===0||e.length>40||e.toLowerCase()===ve?ve:e}function zb(t){let e=nd();if(!t||typeof t!="object")return e;let r=t.language;if(!r||typeof r!="object"||Array.isArray(r))return e;let n=r;for(let o of oo)e[o]=Yb(n[o]);return e}function Vb(t){return oo.every(e=>od(t[e]))}var ve,oo,Jr,io,ja=x(()=>{"use strict";ve="auto",oo=["primary","context","tasks","docs","code_comments","chat","code_review"],Jr=["English","Russian","German","Spanish","French","Portuguese","Italian","Chinese","Japanese","Korean"],io=40});function Ma(t=id){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...Ma(r.groups));return e}function sd(t,e){let r=JSON.stringify(e);return Ma().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function Da(t){let e=sd(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.type==="string"&&e.mustContain&&!i.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:e.maxLength!==void 0&&i.length>e.maxLength?{ok:!1,error:`${e.id} must be \u2264 ${e.maxLength} chars`}:{ok:!0,field:e,value:i}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)?{ok:!1,error:`${e.id} must be a number`}:!e.float&&!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}case"string_map":{if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,error:`${e.id} must be a name\u2192value map`};let i=Object.entries(r);if(i.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(i.length>Na)return{ok:!1,error:`${e.id} must have \u2264 ${Na} entries`};let s={};for(let[a,c]of i){if(!Je.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Je}`};if(Mt(a))return{ok:!1,error:`${e.id}: name "${a}" is reserved`};if(typeof c!="string")return{ok:!1,error:`${e.id}: value of "${a}" must be a string`};if(c.length>Oa)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${Oa} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var Xb,Jb,Na,Oa,La,id,ad=x(()=>{"use strict";_a();Ta();wa();ja();Xb={primary:"Primary language",context:"Context documents",tasks:"Tracker issues",docs:"Repo documentation",code_comments:"Code comments",chat:"Agent chat",code_review:"Code review comments"},Jb={primary:"The project's main language (agent status notes ride it). Empty \u21D2 auto.",context:"Knowledge, ADRs and task artifacts in the Context Repo. Empty \u21D2 auto.",tasks:"Issue titles/bodies the agent drafts. Empty \u21D2 auto.",docs:"Documentation changes in the project repos. Empty \u21D2 auto.",code_comments:"New code comments the agent writes. Empty \u21D2 auto.",chat:"The interactive task-drafting chat. Empty/auto \u21D2 mirror the user's messages.",code_review:"Review findings and PR comments. Empty \u21D2 follows the tracker-issues language."},Na=64,Oa=2e3,La=2e3,id=[{id:"branch",label:"Branch",help:"Task-branch naming.",fields:[{id:"branch.pattern",file:"project.yaml",path:["branch","pattern"],type:"string",label:"Task-branch pattern",nullable:!0,mustContain:"<TASK_ID>",help:"Template for the per-task branch name. Must contain the <TASK_ID> placeholder. Empty \u21D2 default codepipe/<TASK_ID>."}]},{id:"llm",label:"LLM",fields:[{id:"llm.provider",file:"regimen.yaml",path:["llm","provider"],type:"enum",label:"Provider",nullable:!1,suggestions:[...xa],help:"LLM backend for this project. Currently only claude is available."}],groups:[{id:"llm.models",label:"Models by role",help:"Model per pipeline stage. Empty \u21D2 the role's recommended default applies.",fields:[{id:"llm.models.default",file:"regimen.yaml",path:["llm","models","default"],type:"model",label:"default (catch-all)",nullable:!0,suggestions:[...ii],help:"Overrides the recommended defaults for every role not listed below."},...Sa.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...ii],help:`recommended: ${no[t]}`}))]}]},{id:"apply.style",label:"Commits & PRs",help:"Instructions for the AI agent on how to write commit messages and PR descriptions. Empty \u21D2 built-in templates.",fields:[{id:"apply.commit_style",file:"project.yaml",path:["apply","commit_style"],type:"string",label:"Commit message style",nullable:!0,multiline:!0,maxLength:La,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:La,help:`e.g. "implementation details, bullet list of what was done, in the tracker's language". Empty \u21D2 the default PR body.`}]},{id:"apply.delivery",label:"Delivery & merge",help:"How a finished change reaches the repository: with or without a pull request, and who merges it.",fields:[{id:"apply.pull_request",file:"project.yaml",path:["apply","pull_request"],type:"boolean",label:"Open a pull request",nullable:!1,help:"On (default): the task branch is pushed and a pull request is opened \u2014 the change is reviewable in the git host and keeps a history of review comments. Off: no PR at all; the branch is merged into the default branch directly, and the agent's review remarks live only in the dashboard and the Context Repo."},{id:"apply.done",file:"project.yaml",path:["apply","done"],type:"enum",label:"Task is done when",nullable:!1,suggestions:["merge","branch"],help:"merge (default): the task is finished only once its change lands in the default branch. branch: the task ends at the pushed branch (plus the PR, if enabled) and nothing is merged for you."},{id:"apply.auto_merge",file:"project.yaml",path:["apply","auto_merge"],type:"enum",label:"Auto-merge pull requests",nullable:!1,suggestions:["off","on_ci_green"],help:"Applies to the pull-request path only. off (default): the merge waits for you (Approve on the task card). on_ci_green: as soon as the PR is open, conflict-free and its CI is green, CodePipe merges it \u2014 changes reach the default branch with no further review from you. Requires full automation; branch protection on the host still applies (a refused merge parks the task). Without pull requests, full automation merges the branch itself and this switch does not apply."}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{id:"testing",label:"Testing",help:"An optional phase after code review: writes the test plan you run in the morning and reports what it could verify.",fields:[{id:"testing.enabled",file:"regimen.yaml",path:["testing","enabled"],type:"boolean",nullable:!1,label:"Run the testing phase",help:"Off by default. When on, a task passing code review goes through a test pass before the PR: it derives TESTPLAN.md from the plan's requirements and reports per requirement what it could verify. A requirement it finds broken sends the change back for a fix (bounded below)."},{id:"testing.max_iterations",file:"regimen.yaml",path:["testing","max_iterations"],type:"number",nullable:!0,min:1,max:10,label:"Fix rounds before stopping",help:"How many times a failed test pass may send the change back before the task waits for you. Empty \u21D2 2."}]},{id:"code_review",label:"Code review",help:"One review mechanism for the pipeline's own changes and for developers' branches (the review column); they differ only in where the findings go.",fields:[{id:"code_review.verify_pass",file:"regimen.yaml",path:["code_review","verify_pass"],type:"boolean",nullable:!1,label:"Verifier pass (precision)",help:"On by default, paired with the critics panel. A second, narrow agent checks every finding against the code (real? re-grade) before it costs a rework round or reaches a developer; the findings threshold below keeps small rounds cheap."},{id:"code_review.panel",file:"regimen.yaml",path:["code_review","panel"],type:"boolean",nullable:!1,label:"Critics panel",help:"On by default. The reviewer delegates to the project's critic roles (roles/ in the Context Repo, or the bundled set) as parallel subagents before its own pass. Cost grows with the number of roles."},{id:"code_review.verify_min_findings",file:"regimen.yaml",path:["code_review","verify_min_findings"],type:"number",nullable:!0,min:1,label:"Verifier threshold (findings)",help:"The verifier runs only when a round carries at least this many actionable findings \u2014 1-2 are cheap to absorb, noise scales with volume. Empty = 3; 1 = verify every round."},{id:"code_review.max_blocking",file:"regimen.yaml",path:["code_review","max_blocking"],type:"number",nullable:!0,label:"Blocking budget (internal)",help:"Max blocker findings that keep their power in the pipeline's own review; the rest are demoted to major, weakest confidence first. Empty = 5."},{id:"code_review.external.max_blocking",file:"regimen.yaml",path:["code_review","external","max_blocking"],type:"number",nullable:!0,label:"Blocking budget (external)",help:"The same budget for a developer's branch review \u2014 tighter by default because a human reads these. Empty = 3."}]},{id:"skills",label:"Skills",help:"Reusable procedures the agent can invoke instead of improvising. Only their names and one-line descriptions sit in the prompt; the steps load when a skill is used.",fields:[{id:"skills.from_bundled",file:"regimen.yaml",path:["skills","from_bundled"],type:"boolean",nullable:!1,label:"Use the skills shipped with CodePipe",help:"On by default. General procedures maintained with the product."},{id:"skills.from_context_repo",file:"regimen.yaml",path:["skills","from_context_repo"],type:"boolean",nullable:!1,label:"Use this project's skills",help:"On by default. Skills the team writes in the context repository under `skills/<name>/SKILL.md`. These override a bundled skill of the same name."},{id:"skills.from_project_repo",file:"regimen.yaml",path:["skills","from_project_repo"],type:"boolean",nullable:!1,label:"Use the code repository's skills",help:"On by default. `.claude/skills/` inside the project repositories \u2014 the skills your developers already use locally. These win over both other sources."}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (on by default; orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on (default), a task taken from Develop waits in the QUEUE for a single Confirm before the pipeline starts \u2014 the Confirm pulls in dependency closure and topologically orders the queue. Off \u21D2 conveyor: the task starts the pipeline immediately."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]},{id:"language",label:"Language",help:"Languages the agent writes in, per area. Empty \u21D2 auto: mirror the language of the user's material.",fields:oo.map(t=>({id:`language.${t}`,file:"project.yaml",path:["language",t],type:"string",label:Xb[t],nullable:!0,maxLength:40,suggestions:t==="chat"?[ve,...Jr]:[...Jr],help:Jb[t]}))},{id:"context.model",label:"Project map",help:"Parameters of the project map (built from git history by the CLI). Empty fields keep the defaults.",fields:[{id:"context.model.enabled",file:"regimen.yaml",path:["context","model","enabled"],type:"boolean",label:"Enable in the pipeline",nullable:!1,help:"When on, agents are asked to record intent annotations and (once available) receive an assembled context pack. Off \u21D2 the pipeline ignores the map entirely."},{id:"context.model.prompt.pack",file:"regimen.yaml",path:["context","model","prompt","pack"],type:"boolean",nullable:!1,label:"Give agents the context pack",help:"On by default. The assembled pack costs up to ~4000 tokens on every task of the analyze / estimate / implement / rework roles. Turning it off keeps the map building and stops the spend \u2014 the way to see what the pack is actually worth on this project."},{id:"context.model.prompt.annotations",file:"regimen.yaml",path:["context","model","prompt","annotations"],type:"boolean",nullable:!1,label:"Ask agents for intent annotations",help:"On by default. Adds the annotations block to the implement and rework prompts \u2014 the layer that records WHY the code is shaped this way. Cheap, and worth accumulating even while the pack is off."},{id:"context.index.hub",file:"regimen.yaml",path:["context","index","hub"],type:"enum",label:"Search index on the server",nullable:!0,suggestions:["off","metadata"],help:"off (default): search runs on your machine, nothing is uploaded. metadata: paths, labels and task texts (never code) are mirrored to the server so search and structure stay available while your machine is offline. Switching back to off deletes the mirrored rows."},{id:"context.model.issue_key_pattern",file:"regimen.yaml",path:["context","model","issue_key_pattern"],type:"string",label:"Issue-key pattern (regex)",nullable:!0,maxLength:200,help:"Regex that finds tracker issue keys in commit subjects when mining task events from history. Empty \u21D2 derived from the tracker project key (e.g. DEV-\\d+)."},{id:"context.model.cochange.window_commits",file:"regimen.yaml",path:["context","model","cochange","window_commits"],type:"number",label:"History window (commits)",nullable:!0,min:50,max:5e4,help:`How many commits back from the build commit are mined. Default ${ot.windowCommits}.`},{id:"context.model.cochange.commit_file_cap",file:"regimen.yaml",path:["context","model","cochange","commit_file_cap"],type:"number",label:"Commit size cap (files)",nullable:!0,min:2,max:500,help:`Commits touching more files are ignored as noise. Default ${ot.commitFileCap}.`},{id:"context.model.cochange.support_min",file:"regimen.yaml",path:["context","model","cochange","support_min"],type:"number",label:"Minimum co-occurrences",nullable:!0,min:1,max:100,help:`A pair of files must change together at least this many times. Default ${ot.supportMin}.`},{id:"context.model.cochange.jaccard_min_pct",file:"regimen.yaml",path:["context","model","cochange","jaccard_min_pct"],type:"number",label:"Minimum Jaccard (%)",nullable:!0,min:0,max:100,help:`Overlap threshold: |A\u2229B| / |A\u222AB| of the files' commit sets, in percent. Default ${ot.jaccardMinPct}.`},{id:"context.model.cochange.half_life_days",file:"regimen.yaml",path:["context","model","cochange","half_life_days"],type:"number",label:"Time-decay half-life (days)",nullable:!0,min:1,max:3650,help:`A commit this old counts half as much. Default ${ot.halfLifeDays} (~9 months).`},{id:"context.model.cochange.top_k",file:"regimen.yaml",path:["context","model","cochange","top_k"],type:"number",label:"Edges per file (top-k)",nullable:!0,min:1,max:64,help:`Only the k strongest co-change edges of a file survive \u2014 bounds graph density whatever the thresholds. Default ${ot.topK}.`}]},{id:"rate_limit",label:"Rate limit",help:"Automatic project pause as the LLM usage window fills up.",fields:[{id:"rate_limit.auto_pause.enabled",file:"project.yaml",path:["rate_limit","auto_pause","enabled"],type:"boolean",nullable:!1,label:"Pause the project near the limit",help:"On (default): when window utilization reaches the threshold, the project is paused (same pause as the manual one) and you get an email \u2014 the remaining window stays available for your own work. Off: agents keep working until the provider actually runs out."},{id:"rate_limit.auto_pause.threshold",file:"project.yaml",path:["rate_limit","auto_pause","threshold"],type:"number",float:!0,nullable:!0,min:.05,max:1,label:"Pause threshold (share of the window)",help:"Fraction of the usage window at which the pause fires; the rest (1 \u2212 threshold) is your manual-work reserve. Empty \u21D2 0.75."}]},{id:"context.job_logs",label:"Job transcripts",help:"Whether the raw agent transcript of each job is kept in the Context Repo.",fields:[{id:"context.job_logs.enabled",file:"regimen.yaml",path:["context","job_logs","enabled"],type:"boolean",label:"Keep transcripts in the Context Repo",nullable:!1,help:"Off (default): the transcript is discarded after the run \u2014 nothing lands in the Context Repo. On: each job's raw transcript is committed as tasks/<KEY>/logs/job-<id>.jsonl for post-mortem debugging."}]}]});function cd(t){if(t==null)return[];if(!Array.isArray(t))return null;let e=[];for(let r of t){if(typeof r!="string"||r.trim().length===0)return null;e.push(r.trim())}return e}function Ba(t){let{name:e,body:r,origin:n}=t;if(!Ua.test(e))return{ok:!1,error:`role name must match ${Ua} (got "${e}")`};if(r.trim().length===0)return{ok:!1,error:"role body is empty \u2014 the body IS the role's prompt"};let o=t.frontmatter;if(o==null||typeof o!="object"||Array.isArray(o))return{ok:!1,error:"missing or malformed frontmatter block"};let i=o,s=i.description;if(typeof s!="string"||s.trim().length===0)return{ok:!1,error:"description is required (one line: what this role looks for)"};if(s.length>300)return{ok:!1,error:"description must be \u2264 300 characters"};let a=cd(i.refs);if(a===null)return{ok:!1,error:"refs must be a list of non-empty paths"};if(a.length>10)return{ok:!1,error:"refs must list at most 10 files \u2014 a role is a narrow view"};for(let d of a)if(d.startsWith("/")||d.includes(".."))return{ok:!1,error:`ref "${d}" must be a path inside the Context Repo`};let c=cd(i.scenarios);if(c===null)return{ok:!1,error:"scenarios must be a list"};let l=[];for(let d of c){if(!ai.includes(d))return{ok:!1,error:`unknown scenario "${d}" \u2014 one of: ${ai.join(", ")}`};l.includes(d)||l.push(d)}if(l.length===0)return{ok:!1,error:`scenarios must name at least one of: ${ai.join(", ")}`};let u=i.model;if(u!==void 0&&(typeof u!="string"||u.trim().length===0))return{ok:!1,error:"model must be a non-empty string when set"};let p=i.enabled;return p!==void 0&&typeof p!="boolean"?{ok:!1,error:"enabled must be true or false"}:{ok:!0,role:{name:e,description:s.trim(),...typeof u=="string"?{model:u.trim()}:{},refs:a,scenarios:l,enabled:p!==!1,body:r.trim(),origin:n}}}function Fa(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 Ga(t,e){return t.filter(r=>r.enabled&&r.scenarios.includes(e))}var ai,Ua,WA,qA,ld=x(()=>{"use strict";ai=["plan_review","code_review","council"],Ua=/^[a-z][a-z0-9-]{1,39}$/,WA=10,qA=300});function Ka(t){return ud.includes(t)}function Ha(t){return`prompts/${t}.md`}var ud,dd=x(()=>{"use strict";ud=["analysis","analyze","backfill","build","chat","code-review","code-review-external","code-review-fix","code-review-verify","council","draft","estimate","implement","index","observer","resolve-conflict","review-comment","rework","testing"]});function qa(t){if(!Wa.test(t.name))return{ok:!1,error:`skill directory name must match ${Wa}`};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 Ya(t,e,r){let n=new Map;for(let o of[...t,...e,...r])n.set(o.name,o);return[...n.values()].sort((o,i)=>o.name<i.name?-1:o.name>i.name?1:0)}function fd(t){let e=t.trim(),r=e.lastIndexOf("@"),n=r===-1?e:e.slice(0,r),o=r===-1?"":e.slice(r+1).trim();if(!Zb.test(n))return{ok:!1,error:`"${t}": expected <owner>/<repo>[@<40-hex sha>]`};let i=pd.find(s=>s.repo.toLowerCase()===n.toLowerCase());return o&&!Qb.test(o)?{ok:!1,error:`"${t}": pin to a full 40-character commit sha \u2014 a branch or tag can change under you`}:!i&&!o?{ok:!1,error:`"${t}": a third-party marketplace must be pinned to a commit (<owner>/<repo>@<sha>). Its skills run beside your code with the agent's token.`}:{ok:!0,source:{repo:n,sha:o,name:i?.name??n.replace("/","-").toLowerCase(),official:!!i}}}function e$(t){let e=[],r=[],n=new Set;for(let o of t){if(!o.trim())continue;let i=fd(o);if(!i.ok){r.push(i.error);continue}n.has(i.source.name)||(n.add(i.source.name),e.push(i.source))}return{sources:e,errors:r}}function r$(t,e){let r=new Set(e.map(i=>i.name)),n={},o=[];for(let i of t){let s=i.trim();if(s){if(!t$.test(s)||!r.has(s.slice(s.indexOf("@")+1))){o.push(s);continue}n[s]=!0}}return{enabled:n,unknown:o}}var Wa,VA,pd,Zb,Qb,t$,md=x(()=>{"use strict";Wa=/^[a-z][a-z0-9-]{1,39}$/,VA=300;pd=[{repo:"anthropics/skills",name:"anthropic-agent-skills"},{repo:"anthropics/claude-plugins-official",name:"claude-plugins-official"}],Zb=/^[A-Za-z0-9][\w.-]*\/[A-Za-z0-9][\w.-]*$/,Qb=/^[0-9a-f]{40}$/;t$=/^[A-Za-z0-9][\w.-]*@[A-Za-z0-9][\w.-]*$/});function hd(t,e){if(t==null)return[];if(!Array.isArray(t)||t.length>e)return null;let r=[];for(let n of t){if(typeof n!="string"||n.trim().length===0)return null;r.push(n.trim())}return r}function n$(t,e){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:"queue plan must be a JSON object"};let r=new Set(e),n=t,o=hd(n.order,e.length);if(o===null)return{ok:!1,error:"order must be a list of task keys"};for(let f of o)if(!r.has(f))return{ok:!1,error:`order names ${f}, which is not in this batch`};if(new Set(o).size!==o.length)return{ok:!1,error:"order repeats a task key"};let i=e.filter(f=>!o.includes(f));if(o.length>0&&i.length>0)return{ok:!1,error:`order omits ${i.join(", ")}`};let s=n.tasks,a=[];if(s!=null){if(!Array.isArray(s))return{ok:!1,error:"tasks must be a list"};for(let f of s){if(!f||typeof f!="object")return{ok:!1,error:"each task entry must be an object"};let g=f,k=typeof g.taskKey=="string"?g.taskKey.trim():"";if(!r.has(k))return{ok:!1,error:`tasks names ${k||"(empty)"}, which is not in this batch`};let h=hd(g.after,e.length);if(h===null)return{ok:!1,error:`${k}: after must be a list of task keys`};for(let $ of h){if(!r.has($))return{ok:!1,error:`${k}: after names ${$}, not in this batch`};if($===k)return{ok:!1,error:`${k}: cannot come after itself`}}let w=typeof g.decisions=="string"?g.decisions.trim():"";a.push({taskKey:k,decisions:w.slice(0,4e3),after:h})}}let c=[],l=n.conflicts;if(Array.isArray(l))for(let f of l){if(!f||typeof f!="object")continue;let g=f,k=typeof g.taskKey=="string"?g.taskKey.trim():"",h=typeof g.adr=="string"?g.adr.trim():"",w=typeof g.detail=="string"?g.detail.trim():"";!r.has(k)||!w||c.push({taskKey:k,adr:h,detail:w.slice(0,4e3)})}let u=[],p=n.related;if(Array.isArray(p))for(let f of p){if(!f||typeof f!="object")continue;let g=f,k=typeof g.taskKey=="string"?g.taskKey.trim():"",h=typeof g.detail=="string"?g.detail.trim():"";!k||!h||u.push({taskKey:k,detail:h.slice(0,4e3)})}let d=typeof n.summary=="string"?n.summary.trim().slice(0,4e3):"",m=n.deferBehind===!0;return{ok:!0,plan:{order:o,tasks:a,conflicts:c,related:u,summary:d,deferBehind:m}}}var JA,ZA,gd=x(()=>{"use strict";JA=4e3,ZA=4e3});function o$(t,e){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:"council verdict must be a JSON object"};let r=t,n=r.unresolved===!0,o=typeof r.fork=="string"?r.fork.trim().slice(0,4e3):"";if(n)return o?{ok:!0,verdict:{answers:[],unresolved:!0,fork:o}}:{ok:!1,error:"an unresolved verdict must describe the fork"};let i=r.answers;if(!Array.isArray(i))return{ok:!1,error:"answers must be a list"};if(i.length!==e.length)return{ok:!1,error:`expected ${e.length} answer(s), got ${i.length}`};let s=[];for(let[a,c]of i.entries()){if(!c||typeof c!="object")return{ok:!1,error:`answer ${a+1} must be an object`};let l=c,u=typeof l.answer=="string"?l.answer.trim():"";if(!u)return{ok:!1,error:`answer ${a+1} is empty`};s.push({question:typeof l.question=="string"?l.question.trim():e[a],answer:u.slice(0,4e3),rationale:typeof l.rationale=="string"?l.rationale.trim().slice(0,4e3):""})}return{ok:!0,verdict:{answers:s,unresolved:!1,fork:""}}}var e_,yd=x(()=>{"use strict";e_=4e3});function a$(t){let e=t.replace(/^#+\s*/,"").trim();for(let r of i$)if(r.re.test(e))return{kind:r.kind,letter:r.letter};return null}function za(t){let e=[],r=new Map,n="",o=null,i=null;for(let a of t.split(`
8
+ `)){let c=/^#{1,6}\s+(.*)$/.exec(a);if(c){n=c[1].trim(),o=a$(n),i=null;continue}let l=s$.exec(a);if(l&&o){let u=l[1];r.set(u,(r.get(u)??0)+1),i={id:u,kind:o.kind,text:l[2].trim(),section:n},e.push(i);continue}if(i&&a.trim()&&!/^#{1,6}\s/.test(a)&&!/^\s*[-*]\s/.test(a)){i.text=`${i.text}
9
+ ${a.trim()}`.trim();continue}a.trim()||(i=null)}let s=[...r.entries()].filter(([,a])=>a>1).map(([a])=>a);return{items:e,structured:e.length>=2&&s.length===0,duplicateIds:s}}function c$(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 l$(t,e){let r=new Map(t.items.map(s=>[s.id,s])),n=e.filter(s=>!s.approved),o=e.filter(s=>s.approved).map(s=>s.id);if(n.length===0)return"";let i=["Rejected plan items:",""];for(let s of n){let a=r.get(s.id),c=a?`${s.id} \u2014 ${a.text.split(`
10
10
  `)[0]}`:s.id;i.push(`- **${c}**`),s.remark?.trim()&&i.push(` ${s.remark.trim()}`)}return o.length>0&&i.push("",`Approved and settled: ${o.join(", ")}. Do not revisit these unless a`,"rejected item forces it \u2014 and say so explicitly if it does."),i.join(`
11
- `)}function za(t){let e=new Set;for(let r of t.items)if(r.kind==="procedure")for(let n of r.text.matchAll(c$))e.add(n[1]);return[...e]}var n$,o$,c$,yd=x(()=>{"use strict";n$=[{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"}],o$=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*(.*)$/;c$=/`([a-z][a-z0-9-]{1,39})`/g});function d$(t){let e=[],r=null;for(let o of t.split(`
12
- `)){let i=u$.exec(o);if(i){r={id:i[1],status:i[2].toLowerCase(),text:i[3].trim()},e.push(r);continue}if(/^#{1,6}\s/.test(o)||/^\s*[-*]\s/.test(o)||!o.trim()){r=null;continue}r&&(r.text=`${r.text}
13
- ${o.trim()}`.trim())}let n={};for(let o of e)n[o.id]=o;return{items:e,byId:n}}function p$(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 l$,u$,wd=x(()=>{"use strict";l$=["done","deviated","partial","dropped"],u$=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*[—:-]?\s*(done|deviated|partial|dropped)\b\s*[—:-]?\s*(.*)$/i});var kd=x(()=>{"use strict"});var bd=x(()=>{"use strict"});var $d=x(()=>{"use strict"});function Va(t){return`codepipe-host-${t}`}function f$(t){let e=t.filter(r=>r!=="self-hosted");return`runs-on: [self-hosted${e.length?", "+e.join(", "):""}]`}var vd=x(()=>{"use strict"});function m$(t,e){return(t&&t.includes("<TASK_ID>")?t:xd).replace(/<TASK_ID>/g,e.toLowerCase())}function h$(t,e){if(t)return`${t.replace(/\/+$/,"")}/issue/${encodeURIComponent(e)}`}function so(t){return!(!t||t.length>250||!/^[A-Za-z0-9._/-]+$/.test(t)||/^[-/.]/.test(t)||/[/.]$/.test(t)||t.endsWith(".lock")||t.includes("..")||t.includes("//")||t.includes("/."))}function Xa(t){if(!t||typeof t!="object")return null;let e=t,r=typeof e.owner=="string"?e.owner.trim():"",n=typeof e.repo=="string"?e.repo.trim():typeof e.repoName=="string"?e.repoName.trim():"",o=typeof e.host=="string"?e.host.trim():"";return!r||!n||o!=="github"&&o!=="gitlab"&&o!=="bitbucket"?null:{host:o,owner:r,repoName:n}}function Ja(t){if(!t.mirror)return t;let{mirror:e,...r}=t;return{...r,host:e.host,owner:e.owner,repoName:e.repoName}}function St(t){return`${t}${Sd}`}var xd,Yt,Sd,Ed=x(()=>{"use strict";xd="codepipe/<TASK_ID>";Yt=/^[a-z][a-z0-9-]{1,30}$/,Sd="-codepipe-ctx"});function g$(t,e){return`${t}:${e}`}var Td=x(()=>{"use strict"});function Rd(t){let e=(t??"").trim();return/^pr_closed_without_merge\b/.test(e)?"blocked":/^(merge_failed|close_failed)\b/.test(e)||/^chain_base_changed\b/.test(e)||/^write action apply_delivery failed: .*hit conflicts/.test(e)?"conflict":/^(build_failed|ci_failed)\b/.test(e)?"loop_exhausted":"error"}function y$(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.to==="NEEDS_MANUAL")return r}return null}function w$(t,e){if(t==="AWAITING_ANSWER")return{kind:"question"};if(t==="NEEDS_MANUAL"){let n=y$(e)?.reason,o={kind:Rd(n)};return n&&(o.reason=n),o}}var Id=x(()=>{"use strict"});function Sr(t){for(let e of Cd){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var Cd,Pd=x(()=>{"use strict";Cd=[{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 Ad=x(()=>{"use strict"});function _d(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 k$(t,e=Date.now()){return`${_d((e-t)/1e3)} ago`}function b$(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 jd=x(()=>{"use strict"});var Nd=x(()=>{"use strict"});function Od(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function Qa(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=Od(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Er.test(r))return r;let n=Od(t);return Er.test(n)?n:ci}function ec(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 Qr(t){return`tasks/${t}/issue.yaml`}var Za,ao,ci,Er,li,$$,co,Zr,Ld=x(()=>{"use strict";Za=["bug","feature","epic"],ao="feature",ci="TASK",Er=/^[A-Z][A-Z0-9]{1,9}$/;li={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},$$=li.backlog,co="tracker/config.yaml",Zr="tracker/counter"});function lo(t){let e=t.split(`
11
+ `)}function Va(t){let e=new Set;for(let r of t.items)if(r.kind==="procedure")for(let n of r.text.matchAll(u$))e.add(n[1]);return[...e]}var i$,s$,u$,wd=x(()=>{"use strict";i$=[{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"}],s$=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*(.*)$/;u$=/`([a-z][a-z0-9-]{1,39})`/g});function f$(t){let e=[],r=null;for(let o of t.split(`
12
+ `)){let i=p$.exec(o);if(i){r={id:i[1],status:i[2].toLowerCase(),text:i[3].trim()},e.push(r);continue}if(/^#{1,6}\s/.test(o)||/^\s*[-*]\s/.test(o)||!o.trim()){r=null;continue}r&&(r.text=`${r.text}
13
+ ${o.trim()}`.trim())}let n={};for(let o of e)n[o.id]=o;return{items:e,byId:n}}function m$(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 d$,p$,kd=x(()=>{"use strict";d$=["done","deviated","partial","dropped"],p$=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*[—:-]?\s*(done|deviated|partial|dropped)\b\s*[—:-]?\s*(.*)$/i});var bd=x(()=>{"use strict"});var $d=x(()=>{"use strict"});var vd=x(()=>{"use strict"});function Xa(t){return`codepipe-host-${t}`}function h$(t){let e=t.filter(r=>r!=="self-hosted");return`runs-on: [self-hosted${e.length?", "+e.join(", "):""}]`}var xd=x(()=>{"use strict"});function g$(t,e){return(t&&t.includes("<TASK_ID>")?t:Sd).replace(/<TASK_ID>/g,e.toLowerCase())}function y$(t,e){if(t)return`${t.replace(/\/+$/,"")}/issue/${encodeURIComponent(e)}`}function so(t){return!(!t||t.length>250||!/^[A-Za-z0-9._/-]+$/.test(t)||/^[-/.]/.test(t)||/[/.]$/.test(t)||t.endsWith(".lock")||t.includes("..")||t.includes("//")||t.includes("/."))}function Ja(t){if(!t||typeof t!="object")return null;let e=t,r=typeof e.owner=="string"?e.owner.trim():"",n=typeof e.repo=="string"?e.repo.trim():typeof e.repoName=="string"?e.repoName.trim():"",o=typeof e.host=="string"?e.host.trim():"";return!r||!n||o!=="github"&&o!=="gitlab"&&o!=="bitbucket"?null:{host:o,owner:r,repoName:n}}function Za(t){if(!t.mirror)return t;let{mirror:e,...r}=t;return{...r,host:e.host,owner:e.owner,repoName:e.repoName}}function Et(t){return`${t}${Ed}`}var Sd,Yt,Ed,Td=x(()=>{"use strict";Sd="codepipe/<TASK_ID>";Yt=/^[a-z][a-z0-9-]{1,30}$/,Ed="-codepipe-ctx"});function w$(t,e){return`${t}:${e}`}var Rd=x(()=>{"use strict"});function Id(t){let e=(t??"").trim();return/^pr_closed_without_merge\b/.test(e)?"blocked":/^(merge_failed|close_failed)\b/.test(e)||/^chain_base_changed\b/.test(e)||/^write action apply_delivery failed: .*hit conflicts/.test(e)?"conflict":/^(build_failed|ci_failed)\b/.test(e)?"loop_exhausted":"error"}function k$(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.to==="NEEDS_MANUAL")return r}return null}function b$(t,e){if(t==="AWAITING_ANSWER")return{kind:"question"};if(t==="NEEDS_MANUAL"){let n=k$(e)?.reason,o={kind:Id(n)};return n&&(o.reason=n),o}}var Cd=x(()=>{"use strict"});function Sr(t){for(let e of Pd){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var Pd,Ad=x(()=>{"use strict";Pd=[{name:"rework",pattern:/^@(?:codepipe|devpipe)\s+rework:\s*(.+)$/im,description:"Send the task back to ANALYZING with a new instruction.",hasArg:!0},{name:"approve",pattern:/^@(?:codepipe|devpipe)\s+approve\s*$/im,description:"Merge every PR for this task (TRACKING only)."},{name:"reject",pattern:/^@(?:codepipe|devpipe)\s+reject(?::\s*(.+))?\s*$/im,description:"Abandon this task: close any open PR(s) and move it to DONE (reason rejected_and_closed). Valid from any non-terminal phase; from early phases it just skips the task.",hasArg:!0},{name:"merge",pattern:/^@(?:codepipe|devpipe)\s+merge\s*$/im,description:"Merge the task branch into the default branch without a PR (direct apply path, apply.pull_request=false; TRACKING only)."},{name:"rebase",pattern:/^@(?:codepipe|devpipe)\s+rebase\s*$/im,description:"Re-apply the patch on top of the latest base branch and force-push. Use after a PR merge conflict or APPLYING failure."},{name:"update",pattern:/^@(?:codepipe|devpipe)\s+update(?::\s*(.+))?\s*$/im,description:"Update a conflicting PR: resolve conflicts against the current base branch (TRACKING only). Optional `: <instruction>` is forwarded to the agent.",hasArg:!0},{name:"apply",pattern:/^@(?:codepipe|devpipe)\s+apply:\s*(local|auto)\s*$/im,description:"Override apply mode for this task: local (you apply by hand) or auto.",hasArg:!0},{name:"fix",pattern:/^@(?:codepipe|devpipe)\s+fix\s*$/im,description:"Fix the external review remarks on the developer's branch (waiting-for-fix state only)."}]});var _d=x(()=>{"use strict"});function jd(t){let e=Math.max(1,Math.round(t));if(e<60)return`${e}s`;let r=Math.round(e/60);if(r<60)return`${r}m`;let n=Math.round(r/60);return n<24?`${n}h`:`${Math.round(n/24)}d`}function $$(t,e=Date.now()){return`${jd((e-t)/1e3)} ago`}function v$(t){let e=Math.floor(t/86400),r=Math.floor(t%86400/3600),n=Math.floor(t%3600/60);return e>0?`${e}d ${r}h`:r>0?`${r}h ${n}m`:`${n}m`}var Nd=x(()=>{"use strict"});var Od=x(()=>{"use strict"});function Ld(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function ec(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=Ld(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Er.test(r))return r;let n=Ld(t);return Er.test(n)?n:ci}function tc(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 Qr(t){return`tasks/${t}/issue.yaml`}var Qa,ao,ci,Er,li,x$,co,Zr,Md=x(()=>{"use strict";Qa=["bug","feature","epic"],ao="feature",ci="TASK",Er=/^[A-Z][A-Z0-9]{1,9}$/;li={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},x$=li.backlog,co="tracker/config.yaml",Zr="tracker/counter"});function lo(t){let e=t.split(`
14
14
  `),r=e.indexOf("---");if(r<0)return;let n=e.slice(r+1),o=n.lastIndexOf("## Attachments");o>=0&&n.slice(o+1).every(c=>c.trim()===""||/^- \[[^\]]*\]\(attachments\/[^)]*\)$/.test(c.trim()))&&(n=n.slice(0,o));let i=n.join(`
15
- `).trim();if(!(!i||i==="_(no description)_"))return i}function v$(t){return`{{ancestorExcerpt:${t}}}`}var ui,Md=x(()=>{"use strict";ui=/\{\{ancestorExcerpt:([^}]+)\}\}/g});var x$,Dd=x(()=>{"use strict";x$="youtrack"});function Tr(t){let e=t.match(/^git@([^:/]+):/);if(e)return e[1]??null;let r=t.match(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)/);if(r)return r[1]??null;let n=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return n?n[1]??null:null}function uo(t){switch(t){case en.gitlab:return"oauth2";case en.bitbucket:return"x-token-auth";default:return"x-access-token"}}var en,Dt,Ud=x(()=>{"use strict";en={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Dt="x-bitbucket-api-token-auth"});var Bd=x(()=>{"use strict"});var Fd=x(()=>{"use strict";Dd();Ud();Bd()});var Gd={};Fe(Gd,{ACTION_ID_RE:()=>Ta,ACTION_STEP_DEFAULT_TIMEOUT_SEC:()=>Ia,ALL_JOB_ROLES:()=>ba,ALL_MODEL_ROLE_KEYS:()=>xa,ANALYSIS_MAX_DRAFTS:()=>tc,ANCESTOR_EXCERPT_RE:()=>ui,ANCESTOR_EXCERPT_TOKEN:()=>v$,ANNOTATION_MAX_PER_TASK:()=>pa,BACKFILL_MAX_DRAFTS:()=>S$,BITBUCKET_API_TOKEN_GIT_USER:()=>Dt,BUILD_DISCOVERY:()=>zu,COCHANGE_DEFAULTS:()=>nt,CODEPIPE_COMMANDS:()=>Cd,CODE_REVIEW_VERIFY:()=>Vu,COMMIT_STYLE_MAX_LENGTH:()=>Oa,CONTEXT_PACK_DECAY:()=>ma,CONTEXT_PACK_DEFAULTS:()=>$r,CONTEXT_REPO_SUFFIX:()=>Sd,CONTEXT_STAMP_FILE:()=>yt,CONTEXT_TEMPLATE_CHANGELOG:()=>ea,CONTEXT_TEMPLATE_VERSION:()=>Au,COUNCIL_MAX_ANSWER:()=>VA,DEFAULT_BRANCH_PATTERN:()=>xd,DEFAULT_HUB_URL:()=>ht,DEFAULT_INTERNAL_ISSUE_TYPE:()=>ao,DEFAULT_INTERNAL_TRACKER_PREFIX:()=>ci,DEFAULT_LLM_PROVIDER:()=>Xe,DEFAULT_REGIMEN_ALIASES:()=>Qu,DEFAULT_TRACKER_PROVIDER:()=>x$,ENV_NAME_RE:()=>Je,FALLBACK_MODEL:()=>Ju,GIT_HOST_DOMAINS:()=>en,INTERNAL_ISSUE_TYPES:()=>Za,INTERNAL_TRACKER_CONFIG_PATH:()=>co,INTERNAL_TRACKER_COUNTER_PATH:()=>Zr,INTERNAL_TRACKER_DEFAULT_STATUS:()=>$$,INTERNAL_TRACKER_PREFIX_RE:()=>Er,INTERNAL_TRACKER_STATUSES:()=>li,LANE_PHASES:()=>_b,LANE_SEGMENTS:()=>ka,LANGUAGE_AUTO:()=>xe,LANGUAGE_SUGGESTIONS:()=>Jr,LANGUAGE_VALUE_MAX_LENGTH:()=>io,LEGACY_CONTEXT_STAMP_FILE:()=>qr,LLM_PROVIDER_SUGGESTIONS:()=>va,MIN_SUPPORTED_PROTOCOL:()=>Iu,MODEL_ALIAS_SUGGESTIONS:()=>ii,MODEL_DERIVED_DIR:()=>Eb,MODEL_DERIVED_INDEX_PATH:()=>ei,MODEL_DIR:()=>vb,MODEL_EDGE_KINDS:()=>ua,MODEL_ENTITY_ID_RE:()=>Ou,MODEL_FACTS_DIR:()=>Sb,MODEL_FAMILY_PREFERENCE:()=>Zu,MODEL_HAIKU:()=>oi,MODEL_LEVELS:()=>Nu,MODEL_OPUS:()=>Ae,MODEL_README_PATH:()=>xb,MODEL_RELATES_PATH:()=>wr,MODEL_SEARCH_MAX_LIMIT:()=>fa,MODEL_SEARCH_MAX_ROWS:()=>Rb,MODEL_SEARCH_ROW_TEXT_MAX:()=>ri,MODEL_SONNET:()=>Xr,MODEL_SUB_ROLES:()=>Xu,OBSERVER_MAX_DECISION:()=>qA,OBSERVER_MAX_SUMMARY:()=>YA,OFFICIAL_MARKETPLACES:()=>dd,PHASES:()=>wa,PIPELINE_COLUMNS:()=>Hu,PLANNING_LANE_MAX_JOBS:()=>Lb,PLANNING_ROLES:()=>qu,PLATFORM_VERSION:()=>Ve,PROJECT_ID_RE:()=>Yt,PROJECT_LANGUAGE_SECTIONS:()=>oo,PROJECT_MODEL_FORMAT_VERSION:()=>Oe,PROJECT_SETTINGS_MANIFEST:()=>od,PROMPT_ROLES:()=>ld,PROTOCOL_VERSION:()=>gt,RECOMMENDED_ROLE_MODELS:()=>no,RELATES_MIN_OVERLAP:()=>da,ROLE_MAX_DESCRIPTION:()=>FA,ROLE_MAX_REFS:()=>BA,ROLE_NAME_RE:()=>Da,ROLE_SCENARIOS:()=>ai,SKILL_MAX_DESCRIPTION:()=>HA,SKILL_NAME_RE:()=>Ha,SOLUTION_STATUSES:()=>l$,STRING_MAP_MAX_ENTRIES:()=>ja,STRING_MAP_MAX_VALUE_LENGTH:()=>Na,additionsSince:()=>ra,ago:()=>k$,attentionFor:()=>w$,autoLanguageConfig:()=>rd,autoModelDefault:()=>Sa,canonicalizeModelEdgeSheet:()=>Lu,canonicalizeModelIdentityTable:()=>Du,canonicalizeModelShard:()=>Mu,canonicalizeModelTaskEvent:()=>Uu,changesSince:()=>na,classifyAttentionReason:()=>Rd,compilePlanRework:()=>a$,contextRepoName:()=>St,deserializeModelConfig:()=>Fb,emptyModelConfig:()=>Vr,enabledPluginsSetting:()=>e$,extractLanguageConfig:()=>qb,extractTaskMdBody:()=>lo,findSettingField:()=>id,firstFreeInternalTrackerPrefix:()=>ec,flattenSettingFields:()=>La,fmtDuration:()=>_d,fmtUptime:()=>b$,ghRunnerHostLabel:()=>Va,ghRunnerRunsOnSnippet:()=>f$,gitCloneUrlDomain:()=>Tr,httpsTokenUser:()=>uo,internalIssueYamlPath:()=>Qr,isAllAutoLanguage:()=>Yb,isAutoLanguage:()=>nd,isBodyEditFrozen:()=>Ab,isModelEntityId:()=>ti,isPromptRole:()=>Ga,isProtocolCompatible:()=>Jn,isReservedEnvName:()=>Mt,isTerminalPhase:()=>Pb,isValidBranchName:()=>so,jobLane:()=>Ob,laneSegmentForPhase:()=>jb,makeTaskId:()=>g$,mergeRoles:()=>Ba,mergeSkills:()=>qa,mismatchedIds:()=>s$,modelAnnotationPath:()=>sa,modelComponentSlug:()=>ju,modelCorrelatesPath:()=>aa,modelEventPath:()=>kr,modelIdentityPath:()=>eo,modelNodeKey:()=>we,modelShardNeedsRebuild:()=>Ib,modelStructureShardPath:()=>la,modelTaskNodeKey:()=>Ee,modelTouchedPath:()=>ca,parseActionDefinition:()=>Ca,parseCodepipeCommand:()=>Sr,parseContextStamp:()=>ta,parseMarketplaceSource:()=>pd,parseMarketplaces:()=>Zb,parseModelConfig:()=>Ub,parseModelNodeKey:()=>re,parsePlanItems:()=>Ya,parseRepoMirror:()=>Xa,parseSolutionItems:()=>d$,pipelineColumnForPhase:()=>Nb,pipelineRepoSpec:()=>Ja,prescribedSkills:()=>za,promptOverridePath:()=>Ka,renderContextStamp:()=>Zn,resolveBranchName:()=>m$,resolveModelForRole:()=>Mb,resolveProvider:()=>Db,rolesForScenario:()=>Fa,serializeModelConfig:()=>Bb,serializeModelEdgeSheet:()=>br,serializeModelIdentityTable:()=>ga,serializeModelShard:()=>ha,serializeModelTaskEvent:()=>zr,serializeModelYaml:()=>vr,solutionCoverage:()=>p$,suggestInternalTrackerPrefix:()=>Qa,validateActionInput:()=>Pa,validateCouncilVerdict:()=>r$,validateModelEdgeSheet:()=>to,validateModelIdentityTable:()=>ro,validateModelShard:()=>Ot,validateModelTaskEvent:()=>Lt,validateObserverPlan:()=>t$,validateRoleDefinition:()=>Ua,validateSettingEdit:()=>Ma,validateSkill:()=>Wa,youtrackIssueUrl:()=>h$,zeroUsage:()=>qt});var tc,S$,B=x(()=>{"use strict";Cu();Pu();_u();ya();Ku();Wu();$a();Ea();sd();_a();Aa();cd();ud();fd();hd();gd();yd();wd();kd();bd();$d();vd();Ed();Td();Id();Pd();Ad();jd();Nd();Ld();Md();Fd();tc=20,S$=15});function Q(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Ge=x(()=>{"use strict"});import{existsSync as E$,readFileSync as T$,readdirSync as R$}from"node:fs";import{dirname as I$,join as rc}from"node:path";import{parse as C$}from"yaml";function P$(t=process.cwd()){let e=t;for(;;){if(E$(rc(e,ot,"project.yaml")))return e;let r=I$(e);if(r===e)return null;e=r}}function A$(t){return rc(t,ot)}function _e(t=process.cwd()){let e=P$(t);if(!e)return null;let r=A$(e),n=_$(T$(rc(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function Kd(t,e,r){return R$(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 tn(t,e=process.cwd()){try{let r=_e(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function _$(t){let e=C$(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),n=String(e.name??r),o=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of o){if(!s||typeof s!="object")continue;let a=s,c=String(a.repo??a.repoName??""),l=String(a.name??c);if(!l||!c)continue;let u=a.host,p=u==="bitbucket"?"bitbucket":u==="gitlab"?"gitlab":"github",d=Xa(a.mirror);i.push({name:l,host:p,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l),...d?{mirror:d}:{}})}return{projectId:r,name:n,repos:i}}function di(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}var ot,it=x(()=>{"use strict";B();ot=".codepipe"});import{homedir as Hd}from"node:os";import{mkdirSync as j$,readFileSync as N$,writeFileSync as O$,existsSync as nc}from"node:fs";import{dirname as qd,join as pi,resolve as L$}from"node:path";import{fileURLToPath as M$}from"node:url";function Yd(t){let e=pi(Wd,".env");if(nc(e)&&process.loadEnvFile(e),t){let r=pi(Wd,"profiles",t,".env");nc(r)&&process.loadEnvFile(r)}}function rn(t){let e=Q("CONFIG");return e||(t?pi(Hd(),".codepipe","profiles",t,"config.json"):pi(Hd(),".codepipe","config.json"))}function kt(t){let e=rn(t);if(!nc(e))return null;let r=N$(e,"utf-8");return JSON.parse(r)}function Ut(t,e){let r=rn(e);j$(qd(r),{recursive:!0}),O$(r,JSON.stringify(t,null,2)+`
16
- `,{mode:384})}function nn(t){if(t)return{cfg:st(t),profile:t};let e;try{e=_e()?.spec.projectId||void 0}catch{}if(e){let r=kt(e);if(r)return console.log(`[profile] ${e} \u2014 resolved from this folder's workspace`),{cfg:r,profile:e};console.error(`this folder is the workspace of project '${e}', but that CLI profile is not initialised on this machine \u2014 run \`codepipe init\` here (or pass --profile).`),process.exit(1)}return{cfg:st(void 0),profile:void 0}}function st(t){let e=kt(t);if(!e){let r=t?`codepipe init --profile ${t} --hub <url> --token <token> --project ${t}`:"codepipe init --hub <url> --token <token> --project <id>";console.error(t?`CLI profile '${t}' is not initialised. run \`${r}\` first.`:`CLI is not initialised. run \`${r}\` first.`),process.exit(1)}return e.projectId||(console.error(`config at ${rn(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var Wd,Ke=x(()=>{"use strict";Ge();it();Wd=L$(qd(M$(import.meta.url)),"..")});import{homedir as zd}from"node:os";import{existsSync as Vd,mkdirSync as Xd,readFileSync as Jd,writeFileSync as Zd}from"node:fs";import{dirname as Qd,join as ep}from"node:path";function tp(t,e,r){let n=Y(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},ue(n)}function rp(t,e){let r=Y(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],ue(r),!0)}function np(t){return Object.keys(Y(t)?.secrets??{}).sort()}function fi(t,e,r){let n=Y(t);if(!n)return"mismatch";let o=n.sandboxPins??{},i=o[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(o[e]=r,n.sandboxPins=o,ue(n),"pinned")}function op(t,e){let r=Y(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],ue(r),!0):!1}function Et(t){return ep(zd(),".codepipe","secrets",`${t}.json`)}function Y(t){let e=Et(t);return Vd(e)?JSON.parse(Jd(e,"utf-8")):null}function ue(t){let e=Et(t.projectId);Xd(Qd(e),{recursive:!0}),Zd(e,JSON.stringify(t,null,2)+`
17
- `,{mode:384})}function mi(){return ep(zd(),".codepipe","shared.json")}function oc(){let t=mi();return Vd(t)?JSON.parse(Jd(t,"utf-8")):null}function ip(t){let e=mi();Xd(Qd(e),{recursive:!0}),Zd(e,JSON.stringify(t,null,2)+`
18
- `,{mode:384})}function on(t){let e=Y(t)?.claude?.oauthToken;return e||oc()?.claude?.oauthToken}function po(t){let e={GH_TOKEN:t.github?.token,BITBUCKET_EMAIL:t.bitbucket?.email,BITBUCKET_API_TOKEN:t.bitbucket?.apiToken,GITLAB_TOKEN:t.gitlab?.token,YOUTRACK_URL:t.youtrack?.url,YOUTRACK_TOKEN:t.youtrack?.token};for(let r of ic){let n=e[r];n&&!process.env[r]&&(process.env[r]=n)}}function sn(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var ic,me=x(()=>{"use strict";ic=["GH_TOKEN","BITBUCKET_EMAIL","BITBUCKET_API_TOKEN","GITLAB_TOKEN","YOUTRACK_URL","YOUTRACK_TOKEN"]});import{appendFileSync as D$,existsSync as ap,mkdirSync as U$,renameSync as cp,statSync as B$,unlinkSync as F$}from"node:fs";import{Writable as G$}from"node:stream";import{join as K$}from"node:path";function hi(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=H$(process.env[`${t}_MAX_BYTES`]??String(lp.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):lp.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function H$(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 gi(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(W$(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 W$(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:q$(o)).join(" ");return`${r} ${t} ${n}`}function q$(t){try{return JSON.stringify(t)}catch{return String(t)}}var lp,an,sc=x(()=>{"use strict";lp={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},an=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&U$(e.dir,{recursive:!0}),this.currentPath=K$(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
15
+ `).trim();if(!(!i||i==="_(no description)_"))return i}function S$(t){return`{{ancestorExcerpt:${t}}}`}var ui,Dd=x(()=>{"use strict";ui=/\{\{ancestorExcerpt:([^}]+)\}\}/g});var E$,Ud=x(()=>{"use strict";E$="youtrack"});function Tr(t){let e=t.match(/^git@([^:/]+):/);if(e)return e[1]??null;let r=t.match(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)/);if(r)return r[1]??null;let n=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return n?n[1]??null:null}function uo(t){switch(t){case en.gitlab:return"oauth2";case en.bitbucket:return"x-token-auth";default:return"x-access-token"}}var en,Dt,Bd=x(()=>{"use strict";en={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Dt="x-bitbucket-api-token-auth"});var Fd=x(()=>{"use strict"});var Gd=x(()=>{"use strict";Ud();Bd();Fd()});var Kd={};Fe(Kd,{ACTION_ID_RE:()=>Ra,ACTION_STEP_DEFAULT_TIMEOUT_SEC:()=>Ca,ALL_JOB_ROLES:()=>$a,ALL_MODEL_ROLE_KEYS:()=>Sa,ANALYSIS_MAX_DRAFTS:()=>rc,ANCESTOR_EXCERPT_RE:()=>ui,ANCESTOR_EXCERPT_TOKEN:()=>S$,ANNOTATION_MAX_PER_TASK:()=>fa,BACKFILL_MAX_DRAFTS:()=>T$,BITBUCKET_API_TOKEN_GIT_USER:()=>Dt,BUILD_DISCOVERY:()=>Vu,COCHANGE_DEFAULTS:()=>ot,CODEPIPE_COMMANDS:()=>Pd,CODE_REVIEW_VERIFY:()=>Xu,COMMIT_STYLE_MAX_LENGTH:()=>La,CONTEXT_PACK_DECAY:()=>ha,CONTEXT_PACK_DEFAULTS:()=>$r,CONTEXT_REPO_SUFFIX:()=>Ed,CONTEXT_STAMP_FILE:()=>yt,CONTEXT_TEMPLATE_CHANGELOG:()=>ta,CONTEXT_TEMPLATE_VERSION:()=>_u,COUNCIL_MAX_ANSWER:()=>e_,DEFAULT_BRANCH_PATTERN:()=>Sd,DEFAULT_HUB_URL:()=>ht,DEFAULT_INTERNAL_ISSUE_TYPE:()=>ao,DEFAULT_INTERNAL_TRACKER_PREFIX:()=>ci,DEFAULT_LLM_PROVIDER:()=>Xe,DEFAULT_REGIMEN_ALIASES:()=>ed,DEFAULT_TRACKER_PROVIDER:()=>E$,ENV_NAME_RE:()=>Je,FALLBACK_MODEL:()=>Zu,GIT_HOST_DOMAINS:()=>en,INTERNAL_ISSUE_TYPES:()=>Qa,INTERNAL_TRACKER_CONFIG_PATH:()=>co,INTERNAL_TRACKER_COUNTER_PATH:()=>Zr,INTERNAL_TRACKER_DEFAULT_STATUS:()=>x$,INTERNAL_TRACKER_PREFIX_RE:()=>Er,INTERNAL_TRACKER_STATUSES:()=>li,LANE_PHASES:()=>Nb,LANE_SEGMENTS:()=>ba,LANGUAGE_AUTO:()=>ve,LANGUAGE_SUGGESTIONS:()=>Jr,LANGUAGE_VALUE_MAX_LENGTH:()=>io,LEGACY_CONTEXT_STAMP_FILE:()=>qr,LLM_PROVIDER_SUGGESTIONS:()=>xa,MIN_SUPPORTED_PROTOCOL:()=>Cu,MODEL_ALIAS_SUGGESTIONS:()=>ii,MODEL_DERIVED_DIR:()=>Rb,MODEL_DERIVED_INDEX_PATH:()=>ei,MODEL_DIR:()=>Sb,MODEL_EDGE_KINDS:()=>da,MODEL_ENTITY_ID_RE:()=>Lu,MODEL_FACTS_DIR:()=>Tb,MODEL_FAMILY_PREFERENCE:()=>Qu,MODEL_HAIKU:()=>oi,MODEL_LEVELS:()=>Ou,MODEL_OPUS:()=>Pe,MODEL_README_PATH:()=>Eb,MODEL_RELATES_PATH:()=>wr,MODEL_SEARCH_MAX_LIMIT:()=>ma,MODEL_SEARCH_MAX_ROWS:()=>Cb,MODEL_SEARCH_ROW_TEXT_MAX:()=>ri,MODEL_SONNET:()=>Xr,MODEL_SUB_ROLES:()=>Ju,OBSERVER_MAX_DECISION:()=>JA,OBSERVER_MAX_SUMMARY:()=>ZA,OFFICIAL_MARKETPLACES:()=>pd,PHASES:()=>ka,PIPELINE_COLUMNS:()=>Wu,PLANNING_LANE_MAX_JOBS:()=>Db,PLANNING_ROLES:()=>Yu,PLATFORM_VERSION:()=>Ve,PROJECT_ID_RE:()=>Yt,PROJECT_LANGUAGE_SECTIONS:()=>oo,PROJECT_MODEL_FORMAT_VERSION:()=>Le,PROJECT_SETTINGS_MANIFEST:()=>id,PROMPT_ROLES:()=>ud,PROTOCOL_VERSION:()=>gt,RECOMMENDED_ROLE_MODELS:()=>no,RELATES_MIN_OVERLAP:()=>pa,ROLE_MAX_DESCRIPTION:()=>qA,ROLE_MAX_REFS:()=>WA,ROLE_NAME_RE:()=>Ua,ROLE_SCENARIOS:()=>ai,SKILL_MAX_DESCRIPTION:()=>VA,SKILL_NAME_RE:()=>Wa,SOLUTION_STATUSES:()=>d$,STRING_MAP_MAX_ENTRIES:()=>Na,STRING_MAP_MAX_VALUE_LENGTH:()=>Oa,additionsSince:()=>na,ago:()=>$$,attentionFor:()=>b$,autoLanguageConfig:()=>nd,autoModelDefault:()=>Ea,canonicalizeModelEdgeSheet:()=>Mu,canonicalizeModelIdentityTable:()=>Uu,canonicalizeModelShard:()=>Du,canonicalizeModelTaskEvent:()=>Bu,changesSince:()=>oa,classifyAttentionReason:()=>Id,compilePlanRework:()=>l$,contextRepoName:()=>Et,deserializeModelConfig:()=>Kb,emptyModelConfig:()=>Vr,enabledPluginsSetting:()=>r$,extractLanguageConfig:()=>zb,extractTaskMdBody:()=>lo,findSettingField:()=>sd,firstFreeInternalTrackerPrefix:()=>tc,flattenSettingFields:()=>Ma,fmtDuration:()=>jd,fmtUptime:()=>v$,ghRunnerHostLabel:()=>Xa,ghRunnerRunsOnSnippet:()=>h$,gitCloneUrlDomain:()=>Tr,httpsTokenUser:()=>uo,internalIssueYamlPath:()=>Qr,isAllAutoLanguage:()=>Vb,isAutoLanguage:()=>od,isBodyEditFrozen:()=>jb,isModelEntityId:()=>ti,isPromptRole:()=>Ka,isProtocolCompatible:()=>Jn,isReservedEnvName:()=>Mt,isTerminalPhase:()=>_b,isValidBranchName:()=>so,jobLane:()=>Mb,laneSegmentForPhase:()=>Ob,makeTaskId:()=>w$,mergeRoles:()=>Fa,mergeSkills:()=>Ya,mismatchedIds:()=>c$,modelAnnotationPath:()=>aa,modelComponentSlug:()=>Nu,modelCorrelatesPath:()=>ca,modelEventPath:()=>kr,modelIdentityPath:()=>eo,modelNodeKey:()=>ye,modelShardNeedsRebuild:()=>Pb,modelStructureShardPath:()=>ua,modelTaskNodeKey:()=>Se,modelTouchedPath:()=>la,parseActionDefinition:()=>Pa,parseCodepipeCommand:()=>Sr,parseContextStamp:()=>ra,parseMarketplaceSource:()=>fd,parseMarketplaces:()=>e$,parseModelConfig:()=>Fb,parseModelNodeKey:()=>re,parsePlanItems:()=>za,parseRepoMirror:()=>Ja,parseSolutionItems:()=>f$,pipelineColumnForPhase:()=>Lb,pipelineRepoSpec:()=>Za,prescribedSkills:()=>Va,promptOverridePath:()=>Ha,renderContextStamp:()=>Zn,resolveBranchName:()=>g$,resolveModelForRole:()=>Ub,resolveProvider:()=>Bb,rolesForScenario:()=>Ga,serializeModelConfig:()=>Gb,serializeModelEdgeSheet:()=>br,serializeModelIdentityTable:()=>ya,serializeModelShard:()=>ga,serializeModelTaskEvent:()=>zr,serializeModelYaml:()=>vr,solutionCoverage:()=>m$,suggestInternalTrackerPrefix:()=>ec,validateActionInput:()=>Aa,validateCouncilVerdict:()=>o$,validateModelEdgeSheet:()=>to,validateModelIdentityTable:()=>ro,validateModelShard:()=>Ot,validateModelTaskEvent:()=>Lt,validateObserverPlan:()=>n$,validateRoleDefinition:()=>Ba,validateSettingEdit:()=>Da,validateSkill:()=>qa,youtrackIssueUrl:()=>y$,zeroUsage:()=>qt});var rc,T$,B=x(()=>{"use strict";Pu();Au();ju();wa();Hu();qu();va();Ta();ad();ja();_a();ld();dd();md();gd();yd();wd();kd();bd();$d();vd();xd();Td();Rd();Cd();Ad();_d();Nd();Od();Md();Dd();Gd();rc=20,T$=15});function Q(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Ge=x(()=>{"use strict"});import{existsSync as R$,readFileSync as I$,readdirSync as C$}from"node:fs";import{dirname as P$,join as nc}from"node:path";import{parse as A$}from"yaml";function _$(t=process.cwd()){let e=t;for(;;){if(R$(nc(e,it,"project.yaml")))return e;let r=P$(e);if(r===e)return null;e=r}}function j$(t){return nc(t,it)}function Ae(t=process.cwd()){let e=_$(t);if(!e)return null;let r=j$(e),n=N$(I$(nc(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function Hd(t,e,r){return C$(t).filter(o=>o!==".DS_Store").length===0?!0:e?r.some(o=>o.host===e.host&&o.owner===e.owner&&o.repoName===e.repoName):!1}function tn(t,e=process.cwd()){try{let r=Ae(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function N$(t){let e=A$(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),n=String(e.name??r),o=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of o){if(!s||typeof s!="object")continue;let a=s,c=String(a.repo??a.repoName??""),l=String(a.name??c);if(!l||!c)continue;let u=a.host,p=u==="bitbucket"?"bitbucket":u==="gitlab"?"gitlab":"github",d=Ja(a.mirror);i.push({name:l,host:p,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l),...d?{mirror:d}:{}})}return{projectId:r,name:n,repos:i}}function Wd(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}var it,kt=x(()=>{"use strict";B();it=".codepipe"});import{homedir as qd}from"node:os";import{mkdirSync as O$,readFileSync as L$,writeFileSync as M$,existsSync as oc}from"node:fs";import{dirname as zd,join as di,resolve as D$}from"node:path";import{fileURLToPath as U$}from"node:url";function Vd(t){let e=di(Yd,".env");if(oc(e)&&process.loadEnvFile(e),t){let r=di(Yd,"profiles",t,".env");oc(r)&&process.loadEnvFile(r)}}function rn(t){let e=Q("CONFIG");return e||(t?di(qd(),".codepipe","profiles",t,"config.json"):di(qd(),".codepipe","config.json"))}function bt(t){let e=rn(t);if(!oc(e))return null;let r=L$(e,"utf-8");return JSON.parse(r)}function Ut(t,e){let r=rn(e);O$(zd(r),{recursive:!0}),M$(r,JSON.stringify(t,null,2)+`
16
+ `,{mode:384})}function nn(t){if(t)return{cfg:st(t),profile:t};let e;try{e=Ae()?.spec.projectId||void 0}catch{}if(e){let r=bt(e);if(r)return console.log(`[profile] ${e} \u2014 resolved from this folder's workspace`),{cfg:r,profile:e};console.error(`this folder is the workspace of project '${e}', but that CLI profile is not initialised on this machine \u2014 run \`codepipe init\` here (or pass --profile).`),process.exit(1)}return{cfg:st(void 0),profile:void 0}}function st(t){let e=bt(t);if(!e){let r=t?`codepipe init --profile ${t} --hub <url> --token <token> --project ${t}`:"codepipe init --hub <url> --token <token> --project <id>";console.error(t?`CLI profile '${t}' is not initialised. run \`${r}\` first.`:`CLI is not initialised. run \`${r}\` first.`),process.exit(1)}return e.projectId||(console.error(`config at ${rn(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var Yd,Ke=x(()=>{"use strict";Ge();kt();Yd=D$(zd(U$(import.meta.url)),"..")});import{homedir as Xd}from"node:os";import{existsSync as Jd,mkdirSync as Zd,readFileSync as Qd,writeFileSync as ep}from"node:fs";import{dirname as tp,join as rp}from"node:path";function np(t,e,r){let n=Y(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},ce(n)}function op(t,e){let r=Y(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],ce(r),!0)}function ip(t){return Object.keys(Y(t)?.secrets??{}).sort()}function pi(t,e,r){let n=Y(t);if(!n)return"mismatch";let o=n.sandboxPins??{},i=o[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(o[e]=r,n.sandboxPins=o,ce(n),"pinned")}function sp(t,e){let r=Y(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],ce(r),!0):!1}function Tt(t){return rp(Xd(),".codepipe","secrets",`${t}.json`)}function Y(t){let e=Tt(t);return Jd(e)?JSON.parse(Qd(e,"utf-8")):null}function ce(t){let e=Tt(t.projectId);Zd(tp(e),{recursive:!0}),ep(e,JSON.stringify(t,null,2)+`
17
+ `,{mode:384})}function fi(){return rp(Xd(),".codepipe","shared.json")}function ic(){let t=fi();return Jd(t)?JSON.parse(Qd(t,"utf-8")):null}function ap(t){let e=fi();Zd(tp(e),{recursive:!0}),ep(e,JSON.stringify(t,null,2)+`
18
+ `,{mode:384})}function on(t){let e=Y(t)?.claude?.oauthToken;return e||ic()?.claude?.oauthToken}function po(t){let e={GH_TOKEN:t.github?.token,BITBUCKET_EMAIL:t.bitbucket?.email,BITBUCKET_API_TOKEN:t.bitbucket?.apiToken,GITLAB_TOKEN:t.gitlab?.token,YOUTRACK_URL:t.youtrack?.url,YOUTRACK_TOKEN:t.youtrack?.token};for(let r of sc){let n=e[r];n&&!process.env[r]&&(process.env[r]=n)}}function sn(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var sc,fe=x(()=>{"use strict";sc=["GH_TOKEN","BITBUCKET_EMAIL","BITBUCKET_API_TOKEN","GITLAB_TOKEN","YOUTRACK_URL","YOUTRACK_TOKEN"]});import{appendFileSync as B$,existsSync as lp,mkdirSync as F$,renameSync as up,statSync as G$,unlinkSync as K$}from"node:fs";import{Writable as H$}from"node:stream";import{join as W$}from"node:path";function mi(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=q$(process.env[`${t}_MAX_BYTES`]??String(dp.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):dp.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function q$(t){let e=t.trim().match(/^(\d+)\s*([kmg]?)b?$/i);if(!e)return Number(t)||0;let r=Number(e[1]),n=(e[2]??"").toLowerCase();return n==="g"?r*1024**3:n==="m"?r*1024**2:n==="k"?r*1024:r}function hi(t){let e={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},r=(n,o)=>(...i)=>{n(...i);try{t.writeLine(Y$(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 Y$(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:z$(o)).join(" ");return`${r} ${t} ${n}`}function z$(t){try{return JSON.stringify(t)}catch{return String(t)}}var dp,an,ac=x(()=>{"use strict";dp={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},an=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&F$(e.dir,{recursive:!0}),this.currentPath=W$(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
19
19
  `)?e:e+`
20
- `;D$(this.currentPath,r,"utf-8")}asWritable(){return new G$({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||!ap(this.currentPath)||B$(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;ap(n)&&(r>=this.cfg.maxFiles?F$(n):cp(n,`${this.currentPath}.${r+1}`))}cp(this.currentPath,`${this.currentPath}.1`)}}}});function wi(t){return t===429||t>=500}function pp(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
21
- `+t.slice(t.length-e)}async function zt(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),yi);try{let i;try{i=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new at(`cannot reach api.github.com (${l instanceof Error?l.message:String(l)})`)}if(i.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(wi(i.status))throw new at(`api.github.com \u2192 ${i.status} ${i.statusText}`);if(!i.ok)throw new Error(`GitHub \u2192 ${i.status} ${i.statusText}`);let a=(await i.json()).login??"ok",c=i.headers.get("x-oauth-scopes");if(c!==null&&e&&!c.split(",").map(u=>u.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${c||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let l;try{let u=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});u.ok&&(l=(await u.json()).type)}catch{}if(l==="Organization"){let u=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});if(u.status===403)throw new Error(`token cannot access org "${e.owner}" (403) \u2014 for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens; for classic PATs: verify 'repo' or 'admin:org' scope`);if(u.status===404)throw new Error(`org "${e.owner}" not found or not visible to this token \u2014 check the org name; for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens`);if(!u.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${u.status} ${u.statusText}`)}}return a}finally{clearTimeout(o)}}async function ki(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),yi);try{let s;try{s=await fetch(n,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},signal:o.signal})}catch(c){throw new at(`cannot reach api.github.com (${c instanceof Error?c.message:String(c)})`)}if(s.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(s.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(wi(s.status))throw new at(`api.github.com \u2192 ${s.status} ${s.statusText}`);if(!s.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${s.status} ${s.statusText}`);if((await s.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}finally{clearTimeout(i)}}async function Vt(t,e,r){let n=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",o=new AbortController,i=setTimeout(()=>o.abort(),yi);try{let s;try{s=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new at(`cannot reach api.bitbucket.org (${c instanceof Error?c.message:String(c)})`)}if(s.ok)return t;if(s.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;if(wi(s.status))throw new at(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await Q$(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 Q$(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function bi(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=fp.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: ${fp.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function Xt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),yi);try{let n;try{n=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"},signal:e.signal})}catch(i){throw new at(`cannot reach gitlab.com (${i instanceof Error?i.message:String(i)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(wi(n.status))throw new at(`gitlab.com \u2192 ${n.status} ${n.statusText}`);if(!n.ok)throw new Error(`GitLab \u2192 ${n.status} ${n.statusText}`);return(await n.json()).username??"ok"}finally{clearTimeout(r)}}async function mp(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 ev(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 cc(t,e,r){let n=t.host==="github"?"set GH_TOKEN or GITHUB_TOKEN in the CLI env":t.host==="bitbucket"?"set BITBUCKET_EMAIL + BITBUCKET_API_TOKEN in the CLI env":t.host==="gitlab"?"set GITLAB_TOKEN in the CLI env":`no adapter implementation for host '${t.host}'`;return`cannot ${r} PR ${t.owner}/${t.repoName}#${e}: MockGitHost is active (write operations are not allowed) \u2014 ${n}`}function fo(t,e){let r=Ja(e);if(!e.mirror)return{spec:r,host:Ir(r)};let n=t?Y(t)?.mirrorWrite:void 0;return{spec:r,host:Ir(r,n?.token?{token:n.token,...n.email?{bitbucketEmail:n.email}:{}}:void 0)}}function Ir(t,e){if(t.host==="github"){let r=e?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(r)return new uc(r)}if(t.host==="bitbucket"){let r=e?.bitbucketEmail??process.env.BITBUCKET_EMAIL,n=e?.token??process.env.BITBUCKET_API_TOKEN;if(r&&n)return new lc(r,n)}if(t.host==="gitlab"){let r=e?.token??process.env.GITLAB_TOKEN;if(r)return new dc(r)}return new pc}var Rr,at,yi,fp,lc,uc,dc,pc,Jt=x(()=>{"use strict";B();me();Rr=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},at=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},yi=5e3;fp=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];lc=class{constructor(e,r){this.email=e;this.apiToken=r}name="bitbucket";authHeader(){return"Basic "+Buffer.from(`${this.email}:${this.apiToken}`).toString("base64")}async createPullRequest(e,r){let n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json"},body:JSON.stringify({title:r.title,description:r.body,source:{branch:{name:r.branchName}},destination:{branch:{name:r.baseBranch}}})});if(!n.ok)throw new Error(`bitbucket pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.links?.html?.href??"",number:o.id}}async findOpenPrByBranch(e,r){let n=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${n}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!o.ok)return null;let s=(await o.json()).values?.[0];return s?{url:s.links?.html?.href??"",number:s.id}:null}async getPullRequest(e,r){let n=`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(o.status===404)throw new Rr(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){let i=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:o})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:n}})});if(!o.ok)throw new Error(`bitbucket comment PR #${r}: ${o.status} ${await o.text()}`)}async addPRInlineComment(e,r,n,o,i){let s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:i},inline:{path:n,to:o}})});if(!s.ok)throw new Error(`bitbucket inline comment PR #${r} ${n}:${o}: ${s.status} ${await s.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},uc=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json"},body:JSON.stringify({title:r.title,body:r.body,head:r.branchName,base:r.baseBranch})});if(!n.ok)throw new Error(`github pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.html_url,number:o.number}}async findOpenPrByBranch(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls?state=open&head=${encodeURIComponent(`${e.owner}:${r}`)}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.html_url,number:i.number}:null}async getPullRequest(e,r){let n=`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(o.status===404)throw new Rr(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),a=!1,c=!1,l=!1;if(i.ok){let u=await i.json();for(let p of u.check_runs??[])l=!0,p.status!=="completed"?a=!0:p.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(p.conclusion)&&(c=!0)}if(s.ok){let u=await s.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${o}/pulls/${r}`,{headers:n});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${o}/actions/runs?head_sha=${a}&per_page=20`,{headers:n});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],u=[];for(let p of l.filter(d=>d.conclusion&&i.includes(d.conclusion))){let d=await fetch(`${o}/actions/runs/${p.id}/jobs?per_page=50`,{headers:n});if(!d.ok)continue;let m=(await d.json()).jobs??[];for(let f of m.filter(y=>y.conclusion==="failure")){let y=await fetch(`${o}/actions/jobs/${f.id}/logs`,{headers:n});if(!y.ok)continue;let k=await y.text();u.push(`### CI job: ${f.name}
20
+ `;B$(this.currentPath,r,"utf-8")}asWritable(){return new H$({write:(e,r,n)=>{try{let o=typeof e=="string"?e:e.toString("utf-8");for(let i of o.split(/\r?\n/))i&&this.writeLine(i);n()}catch(o){n(o)}}})}rotateIfNeeded(){if(!(this.cfg.maxBytes<=0||!lp(this.currentPath)||G$(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;lp(n)&&(r>=this.cfg.maxFiles?K$(n):up(n,`${this.currentPath}.${r+1}`))}up(this.currentPath,`${this.currentPath}.1`)}}}});function yi(t){return t===429||t>=500}function mp(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
21
+ `+t.slice(t.length-e)}async function zt(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),gi);try{let i;try{i=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new at(`cannot reach api.github.com (${l instanceof Error?l.message:String(l)})`)}if(i.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(yi(i.status))throw new at(`api.github.com \u2192 ${i.status} ${i.statusText}`);if(!i.ok)throw new Error(`GitHub \u2192 ${i.status} ${i.statusText}`);let a=(await i.json()).login??"ok",c=i.headers.get("x-oauth-scopes");if(c!==null&&e&&!c.split(",").map(u=>u.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${c||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let l;try{let u=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});u.ok&&(l=(await u.json()).type)}catch{}if(l==="Organization"){let u=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});if(u.status===403)throw new Error(`token cannot access org "${e.owner}" (403) \u2014 for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens; for classic PATs: verify 'repo' or 'admin:org' scope`);if(u.status===404)throw new Error(`org "${e.owner}" not found or not visible to this token \u2014 check the org name; for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens`);if(!u.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${u.status} ${u.statusText}`)}}return a}finally{clearTimeout(o)}}async function wi(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),gi);try{let s;try{s=await fetch(n,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},signal:o.signal})}catch(c){throw new at(`cannot reach api.github.com (${c instanceof Error?c.message:String(c)})`)}if(s.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(s.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(yi(s.status))throw new at(`api.github.com \u2192 ${s.status} ${s.statusText}`);if(!s.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${s.status} ${s.statusText}`);if((await s.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}finally{clearTimeout(i)}}async function Vt(t,e,r){let n=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",o=new AbortController,i=setTimeout(()=>o.abort(),gi);try{let s;try{s=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new at(`cannot reach api.bitbucket.org (${c instanceof Error?c.message:String(c)})`)}if(s.ok)return t;if(s.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;if(yi(s.status))throw new at(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await tv(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 tv(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function ki(t,e,r,n){let o;try{o=await fetch(`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}/${encodeURIComponent(n)}/pullrequests?pagelen=1`,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch{return}if(o.status!==403)return;let i={};try{i=await o.json()}catch{}let s=i.error?.detail?.granted;if(Array.isArray(s)){let c=hp.filter(l=>!s.includes(l));return c.length===0?void 0:`token lacks scope(s) ${c.join(", ")} \u2014 the pipeline would fail at PR time; re-create the API token with all of: ${hp.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function Xt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),gi);try{let n;try{n=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"},signal:e.signal})}catch(i){throw new at(`cannot reach gitlab.com (${i instanceof Error?i.message:String(i)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(yi(n.status))throw new at(`gitlab.com \u2192 ${n.status} ${n.statusText}`);if(!n.ok)throw new Error(`GitLab \u2192 ${n.status} ${n.statusText}`);return(await n.json()).username??"ok"}finally{clearTimeout(r)}}async function gp(t){try{let e=await fetch("https://gitlab.com/api/v4/personal_access_tokens/self",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}});if(!e.ok)return;let n=(await e.json()).scopes??[];return n.length>0&&!n.includes("api")?`GitLab token scopes [${n.join(", ")}] lack 'api' \u2014 CodePipe can read and push, but cannot create a Context Repo or scaffold its files`:void 0}catch{return}}function rv(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 lc(t,e,r){let n=t.host==="github"?"set GH_TOKEN or GITHUB_TOKEN in the CLI env":t.host==="bitbucket"?"set BITBUCKET_EMAIL + BITBUCKET_API_TOKEN in the CLI env":t.host==="gitlab"?"set GITLAB_TOKEN in the CLI env":`no adapter implementation for host '${t.host}'`;return`cannot ${r} PR ${t.owner}/${t.repoName}#${e}: MockGitHost is active (write operations are not allowed) \u2014 ${n}`}function fo(t,e){let r=Za(e);if(!e.mirror)return{spec:r,host:Ir(r)};let n=t?Y(t)?.mirrorWrite:void 0;return{spec:r,host:Ir(r,n?.token?{token:n.token,...n.email?{bitbucketEmail:n.email}:{}}:void 0)}}function Ir(t,e){if(t.host==="github"){let r=e?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(r)return new dc(r)}if(t.host==="bitbucket"){let r=e?.bitbucketEmail??process.env.BITBUCKET_EMAIL,n=e?.token??process.env.BITBUCKET_API_TOKEN;if(r&&n)return new uc(r,n)}if(t.host==="gitlab"){let r=e?.token??process.env.GITLAB_TOKEN;if(r)return new pc(r)}return new fc}var Rr,at,gi,hp,uc,dc,pc,fc,Jt=x(()=>{"use strict";B();fe();Rr=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},at=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},gi=5e3;hp=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];uc=class{constructor(e,r){this.email=e;this.apiToken=r}name="bitbucket";authHeader(){return"Basic "+Buffer.from(`${this.email}:${this.apiToken}`).toString("base64")}async createPullRequest(e,r){let n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json"},body:JSON.stringify({title:r.title,description:r.body,source:{branch:{name:r.branchName}},destination:{branch:{name:r.baseBranch}}})});if(!n.ok)throw new Error(`bitbucket pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.links?.html?.href??"",number:o.id}}async findOpenPrByBranch(e,r){let n=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${n}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!o.ok)return null;let s=(await o.json()).values?.[0];return s?{url:s.links?.html?.href??"",number:s.id}:null}async getPullRequest(e,r){let n=`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(o.status===404)throw new Rr(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){let i=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:o})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:n}})});if(!o.ok)throw new Error(`bitbucket comment PR #${r}: ${o.status} ${await o.text()}`)}async addPRInlineComment(e,r,n,o,i){let s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:i},inline:{path:n,to:o}})});if(!s.ok)throw new Error(`bitbucket inline comment PR #${r} ${n}:${o}: ${s.status} ${await s.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},dc=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json"},body:JSON.stringify({title:r.title,body:r.body,head:r.branchName,base:r.baseBranch})});if(!n.ok)throw new Error(`github pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.html_url,number:o.number}}async findOpenPrByBranch(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls?state=open&head=${encodeURIComponent(`${e.owner}:${r}`)}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.html_url,number:i.number}:null}async getPullRequest(e,r){let n=`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(o.status===404)throw new Rr(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),a=!1,c=!1,l=!1;if(i.ok){let u=await i.json();for(let p of u.check_runs??[])l=!0,p.status!=="completed"?a=!0:p.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(p.conclusion)&&(c=!0)}if(s.ok){let u=await s.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${o}/pulls/${r}`,{headers:n});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${o}/actions/runs?head_sha=${a}&per_page=20`,{headers:n});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],u=[];for(let p of l.filter(d=>d.conclusion&&i.includes(d.conclusion))){let d=await fetch(`${o}/actions/runs/${p.id}/jobs?per_page=50`,{headers:n});if(!d.ok)continue;let m=(await d.json()).jobs??[];for(let f of m.filter(g=>g.conclusion==="failure")){let g=await fetch(`${o}/actions/jobs/${f.id}/logs`,{headers:n});if(!g.ok)continue;let k=await g.text();u.push(`### CI job: ${f.name}
22
22
 
23
- ${pp(k,8e3)}`)}}return u.length===0?void 0:pp(u.join(`
23
+ ${mp(k,8e3)}`)}}return u.length===0?void 0:mp(u.join(`
24
24
 
25
- `),16e3)}catch{return}}async mergePR(e,r,n,o){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async addPRInlineComment(e,r,n,o,i){let s={Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:s});if(!a.ok)throw new Error(`github PR #${r}: ${a.status} ${await a.text()}`);let c=(await a.json()).head?.sha;if(!c)throw new Error(`github PR #${r}: no head sha`);let l=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/comments`,{method:"POST",headers:{...s,"Content-Type":"application/json"},body:JSON.stringify({body:i,commit_id:c,path:n,line:o,side:"RIGHT"})});if(!l.ok)throw new Error(`github inline comment PR #${r} ${n}:${o}: ${l.status} ${await l.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},dc=class{constructor(e){this.token=e}name="gitlab";pid(e){return encodeURIComponent(`${e.owner}/${e.repoName}`)}headers(e=!1){let r={"PRIVATE-TOKEN":this.token,"User-Agent":"codepipe-cli"};return e&&(r["Content-Type"]="application/json"),r}async createPullRequest(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({source_branch:r.branchName,target_branch:r.baseBranch,title:r.title,description:r.body})});if(!n.ok)throw new Error(`gitlab mr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.web_url??"",number:o.iid}}async findOpenPrByBranch(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests?state=opened&source_branch=${encodeURIComponent(r)}`,{headers:this.headers()});if(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.web_url??"",number:i.iid}:null}async getPullRequest(e,r){let n=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,o=await fetch(n,{method:"GET",headers:this.headers()});if(o.status===404)throw new Rr(`GitLab MR not found: ${e.owner}/${e.repoName}!${r}`);if(o.status>=400)throw new Error(`gitlab GET merge_requests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="merged")return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed"||i.state==="locked")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=ev(i.head_pipeline?.status??i.pipeline?.status),a=i.merge_status==="cannot_be_merged"||i.has_conflicts===!0?"conflict":i.merge_status==="can_be_merged"&&i.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:s,mergeable:a}}async mergePR(e,r,n,o){let i=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,s,a=await fetch(i,{headers:this.headers()});if(a.ok){let u=await a.json().catch(()=>null);s=u?.sha??u?.diff_refs?.head_sha}let c=await fetch(`${i}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:n==="squash",should_remove_source_branch:o,...s?{sha:s}:{}})});if(!c.ok)throw new Error(`gitlab merge MR !${r}: ${c.status} ${await c.text()}`);let l=await c.json().catch(()=>null);return l?.merge_commit_sha?{mergedSha:l.merge_commit_sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`gitlab comment MR !${r}: ${o.status} ${await o.text()}`)}async addPRInlineComment(e,r,n,o,i){let s=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{headers:this.headers(!1)});if(!s.ok)throw new Error(`gitlab MR !${r}: ${s.status} ${await s.text()}`);let a=(await s.json()).diff_refs;if(!a?.base_sha||!a.head_sha||!a.start_sha)throw new Error(`gitlab MR !${r}: no diff refs`);let c=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/discussions`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:i,position:{position_type:"text",new_path:n,new_line:o,base_sha:a.base_sha,head_sha:a.head_sha,start_sha:a.start_sha}})});if(!c.ok)throw new Error(`gitlab inline comment MR !${r} ${n}:${o}: ${c.status} ${await c.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!o.ok)throw new Error(`gitlab close MR !${r}: ${o.status} ${await o.text()}`)}};pc=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(cc(e,r,"merge"))}async closePR(e,r,n){throw new Error(cc(e,r,"close"))}async addPRComment(e,r,n){throw new Error(cc(e,r,"comment"))}}});import{X509Certificate as yp}from"node:crypto";import{readFileSync as tv}from"node:fs";import Zt from"node:tls";function rv(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function bp(t=kp){if(hp)return;hp=!0;let e=Q("EXTRA_CA_FILE");if(!(!e||!wp))try{let r=rv(tv(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Zt.setDefaultCACertificates([...Zt.getCACertificates(),...r]),t(`[tls] trusting ${r.length} extra CA cert(s) from ${e}`)}catch(r){t(`[tls] failed to load CODEPIPE_EXTRA_CA_FILE ${e}: ${r instanceof Error?r.message:String(r)}`)}}function $p(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 nv(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
26
- `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function ov(t,e,r){return new Promise((n,o)=>{let i=Zt.connect({host:t,port:e,servername:t,rejectUnauthorized:!1},()=>{let s=i.getPeerCertificate(!0),a=new Set;for(;s?.issuerCertificate&&s.issuerCertificate!==s&&s.fingerprint256&&!a.has(s.fingerprint256);)a.add(s.fingerprint256),s=s.issuerCertificate;let c=s?.raw?new yp(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function fc(t,e,r){return new Promise(n=>{let o=Zt.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{o.end(),n(!0)});o.on("error",()=>n(!1)),o.setTimeout(r,()=>{o.destroy(),n(!1)})})}async function iv(t){try{let e=await fetch(t);return e.ok?new yp(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function vp(t,e=443,r=kp){let n=`${t}:${e}`,o=gp.get(n);if(o)return o;let i=sv(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return gp.set(n,i),i}async function sv(t,e,r){if(!wp)return!1;let n=8e3;if(await fc(t,e,n))return!0;let o=await ov(t,e,n),i=Zt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=nv(o);if(!c)break;let l=await iv(c);if(!l)break;if(s.push(l.toString()),Zt.setDefaultCACertificates([...i,...s]),await fc(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 fc(t,e,n)}var wp,hp,gp,kp,xp=x(()=>{"use strict";Ge();wp=typeof Zt.getCACertificates=="function"&&typeof Zt.setDefaultCACertificates=="function",hp=!1,gp=new Map,kp=t=>console.warn(t)});function Rp(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function ct(t,e,r){bp();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($p(s)&&await vp(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function av(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function cv(){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 mc(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=cv(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await ct(t,r,n)}catch(u){a=new Error(`${e}: ${u instanceof Error?u.message:String(u)}`)}if(l){if(l.ok)return l;let u=await l.text();if(c<o&&av(l.status,u)){await Sp(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await Sp(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Qt(t){let e;try{e=await ct(t,"/api/users/me?fields=login,fullName")}catch(n){throw new Error(`cannot reach ${t.baseUrl} (${n instanceof Error?n.message:String(n)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the YouTrack PAT)");if(!e.ok)throw new Error(`YouTrack \u2192 ${e.status} ${e.statusText}`);let r=await e.json();return r.login??r.fullName??"ok"}async function Ip(t){try{let e=await ct(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function lv(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=Ep.get(o);if(i)return i;let s=await ct(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!s.ok)throw new Error(`yt resolveStateId ${e}: ${s.status} ${await s.text()}`);let c=(await s.json()).customFields.find(u=>u.name===n);if(!c)throw new Error(`yt: issue ${e} has no ${n} custom field`);let l=c.projectCustomField.bundle.values.find(u=>u.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${n} bundle for ${e}`);return Ep.set(o,l.id),l.id}async function Cp(t,e,r,n=mo){let o=await lv(t,e,r,n);await mc(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 Pp(t,e,r){return await(await mc(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function Ap(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await mc(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function _p(t,e){let r=Tp.get(e);if(r)return r;let n=await ct(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!n.ok)throw new Error(`yt resolveProjectId: ${n.status} ${await n.text()}`);let i=(await n.json()).find(s=>s.shortName===e);if(!i)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return Tp.set(e,i.id),i.id}async function jp(t,e,r,n,o,i=mo){let s=await _p(t,e),a=await ct(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:s},summary:r,description:n,customFields:[{name:i,$type:"StateIssueCustomField",value:{name:o,$type:"StateBundleElement"}}]})});if(!a.ok)throw new Error(`yt createIssue: ${a.status} ${await a.text()}`);let c=await a.json();return{id:c.id,key:c.idReadable}}async function Np(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await ct(t,"/api/commands",{method:"POST",body:JSON.stringify({query:o,issues:[{idReadable:e}]})});if(!i.ok)throw new Error(`yt applyIssueLink (${o} on ${e}): ${i.status} ${await i.text()}`)}function Mp(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 Dp(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 Up(t,e){let r=e.stageField??mo,n=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let c=e.columns.map(l=>`{${l}}`).join(", ");n.push(`${r}: ${c}`)}if(e.updatedSince){let c=new Date(e.updatedSince).toISOString().slice(0,10);n.push(`updated: ${c} .. *`)}e.assignee?n.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&n.push("has: Assignee");let o=n.join(" "),i=`/api/issues?query=${encodeURIComponent(o)}&fields=${Lp}&$top=200`,s=await ct(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);let a=await s.json();if(e.columns&&e.columns.length>0&&a.length>0&&!a.some(l=>(l.customFields??[]).some(u=>u.name===r))){let l=[...new Set((a[0]?.customFields??[]).map(u=>u.name).filter(u=>!!u))];throw new Error(`youtrack.stage_field "${r}" does not exist in project ${e.projectKey} \u2014 YouTrack ignored the status filter and would have returned unrelated issues. `+(l.length>0?`Fields on the issues: ${l.join(", ")}.`:"The issues carry no custom fields at all."))}return a.map(c=>Gp(c,r))}async function Bp(t,e,r=mo){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Lp}`,o=await ct(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Gp(await o.json(),r)}async function Fp(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${dv}&$top=500`,o=await ct(t,n);if(!o.ok)throw new Error(`yt listComments ${e}: ${o.status} ${await o.text()}`);return(await o.json()).filter(s=>s.created>r).map(s=>{let a={id:s.id,issueId:e,author:s.author?.login??"unknown",body:s.text??"",createdAt:new Date(s.created).toISOString()},c=Mp(s.attachments);return c&&(a.attachments=c),a})}function pv(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 Gp(t,e=mo){let r=t.customFields??[],n=r.find(l=>l.name===e),o=r.find(l=>l.name==="Assignee"),i=r.find(l=>l.name==="Type"),s={id:t.id,key:t.idReadable,title:t.summary,status:n?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(s.description=t.description),o?.value?.login&&(s.assignee=o.value.login),i?.value?.name&&(s.issueType=i.value.name),t.tags&&t.tags.length>0&&(s.tags=t.tags.map(l=>l.name));let a=Mp(t.attachments);a&&(s.attachments=a);let c=pv(t.links);return c&&(s.links=c),s}async function Kp(t,e){let r=await fv(t,e);return r.length>0?r:mv(t,e)}async function fv(t,e){let r=await _p(t,e),n=await ct(t,`/api/admin/projects/${encodeURIComponent(r)}/customFields?fields=$type,field(name),bundle(values(name,archived))&$top=100`);if(!n.ok)return[];let o=await n.json(),i=[];for(let s of o)s.$type==="StateProjectCustomField"&&s.field?.name&&i.push({name:s.field.name,values:Hp(s.bundle)});return i}async function mv(t,e){let r=`project: ${e}`,n=await ct(t,`/api/issues?query=${encodeURIComponent(r)}&fields=customFields(name,$type,projectCustomField(bundle(values(name,archived))))&$top=1`);if(!n.ok)throw new Error(`yt fetchProjectStateFields ${e}: ${n.status} ${await n.text()}`);let o=await n.json(),i=[];for(let s of o[0]?.customFields??[])s.$type==="StateIssueCustomField"&&s.name&&i.push({name:s.name,values:Hp(s.projectCustomField?.bundle)});return i}function Hp(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var Sp,mo,Ep,Tp,Op,uv,Lp,dv,Cr=x(()=>{"use strict";xp();Sp=t=>new Promise(e=>setTimeout(e,t));mo="Stage",Ep=new Map;Tp=new Map;Op="attachments(id,name,url,size,mimeType)",uv="links(direction,linkType(name),issues(idReadable))",Lp=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Op},${uv}`,dv=`id,text,created,author(login),${Op}`});function bt(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function cn(t){return t instanceof at}async function Wp(t,e){let r=Y(t),n=[],o=[],i=()=>Date.now();if(e?.trackerProvider==="internal")n.push({name:"tracker",ok:!0,detail:"built-in tracker"});else if(r?.youtrack?.url&&r.youtrack.token)try{let c=await Qt({baseUrl:r.youtrack.url,token:r.youtrack.token});n.push({name:"youtrack",ok:!0}),o.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"youtrack",ok:!1,detail:bt(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:bt(c),checkedAt:i()})}else n.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),o.push({kind:"youtrack",present:!1,checkedAt:i()});let s=!1;if(r?.github?.token){s=!0;try{let c=await zt(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){cn(c)?(n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"github",ok:!1,detail:bt(c)}),o.push({kind:"github",present:!0,ok:!1,detail:bt(c),checkedAt:i()}))}}else o.push({kind:"github",present:!1,checkedAt:i()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){s=!0;try{let c=await Vt(r.bitbucket.email,r.bitbucket.apiToken);n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){cn(c)?(n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"bitbucket",ok:!1,detail:bt(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:bt(c),checkedAt:i()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Xt(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){cn(c)?(n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"gitlab",ok:!1,detail:bt(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:bt(c),checkedAt:i()}))}}else o.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||n.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let u of e?.repos??[])if(u.host==="github")try{await ki(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){cn(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:bt(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await ki(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){cn(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:bt(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await ki(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){cn(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:i()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:bt(l),checkedAt:i()})}else o.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:i()})}else o.push({kind:"contextWrite",present:!1,checkedAt:i()});let a=on(t);if(!a)n.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),o.push({kind:"claude",present:!1,checkedAt:i()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:i()});else{let c=await Bt(a);if(c==="invalid"){let l="Claude refused this token \u2014 refresh it with `claude setup-token`";n.push({name:"claude",ok:!1,detail:l}),o.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function Bt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),8e3);try{let n=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20","content-type":"application/json"},body:JSON.stringify({model:hv,max_tokens:1,messages:[{role:"user",content:"hi"}]}),signal:e.signal});return n.status===200?"valid":n.status===401||n.status===403?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}async function qp(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 hv,ln=x(()=>{"use strict";me();Jt();Cr();hv="claude-haiku-4-5-20251001"});import gv from"node:http";import hc from"node:crypto";function $i(){let t=gc(hc.randomBytes(32)),e=gc(hc.createHash("sha256").update(t).digest()),r=gc(hc.randomBytes(32));return{verifier:t,challenge:e,state:r}}function wc(t){let e=new URL(yv);return e.search=new URLSearchParams({response_type:"code",client_id:Yp,redirect_uri:t.redirectUri,scope:kv,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function $v(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 zp(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 vv(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 kc(t){let e=await fetch(wv,{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:Yp,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return vv(await e.json())}async function bc(t){let e=t.timeoutMs??bv,r=gv.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=wc({redirectUri:o,challenge:t.challenge,state:t.state}),s,a=new Promise((l,u)=>{s=setTimeout(()=>u(new Error("no-callback")),e),r.on("request",(p,d)=>{let m=new URL(p.url??"/",o);if(m.pathname!=="/callback"){d.statusCode=404,d.end();return}clearTimeout(s),d.setHeader("content-type","text/html"),d.end("<h3>Authorized \u2014 you can close this tab.</h3>");try{l($v(m.searchParams,t.state))}catch(f){u(f)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>kc({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function Vp(t){let e=await bc(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
27
- ${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var Yp,yv,wv,yc,kv,bv,gc,$c=x(()=>{"use strict";Yp="9d1c250a-e61b-44d9-88ed-5944d1962f5e",yv="https://platform.claude.com/oauth/authorize",wv="https://platform.claude.com/v1/oauth/token",yc="https://platform.claude.com/oauth/code/callback",kv="org:create_api_key user:profile user:inference",bv=12e4,gc=t=>Buffer.from(t).toString("base64url")});import{spawn as xv}from"node:child_process";function Pr(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=xv(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var vi=x(()=>{"use strict"});import{existsSync as er,mkdirSync as sf,readFileSync as Sc,writeFileSync as un}from"node:fs";import{homedir as _v}from"node:os";import{join as Tt}from"node:path";import{simpleGit as jv}from"simple-git";function go(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=Tt(t,o);er(s)||(un(s,i),r.push(o))}return r}function tr(t,e,r){let n=Tt(_v(),".codepipe","profiles",t,"context-config");return sf(n,{recursive:!0}),un(Tt(n,"project.yaml"),e.projectYaml),un(Tt(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function Ei(t,e,r){if(er(e))for(let n of dn){let o=Tt(e,n),i=Tt(t,n);if(!(!er(o)||er(i)))try{un(i,Sc(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 pn(t){let e=Tt(t,".gitignore"),r=er(e)?Sc(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(dn.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
25
+ `),16e3)}catch{return}}async mergePR(e,r,n,o){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async addPRInlineComment(e,r,n,o,i){let s={Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:s});if(!a.ok)throw new Error(`github PR #${r}: ${a.status} ${await a.text()}`);let c=(await a.json()).head?.sha;if(!c)throw new Error(`github PR #${r}: no head sha`);let l=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/comments`,{method:"POST",headers:{...s,"Content-Type":"application/json"},body:JSON.stringify({body:i,commit_id:c,path:n,line:o,side:"RIGHT"})});if(!l.ok)throw new Error(`github inline comment PR #${r} ${n}:${o}: ${l.status} ${await l.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},pc=class{constructor(e){this.token=e}name="gitlab";pid(e){return encodeURIComponent(`${e.owner}/${e.repoName}`)}headers(e=!1){let r={"PRIVATE-TOKEN":this.token,"User-Agent":"codepipe-cli"};return e&&(r["Content-Type"]="application/json"),r}async createPullRequest(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({source_branch:r.branchName,target_branch:r.baseBranch,title:r.title,description:r.body})});if(!n.ok)throw new Error(`gitlab mr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.web_url??"",number:o.iid}}async findOpenPrByBranch(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests?state=opened&source_branch=${encodeURIComponent(r)}`,{headers:this.headers()});if(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.web_url??"",number:i.iid}:null}async getPullRequest(e,r){let n=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,o=await fetch(n,{method:"GET",headers:this.headers()});if(o.status===404)throw new Rr(`GitLab MR not found: ${e.owner}/${e.repoName}!${r}`);if(o.status>=400)throw new Error(`gitlab GET merge_requests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="merged")return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed"||i.state==="locked")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=rv(i.head_pipeline?.status??i.pipeline?.status),a=i.merge_status==="cannot_be_merged"||i.has_conflicts===!0?"conflict":i.merge_status==="can_be_merged"&&i.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:s,mergeable:a}}async mergePR(e,r,n,o){let i=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,s,a=await fetch(i,{headers:this.headers()});if(a.ok){let u=await a.json().catch(()=>null);s=u?.sha??u?.diff_refs?.head_sha}let c=await fetch(`${i}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:n==="squash",should_remove_source_branch:o,...s?{sha:s}:{}})});if(!c.ok)throw new Error(`gitlab merge MR !${r}: ${c.status} ${await c.text()}`);let l=await c.json().catch(()=>null);return l?.merge_commit_sha?{mergedSha:l.merge_commit_sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`gitlab comment MR !${r}: ${o.status} ${await o.text()}`)}async addPRInlineComment(e,r,n,o,i){let s=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{headers:this.headers(!1)});if(!s.ok)throw new Error(`gitlab MR !${r}: ${s.status} ${await s.text()}`);let a=(await s.json()).diff_refs;if(!a?.base_sha||!a.head_sha||!a.start_sha)throw new Error(`gitlab MR !${r}: no diff refs`);let c=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/discussions`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:i,position:{position_type:"text",new_path:n,new_line:o,base_sha:a.base_sha,head_sha:a.head_sha,start_sha:a.start_sha}})});if(!c.ok)throw new Error(`gitlab inline comment MR !${r} ${n}:${o}: ${c.status} ${await c.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!o.ok)throw new Error(`gitlab close MR !${r}: ${o.status} ${await o.text()}`)}};fc=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(lc(e,r,"merge"))}async closePR(e,r,n){throw new Error(lc(e,r,"close"))}async addPRComment(e,r,n){throw new Error(lc(e,r,"comment"))}}});import{X509Certificate as kp}from"node:crypto";import{readFileSync as nv}from"node:fs";import Zt from"node:tls";function ov(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function vp(t=$p){if(yp)return;yp=!0;let e=Q("EXTRA_CA_FILE");if(!(!e||!bp))try{let r=ov(nv(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Zt.setDefaultCACertificates([...Zt.getCACertificates(),...r]),t(`[tls] trusting ${r.length} extra CA cert(s) from ${e}`)}catch(r){t(`[tls] failed to load CODEPIPE_EXTRA_CA_FILE ${e}: ${r instanceof Error?r.message:String(r)}`)}}function xp(t){let e=t&&typeof t=="object"&&"cause"in t?t.cause?.code:void 0;return e==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||e==="UNABLE_TO_GET_ISSUER_CERT_LOCALLY"||e==="UNABLE_TO_GET_ISSUER_CERT"}function iv(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
26
+ `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function sv(t,e,r){return new Promise((n,o)=>{let i=Zt.connect({host:t,port:e,servername:t,rejectUnauthorized:!1},()=>{let s=i.getPeerCertificate(!0),a=new Set;for(;s?.issuerCertificate&&s.issuerCertificate!==s&&s.fingerprint256&&!a.has(s.fingerprint256);)a.add(s.fingerprint256),s=s.issuerCertificate;let c=s?.raw?new kp(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function mc(t,e,r){return new Promise(n=>{let o=Zt.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{o.end(),n(!0)});o.on("error",()=>n(!1)),o.setTimeout(r,()=>{o.destroy(),n(!1)})})}async function av(t){try{let e=await fetch(t);return e.ok?new kp(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Sp(t,e=443,r=$p){let n=`${t}:${e}`,o=wp.get(n);if(o)return o;let i=cv(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return wp.set(n,i),i}async function cv(t,e,r){if(!bp)return!1;let n=8e3;if(await mc(t,e,n))return!0;let o=await sv(t,e,n),i=Zt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=iv(o);if(!c)break;let l=await av(c);if(!l)break;if(s.push(l.toString()),Zt.setDefaultCACertificates([...i,...s]),await mc(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 mc(t,e,n)}var bp,yp,wp,$p,Ep=x(()=>{"use strict";Ge();bp=typeof Zt.getCACertificates=="function"&&typeof Zt.setDefaultCACertificates=="function",yp=!1,wp=new Map,$p=t=>console.warn(t)});function Cp(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function ct(t,e,r){vp();let n={Authorization:`Bearer ${t.token}`,Accept:"application/json"};r?.body&&(n["Content-Type"]="application/json");let o=t.baseUrl+e,i={...r,headers:{...n,...r?.headers??{}}};try{return await fetch(o,i)}catch(s){if(xp(s)&&await Sp(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function lv(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function uv(){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 hc(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=uv(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await ct(t,r,n)}catch(u){a=new Error(`${e}: ${u instanceof Error?u.message:String(u)}`)}if(l){if(l.ok)return l;let u=await l.text();if(c<o&&lv(l.status,u)){await Tp(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await Tp(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Qt(t){let e;try{e=await ct(t,"/api/users/me?fields=login,fullName")}catch(n){throw new Error(`cannot reach ${t.baseUrl} (${n instanceof Error?n.message:String(n)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the YouTrack PAT)");if(!e.ok)throw new Error(`YouTrack \u2192 ${e.status} ${e.statusText}`);let r=await e.json();return r.login??r.fullName??"ok"}async function Pp(t){try{let e=await ct(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function dv(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=Rp.get(o);if(i)return i;let s=await ct(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!s.ok)throw new Error(`yt resolveStateId ${e}: ${s.status} ${await s.text()}`);let c=(await s.json()).customFields.find(u=>u.name===n);if(!c)throw new Error(`yt: issue ${e} has no ${n} custom field`);let l=c.projectCustomField.bundle.values.find(u=>u.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${n} bundle for ${e}`);return Rp.set(o,l.id),l.id}async function Ap(t,e,r,n=mo){let o=await dv(t,e,r,n);await hc(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:n,$type:"StateIssueCustomField",value:{id:o,$type:"StateBundleElement"}}]})})}async function _p(t,e,r){return await(await hc(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function jp(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await hc(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function Np(t,e){let r=Ip.get(e);if(r)return r;let n=await ct(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!n.ok)throw new Error(`yt resolveProjectId: ${n.status} ${await n.text()}`);let i=(await n.json()).find(s=>s.shortName===e);if(!i)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return Ip.set(e,i.id),i.id}async function Op(t,e,r,n,o,i=mo){let s=await Np(t,e),a=await ct(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:s},summary:r,description:n,customFields:[{name:i,$type:"StateIssueCustomField",value:{name:o,$type:"StateBundleElement"}}]})});if(!a.ok)throw new Error(`yt createIssue: ${a.status} ${await a.text()}`);let c=await a.json();return{id:c.id,key:c.idReadable}}async function Lp(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await ct(t,"/api/commands",{method:"POST",body:JSON.stringify({query:o,issues:[{idReadable:e}]})});if(!i.ok)throw new Error(`yt applyIssueLink (${o} on ${e}): ${i.status} ${await i.text()}`)}function Up(t){if(!t||t.length===0)return;let e=[];for(let r of t)!r.url||!r.name||e.push({id:r.id,name:r.name,url:r.url,...r.mimeType?{mimeType:r.mimeType}:{},...typeof r.size=="number"?{size:r.size}:{}});return e.length>0?e:void 0}async function Bp(t,e){let r=e.startsWith("http")?e:t.baseUrl+e,n=await fetch(r,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok)throw new Error(`yt downloadAttachment ${e}: ${n.status}`);return Buffer.from(await n.arrayBuffer())}async function Fp(t,e){let r=e.stageField??mo,n=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let c=e.columns.map(l=>`{${l}}`).join(", ");n.push(`${r}: ${c}`)}if(e.updatedSince){let c=new Date(e.updatedSince).toISOString().slice(0,10);n.push(`updated: ${c} .. *`)}e.assignee?n.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&n.push("has: Assignee");let o=n.join(" "),i=`/api/issues?query=${encodeURIComponent(o)}&fields=${Dp}&$top=200`,s=await ct(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);let a=await s.json();if(e.columns&&e.columns.length>0&&a.length>0&&!a.some(l=>(l.customFields??[]).some(u=>u.name===r))){let l=[...new Set((a[0]?.customFields??[]).map(u=>u.name).filter(u=>!!u))];throw new Error(`youtrack.stage_field "${r}" does not exist in project ${e.projectKey} \u2014 YouTrack ignored the status filter and would have returned unrelated issues. `+(l.length>0?`Fields on the issues: ${l.join(", ")}.`:"The issues carry no custom fields at all."))}return a.map(c=>Hp(c,r))}async function Gp(t,e,r=mo){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Dp}`,o=await ct(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Hp(await o.json(),r)}async function Kp(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${fv}&$top=500`,o=await ct(t,n);if(!o.ok)throw new Error(`yt listComments ${e}: ${o.status} ${await o.text()}`);return(await o.json()).filter(s=>s.created>r).map(s=>{let a={id:s.id,issueId:e,author:s.author?.login??"unknown",body:s.text??"",createdAt:new Date(s.created).toISOString()},c=Up(s.attachments);return c&&(a.attachments=c),a})}function mv(t){if(!t||t.length===0)return;let e=[];for(let r of t){if(r.direction!=="INWARD")continue;let n=r.linkType?.name==="Depend"?"depends_on":r.linkType?.name==="Subtask"?"subtask":null;if(n)for(let o of r.issues??[])o.idReadable&&e.push({type:n,targetKey:o.idReadable})}return e.length>0?e:void 0}function Hp(t,e=mo){let r=t.customFields??[],n=r.find(l=>l.name===e),o=r.find(l=>l.name==="Assignee"),i=r.find(l=>l.name==="Type"),s={id:t.id,key:t.idReadable,title:t.summary,status:n?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(s.description=t.description),o?.value?.login&&(s.assignee=o.value.login),i?.value?.name&&(s.issueType=i.value.name),t.tags&&t.tags.length>0&&(s.tags=t.tags.map(l=>l.name));let a=Up(t.attachments);a&&(s.attachments=a);let c=mv(t.links);return c&&(s.links=c),s}async function Wp(t,e){let r=await hv(t,e);return r.length>0?r:gv(t,e)}async function hv(t,e){let r=await Np(t,e),n=await ct(t,`/api/admin/projects/${encodeURIComponent(r)}/customFields?fields=$type,field(name),bundle(values(name,archived))&$top=100`);if(!n.ok)return[];let o=await n.json(),i=[];for(let s of o)s.$type==="StateProjectCustomField"&&s.field?.name&&i.push({name:s.field.name,values:qp(s.bundle)});return i}async function gv(t,e){let r=`project: ${e}`,n=await ct(t,`/api/issues?query=${encodeURIComponent(r)}&fields=customFields(name,$type,projectCustomField(bundle(values(name,archived))))&$top=1`);if(!n.ok)throw new Error(`yt fetchProjectStateFields ${e}: ${n.status} ${await n.text()}`);let o=await n.json(),i=[];for(let s of o[0]?.customFields??[])s.$type==="StateIssueCustomField"&&s.name&&i.push({name:s.name,values:qp(s.projectCustomField?.bundle)});return i}function qp(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var Tp,mo,Rp,Ip,Mp,pv,Dp,fv,Cr=x(()=>{"use strict";Ep();Tp=t=>new Promise(e=>setTimeout(e,t));mo="Stage",Rp=new Map;Ip=new Map;Mp="attachments(id,name,url,size,mimeType)",pv="links(direction,linkType(name),issues(idReadable))",Dp=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Mp},${pv}`,fv=`id,text,created,author(login),${Mp}`});function $t(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function cn(t){return t instanceof at}async function Yp(t,e){let r=Y(t),n=[],o=[],i=()=>Date.now();if(e?.trackerProvider==="internal")n.push({name:"tracker",ok:!0,detail:"built-in tracker"});else if(r?.youtrack?.url&&r.youtrack.token)try{let c=await Qt({baseUrl:r.youtrack.url,token:r.youtrack.token});n.push({name:"youtrack",ok:!0}),o.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"youtrack",ok:!1,detail:$t(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:$t(c),checkedAt:i()})}else n.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),o.push({kind:"youtrack",present:!1,checkedAt:i()});let s=!1;if(r?.github?.token){s=!0;try{let c=await zt(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){cn(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:$t(c)}),o.push({kind:"github",present:!0,ok:!1,detail:$t(c),checkedAt:i()}))}}else o.push({kind:"github",present:!1,checkedAt:i()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){s=!0;try{let c=await Vt(r.bitbucket.email,r.bitbucket.apiToken);n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){cn(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:$t(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:$t(c),checkedAt:i()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Xt(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){cn(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:$t(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:$t(c),checkedAt:i()}))}}else o.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||n.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let u of e?.repos??[])if(u.host==="github")try{await wi(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){cn(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:$t(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await wi(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){cn(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:$t(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await wi(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){cn(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:i()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:$t(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=on(t);if(!a)n.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),o.push({kind:"claude",present:!1,checkedAt:i()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:i()});else{let c=await Bt(a);if(c==="invalid"){let l="Claude refused this token \u2014 refresh it with `claude setup-token`";n.push({name:"claude",ok:!1,detail:l}),o.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function Bt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),8e3);try{let n=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20","content-type":"application/json"},body:JSON.stringify({model:yv,max_tokens:1,messages:[{role:"user",content:"hi"}]}),signal:e.signal});return n.status===200?"valid":n.status===401||n.status===403?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}async function zp(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1000",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});if(n.status!==200)return null;let i=(await n.json())?.data;if(!Array.isArray(i))return null;let s=[];for(let a of i){let c=a?.id;if(typeof c!="string"||c.trim().length===0)continue;let l=a?.created_at;s.push({id:c,...typeof l=="string"?{createdAt:l}:{}})}return s}catch{return null}finally{clearTimeout(r)}}var yv,ln=x(()=>{"use strict";fe();Jt();Cr();yv="claude-haiku-4-5-20251001"});import wv from"node:http";import gc from"node:crypto";function bi(){let t=yc(gc.randomBytes(32)),e=yc(gc.createHash("sha256").update(t).digest()),r=yc(gc.randomBytes(32));return{verifier:t,challenge:e,state:r}}function kc(t){let e=new URL(kv);return e.search=new URLSearchParams({response_type:"code",client_id:Vp,redirect_uri:t.redirectUri,scope:$v,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function xv(t,e){let r=t.get("error");if(r)throw new Error(`oauth-error: ${r}`);if(t.get("state")!==e)throw new Error("state-mismatch");let n=t.get("code");if(!n)throw new Error("no-code");return n}function Xp(t,e){let[r,n]=t.trim().split("#");if(!r)throw new Error("no-code");if(n!==void 0&&n!==e)throw new Error("state-mismatch");return r}function Sv(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 bc(t){let e=await fetch(bv,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:t.code,state:t.state,redirect_uri:t.redirectUri,client_id:Vp,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return Sv(await e.json())}async function $c(t){let e=t.timeoutMs??vv,r=wv.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=kc({redirectUri:o,challenge:t.challenge,state:t.state}),s,a=new Promise((l,u)=>{s=setTimeout(()=>u(new Error("no-callback")),e),r.on("request",(p,d)=>{let m=new URL(p.url??"/",o);if(m.pathname!=="/callback"){d.statusCode=404,d.end();return}clearTimeout(s),d.setHeader("content-type","text/html"),d.end("<h3>Authorized \u2014 you can close this tab.</h3>");try{l(xv(m.searchParams,t.state))}catch(f){u(f)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>bc({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function Jp(t){let e=await $c(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
27
+ ${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var Vp,kv,bv,wc,$v,vv,yc,vc=x(()=>{"use strict";Vp="9d1c250a-e61b-44d9-88ed-5944d1962f5e",kv="https://platform.claude.com/oauth/authorize",bv="https://platform.claude.com/v1/oauth/token",wc="https://platform.claude.com/oauth/code/callback",$v="org:create_api_key user:profile user:inference",vv=12e4,yc=t=>Buffer.from(t).toString("base64url")});import{spawn as Ev}from"node:child_process";function Pr(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=Ev(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var $i=x(()=>{"use strict"});import{existsSync as er,mkdirSync as cf,readFileSync as Ec,writeFileSync as un}from"node:fs";import{homedir as Nv}from"node:os";import{join as Rt}from"node:path";import{simpleGit as Ov}from"simple-git";function go(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=Rt(t,o);er(s)||(un(s,i),r.push(o))}return r}function tr(t,e,r){let n=Rt(Nv(),".codepipe","profiles",t,"context-config");return cf(n,{recursive:!0}),un(Rt(n,"project.yaml"),e.projectYaml),un(Rt(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function Si(t,e,r){if(er(e))for(let n of dn){let o=Rt(e,n),i=Rt(t,n);if(!(!er(o)||er(i)))try{un(i,Ec(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 pn(t){let e=Rt(t,".gitignore"),r=er(e)?Ec(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(dn.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
28
28
  `)?"":`
29
- `;return un(e,r+i+Nv.join(`
29
+ `;return un(e,r+i+Lv.join(`
30
30
  `)+`
31
- `),!0}async function af(t,e){try{if(!er(Tt(t,".git")))return;let r=jv(t),n=(await r.raw(["ls-files","--",...dn])).split(`
32
- `).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;pn(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 Rc(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 Ec(t){let e=new Map;for(let r of dn){let n=Tt(t,r);er(n)&&e.set(r,Sc(n))}return e}function Tc(t,e){sf(t,{recursive:!0});for(let[r,n]of e){let o=Tt(t,r);er(o)||un(o,n)}}var dn,Nv,Ft=x(()=>{"use strict";lt();dn=["project.yaml","regimen.yaml"];Nv=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as Ov,mkdirSync as Lv,rmSync as Mv,writeFileSync as Ic}from"node:fs";import{dirname as Dv,isAbsolute as Uv,join as uf,normalize as Ii}from"node:path";import{simpleGit as df}from"simple-git";async function Cc(t,e){let r=Ii(t),o=(Ri.get(r)??Promise.resolve()).catch(()=>{}).then(e);Ri.set(r,o);try{return await o}finally{Ri.get(r)===o&&Ri.delete(r)}}async function Ce(t,e,r){return Cc(t,()=>Pc(t,e,r))}async function Pc(t,e,r){if(!Ov(uf(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=Te(t,a.path);if(a.deleted){Mv(c,{force:!0});continue}Lv(Dv(c),{recursive:!0}),a.encoding==="base64"?Ic(c,Buffer.from(a.content,"base64")):Ic(c,a.content)}let n=df(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+=Ti)await n.raw(["add","-A","-f","--",...o.slice(a,a+Ti)]);for(let a=0;a<i.length;a+=Ti)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...i.slice(a,a+Ti)]);await n.raw(["reset","-q","--",...dn]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await Rc(t))}async function Rc(t){let e=df(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=cf;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 Kv(e);if(i.length>0&&i.every(a=>Bv.has(a)||lf.test(a)||Fv.test(a))){for(let a of i)lf.test(a)?await Gv(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 ${cf} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function Gv(t,e,r){let n=async s=>await t.raw(["show",`:${s}:${r}`]).catch(()=>""),o=new Map;for(let s of[await n(2),await n(3)])for(let a of s.split(`
33
- `)){let c=a.trim();if(c)try{let l=JSON.parse(c);if(typeof l.id!="string")continue;o.has(l.id)||o.set(l.id,{raw:c,createdAt:typeof l.createdAt=="string"?l.createdAt:""})}catch{}}let i=[...o.values()].sort((s,a)=>s.createdAt.localeCompare(a.createdAt)).map(s=>s.raw);Ic(Te(e,r),i.join(`
31
+ `),!0}async function lf(t,e){try{if(!er(Rt(t,".git")))return;let r=Ov(t),n=(await r.raw(["ls-files","--",...dn])).split(`
32
+ `).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;pn(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 Ic(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 Tc(t){let e=new Map;for(let r of dn){let n=Rt(t,r);er(n)&&e.set(r,Ec(n))}return e}function Rc(t,e){cf(t,{recursive:!0});for(let[r,n]of e){let o=Rt(t,r);er(o)||un(o,n)}}var dn,Lv,Ft=x(()=>{"use strict";lt();dn=["project.yaml","regimen.yaml"];Lv=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as Mv,mkdirSync as Dv,rmSync as Uv,writeFileSync as Cc}from"node:fs";import{dirname as Bv,isAbsolute as Fv,join as pf,normalize as Ri}from"node:path";import{simpleGit as ff}from"simple-git";async function Pc(t,e){let r=Ri(t),o=(Ti.get(r)??Promise.resolve()).catch(()=>{}).then(e);Ti.set(r,o);try{return await o}finally{Ti.get(r)===o&&Ti.delete(r)}}async function Ie(t,e,r){return Pc(t,()=>Ac(t,e,r))}async function Ac(t,e,r){if(!Mv(pf(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=Ee(t,a.path);if(a.deleted){Uv(c,{force:!0});continue}Dv(Bv(c),{recursive:!0}),a.encoding==="base64"?Cc(c,Buffer.from(a.content,"base64")):Cc(c,a.content)}let n=ff(t),o=e.filter(a=>!a.deleted).map(a=>a.path),i=e.filter(a=>a.deleted).map(a=>a.path);for(let a=0;a<o.length;a+=Ei)await n.raw(["add","-A","-f","--",...o.slice(a,a+Ei)]);for(let a=0;a<i.length;a+=Ei)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...i.slice(a,a+Ei)]);await n.raw(["reset","-q","--",...dn]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await Ic(t))}async function Ic(t){let e=ff(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=uf;n++){try{await e.push();return}catch(i){r=i}await e.fetch().catch(()=>{});let o=(await e.revparse(["--abbrev-ref","HEAD"])).trim();try{await e.rebase([`origin/${o}`])}catch{let i=await Wv(e);if(i.length>0&&i.every(a=>Gv.has(a)||df.test(a)||Kv.test(a))){for(let a of i)df.test(a)?await Hv(e,t,a):await e.raw(["checkout","--theirs","--",a]);await e.add(i),await e.raw(["-c","core.editor=true","rebase","--continue"])}else throw await e.rebase(["--abort"]).catch(()=>{}),new Error(`context push: rebase conflict in ${i.join(", ")||"unknown files"} \u2014 concurrent writers edited the same entry; resolve manually in the Context Repo`)}}throw new Error(`context push failed after ${uf} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function Hv(t,e,r){let n=async s=>await t.raw(["show",`:${s}:${r}`]).catch(()=>""),o=new Map;for(let s of[await n(2),await n(3)])for(let a of s.split(`
33
+ `)){let c=a.trim();if(c)try{let l=JSON.parse(c);if(typeof l.id!="string")continue;o.has(l.id)||o.set(l.id,{raw:c,createdAt:typeof l.createdAt=="string"?l.createdAt:""})}catch{}}let i=[...o.values()].sort((s,a)=>s.createdAt.localeCompare(a.createdAt)).map(s=>s.raw);Cc(Ee(e,r),i.join(`
34
34
  `)+(i.length>0?`
35
- `:""))}async function Kv(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
36
- `).map(r=>r.trim()).filter(Boolean)}function Te(t,e){if(Uv(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=Ii(uf(t,e)),n=Ii(t+"/");if(r!==Ii(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var cf,Bv,Fv,lf,Ti,Ri,lt=x(()=>{"use strict";Ft();cf=3,Bv=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),Fv=/^model\/derived\//,lf=/^tasks\/[^/]+\/comments\.jsonl$/,Ti=500,Ri=new Map});import{cpSync as Zv,existsSync as yo,mkdirSync as hf,readFileSync as Qv,readdirSync as ex,rmSync as gf,statSync as tx,writeFileSync as rx}from"node:fs";import{join as rr}from"node:path";function fn(t,e,r){let n=rr(t,"skills"),o=rr(e,".claude","skills"),i=rr(o,nx),s=ox(i),a={written:[],removed:[],skipped:[]},c=ix(n);for(let u of s)c.includes(u)||(gf(rr(o,u),{recursive:!0,force:!0}),a.removed.push(u));let l=[];for(let u of c){let p=rr(o,u);if(yo(p)&&!s.includes(u)){a.skipped.push(u);continue}hf(o,{recursive:!0}),gf(p,{recursive:!0,force:!0}),Zv(rr(n,u),p,{recursive:!0}),l.push(u),a.written.push(u)}(l.length>0||a.removed.length>0||yo(i))&&(hf(o,{recursive:!0}),rx(i,JSON.stringify({managed:l.sort()},null,2)+`
37
- `)),(a.written.length>0||a.removed.length>0)&&r.info(`[skills] context \u2192 .claude/skills: ${a.written.length} written`+(a.removed.length>0?`, ${a.removed.length} removed`:""));for(let u of a.skipped)r.warn(`[skills] "${u}" exists in .claude/skills but is not managed by CodePipe \u2014 your copy wins; rename one of them to get the context version`);return a}function ox(t){if(!yo(t))return[];try{let e=JSON.parse(Qv(t,"utf-8"));return Array.isArray(e.managed)?e.managed.filter(r=>typeof r=="string"):[]}catch{return[]}}function ix(t){return yo(t)?ex(t).filter(e=>{if(e.startsWith("."))return!1;let r=rr(t,e);try{return tx(r).isDirectory()&&yo(rr(r,"SKILL.md"))}catch{return!1}}):[]}var nx,Ci=x(()=>{"use strict";nx=".codepipe-managed.json"});import{existsSync as nr,readFileSync as mn,readdirSync as bf}from"node:fs";import{join as _c}from"node:path";import{simpleGit as $f}from"simple-git";import{parse as vf}from"yaml";function xf(t){try{let e=Te(t,co);if(!nr(e))return null;let r=vf(mn(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!Er.test(n)?null:{prefix:n}}catch{return null}}function Sf(t){return`# Built-in tracker configuration \u2014 shared by every team member.
35
+ `:""))}async function Wv(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
36
+ `).map(r=>r.trim()).filter(Boolean)}function Ee(t,e){if(Fv(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=Ri(pf(t,e)),n=Ri(t+"/");if(r!==Ri(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var uf,Gv,Kv,df,Ei,Ti,lt=x(()=>{"use strict";Ft();uf=3,Gv=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),Kv=/^model\/derived\//,df=/^tasks\/[^/]+\/comments\.jsonl$/,Ei=500,Ti=new Map});import{cpSync as ex,existsSync as yo,mkdirSync as yf,readFileSync as tx,readdirSync as rx,rmSync as wf,statSync as nx,writeFileSync as ox}from"node:fs";import{join as rr}from"node:path";function fn(t,e,r){let n=rr(t,"skills"),o=rr(e,".claude","skills"),i=rr(o,ix),s=sx(i),a={written:[],removed:[],skipped:[]},c=ax(n);for(let u of s)c.includes(u)||(wf(rr(o,u),{recursive:!0,force:!0}),a.removed.push(u));let l=[];for(let u of c){let p=rr(o,u);if(yo(p)&&!s.includes(u)){a.skipped.push(u);continue}yf(o,{recursive:!0}),wf(p,{recursive:!0,force:!0}),ex(rr(n,u),p,{recursive:!0}),l.push(u),a.written.push(u)}(l.length>0||a.removed.length>0||yo(i))&&(yf(o,{recursive:!0}),ox(i,JSON.stringify({managed:l.sort()},null,2)+`
37
+ `)),(a.written.length>0||a.removed.length>0)&&r.info(`[skills] context \u2192 .claude/skills: ${a.written.length} written`+(a.removed.length>0?`, ${a.removed.length} removed`:""));for(let u of a.skipped)r.warn(`[skills] "${u}" exists in .claude/skills but is not managed by CodePipe \u2014 your copy wins; rename one of them to get the context version`);return a}function sx(t){if(!yo(t))return[];try{let e=JSON.parse(tx(t,"utf-8"));return Array.isArray(e.managed)?e.managed.filter(r=>typeof r=="string"):[]}catch{return[]}}function ax(t){return yo(t)?rx(t).filter(e=>{if(e.startsWith("."))return!1;let r=rr(t,e);try{return nx(r).isDirectory()&&yo(rr(r,"SKILL.md"))}catch{return!1}}):[]}var ix,Ii=x(()=>{"use strict";ix=".codepipe-managed.json"});import{existsSync as nr,readFileSync as mn,readdirSync as vf}from"node:fs";import{join as jc}from"node:path";import{simpleGit as xf}from"simple-git";import{parse as Sf}from"yaml";function Ef(t){try{let e=Ee(t,co);if(!nr(e))return null;let r=Sf(mn(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!Er.test(n)?null:{prefix:n}}catch{return null}}function Tf(t){return`# Built-in tracker configuration \u2014 shared by every team member.
38
38
  # The issue-key prefix (<PREFIX>-<N>). Fixed at project init: changing it
39
39
  # later would orphan existing tasks/<KEY>/ directories.
40
40
  prefix: ${t}
@@ -42,13 +42,13 @@ prefix: ${t}
42
42
  # Statuses are the built-in default set for now:
43
43
  # Backlog | To Do | In Progress | Review | Done | Rejected
44
44
  # A configurable status set / pipeline mapping is a planned extension.
45
- `}function jc(t=0){return`${t}
46
- `}function lx(t){return t==="depends_on"||t==="subtask"}function ux(t){let e;try{e=vf(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=Za.includes(r.type)?r.type:ao,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;lx(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 Nc(t){let e=[`key: ${t.key}`,`title: ${JSON.stringify(t.title)}`,`type: ${t.type}`,`status: ${JSON.stringify(t.status)}`];if(t.assignee&&e.push(`assignee: ${JSON.stringify(t.assignee)}`),t.links.length>0){e.push("links:");for(let r of t.links)e.push(` - type: ${r.type}`,` target: ${r.targetKey}`)}return e.push(`created: ${t.created}`,`updated: ${t.updated}`),e.join(`
45
+ `}function Nc(t=0){return`${t}
46
+ `}function dx(t){return t==="depends_on"||t==="subtask"}function px(t){let e;try{e=Sf(t)}catch{return null}if(!e||typeof e!="object")return null;let r=e;if(typeof r.key!="string"||r.key.length===0||typeof r.title!="string"||r.title.length===0)return null;let n=Qa.includes(r.type)?r.type:ao,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;dx(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 Oc(t){let e=[`key: ${t.key}`,`title: ${JSON.stringify(t.title)}`,`type: ${t.type}`,`status: ${JSON.stringify(t.status)}`];if(t.assignee&&e.push(`assignee: ${JSON.stringify(t.assignee)}`),t.links.length>0){e.push("links:");for(let r of t.links)e.push(` - type: ${r.type}`,` target: ${r.targetKey}`)}return e.push(`created: ${t.created}`,`updated: ${t.updated}`),e.join(`
47
47
  `)+`
48
- `}function ko(t,e){let r=Te(t,Qr(e));return nr(r)?ux(mn(r,"utf-8")):null}function Ef(t){let e=_c(t,"tasks");if(!nr(e))return[];let r=[];for(let n of bf(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=ko(t,n.name);o&&r.push(o)}return r}function dx(t,e){let r=Te(t,`tasks/${e}/task.md`);if(nr(r))return lo(mn(r,"utf-8"))}function bo(t,e,r={}){let n=r.withDescription?dx(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:px(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function px(t){return t.charAt(0).toUpperCase()+t.slice(1)}function fx(t){let e=Te(t,Zr);if(!nr(e))return 0;let r=Number.parseInt(mn(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function mx(t,e){let r=_c(t,"tasks");if(!nr(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of bf(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 hx(t,e){return Math.max(fx(t),mx(t,e))+1}async function Tf(t,e,r,n){return Cc(t,()=>gx(t,e,r,n))}async function gx(t,e,r,n){if(!nr(_c(t,".git")))throw new Error(`context repo clone not found at ${t}`);await wo(t);let o=null;for(let i=0;i<kf;i++){let s=hx(t,e),a=`${e}-${s}`,c=[...r(a),{path:Zr,content:jc(s)}];try{return await Pc(t,c,n(a)),a}catch(l){if(o=l,await wx(t,n(a)),await wo(t),yx(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${kf} attempts: ${o instanceof Error?o.message:String(o)}`)}function yx(t,e){for(let r of e){let n=Te(t,r.path);if(!nr(n)||(r.encoding==="base64"?mn(n).toString("base64"):mn(n,"utf-8"))!==r.content)return!1}return!0}async function wo(t){let e=$f(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 wx(t,e){let r=$f(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
48
+ `}function ko(t,e){let r=Ee(t,Qr(e));return nr(r)?px(mn(r,"utf-8")):null}function Rf(t){let e=jc(t,"tasks");if(!nr(e))return[];let r=[];for(let n of vf(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=ko(t,n.name);o&&r.push(o)}return r}function fx(t,e){let r=Ee(t,`tasks/${e}/task.md`);if(nr(r))return lo(mn(r,"utf-8"))}function bo(t,e,r={}){let n=r.withDescription?fx(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:mx(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function mx(t){return t.charAt(0).toUpperCase()+t.slice(1)}function hx(t){let e=Ee(t,Zr);if(!nr(e))return 0;let r=Number.parseInt(mn(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function gx(t,e){let r=jc(t,"tasks");if(!nr(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of vf(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 yx(t,e){return Math.max(hx(t),gx(t,e))+1}async function If(t,e,r,n){return Pc(t,()=>wx(t,e,r,n))}async function wx(t,e,r,n){if(!nr(jc(t,".git")))throw new Error(`context repo clone not found at ${t}`);await wo(t);let o=null;for(let i=0;i<$f;i++){let s=yx(t,e),a=`${e}-${s}`,c=[...r(a),{path:Zr,content:Nc(s)}];try{return await Ac(t,c,n(a)),a}catch(l){if(o=l,await bx(t,n(a)),await wo(t),kx(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${$f} attempts: ${o instanceof Error?o.message:String(o)}`)}function kx(t,e){for(let r of e){let n=Ee(t,r.path);if(!nr(n)||(r.encoding==="base64"?mn(n).toString("base64"):mn(n,"utf-8"))!==r.content)return!1}return!0}async function wo(t){let e=xf(t);try{await e.fetch()}catch{return}try{let r=(await e.revparse(["--abbrev-ref","HEAD"])).trim();await e.rebase([`origin/${r}`])}catch{await e.rebase(["--abort"]).catch(()=>{})}}async function bx(t,e){let r=xf(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
49
49
  `)[0]||!(await r.raw(["log","@{u}..HEAD","--pretty=%s"]).catch(()=>"")).trim().split(`
50
50
  `).some(i=>i.trim()===e.split(`
51
- `)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var kf,Ai=x(()=>{"use strict";B();lt();kf=5});function hn(t,e,r,n){return[{path:"README.md",content:_x(t,e)},{path:".gitignore",content:Sx()},{path:"CLAUDE.md",content:Tx(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:Ex()},{path:"knowledge/README.md",content:Rx()},{path:"knowledge/build.yaml",content:Ax()},{path:"actions/README.md",content:Ix()},{path:"roles/README.md",content:Cx()},{path:"skills/README.md",content:Px()},{path:"model/README.md",content:kx()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:xx()},{path:"adr/README.md",content:bx()},{path:"adr/0000-template.md",content:$x()},{path:"adr/INDEX.md",content:vx()},{path:yt,content:Zn()},...t.trackerProvider==="internal"?[{path:co,content:Sf(t.youtrackProjectKey??ci)},{path:Zr,content:jc()}]:[]]}function kx(){return`# model/ \u2014 the project map
51
+ `)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var $f,Pi=x(()=>{"use strict";B();lt();$f=5});function hn(t,e,r,n){return[{path:"README.md",content:Nx(t,e)},{path:".gitignore",content:Tx()},{path:"CLAUDE.md",content:Ix(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:Rx()},{path:"knowledge/README.md",content:Cx()},{path:"knowledge/build.yaml",content:jx()},{path:"actions/README.md",content:Px()},{path:"roles/README.md",content:Ax()},{path:"skills/README.md",content:_x()},{path:"model/README.md",content:$x()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:Ex()},{path:"adr/README.md",content:vx()},{path:"adr/0000-template.md",content:xx()},{path:"adr/INDEX.md",content:Sx()},{path:yt,content:Zn()},...t.trackerProvider==="internal"?[{path:co,content:Tf(t.youtrackProjectKey??ci)},{path:Zr,content:Nc()}]:[]]}function $x(){return`# model/ \u2014 the project map
52
52
 
53
53
  A graph of the project built from **git history and task artifacts**: files
54
54
  and directories connected by the fact of changing together and the fact of
@@ -75,7 +75,7 @@ asset \u2014 treat it like \`knowledge/\`.
75
75
 
76
76
  Every YAML file carries \`modelFormatVersion\`; a reader that meets a
77
77
  different version treats it as "rebuild needed", not as an error.
78
- `}function bx(){return`# ADR \u2014 architecture decision records
78
+ `}function vx(){return`# ADR \u2014 architecture decision records
79
79
 
80
80
  Accepted architectural decisions of this project \u2014 its **framework**. The
81
81
  agent reads this section (start with \`INDEX.md\`) at the beginning of every
@@ -103,7 +103,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
103
103
  canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
104
104
  is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
105
105
  open a PR to this repository.
106
- `}function $x(){return`# ADR-NNNN: <title>
106
+ `}function xx(){return`# ADR-NNNN: <title>
107
107
 
108
108
  - **Status:** accepted | superseded by ADR-NNNN
109
109
  - **Date:** YYYY-MM-DD
@@ -125,12 +125,12 @@ What becomes easier, what becomes harder, what future tasks must keep doing.
125
125
  ## Alternatives considered
126
126
 
127
127
  - **<alternative>** \u2014 why it was rejected.
128
- `}function vx(){return`# ADR index
128
+ `}function Sx(){return`# ADR index
129
129
 
130
130
  <!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->
131
131
 
132
132
  (no accepted ADRs yet)
133
- `}function xx(){return`# Audit
133
+ `}function Ex(){return`# Audit
134
134
 
135
135
  Pipeline event logs. Naming is per-writer: each codepipe
136
136
  project appends only to its own file \u2014
@@ -139,14 +139,14 @@ project appends only to its own file \u2014
139
139
 
140
140
  \u2014 so several team members' CLIs never contend on one file. Do not create a
141
141
  shared aggregate here.
142
- `}function Rt(t,e,r,n,o=Xe,i){let s=t.trackerProvider==="internal";return{projectYaml:s?jx(t):Nx(t,r,n),regimenYaml:Ox(t.automationLevel,s?!0:e,s,o,i)}}function Sx(){return`# codepipe project config is local to each member's workspace
142
+ `}function It(t,e,r,n,o=Xe,i){let s=t.trackerProvider==="internal";return{projectYaml:s?Ox(t):Lx(t,r,n),regimenYaml:Mx(t.automationLevel,s?!0:e,s,o,i)}}function Tx(){return`# codepipe project config is local to each member's workspace
143
143
  project.yaml
144
144
  regimen.yaml
145
145
 
146
146
  # codepipe runtime
147
147
  session.log
148
148
  apply-queue.json
149
- `}function Ex(){return`# Index prompt
149
+ `}function Rx(){return`# Index prompt
150
150
 
151
151
  You are the **Indexer** agent on the CodePipe pipeline. Your one job is to build a
152
152
  navigation map of this project's repositories and save it to the Context Repo, so
@@ -203,7 +203,7 @@ current working directory; write nothing else under the Context Repo.
203
203
  Keep both durable and skimmable \u2014 they are read at the start of every future
204
204
  task. Prefer structure (headings, bullet lists) over prose. If a repository is
205
205
  empty or unavailable, say so briefly rather than inventing content.
206
- `}function Tx(t){return`# Project context for the CodePipe agent
206
+ `}function Ix(t){return`# Project context for the CodePipe agent
207
207
 
208
208
  Instructions for AI agents working on **${t.name}** tasks. Claude Code
209
209
  auto-loads this file when the Context Repo is mounted. Keep it short and
@@ -231,7 +231,7 @@ project's architectural invariants: read them at the start of a task and treat
231
231
  them as binding. New or changed decisions do **not** go here directly \u2014 during
232
232
  analysis you draft them as task artifacts, and they are promoted into \`adr/\`
233
233
  only after the analysis is approved.
234
- `}function Rx(){return`# Knowledge
234
+ `}function Cx(){return`# Knowledge
235
235
 
236
236
  Durable, reusable notes about this project \u2014 the CodePipe agent's long-lived
237
237
  **memory** across tasks. Architectural decisions, domain rules,
@@ -248,7 +248,7 @@ Keep each note in its own file \u2014 never grow one shared aggregate \u2014 so
248
248
  concurrent commits touch different files and rebase cleanly. \`INDEX.md\` is
249
249
  REGENERATED from the entries by the index job: don't hand-edit it, and treat
250
250
  any merge conflict in it as noise (either side converges on the next run).
251
- `}function Ix(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
251
+ `}function Px(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
252
252
 
253
253
  One \`<id>.yml\` per action. Every file here appears as a button on the
254
254
  project's **RUN** tab; an action with \`params\` opens a small wizard first.
@@ -287,7 +287,7 @@ steps:
287
287
  Parameter values are passed to the commands **only as env vars** \u2014 reference
288
288
  them as \`$INPUT_<NAME>\` in \`run\`; they are never substituted into the
289
289
  command text itself.
290
- `}function Cx(){return`# roles/ \u2014 who reviews your work
290
+ `}function Ax(){return`# roles/ \u2014 who reviews your work
291
291
 
292
292
  A **role** is a critic with a narrow view and its own curated context: one
293
293
  \`<name>.md\` per role. Roles review a plan before the work starts, review the
@@ -315,7 +315,7 @@ You are the security critic. \u2026the body is the role's prompt\u2026
315
315
 
316
316
  Keep \`refs\` short and specific: the value of a role is a NARROW view, and
317
317
  "give it everything" is exactly the failure this design avoids.
318
- `}function Px(){return`# skills/ \u2014 procedures the agent can invoke
318
+ `}function _x(){return`# skills/ \u2014 procedures the agent can invoke
319
319
 
320
320
  A **skill** is a directory with a \`SKILL.md\`: a description of when to use it,
321
321
  a body with the steps, and any files the steps need beside it (scripts,
@@ -374,7 +374,7 @@ A third-party marketplace **must** name a full commit sha: its skills run beside
374
374
  your checked-out code with the agent's credentials, and a branch would let that
375
375
  code change between two runs of the same task. Nothing from a marketplace is
376
376
  active until it is listed in \`plugins\`.
377
- `}function Ax(){return`# BUILD phase config. Discovered & maintained by the agent.
377
+ `}function jx(){return`# BUILD phase config. Discovered & maintained by the agent.
378
378
  # Steps run in a rootless Podman container in the SANDBOX, before the PR.
379
379
  # Success = every step exits 0. Credentials are NOT available inside the container.
380
380
  #
@@ -390,7 +390,7 @@ active until it is listed in \`plugins\`.
390
390
  # - name: test
391
391
  # run: npm test
392
392
  # timeout_sec: 600 # per-step timeout (optional, default 600)
393
- `}function _x(t,e){return`# ${e.name}
393
+ `}function Nx(t,e){return`# ${e.name}
394
394
 
395
395
  Context Repo for the **${t.name}** project (CodePipe).
396
396
 
@@ -416,7 +416,7 @@ PRs to this repository (and the agent also writes to \`knowledge/\` and
416
416
  pipeline \u2014 don't edit them by hand.
417
417
 
418
418
  Automation level: **${t.automationLevel}**.
419
- `}function jx(t){return`# Project description for CodePipe.
419
+ `}function Ox(t){return`# Project description for CodePipe.
420
420
  id: ${t.projectId}
421
421
  name: ${t.name}
422
422
 
@@ -441,9 +441,9 @@ adapters:
441
441
  # Branch (must keep the <TASK_ID> placeholder).
442
442
  branch:
443
443
  pattern: codepipe/<TASK_ID>
444
- ${Rf(t)}
444
+ ${Cf(t)}
445
445
  repos:
446
- ${If(t)}
446
+ ${Pf(t)}
447
447
  # A repo may declare a mirror \u2014 a repository CodePipe owns that stands in for
448
448
  # origin for the whole pipeline: task branches, PRs and merges happen there and
449
449
  # your own repository is never written. All-or-nothing: either every repo
@@ -453,21 +453,21 @@ ${If(t)}
453
453
  # host: github
454
454
  # owner: your-org
455
455
  # repo: api-codepipe-mirror
456
- `}function Rf(t){let e=t.language;return!e||Object.keys(e).length===0?"":`
456
+ `}function Cf(t){let e=t.language;return!e||Object.keys(e).length===0?"":`
457
457
  # Languages the agent writes in, per area. \`auto\` = mirror the language of
458
458
  # the user's material. Also editable from the dashboard: project card \u2192
459
459
  # Settings \u2192 Language.
460
460
  language:
461
461
  ${Object.entries(e).map(([n,o])=>` ${n}: ${o}`).join(`
462
462
  `)}
463
- `}function If(t){return t.repos.length===0?` [] # add repos here
463
+ `}function Pf(t){return t.repos.length===0?` [] # add repos here
464
464
  `:t.repos.map(e=>` - name: ${e.name}
465
465
  host: ${e.host}
466
466
  owner: ${e.owner}
467
467
  repo: ${e.repoName}
468
468
  mount_as: ${e.mountAs??e.name}`+(e.defaultBranch?`
469
469
  default_branch: ${e.defaultBranch}`:"")).join(`
470
- `)}function Nx(t,e,r){let n=e?`
470
+ `)}function Lx(t,e,r){let n=e?`
471
471
  tracker_url: ${e}`:`
472
472
  # tracker_url: https://your.youtrack.cloud`,o=r?`require_assignee: true
473
473
  assignee: ${r}`:`require_assignee: false
@@ -515,7 +515,7 @@ ${Object.entries(e).map(([n,o])=>` ${n}: ${o}`).join(`
515
515
  # non-empty assignee. assignee only takes effect when require_assignee=true.
516
516
  ${o}`:` # project_key: \u2026
517
517
  # tracker_url: https://your.youtrack.cloud
518
- poll_interval_sec: 60`,s=If(t);return`# Project description for CodePipe.
518
+ poll_interval_sec: 60`,s=Pf(t);return`# Project description for CodePipe.
519
519
  id: ${t.projectId}
520
520
  name: ${t.name}
521
521
 
@@ -547,10 +547,10 @@ adapters:
547
547
  # Branch (must keep the <TASK_ID> placeholder).
548
548
  branch:
549
549
  pattern: codepipe/<TASK_ID>
550
- ${Rf(t)}
550
+ ${Cf(t)}
551
551
  repos:
552
552
  ${s}
553
- `}function Ox(t,e,r=!1,n=Xe,o){let i=t==="full",s=e?"true":"false",a=o?` # Model selection. This project's Claude subscription did not include every
553
+ `}function Mx(t,e,r=!1,n=Xe,o){let i=t==="full",s=e?"true":"false",a=o?` # Model selection. This project's Claude subscription did not include every
554
554
  # model in the recommended per-role split, so CodePipe set a single default
555
555
  # your subscription can serve for all roles. Tune per role later from the
556
556
  # dashboard (Project Settings \u2192 llm.models) or by editing this file.
@@ -692,35 +692,35 @@ ${a}
692
692
  # sandbox quota (how many runners the account may occupy), enforced by the HUB
693
693
  # and sized on the farm. A solo 'codepipe up' runs one worker. (ADR-0030)
694
694
 
695
- `}var Ar=x(()=>{"use strict";B();Ai()});function Of(t){Nf=t}function ut(t,e="info"){Nf(t,e)}var Nf,ji=x(()=>{"use strict";Nf=t=>console.log(t)});import{homedir as Jx,tmpdir as rN}from"node:os";import{existsSync as Zx,mkdirSync as Qx,mkdtempSync as oN,rmSync as iN}from"node:fs";import{join as Lc}from"node:path";import{simpleGit as Mc}from"simple-git";function je(t,e,r){let n=r??Lc(Jx(),".codepipe","repos");return Lc(n,t,e)}async function or(t,e,r={}){let n=je(t,e.name,r.baseDir),o=r.cloneUrlOverride??Uc(e);if(!Zx(Lc(n,".git"))){Qx(n,{recursive:!0});let c=Mc();ut(`[git] clone ${o} \u2192 ${n}`);try{await c.clone(o,n)}catch(l){let u=l instanceof Error?l.message:String(l);throw new Error(`git clone failed: ${o}
696
- ${u.trim()}`)}}let i=Mc(n),s=(await i.remote(["get-url","origin"]).catch(()=>"")||"").toString().trim();s&&s!==o&&(ut(`[git] ${e.name}: origin ${s} \u2192 ${o} (spec changed)`),await i.remote(["set-url","origin",o]));try{await i.fetch()}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git fetch failed in ${n}
697
- ${l.trim()}`)}let a=e.defaultBranch??"main";return await i.checkout(["-B",a,`origin/${a}`]).catch(()=>{}),i}async function gn(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function eS(t,e){let{contextRepoCloneUrl:r,deliveryRef:n,deliverySha:o,baseSha:i,commitMessage:s}=e;await t.raw(["fetch",r,`+refs/heads/${n}:refs/codepipe-delivery`]);let a=(await t.revparse(["refs/codepipe-delivery"])).trim();o&&a!==o&&ut(`[git] delivery ${n} resolved ${a.slice(0,10)} (expected ${o.slice(0,10)})`);let c=(await t.raw(["rev-parse","refs/codepipe-delivery^{tree}"])).trim();if(await gn(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await gn(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([...Dc,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function tS(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await gn(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await gn(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 Mf(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 tS(t,i,()=>eS(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));p&&await t.raw(["branch","-D",a]).catch(()=>{});let m=`origin/${c}`;await gn(t,m)||(m=`origin/${u??c}`);let f=(await t.revparse([m])).trim(),y=0;if(f===s)await t.raw(["branch","-f",a,d]),await t.checkout(a);else{y=parseInt((await t.raw(["rev-list","--count",`${s}..${f}`]).catch(()=>"1")).trim(),10)||1,await t.checkout(["-B",a,m]);try{await t.raw([...Dc,"cherry-pick",d])}catch(w){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let $=w instanceof Error?w.message:String(w);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
698
- ${$.trim()}`)}}let k=(await t.revparse(["HEAD"])).trim(),h=r.push!==!1;if(h){let w=p?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push(w)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:k,pushed:h,...y>0?{baseMoved:y}:{}}}async function Df(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 Uf(t,e,r){let{branchName:n,dropTaskKeys:o}=r,i=`origin/${n}`;if(!await gn(t,i))throw new Error(`rewrite_cluster_branch: ${i} not found upstream`);let s=`origin/${r.defaultBranch??"main"}`,a=(await t.raw(["merge-base",i,s])).trim(),c=(await t.raw(["rev-list","--reverse",`${a}..${i}`])).split(`
695
+ `}var Ar=x(()=>{"use strict";B();Pi()});function Mf(t){Lf=t}function ut(t,e="info"){Lf(t,e)}var Lf,_i=x(()=>{"use strict";Lf=t=>console.log(t)});import{homedir as Qx,tmpdir as aN}from"node:os";import{existsSync as eS,mkdirSync as tS,mkdtempSync as lN,rmSync as uN}from"node:fs";import{join as Mc}from"node:path";import{simpleGit as Dc}from"simple-git";function _e(t,e,r){let n=r??Mc(Qx(),".codepipe","repos");return Mc(n,t,e)}async function or(t,e,r={}){let n=_e(t,e.name,r.baseDir),o=r.cloneUrlOverride??Bc(e);if(!eS(Mc(n,".git"))){tS(n,{recursive:!0});let c=Dc();ut(`[git] clone ${o} \u2192 ${n}`);try{await c.clone(o,n)}catch(l){let u=l instanceof Error?l.message:String(l);throw new Error(`git clone failed: ${o}
696
+ ${u.trim()}`)}}let i=Dc(n),s=(await i.remote(["get-url","origin"]).catch(()=>"")||"").toString().trim();s&&s!==o&&(ut(`[git] ${e.name}: origin ${s} \u2192 ${o} (spec changed)`),await i.remote(["set-url","origin",o]));try{await i.fetch()}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git fetch failed in ${n}
697
+ ${l.trim()}`)}let a=e.defaultBranch??"main";return await i.checkout(["-B",a,`origin/${a}`]).catch(()=>{}),i}async function gn(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function rS(t,e){let{contextRepoCloneUrl:r,deliveryRef:n,deliverySha:o,baseSha:i,commitMessage:s}=e;await t.raw(["fetch",r,`+refs/heads/${n}:refs/codepipe-delivery`]);let a=(await t.revparse(["refs/codepipe-delivery"])).trim();o&&a!==o&&ut(`[git] delivery ${n} resolved ${a.slice(0,10)} (expected ${o.slice(0,10)})`);let c=(await t.raw(["rev-parse","refs/codepipe-delivery^{tree}"])).trim();if(await gn(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await gn(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([...Uc,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function nS(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await gn(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await gn(t,o)){let s=(await t.revparse([o])).trim();return await t.raw(["update-ref",n,s]).catch(()=>{}),s}let i=await r();return await t.raw(["update-ref",n,i]).catch(()=>{}),i}async function Uf(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:u,force:p}=r,d=await nS(t,i,()=>rS(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));p&&await t.raw(["branch","-D",a]).catch(()=>{});let m=`origin/${c}`;await gn(t,m)||(m=`origin/${u??c}`);let f=(await t.revparse([m])).trim(),g=0;if(f===s)await t.raw(["branch","-f",a,d]),await t.checkout(a);else{g=parseInt((await t.raw(["rev-list","--count",`${s}..${f}`]).catch(()=>"1")).trim(),10)||1,await t.checkout(["-B",a,m]);try{await t.raw([...Uc,"cherry-pick",d])}catch(w){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let $=w instanceof Error?w.message:String(w);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
698
+ ${$.trim()}`)}}let k=(await t.revparse(["HEAD"])).trim(),h=r.push!==!1;if(h){let w=p?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push(w)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:k,pushed:h,...g>0?{baseMoved:g}:{}}}async function Bf(t,e,r){let n=r.force?["--force-with-lease","-u","origin",r.branchName]:["-u","origin",r.branchName];return await t.push(n),{pushed:!0}}async function Ff(t,e,r){let{branchName:n,dropTaskKeys:o}=r,i=`origin/${n}`;if(!await gn(t,i))throw new Error(`rewrite_cluster_branch: ${i} not found upstream`);let s=`origin/${r.defaultBranch??"main"}`,a=(await t.raw(["merge-base",i,s])).trim(),c=(await t.raw(["rev-list","--reverse",`${a}..${i}`])).split(`
699
699
  `).map(m=>m.trim()).filter(m=>m.length>0),l=new Set(o.map(m=>m.toUpperCase())),u=[],p=0;for(let m of c)(await t.raw(["show","-s","--format=%(trailers:key=CodePipe-Task,valueonly)",m])).split(`
700
- `).map(k=>k.trim().toUpperCase()).filter(k=>k.length>0).some(k=>l.has(k))?p++:u.push(m);if(p===0)return{commit:(await t.revparse([i])).trim(),dropped:0};await t.checkout(["-B",n,a]);for(let m of u)try{await t.raw([...Dc,"cherry-pick","--allow-empty","--keep-redundant-commits",m])}catch(f){await t.raw(["cherry-pick","--abort"]).catch(()=>{}),await t.checkout(["-B",n,i]).catch(()=>{});let y=f instanceof Error?f.message:String(f);throw new Error(`rewrite_cluster_branch: replaying ${m.slice(0,10)} after dropping ${o.join(", ")} hit conflicts
701
- ${y.trim()}`)}let d=(await t.revparse(["HEAD"])).trim();return await t.push(["--force-with-lease","-u","origin",n]),{commit:d,dropped:p}}async function Bf(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 Uc(t){return t.mirror?Lf(t.mirror.host,t.mirror.owner,t.mirror.repoName):Lf(t.host,t.owner,t.repoName)}function Lf(t,e,r){return t==="github"?`git@github.com:${e}/${r}.git`:t==="gitlab"?`git@gitlab.com:${e}/${r}.git`:`git@bitbucket.org:${e}/${r}.git`}function Ni(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 Ff(t){return(await Mc().listRemote(["--heads",t])).split(`
702
- `).map(r=>r.trim()).filter(r=>r.length>0).map(r=>r.split(/\s+/)[1]??"").filter(r=>r.startsWith("refs/heads/")).map(r=>r.slice(11))}function Gf(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}var Dc,vo=x(()=>{"use strict";ji();Dc=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{createCipheriv as rS,createDecipheriv as nS,createHash as oS,createPrivateKey as iS,createPublicKey as Bc,diffieHellman as Kf,generateKeyPairSync as Hf,hkdfSync as Wf,randomBytes as sS}from"node:crypto";function Oi(){let{publicKey:t,privateKey:e}=Hf("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function He(t){let e=Buffer.from(t,"base64");return(oS("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function Gt(t,e){let r=Bc({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=Hf("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=Kf({privateKey:o,publicKey:r}),c=Buffer.from(Wf("sha256",a,Buffer.concat([i,s]),qf,32)),l=sS(12),u=rS("aes-256-gcm",c,l),p=typeof e=="string"?Buffer.from(e,"utf-8"):e,d=Buffer.concat([u.update(p),u.final()]),m=u.getAuthTag(),f={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:m.toString("base64"),ct:d.toString("base64")};return Buffer.from(JSON.stringify(f),"utf-8").toString("base64")}function yn(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=iS({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=Bc({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=Bc(n).export({type:"spki",format:"der"}),a=Kf({privateKey:n,publicKey:o}),c=Buffer.from(Wf("sha256",a,Buffer.concat([i,s]),qf,32)),l=nS("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 qf,dt=x(()=>{"use strict";qf=Buffer.from("devpipe-sealedbox-v1","utf-8")});function xo(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@github.com:"),o(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function So(t,e=process.env){if(!t)return!1;let r=`https://oauth2:${t}@gitlab.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@gitlab.com:"),o(1,"ssh://git@gitlab.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function Eo(t,e=process.env){if(!t)return!1;let r=`https://${Dt}:${encodeURIComponent(t)}@bitbucket.org/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@bitbucket.org:"),o(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function Fc(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 zf(t,e=process.env){return Fc(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>xo(t,e),e)}function Vf(t,e=process.env){return Fc(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>So(t,e),e)}function Xf(t,e=process.env){return Fc(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Dt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>Eo(t,e),e)}var Li=x(()=>{"use strict";B()});import{existsSync as sm,readFileSync as am,writeFileSync as cm}from"node:fs";import{join as lm}from"node:path";import{isMap as Mi,parseDocument as um}from"yaml";async function dm(t,e){let r=e.repoName?.trim(),n=e.defaultBranch?.trim();if(!r)throw new Error("repoName must be a non-empty string");if(!n||!so(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=lm(t,"project.yaml");if(!sm(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=um(am(o,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>Mi(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!Mi(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),cm(o,i.toString()),{repoName:r,defaultBranch:n}}function pm(t,e,r){let n=lm(t,"project.yaml");if(!sm(n))throw new Error(`project.yaml not found in context repo (${t})`);let o=um(am(n,"utf-8")),i=o.get("repos"),a=(i&&typeof i=="object"&&"items"in i?i.items:[]).find(c=>Mi(c)&&String(c.get("name")??c.get("repo")??"")===e);if(!Mi(a))throw new Error(`repo "${e}" not found in project.yaml repos[]`);a.set("mirror",{host:r.host,owner:r.owner,repo:r.repoName}),cm(n,o.toString())}var Gc=x(()=>{"use strict";B()});import{existsSync as Yc,readFileSync as zc}from"node:fs";import{join as Vc}from"node:path";import{simpleGit as wm}from"simple-git";import{parse as Xc}from"yaml";function bm(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(TS.source,"g")}function $m(t){let e=Vc(t,"project.yaml");if(Yc(e))try{let o=Xc(zc(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=Vc(t,"tracker","config.yaml");if(Yc(r))try{let o=Xc(zc(r,"utf-8"))?.prefix;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return null}function vm(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 RS(t,e,r){let o=await wm(t).raw(["log","--numstat","--format=@@@ %H %ct %P %x09%s","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
703
- `))if(a.startsWith("@@@ ")){let c=a.indexOf(" "),l=(c>=0?a.slice(4,c):a.slice(4)).trim().split(/\s+/),u=c>=0?a.slice(c+1):"",p=l[0]??"",d=Number(l[1]??0),m=l.slice(2),f=Jc.exec(u)??km.exec(u);s={sha:p,timeSec:d,subject:u,files:[],prNumber:f?Number(f[1]):null,isMerge:m.length>1},i.push(s)}else if(a.trim()&&s){let c=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(a);if(!c)continue;let l=c[1]==="-"?0:Number(c[1]),u=c[2]==="-"?0:Number(c[2]);s.files.push({path:vm(c[3]),churn:l+u})}return i}async function IS(t,e){let n=await wm(t).raw(["diff","--numstat",`${e}^1`,e]).catch(()=>""),o=[];for(let i of n.split(`
704
- `)){let s=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(i);if(!s)continue;let a=s[1]==="-"?0:Number(s[1]),c=s[2]==="-"?0:Number(s[2]);o.push({path:vm(s[3]),churn:a+c})}return o}function CS(t){let{repo:e,issueKeyRe:r,commits:n,pathToCurrent:o,entityByKey:i,ignored:s}=t,a=new Map;for(let c of[...n].reverse()){let l=[...new Set(c.subject.match(r)??[])],u,p,d=l.slice(1);if(l.length>0)u=l[0],p=c.subject.replace(new RegExp(`^\\s*${u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[:\u2014-]\\s*`),"").replace(Jc,"").trim();else if(c.prNumber!==null){if((t.trackerProjectKey??"").toUpperCase()==="PR")continue;u=`PR-${c.prNumber}`,p=c.subject.replace(Jc,"").replace(km,"").replace(/^from\s+/,"").trim()||c.subject}else continue;if(!/^[A-Za-z0-9._-]+$/.test(u))continue;let m=new Map;for(let k of c.files){let h=o.get(k.path)??k.path;s(h)||m.set(h,(m.get(h)??0)+k.churn)}if(m.size===0)continue;let y=a.get(u)??{modelFormatVersion:2,taskKey:u,origin:"bootstrap",title:"",commits:[],files:[]};p&&(y.title=p),c.timeSec>0&&(y.date=new Date(c.timeSec*1e3).toISOString().slice(0,10)),y.commits.push(c.sha);for(let[k,h]of m){let w=we("code",e,k),$=y.files.find(S=>S.key===w);if($)$.churn=($.churn??0)+h;else{let S=i.get(w);y.files.push({key:w,...S?{entityId:S}:{},churn:h})}}if(d.length>0){let k=new Set([...y.links?.tasks??[],...d]);k.delete(u),y.links={...y.links??{},tasks:[...k].sort()}}a.set(u,y)}return a}function ym(t,e){if(!t)return e;if(t.origin==="pipeline")return null;let r=[...new Set([...t.commits,...e.commits])],n=new Map(t.files.map(i=>[i.key,i]));for(let i of e.files)n.has(i.key)||n.set(i.key,i);let o=[...new Set([...t.links?.tasks??[],...e.links?.tasks??[]])].sort();return{...t,commits:r,files:[...n.values()],...o.length>0?{links:{...t.links??{},tasks:o}}:{}}}async function xm(t){let e=await RS(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 IS(t.repoDir,r.sha))}return CS({repo:t.repo,issueKeyRe:t.issueKeyRe,commits:e,pathToCurrent:t.pathToCurrent,entityByKey:t.entityByKey,ignored:t.ignored,trackerProjectKey:t.trackerProjectKey??null})}function Sm(t,e){let r=new Map;for(let i of e)for(let[s,a]of i){let c=r.get(s);r.set(s,c?ym(c,a)??c:a)}let n=[],o=0;for(let[i,s]of[...r.entries()].sort(([a],[c])=>a<c?-1:1)){let a=ym(Bi(t,i),s);if(!a){o++;continue}n.push({path:kr(i),content:zr(a)})}return{files:n,skippedPipeline:o}}function Bi(t,e){let r=Vc(t,kr(e));if(!Yc(r))return null;try{let n=Lt(Xc(zc(r,"utf-8")));return n.ok?n.value:null}catch{return null}}var TS,Jc,km,Zc=x(()=>{"use strict";B();TS=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g,Jc=/\(#(\d+)\)\s*$/,km=/^Merge pull request #(\d+)\b/});import{simpleGit as PS}from"simple-git";async function Tm(t,e,r){let o=await PS(t).raw(["log","--no-merges","--name-only","--format=@@@ %H %ct","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
705
- `))if(a.startsWith("@@@ ")){let[c,l]=a.slice(4).trim().split(/\s+/);s={sha:c??"",timeSec:Number(l??0),files:[]},i.push(s)}else a.trim()&&s&&s.files.push(a.trim());return i}function Fi(t){let e=new Map;for(let r of t.entities){if(r.status!=="active"||!r.aliases)continue;let n=re(r.currentKey);if(n?.level==="code")for(let o of r.aliases){let i=re(o.key);i?.level==="code"&&e.set(i.path,n.path)}}return e}function Rm(t){let{repo:e,headTimeSec:r,filesets:n,pathToCurrent:o,currentPaths:i,ignored:s,settings:a}=t,c=a.halfLifeDays*86400,l=new Map,u=new Map,p=new Map;for(let h of n){let w=new Set;for(let v of h.files){let b=o.get(v)??v;!i.has(b)||s(b)||w.add(b)}if(w.size<2||w.size>a.commitFileCap)continue;let $=Math.max(0,r-h.timeSec),S=Math.pow(.5,$/c),T=[...w].sort();for(let v of T)l.set(v,(l.get(v)??0)+S);for(let v=0;v<T.length;v++)for(let b=v+1;b<T.length;b++){let R=`${T[v]}\0${T[b]}`;u.set(R,(u.get(R)??0)+S),p.set(R,(p.get(R)??0)+1)}}let d=[],m=a.jaccardMinPct/100;for(let[h,w]of u){if((p.get(h)??0)<a.supportMin)continue;let[$,S]=h.split("\0"),T=(l.get($)??0)+(l.get(S)??0)-w,v=T>0?w/T:0;v<m||d.push({a:$,b:S,weight:Math.round(v*Em)/Em})}let f=new Map;for(let h of d)for(let w of[h.a,h.b])f.has(w)||f.set(w,[]),f.get(w).push(h);let y=new Map;for(let[,h]of f)h.sort((w,$)=>$.weight-w.weight||(w.a<$.a?-1:w.a>$.a?1:w.b<$.b?-1:1)).slice(0,a.topK).forEach(w=>y.set(w,(y.get(w)??0)+1));return[...y.entries()].filter(([,h])=>h===2).map(([h])=>h).map(h=>({kind:"correlates",from:we("code",e,h.a),to:we("code",e,h.b),weight:h.weight})).sort((h,w)=>h.from<w.from?-1:h.from>w.from?1:h.to<w.to?-1:1)}var kn,Em,Gi=x(()=>{"use strict";B();kn=["package-lock.json","pnpm-lock.yaml","yarn.lock"];Em=1e4});import{createHash as AS}from"node:crypto";function jS(t,e,r,n){for(let o=0;;o++){let s=`e_${AS("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(s))return s}}function Im(t){let{repo:e,headCommit:r,headDate:n,prev:o,renameChains:i,prevBlobByPath:s,headBlobByPath:a}=t,c=[...t.currentKeys].sort(),l=new Set(c),u=o?.entities??[],p=new Set(u.map(b=>b.entityId)),d=new Set,m=[],f=new Map,y=(b,R)=>{d.add(R),f.set(R,b.entityId),m.push(b)},k=[];for(let b of u)l.has(b.currentKey)&&!d.has(b.currentKey)?y({...b,status:"active",lastSeen:r},b.currentKey):k.push(b);let h=[],w=[];for(let b of k){let R=re(b.currentKey),j=R?i.get(R.path):void 0;if(R&&j){let G=we(R.level,e,j.finalPath);if(l.has(G)&&!d.has(G)){h.push({entity:b,newKey:G,untilCommit:j.commit}),d.add(G);continue}}w.push(b)}let $=[];if(s){let b=new Map;for(let j of c){if(d.has(j))continue;let G=re(j);if(G?.level!=="code")continue;let X=a.get(G.path);X&&b.set(X,b.has(X)?null:j)}let R=new Map;for(let j of w){let G=re(j.currentKey);if(G?.level!=="code")continue;let X=s.get(G.path);X&&R.set(X,R.has(X)?null:j)}for(let j of w){let G=re(j.currentKey),X=G?.level==="code"?s.get(G.path):void 0,A=X?b.get(X):void 0;X&&A&&R.get(X)===j&&!d.has(A)?(h.push({entity:j,newKey:A,untilCommit:r}),d.add(A)):$.push(j)}}else $.push(...w);let S=new Map;for(let b of h){let R=re(b.entity.currentKey),j=re(b.newKey);if(R?.level!=="code"||!j)continue;let G=R.path,X=j.path;for(let A=G.lastIndexOf("/");A>0;A=G.lastIndexOf("/",A-1)){let g=G.slice(0,A),U=G.slice(A+1);if(!X.endsWith(`/${U}`))continue;let N=X.slice(0,X.length-U.length-1);if(N===g)continue;let H=`${g}\0${N}`,ee=S.get(H);S.set(H,{count:(ee?.count??0)+1,commit:ee&&ee.commit>b.untilCommit?ee.commit:b.untilCommit})}}let T=[...S.entries()].filter(([,b])=>b.count>=_S).map(([b,R])=>{let[j,G]=b.split("\0");return{from:j,to:G,commit:R.commit}}).sort((b,R)=>R.from.length-b.from.length||(b.from<R.from?-1:1)),v=[];for(let b of $){let R=re(b.currentKey),j=!1;if(R?.level==="component")for(let G of T){let X=null;if(R.path===G.from?X=G.to:R.path.startsWith(`${G.from}/`)&&(X=G.to+R.path.slice(G.from.length)),X===null)continue;let A=we("component",e,X);l.has(A)&&!d.has(A)&&(h.push({entity:b,newKey:A,untilCommit:G.commit}),d.add(A),j=!0);break}j||v.push(b)}for(let b of h.sort((R,j)=>R.newKey<j.newKey?-1:1))y({...b.entity,currentKey:b.newKey,aliases:[...b.entity.aliases??[],{key:b.entity.currentKey,until:b.untilCommit}],status:"active",lastSeen:r},b.newKey);for(let b of v)m.push({...b,status:"orphaned"});for(let b of c){if(d.has(b))continue;let R=jS(e,b,r,p);p.add(R),y({entityId:R,currentKey:b,firstSeen:n,lastSeen:r,status:"active"},b)}return{table:{modelFormatVersion:2,repo:e,builtFromCommit:r,entities:m},byKey:f}}var _S,Cm=x(()=>{"use strict";B();_S=5});import{simpleGit as NS}from"simple-git";async function Pm(t,e,r){let n=NS(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
706
- `).map(s=>s.trim()).filter(Boolean),i=[];for(let s of o){let c=(await n.raw(["diff","-M","-C","-z","--name-status","--diff-filter=R",`${s}^`,s]).catch(()=>"")).split("\0");for(let l=0;l+2<c.length;){if(!(c[l]??"").startsWith("R")){l+=1;continue}let p=c[l+1]??"",d=c[l+2]??"";p&&d&&i.push({fromPath:p,toPath:d,commit:s}),l+=3}}return i}function Am(t){let e=new Map,r=new Map;for(let n of t){let o=r.get(n.fromPath)??n.fromPath;r.delete(n.fromPath),r.set(n.toPath,o),e.set(o,{finalPath:n.toPath,commit:n.commit})}for(let[n,o]of e)o.finalPath===n&&e.delete(n);return e}var _m=x(()=>{"use strict"});function Ki(t){return we("container",t,OS)}function jm(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function Nm(t,e,r,n){let o=[],i=u=>{let p=we("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:jm(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,LS)}},s=(u,p)=>{let d=we("component",t,u),m=n.get(d);return{key:d,level:"component",label:jm(u),...m?{entityId:m}:{},...p?{aggregate:!0}:{}}},a=(u,p,d)=>{let m=r.filesByDir.get(d)??[],f=r.childDirs.get(d)??[],y=[p,...m.map(i)],k=[...m.map(h=>({kind:"contains",from:p.key,to:we("code",t,h.path)})),...f.map(h=>({kind:"contains",from:p.key,to:we("component",t,h)}))];c(u,y,k)},c=(u,p,d)=>{let m={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},f=Ot(m);if(!f.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${f.errors.join("; ")}`);o.push({path:la(t,u),content:ha(m)})},l={key:Ki(t),level:"container",label:t,...n.get(Ki(t))?{entityId:n.get(Ki(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 Om(t,e){let r=[Ki(t)];for(let n of e.components)r.push(we("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(we("code",t,o.path));return r.sort()}var OS,LS,Lm=x(()=>{"use strict";B();OS=".";LS=12});import{simpleGit as Dm}from"simple-git";function _r(t){let e=new Set,r=[],n=new Set;for(let o of t){let i=o.trim();if(i)if(i.endsWith("/"))e.add(i.slice(0,-1));else if(i.includes("*")){let s=i.replace(/[.*+?^${}()|[\]\\]/g,a=>a==="*"?"\0":`\\${a}`).replace(/\0/g,".*");r.push(new RegExp(`^${s}$`))}else n.add(i)}return o=>{let i=o.split("/"),s=i[i.length-1]??o;if(n.has(o))return!0;for(let a of i)if(e.has(a)||n.has(a))return!0;return r.some(a=>a.test(s))}}async function Bm(t,e="HEAD"){let r=Dm(t),n=(await r.revparse([e])).trim(),[o,i]=(await r.raw(["show","-s","--format=%cs %ct",n])).trim().split(/\s+/);return{commit:n,commitDate:o??"",commitTimeSec:Number(i??0),files:await To(t,n)}}async function To(t,e){let n=await Dm(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 Mm(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function Fm(t,e){let r=[...t].sort((f,y)=>f.path<y.path?-1:f.path>y.path?1:0),n=new Map,o=new Map;for(let f of r){let y=Mm(f.path);n.has(y)||n.set(y,[]),n.get(y).push(f);let k=y;for(;k!=="";){let h=Mm(k);o.has(h)||o.set(h,new Set),o.get(h).add(k),k=h}}let i=f=>[...o.get(f)??[]].sort(),s=Math.max(e,1)-1,a=new Set,c=new Set,l=[""];for(;l.length>0;){let f=l.shift(),y=(n.get(f)??[]).length+i(f).length;if(y<=s)s-=y,c.add(f),l.push(...i(f));else{if(f==="")return{components:[],collapsed:new Set,filesByDir:new Map,childDirs:new Map,counts:{component:0,code:0}};a.add(f)}}let u=[],p=new Map,d=new Map,m=0;for(let f of[...c].sort()){let y=n.get(f)??[];p.set(f,y),d.set(f,i(f)),m+=y.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 Um,Ro=x(()=>{"use strict";Um=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as Gm,readFileSync as Km}from"node:fs";import{join as Hm}from"node:path";import{simpleGit as MS}from"simple-git";import{parse as Wm}from"yaml";function bn(t){let e={ignore:Um,containerNodeCap:DS,cochange:{...nt},issueKeyPattern:null,enabled:!1},r=Hm(t,"regimen.yaml");if(!Gm(r))return e;let n;try{n=Wm(Km(r,"utf-8"))}catch{return e}let o=n?.context,i=o&&typeof o=="object"?o.model:void 0;if(!i||typeof i!="object")return e;let s=i,a=Array.isArray(s.ignore)?s.ignore.filter(m=>typeof m=="string"&&m.trim().length>0):e.ignore,c=(m,f)=>typeof m=="number"&&Number.isInteger(m)&&m>0?m:f,l=c(s.container_node_cap,e.containerNodeCap),u=s.cochange&&typeof s.cochange=="object"?s.cochange:{},p={windowCommits:c(u.window_commits,e.cochange.windowCommits),commitFileCap:c(u.commit_file_cap,e.cochange.commitFileCap),supportMin:c(u.support_min,e.cochange.supportMin),jaccardMinPct:typeof u.jaccard_min_pct=="number"&&Number.isInteger(u.jaccard_min_pct)&&u.jaccard_min_pct>=0&&u.jaccard_min_pct<=100?u.jaccard_min_pct:e.cochange.jaccardMinPct,halfLifeDays:c(u.half_life_days,e.cochange.halfLifeDays),topK:c(u.top_k,e.cochange.topK)},d=typeof s.issue_key_pattern=="string"&&s.issue_key_pattern.trim().length>0?s.issue_key_pattern.trim():null;return{ignore:a,containerNodeCap:l,cochange:p,issueKeyPattern:d,enabled:s.enabled===!0}}function Qc(t,e){let r=Hm(t,eo(e));if(!Gm(r))return null;let n=Wm(Km(r,"utf-8")),o=ro(n);if(!o.ok)throw new Error(`model: ${eo(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function el(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await Bm(r,t.ref??"HEAD"),s=_r(o.ignore),a=i.files.filter(w=>!s(w.path)),c=Fm(a,o.containerNodeCap),l=Qc(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await MS(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=Am(await Pm(r,l.builtFromCommit,i.commit)),p=new Map((await To(r,l.builtFromCommit)).map(S=>[S.path,S.blobHash]))):l?.builtFromCommit===i.commit&&(p=new Map(a.map(w=>[w.path,w.blobHash])));let d=new Map(a.map(w=>[w.path,w.blobHash])),m=Im({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:Om(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),f=Nm(e,i.commit,c,m.byKey),y=_r([...o.ignore,...kn]),k=Rm({repo:e,headTimeSec:i.commitTimeSec,filesets:await Tm(r,i.commit,o.cochange.windowCommits),pathToCurrent:Fi(m.table),currentPaths:new Set(a.map(w=>w.path)),ignored:y,settings:o.cochange}),h=[{path:eo(e),content:ga(m.table)},...f.files.map(w=>({path:w.path,content:w.content})),{path:aa(e),content:br({modelFormatVersion:2,repo:e,builtFromCommit:i.commit,edges:k})}];return{repo:e,headCommit:i.commit,files:h,emittedShardPaths:new Set(f.files.map(w=>w.path)),counts:{...f.counts,correlates:k.length},identityTable:m.table,entityByKey:m.byKey}}var DS,tl=x(()=>{"use strict";B();Gi();Cm();_m();Lm();Ro();DS=1500});import{existsSync as Ym,readFileSync as zm,readdirSync as US}from"node:fs";import{join as rl}from"node:path";import{parse as Vm}from"yaml";function BS(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 Xm(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<da)return null;let s=i/Math.min(n.size,o.size),a=BS(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(s*c*qm)/qm;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[Ee(t.taskKey),Ee(e.taskKey)]:[Ee(e.taskKey),Ee(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function Jm(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=Xm(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 Zm(t,e,r,n){let o=Ee(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=Xm(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 Hi(t){let e=rl(t,"model/facts/events");if(!Ym(e))return[];let r=[];for(let n of US(e).sort())if(n.endsWith(".yaml"))try{let o=Lt(Vm(zm(rl(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function Qm(t){let e=rl(t,wr);if(!Ym(e))return[];try{let r=to(Vm(zm(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function Wi(t){return br({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var qm,nl=x(()=>{"use strict";B();qm=1e4});var Io={};Fe(Io,{collectSearchRows:()=>th,readContextIndexHub:()=>FS,rebuildSearchIndex:()=>rh,searchIndexPath:()=>Vi,searchModelIndex:()=>GS,toFtsQuery:()=>nh});import{existsSync as vn,readFileSync as $n,readdirSync as Yi}from"node:fs";import{join as $t}from"node:path";import{parse as zi}from"yaml";function Vi(t){return $t(t,".git","codepipe-model-index.sqlite")}function FS(t){let e=$t(t,"regimen.yaml");if(!vn(e))return"off";try{let n=zi($n(e,"utf-8"))?.context,o=n&&typeof n=="object"?n.index:null;return(o&&typeof o=="object"?o.hub:null)==="metadata"?"metadata":"off"}catch{return"off"}}async function eh(){try{let{createRequire:t}=await import("node:module");return t(import.meta.url)("node:sqlite")}catch{return null}}function qi(t){return t.length>ri?t.slice(0,ri):t}function ol(t){if(!vn(t))return[];let e=[];for(let r of Yi(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=$t(t,r.name);r.isDirectory()?e.push(...ol(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function th(t){let e=[];for(let i of ol($t(t,"model/derived/structure"))){let s;try{s=zi($n(i,"utf-8"))}catch{continue}let a=Ot(s);if(a.ok)for(let c of a.value.nodes){let l=re(c.key);l&&e.push({nodeId:c.key,kind:l.level,text:qi(`${l.path} ${c.label??""}`.trim())})}}let r=$t(t,"model/facts/events");if(vn(r)){for(let i of Yi(r).sort())if(i.endsWith(".yaml"))try{let s=Lt(zi($n($t(r,i),"utf-8")));if(!s.ok)continue;let a=s.value,c=[...a.links?.adr??[],...a.links?.tasks??[]].join(" ");e.push({nodeId:`task::${a.taskKey}`,kind:"task",text:qi(`${a.taskKey} ${a.title??""} ${c}`.trim())})}catch{}}let n=$t(t,"model/facts/annotations");if(vn(n)){let i=new Map;for(let s of ol($t(t,"model/facts/identity")))try{let a=zi($n(s,"utf-8"));for(let c of a?.entities??[])c.status==="active"&&c.entityId&&c.currentKey&&i.set(c.entityId,c.currentKey)}catch{}for(let s of Yi(n).sort())if(s.endsWith(".md"))try{let a=$n($t(n,s),"utf-8"),c=/^---\n[\s\S]*?entityId:\s*(e_[0-9a-f]{8})[\s\S]*?\n---\n?([\s\S]*)$/.exec(a);if(!c)continue;e.push({nodeId:i.get(c[1])??c[1],kind:"annotation",text:qi(c[2].trim())})}catch{}}let o=$t(t,"adr");if(vn(o))for(let i of Yi(o).sort()){let s=/^(\d{4})-/.exec(i)?.[1];if(!(!s||!i.endsWith(".md")))try{let a=$n($t(o,i),"utf-8").split(`
707
- `).slice(0,6);e.push({nodeId:`adr::ADR-${s}`,kind:"adr",text:qi(a.filter(c=>c.trim()).join(" "))})}catch{}}return e}async function rh(t){let e=th(t),r=await eh();if(!r)return{rows:e,indexed:!1};let n=new r.DatabaseSync(Vi(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 nh(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 GS(t,e,r){let n=await eh();if(!n)throw new Error("model search needs Node with built-in sqlite (>= 22.13) on this CLI");vn(Vi(t))||await rh(t);let o=nh(e);if(!o)return[];let i=Math.min(Math.max(r??20,1),fa),s=new n.DatabaseSync(Vi(t));try{return s.prepare(`SELECT node_id AS nodeId, kind, snippet(model_fts, 2, '[', ']', '\u2026', 10) AS snippet,
700
+ `).map(k=>k.trim().toUpperCase()).filter(k=>k.length>0).some(k=>l.has(k))?p++:u.push(m);if(p===0)return{commit:(await t.revparse([i])).trim(),dropped:0};await t.checkout(["-B",n,a]);for(let m of u)try{await t.raw([...Uc,"cherry-pick","--allow-empty","--keep-redundant-commits",m])}catch(f){await t.raw(["cherry-pick","--abort"]).catch(()=>{}),await t.checkout(["-B",n,i]).catch(()=>{});let g=f instanceof Error?f.message:String(f);throw new Error(`rewrite_cluster_branch: replaying ${m.slice(0,10)} after dropping ${o.join(", ")} hit conflicts
701
+ ${g.trim()}`)}let d=(await t.revparse(["HEAD"])).trim();return await t.push(["--force-with-lease","-u","origin",n]),{commit:d,dropped:p}}async function Gf(t,e,r){let{branchName:n,baseBranch:o,mergeMethod:i,deleteBranch:s}=r,a=`origin/${n}`;return i==="squash"?(await t.raw(["merge","--squash",a]),await t.commit(`Merge branch '${n}'`)):i==="rebase"?(await t.checkout(["-B",n,a]),await t.rebase([o]),await t.checkout(o),await t.merge(["--ff-only",n])):await t.merge(["--no-ff",a,"-m",`Merge branch '${n}'`]),await t.push(["origin",o]),s&&await t.push(["origin","--delete",n]).catch(()=>{}),{mergedSha:(await t.revparse(["HEAD"])).trim()}}function Bc(t){return t.mirror?Df(t.mirror.host,t.mirror.owner,t.mirror.repoName):Df(t.host,t.owner,t.repoName)}function Df(t,e,r){return t==="github"?`git@github.com:${e}/${r}.git`:t==="gitlab"?`git@gitlab.com:${e}/${r}.git`:`git@bitbucket.org:${e}/${r}.git`}function ji(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}async function Kf(t){return(await Dc().listRemote(["--heads",t])).split(`
702
+ `).map(r=>r.trim()).filter(r=>r.length>0).map(r=>r.split(/\s+/)[1]??"").filter(r=>r.startsWith("refs/heads/")).map(r=>r.slice(11))}function Hf(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}var Uc,vo=x(()=>{"use strict";_i();Uc=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{createCipheriv as oS,createDecipheriv as iS,createHash as sS,createPrivateKey as aS,createPublicKey as Fc,diffieHellman as Wf,generateKeyPairSync as qf,hkdfSync as Yf,randomBytes as cS}from"node:crypto";function Ni(){let{publicKey:t,privateKey:e}=qf("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function He(t){let e=Buffer.from(t,"base64");return(sS("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function Gt(t,e){let r=Fc({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=qf("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=Wf({privateKey:o,publicKey:r}),c=Buffer.from(Yf("sha256",a,Buffer.concat([i,s]),zf,32)),l=cS(12),u=oS("aes-256-gcm",c,l),p=typeof e=="string"?Buffer.from(e,"utf-8"):e,d=Buffer.concat([u.update(p),u.final()]),m=u.getAuthTag(),f={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:m.toString("base64"),ct:d.toString("base64")};return Buffer.from(JSON.stringify(f),"utf-8").toString("base64")}function yn(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=aS({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=Fc({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=Fc(n).export({type:"spki",format:"der"}),a=Wf({privateKey:n,publicKey:o}),c=Buffer.from(Yf("sha256",a,Buffer.concat([i,s]),zf,32)),l=iS("aes-256-gcm",c,Buffer.from(r.iv,"base64"));return l.setAuthTag(Buffer.from(r.tag,"base64")),Buffer.concat([l.update(Buffer.from(r.ct,"base64")),l.final()])}var zf,dt=x(()=>{"use strict";zf=Buffer.from("devpipe-sealedbox-v1","utf-8")});function xo(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@github.com:"),o(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function So(t,e=process.env){if(!t)return!1;let r=`https://oauth2:${t}@gitlab.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@gitlab.com:"),o(1,"ssh://git@gitlab.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function Eo(t,e=process.env){if(!t)return!1;let r=`https://${Dt}:${encodeURIComponent(t)}@bitbucket.org/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@bitbucket.org:"),o(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function Gc(t,e,r,n){let o=Number.parseInt(n.GIT_CONFIG_COUNT??"0",10)||0,i=!1;for(let s=0;s<o;s++){let a=n[`GIT_CONFIG_KEY_${s}`];a&&t.test(a)&&(n[`GIT_CONFIG_KEY_${s}`]=`url.${e}.insteadOf`,i=!0)}return i||r()}function Xf(t,e=process.env){return Gc(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>xo(t,e),e)}function Jf(t,e=process.env){return Gc(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>So(t,e),e)}function Zf(t,e=process.env){return Gc(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Dt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>Eo(t,e),e)}var Oi=x(()=>{"use strict";B()});import{existsSync as cm,readFileSync as lm,writeFileSync as um}from"node:fs";import{join as dm}from"node:path";import{isMap as Li,parseDocument as pm}from"yaml";async function fm(t,e){let r=e.repoName?.trim(),n=e.defaultBranch?.trim();if(!r)throw new Error("repoName must be a non-empty string");if(!n||!so(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=dm(t,"project.yaml");if(!cm(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=pm(lm(o,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>Li(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!Li(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),um(o,i.toString()),{repoName:r,defaultBranch:n}}function mm(t,e,r){let n=dm(t,"project.yaml");if(!cm(n))throw new Error(`project.yaml not found in context repo (${t})`);let o=pm(lm(n,"utf-8")),i=o.get("repos"),a=(i&&typeof i=="object"&&"items"in i?i.items:[]).find(c=>Li(c)&&String(c.get("name")??c.get("repo")??"")===e);if(!Li(a))throw new Error(`repo "${e}" not found in project.yaml repos[]`);a.set("mirror",{host:r.host,owner:r.owner,repo:r.repoName}),um(n,o.toString())}var Kc=x(()=>{"use strict";B()});import{existsSync as zc,readFileSync as Vc}from"node:fs";import{join as Xc}from"node:path";import{simpleGit as bm}from"simple-git";import{parse as Jc}from"yaml";function vm(t,e){if(t)try{return new RegExp(t,"g")}catch{}if(e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`\\b${r}-\\d+\\b`,"g")}return new RegExp(IS.source,"g")}function xm(t){let e=Xc(t,"project.yaml");if(zc(e))try{let o=Jc(Vc(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=Xc(t,"tracker","config.yaml");if(zc(r))try{let o=Jc(Vc(r,"utf-8"))?.prefix;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return null}function Sm(t){if(t.includes("=>")){let r=t.replace(/\{([^{}]*) => ([^{}]*)\}/g,(o,i,s)=>s).replace(/\/\//g,"/");if(!r.includes("=>"))return r;let n=r.split("=>");return(n[n.length-1]??r).trim()}return t}async function CS(t,e,r){let o=await bm(t).raw(["log","--numstat","--format=@@@ %H %ct %P %x09%s","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
703
+ `))if(a.startsWith("@@@ ")){let c=a.indexOf(" "),l=(c>=0?a.slice(4,c):a.slice(4)).trim().split(/\s+/),u=c>=0?a.slice(c+1):"",p=l[0]??"",d=Number(l[1]??0),m=l.slice(2),f=Zc.exec(u)??$m.exec(u);s={sha:p,timeSec:d,subject:u,files:[],prNumber:f?Number(f[1]):null,isMerge:m.length>1},i.push(s)}else if(a.trim()&&s){let c=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(a);if(!c)continue;let l=c[1]==="-"?0:Number(c[1]),u=c[2]==="-"?0:Number(c[2]);s.files.push({path:Sm(c[3]),churn:l+u})}return i}async function PS(t,e){let n=await bm(t).raw(["diff","--numstat",`${e}^1`,e]).catch(()=>""),o=[];for(let i of n.split(`
704
+ `)){let s=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(i);if(!s)continue;let a=s[1]==="-"?0:Number(s[1]),c=s[2]==="-"?0:Number(s[2]);o.push({path:Sm(s[3]),churn:a+c})}return o}function AS(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(Zc,"").trim();else if(c.prNumber!==null){if((t.trackerProjectKey??"").toUpperCase()==="PR")continue;u=`PR-${c.prNumber}`,p=c.subject.replace(Zc,"").replace($m,"").replace(/^from\s+/,"").trim()||c.subject}else continue;if(!/^[A-Za-z0-9._-]+$/.test(u))continue;let m=new Map;for(let k of c.files){let h=o.get(k.path)??k.path;s(h)||m.set(h,(m.get(h)??0)+k.churn)}if(m.size===0)continue;let g=a.get(u)??{modelFormatVersion:2,taskKey:u,origin:"bootstrap",title:"",commits:[],files:[]};p&&(g.title=p),c.timeSec>0&&(g.date=new Date(c.timeSec*1e3).toISOString().slice(0,10)),g.commits.push(c.sha);for(let[k,h]of m){let w=ye("code",e,k),$=g.files.find(S=>S.key===w);if($)$.churn=($.churn??0)+h;else{let S=i.get(w);g.files.push({key:w,...S?{entityId:S}:{},churn:h})}}if(d.length>0){let k=new Set([...g.links?.tasks??[],...d]);k.delete(u),g.links={...g.links??{},tasks:[...k].sort()}}a.set(u,g)}return a}function km(t,e){if(!t)return e;if(t.origin==="pipeline")return null;let r=[...new Set([...t.commits,...e.commits])],n=new Map(t.files.map(i=>[i.key,i]));for(let i of e.files)n.has(i.key)||n.set(i.key,i);let o=[...new Set([...t.links?.tasks??[],...e.links?.tasks??[]])].sort();return{...t,commits:r,files:[...n.values()],...o.length>0?{links:{...t.links??{},tasks:o}}:{}}}async function Em(t){let e=await CS(t.repoDir,t.headCommit,t.windowCommits);for(let r of e){let n=(r.subject.match(t.issueKeyRe)??[]).length>0;t.issueKeyRe.lastIndex=0,r.isMerge&&r.prNumber!==null&&!n&&r.files.length===0&&(r.files=await PS(t.repoDir,r.sha))}return AS({repo:t.repo,issueKeyRe:t.issueKeyRe,commits:e,pathToCurrent:t.pathToCurrent,entityByKey:t.entityByKey,ignored:t.ignored,trackerProjectKey:t.trackerProjectKey??null})}function Tm(t,e){let r=new Map;for(let i of e)for(let[s,a]of i){let c=r.get(s);r.set(s,c?km(c,a)??c:a)}let n=[],o=0;for(let[i,s]of[...r.entries()].sort(([a],[c])=>a<c?-1:1)){let a=km(Ui(t,i),s);if(!a){o++;continue}n.push({path:kr(i),content:zr(a)})}return{files:n,skippedPipeline:o}}function Ui(t,e){let r=Xc(t,kr(e));if(!zc(r))return null;try{let n=Lt(Jc(Vc(r,"utf-8")));return n.ok?n.value:null}catch{return null}}var IS,Zc,$m,Qc=x(()=>{"use strict";B();IS=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g,Zc=/\(#(\d+)\)\s*$/,$m=/^Merge pull request #(\d+)\b/});import{simpleGit as _S}from"simple-git";async function Im(t,e,r){let o=await _S(t).raw(["log","--no-merges","--name-only","--format=@@@ %H %ct","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
705
+ `))if(a.startsWith("@@@ ")){let[c,l]=a.slice(4).trim().split(/\s+/);s={sha:c??"",timeSec:Number(l??0),files:[]},i.push(s)}else a.trim()&&s&&s.files.push(a.trim());return i}function Bi(t){let e=new Map;for(let r of t.entities){if(r.status!=="active"||!r.aliases)continue;let n=re(r.currentKey);if(n?.level==="code")for(let o of r.aliases){let i=re(o.key);i?.level==="code"&&e.set(i.path,n.path)}}return e}function Cm(t){let{repo:e,headTimeSec:r,filesets:n,pathToCurrent:o,currentPaths:i,ignored:s,settings:a}=t,c=a.halfLifeDays*86400,l=new Map,u=new Map,p=new Map;for(let h of n){let w=new Set;for(let v of h.files){let b=o.get(v)??v;!i.has(b)||s(b)||w.add(b)}if(w.size<2||w.size>a.commitFileCap)continue;let $=Math.max(0,r-h.timeSec),S=Math.pow(.5,$/c),R=[...w].sort();for(let v of R)l.set(v,(l.get(v)??0)+S);for(let v=0;v<R.length;v++)for(let b=v+1;b<R.length;b++){let I=`${R[v]}\0${R[b]}`;u.set(I,(u.get(I)??0)+S),p.set(I,(p.get(I)??0)+1)}}let d=[],m=a.jaccardMinPct/100;for(let[h,w]of u){if((p.get(h)??0)<a.supportMin)continue;let[$,S]=h.split("\0"),R=(l.get($)??0)+(l.get(S)??0)-w,v=R>0?w/R:0;v<m||d.push({a:$,b:S,weight:Math.round(v*Rm)/Rm})}let f=new Map;for(let h of d)for(let w of[h.a,h.b])f.has(w)||f.set(w,[]),f.get(w).push(h);let g=new Map;for(let[,h]of f)h.sort((w,$)=>$.weight-w.weight||(w.a<$.a?-1:w.a>$.a?1:w.b<$.b?-1:1)).slice(0,a.topK).forEach(w=>g.set(w,(g.get(w)??0)+1));return[...g.entries()].filter(([,h])=>h===2).map(([h])=>h).map(h=>({kind:"correlates",from:ye("code",e,h.a),to:ye("code",e,h.b),weight:h.weight})).sort((h,w)=>h.from<w.from?-1:h.from>w.from?1:h.to<w.to?-1:1)}var kn,Rm,Fi=x(()=>{"use strict";B();kn=["package-lock.json","pnpm-lock.yaml","yarn.lock"];Rm=1e4});import{createHash as jS}from"node:crypto";function OS(t,e,r,n){for(let o=0;;o++){let s=`e_${jS("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(s))return s}}function Pm(t){let{repo:e,headCommit:r,headDate:n,prev:o,renameChains:i,prevBlobByPath:s,headBlobByPath:a}=t,c=[...t.currentKeys].sort(),l=new Set(c),u=o?.entities??[],p=new Set(u.map(b=>b.entityId)),d=new Set,m=[],f=new Map,g=(b,I)=>{d.add(I),f.set(I,b.entityId),m.push(b)},k=[];for(let b of u)l.has(b.currentKey)&&!d.has(b.currentKey)?g({...b,status:"active",lastSeen:r},b.currentKey):k.push(b);let h=[],w=[];for(let b of k){let I=re(b.currentKey),j=I?i.get(I.path):void 0;if(I&&j){let K=ye(I.level,e,j.finalPath);if(l.has(K)&&!d.has(K)){h.push({entity:b,newKey:K,untilCommit:j.commit}),d.add(K);continue}}w.push(b)}let $=[];if(s){let b=new Map;for(let j of c){if(d.has(j))continue;let K=re(j);if(K?.level!=="code")continue;let z=a.get(K.path);z&&b.set(z,b.has(z)?null:j)}let I=new Map;for(let j of w){let K=re(j.currentKey);if(K?.level!=="code")continue;let z=s.get(K.path);z&&I.set(z,I.has(z)?null:j)}for(let j of w){let K=re(j.currentKey),z=K?.level==="code"?s.get(K.path):void 0,A=z?b.get(z):void 0;z&&A&&I.get(z)===j&&!d.has(A)?(h.push({entity:j,newKey:A,untilCommit:r}),d.add(A)):$.push(j)}}else $.push(...w);let S=new Map;for(let b of h){let I=re(b.entity.currentKey),j=re(b.newKey);if(I?.level!=="code"||!j)continue;let K=I.path,z=j.path;for(let A=K.lastIndexOf("/");A>0;A=K.lastIndexOf("/",A-1)){let y=K.slice(0,A),U=K.slice(A+1);if(!z.endsWith(`/${U}`))continue;let O=z.slice(0,z.length-U.length-1);if(O===y)continue;let G=`${y}\0${O}`,ee=S.get(G);S.set(G,{count:(ee?.count??0)+1,commit:ee&&ee.commit>b.untilCommit?ee.commit:b.untilCommit})}}let R=[...S.entries()].filter(([,b])=>b.count>=NS).map(([b,I])=>{let[j,K]=b.split("\0");return{from:j,to:K,commit:I.commit}}).sort((b,I)=>I.from.length-b.from.length||(b.from<I.from?-1:1)),v=[];for(let b of $){let I=re(b.currentKey),j=!1;if(I?.level==="component")for(let K of R){let z=null;if(I.path===K.from?z=K.to:I.path.startsWith(`${K.from}/`)&&(z=K.to+I.path.slice(K.from.length)),z===null)continue;let A=ye("component",e,z);l.has(A)&&!d.has(A)&&(h.push({entity:b,newKey:A,untilCommit:K.commit}),d.add(A),j=!0);break}j||v.push(b)}for(let b of h.sort((I,j)=>I.newKey<j.newKey?-1:1))g({...b.entity,currentKey:b.newKey,aliases:[...b.entity.aliases??[],{key:b.entity.currentKey,until:b.untilCommit}],status:"active",lastSeen:r},b.newKey);for(let b of v)m.push({...b,status:"orphaned"});for(let b of c){if(d.has(b))continue;let I=OS(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 NS,Am=x(()=>{"use strict";B();NS=5});import{simpleGit as LS}from"simple-git";async function _m(t,e,r){let n=LS(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
706
+ `).map(s=>s.trim()).filter(Boolean),i=[];for(let s of o){let c=(await n.raw(["diff","-M","-C","-z","--name-status","--diff-filter=R",`${s}^`,s]).catch(()=>"")).split("\0");for(let l=0;l+2<c.length;){if(!(c[l]??"").startsWith("R")){l+=1;continue}let p=c[l+1]??"",d=c[l+2]??"";p&&d&&i.push({fromPath:p,toPath:d,commit:s}),l+=3}}return i}function jm(t){let e=new Map,r=new Map;for(let n of t){let o=r.get(n.fromPath)??n.fromPath;r.delete(n.fromPath),r.set(n.toPath,o),e.set(o,{finalPath:n.toPath,commit:n.commit})}for(let[n,o]of e)o.finalPath===n&&e.delete(n);return e}var Nm=x(()=>{"use strict"});function Gi(t){return ye("container",t,MS)}function Om(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function Lm(t,e,r,n){let o=[],i=u=>{let p=ye("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:Om(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,DS)}},s=(u,p)=>{let d=ye("component",t,u),m=n.get(d);return{key:d,level:"component",label:Om(u),...m?{entityId:m}:{},...p?{aggregate:!0}:{}}},a=(u,p,d)=>{let m=r.filesByDir.get(d)??[],f=r.childDirs.get(d)??[],g=[p,...m.map(i)],k=[...m.map(h=>({kind:"contains",from:p.key,to:ye("code",t,h.path)})),...f.map(h=>({kind:"contains",from:p.key,to:ye("component",t,h)}))];c(u,g,k)},c=(u,p,d)=>{let m={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},f=Ot(m);if(!f.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${f.errors.join("; ")}`);o.push({path:ua(t,u),content:ga(m)})},l={key:Gi(t),level:"container",label:t,...n.get(Gi(t))?{entityId:n.get(Gi(t))}:{}};a("",l,"");for(let u of r.components)r.collapsed.has(u)?c(u,[s(u,!0)],[]):a(u,s(u,!1),u);return o.sort((u,p)=>u.path<p.path?-1:u.path>p.path?1:0),{files:o,counts:r.counts}}function Mm(t,e){let r=[Gi(t)];for(let n of e.components)r.push(ye("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(ye("code",t,o.path));return r.sort()}var MS,DS,Dm=x(()=>{"use strict";B();MS=".";DS=12});import{simpleGit as Bm}from"simple-git";function _r(t){let e=new Set,r=[],n=new Set;for(let o of t){let i=o.trim();if(i)if(i.endsWith("/"))e.add(i.slice(0,-1));else if(i.includes("*")){let s=i.replace(/[.*+?^${}()|[\]\\]/g,a=>a==="*"?"\0":`\\${a}`).replace(/\0/g,".*");r.push(new RegExp(`^${s}$`))}else n.add(i)}return o=>{let i=o.split("/"),s=i[i.length-1]??o;if(n.has(o))return!0;for(let a of i)if(e.has(a)||n.has(a))return!0;return r.some(a=>a.test(s))}}async function Gm(t,e="HEAD"){let r=Bm(t),n=(await r.revparse([e])).trim(),[o,i]=(await r.raw(["show","-s","--format=%cs %ct",n])).trim().split(/\s+/);return{commit:n,commitDate:o??"",commitTimeSec:Number(i??0),files:await To(t,n)}}async function To(t,e){let n=await Bm(t).raw(["ls-tree","-r","-z",e]),o=[];for(let i of n.split("\0")){if(!i)continue;let s=i.indexOf(" ");if(s<0)continue;let[,a,c]=i.slice(0,s).split(/\s+/);a!=="blob"||!c||o.push({path:i.slice(s+1),blobHash:c})}return o.sort((i,s)=>i.path<s.path?-1:i.path>s.path?1:0),o}function Um(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function Km(t,e){let r=[...t].sort((f,g)=>f.path<g.path?-1:f.path>g.path?1:0),n=new Map,o=new Map;for(let f of r){let g=Um(f.path);n.has(g)||n.set(g,[]),n.get(g).push(f);let k=g;for(;k!=="";){let h=Um(k);o.has(h)||o.set(h,new Set),o.get(h).add(k),k=h}}let i=f=>[...o.get(f)??[]].sort(),s=Math.max(e,1)-1,a=new Set,c=new Set,l=[""];for(;l.length>0;){let f=l.shift(),g=(n.get(f)??[]).length+i(f).length;if(g<=s)s-=g,c.add(f),l.push(...i(f));else{if(f==="")return{components:[],collapsed:new Set,filesByDir:new Map,childDirs:new Map,counts:{component:0,code:0}};a.add(f)}}let u=[],p=new Map,d=new Map,m=0;for(let f of[...c].sort()){let g=n.get(f)??[];p.set(f,g),d.set(f,i(f)),m+=g.length,f!==""&&u.push(f)}for(let f of a)u.push(f);return u.sort(),{components:u,collapsed:a,filesByDir:p,childDirs:d,counts:{component:u.length,code:m}}}var Fm,Ro=x(()=>{"use strict";Fm=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as Hm,readFileSync as Wm}from"node:fs";import{join as qm}from"node:path";import{simpleGit as US}from"simple-git";import{parse as Ym}from"yaml";function bn(t){let e={ignore:Fm,containerNodeCap:BS,cochange:{...ot},issueKeyPattern:null,enabled:!1},r=qm(t,"regimen.yaml");if(!Hm(r))return e;let n;try{n=Ym(Wm(r,"utf-8"))}catch{return e}let o=n?.context,i=o&&typeof o=="object"?o.model:void 0;if(!i||typeof i!="object")return e;let s=i,a=Array.isArray(s.ignore)?s.ignore.filter(m=>typeof m=="string"&&m.trim().length>0):e.ignore,c=(m,f)=>typeof m=="number"&&Number.isInteger(m)&&m>0?m:f,l=c(s.container_node_cap,e.containerNodeCap),u=s.cochange&&typeof s.cochange=="object"?s.cochange:{},p={windowCommits:c(u.window_commits,e.cochange.windowCommits),commitFileCap:c(u.commit_file_cap,e.cochange.commitFileCap),supportMin:c(u.support_min,e.cochange.supportMin),jaccardMinPct:typeof u.jaccard_min_pct=="number"&&Number.isInteger(u.jaccard_min_pct)&&u.jaccard_min_pct>=0&&u.jaccard_min_pct<=100?u.jaccard_min_pct:e.cochange.jaccardMinPct,halfLifeDays:c(u.half_life_days,e.cochange.halfLifeDays),topK:c(u.top_k,e.cochange.topK)},d=typeof s.issue_key_pattern=="string"&&s.issue_key_pattern.trim().length>0?s.issue_key_pattern.trim():null;return{ignore:a,containerNodeCap:l,cochange:p,issueKeyPattern:d,enabled:s.enabled===!0}}function el(t,e){let r=qm(t,eo(e));if(!Hm(r))return null;let n=Ym(Wm(r,"utf-8")),o=ro(n);if(!o.ok)throw new Error(`model: ${eo(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function tl(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await Gm(r,t.ref??"HEAD"),s=_r(o.ignore),a=i.files.filter(w=>!s(w.path)),c=Km(a,o.containerNodeCap),l=el(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await US(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=jm(await _m(r,l.builtFromCommit,i.commit)),p=new Map((await To(r,l.builtFromCommit)).map(S=>[S.path,S.blobHash]))):l?.builtFromCommit===i.commit&&(p=new Map(a.map(w=>[w.path,w.blobHash])));let d=new Map(a.map(w=>[w.path,w.blobHash])),m=Pm({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:Mm(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),f=Lm(e,i.commit,c,m.byKey),g=_r([...o.ignore,...kn]),k=Cm({repo:e,headTimeSec:i.commitTimeSec,filesets:await Im(r,i.commit,o.cochange.windowCommits),pathToCurrent:Bi(m.table),currentPaths:new Set(a.map(w=>w.path)),ignored:g,settings:o.cochange}),h=[{path:eo(e),content:ya(m.table)},...f.files.map(w=>({path:w.path,content:w.content})),{path:ca(e),content:br({modelFormatVersion:2,repo:e,builtFromCommit:i.commit,edges:k})}];return{repo:e,headCommit:i.commit,files:h,emittedShardPaths:new Set(f.files.map(w=>w.path)),counts:{...f.counts,correlates:k.length},identityTable:m.table,entityByKey:m.byKey}}var BS,rl=x(()=>{"use strict";B();Fi();Am();Nm();Dm();Ro();BS=1500});import{existsSync as Vm,readFileSync as Xm,readdirSync as FS}from"node:fs";import{join as nl}from"node:path";import{parse as Jm}from"yaml";function GS(t,e){if(!t||!e)return null;let r=Date.parse(`${t}T00:00:00Z`),n=Date.parse(`${e}T00:00:00Z`);return!Number.isFinite(r)||!Number.isFinite(n)?null:Math.abs(r-n)/864e5}function Zm(t,e,r){let n=new Set(t.files.map(d=>d.key)),o=new Set(e.files.map(d=>d.key)),i=0;for(let d of n)o.has(d)&&i++;if(i<pa)return null;let s=i/Math.min(n.size,o.size),a=GS(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(s*c*zm)/zm;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[Se(t.taskKey),Se(e.taskKey)]:[Se(e.taskKey),Se(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function Qm(t,e){let r=new Map(t.map(s=>[s.taskKey,s])),n=new Map;for(let s of t)for(let a of s.files)n.has(a.key)||n.set(a.key,[]),n.get(a.key).push(s.taskKey);let o=new Set,i=[];for(let s of n.values())if(!(s.length<2))for(let a=0;a<s.length;a++)for(let c=a+1;c<s.length;c++){let[l,u]=s[a]<s[c]?[s[a],s[c]]:[s[c],s[a]],p=`${l}\0${u}`;if(o.has(p))continue;o.add(p);let d=Zm(r.get(l),r.get(u),e);d&&i.push(d)}return i.sort((s,a)=>s.from<a.from?-1:s.from>a.from?1:s.to<a.to?-1:1)}function eh(t,e,r,n){let o=Se(r),i=t.filter(a=>a.from!==o&&a.to!==o),s=e.find(a=>a.taskKey===r);if(s){let a=new Set(s.files.map(c=>c.key));for(let c of e){if(c.taskKey===r||!c.files.some(u=>a.has(u.key)))continue;let l=Zm(s,c,n);l&&i.push(l)}}return i.sort((a,c)=>a.from<c.from?-1:a.from>c.from?1:a.to<c.to?-1:1)}function Ki(t){let e=nl(t,"model/facts/events");if(!Vm(e))return[];let r=[];for(let n of FS(e).sort())if(n.endsWith(".yaml"))try{let o=Lt(Jm(Xm(nl(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function th(t){let e=nl(t,wr);if(!Vm(e))return[];try{let r=to(Jm(Xm(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function Hi(t){return br({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var zm,ol=x(()=>{"use strict";B();zm=1e4});var Io={};Fe(Io,{collectSearchRows:()=>nh,readContextIndexHub:()=>KS,rebuildSearchIndex:()=>oh,searchIndexPath:()=>zi,searchModelIndex:()=>HS,toFtsQuery:()=>ih});import{existsSync as vn,readFileSync as $n,readdirSync as qi}from"node:fs";import{join as vt}from"node:path";import{parse as Yi}from"yaml";function zi(t){return vt(t,".git","codepipe-model-index.sqlite")}function KS(t){let e=vt(t,"regimen.yaml");if(!vn(e))return"off";try{let n=Yi($n(e,"utf-8"))?.context,o=n&&typeof n=="object"?n.index:null;return(o&&typeof o=="object"?o.hub:null)==="metadata"?"metadata":"off"}catch{return"off"}}async function rh(){try{let{createRequire:t}=await import("node:module");return t(import.meta.url)("node:sqlite")}catch{return null}}function Wi(t){return t.length>ri?t.slice(0,ri):t}function il(t){if(!vn(t))return[];let e=[];for(let r of qi(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=vt(t,r.name);r.isDirectory()?e.push(...il(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function nh(t){let e=[];for(let i of il(vt(t,"model/derived/structure"))){let s;try{s=Yi($n(i,"utf-8"))}catch{continue}let a=Ot(s);if(a.ok)for(let c of a.value.nodes){let l=re(c.key);l&&e.push({nodeId:c.key,kind:l.level,text:Wi(`${l.path} ${c.label??""}`.trim())})}}let r=vt(t,"model/facts/events");if(vn(r)){for(let i of qi(r).sort())if(i.endsWith(".yaml"))try{let s=Lt(Yi($n(vt(r,i),"utf-8")));if(!s.ok)continue;let a=s.value,c=[...a.links?.adr??[],...a.links?.tasks??[]].join(" ");e.push({nodeId:`task::${a.taskKey}`,kind:"task",text:Wi(`${a.taskKey} ${a.title??""} ${c}`.trim())})}catch{}}let n=vt(t,"model/facts/annotations");if(vn(n)){let i=new Map;for(let s of il(vt(t,"model/facts/identity")))try{let a=Yi($n(s,"utf-8"));for(let c of a?.entities??[])c.status==="active"&&c.entityId&&c.currentKey&&i.set(c.entityId,c.currentKey)}catch{}for(let s of qi(n).sort())if(s.endsWith(".md"))try{let a=$n(vt(n,s),"utf-8"),c=/^---\n[\s\S]*?entityId:\s*(e_[0-9a-f]{8})[\s\S]*?\n---\n?([\s\S]*)$/.exec(a);if(!c)continue;e.push({nodeId:i.get(c[1])??c[1],kind:"annotation",text:Wi(c[2].trim())})}catch{}}let o=vt(t,"adr");if(vn(o))for(let i of qi(o).sort()){let s=/^(\d{4})-/.exec(i)?.[1];if(!(!s||!i.endsWith(".md")))try{let a=$n(vt(o,i),"utf-8").split(`
707
+ `).slice(0,6);e.push({nodeId:`adr::ADR-${s}`,kind:"adr",text:Wi(a.filter(c=>c.trim()).join(" "))})}catch{}}return e}async function oh(t){let e=nh(t),r=await rh();if(!r)return{rows:e,indexed:!1};let n=new r.DatabaseSync(zi(t));try{n.exec("DROP TABLE IF EXISTS model_fts"),n.exec("CREATE VIRTUAL TABLE model_fts USING fts5(node_id UNINDEXED, kind UNINDEXED, text)");let o=n.prepare("INSERT INTO model_fts (node_id, kind, text) VALUES (?, ?, ?)");for(let i of e)o.run(i.nodeId,i.kind,i.text)}finally{n.close()}return{rows:e,indexed:!0}}function ih(t){let e=t.match(/[\p{L}\p{N}_./-]+/gu)??[];return e.length===0?null:e.map((r,n)=>`"${r.replace(/"/g,"")}"${n===e.length-1?"*":""}`).join(" ")}async function HS(t,e,r){let n=await rh();if(!n)throw new Error("model search needs Node with built-in sqlite (>= 22.13) on this CLI");vn(zi(t))||await oh(t);let o=ih(e);if(!o)return[];let i=Math.min(Math.max(r??20,1),ma),s=new n.DatabaseSync(zi(t));try{return s.prepare(`SELECT node_id AS nodeId, kind, snippet(model_fts, 2, '[', ']', '\u2026', 10) AS snippet,
708
708
  bm25(model_fts) AS rank
709
- FROM model_fts WHERE model_fts MATCH ? ORDER BY bm25(model_fts), node_id LIMIT ?`).all(o,i).map(c=>({nodeId:c.nodeId,kind:c.kind,score:-c.rank,snippet:c.snippet}))}finally{s.close()}}var Co=x(()=>{"use strict";B()});var Zi={};Fe(Zi,{mirrorLag:()=>iE,syncUpstream:()=>oE});import{simpleGit as fh}from"simple-git";async function oE(t,e,r,n){let o=fh(e),i=t.defaultBranch??"main",s=n?.upstream??mh(t);if(!s)return{repo:t.name,upstreamHead:null,updated:!1,error:"repo spec has no host/owner/repo"};try{await o.fetch(s,`+refs/heads/*:${jr}/*`,["--prune"]);let a=(await o.revparse([`${jr}/${i}`]).catch(()=>"")).trim()||null;if(!a)return{repo:t.name,upstreamHead:null,updated:!1,error:`upstream has no branch '${i}'`};let c=n?.mirror??(t.mirror?hh(t.mirror):null);if(!c)return{repo:t.name,upstreamHead:a,updated:!1};let l=await sE(o),u=await cl(o,c),p=[];for(let d of l){if(d==="codepipe"||d.startsWith("codepipe/"))continue;let m=(await o.revparse([`${jr}/${d}`]).catch(()=>"")).trim();!m||u.get(d)===m||p.push(`+${m}:refs/heads/${d}`)}return p.length===0?{repo:t.name,upstreamHead:a,updated:!1}:(await o.push([c,...p]),r.info(`${t.name}: mirror \u2190 ${p.length} branch(es), ${i} @ ${a.slice(0,10)}`),{repo:t.name,upstreamHead:a,updated:!0})}catch(a){let c=a instanceof Error?a.message.split(`
710
- `)[0]:String(a);return{repo:t.name,upstreamHead:null,updated:!1,error:c}}}async function iE(t,e,r){let n=r?.mirror??(t.mirror?hh(t.mirror):null);if(!n)return null;let o=r?.upstream??mh(t);if(!o)return null;let i=fh(e),s=t.defaultBranch??"main";try{let a=(await cl(i,n,s)).get(s);if(!a)return null;let c=(await cl(i,o,s)).get(s);if(!c)return null;if(c===a)return 0;let l=async()=>{let p=await i.raw(["rev-list","--count",`${a}..${c}`]).catch(()=>null);if(p===null)return null;let d=parseInt(p.trim(),10);return Number.isFinite(d)?d:null},u=await l();return u!==null?u:(await i.fetch(o,`+refs/heads/${s}:${jr}/${s}`),await l())}catch{return null}}function mh(t){return!t.host||!t.owner||!t.repoName?null:t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}function hh(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 sE(t){return(await t.raw(["for-each-ref",jr,"--format=%(refname)"]).catch(()=>"")).split(`
711
- `).map(r=>r.trim()).filter(r=>r.startsWith(`${jr}/`)).map(r=>r.slice(jr.length+1))}async function cl(t,e,r){let n=r?["--heads",e,r]:["--heads",e],o=await t.listRemote(n),i=new Map;for(let s of o.split(`
712
- `)){let[a,c]=s.trim().split(/\s+/);!a||!c||!/^[0-9a-f]{40}$/.test(a)||c.startsWith("refs/heads/")&&i.set(c.slice(11),a)}return i}var jr,Qi=x(()=>{"use strict";jr="refs/codepipe/upstream"});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 ll(){return Q("FARM_PINS")??fE(aE(),".codepipe","farm-pins.json")}function wh(){let t=ll();if(!cE(t))return{};try{return JSON.parse(uE(t,"utf-8"))}catch{return{}}}function mE(t){let e=ll();lE(pE(e),{recursive:!0}),dE(e,JSON.stringify(t,null,2)+`
713
- `,{mode:384})}function hE(t){return wh()[t]}function ts(t,e){let r=wh();r[t]=e,mE(r)}function rs(t,e){let r=He(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 ${ll()}.`);return r}var ul=x(()=>{"use strict";Ge();dt()});import{setTimeout as gE}from"node:timers/promises";import yE from"ws";function ns(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new yE(r)}async function ir(t,e,r){return sr(t,e,"/projects",r)}async function kh(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 os(t,e,r,n){return sr(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function bh(t,e,r,n){return sr(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function $h(t,e,r,n){return sr(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function vh(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 is(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 dl(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 xh(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await dl(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 gE(r.delayMs??1500)}throw o}async function Sh(t,e){let r=await fetch(`${t}/cli/bootstrap-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})});if(r.status===403){let n;try{n=(await r.json()).error}catch{}if(n==="registration_required")throw new No(e)}if(!r.ok)throw new K(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function Eh(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 Th(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 Rh(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 Ih(t,e,r,n,o){return sr(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function Oo(t,e,r,n){return sr(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function pl(t,e,r,n){await sr(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function Ch(t,e,r,n){return sr(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function Ph(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 le(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 sr(t,e,r,n){let o=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new K(o.status,s,a)}return s}async function Ah(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/deliverables`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new K(n.status,null,`GET /deliverables HTTP ${n.status}`);return(await n.json()).deliverables}var K,No,Ne=x(()=>{"use strict";K=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};No=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});import{existsSync as Xh,readFileSync as _E,readdirSync as jE}from"node:fs";import{join as Jh}from"node:path";import{simpleGit as NE}from"simple-git";import{parse as OE}from"yaml";function hl(t){let e=new Map,r=Jh(t,ei);if(!Xh(r))return e;let n;try{n=OE(_E(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 LE(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return vr({modelFormatVersion:2,repos:e})}function Zh(t,e){let r=Jh(t,e);if(!Xh(r))return[];let n=[];for(let o of jE(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...Zh(t,i)):n.push(i)}return n}async function cs(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 Zh(t,m))d.emittedShardPaths.has(f)||(n.push({path:f,content:"",deleted:!0}),o++)}let i=hl(t);for(let d of e)i.set(d.repo,{builtFromCommit:d.headCommit,counts:d.counts});n.push({path:ei,content:LE(i)});let s=Hi(t),a=Jm(s,r.halfLifeDays??nt.halfLifeDays);n.push({path:wr,content:Wi(a)});for(let d of e){let m=[];for(let f of s)for(let y of f.files)re(y.key)?.repo===d.repo&&m.push({kind:"touched_by",from:Ee(f.taskKey),to:y.key,...y.churn!==void 0?{weight:y.churn}:{}});n.push({path:ca(d.repo),content:br({modelFormatVersion:2,repo:d.repo,builtFromCommit:d.headCommit,edges:m})})}let c=NE(t),l=(await c.revparse(["HEAD"]).catch(()=>"")).trim(),u=`model: build ${e.map(d=>`${d.repo}@${d.headCommit.slice(0,10)}`).join(", ")}`;await Ce(t,n,u);let p=(await c.revparse(["HEAD"]).catch(()=>"")).trim();if(p!==l){let{rebuildSearchIndex:d}=await Promise.resolve().then(()=>(Co(),Io));await d(t).catch(()=>{})}return{committed:p!==l,filesWritten:n.filter(d=>!d.deleted).length,filesDeleted:o}}var Qh=x(()=>{"use strict";B();nl();lt()});var ds={};Fe(ds,{bootstrapDaemonModel:()=>DE,bootstrapModelForTargets:()=>$l,bootstrapWorkspaceModel:()=>og,modelBootstrapCommand:()=>bl,modelBuildCommand:()=>kl,rebuildWorkspaceModelIfStale:()=>UE});import{existsSync as ls}from"node:fs";import{join as ar}from"node:path";import{cancel as ME,intro as eg,log as gl,outro as yl}from"@clack/prompts";import{simpleGit as wl}from"simple-git";function us(t){ME(t),process.exit(1)}function tg(t,e,r){let n=t.spec.repos.filter(i=>!e||i.name===e);if(n.length===0)throw new Error(e?`repo "${e}" is not part of this project (see project.yaml)`:"the project has no repos configured");let o=[];for(let i of n){let s=i.mountAs==="."?t.root:ar(t.root,i.mountAs);if(!ls(ar(s,".git"))){r(`${i.name}: no local clone at ${s} \u2014 skipped (run \`codepipe clone\` first)`);continue}o.push({name:i.name,dir:s,defaultBranch:i.defaultBranch||"main"})}if(o.length===0)throw new Error("nothing to do \u2014 no repo clones found");return o}async function rg(t){let e=wl(t.dir),r=`origin/${t.defaultBranch}`;return await e.raw(["rev-parse","--verify",r]).then(()=>!0).catch(()=>!1)?r:"HEAD"}async function ng(t,e,r,n){let o=[];for(let i of e)try{let s=await el({repo:i.name,repoDir:i.dir,contextDir:t,settings:r,ref:await rg(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 kl(t){eg("codepipe model build");let e=_e();e||us("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{let r=bn(e.contextDir),n=tg(e,t.repo,s=>gl.warn(s)),o=await ng(e.contextDir,n,r,s=>gl.info(s)),i=await cs(e.contextDir,o,{halfLifeDays:r.cochange.halfLifeDays});i.committed?yl(`model updated: ${i.filesWritten} files written, ${i.filesDeleted} stale removed`):yl("model already up to date (no changes)")}catch(r){us(r instanceof Error?r.message:String(r))}}async function bl(t){eg("codepipe model bootstrap");let e=_e();e||us("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{await og(e,t.repo,{onLog:r=>gl.info(r)})}catch(r){us(r instanceof Error?r.message:String(r))}yl("bootstrap complete")}async function og(t,e,r){let n=tg(t,e,r.onLog);return $l(t.contextDir,n,r)}async function $l(t,e,r){let n=bn(t),o=await ng(t,e,n,r.onLog),i=$m(t),s=bm(n.issueKeyPattern,i),a=_r([...n.ignore,...kn]),c=[];for(let p of o){let d=e.find(f=>f.name===p.repo),m=await xm({repo:p.repo,repoDir:d.dir,headCommit:p.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:s,pathToCurrent:Fi(p.identityTable),entityByKey:p.entityByKey,ignored:a,trackerProjectKey:i});c.push(m),r.onLog(`${p.repo}: ${m.size} task events mined from history`)}let{files:l,skippedPipeline:u}=Sm(t,c);return u>0&&r.onLog(`${u} events already recorded by the live pipeline \u2014 left untouched`),l.length>0&&await Ce(t,l,`model: bootstrap ${l.length} task events from history`),await cs(t,o,{halfLifeDays:n.cochange.halfLifeDays}),{events:l.length}}async function DE(t,e,r,n){if(r.length===0)throw new Error("the project has no repos configured");let o=[];for(let s of r){let a=s.mountAs??s.name,c=a==="."?e.root:ar(e.root,a),l=s.defaultBranch||"main";c!==e.contextDir&&ls(ar(c,".git"))?(await wl(c).fetch(["origin",l]).catch(()=>{}),o.push({name:s.name,dir:c,defaultBranch:l})):(n(`${s.name}: materializing clone in the daemon layout`),await or(t,s),o.push({name:s.name,dir:je(t,s.name),defaultBranch:l}))}let i=await $l(e.contextDir,o,{onLog:n});return{repos:o.length,events:i.events}}async function UE(t,e={}){let r=e.onLog??(()=>{}),n=bn(t.contextDir),o=new Map;for(let l of t.repos){if(!l.mirror)continue;let u=l.mountAs==="."?t.root:ar(t.root,l.mountAs);if(!ls(ar(u,".git")))continue;let{syncUpstream:p}=await Promise.resolve().then(()=>(Qi(),Zi)),d=await p(l,u,{info:m=>r(`[mirror] ${m}`),warn:m=>r(`[mirror] ${m}`)});if(d.error||!d.upstreamHead){r(`[mirror] ${l.name}: sync failed (${d.error??"no upstream head"})`);continue}o.set(l.name,d.upstreamHead)}if(!n.enabled)return{rebuilt:[],skipped:[]};let i=[],s=[],a=hl(t.contextDir),c=[];for(let l of t.repos){let u=l.mountAs==="."?t.root:ar(t.root,l.mountAs);if(!ls(ar(u,".git")))continue;let p=wl(u),d=l.defaultBranch||"main",m=null;if(l.mirror){if(m=o.get(l.name)??null,!m){r(`[mirror] ${l.name}: map not rebuilt \u2014 sync did not complete`);continue}}else e.fetch&&await p.fetch(["origin",d]).catch(()=>{});let f=m??await rg({name:l.name,dir:u,defaultBranch:d}),y=(await p.revparse([f]).catch(()=>"")).trim();if(y){if(a.get(l.name)?.builtFromCommit===y){s.push(l.name);continue}try{c.push(await el({repo:l.name,repoDir:u,contextDir:t.contextDir,settings:n,ref:y})),i.push(l.name)}catch(k){r(`[model] rebuild of ${l.name} failed: ${k instanceof Error?k.message:String(k)}`)}}}return c.length>0&&(await cs(t.contextDir,c,{halfLifeDays:n.cochange.halfLifeDays}),r(`[model] release-path rebuild: ${i.join(", ")} (skipped up-to-date: ${s.join(", ")||"\u2014"})`)),{rebuilt:i,skipped:s}}var Lo=x(()=>{"use strict";lt();Qh();tl();Zc();Gi();Ro();vo();it()});var sg={};Fe(sg,{computeDriftReport:()=>HE,supersededAdrIds:()=>ig});import{existsSync as vl,readFileSync as xl,readdirSync as Sl}from"node:fs";import{join as xn}from"node:path";import{parse as BE}from"yaml";import{simpleGit as FE}from"simple-git";function KE(t,e){let r=xn(t,`model/derived/structure/${e}`),n=[],o="";if(!vl(r))return{nodes:n,builtFromCommit:o};for(let i of Sl(r).sort()){if(!i.endsWith(".yaml"))continue;let s;try{let a=Ot(BE(xl(xn(r,i),"utf-8")));if(!a.ok)continue;s=a.value}catch{continue}o=s.builtFromCommit;for(let a of s.nodes){let c=re(a.key);!c||c.level!=="code"&&c.level!=="component"||n.push({key:a.key,path:c.path,level:c.level,contentHash:a.contentHash,entityId:a.entityId})}}return{nodes:n,builtFromCommit:o}}function ig(t){let e=new Set,r=xn(t,"adr");if(!vl(r))return e;for(let n of Sl(r).sort()){let o=/^(\d{4})-/.exec(n)?.[1];if(!(!o||!n.endsWith(".md")))try{let i=xl(xn(r,n),"utf-8").slice(0,600).toLowerCase();/status[^\n]*superseded/.test(i)&&e.add(`ADR-${o}`)}catch{}}return e}async function HE(t,e,r){let{nodes:n,builtFromCommit:o}=KE(e,r),i=(await FE(t).revparse(["HEAD"])).trim(),s=await To(t,i),a=new Map(s.map(w=>[w.path,w.blobHash])),c=[],l=[],u=new Set,p=[];for(let w of n){if(w.level==="component"){p.push(w);continue}u.add(w.path);let $=a.get(w.path);$?w.contentHash&&$.slice(0,GE)!==w.contentHash&&c.push(w.key):l.push(w.key)}let d=0,m=new Map,f=new Set;for(let w of s){let $=w.path.lastIndexOf("/"),S=$<0?"":w.path.slice(0,$);m.has(S)||m.set(S,new Set),m.get(S).add(w.path),u.has(w.path)||d++;let T=S;for(;T!==""&&!f.has(T);)f.add(T),T=T.includes("/")?T.slice(0,T.lastIndexOf("/")):""}let y=new Map;for(let w of u){let $=w.lastIndexOf("/"),S=$<0?"":w.slice(0,$);y.has(S)||y.set(S,new Set),y.get(S).add(w)}for(let w of p){if(!f.has(w.path)){l.push(w.key);continue}let $=y.get(w.path)??new Set,S=m.get(w.path)??new Set;($.size!==S.size||[...$].some(v=>!S.has(v)))&&c.push(w.key)}let k=[],h=ig(e);if(h.size>0){let w=xn(e,"model/facts/annotations"),$=new Map(n.filter(S=>S.entityId).map(S=>[S.entityId,S.key]));if(vl(w))for(let S of Sl(w).sort()){if(!S.endsWith(".md"))continue;let T=S.replace(/\.md$/,""),v=$.get(T);if(v)try{(xl(xn(w,S),"utf-8").match(/\bADR-(\d{3,4})\b/g)??[]).map(j=>`ADR-${j.slice(4).padStart(4,"0")}`).some(j=>h.has(j))&&k.push(v)}catch{}}}return{repo:r,builtFromCommit:o,headCommit:i,stale:[...new Set(c)].sort(),orphaned:[...new Set(l)].sort(),superseded:[...new Set(k)].sort(),newFiles:d}}var GE,ag=x(()=>{"use strict";B();Ro();GE=12});import{execFileSync as QE}from"node:child_process";import{mkdtempSync as eT,mkdirSync as tT,readFileSync as ug,rmSync as rT,writeFileSync as nT}from"node:fs";import{tmpdir as oT}from"node:os";import{dirname as iT,join as dg}from"node:path";function pg(t="codepipe-context"){let e=eT(dg(oT(),"codepipe-ssh-")),r=dg(e,"id_ed25519");try{return QE("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:ug(r,"utf-8"),publicKey:ug(`${r}.pub`,"utf-8").trim()}}finally{rT(e,{recursive:!0,force:!0})}}async function fg(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 mg(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 hg(t,e){tT(iT(t),{recursive:!0});let r=e.endsWith(`
709
+ FROM model_fts WHERE model_fts MATCH ? ORDER BY bm25(model_fts), node_id LIMIT ?`).all(o,i).map(c=>({nodeId:c.nodeId,kind:c.kind,score:-c.rank,snippet:c.snippet}))}finally{s.close()}}var Co=x(()=>{"use strict";B()});var Ji={};Fe(Ji,{mirrorLag:()=>aE,syncUpstream:()=>sE});import{simpleGit as hh}from"simple-git";async function sE(t,e,r,n){let o=hh(e),i=t.defaultBranch??"main",s=n?.upstream??gh(t);if(!s)return{repo:t.name,upstreamHead:null,updated:!1,error:"repo spec has no host/owner/repo"};try{await o.fetch(s,`+refs/heads/*:${jr}/*`,["--prune"]);let a=(await o.revparse([`${jr}/${i}`]).catch(()=>"")).trim()||null;if(!a)return{repo:t.name,upstreamHead:null,updated:!1,error:`upstream has no branch '${i}'`};let c=n?.mirror??(t.mirror?yh(t.mirror):null);if(!c)return{repo:t.name,upstreamHead:a,updated:!1};let l=await cE(o),u=await ll(o,c),p=[];for(let d of l){if(d==="codepipe"||d.startsWith("codepipe/"))continue;let m=(await o.revparse([`${jr}/${d}`]).catch(()=>"")).trim();!m||u.get(d)===m||p.push(`+${m}:refs/heads/${d}`)}return p.length===0?{repo:t.name,upstreamHead:a,updated:!1}:(await o.push([c,...p]),r.info(`${t.name}: mirror \u2190 ${p.length} branch(es), ${i} @ ${a.slice(0,10)}`),{repo:t.name,upstreamHead:a,updated:!0})}catch(a){let c=a instanceof Error?a.message.split(`
710
+ `)[0]:String(a);return{repo:t.name,upstreamHead:null,updated:!1,error:c}}}async function aE(t,e,r){let n=r?.mirror??(t.mirror?yh(t.mirror):null);if(!n)return null;let o=r?.upstream??gh(t);if(!o)return null;let i=hh(e),s=t.defaultBranch??"main";try{let a=(await ll(i,n,s)).get(s);if(!a)return null;let c=(await ll(i,o,s)).get(s);if(!c)return null;if(c===a)return 0;let l=async()=>{let p=await i.raw(["rev-list","--count",`${a}..${c}`]).catch(()=>null);if(p===null)return null;let d=parseInt(p.trim(),10);return Number.isFinite(d)?d:null},u=await l();return u!==null?u:(await i.fetch(o,`+refs/heads/${s}:${jr}/${s}`),await l())}catch{return null}}function gh(t){return!t.host||!t.owner||!t.repoName?null:t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}function yh(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}async function cE(t){return(await t.raw(["for-each-ref",jr,"--format=%(refname)"]).catch(()=>"")).split(`
711
+ `).map(r=>r.trim()).filter(r=>r.startsWith(`${jr}/`)).map(r=>r.slice(jr.length+1))}async function ll(t,e,r){let n=r?["--heads",e,r]:["--heads",e],o=await t.listRemote(n),i=new Map;for(let s of o.split(`
712
+ `)){let[a,c]=s.trim().split(/\s+/);!a||!c||!/^[0-9a-f]{40}$/.test(a)||c.startsWith("refs/heads/")&&i.set(c.slice(11),a)}return i}var jr,Zi=x(()=>{"use strict";jr="refs/codepipe/upstream"});import{homedir as lE}from"node:os";import{existsSync as uE,mkdirSync as dE,readFileSync as pE,writeFileSync as fE}from"node:fs";import{dirname as mE,join as hE}from"node:path";function ul(){return Q("FARM_PINS")??hE(lE(),".codepipe","farm-pins.json")}function bh(){let t=ul();if(!uE(t))return{};try{return JSON.parse(pE(t,"utf-8"))}catch{return{}}}function gE(t){let e=ul();dE(mE(e),{recursive:!0}),fE(e,JSON.stringify(t,null,2)+`
713
+ `,{mode:384})}function yE(t){return bh()[t]}function es(t,e){let r=bh();r[t]=e,gE(r)}function ts(t,e){let r=He(e),n=yE(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 ${ul()}.`);return r}var dl=x(()=>{"use strict";Ge();dt()});import{setTimeout as wE}from"node:timers/promises";import kE from"ws";function rs(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new kE(r)}async function ir(t,e,r){return sr(t,e,"/projects",r)}async function $h(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new W(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function ns(t,e,r,n){return sr(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function vh(t,e,r,n){return sr(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function xh(t,e,r,n){return sr(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function Sh(t,e){let r=await fetch(`${t}/sandbox/me`,{headers:{Authorization:`Bearer ${e}`}});if(r.ok)return"ok";if(r.status===401)return"unknown";if(r.status===404)return"unsupported";throw new W(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function os(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new W(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function pl(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new W(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function Eh(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await pl(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 wE(r.delayMs??1500)}throw o}async function Th(t,e){let r=await fetch(`${t}/cli/bootstrap-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})});if(r.status===403){let n;try{n=(await r.json()).error}catch{}if(n==="registration_required")throw new No(e)}if(!r.ok)throw new W(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function Rh(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new W(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function Ih(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new W(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function Ch(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new W(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function Ph(t,e,r,n,o){return sr(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function Oo(t,e,r,n){return sr(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function fl(t,e,r,n){await sr(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function Ah(t,e,r,n){return sr(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function _h(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/repos/${encodeURIComponent(n)}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new W(o.status,s,a)}return s}async function ae(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new W(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function sr(t,e,r,n){let o=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new W(o.status,s,a)}return s}async function is(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/deliverables`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new W(n.status,null,`GET /deliverables HTTP ${n.status}`);return(await n.json()).deliverables}var W,No,je=x(()=>{"use strict";W=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};No=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});import{existsSync as eg,readFileSync as DE,readdirSync as UE}from"node:fs";import{join as tg}from"node:path";import{simpleGit as BE}from"simple-git";import{parse as FE}from"yaml";function yl(t){let e=new Map,r=tg(t,ei);if(!eg(r))return e;let n;try{n=FE(DE(r,"utf-8"))}catch{return e}let o=n?.repos;if(!o||typeof o!="object")return e;for(let[i,s]of Object.entries(o)){if(!s||typeof s!="object")continue;let a=s,c=a.counts??{};typeof a.builtFromCommit=="string"&&e.set(i,{builtFromCommit:a.builtFromCommit,counts:{component:typeof c.component=="number"?c.component:0,code:typeof c.code=="number"?c.code:0,correlates:typeof c.correlates=="number"?c.correlates:0}})}return e}function GE(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return vr({modelFormatVersion:2,repos:e})}function rg(t,e){let r=tg(t,e);if(!eg(r))return[];let n=[];for(let o of UE(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...rg(t,i)):n.push(i)}return n}async function ls(t,e,r={}){let n=[],o=0;for(let d of e){n.push(...d.files);let m=`model/derived/structure/${d.repo}`;for(let f of rg(t,m))d.emittedShardPaths.has(f)||(n.push({path:f,content:"",deleted:!0}),o++)}let i=yl(t);for(let d of e)i.set(d.repo,{builtFromCommit:d.headCommit,counts:d.counts});n.push({path:ei,content:GE(i)});let s=Ki(t),a=Qm(s,r.halfLifeDays??ot.halfLifeDays);n.push({path:wr,content:Hi(a)});for(let d of e){let m=[];for(let f of s)for(let g of f.files)re(g.key)?.repo===d.repo&&m.push({kind:"touched_by",from:Se(f.taskKey),to:g.key,...g.churn!==void 0?{weight:g.churn}:{}});n.push({path:la(d.repo),content:br({modelFormatVersion:2,repo:d.repo,builtFromCommit:d.headCommit,edges:m})})}let c=BE(t),l=(await c.revparse(["HEAD"]).catch(()=>"")).trim(),u=`model: build ${e.map(d=>`${d.repo}@${d.headCommit.slice(0,10)}`).join(", ")}`;await Ie(t,n,u);let p=(await c.revparse(["HEAD"]).catch(()=>"")).trim();if(p!==l){let{rebuildSearchIndex:d}=await Promise.resolve().then(()=>(Co(),Io));await d(t).catch(()=>{})}return{committed:p!==l,filesWritten:n.filter(d=>!d.deleted).length,filesDeleted:o}}var ng=x(()=>{"use strict";B();ol();lt()});var ps={};Fe(ps,{bootstrapDaemonModel:()=>HE,bootstrapModelForTargets:()=>xl,bootstrapWorkspaceModel:()=>cg,modelBootstrapCommand:()=>vl,modelBuildCommand:()=>$l,rebuildWorkspaceModelIfStale:()=>WE});import{existsSync as us}from"node:fs";import{join as ar}from"node:path";import{cancel as KE,intro as og,log as wl,outro as kl}from"@clack/prompts";import{simpleGit as bl}from"simple-git";function ds(t){KE(t),process.exit(1)}function ig(t,e,r){let n=t.spec.repos.filter(i=>!e||i.name===e);if(n.length===0)throw new Error(e?`repo "${e}" is not part of this project (see project.yaml)`:"the project has no repos configured");let o=[];for(let i of n){let s=i.mountAs==="."?t.root:ar(t.root,i.mountAs);if(!us(ar(s,".git"))){r(`${i.name}: no local clone at ${s} \u2014 skipped (run \`codepipe clone\` first)`);continue}o.push({name:i.name,dir:s,defaultBranch:i.defaultBranch||"main"})}if(o.length===0)throw new Error("nothing to do \u2014 no repo clones found");return o}async function sg(t){let e=bl(t.dir),r=`origin/${t.defaultBranch}`;return await e.raw(["rev-parse","--verify",r]).then(()=>!0).catch(()=>!1)?r:"HEAD"}async function ag(t,e,r,n){let o=[];for(let i of e)try{let s=await tl({repo:i.name,repoDir:i.dir,contextDir:t,settings:r,ref:await sg(i)});o.push(s),n(`${i.name}: ${s.counts.code} files, ${s.counts.component} components, ${s.counts.correlates} co-change edges @ ${s.headCommit.slice(0,10)}`)}catch(s){throw new Error(`${i.name}: ${s instanceof Error?s.message:String(s)}`)}return o}async function $l(t){og("codepipe model build");let e=Ae();e||ds("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{let r=bn(e.contextDir),n=ig(e,t.repo,s=>wl.warn(s)),o=await ag(e.contextDir,n,r,s=>wl.info(s)),i=await ls(e.contextDir,o,{halfLifeDays:r.cochange.halfLifeDays});i.committed?kl(`model updated: ${i.filesWritten} files written, ${i.filesDeleted} stale removed`):kl("model already up to date (no changes)")}catch(r){ds(r instanceof Error?r.message:String(r))}}async function vl(t){og("codepipe model bootstrap");let e=Ae();e||ds("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{await cg(e,t.repo,{onLog:r=>wl.info(r)})}catch(r){ds(r instanceof Error?r.message:String(r))}kl("bootstrap complete")}async function cg(t,e,r){let n=ig(t,e,r.onLog);return xl(t.contextDir,n,r)}async function xl(t,e,r){let n=bn(t),o=await ag(t,e,n,r.onLog),i=xm(t),s=vm(n.issueKeyPattern,i),a=_r([...n.ignore,...kn]),c=[];for(let p of o){let d=e.find(f=>f.name===p.repo),m=await Em({repo:p.repo,repoDir:d.dir,headCommit:p.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:s,pathToCurrent:Bi(p.identityTable),entityByKey:p.entityByKey,ignored:a,trackerProjectKey:i});c.push(m),r.onLog(`${p.repo}: ${m.size} task events mined from history`)}let{files:l,skippedPipeline:u}=Tm(t,c);return u>0&&r.onLog(`${u} events already recorded by the live pipeline \u2014 left untouched`),l.length>0&&await Ie(t,l,`model: bootstrap ${l.length} task events from history`),await ls(t,o,{halfLifeDays:n.cochange.halfLifeDays}),{events:l.length}}async function HE(t,e,r,n){if(r.length===0)throw new Error("the project has no repos configured");let o=[];for(let s of r){let a=s.mountAs??s.name,c=a==="."?e.root:ar(e.root,a),l=s.defaultBranch||"main";c!==e.contextDir&&us(ar(c,".git"))?(await bl(c).fetch(["origin",l]).catch(()=>{}),o.push({name:s.name,dir:c,defaultBranch:l})):(n(`${s.name}: materializing clone in the daemon layout`),await or(t,s),o.push({name:s.name,dir:_e(t,s.name),defaultBranch:l}))}let i=await xl(e.contextDir,o,{onLog:n});return{repos:o.length,events:i.events}}async function WE(t,e={}){let r=e.onLog??(()=>{}),n=bn(t.contextDir),o=new Map;for(let l of t.repos){if(!l.mirror)continue;let u=l.mountAs==="."?t.root:ar(t.root,l.mountAs);if(!us(ar(u,".git")))continue;let{syncUpstream:p}=await Promise.resolve().then(()=>(Zi(),Ji)),d=await p(l,u,{info:m=>r(`[mirror] ${m}`),warn:m=>r(`[mirror] ${m}`)});if(d.error||!d.upstreamHead){r(`[mirror] ${l.name}: sync failed (${d.error??"no upstream head"})`);continue}o.set(l.name,d.upstreamHead)}if(!n.enabled)return{rebuilt:[],skipped:[]};let i=[],s=[],a=yl(t.contextDir),c=[];for(let l of t.repos){let u=l.mountAs==="."?t.root:ar(t.root,l.mountAs);if(!us(ar(u,".git")))continue;let p=bl(u),d=l.defaultBranch||"main",m=null;if(l.mirror){if(m=o.get(l.name)??null,!m){r(`[mirror] ${l.name}: map not rebuilt \u2014 sync did not complete`);continue}}else e.fetch&&await p.fetch(["origin",d]).catch(()=>{});let f=m??await sg({name:l.name,dir:u,defaultBranch:d}),g=(await p.revparse([f]).catch(()=>"")).trim();if(g){if(a.get(l.name)?.builtFromCommit===g){s.push(l.name);continue}try{c.push(await tl({repo:l.name,repoDir:u,contextDir:t.contextDir,settings:n,ref:g})),i.push(l.name)}catch(k){r(`[model] rebuild of ${l.name} failed: ${k instanceof Error?k.message:String(k)}`)}}}return c.length>0&&(await ls(t.contextDir,c,{halfLifeDays:n.cochange.halfLifeDays}),r(`[model] release-path rebuild: ${i.join(", ")} (skipped up-to-date: ${s.join(", ")||"\u2014"})`)),{rebuilt:i,skipped:s}}var Lo=x(()=>{"use strict";lt();ng();rl();Qc();Fi();Ro();vo();kt()});var ug={};Fe(ug,{computeDriftReport:()=>XE,supersededAdrIds:()=>lg});import{existsSync as Sl,readFileSync as El,readdirSync as Tl}from"node:fs";import{join as xn}from"node:path";import{parse as qE}from"yaml";import{simpleGit as YE}from"simple-git";function VE(t,e){let r=xn(t,`model/derived/structure/${e}`),n=[],o="";if(!Sl(r))return{nodes:n,builtFromCommit:o};for(let i of Tl(r).sort()){if(!i.endsWith(".yaml"))continue;let s;try{let a=Ot(qE(El(xn(r,i),"utf-8")));if(!a.ok)continue;s=a.value}catch{continue}o=s.builtFromCommit;for(let a of s.nodes){let c=re(a.key);!c||c.level!=="code"&&c.level!=="component"||n.push({key:a.key,path:c.path,level:c.level,contentHash:a.contentHash,entityId:a.entityId})}}return{nodes:n,builtFromCommit:o}}function lg(t){let e=new Set,r=xn(t,"adr");if(!Sl(r))return e;for(let n of Tl(r).sort()){let o=/^(\d{4})-/.exec(n)?.[1];if(!(!o||!n.endsWith(".md")))try{let i=El(xn(r,n),"utf-8").slice(0,600).toLowerCase();/status[^\n]*superseded/.test(i)&&e.add(`ADR-${o}`)}catch{}}return e}async function XE(t,e,r){let{nodes:n,builtFromCommit:o}=VE(e,r),i=(await YE(t).revparse(["HEAD"])).trim(),s=await To(t,i),a=new Map(s.map(w=>[w.path,w.blobHash])),c=[],l=[],u=new Set,p=[];for(let w of n){if(w.level==="component"){p.push(w);continue}u.add(w.path);let $=a.get(w.path);$?w.contentHash&&$.slice(0,zE)!==w.contentHash&&c.push(w.key):l.push(w.key)}let d=0,m=new Map,f=new Set;for(let w of s){let $=w.path.lastIndexOf("/"),S=$<0?"":w.path.slice(0,$);m.has(S)||m.set(S,new Set),m.get(S).add(w.path),u.has(w.path)||d++;let R=S;for(;R!==""&&!f.has(R);)f.add(R),R=R.includes("/")?R.slice(0,R.lastIndexOf("/")):""}let g=new Map;for(let w of u){let $=w.lastIndexOf("/"),S=$<0?"":w.slice(0,$);g.has(S)||g.set(S,new Set),g.get(S).add(w)}for(let w of p){if(!f.has(w.path)){l.push(w.key);continue}let $=g.get(w.path)??new Set,S=m.get(w.path)??new Set;($.size!==S.size||[...$].some(v=>!S.has(v)))&&c.push(w.key)}let k=[],h=lg(e);if(h.size>0){let w=xn(e,"model/facts/annotations"),$=new Map(n.filter(S=>S.entityId).map(S=>[S.entityId,S.key]));if(Sl(w))for(let S of Tl(w).sort()){if(!S.endsWith(".md"))continue;let R=S.replace(/\.md$/,""),v=$.get(R);if(v)try{(El(xn(w,S),"utf-8").match(/\bADR-(\d{3,4})\b/g)??[]).map(j=>`ADR-${j.slice(4).padStart(4,"0")}`).some(j=>h.has(j))&&k.push(v)}catch{}}}return{repo:r,builtFromCommit:o,headCommit:i,stale:[...new Set(c)].sort(),orphaned:[...new Set(l)].sort(),superseded:[...new Set(k)].sort(),newFiles:d}}var zE,dg=x(()=>{"use strict";B();Ro();zE=12});import{execFileSync as iT}from"node:child_process";import{mkdtempSync as sT,mkdirSync as aT,readFileSync as fg,rmSync as cT,writeFileSync as lT}from"node:fs";import{tmpdir as uT}from"node:os";import{dirname as dT,join as mg}from"node:path";function hg(t="codepipe-context"){let e=sT(mg(uT(),"codepipe-ssh-")),r=mg(e,"id_ed25519");try{return iT("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:fg(r,"utf-8"),publicKey:fg(`${r}.pub`,"utf-8").trim()}}finally{cT(e,{recursive:!0,force:!0})}}async function gg(t,e,r,n="codepipe-context"){let o=await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/keys`,{method:"POST",headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({title:n,key:r,read_only:!1})});if(o.ok)return;let i=await o.text();if(!(o.status===422&&/already in use/i.test(i)))throw new Error(`add deploy key failed: ${o.status} ${i}`)}function yg(t){if(/^git@[^:]+:.+/.test(t))return t;let e=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(e)return`git@${e[1]}:${e[2]}`;let r=t.match(/^https:\/\/(?:[^@/]+@)?([^/]+)\/(.+)$/);return r?`git@${r[1]}:${r[2]}`:t}function wg(t,e){aT(dT(t),{recursive:!0});let r=e.endsWith(`
714
714
  `)?e:e+`
715
- `;return nT(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var Rl=x(()=>{"use strict"});import{existsSync as gg,mkdirSync as yg}from"node:fs";import{dirname as wg}from"node:path";import{simpleGit as Sn}from"simple-git";function sT(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 aT(t,e){return e?.contextWrite?.token?{user:uo(t),secret:e.contextWrite.token}:t===en.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===en.bitbucket?e?.bitbucket?.apiToken?{user:Dt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function kg(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 fs))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 ms(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await le(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new fs(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=aT(Tr(s.cloneUrl),r);if(a){let c=await cT({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 lT({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 cT(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=sT(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(gg(`${r}/.git`)){let l=Sn(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=Ec(r);await l.reset(["--hard",`origin/${s}`]),Tc(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else yg(wg(r),{recursive:!0}),await Sn().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await bg(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 lT(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=hg(i,n),a=mg(e.cloneUrl),c=e.branch;try{if(gg(`${r}/.git`)){let l=Sn(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=Ec(r);await l.reset(["--hard",`origin/${c}`]),Tc(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else yg(wg(r),{recursive:!0}),await Sn().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await Sn(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await bg(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 bg(t){let e=Sn(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 fs,Il=x(()=>{"use strict";B();Ne();Ft();Rl();fs=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as uT}from"node:child_process";function dT(){try{return uT("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function vg(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:dT(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var xg=x(()=>{"use strict"});import{homedir as pT}from"node:os";import{mkdirSync as fT,readFileSync as mT,writeFileSync as hT,existsSync as Sg}from"node:fs";import{dirname as gT,join as Pl}from"node:path";function yT(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function vt(t){let e=Q("SANDBOX_CONFIG");if(e)return e;let r=Pl(pT(),".codepipe","worker");return t?Pl(r,"profiles",t,"config.json"):Pl(r,"config.json")}function Eg(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function Le(t){let e=vt(t),r=null;return Sg(e)&&(r=JSON.parse(mT(e,"utf-8"))),r?(r.planningLane=yT(),r):null}function Tg(t,e){let r=vt(e);fT(gT(r),{recursive:!0}),hT(r,JSON.stringify(t,null,2)+`
716
- `,{mode:384})}var hs=x(()=>{"use strict";Ge();Sg(".env")&&process.loadEnvFile(".env")});import wT from"ws";var En,Al=x(()=>{"use strict";En=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 wT(e)}}});import{hostname as kT}from"node:os";async function Or(t){let e=Le(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${vt(t.profile)}.`),process.exit(1));let r=t.name??kT(),n=vg({projects:t.projects??[],llm:t.llm??null}),o=new En(t.hub.replace(/\/$/,"")),i=Oi(),s=He(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});Tg({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 ${vt(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 Rg=x(()=>{"use strict";dt();xg();hs();Al()});function Ig(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 gs(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 Cg(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 Tn(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 ys=x(()=>{"use strict"});import{spawn as bT}from"node:child_process";function _l(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function vT(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 xT(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Lr(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function jl(t,e){let r=[{type:"text",text:t}];return e&&r.push({type:"text",text:e}),JSON.stringify({type:"user",message:{role:"user",content:r}})+`
717
- `}async function jg(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Kt;let r=Tn(e.metadata),n=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",Ig(r)];e.model&&e.model.trim().length>0&&n.push("--model",e.model.trim());for(let l of e.addDirs??[])n.push("--add-dir",l);let o=e.onActivity,i=l=>{if(o)try{o(l)}catch{}},s=[],a=null,c=l=>{let u=Date.now(),p=l.type;if(p==="assistant"){let d=l.message;for(let m of d?.content??[]){let f=m.type;if(f==="text"){let y=String(m.text??"").trim();y&&i({ts:u,kind:"text",author:"agent",text:_l(y,Pg)})}else if(f==="tool_use"){let y=String(m.name??""),k=m.input?.file_path??m.input?.path,h=vT(k,e.workspaceDir);i({ts:u,kind:"tool",author:"agent",tool:y,...h?{file:h}:{}})}}return}if(p==="user"){let d=l.message;for(let m of d?.content??[])if(m.type==="tool_result"){let f=m.is_error===!0,y=f?_l(xT(m.content),200):"";i({ts:u,kind:"tool_result",author:"agent",isError:f,...y?{text:y}:{}})}return}if(p==="result"){a=l;let d=String(l.subtype??"").trim();i({ts:u,kind:"result",author:"agent",...d?{text:d}:{}});return}if(p==="system"){let d=String(l.subtype??"").trim();d&&i({ts:u,kind:"system",author:"agent",text:d})}};return i({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((l,u)=>{let p=bT(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,y=()=>{d=!0,p.kill("SIGTERM"),f=setTimeout(()=>p.kill("SIGKILL"),Ag)};e.signal?.addEventListener("abort",y,{once:!0});let k=null,h=()=>{k&&clearTimeout(k),k=setTimeout(()=>{m=!0,console.warn(`[claude:chat] idle for ${_g}ms \u2014 ending session`),p.kill("SIGTERM"),f=setTimeout(()=>p.kill("SIGKILL"),Ag)},_g)},w=()=>{f&&clearTimeout(f),k&&clearTimeout(k),e.signal?.removeEventListener("abort",y)},$=!0,S=b=>{if(!(!$||p.stdin.destroyed))try{p.stdin.write(b)}catch{}};S(jl(e.prompt)),h(),(async()=>{try{for await(let b of e.interactive.inbox){if(d||!$)break;if(h(),b.kind==="user")i({ts:Date.now(),kind:"text",author:"user",text:_l(b.text,Pg)}),S(jl(b.text,Cg(r)));else{S(jl($T)),$=!1;try{p.stdin.end()}catch{}break}}}catch{}})();let T="",v=b=>{let R;try{R=JSON.parse(b)}catch{return}c(R)};p.stdout.on("data",b=>{s.push(b),h(),T+=b;let R;for(;(R=T.indexOf(`
718
- `))!==-1;){let j=T.slice(0,R).trim();T=T.slice(R+1),j&&v(j)}}),p.stderr.on("data",b=>{s.push(b);for(let R of b.split(`
719
- `)){let j=R.trim();j&&console.warn(`[claude:chat:stderr] ${j}`)}}),p.on("error",b=>{w(),u(b)}),p.on("close",b=>{if(w(),d){u(new Kt);return}if(m){u(new Error("chat session ended: idle for too long without a reply"));return}T.trim()&&v(T.trim()),console.log(`[claude:chat] exit code=${b}`),l({artifactPaths:[],log:s.join(""),usage:ST(a)})})})}function ST(t){let e=qt();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=Lr(r.input_tokens),e.outputTokens=Lr(r.output_tokens),e.cacheReadInputTokens=Lr(r.cache_read_input_tokens),e.cacheCreationInputTokens=Lr(r.cache_creation_input_tokens)),e.totalCostUsd=Lr(t.total_cost_usd),e.numTurns=Lr(t.num_turns),e.durationMs=Lr(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var Pg,Ag,_g,$T,Ng=x(()=>{"use strict";B();Rn();ys();Pg=16e3,Ag=5e3,_g=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),$T="The user has finished the conversation. Now, based on everything discussed, write the DRAFT.md file in your current working directory following the contract from your instructions (line 1 \u2014 the issue title, \u2264 80 chars; line 2 \u2014 blank; lines 3+ \u2014 the body in Markdown), in the language of the conversation, and end your turn. Write nothing else."});import{spawn as ET}from"node:child_process";import{existsSync as TT}from"node:fs";function IT(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function Og(t){let e;try{e=JSON.parse(t)}catch{return console.log(`[claude] ${t.slice(0,200)}`),null}let r=e.type;if(r==="system"){let n=e.subtype??"";return console.log(`[claude] system ${n}`),e}if(r==="assistant"){let n=e.message;for(let o of n?.content??[]){let i=o.type;if(i==="text"){let s=String(o.text??"").trim();s&&console.log(`[claude] text: ${cr(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=AT(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=Mg(o.content);console.log(`[claude] tool_result (error)${i?`: ${cr(i,200)}`:""}`)}else console.log("[claude] tool_result");return e}if(r==="result"){let n=e.subtype??"",o=e.num_turns,i=e.total_cost_usd;return console.log(`[claude] result ${n} turns=${o} cost=$${i}`),e}return console.log(`[claude] ${String(r)} ${cr(JSON.stringify(e),200)}`),e}function CT(t,e,r){let n=t===0?["claude reported an error"]:[`claude exited with code ${t}`];if(e){let o=typeof e.result=="string"?e.result.trim():"",i=e.api_error_status,s=e.subtype;o?n.push(cr(o,500)):typeof s=="string"&&s!=="success"&&n.push(s),typeof i=="number"&&n.push(`(api_status=${i})`)}return n.length===1&&r.trim()&&n.push(cr(r.trim().split(`
715
+ `;return lT(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var Pl=x(()=>{"use strict"});import{existsSync as kg,mkdirSync as bg}from"node:fs";import{dirname as $g}from"node:path";import{simpleGit as Sn}from"simple-git";function pT(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 fT(t,e){return e?.contextWrite?.token?{user:uo(t),secret:e.contextWrite.token}:t===en.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===en.bitbucket?e?.bitbucket?.apiToken?{user:Dt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function vg(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 ms))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 hs(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await ae(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new ms(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=fT(Tr(s.cloneUrl),r);if(a){let c=await mT({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 hT({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 mT(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=pT(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(kg(`${r}/.git`)){let l=Sn(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=Tc(r);await l.reset(["--hard",`origin/${s}`]),Rc(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else bg($g(r),{recursive:!0}),await Sn().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await xg(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 hT(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=wg(i,n),a=yg(e.cloneUrl),c=e.branch;try{if(kg(`${r}/.git`)){let l=Sn(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=Tc(r);await l.reset(["--hard",`origin/${c}`]),Rc(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else bg($g(r),{recursive:!0}),await Sn().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await Sn(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await xg(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 xg(t){let e=Sn(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 ms,Al=x(()=>{"use strict";B();je();Ft();Pl();ms=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as gT}from"node:child_process";function yT(){try{return gT("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function Eg(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:yT(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var Tg=x(()=>{"use strict"});import{homedir as wT}from"node:os";import{mkdirSync as kT,readFileSync as bT,writeFileSync as $T,existsSync as Rg}from"node:fs";import{dirname as vT,join as jl}from"node:path";function xT(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function xt(t){let e=Q("SANDBOX_CONFIG");if(e)return e;let r=jl(wT(),".codepipe","worker");return t?jl(r,"profiles",t,"config.json"):jl(r,"config.json")}function Ig(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function Me(t){let e=xt(t),r=null;return Rg(e)&&(r=JSON.parse(bT(e,"utf-8"))),r?(r.planningLane=xT(),r):null}function Cg(t,e){let r=xt(e);kT(vT(r),{recursive:!0}),$T(r,JSON.stringify(t,null,2)+`
716
+ `,{mode:384})}var gs=x(()=>{"use strict";Ge();Rg(".env")&&process.loadEnvFile(".env")});import ST from"ws";var En,Nl=x(()=>{"use strict";En=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 ST(e)}}});import{hostname as ET}from"node:os";async function Or(t){let e=Me(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${xt(t.profile)}.`),process.exit(1));let r=t.name??ET(),n=Eg({projects:t.projects??[],llm:t.llm??null}),o=new En(t.hub.replace(/\/$/,"")),i=Ni(),s=He(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});Cg({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 ${xt(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 Pg=x(()=>{"use strict";dt();Tg();gs();Nl()});function Ag(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 ys(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 _g(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 Tn(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 ws=x(()=>{"use strict"});import{spawn as TT}from"node:child_process";function Ol(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function IT(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 CT(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Lr(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Ll(t,e){let r=[{type:"text",text:t}];return e&&r.push({type:"text",text:e}),JSON.stringify({type:"user",message:{role:"user",content:r}})+`
717
+ `}async function Lg(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Kt;let r=Tn(e.metadata),n=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",Ag(r)];e.model&&e.model.trim().length>0&&n.push("--model",e.model.trim());for(let l of e.addDirs??[])n.push("--add-dir",l);let o=e.onActivity,i=l=>{if(o)try{o(l)}catch{}},s=[],a=null,c=l=>{let u=Date.now(),p=l.type;if(p==="assistant"){let d=l.message;for(let m of d?.content??[]){let f=m.type;if(f==="text"){let g=String(m.text??"").trim();g&&i({ts:u,kind:"text",author:"agent",text:Ol(g,jg)})}else if(f==="tool_use"){let g=String(m.name??""),k=m.input?.file_path??m.input?.path,h=IT(k,e.workspaceDir);i({ts:u,kind:"tool",author:"agent",tool:g,...h?{file:h}:{}})}}return}if(p==="user"){let d=l.message;for(let m of d?.content??[])if(m.type==="tool_result"){let f=m.is_error===!0,g=f?Ol(CT(m.content),200):"";i({ts:u,kind:"tool_result",author:"agent",isError:f,...g?{text:g}:{}})}return}if(p==="result"){a=l;let d=String(l.subtype??"").trim();i({ts:u,kind:"result",author:"agent",...d?{text:d}:{}});return}if(p==="system"){let d=String(l.subtype??"").trim();d&&i({ts:u,kind:"system",author:"agent",text:d})}};return i({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((l,u)=>{let p=TT(t,n,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});p.stdout.setEncoding("utf-8"),p.stderr.setEncoding("utf-8");let d=!1,m=!1,f=null,g=()=>{d=!0,p.kill("SIGTERM"),f=setTimeout(()=>p.kill("SIGKILL"),Ng)};e.signal?.addEventListener("abort",g,{once:!0});let k=null,h=()=>{k&&clearTimeout(k),k=setTimeout(()=>{m=!0,console.warn(`[claude:chat] idle for ${Og}ms \u2014 ending session`),p.kill("SIGTERM"),f=setTimeout(()=>p.kill("SIGKILL"),Ng)},Og)},w=()=>{f&&clearTimeout(f),k&&clearTimeout(k),e.signal?.removeEventListener("abort",g)},$=!0,S=b=>{if(!(!$||p.stdin.destroyed))try{p.stdin.write(b)}catch{}};S(Ll(e.prompt)),h(),(async()=>{try{for await(let b of e.interactive.inbox){if(d||!$)break;if(h(),b.kind==="user")i({ts:Date.now(),kind:"text",author:"user",text:Ol(b.text,jg)}),S(Ll(b.text,_g(r)));else{S(Ll(RT)),$=!1;try{p.stdin.end()}catch{}break}}}catch{}})();let R="",v=b=>{let I;try{I=JSON.parse(b)}catch{return}c(I)};p.stdout.on("data",b=>{s.push(b),h(),R+=b;let I;for(;(I=R.indexOf(`
718
+ `))!==-1;){let j=R.slice(0,I).trim();R=R.slice(I+1),j&&v(j)}}),p.stderr.on("data",b=>{s.push(b);for(let I of b.split(`
719
+ `)){let j=I.trim();j&&console.warn(`[claude:chat:stderr] ${j}`)}}),p.on("error",b=>{w(),u(b)}),p.on("close",b=>{if(w(),d){u(new Kt);return}if(m){u(new Error("chat session ended: idle for too long without a reply"));return}R.trim()&&v(R.trim()),console.log(`[claude:chat] exit code=${b}`),l({artifactPaths:[],log:s.join(""),usage:PT(a)})})})}function PT(t){let e=qt();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=Lr(r.input_tokens),e.outputTokens=Lr(r.output_tokens),e.cacheReadInputTokens=Lr(r.cache_read_input_tokens),e.cacheCreationInputTokens=Lr(r.cache_creation_input_tokens)),e.totalCostUsd=Lr(t.total_cost_usd),e.numTurns=Lr(t.num_turns),e.durationMs=Lr(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var jg,Ng,Og,RT,Mg=x(()=>{"use strict";B();Rn();ws();jg=16e3,Ng=5e3,Og=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),RT="The user has finished the conversation. Now, based on everything discussed, write the DRAFT.md file in your current working directory following the contract from your instructions (line 1 \u2014 the issue title, \u2264 80 chars; line 2 \u2014 blank; lines 3+ \u2014 the body in Markdown), in the language of the conversation, and end your turn. Write nothing else."});import{spawn as AT}from"node:child_process";import{existsSync as _T}from"node:fs";function NT(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function Dg(t){let e;try{e=JSON.parse(t)}catch{return console.log(`[claude] ${t.slice(0,200)}`),null}let r=e.type;if(r==="system"){let n=e.subtype??"";return console.log(`[claude] system ${n}`),e}if(r==="assistant"){let n=e.message;for(let o of n?.content??[]){let i=o.type;if(i==="text"){let s=String(o.text??"").trim();s&&console.log(`[claude] text: ${cr(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=MT(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=Bg(o.content);console.log(`[claude] tool_result (error)${i?`: ${cr(i,200)}`:""}`)}else console.log("[claude] tool_result");return e}if(r==="result"){let n=e.subtype??"",o=e.num_turns,i=e.total_cost_usd;return console.log(`[claude] result ${n} turns=${o} cost=$${i}`),e}return console.log(`[claude] ${String(r)} ${cr(JSON.stringify(e),200)}`),e}function OT(t,e,r){let n=t===0?["claude reported an error"]:[`claude exited with code ${t}`];if(e){let o=typeof e.result=="string"?e.result.trim():"",i=e.api_error_status,s=e.subtype;o?n.push(cr(o,500)):typeof s=="string"&&s!=="success"&&n.push(s),typeof i=="number"&&n.push(`(api_status=${i})`)}return n.length===1&&r.trim()&&n.push(cr(r.trim().split(`
720
720
  `).slice(-5).join(`
721
- `),500)),n.join(" \u2014 ")}function PT(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 Mg(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function AT(t,e){if(!e)return"";if(t==="Write"||t==="Edit"||t==="Read"){let r=e.file_path??e.path;if(typeof r=="string")return`path=${r}`}if(t==="Bash"){let r=e.command;if(typeof r=="string")return`cmd=${cr(r,80)}`}return""}function cr(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function We(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function _T(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=We(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:We(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 jT(t,e,r,n){let o=qt(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=We(i.input_tokens),o.outputTokens=We(i.output_tokens),o.cacheReadInputTokens=We(i.cache_read_input_tokens),o.cacheCreationInputTokens=We(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=We(t?.total_cost_usd),o.numTurns=t&&We(t.num_turns)>0?We(t.num_turns):r,o.durationMs=We(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}function NT(t,e){let r=Date.now(),n=t.type;if(n==="system"){let o=String(t.subtype??"").trim();return o?[{ts:r,kind:"system",text:o}]:[]}if(n==="assistant"){let o=t.message,i=[];for(let s of o?.content??[]){let a=s.type;if(a==="text"){let c=String(s.text??"").trim();c&&i.push({ts:r,kind:"text",text:cr(c,Lg)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,p=OT(u,e);i.push({ts:r,kind:"tool",tool:c,...p?{file:p}:{}})}}return i}if(n==="user"){let o=t.message,i=[];for(let s of o?.content??[])if(s.type==="tool_result"){let a=s.is_error===!0,c=a?cr(Mg(s.content),Lg):"";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 OT(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 In,Kt,RT,Do,Lg,Rn=x(()=>{"use strict";B();Ng();ys();In=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Kt=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},RT=5e3;Do=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return jg(this.binary,e);if(e.signal?.aborted)throw new Kt;let r=["-p",IT(e.prompt),"--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",gs(Tn(e.metadata))];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let f of e.addDirs??[])r.push("--add-dir",f);e.settings&&Object.keys(e.settings).length>0&&r.push("--settings",JSON.stringify(e.settings));let n=[],o=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,u=f=>{if(f){if(f.type==="result"){i=f;return}if(f.type==="rate_limit_event"){let y=_T(f.rate_limit_info);y&&(!l||y.utilization>l.utilization)&&(l=y);return}if(f.type==="assistant"){let y=f.message;typeof y?.model=="string"&&(c=y.model);let k=y?.usage;k&&(a+=1,s.input+=We(k.input_tokens),s.output+=We(k.output_tokens),s.cacheRead+=We(k.cache_read_input_tokens),s.cacheCreate+=We(k.cache_creation_input_tokens))}}},p=e.role,d=e.onActivity,m=f=>{if(d)for(let y of NT(f,e.workspaceDir))try{d(y)}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,y)=>{let k=ET(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{},CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:"1800000"}});k.stdout.setEncoding("utf-8"),k.stderr.setEncoding("utf-8");let h=!1,w=null,$=()=>{h=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${p}`),k.kill("SIGTERM"),w=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),k.kill("SIGKILL")},RT)};e.signal?.addEventListener("abort",$,{once:!0});let S=()=>{w&&clearTimeout(w),e.signal?.removeEventListener("abort",$)},T="";k.stdout.on("data",v=>{n.push(v),T+=v;let b;for(;(b=T.indexOf(`
722
- `))!==-1;){let R=T.slice(0,b).trim();if(T=T.slice(b+1),R){let j=Og(R);u(j),j&&m(j)}}}),k.stderr.on("data",v=>{n.push(v),o.push(v);for(let b of v.split(`
723
- `)){let R=b.trim();R&&console.warn(`[claude:stderr] ${R}`)}}),k.on("error",v=>{S(),y(v)}),k.on("close",v=>{if(S(),h){y(new Kt);return}if(T.trim()){let R=Og(T.trim());u(R),R&&m(R)}let b=i?.is_error===!0;if(v!==0||b){let R=typeof i?.api_error_status=="number"?i.api_error_status:void 0,j=typeof i?.subtype=="string"?i.subtype:void 0,G=typeof i?.result=="string"?i.result:void 0;y(new In(CT(v,i,o.join("")),{code:v,apiErrorStatus:R,subtype:j,resultText:G,retryAfterMs:PT(i)}));return}console.log("[claude] exit code=0"),f({artifactPaths:[],log:n.join(""),usage:jT(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("/")&&TT(n))}};Lg=200});import{mkdirSync as LT,writeFileSync as Cn}from"node:fs";import{dirname as MT,join as Pn}from"node:path";function Dg(t,e,r){let n=Pn(t,e);LT(MT(n),{recursive:!0}),Cn(n,r)}function DT(t,e,r){return`# ${t} \u2014 Estimate
721
+ `),500)),n.join(" \u2014 ")}function LT(t){if(!t)return;let e=t.retry_after;if(typeof e=="number"&&e>0)return Math.round(e*1e3);let r=typeof t.result=="string"?t.result:"",n=/retry[\s-]*after[:\s]*(\d+)|reset[s]?\s+in[:\s]*(\d+)/i.exec(r),o=n?Number(n[1]??n[2]):NaN;return Number.isFinite(o)&&o>0?o*1e3:void 0}function Bg(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function MT(t,e){if(!e)return"";if(t==="Write"||t==="Edit"||t==="Read"){let r=e.file_path??e.path;if(typeof r=="string")return`path=${r}`}if(t==="Bash"){let r=e.command;if(typeof r=="string")return`cmd=${cr(r,80)}`}return""}function cr(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function We(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function DT(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=We(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:We(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 UT(t,e,r,n){let o=qt(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=We(i.input_tokens),o.outputTokens=We(i.output_tokens),o.cacheReadInputTokens=We(i.cache_read_input_tokens),o.cacheCreationInputTokens=We(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=We(t?.total_cost_usd),o.numTurns=t&&We(t.num_turns)>0?We(t.num_turns):r,o.durationMs=We(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}function BT(t,e){let r=Date.now(),n=t.type;if(n==="system"){let o=String(t.subtype??"").trim();return o?[{ts:r,kind:"system",text:o}]:[]}if(n==="assistant"){let o=t.message,i=[];for(let s of o?.content??[]){let a=s.type;if(a==="text"){let c=String(s.text??"").trim();c&&i.push({ts:r,kind:"text",text:cr(c,Ug)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,p=FT(u,e);i.push({ts:r,kind:"tool",tool:c,...p?{file:p}:{}})}}return i}if(n==="user"){let o=t.message,i=[];for(let s of o?.content??[])if(s.type==="tool_result"){let a=s.is_error===!0,c=a?cr(Bg(s.content),Ug):"";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 FT(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 In,Kt,jT,Do,Ug,Rn=x(()=>{"use strict";B();Mg();ws();In=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Kt=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},jT=5e3;Do=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return Lg(this.binary,e);if(e.signal?.aborted)throw new Kt;let r=["-p",NT(e.prompt),"--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",ys(Tn(e.metadata))];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let f of e.addDirs??[])r.push("--add-dir",f);e.settings&&Object.keys(e.settings).length>0&&r.push("--settings",JSON.stringify(e.settings));let n=[],o=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,u=f=>{if(f){if(f.type==="result"){i=f;return}if(f.type==="rate_limit_event"){let g=DT(f.rate_limit_info);g&&(!l||g.utilization>l.utilization)&&(l=g);return}if(f.type==="assistant"){let g=f.message;typeof g?.model=="string"&&(c=g.model);let k=g?.usage;k&&(a+=1,s.input+=We(k.input_tokens),s.output+=We(k.output_tokens),s.cacheRead+=We(k.cache_read_input_tokens),s.cacheCreate+=We(k.cache_creation_input_tokens))}}},p=e.role,d=e.onActivity,m=f=>{if(d)for(let g of BT(f,e.workspaceDir))try{d(g)}catch{}};return d?.({ts:Date.now(),kind:"start",text:`${p} job started`}),console.log(`[claude] spawn ${this.binary} role=${p}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((f,g)=>{let k=AT(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{},CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:"1800000"}});k.stdout.setEncoding("utf-8"),k.stderr.setEncoding("utf-8");let h=!1,w=null,$=()=>{h=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${p}`),k.kill("SIGTERM"),w=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),k.kill("SIGKILL")},jT)};e.signal?.addEventListener("abort",$,{once:!0});let S=()=>{w&&clearTimeout(w),e.signal?.removeEventListener("abort",$)},R="";k.stdout.on("data",v=>{n.push(v),R+=v;let b;for(;(b=R.indexOf(`
722
+ `))!==-1;){let I=R.slice(0,b).trim();if(R=R.slice(b+1),I){let j=Dg(I);u(j),j&&m(j)}}}),k.stderr.on("data",v=>{n.push(v),o.push(v);for(let b of v.split(`
723
+ `)){let I=b.trim();I&&console.warn(`[claude:stderr] ${I}`)}}),k.on("error",v=>{S(),g(v)}),k.on("close",v=>{if(S(),h){g(new Kt);return}if(R.trim()){let I=Dg(R.trim());u(I),I&&m(I)}let b=i?.is_error===!0;if(v!==0||b){let I=typeof i?.api_error_status=="number"?i.api_error_status:void 0,j=typeof i?.subtype=="string"?i.subtype:void 0,K=typeof i?.result=="string"?i.result:void 0;g(new In(OT(v,i,o.join("")),{code:v,apiErrorStatus:I,subtype:j,resultText:K,retryAfterMs:LT(i)}));return}console.log("[claude] exit code=0"),f({artifactPaths:[],log:n.join(""),usage:UT(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("/")&&_T(n))}};Ug=200});import{mkdirSync as GT,writeFileSync as Cn}from"node:fs";import{dirname as KT,join as Pn}from"node:path";function Fg(t,e,r){let n=Pn(t,e);GT(KT(n),{recursive:!0}),Cn(n,r)}function HT(t,e,r){return`# ${t} \u2014 Estimate
724
724
 
725
725
  **Title:** ${e}
726
726
 
@@ -741,7 +741,7 @@ production-grade estimates.)
741
741
  ${r.split(`
742
742
  `).slice(0,8).join(`
743
743
  `).trim()||"(empty)"}
744
- `}function UT(t,e,r,n){let o=n?`
744
+ `}function WT(t,e,r,n){let o=n?`
745
745
  ## Reviewer rework instruction
746
746
 
747
747
  > ${n.split(`
@@ -770,10 +770,10 @@ TBD (mock runner does not yet inspect project code).
770
770
  ${r.split(`
771
771
  `).slice(0,8).join(`
772
772
  `).trim()||"(empty)"}
773
- `}function BT(t){return`# ${t} \u2014 Open questions
773
+ `}function qT(t){return`# ${t} \u2014 Open questions
774
774
 
775
775
  (none \u2014 mock runner did not surface ambiguities.)
776
- `}function FT(t,e,r){let n=r?` (rework: ${r.split(`
776
+ `}function YT(t,e,r){let n=r?` (rework: ${r.split(`
777
777
  `)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
778
778
  index 0000000..1111111 100644
779
779
  --- a/CHANGELOG.md
@@ -784,7 +784,7 @@ index 0000000..1111111 100644
784
784
  +- mock-runner placeholder change for slice 5 testing.
785
785
  +
786
786
  # Changelog
787
- `}function GT(t,e,r){return`# ${t} \u2014 Diff summary
787
+ `}function zT(t,e,r){return`# ${t} \u2014 Diff summary
788
788
 
789
789
  **Title:** ${e}
790
790
  ${r?`
@@ -795,164 +795,164 @@ ${r?`
795
795
  - \`CHANGELOG.md\` \u2014 added entry for ${t}.
796
796
 
797
797
  (Mock-runner output. Replace with claude-headless for production patches.)
798
- `}var Uo,Nl=x(()=>{"use strict";B();Rn();Uo=class{name(){return"mock"}async run(e){if(e.interactive)return this.runInteractive(e);let r=e.metadata??{},n=r.trackerIssueKey??"TASK",o=r.taskTitle??"(unknown task)",i=r.taskDescription??"",s=[];if(e.role==="estimate"){let a=DT(n,o,i);Cn(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;Cn(Pn(e.workspaceDir,"PLAN.md"),UT(n,o,i,a)),s.push("PLAN.md"),Cn(Pn(e.workspaceDir,"QUESTIONS.md"),BT(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Dg(e.workspaceDir,"changes/sample.patch",FT(n,o,a)),s.push("changes/sample.patch"),Dg(e.workspaceDir,"SOLUTION.md",GT(n,o,a)),s.push("SOLUTION.md")}else e.role==="rework"&&(Cn(Pn(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
798
+ `}var Uo,Ml=x(()=>{"use strict";B();Rn();Uo=class{name(){return"mock"}async run(e){if(e.interactive)return this.runInteractive(e);let r=e.metadata??{},n=r.trackerIssueKey??"TASK",o=r.taskTitle??"(unknown task)",i=r.taskDescription??"",s=[];if(e.role==="estimate"){let a=HT(n,o,i);Cn(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;Cn(Pn(e.workspaceDir,"PLAN.md"),WT(n,o,i,a)),s.push("PLAN.md"),Cn(Pn(e.workspaceDir,"QUESTIONS.md"),qT(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Fg(e.workspaceDir,"changes/sample.patch",YT(n,o,a)),s.push("changes/sample.patch"),Fg(e.workspaceDir,"SOLUTION.md",zT(n,o,a)),s.push("SOLUTION.md")}else e.role==="rework"&&(Cn(Pn(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
799
799
  `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:qt()}}async runInteractive(e){let r=e.onActivity,n=i=>{r?.({ts:Date.now(),kind:"text",author:"agent",text:i}),r?.({ts:Date.now(),kind:"result",author:"agent",text:"success"})};r?.({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),n("Hi! Describe the task you'd like to formulate.");let o="Draft from chat";for await(let i of e.interactive.inbox){if(e.signal?.aborted)throw new Kt;if(i.kind==="user")r?.({ts:Date.now(),kind:"text",author:"user",text:i.text}),i.text.trim()&&(o=i.text.trim().slice(0,80)),n(`Got it: **${i.text.trim()}**. Anything else to clarify?`);else break}return Cn(Pn(e.workspaceDir,"DRAFT.md"),`${o}
800
800
 
801
801
  Produced by the interactive chat (mock runner).
802
- `),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:qt()}}}});function Ug(t){switch(t){case"mock":return new Uo;case"claude-headless":return new Do;default:return null}}function Bg(t,e){let r=e&&e.trim().length>0?e.trim():Xe;return t==="mock"?!0:t==="claude-headless"?r==="claude":!1}var Fg=x(()=>{"use strict";B();Rn();Nl();Rn();Nl()});function Hg(t=process.env){return{maxAttempts:ws(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:ws(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:ws(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:ws(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function qT(t){if(t instanceof In){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return HT.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&WT.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:KT.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:Gg.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 Gg.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function Wg(t){if(t instanceof In){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&Kg.test(n)}let e=t instanceof Error?t.message:String(t);return Kg.test(e)}function YT(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 qg(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=qT(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=YT(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 ws(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}var KT,Gg,HT,WT,Kg,Yg=x(()=>{"use strict";Rn();KT=new Set([429,500,502,503,529]),Gg=/(\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,HT=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,WT=new Set(["error_max_turns"]);Kg=/(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 zT,writeFileSync as VT}from"node:fs";import{homedir as XT}from"node:os";import{join as zg}from"node:path";function Xg(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 Jg(t,e,r,n){try{let o=zg(XT(),".codepipe","debug",Vg(t));zT(o,{recursive:!0});let i=new Date().toISOString().replace(/[:.]/g,"-"),s=zg(o,`${i}-${Vg(e)}-${r}.md`);return VT(s,n),s}catch{return null}}var Vg,Zg=x(()=>{"use strict";Vg=t=>t.replace(/[^A-Za-z0-9._-]/g,"_")});import{mkdtempSync as JT,rmSync as ZT,writeFileSync as Qg}from"node:fs";import{tmpdir as QT}from"node:os";import{join as Ol}from"node:path";function ks(t){return`[url "https://${t}/"]
802
+ `),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:qt()}}}});function Gg(t){switch(t){case"mock":return new Uo;case"claude-headless":return new Do;default:return null}}function Kg(t,e){let r=e&&e.trim().length>0?e.trim():Xe;return t==="mock"?!0:t==="claude-headless"?r==="claude":!1}var Hg=x(()=>{"use strict";B();Rn();Ml();Rn();Ml()});function Yg(t=process.env){return{maxAttempts:ks(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:ks(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:ks(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:ks(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function ZT(t){if(t instanceof In){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return XT.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&JT.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:VT.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:Wg.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 Wg.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function zg(t){if(t instanceof In){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&qg.test(n)}let e=t instanceof Error?t.message:String(t);return qg.test(e)}function QT(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 Vg(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=ZT(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=QT(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 ks(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}var VT,Wg,XT,JT,qg,Xg=x(()=>{"use strict";Rn();VT=new Set([429,500,502,503,529]),Wg=/(\bETIMEDOUT\b|\bECONNRESET\b|\bECONNREFUSED\b|\bEAI_AGAIN\b|\bEPIPE\b|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,XT=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,JT=new Set(["error_max_turns"]);qg=/(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 eR,writeFileSync as tR}from"node:fs";import{homedir as rR}from"node:os";import{join as Jg}from"node:path";function Qg(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 ey(t,e,r,n){try{let o=Jg(rR(),".codepipe","debug",Zg(t));eR(o,{recursive:!0});let i=new Date().toISOString().replace(/[:.]/g,"-"),s=Jg(o,`${i}-${Zg(e)}-${r}.md`);return tR(s,n),s}catch{return null}}var Zg,ty=x(()=>{"use strict";Zg=t=>t.replace(/[^A-Za-z0-9._-]/g,"_")});import{mkdtempSync as nR,rmSync as oR,writeFileSync as ry}from"node:fs";import{tmpdir as iR}from"node:os";import{join as Dl}from"node:path";function bs(t){return`[url "https://${t}/"]
803
803
  insteadOf = git@${t}:
804
804
  insteadOf = ssh://git@${t}/
805
- `}function ny(t,e){if(t.length===0)return null;let r=JT(Ol(QT(),"devpipe-gitcreds-")),n=Ol(r,"credentials"),o=Ol(r,"gitconfig");return Qg(n,t.join(`
805
+ `}function sy(t,e){if(t.length===0)return null;let r=nR(Dl(iR(),"devpipe-gitcreds-")),n=Dl(r,"credentials"),o=Dl(r,"gitconfig");return ry(n,t.join(`
806
806
  `)+`
807
- `,{mode:384}),Qg(o,`[credential]
807
+ `,{mode:384}),ry(o,`[credential]
808
808
  helper = store --file=${n}
809
- `+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:o,GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{ZT(r,{recursive:!0,force:!0})}catch{}}}}function Ll(t){let e=[],r=[];if(t.mirrorWrite?.token){let n=t.mirrorWrite.host;(!n||n==="github")&&(e.push(`https://x-access-token:${t.mirrorWrite.token}@github.com`),r.push(ey)),(!n||n==="gitlab")&&(e.push(`https://oauth2:${t.mirrorWrite.token}@gitlab.com`),r.push(ry)),(!n||n==="bitbucket")&&(e.push(`https://${Dt}:${encodeURIComponent(t.mirrorWrite.token)}@bitbucket.org`),r.push(ty))}return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(ey)),t.bitbucket?.apiToken&&(e.push(`https://${Dt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(ty)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(ry)),ny(e,r)}function oy(t,e){if(t.contextWrite?.token){let r=Tr(e)??"github.com",n=uo(r);return ny([`https://${n}:${t.contextWrite.token}@${r}`],[ks(r)])}return Ll(t)}var ey,ty,ry,iy=x(()=>{"use strict";B();ey=ks("github.com"),ty=ks("bitbucket.org"),ry=ks("gitlab.com")});import{spawn as ay}from"node:child_process";import{existsSync as bs,mkdirSync as Bo,readFileSync as eR,rmSync as Ml,symlinkSync as tR}from"node:fs";import{homedir as rR}from"node:os";import{dirname as _n,join as lr}from"node:path";function cy(t){let e=lr(rR(),".codepipe-sandbox","repos");return t?lr(e,t):e}function ly(t,e){let n=(An.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{An.get(t)===o&&An.delete(t)},()=>{An.get(t)===o&&An.delete(t)});return An.set(t,o),n}function sy(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 nR(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 uy(t,e,r,n,o){let i=async c=>{await oe(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await oe(t,["reset","--hard",`origin/${c}`],o),await oe(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!sy(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{bs(t)&&Ml(t,{recursive:!0,force:!0}),Bo(_n(t),{recursive:!0});try{return await oe(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!sy(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),bs(t)&&Ml(t,{recursive:!0,force:!0}),Bo(_n(t),{recursive:!0}),await oe(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(bs(lr(t,".git")))try{return await s()}catch(c){if(!nR(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 dy(t){await oe(t.workspacePath,["reset","--hard",t.baseSha]),await oe(t.workspacePath,["clean","-fdx"])}async function py(t,e){let r=t.workspacePath;await oe(r,["add","-A"]);let n=(await Re(r,["write-tree"])).trim(),o=(await Re(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:jn,GIT_AUTHOR_EMAIL:Nn,GIT_COMMITTER_NAME:jn,GIT_COMMITTER_EMAIL:Nn};return(await Re(r,["commit-tree",n,"-m",e],i)).trim()}async function fy(t,e,r,n,o){try{await oe(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw Tr(n)==="github.com"&&/without `?workflow`? scope|workflow.*scope/i.test(s)?new Error("delivery push rejected: the Context-Repo push token needs the `workflow` scope (the delivery includes .github/workflows/*). Set secrets.contextWrite.token to a fine-grained PAT on the Context Repo with Contents: write + Workflows: write (or add `workflow` to the project token).\n"+s):i}}async function my(t,e){return Re(t.workspacePath,["diff","--binary",t.baseSha,e])}async function hy(t,e,r,n,o){await oe(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await oe(t.workspacePath,["checkout","--force",r])}async function gy(t,e,r,n,o,i){let s=t.workspacePath;await oe(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await Re(s,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=f=>Re(s,["rev-parse","-q","--verify",`${f}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await Re(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await oe(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(y=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(y)}`)}),await c(n)||await oe(s,["fetch","origin",n],i).catch(()=>{}),!await c(n)))throw new Error(`moved-base apply: delivery base ${n.slice(0,10)} is unreachable \u2014 cannot re-apply the previous iteration onto the fresh ${t.ref}`);let l={...i??process.env,GIT_AUTHOR_NAME:jn,GIT_AUTHOR_EMAIL:Nn,GIT_COMMITTER_NAME:jn,GIT_COMMITTER_EMAIL:Nn},u=(await Re(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),p=(await Re(s,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await oe(s,["cherry-pick","--quit"],l).catch(()=>{});let d=null;try{await oe(s,["cherry-pick","--no-commit",p],l)}catch(f){d=f instanceof Error?f.message:String(f)}let m=(await Re(s,["diff","--name-only","--diff-filter=U"])).split(`
810
- `).map(f=>f.trim()).filter(f=>f.length>0);if(d&&m.length===0)throw await oe(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${d}`);return m}async function Dl(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:jn,GIT_AUTHOR_EMAIL:Nn,GIT_COMMITTER_NAME:jn,GIT_COMMITTER_EMAIL:Nn};(await Re(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await oe(n,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),await oe(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await oe(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await Re(n,["diff","--name-only","--diff-filter=U"])).split(`
811
- `).map(l=>l.trim()).filter(l=>l.length>0),c=await Re(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}async function wy(t,e){return Re(t.workspacePath,["diff","--unified=0",`${yy}..HEAD`],e)}async function Ul(t,e,r){await oe(t.workspacePath,["update-ref",yy,e],r)}async function ky(t,e,r){let n=t.workspacePath,o=[`+refs/heads/${e}:refs/remotes/origin/${e}`,...t.ref!==e?[`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`]:[]];await oe(n,["fetch","--depth=1","origin",...o],r).catch(a=>{console.warn(`[git] review-base ${t.name}: base fetch failed: ${String(a)}`)});let i=()=>Re(n,["merge-base",`origin/${e}`,"HEAD"],r).then(a=>a.trim()||null).catch(()=>null),s=await i();for(let a of[64,256,1024]){if(s)break;await oe(n,["fetch",`--deepen=${a}`,"origin",...o],r).catch(c=>{console.warn(`[git] review-base ${t.name}: --deepen=${a} failed: ${String(c)}`)}),s=await i()}return s||(await Re(n,["rev-parse","--is-shallow-repository"],r)).trim()==="true"&&(await oe(n,["fetch","--unshallow","origin",...o],r).catch(c=>{console.warn(`[git] review-base ${t.name}: --unshallow failed: ${String(c)}`)}),s=await i()),s&&await Ul(t,s,r),s}function oe(t,e,r){return new Promise((n,o)=>{let i=ay("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[];i.stderr.setEncoding("utf-8"),i.stderr.on("data",a=>s.push(a)),i.on("error",o),i.on("close",a=>{if(a===0)return n();o(new Error(`git ${e[0]} failed (exit ${a}):
812
- ${s.join("").trim()||"(no stderr)"}`))})})}function Re(t,e,r){return new Promise((n,o)=>{let i=ay("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[],a=[];i.stdout.setEncoding("utf-8"),i.stderr.setEncoding("utf-8"),i.stdout.on("data",c=>s.push(c)),i.stderr.on("data",c=>a.push(c)),i.on("error",o),i.on("close",c=>{if(c===0)return n(s.join(""));o(new Error(`git ${e[0]} failed (exit ${c}):
813
- ${a.join("").trim()||"(no stderr)"}`))})})}function by(t,e){bs(t)&&Ml(t,{recursive:!0,force:!0}),Bo(_n(t),{recursive:!0}),tR(e,t,"dir")}async function $y(t,e,r){await oe(t,["worktree","prune"]).catch(()=>{}),Bo(_n(r),{recursive:!0}),await oe(t,["worktree","add","--detach",r,`origin/${e}`])}async function oR(t,e,r){Bo(_n(r),{recursive:!0}),await oe(_n(r),["clone","--quiet","--no-checkout",t,r]),await oe(r,["checkout","--force","--detach",e])}async function vy(t,e,r,n="worktree",o,i){return r.length===0?[]:ly(e,async()=>{let s=[];for(let a of r){let c=lr(cy(i),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await uy(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 Re(c,["rev-parse","HEAD"])).trim(),p=lr(t,"code",a.name);n==="direct"?(by(p,c),console.log(`[git] code: linked ${p} \u2192 ${c} @ ${u.slice(0,10)}`)):n==="clone"?(await oR(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)}`)),s.push({name:a.name,workspacePath:p,cachePath:c,ref:l,baseSha:u})}return s})}async function xy(t,e,r,n="worktree",o,i){if(!r||!r.cloneUrl)return null;let s=r;return ly(e,async()=>{let a=lr(cy(i),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);try{await uy(a,s.cloneUrl,s.ref,void 0,o)}catch(u){throw new Error(`failed to materialize context repo (${s.cloneUrl}): `+(u instanceof Error?u.message:String(u)))}let c=lr(t,"context");n==="direct"?(by(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await $y(a,s.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await Re(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function Sy(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await oe(r,["add","-A",...n]).catch(()=>{});let o;try{o=await Re(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
814
- `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=eR(lr(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var An,jn,Nn,yy,Ey=x(()=>{"use strict";B();An=new Map;jn="CodePipe Agent",Nn="codepipe@codepartner.ee";yy="refs/worktree/codepipe/review-base"});import{existsSync as iR,readFileSync as sR}from"node:fs";import{join as aR}from"node:path";import{parse as cR}from"yaml";function Ty(t){if(!t)return!1;let e=aR(t,Bl);if(!iR(e))return!1;try{let r=cR(sR(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 Bl,Ry=x(()=>{"use strict";Bl="knowledge/build.yaml"});import{readFileSync as lR}from"node:fs";import{join as uR}from"node:path";function Iy(t){let e=uR(t,Fo),r;try{r=lR(e,"utf-8")}catch{throw new ur(`BUILD produced no ${Fo} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new ur(`${Fo} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new ur(`${Fo} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new ur(`${Fo}: "ok" must be a boolean`);let i=o.ok,a=(Array.isArray(o.steps)?o.steps:[]).flatMap(u=>{if(!u||typeof u!="object")return[];let p=u,d=typeof p.name=="string"?p.name:null,m=typeof p.exitCode=="number"?p.exitCode:null;if(d===null||m===null)return[];let f={name:d,exitCode:m};return typeof p.durationMs=="number"&&(f.durationMs=p.durationMs),[f]}),c=typeof o.logTail=="string"?dR(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 dR(t){let e=Buffer.from(t,"utf-8");return e.length<=Fl?t:`\u2026 [${e.length-Fl} bytes elided] \u2026
815
- `+e.subarray(e.length-Fl).toString("utf-8")}var Fl,ur,Fo,Cy=x(()=>{"use strict";Fl=8*1024,ur=class extends Error{},Fo="meta/build-result.json"});var Py={};Fe(Py,{REVIEW_RESULT_PATH:()=>Mr,ReviewVerdictError:()=>Ct,markFindingScope:()=>kR,parseChangedRanges:()=>wR,readCodeReviewResult:()=>Gl});import{readFileSync as pR}from"node:fs";import{join as fR}from"node:path";function Gl(t){let e=fR(t,Mr),r;try{r=pR(e,"utf-8")}catch{throw new Ct(`code review produced no ${Mr} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(l){throw new Ct(`${Mr} is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}if(!n||typeof n!="object")throw new Ct(`${Mr} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new Ct(`${Mr}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?dr(o.remarks,mR):"";if(!i&&s.trim().length===0)throw new Ct(`${Mr}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?dr(o.summary,hR):"",c=yR(o.findings);return{approved:i,remarks:s,summary:a,...c.length>0?{findings:c}:{}}}function yR(t){if(!Array.isArray(t))return[];let e=[];for(let r of t.slice(0,gR)){if(!r||typeof r!="object")continue;let n=r,o=typeof n.title=="string"?dr(n.title,512).trim():"",i=typeof n.problem=="string"?dr(n.problem,$s).trim():"";if(!o||!i)continue;let s=typeof n.line=="number"&&Number.isInteger(n.line)&&n.line>0?n.line:void 0,a=n.severity==="blocker"||n.severity==="major"||n.severity==="minor"?n.severity:"other",c=typeof n.scenario=="string"&&n.scenario.trim()?dr(n.scenario,$s):void 0;a==="blocker"&&!c&&(console.warn(`[review] blocker "${o.slice(0,80)}" carries no scenario \u2014 demoted to major`),a="major"),e.push({severity:a,title:o,problem:i,...typeof n.repo=="string"&&n.repo?{repo:n.repo}:{},...typeof n.file=="string"&&n.file?{file:dr(n.file,1024)}:{},...s!==void 0?{line:s}:{},...c?{scenario:c}:{},...typeof n.suggestion=="string"&&n.suggestion.trim()?{suggestion:dr(n.suggestion,$s)}:{},...n.confidence==="high"||n.confidence==="medium"||n.confidence==="low"?{confidence:n.confidence}:{},...n.rule_source==="adr"||n.rule_source==="convention"||n.rule_source==="build"||n.rule_source==="judgment"?{ruleSource:n.rule_source}:{},...typeof n.out_of_diff_reason=="string"&&n.out_of_diff_reason.trim()?{outOfDiffReason:dr(n.out_of_diff_reason,$s)}:{}})}return e}function dr(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
816
- \u2026 [${r.length-e} bytes elided]`}function wR(t){let e=new Map,r=null;for(let n of t.split(`
817
- `)){if(n.startsWith("+++ ")){let o=n.slice(4).trim();r=o==="/dev/null"?null:o.replace(/^b\//,""),r&&!e.has(r)&&e.set(r,[]);continue}if(r&&n.startsWith("@@")){let o=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(n);if(!o)continue;let i=Number(o[1]),s=o[2]!==void 0?Number(o[2]):1,a=s===0?Math.max(1,i):i,c=s===0?Math.max(1,i):i+s-1;e.get(r).push([a,c])}}return e}function kR(t,e,r){for(let n of t.findings??[]){if(!n.file)continue;let o=n.repo??r;if(!o)continue;let i=e.get(o);if(!i)continue;let s=i.get(n.file);if(!s){n.scope="outside";continue}if(n.line===void 0||s.length===0){n.scope="diff";continue}let a=n.line;n.scope=s.some(([c,l])=>a>=c&&a<=l)?"diff":"file"}}var mR,hR,Ct,Mr,$s,gR,Kl=x(()=>{"use strict";mR=16*1024,hR=4*1024,Ct=class extends Error{},Mr="meta/review-result.json";$s=8*1024,gR=50});import{readFileSync as bR,statSync as $R}from"node:fs";import{join as Ay}from"node:path";function IR(t){return t.startsWith("meta/")||RR.has(t)}function CR(t,e,r,n){return`[codepipe] artifact omitted from upload: ${t} was ${e} bytes, exceeds the SANDBOX upload budget (per-artifact ${r} / total ${n}). The delivered code (git) and the build/review verdict are unaffected \u2014 only this display/durability copy was dropped.`}function PR(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function _y(t,e,r){let n=r?.maxBytes??vR,o=r?.totalBytes??xR,i=r?.maxCount??SR,s=e.map((f,y)=>{let k=null;try{k=$R(Ay(t,f)).size}catch{}return{path:f,index:y,size:k}}),a=[...s].sort((f,y)=>{let k=h=>IR(h.path)?0:1;return k(f)!==k(y)?k(f)-k(y):(f.size??0)-(y.size??0)}),c=a.slice(0,i),l=a.slice(i).sort((f,y)=>f.index-y.index).map(f=>f.path),u=new Array(s.length),p=[],d=0;for(let f of c){let y=null;if(f.size!==null&&f.size<=n&&d+f.size<=o)try{y=bR(Ay(t,f.path))}catch{}if(y!==null){d+=y.length,u[f.index]={path:f.path,contentBase64:y.toString("base64")};continue}let k=f.size===null?PR(f.path):CR(f.path,f.size,n,o),h=Buffer.from(k,"utf-8");d+=h.length,u[f.index]={path:f.path,contentBase64:h.toString("base64")},p.push({path:f.path,bytes:f.size??0})}let m=u.filter(f=>f!==void 0);if(l.length>0){let f=l.slice(0,TR),y=`# Artifacts omitted from upload
809
+ `+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:o,GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{oR(r,{recursive:!0,force:!0})}catch{}}}}function Ul(t){let e=[],r=[];if(t.mirrorWrite?.token){let n=t.mirrorWrite.host;(!n||n==="github")&&(e.push(`https://x-access-token:${t.mirrorWrite.token}@github.com`),r.push(ny)),(!n||n==="gitlab")&&(e.push(`https://oauth2:${t.mirrorWrite.token}@gitlab.com`),r.push(iy)),(!n||n==="bitbucket")&&(e.push(`https://${Dt}:${encodeURIComponent(t.mirrorWrite.token)}@bitbucket.org`),r.push(oy))}return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(ny)),t.bitbucket?.apiToken&&(e.push(`https://${Dt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(oy)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(iy)),sy(e,r)}function ay(t,e){if(t.contextWrite?.token){let r=Tr(e)??"github.com",n=uo(r);return sy([`https://${n}:${t.contextWrite.token}@${r}`],[bs(r)])}return Ul(t)}var ny,oy,iy,cy=x(()=>{"use strict";B();ny=bs("github.com"),oy=bs("bitbucket.org"),iy=bs("gitlab.com")});import{spawn as uy}from"node:child_process";import{existsSync as $s,mkdirSync as Bo,readFileSync as sR,rmSync as Bl,symlinkSync as aR}from"node:fs";import{homedir as cR}from"node:os";import{dirname as _n,join as lr}from"node:path";function dy(t){let e=lr(cR(),".codepipe-sandbox","repos");return t?lr(e,t):e}function py(t,e){let n=(An.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{An.get(t)===o&&An.delete(t)},()=>{An.get(t)===o&&An.delete(t)});return An.set(t,o),n}function ly(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 lR(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 fy(t,e,r,n,o){let i=async c=>{await oe(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await oe(t,["reset","--hard",`origin/${c}`],o),await oe(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!ly(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{$s(t)&&Bl(t,{recursive:!0,force:!0}),Bo(_n(t),{recursive:!0});try{return await oe(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!ly(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),$s(t)&&Bl(t,{recursive:!0,force:!0}),Bo(_n(t),{recursive:!0}),await oe(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if($s(lr(t,".git")))try{return await s()}catch(c){if(!lR(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 my(t){await oe(t.workspacePath,["reset","--hard",t.baseSha]),await oe(t.workspacePath,["clean","-fdx"])}async function hy(t,e){let r=t.workspacePath;await oe(r,["add","-A"]);let n=(await Te(r,["write-tree"])).trim(),o=(await Te(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:jn,GIT_AUTHOR_EMAIL:Nn,GIT_COMMITTER_NAME:jn,GIT_COMMITTER_EMAIL:Nn};return(await Te(r,["commit-tree",n,"-m",e],i)).trim()}async function gy(t,e,r,n,o){try{await oe(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw Tr(n)==="github.com"&&/without `?workflow`? scope|workflow.*scope/i.test(s)?new Error("delivery push rejected: the Context-Repo push token needs the `workflow` scope (the delivery includes .github/workflows/*). Set secrets.contextWrite.token to a fine-grained PAT on the Context Repo with Contents: write + Workflows: write (or add `workflow` to the project token).\n"+s):i}}async function yy(t,e){return Te(t.workspacePath,["diff","--binary",t.baseSha,e])}async function wy(t,e,r,n,o){await oe(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await oe(t.workspacePath,["checkout","--force",r])}async function ky(t,e,r,n,o,i){let s=t.workspacePath;await oe(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await Te(s,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=f=>Te(s,["rev-parse","-q","--verify",`${f}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await Te(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await oe(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(g=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(g)}`)}),await c(n)||await oe(s,["fetch","origin",n],i).catch(()=>{}),!await c(n)))throw new Error(`moved-base apply: delivery base ${n.slice(0,10)} is unreachable \u2014 cannot re-apply the previous iteration onto the fresh ${t.ref}`);let l={...i??process.env,GIT_AUTHOR_NAME:jn,GIT_AUTHOR_EMAIL:Nn,GIT_COMMITTER_NAME:jn,GIT_COMMITTER_EMAIL:Nn},u=(await Te(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),p=(await Te(s,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await oe(s,["cherry-pick","--quit"],l).catch(()=>{});let d=null;try{await oe(s,["cherry-pick","--no-commit",p],l)}catch(f){d=f instanceof Error?f.message:String(f)}let m=(await Te(s,["diff","--name-only","--diff-filter=U"])).split(`
810
+ `).map(f=>f.trim()).filter(f=>f.length>0);if(d&&m.length===0)throw await oe(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${d}`);return m}async function Fl(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:jn,GIT_AUTHOR_EMAIL:Nn,GIT_COMMITTER_NAME:jn,GIT_COMMITTER_EMAIL:Nn};(await Te(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await oe(n,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),await oe(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await oe(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await Te(n,["diff","--name-only","--diff-filter=U"])).split(`
811
+ `).map(l=>l.trim()).filter(l=>l.length>0),c=await Te(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}async function $y(t,e){return Te(t.workspacePath,["diff","--unified=0",`${by}..HEAD`],e)}async function Gl(t,e,r){await oe(t.workspacePath,["update-ref",by,e],r)}async function vy(t,e,r){let n=t.workspacePath,o=[`+refs/heads/${e}:refs/remotes/origin/${e}`,...t.ref!==e?[`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`]:[]];await oe(n,["fetch","--depth=1","origin",...o],r).catch(a=>{console.warn(`[git] review-base ${t.name}: base fetch failed: ${String(a)}`)});let i=()=>Te(n,["merge-base",`origin/${e}`,"HEAD"],r).then(a=>a.trim()||null).catch(()=>null),s=await i();for(let a of[64,256,1024]){if(s)break;await oe(n,["fetch",`--deepen=${a}`,"origin",...o],r).catch(c=>{console.warn(`[git] review-base ${t.name}: --deepen=${a} failed: ${String(c)}`)}),s=await i()}return s||(await Te(n,["rev-parse","--is-shallow-repository"],r)).trim()==="true"&&(await oe(n,["fetch","--unshallow","origin",...o],r).catch(c=>{console.warn(`[git] review-base ${t.name}: --unshallow failed: ${String(c)}`)}),s=await i()),s&&await Gl(t,s,r),s}function oe(t,e,r){return new Promise((n,o)=>{let i=uy("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[];i.stderr.setEncoding("utf-8"),i.stderr.on("data",a=>s.push(a)),i.on("error",o),i.on("close",a=>{if(a===0)return n();o(new Error(`git ${e[0]} failed (exit ${a}):
812
+ ${s.join("").trim()||"(no stderr)"}`))})})}function Te(t,e,r){return new Promise((n,o)=>{let i=uy("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[],a=[];i.stdout.setEncoding("utf-8"),i.stderr.setEncoding("utf-8"),i.stdout.on("data",c=>s.push(c)),i.stderr.on("data",c=>a.push(c)),i.on("error",o),i.on("close",c=>{if(c===0)return n(s.join(""));o(new Error(`git ${e[0]} failed (exit ${c}):
813
+ ${a.join("").trim()||"(no stderr)"}`))})})}function xy(t,e){$s(t)&&Bl(t,{recursive:!0,force:!0}),Bo(_n(t),{recursive:!0}),aR(e,t,"dir")}async function Sy(t,e,r){await oe(t,["worktree","prune"]).catch(()=>{}),Bo(_n(r),{recursive:!0}),await oe(t,["worktree","add","--detach",r,`origin/${e}`])}async function uR(t,e,r){Bo(_n(r),{recursive:!0}),await oe(_n(r),["clone","--quiet","--no-checkout",t,r]),await oe(r,["checkout","--force","--detach",e])}async function Ey(t,e,r,n="worktree",o,i){return r.length===0?[]:py(e,async()=>{let s=[];for(let a of r){let c=lr(dy(i),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await fy(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 Te(c,["rev-parse","HEAD"])).trim(),p=lr(t,"code",a.name);n==="direct"?(xy(p,c),console.log(`[git] code: linked ${p} \u2192 ${c} @ ${u.slice(0,10)}`)):n==="clone"?(await uR(c,u,p),console.log(`[git] code: clone ${p} \u2190 ${c} @ ${u.slice(0,10)}`)):(await Sy(c,l,p),console.log(`[git] code: worktree ${p} \u2190 ${c} @ ${u.slice(0,10)}`)),s.push({name:a.name,workspacePath:p,cachePath:c,ref:l,baseSha:u})}return s})}async function Ty(t,e,r,n="worktree",o,i){if(!r||!r.cloneUrl)return null;let s=r;return py(e,async()=>{let a=lr(dy(i),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);try{await fy(a,s.cloneUrl,s.ref,void 0,o)}catch(u){throw new Error(`failed to materialize context repo (${s.cloneUrl}): `+(u instanceof Error?u.message:String(u)))}let c=lr(t,"context");n==="direct"?(xy(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await Sy(a,s.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await Te(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function Ry(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await oe(r,["add","-A",...n]).catch(()=>{});let o;try{o=await Te(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
814
+ `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=sR(lr(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var An,jn,Nn,by,Iy=x(()=>{"use strict";B();An=new Map;jn="CodePipe Agent",Nn="codepipe@codepartner.ee";by="refs/worktree/codepipe/review-base"});import{existsSync as dR,readFileSync as pR}from"node:fs";import{join as fR}from"node:path";import{parse as mR}from"yaml";function Cy(t){if(!t)return!1;let e=fR(t,Kl);if(!dR(e))return!1;try{let r=mR(pR(e,"utf-8"));if(!r||typeof r!="object")return!1;let n=r.steps;return!Array.isArray(n)||n.length===0?!1:n.some(o=>o!=null&&typeof o=="object"&&typeof o.run=="string"&&o.run.trim().length>0)}catch{return!1}}var Kl,Py=x(()=>{"use strict";Kl="knowledge/build.yaml"});import{readFileSync as hR}from"node:fs";import{join as gR}from"node:path";function Ay(t){let e=gR(t,Fo),r;try{r=hR(e,"utf-8")}catch{throw new ur(`BUILD produced no ${Fo} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new ur(`${Fo} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new ur(`${Fo} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new ur(`${Fo}: "ok" must be a boolean`);let i=o.ok,a=(Array.isArray(o.steps)?o.steps:[]).flatMap(u=>{if(!u||typeof u!="object")return[];let p=u,d=typeof p.name=="string"?p.name:null,m=typeof p.exitCode=="number"?p.exitCode:null;if(d===null||m===null)return[];let f={name:d,exitCode:m};return typeof p.durationMs=="number"&&(f.durationMs=p.durationMs),[f]}),c=typeof o.logTail=="string"?yR(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 yR(t){let e=Buffer.from(t,"utf-8");return e.length<=Hl?t:`\u2026 [${e.length-Hl} bytes elided] \u2026
815
+ `+e.subarray(e.length-Hl).toString("utf-8")}var Hl,ur,Fo,_y=x(()=>{"use strict";Hl=8*1024,ur=class extends Error{},Fo="meta/build-result.json"});var jy={};Fe(jy,{REVIEW_RESULT_PATH:()=>Mr,ReviewVerdictError:()=>Pt,markFindingScope:()=>ER,parseChangedRanges:()=>SR,readCodeReviewResult:()=>Wl});import{readFileSync as wR}from"node:fs";import{join as kR}from"node:path";function Wl(t){let e=kR(t,Mr),r;try{r=wR(e,"utf-8")}catch{throw new Pt(`code review produced no ${Mr} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(l){throw new Pt(`${Mr} is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}if(!n||typeof n!="object")throw new Pt(`${Mr} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new Pt(`${Mr}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?dr(o.remarks,bR):"";if(!i&&s.trim().length===0)throw new Pt(`${Mr}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?dr(o.summary,$R):"",c=xR(o.findings);return{approved:i,remarks:s,summary:a,...c.length>0?{findings:c}:{}}}function xR(t){if(!Array.isArray(t))return[];let e=[];for(let r of t.slice(0,vR)){if(!r||typeof r!="object")continue;let n=r,o=typeof n.title=="string"?dr(n.title,512).trim():"",i=typeof n.problem=="string"?dr(n.problem,vs).trim():"";if(!o||!i)continue;let s=typeof n.line=="number"&&Number.isInteger(n.line)&&n.line>0?n.line:void 0,a=n.severity==="blocker"||n.severity==="major"||n.severity==="minor"?n.severity:"other",c=typeof n.scenario=="string"&&n.scenario.trim()?dr(n.scenario,vs):void 0;a==="blocker"&&!c&&(console.warn(`[review] blocker "${o.slice(0,80)}" carries no scenario \u2014 demoted to major`),a="major"),e.push({severity:a,title:o,problem:i,...typeof n.repo=="string"&&n.repo?{repo:n.repo}:{},...typeof n.file=="string"&&n.file?{file:dr(n.file,1024)}:{},...s!==void 0?{line:s}:{},...c?{scenario:c}:{},...typeof n.suggestion=="string"&&n.suggestion.trim()?{suggestion:dr(n.suggestion,vs)}:{},...n.confidence==="high"||n.confidence==="medium"||n.confidence==="low"?{confidence:n.confidence}:{},...n.rule_source==="adr"||n.rule_source==="convention"||n.rule_source==="build"||n.rule_source==="judgment"?{ruleSource:n.rule_source}:{},...typeof n.out_of_diff_reason=="string"&&n.out_of_diff_reason.trim()?{outOfDiffReason:dr(n.out_of_diff_reason,vs)}:{}})}return e}function dr(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
816
+ \u2026 [${r.length-e} bytes elided]`}function SR(t){let e=new Map,r=null;for(let n of t.split(`
817
+ `)){if(n.startsWith("+++ ")){let o=n.slice(4).trim();r=o==="/dev/null"?null:o.replace(/^b\//,""),r&&!e.has(r)&&e.set(r,[]);continue}if(r&&n.startsWith("@@")){let o=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(n);if(!o)continue;let i=Number(o[1]),s=o[2]!==void 0?Number(o[2]):1,a=s===0?Math.max(1,i):i,c=s===0?Math.max(1,i):i+s-1;e.get(r).push([a,c])}}return e}function ER(t,e,r){for(let n of t.findings??[]){if(!n.file)continue;let o=n.repo??r;if(!o)continue;let i=e.get(o);if(!i)continue;let s=i.get(n.file);if(!s){n.scope="outside";continue}if(n.line===void 0||s.length===0){n.scope="diff";continue}let a=n.line;n.scope=s.some(([c,l])=>a>=c&&a<=l)?"diff":"file"}}var bR,$R,Pt,Mr,vs,vR,ql=x(()=>{"use strict";bR=16*1024,$R=4*1024,Pt=class extends Error{},Mr="meta/review-result.json";vs=8*1024,vR=50});import{readFileSync as TR,statSync as RR}from"node:fs";import{join as Ny}from"node:path";function NR(t){return t.startsWith("meta/")||jR.has(t)}function OR(t,e,r,n){return`[codepipe] artifact omitted from upload: ${t} was ${e} bytes, exceeds the SANDBOX upload budget (per-artifact ${r} / total ${n}). The delivered code (git) and the build/review verdict are unaffected \u2014 only this display/durability copy was dropped.`}function LR(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function Oy(t,e,r){let n=r?.maxBytes??IR,o=r?.totalBytes??CR,i=r?.maxCount??PR,s=e.map((f,g)=>{let k=null;try{k=RR(Ny(t,f)).size}catch{}return{path:f,index:g,size:k}}),a=[...s].sort((f,g)=>{let k=h=>NR(h.path)?0:1;return k(f)!==k(g)?k(f)-k(g):(f.size??0)-(g.size??0)}),c=a.slice(0,i),l=a.slice(i).sort((f,g)=>f.index-g.index).map(f=>f.path),u=new Array(s.length),p=[],d=0;for(let f of c){let g=null;if(f.size!==null&&f.size<=n&&d+f.size<=o)try{g=TR(Ny(t,f.path))}catch{}if(g!==null){d+=g.length,u[f.index]={path:f.path,contentBase64:g.toString("base64")};continue}let k=f.size===null?LR(f.path):OR(f.path,f.size,n,o),h=Buffer.from(k,"utf-8");d+=h.length,u[f.index]={path:f.path,contentBase64:h.toString("base64")},p.push({path:f.path,bytes:f.size??0})}let m=u.filter(f=>f!==void 0);if(l.length>0){let f=l.slice(0,_R),g=`# Artifacts omitted from upload
818
818
 
819
819
  ${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.
820
820
 
821
821
  `+f.map(k=>`- ${k}
822
822
  `).join("")+(l.length>f.length?`
823
823
  \u2026and ${l.length-f.length} more.
824
- `:"");m.push({path:ER,contentBase64:Buffer.from(y,"utf-8").toString("base64")})}return{artifacts:m,omitted:p,dropped:l}}var vR,xR,SR,ER,TR,RR,jy=x(()=>{"use strict";vR=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),xR=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),SR=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),ER="artifacts-omitted.md",TR=500,RR=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 AR,mkdtempSync as _R,readFileSync as jR,readdirSync as Oy,rmSync as Ny}from"node:fs";import{tmpdir as NR}from"node:os";import{join as vs,relative as OR}from"node:path";function Ly(t){let e=_R(vs(NR(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Ny(e,{recursive:!0,force:!0}),listFiles:()=>My(e,e),readFile:r=>jR(vs(e,r),"utf-8"),clean:()=>{for(let r of Oy(e))MR.has(r)||Ny(vs(e,r),{recursive:!0,force:!0})}}}function My(t,e){let r=[];for(let n of Oy(e)){let o=vs(e,n),i=AR(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&LR.has(n))continue;r.push(...My(t,o))}else r.push(OR(t,o))}return r}var LR,MR,Dy=x(()=>{"use strict";LR=new Set(["code","context","scratch",".claude"]),MR=new Set(["code","context"])});import{readFileSync as DR}from"node:fs";import{join as UR}from"node:path";function HR(t,e){let r=lo(t);return r?By(WR(r),e):""}function Uy(t,e,r={}){let n=r.perAncestorBudget??BR,o=r.totalBudget??FR,i=[...t.matchAll(ui)];if(i.length===0)return t;let s=i.map(l=>{let u=l[1],p=qR(e,u),d=p!=null?HR(p,n):"";return{key:u,text:d||`(\u0442\u0435\u043B\u043E \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u043E \u2014 \u0441\u043C. tasks/${u}/task.md)`}}),a=o,c=new Map;for(let l of s){let u=Math.max(0,Math.min(l.text.length,a));c.set(l.key,By(l.text,u)),a-=u}return t.replace(ui,(l,u)=>c.get(u)??"")}function WR(t){let e=t.split(`
825
- `),r=e.findIndex(a=>KR.test(a));if(r<0)return t;let n=e.slice(0,r).join(`
824
+ `:"");m.push({path:AR,contentBase64:Buffer.from(g,"utf-8").toString("base64")})}return{artifacts:m,omitted:p,dropped:l}}var IR,CR,PR,AR,_R,jR,Ly=x(()=>{"use strict";IR=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),CR=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),PR=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),AR="artifacts-omitted.md",_R=500,jR=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 MR,mkdtempSync as DR,readFileSync as UR,readdirSync as Dy,rmSync as My}from"node:fs";import{tmpdir as BR}from"node:os";import{join as xs,relative as FR}from"node:path";function Uy(t){let e=DR(xs(BR(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>My(e,{recursive:!0,force:!0}),listFiles:()=>By(e,e),readFile:r=>UR(xs(e,r),"utf-8"),clean:()=>{for(let r of Dy(e))KR.has(r)||My(xs(e,r),{recursive:!0,force:!0})}}}function By(t,e){let r=[];for(let n of Dy(e)){let o=xs(e,n),i=MR(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&GR.has(n))continue;r.push(...By(t,o))}else r.push(FR(t,o))}return r}var GR,KR,Fy=x(()=>{"use strict";GR=new Set(["code","context","scratch",".claude"]),KR=new Set(["code","context"])});import{readFileSync as HR}from"node:fs";import{join as WR}from"node:path";function XR(t,e){let r=lo(t);return r?Ky(JR(r),e):""}function Gy(t,e,r={}){let n=r.perAncestorBudget??qR,o=r.totalBudget??YR,i=[...t.matchAll(ui)];if(i.length===0)return t;let s=i.map(l=>{let u=l[1],p=ZR(e,u),d=p!=null?XR(p,n):"";return{key:u,text:d||`(\u0442\u0435\u043B\u043E \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u043E \u2014 \u0441\u043C. tasks/${u}/task.md)`}}),a=o,c=new Map;for(let l of s){let u=Math.max(0,Math.min(l.text.length,a));c.set(l.key,Ky(l.text,u)),a-=u}return t.replace(ui,(l,u)=>c.get(u)??"")}function JR(t){let e=t.split(`
825
+ `),r=e.findIndex(a=>VR.test(a));if(r<0)return t;let n=e.slice(0,r).join(`
826
826
  `).trim(),o=(e[r]??"").match(/^#+/)?.[0].length??1,i=e.length;for(let a=r+1;a<e.length;a++){let c=(e[a]??"").match(/^(#{1,6})\s/);if(c&&(c[1]?.length??0)<=o){i=a;break}}let s=e.slice(r,i).join(`
827
827
  `).trim();return[n,s].filter(Boolean).join(`
828
828
 
829
- `)}function By(t,e){return t.length<=e?t:t.slice(0,e).trimEnd()+GR}function qR(t,e){if(!t)return null;try{return DR(UR(t,"tasks",e,"task.md"),"utf-8")}catch{return null}}var BR,FR,GR,KR,Fy=x(()=>{"use strict";B();BR=1200,FR=3e3,GR=`
829
+ `)}function Ky(t,e){return t.length<=e?t:t.slice(0,e).trimEnd()+zR}function ZR(t,e){if(!t)return null;try{return HR(WR(t,"tasks",e,"task.md"),"utf-8")}catch{return null}}var qR,YR,zR,VR,Hy=x(()=>{"use strict";B();qR=1200,YR=3e3,zR=`
830
830
 
831
- \u2026(\u043E\u0431\u0440\u0435\u0437\u0430\u043D\u043E)`,KR=/^#{1,6}\s.*(приёмк|acceptance|критери)/i});import{existsSync as Ss,readFileSync as Gy,readdirSync as Hl}from"node:fs";import{join as Ht}from"node:path";import{parse as YR}from"yaml";function Es(t){if(!Ss(t))return[];let e=[];for(let r of Hl(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=Ht(t,r.name);r.isDirectory()?e.push(...Es(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function xs(t){try{return YR(Gy(t,"utf-8"))}catch{return null}}function Ky(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 Es(Ht(t,"model/derived/structure"))){let s=Ot(xs(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[...Es(Ht(t,"model/derived/correlates")),Ht(t,"model/derived/relates.yaml")]){if(!Ss(i))continue;let s=to(xs(i));if(s.ok)for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}let n=Ht(t,"model/facts/events");if(Ss(n))for(let i of Hl(n).sort()){if(!i.endsWith(".yaml"))continue;let s=Lt(xs(Ht(n,i)));if(!s.ok)continue;let a=s.value;e.events.set(a.taskKey,a);let c=Ee(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,Ee(l),"references",1)}for(let i of Es(Ht(t,"model/facts/identity"))){let s=ro(xs(i));if(s.ok)for(let a of s.value.entities)a.status==="orphaned"?e.orphanedEntities.add(a.entityId):e.keyByEntity.set(a.entityId,a.currentKey)}let o=Ht(t,"model/facts/annotations");if(Ss(o)){for(let i of Hl(o).sort())if(i.endsWith(".md"))try{let s=Gy(Ht(o,i),"utf-8"),a=/^---\n[\s\S]*?entityId:\s*(e_[0-9a-f]{8})[\s\S]*?\n---\n?([\s\S]*)$/.exec(s);a&&e.annotations.set(a[1],a[2].trim())}catch{}}return e.empty=e.nodes.size===0&&e.events.size===0,e}var Hy=x(()=>{"use strict";B()});function qy(t){return new Set((t.toLowerCase().match(/[a-zа-я0-9_]{4,}/g)??[]).filter(e=>!/^\d+$/.test(e)))}function eI(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 Yy(t){let{taskKey:e,title:r,text:n,model:o}=t,i=new Map,s=(m,f)=>{(i.get(m)??0)<f&&i.set(m,f)};(o.events.has(e)||o.adjacency.has(Ee(e)))&&s(Ee(e),Wy);for(let m of`${r}
832
- ${n}`.match(QR)??[]){if(m===e)continue;let f=Ee(m);(o.events.has(m)||o.adjacency.has(f))&&s(f,Wy)}let a=new Map;for(let m of o.nodes.keys()){let f=re(m);if(f?.level!=="code")continue;let y=f.path.slice(f.path.lastIndexOf("/")+1);for(let k of[f.path,y])a.has(k)||a.set(k,[]),a.get(k).push(m)}let c=`${r}
833
- ${n}`.split(/[\s,;()[\]{}<>"'!?]+/);for(let m of c){let f=m.replace(/^[`*_]+|[`*_.:]+$/g,"");if(!f||!f.includes("/")&&!f.includes("."))continue;let y=a.get(f)??[];y.length===1&&s(y[0],zR)}let l=new Map,u=(m,f)=>{let y=m.toLowerCase();!y||y.length<4||l.set(y,l.has(y)&&l.get(y)!==f?null:f)};for(let m of o.nodes.keys()){let f=re(m);if(!f)continue;let y=f.path.slice(f.path.lastIndexOf("/")+1);f.level==="code"&&u(y.replace(/\.[a-z0-9]+$/i,""),m),f.level==="component"&&u(y,m)}for(let m of`${r}
834
- ${n}`.match(/[A-Za-z][A-Za-z0-9_-]{3,}/g)??[]){let f=l.get(m.toLowerCase());f&&s(f,VR)}let p=qy(`${r}
835
- ${n}`),d=[];for(let[m,f]of o.events){if(m===e||!f.title)continue;let y=eI(p,qy(f.title));y>=JR&&d.push({key:Ee(m),score:y})}return d.sort((m,f)=>f.score-m.score||(m.key<f.key?-1:1)).slice(0,ZR).forEach(m=>s(m.key,XR)),i}var Wy,zR,VR,XR,JR,ZR,QR,zy=x(()=>{"use strict";B();Wy=1,zR=.9,VR=.7,XR=.5,JR=.15,ZR=3,QR=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g});function Vy(t,e,r={}){let n=r.cutoff??$r.activationCutoff,o=r.topK??$r.topKPerNode,i=r.nodeCap??$r.nodeCap,s=new Map;for(let[l,u]of e)s.set(l,{activation:u});let a=[...e].map(([l,u])=>({key:l,activation:u})).sort((l,u)=>u.activation-l.activation||(l.key<u.key?-1:1)),c=new Set;for(;a.length>0;){a.sort((p,d)=>d.activation-p.activation||(p.key<d.key?-1:1));let l=a.shift();if(c.has(l.key)||(s.get(l.key)?.activation??0)>l.activation)continue;if(c.add(l.key),c.size>i)break;let u=[...t.adjacency.get(l.key)??[]].sort((p,d)=>d.weight-p.weight||(p.to<d.to?-1:1)).slice(0,o);for(let p of u){let d=ma[p.kind]??.3,m=l.activation*d*Math.min(p.weight,1);if(m<n)continue;let f=s.get(p.to);(!f||f.activation<m)&&(s.set(p.to,{activation:m,via:{from:l.key,kind:p.kind}}),a.push({key:p.to,activation:m}))}}return s}var Xy=x(()=>{"use strict";B()});import{existsSync as ql,readFileSync as Jy,readdirSync as tI}from"node:fs";import{join as Is}from"node:path";function Wl(t){return Math.ceil(t.length/4)}function Ts(t,e){return[...t.entries()].filter(([r])=>e(r)).map(([r,n])=>({key:r,activation:n.activation,via:n.via})).sort((r,n)=>n.activation-r.activation||(r.key<n.key?-1:1))}function pr(t){let e=re(t);return e?(e.level==="task"||e.level==="adr",e.path):t}function Rs(t){if(!t.via)return"matched from the task text";let e=pr(t.via.from);switch(t.via.kind){case"touched_by":return t.via.from.startsWith("task::")?`touched by ${e}`:`touches ${e}`;case"correlates":return`co-changes with ${e}`;case"relates":return`related to ${e} (shared files)`;case"references":return`referenced by ${e}`;case"contains":return`contained in ${e}`;default:return`linked to ${e}`}}function iI(t,e){let r=/^ADR-(\d{3,4})$/.exec(e)?.[1];if(!r)return null;let n=Is(t,"adr");if(!ql(n))return null;let o=r.padStart(4,"0");for(let i of tI(n).sort())if(!(!i.startsWith(`${o}-`)||!i.endsWith(".md")))try{return{file:`adr/${i}`,content:Jy(Is(n,i),"utf-8").trim()}}catch{return null}return null}function Zy(t){let{taskKey:e,title:r,contextDir:n,model:o,activated:i}=t,s=t.budgetTokens??$r.budgetTokens,a=[],c=0,l=v=>{let b=Wl(v);return c+b>s?!1:(a.push(v),c+=b,!0)};l([`# Context pack \u2014 ${e}: ${r}`,"","Assembled deterministically from the project map (git history, past","tasks, decisions). No file bodies here \u2014 the paths are ENTRY POINTS","into the repositories; each line says why it made the list."].join(`
836
- `));let u=Ts(i,v=>v.startsWith("adr::")),p=!1;for(let v of u){let b=iI(n,pr(v.key));if(!b)continue;let R=`${p?"":`
831
+ \u2026(\u043E\u0431\u0440\u0435\u0437\u0430\u043D\u043E)`,VR=/^#{1,6}\s.*(приёмк|acceptance|критери)/i});import{existsSync as Es,readFileSync as Wy,readdirSync as Yl}from"node:fs";import{join as Ht}from"node:path";import{parse as QR}from"yaml";function Ts(t){if(!Es(t))return[];let e=[];for(let r of Yl(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=Ht(t,r.name);r.isDirectory()?e.push(...Ts(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function Ss(t){try{return QR(Wy(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=(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 Ts(Ht(t,"model/derived/structure"))){let s=Ot(Ss(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[...Ts(Ht(t,"model/derived/correlates")),Ht(t,"model/derived/relates.yaml")]){if(!Es(i))continue;let s=to(Ss(i));if(s.ok)for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}let n=Ht(t,"model/facts/events");if(Es(n))for(let i of Yl(n).sort()){if(!i.endsWith(".yaml"))continue;let s=Lt(Ss(Ht(n,i)));if(!s.ok)continue;let a=s.value;e.events.set(a.taskKey,a);let c=Se(a.taskKey);for(let l of a.files)r(c,l.key,"touched_by",1);for(let l of a.links?.adr??[])r(c,`adr::${l}`,"references",1);for(let l of a.links?.tasks??[])r(c,Se(l),"references",1)}for(let i of Ts(Ht(t,"model/facts/identity"))){let s=ro(Ss(i));if(s.ok)for(let a of s.value.entities)a.status==="orphaned"?e.orphanedEntities.add(a.entityId):e.keyByEntity.set(a.entityId,a.currentKey)}let o=Ht(t,"model/facts/annotations");if(Es(o)){for(let i of Yl(o).sort())if(i.endsWith(".md"))try{let s=Wy(Ht(o,i),"utf-8"),a=/^---\n[\s\S]*?entityId:\s*(e_[0-9a-f]{8})[\s\S]*?\n---\n?([\s\S]*)$/.exec(s);a&&e.annotations.set(a[1],a[2].trim())}catch{}}return e.empty=e.nodes.size===0&&e.events.size===0,e}var Yy=x(()=>{"use strict";B()});function Vy(t){return new Set((t.toLowerCase().match(/[a-zа-я0-9_]{4,}/g)??[]).filter(e=>!/^\d+$/.test(e)))}function sI(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 Xy(t){let{taskKey:e,title:r,text:n,model:o}=t,i=new Map,s=(m,f)=>{(i.get(m)??0)<f&&i.set(m,f)};(o.events.has(e)||o.adjacency.has(Se(e)))&&s(Se(e),zy);for(let m of`${r}
832
+ ${n}`.match(iI)??[]){if(m===e)continue;let f=Se(m);(o.events.has(m)||o.adjacency.has(f))&&s(f,zy)}let a=new Map;for(let m of o.nodes.keys()){let f=re(m);if(f?.level!=="code")continue;let g=f.path.slice(f.path.lastIndexOf("/")+1);for(let k of[f.path,g])a.has(k)||a.set(k,[]),a.get(k).push(m)}let c=`${r}
833
+ ${n}`.split(/[\s,;()[\]{}<>"'!?]+/);for(let m of c){let f=m.replace(/^[`*_]+|[`*_.:]+$/g,"");if(!f||!f.includes("/")&&!f.includes("."))continue;let g=a.get(f)??[];g.length===1&&s(g[0],eI)}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}
834
+ ${n}`.match(/[A-Za-z][A-Za-z0-9_-]{3,}/g)??[]){let f=l.get(m.toLowerCase());f&&s(f,tI)}let p=Vy(`${r}
835
+ ${n}`),d=[];for(let[m,f]of o.events){if(m===e||!f.title)continue;let g=sI(p,Vy(f.title));g>=nI&&d.push({key:Se(m),score:g})}return d.sort((m,f)=>f.score-m.score||(m.key<f.key?-1:1)).slice(0,oI).forEach(m=>s(m.key,rI)),i}var zy,eI,tI,rI,nI,oI,iI,Jy=x(()=>{"use strict";B();zy=1,eI=.9,tI=.7,rI=.5,nI=.15,oI=3,iI=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g});function Zy(t,e,r={}){let n=r.cutoff??$r.activationCutoff,o=r.topK??$r.topKPerNode,i=r.nodeCap??$r.nodeCap,s=new Map;for(let[l,u]of e)s.set(l,{activation:u});let a=[...e].map(([l,u])=>({key:l,activation:u})).sort((l,u)=>u.activation-l.activation||(l.key<u.key?-1:1)),c=new Set;for(;a.length>0;){a.sort((p,d)=>d.activation-p.activation||(p.key<d.key?-1:1));let l=a.shift();if(c.has(l.key)||(s.get(l.key)?.activation??0)>l.activation)continue;if(c.add(l.key),c.size>i)break;let u=[...t.adjacency.get(l.key)??[]].sort((p,d)=>d.weight-p.weight||(p.to<d.to?-1:1)).slice(0,o);for(let p of u){let d=ha[p.kind]??.3,m=l.activation*d*Math.min(p.weight,1);if(m<n)continue;let f=s.get(p.to);(!f||f.activation<m)&&(s.set(p.to,{activation:m,via:{from:l.key,kind:p.kind}}),a.push({key:p.to,activation:m}))}}return s}var Qy=x(()=>{"use strict";B()});import{existsSync as Vl,readFileSync as ew,readdirSync as aI}from"node:fs";import{join as Cs}from"node:path";function zl(t){return Math.ceil(t.length/4)}function Rs(t,e){return[...t.entries()].filter(([r])=>e(r)).map(([r,n])=>({key:r,activation:n.activation,via:n.via})).sort((r,n)=>n.activation-r.activation||(r.key<n.key?-1:1))}function pr(t){let e=re(t);return e?(e.level==="task"||e.level==="adr",e.path):t}function Is(t){if(!t.via)return"matched from the task text";let e=pr(t.via.from);switch(t.via.kind){case"touched_by":return t.via.from.startsWith("task::")?`touched by ${e}`:`touches ${e}`;case"correlates":return`co-changes with ${e}`;case"relates":return`related to ${e} (shared files)`;case"references":return`referenced by ${e}`;case"contains":return`contained in ${e}`;default:return`linked to ${e}`}}function dI(t,e){let r=/^ADR-(\d{3,4})$/.exec(e)?.[1];if(!r)return null;let n=Cs(t,"adr");if(!Vl(n))return null;let o=r.padStart(4,"0");for(let i of aI(n).sort())if(!(!i.startsWith(`${o}-`)||!i.endsWith(".md")))try{return{file:`adr/${i}`,content:ew(Cs(n,i),"utf-8").trim()}}catch{return null}return null}function tw(t){let{taskKey:e,title:r,contextDir:n,model:o,activated:i}=t,s=t.budgetTokens??$r.budgetTokens,a=[],c=0,l=v=>{let b=zl(v);return c+b>s?!1:(a.push(v),c+=b,!0)};l([`# Context pack \u2014 ${e}: ${r}`,"","Assembled deterministically from the project map (git history, past","tasks, decisions). No file bodies here \u2014 the paths are ENTRY POINTS","into the repositories; each line says why it made the list."].join(`
836
+ `));let u=Rs(i,v=>v.startsWith("adr::")),p=!1;for(let v of u){let b=dI(n,pr(v.key));if(!b)continue;let I=`${p?"":`
837
837
  ## Governing decisions
838
838
  `}
839
- ### ${pr(v.key)} (\`${b.file}\`, ${Rs(v)})
839
+ ### ${pr(v.key)} (\`${b.file}\`, ${Is(v)})
840
840
 
841
841
  ${b.content}
842
- `;if(!l(R))break;p=!0}let d=Ts(i,v=>o.nodes.get(v)?.entityId!==void 0).filter(v=>o.annotations.has(o.nodes.get(v.key).entityId)),m=t.staleKeys??new Set,f=!1;for(let v of d){let b=o.nodes.get(v.key).entityId,R=o.annotations.get(b),j=m.has(v.key)?" \u2014 \u26A0 the file changed since the map was built":o.orphanedEntities.has(b)?" \u2014 \u26A0 the file no longer exists":"",G=`${f?"":`
842
+ `;if(!l(I))break;p=!0}let d=Rs(i,v=>o.nodes.get(v)?.entityId!==void 0).filter(v=>o.annotations.has(o.nodes.get(v.key).entityId)),m=t.staleKeys??new Set,f=!1;for(let v of d){let b=o.nodes.get(v.key).entityId,I=o.annotations.get(b),j=m.has(v.key)?" \u2014 \u26A0 the file changed since the map was built":o.orphanedEntities.has(b)?" \u2014 \u26A0 the file no longer exists":"",K=`${f?"":`
843
843
  ## Why the code is shaped this way (intent notes)
844
844
  `}
845
845
  ### \`${pr(v.key)}\`${j}
846
846
 
847
- ${R}
848
- `;if(!l(G))break;f=!0}let y=Ee(e),k=Ts(i,v=>v.startsWith("task::")&&v!==y).slice(0,rI),h=!1;for(let v of k){let b=o.events.get(pr(v.key));if(!b)continue;let R=[...b.files].filter(g=>!m.has(g.key)&&(!g.entityId||!o.orphanedEntities.has(g.entityId))).sort((g,U)=>(U.churn??0)-(g.churn??0)||(g.key<U.key?-1:1)).slice(0,3).map(g=>`\`${pr(g.key)}\``).join(", "),j="",G=b.links?.solution??[`tasks/${b.taskKey}/PLAN.md`,`tasks/${b.taskKey}/SOLUTION.md`].find(g=>ql(Is(n,g)))??`tasks/${b.taskKey}/PLAN.md`,X=Is(n,G);if(ql(X))try{j=`
849
- > ${Jy(X,"utf-8").trim().slice(0,oI).replace(/\n+/g," ").trim()}\u2026
850
- > _(full text: \`${G}\`)_`}catch{}let A=`${h?"":`
847
+ ${I}
848
+ `;if(!l(K))break;f=!0}let g=Se(e),k=Rs(i,v=>v.startsWith("task::")&&v!==g).slice(0,cI),h=!1;for(let v of k){let b=o.events.get(pr(v.key));if(!b)continue;let I=[...b.files].filter(y=>!m.has(y.key)&&(!y.entityId||!o.orphanedEntities.has(y.entityId))).sort((y,U)=>(U.churn??0)-(y.churn??0)||(y.key<U.key?-1:1)).slice(0,3).map(y=>`\`${pr(y.key)}\``).join(", "),j="",K=b.links?.solution??[`tasks/${b.taskKey}/PLAN.md`,`tasks/${b.taskKey}/SOLUTION.md`].find(y=>Vl(Cs(n,y)))??`tasks/${b.taskKey}/PLAN.md`,z=Cs(n,K);if(Vl(z))try{j=`
849
+ > ${ew(z,"utf-8").trim().slice(0,uI).replace(/\n+/g," ").trim()}\u2026
850
+ > _(full text: \`${K}\`)_`}catch{}let A=`${h?"":`
851
851
  ## Related past tasks
852
852
  `}
853
- - **${b.taskKey}**${b.title?` \u2014 ${b.title}`:""}${b.date?` (${b.date})`:""}, ${Rs(v)}. Files: ${R||"\u2014"}.${j}`;if(!l(A))break;h=!0}let w=v=>{if(m.has(v.key))return!1;let b=o.nodes.get(v.key)?.entityId;return!b||!o.orphanedEntities.has(b)},$=Ts(i,v=>v.startsWith("code:")),S=$.filter(w).slice(0,nI);if(S.length>0){let v=["","## Files likely involved",""];for(let b of S){let R=`- \`${pr(b.key)}\` \u2014 ${Rs(b)}`;if(c+Wl(v.join(`
854
- `))+Wl(R)>s)break;v.push(R)}v.length>3&&l(v.join(`
855
- `))}let T=$.filter(v=>!w(v)).slice(0,10);if(T.length>0){let v=["","## Possibly stale (verify before trusting)","","These entries reference files that changed after the map was built or","no longer exist at their recorded location. Useful as history, wrong","as current fact.","",...T.map(b=>`- \`${pr(b.key)}\` \u2014 ${Rs(b)}${m.has(b.key)?" (changed since the map was built)":" (file gone)"}`)];l(v.join(`
853
+ - **${b.taskKey}**${b.title?` \u2014 ${b.title}`:""}${b.date?` (${b.date})`:""}, ${Is(v)}. Files: ${I||"\u2014"}.${j}`;if(!l(A))break;h=!0}let w=v=>{if(m.has(v.key))return!1;let b=o.nodes.get(v.key)?.entityId;return!b||!o.orphanedEntities.has(b)},$=Rs(i,v=>v.startsWith("code:")),S=$.filter(w).slice(0,lI);if(S.length>0){let v=["","## Files likely involved",""];for(let b of S){let I=`- \`${pr(b.key)}\` \u2014 ${Is(b)}`;if(c+zl(v.join(`
854
+ `))+zl(I)>s)break;v.push(I)}v.length>3&&l(v.join(`
855
+ `))}let R=$.filter(v=>!w(v)).slice(0,10);if(R.length>0){let v=["","## Possibly stale (verify before trusting)","","These entries reference files that changed after the map was built or","no longer exist at their recorded location. Useful as history, wrong","as current fact.","",...R.map(b=>`- \`${pr(b.key)}\` \u2014 ${Is(b)}${m.has(b.key)?" (changed since the map was built)":" (file gone)"}`)];l(v.join(`
856
856
  `))}return a.length<=1?null:a.join(`
857
857
  `)+`
858
- `}var rI,nI,oI,Qy=x(()=>{"use strict";B();rI=5,nI=300,oI=400});var nw={};Fe(nw,{assembleContextPack:()=>lI});import{createHash as sI}from"node:crypto";import{existsSync as ew,readFileSync as tw}from"node:fs";import{join as rw}from"node:path";function aI(t){return sI("sha1").update(`blob ${t.length}\0`).update(t).digest("hex")}function cI(t,e,r){let n=new Set;for(let o of e.keys()){let i=re(o);if(i?.level!=="code")continue;let s=t.nodes.get(o);if(!s?.contentHash)continue;let a=r.get(i.repo);if(!a)continue;let c=rw(a,i.path);try{if(!ew(c)){n.add(o);continue}aI(tw(c)).startsWith(s.contentHash)||n.add(o)}catch{}}return n}function lI(t){let e=Ky(t.contextDir);if(e.empty)return null;let r="",n=rw(t.contextDir,`tasks/${t.taskKey}/task.md`);if(ew(n))try{r=tw(n,"utf-8")}catch{r=""}let o=Yy({taskKey:t.taskKey,title:t.title,text:r,model:e});if(o.size===0)return null;let i=Vy(e,o),s=t.repoDirs?cI(e,i,t.repoDirs):new Set;return Zy({taskKey:t.taskKey,title:t.title,contextDir:t.contextDir,model:e,activated:i,staleKeys:s,...t.budgetTokens!==void 0?{budgetTokens:t.budgetTokens}:{}})}var ow=x(()=>{"use strict";B();Hy();zy();Xy();Qy()});var cw={};Fe(cw,{SKILLS_DIR:()=>Yl,loadSkills:()=>kI,materializeSkills:()=>bI,renderSkillsBlock:()=>$I,resolveBundledSkillsDir:()=>aw});import{cpSync as uI,existsSync as iw,mkdirSync as dI,readFileSync as pI,readdirSync as sw}from"node:fs";import{dirname as fI,join as fr}from"node:path";import{fileURLToPath as mI}from"node:url";import{parse as hI}from"yaml";function aw(t){for(let e of[t,fr(t,"skills")])try{if(sw(e,{withFileTypes:!0}).some(n=>n.isDirectory()&&iw(fr(e,n.name,"SKILL.md"))))return e}catch{}return t}function yI(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
858
+ `}var cI,lI,uI,rw=x(()=>{"use strict";B();cI=5,lI=300,uI=400});var sw={};Fe(sw,{assembleContextPack:()=>hI});import{createHash as pI}from"node:crypto";import{existsSync as nw,readFileSync as ow}from"node:fs";import{join as iw}from"node:path";function fI(t){return pI("sha1").update(`blob ${t.length}\0`).update(t).digest("hex")}function mI(t,e,r){let n=new Set;for(let o of e.keys()){let i=re(o);if(i?.level!=="code")continue;let s=t.nodes.get(o);if(!s?.contentHash)continue;let a=r.get(i.repo);if(!a)continue;let c=iw(a,i.path);try{if(!nw(c)){n.add(o);continue}fI(ow(c)).startsWith(s.contentHash)||n.add(o)}catch{}}return n}function hI(t){let e=qy(t.contextDir);if(e.empty)return null;let r="",n=iw(t.contextDir,`tasks/${t.taskKey}/task.md`);if(nw(n))try{r=ow(n,"utf-8")}catch{r=""}let o=Xy({taskKey:t.taskKey,title:t.title,text:r,model:e});if(o.size===0)return null;let i=Zy(e,o),s=t.repoDirs?mI(e,i,t.repoDirs):new Set;return tw({taskKey:t.taskKey,title:t.title,contextDir:t.contextDir,model:e,activated:i,staleKeys:s,...t.budgetTokens!==void 0?{budgetTokens:t.budgetTokens}:{}})}var aw=x(()=>{"use strict";B();Yy();Jy();Qy();rw()});var dw={};Fe(dw,{SKILLS_DIR:()=>Xl,loadSkills:()=>EI,materializeSkills:()=>TI,renderSkillsBlock:()=>RI,resolveBundledSkillsDir:()=>uw});import{cpSync as gI,existsSync as cw,mkdirSync as yI,readFileSync as wI,readdirSync as lw}from"node:fs";import{dirname as kI,join as fr}from"node:path";import{fileURLToPath as bI}from"node:url";import{parse as $I}from"yaml";function uw(t){for(let e of[t,fr(t,"skills")])try{if(lw(e,{withFileTypes:!0}).some(n=>n.isDirectory()&&cw(fr(e,n.name,"SKILL.md"))))return e}catch{}return t}function xI(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
859
859
  ---`,3);return r===-1?null:{yaml:e.slice(e.indexOf(`
860
860
  `,3)+1,r),body:e.slice(e.indexOf(`
861
- `,r+1)+1)}}function wI(t,e,r){let n=[],o=[];if(!iw(t))return{skills:n,errors:o};let i;try{i=sw(t,{withFileTypes:!0}).filter(s=>s.isDirectory()).map(s=>s.name).sort()}catch(s){return{skills:n,errors:[{source:r,error:`cannot read: ${String(s)}`}]}}for(let s of i){let a=fr(t,s),c=`${r}/${s}`,l;try{l=pI(fr(a,"SKILL.md"),"utf-8")}catch{o.push({source:c,error:"no SKILL.md in the directory"});continue}let u=yI(l);if(!u){o.push({source:c,error:"SKILL.md has no frontmatter block"});continue}let p;try{p=hI(u.yaml)}catch(m){o.push({source:c,error:`frontmatter is not valid YAML: ${String(m)}`});continue}let d=Wa({name:s,frontmatter:p,body:u.body});d.ok?n.push({...d.skill,dir:a,origin:e}):o.push({source:c,error:d.error})}return{skills:n,errors:o}}function kI(t){let e=[],r=(s,a,c)=>{let l=wI(s,a,c);return e.push(...l.errors),l.skills},n=t.sources.bundled?r(gI,"bundled","bundled"):[],o=t.sources.context&&t.contextDir?r(fr(t.contextDir,"skills"),"context","skills"):[],i=t.sources.repo?t.repoDirs.flatMap(s=>r(fr(s,".claude","skills"),"repo","repo")):[];return{skills:qa(n,o,i),errors:e}}function bI(t,e){if(e.length===0)return[];let r=fr(t,Yl);dI(r,{recursive:!0});let n=[];for(let o of e)uI(o.dir,fr(r,o.name),{recursive:!0}),n.push(`${Yl}/${o.name}`);return n}function $I(t,e=[]){let r=new Set(t.map(s=>s.name)),n=e.filter(s=>!r.has(s));if(t.length===0&&n.length===0)return"";let o=[];t.length>0&&o.push("## Skills available to you","",...t.map(s=>`- **${s.name}** \u2014 ${s.description}`),"","Only these lines are in context; a skill's steps load when you invoke it.","When one covers what you are about to do, use it: it was written down","because the obvious approach was wrong or costly.","");let i=e.filter(s=>r.has(s));return i.length>0&&o.push("**The approved plan requires this task to follow: "+i.map(s=>`\`${s}\``).join(", ")+".**","This is not a suggestion \u2014 a reviewer approved it as a requirement.",""),n.length>0&&o.push("**The plan prescribes "+n.map(s=>`\`${s}\``).join(", ")+", which is not available here.**","Proceed without it and say so in your result \u2014 do not invent the procedure.",""),o.join(`
862
- `)}var Yl,gI,lw=x(()=>{"use strict";B();Yl=".claude/skills";gI=aw(fI(mI(import.meta.url)))});var fw={};Fe(fw,{seedMarketplaces:()=>AI});import{spawn as vI}from"node:child_process";import{cpSync as xI,existsSync as uw,mkdirSync as dw,rmSync as zl,symlinkSync as SI,writeFileSync as EI}from"node:fs";import{homedir as TI}from"node:os";import{join as mr}from"node:path";function pw(){return mr(TI(),".codepipe-sandbox","plugins")}function CI(t){return mr(pw(),"src",`${t.name}@${t.sha||"head"}`)}function Go(t,e){return new Promise((r,n)=>{let o=vI("git",t,{cwd:e,stdio:["ignore","ignore","pipe"],env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"}}),i=[];o.stderr.setEncoding("utf-8"),o.stderr.on("data",s=>i.push(s)),o.on("error",n),o.on("close",s=>{if(s===0)return r();n(new Error(`git ${t[0]} failed (exit ${s}): ${i.join("").trim().slice(0,400)}`))})})}async function PI(t){let e=CI(t);if(uw(mr(e,".claude-plugin","marketplace.json")))return e;zl(e,{recursive:!0,force:!0}),dw(e,{recursive:!0});let r=`https://github.com/${t.repo}.git`;if(t.sha?(await Go(["init","--quiet"],e),await Go(["remote","add","origin",r],e),await Go(["fetch","--quiet","--depth","1","origin",t.sha],e),await Go(["checkout","--quiet","FETCH_HEAD"],e)):await Go(["clone","--quiet","--depth","1",r,e]),!uw(mr(e,".claude-plugin","marketplace.json")))throw zl(e,{recursive:!0,force:!0}),new Error("no .claude-plugin/marketplace.json \u2014 this repository is not a marketplace");return e}async function AI(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 PI(a)),r.push(a)}catch(c){e.push({repo:a.repo,error:c instanceof Error?c.message:String(c)})}if(r.length===0)return{dir:null,ready:r,errors:e};let o=mr(pw(),"seed",r.map(a=>`${a.name}@${a.sha||"head"}`).sort().join("_")),i=mr(o,RI);dw(i,{recursive:!0});let s={};for(let a of r){let c=mr(i,a.name);zl(c,{recursive:!0,force:!0}),_I(n.get(a.name),c),s[a.name]={source:{source:"github",repo:a.repo},installLocation:c,...a.sha?{commit:a.sha}:{}}}return EI(mr(o,II),`${JSON.stringify(s,null,2)}
863
- `),{dir:o,ready:r,errors:e}}function _I(t,e){try{SI(t,e,"dir")}catch{xI(t,e,{recursive:!0,filter:r=>!/(^|\/)\.git(\/|$)/.test(r)})}}var RI,II,mw=x(()=>{"use strict";RI="marketplaces",II="known_marketplaces.json"});var ww={};Fe(ww,{loadRoles:()=>BI,resolveBundledRolesDir:()=>yw});import{existsSync as jI,readFileSync as NI,readdirSync as gw}from"node:fs";import{dirname as OI,join as Vl}from"node:path";import{fileURLToPath as LI}from"node:url";import{parse as MI}from"yaml";function yw(t){for(let e of[t,Vl(t,"roles")])try{if(gw(e).some(r=>r.endsWith(".md")))return e}catch{}return t}function UI(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
861
+ `,r+1)+1)}}function SI(t,e,r){let n=[],o=[];if(!cw(t))return{skills:n,errors:o};let i;try{i=lw(t,{withFileTypes:!0}).filter(s=>s.isDirectory()).map(s=>s.name).sort()}catch(s){return{skills:n,errors:[{source:r,error:`cannot read: ${String(s)}`}]}}for(let s of i){let a=fr(t,s),c=`${r}/${s}`,l;try{l=wI(fr(a,"SKILL.md"),"utf-8")}catch{o.push({source:c,error:"no SKILL.md in the directory"});continue}let u=xI(l);if(!u){o.push({source:c,error:"SKILL.md has no frontmatter block"});continue}let p;try{p=$I(u.yaml)}catch(m){o.push({source:c,error:`frontmatter is not valid YAML: ${String(m)}`});continue}let d=qa({name:s,frontmatter:p,body:u.body});d.ok?n.push({...d.skill,dir:a,origin:e}):o.push({source:c,error:d.error})}return{skills:n,errors:o}}function EI(t){let e=[],r=(s,a,c)=>{let l=SI(s,a,c);return e.push(...l.errors),l.skills},n=t.sources.bundled?r(vI,"bundled","bundled"):[],o=t.sources.context&&t.contextDir?r(fr(t.contextDir,"skills"),"context","skills"):[],i=t.sources.repo?t.repoDirs.flatMap(s=>r(fr(s,".claude","skills"),"repo","repo")):[];return{skills:Ya(n,o,i),errors:e}}function TI(t,e){if(e.length===0)return[];let r=fr(t,Xl);yI(r,{recursive:!0});let n=[];for(let o of e)gI(o.dir,fr(r,o.name),{recursive:!0}),n.push(`${Xl}/${o.name}`);return n}function RI(t,e=[]){let r=new Set(t.map(s=>s.name)),n=e.filter(s=>!r.has(s));if(t.length===0&&n.length===0)return"";let o=[];t.length>0&&o.push("## Skills available to you","",...t.map(s=>`- **${s.name}** \u2014 ${s.description}`),"","Only these lines are in context; a skill's steps load when you invoke it.","When one covers what you are about to do, use it: it was written down","because the obvious approach was wrong or costly.","");let i=e.filter(s=>r.has(s));return i.length>0&&o.push("**The approved plan requires this task to follow: "+i.map(s=>`\`${s}\``).join(", ")+".**","This is not a suggestion \u2014 a reviewer approved it as a requirement.",""),n.length>0&&o.push("**The plan prescribes "+n.map(s=>`\`${s}\``).join(", ")+", which is not available here.**","Proceed without it and say so in your result \u2014 do not invent the procedure.",""),o.join(`
862
+ `)}var Xl,vI,pw=x(()=>{"use strict";B();Xl=".claude/skills";vI=uw(kI(bI(import.meta.url)))});var gw={};Fe(gw,{seedMarketplaces:()=>MI});import{spawn as II}from"node:child_process";import{cpSync as CI,existsSync as fw,mkdirSync as mw,rmSync as Jl,symlinkSync as PI,writeFileSync as AI}from"node:fs";import{homedir as _I}from"node:os";import{join as mr}from"node:path";function hw(){return mr(_I(),".codepipe-sandbox","plugins")}function OI(t){return mr(hw(),"src",`${t.name}@${t.sha||"head"}`)}function Go(t,e){return new Promise((r,n)=>{let o=II("git",t,{cwd:e,stdio:["ignore","ignore","pipe"],env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"}}),i=[];o.stderr.setEncoding("utf-8"),o.stderr.on("data",s=>i.push(s)),o.on("error",n),o.on("close",s=>{if(s===0)return r();n(new Error(`git ${t[0]} failed (exit ${s}): ${i.join("").trim().slice(0,400)}`))})})}async function LI(t){let e=OI(t);if(fw(mr(e,".claude-plugin","marketplace.json")))return e;Jl(e,{recursive:!0,force:!0}),mw(e,{recursive:!0});let r=`https://github.com/${t.repo}.git`;if(t.sha?(await Go(["init","--quiet"],e),await Go(["remote","add","origin",r],e),await Go(["fetch","--quiet","--depth","1","origin",t.sha],e),await Go(["checkout","--quiet","FETCH_HEAD"],e)):await Go(["clone","--quiet","--depth","1",r,e]),!fw(mr(e,".claude-plugin","marketplace.json")))throw Jl(e,{recursive:!0,force:!0}),new Error("no .claude-plugin/marketplace.json \u2014 this repository is not a marketplace");return e}async function MI(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 LI(a)),r.push(a)}catch(c){e.push({repo:a.repo,error:c instanceof Error?c.message:String(c)})}if(r.length===0)return{dir:null,ready:r,errors:e};let o=mr(hw(),"seed",r.map(a=>`${a.name}@${a.sha||"head"}`).sort().join("_")),i=mr(o,jI);mw(i,{recursive:!0});let s={};for(let a of r){let c=mr(i,a.name);Jl(c,{recursive:!0,force:!0}),DI(n.get(a.name),c),s[a.name]={source:{source:"github",repo:a.repo},installLocation:c,...a.sha?{commit:a.sha}:{}}}return AI(mr(o,NI),`${JSON.stringify(s,null,2)}
863
+ `),{dir:o,ready:r,errors:e}}function DI(t,e){try{PI(t,e,"dir")}catch{CI(t,e,{recursive:!0,filter:r=>!/(^|\/)\.git(\/|$)/.test(r)})}}var jI,NI,yw=x(()=>{"use strict";jI="marketplaces",NI="known_marketplaces.json"});var $w={};Fe($w,{loadRoles:()=>qI,resolveBundledRolesDir:()=>bw});import{existsSync as UI,readFileSync as BI,readdirSync as kw}from"node:fs";import{dirname as FI,join as Zl}from"node:path";import{fileURLToPath as GI}from"node:url";import{parse as KI}from"yaml";function bw(t){for(let e of[t,Zl(t,"roles")])try{if(kw(e).some(r=>r.endsWith(".md")))return e}catch{}return t}function WI(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
864
864
  ---`,3);if(r===-1)return null;let n=e.slice(e.indexOf(`
865
865
  `,3)+1,r),o=e.indexOf(`
866
- `,r+1);return{yaml:n,body:o===-1?"":e.slice(o+1)}}function hw(t,e,r){let n=[],o=[];if(!jI(t))return{roles:n,errors:o};let i;try{i=gw(t).sort()}catch(s){return{roles:n,errors:[{file:r,error:`cannot read: ${String(s)}`}]}}for(let s of i){if(!s.endsWith(".md"))continue;let a=`${r}/${s}`,c;try{c=NI(Vl(t,s),"utf-8")}catch(d){o.push({file:a,error:`cannot read: ${String(d)}`});continue}let l=UI(c);if(!l){o.push({file:a,error:"missing frontmatter block (--- \u2026 ---) at the top of the file"});continue}let u;try{u=MI(l.yaml)}catch(d){o.push({file:a,error:`frontmatter is not valid YAML: ${String(d)}`});continue}let p=Ua({name:s.slice(0,-3),frontmatter:u,body:l.body,origin:e});p.ok?n.push(p.role):o.push({file:a,error:p.error})}return{roles:n,errors:o}}function BI(t){let e=hw(DI,"bundled","bundled"),r=t?hw(Vl(t,"roles"),"project","roles"):{roles:[],errors:[]};return{roles:Ba(e.roles,r.roles),errors:[...e.errors,...r.errors]}}var DI,kw=x(()=>{"use strict";B();DI=yw(OI(LI(import.meta.url)))});var bw={};Fe(bw,{ROLE_AGENTS_DIR:()=>Jl,materializeRoleAgents:()=>HI,renderRolesBlock:()=>WI});import{mkdirSync as FI,writeFileSync as GI}from"node:fs";import{join as Xl}from"node:path";function KI(t,e){let r=["---",`name: ${t.name}`,`description: ${t.description}`,...t.model?[`model: ${t.model}`]:[],"---",""].join(`
867
- `),n=t.refs.length>0&&e?["","## Read these first","",...t.refs.map(o=>`- \`${Xl(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(`
866
+ `,r+1);return{yaml:n,body:o===-1?"":e.slice(o+1)}}function ww(t,e,r){let n=[],o=[];if(!UI(t))return{roles:n,errors:o};let i;try{i=kw(t).sort()}catch(s){return{roles:n,errors:[{file:r,error:`cannot read: ${String(s)}`}]}}for(let s of i){if(!s.endsWith(".md"))continue;let a=`${r}/${s}`,c;try{c=BI(Zl(t,s),"utf-8")}catch(d){o.push({file:a,error:`cannot read: ${String(d)}`});continue}let l=WI(c);if(!l){o.push({file:a,error:"missing frontmatter block (--- \u2026 ---) at the top of the file"});continue}let u;try{u=KI(l.yaml)}catch(d){o.push({file:a,error:`frontmatter is not valid YAML: ${String(d)}`});continue}let p=Ba({name:s.slice(0,-3),frontmatter:u,body:l.body,origin:e});p.ok?n.push(p.role):o.push({file:a,error:p.error})}return{roles:n,errors:o}}function qI(t){let e=ww(HI,"bundled","bundled"),r=t?ww(Zl(t,"roles"),"project","roles"):{roles:[],errors:[]};return{roles:Fa(e.roles,r.roles),errors:[...e.errors,...r.errors]}}var HI,vw=x(()=>{"use strict";B();HI=bw(FI(GI(import.meta.url)))});var xw={};Fe(xw,{ROLE_AGENTS_DIR:()=>eu,materializeRoleAgents:()=>XI,renderRolesBlock:()=>JI});import{mkdirSync as YI,writeFileSync as zI}from"node:fs";import{join as Ql}from"node:path";function VI(t,e){let r=["---",`name: ${t.name}`,`description: ${t.description}`,...t.model?[`model: ${t.model}`]:[],"---",""].join(`
867
+ `),n=t.refs.length>0&&e?["","## Read these first","",...t.refs.map(o=>`- \`${Ql(e,o)}\``),"","They are this role's curated context. If one is missing, say so in a line and continue \u2014","its absence is not an error.",""].join(`
868
868
  `):"";return`${r}${t.body}
869
- ${n}`}function HI(t,e,r,n){let o=Fa(e,r);if(o.length===0)return{roles:[],files:[]};let i=Xl(t,Jl);FI(i,{recursive:!0});let s=[];for(let a of o)GI(Xl(i,`${a.name}.md`),KI(a,n)),s.push(`${Jl}/${a.name}.md`);return{roles:o,files:s}}function WI(t,e){return t.roles.length===0?"":["## The panel \u2014 run these critics first","","This project reviews through a panel of roles. Each is available to you as a","subagent with its own narrow view and its own reading list:","",t.roles.map(n=>`- **${n.name}** \u2014 ${n.description}`).join(`
869
+ ${n}`}function XI(t,e,r,n){let o=Ga(e,r);if(o.length===0)return{roles:[],files:[]};let i=Ql(t,eu);YI(i,{recursive:!0});let s=[];for(let a of o)zI(Ql(i,`${a.name}.md`),VI(a,n)),s.push(`${eu}/${a.name}.md`);return{roles:o,files:s}}function JI(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(`
870
870
  `),"","Delegate to **every** role above \u2014 **in parallel**, all Task calls in one","turn. Give each role the SAME briefing (DEV-651 \u2014 the panel's quality is","the briefing's quality, not the coordinator's mood):","","- the review subject: `git diff refs/worktree/codepipe/review-base..HEAD`"," in each repo under `code/` \u2014 the base ref is pinned, do not diff against"," a branch tip;","- the finding contract: every finding names file + line, the concrete"," failing scenario, and stays within the diff \u2014 or states explicitly how"," the change broke an untouched place;","- established facts the role must not re-derive (the BUILD verdict when"," your prompt carries one).","","The roles are independent read-only views that never wait on each other,","so the panel costs the time of its slowest member, not the sum. Then do","your own job on what comes back:","",`1. Save each role's findings verbatim as \`${e}/<role>.md\`.`,"2. **Deduplicate.** Two roles reporting the same defect is one finding, not two.","3. **Filter.** A finding earns a round-trip only if it is a real defect, a"," regression or a convention the project actually enforces. Taste-level notes"," go in the summary, never in the remarks.","4. **Decide.** The verdict is yours, not a vote: a role can be wrong, and you"," are the one who read the code. When you overrule a role, say why in the"," summary.","","A role that returns nothing is a normal outcome \u2014 do not manufacture findings","to justify the panel.",""].join(`
871
- `)}var Jl,$w=x(()=>{"use strict";B();Jl=".claude/agents"});var xw={};Fe(xw,{COUNCIL_ANSWER_PATH:()=>vw,readCouncilVerdict:()=>zI});import{readFileSync as qI}from"node:fs";import{join as YI}from"node:path";function zI(t){let e;try{e=qI(YI(t,vw),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var vw,Sw=x(()=>{"use strict";vw="meta/council-answer.json"});var Tw={};Fe(Tw,{QUEUE_PLAN_PATH:()=>Ew,readQueuePlan:()=>JI});import{readFileSync as VI}from"node:fs";import{join as XI}from"node:path";function JI(t){let e;try{e=VI(XI(t,Ew),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var Ew,Rw=x(()=>{"use strict";Ew="meta/queue-plan.json"});import{mkdirSync as Iw,readFileSync as Cs,readdirSync as ZI,writeFileSync as Cw}from"node:fs";import{homedir as QI}from"node:os";import{dirname as eC,join as Pt}from"node:path";function rC(t){let e=Buffer.from(t,"utf-8");if(e.length<=Ps)return t;let r=Math.floor(Ps/4),n=Ps-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}
871
+ `)}var eu,Sw=x(()=>{"use strict";B();eu=".claude/agents"});var Tw={};Fe(Tw,{COUNCIL_ANSWER_PATH:()=>Ew,readCouncilVerdict:()=>eC});import{readFileSync as ZI}from"node:fs";import{join as QI}from"node:path";function eC(t){let e;try{e=ZI(QI(t,Ew),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var Ew,Rw=x(()=>{"use strict";Ew="meta/council-answer.json"});var Cw={};Fe(Cw,{QUEUE_PLAN_PATH:()=>Iw,readQueuePlan:()=>nC});import{readFileSync as tC}from"node:fs";import{join as rC}from"node:path";function nC(t){let e;try{e=tC(rC(t,Iw),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var Iw,Pw=x(()=>{"use strict";Iw="meta/queue-plan.json"});import{mkdirSync as Aw,readFileSync as Ps,readdirSync as oC,writeFileSync as _w}from"node:fs";import{homedir as iC}from"node:os";import{dirname as sC,join as At}from"node:path";function cC(t){let e=Buffer.from(t,"utf-8");if(e.length<=As)return t;let r=Math.floor(As/4),n=As-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}
872
872
 
873
- \u2026 [${s} bytes elided \u2014 log capped at ${Ps} bytes for upload] \u2026
873
+ \u2026 [${s} bytes elided \u2014 log capped at ${As} bytes for upload] \u2026
874
874
 
875
- ${i}`}function nC(){let t=[],e=!1,r=null,n=i=>{if(r){let s=r;r=null,s({value:i,done:!1})}else t.push(i)},o=()=>{if(r){let i=r;r=null,i({value:void 0,done:!0})}};return{push(i){e||n(i)},finalize(){e||(n({kind:"finalize"}),e=!0)},close(){e=!0,t.length=0,o()},iterable:{[Symbol.asyncIterator](){return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):e?Promise.resolve({value:void 0,done:!0}):new Promise(i=>{r=i})}}}}}}async function Ko(t={}){let e=Le(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,n=e.sandboxId,o=e.llm,i=Eg(t.profile,e.sandboxId,!!Q("SANDBOX_CONFIG")),s=Pt(QI(),".codepipe","logs"),a=hi("SANDBOX_LOG",i,s);if(a.enabled){let A=new an(a);gi(A),console.log(`[log] file logging \u2192 ${A.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${Ve} (protocol ${gt})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=Ug(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=Hg();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let u=new En(e.hubUrl,e.token),p=!1,d=new AbortController,m=new Map,f=null,y=null,k=!1,h=()=>{let A=u.openControlSocket();return f=A,A.on("open",()=>{console.log("[ws] connected");let g={type:"sandbox_hello",platformVersion:Ve,protocolVersion:gt};A.send(JSON.stringify(g))}),A.on("message",g=>{let U=g.toString("utf-8"),N=null;try{let H=JSON.parse(U);H&&typeof H=="object"&&(N=H)}catch{}if(N&&N.type==="hello"){let H=N;y=Jn(H.protocolVersion);let ee=y?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${H.platformVersion} (protocol ${H.protocolVersion}) \u2014 ${ee}`),y&&(k=!1);return}if(N&&N.type==="pause_job"){let H=typeof N.jobId=="string"?N.jobId:"",ee=H?m.get(H):void 0;ee?(console.warn(`[ws] pause_job ${H} \u2014 aborting agent`),ee.paused=!0,ee.abort.abort()):console.log(`[ws] pause_job ${H} \u2014 not a running job, ignoring`),H&&A.send(JSON.stringify({type:"job_paused",jobId:H}));return}if(N&&(N.type==="chat_user_message"||N.type==="chat_finalize")){let H=typeof N.jobId=="string"?N.jobId:"",ee=H?m.get(H):void 0;if(ee?.chatInbox)if(N.type==="chat_user_message"){let se=typeof N.text=="string"?N.text:"";se.trim()&&ee.chatInbox.push({kind:"user",text:se})}else ee.chatInbox.finalize();else console.log(`[ws] ${String(N.type)} ${H} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${U}`)}),A.on("close",(g,U)=>{console.log(`[ws] closed code=${g} reason=${U?.toString()||""}`),f===A&&(f=null),!p&&setTimeout(h,2e3)}),A.on("error",g=>console.warn(`[ws] error: ${g.message}`)),A},w=h(),$=async A=>{for(;!p;){if(y===!1){k||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${Ve}, protocol ${gt}) \u2014 not claiming jobs until versions align.`),k=!0),await new Promise(g=>setTimeout(g,5e3));continue}try{let g=await u.claim(d.signal,A);if(g.status===204)continue;if(g.status===401){console.error("[claim] 401 unauthorized \u2014 the HUB does not know this worker registration. It was removed; re-register with `codepipe up --reregister` (or `codepipe worker register --force`). exiting."),process.exitCode=1,p=!0;break}if(!g.ok){console.warn(`[claim:${A}] ${g.status} \u2014 backoff 5s`),await new Promise(N=>setTimeout(N,5e3));continue}let U=await g.json();await S(u,U)}catch(g){if(d.signal.aborted)break;let U=g instanceof Error?g.message:String(g);console.warn(`[claim:${A}] error: ${U} \u2014 backoff 5s`),await new Promise(N=>setTimeout(N,5e3))}}};async function S(A,g){let U={abort:new AbortController,paused:!1};g.role==="chat"&&(U.chatInbox=nC()),m.set(g.jobId,U);let N=!1,H=null,ee=null,se=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),jt=async()=>{try{await A.heartbeat(g.jobId)==="claim_lost"&&(N=!0,console.warn(`[job] ${g.jobId} claim lost \u2014 HUB sweeper took it`))}catch(L){let fe=L instanceof Error?L.message:String(L);console.warn(`[job] ${g.jobId} heartbeat error: ${fe}`)}};jt();let ft=setInterval(()=>{jt()},se),Ue=new Date().toISOString();console.log(`[job] ${g.jobId} claimed \u2014 role=${g.role} task=${g.taskId} phase=${g.phase}`),console.log(`[job] ${g.jobId} prompt (${g.prompt.length} chars):`),console.log(v(g.prompt," \u2502 "));let M=[],F=null,D=400,z=25,W=500,E=()=>{if(F&&(clearTimeout(F),F=null),M.length===0)return;let L=M.splice(0,M.length),fe=f;if(!fe||fe.readyState!==fe.OPEN)return;let ge={type:"agent_activity",jobId:g.jobId,taskId:g.taskId,projectId:g.projectId,role:g.role,phase:g.phase,events:L};try{fe.send(JSON.stringify(ge))}catch{}},I=L=>{M.push(L),M.length>W&&M.shift(),M.length>=z?E():F||(F=setTimeout(E,D))},te=g.role==="analysis"&&g.taskId.startsWith("draft::")?g.taskId.slice(7):null,ae=new Set,P=null;try{if(!c){N||await A.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:Ue,finishedAt:new Date().toISOString()});return}if(!Bg(o,g.provider??null)){N||await A.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${g.provider??"claude"}"`},startedAt:Ue,finishedAt:new Date().toISOString()});return}let L=Ly(g.jobId);console.log(`[job] ${g.jobId} workspace=${L.dir}`);let fe=T(g,r);H=fe.gitCreds,ee=fe.contextGitCreds;let ge=H?.env,mt=fe.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:fe.claudeOauthToken}:void 0,ce=[],ne=null,qs=null;try{let O=g.role==="build"?"clone":"worktree";ce=await vy(L.dir,g.projectId,g.projectRepos,O,ge,n);let _=await xy(L.dir,g.projectId,g.contextRepo,"worktree",ge,n);qs=_,ne=_?.workspacePath??null}catch(O){let _=O instanceof Error?O.message:String(O);console.warn(`[job] ${g.jobId} materialize failed: ${_}`),N||await A.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${_}`},startedAt:Ue,finishedAt:new Date().toISOString()}),L.dispose();return}let qn=g.model;g.role==="build"&&g.modelDiscovery&&!Ty(ne)&&(qn=g.modelDiscovery,console.log(`[job] ${g.jobId} BUILD discovery (no steps in ${Bl}) \u2014 model=${qn}`));let $u=async()=>{if(!g.deliveries||g.deliveries.length===0)return[];let O=g.contextRepo?.cloneUrl;if(!O||!ge)throw new Error(O?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let _=[];for(let q of g.deliveries){let V=ce.find(ie=>ie.name===q.name);if(V){if(g.role==="implement"&&q.baseSha&&q.baseSha!==V.baseSha){let ie=await gy(V,q.deliveryRef,q.deliverySha,q.baseSha,O,ge);console.log(`[job] ${g.jobId} ${V.name}: base moved ${q.baseSha.slice(0,10)} \u2192 ${V.baseSha.slice(0,10)} \u2014 re-applied delivery ${q.deliverySha.slice(0,10)} (${ie.length} conflicted file(s))`),ie.length>0&&_.push(`- **${V.name}**:`,...ie.map(tt=>` - \`${tt}\``));continue}await hy(V,q.deliveryRef,q.deliverySha,O,ge),console.log(`[job] ${g.jobId} ${V.name}: checked out delivery ${q.deliverySha.slice(0,10)} for ${g.role}`)}}return _},Ys=[];if(g.role==="build"||g.role==="implement"||g.role==="code-review")try{Ys=await $u()}catch(O){let _=O instanceof Error?O.message:String(O);console.warn(`[job] ${g.jobId} delivery checkout failed: ${_}`),N||await A.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${_}`},startedAt:Ue,finishedAt:new Date().toISOString()}),L.dispose();return}if(g.role==="code-review"){let O=g.metadata?.externalReview===!0;for(let _ of ce)try{if(O){let q=g.projectRepos.find(ie=>ie.name===_.name)?.defaultBranch??_.ref,V=await ky(_,q,ge);V?console.log(`[job] ${g.jobId} ${_.name}: review base ${V.slice(0,10)} (merge-base with ${q})`):console.warn(`[job] ${g.jobId} ${_.name}: no merge-base with ${q} \u2014 review base not pinned (agent falls back to manual deepen)`)}else await Ul(_,_.baseSha,ge),console.log(`[job] ${g.jobId} ${_.name}: review base ${_.baseSha.slice(0,10)} (pre-delivery)`)}catch(q){let V=q instanceof Error?q.message:String(q);console.warn(`[job] ${g.jobId} ${_.name}: review-base pin failed: ${V}`)}}let zs=g.role==="resolve-conflict"?g.metadata?.mergeBranchByRepo??g.metadata?.taskBranchByRepo??{}:{},vu="";if(g.role==="resolve-conflict"){if(!ce.some(O=>zs[O.name])){let O="resolve-conflict job carries no branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${g.jobId} ${O}`),N||await A.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:O},startedAt:Ue,finishedAt:new Date().toISOString()}),L.dispose();return}try{let O=[];for(let _ of ce){let q=zs[_.name];if(!q)continue;let V=await Dl(_,q,ge);console.log(`[job] ${g.jobId} ${_.name}: merged ${q} into ${_.ref} \u2014 ${V.length} conflicted file(s)`),V.length>0?O.push(`- **${_.name}**:`,...V.map(ie=>` - \`${ie}\``)):O.push(`- **${_.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}vu=`
875
+ ${i}`}function lC(){let t=[],e=!1,r=null,n=i=>{if(r){let s=r;r=null,s({value:i,done:!1})}else t.push(i)},o=()=>{if(r){let i=r;r=null,i({value:void 0,done:!0})}};return{push(i){e||n(i)},finalize(){e||(n({kind:"finalize"}),e=!0)},close(){e=!0,t.length=0,o()},iterable:{[Symbol.asyncIterator](){return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):e?Promise.resolve({value:void 0,done:!0}):new Promise(i=>{r=i})}}}}}}async function Ko(t={}){let e=Me(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,n=e.sandboxId,o=e.llm,i=Ig(t.profile,e.sandboxId,!!Q("SANDBOX_CONFIG")),s=At(iC(),".codepipe","logs"),a=mi("SANDBOX_LOG",i,s);if(a.enabled){let A=new an(a);hi(A),console.log(`[log] file logging \u2192 ${A.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${Ve} (protocol ${gt})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=Gg(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=Yg();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let u=new En(e.hubUrl,e.token),p=!1,d=new AbortController,m=new Map,f=null,g=null,k=!1,h=()=>{let A=u.openControlSocket();return f=A,A.on("open",()=>{console.log("[ws] connected");let y={type:"sandbox_hello",platformVersion:Ve,protocolVersion:gt};A.send(JSON.stringify(y))}),A.on("message",y=>{let U=y.toString("utf-8"),O=null;try{let G=JSON.parse(U);G&&typeof G=="object"&&(O=G)}catch{}if(O&&O.type==="hello"){let G=O;g=Jn(G.protocolVersion);let ee=g?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${G.platformVersion} (protocol ${G.protocolVersion}) \u2014 ${ee}`),g&&(k=!1);return}if(O&&O.type==="pause_job"){let G=typeof O.jobId=="string"?O.jobId:"",ee=G?m.get(G):void 0;ee?(console.warn(`[ws] pause_job ${G} \u2014 aborting agent`),ee.paused=!0,ee.abort.abort()):console.log(`[ws] pause_job ${G} \u2014 not a running job, ignoring`),G&&A.send(JSON.stringify({type:"job_paused",jobId:G}));return}if(O&&(O.type==="chat_user_message"||O.type==="chat_finalize")){let G=typeof O.jobId=="string"?O.jobId:"",ee=G?m.get(G):void 0;if(ee?.chatInbox)if(O.type==="chat_user_message"){let ue=typeof O.text=="string"?O.text:"";ue.trim()&&ee.chatInbox.push({kind:"user",text:ue})}else ee.chatInbox.finalize();else console.log(`[ws] ${String(O.type)} ${G} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${U}`)}),A.on("close",(y,U)=>{console.log(`[ws] closed code=${y} reason=${U?.toString()||""}`),f===A&&(f=null),!p&&setTimeout(h,2e3)}),A.on("error",y=>console.warn(`[ws] error: ${y.message}`)),A},w=h(),$=async A=>{for(;!p;){if(g===!1){k||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${Ve}, protocol ${gt}) \u2014 not claiming jobs until versions align.`),k=!0),await new Promise(y=>setTimeout(y,5e3));continue}try{let y=await u.claim(d.signal,A);if(y.status===204)continue;if(y.status===401){console.error("[claim] 401 unauthorized \u2014 the HUB does not know this worker registration. It was removed; re-register with `codepipe up --reregister` (or `codepipe worker register --force`). exiting."),process.exitCode=1,p=!0;break}if(!y.ok){console.warn(`[claim:${A}] ${y.status} \u2014 backoff 5s`),await new Promise(O=>setTimeout(O,5e3));continue}let U=await y.json();await S(u,U)}catch(y){if(d.signal.aborted)break;let U=y instanceof Error?y.message:String(y);console.warn(`[claim:${A}] error: ${U} \u2014 backoff 5s`),await new Promise(O=>setTimeout(O,5e3))}}};async function S(A,y){let U={abort:new AbortController,paused:!1};y.role==="chat"&&(U.chatInbox=lC()),m.set(y.jobId,U);let O=!1,G=null,ee=null,ue=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),tt=async()=>{try{await A.heartbeat(y.jobId)==="claim_lost"&&(O=!0,console.warn(`[job] ${y.jobId} claim lost \u2014 HUB sweeper took it`))}catch(N){let pe=N instanceof Error?N.message:String(N);console.warn(`[job] ${y.jobId} heartbeat error: ${pe}`)}};tt();let ft=setInterval(()=>{tt()},ue),Ne=new Date().toISOString();console.log(`[job] ${y.jobId} claimed \u2014 role=${y.role} task=${y.taskId} phase=${y.phase}`),console.log(`[job] ${y.jobId} prompt (${y.prompt.length} chars):`),console.log(v(y.prompt," \u2502 "));let Oe=[],M=null,F=400,D=25,X=500,H=()=>{if(M&&(clearTimeout(M),M=null),Oe.length===0)return;let N=Oe.splice(0,Oe.length),pe=f;if(!pe||pe.readyState!==pe.OPEN)return;let he={type:"agent_activity",jobId:y.jobId,taskId:y.taskId,projectId:y.projectId,role:y.role,phase:y.phase,events:N};try{pe.send(JSON.stringify(he))}catch{}},E=N=>{Oe.push(N),Oe.length>X&&Oe.shift(),Oe.length>=D?H():M||(M=setTimeout(H,F))},C=y.role==="analysis"&&y.taskId.startsWith("draft::")?y.taskId.slice(7):null,te=new Set,T=null;try{if(!c){O||await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:Ne,finishedAt:new Date().toISOString()});return}if(!Kg(o,y.provider??null)){O||await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${y.provider??"claude"}"`},startedAt:Ne,finishedAt:new Date().toISOString()});return}let N=Uy(y.jobId);console.log(`[job] ${y.jobId} workspace=${N.dir}`);let pe=R(y,r);G=pe.gitCreds,ee=pe.contextGitCreds;let he=G?.env,mt=pe.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:pe.claudeOauthToken}:void 0,se=[],ne=null,Ys=null;try{let L=y.role==="build"?"clone":"worktree";se=await Ey(N.dir,y.projectId,y.projectRepos,L,he,n);let _=await Ty(N.dir,y.projectId,y.contextRepo,"worktree",he,n);Ys=_,ne=_?.workspacePath??null}catch(L){let _=L instanceof Error?L.message:String(L);console.warn(`[job] ${y.jobId} materialize failed: ${_}`),O||await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${_}`},startedAt:Ne,finishedAt:new Date().toISOString()}),N.dispose();return}let qn=y.model;y.role==="build"&&y.modelDiscovery&&!Cy(ne)&&(qn=y.modelDiscovery,console.log(`[job] ${y.jobId} BUILD discovery (no steps in ${Kl}) \u2014 model=${qn}`));let vu=async()=>{if(!y.deliveries||y.deliveries.length===0)return[];let L=y.contextRepo?.cloneUrl;if(!L||!he)throw new Error(L?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let _=[];for(let q of y.deliveries){let V=se.find(ie=>ie.name===q.name);if(V){if(y.role==="implement"&&q.baseSha&&q.baseSha!==V.baseSha){let ie=await ky(V,q.deliveryRef,q.deliverySha,q.baseSha,L,he);console.log(`[job] ${y.jobId} ${V.name}: base moved ${q.baseSha.slice(0,10)} \u2192 ${V.baseSha.slice(0,10)} \u2014 re-applied delivery ${q.deliverySha.slice(0,10)} (${ie.length} conflicted file(s))`),ie.length>0&&_.push(`- **${V.name}**:`,...ie.map(rt=>` - \`${rt}\``));continue}await wy(V,q.deliveryRef,q.deliverySha,L,he),console.log(`[job] ${y.jobId} ${V.name}: checked out delivery ${q.deliverySha.slice(0,10)} for ${y.role}`)}}return _},zs=[];if(y.role==="build"||y.role==="implement"||y.role==="code-review")try{zs=await vu()}catch(L){let _=L instanceof Error?L.message:String(L);console.warn(`[job] ${y.jobId} delivery checkout failed: ${_}`),O||await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${_}`},startedAt:Ne,finishedAt:new Date().toISOString()}),N.dispose();return}if(y.role==="code-review"){let L=y.metadata?.externalReview===!0;for(let _ of se)try{if(L){let q=y.projectRepos.find(ie=>ie.name===_.name)?.defaultBranch??_.ref,V=await vy(_,q,he);V?console.log(`[job] ${y.jobId} ${_.name}: review base ${V.slice(0,10)} (merge-base with ${q})`):console.warn(`[job] ${y.jobId} ${_.name}: no merge-base with ${q} \u2014 review base not pinned (agent falls back to manual deepen)`)}else await Gl(_,_.baseSha,he),console.log(`[job] ${y.jobId} ${_.name}: review base ${_.baseSha.slice(0,10)} (pre-delivery)`)}catch(q){let V=q instanceof Error?q.message:String(q);console.warn(`[job] ${y.jobId} ${_.name}: review-base pin failed: ${V}`)}}let Vs=y.role==="resolve-conflict"?y.metadata?.mergeBranchByRepo??y.metadata?.taskBranchByRepo??{}:{},xu="";if(y.role==="resolve-conflict"){if(!se.some(L=>Vs[L.name])){let L="resolve-conflict job carries no branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${y.jobId} ${L}`),O||await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:L},startedAt:Ne,finishedAt:new Date().toISOString()}),N.dispose();return}try{let L=[];for(let _ of se){let q=Vs[_.name];if(!q)continue;let V=await Fl(_,q,he);console.log(`[job] ${y.jobId} ${_.name}: merged ${q} into ${_.ref} \u2014 ${V.length} conflicted file(s)`),V.length>0?L.push(`- **${_.name}**:`,...V.map(ie=>` - \`${ie}\``)):L.push(`- **${_.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}xu=`
876
876
 
877
877
  ## Conflicts to resolve
878
878
 
879
- `+(O.length>0?O.join(`
879
+ `+(L.length>0?L.join(`
880
880
  `):"(no task branches to merge)")+`
881
- `}catch(O){let _=O instanceof Error?O.message:String(O);console.warn(`[job] ${g.jobId} conflict merge failed: ${_}`),N||await A.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${_}`},startedAt:Ue,finishedAt:new Date().toISOString()}),L.dispose();return}}let Vs=null;if(g.contextPack&&ne)try{let{assembleContextPack:O}=await Promise.resolve().then(()=>(ow(),nw)),_=O({contextDir:ne,taskKey:String(g.metadata?.trackerIssueKey??g.taskId.split(":")[1]??""),title:String(g.metadata?.taskTitle??""),repoDirs:new Map(ce.map(q=>[q.name,q.workspacePath]))});_?(Iw(Pt(L.dir,"meta"),{recursive:!0}),Cw(Pt(L.dir,"meta","context-pack.md"),_),Vs=_,console.log(`[job] ${g.jobId} context pack: ${_.length} chars \u2192 meta/context-pack.md`)):console.log(`[job] ${g.jobId} context pack: model empty or no signal \u2014 skipped`)}catch(O){let _=O instanceof Error?O.message:String(O);console.warn(`[job] ${g.jobId} context pack failed (non-fatal): ${_}`)}let xu="",Qo=null,Xs=null;try{let{loadSkills:O,materializeSkills:_,renderSkillsBlock:q}=await Promise.resolve().then(()=>(lw(),cw)),V=g.skills??{bundled:!0,context:!0,repo:!0},ie=O({contextDir:ne,repoDirs:ce.map(rt=>rt.workspacePath),sources:V});for(let rt of ie.errors)console.warn(`[job] ${g.jobId} skill ${rt.source}: ${rt.error}`);let tt=_(L.dir,ie.skills),ye=["implement","rework","testing"].includes(g.role)?za(Ya(R(ne,g.taskId))):[];xu=q(ie.skills,ye),tt.length>0&&console.log(`[job] ${g.jobId} skills: ${ie.skills.map(rt=>rt.name).join(", ")}`);let{parseMarketplaces:Be,enabledPluginsSetting:Fr}=await Promise.resolve().then(()=>(B(),Gd)),{sources:Gr,errors:zn}=Be(V.marketplaces??[]);for(let rt of zn)console.warn(`[job] ${g.jobId} marketplace ${rt}`);if(Gr.length>0&&(V.plugins??[]).length>0){let{seedMarketplaces:rt}=await Promise.resolve().then(()=>(mw(),fw)),Kr=await rt(Gr);for(let J of Kr.errors)console.warn(`[job] ${g.jobId} marketplace ${J.repo}: ${J.error}`);let{enabled:Hr,unknown:Wr}=Fr(V.plugins??[],Kr.ready);for(let J of Wr)console.warn(`[job] ${g.jobId} plugin ${J}: no such marketplace in this project`);Kr.dir&&Object.keys(Hr).length>0&&(Qo=Kr.dir,Xs={enabledPlugins:Hr},console.log(`[job] ${g.jobId} plugins: ${Object.keys(Hr).join(", ")}`))}}catch(O){let _=O instanceof Error?O.message:String(O);console.warn(`[job] ${g.jobId} skills unavailable (non-fatal): ${_}`)}let Su="",wb=g.role==="code-review"&&g.metadata?.reviewPanel===!1;if(["code-review","council","analyze","testing"].includes(g.role)&&!wb)try{let{loadRoles:O}=await Promise.resolve().then(()=>(kw(),ww)),{materializeRoleAgents:_,renderRolesBlock:q}=await Promise.resolve().then(()=>($w(),bw)),V=O(ne);for(let Be of V.errors)console.warn(`[job] ${g.jobId} role ${Be.file}: ${Be.error}`);let ie=g.role==="council"?"council":g.role==="analyze"?"plan_review":"code_review",tt=g.role==="council"?"council":g.role==="analyze"?"plan-review":g.role==="testing"?"testing":"code-review",ye=_(L.dir,V.roles,ie,ne);Su=q(ye,tt),console.log(`[job] ${g.jobId} review panel: ${ye.roles.length>0?ye.roles.map(Be=>Be.name).join(", "):"(no roles)"}`)}catch(O){let _=O instanceof Error?O.message:String(O);console.warn(`[job] ${g.jobId} review panel unavailable (non-fatal): ${_}`)}let kb=Ys.length>0?`
881
+ `}catch(L){let _=L instanceof Error?L.message:String(L);console.warn(`[job] ${y.jobId} conflict merge failed: ${_}`),O||await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${_}`},startedAt:Ne,finishedAt:new Date().toISOString()}),N.dispose();return}}let Xs=null;if(y.contextPack&&ne)try{let{assembleContextPack:L}=await Promise.resolve().then(()=>(aw(),sw)),_=L({contextDir:ne,taskKey:String(y.metadata?.trackerIssueKey??y.taskId.split(":")[1]??""),title:String(y.metadata?.taskTitle??""),repoDirs:new Map(se.map(q=>[q.name,q.workspacePath]))});_?(Aw(At(N.dir,"meta"),{recursive:!0}),_w(At(N.dir,"meta","context-pack.md"),_),Xs=_,console.log(`[job] ${y.jobId} context pack: ${_.length} chars \u2192 meta/context-pack.md`)):console.log(`[job] ${y.jobId} context pack: model empty or no signal \u2014 skipped`)}catch(L){let _=L instanceof Error?L.message:String(L);console.warn(`[job] ${y.jobId} context pack failed (non-fatal): ${_}`)}let Su="",Qo=null,Js=null;try{let{loadSkills:L,materializeSkills:_,renderSkillsBlock:q}=await Promise.resolve().then(()=>(pw(),dw)),V=y.skills??{bundled:!0,context:!0,repo:!0},ie=L({contextDir:ne,repoDirs:se.map(nt=>nt.workspacePath),sources:V});for(let nt of ie.errors)console.warn(`[job] ${y.jobId} skill ${nt.source}: ${nt.error}`);let rt=_(N.dir,ie.skills),ge=["implement","rework","testing"].includes(y.role)?Va(za(I(ne,y.taskId))):[];Su=q(ie.skills,ge),rt.length>0&&console.log(`[job] ${y.jobId} skills: ${ie.skills.map(nt=>nt.name).join(", ")}`);let{parseMarketplaces:Be,enabledPluginsSetting:Fr}=await Promise.resolve().then(()=>(B(),Kd)),{sources:Gr,errors:zn}=Be(V.marketplaces??[]);for(let nt of zn)console.warn(`[job] ${y.jobId} marketplace ${nt}`);if(Gr.length>0&&(V.plugins??[]).length>0){let{seedMarketplaces:nt}=await Promise.resolve().then(()=>(yw(),gw)),Kr=await nt(Gr);for(let J of Kr.errors)console.warn(`[job] ${y.jobId} marketplace ${J.repo}: ${J.error}`);let{enabled:Hr,unknown:Wr}=Fr(V.plugins??[],Kr.ready);for(let J of Wr)console.warn(`[job] ${y.jobId} plugin ${J}: no such marketplace in this project`);Kr.dir&&Object.keys(Hr).length>0&&(Qo=Kr.dir,Js={enabledPlugins:Hr},console.log(`[job] ${y.jobId} plugins: ${Object.keys(Hr).join(", ")}`))}}catch(L){let _=L instanceof Error?L.message:String(L);console.warn(`[job] ${y.jobId} skills unavailable (non-fatal): ${_}`)}let Eu="",bb=y.role==="code-review"&&y.metadata?.reviewPanel===!1;if(["code-review","council","analyze","testing"].includes(y.role)&&!bb)try{let{loadRoles:L}=await Promise.resolve().then(()=>(vw(),$w)),{materializeRoleAgents:_,renderRolesBlock:q}=await Promise.resolve().then(()=>(Sw(),xw)),V=L(ne);for(let Be of V.errors)console.warn(`[job] ${y.jobId} role ${Be.file}: ${Be.error}`);let ie=y.role==="council"?"council":y.role==="analyze"?"plan_review":"code_review",rt=y.role==="council"?"council":y.role==="analyze"?"plan-review":y.role==="testing"?"testing":"code-review",ge=_(N.dir,V.roles,ie,ne);Eu=q(ge,rt),console.log(`[job] ${y.jobId} review panel: ${ge.roles.length>0?ge.roles.map(Be=>Be.name).join(", "):"(no roles)"}`)}catch(L){let _=L instanceof Error?L.message:String(L);console.warn(`[job] ${y.jobId} review panel unavailable (non-fatal): ${_}`)}let $b=zs.length>0?`
882
882
 
883
883
  ## Base branch moved \u2014 conflicts to resolve
884
884
 
885
885
  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:
886
886
 
887
- `+Ys.join(`
887
+ `+zs.join(`
888
888
  `)+`
889
- `:"",Eu=j(b(g.prompt,ce,ne),ne,g.taskId).replace(/\{\{rolesBlock\}\}/g,Su).replace(/\{\{skillsBlock\}\}/g,xu)+vu+kb,Yn=[...ce.map(O=>O.workspacePath),...ne?[ne]:[]];if(Yn.length>0&&console.log(`[job] ${g.jobId} --add-dir: ${Yn.join(", ")}`),Xg("agent-request")){let O=gs(Tn(g.metadata??{})),_=Jg(g.projectId,g.jobId,"agent-request",[`# Agent request \u2014 job ${g.jobId}`,"",`- project: ${g.projectId}`,`- task: ${g.taskId}`,`- role: ${g.role}`,`- model: ${qn??"(backend default)"}`,`- add-dirs:${Yn.length>0?"":" (none)"}`,...Yn.map(q=>` - ${q}`),"","## Append-system-prompt (language directive)","","```",O,"```","","## Prompt","",Eu,"",...Vs?["## Context pack (meta/context-pack.md)","",Vs]:["## Context pack","","(not generated for this job)"],""].join(`
890
- `));_&&console.log(`[debug] ${g.jobId} agent request \u2192 ${_}`)}te&&(P=setInterval(()=>{let _=f;if(!_||_.readyState!==_.OPEN)return;let q;try{q=ZI(Pt(L.dir,"drafts")).filter(V=>V.endsWith(".json")).sort()}catch{return}for(let V of q){if(ae.has(V))continue;if(ae.size>=tc)break;let ie;try{let ye=JSON.parse(Cs(Pt(L.dir,"drafts",V),"utf-8")),Be=typeof ye.localRef=="string"?ye.localRef:"",Fr=typeof ye.title=="string"?ye.title:"",Gr=typeof ye.body=="string"?ye.body:"";if(!Be||!Fr)continue;ie={localRef:Be,title:Fr,body:Gr,...ye.isEpic===!0?{isEpic:!0}:{},...Array.isArray(ye.links)?{links:ye.links}:{}}}catch{continue}ae.add(V);let tt={type:"child_draft",jobId:g.jobId,projectId:g.projectId,draftId:te,child:ie};try{_.send(JSON.stringify(tt))}catch{}}},1500));try{let O={workspaceDir:L.dir,role:g.role,prompt:Eu,addDirs:Yn,metadata:g.metadata??{},...qn?{model:qn}:{},...mt||Qo?{env:{...mt??{},...Qo?{CLAUDE_CODE_PLUGIN_SEED_DIR:Qo}:{}}}:{},...Xs?{settings:Xs}:{},signal:U.abort.signal,onActivity:I},_=U.chatInbox?await c.run({...O,interactive:{inbox:U.chatInbox.iterable}}):await qg(c,O,{jobId:g.jobId,policy:l,onBeforeRetry:async()=>{L.clean();for(let J of ce)try{await dy(J);let ve=zs[J.name];g.role==="resolve-conflict"&&ve&&await Dl(J,ve,ge)}catch(ve){let Wt=ve instanceof Error?ve.message:String(ve);console.warn(`[job] ${g.jobId} worktree reset failed (${J.name}): ${Wt}`)}try{await $u()}catch(J){let ve=J instanceof Error?J.message:String(J);console.warn(`[job] ${g.jobId} delivery re-checkout failed: ${ve}`)}},aborted:()=>N||U.paused}),q=[];if(tC.has(g.role)&&ce.length>0){let J=g.metadata??{},ve=typeof J.commitMessage=="string"?J.commitMessage:`${g.taskId}: changes`,Wt=g.contextRepo?.cloneUrl,Vn=ee?.env;if(!Wt||!Vn)throw new Error("delivery requested but "+(Wt?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let Js=g.taskId.includes(":")?g.taskId.slice(g.taskId.indexOf(":")+1):g.taskId;for(let Nt of ce){let Xn=await py(Nt,ve);if(!Xn){console.log(`[job] ${g.jobId} ${Nt.name}: no changes \u2014 no delivery`);continue}let Zs=`codepipe/deliveries/${Js}/${g.jobId}/${Nt.name}`;await fy(Nt,Xn,Zs,Wt,Vn),q.push({name:Nt.name,deliveryRef:Zs,deliverySha:Xn,baseSha:Nt.baseSha}),console.log(`[job] ${g.jobId} ${Nt.name}: delivered ${Xn.slice(0,10)} \u2192 ${Zs}`);let Tu=await my(Nt,Xn);if(Tu.trim().length>0){let bb=Pt("display",`${Nt.name}.diff`),Ru=Pt(L.dir,bb);Iw(eC(Ru),{recursive:!0}),Cw(Ru,Tu)}}}if(g.role==="resolve-conflict"&&q.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's SOLUTION.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let V;g.role==="build"&&(V=Iy(L.dir),console.log(`[job] ${g.jobId} build verdict: ok=${V.ok}`+(V.failedStep?` failedStep=${V.failedStep}`:"")));let ie;if(g.role==="code-review"){ie=Gl(L.dir),console.log(`[job] ${g.jobId} review verdict: approved=${ie.approved}`);try{let{parseChangedRanges:J,markFindingScope:ve}=await Promise.resolve().then(()=>(Kl(),Py)),Wt=new Map;for(let Vn of ce)try{let Js=await wy(Vn,ge);Wt.set(Vn.name,J(Js))}catch{}ve(ie,Wt,ce.length===1?ce[0].name:void 0)}catch(J){console.warn(`[job] ${g.jobId} finding scope marking failed (non-fatal): ${String(J)}`)}}let tt;if(g.role==="council"){let{readCouncilVerdict:J}=await Promise.resolve().then(()=>(Sw(),xw));tt=J(L.dir)??void 0,console.log(`[job] ${g.jobId} council: ${tt?"answered":"no verdict \u2014 task stops for a human"}`)}let ye;if(g.role==="testing"){try{let J=Cs(Pt(L.dir,"meta","test-result.json"),"utf-8");ye=JSON.parse(J)}catch{ye=void 0}console.log(`[job] ${g.jobId} test verdict: ${ye?"written":"none \u2014 proceeding to the PR"}`)}let Be;if(g.role==="observer"){let{readQueuePlan:J}=await Promise.resolve().then(()=>(Rw(),Tw));Be=J(L.dir)??void 0,console.log(`[job] ${g.jobId} queue plan: ${Be?"produced":"none \u2014 batch keeps the staged order"}`)}let Fr=_.artifactPaths.length>0?_.artifactPaths:L.listFiles(),Gr=Array.from(new Set(Fr)),zn;if(qs)try{let J=g.role==="index"?["adr/SOURCES.md"]:g.role==="backfill"?["adr"]:[],ve=await Sy(qs,J);ve.length>0&&(zn=ve,console.log(`[job] ${g.jobId} captured ${ve.length} knowledge file(s) for Context Repo`))}catch(J){let ve=J instanceof Error?J.message:String(J);console.warn(`[job] ${g.jobId} knowledge capture failed (non-fatal): ${ve}`)}let{artifacts:rt,omitted:Kr,dropped:Hr}=_y(L.dir,Gr);for(let J of Kr)console.warn(`[job] ${g.jobId} artifact ${J.path} (${J.bytes} bytes) exceeded upload budget \u2014 content omitted`);Hr.length>0&&console.warn(`[job] ${g.jobId} artifact listing truncated: ${Hr.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let Wr={jobId:g.jobId,status:"succeeded",artifacts:rt,...zn?{contextWrites:zn}:{},...q.length>0?{deliveries:q}:{},log:rC(_.log),startedAt:Ue,finishedAt:new Date().toISOString(),usage:_.usage,..._.rateLimit?{rateLimit:_.rateLimit}:{},...V?{build:V}:{},...ie?{review:ie}:{},...Be!==void 0?{queuePlan:Be}:{},...tt!==void 0?{council:tt}:{},...ye!==void 0?{test:ye}:{}};if(N||U.paused)console.warn(`[job] ${g.jobId} skipping result upload \u2014 ${U.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await A.submitResult(Wr),console.log(`[job] ${g.jobId} done \u2014 uploaded ${Wr.artifacts.length} artifact(s):`);for(let J of Wr.artifacts){let ve=Buffer.from(J.contentBase64,"base64").length;console.log(` \xB7 ${J.path} (${ve} bytes)`)}Wr.artifacts.length===0&&console.warn(`[job] ${g.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(O){let _=O instanceof Error?O.message:String(O);if(U.paused)console.log(`[job] ${g.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(N)console.warn(`[job] ${g.jobId} failed after claim lost (${_}) \u2014 skipping result upload`);else{let q=Wg(O),V=O instanceof ur,ie=O instanceof Ct;console.warn(q?`[job] ${g.jobId} failed: ${_} (Claude auth \u2014 token invalid/expired)`:V?`[job] ${g.jobId} failed: ${_} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:ie?`[job] ${g.jobId} failed: ${_} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${g.jobId} failed: ${_}`),await A.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:_},startedAt:Ue,finishedAt:new Date().toISOString(),...q?{authError:!0}:{},...V?{buildInconclusive:!0}:{},...ie?{reviewInconclusive:!0}:{}})}}finally{L.dispose()}}finally{clearInterval(ft),P&&clearInterval(P),E(),U.chatInbox?.close(),m.delete(g.jobId),H?.cleanup(),ee?.cleanup()}}function T(A,g){if(!A.credBundle)return{gitCreds:null,contextGitCreds:null};if(!g)return console.warn(`[job] ${A.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let U;try{U=JSON.parse(yn(g,A.credBundle).toString("utf-8"))}catch(se){return console.warn(`[job] ${A.jobId} failed to open credBundle: ${se instanceof Error?se.message:String(se)}`),{gitCreds:null,contextGitCreds:null}}let N=Ll(U);N&&console.log(`[job] ${A.jobId} cred bundle opened \u2014 git creds configured`);let H=oy(U,A.contextRepo.cloneUrl),ee={gitCreds:N,contextGitCreds:H};return U.claudeOauthToken&&(ee.claudeOauthToken=U.claudeOauthToken),ee}function v(A,g){return A.split(`
891
- `).map(U=>g+U).join(`
892
- `)}function b(A,g,U){let N=g[0]?.workspacePath??"";return A.replace(/\{\{codeDir\}\}/g,N).replace(/\{\{codeRoot\}\}/g,N?N.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,U??"")}function R(A,g){let U=g.includes("::")?"":g.split(":",2)[1]??"";if(!A||!U)return"";for(let N of["PLAN.md","SOLUTION.md"])try{return Cs(Pt(A,"tasks",U,N),"utf-8")}catch{}return""}function j(A,g,U){let N=A,H=U.includes("::")?"":U.split(":",2)[1]??"",ee=se=>{if(!g||!H)return"";try{return Cs(Pt(g,"tasks",H,se),"utf-8").trim()}catch{return""}};if(N.includes("{{planMd}}")||N.includes("{{solutionMd}}")){let se=ee("PLAN.md")||ee("SOLUTION.md")||"(PLAN.md missing \u2014 proceed from the task description)";N=N.replace(/\{\{planMd\}\}/g,()=>se),N=N.replace(/\{\{solutionMd\}\}/g,()=>se)}if(N.includes("{{taskDescription}}")){let se=ee("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";N=N.replace(/\{\{taskDescription\}\}/g,()=>se)}return N=Uy(N,g),N}let G=A=>{if(p)return;p=!0,console.log(`
893
- [${A}] shutting down`),d.abort();let g=[...m.keys()];for(let H of m.values())H.abort.abort();let U=new AbortController,N=setTimeout(()=>U.abort(),3e3);(async()=>(await Promise.all(g.map(async H=>{try{await u.releaseJob(H,`sandbox ${A}`,U.signal),console.log(`[${A}] released job ${H}`)}catch(ee){let se=ee instanceof Error?ee.message:String(ee);console.warn(`[${A}] release failed: ${se} (sweeper will reclaim)`)}})),clearTimeout(N),w.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>G("SIGINT")),process.on("SIGTERM",()=>G("SIGTERM"));let X=[$("implementation")];e.planningLane!==!1?X.push($("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(X)}var Ps,tC,Pw=x(()=>{"use strict";B();dt();sc();Fg();ys();Yg();Zg();Ge();hs();iy();Al();Ey();Ry();Cy();Kl();jy();Dy();Fy();Ps=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),tC=new Set(["implement","resolve-conflict"])});var On=x(()=>{"use strict";Rg();Pw();hs()});import{cancel as oC,isCancel as _w,log as Ze,password as iC,text as sC}from"@clack/prompts";function aC(t){return _w(t)&&(oC("aborted"),process.exit(1)),typeof t=="string"?t:""}function jw(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function cC(t){let e=wc({redirectUri:yc,challenge:t.challenge,state:t.state});Ze.message(`Open this URL, approve the access, and paste the code shown:
894
- ${e}`);let r=await sC({message:"Authorization code \u2014 blank to skip"});if(_w(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=zp(r,t.state);return await kc({code:n,verifier:t.verifier,state:t.state,redirectUri:yc})}catch(n){return Ze.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function lC(t){if(oc()?.claude?.oauthToken&&!t.farm)return Ze.message("Claude: this machine already has a shared OAuth token \u2014 the project will use it (set a project-specific one later with `codepipe login`)."),"";if(process.env.CODEPIPE_CLAUDE_AUTOLOGIN!=="1"||!process.stdout.isTTY)return null;Ze.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=$i(),n;try{n=await Vp({...r,openUrl:Pr,log:i=>Ze.message(i)})}catch(i){Ze.warn(`Browser sign-in didn't complete (${i instanceof Error?i.message:String(i)}) \u2014 trying the code-paste fallback.`);let s=await cC(r);if(s===null)return null;n=s}let o=await Bt(n.oauthToken);return o==="invalid"?(Ze.warn("Claude rejected the obtained token (401) \u2014 falling back to manual entry."),null):(Ze.success(`Claude: logged in \u2014 ${jw(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function Nw(t){Ze.message(`Claude \u2014 the pipeline's agents run on your Claude subscription.
889
+ `:"",Tu=j(b(y.prompt,se,ne),ne,y.taskId).replace(/\{\{rolesBlock\}\}/g,Eu).replace(/\{\{skillsBlock\}\}/g,Su)+xu+$b,Yn=[...se.map(L=>L.workspacePath),...ne?[ne]:[]];if(Yn.length>0&&console.log(`[job] ${y.jobId} --add-dir: ${Yn.join(", ")}`),Qg("agent-request")){let L=ys(Tn(y.metadata??{})),_=ey(y.projectId,y.jobId,"agent-request",[`# Agent request \u2014 job ${y.jobId}`,"",`- project: ${y.projectId}`,`- task: ${y.taskId}`,`- role: ${y.role}`,`- model: ${qn??"(backend default)"}`,`- add-dirs:${Yn.length>0?"":" (none)"}`,...Yn.map(q=>` - ${q}`),"","## Append-system-prompt (language directive)","","```",L,"```","","## Prompt","",Tu,"",...Xs?["## Context pack (meta/context-pack.md)","",Xs]:["## Context pack","","(not generated for this job)"],""].join(`
890
+ `));_&&console.log(`[debug] ${y.jobId} agent request \u2192 ${_}`)}C&&(T=setInterval(()=>{let _=f;if(!_||_.readyState!==_.OPEN)return;let q;try{q=oC(At(N.dir,"drafts")).filter(V=>V.endsWith(".json")).sort()}catch{return}for(let V of q){if(te.has(V))continue;if(te.size>=rc)break;let ie;try{let ge=JSON.parse(Ps(At(N.dir,"drafts",V),"utf-8")),Be=typeof ge.localRef=="string"?ge.localRef:"",Fr=typeof ge.title=="string"?ge.title:"",Gr=typeof ge.body=="string"?ge.body:"";if(!Be||!Fr)continue;ie={localRef:Be,title:Fr,body:Gr,...ge.isEpic===!0?{isEpic:!0}:{},...Array.isArray(ge.links)?{links:ge.links}:{}}}catch{continue}te.add(V);let rt={type:"child_draft",jobId:y.jobId,projectId:y.projectId,draftId:C,child:ie};try{_.send(JSON.stringify(rt))}catch{}}},1500));try{let L={workspaceDir:N.dir,role:y.role,prompt:Tu,addDirs:Yn,metadata:y.metadata??{},...qn?{model:qn}:{},...mt||Qo?{env:{...mt??{},...Qo?{CLAUDE_CODE_PLUGIN_SEED_DIR:Qo}:{}}}:{},...Js?{settings:Js}:{},signal:U.abort.signal,onActivity:E},_=U.chatInbox?await c.run({...L,interactive:{inbox:U.chatInbox.iterable}}):await Vg(c,L,{jobId:y.jobId,policy:l,onBeforeRetry:async()=>{N.clean();for(let J of se)try{await my(J);let $e=Vs[J.name];y.role==="resolve-conflict"&&$e&&await Fl(J,$e,he)}catch($e){let Wt=$e instanceof Error?$e.message:String($e);console.warn(`[job] ${y.jobId} worktree reset failed (${J.name}): ${Wt}`)}try{await vu()}catch(J){let $e=J instanceof Error?J.message:String(J);console.warn(`[job] ${y.jobId} delivery re-checkout failed: ${$e}`)}},aborted:()=>O||U.paused}),q=[];if(aC.has(y.role)&&se.length>0){let J=y.metadata??{},$e=typeof J.commitMessage=="string"?J.commitMessage:`${y.taskId}: changes`,Wt=y.contextRepo?.cloneUrl,Vn=ee?.env;if(!Wt||!Vn)throw new Error("delivery requested but "+(Wt?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let Zs=y.taskId.includes(":")?y.taskId.slice(y.taskId.indexOf(":")+1):y.taskId;for(let Nt of se){let Xn=await hy(Nt,$e);if(!Xn){console.log(`[job] ${y.jobId} ${Nt.name}: no changes \u2014 no delivery`);continue}let Qs=`codepipe/deliveries/${Zs}/${y.jobId}/${Nt.name}`;await gy(Nt,Xn,Qs,Wt,Vn),q.push({name:Nt.name,deliveryRef:Qs,deliverySha:Xn,baseSha:Nt.baseSha}),console.log(`[job] ${y.jobId} ${Nt.name}: delivered ${Xn.slice(0,10)} \u2192 ${Qs}`);let Ru=await yy(Nt,Xn);if(Ru.trim().length>0){let vb=At("display",`${Nt.name}.diff`),Iu=At(N.dir,vb);Aw(sC(Iu),{recursive:!0}),_w(Iu,Ru)}}}if(y.role==="resolve-conflict"&&q.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's SOLUTION.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let V;y.role==="build"&&(V=Ay(N.dir),console.log(`[job] ${y.jobId} build verdict: ok=${V.ok}`+(V.failedStep?` failedStep=${V.failedStep}`:"")));let ie;if(y.role==="code-review"){ie=Wl(N.dir),console.log(`[job] ${y.jobId} review verdict: approved=${ie.approved}`);try{let{parseChangedRanges:J,markFindingScope:$e}=await Promise.resolve().then(()=>(ql(),jy)),Wt=new Map;for(let Vn of se)try{let Zs=await $y(Vn,he);Wt.set(Vn.name,J(Zs))}catch{}$e(ie,Wt,se.length===1?se[0].name:void 0)}catch(J){console.warn(`[job] ${y.jobId} finding scope marking failed (non-fatal): ${String(J)}`)}}let rt;if(y.role==="council"){let{readCouncilVerdict:J}=await Promise.resolve().then(()=>(Rw(),Tw));rt=J(N.dir)??void 0,console.log(`[job] ${y.jobId} council: ${rt?"answered":"no verdict \u2014 task stops for a human"}`)}let ge;if(y.role==="testing"){try{let J=Ps(At(N.dir,"meta","test-result.json"),"utf-8");ge=JSON.parse(J)}catch{ge=void 0}console.log(`[job] ${y.jobId} test verdict: ${ge?"written":"none \u2014 proceeding to the PR"}`)}let Be;if(y.role==="observer"){let{readQueuePlan:J}=await Promise.resolve().then(()=>(Pw(),Cw));Be=J(N.dir)??void 0,console.log(`[job] ${y.jobId} queue plan: ${Be?"produced":"none \u2014 batch keeps the staged order"}`)}let Fr=_.artifactPaths.length>0?_.artifactPaths:N.listFiles(),Gr=Array.from(new Set(Fr)),zn;if(Ys)try{let J=y.role==="index"?["adr/SOURCES.md"]:y.role==="backfill"?["adr"]:[],$e=await Ry(Ys,J);$e.length>0&&(zn=$e,console.log(`[job] ${y.jobId} captured ${$e.length} knowledge file(s) for Context Repo`))}catch(J){let $e=J instanceof Error?J.message:String(J);console.warn(`[job] ${y.jobId} knowledge capture failed (non-fatal): ${$e}`)}let{artifacts:nt,omitted:Kr,dropped:Hr}=Oy(N.dir,Gr);for(let J of Kr)console.warn(`[job] ${y.jobId} artifact ${J.path} (${J.bytes} bytes) exceeded upload budget \u2014 content omitted`);Hr.length>0&&console.warn(`[job] ${y.jobId} artifact listing truncated: ${Hr.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let Wr={jobId:y.jobId,status:"succeeded",artifacts:nt,...zn?{contextWrites:zn}:{},...q.length>0?{deliveries:q}:{},log:cC(_.log),startedAt:Ne,finishedAt:new Date().toISOString(),usage:_.usage,..._.rateLimit?{rateLimit:_.rateLimit}:{},...V?{build:V}:{},...ie?{review:ie}:{},...Be!==void 0?{queuePlan:Be}:{},...rt!==void 0?{council:rt}:{},...ge!==void 0?{test:ge}:{}};if(O||U.paused)console.warn(`[job] ${y.jobId} skipping result upload \u2014 ${U.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await A.submitResult(Wr),console.log(`[job] ${y.jobId} done \u2014 uploaded ${Wr.artifacts.length} artifact(s):`);for(let J of Wr.artifacts){let $e=Buffer.from(J.contentBase64,"base64").length;console.log(` \xB7 ${J.path} (${$e} bytes)`)}Wr.artifacts.length===0&&console.warn(`[job] ${y.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(L){let _=L instanceof Error?L.message:String(L);if(U.paused)console.log(`[job] ${y.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(O)console.warn(`[job] ${y.jobId} failed after claim lost (${_}) \u2014 skipping result upload`);else{let q=zg(L),V=L instanceof ur,ie=L instanceof Pt;console.warn(q?`[job] ${y.jobId} failed: ${_} (Claude auth \u2014 token invalid/expired)`:V?`[job] ${y.jobId} failed: ${_} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:ie?`[job] ${y.jobId} failed: ${_} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${y.jobId} failed: ${_}`),await A.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:_},startedAt:Ne,finishedAt:new Date().toISOString(),...q?{authError:!0}:{},...V?{buildInconclusive:!0}:{},...ie?{reviewInconclusive:!0}:{}})}}finally{N.dispose()}}finally{clearInterval(ft),T&&clearInterval(T),H(),U.chatInbox?.close(),m.delete(y.jobId),G?.cleanup(),ee?.cleanup()}}function R(A,y){if(!A.credBundle)return{gitCreds:null,contextGitCreds:null};if(!y)return console.warn(`[job] ${A.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let U;try{U=JSON.parse(yn(y,A.credBundle).toString("utf-8"))}catch(ue){return console.warn(`[job] ${A.jobId} failed to open credBundle: ${ue instanceof Error?ue.message:String(ue)}`),{gitCreds:null,contextGitCreds:null}}let O=Ul(U);O&&console.log(`[job] ${A.jobId} cred bundle opened \u2014 git creds configured`);let G=ay(U,A.contextRepo.cloneUrl),ee={gitCreds:O,contextGitCreds:G};return U.claudeOauthToken&&(ee.claudeOauthToken=U.claudeOauthToken),ee}function v(A,y){return A.split(`
891
+ `).map(U=>y+U).join(`
892
+ `)}function b(A,y,U){let O=y[0]?.workspacePath??"";return A.replace(/\{\{codeDir\}\}/g,O).replace(/\{\{codeRoot\}\}/g,O?O.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,U??"")}function I(A,y){let U=y.includes("::")?"":y.split(":",2)[1]??"";if(!A||!U)return"";for(let O of["PLAN.md","SOLUTION.md"])try{return Ps(At(A,"tasks",U,O),"utf-8")}catch{}return""}function j(A,y,U){let O=A,G=U.includes("::")?"":U.split(":",2)[1]??"",ee=ue=>{if(!y||!G)return"";try{return Ps(At(y,"tasks",G,ue),"utf-8").trim()}catch{return""}};if(O.includes("{{planMd}}")||O.includes("{{solutionMd}}")){let ue=ee("PLAN.md")||ee("SOLUTION.md")||"(PLAN.md missing \u2014 proceed from the task description)";O=O.replace(/\{\{planMd\}\}/g,()=>ue),O=O.replace(/\{\{solutionMd\}\}/g,()=>ue)}if(O.includes("{{taskDescription}}")){let ue=ee("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";O=O.replace(/\{\{taskDescription\}\}/g,()=>ue)}return O=Gy(O,y),O}let K=A=>{if(p)return;p=!0,console.log(`
893
+ [${A}] shutting down`),d.abort();let y=[...m.keys()];for(let G of m.values())G.abort.abort();let U=new AbortController,O=setTimeout(()=>U.abort(),3e3);(async()=>(await Promise.all(y.map(async G=>{try{await u.releaseJob(G,`sandbox ${A}`,U.signal),console.log(`[${A}] released job ${G}`)}catch(ee){let ue=ee instanceof Error?ee.message:String(ee);console.warn(`[${A}] release failed: ${ue} (sweeper will reclaim)`)}})),clearTimeout(O),w.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>K("SIGINT")),process.on("SIGTERM",()=>K("SIGTERM"));let z=[$("implementation")];e.planningLane!==!1?z.push($("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(z)}var As,aC,jw=x(()=>{"use strict";B();dt();ac();Hg();ws();Xg();ty();Ge();gs();cy();Nl();Iy();Py();_y();ql();Ly();Fy();Hy();As=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),aC=new Set(["implement","resolve-conflict"])});var On=x(()=>{"use strict";Pg();jw();gs()});import{cancel as uC,isCancel as Ow,log as Ze,password as dC,text as pC}from"@clack/prompts";function fC(t){return Ow(t)&&(uC("aborted"),process.exit(1)),typeof t=="string"?t:""}function Lw(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function mC(t){let e=kc({redirectUri:wc,challenge:t.challenge,state:t.state});Ze.message(`Open this URL, approve the access, and paste the code shown:
894
+ ${e}`);let r=await pC({message:"Authorization code \u2014 blank to skip"});if(Ow(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=Xp(r,t.state);return await bc({code:n,verifier:t.verifier,state:t.state,redirectUri:wc})}catch(n){return Ze.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function hC(t){if(ic()?.claude?.oauthToken&&!t.farm)return Ze.message("Claude: this machine already has a shared OAuth token \u2014 the project will use it (set a project-specific one later with `codepipe login`)."),"";if(process.env.CODEPIPE_CLAUDE_AUTOLOGIN!=="1"||!process.stdout.isTTY)return null;Ze.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=bi(),n;try{n=await Jp({...r,openUrl:Pr,log:i=>Ze.message(i)})}catch(i){Ze.warn(`Browser sign-in didn't complete (${i instanceof Error?i.message:String(i)}) \u2014 trying the code-paste fallback.`);let s=await mC(r);if(s===null)return null;n=s}let o=await Bt(n.oauthToken);return o==="invalid"?(Ze.warn("Claude rejected the obtained token (401) \u2014 falling back to manual entry."),null):(Ze.success(`Claude: logged in \u2014 ${Lw(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function Mw(t){Ze.message(`Claude \u2014 the pipeline's agents run on your Claude subscription.
895
895
  In another terminal:
896
896
  1. install Claude Code \u2014 https://claude.com/claude-code
897
897
  2. run \`claude setup-token\`
898
898
  3. paste the token it prints (starts with sk-ant-) below`+(t.farm?`
899
- Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=aC(await iC({message:"Claude OAuth token \u2014 blank to skip"})).trim();if(!e)return Ze.warn(t.farm?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"";e.startsWith("sk-ant-")||Ze.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`.");let r=await Bt(e);return r==="invalid"?(Ze.warn("Claude refused this token. Run `claude setup-token` again and paste the new one."),Nw(t)):(Ze.success(`Claude: ${jw(e)} \u2014 ${r==="valid"?"verified":"check inconclusive, saved"}.`),e)}var Ow,Lw=x(()=>{"use strict";vi();ln();me();$c();Ow={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:lC,promptManual:Nw,validate:Bt}});function Mw(t){return Ow}async function Dw(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var Uw=x(()=>{"use strict";Lw()});async function Ln(t,e,r){return e.host==="github"?dC(t,e,r):e.host==="gitlab"?yC(t,e,r):kC(t,e,r)}async function Bw(t,e,r={}){let n=r.explain??!0,o=`${t.owner}/${t.name} not found on ${t.host}`;try{if(t.host==="github")return e.githubToken?(await Qe(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Fw(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 qe(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Gw(e.gitlabToken,t):o}}return e.bitbucket?(await At(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Kw(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 Fw(t,e){let r=!1;try{r=(await Qe(t,"GET",`/users/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitHub repo ${e.owner}/${e.name} does not exist, or the token cannot see it \u2014 check the name; a fine-grained PAT must be scoped to this repo (and approved in the org)`:`GitHub owner "${e.owner}" not found \u2014 check the org/user spelling`}async function Gw(t,e){let r=!1;try{r=(await qe(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 Kw(t,e){let r=!1;try{r=(await At(t,"GET",`/workspaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`Bitbucket repo ${e.owner}/${e.name} does not exist in workspace "${e.owner}" (which the credential can see) \u2014 check the repo name, or the API token lacks access to it`:`Bitbucket workspace "${e.owner}" is not visible to this credential \u2014 check the workspace name and the token's read:repository:bitbucket scope`}async function Qe(t,e,r,n){let o={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};n!==void 0&&(o.body=JSON.stringify(n),o.headers["Content-Type"]="application/json");let i=await fetch(uC+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 dC(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 pC(n,e,r),i=await fC(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=hn(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await mC(n,o.owner,o.name,a.path,i)||await hC(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 pC(t,e,r){let n=await Qe(t,"GET",`/repos/${e.owner}/${encodeURIComponent(e.name)}`);if(n.status===200&&n.data)return r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),{owner:n.data.owner.login,name:n.data.name,sshUrl:n.data.ssh_url};if(r.mode==="attach")throw new Error(`attach: ${await Fw(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Zl(t,e.owner),i=o?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${o?"org":"user"})`);let s=await Qe(t,"POST",i,{name:e.name,private:!0,auto_init:!0,description:`CodePipe Context Repo for project ${e.name}`});if(!s.data)throw new Error("GitHub createRepo: empty response");return{owner:s.data.owner.login,name:s.data.name,sshUrl:s.data.ssh_url}}async function Zl(t,e){let{status:r,data:n}=await Qe(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function fC(t,e,r){let{data:n}=await Qe(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function mC(t,e,r,n,o){let{status:i,data:s}=await Qe(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function hC(t,e,r,n,o,i,s,a){let c={message:i,content:Buffer.from(o,"utf-8").toString("base64"),branch:s};a&&(c.sha=a),await Qe(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function qe(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(gC+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 yC(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 qe(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 Gw(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await qe(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 qe(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 qe(n,"POST","/projects",d);if(!m.data)throw new Error("GitLab create project: empty response");i=m.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=hn(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let m=(await qe(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let f of m)l.add(f.path);if(m.length<100)break}let u=c.filter(p=>!l.has(p.path)).map(p=>({action:"create",file_path:p.path,content:p.content}));return u.length>0?await qe(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 At(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(wC+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 kC(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 At(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 Kw(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 At(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(p.status===404||!p.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);i=p.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=hn(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await At(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 At(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 uC,gC,wC,Ho=x(()=>{"use strict";Ar();uC="https://api.github.com";gC="https://gitlab.com/api/v4";wC="https://api.bitbucket.org/2.0"});function Ye(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=bC[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 bC,As=x(()=>{"use strict";bC={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as $C}from"node:crypto";import{existsSync as Hw,mkdirSync as vC,readFileSync as Ww,readdirSync as xC,rmSync as _s,writeFileSync as SC}from"node:fs";import{homedir as EC}from"node:os";import{dirname as TC,join as Ql}from"node:path";function qw(){return Ql(EC(),".codepipe","init-drafts")}function eu(t){let e=$C("sha256").update(t).digest("hex").slice(0,16);return Ql(qw(),`${e}.json`)}function Yw(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=RC)}function zw(t){let e=eu(t);if(!Hw(e))return null;try{let r=JSON.parse(Ww(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Yw(r.savedAt)?(_s(e,{force:!0}),null):r}catch{return null}}function tu(t){_s(eu(t),{force:!0})}function Vw(){let t=qw();if(Hw(t))for(let e of xC(t)){let r=Ql(t,e);try{let n=JSON.parse(Ww(r,"utf-8"));Yw(n.savedAt)&&_s(r,{force:!0})}catch{_s(r,{force:!0})}}}var RC,Mn,Xw=x(()=>{"use strict";RC=24*60*60*1e3;Mn=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(){tu(this.cwd)}persist(){let e=eu(this.cwd);vC(TC(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};SC(e,JSON.stringify(r,null,2)+`
900
- `,{mode:384})}}});function Jw(t){let e=[],r=[];return t.localClones&&(e.push({value:"map",label:"Project map from git history",hint:"local, a few seconds \u2014 a graph of files, tasks and their connections for the AI agent"}),r.push("map")),e.push(t.indexExists?{value:"index",label:"Re-index the context (an index already exists)",hint:"background job; keeps nothing if skipped"}:{value:"index",label:"Context index \u2014 knowledge and docs map",hint:"background job, recommended on first run"}),t.indexExists||r.push("index"),!t.indexExists&&t.reposNonEmpty&&(e.push({value:"backfill",label:"Reconstruct architecture decisions from the existing code",hint:"deep one-off AI analysis \u2014 proposes decision drafts you review before they become canonical"}),r.push("backfill")),{message:"Analyze the project? Pick what to run (space to toggle, enter to confirm):",options:e,initialValues:r,reindex:t.indexExists}}async function Zw(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 Qw=x(()=>{"use strict"});import{existsSync as IC}from"node:fs";import{join as CC}from"node:path";import{simpleGit as PC}from"simple-git";function NC(t){let e=t.split("/");return e[e.length-1]??t}function ek(t){if(t.filter(r=>!_C.test(NC(r))).length>AC)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(jC.has(n))return!0}return!1}async function OC(t){try{let r=(await PC(t).raw(["ls-files"])).split(`
901
- `).map(n=>n.trim()).filter(Boolean);return ek(r)}catch{return!1}}async function LC(t,e){if(t.host!=="github")return!1;let r=e.github?.token;if(!r)return!1;let n=t.defaultBranch??"main";try{let o=await fetch(`https://api.github.com/repos/${t.owner}/${t.repoName}/contents/?ref=${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(o.status!==200)return!1;let i=await o.json();return Array.isArray(i)?ek(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function tk(t,e){for(let r of t)try{let n=e.localRoot!=null?CC(e.localRoot,r.mountAs??r.name):null;if(n&&IC(n)?await OC(n):await LC(r,e.tokens))return!0}catch{}return!1}var AC,_C,jC,rk=x(()=>{"use strict";AC=3,_C=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,jC=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as nk}from"node:fs";import{join as ok}from"node:path";import{simpleGit as ik}from"simple-git";async function qo(t,e,r={}){let n=r.log??MC,o=[];for(let i of e){let s=ok(t,i.mountAs),a=di(i);if(!nk(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 ik().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(!nk(ok(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=ik(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!DC(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 DC(t,e){return sk(t)===sk(e)}function sk(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function Wo(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function ak(t={}){let e=_e();e||(console.error("no .codepipe/ workspace found in this directory or any parent. run `codepipe init` first."),process.exit(1)),console.log(`codepipe sync \u2014 project ${e.spec.projectId} (${e.spec.repos.length} repos)`);let r=await qo(e.root,e.spec.repos,{dryRun:t.dryRun===!0});for(let n of r)console.log(` ${n.mountAs}: ${n.status}${n.detail?` \u2014 ${n.detail}`:""}`)}var MC,js=x(()=>{"use strict";it();MC={info:t=>console.log(t),warn:t=>console.warn(t)}});import{simpleGit as UC}from"simple-git";async function ck(t,e,r){return t.host==="github"?BC(t,e,r):t.host==="gitlab"?FC(t,e,r):GC(t,e,r)}function ru(t){return new Error(`${t.owner}/${t.repoName} exists but is PUBLIC \u2014 a mirror holds the repository's full history and must be private. Make it private (or pick another name) and re-run`)}async function BC(t,e,r){let n=e.githubToken;if(!n)throw new Error("GitHub token required to create a github-hosted mirror");let o=await Qe(n,"GET",`/repos/${t.owner}/${encodeURIComponent(t.repoName)}`);if(o.status===200&&o.data){if(o.data.private!==!0)throw ru(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:o.data.ssh_url,created:!1}}let i=(await Qe(n,"GET","/user")).data?.login??"",s=i.toLowerCase()===t.owner.toLowerCase(),a=!s&&await Zl(n,t.owner);if(!s&&!a)throw new Error(`"${t.owner}" is neither the token's account ("${i}") nor an organization it can see \u2014 nothing was created. Use a GitHub username or organization (not an email)`);r.info(`creating mirror ${t.owner}/${t.repoName} (github, ${a?"org":"user"})`);let c=await Qe(n,"POST",a?`/orgs/${t.owner}/repos`:"/user/repos",{name:t.repoName,private:!0,auto_init:!1,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"});if(!c.data)throw new Error(`GitHub: could not create ${t.owner}/${t.repoName}`);return{spec:t,sshUrl:c.data.ssh_url,created:!0}}async function lk(t,e,r){try{return t==="github"?(await Qe(e,"GET","/user")).data?.login??null:t==="gitlab"?(await qe(e,"GET","/user")).data?.username??null:r?(await At({email:r,apiToken:e},"GET","/workspaces?role=contributor&pagelen=1")).data?.values?.[0]?.slug??null:null}catch{return null}}async function FC(t,e,r){let n=e.gitlabToken;if(!n)throw new Error("GitLab PAT required to create a gitlab-hosted mirror");let o=encodeURIComponent(`${t.owner}/${t.repoName}`),i=await qe(n,"GET",`/projects/${o}`);if(i.status===200&&i.data){if(i.data.visibility!=="private")throw ru(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:i.data.ssh_url_to_repo,created:!1}}let s={name:t.repoName,path:t.repoName,visibility:"private",initialize_with_readme:!1,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"};if((await qe(n,"GET","/user")).data?.username!==t.owner){let l=await qe(n,"GET",`/namespaces/${encodeURIComponent(t.owner)}`);if(l.status===404||!l.data)throw new Error(`GitLab namespace "${t.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);s.namespace_id=l.data.id}r.info(`creating mirror ${t.owner}/${t.repoName} (gitlab)`);let c=await qe(n,"POST","/projects",s);if(!c.data)throw new Error(`GitLab: could not create ${t.owner}/${t.repoName}`);return{spec:t,sshUrl:c.data.ssh_url_to_repo,created:!0}}async function GC(t,e,r){let n=e.bitbucket;if(!n)throw new Error("Bitbucket email + API token required to create a bitbucket-hosted mirror");let o=`/repositories/${t.owner}/${encodeURIComponent(t.repoName)}`,i=`git@bitbucket.org:${t.owner}/${t.repoName}.git`,s=await At(n,"GET",o);if(s.status===200&&s.data){if(s.data.is_private!==!0)throw ru(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:i,created:!1}}r.info(`creating mirror ${t.owner}/${t.repoName} (bitbucket)`);let a=await At(n,"POST",o,{json:{scm:"git",is_private:!0,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"}});if(a.status===404||!a.data?.slug)throw new Error(`Bitbucket cannot create ${t.owner}/${t.repoName} \u2014 check the workspace and that the credential may create repositories in it`);return{spec:t,sshUrl:i,created:!0}}async function uk(t,e,r){let n=UC(t);if((await n.raw(["rev-parse","--is-shallow-repository"])).trim()==="true")throw new Error("this clone is shallow \u2014 the mirror would be seeded with partial history. Run `git fetch --unshallow` first");if((await n.listRemote(["--heads",e])).trim().length>0)return r.info("mirror already has branches \u2014 leaving its content alone"),{seeded:!1};r.info("seeding mirror with the repository's branches and tags\u2026");let i=(await n.raw(["for-each-ref","refs/remotes/origin","--format=%(refname)"])).split(`
902
- `).map(a=>a.trim()).filter(a=>a.length>0&&a!=="refs/remotes/origin/HEAD");if(i.length===0)throw new Error("the local clone has no origin branches to seed from");let s=i.map(a=>`${a}:refs/heads/${a.slice(20)}`);return await n.push([e,...s]),await n.push([e,"--tags"]),{seeded:!0}}function dk(t){return`${t}-codepipe-mirror`}var pk=x(()=>{"use strict";Ho()});var yk={};Fe(yk,{ensureEmbeddedWorker:()=>Os,spawnWorkerProcess:()=>Ls,upCommand:()=>Ms,workerChildEnv:()=>gk,workerStartArgs:()=>hk});import{spawn as mk}from"node:child_process";import{existsSync as fk}from"node:fs";import{homedir as KC,hostname as HC}from"node:os";import{join as Ns}from"node:path";async function WC(t,e,r){let n=Le(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${vt(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 vh(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 ${vt(e)} still holds its token.
903
- 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`),op(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function qC(t,e,r){let n=Le(e)!==null;if(!await WC(t,e,r))return;console.log(n?"[up] re-registering the worker \u2014 requesting an account-issued token from HUB":"[up] no worker registration \u2014 requesting an account-issued token from HUB");let o;try{({secret:o}=await is(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 Or({hub:t.hubUrl,token:o,name:r.name??`${HC()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function YC(t,e){let r=Le(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=He(r.sealPublicKey);if(!Y(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=fi(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 Os(t,e,r){await qC(t,e,r),YC(t.projectId,e)}function hk(t){return[...t?["--profile",t]:[],"worker","start"]}function gk(t){let e={...t};for(let r of ic)delete e[r];return e}function Ls(t){let e=mk(process.execPath,[t.entry,...hk(t.profile)],{stdio:["ignore","pipe","pipe"],env:gk(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
904
- `))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function zC(t,e){let r=process.cwd(),n=Ns(r,ot);if(tn(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(fk(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 le(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 nu(r);if(!Kd(r,i?.parsed??null,o.repos)){console.log(`[up] this folder is neither empty nor a repo of ${t.projectId} \u2014 the context stays under ~/.codepipe/profiles`);return}let s=Y(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await ms({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=Ns(KC(),".codepipe",e?Ns("profiles",e,"context-config"):"context-config");if(Ei(c.contextDir,l,a),!fk(Ns(c.contextDir,"project.yaml"))){pn(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};go(c.contextDir,Rt(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 Ms(t){let{cfg:e,profile:r}=nn(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 zC(e,r),await Os(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 y=k=>h=>{for(let w of h.toString("utf-8").split(`
899
+ Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=fC(await dC({message:"Claude OAuth token \u2014 blank to skip"})).trim();if(!e)return Ze.warn(t.farm?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"";e.startsWith("sk-ant-")||Ze.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`.");let r=await Bt(e);return r==="invalid"?(Ze.warn("Claude refused this token. Run `claude setup-token` again and paste the new one."),Mw(t)):(Ze.success(`Claude: ${Lw(e)} \u2014 ${r==="valid"?"verified":"check inconclusive, saved"}.`),e)}var Dw,Uw=x(()=>{"use strict";$i();ln();fe();vc();Dw={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:hC,promptManual:Mw,validate:Bt}});function Bw(t){return Dw}async function Fw(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var Gw=x(()=>{"use strict";Uw()});async function Ln(t,e,r){return e.host==="github"?yC(t,e,r):e.host==="gitlab"?xC(t,e,r):EC(t,e,r)}async function Kw(t,e,r={}){let n=r.explain??!0,o=`${t.owner}/${t.name} not found on ${t.host}`;try{if(t.host==="github")return e.githubToken?(await Qe(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Hw(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 qe(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Ww(e.gitlabToken,t):o}}return e.bitbucket?(await _t(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await qw(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 Hw(t,e){let r=!1;try{r=(await Qe(t,"GET",`/users/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitHub repo ${e.owner}/${e.name} does not exist, or the token cannot see it \u2014 check the name; a fine-grained PAT must be scoped to this repo (and approved in the org)`:`GitHub owner "${e.owner}" not found \u2014 check the org/user spelling`}async function Ww(t,e){let r=!1;try{r=(await qe(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 qw(t,e){let r=!1;try{r=(await _t(t,"GET",`/workspaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`Bitbucket repo ${e.owner}/${e.name} does not exist in workspace "${e.owner}" (which the credential can see) \u2014 check the repo name, or the API token lacks access to it`:`Bitbucket workspace "${e.owner}" is not visible to this credential \u2014 check the workspace name and the token's read:repository:bitbucket scope`}async function Qe(t,e,r,n){let o={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};n!==void 0&&(o.body=JSON.stringify(n),o.headers["Content-Type"]="application/json");let i=await fetch(gC+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 yC(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 wC(n,e,r),i=await kC(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=hn(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await bC(n,o.owner,o.name,a.path,i)||await $C(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 wC(t,e,r){let n=await Qe(t,"GET",`/repos/${e.owner}/${encodeURIComponent(e.name)}`);if(n.status===200&&n.data)return r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),{owner:n.data.owner.login,name:n.data.name,sshUrl:n.data.ssh_url};if(r.mode==="attach")throw new Error(`attach: ${await Hw(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await tu(t,e.owner),i=o?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${o?"org":"user"})`);let s=await Qe(t,"POST",i,{name:e.name,private:!0,auto_init:!0,description:`CodePipe Context Repo for project ${e.name}`});if(!s.data)throw new Error("GitHub createRepo: empty response");return{owner:s.data.owner.login,name:s.data.name,sshUrl:s.data.ssh_url}}async function tu(t,e){let{status:r,data:n}=await Qe(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function kC(t,e,r){let{data:n}=await Qe(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function bC(t,e,r,n,o){let{status:i,data:s}=await Qe(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function $C(t,e,r,n,o,i,s,a){let c={message:i,content:Buffer.from(o,"utf-8").toString("base64"),branch:s};a&&(c.sha=a),await Qe(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function qe(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(vC+r,o),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?JSON.stringify(a.message):s;throw new Error(`GitLab ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function xC(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 qe(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 Ww(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await qe(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 qe(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 qe(n,"POST","/projects",d);if(!m.data)throw new Error("GitLab create project: empty response");i=m.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=hn(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let m=(await qe(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let f of m)l.add(f.path);if(m.length<100)break}let u=c.filter(p=>!l.has(p.path)).map(p=>({action:"create",file_path:p.path,content:p.content}));return u.length>0?await qe(n,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:u}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}async function _t(t,e,r,n){let o={method:e,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${t.apiToken}`).toString("base64"),"User-Agent":"codepipe-cli"}};n?.json!==void 0?(o.body=JSON.stringify(n.json),o.headers["Content-Type"]="application/json"):n?.form&&(o.body=n.form);let i=await fetch(SC+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 EC(t,e,r){let n=r.bitbucket;if(!n)throw new Error("Bitbucket account email + API token required to provision a bitbucket-hosted Context Repo \u2014 provide them during `codepipe init`");let o=`/repositories/${e.owner}/${encodeURIComponent(e.name)}`,i,s=await _t(n,"GET",o);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await qw(n,e)} (attach joins an existing Context Repo and never creates one)`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let p=await _t(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(p.status===404||!p.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);i=p.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=hn(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await _t(n,"GET",`${o}/src/${encodeURIComponent(a)}/${p.path}?format=meta`)).status===404&&l.push(p);if(l.length>0){let p=new URLSearchParams;p.set("message","chore(codepipe): scaffold context repo files"),p.set("branch",a);for(let m of l)p.set(m.path,m.content);if((await _t(n,"POST",`${o}/src`,{form:p})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let u=i.links?.clone?.find(p=>p.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:u??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var gC,vC,SC,Ho=x(()=>{"use strict";Ar();gC="https://api.github.com";vC="https://gitlab.com/api/v4";SC="https://api.bitbucket.org/2.0"});function Ye(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=TC[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 TC,_s=x(()=>{"use strict";TC={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as RC}from"node:crypto";import{existsSync as Yw,mkdirSync as IC,readFileSync as zw,readdirSync as CC,rmSync as js,writeFileSync as PC}from"node:fs";import{homedir as AC}from"node:os";import{dirname as _C,join as ru}from"node:path";function Vw(){return ru(AC(),".codepipe","init-drafts")}function nu(t){let e=RC("sha256").update(t).digest("hex").slice(0,16);return ru(Vw(),`${e}.json`)}function Xw(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=jC)}function Jw(t){let e=nu(t);if(!Yw(e))return null;try{let r=JSON.parse(zw(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Xw(r.savedAt)?(js(e,{force:!0}),null):r}catch{return null}}function ou(t){js(nu(t),{force:!0})}function Zw(){let t=Vw();if(Yw(t))for(let e of CC(t)){let r=ru(t,e);try{let n=JSON.parse(zw(r,"utf-8"));Xw(n.savedAt)&&js(r,{force:!0})}catch{js(r,{force:!0})}}}var jC,Mn,Qw=x(()=>{"use strict";jC=24*60*60*1e3;Mn=class{constructor(e,r){this.cwd=e;this.answers=r?.answers?{...r.answers}:{}}answers;get(e){return this.answers[e]}set(e,r){this.answers[e]=r,this.persist()}delete(e){delete this.answers[e],this.persist()}async ask(e,r){if(e in this.answers)return this.answers[e];let n=await r();return this.set(e,n),n}clear(){ou(this.cwd)}persist(){let e=nu(this.cwd);IC(_C(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};PC(e,JSON.stringify(r,null,2)+`
900
+ `,{mode:384})}}});function ek(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 tk(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 rk=x(()=>{"use strict"});import{existsSync as NC}from"node:fs";import{join as OC}from"node:path";import{simpleGit as LC}from"simple-git";function BC(t){let e=t.split("/");return e[e.length-1]??t}function nk(t){if(t.filter(r=>!DC.test(BC(r))).length>MC)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(UC.has(n))return!0}return!1}async function FC(t){try{let r=(await LC(t).raw(["ls-files"])).split(`
901
+ `).map(n=>n.trim()).filter(Boolean);return nk(r)}catch{return!1}}async function GC(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)?nk(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function ok(t,e){for(let r of t)try{let n=e.localRoot!=null?OC(e.localRoot,r.mountAs??r.name):null;if(n&&NC(n)?await FC(n):await GC(r,e.tokens))return!0}catch{}return!1}var MC,DC,UC,ik=x(()=>{"use strict";MC=3,DC=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,UC=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as sk}from"node:fs";import{join as ak}from"node:path";import{simpleGit as ck}from"simple-git";async function qo(t,e,r={}){let n=r.log??KC,o=[];for(let i of e){let s=ak(t,i.mountAs),a=Wd(i);if(!sk(s)){if(r.dryRun){n.info(`would clone ${a} \u2192 ${i.mountAs}/`),o.push({mountAs:i.mountAs,status:"cloned",detail:"(dry-run)"});continue}try{n.info(`cloning ${a} \u2192 ${i.mountAs}/`),await ck().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(!sk(ak(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=ck(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!HC(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 HC(t,e){return lk(t)===lk(e)}function lk(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function Wo(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function uk(t={}){let e=Ae();e||(console.error("no .codepipe/ workspace found in this directory or any parent. run `codepipe init` first."),process.exit(1)),console.log(`codepipe sync \u2014 project ${e.spec.projectId} (${e.spec.repos.length} repos)`);let r=await qo(e.root,e.spec.repos,{dryRun:t.dryRun===!0});for(let n of r)console.log(` ${n.mountAs}: ${n.status}${n.detail?` \u2014 ${n.detail}`:""}`)}var KC,Ns=x(()=>{"use strict";kt();KC={info:t=>console.log(t),warn:t=>console.warn(t)}});import{simpleGit as WC}from"simple-git";async function dk(t,e,r){return t.host==="github"?qC(t,e,r):t.host==="gitlab"?YC(t,e,r):zC(t,e,r)}function iu(t){return new Error(`${t.owner}/${t.repoName} exists but is PUBLIC \u2014 a mirror holds the repository's full history and must be private. Make it private (or pick another name) and re-run`)}async function qC(t,e,r){let n=e.githubToken;if(!n)throw new Error("GitHub token required to create a github-hosted mirror");let o=await Qe(n,"GET",`/repos/${t.owner}/${encodeURIComponent(t.repoName)}`);if(o.status===200&&o.data){if(o.data.private!==!0)throw iu(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:o.data.ssh_url,created:!1}}let i=(await Qe(n,"GET","/user")).data?.login??"",s=i.toLowerCase()===t.owner.toLowerCase(),a=!s&&await tu(n,t.owner);if(!s&&!a)throw new Error(`"${t.owner}" is neither the token's account ("${i}") nor an organization it can see \u2014 nothing was created. Use a GitHub username or organization (not an email)`);r.info(`creating mirror ${t.owner}/${t.repoName} (github, ${a?"org":"user"})`);let c=await Qe(n,"POST",a?`/orgs/${t.owner}/repos`:"/user/repos",{name:t.repoName,private:!0,auto_init:!1,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"});if(!c.data)throw new Error(`GitHub: could not create ${t.owner}/${t.repoName}`);return{spec:t,sshUrl:c.data.ssh_url,created:!0}}async function pk(t,e,r){try{return t==="github"?(await Qe(e,"GET","/user")).data?.login??null:t==="gitlab"?(await qe(e,"GET","/user")).data?.username??null:r?(await _t({email:r,apiToken:e},"GET","/workspaces?role=contributor&pagelen=1")).data?.values?.[0]?.slug??null:null}catch{return null}}async function YC(t,e,r){let n=e.gitlabToken;if(!n)throw new Error("GitLab PAT required to create a gitlab-hosted mirror");let o=encodeURIComponent(`${t.owner}/${t.repoName}`),i=await qe(n,"GET",`/projects/${o}`);if(i.status===200&&i.data){if(i.data.visibility!=="private")throw iu(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:i.data.ssh_url_to_repo,created:!1}}let s={name:t.repoName,path:t.repoName,visibility:"private",initialize_with_readme:!1,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"};if((await qe(n,"GET","/user")).data?.username!==t.owner){let l=await qe(n,"GET",`/namespaces/${encodeURIComponent(t.owner)}`);if(l.status===404||!l.data)throw new Error(`GitLab namespace "${t.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);s.namespace_id=l.data.id}r.info(`creating mirror ${t.owner}/${t.repoName} (gitlab)`);let c=await qe(n,"POST","/projects",s);if(!c.data)throw new Error(`GitLab: could not create ${t.owner}/${t.repoName}`);return{spec:t,sshUrl:c.data.ssh_url_to_repo,created:!0}}async function zC(t,e,r){let n=e.bitbucket;if(!n)throw new Error("Bitbucket email + API token required to create a bitbucket-hosted mirror");let o=`/repositories/${t.owner}/${encodeURIComponent(t.repoName)}`,i=`git@bitbucket.org:${t.owner}/${t.repoName}.git`,s=await _t(n,"GET",o);if(s.status===200&&s.data){if(s.data.is_private!==!0)throw iu(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:i,created:!1}}r.info(`creating mirror ${t.owner}/${t.repoName} (bitbucket)`);let a=await _t(n,"POST",o,{json:{scm:"git",is_private:!0,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"}});if(a.status===404||!a.data?.slug)throw new Error(`Bitbucket cannot create ${t.owner}/${t.repoName} \u2014 check the workspace and that the credential may create repositories in it`);return{spec:t,sshUrl:i,created:!0}}async function fk(t,e,r){let n=WC(t);if((await n.raw(["rev-parse","--is-shallow-repository"])).trim()==="true")throw new Error("this clone is shallow \u2014 the mirror would be seeded with partial history. Run `git fetch --unshallow` first");if((await n.listRemote(["--heads",e])).trim().length>0)return r.info("mirror already has branches \u2014 leaving its content alone"),{seeded:!1};r.info("seeding mirror with the repository's branches and tags\u2026");let i=(await n.raw(["for-each-ref","refs/remotes/origin","--format=%(refname)"])).split(`
902
+ `).map(a=>a.trim()).filter(a=>a.length>0&&a!=="refs/remotes/origin/HEAD");if(i.length===0)throw new Error("the local clone has no origin branches to seed from");let s=i.map(a=>`${a}:refs/heads/${a.slice(20)}`);return await n.push([e,...s]),await n.push([e,"--tags"]),{seeded:!0}}function mk(t){return`${t}-codepipe-mirror`}var hk=x(()=>{"use strict";Ho()});var bk={};Fe(bk,{ensureEmbeddedWorker:()=>Ls,spawnWorkerProcess:()=>Ms,upCommand:()=>Ds,workerChildEnv:()=>kk,workerStartArgs:()=>wk});import{spawn as yk}from"node:child_process";import{existsSync as gk}from"node:fs";import{homedir as VC,hostname as XC}from"node:os";import{join as Os}from"node:path";async function JC(t,e,r){let n=Me(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${xt(e)} points at a different HUB (${n.hubUrl}). Re-register it explicitly: codepipe worker register --hub ${t.hubUrl} --token \u2026 --force`);let o;try{o=await Sh(t.hubUrl.replace(/\/$/,""),n.token)}catch(i){return console.warn(`[up] could not verify the worker registration (${i instanceof Error?i.message:String(i)}) \u2014 continuing`),!1}if(o==="unsupported")return console.log(`[up] worker already registered as ${n.sandboxId} (${n.name})`),!1;if(o==="ok")return console.log(`[up] worker already registered as ${n.sandboxId} (${n.name})`),!1;if(!r.reregister)throw new Error(`the HUB no longer knows this worker registration (${n.sandboxId}) \u2014 it was removed on ${t.hubUrl}, but ${xt(e)} still holds its token.
903
+ Re-register it: codepipe up --reregister (or delete that file and run codepipe up)`);return console.log(`[up] --reregister: the HUB no longer knows ${n.sandboxId} \u2014 replacing the registration`),sp(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function ZC(t,e,r){let n=Me(e)!==null;if(!await JC(t,e,r))return;console.log(n?"[up] re-registering the worker \u2014 requesting an account-issued token from HUB":"[up] no worker registration \u2014 requesting an account-issued token from HUB");let o;try{({secret:o}=await os(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof W&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof W&&i.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):i instanceof W?i:new Error(`cannot reach the HUB at ${t.hubUrl} (${i instanceof Error?i.message:String(i)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await Or({hub:t.hubUrl,token:o,name:r.name??`${XC()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function QC(t,e){let r=Me(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=He(r.sealPublicKey);if(!Y(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=pi(t,r.sandboxId,n);if(o==="mismatch")throw new Error(`pinned fingerprint for ${r.sandboxId} differs from the local worker key (${n}). The registration was replaced \u2014 remove the stale pin from the project secrets to accept the new key.`);console.log(`[up] worker key ${o==="pinned"?"auto-pinned":"already pinned"} for ${t} (${n})`)}async function Ls(t,e,r){await ZC(t,e,r),QC(t.projectId,e)}function wk(t){return[...t?["--profile",t]:[],"worker","start"]}function kk(t){let e={...t};for(let r of sc)delete e[r];return e}function Ms(t){let e=yk(process.execPath,[t.entry,...wk(t.profile)],{stdio:["ignore","pipe","pipe"],env:kk(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
904
+ `))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function eP(t,e){let r=process.cwd(),n=Os(r,it);if(tn(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(gk(n)){console.warn(`[up] ${n} exists but is not this project's workspace \u2014 the context stays under ~/.codepipe/profiles`);return}let o;try{o=await ae(t.hubUrl,t.cliToken,t.projectId)}catch(u){console.warn(`[up] could not fetch the project summary (${u instanceof Error?u.message:String(u)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await su(r);if(!Hd(r,i?.parsed??null,o.repos)){console.log(`[up] this folder is neither empty nor a repo of ${t.projectId} \u2014 the context stays under ~/.codepipe/profiles`);return}let s=Y(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await hs({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=Os(VC(),".codepipe",e?Os("profiles",e,"context-config"):"context-config");if(Si(c.contextDir,l,a),!gk(Os(c.contextDir,"project.yaml"))){pn(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};go(c.contextDir,It(u,!0,s?.youtrack?.url)),console.log("[up] local project config seeded with defaults \u2014 review .codepipe/project.yaml")}console.log(`[up] project context materialized \u2192 ${n}`)}async function Ds(t){let{cfg:e,profile:r}=nn(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 eP(e,r),await Ls(e,r,t);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(m,f)=>{let g=k=>h=>{for(let w of h.toString("utf-8").split(`
905
905
  `))w.length>0&&k.write(`${f} ${w}
906
- `)};m.stdout?.on("data",y(process.stdout)),m.stderr?.on("data",y(process.stderr))},i=(m,f)=>{let y=mk(process.execPath,[n,...f],{stdio:["ignore","pipe","pipe"],env:process.env});return o(y,m),y};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=Ls({entry:n,profile:r,onLine:m=>process.stdout.write(`[worker] ${m}
906
+ `)};m.stdout?.on("data",g(process.stdout)),m.stderr?.on("data",g(process.stderr))},i=(m,f)=>{let g=yk(process.execPath,[n,...f],{stdio:["ignore","pipe","pipe"],env:process.env});return o(g,m),g};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=Ms({entry:n,profile:r,onLine:m=>process.stdout.write(`[worker] ${m}
907
907
  `)}),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,u=m=>{if(!l){l=!0,console.log(`
908
- [up] ${m} \u2014 stopping both roles`);for(let{child:f}of c)f.exitCode===null&&f.kill(m);setTimeout(()=>{for(let{name:f,child:y}of c)y.exitCode===null&&(console.warn(`[up] ${f} did not stop \u2014 SIGKILL`),y.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:m,child:f})=>new Promise(y=>{f.on("exit",(k,h)=>y({name:m,code:k??(h?1:0)}))})),d=await Promise.race(p);l||(console.log(`[up] ${d.name} exited (code ${d.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(p),process.exit(d.code)}var Ds=x(()=>{"use strict";dt();On();Ke();Ft();Il();Ar();Ne();me();it();Yo()});import{existsSync as Dr,mkdirSync as kk,readFileSync as Us,readdirSync as VC,writeFileSync as bk}from"node:fs";import{join as ze,resolve as $k}from"node:path";import{setTimeout as ou}from"node:timers/promises";import{cancel as vk,confirm as zo,intro as xk,isCancel as au,log as C,multiselect as XC,outro as iu,password as Vo,select as pt,spinner as cu,text as be}from"@clack/prompts";import{simpleGit as Dn}from"simple-git";function he(t){vk(t),process.exit(1)}function ke(t){return au(t)&&he("aborted"),t}function de(t){return au(t)&&he("aborted"),typeof t=="string"?t:""}async function Sk(t={}){xk("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Vw();let r=zw(e),n,o=!1;r&&Object.keys(r.answers).length>0?ke(await zo({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(C.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new Mn(e,r),o=!0):(tu(e),n=new Mn(e)):n=new Mn(e);let i=t.force===!0?null:await nu(e),s=await n.ask("target",async()=>ke(await pt({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i??(t.force===!0?null:await ZC(e,n)),a?C.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):o&&n.get("contextRepo")!==void 0||Tk(e,t.force===!0));let c=await n.ask("hubUrl",async()=>de(await be({message:"HUB URL",placeholder:ht,initialValue:Q("HUB_URL")??ht,validate:P=>P.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>Un()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>Bn(c,l)),d=null;s==="farm"&&(d=await JC(c,u));let m=a?tP(a.parsed.repoName):"",f=await n.ask("projectId",async()=>de(await be({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:P=>Yt.test(P.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),y=await n.ask("projectName",async()=>de(await be({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:P=>P.trim().length>0?void 0:"required"})).trim()),k=await n.ask("language",()=>dP()),h=await n.ask("automationLevel",async()=>ke(await pt({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),$=(s==="farm"?"no":await n.ask("mirrorChoice",async()=>ke(await pt({message:"how much access should CodePipe have to your repositories?",options:[{value:"no",label:"read and write \u2014 branches and pull requests go into your repositories"},{value:"yes",label:"read only \u2014 CodePipe mirrors them and works in the mirrors",hint:"a mirror is a full copy of the history, in the account you choose next"}],initialValue:"no"}))))==="yes";$&&C.message("read-only token tip: if you want CodePipe to review pull requests people open in your repositories, the token also needs PR-comment permission (GitHub: Pull requests write; Bitbucket: pullrequest:write). Code stays read-only either way.");let S=await n.ask("trackerProvider",async()=>ke(await pt({message:"task tracker",options:[{value:"internal",label:"built-in \u2014 CodePipe tracks tasks itself (no external tracker needed)"},{value:"youtrack",label:"YouTrack \u2014 connect an existing YouTrack project"}],initialValue:"internal"}))),T=S==="internal",v=null,b,R=!0;if(T){let P,L=cu();L.start("checking task-key prefixes on your account\u2026");try{P=await xh(c,u,{excludeProjectId:f}),L.stop("prefixes checked")}catch{L.stop("could not reach the HUB",1),he("Could not verify the task-key prefix against your account \u2014 the HUB is unreachable right now. Prefix uniqueness is required, so init can't continue. Check your connection and re-run `codepipe init` later.")}let fe=ec(Qa(y),P);b=await n.ask("trackerPrefix",async()=>de(await be({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:fe,initialValue:fe,validate:ge=>{let mt=ge.trim();if(!Er.test(mt))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(P.has(mt.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else v=await n.ask("youtrack",()=>Ok()),b=await n.ask("youtrackProjectKey",async()=>de(await be({message:"YouTrack project key",placeholder:"DEV",validate:P=>P.trim().length>0?void 0:"required"})).trim()),R=await n.ask("youtrackWrites",async()=>ke(await zo({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let j=n.get("tokens")??{},G=()=>n.set("tokens",j),X=await n.ask("repos",()=>iP(j,l,a,{onCred:G,initial:n.get("reposPartial")??[],onProgress:P=>n.set("reposPartial",P)}));n.delete("reposPartial");let A=null,g="",U="";if($){let P=ke(await n.ask("mirrorHost",async()=>ke(await pt({message:"where should the mirrors live? (your Context Repo will default there too)",options:["github","gitlab","bitbucket"].map(ce=>({value:ce,label:ce===X[0]?.host?`${ce} (same as your repositories)`:ce})),initialValue:X[0]?.host??"github"}))));g=de(await n.ask("mirrorToken",async()=>ke(await Vo({message:`token that may CREATE and PUSH repositories on ${P}`})))).trim(),P==="bitbucket"&&(U=de(await n.ask("mirrorEmail",async()=>ke(await be({message:"Atlassian account email for that token",...j.bitbucket?.email?{placeholder:j.bitbucket.email,defaultValue:j.bitbucket.email}:{}})))).trim());let L=await lk(P,g,U||void 0),fe=P==="bitbucket"?"workspace slug":"username or organization (not an email)",mt=de(await n.ask("mirrorOwnerLogin",async()=>ke(await be({message:`account for the mirrors \u2014 ${P} ${fe}`,...L?{placeholder:L,defaultValue:L}:{},validate:ce=>{let ne=(ce??"").trim();if(!ne&&!L)return"required";if(ne.includes("@"))return`that looks like an email \u2014 a ${P} ${fe} is expected`;if(/\s/.test(ne))return"no spaces"}})))).trim()||L||"";if(!mt||mt.includes("@")){vk("mirrors need a host account to live in (a username/organization, not an email)");return}A={host:P,owner:mt}}let N=await sP(await n.ask("contextRepo",()=>_k(f,X,j,l,A??void 0)),f,X,j,l,G,P=>n.set("contextRepo",P),A??void 0),{spec:H,mode:ee}=N,se;T||(C.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),se=await n.ask("assigneeLogin",async()=>de(await be({message:"your YouTrack login (the assignee value)",...v?.login?{initialValue:v.login}:{},validate:P=>P.trim().length>0?void 0:"required"})).trim()));let jt=await n.ask("llmProvider",async()=>{for(;;){if(ke(await pt({message:"LLM provider",options:[{value:"claude",label:"Claude",hint:"recommended"},{value:"codex",label:"Codex",hint:"coming soon"}],initialValue:"claude"}))==="claude")return"claude";C.warn("Codex support is coming soon \u2014 pick Claude for now.")}}),ft=jt==="claude"?await n.ask("claudeToken",()=>Dw(Mw("claude"),{farm:s==="farm"})):"",Ue;if(ft){let P=await qp(ft);if(P){let L=Sa(P);L&&(Ue=L,C.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${L} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let M={projectId:f,name:y,automationLevel:h,repos:X,trackerProvider:S,youtrackProjectKey:b,language:k};C.step(`${ee==="attach"?"attaching to":"provisioning"} Context Repo ${H.owner}/${H.name} (${H.host})\u2026`);let F;try{F=await Ln(M,H,{...jk(j),youtrackWrites:R,...v?{trackerUrl:v.url}:{},mode:ee,log:{info:P=>C.message(P),warn:P=>C.warn(P)}})}catch(P){he(`Context Repo provisioning failed: ${P instanceof Error?P.message:String(P)}`)}M.contextRepo=F,C.success(`Context Repo ready: ${F.owner}/${F.name}@${F.branch}`),C.step(`registering project on ${c}\u2026`);let D;try{D=await ir(c,u,M)}catch(P){if(P instanceof K&&P.status===409){C.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{D=await le(c,u,f)}catch(L){throw L instanceof K&&he(`HUB \u2192 ${L.status} ${L.message}`),L}}else if(P instanceof K&&P.status===401)n.delete("cliToken"),he("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(P instanceof K)he(`HUB \u2192 ${P.status} ${P.message}`);else throw P}let z=D.contextRepo??F;C.success(`project ${D.projectId} ready (${D.provisioningStatus})`);let W=v?{url:v.url,token:v.token}:void 0;if(s==="farm"){let P=d,L={...j,...ft?{claude:{oauthToken:ft}}:{},...W?{youtrack:W}:{}},fe=j.github?.token;if(z.host==="github"&&fe)try{let ne=pg(`devpipe-${f}`);await fg(z,fe,ne.publicKey,`devpipe-${f}`),L.contextSsh={privateKey:ne.privateKey},C.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(ne){C.warn(`could not set up Context Repo SSH deploy key (${ne instanceof Error?ne.message:String(ne)}); the farm will fall back to the token path.`)}let ge={projectId:f,config:{hubUrl:c,cliToken:u,projectId:f},secrets:L,contextRepo:z,projectConfig:Rt(M,R,v?.url,se||void 0,jt,Ue)},mt=Gt(P.farm.publicKey,JSON.stringify(ge));C.step(`handing project ${f} to farm ${P.farm.name}\u2026`);let ce;try{ce=await os(c,u,P.farm.farmId,{projectId:f,sealedBundle:mt})}catch(ne){throw ne instanceof K&&he(ne.status===409?`farm ${P.farm.name} is offline \u2014 start it and re-run.`:ne.status===504?`farm ${P.farm.name} did not respond in time.`:`HUB \u2192 ${ne.status} ${ne.message}`),ne}ce.ok||he(`farm rejected provisioning: ${ce.error??"unknown error"}`),await su(c,u,f,z,fe,D.repos,null,j),n.clear(),iu(`done. project ${f} is now hosted on farm ${P.farm.name} (daemon ${ce.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}Nk(j),await Ck(e,z.cloneUrl,z.branch),Ak(e);try{fn(ze(e,ot),e,{info:P=>C.message(P),warn:P=>C.warn(P)})}catch(P){C.warn(`skills materialize failed \u2014 ${P instanceof Error?P.message:String(P)}`)}a&&await nP(e);{let P=ze(e,ot);pn(P);let L=Rt(M,R,v?.url,se||void 0,jt,Ue),fe=go(P,L);fe.length>0&&C.success(`local project config \u2192 .codepipe/{${fe.join(", ")}}`),tr(f,L,{info:ge=>C.message(ge),warn:ge=>C.warn(ge)})}await Pk(e,D.repos);let E=!1;if($&&A&&(E=await oP(e,ze(e,ot),D.repos,{host:A.host,owner:A.owner,token:g,...U?{email:U}:{}}),E)){let P=ze(e,ot);tr(f,{projectYaml:Us(ze(P,"project.yaml"),"utf-8"),regimenYaml:Us(ze(P,"regimen.yaml"),"utf-8")},{info:L=>C.message(L),warn:L=>C.warn(L)})}let I={hubUrl:c,cliToken:u,projectId:f,...j,...ft?{claude:{oauthToken:ft}}:{},...W?{youtrack:W}:{},...E?{mirrorWrite:{token:g,host:A.host,...U?{email:U}:{}}}:{}};ue(I),Ut({hubUrl:c,cliToken:u,projectId:f,accountEmail:p},f),C.success(`secrets \u2192 ${Et(f)}`),await su(c,u,f,z,j.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,D.repos,e,j),n.clear();let te=`${c}/?project=${encodeURIComponent(f)}`;Pr(te),iu(`done. your project on the dashboard (sign in there to work with it):
909
- ${te}
910
- starting codepipe up \u2014 the CLI daemon and an agent worker, with their logs on screen. Ctrl+C to stop (restart anytime with \`codepipe up\` from this folder).`);let{upCommand:ae}=await Promise.resolve().then(()=>(Ds(),yk));await ae({profile:void 0})}async function su(t,e,r,n,o,i=[],s=null,a={}){let c=await Zw(n,o),l=!1;if(!c)try{l=await tk(i,{localRoot:s,tokens:a})}catch{l=!1}let u=Jw({indexExists:c,localClones:s!==null,reposNonEmpty:l}),p=await XC({message:u.message,options:u.options,initialValues:u.initialValues,required:!1});if(au(p))return;let d=new Set(p);if(d.has("map")&&s!==null)try{let m=_e(s);if(!m)throw new Error("workspace not found");let{bootstrapWorkspaceModel:f}=await Promise.resolve().then(()=>(Lo(),ds)),y=await f(m,void 0,{onLog:k=>C.message(k)});C.success(`project map ready: ${y.events} task events mined from history`)}catch(m){C.warn(`could not build the project map: ${m instanceof Error?m.message:String(m)}. Registration is not affected \u2014 run \`codepipe model bootstrap\` later.`)}if(d.has("backfill"))try{let{jobId:m}=await Oo(t,e,r,{reindex:!1,backfill:!0});C.success(`retrospective architecture analysis queued (job ${m}); decision drafts will appear on the project card for review once a SANDBOX picks up the job.`)}catch(m){C.warn(`could not start the retrospective analysis: ${m instanceof Error?m.message:String(m)}. Registration is not affected.`)}if(d.has("index"))try{let{jobId:m}=await Oo(t,e,r,{reindex:u.reindex});C.success(`indexing queued (job ${m}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(m){C.warn(`could not start indexing: ${m instanceof Error?m.message:String(m)}. You can retry later \u2014 registration is not affected.`)}}async function JC(t,e){let r;try{r=await kh(t,e)}catch(c){throw c instanceof K&&he(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&he("no farm is available to this account. Farms are assigned by the operator \u2014 ask them to assign one to you (or, if you run your own farm host: `codepipe-farm register --hub <url> --token <token>` and `codepipe-farm start`, then have the operator assign it).");let o=ke(await pt({message:"target farm",options:n.map(c=>({value:c.farmId,label:`${c.name}${c.online?"":" (offline)"} \u2014 ${c.keyFingerprint??"no fingerprint"}`}))})),i=n.find(c=>c.farmId===o),s;try{s=rs(i.farmId,i.publicKey)}catch(c){he(c instanceof Error?c.message:String(c))}return ke(await zo({message:`confirm farm ${i.name} cred-channel fingerprint:
908
+ [up] ${m} \u2014 stopping both roles`);for(let{child:f}of c)f.exitCode===null&&f.kill(m);setTimeout(()=>{for(let{name:f,child:g}of c)g.exitCode===null&&(console.warn(`[up] ${f} did not stop \u2014 SIGKILL`),g.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:m,child:f})=>new Promise(g=>{f.on("exit",(k,h)=>g({name:m,code:k??(h?1:0)}))})),d=await Promise.race(p);l||(console.log(`[up] ${d.name} exited (code ${d.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(p),process.exit(d.code)}var Us=x(()=>{"use strict";dt();On();Ke();Ft();Al();Ar();je();fe();kt();Yo()});import{existsSync as Dr,mkdirSync as vk,readFileSync as Bs,readdirSync as tP,writeFileSync as xk}from"node:fs";import{join as ze,resolve as Sk}from"node:path";import{setTimeout as au}from"node:timers/promises";import{cancel as Ek,confirm as zo,intro as Tk,isCancel as uu,log as P,multiselect as rP,outro as cu,password as Vo,select as pt,spinner as du,text as ke}from"@clack/prompts";import{simpleGit as Dn}from"simple-git";function me(t){Ek(t),process.exit(1)}function we(t){return uu(t)&&me("aborted"),t}function le(t){return uu(t)&&me("aborted"),typeof t=="string"?t:""}async function Rk(t={}){Tk("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Zw();let r=Jw(e),n,o=!1;r&&Object.keys(r.answers).length>0?we(await zo({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 Mn(e,r),o=!0):(ou(e),n=new Mn(e)):n=new Mn(e);let i=t.force===!0?null:await su(e),s=await n.ask("target",async()=>we(await pt({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i??(t.force===!0?null:await oP(e,n)),a?P.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):o&&n.get("contextRepo")!==void 0||Ck(e,t.force===!0));let c=await n.ask("hubUrl",async()=>le(await ke({message:"HUB URL",placeholder:ht,initialValue:Q("HUB_URL")??ht,validate:T=>T.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>Un()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>Bn(c,l)),d=null;s==="farm"&&(d=await nP(c,u));let m=a?aP(a.parsed.repoName):"",f=await n.ask("projectId",async()=>le(await ke({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:T=>Yt.test(T.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await n.ask("projectName",async()=>le(await ke({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:T=>T.trim().length>0?void 0:"required"})).trim()),k=await n.ask("language",()=>yP()),h=await n.ask("automationLevel",async()=>we(await pt({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),$=(s==="farm"?"no":await n.ask("mirrorChoice",async()=>we(await pt({message:"how much access should CodePipe have to your repositories?",options:[{value:"no",label:"read and write \u2014 branches and pull requests go into your repositories"},{value:"yes",label:"read only \u2014 CodePipe mirrors them and works in the mirrors",hint:"a mirror is a full copy of the history, in the account you choose next"}],initialValue:"no"}))))==="yes";$&&P.message("read-only token tip: if you want CodePipe to review pull requests people open in your repositories, the token also needs PR-comment permission (GitHub: Pull requests write; Bitbucket: pullrequest:write). Code stays read-only either way.");let S=await n.ask("trackerProvider",async()=>we(await pt({message:"task tracker",options:[{value:"internal",label:"built-in \u2014 CodePipe tracks tasks itself (no external tracker needed)"},{value:"youtrack",label:"YouTrack \u2014 connect an existing YouTrack project"}],initialValue:"internal"}))),R=S==="internal",v=null,b,I=!0;if(R){let T,N=du();N.start("checking task-key prefixes on your account\u2026");try{T=await Eh(c,u,{excludeProjectId:f}),N.stop("prefixes checked")}catch{N.stop("could not reach the HUB",1),me("Could not verify the task-key prefix against your account \u2014 the HUB is unreachable right now. Prefix uniqueness is required, so init can't continue. Check your connection and re-run `codepipe init` later.")}let pe=tc(ec(g),T);b=await n.ask("trackerPrefix",async()=>le(await ke({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:pe,initialValue:pe,validate:he=>{let mt=he.trim();if(!Er.test(mt))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(T.has(mt.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else v=await n.ask("youtrack",()=>Dk()),b=await n.ask("youtrackProjectKey",async()=>le(await ke({message:"YouTrack project key",placeholder:"DEV",validate:T=>T.trim().length>0?void 0:"required"})).trim()),I=await n.ask("youtrackWrites",async()=>we(await zo({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let j=n.get("tokens")??{},K=()=>n.set("tokens",j),z=await n.ask("repos",()=>dP(j,l,a,{onCred:K,initial:n.get("reposPartial")??[],onProgress:T=>n.set("reposPartial",T)}));n.delete("reposPartial");let A=null,y="",U="";if($){let T=we(await n.ask("mirrorHost",async()=>we(await pt({message:"where should the mirrors live? (your Context Repo will default there too)",options:["github","gitlab","bitbucket"].map(se=>({value:se,label:se===z[0]?.host?`${se} (same as your repositories)`:se})),initialValue:z[0]?.host??"github"}))));y=le(await n.ask("mirrorToken",async()=>we(await Vo({message:`token that may CREATE and PUSH repositories on ${T}`})))).trim(),T==="bitbucket"&&(U=le(await n.ask("mirrorEmail",async()=>we(await ke({message:"Atlassian account email for that token",...j.bitbucket?.email?{placeholder:j.bitbucket.email,defaultValue:j.bitbucket.email}:{}})))).trim());let N=await pk(T,y,U||void 0),pe=T==="bitbucket"?"workspace slug":"username or organization (not an email)",mt=le(await n.ask("mirrorOwnerLogin",async()=>we(await ke({message:`account for the mirrors \u2014 ${T} ${pe}`,...N?{placeholder:N,defaultValue:N}:{},validate:se=>{let ne=(se??"").trim();if(!ne&&!N)return"required";if(ne.includes("@"))return`that looks like an email \u2014 a ${T} ${pe} is expected`;if(/\s/.test(ne))return"no spaces"}})))).trim()||N||"";if(!mt||mt.includes("@")){Ek("mirrors need a host account to live in (a username/organization, not an email)");return}A={host:T,owner:mt}}let O=await pP(await n.ask("contextRepo",()=>Ok(f,z,j,l,A??void 0)),f,z,j,l,K,T=>n.set("contextRepo",T),A??void 0),{spec:G,mode:ee}=O,ue;R||(P.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),ue=await n.ask("assigneeLogin",async()=>le(await ke({message:"your YouTrack login (the assignee value)",...v?.login?{initialValue:v.login}:{},validate:T=>T.trim().length>0?void 0:"required"})).trim()));let tt=await n.ask("llmProvider",async()=>{for(;;){if(we(await pt({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.")}}),ft=tt==="claude"?await n.ask("claudeToken",()=>Fw(Bw("claude"),{farm:s==="farm"})):"",Ne;if(ft){let T=await zp(ft);if(T){let N=Ea(T);N&&(Ne=N,P.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 Oe={projectId:f,name:g,automationLevel:h,repos:z,trackerProvider:S,youtrackProjectKey:b,language:k};P.step(`${ee==="attach"?"attaching to":"provisioning"} Context Repo ${G.owner}/${G.name} (${G.host})\u2026`);let M;try{M=await Ln(Oe,G,{...Lk(j),youtrackWrites:I,...v?{trackerUrl:v.url}:{},mode:ee,log:{info:T=>P.message(T),warn:T=>P.warn(T)}})}catch(T){me(`Context Repo provisioning failed: ${T instanceof Error?T.message:String(T)}`)}Oe.contextRepo=M,P.success(`Context Repo ready: ${M.owner}/${M.name}@${M.branch}`),P.step(`registering project on ${c}\u2026`);let F;try{F=await ir(c,u,Oe)}catch(T){if(T instanceof W&&T.status===409){P.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{F=await ae(c,u,f)}catch(N){throw N instanceof W&&me(`HUB \u2192 ${N.status} ${N.message}`),N}}else if(T instanceof W&&T.status===401)n.delete("cliToken"),me("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(T instanceof W)me(`HUB \u2192 ${T.status} ${T.message}`);else throw T}let D=F.contextRepo??M;P.success(`project ${F.projectId} ready (${F.provisioningStatus})`);let X=v?{url:v.url,token:v.token}:void 0;if(s==="farm"){let T=d,N={...j,...ft?{claude:{oauthToken:ft}}:{},...X?{youtrack:X}:{}},pe=j.github?.token;if(D.host==="github"&&pe)try{let ne=hg(`devpipe-${f}`);await gg(D,pe,ne.publicKey,`devpipe-${f}`),N.contextSsh={privateKey:ne.privateKey},P.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(ne){P.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 he={projectId:f,config:{hubUrl:c,cliToken:u,projectId:f},secrets:N,contextRepo:D,projectConfig:It(Oe,I,v?.url,ue||void 0,tt,Ne)},mt=Gt(T.farm.publicKey,JSON.stringify(he));P.step(`handing project ${f} to farm ${T.farm.name}\u2026`);let se;try{se=await ns(c,u,T.farm.farmId,{projectId:f,sealedBundle:mt})}catch(ne){throw ne instanceof W&&me(ne.status===409?`farm ${T.farm.name} is offline \u2014 start it and re-run.`:ne.status===504?`farm ${T.farm.name} did not respond in time.`:`HUB \u2192 ${ne.status} ${ne.message}`),ne}se.ok||me(`farm rejected provisioning: ${se.error??"unknown error"}`),await lu(c,u,f,D,pe,F.repos,null,j),n.clear(),cu(`done. project ${f} is now hosted on farm ${T.farm.name} (daemon ${se.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}Mk(j),await _k(e,D.cloneUrl,D.branch),Nk(e);try{fn(ze(e,it),e,{info:T=>P.message(T),warn:T=>P.warn(T)})}catch(T){P.warn(`skills materialize failed \u2014 ${T instanceof Error?T.message:String(T)}`)}a&&await lP(e);{let T=ze(e,it);pn(T);let N=It(Oe,I,v?.url,ue||void 0,tt,Ne),pe=go(T,N);pe.length>0&&P.success(`local project config \u2192 .codepipe/{${pe.join(", ")}}`),tr(f,N,{info:he=>P.message(he),warn:he=>P.warn(he)})}await jk(e,F.repos);let H=!1;if($&&A&&(H=await uP(e,ze(e,it),F.repos,{host:A.host,owner:A.owner,token:y,...U?{email:U}:{}}),H)){let T=ze(e,it);tr(f,{projectYaml:Bs(ze(T,"project.yaml"),"utf-8"),regimenYaml:Bs(ze(T,"regimen.yaml"),"utf-8")},{info:N=>P.message(N),warn:N=>P.warn(N)})}let E={hubUrl:c,cliToken:u,projectId:f,...j,...ft?{claude:{oauthToken:ft}}:{},...X?{youtrack:X}:{},...H?{mirrorWrite:{token:y,host:A.host,...U?{email:U}:{}}}:{}};ce(E),Ut({hubUrl:c,cliToken:u,projectId:f,accountEmail:p},f),P.success(`secrets \u2192 ${Tt(f)}`),await lu(c,u,f,D,j.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,F.repos,e,j),n.clear();let C=`${c}/?project=${encodeURIComponent(f)}`;Pr(C),cu(`done. your project on the dashboard (sign in there to work with it):
909
+ ${C}
910
+ starting codepipe up \u2014 the CLI daemon and an agent worker, with their logs on screen. Ctrl+C to stop (restart anytime with \`codepipe up\` from this folder).`);let{upCommand:te}=await Promise.resolve().then(()=>(Us(),bk));await te({profile:void 0})}async function lu(t,e,r,n,o,i=[],s=null,a={}){let c=await tk(n,o),l=!1;if(!c)try{l=await ok(i,{localRoot:s,tokens:a})}catch{l=!1}let u=ek({indexExists:c,localClones:s!==null,reposNonEmpty:l}),p=await rP({message:u.message,options:u.options,initialValues:u.initialValues,required:!1});if(uu(p))return;let d=new Set(p);if(d.has("map")&&s!==null)try{let m=Ae(s);if(!m)throw new Error("workspace not found");let{bootstrapWorkspaceModel:f}=await Promise.resolve().then(()=>(Lo(),ps)),g=await f(m,void 0,{onLog:k=>P.message(k)});P.success(`project map ready: ${g.events} task events mined from history`)}catch(m){P.warn(`could not build the project map: ${m instanceof Error?m.message:String(m)}. Registration is not affected \u2014 run \`codepipe model bootstrap\` later.`)}if(d.has("backfill"))try{let{jobId:m}=await Oo(t,e,r,{reindex:!1,backfill:!0});P.success(`retrospective architecture analysis queued (job ${m}); decision drafts will appear on the project card for review once a SANDBOX picks up the job.`)}catch(m){P.warn(`could not start the retrospective analysis: ${m instanceof Error?m.message:String(m)}. Registration is not affected.`)}if(d.has("index"))try{let{jobId:m}=await Oo(t,e,r,{reindex:u.reindex});P.success(`indexing queued (job ${m}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(m){P.warn(`could not start indexing: ${m instanceof Error?m.message:String(m)}. You can retry later \u2014 registration is not affected.`)}}async function nP(t,e){let r;try{r=await $h(t,e)}catch(c){throw c instanceof W&&me(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&me("no farm is available to this account. Farms are assigned by the operator \u2014 ask them to assign one to you (or, if you run your own farm host: `codepipe-farm register --hub <url> --token <token>` and `codepipe-farm start`, then have the operator assign it).");let o=we(await pt({message:"target farm",options:n.map(c=>({value:c.farmId,label:`${c.name}${c.online?"":" (offline)"} \u2014 ${c.keyFingerprint??"no fingerprint"}`}))})),i=n.find(c=>c.farmId===o),s;try{s=ts(i.farmId,i.publicKey)}catch(c){me(c instanceof Error?c.message:String(c))}return we(await zo({message:`confirm farm ${i.name} cred-channel fingerprint:
911
911
  ${s}
912
- (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||he("farm fingerprint not confirmed \u2014 aborting."),ts(i.farmId,s),{farm:i,fingerprint:s}}async function Ek(t){xk(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();Tk(e,t.force===!0);let r=de(await be({message:"HUB URL",initialValue:Q("HUB_URL")??ht,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await Un(),{cliToken:o,accountEmail:i}=await Bn(r,n);C.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await le(r,o,t.projectId)}catch(d){throw d instanceof K&&he(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||he(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await Ok(),l={},u=new Set(s.repos.map(d=>d.host));u.add(s.contextRepo.host);for(let d of u){let m=s.repos.find(f=>f.host===d);await Bs(d,l,m?.owner??s.contextRepo.owner,n,m?.repoName)}Nk(l),await Ck(e,s.contextRepo.cloneUrl,s.contextRepo.branch),Ak(e);{let d=ze(e,ot);pn(d);let m={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.trackerProvider?{trackerProvider:s.trackerProvider}:{},...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{},...s.language?{language:s.language}:{}},f=Rt(m,!0,c?.url,void 0,s.llmProvider??Xe),y=go(d,f);y.length>0&&C.success(`local project config \u2192 .codepipe/{${y.join(", ")}} (defaults \u2014 review and adjust)`),tr(t.projectId,f,{info:k=>C.message(k),warn:k=>C.warn(k)})}await Pk(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};ue(p),Ut({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),C.success(`secrets \u2192 ${Et(t.projectId)}`),await su(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),iu("done.")}function Tk(t,e){if(!Dr(t)){kk(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=VC(t).filter(o=>!r.has(o));n.length!==0&&(e||he(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function nu(t){if(!Dr(ze(t,".git")))return null;try{let e=Ye(await Rk(t));return e?{parsed:e,defaultBranch:await Ik(t)}:null}catch{return null}}async function Rk(t){try{return(await Dn(t).remote(["get-url","origin"])||"").toString().trim()}catch{return""}}async function ZC(t,e){if(!Dr(ze(t,".git")))return null;let r=await e.ask("inPlaceOrigin",async()=>{let o=await Rk(t);return C.warn(o?`this folder is a git checkout, but its origin (${o}) is not a github.com / gitlab.com / bitbucket.org URL`:"this folder is a git checkout without an `origin` remote"),de(await be({message:"clone URL of this repository \u2014 blank if this folder is not the project repo",placeholder:"git@github.com:acme/api.git",validate:i=>!i||!i.trim()||Ye(i)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim()}),n=r?Ye(r):null;return n?{parsed:n,defaultBranch:await Ik(t)}:null}async function QC(t){try{let e=await Dn().listRemote(["--symref",t,"HEAD"]);return/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m.exec(e)?.[1]??null}catch{return null}}async function eP(t,e){try{return(await Dn().listRemote([t,`refs/heads/${e}`])).trim().length>0}catch{return!0}}async function Ik(t){let e=Dn(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 tP(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Yt.test(e)?e:""}function rP(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function nP(t){let e=ze(t,".gitignore"),r=Dr(e)?Us(e,"utf-8"):"";if(rP(r))return;if(!ke(await zo({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){C.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
912
+ (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||me("farm fingerprint not confirmed \u2014 aborting."),es(i.farmId,s),{farm:i,fingerprint:s}}async function Ik(t){Tk(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();Ck(e,t.force===!0);let r=le(await ke({message:"HUB URL",initialValue:Q("HUB_URL")??ht,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await Un(),{cliToken:o,accountEmail:i}=await Bn(r,n);P.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await ae(r,o,t.projectId)}catch(d){throw d instanceof W&&me(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||me(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await Dk(),l={},u=new Set(s.repos.map(d=>d.host));u.add(s.contextRepo.host);for(let d of u){let m=s.repos.find(f=>f.host===d);await Fs(d,l,m?.owner??s.contextRepo.owner,n,m?.repoName)}Mk(l),await _k(e,s.contextRepo.cloneUrl,s.contextRepo.branch),Nk(e);{let d=ze(e,it);pn(d);let m={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.trackerProvider?{trackerProvider:s.trackerProvider}:{},...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{},...s.language?{language:s.language}:{}},f=It(m,!0,c?.url,void 0,s.llmProvider??Xe),g=go(d,f);g.length>0&&P.success(`local project config \u2192 .codepipe/{${g.join(", ")}} (defaults \u2014 review and adjust)`),tr(t.projectId,f,{info:k=>P.message(k),warn:k=>P.warn(k)})}await jk(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};ce(p),Ut({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),P.success(`secrets \u2192 ${Tt(t.projectId)}`),await lu(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),cu("done.")}function Ck(t,e){if(!Dr(t)){vk(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=tP(t).filter(o=>!r.has(o));n.length!==0&&(e||me(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function su(t){if(!Dr(ze(t,".git")))return null;try{let e=Ye(await Pk(t));return e?{parsed:e,defaultBranch:await Ak(t)}:null}catch{return null}}async function Pk(t){try{return(await Dn(t).remote(["get-url","origin"])||"").toString().trim()}catch{return""}}async function oP(t,e){if(!Dr(ze(t,".git")))return null;let r=await e.ask("inPlaceOrigin",async()=>{let o=await Pk(t);return P.warn(o?`this folder is a git checkout, but its origin (${o}) is not a github.com / gitlab.com / bitbucket.org URL`:"this folder is a git checkout without an `origin` remote"),le(await ke({message:"clone URL of this repository \u2014 blank if this folder is not the project repo",placeholder:"git@github.com:acme/api.git",validate:i=>!i||!i.trim()||Ye(i)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim()}),n=r?Ye(r):null;return n?{parsed:n,defaultBranch:await Ak(t)}:null}async function iP(t){try{let e=await Dn().listRemote(["--symref",t,"HEAD"]);return/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m.exec(e)?.[1]??null}catch{return null}}async function sP(t,e){try{return(await Dn().listRemote([t,`refs/heads/${e}`])).trim().length>0}catch{return!0}}async function Ak(t){let e=Dn(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 aP(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Yt.test(e)?e:""}function cP(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function lP(t){let e=ze(t,".gitignore"),r=Dr(e)?Bs(e,"utf-8"):"";if(cP(r))return;if(!we(await zo({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(`
913
913
  `)?"":`
914
- `;bk(e,r+o+`
914
+ `;xk(e,r+o+`
915
915
  # codepipe workspace (added by \`codepipe init\`)
916
916
  .codepipe/
917
- `),C.success(`.codepipe/ added to ${$k(e)}`)}async function Un(){let t="";try{t=(await Dn().raw(["config","--global","user.email"])||"").trim()}catch{}return de(await be({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function Bn(t,e){C.step(`connecting account ${e}`);let r;try{r=await Sh(t,e)}catch(s){throw s instanceof No&&he(`${e} is not authorized on this HUB yet.
917
+ `),P.success(`.codepipe/ added to ${Sk(e)}`)}async function Un(){let t="";try{t=(await Dn().raw(["config","--global","user.email"])||"").trim()}catch{}return le(await ke({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function Bn(t,e){P.step(`connecting account ${e}`);let r;try{r=await Th(t,e)}catch(s){throw s instanceof No&&me(`${e} is not authorized on this HUB yet.
918
918
  Sign up at ${t} (registration form on the login screen),
919
919
  wait for the operator to approve it by email, then re-run
920
- \`codepipe init\` with the same email.`),s}r.accountCreated&&C.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&C.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(Pr(r.authorizeUrl),C.message(`a browser tab was opened to confirm this CLI:
920
+ \`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&&(Pr(r.authorizeUrl),P.message(`a browser tab was opened to confirm this CLI:
921
921
  ${r.authorizeUrl}
922
922
  `+(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
923
- otherwise use the emailed link the page offers.`))),r.approvalRequired&&C.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),C.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let n=!1,o=Date.now(),i=o+15*6e4;for(;Date.now()<i;){let s;try{s=await Eh(t,r.requestId)}catch(a){C.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await ou(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&C.message(`connected as ${a} (the account confirmed in the browser).`),C.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&he("the HUB rejected this account"),s.status==="expired"&&he("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,C.message(`email confirmed. waiting for the operator to approve your account\u2026
924
- (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await ou(5e3);continue}await ou(2e3)}he("bootstrap timed out")}async function Ck(t,e,r){let n=ze(t,ot);if(Dr(ze(n,".git"))){C.message(`${n} already cloned \u2014 skipping`);return}Dr(n)&&he(`${n} exists but is not a git repo \u2014 remove it and re-run`),kk(n,{recursive:!0}),C.step(`cloning Context Repo \u2192 ${n}`);try{await Dn().clone(e,n,["--branch",r]),C.success(`cloned ${e}`)}catch(o){he(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function oP(t,e,r,n){if(r.length===0)return!1;C.step(`setting up ${r.length} mirror(s) \u2014 your repositories stay read-only`);let o={info:a=>C.message(` ${a}`),warn:a=>C.warn(` ${a}`)},i={...n.host==="github"?{githubToken:n.token}:{},...n.host==="gitlab"?{gitlabToken:n.token}:{},...n.host==="bitbucket"&&n.email?{bitbucket:{email:n.email,apiToken:n.token}}:{}},s=[];for(let a of r){let c={host:n.host,owner:n.owner,repoName:dk(a.repoName)};try{let l=await ck(c,i,o);await uk(ze(t,a.mountAs??a.name),l.sshUrl,o),s.push({repoName:a.name,spec:c})}catch(l){return C.warn(` ${a.name}: mirror not set up \u2014 ${l instanceof Error?l.message:String(l)}`),C.warn("mirroring is all-or-nothing: NO mirrors were recorded and the project keeps working against its own repositories. Fix the cause and re-run `codepipe init`"),!1}}for(let a of s)pm(e,a.repoName,a.spec);for(let a of s)C.success(` ${a.repoName} \u2192 ${a.spec.owner}/${a.spec.repoName}`);return!0}async function Pk(t,e){if(e.length===0)return;C.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(o=>({name:o.name,host:o.host,owner:o.owner,repoName:o.repoName,defaultBranch:o.defaultBranch??"main",mountAs:o.mountAs??o.name})),n=await qo(t,r,{log:{info:o=>C.message(o),warn:o=>C.warn(o)}});for(let o of n)C.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function Ak(t){let e=ze(t,ot,".gitignore"),r="";if(Dr(e)&&(r=Us(e,"utf-8")),wk.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
923
+ 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 Rh(t,r.requestId)}catch(a){P.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await au(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&P.message(`connected as ${a} (the account confirmed in the browser).`),P.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&me("the HUB rejected this account"),s.status==="expired"&&me("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,P.message(`email confirmed. waiting for the operator to approve your account\u2026
924
+ (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await au(5e3);continue}await au(2e3)}me("bootstrap timed out")}async function _k(t,e,r){let n=ze(t,it);if(Dr(ze(n,".git"))){P.message(`${n} already cloned \u2014 skipping`);return}Dr(n)&&me(`${n} exists but is not a git repo \u2014 remove it and re-run`),vk(n,{recursive:!0}),P.step(`cloning Context Repo \u2192 ${n}`);try{await Dn().clone(e,n,["--branch",r]),P.success(`cloned ${e}`)}catch(o){me(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function uP(t,e,r,n){if(r.length===0)return!1;P.step(`setting up ${r.length} mirror(s) \u2014 your repositories stay read-only`);let o={info:a=>P.message(` ${a}`),warn:a=>P.warn(` ${a}`)},i={...n.host==="github"?{githubToken:n.token}:{},...n.host==="gitlab"?{gitlabToken:n.token}:{},...n.host==="bitbucket"&&n.email?{bitbucket:{email:n.email,apiToken:n.token}}:{}},s=[];for(let a of r){let c={host:n.host,owner:n.owner,repoName:mk(a.repoName)};try{let l=await dk(c,i,o);await fk(ze(t,a.mountAs??a.name),l.sshUrl,o),s.push({repoName:a.name,spec:c})}catch(l){return P.warn(` ${a.name}: mirror not set up \u2014 ${l instanceof Error?l.message:String(l)}`),P.warn("mirroring is all-or-nothing: NO mirrors were recorded and the project keeps working against its own repositories. Fix the cause and re-run `codepipe init`"),!1}}for(let a of s)mm(e,a.repoName,a.spec);for(let a of s)P.success(` ${a.repoName} \u2192 ${a.spec.owner}/${a.spec.repoName}`);return!0}async function jk(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 qo(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 Nk(t){let e=ze(t,it,".gitignore"),r="";if(Dr(e)&&(r=Bs(e,"utf-8")),$k.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
925
925
  `)||r.length===0?"":`
926
- `,i=wk.join(`
926
+ `,i=$k.join(`
927
927
  `)+`
928
- `;bk(e,r+o+(r?`
929
- `:"")+i),C.message(`appended runtime entries to ${$k(e)}`)}async function iP(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;await Bs(s.host,t,s.owner,e,s.repoName),i?.(),o.push({name:s.repoName,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:a,mountAs:"."}),n.onProgress?.(o),C.success(`added this repository: ${s.host}: ${s.owner}/${s.repoName} (this folder, default branch ${a})`)}for(;ke(await zo({message:o.length===0?"Add a project repository?":`Project repositories: ${o.map(f=>f.name).join(", ")}. Add another one?`,initialValue:o.length===0}));){let a=de(await be({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:f=>!f||!f.trim()||Ye(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=Ye(a);C.message(`${c.host}: ${c.owner}/${c.repoName}`),await Bs(c.host,t,c.owner,e,c.repoName),i?.();let l=de(await be({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:f=>f.trim().length>0?void 0:"required"})).trim(),u=await QC(a),p="";for(;p=de(await be({message:"default branch",placeholder:u??"main",...u?{initialValue:u}:{}})).trim(),!(!p||!u||p===u||await eP(a,p));)C.warn(`branch "${p}" does not exist in ${c.owner}/${c.repoName} (the repository's default is "${u}")`);let d=de(await be({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),m={name:l,host:c.host,owner:c.owner,repoName:c.repoName};p&&(m.defaultBranch=p),d&&d!==l&&(m.mountAs=d),o.push(m),n.onProgress?.(o)}return o}async function _k(t,e,r,n,o){C.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let i=ke(await pt({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));i==="attach"&&C.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let s=o?.host??e[0]?.host,a=o?.owner??e[0]?.owner,c;if(s&&a){let l=de(await be({message:`Context Repo \u2014 a name (hosted at ${s}: ${a}/<name>) or a full clone URL`,initialValue:St(t),validate:p=>{let d=(p??"").trim();if(!d)return"required";if(!Ye(d)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(d))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),u=Ye(l);c=u?{host:u.host,owner:u.owner,name:u.repoName}:{host:s,owner:a,name:l}}else{let l=await aP(),u=de(await be({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:d=>d.trim().length>0?void 0:"required"})).trim(),p=de(await be({message:"Context Repo name",placeholder:St(t),initialValue:St(t),validate:d=>d.trim().length>0?void 0:"required"})).trim();c={host:l,owner:u,name:p}}return{spec:c,mode:i}}function jk(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??sn()}}async function sP(t,e,r,n,o,i,s,a){let c=t;for(;;){let{spec:l,mode:u}=c;await Bs(l.host,n,l.owner,o),i?.();let p=cu();p.start(`checking ${l.owner}/${l.name} on ${l.host}\u2026`);let d=await Bw(l,jk(n),{explain:u==="attach"});if(d.found===!0)return p.stop(`${l.owner}/${l.name} found${u==="create"?" \u2014 existing repo will be reused":""}`),c;if(d.found==="unknown")return p.stop(`could not check ${l.owner}/${l.name} (${d.detail}) \u2014 continuing`,1),c;if(u==="create")return p.stop(`${l.owner}/${l.name} not found \u2014 will be created`),c;p.stop(d.detail,1);let m=ke(await pt({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(m==="abort"&&he("aborted"),m==="create")return c={spec:l,mode:"create"},s(c),c;c=await _k(e,r,n,o,a),s(c)}}async function aP(){return ke(await pt({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Fs(t,e){let r=cu();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 Nk(t){xo(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),So(t.gitlab?.token??process.env.GITLAB_TOKEN),Eo(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Bs(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await cP(r);i?e.github=i:C.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let i=await lP(r,n,o);i?e.bitbucket=i:C.warn("no Bitbucket API token \u2014 git falls back to this machine's SSH keys / BITBUCKET_* env; private repos won't clone over HTTPS and PRs won't open.")}else{let i=await uP();i?e.gitlab=i:C.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function cP(t){for(;;){let e=de(await Vo({message:`GitHub PAT \u2014 blank to skip
928
+ `;xk(e,r+o+(r?`
929
+ `:"")+i),P.message(`appended runtime entries to ${Sk(e)}`)}async function dP(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;await Fs(s.host,t,s.owner,e,s.repoName),i?.(),o.push({name:s.repoName,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:a,mountAs:"."}),n.onProgress?.(o),P.success(`added this repository: ${s.host}: ${s.owner}/${s.repoName} (this folder, default branch ${a})`)}for(;we(await zo({message:o.length===0?"Add a project repository?":`Project repositories: ${o.map(f=>f.name).join(", ")}. Add another one?`,initialValue:o.length===0}));){let a=le(await ke({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:f=>!f||!f.trim()||Ye(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=Ye(a);P.message(`${c.host}: ${c.owner}/${c.repoName}`),await Fs(c.host,t,c.owner,e,c.repoName),i?.();let l=le(await ke({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:f=>f.trim().length>0?void 0:"required"})).trim(),u=await iP(a),p="";for(;p=le(await ke({message:"default branch",placeholder:u??"main",...u?{initialValue:u}:{}})).trim(),!(!p||!u||p===u||await sP(a,p));)P.warn(`branch "${p}" does not exist in ${c.owner}/${c.repoName} (the repository's default is "${u}")`);let d=le(await ke({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),m={name:l,host:c.host,owner:c.owner,repoName:c.repoName};p&&(m.defaultBranch=p),d&&d!==l&&(m.mountAs=d),o.push(m),n.onProgress?.(o)}return o}async function Ok(t,e,r,n,o){P.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let i=we(await pt({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));i==="attach"&&P.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let s=o?.host??e[0]?.host,a=o?.owner??e[0]?.owner,c;if(s&&a){let l=le(await ke({message:`Context Repo \u2014 a name (hosted at ${s}: ${a}/<name>) or a full clone URL`,initialValue:Et(t),validate:p=>{let d=(p??"").trim();if(!d)return"required";if(!Ye(d)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(d))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),u=Ye(l);c=u?{host:u.host,owner:u.owner,name:u.repoName}:{host:s,owner:a,name:l}}else{let l=await fP(),u=le(await ke({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:d=>d.trim().length>0?void 0:"required"})).trim(),p=le(await ke({message:"Context Repo name",placeholder:Et(t),initialValue:Et(t),validate:d=>d.trim().length>0?void 0:"required"})).trim();c={host:l,owner:u,name:p}}return{spec:c,mode:i}}function Lk(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??sn()}}async function pP(t,e,r,n,o,i,s,a){let c=t;for(;;){let{spec:l,mode:u}=c;await Fs(l.host,n,l.owner,o),i?.();let p=du();p.start(`checking ${l.owner}/${l.name} on ${l.host}\u2026`);let d=await Kw(l,Lk(n),{explain:u==="attach"});if(d.found===!0)return p.stop(`${l.owner}/${l.name} found${u==="create"?" \u2014 existing repo will be reused":""}`),c;if(d.found==="unknown")return p.stop(`could not check ${l.owner}/${l.name} (${d.detail}) \u2014 continuing`,1),c;if(u==="create")return p.stop(`${l.owner}/${l.name} not found \u2014 will be created`),c;p.stop(d.detail,1);let m=we(await pt({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(m==="abort"&&me("aborted"),m==="create")return c={spec:l,mode:"create"},s(c),c;c=await Ok(e,r,n,o,a),s(c)}}async function fP(){return we(await pt({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Gs(t,e){let r=du();r.start(`verifying ${t}\u2026`);try{let n=await e();return r.stop(`${t} OK \u2014 ${n}`),!0}catch(n){return r.stop(`${t} failed \u2014 ${n instanceof Error?n.message:String(n)}`,1),!1}}function Mk(t){xo(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),So(t.gitlab?.token??process.env.GITLAB_TOKEN),Eo(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Fs(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await mP(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 hP(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 gP();i?e.gitlab=i:P.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function mP(t){for(;;){let e=le(await Vo({message:`GitHub PAT \u2014 blank to skip
930
930
  classic PAT: 'repo' + 'workflow'
931
931
  fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
932
932
  if org: approve token in org Settings \u2192 Personal access tokens.
933
- (Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo.)`})).trim();if(!e)return;if(await Fs("GitHub",()=>zt(e,t?{owner:t}:void 0)))return{token:e};C.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function lP(t,e,r){for(C.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
933
+ (Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo.)`})).trim();if(!e)return;if(await Gs("GitHub",()=>zt(e,t?{owner:t}:void 0)))return{token:e};P.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function hP(t,e,r){for(P.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
934
934
  How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
935
935
  'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes:
936
936
  read:repository:bitbucket + write:repository:bitbucket +
937
937
  read:pullrequest:bitbucket + write:pullrequest:bitbucket
938
938
  \u2014 write scopes do NOT include read: pick BOTH scopes of each pair
939
939
  (+ admin:repository:bitbucket if this token will provision the Context Repo).
940
- The token is shown ONCE \u2014 copy it right away.`);;){let n=de(await be({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=de(await Vo({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){C.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await Fs("Bitbucket",async()=>{let i=await Vt(n,o,t);if(t&&r){let s=await bi(n,o,t,r);if(s)throw new Error(s)}return i}))return{email:n,apiToken:o};C.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function uP(){for(;;){let t=de(await Vo({message:`GitLab PAT \u2014 blank to skip
941
- scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Fs("GitLab",()=>Xt(t))){let e=await mp(t);return e&&C.warn(e),{token:t}}C.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function dP(){let t="__other__",e=async()=>de(await be({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=ke(await pt({message:"project language",options:[...Jr.map(s=>({value:s,label:s==="English"?"English (default)":s})),{value:t,label:"other\u2026"}],initialValue:"English"})),n=r===t?await e():r;if(n==="English")return{primary:n,context:n,tasks:n,docs:n,code_comments:n,chat:xe};let o=[{key:"context",label:"context documents (knowledge, ADRs, task artifacts)",initial:n},{key:"tasks",label:"tracker issues the agent drafts",initial:n},{key:"docs",label:"documentation in the project repos",initial:n},{key:"code_comments",label:"code comments",initial:n},{key:"chat",label:"chat with the agent",initial:xe}],i={primary:n};for(let s of o){let a=new Set,c=[s.initial,n,"English",xe].filter(u=>a.has(u)?!1:(a.add(u),!0)).map(u=>({value:u,label:u===xe?"auto \u2014 mirror the language of the user's material":u}));c.push({value:t,label:"other\u2026"});let l=ke(await pt({message:`language for ${s.label}`,options:c,initialValue:s.initial}));i[s.key]=l===t?await e():l}return i}async function Ok(){for(;;){let t=de(await be({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=de(await Vo({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Fs("YouTrack",()=>Qt({baseUrl:t,token:e}))){let r=await Ip({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}C.warn("re-enter the YouTrack URL / token.")}}var wk,Yo=x(()=>{"use strict";Ge();B();dt();Uw();vi();Ke();Ft();Ar();ln();Ho();Rl();As();Jt();Cr();Xw();Ne();Qw();rk();ul();Li();me();js();Gc();pk();Ci();it();wk=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});B();Ge();Ke();import{Command as wA}from"commander";Ke();me();async function sp(t){let e=t.profile??t.project;t.profile&&t.profile!==t.project&&(console.error(`--profile (${t.profile}) must equal --project (${t.project}). Profile id is the project id.`),process.exit(1));let r=kt(e);r&&!t.force&&(console.error(`already configured at ${rn(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");Ut({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...Y(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};ue(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${rn(e)}`)}sc();Ke();import{homedir as Cl}from"node:os";import{join as Mo}from"node:path";Ge();B();import{existsSync as lg,rmSync as WE}from"node:fs";import{join as Nr}from"node:path";import{simpleGit as qE}from"simple-git";import"ws";Ge();me();import{createHash as Y$}from"node:crypto";import{existsSync as z$,readFileSync as V$}from"node:fs";import{homedir as X$,hostname as ac}from"node:os";import{join as J$}from"node:path";function up(t){return Y$("sha256").update(t).digest("hex").slice(0,12)}function Z$(){let t=Q("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=J$(X$(),".claude","credentials.json");if(!z$(e))return;let r=JSON.parse(V$(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 dp(t){let e=Z$(),r=Q("ACCOUNT_ID")?.trim(),n=Q("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=on(t);return o?{accountId:`acct-${up(o)}`,label:n||ac(),...e?{email:e}:{}}:{accountId:`acct-${up(`host:${ac()}`)}`,label:n||ac(),...e?{email:e}:{}}}Ge();ln();me();$c();async function Xp(t,e,r,n,o){let i=c=>{e.readyState===e.OPEN&&e.send(JSON.stringify(c))},s=c=>i({type:"agent_login_url",requestId:r.requestId,projectId:t.projectId,error:c});if(Q("ORIGIN")==="farm"||Q("CLAUDE_AUTOLOGIN")!=="1"){s("autologin_disabled");return}let a;try{a=await bc($i())}catch(c){s(`listener failed: ${c instanceof Error?c.message:String(c)}`);return}i({type:"agent_login_url",requestId:r.requestId,projectId:t.projectId,authUrl:a.authUrl}),n.info(`[agent-auth] authorize Claude in a browser on THIS machine: ${a.authUrl}`),n.info(`[agent-auth] waiting for the redirect on ${a.redirectUri} \u2026`);try{let c=await a.waitForToken(),l=await Bt(c.oauthToken);if(l==="invalid"){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"token rejected (401) \u2014 previous token kept"}),n.warn("[agent-auth] new Claude token rejected (401) \u2014 previous token kept");return}let u=Y(t.projectId);if(!u){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"no secrets file for this project on the CLI"}),n.warn("[agent-auth] no secrets file for this project \u2014 token not saved");return}u.claude={oauthToken:c.oauthToken},ue(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()}}Ge();function Jp(t,e){let r=t.find(n=>n.kind==="claude");return r?.present===!0&&r.ok===!1?Q("ORIGIN")==="farm"||Q("CLAUDE_AUTOLOGIN")!=="1"||e?"none":"open":r?.ok===!0?"rearm":"none"}function Zp(t,e){return`${t.replace(/\/$/,"")}/?project=${encodeURIComponent(e)}`}vi();import{existsSync as Sv}from"node:fs";import{join as Ev}from"node:path";import{simpleGit as Tv}from"simple-git";async function Qp(t,e){if(!Sv(Ev(t,".git")))return{status:"skipped"};let r=Tv(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${Rv(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 Rv(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as xc,readFileSync as of,readdirSync as Pv,watch as Av}from"node:fs";import{join as ho}from"node:path";B();import{existsSync as ef,readFileSync as tf,readdirSync as Iv,statSync as Cv}from"node:fs";import{join as vc}from"node:path";import{parse as rf}from"yaml";function xi(t){let e=vc(t,"actions"),r=[],n=[];if(!ef(e))return{defs:r,errors:n};let o;try{o=Iv(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=vc(e,s);try{if(!Cv(a).isFile())continue;let c=Ca(s,rf(tf(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 nf(t){let e={},r=vc(t,"project.yaml");if(!ef(r))return e;let n;try{n=rf(tf(r,"utf-8"))}catch{return e}if(!n||typeof n!="object")return e;let o=n.variables;if(!o||typeof o!="object"||Array.isArray(o))return e;for(let[i,s]of Object.entries(o))!Je.test(i)||Mt(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var Si=class{constructor(e,r,n,o,i=6e4){this.contextDir=e;this.projectId=r;this.send=n;this.log=o;this.intervalMs=i}timer=null;watchers=[];debounce=null;started=!1;start(){this.started||(this.started=!0,this.report(),this.timer=setInterval(()=>this.report(),this.intervalMs),this.timer.unref?.(),this.installWatcher())}stop(){this.started=!1,this.timer&&clearInterval(this.timer),this.timer=null,this.debounce&&clearTimeout(this.debounce),this.debounce=null;for(let e of this.watchers)try{e.close()}catch{}this.watchers=[]}installWatcher(){let e=()=>{this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>this.report(),500),this.debounce.unref?.()},r=[this.contextDir,ho(this.contextDir,"prompts"),ho(this.contextDir,"actions")];for(let n of r)if(xc(n))try{let o=Av(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=xi(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(!xc(r))return null;try{return of(r,"utf-8")}catch{return null}}readPrompts(){let e=ho(this.contextDir,"prompts"),r={};if(!xc(e))return r;let n;try{n=Pv(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=of(ho(e,o),"utf-8")}catch{}}return r}};lt();import{existsSync as Ac,readFileSync as pf,readdirSync as Hv}from"node:fs";import{join as ff}from"node:path";import{simpleGit as Wv}from"simple-git";var qv=/^(\d{4})-(.+)\.md$/,Yv="0000-template.md";function zv(t){let e=t.split(`
942
- `),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 Vv(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
943
- `),a=s.findIndex(h=>h.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),u=[],p="",d=null,m=a>=0?a+1:0;for(let h=m;h<s.length;h++){let w=(s[h]??"").trim();if(w===""){m=h+1;continue}let $=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(w);if(!$)break;let S=($[1]??"").trim().toLowerCase(),T=($[2]??"").trim(),v=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(w);v&&(d=parseInt(v[1]??"",10)),S==="tasks"&&(p=T),l.has(S)||u.push(w),m=h+1}let f=p?p.includes(n)?p:`${p}, ${n}`:n,y=s.slice(m).join(`
944
- `).replace(/^\n+/,""),k=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${f}`,...u,"",y].join(`
940
+ The token is shown ONCE \u2014 copy it right away.`);;){let n=le(await ke({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:i=>!i||!i.trim()||i.includes("@")?void 0:"must be an email"})).trim();if(!n)return;let o=le(await Vo({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 Gs("Bitbucket",async()=>{let i=await Vt(n,o,t);if(t&&r){let s=await ki(n,o,t,r);if(s)throw new Error(s)}return i}))return{email:n,apiToken:o};P.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function gP(){for(;;){let t=le(await Vo({message:`GitLab PAT \u2014 blank to skip
941
+ scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Gs("GitLab",()=>Xt(t))){let e=await gp(t);return e&&P.warn(e),{token:t}}P.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function yP(){let t="__other__",e=async()=>le(await ke({message:"language name (in English, e.g. Ukrainian)",validate:s=>{let a=s.trim();if(a.length===0)return"required";if(a.length>40)return`\u2264 ${40} chars`}})).trim(),r=we(await pt({message:"project language",options:[...Jr.map(s=>({value:s,label:s==="English"?"English (default)":s})),{value:t,label:"other\u2026"}],initialValue:"English"})),n=r===t?await e():r;if(n==="English")return{primary:n,context:n,tasks:n,docs:n,code_comments:n,chat:ve};let o=[{key:"context",label:"context documents (knowledge, ADRs, task artifacts)",initial:n},{key:"tasks",label:"tracker issues the agent drafts",initial:n},{key:"docs",label:"documentation in the project repos",initial:n},{key:"code_comments",label:"code comments",initial:n},{key:"chat",label:"chat with the agent",initial:ve}],i={primary:n};for(let s of o){let a=new Set,c=[s.initial,n,"English",ve].filter(u=>a.has(u)?!1:(a.add(u),!0)).map(u=>({value:u,label:u===ve?"auto \u2014 mirror the language of the user's material":u}));c.push({value:t,label:"other\u2026"});let l=we(await pt({message:`language for ${s.label}`,options:c,initialValue:s.initial}));i[s.key]=l===t?await e():l}return i}async function Dk(){for(;;){let t=le(await ke({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let n=r.trim();if(!n)return"required";if(!n.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=le(await Vo({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Gs("YouTrack",()=>Qt({baseUrl:t,token:e}))){let r=await Pp({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}P.warn("re-enter the YouTrack URL / token.")}}var $k,Yo=x(()=>{"use strict";Ge();B();dt();Gw();$i();Ke();Ft();Ar();ln();Ho();Pl();_s();Jt();Cr();Qw();je();rk();ik();dl();Oi();fe();Ns();Kc();hk();Ii();kt();$k=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});B();Ge();Ke();import{Command as xA}from"commander";Ke();fe();async function cp(t){let e=t.profile??t.project;t.profile&&t.profile!==t.project&&(console.error(`--profile (${t.profile}) must equal --project (${t.project}). Profile id is the project id.`),process.exit(1));let r=bt(e);r&&!t.force&&(console.error(`already configured at ${rn(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");Ut({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...Y(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};ce(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${rn(e)}`)}ac();Ke();import{homedir as _l}from"node:os";import{join as Mo}from"node:path";Ge();B();import{existsSync as pg,rmSync as JE}from"node:fs";import{join as Nr}from"node:path";import{simpleGit as ZE}from"simple-git";import"ws";Ge();fe();import{createHash as V$}from"node:crypto";import{existsSync as X$,readFileSync as J$}from"node:fs";import{homedir as Z$,hostname as cc}from"node:os";import{join as Q$}from"node:path";function pp(t){return V$("sha256").update(t).digest("hex").slice(0,12)}function ev(){let t=Q("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=Q$(Z$(),".claude","credentials.json");if(!X$(e))return;let r=JSON.parse(J$(e,"utf-8")),n=[r.email,r.account?.email,r.user?.email];for(let o of n)if(typeof o=="string"&&o.includes("@"))return o.trim().toLowerCase()}catch{}}function fp(t){let e=ev(),r=Q("ACCOUNT_ID")?.trim(),n=Q("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=on(t);return o?{accountId:`acct-${pp(o)}`,label:n||cc(),...e?{email:e}:{}}:{accountId:`acct-${pp(`host:${cc()}`)}`,label:n||cc(),...e?{email:e}:{}}}Ge();ln();fe();vc();async function Zp(t,e,r,n,o){let i=c=>{e.readyState===e.OPEN&&e.send(JSON.stringify(c))},s=c=>i({type:"agent_login_url",requestId:r.requestId,projectId:t.projectId,error:c});if(Q("ORIGIN")==="farm"||Q("CLAUDE_AUTOLOGIN")!=="1"){s("autologin_disabled");return}let a;try{a=await $c(bi())}catch(c){s(`listener failed: ${c instanceof Error?c.message:String(c)}`);return}i({type:"agent_login_url",requestId:r.requestId,projectId:t.projectId,authUrl:a.authUrl}),n.info(`[agent-auth] authorize Claude in a browser on THIS machine: ${a.authUrl}`),n.info(`[agent-auth] waiting for the redirect on ${a.redirectUri} \u2026`);try{let c=await a.waitForToken(),l=await Bt(c.oauthToken);if(l==="invalid"){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"token rejected (401) \u2014 previous token kept"}),n.warn("[agent-auth] new Claude token rejected (401) \u2014 previous token kept");return}let u=Y(t.projectId);if(!u){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"no secrets file for this project on the CLI"}),n.warn("[agent-auth] no secrets file for this project \u2014 token not saved");return}u.claude={oauthToken:c.oauthToken},ce(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()}}Ge();function Qp(t,e){let r=t.find(n=>n.kind==="claude");return r?.present===!0&&r.ok===!1?Q("ORIGIN")==="farm"||Q("CLAUDE_AUTOLOGIN")!=="1"||e?"none":"open":r?.ok===!0?"rearm":"none"}function ef(t,e){return`${t.replace(/\/$/,"")}/?project=${encodeURIComponent(e)}`}$i();import{existsSync as Tv}from"node:fs";import{join as Rv}from"node:path";import{simpleGit as Iv}from"simple-git";async function tf(t,e){if(!Tv(Rv(t,".git")))return{status:"skipped"};let r=Iv(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${Cv(o)}`}}let n=await r.status();if(!n.isClean())return{status:"warn",reason:"uncommitted changes \u2014 working copy left as-is"};if(n.current!==e)return{status:"warn",reason:`on '${n.current??"detached HEAD"}', not '${e}' \u2014 not fast-forwarded`};try{await r.merge(["--ff-only",`origin/${e}`])}catch{return{status:"warn",reason:`'${e}' can't fast-forward to origin (diverged) \u2014 not updated`}}return{status:"updated"}}function Cv(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as Sc,readFileSync as af,readdirSync as _v,watch as jv}from"node:fs";import{join as ho}from"node:path";B();import{existsSync as rf,readFileSync as nf,readdirSync as Pv,statSync as Av}from"node:fs";import{join as xc}from"node:path";import{parse as of}from"yaml";function vi(t){let e=xc(t,"actions"),r=[],n=[];if(!rf(e))return{defs:r,errors:n};let o;try{o=Pv(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=xc(e,s);try{if(!Av(a).isFile())continue;let c=Pa(s,of(nf(a,"utf-8")));if(i.has(c.id))throw new Error(`duplicate action id "${c.id}"`);i.add(c.id),r.push(c)}catch(c){n.push({file:`actions/${s}`,error:c instanceof Error?c.message:String(c)})}}return{defs:r,errors:n}}function sf(t){let e={},r=xc(t,"project.yaml");if(!rf(r))return e;let n;try{n=of(nf(r,"utf-8"))}catch{return e}if(!n||typeof n!="object")return e;let o=n.variables;if(!o||typeof o!="object"||Array.isArray(o))return e;for(let[i,s]of Object.entries(o))!Je.test(i)||Mt(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var xi=class{constructor(e,r,n,o,i=6e4){this.contextDir=e;this.projectId=r;this.send=n;this.log=o;this.intervalMs=i}timer=null;watchers=[];debounce=null;started=!1;start(){this.started||(this.started=!0,this.report(),this.timer=setInterval(()=>this.report(),this.intervalMs),this.timer.unref?.(),this.installWatcher())}stop(){this.started=!1,this.timer&&clearInterval(this.timer),this.timer=null,this.debounce&&clearTimeout(this.debounce),this.debounce=null;for(let e of this.watchers)try{e.close()}catch{}this.watchers=[]}installWatcher(){let e=()=>{this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>this.report(),500),this.debounce.unref?.()},r=[this.contextDir,ho(this.contextDir,"prompts"),ho(this.contextDir,"actions")];for(let n of r)if(Sc(n))try{let o=jv(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=vi(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(!Sc(r))return null;try{return af(r,"utf-8")}catch{return null}}readPrompts(){let e=ho(this.contextDir,"prompts"),r={};if(!Sc(e))return r;let n;try{n=_v(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=af(ho(e,o),"utf-8")}catch{}}return r}};lt();import{existsSync as _c,readFileSync as mf,readdirSync as qv}from"node:fs";import{join as hf}from"node:path";import{simpleGit as Yv}from"simple-git";var zv=/^(\d{4})-(.+)\.md$/,Vv="0000-template.md";function Xv(t){let e=t.split(`
942
+ `),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 Jv(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
943
+ `),a=s.findIndex(h=>h.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),u=[],p="",d=null,m=a>=0?a+1:0;for(let h=m;h<s.length;h++){let w=(s[h]??"").trim();if(w===""){m=h+1;continue}let $=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(w);if(!$)break;let S=($[1]??"").trim().toLowerCase(),R=($[2]??"").trim(),v=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(w);v&&(d=parseInt(v[1]??"",10)),S==="tasks"&&(p=R),l.has(S)||u.push(w),m=h+1}let f=p?p.includes(n)?p:`${p}, ${n}`:n,g=s.slice(m).join(`
944
+ `).replace(/^\n+/,""),k=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${f}`,...u,"",g].join(`
945
945
  `);return{content:k.endsWith(`
946
946
  `)?k:k+`
947
- `,supersedes:d}}function Xv(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
947
+ `,supersedes:d}}function Zv(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
948
948
 
949
- - **Status:** superseded by ADR-${r}`):n}function Jv(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(`
949
+ - **Status:** superseded by ADR-${r}`):n}function Qv(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(`
950
950
  `)+`
951
- `}async function mf(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await Wv(t).pull(void 0,void 0,["--rebase"])}catch{}let i=k=>o==="staging"?`adr/DRAFT-${k}.md`:`tasks/${e}/adr/DRAFT-${k}.md`,s=[],a=[];for(let k of r){let h=Te(t,i(k));if(!Ac(h)){a.push(k);continue}s.push({slug:k,content:pf(h,"utf-8")})}let c=ff(t,"adr"),l=new Map;if(Ac(c))for(let k of Hv(c)){let h=qv.exec(k);!h||k===Yv||l.set(k,{num:parseInt(h[1]??"",10),slug:h[2]??"",content:pf(ff(c,k),"utf-8")})}let u=Math.max(0,...[...l.values()].map(k=>k.num))+1,p=new Map,d=[],m=[];for(let k of s){if([...l.entries()].find(([,v])=>v.slug===k.slug&&v.content.includes(e))){m.push(k.slug);continue}let w=u++,$=`${String(w).padStart(4,"0")}-${k.slug}.md`,{content:S,supersedes:T}=Vv(k.content,w,k.slug,e,n);if(p.set($,S),l.set($,{num:w,slug:k.slug,content:S}),d.push(`adr/${$}`),T!==null){let v=[...l.keys()].find(b=>b.startsWith(`${String(T).padStart(4,"0")}-`));if(v&&v!==$){let b=Xv(p.get(v)??l.get(v).content,w);p.set(v,b),l.set(v,{...l.get(v),content:b})}}}let f=[];if(o==="staging")for(let k of s)Ac(Te(t,`adr/DRAFT-${k.slug}.md`))&&f.push({path:`adr/DRAFT-${k.slug}.md`,content:"",deleted:!0});if(d.length===0&&f.length===0)return{promoted:d,skipped:m,missing:a};if(d.length>0){let k=[...l.entries()].map(([h,w])=>({num:w.num,file:h,header:zv(w.content)}));p.set("INDEX.md",Jv(k))}for(let[k,h]of p.entries())f.push({path:`adr/${k}`,content:h});let y=d.length>0?`adr(${e}): promote ${s.map(k=>k.slug).join(", ")}`:`adr(${e}): drop stale staged ${m.join(", ")}`;return await Ce(t,f,y),{promoted:d,skipped:m,missing:a}}lt();Ci();Ft();B();import{existsSync as yf,readFileSync as sx}from"node:fs";import{join as wf}from"node:path";function ax(t){for(let e of[yt,qr]){let r=wf(t,e);if(yf(r))try{return ta(sx(r,"utf-8"))}catch{return 0}}return 0}function cx(t,e,r,n=6){let o=e<n,i=o?ra(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function Pi(t,e){return cx(e,ax(t),r=>yf(wf(t,r)))}B();Jt();import{existsSync as Cf,mkdirSync as Lx,mkdtempSync as Mx,rmSync as Pf,writeFileSync as Af}from"node:fs";import{tmpdir as Dx}from"node:os";import{dirname as Ux,join as _i}from"node:path";import{simpleGit as Oc}from"simple-git";Ar();function Bx(t){return`codepipe/context-migration-v${t}`}function Fx(t){let e=na(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 \`${yt}\` stamp (renamed from \`${qr}\``,"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(`
952
- `)}async function _f(t,e,r,n){let o=Oc(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Pi(t,e);if(!i.outdated)return i;let s=Bx(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 Gx(t,e,r,i,s,a,n):n.info(`[ctx] migration branch ${s} already on origin \u2014 reusing`)}catch(l){return n.warn(`[ctx] context migration branch failed (will retry next start): ${l instanceof Error?l.message:String(l)}`),i}if(!r)return i;let c={name:r.name,host:r.host,owner:r.owner,repoName:r.name};try{let l=Ir(c),u=await l.findOpenPrByBranch?.(c,s)??null;if(u)return n.info(`[ctx] migration PR already open: ${u.url}`),{...i,migrationPrUrl:u.url};let p=await l.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:s,baseBranch:a,title:`CodePipe: context format v${i.templateVersion} \u2192 v${i.currentVersion}`,body:Fx(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 Gx(t,e,r,n,o,i,s){let a=Oc(t),c=Mx(_i(Dx(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",o,c,`origin/${i}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},u={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},p=new Map(hn(l,u).map(y=>[y.path,y.content])),d=0;for(let y of n.missingPaths){if(y===yt)continue;let k=p.get(y);if(k==null){s.warn(`[ctx] migration: no template for ${y} \u2014 skipped`);continue}let h=_i(c,y);Cf(h)||(Lx(Ux(h),{recursive:!0}),Af(h,k),d++)}Af(_i(c,yt),Zn(n.currentVersion)),d++;let m=_i(c,qr);Cf(m)&&(Pf(m,{force:!0}),d++);let f=Oc(c);await f.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await f.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await f.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${d} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),Pf(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{existsSync as Kx,readFileSync as Hx,writeFileSync as Wx}from"node:fs";import{homedir as qx}from"node:os";import{join as jf}from"node:path";import{parseDocument as Yx}from"yaml";function zx(t,e){let r={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(r.default_branch=t.defaultBranch),e!==void 0&&(r.mirror=e),r}function Vx(t,e){let r=Yx(t),n=new Map,o=r.toJS();for(let i of o?.repos??[]){if(!i||typeof i!="object")continue;let s=typeof i.name=="string"?i.name:String(i.repo??"");s&&i.mirror!==void 0&&i.mirror!==null&&n.set(s,i.mirror)}return r.set("repos",e.map(i=>zx(i,n.get(i.name)))),r.toString()}function Xx(t,e){let r=[jf(qx(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(jf(e,"project.yaml")),r}function $o(t,e,r){let n=[],o=[];for(let i of Xx(t,r))if(Kx(i))try{let s=Hx(i,"utf-8"),a=Vx(s,e);a!==s&&(Wx(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}vo();dt();me();function aS(t,e){let r={};t.github?.token&&(r.github={token:t.github.token}),t.bitbucket?.apiToken&&(r.bitbucket={apiToken:t.bitbucket.apiToken}),t.gitlab?.token&&(r.gitlab={token:t.gitlab.token});let n=e??t.claude?.oauthToken;return n&&(r.claudeOauthToken=n),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),t.mirrorWrite?.token&&(r.mirrorWrite={token:t.mirrorWrite.token,...t.mirrorWrite.host?{host:t.mirrorWrite.host}:{}}),r}function Yf(t,e,r,n){let o=aS(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=fi(t.projectId,a.sandboxId,a.fingerprint);if(c==="mismatch"){n.warn(`[cred] SANDBOX ${a.name} (${a.sandboxId}) key fingerprint CHANGED \u2014 refusing to seal creds. Expected the pinned key; got ${a.fingerprint}. If this is intentional, clear the pin in the secrets file and re-run.`);continue}c==="pinned"&&n.info(`[cred] pinned SANDBOX ${a.name} (${a.sandboxId}) fingerprint ${a.fingerprint}`);let l;try{l=Gt(a.publicKey,i)}catch(u){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}dt();me();Jt();Cr();ln();Li();function Jf(t){let e=Y(t);if(!e)return null;if(!e.sealKey){let r=Oi();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},ue(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:He(e.sealKey.publicKey)}}async function Zf(t,e,r,n){let o;try{o=JSON.parse(yn(n,r).toString("utf-8"))}catch(s){return{ok:!1,detail:`cannot open the sealed credential (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}let i=Y(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await zt(o.token);return i.github={token:o.token},wn(i,()=>{process.env.GH_TOKEN=o.token,zf(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Xt(o.token);return i.gitlab={token:o.token},wn(i,()=>{process.env.GITLAB_TOKEN=o.token,Vf(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"bitbucket":{if(!o.email||!o.apiToken)return{ok:!1,detail:"payload needs email + apiToken"};let s=await Vt(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},wn(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,Xf(o.apiToken)}),{ok:!0,detail:`authenticated as ${s}`}}case"youtrack":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=o.url?.trim().replace(/\/$/,"")||i.youtrack?.url;if(!s)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await Qt({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},wn(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},wn(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},wn(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 wn(t,e){ue(t),e()}B();B();import{spawn as cS}from"node:child_process";var lS=124,Qf=16*1024,em=4e3;function uS(t,e,r,n,o,i){let s={...t},a=(c,l)=>{Mt(c)||(s[c]=l)};for(let[c,l]of Object.entries(e))a(c,l);for(let[c,l]of Object.entries(r))a(c,l);for(let[c,l]of Object.entries(n??{}))a(c,l);for(let[c,l]of Object.entries(o))s[c]=l;for(let[c,l]of Object.entries(i))s[`INPUT_${c}`]=String(l);return s}async function tm(t){let{def:e,onEvent:r}=t,n=uS(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
953
- `,o.length>Qf&&(o=o.slice(o.length-Qf))},s=(a,c)=>{let l=c.length>em?c.slice(0,em)+"\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 dS(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 dS(t,e,r,n,o){return new Promise(i=>{let s=cS("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??Ia)*1e3,l=setTimeout(()=>{a=!0,o("stderr",`step timed out after ${c/1e3}s \u2014 killing`),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},c);l.unref?.();let u=m=>{let f="";return{data:y=>{f+=y.toString("utf-8");let k;for(;(k=f.indexOf(`
954
- `))!==-1;)o(m,f.slice(0,k).replace(/\r$/,"")),f=f.slice(k+1)},flush:()=>{f.length>0&&o(m,f.replace(/\r$/,"")),f=""}}},p=u("stdout"),d=u("stderr");s.stdout?.on("data",p.data),s.stderr?.on("data",d.data),s.on("error",m=>{clearTimeout(l),o("stderr",`spawn failed: ${m.message}`),i(127)}),s.on("close",(m,f)=>{clearTimeout(l),p.flush(),d.flush(),i(a?lS:m??(f?1:0))})})}lt();lt();import{existsSync as pS,readFileSync as fS,statSync as rm}from"node:fs";var nm=2*1024*1024;function mS(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function om(t,e){let r=Te(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!pS(r)||!rm(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=rm(r);if(n>nm)throw new Error(`file too large: ${e} is ${n} bytes (limit ${nm})`);let o=fS(r);return mS(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}me();B();import{existsSync as hS,readFileSync as gS,writeFileSync as yS}from"node:fs";import{join as wS}from"node:path";import{parseDocument as kS}from"yaml";async function im(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=Ma(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=wS(t,o);if(!hS(s))throw new Error(`${o} not found in context repo (${t})`);let a=kS(gS(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);yS(s,a.toString()),n.push(o)}return{files:n}}Gc();import{existsSync as Kc,readFileSync as Hc,writeFileSync as bS}from"node:fs";import{join as Di}from"node:path";import{parseDocument as Wc}from"yaml";async function fm(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=Di(t,"project.yaml");if(!Kc(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=Wc(Hc(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=Di(t,"regimen.yaml");if(!Kc(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=Wc(Hc(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)bS(Di(t,i.path),i.content);return{files:r.map(i=>i.path)}}function Ui(t){if(!t)return"Stage";try{let e=Di(t,"project.yaml");if(!Kc(e))return"Stage";let n=Wc(Hc(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}Jt();ji();vo();B();lt();import{existsSync as KS,readFileSync as HS}from"node:fs";import{join as oh}from"node:path";import{simpleGit as il}from"simple-git";B();import{existsSync as mm,readFileSync as hm,readdirSync as $S}from"node:fs";import{join as qc}from"node:path";import{simpleGit as vS}from"simple-git";function xS(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(`
955
- `)){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 SS(t,e){let r=qc(t,`tasks/${e}/annotations`);if(!mm(r))return[];let n=[];for(let o of $S(r).sort())if(o.endsWith(".md")){try{let i=xS(o,hm(qc(r,o),"utf-8"));i&&n.push(i)}catch{}if(n.length>=pa)break}return n}var ES=12;async function gm(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=vS(o),p=[];for(let d of SS(e,r)){if(d.repo!==n)continue;let m=we("code",n,d.path);if(!a.has(m))continue;let f=l.get(m);if(!f)continue;let y=(await u.raw(["rev-parse",`${i}:${d.path}`]).catch(()=>"")).trim().slice(0,ES),k=sa(f),h=qc(e,k),w=p.find(R=>R.path===k),$=w?.content??(mm(h)?hm(h,"utf-8"):null),S=`<!-- ${r}${y?`:${y}`:""} -->`;if($?.includes(S))continue;let T=$??`---
951
+ `}async function gf(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await Yv(t).pull(void 0,void 0,["--rebase"])}catch{}let i=k=>o==="staging"?`adr/DRAFT-${k}.md`:`tasks/${e}/adr/DRAFT-${k}.md`,s=[],a=[];for(let k of r){let h=Ee(t,i(k));if(!_c(h)){a.push(k);continue}s.push({slug:k,content:mf(h,"utf-8")})}let c=hf(t,"adr"),l=new Map;if(_c(c))for(let k of qv(c)){let h=zv.exec(k);!h||k===Vv||l.set(k,{num:parseInt(h[1]??"",10),slug:h[2]??"",content:mf(hf(c,k),"utf-8")})}let u=Math.max(0,...[...l.values()].map(k=>k.num))+1,p=new Map,d=[],m=[];for(let k of s){if([...l.entries()].find(([,v])=>v.slug===k.slug&&v.content.includes(e))){m.push(k.slug);continue}let w=u++,$=`${String(w).padStart(4,"0")}-${k.slug}.md`,{content:S,supersedes:R}=Jv(k.content,w,k.slug,e,n);if(p.set($,S),l.set($,{num:w,slug:k.slug,content:S}),d.push(`adr/${$}`),R!==null){let v=[...l.keys()].find(b=>b.startsWith(`${String(R).padStart(4,"0")}-`));if(v&&v!==$){let b=Zv(p.get(v)??l.get(v).content,w);p.set(v,b),l.set(v,{...l.get(v),content:b})}}}let f=[];if(o==="staging")for(let k of s)_c(Ee(t,`adr/DRAFT-${k.slug}.md`))&&f.push({path:`adr/DRAFT-${k.slug}.md`,content:"",deleted:!0});if(d.length===0&&f.length===0)return{promoted:d,skipped:m,missing:a};if(d.length>0){let k=[...l.entries()].map(([h,w])=>({num:w.num,file:h,header:Xv(w.content)}));p.set("INDEX.md",Qv(k))}for(let[k,h]of p.entries())f.push({path:`adr/${k}`,content:h});let g=d.length>0?`adr(${e}): promote ${s.map(k=>k.slug).join(", ")}`:`adr(${e}): drop stale staged ${m.join(", ")}`;return await Ie(t,f,g),{promoted:d,skipped:m,missing:a}}lt();Ii();Ft();B();import{existsSync as kf,readFileSync as cx}from"node:fs";import{join as bf}from"node:path";function lx(t){for(let e of[yt,qr]){let r=bf(t,e);if(kf(r))try{return ra(cx(r,"utf-8"))}catch{return 0}}return 0}function ux(t,e,r,n=6){let o=e<n,i=o?na(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function Ci(t,e){return ux(e,lx(t),r=>kf(bf(t,r)))}B();Jt();import{existsSync as Af,mkdirSync as Dx,mkdtempSync as Ux,rmSync as _f,writeFileSync as jf}from"node:fs";import{tmpdir as Bx}from"node:os";import{dirname as Fx,join as Ai}from"node:path";import{simpleGit as Lc}from"simple-git";Ar();function Gx(t){return`codepipe/context-migration-v${t}`}function Kx(t){let e=oa(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 \`${yt}\` stamp (renamed from \`${qr}\``,"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(`
952
+ `)}async function Nf(t,e,r,n){let o=Lc(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Ci(t,e);if(!i.outdated)return i;let s=Gx(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 Hx(t,e,r,i,s,a,n):n.info(`[ctx] migration branch ${s} already on origin \u2014 reusing`)}catch(l){return n.warn(`[ctx] context migration branch failed (will retry next start): ${l instanceof Error?l.message:String(l)}`),i}if(!r)return i;let c={name:r.name,host:r.host,owner:r.owner,repoName:r.name};try{let l=Ir(c),u=await l.findOpenPrByBranch?.(c,s)??null;if(u)return n.info(`[ctx] migration PR already open: ${u.url}`),{...i,migrationPrUrl:u.url};let p=await l.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:s,baseBranch:a,title:`CodePipe: context format v${i.templateVersion} \u2192 v${i.currentVersion}`,body:Kx(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 Hx(t,e,r,n,o,i,s){let a=Lc(t),c=Ux(Ai(Bx(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",o,c,`origin/${i}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},u={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},p=new Map(hn(l,u).map(g=>[g.path,g.content])),d=0;for(let g of n.missingPaths){if(g===yt)continue;let k=p.get(g);if(k==null){s.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let h=Ai(c,g);Af(h)||(Dx(Fx(h),{recursive:!0}),jf(h,k),d++)}jf(Ai(c,yt),Zn(n.currentVersion)),d++;let m=Ai(c,qr);Af(m)&&(_f(m,{force:!0}),d++);let f=Lc(c);await f.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await f.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await f.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${d} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),_f(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{existsSync as Wx,readFileSync as qx,writeFileSync as Yx}from"node:fs";import{homedir as zx}from"node:os";import{join as Of}from"node:path";import{parseDocument as Vx}from"yaml";function Xx(t,e){let r={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(r.default_branch=t.defaultBranch),e!==void 0&&(r.mirror=e),r}function Jx(t,e){let r=Vx(t),n=new Map,o=r.toJS();for(let i of o?.repos??[]){if(!i||typeof i!="object")continue;let s=typeof i.name=="string"?i.name:String(i.repo??"");s&&i.mirror!==void 0&&i.mirror!==null&&n.set(s,i.mirror)}return r.set("repos",e.map(i=>Xx(i,n.get(i.name)))),r.toString()}function Zx(t,e){let r=[Of(zx(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(Of(e,"project.yaml")),r}function $o(t,e,r){let n=[],o=[];for(let i of Zx(t,r))if(Wx(i))try{let s=qx(i,"utf-8"),a=Jx(s,e);a!==s&&(Yx(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}vo();dt();fe();function lS(t,e){let r={};t.github?.token&&(r.github={token:t.github.token}),t.bitbucket?.apiToken&&(r.bitbucket={apiToken:t.bitbucket.apiToken}),t.gitlab?.token&&(r.gitlab={token:t.gitlab.token});let n=e??t.claude?.oauthToken;return n&&(r.claudeOauthToken=n),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),t.mirrorWrite?.token&&(r.mirrorWrite={token:t.mirrorWrite.token,...t.mirrorWrite.host?{host:t.mirrorWrite.host}:{}}),r}function Vf(t,e,r,n){let o=lS(e,r);t.sandboxes.length>0&&!o.claudeOauthToken&&n.warn("[cred] no Claude OAuth token set \u2014 agent jobs will fail in the SANDBOX. Set one with `codepipe login` (per project) or `make farm-config` (shared farm token)."),t.sandboxes.length>0&&!o.contextWrite&&(o.github||o.gitlab||o.bitbucket)&&n.warn("[cred] no dedicated contextWrite token \u2014 SANDBOX pushes deliveries with the project token of the context repo's host (broader scope than necessary). Set secrets.contextWrite.token (a token scoped to the Context Repo only) to tighten. NOTE (GitHub): the push token MUST have the `workflow` scope, else delivery pushes that carry `.github/workflows/*` are rejected.");let i=JSON.stringify(o),s=[];for(let a of t.sandboxes){let c=pi(t.projectId,a.sandboxId,a.fingerprint);if(c==="mismatch"){n.warn(`[cred] SANDBOX ${a.name} (${a.sandboxId}) key fingerprint CHANGED \u2014 refusing to seal creds. Expected the pinned key; got ${a.fingerprint}. If this is intentional, clear the pin in the secrets file and re-run.`);continue}c==="pinned"&&n.info(`[cred] pinned SANDBOX ${a.name} (${a.sandboxId}) fingerprint ${a.fingerprint}`);let l;try{l=Gt(a.publicKey,i)}catch(u){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}dt();fe();Jt();Cr();ln();Oi();function Qf(t){let e=Y(t);if(!e)return null;if(!e.sealKey){let r=Ni();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},ce(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:He(e.sealKey.publicKey)}}async function em(t,e,r,n){let o;try{o=JSON.parse(yn(n,r).toString("utf-8"))}catch(s){return{ok:!1,detail:`cannot open the sealed credential (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}let i=Y(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await zt(o.token);return i.github={token:o.token},wn(i,()=>{process.env.GH_TOKEN=o.token,Xf(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Xt(o.token);return i.gitlab={token:o.token},wn(i,()=>{process.env.GITLAB_TOKEN=o.token,Jf(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"bitbucket":{if(!o.email||!o.apiToken)return{ok:!1,detail:"payload needs email + apiToken"};let s=await Vt(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},wn(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,Zf(o.apiToken)}),{ok:!0,detail:`authenticated as ${s}`}}case"youtrack":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=o.url?.trim().replace(/\/$/,"")||i.youtrack?.url;if(!s)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await Qt({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},wn(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},wn(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},wn(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 wn(t,e){ce(t),e()}B();B();import{spawn as uS}from"node:child_process";var dS=124,tm=16*1024,rm=4e3;function pS(t,e,r,n,o,i){let s={...t},a=(c,l)=>{Mt(c)||(s[c]=l)};for(let[c,l]of Object.entries(e))a(c,l);for(let[c,l]of Object.entries(r))a(c,l);for(let[c,l]of Object.entries(n??{}))a(c,l);for(let[c,l]of Object.entries(o))s[c]=l;for(let[c,l]of Object.entries(i))s[`INPUT_${c}`]=String(l);return s}async function nm(t){let{def:e,onEvent:r}=t,n=pS(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
953
+ `,o.length>tm&&(o=o.slice(o.length-tm))},s=(a,c)=>{let l=c.length>rm?c.slice(0,rm)+"\u2026":c;i(l),r({ts:Date.now(),kind:"log",stream:a,text:l})};r({ts:Date.now(),kind:"start",status:"running"});for(let[a,c]of e.steps.entries()){let l=c.name??`step ${a+1}`;r({ts:Date.now(),kind:"step",stepName:l});let u=await fS(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 fS(t,e,r,n,o){return new Promise(i=>{let s=uS("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??Ca)*1e3,l=setTimeout(()=>{a=!0,o("stderr",`step timed out after ${c/1e3}s \u2014 killing`),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},c);l.unref?.();let u=m=>{let f="";return{data:g=>{f+=g.toString("utf-8");let k;for(;(k=f.indexOf(`
954
+ `))!==-1;)o(m,f.slice(0,k).replace(/\r$/,"")),f=f.slice(k+1)},flush:()=>{f.length>0&&o(m,f.replace(/\r$/,"")),f=""}}},p=u("stdout"),d=u("stderr");s.stdout?.on("data",p.data),s.stderr?.on("data",d.data),s.on("error",m=>{clearTimeout(l),o("stderr",`spawn failed: ${m.message}`),i(127)}),s.on("close",(m,f)=>{clearTimeout(l),p.flush(),d.flush(),i(a?dS:m??(f?1:0))})})}lt();lt();import{existsSync as mS,readFileSync as hS,statSync as om}from"node:fs";var im=2*1024*1024;function gS(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function sm(t,e){let r=Ee(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!mS(r)||!om(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=om(r);if(n>im)throw new Error(`file too large: ${e} is ${n} bytes (limit ${im})`);let o=hS(r);return gS(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}fe();B();import{existsSync as yS,readFileSync as wS,writeFileSync as kS}from"node:fs";import{join as bS}from"node:path";import{parseDocument as $S}from"yaml";async function am(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=Da(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=bS(t,o);if(!yS(s))throw new Error(`${o} not found in context repo (${t})`);let a=$S(wS(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);kS(s,a.toString()),n.push(o)}return{files:n}}Kc();import{existsSync as Hc,readFileSync as Wc,writeFileSync as vS}from"node:fs";import{join as Mi}from"node:path";import{parseDocument as qc}from"yaml";async function hm(t,e){let r=[];if(e.stageField!==void 0||e.sourceColumns!==void 0||e.rejectColumns!==void 0||e.doneColumns!==void 0||e.reviewColumns!==void 0||e.statusColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0||e.backlogScope!==void 0){let i=Mi(t,"project.yaml");if(!Hc(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=qc(Wc(i,"utf-8"));if(e.stageField!==void 0){let a=typeof e.stageField=="string"?e.stageField.trim():"";a&&a!=="Stage"?s.setIn(["youtrack","stage_field"],a):s.deleteIn(["youtrack","stage_field"])}if(e.rejectColumns!==void 0){let a=e.rejectColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","reject_columns"],a):s.deleteIn(["youtrack","reject_columns"])}if(e.doneColumns!==void 0){let a=e.doneColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","done_columns"],a):s.deleteIn(["youtrack","done_columns"])}if(e.reviewColumns!==void 0){let a=e.reviewColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","review_columns"],a):s.deleteIn(["youtrack","review_columns"])}if(e.statusColumns!==void 0){let a=e.statusColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","status_columns"],a):s.deleteIn(["youtrack","status_columns"])}if(e.sourceColumns!==void 0){let a=e.sourceColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);if(a.length===0)throw new Error("source_columns must be a non-empty list of non-empty strings");s.setIn(["youtrack","source_columns"],a)}if(e.backlogColumn!==void 0){let a=typeof e.backlogColumn=="string"?e.backlogColumn.trim():"";a?s.setIn(["youtrack","backlog_column"],a):s.deleteIn(["youtrack","backlog_column"])}if(e.assignee!==void 0){let a=typeof e.assignee=="string"?e.assignee.trim():"";a?s.setIn(["youtrack","assignee"],a):s.deleteIn(["youtrack","assignee"])}e.requireAssignee!==void 0&&s.setIn(["youtrack","require_assignee"],e.requireAssignee===!0),e.backlogScope!==void 0&&(e.backlogScope==="personal"?s.setIn(["youtrack","backlog_scope"],"personal"):e.backlogScope==="shared"?s.setIn(["youtrack","backlog_scope"],"shared"):s.deleteIn(["youtrack","backlog_scope"])),r.push({path:"project.yaml",content:s.toString()})}if(e.reviewStatus!==void 0||e.writes!==void 0){let i=Mi(t,"regimen.yaml");if(!Hc(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=qc(Wc(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)vS(Mi(t,i.path),i.content);return{files:r.map(i=>i.path)}}function Di(t){if(!t)return"Stage";try{let e=Mi(t,"project.yaml");if(!Hc(e))return"Stage";let n=qc(Wc(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}Jt();_i();vo();B();lt();import{existsSync as WS,readFileSync as qS}from"node:fs";import{join as sh}from"node:path";import{simpleGit as sl}from"simple-git";B();import{existsSync as gm,readFileSync as ym,readdirSync as xS}from"node:fs";import{join as Yc}from"node:path";import{simpleGit as SS}from"simple-git";function ES(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(`
955
+ `)){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 TS(t,e){let r=Yc(t,`tasks/${e}/annotations`);if(!gm(r))return[];let n=[];for(let o of xS(r).sort())if(o.endsWith(".md")){try{let i=ES(o,ym(Yc(r,o),"utf-8"));i&&n.push(i)}catch{}if(n.length>=fa)break}return n}var RS=12;async function wm(t){let{contextDir:e,taskKey:r,repoName:n,repoDir:o,commitSha:i,date:s,touchedKeys:a,identity:c}=t;if(!c)return[];let l=new Map(c.entities.filter(d=>d.status==="active").map(d=>[d.currentKey,d.entityId])),u=SS(o),p=[];for(let d of TS(e,r)){if(d.repo!==n)continue;let m=ye("code",n,d.path);if(!a.has(m))continue;let f=l.get(m);if(!f)continue;let g=(await u.raw(["rev-parse",`${i}:${d.path}`]).catch(()=>"")).trim().slice(0,RS),k=aa(f),h=Yc(e,k),w=p.find(I=>I.path===k),$=w?.content??(gm(h)?ym(h,"utf-8"):null),S=`<!-- ${r}${g?`:${g}`:""} -->`;if($?.includes(S))continue;let R=$??`---
956
956
  entityId: ${f}
957
957
  ---
958
958
 
@@ -960,34 +960,34 @@ entityId: ${f}
960
960
 
961
961
  Append-only. Keyed by entityId \u2014 never by path; entries survive renames.
962
962
  `,v=["",`## ${s} \u2014 ${r}`,S,"",d.body,""].join(`
963
- `),b=T+v;w?w.content=b:p.push({path:k,content:b})}return p}Zc();tl();Gi();nl();Ro();async function WS(t,e){let n=await il(t).raw(["diff","--numstat",`${e}^`,e]).catch(()=>""),o=[];for(let i of n.split(`
964
- `)){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 qS(t,e){let n=[`tasks/${e}/PLAN.md`,`tasks/${e}/SOLUTION.md`].find(i=>KS(oh(t,i)));if(!n)return{};let o=oh(t,n);try{let i=HS(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 ih(t){let{contextDir:e,repoDir:r,repoName:n,taskKey:o,commitSha:i}=t,s=bn(e),a=_r([...s.ignore,...kn]),c=await WS(r,i),l=(await il(r).raw(["show","-s","--format=%cs",i])).trim(),u=null,p=new Map;try{u=Qc(e,n),u&&(p=new Map(u.entities.filter(T=>T.status==="active").map(T=>[T.currentKey,T.entityId])))}catch{}let d=[];for(let T of c){if(a(T.path))continue;let v=we("code",n,T.path),b=p.get(v);d.push({key:v,...b?{entityId:b}:{},churn:T.churn})}if(d.length===0)return{recorded:!1};let m=qS(e,o),f=Bi(e,o),y=f?.origin==="pipeline"?f.files.filter(T=>re(T.key)?.repo!==n):[],k=f?.origin==="pipeline"?f.commits:[],h={modelFormatVersion:2,taskKey:o,origin:"pipeline",...f?.title?{title:f.title}:{},...l?{date:l}:{},commits:[...new Set([...k,i])],files:[...y,...d],links:{...f?.origin==="pipeline"?f.links:{},...m}};h.links&&Object.keys(h.links).length===0&&delete h.links;let w=[...Hi(e).filter(T=>T.taskKey!==o),h],$=Zm(Qm(e),w,o,s.cochange.halfLifeDays),S=await gm({contextDir:e,taskKey:o,repoName:n,repoDir:r,commitSha:i,date:l,touchedKeys:new Set(d.map(T=>T.key)),identity:u}).catch(()=>[]);await Ce(e,[{path:kr(o),content:zr(h)},{path:wr,content:Wi($)},...S],`model: task event ${o}`);{let{rebuildSearchIndex:T}=await Promise.resolve().then(()=>(Co(),Io));await T(e).catch(()=>{})}return{recorded:!0}}async function sh(t){let e=new Set([t.fallbackTaskKey]);try{let r=il(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(`
965
- `)){let s=i.trim();s&&e.add(s)}}catch{}for(let r of[...e].sort())await YS(t.contextDir,r,t.prUrl)}async function YS(t,e,r){let n=Bi(t,e);if(!n||n.origin!=="pipeline"||n.links?.pr===r)return;let o={...n,links:{...n.links??{},pr:r}};await Ce(t,[{path:kr(e),content:zr(o)}],`model: pr link for ${e}`)}Cr();import{existsSync as lh,readFileSync as uh}from"node:fs";import{join as dh}from"node:path";import{parseDocument as ph}from"yaml";Cr();var Po=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return Up(this.cfg,e)}getIssue(e,r){return Bp(this.cfg,e,r??Ui(this.contextDir))}listComments(e,r){return Fp(this.cfg,e,r)}downloadAttachment(e){return Dp(this.cfg,e)}updateStatus(e,r){return Cp(this.cfg,e,r,Ui(this.contextDir))}addComment(e,r,n){return Pp(this.cfg,e,r)}createIssue(e){return jp(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,Ui(this.contextDir))}editIssue(e,r){return Ap(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return Np(this.cfg,e,r,n)}fetchStateFields(e){return Kp(this.cfg,e)}};B();lt();import{existsSync as eE,readFileSync as tE}from"node:fs";import{randomBytes as rE}from"node:crypto";import{existsSync as sl,readFileSync as zS,readdirSync as VS}from"node:fs";B();lt();function Xi(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=QS(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:XS(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:ZS(JS(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 ah(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),sl(Te(t,`tasks/${c}/task.md`))))continue;let l=null;try{l=await r(c)}catch{continue}l&&(a.push({issue:l,comments:[],attachments:[]}),i.push(...s(l)))}return a}async function Ji(t,e,r){if(r.length===0)return;let n=Xi(t,e,r),o=r.map(i=>i.issue.key);await Ce(t,n,`sync(${o.join(", ")}): task data`)}function XS(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(`
966
- `)}function JS(t,e,r){let n=new Map,o=Te(t,`tasks/${e}/comments.jsonl`);if(sl(o))for(let i of zS(o,"utf-8").split(`
967
- `)){let s=i.trim();if(s)try{let a=JSON.parse(s);a&&typeof a.id=="string"&&n.set(a.id,a)}catch{}}for(let i of r){if(n.has(i.id))continue;let s={id:i.id,author:i.author,origin:"youtrack",body:i.body,createdAt:new Date(i.createdAt).toISOString()},a=Sr(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function ZS(t){return t.map(e=>JSON.stringify(e)).join(`
963
+ `),b=R+v;w?w.content=b:p.push({path:k,content:b})}return p}Qc();rl();Fi();ol();Ro();async function YS(t,e){let n=await sl(t).raw(["diff","--numstat",`${e}^`,e]).catch(()=>""),o=[];for(let i of n.split(`
964
+ `)){let s=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(i);if(!s)continue;let a=s[1]==="-"?0:Number(s[1]),c=s[2]==="-"?0:Number(s[2]);o.push({path:s[3],churn:a+c})}return o}function zS(t,e){let n=[`tasks/${e}/PLAN.md`,`tasks/${e}/SOLUTION.md`].find(i=>WS(sh(t,i)));if(!n)return{};let o=sh(t,n);try{let i=qS(o,"utf-8"),s=[...new Set(i.match(/\bADR-\d{3,4}\b/g)??[])].sort();return{solution:n,...s.length>0?{adr:s}:{}}}catch{return{solution:n}}}async function ah(t){let{contextDir:e,repoDir:r,repoName:n,taskKey:o,commitSha:i}=t,s=bn(e),a=_r([...s.ignore,...kn]),c=await YS(r,i),l=(await sl(r).raw(["show","-s","--format=%cs",i])).trim(),u=null,p=new Map;try{u=el(e,n),u&&(p=new Map(u.entities.filter(R=>R.status==="active").map(R=>[R.currentKey,R.entityId])))}catch{}let d=[];for(let R of c){if(a(R.path))continue;let v=ye("code",n,R.path),b=p.get(v);d.push({key:v,...b?{entityId:b}:{},churn:R.churn})}if(d.length===0)return{recorded:!1};let m=zS(e,o),f=Ui(e,o),g=f?.origin==="pipeline"?f.files.filter(R=>re(R.key)?.repo!==n):[],k=f?.origin==="pipeline"?f.commits:[],h={modelFormatVersion:2,taskKey:o,origin:"pipeline",...f?.title?{title:f.title}:{},...l?{date:l}:{},commits:[...new Set([...k,i])],files:[...g,...d],links:{...f?.origin==="pipeline"?f.links:{},...m}};h.links&&Object.keys(h.links).length===0&&delete h.links;let w=[...Ki(e).filter(R=>R.taskKey!==o),h],$=eh(th(e),w,o,s.cochange.halfLifeDays),S=await wm({contextDir:e,taskKey:o,repoName:n,repoDir:r,commitSha:i,date:l,touchedKeys:new Set(d.map(R=>R.key)),identity:u}).catch(()=>[]);await Ie(e,[{path:kr(o),content:zr(h)},{path:wr,content:Hi($)},...S],`model: task event ${o}`);{let{rebuildSearchIndex:R}=await Promise.resolve().then(()=>(Co(),Io));await R(e).catch(()=>{})}return{recorded:!0}}async function ch(t){let e=new Set([t.fallbackTaskKey]);try{let r=sl(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(`
965
+ `)){let s=i.trim();s&&e.add(s)}}catch{}for(let r of[...e].sort())await VS(t.contextDir,r,t.prUrl)}async function VS(t,e,r){let n=Ui(t,e);if(!n||n.origin!=="pipeline"||n.links?.pr===r)return;let o={...n,links:{...n.links??{},pr:r}};await Ie(t,[{path:kr(e),content:zr(o)}],`model: pr link for ${e}`)}Cr();import{existsSync as dh,readFileSync as ph}from"node:fs";import{join as fh}from"node:path";import{parseDocument as mh}from"yaml";Cr();var Po=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return Fp(this.cfg,e)}getIssue(e,r){return Gp(this.cfg,e,r??Di(this.contextDir))}listComments(e,r){return Kp(this.cfg,e,r)}downloadAttachment(e){return Bp(this.cfg,e)}updateStatus(e,r){return Ap(this.cfg,e,r,Di(this.contextDir))}addComment(e,r,n){return _p(this.cfg,e,r)}createIssue(e){return Op(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,Di(this.contextDir))}editIssue(e,r){return jp(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return Lp(this.cfg,e,r,n)}fetchStateFields(e){return Wp(this.cfg,e)}};B();lt();import{existsSync as rE,readFileSync as nE}from"node:fs";import{randomBytes as oE}from"node:crypto";import{existsSync as al,readFileSync as XS,readdirSync as JS}from"node:fs";B();lt();function Vi(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=tE(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:ZS(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:eE(QS(t,i,o.comments))});for(let a of o.attachments)n.push({path:`tasks/${i}/attachments/${a.name}`,content:a.contentBase64,encoding:"base64"})}return n}async function lh(t,e,r,n=10){let o=new Set(e.map(c=>c.issue.key)),i=[],s=c=>(c.links??[]).filter(l=>l.type==="subtask").map(l=>l.targetKey);for(let c of e)i.push(...s(c.issue));let a=[];for(;i.length>0&&a.length<n;){let c=i.shift();if(o.has(c)||(o.add(c),al(Ee(t,`tasks/${c}/task.md`))))continue;let l=null;try{l=await r(c)}catch{continue}l&&(a.push({issue:l,comments:[],attachments:[]}),i.push(...s(l)))}return a}async function Xi(t,e,r){if(r.length===0)return;let n=Vi(t,e,r),o=r.map(i=>i.issue.key);await Ie(t,n,`sync(${o.join(", ")}): task data`)}function ZS(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(`
966
+ `)}function QS(t,e,r){let n=new Map,o=Ee(t,`tasks/${e}/comments.jsonl`);if(al(o))for(let i of XS(o,"utf-8").split(`
967
+ `)){let s=i.trim();if(s)try{let a=JSON.parse(s);a&&typeof a.id=="string"&&n.set(a.id,a)}catch{}}for(let i of r){if(n.has(i.id))continue;let s={id:i.id,author:i.author,origin:"youtrack",body:i.body,createdAt:new Date(i.createdAt).toISOString()},a=Sr(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function eE(t){return t.map(e=>JSON.stringify(e)).join(`
968
968
  `)+(t.length>0?`
969
- `:"")}function QS(t,e,r){let n=[],o=Te(t,`tasks/${e}/attachments`);if(sl(o))for(let i of VS(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}Ai();var Ao=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await wo(this.contextDir);let r=e.columns??[];return Ef(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>bo(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=ko(this.contextDir,e);return r?bo(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return ch(this.contextDir,e).map(n=>({id:n.id,issueId:e,author:n.author,body:n.body,createdAt:n.createdAt}))}async downloadAttachment(e){throw new Error(`internal tracker: no remote attachments (${e})`)}async updateStatus(e,r){await this.mutateRecord(e,n=>({...n,status:r}))}async addComment(e,r,n){if(await wo(this.contextDir),!ko(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${rE(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=Sr(r);s&&(i.parsedCommand=s);let c=[...ch(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
969
+ `:"")}function tE(t,e,r){let n=[],o=Ee(t,`tasks/${e}/attachments`);if(al(o))for(let i of JS(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}Pi();var Ao=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await wo(this.contextDir);let r=e.columns??[];return Rf(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>bo(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=ko(this.contextDir,e);return r?bo(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return uh(this.contextDir,e).map(n=>({id:n.id,issueId:e,author:n.author,body:n.body,createdAt:n.createdAt}))}async downloadAttachment(e){throw new Error(`internal tracker: no remote attachments (${e})`)}async updateStatus(e,r){await this.mutateRecord(e,n=>({...n,status:r}))}async addComment(e,r,n){if(await wo(this.contextDir),!ko(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${oE(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=Sr(r);s&&(i.parsedCommand=s);let c=[...uh(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
970
970
  `)+`
971
- `;return await Ce(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 Tf(this.contextDir,this.config.prefix,o=>this.renderNewIssueFiles(o,e,r),o=>`tracker(${o}): create issue`);return{id:n,key:n}}async editIssue(e,r){await this.mutateRecord(e,n=>({...n,...r.title!==void 0?{title:r.title}:{}}),r.body)}async applyLink(e,r,n){let o=r==="subtask_of"?"subtask":"depends_on";await this.mutateRecord(e,i=>{let s=i.links.filter(a=>!(a.type===o&&a.targetKey===n));return s.push({type:o,targetKey:n}),{...i,links:s}})}async fetchStateFields(e){return[{name:"Status",values:li.statusColumns}]}async mutateRecord(e,r,n){let o=ko(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=bo(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:Qr(e),content:Nc(i)},...Xi(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await Ce(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:ao,status:r.targetStatus,links:[],created:n,updated:n},i=bo(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:Qr(e),content:Nc(o)},...Xi(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}};function ch(t,e){let r=Te(t,`tasks/${e}/comments.jsonl`);if(!eE(r))return[];let n=[];for(let o of tE(r,"utf-8").split(`
972
- `)){let i=o.trim();if(i)try{let s=JSON.parse(i);s&&typeof s.id=="string"&&typeof s.body=="string"&&n.push(s)}catch{}}return n}Ai();function al(t){if(!t)return"youtrack";try{let e=dh(t,"project.yaml");return lh(e)&&ph(uh(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function It(t){let e=al(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=xf(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=nE(n);return i?{ok:!0,kind:e,provider:new Ao(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=Rp();return r?{ok:!0,kind:e,provider:new Po(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function nE(t){try{let e=dh(t,"project.yaml");if(!lh(e))return null;let r=ph(uh(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var es=new Map;async function _o(t,e){let n=(es.get(t)??Promise.resolve()).catch(()=>{}).then(e);es.set(t,n);try{return await n}finally{es.get(t)===n&&es.delete(t)}}function jo(t,e){return fo(t.split(":",2)[0]??"",e)}function gh(t){let{mirror:e,...r}=t;return{spec:r,host:Ir(r)}}async function yh(t){let{action:e,repo:r}=t,n="repoName"in e?e.repoName:"-",o="taskId"in e?e.taskId:"draftId"in e?e.draftId:e.projectId;ut(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return Z("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return _o(`${i}/${r.name}`,async()=>{let s=await or(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=je(i,r.name,t.baseDir);if(r.mirror){let{syncUpstream:p}=await Promise.resolve().then(()=>(Qi(),Zi)),d=await p(r,a,{info:m=>ut(`[mirror] ${m}`),warn:m=>ut(`[mirror] WARN ${m}`)});d.error&&ut(`[mirror] ${r.name}: pre-apply sync failed \u2014 ${d.error}`)}let{commit:c,pushed:l,baseMoved:u}=await Mf(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force,push:e.push});if(t.contextDir){let p=e.taskId.split(":")[1]??"";p&&await ih({contextDir:t.contextDir,repoDir:a,repoName:r.name,taskKey:p,commitSha:c}).catch(d=>{ut(`[model] task event for ${p} failed: ${d instanceof Error?d.message:String(d)}`)})}return pe({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,pushed:l,...typeof u=="number"&&u>0?{baseMoved:u}:{},...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"push_branch":{if(!r)return Z("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return _o(`${i}/${r.name}`,async()=>{let s=await or(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=je(i,r.name,t.baseDir);return await Df(s,a,{branchName:e.branchName,force:e.force}),pe({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"create_pr":{if(!r)return Z("no repo spec");let{spec:i,host:s}=jo(e.taskId,r),a=await s.createPullRequest(i,e);if(t.contextDir){let c=e.taskId.split(":")[1]??"",l=e.taskId.split(":",2)[0]??"?";c&&await sh({contextDir:t.contextDir,repoDir:je(l,r.name,t.baseDir),branchName:e.branchName,baseBranch:e.baseBranch,fallbackTaskKey:c,prUrl:a.url}).catch(u=>{ut(`[model] pr link for ${c} failed: ${u instanceof Error?u.message:String(u)}`)})}return pe({url:a.url,number:a.number,host:s.name})}case"merge_pr":{if(!r)return Z("no repo spec");let{spec:i,host:s}=jo(e.taskId,r),a=await s.mergePR(i,e.prNumber,e.mergeMethod,e.deleteBranch);return pe({prNumber:e.prNumber,host:s.name,...a.mergedSha?{mergedSha:a.mergedSha}:{}})}case"close_pr":{if(!r)return Z("no repo spec");let{spec:i,host:s}=jo(e.taskId,r);return await s.closePR(i,e.prNumber,e.comment),pe({prNumber:e.prNumber,host:s.name})}case"rewrite_cluster_branch":{if(!r)return Z("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return _o(`${i}/${r.name}`,async()=>{let s=await or(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=je(i,r.name,t.baseDir),{commit:c,dropped:l}=await Uf(s,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:r.defaultBranch});return pe({branch:e.branchName,commit:c,dropped:l,pushed:l>0})})}case"merge_branch":{if(!r)return Z("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return _o(`${i}/${r.name}`,async()=>{let s=await or(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=je(i,r.name,t.baseDir),{mergedSha:c}=await Bf(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return pe({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return Z("no repo spec");let i=t.cloneUrlOverride??Ni(r),a=(await Ff(i)).filter(u=>Gf(u,e.issueKey)),c=Ir(r),l=null;if(c.findOpenPrByBranch)for(let u of a){let p=await c.findOpenPrByBranch(r,u).catch(()=>null);if(p){l={number:p.number,url:p.url};break}}return pe({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return Z("no repo spec");let{spec:i,host:s}=e.upstream?gh(r):jo(e.taskId,r);return await s.addPRComment(i,e.prNumber,e.body),pe({prNumber:e.prNumber,host:s.name})}case"add_pr_inline_comment":{if(!r)return Z("no repo spec");let{spec:i,host:s}=e.upstream?gh(r):jo(e.taskId,r);if(s.addPRInlineComment)try{return await s.addPRInlineComment(i,e.prNumber,e.path,e.line,e.body),pe({prNumber:e.prNumber,inline:!0,host:s.name})}catch(a){ut(`[exec] inline comment ${e.path}:${e.line} failed (${a instanceof Error?a.message.split(`
971
+ `;return await Ie(this.contextDir,[{path:`tasks/${e}/comments.jsonl`,content:c}],`tracker(${e}): comment`),{id:i.id}}async createIssue(e){let r=new Date().toISOString(),n=await If(this.contextDir,this.config.prefix,o=>this.renderNewIssueFiles(o,e,r),o=>`tracker(${o}): create issue`);return{id:n,key:n}}async editIssue(e,r){await this.mutateRecord(e,n=>({...n,...r.title!==void 0?{title:r.title}:{}}),r.body)}async applyLink(e,r,n){let o=r==="subtask_of"?"subtask":"depends_on";await this.mutateRecord(e,i=>{let s=i.links.filter(a=>!(a.type===o&&a.targetKey===n));return s.push({type:o,targetKey:n}),{...i,links:s}})}async fetchStateFields(e){return[{name:"Status",values:li.statusColumns}]}async mutateRecord(e,r,n){let o=ko(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=bo(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:Qr(e),content:Oc(i)},...Vi(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await Ie(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:ao,status:r.targetStatus,links:[],created:n,updated:n},i=bo(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:Qr(e),content:Oc(o)},...Vi(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}};function uh(t,e){let r=Ee(t,`tasks/${e}/comments.jsonl`);if(!rE(r))return[];let n=[];for(let o of nE(r,"utf-8").split(`
972
+ `)){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}Pi();function cl(t){if(!t)return"youtrack";try{let e=fh(t,"project.yaml");return dh(e)&&mh(ph(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function Ct(t){let e=cl(t.contextDir);if(e==="internal"){let n=t.contextDir;if(!n)return{ok:!1,kind:e,error:"internal tracker: no Context Repo clone on this CLI"};let o=Ef(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=iE(n);return i?{ok:!0,kind:e,provider:new Ao(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=Cp();return r?{ok:!0,kind:e,provider:new Po(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function iE(t){try{let e=fh(t,"project.yaml");if(!dh(e))return null;let r=mh(ph(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var Qi=new Map;async function _o(t,e){let n=(Qi.get(t)??Promise.resolve()).catch(()=>{}).then(e);Qi.set(t,n);try{return await n}finally{Qi.get(t)===n&&Qi.delete(t)}}function jo(t,e){return fo(t.split(":",2)[0]??"",e)}function wh(t){let{mirror:e,...r}=t;return{spec:r,host:Ir(r)}}async function kh(t){let{action:e,repo:r}=t,n="repoName"in e?e.repoName:"-",o="taskId"in e?e.taskId:"draftId"in e?e.draftId:e.projectId;ut(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return Z("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return _o(`${i}/${r.name}`,async()=>{let s=await or(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir);if(r.mirror){let{syncUpstream:p}=await Promise.resolve().then(()=>(Zi(),Ji)),d=await p(r,a,{info:m=>ut(`[mirror] ${m}`),warn:m=>ut(`[mirror] WARN ${m}`)});d.error&&ut(`[mirror] ${r.name}: pre-apply sync failed \u2014 ${d.error}`)}let{commit:c,pushed:l,baseMoved:u}=await Uf(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force,push:e.push});if(t.contextDir){let p=e.taskId.split(":")[1]??"";p&&await ah({contextDir:t.contextDir,repoDir:a,repoName:r.name,taskKey:p,commitSha:c}).catch(d=>{ut(`[model] task event for ${p} failed: ${d instanceof Error?d.message:String(d)}`)})}return de({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,pushed:l,...typeof u=="number"&&u>0?{baseMoved:u}:{},...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"push_branch":{if(!r)return Z("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return _o(`${i}/${r.name}`,async()=>{let s=await or(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir);return await Bf(s,a,{branchName:e.branchName,force:e.force}),de({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"create_pr":{if(!r)return Z("no repo spec");let{spec:i,host:s}=jo(e.taskId,r),a=await s.createPullRequest(i,e);if(t.contextDir){let c=e.taskId.split(":")[1]??"",l=e.taskId.split(":",2)[0]??"?";c&&await ch({contextDir:t.contextDir,repoDir:_e(l,r.name,t.baseDir),branchName:e.branchName,baseBranch:e.baseBranch,fallbackTaskKey:c,prUrl:a.url}).catch(u=>{ut(`[model] pr link for ${c} failed: ${u instanceof Error?u.message:String(u)}`)})}return de({url:a.url,number:a.number,host:s.name})}case"merge_pr":{if(!r)return Z("no repo spec");let{spec:i,host:s}=jo(e.taskId,r),a=await s.mergePR(i,e.prNumber,e.mergeMethod,e.deleteBranch);return de({prNumber:e.prNumber,host:s.name,...a.mergedSha?{mergedSha:a.mergedSha}:{}})}case"close_pr":{if(!r)return Z("no repo spec");let{spec:i,host:s}=jo(e.taskId,r);return await s.closePR(i,e.prNumber,e.comment),de({prNumber:e.prNumber,host:s.name})}case"rewrite_cluster_branch":{if(!r)return Z("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return _o(`${i}/${r.name}`,async()=>{let s=await or(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir),{commit:c,dropped:l}=await Ff(s,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:r.defaultBranch});return de({branch:e.branchName,commit:c,dropped:l,pushed:l>0})})}case"merge_branch":{if(!r)return Z("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return _o(`${i}/${r.name}`,async()=>{let s=await or(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir),{mergedSha:c}=await Gf(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return de({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return Z("no repo spec");let i=t.cloneUrlOverride??ji(r),a=(await Kf(i)).filter(u=>Hf(u,e.issueKey)),c=Ir(r),l=null;if(c.findOpenPrByBranch)for(let u of a){let p=await c.findOpenPrByBranch(r,u).catch(()=>null);if(p){l={number:p.number,url:p.url};break}}return de({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return Z("no repo spec");let{spec:i,host:s}=e.upstream?wh(r):jo(e.taskId,r);return await s.addPRComment(i,e.prNumber,e.body),de({prNumber:e.prNumber,host:s.name})}case"add_pr_inline_comment":{if(!r)return Z("no repo spec");let{spec:i,host:s}=e.upstream?wh(r):jo(e.taskId,r);if(s.addPRInlineComment)try{return await s.addPRInlineComment(i,e.prNumber,e.path,e.line,e.body),de({prNumber:e.prNumber,inline:!0,host:s.name})}catch(a){ut(`[exec] inline comment ${e.path}:${e.line} failed (${a instanceof Error?a.message.split(`
973
973
  `)[0]:String(a)}) \u2014 posting as a plain comment`)}return await s.addPRComment(i,e.prNumber,`\u{1F4CD} \`${e.path}:${e.line}\`
974
974
 
975
- ${e.body}`),pe({prNumber:e.prNumber,inline:!1,host:s.name})}case"tracker_status":{let i=It({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),pe({issueId:t.trackerIssueId,newStatus:e.newStatus})):Z("no tracker_issue_id provided"):Z(i.error)}case"tracker_comment":{let i=It({contextDir:t.contextDir});if(!i.ok)return Z(i.error);if(!t.trackerIssueId)return Z("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return pe({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=It({contextDir:t.contextDir});if(!i.ok)return Z(i.error);if(!e.projectKey)return Z("no projectKey in create_tracker_issue action");let{id:s,key:a}=await i.provider.createIssue({projectKey:e.projectKey,title:e.title,body:e.body,targetStatus:e.targetStatus});return pe({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=It({contextDir:t.contextDir});if(!i.ok)return Z(i.error);let s=0;for(let a of e.links)try{await i.provider.applyLink(a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return Z(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return pe({applied:s})}case"set_project_setting":{if(!t.contextDir)return Z("no context repo clone on this CLI");let i=await im(t.contextDir,e.edits);return pe({files:i.files})}case"set_prompt_override":{if(!t.contextDir)return Z("no context repo clone on this CLI");if(!Ga(e.role))return Z(`unknown prompt operation: ${e.role}`);let i=Ka(e.role);return await Ce(t.contextDir,[e.content===null?{path:i,content:"",deleted:!0}:{path:i,content:e.content}],e.commitMessage),t.requestConfigReport?.(),pe({path:i,reset:e.content===null})}case"tracker_edit":{let i=It({contextDir:t.contextDir});if(!i.ok)return Z(i.error);if(!t.contextDir)return Z("no context repo clone on this CLI");await i.provider.editIssue(e.issueKey,{...e.title!==void 0?{title:e.title}:{},...e.body!==void 0?{body:e.body}:{}});let s=await i.provider.getIssue(e.issueKey);return s&&await Ji(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),pe({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return Z("no context repo clone on this CLI");let i=await fm(t.contextDir,e);return pe({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return Z("no context repo clone on this CLI");let i=await dm(t.contextDir,e);return pe({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),pe({reported:!0})):Z("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return Z("no context repo clone on this CLI");let i=await t.refreshContextStatus();return pe({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return Z("no project workspace on this CLI");if(!r)return Z("no repo spec");if(!t.onRunActivity)return Z("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=xi(t.contextDir),c=s.find(m=>m.id===e.actionId);if(!c){let m=a.find(f=>f.file===`actions/${e.actionId}.yml`);return Z(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=Pa(c,e.input);if(!l.ok)return Z(l.error);let u=nf(t.contextDir),p=Y(e.projectId),d={};return p?.github?.token&&(d.GH_TOKEN=p.github.token),p?.gitlab?.token&&(d.GITLAB_TOKEN=p.gitlab.token),p?.bitbucket&&(d.BITBUCKET_EMAIL=p.bitbucket.email,d.BITBUCKET_API_TOKEN=p.bitbucket.apiToken),p?.youtrack&&(d.YOUTRACK_URL=p.youtrack.url,d.YOUTRACK_TOKEN=p.youtrack.token),_o(`${e.projectId}/${r.name}`,async()=>{await or(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=je(e.projectId,r.name,t.baseDir),f=await tm({cwd:m,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:y=>i(e.runId,y)});return pe({runId:e.runId,status:f.status,exitCode:f.exitCode,...f.failedStep?{failedStep:f.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return Z("no context repo clone on this CLI");let i=om(t.contextDir,e.path);return pe({path:e.path,...i})}case"search_model":{if(!t.contextDir)return Z("no context repo clone on this CLI");let{searchModelIndex:i}=await Promise.resolve().then(()=>(Co(),Io)),s=await i(t.contextDir,e.q,e.limit);return pe({hits:s})}case"model_drift":return Z("model_drift requires a local workspace (handled by the daemon)");case"model_bootstrap":return Z("model_bootstrap requires a local workspace (handled by the daemon)");default:return Z(`unsupported action type: ${e.type}`)}}catch(i){return Z(i instanceof Error?i.message:String(i))}}function pe(t){return{status:"done",result:t}}function Z(t){return{status:"failed",error:t}}dt();ul();Ne();me();import{existsSync as _h,readFileSync as jh}from"node:fs";import{join as Nh}from"node:path";async function Oh(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=He(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");rs(e.farmId,e.farmPublicKey);let s=Y(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await le(t.hubUrl,t.cliToken,t.projectId),c;if(r){let d=Nh(r,"project.yaml"),m=Nh(r,"regimen.yaml");_h(d)&&_h(m)?c={projectYaml:jh(d,"utf-8"),regimenYaml:jh(m,"utf-8")}:n.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},u=Gt(e.farmPublicKey,JSON.stringify(l));ts(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let p=await os(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))}}B();dt();Ge();dt();import{homedir as wE}from"node:os";import{existsSync as kE,mkdirSync as bE,readFileSync as $E,writeFileSync as vE}from"node:fs";import{dirname as xE,join as SE}from"node:path";function fl(){return Q("RUNNER_PINS")??SE(wE(),".codepipe","runner-pins.json")}function Lh(){let t=fl();if(!kE(t))return{};try{return JSON.parse($E(t,"utf-8"))}catch{return{}}}function EE(t){let e=fl();bE(xE(e),{recursive:!0}),vE(e,JSON.stringify(t,null,2)+`
976
- `,{mode:384})}function TE(t){return Lh()[t]}function ml(t,e){let r=Lh();r[t]=e,EE(r)}function Mh(t,e){let r=He(e),n=TE(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 ${fl()}.`);return r}Ne();me();var Uh=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function Dh(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:Uh(t)});if(!o.ok)throw new Error(`github ${n} for ${e}/${r}: HTTP ${o.status}`);let i=await o.json();if(!i.token)throw new Error(`github ${n} for ${e}/${r}: no token in response`);return i.token}var RE={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Uh(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)=>Dh(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Dh(t,e,r,"remove-token")},Bh={api:RE,fetchProject:le,provisionOnRunner:bh,teardownOnRunner:$h};async function Fh(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(He(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Mh(e.runnerId,e.runnerPublicKey);let i=Y(t.projectId)?.github?.token;if(!i)throw new Error("no GitHub token stored for this project on this CLI");let a=((await r.fetchProject(t.hubUrl,t.cliToken,t.projectId)).repos??[]).find(c=>c.host==="github"&&c.owner===e.owner&&c.repoName===e.repo);if(!a)throw new Error(`${e.owner}/${e.repo} is not a GitHub repository of this project`);return{githubToken:i,repo:a}}async function Gh(t,e,r,n=Bh){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 Fh(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:[Va(e.runnerId)]},c=Gt(e.runnerPublicKey,JSON.stringify(a));ml(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 Kh(t,e,r,n=Bh){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 Fh(t,e,n),a={owner:s.owner,repo:s.repoName};try{a.removeToken=await n.api.mintRemoveToken(i,s.owner,s.repoName)}catch(p){r.warn(`[ghr] remove-token for ${s.owner}/${s.repoName} failed (${p instanceof Error?p.message:p}) \u2014 the runner host will force-remove`)}let c={projectId:t.projectId,runners:[a]},l=Gt(e.runnerPublicKey,JSON.stringify(c));ml(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))}}Ne();B();dt();me();var Hh=16*1024;function IE(t){return Je.test(t)?Mt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Je}`}function Wh(t,e,r,n){let o=IE(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(yn(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>Hh)return{ok:!1,detail:`secret value too large (max ${Hh} chars)`};try{return tp(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function qh(t,e){try{return rp(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)}}}ln();me();Jt();var ss=class{constructor(e,r,n){this.intervalMs=e;this.send=r;this.log=n}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let n=[],o=e.split(":",2)[0]??"";for(let a of r.prs){let{spec:c,host:l}=fo(o,a.repoSpec);try{let u=await l.getPullRequest(c,a.number);n.push({number:a.number,repoName:a.repoSpec.name,url:a.url,state:u.state,merged:u.merged,ci:u.ci,mergeable:u.mergeable})}catch(u){if(u instanceof Rr){this.log.warn(`[track] task=${e} pr=${a.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${a.url} fetch failed: ${u instanceof Error?u.message:String(u)}`);return}}let i=n.map(a=>`${a.repoName??""}#${a.number}:${a.state}:${a.merged?1:0}:${a.ci}:${a.mergeable}`).join("|");if(this.lastSig.get(e)===i)return;for(let a=0;a<n.length;a++){let c=n[a];if(c.ci!=="failed")continue;let{spec:l,host:u}=fo(o,r.prs[a].repoSpec);if(u.getCiFailureLog)try{let p=await u.getCiFailureLog(l,c.number);p&&(c.ciFailureLog=p)}catch(p){this.log.warn(`[track] task=${e} pr=${c.url} ci-log fetch failed: ${p instanceof Error?p.message:String(p)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:n}),this.lastSig.set(e,i);let s=CE(n);this.log.info(`[track] task=${e} snapshot signalled${s?` \u2192 ${s}`:""} (${n.length} PR(s))`)}};function CE(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}B();var as=class t{constructor(e,r,n,o={contextDir:null}){this.intervalMs=e;this.send=r;this.log=n;this.options=o}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;abandonedTicks=0;static MAX_ABANDONED_TICKS=3;setRequest(e){let r=this.request?.projectId;this.request=e,this.log.info(`[yt-sync] request updated: project=${e.projectKey} columns=[${e.sourceColumns.join(",")}] sinceMs=${e.sinceMs} offBoard=${e.offBoardIssueIds.length}`),this.timer||this.start(),r&&r!==e.projectId&&this.log.info(`[yt-sync] project switch ${r} \u2192 ${e.projectId}`)}start(){if(this.timer)return;this.log.info(`[yt-sync] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[yt-sync] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[yt-sync] poller stopped"))}async tickOnce(){await this.tick()}async forceSync(){if(!this.request){this.log.info("[yt-sync] force requested but no sync_request yet \u2014 ignored");return}this.log.info("[yt-sync] force sync requested (manual)"),await this.tick()}async tick(){if(this.running||!this.request)return;let r=(this.options.resolveProvider??(()=>It({contextDir:this.options.contextDir})))();if(!r.ok){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn(`[yt-sync] tracker provider unavailable (${r.error}) \u2014 poller idle.`));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,r.provider)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let $=e.stageField?{stageField:e.stageField}:{},S=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},v=(e.backlogScope??"personal")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(v){let b=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[R,j]=await Promise.all([b.length>0?r.listIssues({projectKey:e.projectKey,columns:b,...$,...S}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...$})]),G=new Map;for(let X of[...R,...j])G.set(X.id,X);o=[...G.values()]}else{let b=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:b,...$,...S})}}catch($){let S=$ instanceof Error?$.message:String($);S.includes("stage_field")?this.log.warn(`[yt-sync] CONFIGURATION ERROR \u2014 ${S}`):this.log.warn(`[yt-sync] listIssues failed: ${S}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let $ of o){if(s.add($.id),a.has($.status))continue;let S=await Vh(r,$.id,e.sinceMs,this.log);S&&i.set($.id,S)}let c=[];for(let $ of e.offBoardIssueIds){if(s.has($))continue;let S=await Vh(r,$,e.sinceMs,this.log);if(S&&S.length>0&&i.set($,S),e.requireAssignee||S&&S.length>0){let T=await zh(r,$,e.stageField,this.log);if(T)c.push(T);else if(S&&S.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter($=>!a.has($.status)),{attachmentsByIssue:u,attachmentKeys:p}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let d=[...l,...c].map($=>({issue:$,comments:i.get($.id)??[],attachments:u.get($.id)??[]}));d.push(...await ah(this.options.contextDir,d,$=>zh(r,$,e.stageField,this.log)));try{await Ji(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let $ of p)this.shippedAttachments.add($)}catch($){let S=$ instanceof Error?$.message:String($);this.abandonTick(`context task sync failed: ${S}`);return}let m=this.options.isSelfComment??(()=>!1),f=[],y=[];for(let[$,S]of i){let T=S.filter(b=>!m(b.id));if(T.length===0)continue;f.push({issueId:$,comments:T.map(PE)});let v=T.flatMap(b=>{let R=Sr(b.body);return R?[{commentId:b.id,author:b.author,name:R.name,args:R.args,createdAt:b.createdAt}]:[]});v.length>0&&y.push({issueId:$,commands:v})}let k={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Yh),commentsBatch:f,...y.length>0?{commandsBatch:y}:{},...c.length>0?{offBoardIssues:c.map(Yh)}:{},observedAtMs:n};this.send(k);let h=f.reduce(($,S)=>$+S.comments.length,0),w=y.reduce(($,S)=>$+S.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${h} commands=${w} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let p=`${s.id}:${u.id}`;if(this.shippedAttachments.has(p))continue;let d;try{d=await n.downloadAttachment(u.url)}catch(f){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${f instanceof Error?f.message:String(f)}`);continue}let m=AE(u.name);l.has(m)&&(m=`${u.id}-${m}`),l.add(m),c.push({name:m,contentBase64:d.toString("base64")}),i.push(p)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}};function Yh(t){let{description:e,...r}=t;return r}function PE(t){let{body:e,...r}=t;return r}function AE(t){let r=(t.split(/[\\/]/).pop()??t).replace(/[^A-Za-z0-9._-]/g,"_").replace(/^\.+/,"");return r.length>0?r.slice(0,120):"attachment"}async function zh(t,e,r,n){try{return await t.getIssue(e,r)}catch(o){return n.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function Vh(t,e,r,n){try{return await t.listComments(e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function YE(t,e){let r=t.repos.filter(i=>i.mirror);if(r.length===0)return[];let{mirrorLag:n}=await Promise.resolve().then(()=>(Qi(),Zi)),o=[];for(let i of r){let s=i.mountAs==="."?t.root:Nr(t.root,i.mountAs);try{o.push({repo:i.name,behind:await n(i,s)})}catch(a){e.warn(`[mirror] lag for ${i.name} unknown: ${a instanceof Error?a.message:String(a)}`),o.push({repo:i.name,behind:null})}}return o}var El="npm i -g @code-partner/codepipe@latest";function ps(t,e={}){let r=e.log??{info:h=>console.log(h),warn:h=>console.warn(h)};r.info(`codepipe-cli v${Ve} (protocol ${gt})`);let n=h=>e.onEvent?.(h),o=e.workspace;o?.contextDir&&af(o.contextDir,r);let i=()=>{if(o?.contextDir)try{fn(o.contextDir,o.root,r)}catch(h){r.warn(`[skills] materialize failed (non-fatal): ${h instanceof Error?h.message:String(h)}`)}};i();let s=cg("CLI_TRACKING_POLL_INTERVAL_SEC"),a=cg("CLI_YOUTRACK_POLL_INTERVAL_SEC"),c=(()=>{let h=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(h)&&h>0?h*1e3:6e5})(),l=!1,u=!1,p=!1,d=new Set,m=!1,f=new Set,y=k();function k(){let h=ns(t.hubUrl,t.cliToken),w=null,$=new ss(s,M=>{h.readyState===h.OPEN&&h.send(JSON.stringify(M))},r),S=new as(a,M=>{h.readyState===h.OPEN&&h.send(JSON.stringify(M))},r,{contextDir:o?.contextDir??null,isSelfComment:M=>f.has(M)}),T=null,v=async()=>{try{let M={trackerProvider:al(o?.contextDir??null)};try{let E=await le(t.hubUrl,t.cliToken,t.projectId);M={...M,repos:E.repos,contextRepo:E.contextRepo}}catch(E){r.warn(`[readiness] could not fetch project summary for push checks: ${E instanceof Error?E.message:String(E)}`)}let F=await Wp(t.projectId,M),D=o?await YE(o,r):[];if(i(),h.readyState!==h.OPEN)return;let z={type:"cli_readiness",projectId:t.projectId,ready:F.ready,checks:F.checks,creds:F.creds,secretNames:np(t.projectId),...o?{mirrors:D}:{},checkedAt:F.checkedAt};if(h.send(JSON.stringify(z)),F.ready)r.info("[readiness] ready");else{let E=F.checks.filter(I=>!I.ok).map(I=>`${I.name}(${I.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${E.join(", ")}`)}let W=Jp(F.creds,p);if(W==="open"){p=!0;let E=Zp(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${E}`),Pr(E)}else W==="rearm"&&(p=!1)}catch(M){r.warn(`[readiness] check failed: ${M instanceof Error?M.message:String(M)}`)}},b=()=>{v(),T=setInterval(()=>void v(),c),typeof T.unref=="function"&&T.unref()},R=()=>{T&&(clearInterval(T),T=null)},j=150,G=new Map,X=M=>{let F=G.get(M);if(!F||(F.timer&&clearTimeout(F.timer),G.delete(M),F.events.length===0||h.readyState!==h.OPEN))return;let D={type:"run_activity",projectId:t.projectId,runId:M,events:F.events};h.send(JSON.stringify(D))},A=(M,F)=>{let D=G.get(M);if(D||(D={events:[],timer:null},G.set(M,D)),D.events.push(F),F.kind==="result"){X(M);return}D.timer||(D.timer=setTimeout(()=>X(M),j),D.timer.unref?.())},g=o?.contextDir?new Si(o.contextDir,t.projectId,M=>{h.readyState===h.OPEN&&h.send(JSON.stringify(M))},r):null,U=async()=>{let M=o?.contextDir;if(!M)throw new Error("no context repo clone on this CLI");let F;try{F=(await le(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let D=await _f(M,t.projectId,F,r);return h.readyState===h.OPEN&&h.send(JSON.stringify(D)),D},N=null,H=async()=>{let M=o?.contextDir;if(M)try{let{readContextIndexHub:F,collectSearchRows:D}=await Promise.resolve().then(()=>(Co(),Io));if(F(M)!=="metadata")return;let z=D(M);h.readyState===h.OPEN&&(h.send(JSON.stringify({type:"model_index",projectId:t.projectId,rows:z})),r.info(`[model] tier-2 index snapshot pushed (${z.length} rows)`))}catch(F){r.warn(`[model] tier-2 index push failed (non-fatal): ${F instanceof Error?F.message:String(F)}`)}},ee=()=>{N&&clearTimeout(N),N=setTimeout(()=>void H(),5e3)},se=null,jt=async M=>{if(o?.contextDir)try{let{rebuildWorkspaceModelIfStale:F}=await Promise.resolve().then(()=>(Lo(),ds));(await F({root:o.root,contextDir:o.contextDir,repos:o.repos},{fetch:M,onLog:z=>r.info(z)})).rebuilt.length>0&&ee()}catch(F){r.warn(`[model] release-path rebuild failed (non-fatal): ${F instanceof Error?F.message:String(F)}`)}},ft=M=>{se&&clearTimeout(se),se=setTimeout(()=>void jt(M),6e4)},Ue=setInterval(()=>void jt(!0),6*36e5);return h.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let M=dp(t.projectId),F=Q("ORIGIN")==="farm"?"farm":"local",D=Q("FARM_ID"),z=t.accountEmail??M.email,W;try{let I=Jf(t.projectId);I&&(W=I.publicKey,r.info(`[cred-channel] key fingerprint: ${I.fingerprint}`))}catch(I){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${I instanceof Error?I.message:String(I)}`)}let E={type:"register",projectId:t.projectId,platformVersion:Ve,protocolVersion:gt,accountId:M.accountId,accountLabel:M.label,origin:F,inFlightActionIds:[...d],...z?{accountEmail:z}:{},...F==="farm"&&D?{farmId:D}:{},...W?{sealPublicKey:W}:{}};h.send(JSON.stringify(E))}),h.on("message",async M=>{let F=M.toString("utf-8");if(F==="pong"||F==="ping")return;let D;try{D=JSON.parse(F)}catch{return}if(!D||typeof D!="object")return;let z=D.type;if(z==="registered"){let E=D;if(E.ok){if(r.info(`[ws] registered for project ${E.projectId}`),n({kind:"registered",projectId:E.projectId??t.projectId}),$.start(),g?.start(),b(),Tl(t,o,r),o?.contextDir){try{let I=Pi(o.contextDir,t.projectId);h.readyState===h.OPEN&&h.send(JSON.stringify(I)),I.outdated&&(r.warn(`[ctx] context format outdated: v${I.templateVersion} \u2192 v${I.currentVersion}`+(I.missingPaths.length>0?` (missing: ${I.missingPaths.join(", ")})`:"")),u||(u=!0,U().catch(()=>{})))}catch(I){r.warn(`[ctx] context-format detect failed (non-fatal): ${I instanceof Error?I.message:String(I)}`)}H(),ft(!0)}}else r.warn(`[ws] register rejected: ${E.reason??"unknown"}`),n({kind:"register_rejected",reason:E.reason??"unknown"}),l=!0,h.close();return}if(z==="hello"){let E=D;w=Jn(E.protocolVersion);let I=w?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${E.platformVersion} (protocol ${E.protocolVersion}) \u2014 ${I}`),w||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Ve}, protocol ${gt}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${El}`),n({kind:"incompatible",hubVersion:typeof E.platformVersion=="string"?E.platformVersion:null,hubProtocol:typeof E.protocolVersion=="number"?E.protocolVersion:null,updateCommand:El}));return}if(z==="tracking_targets"){$.setTargets(D.targets);return}if(z==="youtrack_sync_request"){S.setRequest(D);return}if(z==="youtrack_force_sync"){S.forceSync();return}if(z==="sync_local"){await XE(D,o,h,r);return}if(z==="provision_repo"){let E=D;r.info(`[repo] provision_repo: ${E.repo.name} (${E.repo.host}:${E.repo.owner}/${E.repo.repoName})`),await zE(t,o,E.repo,r),await Tl(t,o,r);return}if(z==="remove_repo"){let E=D;r.info(`[repo] remove_repo: ${E.repoName}${E.purge?" (purge)":""}`),await Tl(t,o,r),E.purge&&VE(t,o,E.repoName,r);return}if(z==="context_write"){await JE(D,o,h,r),i();return}if(z==="adr_promote"){await ZE(D,o,h,r),i();return}if(z==="cred_update"){let E=D,I=Y(t.projectId),te=I?.sealKey?await Zf(t.projectId,E.kind,E.sealed,I.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},ae={type:"cred_update_result",updateId:E.updateId,projectId:t.projectId,ok:te.ok,...te.detail?{detail:te.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(ae)),te.ok?(r.info(`[cred] ${E.kind} replaced${te.detail?` \u2014 ${te.detail}`:""}`),v()):r.warn(`[cred] ${E.kind} replacement rejected: ${te.detail??"unknown"}`);return}if(z==="readiness_check"){r.info("[readiness] on-demand check requested"),v();return}if(z==="agent_login_start"){Xp(t,h,D,r,v);return}if(z==="move_to_farm"){let E=D;r.info(`[farm-move] request to move ${t.projectId} onto farm ${E.farmName} (${E.farmId})`);let I=await Oh(t,E,o?.contextDir,r);h.readyState===h.OPEN&&h.send(JSON.stringify(I)),I.ok?r.info(`[farm-move] done \u2014 farm daemon ${I.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${I.error??"unknown error"}`);return}if(z==="gh_runner_setup"){let E=D;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${E.runnerName} (${E.runnerId})`);let I=await Gh(t,E,r);h.readyState===h.OPEN&&h.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners connected on ${E.runnerName}`):r.warn(`[ghr] setup failed: ${I.error??"see per-repo statuses"}`);return}if(z==="gh_runner_teardown"){let E=D;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${E.runnerName} (${E.runnerId})`);let I=await Kh(t,E,r);h.readyState===h.OPEN&&h.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners disconnected from ${E.runnerName}`):r.warn(`[ghr] teardown failed: ${I.error??"unknown error"}`);return}if(z==="tracker_fields_request"){let E=D,I={type:"tracker_fields_result",requestId:E.requestId,projectId:t.projectId,ok:!1},te=It({contextDir:o?.contextDir??null});if(!te.ok)I.error=te.error;else try{I.fields=await te.provider.fetchStateFields(E.projectKey),I.ok=!0}catch(ae){I.error=ae instanceof Error?ae.message:String(ae)}h.readyState===h.OPEN&&h.send(JSON.stringify(I)),I.ok||r.warn(`[yt-fields] listing failed: ${I.error??"unknown"}`);return}if(z==="project_secret_update"||z==="project_secret_delete"){let E=D,I;if(E.type==="project_secret_update"){let ae=Y(t.projectId);I=ae?.sealKey?Wh(t.projectId,E.name,E.sealed,ae.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else I=qh(t.projectId,E.name);let te={type:"project_secret_update_result",updateId:E.updateId,projectId:t.projectId,ok:I.ok,...I.detail?{detail:I.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(te)),I.ok?(r.info(`[secret] ${E.name} ${E.type==="project_secret_update"?"saved":"deleted"}`+(I.detail?` \u2014 ${I.detail}`:"")),v()):r.warn(`[secret] ${E.name} rejected: ${I.detail??"unknown"}`);return}if(z==="sandbox_keys"){let E=Y(t.projectId);if(!E){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let I=on(t.projectId),te=Yf(D,E,I,r);for(let ae of te)h.readyState===h.OPEN&&h.send(JSON.stringify(ae));return}if(z!=="dispatch_action")return;let W=D;if(w===!1){let E=`refused: HUB protocol incompatible with CLI v${Ve} (protocol ${gt})`;h.send(JSON.stringify({type:"action_result",actionId:W.actionId,status:"failed",error:E})),r.warn(`[exec] ${W.actionId} (${W.action.type}) \u2192 REFUSED: ${E}`),r.warn(`[exec] update the CLI to clear this: ${El}`),n({kind:"action",actionId:W.actionId,actionType:W.action.type,ok:!1,error:E});return}if(W.action.type==="model_drift"){d.add(W.actionId);try{let E,I=o?.repos.find(te=>te.name===W.action.repoName);if(!o?.contextDir||!I)E={status:"failed",error:"no local workspace/repo clone on this CLI"};else try{let{computeDriftReport:te}=await Promise.resolve().then(()=>(ag(),sg)),ae=I.mountAs==="."?o.root:Nr(o.root,I.mountAs);E={status:"done",result:{report:await te(ae,o.contextDir,I.name)}}}catch(te){E={status:"failed",error:te instanceof Error?te.message:String(te)}}h.send(JSON.stringify({type:"action_result",actionId:W.actionId,...E}))}finally{d.delete(W.actionId)}return}if(W.action.type==="model_bootstrap"){d.add(W.actionId);try{let E;if(!o?.contextDir)E={status:"failed",error:"no Context Repo clone on this CLI"};else if(m)E={status:"failed",error:"model bootstrap is already running"};else{m=!0;try{let I=await le(t.hubUrl,t.cliToken,t.projectId),{bootstrapDaemonModel:te}=await Promise.resolve().then(()=>(Lo(),ds)),ae=await te(t.projectId,{root:o.root,contextDir:o.contextDir},I.repos,P=>r.info(`[model] ${P}`));r.info(`[model] bootstrap done: ${ae.repos} repos, ${ae.events} task events`),ee(),E={status:"done",result:{repos:ae.repos,events:ae.events}}}catch(I){E={status:"failed",error:I instanceof Error?I.message:String(I)},r.warn(`[model] bootstrap failed: ${E.error}`)}finally{m=!1}}h.readyState===h.OPEN&&h.send(JSON.stringify({type:"action_result",actionId:W.actionId,...E}))}finally{d.delete(W.actionId)}return}d.add(W.actionId);try{let E=await yh({action:W.action,repo:W.repo,trackerIssueId:W.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:g?()=>g.reportNow():void 0,refreshContextStatus:o?.contextDir?U:void 0,onRunActivity:A}).catch(ae=>({status:"failed",error:ae instanceof Error?ae.message:String(ae)}));W.action.type==="tracker_comment"&&E.status==="done"&&"result"in E&&typeof E.result?.commentId=="string"&&f.add(E.result.commentId),h.send(JSON.stringify({type:"action_result",actionId:W.actionId,...E}));let I=E.status!=="failed",te=!I&&"error"in E?E.error:void 0;I?r.info(`[exec] ${W.actionId} (${W.action.type}) \u2192 done`):r.warn(`[exec] ${W.actionId} (${W.action.type}) \u2192 FAILED: ${te??"?"}`),n({kind:"action",actionId:W.actionId,actionType:W.action.type,ok:I,...te?{error:te}:{}}),I&&["apply_delivery","context_write","create_pr"].includes(W.action.type)&&ee(),I&&["merge_pr","merge_branch"].includes(W.action.type)&&ft(!0)}finally{d.delete(W.actionId)}}),h.on("close",(M,F)=>{let D=F?.toString("utf-8")??"";if(r.info(`[ws] closed code=${M}${D?` reason=${D}`:""}`),$.stop(),S.stop(),g?.stop(),R(),clearInterval(Ue),se&&clearTimeout(se),N&&clearTimeout(N),D==="replaced"){l=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:M}),!l&&setTimeout(()=>{y=k()},2e3)}),h.on("error",M=>r.warn(`[ws] error: ${M.message}`)),h}return{stop(){l=!0,y.close()}}}async function Tl(t,e,r){try{let n=await le(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=$o(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 zE(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?Nr(e.root,o):je(t.projectId,r.name);if(lg(Nr(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await qE().clone(e?Ni(r):Uc(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 VE(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?Nr(e.root,o):je(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!lg(Nr(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{WE(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 XE(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=Nr(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Qp(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 JE(t,e,r,n){let o=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{await Ce(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 ZE(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 mf(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 cg(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}Ne();me();Ft();Il();it();Li();async function $g(t={profile:void 0}){let{cfg:e,profile:r}=nn(t.profile),n=Y(e.projectId);n&&po(n),xo(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),So(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),Eo(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=Mo(Cl(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=hi("CLI_LOG",i,o);if(s.enabled){let d=new an(s);gi(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=tn(e.projectId);if(c&&(a={root:c.root,contextDir:c.contextDir,repos:c.spec.repos},console.log(`[ctx] workspace found at ${c.root} \u2014 using its Context Repo clone`)),!a){let d=Mo(Cl(),".codepipe",r?Mo("profiles",r,"context"):"context");if(await pl(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await kg(()=>ms({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 pl(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let m=Mo(Cl(),".codepipe",r?Mo("profiles",r,"context-config"):"context-config");Ei(a.contextDir,m,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=ps(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(`
977
- [${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}On();Ke();Ne();async function Aw(t={profile:void 0}){let e=st(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=ns(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 le(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=Le(t.profile);o?o.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${o.sandboxId} (${o.name}), llm=${o.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${o.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}Yo();import{readFileSync as pP}from"node:fs";B();Ke();Ft();Ho();Ar();Jt();Cr();Ne();me();function Se(t){throw new Error(t)}function Pe(t,e){return(typeof t!="string"||t.trim().length===0)&&Se(`config: '${e}' must be a non-empty string`),t.trim()}function Xo(t,e){if(t==null)return;typeof t!="string"&&Se(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function fP(t){(!t||typeof t!="object")&&Se("config: expected a JSON object");let e=t,r=Pe(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||Se("config: 'hubUrl' must start with http(s)://");let n=Pe(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&Se("config: 'project' is required");let i=o,s=Pe(i.id,"project.id");Yt.test(s)||Se("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=Pe(i.name,"project.name"),c=Pe(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&Se("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||Se("config: 'project.repos' must be an array");let u=l.map((w,$)=>{(!w||typeof w!="object")&&Se(`config: project.repos[${$}] must be an object`);let S=w,T=Pe(S.host,`project.repos[${$}].host`);T!=="github"&&T!=="bitbucket"&&T!=="gitlab"&&Se(`config: project.repos[${$}].host must be 'github', 'bitbucket' or 'gitlab'`);let v={name:Pe(S.name,`project.repos[${$}].name`),host:T,owner:Pe(S.owner,`project.repos[${$}].owner`),repoName:Pe(S.repoName,`project.repos[${$}].repoName`)},b=Xo(S.defaultBranch,`project.repos[${$}].defaultBranch`);b&&(v.defaultBranch=b);let R=Xo(S.mountAs,`project.repos[${$}].mountAs`);return R&&(v.mountAs=R),v}),p=i.contextRepo;(!p||typeof p!="object")&&Se("config: 'project.contextRepo' is required");let d=p,m=Xo(d.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&Se("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:m,owner:Pe(d.owner,"project.contextRepo.owner"),name:Xo(d.name,"project.contextRepo.name")??St(s)},y={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:f}},k=Xo(i.youtrackProjectKey,"project.youtrackProjectKey");if(k&&(y.project.youtrackProjectKey=k),i.index!==void 0&&(typeof i.index!="boolean"&&Se("config: 'project.index' must be a boolean"),y.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&Se("config: 'project.youtrackWrites' must be a boolean"),y.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let w=Pe(i.llmProvider,"project.llmProvider");w==="codex"&&Se(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),w!=="claude"&&Se("config: 'project.llmProvider' must be 'claude'"),y.project.llmProvider=w}let h=e.secrets;if(h!==void 0){(typeof h!="object"||h===null)&&Se("config: 'secrets' must be an object");let w=h,$={};if(w.github){let S=w.github;$.github={token:Pe(S.token,"secrets.github.token")}}if(w.bitbucket){let S=w.bitbucket;$.bitbucket={email:Pe(S.email,"secrets.bitbucket.email"),apiToken:Pe(S.apiToken,"secrets.bitbucket.apiToken")}}if(w.gitlab){let S=w.gitlab;$.gitlab={token:Pe(S.token,"secrets.gitlab.token")}}if(w.youtrack){let S=w.youtrack;$.youtrack={url:Pe(S.url,"secrets.youtrack.url").replace(/\/$/,""),token:Pe(S.token,"secrets.youtrack.token")}}if(w.contextWrite){let S=w.contextWrite;$.contextWrite={token:Pe(S.token,"secrets.contextWrite.token")}}y.secrets=$}return y}async function mP(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function hP(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await zt(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${n}`)}if(e.bitbucket){let r=t.project.repos.find(i=>i.host==="bitbucket"),n=r?.owner??(t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:void 0),o=await Vt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await bi(e.bitbucket.email,e.bitbucket.apiToken,r.owner,r.repoName);if(i)throw new Error(`Bitbucket: ${i}`)}console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await Xt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Qt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Lk(t){let e=!t.configPath||t.configPath==="-"?await mP():pP(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){Se(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=fP(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 hP(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 Ln(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??sn(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){Se(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let u;try{u=await ir(o,i,a)}catch(d){if(d instanceof K&&d.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await le(o,i,s.id);else if(d instanceof K)Se(`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(ue(p),Ut({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Et(s.id)}`),tr(s.id,Rt(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,s.llmProvider??Xe),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await Oo(o,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${d}); runs once a SANDBOX claims it.`)}catch(d){console.warn(`could not enqueue index job: ${d instanceof Error?d.message:String(d)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}Ke();me();import{cancel as Mk,intro as Dk,isCancel as Uk,log as lu,outro as gP,password as Bk}from"@clack/prompts";async function yP(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Fk(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await yP(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Dk("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),lu.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Bk({message:"Claude OAuth token"});Uk(i)&&(Mk("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),ip({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${mi()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=st(t.profile);if(!e){Dk(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),lu.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Bk({message:"Claude OAuth token"});Uk(i)&&(Mk("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=Y(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},ue(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(lu.success("Claude OAuth token saved."),gP("It will be sealed into job bundles when a SANDBOX (re)connects."))}Lo();B();Ke();Ft();Ho();Ar();As();Ne();me();import{cancel as wP,confirm as kP,intro as bP,isCancel as Gk,log as Me,outro as $P,select as Kk,text as hr}from"@clack/prompts";function Hk(t){wP(t),process.exit(1)}function Fn(t){return Gk(t)&&Hk("aborted"),t}function Jo(t){return Gk(t)&&Hk("aborted"),typeof t=="string"?t:""}async function vP(t,e){let r=Fn(await Kk({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),n=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",o=Jo(await hr({message:"Context Repo owner (org / group / workspace / user)",placeholder:n||"your-org",initialValue:n,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=Jo(await hr({message:"Context Repo name",placeholder:St(t),initialValue:St(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function Wk(t={profile:void 0}){let e=st(t.profile);bP(`codepipe project add \u2192 ${e.hubUrl}`);let r=Fn(await hr({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>Yt.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=Fn(await hr({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=Fn(await Kk({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=Fn(await hr({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Fn(await kP({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=Jo(await hr({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:h=>!h||!h.trim()||Ye(h)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!d)break;let m=Ye(d);Me.message(`${m.host}: ${m.owner}/${m.repoName}`);let f=Jo(await hr({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:h=>h.trim().length>0?void 0:"required"})).trim(),y=Jo(await hr({message:"default branch (optional)",placeholder:"main"})).trim(),k={name:f,host:m.host,owner:m.owner,repoName:m.repoName};y&&(k.defaultBranch=y),a.push(k)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await vP(r,a),u=Y(e.projectId);Me.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await Ln(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??sn(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:d=>Me.message(d),warn:d=>Me.warn(d)}})}catch(d){Me.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,Me.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await ir(e.hubUrl,e.cliToken,c);Me.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),tr(r,Rt(c,s,u?.youtrack?.url),{info:m=>Me.message(m),warn:m=>Me.warn(m)}),d.contextRepo&&(Me.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),Me.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&Me.error(` error: ${d.provisioningError}`),$P("done")}catch(d){d instanceof K?(Me.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&Me.message(JSON.stringify(d.payload,null,2))):Me.error(d instanceof Error?d.message:String(d)),process.exit(1)}}On();Ke();Ne();me();it();Yo();import{existsSync as xP,rmSync as SP}from"node:fs";import{confirm as EP,intro as TP,isCancel as RP,log as gr,outro as IP,spinner as CP}from"@clack/prompts";function _t(t){gr.error(t),process.exit(1)}var qk=t=>t.trim().replace(/\/+$/,"");async function Yk(t){TP("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??_e()?.spec.projectId??void 0;e||_t("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=kt(e);r||_t(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=qk(r.hubUrl),o=r.projectId,i=qk(t.hub);i.startsWith("http")||_t("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&_t(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let h=CP();h.start(`reading project ${o} from ${n}\u2026`);try{l=await le(n,r.cliToken,o),h.stop(`read project ${o} (${l.name})`)}catch(w){throw h.stop("could not read the source project",1),w instanceof K&&_t(`source HUB ${n} \u2192 ${w.status} ${w.message}. The source HUB must be reachable with a valid token to move a project.`),w}}l.contextRepo||_t(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=Y(o),p=(t.account??r.accountEmail??await Un()).trim().toLowerCase();if(gr.message(`move project '${o}'
975
+ ${e.body}`),de({prNumber:e.prNumber,inline:!1,host:s.name})}case"tracker_status":{let i=Ct({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),de({issueId:t.trackerIssueId,newStatus:e.newStatus})):Z("no tracker_issue_id provided"):Z(i.error)}case"tracker_comment":{let i=Ct({contextDir:t.contextDir});if(!i.ok)return Z(i.error);if(!t.trackerIssueId)return Z("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return de({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Ct({contextDir:t.contextDir});if(!i.ok)return Z(i.error);if(!e.projectKey)return Z("no projectKey in create_tracker_issue action");let{id:s,key:a}=await i.provider.createIssue({projectKey:e.projectKey,title:e.title,body:e.body,targetStatus:e.targetStatus});return de({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Ct({contextDir:t.contextDir});if(!i.ok)return Z(i.error);let s=0;for(let a of e.links)try{await i.provider.applyLink(a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return Z(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return de({applied:s})}case"set_project_setting":{if(!t.contextDir)return Z("no context repo clone on this CLI");let i=await am(t.contextDir,e.edits);return de({files:i.files})}case"set_prompt_override":{if(!t.contextDir)return Z("no context repo clone on this CLI");if(!Ka(e.role))return Z(`unknown prompt operation: ${e.role}`);let i=Ha(e.role);return await Ie(t.contextDir,[e.content===null?{path:i,content:"",deleted:!0}:{path:i,content:e.content}],e.commitMessage),t.requestConfigReport?.(),de({path:i,reset:e.content===null})}case"tracker_edit":{let i=Ct({contextDir:t.contextDir});if(!i.ok)return Z(i.error);if(!t.contextDir)return Z("no context repo clone on this CLI");await i.provider.editIssue(e.issueKey,{...e.title!==void 0?{title:e.title}:{},...e.body!==void 0?{body:e.body}:{}});let s=await i.provider.getIssue(e.issueKey);return s&&await Xi(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),de({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return Z("no context repo clone on this CLI");let i=await hm(t.contextDir,e);return de({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return Z("no context repo clone on this CLI");let i=await fm(t.contextDir,e);return de({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),de({reported:!0})):Z("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return Z("no context repo clone on this CLI");let i=await t.refreshContextStatus();return de({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return Z("no project workspace on this CLI");if(!r)return Z("no repo spec");if(!t.onRunActivity)return Z("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=vi(t.contextDir),c=s.find(m=>m.id===e.actionId);if(!c){let m=a.find(f=>f.file===`actions/${e.actionId}.yml`);return Z(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=Aa(c,e.input);if(!l.ok)return Z(l.error);let u=sf(t.contextDir),p=Y(e.projectId),d={};return p?.github?.token&&(d.GH_TOKEN=p.github.token),p?.gitlab?.token&&(d.GITLAB_TOKEN=p.gitlab.token),p?.bitbucket&&(d.BITBUCKET_EMAIL=p.bitbucket.email,d.BITBUCKET_API_TOKEN=p.bitbucket.apiToken),p?.youtrack&&(d.YOUTRACK_URL=p.youtrack.url,d.YOUTRACK_TOKEN=p.youtrack.token),_o(`${e.projectId}/${r.name}`,async()=>{await or(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=_e(e.projectId,r.name,t.baseDir),f=await nm({cwd:m,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:g=>i(e.runId,g)});return de({runId:e.runId,status:f.status,exitCode:f.exitCode,...f.failedStep?{failedStep:f.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return Z("no context repo clone on this CLI");let i=sm(t.contextDir,e.path);return de({path:e.path,...i})}case"search_model":{if(!t.contextDir)return Z("no context repo clone on this CLI");let{searchModelIndex:i}=await Promise.resolve().then(()=>(Co(),Io)),s=await i(t.contextDir,e.q,e.limit);return de({hits:s})}case"model_drift":return Z("model_drift requires a local workspace (handled by the daemon)");case"model_bootstrap":return Z("model_bootstrap requires a local workspace (handled by the daemon)");default:return Z(`unsupported action type: ${e.type}`)}}catch(i){return Z(i instanceof Error?i.message:String(i))}}function de(t){return{status:"done",result:t}}function Z(t){return{status:"failed",error:t}}dt();dl();je();fe();import{existsSync as jh,readFileSync as Nh}from"node:fs";import{join as Oh}from"node:path";async function Lh(t,e,r,n){let o=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return o(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=He(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");ts(e.farmId,e.farmPublicKey);let s=Y(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await ae(t.hubUrl,t.cliToken,t.projectId),c;if(r){let d=Oh(r,"project.yaml"),m=Oh(r,"regimen.yaml");jh(d)&&jh(m)?c={projectYaml:Nh(d,"utf-8"),regimenYaml:Nh(m,"utf-8")}:n.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},u=Gt(e.farmPublicKey,JSON.stringify(l));es(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let p=await ns(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:u});return p.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...p.daemonStatus?{daemonStatus:p.daemonStatus}:{}}:o(p.error??"farm provisioning failed")}catch(i){return o(i instanceof Error?i.message:String(i))}}B();dt();Ge();dt();import{homedir as bE}from"node:os";import{existsSync as $E,mkdirSync as vE,readFileSync as xE,writeFileSync as SE}from"node:fs";import{dirname as EE,join as TE}from"node:path";function ml(){return Q("RUNNER_PINS")??TE(bE(),".codepipe","runner-pins.json")}function Mh(){let t=ml();if(!$E(t))return{};try{return JSON.parse(xE(t,"utf-8"))}catch{return{}}}function RE(t){let e=ml();vE(EE(e),{recursive:!0}),SE(e,JSON.stringify(t,null,2)+`
976
+ `,{mode:384})}function IE(t){return Mh()[t]}function hl(t,e){let r=Mh();r[t]=e,RE(r)}function Dh(t,e){let r=He(e),n=IE(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 ${ml()}.`);return r}je();fe();var Bh=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function Uh(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:Bh(t)});if(!o.ok)throw new Error(`github ${n} for ${e}/${r}: HTTP ${o.status}`);let i=await o.json();if(!i.token)throw new Error(`github ${n} for ${e}/${r}: no token in response`);return i.token}var CE={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Bh(t)});if(!n.ok)throw new Error(`github GET /repos/${e}/${r}: HTTP ${n.status}`);return(await n.json()).permissions?.admin===!0},mintRegistrationToken:(t,e,r)=>Uh(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Uh(t,e,r,"remove-token")},Fh={api:CE,fetchProject:ae,provisionOnRunner:vh,teardownOnRunner:xh};async function Gh(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(He(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Dh(e.runnerId,e.runnerPublicKey);let i=Y(t.projectId)?.github?.token;if(!i)throw new Error("no GitHub token stored for this project on this CLI");let a=((await r.fetchProject(t.hubUrl,t.cliToken,t.projectId)).repos??[]).find(c=>c.host==="github"&&c.owner===e.owner&&c.repoName===e.repo);if(!a)throw new Error(`${e.owner}/${e.repo} is not a GitHub repository of this project`);return{githubToken:i,repo:a}}async function Kh(t,e,r,n=Fh){let o=i=>({type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repo:s}=await Gh(t,e,n);if(!await n.api.repoHasAdmin(i,s.owner,s.repoName))return o(`the GitHub token lacks admin access on ${s.owner}/${s.repoName} \u2014 replace it (project page \u2192 Tokens \u2192 Replace) with a token that has admin rights on this repository`);let a={projectId:t.projectId,runners:[{owner:s.owner,repo:s.repoName,regToken:await n.api.mintRegistrationToken(i,s.owner,s.repoName)}],labels:[Xa(e.runnerId)]},c=Gt(e.runnerPublicKey,JSON.stringify(a));hl(e.runnerId,e.fingerprint),r.info(`[ghr] registration token for ${s.owner}/${s.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let l=await n.provisionOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:c});return{type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:l.ok,...l.runners?{runners:l.runners}:{},...l.error?{error:l.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}async function Hh(t,e,r,n=Fh){let o=i=>({type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repo:s}=await Gh(t,e,n),a={owner:s.owner,repo:s.repoName};try{a.removeToken=await n.api.mintRemoveToken(i,s.owner,s.repoName)}catch(p){r.warn(`[ghr] remove-token for ${s.owner}/${s.repoName} failed (${p instanceof Error?p.message:p}) \u2014 the runner host will force-remove`)}let c={projectId:t.projectId,runners:[a]},l=Gt(e.runnerPublicKey,JSON.stringify(c));hl(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle for ${s.owner}/${s.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let u=await n.teardownOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:l,owner:s.owner,repo:s.repoName});return{type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:u.ok,...u.error?{error:u.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}je();B();import{existsSync as PE}from"node:fs";import{join as Wh}from"node:path";import{simpleGit as Yh}from"simple-git";async function gl(t,e,r,n,o){for(let i of r.repos){let s=e.find(u=>u.name===i.repoName);if(!s)continue;let a=`${r.taskKey}:${s.name}:${i.branchName}`;if(!so(i.branchName)){n.has(a)||(n.add(a),o.warn(`[pull] ${r.taskKey} ${s.mountAs}: refusing suspicious branch name`));continue}let c=Wh(t,s.mountAs);if(!PE(Wh(c,".git")))continue;let l=Yh(c);try{let u=await jE(l,i.branchName);await l.fetch(await AE(l,s),`refs/heads/${i.branchName}`);let p=(await l.revparse(["FETCH_HEAD"])).trim();if(u===p)continue;if(await _E(l,c,i.branchName)){n.has(a)||(n.add(a),o.info(`[pull] ${r.taskKey} \u2192 ${s.mountAs}: ${i.branchName} is checked out here \u2014 fetched ${p.slice(0,10)}; merge or pull it in that checkout yourself`));continue}await l.raw(["branch","-f",i.branchName,p]),o.info(`[pull] ${r.taskKey} \u2192 ${s.mountAs}: ${i.branchName} ${p.slice(0,10)} (checkout untouched)`)}catch(u){if(n.has(a))continue;n.add(a),o.warn(`[pull] ${r.taskKey} ${s.mountAs}: ${i.branchName} unavailable \u2014 `+(u instanceof Error?u.message.split(`
977
+ `)[0]:String(u)))}}}async function AE(t,e){if(e.mirror)return qh(e.mirror);try{if((await t.getRemotes(!0)).find(n=>n.name==="origin")?.refs?.fetch)return"origin"}catch{}return e.host&&e.owner&&e.repoName?qh({host:e.host,owner:e.owner,repoName:e.repoName}):"origin"}function qh(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}async function _E(t,e,r){try{return(await t.raw(["worktree","list","--porcelain"])).split(`
978
+ `).some(o=>o.trim()===`branch refs/heads/${r}`)}catch{try{return(await Yh(e).revparse(["--abbrev-ref","HEAD"])).trim()===r}catch{return!1}}}async function jE(t,e){try{return(await t.revparse([e])).trim()}catch{return null}}var ss=class{constructor(e,r,n,o){this.intervalMs=e;this.fetchDeliverables=r;this.workspace=n;this.log=o}timer=null;running=!1;caughtUp=!1;warned=new Set;start(){if(this.timer)return;this.log.info(`[pull] local delivery started (interval=${this.intervalMs}ms)`);let e=()=>void this.runOnce();e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[pull] local delivery stopped"))}poke(){this.runOnce()}async runOnce(){if(!this.running){this.running=!0;try{let e=await this.fetchDeliverables(),r=this.caughtUp?e.filter(n=>n.phase==="TRACKING"||n.phase==="AWAITING_CLUSTER"):e;for(let n of r)await gl(this.workspace.root,this.workspace.repos,n,this.warned,this.log);this.caughtUp=!0}catch(e){this.log.warn(`[pull] pass failed: ${e instanceof Error?e.message:String(e)}`)}finally{this.running=!1}}}};B();dt();fe();var zh=16*1024;function NE(t){return Je.test(t)?Mt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Je}`}function Vh(t,e,r,n){let o=NE(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(yn(n,r).toString("utf-8"));if(typeof s.value!="string"||s.value.length===0)return{ok:!1,detail:"payload has no value"};i=s.value}catch(s){return{ok:!1,detail:`cannot open the sealed secret (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}if(i.length>zh)return{ok:!1,detail:`secret value too large (max ${zh} chars)`};try{return np(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function Xh(t,e){try{return op(t,e)?{ok:!0}:{ok:!0,detail:"no such secret (already absent)"}}catch(r){return{ok:!1,detail:r instanceof Error?r.message:String(r)}}}ln();fe();Jt();var as=class{constructor(e,r,n){this.intervalMs=e;this.send=r;this.log=n}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let n=[],o=e.split(":",2)[0]??"";for(let a of r.prs){let{spec:c,host:l}=fo(o,a.repoSpec);try{let u=await l.getPullRequest(c,a.number);n.push({number:a.number,repoName:a.repoSpec.name,url:a.url,state:u.state,merged:u.merged,ci:u.ci,mergeable:u.mergeable})}catch(u){if(u instanceof Rr){this.log.warn(`[track] task=${e} pr=${a.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${a.url} fetch failed: ${u instanceof Error?u.message:String(u)}`);return}}let i=n.map(a=>`${a.repoName??""}#${a.number}:${a.state}:${a.merged?1:0}:${a.ci}:${a.mergeable}`).join("|");if(this.lastSig.get(e)===i)return;for(let a=0;a<n.length;a++){let c=n[a];if(c.ci!=="failed")continue;let{spec:l,host:u}=fo(o,r.prs[a].repoSpec);if(u.getCiFailureLog)try{let p=await u.getCiFailureLog(l,c.number);p&&(c.ciFailureLog=p)}catch(p){this.log.warn(`[track] task=${e} pr=${c.url} ci-log fetch failed: ${p instanceof Error?p.message:String(p)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:n}),this.lastSig.set(e,i);let s=OE(n);this.log.info(`[track] task=${e} snapshot signalled${s?` \u2192 ${s}`:""} (${n.length} PR(s))`)}};function OE(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}B();var cs=class t{constructor(e,r,n,o={contextDir:null}){this.intervalMs=e;this.send=r;this.log=n;this.options=o}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;abandonedTicks=0;static MAX_ABANDONED_TICKS=3;setRequest(e){let r=this.request?.projectId;this.request=e,this.log.info(`[yt-sync] request updated: project=${e.projectKey} columns=[${e.sourceColumns.join(",")}] sinceMs=${e.sinceMs} offBoard=${e.offBoardIssueIds.length}`),this.timer||this.start(),r&&r!==e.projectId&&this.log.info(`[yt-sync] project switch ${r} \u2192 ${e.projectId}`)}start(){if(this.timer)return;this.log.info(`[yt-sync] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[yt-sync] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[yt-sync] poller stopped"))}async tickOnce(){await this.tick()}async forceSync(){if(!this.request){this.log.info("[yt-sync] force requested but no sync_request yet \u2014 ignored");return}this.log.info("[yt-sync] force sync requested (manual)"),await this.tick()}async tick(){if(this.running||!this.request)return;let r=(this.options.resolveProvider??(()=>Ct({contextDir:this.options.contextDir})))();if(!r.ok){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn(`[yt-sync] tracker provider unavailable (${r.error}) \u2014 poller idle.`));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,r.provider)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let $=e.stageField?{stageField:e.stageField}:{},S=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},v=(e.backlogScope??"personal")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(v){let b=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[I,j]=await Promise.all([b.length>0?r.listIssues({projectKey:e.projectKey,columns:b,...$,...S}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...$})]),K=new Map;for(let z of[...I,...j])K.set(z.id,z);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,...$,...S})}}catch($){let S=$ instanceof Error?$.message:String($);S.includes("stage_field")?this.log.warn(`[yt-sync] CONFIGURATION ERROR \u2014 ${S}`):this.log.warn(`[yt-sync] listIssues failed: ${S}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let $ of o){if(s.add($.id),a.has($.status))continue;let S=await Qh(r,$.id,e.sinceMs,this.log);S&&i.set($.id,S)}let c=[];for(let $ of e.offBoardIssueIds){if(s.has($))continue;let S=await Qh(r,$,e.sinceMs,this.log);if(S&&S.length>0&&i.set($,S),e.requireAssignee||S&&S.length>0){let R=await Zh(r,$,e.stageField,this.log);if(R)c.push(R);else if(S&&S.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter($=>!a.has($.status)),{attachmentsByIssue:u,attachmentKeys:p}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let d=[...l,...c].map($=>({issue:$,comments:i.get($.id)??[],attachments:u.get($.id)??[]}));d.push(...await lh(this.options.contextDir,d,$=>Zh(r,$,e.stageField,this.log)));try{await Xi(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let $ of p)this.shippedAttachments.add($)}catch($){let S=$ instanceof Error?$.message:String($);this.abandonTick(`context task sync failed: ${S}`);return}let m=this.options.isSelfComment??(()=>!1),f=[],g=[];for(let[$,S]of i){let R=S.filter(b=>!m(b.id));if(R.length===0)continue;f.push({issueId:$,comments:R.map(LE)});let v=R.flatMap(b=>{let I=Sr(b.body);return I?[{commentId:b.id,author:b.author,name:I.name,args:I.args,createdAt:b.createdAt}]:[]});v.length>0&&g.push({issueId:$,commands:v})}let k={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Jh),commentsBatch:f,...g.length>0?{commandsBatch:g}:{},...c.length>0?{offBoardIssues:c.map(Jh)}:{},observedAtMs:n};this.send(k);let h=f.reduce(($,S)=>$+S.comments.length,0),w=g.reduce(($,S)=>$+S.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${h} commands=${w} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let p=`${s.id}:${u.id}`;if(this.shippedAttachments.has(p))continue;let d;try{d=await n.downloadAttachment(u.url)}catch(f){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${f instanceof Error?f.message:String(f)}`);continue}let m=ME(u.name);l.has(m)&&(m=`${u.id}-${m}`),l.add(m),c.push({name:m,contentBase64:d.toString("base64")}),i.push(p)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}};function Jh(t){let{description:e,...r}=t;return r}function LE(t){let{body:e,...r}=t;return r}function ME(t){let r=(t.split(/[\\/]/).pop()??t).replace(/[^A-Za-z0-9._-]/g,"_").replace(/^\.+/,"");return r.length>0?r.slice(0,120):"attachment"}async function Zh(t,e,r,n){try{return await t.getIssue(e,r)}catch(o){return n.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function Qh(t,e,r,n){try{return await t.listComments(e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function QE(t,e){let r=t.repos.filter(i=>i.mirror);if(r.length===0)return[];let{mirrorLag:n}=await Promise.resolve().then(()=>(Zi(),Ji)),o=[];for(let i of r){let s=i.mountAs==="."?t.root:Nr(t.root,i.mountAs);try{o.push({repo:i.name,behind:await n(i,s)})}catch(a){e.warn(`[mirror] lag for ${i.name} unknown: ${a instanceof Error?a.message:String(a)}`),o.push({repo:i.name,behind:null})}}return o}var Rl="npm i -g @code-partner/codepipe@latest";function fs(t,e={}){let r=e.log??{info:h=>console.log(h),warn:h=>console.warn(h)};r.info(`codepipe-cli v${Ve} (protocol ${gt})`);let n=h=>e.onEvent?.(h),o=e.workspace;o?.contextDir&&lf(o.contextDir,r);let i=()=>{if(o?.contextDir)try{fn(o.contextDir,o.root,r)}catch(h){r.warn(`[skills] materialize failed (non-fatal): ${h instanceof Error?h.message:String(h)}`)}};i();let s=Cl("CLI_TRACKING_POLL_INTERVAL_SEC"),a=Cl("CLI_YOUTRACK_POLL_INTERVAL_SEC"),c=(()=>{let h=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(h)&&h>0?h*1e3:6e5})(),l=!1,u=!1,p=!1,d=new Set,m=!1,f=new Set,g=k();function k(){let h=rs(t.hubUrl,t.cliToken),w=null,$=new as(s,M=>{h.readyState===h.OPEN&&h.send(JSON.stringify(M))},r),S=o&&o.repos.length>0?new ss(Cl("CLI_LOCAL_PULL_INTERVAL_SEC"),()=>is(t.hubUrl,t.cliToken,t.projectId),{root:o.root,repos:o.repos},r):null,R=new cs(a,M=>{h.readyState===h.OPEN&&h.send(JSON.stringify(M))},r,{contextDir:o?.contextDir??null,isSelfComment:M=>f.has(M)}),v=null,b=async()=>{try{let M={trackerProvider:cl(o?.contextDir??null)};try{let E=await ae(t.hubUrl,t.cliToken,t.projectId);M={...M,repos:E.repos,contextRepo:E.contextRepo}}catch(E){r.warn(`[readiness] could not fetch project summary for push checks: ${E instanceof Error?E.message:String(E)}`)}let F=await Yp(t.projectId,M),D=o?await QE(o,r):[];if(i(),h.readyState!==h.OPEN)return;let X={type:"cli_readiness",projectId:t.projectId,ready:F.ready,checks:F.checks,creds:F.creds,secretNames:ip(t.projectId),...o?{mirrors:D}:{},checkedAt:F.checkedAt};if(h.send(JSON.stringify(X)),F.ready)r.info("[readiness] ready");else{let E=F.checks.filter(C=>!C.ok).map(C=>`${C.name}(${C.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${E.join(", ")}`)}let H=Qp(F.creds,p);if(H==="open"){p=!0;let E=ef(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${E}`),Pr(E)}else H==="rearm"&&(p=!1)}catch(M){r.warn(`[readiness] check failed: ${M instanceof Error?M.message:String(M)}`)}},I=()=>{b(),v=setInterval(()=>void b(),c),typeof v.unref=="function"&&v.unref()},j=()=>{v&&(clearInterval(v),v=null)},K=150,z=new Map,A=M=>{let F=z.get(M);if(!F||(F.timer&&clearTimeout(F.timer),z.delete(M),F.events.length===0||h.readyState!==h.OPEN))return;let D={type:"run_activity",projectId:t.projectId,runId:M,events:F.events};h.send(JSON.stringify(D))},y=(M,F)=>{let D=z.get(M);if(D||(D={events:[],timer:null},z.set(M,D)),D.events.push(F),F.kind==="result"){A(M);return}D.timer||(D.timer=setTimeout(()=>A(M),K),D.timer.unref?.())},U=o?.contextDir?new xi(o.contextDir,t.projectId,M=>{h.readyState===h.OPEN&&h.send(JSON.stringify(M))},r):null,O=async()=>{let M=o?.contextDir;if(!M)throw new Error("no context repo clone on this CLI");let F;try{F=(await ae(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let D=await Nf(M,t.projectId,F,r);return h.readyState===h.OPEN&&h.send(JSON.stringify(D)),D},G=null,ee=async()=>{let M=o?.contextDir;if(M)try{let{readContextIndexHub:F,collectSearchRows:D}=await Promise.resolve().then(()=>(Co(),Io));if(F(M)!=="metadata")return;let X=D(M);h.readyState===h.OPEN&&(h.send(JSON.stringify({type:"model_index",projectId:t.projectId,rows:X})),r.info(`[model] tier-2 index snapshot pushed (${X.length} rows)`))}catch(F){r.warn(`[model] tier-2 index push failed (non-fatal): ${F instanceof Error?F.message:String(F)}`)}},ue=()=>{G&&clearTimeout(G),G=setTimeout(()=>void ee(),5e3)},tt=null,ft=async M=>{if(o?.contextDir)try{let{rebuildWorkspaceModelIfStale:F}=await Promise.resolve().then(()=>(Lo(),ps));(await F({root:o.root,contextDir:o.contextDir,repos:o.repos},{fetch:M,onLog:X=>r.info(X)})).rebuilt.length>0&&ue()}catch(F){r.warn(`[model] release-path rebuild failed (non-fatal): ${F instanceof Error?F.message:String(F)}`)}},Ne=M=>{tt&&clearTimeout(tt),tt=setTimeout(()=>void ft(M),6e4)},Oe=setInterval(()=>void ft(!0),6*36e5);return h.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let M=fp(t.projectId),F=Q("ORIGIN")==="farm"?"farm":"local",D=Q("FARM_ID"),X=t.accountEmail??M.email,H;try{let C=Qf(t.projectId);C&&(H=C.publicKey,r.info(`[cred-channel] key fingerprint: ${C.fingerprint}`))}catch(C){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${C instanceof Error?C.message:String(C)}`)}let E={type:"register",projectId:t.projectId,platformVersion:Ve,protocolVersion:gt,accountId:M.accountId,accountLabel:M.label,origin:F,inFlightActionIds:[...d],...X?{accountEmail:X}:{},...F==="farm"&&D?{farmId:D}:{},...H?{sealPublicKey:H}:{}};h.send(JSON.stringify(E))}),h.on("message",async M=>{let F=M.toString("utf-8");if(F==="pong"||F==="ping")return;let D;try{D=JSON.parse(F)}catch{return}if(!D||typeof D!="object")return;let X=D.type;if(X==="registered"){let E=D;if(E.ok){if(r.info(`[ws] registered for project ${E.projectId}`),n({kind:"registered",projectId:E.projectId??t.projectId}),$.start(),S?.start(),U?.start(),I(),Il(t,o,r),o?.contextDir){try{let C=Ci(o.contextDir,t.projectId);h.readyState===h.OPEN&&h.send(JSON.stringify(C)),C.outdated&&(r.warn(`[ctx] context format outdated: v${C.templateVersion} \u2192 v${C.currentVersion}`+(C.missingPaths.length>0?` (missing: ${C.missingPaths.join(", ")})`:"")),u||(u=!0,O().catch(()=>{})))}catch(C){r.warn(`[ctx] context-format detect failed (non-fatal): ${C instanceof Error?C.message:String(C)}`)}ee(),Ne(!0)}}else r.warn(`[ws] register rejected: ${E.reason??"unknown"}`),n({kind:"register_rejected",reason:E.reason??"unknown"}),l=!0,h.close();return}if(X==="hello"){let E=D;w=Jn(E.protocolVersion);let C=w?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${E.platformVersion} (protocol ${E.protocolVersion}) \u2014 ${C}`),w||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Ve}, protocol ${gt}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Rl}`),n({kind:"incompatible",hubVersion:typeof E.platformVersion=="string"?E.platformVersion:null,hubProtocol:typeof E.protocolVersion=="number"?E.protocolVersion:null,updateCommand:Rl}));return}if(X==="tracking_targets"){$.setTargets(D.targets),S?.poke();return}if(X==="youtrack_sync_request"){R.setRequest(D);return}if(X==="youtrack_force_sync"){R.forceSync();return}if(X==="sync_local"){await rT(D,o,h,r);return}if(X==="provision_repo"){let E=D;r.info(`[repo] provision_repo: ${E.repo.name} (${E.repo.host}:${E.repo.owner}/${E.repo.repoName})`),await eT(t,o,E.repo,r),await Il(t,o,r);return}if(X==="remove_repo"){let E=D;r.info(`[repo] remove_repo: ${E.repoName}${E.purge?" (purge)":""}`),await Il(t,o,r),E.purge&&tT(t,o,E.repoName,r);return}if(X==="context_write"){await nT(D,o,h,r),i();return}if(X==="adr_promote"){await oT(D,o,h,r),i();return}if(X==="cred_update"){let E=D,C=Y(t.projectId),te=C?.sealKey?await em(t.projectId,E.kind,E.sealed,C.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},T={type:"cred_update_result",updateId:E.updateId,projectId:t.projectId,ok:te.ok,...te.detail?{detail:te.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(T)),te.ok?(r.info(`[cred] ${E.kind} replaced${te.detail?` \u2014 ${te.detail}`:""}`),b()):r.warn(`[cred] ${E.kind} replacement rejected: ${te.detail??"unknown"}`);return}if(X==="readiness_check"){r.info("[readiness] on-demand check requested"),b();return}if(X==="agent_login_start"){Zp(t,h,D,r,b);return}if(X==="move_to_farm"){let E=D;r.info(`[farm-move] request to move ${t.projectId} onto farm ${E.farmName} (${E.farmId})`);let C=await Lh(t,E,o?.contextDir,r);h.readyState===h.OPEN&&h.send(JSON.stringify(C)),C.ok?r.info(`[farm-move] done \u2014 farm daemon ${C.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${C.error??"unknown error"}`);return}if(X==="gh_runner_setup"){let E=D;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${E.runnerName} (${E.runnerId})`);let C=await Kh(t,E,r);h.readyState===h.OPEN&&h.send(JSON.stringify(C)),C.ok?r.info(`[ghr] runners connected on ${E.runnerName}`):r.warn(`[ghr] setup failed: ${C.error??"see per-repo statuses"}`);return}if(X==="gh_runner_teardown"){let E=D;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${E.runnerName} (${E.runnerId})`);let C=await Hh(t,E,r);h.readyState===h.OPEN&&h.send(JSON.stringify(C)),C.ok?r.info(`[ghr] runners disconnected from ${E.runnerName}`):r.warn(`[ghr] teardown failed: ${C.error??"unknown error"}`);return}if(X==="tracker_fields_request"){let E=D,C={type:"tracker_fields_result",requestId:E.requestId,projectId:t.projectId,ok:!1},te=Ct({contextDir:o?.contextDir??null});if(!te.ok)C.error=te.error;else try{C.fields=await te.provider.fetchStateFields(E.projectKey),C.ok=!0}catch(T){C.error=T instanceof Error?T.message:String(T)}h.readyState===h.OPEN&&h.send(JSON.stringify(C)),C.ok||r.warn(`[yt-fields] listing failed: ${C.error??"unknown"}`);return}if(X==="project_secret_update"||X==="project_secret_delete"){let E=D,C;if(E.type==="project_secret_update"){let T=Y(t.projectId);C=T?.sealKey?Vh(t.projectId,E.name,E.sealed,T.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else C=Xh(t.projectId,E.name);let te={type:"project_secret_update_result",updateId:E.updateId,projectId:t.projectId,ok:C.ok,...C.detail?{detail:C.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(te)),C.ok?(r.info(`[secret] ${E.name} ${E.type==="project_secret_update"?"saved":"deleted"}`+(C.detail?` \u2014 ${C.detail}`:"")),b()):r.warn(`[secret] ${E.name} rejected: ${C.detail??"unknown"}`);return}if(X==="sandbox_keys"){let E=Y(t.projectId);if(!E){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let C=on(t.projectId),te=Vf(D,E,C,r);for(let T of te)h.readyState===h.OPEN&&h.send(JSON.stringify(T));return}if(X!=="dispatch_action")return;let H=D;if(w===!1){let E=`refused: HUB protocol incompatible with CLI v${Ve} (protocol ${gt})`;h.send(JSON.stringify({type:"action_result",actionId:H.actionId,status:"failed",error:E})),r.warn(`[exec] ${H.actionId} (${H.action.type}) \u2192 REFUSED: ${E}`),r.warn(`[exec] update the CLI to clear this: ${Rl}`),n({kind:"action",actionId:H.actionId,actionType:H.action.type,ok:!1,error:E});return}if(H.action.type==="model_drift"){d.add(H.actionId);try{let E,C=o?.repos.find(te=>te.name===H.action.repoName);if(!o?.contextDir||!C)E={status:"failed",error:"no local workspace/repo clone on this CLI"};else try{let{computeDriftReport:te}=await Promise.resolve().then(()=>(dg(),ug)),T=C.mountAs==="."?o.root:Nr(o.root,C.mountAs);E={status:"done",result:{report:await te(T,o.contextDir,C.name)}}}catch(te){E={status:"failed",error:te instanceof Error?te.message:String(te)}}h.send(JSON.stringify({type:"action_result",actionId:H.actionId,...E}))}finally{d.delete(H.actionId)}return}if(H.action.type==="model_bootstrap"){d.add(H.actionId);try{let E;if(!o?.contextDir)E={status:"failed",error:"no Context Repo clone on this CLI"};else if(m)E={status:"failed",error:"model bootstrap is already running"};else{m=!0;try{let C=await ae(t.hubUrl,t.cliToken,t.projectId),{bootstrapDaemonModel:te}=await Promise.resolve().then(()=>(Lo(),ps)),T=await te(t.projectId,{root:o.root,contextDir:o.contextDir},C.repos,N=>r.info(`[model] ${N}`));r.info(`[model] bootstrap done: ${T.repos} repos, ${T.events} task events`),ue(),E={status:"done",result:{repos:T.repos,events:T.events}}}catch(C){E={status:"failed",error:C instanceof Error?C.message:String(C)},r.warn(`[model] bootstrap failed: ${E.error}`)}finally{m=!1}}h.readyState===h.OPEN&&h.send(JSON.stringify({type:"action_result",actionId:H.actionId,...E}))}finally{d.delete(H.actionId)}return}d.add(H.actionId);try{let E=await kh({action:H.action,repo:H.repo,trackerIssueId:H.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:U?()=>U.reportNow():void 0,refreshContextStatus:o?.contextDir?O:void 0,onRunActivity:y}).catch(T=>({status:"failed",error:T instanceof Error?T.message:String(T)}));H.action.type==="tracker_comment"&&E.status==="done"&&"result"in E&&typeof E.result?.commentId=="string"&&f.add(E.result.commentId),h.send(JSON.stringify({type:"action_result",actionId:H.actionId,...E}));let C=E.status!=="failed",te=!C&&"error"in E?E.error:void 0;C?r.info(`[exec] ${H.actionId} (${H.action.type}) \u2192 done`):r.warn(`[exec] ${H.actionId} (${H.action.type}) \u2192 FAILED: ${te??"?"}`),n({kind:"action",actionId:H.actionId,actionType:H.action.type,ok:C,...te?{error:te}:{}}),C&&["apply_delivery","context_write","create_pr"].includes(H.action.type)&&ue(),C&&["merge_pr","merge_branch"].includes(H.action.type)&&Ne(!0)}finally{d.delete(H.actionId)}}),h.on("close",(M,F)=>{let D=F?.toString("utf-8")??"";if(r.info(`[ws] closed code=${M}${D?` reason=${D}`:""}`),$.stop(),S?.stop(),R.stop(),U?.stop(),j(),clearInterval(Oe),tt&&clearTimeout(tt),G&&clearTimeout(G),D==="replaced"){l=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:M}),!l&&setTimeout(()=>{g=k()},2e3)}),h.on("error",M=>r.warn(`[ws] error: ${M.message}`)),h}return{stop(){l=!0,g.close()}}}async function Il(t,e,r){try{let n=await ae(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=$o(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 eT(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?Nr(e.root,o):_e(t.projectId,r.name);if(pg(Nr(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await ZE().clone(e?ji(r):Bc(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 tT(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?Nr(e.root,o):_e(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!pg(Nr(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{JE(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 rT(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=Nr(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await tf(s,a).catch(l=>({status:"warn",reason:l instanceof Error?l.message:String(l)}));c.status==="updated"?n.info(`[sync] ${o.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?n.info(`[sync] ${o.repoName}: not cloned in workspace \u2014 skipped`):(n.warn(`[sync] ${o.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:o.repoName,reason:c.reason??"sync skipped"})))}}async function nT(t,e,r,n){let o=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{await Ie(e.contextDir,t.files,t.message),n.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[ctx] context_write ${t.id} failed: ${s}`),o("failed",s)}}async function oT(t,e,r,n){let o=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[adr] adr_promote ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{let i=t.source??"task",s=await gf(e.contextDir,t.taskKey,t.slugs,void 0,i);if(n.info(`[adr] adr_promote ${t.id}: promoted ${s.promoted.length}, skipped ${s.skipped.length}`+(s.promoted.length>0?` (${s.promoted.join(", ")})`:"")),s.missing.length>0){let a=l=>i==="staging"?`adr/DRAFT-${l}.md`:`tasks/${t.taskKey}/adr/DRAFT-${l}.md`,c=`draft file(s) missing in clone: ${s.missing.map(a).join(", ")}`;n.warn(`[adr] adr_promote ${t.id}: ${c}`),o("failed",c);return}o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[adr] adr_promote ${t.id} failed: ${s}`),o("failed",s)}}function Cl(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}je();fe();Ft();Al();kt();Oi();async function Sg(t={profile:void 0}){let{cfg:e,profile:r}=nn(t.profile),n=Y(e.projectId);n&&po(n),xo(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),So(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),Eo(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=Mo(_l(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=mi("CLI_LOG",i,o);if(s.enabled){let d=new an(s);hi(d),console.log(`[log] file logging \u2192 ${d.path} (rotate at ${s.maxBytes}B, keep ${s.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let a=null,c=tn(e.projectId);if(c&&(a={root:c.root,contextDir:c.contextDir,repos:c.spec.repos},console.log(`[ctx] workspace found at ${c.root} \u2014 using its Context Repo clone`)),!a){let d=Mo(_l(),".codepipe",r?Mo("profiles",r,"context"):"context");if(await fl(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await vg(()=>hs({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 fl(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let m=Mo(_l(),".codepipe",r?Mo("profiles",r,"context-config"):"context-config");Si(a.contextDir,m,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=fs(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(`
979
+ [${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}On();Ke();je();async function Nw(t={profile:void 0}){let e=st(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=rs(e.hubUrl,e.cliToken),n=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let u=l.toString("utf-8");if(s.push(`msg:${u}`),u!=="pong")try{let p=JSON.parse(u);p.type==="registered"?(a=!!p.ok,clearTimeout(c),r.send("ping")):p.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,u)=>{s.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of n.events)console.log(` ${i}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await ae(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=Me(t.profile);o?o.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${o.sandboxId} (${o.name}), llm=${o.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${o.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}Yo();import{readFileSync as wP}from"node:fs";B();Ke();Ft();Ho();Ar();Jt();Cr();je();fe();function xe(t){throw new Error(t)}function Ce(t,e){return(typeof t!="string"||t.trim().length===0)&&xe(`config: '${e}' must be a non-empty string`),t.trim()}function Xo(t,e){if(t==null)return;typeof t!="string"&&xe(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function kP(t){(!t||typeof t!="object")&&xe("config: expected a JSON object");let e=t,r=Ce(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||xe("config: 'hubUrl' must start with http(s)://");let n=Ce(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&xe("config: 'project' is required");let i=o,s=Ce(i.id,"project.id");Yt.test(s)||xe("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=Ce(i.name,"project.name"),c=Ce(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&xe("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||xe("config: 'project.repos' must be an array");let u=l.map((w,$)=>{(!w||typeof w!="object")&&xe(`config: project.repos[${$}] must be an object`);let S=w,R=Ce(S.host,`project.repos[${$}].host`);R!=="github"&&R!=="bitbucket"&&R!=="gitlab"&&xe(`config: project.repos[${$}].host must be 'github', 'bitbucket' or 'gitlab'`);let v={name:Ce(S.name,`project.repos[${$}].name`),host:R,owner:Ce(S.owner,`project.repos[${$}].owner`),repoName:Ce(S.repoName,`project.repos[${$}].repoName`)},b=Xo(S.defaultBranch,`project.repos[${$}].defaultBranch`);b&&(v.defaultBranch=b);let I=Xo(S.mountAs,`project.repos[${$}].mountAs`);return I&&(v.mountAs=I),v}),p=i.contextRepo;(!p||typeof p!="object")&&xe("config: 'project.contextRepo' is required");let d=p,m=Xo(d.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&xe("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:m,owner:Ce(d.owner,"project.contextRepo.owner"),name:Xo(d.name,"project.contextRepo.name")??Et(s)},g={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:f}},k=Xo(i.youtrackProjectKey,"project.youtrackProjectKey");if(k&&(g.project.youtrackProjectKey=k),i.index!==void 0&&(typeof i.index!="boolean"&&xe("config: 'project.index' must be a boolean"),g.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&xe("config: 'project.youtrackWrites' must be a boolean"),g.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let w=Ce(i.llmProvider,"project.llmProvider");w==="codex"&&xe(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),w!=="claude"&&xe("config: 'project.llmProvider' must be 'claude'"),g.project.llmProvider=w}let h=e.secrets;if(h!==void 0){(typeof h!="object"||h===null)&&xe("config: 'secrets' must be an object");let w=h,$={};if(w.github){let S=w.github;$.github={token:Ce(S.token,"secrets.github.token")}}if(w.bitbucket){let S=w.bitbucket;$.bitbucket={email:Ce(S.email,"secrets.bitbucket.email"),apiToken:Ce(S.apiToken,"secrets.bitbucket.apiToken")}}if(w.gitlab){let S=w.gitlab;$.gitlab={token:Ce(S.token,"secrets.gitlab.token")}}if(w.youtrack){let S=w.youtrack;$.youtrack={url:Ce(S.url,"secrets.youtrack.url").replace(/\/$/,""),token:Ce(S.token,"secrets.youtrack.token")}}if(w.contextWrite){let S=w.contextWrite;$.contextWrite={token:Ce(S.token,"secrets.contextWrite.token")}}g.secrets=$}return g}async function bP(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function $P(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await zt(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${n}`)}if(e.bitbucket){let r=t.project.repos.find(i=>i.host==="bitbucket"),n=r?.owner??(t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:void 0),o=await Vt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await ki(e.bitbucket.email,e.bitbucket.apiToken,r.owner,r.repoName);if(i)throw new Error(`Bitbucket: ${i}`)}console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await Xt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Qt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Uk(t){let e=!t.configPath||t.configPath==="-"?await bP():wP(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){xe(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=kP(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 $P(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 Ln(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??sn(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){xe(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let u;try{u=await ir(o,i,a)}catch(d){if(d instanceof W&&d.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await ae(o,i,s.id);else if(d instanceof W)xe(`HUB \u2192 ${d.status} ${d.message}`);else throw d}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let p={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(ce(p),Ut({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Tt(s.id)}`),tr(s.id,It(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,s.llmProvider??Xe),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await Oo(o,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${d}); runs once a SANDBOX claims it.`)}catch(d){console.warn(`could not enqueue index job: ${d instanceof Error?d.message:String(d)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}Ke();fe();import{cancel as Bk,intro as Fk,isCancel as Gk,log as pu,outro as vP,password as Kk}from"@clack/prompts";async function xP(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Hk(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await xP(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Fk("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),pu.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Kk({message:"Claude OAuth token"});Gk(i)&&(Bk("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),ap({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${fi()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=st(t.profile);if(!e){Fk(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),pu.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Kk({message:"Claude OAuth token"});Gk(i)&&(Bk("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=Y(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},ce(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(pu.success("Claude OAuth token saved."),vP("It will be sealed into job bundles when a SANDBOX (re)connects."))}Lo();B();Ke();Ft();Ho();Ar();_s();je();fe();import{cancel as SP,confirm as EP,intro as TP,isCancel as Wk,log as De,outro as RP,select as qk,text as hr}from"@clack/prompts";function Yk(t){SP(t),process.exit(1)}function Fn(t){return Wk(t)&&Yk("aborted"),t}function Jo(t){return Wk(t)&&Yk("aborted"),typeof t=="string"?t:""}async function IP(t,e){let r=Fn(await qk({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),n=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",o=Jo(await hr({message:"Context Repo owner (org / group / workspace / user)",placeholder:n||"your-org",initialValue:n,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=Jo(await hr({message:"Context Repo name",placeholder:Et(t),initialValue:Et(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function zk(t={profile:void 0}){let e=st(t.profile);TP(`codepipe project add \u2192 ${e.hubUrl}`);let r=Fn(await hr({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>Yt.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=Fn(await hr({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=Fn(await qk({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=Fn(await hr({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Fn(await EP({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=Jo(await hr({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:h=>!h||!h.trim()||Ye(h)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!d)break;let m=Ye(d);De.message(`${m.host}: ${m.owner}/${m.repoName}`);let f=Jo(await hr({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:h=>h.trim().length>0?void 0:"required"})).trim(),g=Jo(await hr({message:"default branch (optional)",placeholder:"main"})).trim(),k={name:f,host:m.host,owner:m.owner,repoName:m.repoName};g&&(k.defaultBranch=g),a.push(k)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await IP(r,a),u=Y(e.projectId);De.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await Ln(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??sn(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:d=>De.message(d),warn:d=>De.warn(d)}})}catch(d){De.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,De.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await ir(e.hubUrl,e.cliToken,c);De.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),tr(r,It(c,s,u?.youtrack?.url),{info:m=>De.message(m),warn:m=>De.warn(m)}),d.contextRepo&&(De.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),De.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&De.error(` error: ${d.provisioningError}`),RP("done")}catch(d){d instanceof W?(De.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&De.message(JSON.stringify(d.payload,null,2))):De.error(d instanceof Error?d.message:String(d)),process.exit(1)}}On();Ke();je();fe();kt();Yo();import{existsSync as CP,rmSync as PP}from"node:fs";import{confirm as AP,intro as _P,isCancel as jP,log as gr,outro as NP,spinner as OP}from"@clack/prompts";function jt(t){gr.error(t),process.exit(1)}var Vk=t=>t.trim().replace(/\/+$/,"");async function Xk(t){_P("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Ae()?.spec.projectId??void 0;e||jt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=bt(e);r||jt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Vk(r.hubUrl),o=r.projectId,i=Vk(t.hub);i.startsWith("http")||jt("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&jt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let h=OP();h.start(`reading project ${o} from ${n}\u2026`);try{l=await ae(n,r.cliToken,o),h.stop(`read project ${o} (${l.name})`)}catch(w){throw h.stop("could not read the source project",1),w instanceof W&&jt(`source HUB ${n} \u2192 ${w.status} ${w.message}. The source HUB must be reachable with a valid token to move a project.`),w}}l.contextRepo||jt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=Y(o),p=(t.account??r.accountEmail??await Un()).trim().toLowerCase();if(gr.message(`move project '${o}'
978
980
  from : ${n} (profile ${e})
979
981
  to : ${i} (profile ${s}, project ${a}, account ${p})
980
982
  \u2022 the source registration on the old HUB is left intact (non-destructive)
981
983
  \u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
982
- `+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let h=await EP({message:"Continue?",initialValue:!0});(RP(h)||!h)&&_t("aborted")}!c&&a===o&&gr.warn(`source and destination share the same project id, so they share one secrets file (${Et(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 Bn(i,p),f={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:m,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};gr.step(`registering project on ${i}\u2026`);let y;try{y=await ir(i,d,f)}catch(h){if(h instanceof K&&h.status===409){gr.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{y=await le(i,d,a)}catch(w){throw w instanceof K&&_t(`target HUB \u2192 ${w.status} ${w.message}`),w}}else if(h instanceof K&&h.status===403)_t(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(h instanceof K)_t(`target HUB \u2192 ${h.status} ${h.message}`);else throw h}gr.success(`project ${y.projectId} ready on ${i} (${y.provisioningStatus})`),Ut({hubUrl:i,cliToken:d,projectId:a,accountEmail:m},s);let k={...u??{},hubUrl:i,cliToken:d,projectId:a};if(delete k.sandboxPins,ue(k),gr.success(`profile '${s}' \u2192 ${Et(a)}`),c){let h=vt(s);xP(h)&&(SP(h),gr.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}IP(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}Ke();import{existsSync as uu,rmSync as PP,statSync as AP}from"node:fs";import{join as Gs,relative as _P,resolve as jP}from"node:path";import{cancel as NP,intro as Vk,isCancel as OP,log as Ie,outro as Xk,text as Ur}from"@clack/prompts";import{simpleGit as Jk}from"simple-git";As();Ne();vo();me();it();function et(t){NP(t),process.exit(1)}function Br(t){return OP(t)&&et("aborted"),typeof t=="string"?t:""}async function zk(t){try{let e=await Jk(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function LP(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function MP(t,e){let r=Y(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(LP(r,e)){Ie.message(`reusing existing ${e} credentials`);return}if(Ie.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=Br(await Ur({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=Br(await Ur({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=Br(await Ur({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}}ue(r),Ie.success(`saved ${e} credentials`)}async function Zk(t){let e=st(t.profile);Vk(`codepipe repo add \u2192 project ${e.projectId}`);let r=_e()??void 0,n;try{n=(await le(e.hubUrl,e.cliToken,e.projectId)).repos}catch(w){et(`could not read project from HUB: ${w instanceof Error?w.message:String(w)}`)}let o=t.target?.trim();if(!o){let w=await zk(process.cwd());w?(o=process.cwd(),Ie.message(`using the current directory (${w})`)):o=Br(await Ur({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:$=>$.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(uu(o)&&AP(o).isDirectory()){i=jP(o);let w=await zk(i);w||et(`${i} is not a git repository (no origin remote)`);let $=Ye(w);$||et(`origin ${w} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=$,s=w,Ie.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let w=Ye(o);w||et(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=w,s=o,Ie.message(`${a}: ${c}/${l}`)}let u=Br(await Ur({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:w=>w.trim()?void 0:"required"})).trim();n.some(w=>w.name===u)&&et(`a repo named "${u}" is already registered`);let p=Br(await Ur({message:"default branch (optional)",placeholder:"main"})).trim(),d=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let w=_P(r.root,i);d=w===""?".":w}let m=Br(await Ur({message:"mount_as (directory relative to the workspace root)",placeholder:d,initialValue:d})).trim()||d;n.some(w=>(w.mountAs??w.name)===m)&&et(`mount_as "${m}" is already used by another repo`),await MP(e,a);let f={name:u,host:a,owner:c,repoName:l,mountAs:m,...p?{defaultBranch:p}:{}};if(!i){let w=r?Gs(r.root,m):je(e.projectId,u);if(uu(Gs(w,".git")))Ie.message(`already cloned at ${w}`);else{Ie.info(`cloning ${s} \u2192 ${w} \u2026`);try{await Jk().clone(s,w),Ie.success(`cloned into ${w}`)}catch($){et(`clone failed: ${$ instanceof Error?$.message.trim():String($)}
983
- check that your ${a} credentials grant read access to ${c}/${l}`)}}}let y;try{y=await Ch(e.hubUrl,e.cliToken,e.projectId,f)}catch(w){w instanceof K&&et(`HUB \u2192 ${w.status} ${w.message}`),et(w instanceof Error?w.message:String(w))}let{updated:k,errors:h}=$o(e.projectId,y.repos,r?.contextDir);for(let w of k)Ie.message(`updated ${w}`);for(let w of h)Ie.warn(`could not update ${w.path}: ${w.error}`);Ie.success(`added "${u}" \u2014 project now has ${y.repos.length} repo(s)`),Xk("done")}async function Qk(t){let e=st(t.profile);Vk(`codepipe repo remove \u2192 project ${e.projectId}`);let r=_e()??void 0,n;try{let c=(await le(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 Ph(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof K&&(a.status===404&&et(`no repo named "${t.name}" in this project`),et(`HUB \u2192 ${a.status} ${a.message}`)),et(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=$o(e.projectId,o.repos,r?.contextDir);for(let a of i)Ie.message(`updated ${a}`);for(let a of s)Ie.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")Ie.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?Gs(r.root,n):je(e.projectId,t.name);if(uu(Gs(a,".git")))try{PP(a,{recursive:!0,force:!0}),Ie.message(`deleted local clone ${a}`)}catch(c){Ie.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else Ie.message(`no local clone found to purge (${a})`)}Ie.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),Xk("done")}async function eb(t){let e=st(t.profile),r;try{r=(await le(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}`)}}js();B();Ke();Ci();Ne();it();it();import{existsSync as tb}from"node:fs";import{join as du}from"node:path";import{simpleGit as pu}from"simple-git";var DP=60;async function rb(t){let{cfg:e}=nn(t.profile),r=tn(e.projectId);if(!r)throw new Error(`no workspace for ${e.projectId} here \u2014 run this from the project folder (the one with .codepipe/)`);let n=new Set,o=async()=>{let s=await Ah(e.hubUrl,e.cliToken,e.projectId);if(s.length===0){console.log("[pull] nothing ready yet");return}for(let a of s)await UP(r.root,r.spec.repos,a,n);if(await KP(r.contextDir),r.contextDir)try{fn(r.contextDir,r.root,{info:a=>console.log(`[pull] ${a}`),warn:a=>console.warn(`[pull] ${a}`)})}catch(a){console.warn(`[pull] skills materialize failed \u2014 ${a instanceof Error?a.message:String(a)}`)}};if(!t.watch){await o();return}try{await o()}catch(s){console.warn(`[pull] ${s instanceof Error?s.message:String(s)}`)}let i=Math.max(10,t.intervalSec??DP)*1e3;for(console.log(`[pull] watching \u2014 every ${Math.round(i/1e3)}s, Ctrl+C to stop`);;){await new Promise(s=>setTimeout(s,i));try{await o()}catch(s){console.warn(`[pull] ${s instanceof Error?s.message:String(s)}`)}}}async function UP(t,e,r,n){for(let o of r.repos){let i=e.find(l=>l.name===o.repoName);if(!i)continue;let s=`${r.taskKey}:${i.name}:${o.branchName}`;if(!so(o.branchName)){n.has(s)||(n.add(s),console.warn(`[pull] ${r.taskKey} ${i.mountAs}: refusing suspicious branch name`));continue}let a=du(t,i.mountAs);if(!tb(du(a,".git")))continue;let c=pu(a);try{let l=await GP(c,o.branchName);await c.fetch(await BP(c,i),`refs/heads/${o.branchName}`);let u=(await c.revparse(["FETCH_HEAD"])).trim();if(l===u)continue;if(await FP(c,a,o.branchName)){n.has(s)||(n.add(s),console.log(`[pull] ${r.taskKey} \u2192 ${i.mountAs}: ${o.branchName} is checked out here \u2014 fetched ${u.slice(0,10)}; merge or pull it in that checkout yourself`));continue}await c.raw(["branch","-f",o.branchName,u]),console.log(`[pull] ${r.taskKey} \u2192 ${i.mountAs}: ${o.branchName} ${u.slice(0,10)} (checkout untouched)`)}catch(l){if(n.has(s))continue;n.add(s),console.warn(`[pull] ${r.taskKey} ${i.mountAs}: ${o.branchName} unavailable \u2014 `+(l instanceof Error?l.message.split(`
984
- `)[0]:String(l)))}}}async function BP(t,e){if(e.mirror){let r=e.mirror;return r.host==="github"?`git@github.com:${r.owner}/${r.repoName}.git`:r.host==="gitlab"?`git@gitlab.com:${r.owner}/${r.repoName}.git`:`git@bitbucket.org:${r.owner}/${r.repoName}.git`}try{if((await t.getRemotes(!0)).find(n=>n.name==="origin")?.refs?.fetch)return"origin"}catch{}return di(e)}async function FP(t,e,r){try{return(await t.raw(["worktree","list","--porcelain"])).split(`
985
- `).some(o=>o.trim()===`branch refs/heads/${r}`)}catch{try{return(await pu(e).revparse(["--abbrev-ref","HEAD"])).trim()===r}catch{return!1}}}async function GP(t,e){try{return(await t.revparse([e])).trim()}catch{return null}}async function KP(t){if(!(!t||!tb(du(t,".git"))))try{await pu(t).pull(["--ff-only"])}catch(e){console.warn(`[pull] context repo not updated \u2014 ${e instanceof Error?e.message.split(`
986
- `)[0]:String(e)}`)}}Ds();import{existsSync as ab,mkdirSync as HP,readFileSync as WP,writeFileSync as qP}from"node:fs";import{homedir as YP}from"node:os";import{dirname as zP,join as cb}from"node:path";import*as Kn from"node:readline";Ne();ji();me();it();js();Ds();var Ks=cb(YP(),".codepipe","history"),nb=["/help","/status","/tasks","/task","/sync","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],lb=500,ob=40;async function ub(t={}){let e=_e();e||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let r=Y(e.spec.projectId);r||(console.error(`no secrets for project ${e.spec.projectId} at ~/.codepipe/secrets/${e.spec.projectId}.json. run \`codepipe init\` or \`codepipe clone\` to set them up.`),process.exit(1)),po(r),console.log(`connected to ${r.hubUrl} as project ${e.spec.projectId}`),console.log("the CLI daemon and an embedded agent worker run in this session; /logs and /monitor show their output."),console.log("type /help to list commands. Ctrl+D or /quit to exit."),console.log("");let n=Kn.createInterface({input:process.stdin,output:process.stdout,completer:VP,history:uA(),removeHistoryDuplicates:!0}),o={ws:e,secrets:r,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};Of(i=>yr(o,i)),o.daemon=ps({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:i=>yr(o,i),warn:i=>yr(o,i)},onEvent:i=>sA(o,i),workspace:{root:e.root,contextDir:e.contextDir,repos:e.spec.repos}});try{let i={hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId};await Os(i,t.profile,{profile:t.profile});let s=process.argv[1];if(!s)throw new Error("cannot resolve the codepipe entry script for the worker process");let a=Ls({entry:s,profile:t.profile,onLine:c=>yr(o,`[worker] ${c}`)});a.on("exit",(c,l)=>{o.workerExited=!0,!hu&&Gn(o,`[worker] exited (code ${c??(l?1:0)}) \u2014 agent jobs will NOT run; /quit and restart codepipe to bring it back`)}),o.workerChild=a,console.log("embedded agent worker started \u2014 agent jobs run on this machine.")}catch(i){console.warn(`[worker] could not start the embedded worker (${i instanceof Error?i.message:String(i)}). REPL commands still work; run \`codepipe up --reregister\` if the registration was removed.`)}mu(o),n.prompt(),n.on("line",async i=>{let s=i.trim();if(s.length>0)try{if(await XP(o,s)){sb(o);return}}catch(a){console.error(a instanceof Error?a.message:String(a))}o.unread=0,mu(o),n.prompt()}),n.on("close",()=>{sb(o)})}function VP(t){let e=nb.filter(r=>r.startsWith(t));return[e.length?e:nb,t]}async function XP(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return JP(),!1;case"/status":return await ZP(t),!1;case"/tasks":return await QP(t,n),!1;case"/task":return await eA(t,n),!1;case"/sync":return await tA(t),!1;case"/logs":return aA(t,n),!1;case"/monitor":return cA(t),!1;case"/approve":return await ib(t,n,"approve"),!1;case"/merge":return await ib(t,n,"merge"),!1;case"/login":return rA(t,n),!1;case"/secret":return nA(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function JP(){console.log(["/help show this list","/status connection, project, embedded worker, siblings","/tasks [--phase P] list tasks (optionally filtered by phase)","/task <key> task detail (phase + artifacts)","/sync clone/fetch project repos per project.yaml","/logs [n|follow|clear] tail last n daemon/worker logs / toggle live / clear buffer","/monitor toggle live daemon/worker log streaming (alias /logs follow)","/approve <key> merge the task's PR(s) (TRACKING, PR mode)","/merge <key> direct-merge the branch to main (TRACKING, no-PR mode)","/login <token> set the Claude OAuth token (not stored in history)","/secret set <k> <v> set a secret (not stored in history)","/secret list list secret keys (no values)","/secret unset <k> remove a secret","/quit stop the daemon and the worker, exit"].join(`
987
- `))}async function ZP(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=ab(cb(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function QP(t,e){let r=lA(e,"--phase");try{let n=await Th(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){gu(n)}}async function eA(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await Rh(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){gu(n)}}async function tA(t){let e=await qo(t.ws.root,t.ws.spec.repos);for(let r of e)console.log(` ${r.mountAs}: ${r.status}${r.detail?` \u2014 ${r.detail}`:""}`)}async function ib(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await Ih(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){gu(o)}}function rA(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},ue(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 nA(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(`
988
- `)}`:" (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}oA(t.secrets,n,i),ue(t.secrets),po(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}iA(t.secrets,n),ue(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function oA(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 iA(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",yr(t,"[hub] connected");break;case"registered":t.connection="registered",yr(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Gn(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",yr(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Gn(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Gn(t,`[hub] HUB v${e.hubVersion??"?"} (protocol ${e.hubProtocol??"?"}) is incompatible with this CLI \u2014 WriteActions are refused. Update: ${e.updateCommand}`);break;case"action":e.ok?yr(t,`[hub] action ${e.actionType} done`):Gn(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function yr(t,e){t.logBuffer.push(e),t.logBuffer.length>lb&&t.logBuffer.shift(),t.follow&&Gn(t,e)}function aA(t,e){let r=e[0];if(r==="follow"||r==="on"){fu(t,!0);return}if(r==="off"){fu(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(lb,Number(r)||ob)):ob,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 cA(t){fu(t,!t.follow)}function fu(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Gn(t,e){Kn.cursorTo(process.stdout,0),Kn.clearLine(process.stdout,0),process.stdout.write(e+`
989
- `),t.unread+=1,mu(t),t.rl.prompt(!0)}function mu(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var hu=!1;function sb(t){if(hu)return;hu=!0,dA(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
984
+ `+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let h=await AP({message:"Continue?",initialValue:!0});(jP(h)||!h)&&jt("aborted")}!c&&a===o&&gr.warn(`source and destination share the same project id, so they share one secrets file (${Tt(a)}). Running both profiles at the same time will conflict \u2014 pass --project <newId> for a parallel setup, or keep only one active.`);let{cliToken:d,accountEmail:m}=await Bn(i,p),f={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:m,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};gr.step(`registering project on ${i}\u2026`);let g;try{g=await ir(i,d,f)}catch(h){if(h instanceof W&&h.status===409){gr.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{g=await ae(i,d,a)}catch(w){throw w instanceof W&&jt(`target HUB \u2192 ${w.status} ${w.message}`),w}}else if(h instanceof W&&h.status===403)jt(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(h instanceof W)jt(`target HUB \u2192 ${h.status} ${h.message}`);else throw h}gr.success(`project ${g.projectId} ready on ${i} (${g.provisioningStatus})`),Ut({hubUrl:i,cliToken:d,projectId:a,accountEmail:m},s);let k={...u??{},hubUrl:i,cliToken:d,projectId:a};if(delete k.sandboxPins,ce(k),gr.success(`profile '${s}' \u2192 ${Tt(a)}`),c){let h=xt(s);CP(h)&&(PP(h),gr.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}NP(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}Ke();import{existsSync as fu,rmSync as LP,statSync as MP}from"node:fs";import{join as Ks,relative as DP,resolve as UP}from"node:path";import{cancel as BP,intro as Zk,isCancel as FP,log as Re,outro as Qk,text as Ur}from"@clack/prompts";import{simpleGit as eb}from"simple-git";_s();je();vo();fe();kt();function et(t){BP(t),process.exit(1)}function Br(t){return FP(t)&&et("aborted"),typeof t=="string"?t:""}async function Jk(t){try{let e=await eb(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function GP(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function KP(t,e){let r=Y(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(GP(r,e)){Re.message(`reusing existing ${e} credentials`);return}if(Re.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=Br(await Ur({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=Br(await Ur({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=Br(await Ur({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}}ce(r),Re.success(`saved ${e} credentials`)}async function tb(t){let e=st(t.profile);Zk(`codepipe repo add \u2192 project ${e.projectId}`);let r=Ae()??void 0,n;try{n=(await ae(e.hubUrl,e.cliToken,e.projectId)).repos}catch(w){et(`could not read project from HUB: ${w instanceof Error?w.message:String(w)}`)}let o=t.target?.trim();if(!o){let w=await Jk(process.cwd());w?(o=process.cwd(),Re.message(`using the current directory (${w})`)):o=Br(await Ur({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:$=>$.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(fu(o)&&MP(o).isDirectory()){i=UP(o);let w=await Jk(i);w||et(`${i} is not a git repository (no origin remote)`);let $=Ye(w);$||et(`origin ${w} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=$,s=w,Re.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let w=Ye(o);w||et(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=w,s=o,Re.message(`${a}: ${c}/${l}`)}let u=Br(await Ur({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:w=>w.trim()?void 0:"required"})).trim();n.some(w=>w.name===u)&&et(`a repo named "${u}" is already registered`);let p=Br(await Ur({message:"default branch (optional)",placeholder:"main"})).trim(),d=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let w=DP(r.root,i);d=w===""?".":w}let m=Br(await Ur({message:"mount_as (directory relative to the workspace root)",placeholder:d,initialValue:d})).trim()||d;n.some(w=>(w.mountAs??w.name)===m)&&et(`mount_as "${m}" is already used by another repo`),await KP(e,a);let f={name:u,host:a,owner:c,repoName:l,mountAs:m,...p?{defaultBranch:p}:{}};if(!i){let w=r?Ks(r.root,m):_e(e.projectId,u);if(fu(Ks(w,".git")))Re.message(`already cloned at ${w}`);else{Re.info(`cloning ${s} \u2192 ${w} \u2026`);try{await eb().clone(s,w),Re.success(`cloned into ${w}`)}catch($){et(`clone failed: ${$ instanceof Error?$.message.trim():String($)}
985
+ check that your ${a} credentials grant read access to ${c}/${l}`)}}}let g;try{g=await Ah(e.hubUrl,e.cliToken,e.projectId,f)}catch(w){w instanceof W&&et(`HUB \u2192 ${w.status} ${w.message}`),et(w instanceof Error?w.message:String(w))}let{updated:k,errors:h}=$o(e.projectId,g.repos,r?.contextDir);for(let w of k)Re.message(`updated ${w}`);for(let w of h)Re.warn(`could not update ${w.path}: ${w.error}`);Re.success(`added "${u}" \u2014 project now has ${g.repos.length} repo(s)`),Qk("done")}async function rb(t){let e=st(t.profile);Zk(`codepipe repo remove \u2192 project ${e.projectId}`);let r=Ae()??void 0,n;try{let c=(await ae(e.hubUrl,e.cliToken,e.projectId)).repos.find(l=>l.name===t.name);n=c?c.mountAs??c.name:void 0}catch{}let o;try{o=await _h(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof W&&(a.status===404&&et(`no repo named "${t.name}" in this project`),et(`HUB \u2192 ${a.status} ${a.message}`)),et(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=$o(e.projectId,o.repos,r?.contextDir);for(let a of i)Re.message(`updated ${a}`);for(let a of s)Re.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")Re.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):_e(e.projectId,t.name);if(fu(Ks(a,".git")))try{LP(a,{recursive:!0,force:!0}),Re.message(`deleted local clone ${a}`)}catch(c){Re.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else Re.message(`no local clone found to purge (${a})`)}Re.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),Qk("done")}async function nb(t){let e=st(t.profile),r;try{r=(await ae(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}`)}}Ns();Ke();Ii();je();import{existsSync as HP}from"node:fs";import{join as WP}from"node:path";import{simpleGit as qP}from"simple-git";kt();var YP=60;async function ob(t){let{cfg:e}=nn(t.profile),r=tn(e.projectId);if(!r)throw new Error(`no workspace for ${e.projectId} here \u2014 run this from the project folder (the one with .codepipe/)`);let n=new Set,o={info:a=>console.log(a),warn:a=>console.warn(a)},i=async()=>{let a=await is(e.hubUrl,e.cliToken,e.projectId);if(a.length===0){console.log("[pull] nothing ready yet");return}for(let c of a)await gl(r.root,r.spec.repos,c,n,o);if(await zP(r.contextDir),r.contextDir)try{fn(r.contextDir,r.root,{info:c=>console.log(`[pull] ${c}`),warn:c=>console.warn(`[pull] ${c}`)})}catch(c){console.warn(`[pull] skills materialize failed \u2014 ${c instanceof Error?c.message:String(c)}`)}};if(!t.watch){await i();return}try{await i()}catch(a){console.warn(`[pull] ${a instanceof Error?a.message:String(a)}`)}let s=Math.max(10,t.intervalSec??YP)*1e3;for(console.log(`[pull] watching \u2014 every ${Math.round(s/1e3)}s, Ctrl+C to stop`);;){await new Promise(a=>setTimeout(a,s));try{await i()}catch(a){console.warn(`[pull] ${a instanceof Error?a.message:String(a)}`)}}}async function zP(t){if(!(!t||!HP(WP(t,".git"))))try{await qP(t).pull(["--ff-only"])}catch(e){console.warn(`[pull] context repo not updated \u2014 ${e instanceof Error?e.message.split(`
986
+ `)[0]:String(e)}`)}}Us();import{existsSync as lb,mkdirSync as VP,readFileSync as XP,writeFileSync as JP}from"node:fs";import{homedir as ZP}from"node:os";import{dirname as QP,join as ub}from"node:path";import*as Kn from"node:readline";je();_i();fe();kt();Ns();Us();var Hs=ub(ZP(),".codepipe","history"),ib=["/help","/status","/tasks","/task","/sync","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],db=500,sb=40;async function pb(t={}){let e=Ae();e||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let r=Y(e.spec.projectId);r||(console.error(`no secrets for project ${e.spec.projectId} at ~/.codepipe/secrets/${e.spec.projectId}.json. run \`codepipe init\` or \`codepipe clone\` to set them up.`),process.exit(1)),po(r),console.log(`connected to ${r.hubUrl} as project ${e.spec.projectId}`),console.log("the CLI daemon and an embedded agent worker run in this session; /logs and /monitor show their output."),console.log("type /help to list commands. Ctrl+D or /quit to exit."),console.log("");let n=Kn.createInterface({input:process.stdin,output:process.stdout,completer:eA,history:hA(),removeHistoryDuplicates:!0}),o={ws:e,secrets:r,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};Mf(i=>yr(o,i)),o.daemon=fs({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:i=>yr(o,i),warn:i=>yr(o,i)},onEvent:i=>dA(o,i),workspace:{root:e.root,contextDir:e.contextDir,repos:e.spec.repos}});try{let i={hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId};await Ls(i,t.profile,{profile:t.profile});let s=process.argv[1];if(!s)throw new Error("cannot resolve the codepipe entry script for the worker process");let a=Ms({entry:s,profile:t.profile,onLine:c=>yr(o,`[worker] ${c}`)});a.on("exit",(c,l)=>{o.workerExited=!0,!gu&&Gn(o,`[worker] exited (code ${c??(l?1:0)}) \u2014 agent jobs will NOT run; /quit and restart codepipe to bring it back`)}),o.workerChild=a,console.log("embedded agent worker started \u2014 agent jobs run on this machine.")}catch(i){console.warn(`[worker] could not start the embedded worker (${i instanceof Error?i.message:String(i)}). REPL commands still work; run \`codepipe up --reregister\` if the registration was removed.`)}hu(o),n.prompt(),n.on("line",async i=>{let s=i.trim();if(s.length>0)try{if(await tA(o,s)){cb(o);return}}catch(a){console.error(a instanceof Error?a.message:String(a))}o.unread=0,hu(o),n.prompt()}),n.on("close",()=>{cb(o)})}function eA(t){let e=ib.filter(r=>r.startsWith(t));return[e.length?e:ib,t]}async function tA(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return rA(),!1;case"/status":return await nA(t),!1;case"/tasks":return await oA(t,n),!1;case"/task":return await iA(t,n),!1;case"/sync":return await sA(t),!1;case"/logs":return pA(t,n),!1;case"/monitor":return fA(t),!1;case"/approve":return await ab(t,n,"approve"),!1;case"/merge":return await ab(t,n,"merge"),!1;case"/login":return aA(t,n),!1;case"/secret":return cA(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function rA(){console.log(["/help show this list","/status connection, project, embedded worker, siblings","/tasks [--phase P] list tasks (optionally filtered by phase)","/task <key> task detail (phase + artifacts)","/sync clone/fetch project repos per project.yaml","/logs [n|follow|clear] tail last n daemon/worker logs / toggle live / clear buffer","/monitor toggle live daemon/worker log streaming (alias /logs follow)","/approve <key> merge the task's PR(s) (TRACKING, PR mode)","/merge <key> direct-merge the branch to main (TRACKING, no-PR mode)","/login <token> set the Claude OAuth token (not stored in history)","/secret set <k> <v> set a secret (not stored in history)","/secret list list secret keys (no values)","/secret unset <k> remove a secret","/quit stop the daemon and the worker, exit"].join(`
987
+ `))}async function nA(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=lb(ub(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function oA(t,e){let r=mA(e,"--phase");try{let n=await Ih(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId),o=r?n.filter(i=>i.phase.toLowerCase()===r.toLowerCase()):n;if(o.length===0){console.log(" (no tasks)");return}for(let i of o)console.log(` ${i.key.padEnd(10)} ${i.phase.padEnd(16)} ${i.title}`)}catch(n){yu(n)}}async function iA(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await Ch(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r);if(console.log(` ${r}: ${n.task.phase} \u2014 ${n.task.title}`),n.artifacts.length>0){console.log(" artifacts:");for(let o of n.artifacts)console.log(` ${o.path}`)}}catch(n){yu(n)}}async function sA(t){let e=await qo(t.ws.root,t.ws.spec.repos);for(let r of e)console.log(` ${r.mountAs}: ${r.status}${r.detail?` \u2014 ${r.detail}`:""}`)}async function ab(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await Ph(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){yu(o)}}function aA(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},ce(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 cA(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(`
988
+ `)}`:" (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}lA(t.secrets,n,i),ce(t.secrets),po(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}uA(t.secrets,n),ce(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function lA(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 uA(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 dA(t,e){switch(e.kind){case"connected":t.connection="connecting",yr(t,"[hub] connected");break;case"registered":t.connection="registered",yr(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Gn(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",yr(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Gn(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Gn(t,`[hub] HUB v${e.hubVersion??"?"} (protocol ${e.hubProtocol??"?"}) is incompatible with this CLI \u2014 WriteActions are refused. Update: ${e.updateCommand}`);break;case"action":e.ok?yr(t,`[hub] action ${e.actionType} done`):Gn(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function yr(t,e){t.logBuffer.push(e),t.logBuffer.length>db&&t.logBuffer.shift(),t.follow&&Gn(t,e)}function pA(t,e){let r=e[0];if(r==="follow"||r==="on"){mu(t,!0);return}if(r==="off"){mu(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(db,Number(r)||sb)):sb,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 fA(t){mu(t,!t.follow)}function mu(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Gn(t,e){Kn.cursorTo(process.stdout,0),Kn.clearLine(process.stdout,0),process.stdout.write(e+`
989
+ `),t.unread+=1,hu(t),t.rl.prompt(!0)}function hu(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var gu=!1;function cb(t){if(gu)return;gu=!0,gA(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
990
990
  bye.`),setTimeout(()=>process.exit(0),150);return}console.log(`
991
- 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 lA(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function gu(t){t instanceof K?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function uA(){if(!ab(Ks))return[];try{return WP(Ks,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function dA(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{HP(zP(Ks),{recursive:!0}),qP(Ks,r.slice().reverse().join(`
991
+ 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 mA(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function yu(t){t instanceof W?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function hA(){if(!lb(Hs))return[];try{return XP(Hs,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function gA(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{VP(QP(Hs),{recursive:!0}),JP(Hs,r.slice().reverse().join(`
992
992
  `)+`
993
- `)}catch{}}On();B();Ge();On();Ke();Ne();Yo();import{hostname as pA}from"node:os";import{cancel as fA,confirm as db,intro as mA,isCancel as mb,log as Hn,multiselect as hA,outro as pb,password as gA,select as yu,text as wu}from"@clack/prompts";function Zo(t){fA(t),process.exit(1)}function Wn(t){return mb(t)&&Zo("aborted"),t}function Hs(t){return mb(t)&&Zo("aborted"),typeof t=="string"?t:""}function Ws(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function fb(t,e){try{let{secret:r}=await is(t,e);return r}catch(r){throw r instanceof K&&r.status===404&&Zo("this HUB has no account-issued sandbox registration \u2014 issue a registration token in the dashboard (Status \u2192 SANDBOX) and re-run with it"),r}}async function yA(t,e){if(Wn(await yu({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 dl(t,e);if(o.length>0)return Wn(await hA({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}));Hn.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Hn.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return Hs(await wu({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 ku(t){mA("codepipe worker \u2014 set up this machine as a runner");let e=Le(t.profile);e&&(Hn.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Wn(await db({message:"re-register this worker?",initialValue:!1}))||Zo("keeping the existing registration"));let r=kt(t.profile)??kt(),n=Hs(await wu({message:"HUB URL",placeholder:ht,initialValue:Q("HUB_URL")??r?.hubUrl??ht,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=Wn(await yu({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 fb(n,a),Hn.success("account-issued registration token minted");else if(i==="login"){let d=await Un();a=(await Bn(n,d)).cliToken,s=await fb(n,a),Hn.success("account-issued registration token minted")}else s=Hs(await gA({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||Zo("a registration token is required");let c=await yA(n,a),l=Hs(await wu({message:"worker name",initialValue:pA(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=Wn(await yu({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 Or({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Hn.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Wn(await db({message:"start the claim-loop now?",initialValue:!0}))){pb("registered. start later with `codepipe worker`.");return}pb("starting the claim-loop\u2026"),await Ko(t.profile?{profile:t.profile}:{})}function kA(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return Q("PROFILE")}var $e=kA();Yd($e);var De=new wA;De.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Ve).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{Ws()?await ub({profile:$e}):await Ms({profile:$e})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});De.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await Lk({configPath:t.config,skipVerify:t.skipVerify===!0}):await Sk({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","Personal CLI token (issued during `codepipe init`)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await sp({...t,profile:$e})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await Ek({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});De.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await $g({profile:$e})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});De.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await ak({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("login").description("Set the Claude OAuth token (sealed into job bundles)").option("--token <token>","Provide the token non-interactively").option("--shared","Save to the machine/farm-wide ~/.codepipe/shared.json instead of this project").option("--stdin","Read the token from stdin (for scripted/ssh delivery)").action(async t=>{try{await Fk({profile:$e,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Aw({profile:$e})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});De.command("pull").description("Fetch finished task branches into your local clones (no checkout switch)").option("--profile <name>","Config profile").option("--watch","Keep pulling instead of exiting after one pass").option("--interval <sec>","Watch interval in seconds (default 60, minimum 10)",t=>parseInt(t,10)).action(async t=>{if(t.interval!==void 0&&!Number.isFinite(t.interval))throw new Error("--interval expects a number of seconds");await rb({profile:t.profile,...t.watch?{watch:!0}:{},...Number.isFinite(t.interval)?{intervalSec:t.interval}:{}})});De.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).option("--debug [categories]","Write local debug logs (comma-separated categories; default: agent-request \u2014 the full prompt and context each agent job receives, under ~/.codepipe/debug/)").action(async t=>{try{await Ms({profile:$e,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var hb=De.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");hb.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??Q("HUB_URL")??kt($e)?.hubUrl??ht,r=t.token??Q("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Ws()){await ku({profile:$e});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let n=Q("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??Q("WORKER_NAME"),i=t.llm??Q("WORKER_LLM");await Or({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...$e?{profile:$e}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});hb.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!Le($e)&&Ws()){await ku({profile:$e});return}await Ko($e?{profile:$e}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var gb=De.command("project").description("Manage CodePipe projects");gb.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Wk({profile:$e})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});gb.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 Yk({...t,cliProfile:$e})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var bu=De.command("repo").description("Manage the project's git repositories");bu.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 Zk({profile:$e,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});bu.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 Qk({profile:$e,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});bu.command("list").description("List the project's repos").action(async()=>{try{await eb({profile:$e})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var yb=De.command("model").description("Project map (model/ in the Context Repo)");yb.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 kl({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});yb.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 bl({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.parseAsync();
993
+ `)}catch{}}On();B();Ge();On();Ke();je();Yo();import{hostname as yA}from"node:os";import{cancel as wA,confirm as fb,intro as kA,isCancel as gb,log as Hn,multiselect as bA,outro as mb,password as $A,select as wu,text as ku}from"@clack/prompts";function Zo(t){wA(t),process.exit(1)}function Wn(t){return gb(t)&&Zo("aborted"),t}function Ws(t){return gb(t)&&Zo("aborted"),typeof t=="string"?t:""}function qs(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function hb(t,e){try{let{secret:r}=await os(t,e);return r}catch(r){throw r instanceof W&&r.status===404&&Zo("this HUB has no account-issued sandbox registration \u2014 issue a registration token in the dashboard (Status \u2192 SANDBOX) and re-run with it"),r}}async function vA(t,e){if(Wn(await wu({message:"which projects should this worker serve?",options:[{value:"all",label:"all my projects (recommended \u2014 new projects included automatically)"},{value:"selected",label:"only selected projects"}],initialValue:"all"}))==="all")return[];if(e)try{let o=await pl(t,e);if(o.length>0)return Wn(await bA({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}));Hn.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Hn.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return Ws(await ku({message:"project ids (comma or space separated)",placeholder:"acme, beta",validate:o=>o.trim().length>0?void 0:"required"})).split(/[\s,]+/).filter(Boolean)}async function bu(t){kA("codepipe worker \u2014 set up this machine as a runner");let e=Me(t.profile);e&&(Hn.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Wn(await fb({message:"re-register this worker?",initialValue:!1}))||Zo("keeping the existing registration"));let r=bt(t.profile)??bt(),n=Ws(await ku({message:"HUB URL",placeholder:ht,initialValue:Q("HUB_URL")??r?.hubUrl??ht,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=Wn(await wu({message:"how to authorize the registration?",options:[...o?[{value:"local",label:"this machine's CLI account (recommended \u2014 no token hand-off)"}]:[],{value:"login",label:"log in by email (magic-link, like codepipe init)"},{value:"paste",label:"paste a registration token from the dashboard"}],initialValue:o?"local":"login"})),s,a=null;if(i==="local")a=r.cliToken,s=await hb(n,a),Hn.success("account-issued registration token minted");else if(i==="login"){let d=await Un();a=(await Bn(n,d)).cliToken,s=await hb(n,a),Hn.success("account-issued registration token minted")}else s=Ws(await $A({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||Zo("a registration token is required");let c=await vA(n,a),l=Ws(await ku({message:"worker name",initialValue:yA(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=Wn(await wu({message:"agent backend",options:[{value:"claude-headless",label:"claude-headless \u2014 Claude Code on PATH (the real thing)"},{value:"mock",label:"mock \u2014 deterministic stub (development)"},{value:"",label:"none \u2014 this worker will not claim agent jobs"}],initialValue:"claude-headless"}));if(await Or({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Hn.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Wn(await fb({message:"start the claim-loop now?",initialValue:!0}))){mb("registered. start later with `codepipe worker`.");return}mb("starting the claim-loop\u2026"),await Ko(t.profile?{profile:t.profile}:{})}function SA(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return Q("PROFILE")}var be=SA();Vd(be);var Ue=new xA;Ue.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Ve).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{qs()?await pb({profile:be}):await Ds({profile:be})}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 Uk({configPath:t.config,skipVerify:t.skipVerify===!0}):await Rk({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 cp({...t,profile:be})}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 Ik({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 Sg({profile:be})}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 uk({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 Hk({profile:be,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 Nw({profile:be})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ue.command("pull").description("Fetch finished task branches into your local clones (no checkout switch)").option("--profile <name>","Config profile").option("--watch","Keep pulling instead of exiting after one pass").option("--interval <sec>","Watch interval in seconds (default 60, minimum 10)",t=>parseInt(t,10)).action(async t=>{if(t.interval!==void 0&&!Number.isFinite(t.interval))throw new Error("--interval expects a number of seconds");await ob({profile:t.profile,...t.watch?{watch:!0}:{},...Number.isFinite(t.interval)?{intervalSec:t.interval}:{}})});Ue.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).option("--debug [categories]","Write local debug logs (comma-separated categories; default: agent-request \u2014 the full prompt and context each agent job receives, under ~/.codepipe/debug/)").action(async t=>{try{await Ds({profile:be,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var yb=Ue.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");yb.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??Q("HUB_URL")??bt(be)?.hubUrl??ht,r=t.token??Q("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&qs()){await bu({profile:be});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let n=Q("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??Q("WORKER_NAME"),i=t.llm??Q("WORKER_LLM");await Or({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...be?{profile:be}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});yb.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!Me(be)&&qs()){await bu({profile:be});return}await Ko(be?{profile:be}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var wb=Ue.command("project").description("Manage CodePipe projects");wb.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await zk({profile:be})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});wb.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 Xk({...t,cliProfile:be})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var $u=Ue.command("repo").description("Manage the project's git repositories");$u.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:be,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});$u.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:be,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});$u.command("list").description("List the project's repos").action(async()=>{try{await nb({profile:be})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var kb=Ue.command("model").description("Project map (model/ in the Context Repo)");kb.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 $l({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});kb.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 vl({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ue.parseAsync();