@code-partner/codepipe 0.12.1-dev.243.g018cd70 → 0.12.1-dev.244.g988f0b1

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 +71 -71
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,33 +1,33 @@
1
1
  #!/usr/bin/env node
2
- var Vk=Object.defineProperty;var S=(t,e)=>()=>(t&&(e=t(t=0)),e);var We=(t,e)=>{for(var r in e)Vk(t,r,{get:e[r],enumerable:!0})};var qe,dt,Fs=S(()=>{"use strict";qe="0.12.1-dev.243.g018cd70",dt="https://hub.dev.codepipe.dev"});function Wn(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=hu&&t<=pt}var pt,hu,gu=S(()=>{"use strict";Fs();pt=4,hu=4});var yu=S(()=>{"use strict";Fs()});function qn(t=6){return`# CodePipe Context Repo format version.
2
+ var Vk=Object.defineProperty;var S=(t,e)=>()=>(t&&(e=t(t=0)),e);var We=(t,e)=>{for(var r in e)Vk(t,r,{get:e[r],enumerable:!0})};var qe,lt,Fs=S(()=>{"use strict";qe="0.12.1-dev.244.g988f0b1",lt="https://hub.dev.codepipe.dev"});function Wn(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=hu&&t<=ut}var ut,hu,gu=S(()=>{"use strict";Fs();ut=4,hu=4});var yu=S(()=>{"use strict";Fs()});function qn(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 Ks(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 Hs(t,e=Gs){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 Ws(t,e=Gs){return e.filter(r=>r.version>t)}var wu,ft,Br,Gs,ku=S(()=>{"use strict";wu=6,ft=".codepipe-context.yaml",Br=".devpipe-context.yaml",Gs=[{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",ft]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[ft]},{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 Vn(t){return`model/facts/identity/${t}.yaml`}function mr(t){return`model/facts/events/${t}.yaml`}function Vs(t){return`model/facts/annotations/${t}.md`}function zs(t){return`model/derived/correlates/${t}.yaml`}function Xs(t){return`model/derived/touched/${t}.yaml`}function bu(t){return t===""?"root":t.replace(/\//g,"-")}function Js(t,e){return`model/derived/structure/${t}/${bu(e)}.yaml`}function Yo(t){return typeof t=="string"&&vu.test(t)}function te(t){if(typeof t!="string")return null;let e=t.indexOf(":");if(e<=0)return null;let r=t.indexOf(":",e+1);if(r<0)return null;let n=t.slice(0,e);if(!$u.includes(n))return null;let o=t.slice(e+1,r),i=t.slice(r+1);return o===""&&!Qk.includes(n)||i===""?null:{level:n,repo:o,path:i}}function $e(t){return`task::${t}`}function ge(t,e,r){return`${t}:${e}:${r}`}function zn(t){let e=[];return $t(t)?(zo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),typeof t.repo!="string"&&e.push("repo: missing (empty string = cross-repo)"),typeof t.builtFromCommit!="string"&&e.push("builtFromCommit: missing"),Array.isArray(t.edges)?t.edges.forEach((r,n)=>{if(!$t(r)){e.push(`edges[${n}]: not an object`);return}Zs.includes(r.kind)||e.push(`edges[${n}].kind: unknown "${String(r.kind)}"`),te(r.from)||e.push(`edges[${n}].from: malformed nodeKey`),te(r.to)||e.push(`edges[${n}].to: malformed nodeKey`),r.weight!==void 0&&!(typeof r.weight=="number"&&Number.isFinite(r.weight))&&e.push(`edges[${n}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}):{ok:!1,errors:["edge sheet: not an object"]}}function xu(t){return{...t,edges:Fr(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function hr(t){return yr(xu(t))}function $t(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function zo(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function mt(t){return typeof t=="string"&&t.length>0}function tb(t){return t.modelFormatVersion!==2}function Pt(t){let e=[];if(!$t(t))return{ok:!1,errors:["shard: not an object"]};zo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),mt(t.repo)||e.push("repo: missing or empty"),mt(t.builtFromCommit)||e.push("builtFromCommit: missing or empty");let r=typeof t.repo=="string"?t.repo:"",n=new Set;return Array.isArray(t.nodes)?t.nodes.forEach((o,i)=>{if(!$t(o)){e.push(`nodes[${i}]: not an object`);return}let s=te(o.key);if(!s){e.push(`nodes[${i}].key: malformed nodeKey (${JSON.stringify(o.key??null)})`);return}o.level!==s.level&&e.push(`nodes[${i}]: level "${String(o.level)}" does not match key prefix "${s.level}"`),r&&s.repo!==r&&e.push(`nodes[${i}].key: repo "${s.repo}" mixed into shard of repo "${r}"`);let a=o.key;n.has(a)&&e.push(`nodes[${i}].key: duplicate "${a}"`),n.add(a),o.entityId!==void 0&&!Yo(o.entityId)&&e.push(`nodes[${i}].entityId: malformed (${JSON.stringify(o.entityId)})`)}):e.push("nodes: not an array"),Array.isArray(t.edges)?t.edges.forEach((o,i)=>{if(!$t(o)){e.push(`edges[${i}]: not an object`);return}Zs.includes(o.kind)||e.push(`edges[${i}].kind: unknown "${String(o.kind)}"`),(!mt(o.to)||!te(o.to))&&e.push(`edges[${i}].to: malformed nodeKey`),(!mt(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 Xn(t){let e=[];if(!$t(t))return{ok:!1,errors:["identity: not an object"]};if(zo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),mt(t.repo)||e.push("repo: missing or empty"),t.builtFromCommit!==void 0&&!mt(t.builtFromCommit)&&e.push("builtFromCommit: not a non-empty string"),!Array.isArray(t.entities))e.push("entities: not an array");else{let r=new Set;t.entities.forEach((n,o)=>{if(!$t(n)){e.push(`entities[${o}]: not an object`);return}Yo(n.entityId)?r.has(n.entityId)?e.push(`entities[${o}].entityId: duplicate "${n.entityId}"`):r.add(n.entityId):e.push(`entities[${o}].entityId: malformed (${JSON.stringify(n.entityId??null)})`),te(n.currentKey)||e.push(`entities[${o}].currentKey: malformed nodeKey`),n.status!=="active"&&n.status!=="orphaned"&&e.push(`entities[${o}].status: expected active|orphaned`),mt(n.firstSeen)||e.push(`entities[${o}].firstSeen: missing`),mt(n.lastSeen)||e.push(`entities[${o}].lastSeen: missing`),n.aliases!==void 0&&(Array.isArray(n.aliases)?n.aliases.forEach((i,s)=>{(!$t(i)||!te(i.key)||!mt(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 At(t){let e=[];return $t(t)?(zo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),mt(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=>!mt(r)))&&e.push("commits: not an array of non-empty strings"),Array.isArray(t.files)?t.files.forEach((r,n)=>{if(!$t(r)||!te(r.key)){e.push(`files[${n}].key: malformed nodeKey`);return}r.entityId!==void 0&&!Yo(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 Fr(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function Su(t){return{...t,nodes:Fr(t.nodes,e=>e.key),edges:Fr(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function Eu(t){return{...t,entities:Fr(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:Fr(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function Tu(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:Fr(t.files,r=>r.key),...e?{links:e}:{}}}function Yn(t){return rb.test(t)?t:JSON.stringify(t)}function Iu(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 Ru(t){return t===null||["boolean","number","string"].includes(typeof t)}function qs(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function Cu(t,e,r){if(Array.isArray(t)){for(let n of t)if(Ru(n))r.push(`${e}- ${Iu(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=qs(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([i,s],a)=>{let c=a===0?`${e}- `:`${e} `;Ys(i,s,c,`${e} `,r)})}}return}for(let[n,o]of qs(t))Ys(n,o,e,e,r)}function Ys(t,e,r,n,o){if(Ru(e))o.push(`${r}${Yn(t)}: ${Iu(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${Yn(t)}: []`):(o.push(`${r}${Yn(t)}:`),Cu(e,`${n} `,o));else{let i=qs(e);if(i.length===0)o.push(`${r}${Yn(t)}: {}`);else{o.push(`${r}${Yn(t)}:`);for(let[s,a]of i)Ys(s,a,`${n} `,`${n} `,o)}}}function yr(t){let e=[];return Cu(t,"",e),e.join(`
5
+ `}function Ks(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 Hs(t,e=Gs){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 Ws(t,e=Gs){return e.filter(r=>r.version>t)}var wu,dt,Br,Gs,ku=S(()=>{"use strict";wu=6,dt=".codepipe-context.yaml",Br=".devpipe-context.yaml",Gs=[{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",dt]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[dt]},{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 Vn(t){return`model/facts/identity/${t}.yaml`}function mr(t){return`model/facts/events/${t}.yaml`}function Vs(t){return`model/facts/annotations/${t}.md`}function zs(t){return`model/derived/correlates/${t}.yaml`}function Xs(t){return`model/derived/touched/${t}.yaml`}function bu(t){return t===""?"root":t.replace(/\//g,"-")}function Js(t,e){return`model/derived/structure/${t}/${bu(e)}.yaml`}function Yo(t){return typeof t=="string"&&vu.test(t)}function te(t){if(typeof t!="string")return null;let e=t.indexOf(":");if(e<=0)return null;let r=t.indexOf(":",e+1);if(r<0)return null;let n=t.slice(0,e);if(!$u.includes(n))return null;let o=t.slice(e+1,r),i=t.slice(r+1);return o===""&&!Qk.includes(n)||i===""?null:{level:n,repo:o,path:i}}function $e(t){return`task::${t}`}function ge(t,e,r){return`${t}:${e}:${r}`}function zn(t){let e=[];return bt(t)?(zo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),typeof t.repo!="string"&&e.push("repo: missing (empty string = cross-repo)"),typeof t.builtFromCommit!="string"&&e.push("builtFromCommit: missing"),Array.isArray(t.edges)?t.edges.forEach((r,n)=>{if(!bt(r)){e.push(`edges[${n}]: not an object`);return}Zs.includes(r.kind)||e.push(`edges[${n}].kind: unknown "${String(r.kind)}"`),te(r.from)||e.push(`edges[${n}].from: malformed nodeKey`),te(r.to)||e.push(`edges[${n}].to: malformed nodeKey`),r.weight!==void 0&&!(typeof r.weight=="number"&&Number.isFinite(r.weight))&&e.push(`edges[${n}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}):{ok:!1,errors:["edge sheet: not an object"]}}function xu(t){return{...t,edges:Fr(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function hr(t){return yr(xu(t))}function bt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function zo(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function pt(t){return typeof t=="string"&&t.length>0}function tb(t){return t.modelFormatVersion!==2}function Pt(t){let e=[];if(!bt(t))return{ok:!1,errors:["shard: not an object"]};zo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),pt(t.repo)||e.push("repo: missing or empty"),pt(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(!bt(o)){e.push(`nodes[${i}]: not an object`);return}let s=te(o.key);if(!s){e.push(`nodes[${i}].key: malformed nodeKey (${JSON.stringify(o.key??null)})`);return}o.level!==s.level&&e.push(`nodes[${i}]: level "${String(o.level)}" does not match key prefix "${s.level}"`),r&&s.repo!==r&&e.push(`nodes[${i}].key: repo "${s.repo}" mixed into shard of repo "${r}"`);let a=o.key;n.has(a)&&e.push(`nodes[${i}].key: duplicate "${a}"`),n.add(a),o.entityId!==void 0&&!Yo(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(!bt(o)){e.push(`edges[${i}]: not an object`);return}Zs.includes(o.kind)||e.push(`edges[${i}].kind: unknown "${String(o.kind)}"`),(!pt(o.to)||!te(o.to))&&e.push(`edges[${i}].to: malformed nodeKey`),(!pt(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 Xn(t){let e=[];if(!bt(t))return{ok:!1,errors:["identity: not an object"]};if(zo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),pt(t.repo)||e.push("repo: missing or empty"),t.builtFromCommit!==void 0&&!pt(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(!bt(n)){e.push(`entities[${o}]: not an object`);return}Yo(n.entityId)?r.has(n.entityId)?e.push(`entities[${o}].entityId: duplicate "${n.entityId}"`):r.add(n.entityId):e.push(`entities[${o}].entityId: malformed (${JSON.stringify(n.entityId??null)})`),te(n.currentKey)||e.push(`entities[${o}].currentKey: malformed nodeKey`),n.status!=="active"&&n.status!=="orphaned"&&e.push(`entities[${o}].status: expected active|orphaned`),pt(n.firstSeen)||e.push(`entities[${o}].firstSeen: missing`),pt(n.lastSeen)||e.push(`entities[${o}].lastSeen: missing`),n.aliases!==void 0&&(Array.isArray(n.aliases)?n.aliases.forEach((i,s)=>{(!bt(i)||!te(i.key)||!pt(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 At(t){let e=[];return bt(t)?(zo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),pt(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=>!pt(r)))&&e.push("commits: not an array of non-empty strings"),Array.isArray(t.files)?t.files.forEach((r,n)=>{if(!bt(r)||!te(r.key)){e.push(`files[${n}].key: malformed nodeKey`);return}r.entityId!==void 0&&!Yo(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 Fr(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function Su(t){return{...t,nodes:Fr(t.nodes,e=>e.key),edges:Fr(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function Eu(t){return{...t,entities:Fr(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:Fr(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function Tu(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:Fr(t.files,r=>r.key),...e?{links:e}:{}}}function Yn(t){return rb.test(t)?t:JSON.stringify(t)}function Iu(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 Ru(t){return t===null||["boolean","number","string"].includes(typeof t)}function qs(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function Cu(t,e,r){if(Array.isArray(t)){for(let n of t)if(Ru(n))r.push(`${e}- ${Iu(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=qs(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([i,s],a)=>{let c=a===0?`${e}- `:`${e} `;Ys(i,s,c,`${e} `,r)})}}return}for(let[n,o]of qs(t))Ys(n,o,e,e,r)}function Ys(t,e,r,n,o){if(Ru(e))o.push(`${r}${Yn(t)}: ${Iu(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${Yn(t)}: []`):(o.push(`${r}${Yn(t)}:`),Cu(e,`${n} `,o));else{let i=qs(e);if(i.length===0)o.push(`${r}${Yn(t)}: {}`);else{o.push(`${r}${Yn(t)}:`);for(let[s,a]of i)Ys(s,a,`${n} `,`${n} `,o)}}}function yr(t){let e=[];return Cu(t,"",e),e.join(`
6
6
  `)+`
7
- `}function na(t){return yr(Su(t))}function oa(t){return yr(Eu(t))}function Gr(t){return yr(Tu(t))}var Oe,zk,Xk,Jk,Zk,qo,fr,$u,Zs,vu,Qk,tt,Qs,ea,ta,Vo,eb,ra,gr,rb,ia=S(()=>{"use strict";Oe=2,zk="model",Xk="model/README.md",Jk="model/facts",Zk="model/derived",qo="model/derived/INDEX.yaml",fr="model/derived/relates.yaml";$u=["system","container","component","code","task","adr"],Zs=["contains","touched_by","correlates","relates","references","depends_on"],vu=/^e_[0-9a-f]{8}$/;Qk=["system","task","adr"];tt={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};Qs=2,ea=5,ta=50,Vo=2e3,eb=5e4,ra={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},gr={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};rb=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});function nb(t){return t==="DONE"}function ob(t){return t==="AWAITING_EXTERNAL_FIX"?!1:sa.indexOf(t)>=sa.indexOf("IMPLEMENTING")}var sa,Pu=S(()=>{"use strict";sa=["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 sb(t){for(let e of aa)if(e.phases.includes(t))return e.id;return null}function ab(t){for(let e of Au)if(e.phases.includes(t))return e.id;return null}var aa,ib,Au,_u=S(()=>{"use strict";aa=[{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"]}],ib=aa.flatMap(t=>t.phases),Au=[{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 cb(t){return ju.includes(t)?"planning":"implementation"}function Kt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var ca,ju,lb,la=S(()=>{"use strict";ca=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat","observer","council","testing"],ju=["draft","analysis","chat","observer","council"];lb=1});function Nu(t,e){return e.toLowerCase().includes(t.toLowerCase())}function pa(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||Uu.every(o=>e.some(i=>Nu(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 Du){let i=n.find(s=>Nu(o,s.id));if(i)return i.id}return n[0].id}function Kr(){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():Zn[e]??Mu}function db(t){let e=t?.provider;return typeof e=="string"&&e.trim().length>0?e.trim():Ye}function pb(t){let e=Kr();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 fb(t){let e=typeof t.provider=="string"&&t.provider.trim().length>0&&t.provider.trim()!==Ye;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 mb(t){if(!t)return Kr();try{let e=JSON.parse(t);if(!e||typeof e!="object")return Kr();let r=e,n=Kr();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 Kr()}}var Ye,ua,Ce,Jn,Xo,Jo,Ou,Lu,da,Zn,Mu,Du,Uu,fa=S(()=>{"use strict";la();Ye="claude",ua=[Ye],Ce="opus",Jn="sonnet",Xo="haiku",Jo=[Ce,Jn,Xo],Ou="build-discovery",Lu=[Ou],da=[...ca,...Lu],Zn={analyze:Ce,implement:Ce,"resolve-conflict":Ce,rework:Ce,estimate:Jn,build:Xo,"build-discovery":Ce,"code-review":Ce,draft:Jn,index:Ce,backfill:Ce,analysis:Ce,chat:Ce,observer:Ce,council:Ce,testing:Ce},Mu=Ce,Du=[Ce,Jn,Xo],Uu=Array.from(new Set(Object.values(Zn)))});function _t(t){return hb.has(t)?!0:gb.some(e=>t.startsWith(e))}function Zo(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function wr(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function ha(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function ya(t,e){let r=Zo(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=wr(r.id,"id")??n;if(!ma.test(o))throw new Error(`id must match ${ma} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=wr(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=Zo(r.env,"env");s={};for(let[d,m]of Object.entries(p)){if(!Ve.test(d))throw new Error(`env name "${d}" must match ${Ve}`);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>Bu)throw new Error(`too many params (max ${Bu})`);let p=new Set;a=c.map((d,m)=>yb(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>Fu)throw new Error(`too many steps (max ${Fu})`);let u=l.map((p,d)=>{let m=Zo(p,`steps[${d}]`),f=wr(m.run,`steps[${d}].run`);if(!f||f.trim().length===0)throw new Error(`steps[${d}].run is required`);let g=wr(m.name,`steps[${d}].name`),h=ha(m.timeout_sec,`steps[${d}].timeout_sec`);if(h!==void 0&&(!Number.isInteger(h)||h<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:f,...g?{name:g}:{},...h!==void 0?{timeout_sec:h}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function yb(t,e,r){let n=Zo(t,`params[${e}]`),o=wr(n.name,`params[${e}].name`);if(!o||!Ve.test(o))throw new Error(`params[${e}].name must match ${Ve}`);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=wr(n.label,`params[${e}].label`),c=wr(n.help,`params[${e}].help`),l=n.required===!0,u=ha(n.min,`params[${e}].min`),p=ha(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 wa(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 Ve,hb,gb,ga,ma,Bu,Fu,ka=S(()=>{"use strict";Ve=/^[A-Z][A-Z0-9_]*$/,hb=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),gb=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];ga=600,ma=/^[a-z0-9-]+$/,Bu=32,Fu=64});function Gu(){return{primary:ve,context:ve,tasks:ve,docs:ve,code_comments:ve,chat:ve}}function Ku(t){return!t||t.trim().length===0||t.trim().toLowerCase()===ve}function wb(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 kb(t){let e=Gu();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 Qn)e[o]=wb(n[o]);return e}function bb(t){return Qn.every(e=>Ku(t[e]))}var ve,Qn,Hr,eo,ba=S(()=>{"use strict";ve="auto",Qn=["primary","context","tasks","docs","code_comments","chat"],Hr=["English","Russian","German","Spanish","French","Portuguese","Italian","Chinese","Japanese","Korean"],eo=40});function Sa(t=Hu){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...Sa(r.groups));return e}function Wu(t,e){let r=JSON.stringify(e);return Sa().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function Ea(t){let e=Wu(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.type==="string"&&e.mustContain&&!i.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:e.maxLength!==void 0&&i.length>e.maxLength?{ok:!1,error:`${e.id} must be \u2264 ${e.maxLength} chars`}:{ok:!0,field:e,value:i}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}case"string_map":{if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,error:`${e.id} must be a name\u2192value map`};let i=Object.entries(r);if(i.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(i.length>$a)return{ok:!1,error:`${e.id} must have \u2264 ${$a} entries`};let s={};for(let[a,c]of i){if(!Ve.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Ve}`};if(_t(a))return{ok:!1,error:`${e.id}: name "${a}" is reserved`};if(typeof c!="string")return{ok:!1,error:`${e.id}: value of "${a}" must be a string`};if(c.length>va)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${va} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var $b,vb,$a,va,xa,Hu,qu=S(()=>{"use strict";ka();fa();ia();ba();$b={primary:"Primary language",context:"Context documents",tasks:"Tracker issues",docs:"Repo documentation",code_comments:"Code comments",chat:"Agent chat"},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."},$a=64,va=2e3,xa=2e3,Hu=[{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:[...ua],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:[...Jo],help:"Overrides the recommended defaults for every role not listed below."},...da.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Jo],help:`recommended: ${Zn[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:xa,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:xa,help:`e.g. "implementation details, bullet list of what was done, in the tracker's language". Empty \u21D2 the default PR body.`}]},{id:"apply.delivery",label:"Delivery & merge",help:"How a finished change reaches the repository: with or without a pull request, and who merges it.",fields:[{id:"apply.pull_request",file:"project.yaml",path:["apply","pull_request"],type:"boolean",label:"Open a pull request",nullable:!1,help:"On (default): the task branch is pushed and a pull request is opened \u2014 the change is reviewable in the git host and keeps a history of review comments. Off: no PR at all; the branch is merged into the default branch directly, and the agent's review remarks live only in the dashboard and the Context Repo."},{id:"apply.done",file:"project.yaml",path:["apply","done"],type:"enum",label:"Task is done when",nullable:!1,suggestions:["merge","branch"],help:"merge (default): the task is finished only once its change lands in the default branch. branch: the task ends at the pushed branch (plus the PR, if enabled) and nothing is merged for you."},{id:"apply.auto_merge",file:"project.yaml",path:["apply","auto_merge"],type:"enum",label:"Auto-merge pull requests",nullable:!1,suggestions:["off","on_ci_green"],help:"Applies to the pull-request path only. off (default): the merge waits for you (Approve on the task card). on_ci_green: as soon as the PR is open, conflict-free and its CI is green, CodePipe merges it \u2014 changes reach the default branch with no further review from you. Requires full automation; branch protection on the host still applies (a refused merge parks the task). Without pull requests, full automation merges the branch itself and this switch does not apply."}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{id:"testing",label:"Testing",help:"An optional phase after code review: writes the test plan you run in the morning and reports what it could verify.",fields:[{id:"testing.enabled",file:"regimen.yaml",path:["testing","enabled"],type:"boolean",nullable:!1,label:"Run the testing phase",help:"Off by default. When on, a task passing code review goes through a test pass before the PR: it derives TESTPLAN.md from the plan's requirements and reports per requirement what it could verify. A requirement it finds broken sends the change back for a fix (bounded below)."},{id:"testing.max_iterations",file:"regimen.yaml",path:["testing","max_iterations"],type:"number",nullable:!0,min:1,max:10,label:"Fix rounds before stopping",help:"How many times a failed test pass may send the change back before the task waits for you. Empty \u21D2 2."}]},{id:"skills",label:"Skills",help:"Reusable procedures the agent can invoke instead of improvising. Only their names and one-line descriptions sit in the prompt; the steps load when a skill is used.",fields:[{id:"skills.from_bundled",file:"regimen.yaml",path:["skills","from_bundled"],type:"boolean",nullable:!1,label:"Use the skills shipped with CodePipe",help:"On by default. General procedures maintained with the product."},{id:"skills.from_context_repo",file:"regimen.yaml",path:["skills","from_context_repo"],type:"boolean",nullable:!1,label:"Use this project's skills",help:"On by default. Skills the team writes in the context repository under `skills/<name>/SKILL.md`. These override a bundled skill of the same name."},{id:"skills.from_project_repo",file:"regimen.yaml",path:["skills","from_project_repo"],type:"boolean",nullable:!1,label:"Use the code repository's skills",help:"On by default. `.claude/skills/` inside the project repositories \u2014 the skills your developers already use locally. These win over both other sources."}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (on by default; orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on (default), a task taken from Develop waits in the QUEUE for a single Confirm before the pipeline starts \u2014 the Confirm pulls in dependency closure and topologically orders the queue. Off \u21D2 conveyor: the task starts the pipeline immediately."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]},{id:"language",label:"Language",help:"Languages the agent writes in, per area. Empty \u21D2 auto: mirror the language of the user's material.",fields:Qn.map(t=>({id:`language.${t}`,file:"project.yaml",path:["language",t],type:"string",label:$b[t],nullable:!0,maxLength:40,suggestions:t==="chat"?[ve,...Hr]:[...Hr],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 ${tt.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 ${tt.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 ${tt.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 ${tt.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 ${tt.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 ${tt.topK}.`}]},{id:"context.job_logs",label:"Job transcripts",help:"Whether the raw agent transcript of each job is kept in the Context Repo.",fields:[{id:"context.job_logs.enabled",file:"regimen.yaml",path:["context","job_logs","enabled"],type:"boolean",label:"Keep transcripts in the Context Repo",nullable:!1,help:"Off (default): the transcript is discarded after the run \u2014 nothing lands in the Context Repo. On: each job's raw transcript is committed as tasks/<KEY>/logs/job-<id>.jsonl for post-mortem debugging."}]}]});function Yu(t){if(t==null)return[];if(!Array.isArray(t))return null;let e=[];for(let r of t){if(typeof r!="string"||r.trim().length===0)return null;e.push(r.trim())}return e}function Ia(t){let{name:e,body:r,origin:n}=t;if(!Ta.test(e))return{ok:!1,error:`role name must match ${Ta} (got "${e}")`};if(r.trim().length===0)return{ok:!1,error:"role body is empty \u2014 the body IS the role's prompt"};let o=t.frontmatter;if(o==null||typeof o!="object"||Array.isArray(o))return{ok:!1,error:"missing or malformed frontmatter block"};let 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=Yu(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=Yu(i.scenarios);if(c===null)return{ok:!1,error:"scenarios must be a list"};let l=[];for(let d of c){if(!Qo.includes(d))return{ok:!1,error:`unknown scenario "${d}" \u2014 one of: ${Qo.join(", ")}`};l.includes(d)||l.push(d)}if(l.length===0)return{ok:!1,error:`scenarios must name at least one of: ${Qo.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 Ra(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 Ca(t,e){return t.filter(r=>r.enabled&&r.scenarios.includes(e))}var Qo,Ta,qP,YP,Vu=S(()=>{"use strict";Qo=["plan_review","code_review","council"],Ta=/^[a-z][a-z0-9-]{1,39}$/,qP=10,YP=300});function Pa(t){return zu.includes(t)}function Aa(t){return`prompts/${t}.md`}var zu,Xu=S(()=>{"use strict";zu=["analysis","analyze","backfill","build","chat","code-review","code-review-external","code-review-fix","council","draft","estimate","implement","index","observer","resolve-conflict","rework","testing"]});function ja(t){if(!_a.test(t.name))return{ok:!1,error:`skill directory name must match ${_a}`};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 Na(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 Zu(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=Ju.find(s=>s.repo.toLowerCase()===n.toLowerCase());return o&&!Sb.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 Eb(t){let e=[],r=[],n=new Set;for(let o of t){if(!o.trim())continue;let i=Zu(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 Ib(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(!Tb.test(s)||!r.has(s.slice(s.indexOf("@")+1))){o.push(s);continue}n[s]=!0}}return{enabled:n,unknown:o}}var _a,XP,Ju,xb,Sb,Tb,Qu=S(()=>{"use strict";_a=/^[a-z][a-z0-9-]{1,39}$/,XP=300;Ju=[{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.-]*$/,Sb=/^[0-9a-f]{40}$/;Tb=/^[A-Za-z0-9][\w.-]*@[A-Za-z0-9][\w.-]*$/});function ed(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 Rb(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=ed(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,h=typeof g.taskKey=="string"?g.taskKey.trim():"";if(!r.has(h))return{ok:!1,error:`tasks names ${h||"(empty)"}, which is not in this batch`};let k=ed(g.after,e.length);if(k===null)return{ok:!1,error:`${h}: after must be a list of task keys`};for(let $ of k){if(!r.has($))return{ok:!1,error:`${h}: after names ${$}, not in this batch`};if($===h)return{ok:!1,error:`${h}: cannot come after itself`}}let w=typeof g.decisions=="string"?g.decisions.trim():"";a.push({taskKey:h,decisions:w.slice(0,4e3),after:k})}}let c=[],l=n.conflicts;if(Array.isArray(l))for(let f of l){if(!f||typeof f!="object")continue;let g=f,h=typeof g.taskKey=="string"?g.taskKey.trim():"",k=typeof g.adr=="string"?g.adr.trim():"",w=typeof g.detail=="string"?g.detail.trim():"";!r.has(h)||!w||c.push({taskKey:h,adr:k,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,h=typeof g.taskKey=="string"?g.taskKey.trim():"",k=typeof g.detail=="string"?g.detail.trim():"";!h||!k||u.push({taskKey:h,detail:k.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 ZP,QP,td=S(()=>{"use strict";ZP=4e3,QP=4e3});function Cb(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 tA,rd=S(()=>{"use strict";tA=4e3});function _b(t){let e=t.replace(/^#+\s*/,"").trim();for(let r of Pb)if(r.re.test(e))return{kind:r.kind,letter:r.letter};return null}function Oa(t){let e=[],r=new Map,n="",o=null,i=null;for(let a of t.split(`
7
+ `}function na(t){return yr(Su(t))}function oa(t){return yr(Eu(t))}function Gr(t){return yr(Tu(t))}var Oe,zk,Xk,Jk,Zk,qo,fr,$u,Zs,vu,Qk,tt,Qs,ea,ta,Vo,eb,ra,gr,rb,ia=S(()=>{"use strict";Oe=2,zk="model",Xk="model/README.md",Jk="model/facts",Zk="model/derived",qo="model/derived/INDEX.yaml",fr="model/derived/relates.yaml";$u=["system","container","component","code","task","adr"],Zs=["contains","touched_by","correlates","relates","references","depends_on"],vu=/^e_[0-9a-f]{8}$/;Qk=["system","task","adr"];tt={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};Qs=2,ea=5,ta=50,Vo=2e3,eb=5e4,ra={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},gr={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};rb=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});function nb(t){return t==="DONE"}function ob(t){return t==="AWAITING_EXTERNAL_FIX"?!1:sa.indexOf(t)>=sa.indexOf("IMPLEMENTING")}var sa,Pu=S(()=>{"use strict";sa=["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 sb(t){for(let e of aa)if(e.phases.includes(t))return e.id;return null}function ab(t){for(let e of Au)if(e.phases.includes(t))return e.id;return null}var aa,ib,Au,_u=S(()=>{"use strict";aa=[{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"]}],ib=aa.flatMap(t=>t.phases),Au=[{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 cb(t){return ju.includes(t)?"planning":"implementation"}function Kt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var ca,ju,lb,la=S(()=>{"use strict";ca=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat","observer","council","testing"],ju=["draft","analysis","chat","observer","council"];lb=1});function Nu(t,e){return e.toLowerCase().includes(t.toLowerCase())}function pa(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||Uu.every(o=>e.some(i=>Nu(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 Du){let i=n.find(s=>Nu(o,s.id));if(i)return i.id}return n[0].id}function Kr(){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():Zn[e]??Mu}function db(t){let e=t?.provider;return typeof e=="string"&&e.trim().length>0?e.trim():Ye}function pb(t){let e=Kr();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 fb(t){let e=typeof t.provider=="string"&&t.provider.trim().length>0&&t.provider.trim()!==Ye;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 mb(t){if(!t)return Kr();try{let e=JSON.parse(t);if(!e||typeof e!="object")return Kr();let r=e,n=Kr();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 Kr()}}var Ye,ua,Ce,Jn,Xo,Jo,Ou,Lu,da,Zn,Mu,Du,Uu,fa=S(()=>{"use strict";la();Ye="claude",ua=[Ye],Ce="opus",Jn="sonnet",Xo="haiku",Jo=[Ce,Jn,Xo],Ou="build-discovery",Lu=[Ou],da=[...ca,...Lu],Zn={analyze:Ce,implement:Ce,"resolve-conflict":Ce,rework:Ce,estimate:Jn,build:Xo,"build-discovery":Ce,"code-review":Ce,draft:Jn,index:Ce,backfill:Ce,analysis:Ce,chat:Ce,observer:Ce,council:Ce,testing:Ce},Mu=Ce,Du=[Ce,Jn,Xo],Uu=Array.from(new Set(Object.values(Zn)))});function _t(t){return hb.has(t)?!0:gb.some(e=>t.startsWith(e))}function Zo(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function wr(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function ha(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function ya(t,e){let r=Zo(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=wr(r.id,"id")??n;if(!ma.test(o))throw new Error(`id must match ${ma} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=wr(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=Zo(r.env,"env");s={};for(let[d,m]of Object.entries(p)){if(!Ve.test(d))throw new Error(`env name "${d}" must match ${Ve}`);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>Bu)throw new Error(`too many params (max ${Bu})`);let p=new Set;a=c.map((d,m)=>yb(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>Fu)throw new Error(`too many steps (max ${Fu})`);let u=l.map((p,d)=>{let m=Zo(p,`steps[${d}]`),f=wr(m.run,`steps[${d}].run`);if(!f||f.trim().length===0)throw new Error(`steps[${d}].run is required`);let g=wr(m.name,`steps[${d}].name`),h=ha(m.timeout_sec,`steps[${d}].timeout_sec`);if(h!==void 0&&(!Number.isInteger(h)||h<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:f,...g?{name:g}:{},...h!==void 0?{timeout_sec:h}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function yb(t,e,r){let n=Zo(t,`params[${e}]`),o=wr(n.name,`params[${e}].name`);if(!o||!Ve.test(o))throw new Error(`params[${e}].name must match ${Ve}`);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=wr(n.label,`params[${e}].label`),c=wr(n.help,`params[${e}].help`),l=n.required===!0,u=ha(n.min,`params[${e}].min`),p=ha(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 wa(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 Ve,hb,gb,ga,ma,Bu,Fu,ka=S(()=>{"use strict";Ve=/^[A-Z][A-Z0-9_]*$/,hb=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),gb=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];ga=600,ma=/^[a-z0-9-]+$/,Bu=32,Fu=64});function Gu(){return{primary:ve,context:ve,tasks:ve,docs:ve,code_comments:ve,chat:ve}}function Ku(t){return!t||t.trim().length===0||t.trim().toLowerCase()===ve}function wb(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 kb(t){let e=Gu();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 Qn)e[o]=wb(n[o]);return e}function bb(t){return Qn.every(e=>Ku(t[e]))}var ve,Qn,Hr,eo,ba=S(()=>{"use strict";ve="auto",Qn=["primary","context","tasks","docs","code_comments","chat"],Hr=["English","Russian","German","Spanish","French","Portuguese","Italian","Chinese","Japanese","Korean"],eo=40});function Sa(t=Hu){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...Sa(r.groups));return e}function Wu(t,e){let r=JSON.stringify(e);return Sa().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function Ea(t){let e=Wu(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.type==="string"&&e.mustContain&&!i.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:e.maxLength!==void 0&&i.length>e.maxLength?{ok:!1,error:`${e.id} must be \u2264 ${e.maxLength} chars`}:{ok:!0,field:e,value:i}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}case"string_map":{if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,error:`${e.id} must be a name\u2192value map`};let i=Object.entries(r);if(i.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(i.length>$a)return{ok:!1,error:`${e.id} must have \u2264 ${$a} entries`};let s={};for(let[a,c]of i){if(!Ve.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Ve}`};if(_t(a))return{ok:!1,error:`${e.id}: name "${a}" is reserved`};if(typeof c!="string")return{ok:!1,error:`${e.id}: value of "${a}" must be a string`};if(c.length>va)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${va} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var $b,vb,$a,va,xa,Hu,qu=S(()=>{"use strict";ka();fa();ia();ba();$b={primary:"Primary language",context:"Context documents",tasks:"Tracker issues",docs:"Repo documentation",code_comments:"Code comments",chat:"Agent chat"},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."},$a=64,va=2e3,xa=2e3,Hu=[{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:[...ua],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:[...Jo],help:"Overrides the recommended defaults for every role not listed below."},...da.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Jo],help:`recommended: ${Zn[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:xa,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:xa,help:`e.g. "implementation details, bullet list of what was done, in the tracker's language". Empty \u21D2 the default PR body.`}]},{id:"apply.delivery",label:"Delivery & merge",help:"How a finished change reaches the repository: with or without a pull request, and who merges it.",fields:[{id:"apply.pull_request",file:"project.yaml",path:["apply","pull_request"],type:"boolean",label:"Open a pull request",nullable:!1,help:"On (default): the task branch is pushed and a pull request is opened \u2014 the change is reviewable in the git host and keeps a history of review comments. Off: no PR at all; the branch is merged into the default branch directly, and the agent's review remarks live only in the dashboard and the Context Repo."},{id:"apply.done",file:"project.yaml",path:["apply","done"],type:"enum",label:"Task is done when",nullable:!1,suggestions:["merge","branch"],help:"merge (default): the task is finished only once its change lands in the default branch. branch: the task ends at the pushed branch (plus the PR, if enabled) and nothing is merged for you."},{id:"apply.auto_merge",file:"project.yaml",path:["apply","auto_merge"],type:"enum",label:"Auto-merge pull requests",nullable:!1,suggestions:["off","on_ci_green"],help:"Applies to the pull-request path only. off (default): the merge waits for you (Approve on the task card). on_ci_green: as soon as the PR is open, conflict-free and its CI is green, CodePipe merges it \u2014 changes reach the default branch with no further review from you. Requires full automation; branch protection on the host still applies (a refused merge parks the task). Without pull requests, full automation merges the branch itself and this switch does not apply."}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{id:"testing",label:"Testing",help:"An optional phase after code review: writes the test plan you run in the morning and reports what it could verify.",fields:[{id:"testing.enabled",file:"regimen.yaml",path:["testing","enabled"],type:"boolean",nullable:!1,label:"Run the testing phase",help:"Off by default. When on, a task passing code review goes through a test pass before the PR: it derives TESTPLAN.md from the plan's requirements and reports per requirement what it could verify. A requirement it finds broken sends the change back for a fix (bounded below)."},{id:"testing.max_iterations",file:"regimen.yaml",path:["testing","max_iterations"],type:"number",nullable:!0,min:1,max:10,label:"Fix rounds before stopping",help:"How many times a failed test pass may send the change back before the task waits for you. Empty \u21D2 2."}]},{id:"skills",label:"Skills",help:"Reusable procedures the agent can invoke instead of improvising. Only their names and one-line descriptions sit in the prompt; the steps load when a skill is used.",fields:[{id:"skills.from_bundled",file:"regimen.yaml",path:["skills","from_bundled"],type:"boolean",nullable:!1,label:"Use the skills shipped with CodePipe",help:"On by default. General procedures maintained with the product."},{id:"skills.from_context_repo",file:"regimen.yaml",path:["skills","from_context_repo"],type:"boolean",nullable:!1,label:"Use this project's skills",help:"On by default. Skills the team writes in the context repository under `skills/<name>/SKILL.md`. These override a bundled skill of the same name."},{id:"skills.from_project_repo",file:"regimen.yaml",path:["skills","from_project_repo"],type:"boolean",nullable:!1,label:"Use the code repository's skills",help:"On by default. `.claude/skills/` inside the project repositories \u2014 the skills your developers already use locally. These win over both other sources."}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (on by default; orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on (default), a task taken from Develop waits in the QUEUE for a single Confirm before the pipeline starts \u2014 the Confirm pulls in dependency closure and topologically orders the queue. Off \u21D2 conveyor: the task starts the pipeline immediately."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]},{id:"language",label:"Language",help:"Languages the agent writes in, per area. Empty \u21D2 auto: mirror the language of the user's material.",fields:Qn.map(t=>({id:`language.${t}`,file:"project.yaml",path:["language",t],type:"string",label:$b[t],nullable:!0,maxLength:40,suggestions:t==="chat"?[ve,...Hr]:[...Hr],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 ${tt.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 ${tt.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 ${tt.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 ${tt.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 ${tt.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 ${tt.topK}.`}]},{id:"context.job_logs",label:"Job transcripts",help:"Whether the raw agent transcript of each job is kept in the Context Repo.",fields:[{id:"context.job_logs.enabled",file:"regimen.yaml",path:["context","job_logs","enabled"],type:"boolean",label:"Keep transcripts in the Context Repo",nullable:!1,help:"Off (default): the transcript is discarded after the run \u2014 nothing lands in the Context Repo. On: each job's raw transcript is committed as tasks/<KEY>/logs/job-<id>.jsonl for post-mortem debugging."}]}]});function Yu(t){if(t==null)return[];if(!Array.isArray(t))return null;let e=[];for(let r of t){if(typeof r!="string"||r.trim().length===0)return null;e.push(r.trim())}return e}function Ia(t){let{name:e,body:r,origin:n}=t;if(!Ta.test(e))return{ok:!1,error:`role name must match ${Ta} (got "${e}")`};if(r.trim().length===0)return{ok:!1,error:"role body is empty \u2014 the body IS the role's prompt"};let o=t.frontmatter;if(o==null||typeof o!="object"||Array.isArray(o))return{ok:!1,error:"missing or malformed frontmatter block"};let 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=Yu(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=Yu(i.scenarios);if(c===null)return{ok:!1,error:"scenarios must be a list"};let l=[];for(let d of c){if(!Qo.includes(d))return{ok:!1,error:`unknown scenario "${d}" \u2014 one of: ${Qo.join(", ")}`};l.includes(d)||l.push(d)}if(l.length===0)return{ok:!1,error:`scenarios must name at least one of: ${Qo.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 Ra(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 Ca(t,e){return t.filter(r=>r.enabled&&r.scenarios.includes(e))}var Qo,Ta,qP,YP,Vu=S(()=>{"use strict";Qo=["plan_review","code_review","council"],Ta=/^[a-z][a-z0-9-]{1,39}$/,qP=10,YP=300});function Pa(t){return zu.includes(t)}function Aa(t){return`prompts/${t}.md`}var zu,Xu=S(()=>{"use strict";zu=["analysis","analyze","backfill","build","chat","code-review","code-review-external","code-review-fix","council","draft","estimate","implement","index","observer","resolve-conflict","rework","testing"]});function ja(t){if(!_a.test(t.name))return{ok:!1,error:`skill directory name must match ${_a}`};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 Na(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 Zu(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=Ju.find(s=>s.repo.toLowerCase()===n.toLowerCase());return o&&!Sb.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 Eb(t){let e=[],r=[],n=new Set;for(let o of t){if(!o.trim())continue;let i=Zu(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 Ib(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(!Tb.test(s)||!r.has(s.slice(s.indexOf("@")+1))){o.push(s);continue}n[s]=!0}}return{enabled:n,unknown:o}}var _a,XP,Ju,xb,Sb,Tb,Qu=S(()=>{"use strict";_a=/^[a-z][a-z0-9-]{1,39}$/,XP=300;Ju=[{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.-]*$/,Sb=/^[0-9a-f]{40}$/;Tb=/^[A-Za-z0-9][\w.-]*@[A-Za-z0-9][\w.-]*$/});function ed(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 Rb(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=ed(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,h=typeof g.taskKey=="string"?g.taskKey.trim():"";if(!r.has(h))return{ok:!1,error:`tasks names ${h||"(empty)"}, which is not in this batch`};let k=ed(g.after,e.length);if(k===null)return{ok:!1,error:`${h}: after must be a list of task keys`};for(let $ of k){if(!r.has($))return{ok:!1,error:`${h}: after names ${$}, not in this batch`};if($===h)return{ok:!1,error:`${h}: cannot come after itself`}}let y=typeof g.decisions=="string"?g.decisions.trim():"";a.push({taskKey:h,decisions:y.slice(0,4e3),after:k})}}let c=[],l=n.conflicts;if(Array.isArray(l))for(let f of l){if(!f||typeof f!="object")continue;let g=f,h=typeof g.taskKey=="string"?g.taskKey.trim():"",k=typeof g.adr=="string"?g.adr.trim():"",y=typeof g.detail=="string"?g.detail.trim():"";!r.has(h)||!y||c.push({taskKey:h,adr:k,detail:y.slice(0,4e3)})}let u=[],p=n.related;if(Array.isArray(p))for(let f of p){if(!f||typeof f!="object")continue;let g=f,h=typeof g.taskKey=="string"?g.taskKey.trim():"",k=typeof g.detail=="string"?g.detail.trim():"";!h||!k||u.push({taskKey:h,detail:k.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 ZP,QP,td=S(()=>{"use strict";ZP=4e3,QP=4e3});function Cb(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 tA,rd=S(()=>{"use strict";tA=4e3});function _b(t){let e=t.replace(/^#+\s*/,"").trim();for(let r of Pb)if(r.re.test(e))return{kind:r.kind,letter:r.letter};return null}function Oa(t){let e=[],r=new Map,n="",o=null,i=null;for(let a of t.split(`
8
8
  `)){let c=/^#{1,6}\s+(.*)$/.exec(a);if(c){n=c[1].trim(),o=_b(n),i=null;continue}let l=Ab.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
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 jb(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 Nb(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
11
  `)}function La(t){let e=new Set;for(let r of t.items)if(r.kind==="procedure")for(let n of r.text.matchAll(Ob))e.add(n[1]);return[...e]}var Pb,Ab,Ob,nd=S(()=>{"use strict";Pb=[{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"}],Ab=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*(.*)$/;Ob=/`([a-z][a-z0-9-]{1,39})`/g});function Db(t){let e=[],r=null;for(let o of t.split(`
12
12
  `)){let i=Mb.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 Ub(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 Lb,Mb,od=S(()=>{"use strict";Lb=["done","deviated","partial","dropped"],Mb=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*[—:-]?\s*(done|deviated|partial|dropped)\b\s*[—:-]?\s*(.*)$/i});var id=S(()=>{"use strict"});var sd=S(()=>{"use strict"});var ad=S(()=>{"use strict"});function Ma(t){return`codepipe-host-${t}`}function Bb(t){let e=t.filter(r=>r!=="self-hosted");return`runs-on: [self-hosted${e.length?", "+e.join(", "):""}]`}var cd=S(()=>{"use strict"});function Fb(t,e){return(t&&t.includes("<TASK_ID>")?t:ld).replace(/<TASK_ID>/g,e.toLowerCase())}function Gb(t,e){if(t)return`${t.replace(/\/+$/,"")}/issue/${encodeURIComponent(e)}`}function to(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 Da(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 Ua(t){if(!t.mirror)return t;let{mirror:e,...r}=t;return{...r,host:e.host,owner:e.owner,repoName:e.repoName}}function vt(t){return`${t}${ud}`}var ld,Ht,ud,dd=S(()=>{"use strict";ld="codepipe/<TASK_ID>";Ht=/^[a-z][a-z0-9-]{1,30}$/,ud="-codepipe-ctx"});function Kb(t,e){return`${t}:${e}`}var pd=S(()=>{"use strict"});function fd(t){let e=(t??"").trim();return/^pr_closed_without_merge\b/.test(e)?"blocked":/^(merge_failed|close_failed)\b/.test(e)||/^chain_base_changed\b/.test(e)?"conflict":/^(build_failed|ci_failed)\b/.test(e)?"loop_exhausted":"error"}function Hb(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.to==="NEEDS_MANUAL")return r}return null}function Wb(t,e){if(t==="AWAITING_ANSWER")return{kind:"question"};if(t==="NEEDS_MANUAL"){let n=Hb(e)?.reason,o={kind:fd(n)};return n&&(o.reason=n),o}}var md=S(()=>{"use strict"});function kr(t){for(let e of hd){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var hd,gd=S(()=>{"use strict";hd=[{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 yd=S(()=>{"use strict"});function wd(t){let e=Math.max(1,Math.round(t));if(e<60)return`${e}s`;let r=Math.round(e/60);if(r<60)return`${r}m`;let n=Math.round(r/60);return n<24?`${n}h`:`${Math.round(n/24)}d`}function qb(t,e=Date.now()){return`${wd((e-t)/1e3)} ago`}function Yb(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 kd=S(()=>{"use strict"});var bd=S(()=>{"use strict"});function $d(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function Fa(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=$d(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(br.test(r))return r;let n=$d(t);return br.test(n)?n:ei}function Ga(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 Ba,ro,ei,br,ti,Vb,no,Wr,vd=S(()=>{"use strict";Ba=["bug","feature","epic"],ro="feature",ei="TASK",br=/^[A-Z][A-Z0-9]{1,9}$/;ti={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},Vb=ti.backlog,no="tracker/config.yaml",Wr="tracker/counter"});var zb,xd=S(()=>{"use strict";zb="youtrack"});function $r(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 oo(t){switch(t){case Yr.gitlab:return"oauth2";case Yr.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Yr,jt,Sd=S(()=>{"use strict";Yr={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};jt="x-bitbucket-api-token-auth"});var Ed=S(()=>{"use strict"});var Td=S(()=>{"use strict";xd();Sd();Ed()});var Id={};We(Id,{ACTION_ID_RE:()=>ma,ACTION_STEP_DEFAULT_TIMEOUT_SEC:()=>ga,ALL_JOB_ROLES:()=>ca,ALL_MODEL_ROLE_KEYS:()=>da,ANALYSIS_MAX_DRAFTS:()=>Ka,ANNOTATION_MAX_PER_TASK:()=>ea,BACKFILL_MAX_DRAFTS:()=>Xb,BITBUCKET_API_TOKEN_GIT_USER:()=>jt,BUILD_DISCOVERY:()=>Ou,COCHANGE_DEFAULTS:()=>tt,CODEPIPE_COMMANDS:()=>hd,COMMIT_STYLE_MAX_LENGTH:()=>xa,CONTEXT_PACK_DECAY:()=>ra,CONTEXT_PACK_DEFAULTS:()=>gr,CONTEXT_REPO_SUFFIX:()=>ud,CONTEXT_STAMP_FILE:()=>ft,CONTEXT_TEMPLATE_CHANGELOG:()=>Gs,CONTEXT_TEMPLATE_VERSION:()=>wu,COUNCIL_MAX_ANSWER:()=>tA,DEFAULT_BRANCH_PATTERN:()=>ld,DEFAULT_HUB_URL:()=>dt,DEFAULT_INTERNAL_ISSUE_TYPE:()=>ro,DEFAULT_INTERNAL_TRACKER_PREFIX:()=>ei,DEFAULT_LLM_PROVIDER:()=>Ye,DEFAULT_REGIMEN_ALIASES:()=>Uu,DEFAULT_TRACKER_PROVIDER:()=>zb,ENV_NAME_RE:()=>Ve,FALLBACK_MODEL:()=>Mu,GIT_HOST_DOMAINS:()=>Yr,INTERNAL_ISSUE_TYPES:()=>Ba,INTERNAL_TRACKER_CONFIG_PATH:()=>no,INTERNAL_TRACKER_COUNTER_PATH:()=>Wr,INTERNAL_TRACKER_DEFAULT_STATUS:()=>Vb,INTERNAL_TRACKER_PREFIX_RE:()=>br,INTERNAL_TRACKER_STATUSES:()=>ti,LANE_PHASES:()=>ib,LANE_SEGMENTS:()=>aa,LANGUAGE_AUTO:()=>ve,LANGUAGE_SUGGESTIONS:()=>Hr,LANGUAGE_VALUE_MAX_LENGTH:()=>eo,LEGACY_CONTEXT_STAMP_FILE:()=>Br,LLM_PROVIDER_SUGGESTIONS:()=>ua,MIN_SUPPORTED_PROTOCOL:()=>hu,MODEL_ALIAS_SUGGESTIONS:()=>Jo,MODEL_DERIVED_DIR:()=>Zk,MODEL_DERIVED_INDEX_PATH:()=>qo,MODEL_DIR:()=>zk,MODEL_EDGE_KINDS:()=>Zs,MODEL_ENTITY_ID_RE:()=>vu,MODEL_FACTS_DIR:()=>Jk,MODEL_FAMILY_PREFERENCE:()=>Du,MODEL_HAIKU:()=>Xo,MODEL_LEVELS:()=>$u,MODEL_OPUS:()=>Ce,MODEL_README_PATH:()=>Xk,MODEL_RELATES_PATH:()=>fr,MODEL_SEARCH_MAX_LIMIT:()=>ta,MODEL_SEARCH_MAX_ROWS:()=>eb,MODEL_SEARCH_ROW_TEXT_MAX:()=>Vo,MODEL_SONNET:()=>Jn,MODEL_SUB_ROLES:()=>Lu,OBSERVER_MAX_DECISION:()=>ZP,OBSERVER_MAX_SUMMARY:()=>QP,OFFICIAL_MARKETPLACES:()=>Ju,PHASES:()=>sa,PIPELINE_COLUMNS:()=>Au,PLANNING_LANE_MAX_JOBS:()=>lb,PLANNING_ROLES:()=>ju,PLATFORM_VERSION:()=>qe,PROJECT_ID_RE:()=>Ht,PROJECT_LANGUAGE_SECTIONS:()=>Qn,PROJECT_MODEL_FORMAT_VERSION:()=>Oe,PROJECT_SETTINGS_MANIFEST:()=>Hu,PROMPT_ROLES:()=>zu,PROTOCOL_VERSION:()=>pt,RECOMMENDED_ROLE_MODELS:()=>Zn,RELATES_MIN_OVERLAP:()=>Qs,ROLE_MAX_DESCRIPTION:()=>YP,ROLE_MAX_REFS:()=>qP,ROLE_NAME_RE:()=>Ta,ROLE_SCENARIOS:()=>Qo,SKILL_MAX_DESCRIPTION:()=>XP,SKILL_NAME_RE:()=>_a,SOLUTION_STATUSES:()=>Lb,STRING_MAP_MAX_ENTRIES:()=>$a,STRING_MAP_MAX_VALUE_LENGTH:()=>va,additionsSince:()=>Hs,ago:()=>qb,attentionFor:()=>Wb,autoLanguageConfig:()=>Gu,autoModelDefault:()=>pa,canonicalizeModelEdgeSheet:()=>xu,canonicalizeModelIdentityTable:()=>Eu,canonicalizeModelShard:()=>Su,canonicalizeModelTaskEvent:()=>Tu,changesSince:()=>Ws,classifyAttentionReason:()=>fd,compilePlanRework:()=>Nb,contextRepoName:()=>vt,deserializeModelConfig:()=>mb,emptyModelConfig:()=>Kr,enabledPluginsSetting:()=>Ib,extractLanguageConfig:()=>kb,findSettingField:()=>Wu,firstFreeInternalTrackerPrefix:()=>Ga,flattenSettingFields:()=>Sa,fmtDuration:()=>wd,fmtUptime:()=>Yb,ghRunnerHostLabel:()=>Ma,ghRunnerRunsOnSnippet:()=>Bb,gitCloneUrlDomain:()=>$r,httpsTokenUser:()=>oo,internalIssueYamlPath:()=>qr,isAllAutoLanguage:()=>bb,isAutoLanguage:()=>Ku,isBodyEditFrozen:()=>ob,isModelEntityId:()=>Yo,isPromptRole:()=>Pa,isProtocolCompatible:()=>Wn,isReservedEnvName:()=>_t,isTerminalPhase:()=>nb,isValidBranchName:()=>to,jobLane:()=>cb,laneSegmentForPhase:()=>sb,makeTaskId:()=>Kb,mergeRoles:()=>Ra,mergeSkills:()=>Na,mismatchedIds:()=>jb,modelAnnotationPath:()=>Vs,modelComponentSlug:()=>bu,modelCorrelatesPath:()=>zs,modelEventPath:()=>mr,modelIdentityPath:()=>Vn,modelNodeKey:()=>ge,modelShardNeedsRebuild:()=>tb,modelStructureShardPath:()=>Js,modelTaskNodeKey:()=>$e,modelTouchedPath:()=>Xs,parseActionDefinition:()=>ya,parseCodepipeCommand:()=>kr,parseContextStamp:()=>Ks,parseMarketplaceSource:()=>Zu,parseMarketplaces:()=>Eb,parseModelConfig:()=>pb,parseModelNodeKey:()=>te,parsePlanItems:()=>Oa,parseRepoMirror:()=>Da,parseSolutionItems:()=>Db,pipelineColumnForPhase:()=>ab,pipelineRepoSpec:()=>Ua,prescribedSkills:()=>La,promptOverridePath:()=>Aa,renderContextStamp:()=>qn,resolveBranchName:()=>Fb,resolveModelForRole:()=>ub,resolveProvider:()=>db,rolesForScenario:()=>Ca,serializeModelConfig:()=>fb,serializeModelEdgeSheet:()=>hr,serializeModelIdentityTable:()=>oa,serializeModelShard:()=>na,serializeModelTaskEvent:()=>Gr,serializeModelYaml:()=>yr,solutionCoverage:()=>Ub,suggestInternalTrackerPrefix:()=>Fa,validateActionInput:()=>wa,validateCouncilVerdict:()=>Cb,validateModelEdgeSheet:()=>zn,validateModelIdentityTable:()=>Xn,validateModelShard:()=>Pt,validateModelTaskEvent:()=>At,validateObserverPlan:()=>Rb,validateRoleDefinition:()=>Ia,validateSettingEdit:()=>Ea,validateSkill:()=>ja,youtrackIssueUrl:()=>Gb,zeroUsage:()=>Kt});var Ka,Xb,F=S(()=>{"use strict";gu();yu();ku();ia();Pu();_u();la();fa();qu();ba();ka();Vu();Xu();Qu();td();rd();nd();od();id();sd();ad();cd();dd();pd();md();gd();yd();kd();bd();vd();Td();Ka=20,Xb=15});function z(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Be=S(()=>{"use strict"});import{existsSync as Jb,readFileSync as Zb,readdirSync as Qb}from"node:fs";import{dirname as e$,join as Ha}from"node:path";import{parse as t$}from"yaml";function r$(t=process.cwd()){let e=t;for(;;){if(Jb(Ha(e,ht,"project.yaml")))return e;let r=e$(e);if(r===e)return null;e=r}}function n$(t){return Ha(t,ht)}function Pe(t=process.cwd()){let e=r$(t);if(!e)return null;let r=n$(e),n=o$(Zb(Ha(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function Rd(t,e,r){return Qb(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 Vr(t,e=process.cwd()){try{let r=Pe(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function o$(t){let e=t$(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=Da(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 ri(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 ht,rt=S(()=>{"use strict";F();ht=".codepipe"});import{homedir as Cd}from"node:os";import{mkdirSync as i$,readFileSync as s$,writeFileSync as a$,existsSync as Wa}from"node:fs";import{dirname as Ad,join as ni,resolve as c$}from"node:path";import{fileURLToPath as l$}from"node:url";function _d(t){let e=ni(Pd,".env");if(Wa(e)&&process.loadEnvFile(e),t){let r=ni(Pd,"profiles",t,".env");Wa(r)&&process.loadEnvFile(r)}}function zr(t){let e=z("CONFIG");return e||(t?ni(Cd(),".codepipe","profiles",t,"config.json"):ni(Cd(),".codepipe","config.json"))}function gt(t){let e=zr(t);if(!Wa(e))return null;let r=s$(e,"utf-8");return JSON.parse(r)}function Nt(t,e){let r=zr(e);i$(Ad(r),{recursive:!0}),a$(r,JSON.stringify(t,null,2)+`
14
- `,{mode:384})}function Xr(t){if(t)return{cfg:nt(t),profile:t};let e;try{e=Pe()?.spec.projectId||void 0}catch{}if(e){let r=gt(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:nt(void 0),profile:void 0}}function nt(t){let e=gt(t);if(!e){let r=t?`codepipe init --profile ${t} --hub <url> --token <token> --project ${t}`:"codepipe init --hub <url> --token <token> --project <id>";console.error(t?`CLI profile '${t}' is not initialised. run \`${r}\` first.`:`CLI is not initialised. run \`${r}\` first.`),process.exit(1)}return e.projectId||(console.error(`config at ${zr(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var Pd,Fe=S(()=>{"use strict";Be();rt();Pd=c$(Ad(l$(import.meta.url)),"..")});import{homedir as jd}from"node:os";import{existsSync as Nd,mkdirSync as Od,readFileSync as Ld,writeFileSync as Md}from"node:fs";import{dirname as Dd,join as Ud}from"node:path";function Bd(t,e,r){let n=V(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},ae(n)}function Fd(t,e){let r=V(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],ae(r),!0)}function Gd(t){return Object.keys(V(t)?.secrets??{}).sort()}function oi(t,e,r){let n=V(t);if(!n)return"mismatch";let o=n.sandboxPins??{},i=o[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(o[e]=r,n.sandboxPins=o,ae(n),"pinned")}function Kd(t,e){let r=V(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],ae(r),!0):!1}function xt(t){return Ud(jd(),".codepipe","secrets",`${t}.json`)}function V(t){let e=xt(t);return Nd(e)?JSON.parse(Ld(e,"utf-8")):null}function ae(t){let e=xt(t.projectId);Od(Dd(e),{recursive:!0}),Md(e,JSON.stringify(t,null,2)+`
13
+ ${o.trim()}`.trim())}let n={};for(let o of e)n[o.id]=o;return{items:e,byId:n}}function Ub(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 Lb,Mb,od=S(()=>{"use strict";Lb=["done","deviated","partial","dropped"],Mb=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*[—:-]?\s*(done|deviated|partial|dropped)\b\s*[—:-]?\s*(.*)$/i});var id=S(()=>{"use strict"});var sd=S(()=>{"use strict"});var ad=S(()=>{"use strict"});function Ma(t){return`codepipe-host-${t}`}function Bb(t){let e=t.filter(r=>r!=="self-hosted");return`runs-on: [self-hosted${e.length?", "+e.join(", "):""}]`}var cd=S(()=>{"use strict"});function Fb(t,e){return(t&&t.includes("<TASK_ID>")?t:ld).replace(/<TASK_ID>/g,e.toLowerCase())}function Gb(t,e){if(t)return`${t.replace(/\/+$/,"")}/issue/${encodeURIComponent(e)}`}function to(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 Da(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 Ua(t){if(!t.mirror)return t;let{mirror:e,...r}=t;return{...r,host:e.host,owner:e.owner,repoName:e.repoName}}function $t(t){return`${t}${ud}`}var ld,Ht,ud,dd=S(()=>{"use strict";ld="codepipe/<TASK_ID>";Ht=/^[a-z][a-z0-9-]{1,30}$/,ud="-codepipe-ctx"});function Kb(t,e){return`${t}:${e}`}var pd=S(()=>{"use strict"});function fd(t){let e=(t??"").trim();return/^pr_closed_without_merge\b/.test(e)?"blocked":/^(merge_failed|close_failed)\b/.test(e)||/^chain_base_changed\b/.test(e)?"conflict":/^(build_failed|ci_failed)\b/.test(e)?"loop_exhausted":"error"}function Hb(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.to==="NEEDS_MANUAL")return r}return null}function Wb(t,e){if(t==="AWAITING_ANSWER")return{kind:"question"};if(t==="NEEDS_MANUAL"){let n=Hb(e)?.reason,o={kind:fd(n)};return n&&(o.reason=n),o}}var md=S(()=>{"use strict"});function kr(t){for(let e of hd){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var hd,gd=S(()=>{"use strict";hd=[{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 yd=S(()=>{"use strict"});function wd(t){let e=Math.max(1,Math.round(t));if(e<60)return`${e}s`;let r=Math.round(e/60);if(r<60)return`${r}m`;let n=Math.round(r/60);return n<24?`${n}h`:`${Math.round(n/24)}d`}function qb(t,e=Date.now()){return`${wd((e-t)/1e3)} ago`}function Yb(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 kd=S(()=>{"use strict"});var bd=S(()=>{"use strict"});function $d(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function Fa(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=$d(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(br.test(r))return r;let n=$d(t);return br.test(n)?n:ei}function Ga(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 Ba,ro,ei,br,ti,Vb,no,Wr,vd=S(()=>{"use strict";Ba=["bug","feature","epic"],ro="feature",ei="TASK",br=/^[A-Z][A-Z0-9]{1,9}$/;ti={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},Vb=ti.backlog,no="tracker/config.yaml",Wr="tracker/counter"});var zb,xd=S(()=>{"use strict";zb="youtrack"});function $r(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 oo(t){switch(t){case Yr.gitlab:return"oauth2";case Yr.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Yr,jt,Sd=S(()=>{"use strict";Yr={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};jt="x-bitbucket-api-token-auth"});var Ed=S(()=>{"use strict"});var Td=S(()=>{"use strict";xd();Sd();Ed()});var Id={};We(Id,{ACTION_ID_RE:()=>ma,ACTION_STEP_DEFAULT_TIMEOUT_SEC:()=>ga,ALL_JOB_ROLES:()=>ca,ALL_MODEL_ROLE_KEYS:()=>da,ANALYSIS_MAX_DRAFTS:()=>Ka,ANNOTATION_MAX_PER_TASK:()=>ea,BACKFILL_MAX_DRAFTS:()=>Xb,BITBUCKET_API_TOKEN_GIT_USER:()=>jt,BUILD_DISCOVERY:()=>Ou,COCHANGE_DEFAULTS:()=>tt,CODEPIPE_COMMANDS:()=>hd,COMMIT_STYLE_MAX_LENGTH:()=>xa,CONTEXT_PACK_DECAY:()=>ra,CONTEXT_PACK_DEFAULTS:()=>gr,CONTEXT_REPO_SUFFIX:()=>ud,CONTEXT_STAMP_FILE:()=>dt,CONTEXT_TEMPLATE_CHANGELOG:()=>Gs,CONTEXT_TEMPLATE_VERSION:()=>wu,COUNCIL_MAX_ANSWER:()=>tA,DEFAULT_BRANCH_PATTERN:()=>ld,DEFAULT_HUB_URL:()=>lt,DEFAULT_INTERNAL_ISSUE_TYPE:()=>ro,DEFAULT_INTERNAL_TRACKER_PREFIX:()=>ei,DEFAULT_LLM_PROVIDER:()=>Ye,DEFAULT_REGIMEN_ALIASES:()=>Uu,DEFAULT_TRACKER_PROVIDER:()=>zb,ENV_NAME_RE:()=>Ve,FALLBACK_MODEL:()=>Mu,GIT_HOST_DOMAINS:()=>Yr,INTERNAL_ISSUE_TYPES:()=>Ba,INTERNAL_TRACKER_CONFIG_PATH:()=>no,INTERNAL_TRACKER_COUNTER_PATH:()=>Wr,INTERNAL_TRACKER_DEFAULT_STATUS:()=>Vb,INTERNAL_TRACKER_PREFIX_RE:()=>br,INTERNAL_TRACKER_STATUSES:()=>ti,LANE_PHASES:()=>ib,LANE_SEGMENTS:()=>aa,LANGUAGE_AUTO:()=>ve,LANGUAGE_SUGGESTIONS:()=>Hr,LANGUAGE_VALUE_MAX_LENGTH:()=>eo,LEGACY_CONTEXT_STAMP_FILE:()=>Br,LLM_PROVIDER_SUGGESTIONS:()=>ua,MIN_SUPPORTED_PROTOCOL:()=>hu,MODEL_ALIAS_SUGGESTIONS:()=>Jo,MODEL_DERIVED_DIR:()=>Zk,MODEL_DERIVED_INDEX_PATH:()=>qo,MODEL_DIR:()=>zk,MODEL_EDGE_KINDS:()=>Zs,MODEL_ENTITY_ID_RE:()=>vu,MODEL_FACTS_DIR:()=>Jk,MODEL_FAMILY_PREFERENCE:()=>Du,MODEL_HAIKU:()=>Xo,MODEL_LEVELS:()=>$u,MODEL_OPUS:()=>Ce,MODEL_README_PATH:()=>Xk,MODEL_RELATES_PATH:()=>fr,MODEL_SEARCH_MAX_LIMIT:()=>ta,MODEL_SEARCH_MAX_ROWS:()=>eb,MODEL_SEARCH_ROW_TEXT_MAX:()=>Vo,MODEL_SONNET:()=>Jn,MODEL_SUB_ROLES:()=>Lu,OBSERVER_MAX_DECISION:()=>ZP,OBSERVER_MAX_SUMMARY:()=>QP,OFFICIAL_MARKETPLACES:()=>Ju,PHASES:()=>sa,PIPELINE_COLUMNS:()=>Au,PLANNING_LANE_MAX_JOBS:()=>lb,PLANNING_ROLES:()=>ju,PLATFORM_VERSION:()=>qe,PROJECT_ID_RE:()=>Ht,PROJECT_LANGUAGE_SECTIONS:()=>Qn,PROJECT_MODEL_FORMAT_VERSION:()=>Oe,PROJECT_SETTINGS_MANIFEST:()=>Hu,PROMPT_ROLES:()=>zu,PROTOCOL_VERSION:()=>ut,RECOMMENDED_ROLE_MODELS:()=>Zn,RELATES_MIN_OVERLAP:()=>Qs,ROLE_MAX_DESCRIPTION:()=>YP,ROLE_MAX_REFS:()=>qP,ROLE_NAME_RE:()=>Ta,ROLE_SCENARIOS:()=>Qo,SKILL_MAX_DESCRIPTION:()=>XP,SKILL_NAME_RE:()=>_a,SOLUTION_STATUSES:()=>Lb,STRING_MAP_MAX_ENTRIES:()=>$a,STRING_MAP_MAX_VALUE_LENGTH:()=>va,additionsSince:()=>Hs,ago:()=>qb,attentionFor:()=>Wb,autoLanguageConfig:()=>Gu,autoModelDefault:()=>pa,canonicalizeModelEdgeSheet:()=>xu,canonicalizeModelIdentityTable:()=>Eu,canonicalizeModelShard:()=>Su,canonicalizeModelTaskEvent:()=>Tu,changesSince:()=>Ws,classifyAttentionReason:()=>fd,compilePlanRework:()=>Nb,contextRepoName:()=>$t,deserializeModelConfig:()=>mb,emptyModelConfig:()=>Kr,enabledPluginsSetting:()=>Ib,extractLanguageConfig:()=>kb,findSettingField:()=>Wu,firstFreeInternalTrackerPrefix:()=>Ga,flattenSettingFields:()=>Sa,fmtDuration:()=>wd,fmtUptime:()=>Yb,ghRunnerHostLabel:()=>Ma,ghRunnerRunsOnSnippet:()=>Bb,gitCloneUrlDomain:()=>$r,httpsTokenUser:()=>oo,internalIssueYamlPath:()=>qr,isAllAutoLanguage:()=>bb,isAutoLanguage:()=>Ku,isBodyEditFrozen:()=>ob,isModelEntityId:()=>Yo,isPromptRole:()=>Pa,isProtocolCompatible:()=>Wn,isReservedEnvName:()=>_t,isTerminalPhase:()=>nb,isValidBranchName:()=>to,jobLane:()=>cb,laneSegmentForPhase:()=>sb,makeTaskId:()=>Kb,mergeRoles:()=>Ra,mergeSkills:()=>Na,mismatchedIds:()=>jb,modelAnnotationPath:()=>Vs,modelComponentSlug:()=>bu,modelCorrelatesPath:()=>zs,modelEventPath:()=>mr,modelIdentityPath:()=>Vn,modelNodeKey:()=>ge,modelShardNeedsRebuild:()=>tb,modelStructureShardPath:()=>Js,modelTaskNodeKey:()=>$e,modelTouchedPath:()=>Xs,parseActionDefinition:()=>ya,parseCodepipeCommand:()=>kr,parseContextStamp:()=>Ks,parseMarketplaceSource:()=>Zu,parseMarketplaces:()=>Eb,parseModelConfig:()=>pb,parseModelNodeKey:()=>te,parsePlanItems:()=>Oa,parseRepoMirror:()=>Da,parseSolutionItems:()=>Db,pipelineColumnForPhase:()=>ab,pipelineRepoSpec:()=>Ua,prescribedSkills:()=>La,promptOverridePath:()=>Aa,renderContextStamp:()=>qn,resolveBranchName:()=>Fb,resolveModelForRole:()=>ub,resolveProvider:()=>db,rolesForScenario:()=>Ca,serializeModelConfig:()=>fb,serializeModelEdgeSheet:()=>hr,serializeModelIdentityTable:()=>oa,serializeModelShard:()=>na,serializeModelTaskEvent:()=>Gr,serializeModelYaml:()=>yr,solutionCoverage:()=>Ub,suggestInternalTrackerPrefix:()=>Fa,validateActionInput:()=>wa,validateCouncilVerdict:()=>Cb,validateModelEdgeSheet:()=>zn,validateModelIdentityTable:()=>Xn,validateModelShard:()=>Pt,validateModelTaskEvent:()=>At,validateObserverPlan:()=>Rb,validateRoleDefinition:()=>Ia,validateSettingEdit:()=>Ea,validateSkill:()=>ja,youtrackIssueUrl:()=>Gb,zeroUsage:()=>Kt});var Ka,Xb,F=S(()=>{"use strict";gu();yu();ku();ia();Pu();_u();la();fa();qu();ba();ka();Vu();Xu();Qu();td();rd();nd();od();id();sd();ad();cd();dd();pd();md();gd();yd();kd();bd();vd();Td();Ka=20,Xb=15});function X(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Be=S(()=>{"use strict"});import{existsSync as Jb,readFileSync as Zb,readdirSync as Qb}from"node:fs";import{dirname as e$,join as Ha}from"node:path";import{parse as t$}from"yaml";function r$(t=process.cwd()){let e=t;for(;;){if(Jb(Ha(e,ft,"project.yaml")))return e;let r=e$(e);if(r===e)return null;e=r}}function n$(t){return Ha(t,ft)}function Pe(t=process.cwd()){let e=r$(t);if(!e)return null;let r=n$(e),n=o$(Zb(Ha(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function Rd(t,e,r){return Qb(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 Vr(t,e=process.cwd()){try{let r=Pe(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function o$(t){let e=t$(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=Da(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 ri(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}var ft,rt=S(()=>{"use strict";F();ft=".codepipe"});import{homedir as Cd}from"node:os";import{mkdirSync as i$,readFileSync as s$,writeFileSync as a$,existsSync as Wa}from"node:fs";import{dirname as Ad,join as ni,resolve as c$}from"node:path";import{fileURLToPath as l$}from"node:url";function _d(t){let e=ni(Pd,".env");if(Wa(e)&&process.loadEnvFile(e),t){let r=ni(Pd,"profiles",t,".env");Wa(r)&&process.loadEnvFile(r)}}function zr(t){let e=X("CONFIG");return e||(t?ni(Cd(),".codepipe","profiles",t,"config.json"):ni(Cd(),".codepipe","config.json"))}function mt(t){let e=zr(t);if(!Wa(e))return null;let r=s$(e,"utf-8");return JSON.parse(r)}function Nt(t,e){let r=zr(e);i$(Ad(r),{recursive:!0}),a$(r,JSON.stringify(t,null,2)+`
14
+ `,{mode:384})}function Xr(t){if(t)return{cfg:nt(t),profile:t};let e;try{e=Pe()?.spec.projectId||void 0}catch{}if(e){let r=mt(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:nt(void 0),profile:void 0}}function nt(t){let e=mt(t);if(!e){let r=t?`codepipe init --profile ${t} --hub <url> --token <token> --project ${t}`:"codepipe init --hub <url> --token <token> --project <id>";console.error(t?`CLI profile '${t}' is not initialised. run \`${r}\` first.`:`CLI is not initialised. run \`${r}\` first.`),process.exit(1)}return e.projectId||(console.error(`config at ${zr(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var Pd,Fe=S(()=>{"use strict";Be();rt();Pd=c$(Ad(l$(import.meta.url)),"..")});import{homedir as jd}from"node:os";import{existsSync as Nd,mkdirSync as Od,readFileSync as Ld,writeFileSync as Md}from"node:fs";import{dirname as Dd,join as Ud}from"node:path";function Bd(t,e,r){let n=Y(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},ae(n)}function Fd(t,e){let r=Y(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],ae(r),!0)}function Gd(t){return Object.keys(Y(t)?.secrets??{}).sort()}function oi(t,e,r){let n=Y(t);if(!n)return"mismatch";let o=n.sandboxPins??{},i=o[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(o[e]=r,n.sandboxPins=o,ae(n),"pinned")}function Kd(t,e){let r=Y(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],ae(r),!0):!1}function vt(t){return Ud(jd(),".codepipe","secrets",`${t}.json`)}function Y(t){let e=vt(t);return Nd(e)?JSON.parse(Ld(e,"utf-8")):null}function ae(t){let e=vt(t.projectId);Od(Dd(e),{recursive:!0}),Md(e,JSON.stringify(t,null,2)+`
15
15
  `,{mode:384})}function ii(){return Ud(jd(),".codepipe","shared.json")}function qa(){let t=ii();return Nd(t)?JSON.parse(Ld(t,"utf-8")):null}function Hd(t){let e=ii();Od(Dd(e),{recursive:!0}),Md(e,JSON.stringify(t,null,2)+`
16
- `,{mode:384})}function Jr(t){let e=V(t)?.claude?.oauthToken;return e||qa()?.claude?.oauthToken}function io(t){let e={GH_TOKEN:t.github?.token,BITBUCKET_EMAIL:t.bitbucket?.email,BITBUCKET_API_TOKEN:t.bitbucket?.apiToken,GITLAB_TOKEN:t.gitlab?.token,YOUTRACK_URL:t.youtrack?.url,YOUTRACK_TOKEN:t.youtrack?.token};for(let r of Ya){let n=e[r];n&&!process.env[r]&&(process.env[r]=n)}}function Zr(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var Ya,pe=S(()=>{"use strict";Ya=["GH_TOKEN","BITBUCKET_EMAIL","BITBUCKET_API_TOKEN","GITLAB_TOKEN","YOUTRACK_URL","YOUTRACK_TOKEN"]});import{appendFileSync as u$,existsSync as qd,mkdirSync as d$,renameSync as Yd,statSync as p$,unlinkSync as f$}from"node:fs";import{Writable as m$}from"node:stream";import{join as h$}from"node:path";function si(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=g$(process.env[`${t}_MAX_BYTES`]??String(Vd.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):Vd.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function g$(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 ai(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:w$(o)).join(" ");return`${r} ${t} ${n}`}function w$(t){try{return JSON.stringify(t)}catch{return String(t)}}var Vd,Qr,Va=S(()=>{"use strict";Vd={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},Qr=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&d$(e.dir,{recursive:!0}),this.currentPath=h$(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
16
+ `,{mode:384})}function Jr(t){let e=Y(t)?.claude?.oauthToken;return e||qa()?.claude?.oauthToken}function io(t){let e={GH_TOKEN:t.github?.token,BITBUCKET_EMAIL:t.bitbucket?.email,BITBUCKET_API_TOKEN:t.bitbucket?.apiToken,GITLAB_TOKEN:t.gitlab?.token,YOUTRACK_URL:t.youtrack?.url,YOUTRACK_TOKEN:t.youtrack?.token};for(let r of Ya){let n=e[r];n&&!process.env[r]&&(process.env[r]=n)}}function Zr(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var Ya,pe=S(()=>{"use strict";Ya=["GH_TOKEN","BITBUCKET_EMAIL","BITBUCKET_API_TOKEN","GITLAB_TOKEN","YOUTRACK_URL","YOUTRACK_TOKEN"]});import{appendFileSync as u$,existsSync as qd,mkdirSync as d$,renameSync as Yd,statSync as p$,unlinkSync as f$}from"node:fs";import{Writable as m$}from"node:stream";import{join as h$}from"node:path";function si(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=g$(process.env[`${t}_MAX_BYTES`]??String(Vd.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):Vd.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function g$(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 ai(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:w$(o)).join(" ");return`${r} ${t} ${n}`}function w$(t){try{return JSON.stringify(t)}catch{return String(t)}}var Vd,Qr,Va=S(()=>{"use strict";Vd={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},Qr=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&d$(e.dir,{recursive:!0}),this.currentPath=h$(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
17
17
  `)?e:e+`
18
18
  `;u$(this.currentPath,r,"utf-8")}asWritable(){return new m$({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||!qd(this.currentPath)||p$(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;qd(n)&&(r>=this.cfg.maxFiles?f$(n):Yd(n,`${this.currentPath}.${r+1}`))}Yd(this.currentPath,`${this.currentPath}.1`)}}}});function li(t){return t===429||t>=500}function Jd(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
19
- `+t.slice(t.length-e)}async function Wt(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),ci);try{let i;try{i=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new ot(`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(li(i.status))throw new ot(`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 ui(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),ci);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 ot(`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(li(s.status))throw new ot(`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 qt(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(),ci);try{let s;try{s=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new ot(`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(li(s.status))throw new ot(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await E$(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 E$(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function di(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=Zd.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: ${Zd.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function Yt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),ci);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 ot(`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(li(n.status))throw new ot(`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 Qd(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 T$(t){switch(t){case"running":case"pending":case"created":case"waiting_for_resource":case"preparing":case"scheduled":return"running";case"success":return"success";case"failed":case"canceled":case"cancelled":return"failed";default:return"none"}}function Xa(t,e,r){let n=t.host==="github"?"set GH_TOKEN or GITHUB_TOKEN in the CLI env":t.host==="bitbucket"?"set BITBUCKET_EMAIL + BITBUCKET_API_TOKEN in the CLI env":t.host==="gitlab"?"set GITLAB_TOKEN in the CLI env":`no adapter implementation for host '${t.host}'`;return`cannot ${r} PR ${t.owner}/${t.repoName}#${e}: MockGitHost is active (write operations are not allowed) \u2014 ${n}`}function so(t,e){let r=Ua(e);if(!e.mirror)return{spec:r,host:en(r)};let n=t?V(t)?.mirrorWrite:void 0;return{spec:r,host:en(r,n?.token?{token:n.token,...n.email?{bitbucketEmail:n.email}:{}}:void 0)}}function en(t,e){if(t.host==="github"){let r=e?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(r)return new Za(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 Ja(r,n)}if(t.host==="gitlab"){let r=e?.token??process.env.GITLAB_TOKEN;if(r)return new Qa(r)}return new ec}var vr,ot,ci,Zd,Ja,Za,Qa,ec,Vt=S(()=>{"use strict";F();pe();vr=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},ot=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},ci=5e3;Zd=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];Ja=class{constructor(e,r){this.email=e;this.apiToken=r}name="bitbucket";authHeader(){return"Basic "+Buffer.from(`${this.email}:${this.apiToken}`).toString("base64")}async createPullRequest(e,r){let n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json"},body:JSON.stringify({title:r.title,description:r.body,source:{branch:{name:r.branchName}},destination:{branch:{name:r.baseBranch}}})});if(!n.ok)throw new Error(`bitbucket pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.links?.html?.href??"",number:o.id}}async findOpenPrByBranch(e,r){let n=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${n}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!o.ok)return null;let 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 vr(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){let i=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:o})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:n}})});if(!o.ok)throw new Error(`bitbucket comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},Za=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json"},body:JSON.stringify({title:r.title,body:r.body,head:r.branchName,base:r.baseBranch})});if(!n.ok)throw new Error(`github pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.html_url,number:o.number}}async findOpenPrByBranch(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls?state=open&head=${encodeURIComponent(`${e.owner}:${r}`)}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(!n.ok)return null;let 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 vr(`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 h=await g.text();u.push(`### CI job: ${f.name}
19
+ `+t.slice(t.length-e)}async function Wt(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),ci);try{let i;try{i=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new ot(`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(li(i.status))throw new ot(`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 ui(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),ci);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 ot(`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(li(s.status))throw new ot(`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 qt(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(),ci);try{let s;try{s=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new ot(`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(li(s.status))throw new ot(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await E$(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 E$(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function di(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=Zd.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: ${Zd.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function Yt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),ci);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 ot(`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(li(n.status))throw new ot(`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 Qd(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 T$(t){switch(t){case"running":case"pending":case"created":case"waiting_for_resource":case"preparing":case"scheduled":return"running";case"success":return"success";case"failed":case"canceled":case"cancelled":return"failed";default:return"none"}}function Xa(t,e,r){let n=t.host==="github"?"set GH_TOKEN or GITHUB_TOKEN in the CLI env":t.host==="bitbucket"?"set BITBUCKET_EMAIL + BITBUCKET_API_TOKEN in the CLI env":t.host==="gitlab"?"set GITLAB_TOKEN in the CLI env":`no adapter implementation for host '${t.host}'`;return`cannot ${r} PR ${t.owner}/${t.repoName}#${e}: MockGitHost is active (write operations are not allowed) \u2014 ${n}`}function so(t,e){let r=Ua(e);if(!e.mirror)return{spec:r,host:en(r)};let n=t?Y(t)?.mirrorWrite:void 0;return{spec:r,host:en(r,n?.token?{token:n.token,...n.email?{bitbucketEmail:n.email}:{}}:void 0)}}function en(t,e){if(t.host==="github"){let r=e?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(r)return new Za(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 Ja(r,n)}if(t.host==="gitlab"){let r=e?.token??process.env.GITLAB_TOKEN;if(r)return new Qa(r)}return new ec}var vr,ot,ci,Zd,Ja,Za,Qa,ec,Vt=S(()=>{"use strict";F();pe();vr=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},ot=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},ci=5e3;Zd=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];Ja=class{constructor(e,r){this.email=e;this.apiToken=r}name="bitbucket";authHeader(){return"Basic "+Buffer.from(`${this.email}:${this.apiToken}`).toString("base64")}async createPullRequest(e,r){let n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json"},body:JSON.stringify({title:r.title,description:r.body,source:{branch:{name:r.branchName}},destination:{branch:{name:r.baseBranch}}})});if(!n.ok)throw new Error(`bitbucket pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.links?.html?.href??"",number:o.id}}async findOpenPrByBranch(e,r){let n=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${n}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!o.ok)return null;let 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 vr(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){let i=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:o})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:n}})});if(!o.ok)throw new Error(`bitbucket comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},Za=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json"},body:JSON.stringify({title:r.title,body:r.body,head:r.branchName,base:r.baseBranch})});if(!n.ok)throw new Error(`github pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.html_url,number:o.number}}async findOpenPrByBranch(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls?state=open&head=${encodeURIComponent(`${e.owner}:${r}`)}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(!n.ok)return null;let 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 vr(`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 h=await g.text();u.push(`### CI job: ${f.name}
20
20
 
21
21
  ${Jd(h,8e3)}`)}}return u.length===0?void 0:Jd(u.join(`
22
22
 
23
- `),16e3)}catch{return}}async mergePR(e,r,n,o){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},Qa=class{constructor(e){this.token=e}name="gitlab";pid(e){return encodeURIComponent(`${e.owner}/${e.repoName}`)}headers(e=!1){let r={"PRIVATE-TOKEN":this.token,"User-Agent":"codepipe-cli"};return e&&(r["Content-Type"]="application/json"),r}async createPullRequest(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({source_branch:r.branchName,target_branch:r.baseBranch,title:r.title,description:r.body})});if(!n.ok)throw new Error(`gitlab mr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.web_url??"",number:o.iid}}async findOpenPrByBranch(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests?state=opened&source_branch=${encodeURIComponent(r)}`,{headers:this.headers()});if(!n.ok)return null;let 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 vr(`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=T$(i.head_pipeline?.status??i.pipeline?.status),a=i.merge_status==="cannot_be_merged"||i.has_conflicts===!0?"conflict":i.merge_status==="can_be_merged"&&i.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:s,mergeable:a}}async mergePR(e,r,n,o){let i=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,s,a=await fetch(i,{headers:this.headers()});if(a.ok){let u=await a.json().catch(()=>null);s=u?.sha??u?.diff_refs?.head_sha}let c=await fetch(`${i}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:n==="squash",should_remove_source_branch:o,...s?{sha:s}:{}})});if(!c.ok)throw new Error(`gitlab merge MR !${r}: ${c.status} ${await c.text()}`);let l=await c.json().catch(()=>null);return l?.merge_commit_sha?{mergedSha:l.merge_commit_sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`gitlab comment MR !${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!o.ok)throw new Error(`gitlab close MR !${r}: ${o.status} ${await o.text()}`)}};ec=class{name="mock";async createPullRequest(e,r){let n=Math.floor(Math.random()*9e3)+1e3;return{url:`https://example.com/${e.owner}/${e.repoName}/pull-requests/${n}`,number:n}}async getPullRequest(e,r){return{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){throw new Error(Xa(e,r,"merge"))}async closePR(e,r,n){throw new Error(Xa(e,r,"close"))}async addPRComment(e,r,n){throw new Error(Xa(e,r,"comment"))}}});import{X509Certificate as rp}from"node:crypto";import{readFileSync as I$}from"node:fs";import zt from"node:tls";function R$(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function ip(t=op){if(ep)return;ep=!0;let e=z("EXTRA_CA_FILE");if(!(!e||!np))try{let r=R$(I$(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 sp(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 C$(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
24
- `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function P$(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 rp(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function tc(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 A$(t){try{let e=await fetch(t);return e.ok?new rp(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function ap(t,e=443,r=op){let n=`${t}:${e}`,o=tp.get(n);if(o)return o;let i=_$(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return tp.set(n,i),i}async function _$(t,e,r){if(!np)return!1;let n=8e3;if(await tc(t,e,n))return!0;let o=await P$(t,e,n),i=zt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=C$(o);if(!c)break;let l=await A$(c);if(!l)break;if(s.push(l.toString()),zt.setDefaultCACertificates([...i,...s]),await tc(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 tc(t,e,n)}var np,ep,tp,op,cp=S(()=>{"use strict";Be();np=typeof zt.getCACertificates=="function"&&typeof zt.setDefaultCACertificates=="function",ep=!1,tp=new Map,op=t=>console.warn(t)});function pp(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function it(t,e,r){ip();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(sp(s)&&await ap(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function j$(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function N$(){let t=Number(process.env.YOUTRACK_WRITE_RETRIES);return{attempts:Number.isFinite(t)&&t>=1?Math.floor(t):6,baseMs:1e3,capMs:15e3}}async function rc(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=N$(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await it(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&&j$(l.status,u)){await lp(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await lp(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Xt(t){let e;try{e=await it(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 fp(t){try{let e=await it(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function O$(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=up.get(o);if(i)return i;let s=await it(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 up.set(o,l.id),l.id}async function mp(t,e,r,n=ao){let o=await O$(t,e,r,n);await rc(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:n,$type:"StateIssueCustomField",value:{id:o,$type:"StateBundleElement"}}]})})}async function hp(t,e,r){return await(await rc(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function gp(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await rc(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function yp(t,e){let r=dp.get(e);if(r)return r;let n=await it(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 dp.set(e,i.id),i.id}async function wp(t,e,r,n,o,i=ao){let s=await yp(t,e),a=await it(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 kp(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await it(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 vp(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 xp(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 Sp(t,e){let r=e.stageField??ao,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=${$p}&$top=200`,s=await it(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=>Ip(c,r))}async function Ep(t,e,r=ao){let n=`/api/issues/${encodeURIComponent(e)}?fields=${$p}`,o=await it(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Ip(await o.json(),r)}async function Tp(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${M$}&$top=500`,o=await it(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=vp(s.attachments);return c&&(a.attachments=c),a})}function D$(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 Ip(t,e=ao){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=vp(t.attachments);a&&(s.attachments=a);let c=D$(t.links);return c&&(s.links=c),s}async function Rp(t,e){let r=await U$(t,e);return r.length>0?r:B$(t,e)}async function U$(t,e){let r=await yp(t,e),n=await it(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:Cp(s.bundle)});return i}async function B$(t,e){let r=`project: ${e}`,n=await it(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:Cp(s.projectCustomField?.bundle)});return i}function Cp(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var lp,ao,up,dp,bp,L$,$p,M$,xr=S(()=>{"use strict";cp();lp=t=>new Promise(e=>setTimeout(e,t));ao="Stage",up=new Map;dp=new Map;bp="attachments(id,name,url,size,mimeType)",L$="links(direction,linkType(name),issues(idReadable))",$p=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${bp},${L$}`,M$=`id,text,created,author(login),${bp}`});function yt(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function tn(t){return t instanceof ot}async function Pp(t,e){let r=V(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 Xt({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:yt(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:yt(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 Wt(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){tn(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:yt(c)}),o.push({kind:"github",present:!0,ok:!1,detail:yt(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 qt(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){tn(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:yt(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:yt(c),checkedAt:i()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Yt(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){tn(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:yt(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:yt(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 ui(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){tn(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:yt(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await ui(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){tn(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:yt(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await ui(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){tn(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:i()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:yt(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=Jr(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 Ot(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 Ot(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:F$,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 Ap(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 F$,rn=S(()=>{"use strict";pe();Vt();xr();F$="claude-haiku-4-5-20251001"});import G$ from"node:http";import nc from"node:crypto";function pi(){let t=oc(nc.randomBytes(32)),e=oc(nc.createHash("sha256").update(t).digest()),r=oc(nc.randomBytes(32));return{verifier:t,challenge:e,state:r}}function sc(t){let e=new URL(K$);return e.search=new URLSearchParams({response_type:"code",client_id:_p,redirect_uri:t.redirectUri,scope:W$,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function Y$(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 jp(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 V$(t){let e=t,r=e?.access_token;if(!r||typeof r!="string")throw new Error(`no access_token in response: ${JSON.stringify(t)}`);return{oauthToken:r,...typeof e.refresh_token=="string"?{refreshToken:e.refresh_token}:{},...typeof e.expires_in=="number"?{expiresIn:e.expires_in}:{}}}async function ac(t){let e=await fetch(H$,{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:_p,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return V$(await e.json())}async function cc(t){let e=t.timeoutMs??q$,r=G$.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=sc({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(Y$(m.searchParams,t.state))}catch(f){u(f)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>ac({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function Np(t){let e=await cc(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
25
- ${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var _p,K$,H$,ic,W$,q$,oc,lc=S(()=>{"use strict";_p="9d1c250a-e61b-44d9-88ed-5944d1962f5e",K$="https://platform.claude.com/oauth/authorize",H$="https://platform.claude.com/v1/oauth/token",ic="https://platform.claude.com/oauth/code/callback",W$="org:create_api_key user:profile user:inference",q$=12e4,oc=t=>Buffer.from(t).toString("base64url")});import{spawn as z$}from"node:child_process";function Sr(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=z$(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var fi=S(()=>{"use strict"});import{existsSync as Jt,mkdirSync as Hp,readFileSync as pc,writeFileSync as nn}from"node:fs";import{homedir as ov}from"node:os";import{join as St}from"node:path";import{simpleGit as iv}from"simple-git";function lo(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=St(t,o);Jt(s)||(nn(s,i),r.push(o))}return r}function Zt(t,e,r){let n=St(ov(),".codepipe","profiles",t,"context-config");return Hp(n,{recursive:!0}),nn(St(n,"project.yaml"),e.projectYaml),nn(St(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function gi(t,e,r){if(Jt(e))for(let n of on){let o=St(e,n),i=St(t,n);if(!(!Jt(o)||Jt(i)))try{nn(i,pc(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 sn(t){let e=St(t,".gitignore"),r=Jt(e)?pc(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(on.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
23
+ `),16e3)}catch{return}}async mergePR(e,r,n,o){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},Qa=class{constructor(e){this.token=e}name="gitlab";pid(e){return encodeURIComponent(`${e.owner}/${e.repoName}`)}headers(e=!1){let r={"PRIVATE-TOKEN":this.token,"User-Agent":"codepipe-cli"};return e&&(r["Content-Type"]="application/json"),r}async createPullRequest(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({source_branch:r.branchName,target_branch:r.baseBranch,title:r.title,description:r.body})});if(!n.ok)throw new Error(`gitlab mr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.web_url??"",number:o.iid}}async findOpenPrByBranch(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests?state=opened&source_branch=${encodeURIComponent(r)}`,{headers:this.headers()});if(!n.ok)return null;let 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 vr(`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=T$(i.head_pipeline?.status??i.pipeline?.status),a=i.merge_status==="cannot_be_merged"||i.has_conflicts===!0?"conflict":i.merge_status==="can_be_merged"&&i.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:s,mergeable:a}}async mergePR(e,r,n,o){let i=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,s,a=await fetch(i,{headers:this.headers()});if(a.ok){let u=await a.json().catch(()=>null);s=u?.sha??u?.diff_refs?.head_sha}let c=await fetch(`${i}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:n==="squash",should_remove_source_branch:o,...s?{sha:s}:{}})});if(!c.ok)throw new Error(`gitlab merge MR !${r}: ${c.status} ${await c.text()}`);let l=await c.json().catch(()=>null);return l?.merge_commit_sha?{mergedSha:l.merge_commit_sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`gitlab comment MR !${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!o.ok)throw new Error(`gitlab close MR !${r}: ${o.status} ${await o.text()}`)}};ec=class{name="mock";async createPullRequest(e,r){let n=Math.floor(Math.random()*9e3)+1e3;return{url:`https://example.com/${e.owner}/${e.repoName}/pull-requests/${n}`,number:n}}async getPullRequest(e,r){return{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){throw new Error(Xa(e,r,"merge"))}async closePR(e,r,n){throw new Error(Xa(e,r,"close"))}async addPRComment(e,r,n){throw new Error(Xa(e,r,"comment"))}}});import{X509Certificate as rp}from"node:crypto";import{readFileSync as I$}from"node:fs";import zt from"node:tls";function R$(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function ip(t=op){if(ep)return;ep=!0;let e=X("EXTRA_CA_FILE");if(!(!e||!np))try{let r=R$(I$(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 sp(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 C$(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
24
+ `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function P$(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 rp(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function tc(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 A$(t){try{let e=await fetch(t);return e.ok?new rp(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function ap(t,e=443,r=op){let n=`${t}:${e}`,o=tp.get(n);if(o)return o;let i=_$(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return tp.set(n,i),i}async function _$(t,e,r){if(!np)return!1;let n=8e3;if(await tc(t,e,n))return!0;let o=await P$(t,e,n),i=zt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=C$(o);if(!c)break;let l=await A$(c);if(!l)break;if(s.push(l.toString()),zt.setDefaultCACertificates([...i,...s]),await tc(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 tc(t,e,n)}var np,ep,tp,op,cp=S(()=>{"use strict";Be();np=typeof zt.getCACertificates=="function"&&typeof zt.setDefaultCACertificates=="function",ep=!1,tp=new Map,op=t=>console.warn(t)});function pp(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function it(t,e,r){ip();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(sp(s)&&await ap(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function j$(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function N$(){let t=Number(process.env.YOUTRACK_WRITE_RETRIES);return{attempts:Number.isFinite(t)&&t>=1?Math.floor(t):6,baseMs:1e3,capMs:15e3}}async function rc(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=N$(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await it(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&&j$(l.status,u)){await lp(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await lp(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Xt(t){let e;try{e=await it(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 fp(t){try{let e=await it(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function O$(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=up.get(o);if(i)return i;let s=await it(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 up.set(o,l.id),l.id}async function mp(t,e,r,n=ao){let o=await O$(t,e,r,n);await rc(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:n,$type:"StateIssueCustomField",value:{id:o,$type:"StateBundleElement"}}]})})}async function hp(t,e,r){return await(await rc(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function gp(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await rc(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function yp(t,e){let r=dp.get(e);if(r)return r;let n=await it(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 dp.set(e,i.id),i.id}async function wp(t,e,r,n,o,i=ao){let s=await yp(t,e),a=await it(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 kp(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await it(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 vp(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 xp(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 Sp(t,e){let r=e.stageField??ao,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=${$p}&$top=200`,s=await it(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=>Ip(c,r))}async function Ep(t,e,r=ao){let n=`/api/issues/${encodeURIComponent(e)}?fields=${$p}`,o=await it(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Ip(await o.json(),r)}async function Tp(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${M$}&$top=500`,o=await it(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=vp(s.attachments);return c&&(a.attachments=c),a})}function D$(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 Ip(t,e=ao){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=vp(t.attachments);a&&(s.attachments=a);let c=D$(t.links);return c&&(s.links=c),s}async function Rp(t,e){let r=await U$(t,e);return r.length>0?r:B$(t,e)}async function U$(t,e){let r=await yp(t,e),n=await it(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:Cp(s.bundle)});return i}async function B$(t,e){let r=`project: ${e}`,n=await it(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:Cp(s.projectCustomField?.bundle)});return i}function Cp(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var lp,ao,up,dp,bp,L$,$p,M$,xr=S(()=>{"use strict";cp();lp=t=>new Promise(e=>setTimeout(e,t));ao="Stage",up=new Map;dp=new Map;bp="attachments(id,name,url,size,mimeType)",L$="links(direction,linkType(name),issues(idReadable))",$p=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${bp},${L$}`,M$=`id,text,created,author(login),${bp}`});function ht(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function tn(t){return t instanceof ot}async function Pp(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 Xt({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:ht(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:ht(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 Wt(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){tn(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:ht(c)}),o.push({kind:"github",present:!0,ok:!1,detail:ht(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 qt(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){tn(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:ht(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:ht(c),checkedAt:i()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Yt(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){tn(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:ht(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:ht(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 ui(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){tn(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:ht(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await ui(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){tn(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:ht(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await ui(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){tn(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:i()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:ht(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=Jr(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 Ot(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 Ot(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:F$,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 Ap(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 F$,rn=S(()=>{"use strict";pe();Vt();xr();F$="claude-haiku-4-5-20251001"});import G$ from"node:http";import nc from"node:crypto";function pi(){let t=oc(nc.randomBytes(32)),e=oc(nc.createHash("sha256").update(t).digest()),r=oc(nc.randomBytes(32));return{verifier:t,challenge:e,state:r}}function sc(t){let e=new URL(K$);return e.search=new URLSearchParams({response_type:"code",client_id:_p,redirect_uri:t.redirectUri,scope:W$,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function Y$(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 jp(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 V$(t){let e=t,r=e?.access_token;if(!r||typeof r!="string")throw new Error(`no access_token in response: ${JSON.stringify(t)}`);return{oauthToken:r,...typeof e.refresh_token=="string"?{refreshToken:e.refresh_token}:{},...typeof e.expires_in=="number"?{expiresIn:e.expires_in}:{}}}async function ac(t){let e=await fetch(H$,{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:_p,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return V$(await e.json())}async function cc(t){let e=t.timeoutMs??q$,r=G$.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=sc({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(Y$(m.searchParams,t.state))}catch(f){u(f)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>ac({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function Np(t){let e=await cc(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
25
+ ${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var _p,K$,H$,ic,W$,q$,oc,lc=S(()=>{"use strict";_p="9d1c250a-e61b-44d9-88ed-5944d1962f5e",K$="https://platform.claude.com/oauth/authorize",H$="https://platform.claude.com/v1/oauth/token",ic="https://platform.claude.com/oauth/code/callback",W$="org:create_api_key user:profile user:inference",q$=12e4,oc=t=>Buffer.from(t).toString("base64url")});import{spawn as z$}from"node:child_process";function Sr(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=z$(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var fi=S(()=>{"use strict"});import{existsSync as Jt,mkdirSync as Hp,readFileSync as pc,writeFileSync as nn}from"node:fs";import{homedir as ov}from"node:os";import{join as xt}from"node:path";import{simpleGit as iv}from"simple-git";function lo(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=xt(t,o);Jt(s)||(nn(s,i),r.push(o))}return r}function Zt(t,e,r){let n=xt(ov(),".codepipe","profiles",t,"context-config");return Hp(n,{recursive:!0}),nn(xt(n,"project.yaml"),e.projectYaml),nn(xt(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function gi(t,e,r){if(Jt(e))for(let n of on){let o=xt(e,n),i=xt(t,n);if(!(!Jt(o)||Jt(i)))try{nn(i,pc(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 sn(t){let e=xt(t,".gitignore"),r=Jt(e)?pc(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(on.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
26
26
  `)?"":`
27
27
  `;return nn(e,r+i+sv.join(`
28
28
  `)+`
29
- `),!0}async function Wp(t,e){try{if(!Jt(St(t,".git")))return;let r=iv(t),n=(await r.raw(["ls-files","--",...on])).split(`
30
- `).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;sn(t),await r.raw(["rm","--cached","--quiet","--",...n]),await r.add([".gitignore"]),await r.commit("chore(context): move project config out of the Context Repo"),await hc(t),e.info(`[config] migrated ${n.join(", ")} out of the Context Repo \u2014 the local copies are now the config`)}catch(r){e.warn(`[config] context-config migration failed (will retry on next start): ${r instanceof Error?r.message:String(r)}`)}}function fc(t){let e=new Map;for(let r of on){let n=St(t,r);Jt(n)&&e.set(r,pc(n))}return e}function mc(t,e){Hp(t,{recursive:!0});for(let[r,n]of e){let o=St(t,r);Jt(o)||nn(o,n)}}var on,sv,Lt=S(()=>{"use strict";st();on=["project.yaml","regimen.yaml"];sv=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as av,mkdirSync as cv,rmSync as lv,writeFileSync as gc}from"node:fs";import{dirname as uv,isAbsolute as dv,join as Vp,normalize as ki}from"node:path";import{simpleGit as zp}from"simple-git";async function yc(t,e){let r=ki(t),o=(wi.get(r)??Promise.resolve()).catch(()=>{}).then(e);wi.set(r,o);try{return await o}finally{wi.get(r)===o&&wi.delete(r)}}async function Te(t,e,r){return yc(t,()=>wc(t,e,r))}async function wc(t,e,r){if(!av(Vp(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=xe(t,a.path);if(a.deleted){lv(c,{force:!0});continue}cv(uv(c),{recursive:!0}),a.encoding==="base64"?gc(c,Buffer.from(a.content,"base64")):gc(c,a.content)}let n=zp(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+=yi)await n.raw(["add","-A","-f","--",...o.slice(a,a+yi)]);for(let a=0;a<i.length;a+=yi)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...i.slice(a,a+yi)]);await n.raw(["reset","-q","--",...on]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await hc(t))}async function hc(t){let e=zp(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=qp;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 hv(e);if(i.length>0&&i.every(a=>pv.has(a)||Yp.test(a)||fv.test(a))){for(let a of i)Yp.test(a)?await mv(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 ${qp} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function mv(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(`
29
+ `),!0}async function Wp(t,e){try{if(!Jt(xt(t,".git")))return;let r=iv(t),n=(await r.raw(["ls-files","--",...on])).split(`
30
+ `).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;sn(t),await r.raw(["rm","--cached","--quiet","--",...n]),await r.add([".gitignore"]),await r.commit("chore(context): move project config out of the Context Repo"),await hc(t),e.info(`[config] migrated ${n.join(", ")} out of the Context Repo \u2014 the local copies are now the config`)}catch(r){e.warn(`[config] context-config migration failed (will retry on next start): ${r instanceof Error?r.message:String(r)}`)}}function fc(t){let e=new Map;for(let r of on){let n=xt(t,r);Jt(n)&&e.set(r,pc(n))}return e}function mc(t,e){Hp(t,{recursive:!0});for(let[r,n]of e){let o=xt(t,r);Jt(o)||nn(o,n)}}var on,sv,Lt=S(()=>{"use strict";st();on=["project.yaml","regimen.yaml"];sv=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as av,mkdirSync as cv,rmSync as lv,writeFileSync as gc}from"node:fs";import{dirname as uv,isAbsolute as dv,join as Vp,normalize as ki}from"node:path";import{simpleGit as zp}from"simple-git";async function yc(t,e){let r=ki(t),o=(wi.get(r)??Promise.resolve()).catch(()=>{}).then(e);wi.set(r,o);try{return await o}finally{wi.get(r)===o&&wi.delete(r)}}async function Te(t,e,r){return yc(t,()=>wc(t,e,r))}async function wc(t,e,r){if(!av(Vp(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=xe(t,a.path);if(a.deleted){lv(c,{force:!0});continue}cv(uv(c),{recursive:!0}),a.encoding==="base64"?gc(c,Buffer.from(a.content,"base64")):gc(c,a.content)}let n=zp(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+=yi)await n.raw(["add","-A","-f","--",...o.slice(a,a+yi)]);for(let a=0;a<i.length;a+=yi)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...i.slice(a,a+yi)]);await n.raw(["reset","-q","--",...on]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await hc(t))}async function hc(t){let e=zp(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=qp;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 hv(e);if(i.length>0&&i.every(a=>pv.has(a)||Yp.test(a)||fv.test(a))){for(let a of i)Yp.test(a)?await mv(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 ${qp} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function mv(t,e,r){let n=async s=>await t.raw(["show",`:${s}:${r}`]).catch(()=>""),o=new Map;for(let s of[await n(2),await n(3)])for(let a of s.split(`
31
31
  `)){let c=a.trim();if(c)try{let l=JSON.parse(c);if(typeof l.id!="string")continue;o.has(l.id)||o.set(l.id,{raw:c,createdAt:typeof l.createdAt=="string"?l.createdAt:""})}catch{}}let i=[...o.values()].sort((s,a)=>s.createdAt.localeCompare(a.createdAt)).map(s=>s.raw);gc(xe(e,r),i.join(`
32
32
  `)+(i.length>0?`
33
33
  `:""))}async function hv(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
@@ -47,7 +47,7 @@ prefix: ${t}
47
47
  `).trim();if(!(!a||a==="_(no description)_"))return a}function fo(t,e,r={}){let n=r.withDescription?Cv(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:Pv(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function Pv(t){return t.charAt(0).toUpperCase()+t.slice(1)}function Av(t){let e=xe(t,Wr);if(!Qt(e))return 0;let r=Number.parseInt(an(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function _v(t,e){let r=bc(t,"tasks");if(!Qt(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of rf(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 jv(t,e){return Math.max(Av(t),_v(t,e))+1}async function lf(t,e,r,n){return yc(t,()=>Nv(t,e,r,n))}async function Nv(t,e,r,n){if(!Qt(bc(t,".git")))throw new Error(`context repo clone not found at ${t}`);await uo(t);let o=null;for(let i=0;i<tf;i++){let s=jv(t,e),a=`${e}-${s}`,c=[...r(a),{path:Wr,content:$c(s)}];try{return await wc(t,c,n(a)),a}catch(l){if(o=l,await Lv(t,n(a)),await uo(t),Ov(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${tf} attempts: ${o instanceof Error?o.message:String(o)}`)}function Ov(t,e){for(let r of e){let n=xe(t,r.path);if(!Qt(n)||(r.encoding==="base64"?an(n).toString("base64"):an(n,"utf-8"))!==r.content)return!1}return!0}async function uo(t){let e=nf(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 Lv(t,e){let r=nf(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
48
48
  `)[0]||!(await r.raw(["log","@{u}..HEAD","--pretty=%s"]).catch(()=>"")).trim().split(`
49
49
  `).some(i=>i.trim()===e.split(`
50
- `)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var tf,$i=S(()=>{"use strict";F();st();tf=5});function cn(t,e,r,n){return[{path:"README.md",content:Xv(t,e)},{path:".gitignore",content:Gv()},{path:"CLAUDE.md",content:Hv(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:Kv()},{path:"knowledge/README.md",content:Wv()},{path:"knowledge/build.yaml",content:zv()},{path:"actions/README.md",content:qv()},{path:"roles/README.md",content:Yv()},{path:"skills/README.md",content:Vv()},{path:"model/README.md",content:Mv()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:Fv()},{path:"adr/README.md",content:Dv()},{path:"adr/0000-template.md",content:Uv()},{path:"adr/INDEX.md",content:Bv()},{path:ft,content:qn()},...t.trackerProvider==="internal"?[{path:no,content:af(t.youtrackProjectKey??ei)},{path:Wr,content:$c()}]:[]]}function Mv(){return`# model/ \u2014 the project map
50
+ `)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var tf,$i=S(()=>{"use strict";F();st();tf=5});function cn(t,e,r,n){return[{path:"README.md",content:Xv(t,e)},{path:".gitignore",content:Gv()},{path:"CLAUDE.md",content:Hv(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:Kv()},{path:"knowledge/README.md",content:Wv()},{path:"knowledge/build.yaml",content:zv()},{path:"actions/README.md",content:qv()},{path:"roles/README.md",content:Yv()},{path:"skills/README.md",content:Vv()},{path:"model/README.md",content:Mv()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:Fv()},{path:"adr/README.md",content:Dv()},{path:"adr/0000-template.md",content:Uv()},{path:"adr/INDEX.md",content:Bv()},{path:dt,content:qn()},...t.trackerProvider==="internal"?[{path:no,content:af(t.youtrackProjectKey??ei)},{path:Wr,content:$c()}]:[]]}function Mv(){return`# model/ \u2014 the project map
51
51
 
52
52
  A graph of the project built from **git history and task artifacts**: files
53
53
  and directories connected by the fact of changing together and the fact of
@@ -138,7 +138,7 @@ project appends only to its own file \u2014
138
138
 
139
139
  \u2014 so several team members' CLIs never contend on one file. Do not create a
140
140
  shared aggregate here.
141
- `}function Et(t,e,r,n,o=Ye,i){let s=t.trackerProvider==="internal";return{projectYaml:s?Jv(t):Zv(t,r,n),regimenYaml:Qv(t.automationLevel,s?!0:e,s,o,i)}}function Gv(){return`# codepipe project config is local to each member's workspace
141
+ `}function St(t,e,r,n,o=Ye,i){let s=t.trackerProvider==="internal";return{projectYaml:s?Jv(t):Zv(t,r,n),regimenYaml:Qv(t.automationLevel,s?!0:e,s,o,i)}}function Gv(){return`# codepipe project config is local to each member's workspace
142
142
  project.yaml
143
143
  regimen.yaml
144
144
 
@@ -693,31 +693,31 @@ ${a}
693
693
 
694
694
  `}var Er=S(()=>{"use strict";F();$i()});function wf(t){yf=t}function Tr(t,e="info"){yf(t,e)}var yf,xi=S(()=>{"use strict";yf=t=>console.log(t)});import{homedir as hx,tmpdir as n0}from"node:os";import{existsSync as gx,mkdirSync as yx,mkdtempSync as i0,rmSync as s0}from"node:fs";import{join as Sc}from"node:path";import{simpleGit as Ec}from"simple-git";function _e(t,e,r){let n=r??Sc(hx(),".codepipe","repos");return Sc(n,t,e)}async function er(t,e,r={}){let n=_e(t,e.name,r.baseDir),o=r.cloneUrlOverride??Ic(e);if(!gx(Sc(n,".git"))){yx(n,{recursive:!0});let a=Ec();Tr(`[git] clone ${o} \u2192 ${n}`);try{await a.clone(o,n)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${o}
695
695
  ${l.trim()}`)}}let i=Ec(n);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
696
- ${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function ln(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function wx(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&&Tr(`[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 ln(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await ln(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([...Tc,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function kx(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await ln(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await ln(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 bf(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 kx(t,i,()=>wx(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));p&&await t.raw(["branch","-D",a]).catch(()=>{});let m=`origin/${c}`;await ln(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([...Tc,"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
697
- ${$.trim()}`)}}let h=(await t.revparse(["HEAD"])).trim(),k=r.push!==!1;if(k){let w=p?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push(w)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:h,pushed:k,...g>0?{baseMoved:g}:{}}}async function $f(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 vf(t,e,r){let{branchName:n,dropTaskKeys:o}=r,i=`origin/${n}`;if(!await ln(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(`
696
+ ${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function ln(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function wx(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&&Tr(`[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 ln(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await ln(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([...Tc,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function kx(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await ln(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await ln(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 bf(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 kx(t,i,()=>wx(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));p&&await t.raw(["branch","-D",a]).catch(()=>{});let m=`origin/${c}`;await ln(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([...Tc,"cherry-pick",d])}catch(y){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let $=y instanceof Error?y.message:String(y);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
697
+ ${$.trim()}`)}}let h=(await t.revparse(["HEAD"])).trim(),k=r.push!==!1;if(k){let y=p?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push(y)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:h,pushed:k,...g>0?{baseMoved:g}:{}}}async function $f(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 vf(t,e,r){let{branchName:n,dropTaskKeys:o}=r,i=`origin/${n}`;if(!await ln(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(`
698
698
  `).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(`
699
699
  `).map(h=>h.trim().toUpperCase()).filter(h=>h.length>0).some(h=>l.has(h))?p++:u.push(m);if(p===0)return{commit:(await t.revparse([i])).trim(),dropped:0};await t.checkout(["-B",n,a]);for(let m of u)try{await t.raw([...Tc,"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
700
700
  ${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 xf(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 Ic(t){return t.mirror?kf(t.mirror.host,t.mirror.owner,t.mirror.repoName):kf(t.host,t.owner,t.repoName)}function kf(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 Si(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}async function Sf(t){return(await Ec().listRemote(["--heads",t])).split(`
701
701
  `).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 Ef(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}var Tc,ho=S(()=>{"use strict";xi();Tc=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{createCipheriv as bx,createDecipheriv as $x,createHash as vx,createPrivateKey as xx,createPublicKey as Rc,diffieHellman as Tf,generateKeyPairSync as If,hkdfSync as Rf,randomBytes as Sx}from"node:crypto";function Ei(){let{publicKey:t,privateKey:e}=If("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function Ge(t){let e=Buffer.from(t,"base64");return(vx("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function Mt(t,e){let r=Rc({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=If("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=Tf({privateKey:o,publicKey:r}),c=Buffer.from(Rf("sha256",a,Buffer.concat([i,s]),Cf,32)),l=Sx(12),u=bx("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 un(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=xx({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=Rc({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=Rc(n).export({type:"spki",format:"der"}),a=Tf({privateKey:n,publicKey:o}),c=Buffer.from(Rf("sha256",a,Buffer.concat([i,s]),Cf,32)),l=$x("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 Cf,at=S(()=>{"use strict";Cf=Buffer.from("devpipe-sealedbox-v1","utf-8")});function go(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 yo(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 wo(t,e=process.env){if(!t)return!1;let r=`https://${jt}:${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 Cc(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 Af(t,e=process.env){return Cc(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>go(t,e),e)}function _f(t,e=process.env){return Cc(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>yo(t,e),e)}function jf(t,e=process.env){return Cc(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${jt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>wo(t,e),e)}var Ti=S(()=>{"use strict";F()});import{existsSync as Kf,readFileSync as Hf,writeFileSync as Wf}from"node:fs";import{join as qf}from"node:path";import{isMap as Ii,parseDocument as Yf}from"yaml";async function Vf(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||!to(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=qf(t,"project.yaml");if(!Kf(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=Yf(Hf(o,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>Ii(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!Ii(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),Wf(o,i.toString()),{repoName:r,defaultBranch:n}}function zf(t,e,r){let n=qf(t,"project.yaml");if(!Kf(n))throw new Error(`project.yaml not found in context repo (${t})`);let o=Yf(Hf(n,"utf-8")),i=o.get("repos"),a=(i&&typeof i=="object"&&"items"in i?i.items:[]).find(c=>Ii(c)&&String(c.get("name")??c.get("repo")??"")===e);if(!Ii(a))throw new Error(`repo "${e}" not found in project.yaml repos[]`);a.set("mirror",{host:r.host,owner:r.owner,repo:r.repoName}),Wf(n,o.toString())}var Pc=S(()=>{"use strict";F()});import{existsSync as Oc,readFileSync as Lc}from"node:fs";import{join as Mc}from"node:path";import{simpleGit as tm}from"simple-git";import{parse as Dc}from"yaml";function nm(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(Hx.source,"g")}function om(t){let e=Mc(t,"project.yaml");if(Oc(e))try{let o=Dc(Lc(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=Mc(t,"tracker","config.yaml");if(Oc(r))try{let o=Dc(Lc(r,"utf-8"))?.prefix;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return null}function im(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 Wx(t,e,r){let o=await tm(t).raw(["log","--numstat","--format=@@@ %H %ct %P %x09%s","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
702
702
  `))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=Uc.exec(u)??rm.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:im(c[3]),churn:l+u})}return i}async function qx(t,e){let n=await tm(t).raw(["diff","--numstat",`${e}^1`,e]).catch(()=>""),o=[];for(let i of n.split(`
703
- `)){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:im(s[3]),churn:a+c})}return o}function Yx(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(Uc,"").trim();else if(c.prNumber!==null){if((t.trackerProjectKey??"").toUpperCase()==="PR")continue;u=`PR-${c.prNumber}`,p=c.subject.replace(Uc,"").replace(rm,"").replace(/^from\s+/,"").trim()||c.subject}else continue;if(!/^[A-Za-z0-9._-]+$/.test(u))continue;let m=new Map;for(let h of c.files){let k=o.get(h.path)??h.path;s(k)||m.set(k,(m.get(k)??0)+h.churn)}if(m.size===0)continue;let g=a.get(u)??{modelFormatVersion:2,taskKey:u,origin:"bootstrap",title:"",commits:[],files:[]};p&&(g.title=p),c.timeSec>0&&(g.date=new Date(c.timeSec*1e3).toISOString().slice(0,10)),g.commits.push(c.sha);for(let[h,k]of m){let w=ge("code",e,h),$=g.files.find(x=>x.key===w);if($)$.churn=($.churn??0)+k;else{let x=i.get(w);g.files.push({key:w,...x?{entityId:x}:{},churn:k})}}if(d.length>0){let h=new Set([...g.links?.tasks??[],...d]);h.delete(u),g.links={...g.links??{},tasks:[...h].sort()}}a.set(u,g)}return a}function em(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 sm(t){let e=await Wx(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 qx(t.repoDir,r.sha))}return Yx({repo:t.repo,issueKeyRe:t.issueKeyRe,commits:e,pathToCurrent:t.pathToCurrent,entityByKey:t.entityByKey,ignored:t.ignored,trackerProjectKey:t.trackerProjectKey??null})}function am(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?em(c,a)??c:a)}let n=[],o=0;for(let[i,s]of[...r.entries()].sort(([a],[c])=>a<c?-1:1)){let a=em(Pi(t,i),s);if(!a){o++;continue}n.push({path:mr(i),content:Gr(a)})}return{files:n,skippedPipeline:o}}function Pi(t,e){let r=Mc(t,mr(e));if(!Oc(r))return null;try{let n=At(Dc(Lc(r,"utf-8")));return n.ok?n.value:null}catch{return null}}var Hx,Uc,rm,Bc=S(()=>{"use strict";F();Hx=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g,Uc=/\(#(\d+)\)\s*$/,rm=/^Merge pull request #(\d+)\b/});import{simpleGit as Vx}from"simple-git";async function lm(t,e,r){let o=await Vx(t).raw(["log","--no-merges","--name-only","--format=@@@ %H %ct","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
704
- `))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 Ai(t){let e=new Map;for(let r of t.entities){if(r.status!=="active"||!r.aliases)continue;let n=te(r.currentKey);if(n?.level==="code")for(let o of r.aliases){let i=te(o.key);i?.level==="code"&&e.set(i.path,n.path)}}return e}function um(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 k of n){let w=new Set;for(let v of k.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-k.timeSec),x=Math.pow(.5,$/c),T=[...w].sort();for(let v of T)l.set(v,(l.get(v)??0)+x);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)+x),p.set(R,(p.get(R)??0)+1)}}let d=[],m=a.jaccardMinPct/100;for(let[k,w]of u){if((p.get(k)??0)<a.supportMin)continue;let[$,x]=k.split("\0"),T=(l.get($)??0)+(l.get(x)??0)-w,v=T>0?w/T:0;v<m||d.push({a:$,b:x,weight:Math.round(v*cm)/cm})}let f=new Map;for(let k of d)for(let w of[k.a,k.b])f.has(w)||f.set(w,[]),f.get(w).push(k);let g=new Map;for(let[,k]of f)k.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(([,k])=>k===2).map(([k])=>k).map(k=>({kind:"correlates",from:ge("code",e,k.a),to:ge("code",e,k.b),weight:k.weight})).sort((k,w)=>k.from<w.from?-1:k.from>w.from?1:k.to<w.to?-1:1)}var pn,cm,_i=S(()=>{"use strict";F();pn=["package-lock.json","pnpm-lock.yaml","yarn.lock"];cm=1e4});import{createHash as zx}from"node:crypto";function Jx(t,e,r,n){for(let o=0;;o++){let s=`e_${zx("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(s))return s}}function dm(t){let{repo:e,headCommit:r,headDate:n,prev:o,renameChains:i,prevBlobByPath:s,headBlobByPath:a}=t,c=[...t.currentKeys].sort(),l=new Set(c),u=o?.entities??[],p=new Set(u.map(b=>b.entityId)),d=new Set,m=[],f=new Map,g=(b,R)=>{d.add(R),f.set(R,b.entityId),m.push(b)},h=[];for(let b of u)l.has(b.currentKey)&&!d.has(b.currentKey)?g({...b,status:"active",lastSeen:r},b.currentKey):h.push(b);let k=[],w=[];for(let b of h){let R=te(b.currentKey),A=R?i.get(R.path):void 0;if(R&&A){let G=ge(R.level,e,A.finalPath);if(l.has(G)&&!d.has(G)){k.push({entity:b,newKey:G,untilCommit:A.commit}),d.add(G);continue}}w.push(b)}let $=[];if(s){let b=new Map;for(let A of c){if(d.has(A))continue;let G=te(A);if(G?.level!=="code")continue;let J=a.get(G.path);J&&b.set(J,b.has(J)?null:A)}let R=new Map;for(let A of w){let G=te(A.currentKey);if(G?.level!=="code")continue;let J=s.get(G.path);J&&R.set(J,R.has(J)?null:A)}for(let A of w){let G=te(A.currentKey),J=G?.level==="code"?s.get(G.path):void 0,P=J?b.get(J):void 0;J&&P&&R.get(J)===A&&!d.has(P)?(k.push({entity:A,newKey:P,untilCommit:r}),d.add(P)):$.push(A)}}else $.push(...w);let x=new Map;for(let b of k){let R=te(b.entity.currentKey),A=te(b.newKey);if(R?.level!=="code"||!A)continue;let G=R.path,J=A.path;for(let P=G.lastIndexOf("/");P>0;P=G.lastIndexOf("/",P-1)){let y=G.slice(0,P),B=G.slice(P+1);if(!J.endsWith(`/${B}`))continue;let _=J.slice(0,J.length-B.length-1);if(_===y)continue;let W=`${y}\0${_}`,Y=x.get(W);x.set(W,{count:(Y?.count??0)+1,commit:Y&&Y.commit>b.untilCommit?Y.commit:b.untilCommit})}}let T=[...x.entries()].filter(([,b])=>b.count>=Xx).map(([b,R])=>{let[A,G]=b.split("\0");return{from:A,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=te(b.currentKey),A=!1;if(R?.level==="component")for(let G of T){let J=null;if(R.path===G.from?J=G.to:R.path.startsWith(`${G.from}/`)&&(J=G.to+R.path.slice(G.from.length)),J===null)continue;let P=ge("component",e,J);l.has(P)&&!d.has(P)&&(k.push({entity:b,newKey:P,untilCommit:G.commit}),d.add(P),A=!0);break}A||v.push(b)}for(let b of k.sort((R,A)=>R.newKey<A.newKey?-1:1))g({...b.entity,currentKey:b.newKey,aliases:[...b.entity.aliases??[],{key:b.entity.currentKey,until:b.untilCommit}],status:"active",lastSeen:r},b.newKey);for(let b of v)m.push({...b,status:"orphaned"});for(let b of c){if(d.has(b))continue;let R=Jx(e,b,r,p);p.add(R),g({entityId:R,currentKey:b,firstSeen:n,lastSeen:r,status:"active"},b)}return{table:{modelFormatVersion:2,repo:e,builtFromCommit:r,entities:m},byKey:f}}var Xx,pm=S(()=>{"use strict";F();Xx=5});import{simpleGit as Zx}from"simple-git";async function fm(t,e,r){let n=Zx(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
705
- `).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 mm(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 hm=S(()=>{"use strict"});function ji(t){return ge("container",t,Qx)}function gm(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function ym(t,e,r,n){let o=[],i=u=>{let p=ge("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:gm(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,eS)}},s=(u,p)=>{let d=ge("component",t,u),m=n.get(d);return{key:d,level:"component",label:gm(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)],h=[...m.map(k=>({kind:"contains",from:p.key,to:ge("code",t,k.path)})),...f.map(k=>({kind:"contains",from:p.key,to:ge("component",t,k)}))];c(u,g,h)},c=(u,p,d)=>{let m={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},f=Pt(m);if(!f.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${f.errors.join("; ")}`);o.push({path:Js(t,u),content:na(m)})},l={key:ji(t),level:"container",label:t,...n.get(ji(t))?{entityId:n.get(ji(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 wm(t,e){let r=[ji(t)];for(let n of e.components)r.push(ge("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(ge("code",t,o.path));return r.sort()}var Qx,eS,km=S(()=>{"use strict";F();Qx=".";eS=12});import{simpleGit as $m}from"simple-git";function Ir(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 xm(t,e="HEAD"){let r=$m(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 ko(t,n)}}async function ko(t,e){let n=await $m(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 bm(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function Sm(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=bm(f.path);n.has(g)||n.set(g,[]),n.get(g).push(f);let h=g;for(;h!=="";){let k=bm(h);o.has(k)||o.set(k,new Set),o.get(k).add(h),h=k}}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 vm,bo=S(()=>{"use strict";vm=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as Em,readFileSync as Tm}from"node:fs";import{join as Im}from"node:path";import{simpleGit as tS}from"simple-git";import{parse as Rm}from"yaml";function fn(t){let e={ignore:vm,containerNodeCap:rS,cochange:{...tt},issueKeyPattern:null,enabled:!1},r=Im(t,"regimen.yaml");if(!Em(r))return e;let n;try{n=Rm(Tm(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 Fc(t,e){let r=Im(t,Vn(e));if(!Em(r))return null;let n=Rm(Tm(r,"utf-8")),o=Xn(n);if(!o.ok)throw new Error(`model: ${Vn(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function Gc(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await xm(r,t.ref??"HEAD"),s=Ir(o.ignore),a=i.files.filter(w=>!s(w.path)),c=Sm(a,o.containerNodeCap),l=Fc(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await tS(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=mm(await fm(r,l.builtFromCommit,i.commit)),p=new Map((await ko(r,l.builtFromCommit)).map(x=>[x.path,x.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=dm({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:wm(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),f=ym(e,i.commit,c,m.byKey),g=Ir([...o.ignore,...pn]),h=um({repo:e,headTimeSec:i.commitTimeSec,filesets:await lm(r,i.commit,o.cochange.windowCommits),pathToCurrent:Ai(m.table),currentPaths:new Set(a.map(w=>w.path)),ignored:g,settings:o.cochange}),k=[{path:Vn(e),content:oa(m.table)},...f.files.map(w=>({path:w.path,content:w.content})),{path:zs(e),content:hr({modelFormatVersion:2,repo:e,builtFromCommit:i.commit,edges:h})}];return{repo:e,headCommit:i.commit,files:k,emittedShardPaths:new Set(f.files.map(w=>w.path)),counts:{...f.counts,correlates:h.length},identityTable:m.table,entityByKey:m.byKey}}var rS,Kc=S(()=>{"use strict";F();_i();pm();hm();km();bo();rS=1500});import{existsSync as Pm,readFileSync as Am,readdirSync as nS}from"node:fs";import{join as Hc}from"node:path";import{parse as _m}from"yaml";function oS(t,e){if(!t||!e)return null;let r=Date.parse(`${t}T00:00:00Z`),n=Date.parse(`${e}T00:00:00Z`);return!Number.isFinite(r)||!Number.isFinite(n)?null:Math.abs(r-n)/864e5}function jm(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<Qs)return null;let s=i/Math.min(n.size,o.size),a=oS(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(s*c*Cm)/Cm;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[$e(t.taskKey),$e(e.taskKey)]:[$e(e.taskKey),$e(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function Nm(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=jm(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 Om(t,e,r,n){let o=$e(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=jm(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 Ni(t){let e=Hc(t,"model/facts/events");if(!Pm(e))return[];let r=[];for(let n of nS(e).sort())if(n.endsWith(".yaml"))try{let o=At(_m(Am(Hc(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function Lm(t){let e=Hc(t,fr);if(!Pm(e))return[];try{let r=zn(_m(Am(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function Oi(t){return hr({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var Cm,Wc=S(()=>{"use strict";F();Cm=1e4});var $o={};We($o,{collectSearchRows:()=>Dm,readContextIndexHub:()=>iS,rebuildSearchIndex:()=>Um,searchIndexPath:()=>Ui,searchModelIndex:()=>sS,toFtsQuery:()=>Bm});import{existsSync as hn,readFileSync as mn,readdirSync as Mi}from"node:fs";import{join as wt}from"node:path";import{parse as Di}from"yaml";function Ui(t){return wt(t,".git","codepipe-model-index.sqlite")}function iS(t){let e=wt(t,"regimen.yaml");if(!hn(e))return"off";try{let n=Di(mn(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 Mm(){try{let{createRequire:t}=await import("node:module");return t(import.meta.url)("node:sqlite")}catch{return null}}function Li(t){return t.length>Vo?t.slice(0,Vo):t}function qc(t){if(!hn(t))return[];let e=[];for(let r of Mi(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=wt(t,r.name);r.isDirectory()?e.push(...qc(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function Dm(t){let e=[];for(let i of qc(wt(t,"model/derived/structure"))){let s;try{s=Di(mn(i,"utf-8"))}catch{continue}let a=Pt(s);if(a.ok)for(let c of a.value.nodes){let l=te(c.key);l&&e.push({nodeId:c.key,kind:l.level,text:Li(`${l.path} ${c.label??""}`.trim())})}}let r=wt(t,"model/facts/events");if(hn(r)){for(let i of Mi(r).sort())if(i.endsWith(".yaml"))try{let s=At(Di(mn(wt(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:Li(`${a.taskKey} ${a.title??""} ${c}`.trim())})}catch{}}let n=wt(t,"model/facts/annotations");if(hn(n)){let i=new Map;for(let s of qc(wt(t,"model/facts/identity")))try{let a=Di(mn(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 Mi(n).sort())if(s.endsWith(".md"))try{let a=mn(wt(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:Li(c[2].trim())})}catch{}}let o=wt(t,"adr");if(hn(o))for(let i of Mi(o).sort()){let s=/^(\d{4})-/.exec(i)?.[1];if(!(!s||!i.endsWith(".md")))try{let a=mn(wt(o,i),"utf-8").split(`
703
+ `)){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:im(s[3]),churn:a+c})}return o}function Yx(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(Uc,"").trim();else if(c.prNumber!==null){if((t.trackerProjectKey??"").toUpperCase()==="PR")continue;u=`PR-${c.prNumber}`,p=c.subject.replace(Uc,"").replace(rm,"").replace(/^from\s+/,"").trim()||c.subject}else continue;if(!/^[A-Za-z0-9._-]+$/.test(u))continue;let m=new Map;for(let h of c.files){let k=o.get(h.path)??h.path;s(k)||m.set(k,(m.get(k)??0)+h.churn)}if(m.size===0)continue;let g=a.get(u)??{modelFormatVersion:2,taskKey:u,origin:"bootstrap",title:"",commits:[],files:[]};p&&(g.title=p),c.timeSec>0&&(g.date=new Date(c.timeSec*1e3).toISOString().slice(0,10)),g.commits.push(c.sha);for(let[h,k]of m){let y=ge("code",e,h),$=g.files.find(x=>x.key===y);if($)$.churn=($.churn??0)+k;else{let x=i.get(y);g.files.push({key:y,...x?{entityId:x}:{},churn:k})}}if(d.length>0){let h=new Set([...g.links?.tasks??[],...d]);h.delete(u),g.links={...g.links??{},tasks:[...h].sort()}}a.set(u,g)}return a}function em(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 sm(t){let e=await Wx(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 qx(t.repoDir,r.sha))}return Yx({repo:t.repo,issueKeyRe:t.issueKeyRe,commits:e,pathToCurrent:t.pathToCurrent,entityByKey:t.entityByKey,ignored:t.ignored,trackerProjectKey:t.trackerProjectKey??null})}function am(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?em(c,a)??c:a)}let n=[],o=0;for(let[i,s]of[...r.entries()].sort(([a],[c])=>a<c?-1:1)){let a=em(Pi(t,i),s);if(!a){o++;continue}n.push({path:mr(i),content:Gr(a)})}return{files:n,skippedPipeline:o}}function Pi(t,e){let r=Mc(t,mr(e));if(!Oc(r))return null;try{let n=At(Dc(Lc(r,"utf-8")));return n.ok?n.value:null}catch{return null}}var Hx,Uc,rm,Bc=S(()=>{"use strict";F();Hx=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g,Uc=/\(#(\d+)\)\s*$/,rm=/^Merge pull request #(\d+)\b/});import{simpleGit as Vx}from"simple-git";async function lm(t,e,r){let o=await Vx(t).raw(["log","--no-merges","--name-only","--format=@@@ %H %ct","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
704
+ `))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 Ai(t){let e=new Map;for(let r of t.entities){if(r.status!=="active"||!r.aliases)continue;let n=te(r.currentKey);if(n?.level==="code")for(let o of r.aliases){let i=te(o.key);i?.level==="code"&&e.set(i.path,n.path)}}return e}function um(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 k of n){let y=new Set;for(let v of k.files){let b=o.get(v)??v;!i.has(b)||s(b)||y.add(b)}if(y.size<2||y.size>a.commitFileCap)continue;let $=Math.max(0,r-k.timeSec),x=Math.pow(.5,$/c),T=[...y].sort();for(let v of T)l.set(v,(l.get(v)??0)+x);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)+x),p.set(R,(p.get(R)??0)+1)}}let d=[],m=a.jaccardMinPct/100;for(let[k,y]of u){if((p.get(k)??0)<a.supportMin)continue;let[$,x]=k.split("\0"),T=(l.get($)??0)+(l.get(x)??0)-y,v=T>0?y/T:0;v<m||d.push({a:$,b:x,weight:Math.round(v*cm)/cm})}let f=new Map;for(let k of d)for(let y of[k.a,k.b])f.has(y)||f.set(y,[]),f.get(y).push(k);let g=new Map;for(let[,k]of f)k.sort((y,$)=>$.weight-y.weight||(y.a<$.a?-1:y.a>$.a?1:y.b<$.b?-1:1)).slice(0,a.topK).forEach(y=>g.set(y,(g.get(y)??0)+1));return[...g.entries()].filter(([,k])=>k===2).map(([k])=>k).map(k=>({kind:"correlates",from:ge("code",e,k.a),to:ge("code",e,k.b),weight:k.weight})).sort((k,y)=>k.from<y.from?-1:k.from>y.from?1:k.to<y.to?-1:1)}var pn,cm,_i=S(()=>{"use strict";F();pn=["package-lock.json","pnpm-lock.yaml","yarn.lock"];cm=1e4});import{createHash as zx}from"node:crypto";function Jx(t,e,r,n){for(let o=0;;o++){let s=`e_${zx("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(s))return s}}function dm(t){let{repo:e,headCommit:r,headDate:n,prev:o,renameChains:i,prevBlobByPath:s,headBlobByPath:a}=t,c=[...t.currentKeys].sort(),l=new Set(c),u=o?.entities??[],p=new Set(u.map(b=>b.entityId)),d=new Set,m=[],f=new Map,g=(b,R)=>{d.add(R),f.set(R,b.entityId),m.push(b)},h=[];for(let b of u)l.has(b.currentKey)&&!d.has(b.currentKey)?g({...b,status:"active",lastSeen:r},b.currentKey):h.push(b);let k=[],y=[];for(let b of h){let R=te(b.currentKey),A=R?i.get(R.path):void 0;if(R&&A){let G=ge(R.level,e,A.finalPath);if(l.has(G)&&!d.has(G)){k.push({entity:b,newKey:G,untilCommit:A.commit}),d.add(G);continue}}y.push(b)}let $=[];if(s){let b=new Map;for(let A of c){if(d.has(A))continue;let G=te(A);if(G?.level!=="code")continue;let V=a.get(G.path);V&&b.set(V,b.has(V)?null:A)}let R=new Map;for(let A of y){let G=te(A.currentKey);if(G?.level!=="code")continue;let V=s.get(G.path);V&&R.set(V,R.has(V)?null:A)}for(let A of y){let G=te(A.currentKey),V=G?.level==="code"?s.get(G.path):void 0,C=V?b.get(V):void 0;V&&C&&R.get(V)===A&&!d.has(C)?(k.push({entity:A,newKey:C,untilCommit:r}),d.add(C)):$.push(A)}}else $.push(...y);let x=new Map;for(let b of k){let R=te(b.entity.currentKey),A=te(b.newKey);if(R?.level!=="code"||!A)continue;let G=R.path,V=A.path;for(let C=G.lastIndexOf("/");C>0;C=G.lastIndexOf("/",C-1)){let w=G.slice(0,C),U=G.slice(C+1);if(!V.endsWith(`/${U}`))continue;let _=V.slice(0,V.length-U.length-1);if(_===w)continue;let H=`${w}\0${_}`,z=x.get(H);x.set(H,{count:(z?.count??0)+1,commit:z&&z.commit>b.untilCommit?z.commit:b.untilCommit})}}let T=[...x.entries()].filter(([,b])=>b.count>=Xx).map(([b,R])=>{let[A,G]=b.split("\0");return{from:A,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=te(b.currentKey),A=!1;if(R?.level==="component")for(let G of T){let V=null;if(R.path===G.from?V=G.to:R.path.startsWith(`${G.from}/`)&&(V=G.to+R.path.slice(G.from.length)),V===null)continue;let C=ge("component",e,V);l.has(C)&&!d.has(C)&&(k.push({entity:b,newKey:C,untilCommit:G.commit}),d.add(C),A=!0);break}A||v.push(b)}for(let b of k.sort((R,A)=>R.newKey<A.newKey?-1:1))g({...b.entity,currentKey:b.newKey,aliases:[...b.entity.aliases??[],{key:b.entity.currentKey,until:b.untilCommit}],status:"active",lastSeen:r},b.newKey);for(let b of v)m.push({...b,status:"orphaned"});for(let b of c){if(d.has(b))continue;let R=Jx(e,b,r,p);p.add(R),g({entityId:R,currentKey:b,firstSeen:n,lastSeen:r,status:"active"},b)}return{table:{modelFormatVersion:2,repo:e,builtFromCommit:r,entities:m},byKey:f}}var Xx,pm=S(()=>{"use strict";F();Xx=5});import{simpleGit as Zx}from"simple-git";async function fm(t,e,r){let n=Zx(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
705
+ `).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 mm(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 hm=S(()=>{"use strict"});function ji(t){return ge("container",t,Qx)}function gm(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function ym(t,e,r,n){let o=[],i=u=>{let p=ge("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:gm(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,eS)}},s=(u,p)=>{let d=ge("component",t,u),m=n.get(d);return{key:d,level:"component",label:gm(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)],h=[...m.map(k=>({kind:"contains",from:p.key,to:ge("code",t,k.path)})),...f.map(k=>({kind:"contains",from:p.key,to:ge("component",t,k)}))];c(u,g,h)},c=(u,p,d)=>{let m={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},f=Pt(m);if(!f.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${f.errors.join("; ")}`);o.push({path:Js(t,u),content:na(m)})},l={key:ji(t),level:"container",label:t,...n.get(ji(t))?{entityId:n.get(ji(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 wm(t,e){let r=[ji(t)];for(let n of e.components)r.push(ge("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(ge("code",t,o.path));return r.sort()}var Qx,eS,km=S(()=>{"use strict";F();Qx=".";eS=12});import{simpleGit as $m}from"simple-git";function Ir(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 xm(t,e="HEAD"){let r=$m(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 ko(t,n)}}async function ko(t,e){let n=await $m(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 bm(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function Sm(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=bm(f.path);n.has(g)||n.set(g,[]),n.get(g).push(f);let h=g;for(;h!=="";){let k=bm(h);o.has(k)||o.set(k,new Set),o.get(k).add(h),h=k}}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 vm,bo=S(()=>{"use strict";vm=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as Em,readFileSync as Tm}from"node:fs";import{join as Im}from"node:path";import{simpleGit as tS}from"simple-git";import{parse as Rm}from"yaml";function fn(t){let e={ignore:vm,containerNodeCap:rS,cochange:{...tt},issueKeyPattern:null,enabled:!1},r=Im(t,"regimen.yaml");if(!Em(r))return e;let n;try{n=Rm(Tm(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 Fc(t,e){let r=Im(t,Vn(e));if(!Em(r))return null;let n=Rm(Tm(r,"utf-8")),o=Xn(n);if(!o.ok)throw new Error(`model: ${Vn(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function Gc(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await xm(r,t.ref??"HEAD"),s=Ir(o.ignore),a=i.files.filter(y=>!s(y.path)),c=Sm(a,o.containerNodeCap),l=Fc(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await tS(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=mm(await fm(r,l.builtFromCommit,i.commit)),p=new Map((await ko(r,l.builtFromCommit)).map(x=>[x.path,x.blobHash]))):l?.builtFromCommit===i.commit&&(p=new Map(a.map(y=>[y.path,y.blobHash])));let d=new Map(a.map(y=>[y.path,y.blobHash])),m=dm({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:wm(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),f=ym(e,i.commit,c,m.byKey),g=Ir([...o.ignore,...pn]),h=um({repo:e,headTimeSec:i.commitTimeSec,filesets:await lm(r,i.commit,o.cochange.windowCommits),pathToCurrent:Ai(m.table),currentPaths:new Set(a.map(y=>y.path)),ignored:g,settings:o.cochange}),k=[{path:Vn(e),content:oa(m.table)},...f.files.map(y=>({path:y.path,content:y.content})),{path:zs(e),content:hr({modelFormatVersion:2,repo:e,builtFromCommit:i.commit,edges:h})}];return{repo:e,headCommit:i.commit,files:k,emittedShardPaths:new Set(f.files.map(y=>y.path)),counts:{...f.counts,correlates:h.length},identityTable:m.table,entityByKey:m.byKey}}var rS,Kc=S(()=>{"use strict";F();_i();pm();hm();km();bo();rS=1500});import{existsSync as Pm,readFileSync as Am,readdirSync as nS}from"node:fs";import{join as Hc}from"node:path";import{parse as _m}from"yaml";function oS(t,e){if(!t||!e)return null;let r=Date.parse(`${t}T00:00:00Z`),n=Date.parse(`${e}T00:00:00Z`);return!Number.isFinite(r)||!Number.isFinite(n)?null:Math.abs(r-n)/864e5}function jm(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<Qs)return null;let s=i/Math.min(n.size,o.size),a=oS(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(s*c*Cm)/Cm;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[$e(t.taskKey),$e(e.taskKey)]:[$e(e.taskKey),$e(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function Nm(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=jm(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 Om(t,e,r,n){let o=$e(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=jm(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 Ni(t){let e=Hc(t,"model/facts/events");if(!Pm(e))return[];let r=[];for(let n of nS(e).sort())if(n.endsWith(".yaml"))try{let o=At(_m(Am(Hc(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function Lm(t){let e=Hc(t,fr);if(!Pm(e))return[];try{let r=zn(_m(Am(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function Oi(t){return hr({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var Cm,Wc=S(()=>{"use strict";F();Cm=1e4});var $o={};We($o,{collectSearchRows:()=>Dm,readContextIndexHub:()=>iS,rebuildSearchIndex:()=>Um,searchIndexPath:()=>Ui,searchModelIndex:()=>sS,toFtsQuery:()=>Bm});import{existsSync as hn,readFileSync as mn,readdirSync as Mi}from"node:fs";import{join as gt}from"node:path";import{parse as Di}from"yaml";function Ui(t){return gt(t,".git","codepipe-model-index.sqlite")}function iS(t){let e=gt(t,"regimen.yaml");if(!hn(e))return"off";try{let n=Di(mn(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 Mm(){try{let{createRequire:t}=await import("node:module");return t(import.meta.url)("node:sqlite")}catch{return null}}function Li(t){return t.length>Vo?t.slice(0,Vo):t}function qc(t){if(!hn(t))return[];let e=[];for(let r of Mi(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=gt(t,r.name);r.isDirectory()?e.push(...qc(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function Dm(t){let e=[];for(let i of qc(gt(t,"model/derived/structure"))){let s;try{s=Di(mn(i,"utf-8"))}catch{continue}let a=Pt(s);if(a.ok)for(let c of a.value.nodes){let l=te(c.key);l&&e.push({nodeId:c.key,kind:l.level,text:Li(`${l.path} ${c.label??""}`.trim())})}}let r=gt(t,"model/facts/events");if(hn(r)){for(let i of Mi(r).sort())if(i.endsWith(".yaml"))try{let s=At(Di(mn(gt(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:Li(`${a.taskKey} ${a.title??""} ${c}`.trim())})}catch{}}let n=gt(t,"model/facts/annotations");if(hn(n)){let i=new Map;for(let s of qc(gt(t,"model/facts/identity")))try{let a=Di(mn(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 Mi(n).sort())if(s.endsWith(".md"))try{let a=mn(gt(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:Li(c[2].trim())})}catch{}}let o=gt(t,"adr");if(hn(o))for(let i of Mi(o).sort()){let s=/^(\d{4})-/.exec(i)?.[1];if(!(!s||!i.endsWith(".md")))try{let a=mn(gt(o,i),"utf-8").split(`
706
706
  `).slice(0,6);e.push({nodeId:`adr::ADR-${s}`,kind:"adr",text:Li(a.filter(c=>c.trim()).join(" "))})}catch{}}return e}async function Um(t){let e=Dm(t),r=await Mm();if(!r)return{rows:e,indexed:!1};let n=new r.DatabaseSync(Ui(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 Bm(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 sS(t,e,r){let n=await Mm();if(!n)throw new Error("model search needs Node with built-in sqlite (>= 22.13) on this CLI");hn(Ui(t))||await Um(t);let o=Bm(e);if(!o)return[];let i=Math.min(Math.max(r??20,1),ta),s=new n.DatabaseSync(Ui(t));try{return s.prepare(`SELECT node_id AS nodeId, kind, snippet(model_fts, 2, '[', ']', '\u2026', 10) AS snippet,
707
707
  bm25(model_fts) AS rank
708
- 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 vo=S(()=>{"use strict";F()});import{homedir as vS}from"node:os";import{existsSync as xS,mkdirSync as SS,readFileSync as ES,writeFileSync as TS}from"node:fs";import{dirname as IS,join as RS}from"node:path";function Xc(){return z("FARM_PINS")??RS(vS(),".codepipe","farm-pins.json")}function Jm(){let t=Xc();if(!xS(t))return{};try{return JSON.parse(ES(t,"utf-8"))}catch{return{}}}function CS(t){let e=Xc();SS(IS(e),{recursive:!0}),TS(e,JSON.stringify(t,null,2)+`
709
- `,{mode:384})}function PS(t){return Jm()[t]}function Hi(t,e){let r=Jm();r[t]=e,CS(r)}function Wi(t,e){let r=Ge(e),n=PS(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 ${Xc()}.`);return r}var Jc=S(()=>{"use strict";Be();at()});import{setTimeout as AS}from"node:timers/promises";import _S from"ws";function qi(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new _S(r)}async function tr(t,e,r){return rr(t,e,"/projects",r)}async function Zm(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new H(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function Yi(t,e,r,n){return rr(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function Qm(t,e,r,n){return rr(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function eh(t,e,r,n){return rr(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function th(t,e){let r=await fetch(`${t}/sandbox/me`,{headers:{Authorization:`Bearer ${e}`}});if(r.ok)return"ok";if(r.status===401)return"unknown";if(r.status===404)return"unsupported";throw new H(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function Vi(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new H(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function Zc(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new H(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function rh(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await Zc(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 AS(r.delayMs??1500)}throw o}async function nh(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 To(e)}if(!r.ok)throw new H(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function oh(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new H(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function ih(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new H(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function sh(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new H(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function ah(t,e,r,n,o){return rr(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function Io(t,e,r,n){return rr(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function Qc(t,e,r,n){await rr(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function ch(t,e,r,n){return rr(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function lh(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 H(o.status,s,a)}return s}async function oe(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new H(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function rr(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 H(o.status,s,a)}return s}async function uh(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/deliverables`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new H(n.status,null,`GET /deliverables HTTP ${n.status}`);return(await n.json()).deliverables}var H,To,je=S(()=>{"use strict";H=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};To=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});var nl={};We(nl,{mirrorLag:()=>VS,syncUpstream:()=>YS});import{simpleGit as Ch}from"simple-git";async function YS(t,e,r,n){let o=Ch(e),i=t.defaultBranch??"main",s=n?.upstream??Ph(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/*:${Rr}/*`,["--prune"]);let a=(await o.revparse([`${Rr}/${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?Ah(t.mirror):null);if(!c)return{repo:t.name,upstreamHead:a,updated:!1};let l=await zS(o),u=await rl(o,c),p=[];for(let d of l){if(d==="codepipe"||d.startsWith("codepipe/"))continue;let m=(await o.revparse([`${Rr}/${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(`
708
+ 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 vo=S(()=>{"use strict";F()});import{homedir as vS}from"node:os";import{existsSync as xS,mkdirSync as SS,readFileSync as ES,writeFileSync as TS}from"node:fs";import{dirname as IS,join as RS}from"node:path";function Xc(){return X("FARM_PINS")??RS(vS(),".codepipe","farm-pins.json")}function Jm(){let t=Xc();if(!xS(t))return{};try{return JSON.parse(ES(t,"utf-8"))}catch{return{}}}function CS(t){let e=Xc();SS(IS(e),{recursive:!0}),TS(e,JSON.stringify(t,null,2)+`
709
+ `,{mode:384})}function PS(t){return Jm()[t]}function Hi(t,e){let r=Jm();r[t]=e,CS(r)}function Wi(t,e){let r=Ge(e),n=PS(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 ${Xc()}.`);return r}var Jc=S(()=>{"use strict";Be();at()});import{setTimeout as AS}from"node:timers/promises";import _S from"ws";function qi(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new _S(r)}async function tr(t,e,r){return rr(t,e,"/projects",r)}async function Zm(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 Yi(t,e,r,n){return rr(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function Qm(t,e,r,n){return rr(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function eh(t,e,r,n){return rr(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function th(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 Vi(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 Zc(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 rh(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await Zc(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 AS(r.delayMs??1500)}throw o}async function nh(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 To(e)}if(!r.ok)throw new W(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function oh(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 sh(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new W(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function ah(t,e,r,n,o){return rr(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function Io(t,e,r,n){return rr(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function Qc(t,e,r,n){await rr(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function ch(t,e,r,n){return rr(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function lh(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 oe(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 rr(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 uh(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,To,je=S(()=>{"use strict";W=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};To=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});var nl={};We(nl,{mirrorLag:()=>VS,syncUpstream:()=>YS});import{simpleGit as Ch}from"simple-git";async function YS(t,e,r,n){let o=Ch(e),i=t.defaultBranch??"main",s=n?.upstream??Ph(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/*:${Rr}/*`,["--prune"]);let a=(await o.revparse([`${Rr}/${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?Ah(t.mirror):null);if(!c)return{repo:t.name,upstreamHead:a,updated:!1};let l=await zS(o),u=await rl(o,c),p=[];for(let d of l){if(d==="codepipe"||d.startsWith("codepipe/"))continue;let m=(await o.revparse([`${Rr}/${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
710
  `)[0]:String(a);return{repo:t.name,upstreamHead:null,updated:!1,error:c}}}async function VS(t,e,r){let n=r?.mirror??(t.mirror?Ah(t.mirror):null);if(!n)return null;let o=r?.upstream??Ph(t);if(!o)return null;let i=Ch(e),s=t.defaultBranch??"main";try{let a=(await rl(i,n,s)).get(s);if(!a)return null;let c=(await rl(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}:${Rr}/${s}`),await l())}catch{return null}}function Ph(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 Ah(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 zS(t){return(await t.raw(["for-each-ref",Rr,"--format=%(refname)"]).catch(()=>"")).split(`
711
711
  `).map(r=>r.trim()).filter(r=>r.startsWith(`${Rr}/`)).map(r=>r.slice(Rr.length+1))}async function rl(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 Rr,ol=S(()=>{"use strict";Rr="refs/codepipe/upstream"});import{existsSync as _h,readFileSync as XS,readdirSync as JS}from"node:fs";import{join as jh}from"node:path";import{simpleGit as ZS}from"simple-git";import{parse as QS}from"yaml";function il(t){let e=new Map,r=jh(t,qo);if(!_h(r))return e;let n;try{n=QS(XS(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 eE(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return yr({modelFormatVersion:2,repos:e})}function Nh(t,e){let r=jh(t,e);if(!_h(r))return[];let n=[];for(let o of JS(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...Nh(t,i)):n.push(i)}return n}async function Ji(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 Nh(t,m))d.emittedShardPaths.has(f)||(n.push({path:f,content:"",deleted:!0}),o++)}let i=il(t);for(let d of e)i.set(d.repo,{builtFromCommit:d.headCommit,counts:d.counts});n.push({path:qo,content:eE(i)});let s=Ni(t),a=Nm(s,r.halfLifeDays??tt.halfLifeDays);n.push({path:fr,content:Oi(a)});for(let d of e){let m=[];for(let f of s)for(let g of f.files)te(g.key)?.repo===d.repo&&m.push({kind:"touched_by",from:$e(f.taskKey),to:g.key,...g.churn!==void 0?{weight:g.churn}:{}});n.push({path:Xs(d.repo),content:hr({modelFormatVersion:2,repo:d.repo,builtFromCommit:d.headCommit,edges:m})})}let c=ZS(t),l=(await c.revparse(["HEAD"]).catch(()=>"")).trim(),u=`model: build ${e.map(d=>`${d.repo}@${d.headCommit.slice(0,10)}`).join(", ")}`;await Te(t,n,u);let p=(await c.revparse(["HEAD"]).catch(()=>"")).trim();if(p!==l){let{rebuildSearchIndex:d}=await Promise.resolve().then(()=>(vo(),$o));await d(t).catch(()=>{})}return{committed:p!==l,filesWritten:n.filter(d=>!d.deleted).length,filesDeleted:o}}var Oh=S(()=>{"use strict";F();Wc();st()});var es={};We(es,{bootstrapDaemonModel:()=>rE,bootstrapModelForTargets:()=>dl,bootstrapWorkspaceModel:()=>Bh,modelBootstrapCommand:()=>ul,modelBuildCommand:()=>ll,rebuildWorkspaceModelIfStale:()=>nE});import{existsSync as Zi}from"node:fs";import{join as nr}from"node:path";import{cancel as tE,intro as Lh,log as sl,outro as al}from"@clack/prompts";import{simpleGit as cl}from"simple-git";function Qi(t){tE(t),process.exit(1)}function Mh(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:nr(t.root,i.mountAs);if(!Zi(nr(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 Dh(t){let e=cl(t.dir),r=`origin/${t.defaultBranch}`;return await e.raw(["rev-parse","--verify",r]).then(()=>!0).catch(()=>!1)?r:"HEAD"}async function Uh(t,e,r,n){let o=[];for(let i of e)try{let s=await Gc({repo:i.name,repoDir:i.dir,contextDir:t,settings:r,ref:await Dh(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 ll(t){Lh("codepipe model build");let e=Pe();e||Qi("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{let r=fn(e.contextDir),n=Mh(e,t.repo,s=>sl.warn(s)),o=await Uh(e.contextDir,n,r,s=>sl.info(s)),i=await Ji(e.contextDir,o,{halfLifeDays:r.cochange.halfLifeDays});i.committed?al(`model updated: ${i.filesWritten} files written, ${i.filesDeleted} stale removed`):al("model already up to date (no changes)")}catch(r){Qi(r instanceof Error?r.message:String(r))}}async function ul(t){Lh("codepipe model bootstrap");let e=Pe();e||Qi("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{await Bh(e,t.repo,{onLog:r=>sl.info(r)})}catch(r){Qi(r instanceof Error?r.message:String(r))}al("bootstrap complete")}async function Bh(t,e,r){let n=Mh(t,e,r.onLog);return dl(t.contextDir,n,r)}async function dl(t,e,r){let n=fn(t),o=await Uh(t,e,n,r.onLog),i=om(t),s=nm(n.issueKeyPattern,i),a=Ir([...n.ignore,...pn]),c=[];for(let p of o){let d=e.find(f=>f.name===p.repo),m=await sm({repo:p.repo,repoDir:d.dir,headCommit:p.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:s,pathToCurrent:Ai(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}=am(t,c);return u>0&&r.onLog(`${u} events already recorded by the live pipeline \u2014 left untouched`),l.length>0&&await Te(t,l,`model: bootstrap ${l.length} task events from history`),await Ji(t,o,{halfLifeDays:n.cochange.halfLifeDays}),{events:l.length}}async function rE(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:nr(e.root,a),l=s.defaultBranch||"main";c!==e.contextDir&&Zi(nr(c,".git"))?(await cl(c).fetch(["origin",l]).catch(()=>{}),o.push({name:s.name,dir:c,defaultBranch:l})):(n(`${s.name}: materializing clone in the daemon layout`),await er(t,s),o.push({name:s.name,dir:_e(t,s.name),defaultBranch:l}))}let i=await dl(e.contextDir,o,{onLog:n});return{repos:o.length,events:i.events}}async function nE(t,e={}){let r=e.onLog??(()=>{}),n=fn(t.contextDir),o=new Map;for(let l of t.repos){if(!l.mirror)continue;let u=l.mountAs==="."?t.root:nr(t.root,l.mountAs);if(!Zi(nr(u,".git")))continue;let{syncUpstream:p}=await Promise.resolve().then(()=>(ol(),nl)),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=il(t.contextDir),c=[];for(let l of t.repos){let u=l.mountAs==="."?t.root:nr(t.root,l.mountAs);if(!Zi(nr(u,".git")))continue;let p=cl(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 Dh({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 Gc({repo:l.name,repoDir:u,contextDir:t.contextDir,settings:n,ref:g})),i.push(l.name)}catch(h){r(`[model] rebuild of ${l.name} failed: ${h instanceof Error?h.message:String(h)}`)}}}return c.length>0&&(await Ji(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 Ro=S(()=>{"use strict";st();Oh();Kc();Bc();_i();bo();ho();rt()});var Gh={};We(Gh,{computeDriftReport:()=>cE,supersededAdrIds:()=>Fh});import{existsSync as pl,readFileSync as fl,readdirSync as ml}from"node:fs";import{join as gn}from"node:path";import{parse as oE}from"yaml";import{simpleGit as iE}from"simple-git";function aE(t,e){let r=gn(t,`model/derived/structure/${e}`),n=[],o="";if(!pl(r))return{nodes:n,builtFromCommit:o};for(let i of ml(r).sort()){if(!i.endsWith(".yaml"))continue;let s;try{let a=Pt(oE(fl(gn(r,i),"utf-8")));if(!a.ok)continue;s=a.value}catch{continue}o=s.builtFromCommit;for(let a of s.nodes){let c=te(a.key);!c||c.level!=="code"&&c.level!=="component"||n.push({key:a.key,path:c.path,level:c.level,contentHash:a.contentHash,entityId:a.entityId})}}return{nodes:n,builtFromCommit:o}}function Fh(t){let e=new Set,r=gn(t,"adr");if(!pl(r))return e;for(let n of ml(r).sort()){let o=/^(\d{4})-/.exec(n)?.[1];if(!(!o||!n.endsWith(".md")))try{let i=fl(gn(r,n),"utf-8").slice(0,600).toLowerCase();/status[^\n]*superseded/.test(i)&&e.add(`ADR-${o}`)}catch{}}return e}async function cE(t,e,r){let{nodes:n,builtFromCommit:o}=aE(e,r),i=(await iE(t).revparse(["HEAD"])).trim(),s=await ko(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,sE)!==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("/"),x=$<0?"":w.path.slice(0,$);m.has(x)||m.set(x,new Set),m.get(x).add(w.path),u.has(w.path)||d++;let T=x;for(;T!==""&&!f.has(T);)f.add(T),T=T.includes("/")?T.slice(0,T.lastIndexOf("/")):""}let g=new Map;for(let w of u){let $=w.lastIndexOf("/"),x=$<0?"":w.slice(0,$);g.has(x)||g.set(x,new Set),g.get(x).add(w)}for(let w of p){if(!f.has(w.path)){l.push(w.key);continue}let $=g.get(w.path)??new Set,x=m.get(w.path)??new Set;($.size!==x.size||[...$].some(v=>!x.has(v)))&&c.push(w.key)}let h=[],k=Fh(e);if(k.size>0){let w=gn(e,"model/facts/annotations"),$=new Map(n.filter(x=>x.entityId).map(x=>[x.entityId,x.key]));if(pl(w))for(let x of ml(w).sort()){if(!x.endsWith(".md"))continue;let T=x.replace(/\.md$/,""),v=$.get(T);if(v)try{(fl(gn(w,x),"utf-8").match(/\bADR-(\d{3,4})\b/g)??[]).map(A=>`ADR-${A.slice(4).padStart(4,"0")}`).some(A=>k.has(A))&&h.push(v)}catch{}}}return{repo:r,builtFromCommit:o,headCommit:i,stale:[...new Set(c)].sort(),orphaned:[...new Set(l)].sort(),superseded:[...new Set(h)].sort(),newFiles:d}}var sE,Kh=S(()=>{"use strict";F();bo();sE=12});import{execFileSync as yE}from"node:child_process";import{mkdtempSync as wE,mkdirSync as kE,readFileSync as qh,rmSync as bE,writeFileSync as $E}from"node:fs";import{tmpdir as vE}from"node:os";import{dirname as xE,join as Yh}from"node:path";function Vh(t="codepipe-context"){let e=wE(Yh(vE(),"codepipe-ssh-")),r=Yh(e,"id_ed25519");try{return yE("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:qh(r,"utf-8"),publicKey:qh(`${r}.pub`,"utf-8").trim()}}finally{bE(e,{recursive:!0,force:!0})}}async function zh(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 Xh(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 Jh(t,e){kE(xE(t),{recursive:!0});let r=e.endsWith(`
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 Rr,ol=S(()=>{"use strict";Rr="refs/codepipe/upstream"});import{existsSync as _h,readFileSync as XS,readdirSync as JS}from"node:fs";import{join as jh}from"node:path";import{simpleGit as ZS}from"simple-git";import{parse as QS}from"yaml";function il(t){let e=new Map,r=jh(t,qo);if(!_h(r))return e;let n;try{n=QS(XS(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 eE(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return yr({modelFormatVersion:2,repos:e})}function Nh(t,e){let r=jh(t,e);if(!_h(r))return[];let n=[];for(let o of JS(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...Nh(t,i)):n.push(i)}return n}async function Ji(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 Nh(t,m))d.emittedShardPaths.has(f)||(n.push({path:f,content:"",deleted:!0}),o++)}let i=il(t);for(let d of e)i.set(d.repo,{builtFromCommit:d.headCommit,counts:d.counts});n.push({path:qo,content:eE(i)});let s=Ni(t),a=Nm(s,r.halfLifeDays??tt.halfLifeDays);n.push({path:fr,content:Oi(a)});for(let d of e){let m=[];for(let f of s)for(let g of f.files)te(g.key)?.repo===d.repo&&m.push({kind:"touched_by",from:$e(f.taskKey),to:g.key,...g.churn!==void 0?{weight:g.churn}:{}});n.push({path:Xs(d.repo),content:hr({modelFormatVersion:2,repo:d.repo,builtFromCommit:d.headCommit,edges:m})})}let c=ZS(t),l=(await c.revparse(["HEAD"]).catch(()=>"")).trim(),u=`model: build ${e.map(d=>`${d.repo}@${d.headCommit.slice(0,10)}`).join(", ")}`;await Te(t,n,u);let p=(await c.revparse(["HEAD"]).catch(()=>"")).trim();if(p!==l){let{rebuildSearchIndex:d}=await Promise.resolve().then(()=>(vo(),$o));await d(t).catch(()=>{})}return{committed:p!==l,filesWritten:n.filter(d=>!d.deleted).length,filesDeleted:o}}var Oh=S(()=>{"use strict";F();Wc();st()});var es={};We(es,{bootstrapDaemonModel:()=>rE,bootstrapModelForTargets:()=>dl,bootstrapWorkspaceModel:()=>Bh,modelBootstrapCommand:()=>ul,modelBuildCommand:()=>ll,rebuildWorkspaceModelIfStale:()=>nE});import{existsSync as Zi}from"node:fs";import{join as nr}from"node:path";import{cancel as tE,intro as Lh,log as sl,outro as al}from"@clack/prompts";import{simpleGit as cl}from"simple-git";function Qi(t){tE(t),process.exit(1)}function Mh(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:nr(t.root,i.mountAs);if(!Zi(nr(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 Dh(t){let e=cl(t.dir),r=`origin/${t.defaultBranch}`;return await e.raw(["rev-parse","--verify",r]).then(()=>!0).catch(()=>!1)?r:"HEAD"}async function Uh(t,e,r,n){let o=[];for(let i of e)try{let s=await Gc({repo:i.name,repoDir:i.dir,contextDir:t,settings:r,ref:await Dh(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 ll(t){Lh("codepipe model build");let e=Pe();e||Qi("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{let r=fn(e.contextDir),n=Mh(e,t.repo,s=>sl.warn(s)),o=await Uh(e.contextDir,n,r,s=>sl.info(s)),i=await Ji(e.contextDir,o,{halfLifeDays:r.cochange.halfLifeDays});i.committed?al(`model updated: ${i.filesWritten} files written, ${i.filesDeleted} stale removed`):al("model already up to date (no changes)")}catch(r){Qi(r instanceof Error?r.message:String(r))}}async function ul(t){Lh("codepipe model bootstrap");let e=Pe();e||Qi("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{await Bh(e,t.repo,{onLog:r=>sl.info(r)})}catch(r){Qi(r instanceof Error?r.message:String(r))}al("bootstrap complete")}async function Bh(t,e,r){let n=Mh(t,e,r.onLog);return dl(t.contextDir,n,r)}async function dl(t,e,r){let n=fn(t),o=await Uh(t,e,n,r.onLog),i=om(t),s=nm(n.issueKeyPattern,i),a=Ir([...n.ignore,...pn]),c=[];for(let p of o){let d=e.find(f=>f.name===p.repo),m=await sm({repo:p.repo,repoDir:d.dir,headCommit:p.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:s,pathToCurrent:Ai(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}=am(t,c);return u>0&&r.onLog(`${u} events already recorded by the live pipeline \u2014 left untouched`),l.length>0&&await Te(t,l,`model: bootstrap ${l.length} task events from history`),await Ji(t,o,{halfLifeDays:n.cochange.halfLifeDays}),{events:l.length}}async function rE(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:nr(e.root,a),l=s.defaultBranch||"main";c!==e.contextDir&&Zi(nr(c,".git"))?(await cl(c).fetch(["origin",l]).catch(()=>{}),o.push({name:s.name,dir:c,defaultBranch:l})):(n(`${s.name}: materializing clone in the daemon layout`),await er(t,s),o.push({name:s.name,dir:_e(t,s.name),defaultBranch:l}))}let i=await dl(e.contextDir,o,{onLog:n});return{repos:o.length,events:i.events}}async function nE(t,e={}){let r=e.onLog??(()=>{}),n=fn(t.contextDir),o=new Map;for(let l of t.repos){if(!l.mirror)continue;let u=l.mountAs==="."?t.root:nr(t.root,l.mountAs);if(!Zi(nr(u,".git")))continue;let{syncUpstream:p}=await Promise.resolve().then(()=>(ol(),nl)),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=il(t.contextDir),c=[];for(let l of t.repos){let u=l.mountAs==="."?t.root:nr(t.root,l.mountAs);if(!Zi(nr(u,".git")))continue;let p=cl(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 Dh({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 Gc({repo:l.name,repoDir:u,contextDir:t.contextDir,settings:n,ref:g})),i.push(l.name)}catch(h){r(`[model] rebuild of ${l.name} failed: ${h instanceof Error?h.message:String(h)}`)}}}return c.length>0&&(await Ji(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 Ro=S(()=>{"use strict";st();Oh();Kc();Bc();_i();bo();ho();rt()});var Gh={};We(Gh,{computeDriftReport:()=>cE,supersededAdrIds:()=>Fh});import{existsSync as pl,readFileSync as fl,readdirSync as ml}from"node:fs";import{join as gn}from"node:path";import{parse as oE}from"yaml";import{simpleGit as iE}from"simple-git";function aE(t,e){let r=gn(t,`model/derived/structure/${e}`),n=[],o="";if(!pl(r))return{nodes:n,builtFromCommit:o};for(let i of ml(r).sort()){if(!i.endsWith(".yaml"))continue;let s;try{let a=Pt(oE(fl(gn(r,i),"utf-8")));if(!a.ok)continue;s=a.value}catch{continue}o=s.builtFromCommit;for(let a of s.nodes){let c=te(a.key);!c||c.level!=="code"&&c.level!=="component"||n.push({key:a.key,path:c.path,level:c.level,contentHash:a.contentHash,entityId:a.entityId})}}return{nodes:n,builtFromCommit:o}}function Fh(t){let e=new Set,r=gn(t,"adr");if(!pl(r))return e;for(let n of ml(r).sort()){let o=/^(\d{4})-/.exec(n)?.[1];if(!(!o||!n.endsWith(".md")))try{let i=fl(gn(r,n),"utf-8").slice(0,600).toLowerCase();/status[^\n]*superseded/.test(i)&&e.add(`ADR-${o}`)}catch{}}return e}async function cE(t,e,r){let{nodes:n,builtFromCommit:o}=aE(e,r),i=(await iE(t).revparse(["HEAD"])).trim(),s=await ko(t,i),a=new Map(s.map(y=>[y.path,y.blobHash])),c=[],l=[],u=new Set,p=[];for(let y of n){if(y.level==="component"){p.push(y);continue}u.add(y.path);let $=a.get(y.path);$?y.contentHash&&$.slice(0,sE)!==y.contentHash&&c.push(y.key):l.push(y.key)}let d=0,m=new Map,f=new Set;for(let y of s){let $=y.path.lastIndexOf("/"),x=$<0?"":y.path.slice(0,$);m.has(x)||m.set(x,new Set),m.get(x).add(y.path),u.has(y.path)||d++;let T=x;for(;T!==""&&!f.has(T);)f.add(T),T=T.includes("/")?T.slice(0,T.lastIndexOf("/")):""}let g=new Map;for(let y of u){let $=y.lastIndexOf("/"),x=$<0?"":y.slice(0,$);g.has(x)||g.set(x,new Set),g.get(x).add(y)}for(let y of p){if(!f.has(y.path)){l.push(y.key);continue}let $=g.get(y.path)??new Set,x=m.get(y.path)??new Set;($.size!==x.size||[...$].some(v=>!x.has(v)))&&c.push(y.key)}let h=[],k=Fh(e);if(k.size>0){let y=gn(e,"model/facts/annotations"),$=new Map(n.filter(x=>x.entityId).map(x=>[x.entityId,x.key]));if(pl(y))for(let x of ml(y).sort()){if(!x.endsWith(".md"))continue;let T=x.replace(/\.md$/,""),v=$.get(T);if(v)try{(fl(gn(y,x),"utf-8").match(/\bADR-(\d{3,4})\b/g)??[]).map(A=>`ADR-${A.slice(4).padStart(4,"0")}`).some(A=>k.has(A))&&h.push(v)}catch{}}}return{repo:r,builtFromCommit:o,headCommit:i,stale:[...new Set(c)].sort(),orphaned:[...new Set(l)].sort(),superseded:[...new Set(h)].sort(),newFiles:d}}var sE,Kh=S(()=>{"use strict";F();bo();sE=12});import{execFileSync as yE}from"node:child_process";import{mkdtempSync as wE,mkdirSync as kE,readFileSync as qh,rmSync as bE,writeFileSync as $E}from"node:fs";import{tmpdir as vE}from"node:os";import{dirname as xE,join as Yh}from"node:path";function Vh(t="codepipe-context"){let e=wE(Yh(vE(),"codepipe-ssh-")),r=Yh(e,"id_ed25519");try{return yE("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:qh(r,"utf-8"),publicKey:qh(`${r}.pub`,"utf-8").trim()}}finally{bE(e,{recursive:!0,force:!0})}}async function zh(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 Xh(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 Jh(t,e){kE(xE(t),{recursive:!0});let r=e.endsWith(`
713
713
  `)?e:e+`
714
- `;return $E(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var yl=S(()=>{"use strict"});import{existsSync as Zh,mkdirSync as Qh}from"node:fs";import{dirname as eg}from"node:path";import{simpleGit as yn}from"simple-git";function SE(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 EE(t,e){return e?.contextWrite?.token?{user:oo(t),secret:e.contextWrite.token}:t===Yr.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Yr.bitbucket?e?.bitbucket?.apiToken?{user:jt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function tg(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 rs))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 ns(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await oe(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new rs(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=EE($r(s.cloneUrl),r);if(a){let c=await TE({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 IE({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 TE(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=SE(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(Zh(`${r}/.git`)){let l=yn(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=fc(r);await l.reset(["--hard",`origin/${s}`]),mc(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Qh(eg(r),{recursive:!0}),await yn().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await rg(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 IE(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=Jh(i,n),a=Xh(e.cloneUrl),c=e.branch;try{if(Zh(`${r}/.git`)){let l=yn(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=fc(r);await l.reset(["--hard",`origin/${c}`]),mc(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Qh(eg(r),{recursive:!0}),await yn().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await yn(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await rg(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 rg(t){let e=yn(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 rs,wl=S(()=>{"use strict";F();je();Lt();yl();rs=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as RE}from"node:child_process";function CE(){try{return RE("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function og(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:CE(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var ig=S(()=>{"use strict"});import{homedir as PE}from"node:os";import{mkdirSync as AE,readFileSync as _E,writeFileSync as jE,existsSync as sg}from"node:fs";import{dirname as NE,join as bl}from"node:path";function OE(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function kt(t){let e=z("SANDBOX_CONFIG");if(e)return e;let r=bl(PE(),".codepipe","worker");return t?bl(r,"profiles",t,"config.json"):bl(r,"config.json")}function ag(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function Le(t){let e=kt(t),r=null;return sg(e)&&(r=JSON.parse(_E(e,"utf-8"))),r?(r.planningLane=OE(),r):null}function cg(t,e){let r=kt(e);AE(NE(r),{recursive:!0}),jE(r,JSON.stringify(t,null,2)+`
715
- `,{mode:384})}var os=S(()=>{"use strict";Be();sg(".env")&&process.loadEnvFile(".env")});import LE from"ws";var wn,$l=S(()=>{"use strict";wn=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};e&&(n.signal=e);let o=r?`${this.hubUrl}/jobs/claim?lane=${encodeURIComponent(r)}`:`${this.hubUrl}/jobs/claim`;return fetch(o,n)}async submitResult(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/jobs/result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});if(!r.ok)throw new Error(`submitResult failed: ${r.status} ${await r.text()}`)}async heartbeat(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e})};r&&(n.signal=r);let o=await fetch(`${this.hubUrl}/jobs/heartbeat`,n);if(o.status===410)return"claim_lost";if(!o.ok)throw new Error(`heartbeat failed: ${o.status} ${await o.text()}`);return"ok"}async releaseJob(e,r,n){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e,reason:r})};n&&(o.signal=n);let 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 LE(e)}}});import{hostname as ME}from"node:os";async function Pr(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 ${kt(t.profile)}.`),process.exit(1));let r=t.name??ME(),n=og({projects:t.projects??[],llm:t.llm??null}),o=new wn(t.hub.replace(/\/$/,"")),i=Ei(),s=Ge(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 ${kt(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 lg=S(()=>{"use strict";at();ig();os();$l()});function ug(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 is(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 dg(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 kn(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 ss=S(()=>{"use strict"});import{spawn as DE}from"node:child_process";function vl(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function BE(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 FE(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Ar(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function xl(t,e){let r=[{type:"text",text:t}];return e&&r.push({type:"text",text:e}),JSON.stringify({type:"user",message:{role:"user",content:r}})+`
716
- `}async function hg(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Dt;let r=kn(e.metadata),n=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",ug(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:vl(g,pg)})}else if(f==="tool_use"){let g=String(m.name??""),h=m.input?.file_path??m.input?.path,k=BE(h,e.workspaceDir);i({ts:u,kind:"tool",author:"agent",tool:g,...k?{file:k}:{}})}}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?vl(FE(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=DE(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"),fg)};e.signal?.addEventListener("abort",g,{once:!0});let h=null,k=()=>{h&&clearTimeout(h),h=setTimeout(()=>{m=!0,console.warn(`[claude:chat] idle for ${mg}ms \u2014 ending session`),p.kill("SIGTERM"),f=setTimeout(()=>p.kill("SIGKILL"),fg)},mg)},w=()=>{f&&clearTimeout(f),h&&clearTimeout(h),e.signal?.removeEventListener("abort",g)},$=!0,x=b=>{if(!(!$||p.stdin.destroyed))try{p.stdin.write(b)}catch{}};x(xl(e.prompt)),k(),(async()=>{try{for await(let b of e.interactive.inbox){if(d||!$)break;if(k(),b.kind==="user")i({ts:Date.now(),kind:"text",author:"user",text:vl(b.text,pg)}),x(xl(b.text,dg(r)));else{x(xl(UE)),$=!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),k(),T+=b;let R;for(;(R=T.indexOf(`
714
+ `;return $E(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var yl=S(()=>{"use strict"});import{existsSync as Zh,mkdirSync as Qh}from"node:fs";import{dirname as eg}from"node:path";import{simpleGit as yn}from"simple-git";function SE(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 EE(t,e){return e?.contextWrite?.token?{user:oo(t),secret:e.contextWrite.token}:t===Yr.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Yr.bitbucket?e?.bitbucket?.apiToken?{user:jt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function tg(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 rs))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 ns(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await oe(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new rs(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=EE($r(s.cloneUrl),r);if(a){let c=await TE({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 IE({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 TE(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=SE(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(Zh(`${r}/.git`)){let l=yn(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=fc(r);await l.reset(["--hard",`origin/${s}`]),mc(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Qh(eg(r),{recursive:!0}),await yn().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await rg(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 IE(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=Jh(i,n),a=Xh(e.cloneUrl),c=e.branch;try{if(Zh(`${r}/.git`)){let l=yn(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=fc(r);await l.reset(["--hard",`origin/${c}`]),mc(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Qh(eg(r),{recursive:!0}),await yn().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await yn(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await rg(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 rg(t){let e=yn(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 rs,wl=S(()=>{"use strict";F();je();Lt();yl();rs=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as RE}from"node:child_process";function CE(){try{return RE("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function og(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:CE(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var ig=S(()=>{"use strict"});import{homedir as PE}from"node:os";import{mkdirSync as AE,readFileSync as _E,writeFileSync as jE,existsSync as sg}from"node:fs";import{dirname as NE,join as bl}from"node:path";function OE(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function yt(t){let e=X("SANDBOX_CONFIG");if(e)return e;let r=bl(PE(),".codepipe","worker");return t?bl(r,"profiles",t,"config.json"):bl(r,"config.json")}function ag(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function Le(t){let e=yt(t),r=null;return sg(e)&&(r=JSON.parse(_E(e,"utf-8"))),r?(r.planningLane=OE(),r):null}function cg(t,e){let r=yt(e);AE(NE(r),{recursive:!0}),jE(r,JSON.stringify(t,null,2)+`
715
+ `,{mode:384})}var os=S(()=>{"use strict";Be();sg(".env")&&process.loadEnvFile(".env")});import LE from"ws";var wn,$l=S(()=>{"use strict";wn=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};e&&(n.signal=e);let o=r?`${this.hubUrl}/jobs/claim?lane=${encodeURIComponent(r)}`:`${this.hubUrl}/jobs/claim`;return fetch(o,n)}async submitResult(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/jobs/result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});if(!r.ok)throw new Error(`submitResult failed: ${r.status} ${await r.text()}`)}async heartbeat(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e})};r&&(n.signal=r);let o=await fetch(`${this.hubUrl}/jobs/heartbeat`,n);if(o.status===410)return"claim_lost";if(!o.ok)throw new Error(`heartbeat failed: ${o.status} ${await o.text()}`);return"ok"}async releaseJob(e,r,n){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e,reason:r})};n&&(o.signal=n);let 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 LE(e)}}});import{hostname as ME}from"node:os";async function Pr(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 ${yt(t.profile)}.`),process.exit(1));let r=t.name??ME(),n=og({projects:t.projects??[],llm:t.llm??null}),o=new wn(t.hub.replace(/\/$/,"")),i=Ei(),s=Ge(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 ${yt(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 lg=S(()=>{"use strict";at();ig();os();$l()});function ug(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 is(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 dg(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 kn(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 ss=S(()=>{"use strict"});import{spawn as DE}from"node:child_process";function vl(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function BE(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 FE(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Ar(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function xl(t,e){let r=[{type:"text",text:t}];return e&&r.push({type:"text",text:e}),JSON.stringify({type:"user",message:{role:"user",content:r}})+`
716
+ `}async function hg(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Dt;let r=kn(e.metadata),n=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",ug(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:vl(g,pg)})}else if(f==="tool_use"){let g=String(m.name??""),h=m.input?.file_path??m.input?.path,k=BE(h,e.workspaceDir);i({ts:u,kind:"tool",author:"agent",tool:g,...k?{file:k}:{}})}}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?vl(FE(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=DE(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"),fg)};e.signal?.addEventListener("abort",g,{once:!0});let h=null,k=()=>{h&&clearTimeout(h),h=setTimeout(()=>{m=!0,console.warn(`[claude:chat] idle for ${mg}ms \u2014 ending session`),p.kill("SIGTERM"),f=setTimeout(()=>p.kill("SIGKILL"),fg)},mg)},y=()=>{f&&clearTimeout(f),h&&clearTimeout(h),e.signal?.removeEventListener("abort",g)},$=!0,x=b=>{if(!(!$||p.stdin.destroyed))try{p.stdin.write(b)}catch{}};x(xl(e.prompt)),k(),(async()=>{try{for await(let b of e.interactive.inbox){if(d||!$)break;if(k(),b.kind==="user")i({ts:Date.now(),kind:"text",author:"user",text:vl(b.text,pg)}),x(xl(b.text,dg(r)));else{x(xl(UE)),$=!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),k(),T+=b;let R;for(;(R=T.indexOf(`
717
717
  `))!==-1;){let A=T.slice(0,R).trim();T=T.slice(R+1),A&&v(A)}}),p.stderr.on("data",b=>{s.push(b);for(let R of b.split(`
718
- `)){let A=R.trim();A&&console.warn(`[claude:chat:stderr] ${A}`)}}),p.on("error",b=>{w(),u(b)}),p.on("close",b=>{if(w(),d){u(new Dt);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:GE(a)})})})}function GE(t){let e=Kt();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=Ar(r.input_tokens),e.outputTokens=Ar(r.output_tokens),e.cacheReadInputTokens=Ar(r.cache_read_input_tokens),e.cacheCreationInputTokens=Ar(r.cache_creation_input_tokens)),e.totalCostUsd=Ar(t.total_cost_usd),e.numTurns=Ar(t.num_turns),e.durationMs=Ar(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var pg,fg,mg,UE,gg=S(()=>{"use strict";F();bn();ss();pg=16e3,fg=5e3,mg=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),UE="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 KE}from"node:child_process";import{existsSync as HE}from"node:fs";function qE(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function yg(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: ${or(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=zE(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=kg(o.content);console.log(`[claude] tool_result (error)${i?`: ${or(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)} ${or(JSON.stringify(e),200)}`),e}function YE(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(or(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(or(r.trim().split(`
718
+ `)){let A=R.trim();A&&console.warn(`[claude:chat:stderr] ${A}`)}}),p.on("error",b=>{y(),u(b)}),p.on("close",b=>{if(y(),d){u(new Dt);return}if(m){u(new Error("chat session ended: idle for too long without a reply"));return}T.trim()&&v(T.trim()),console.log(`[claude:chat] exit code=${b}`),l({artifactPaths:[],log:s.join(""),usage:GE(a)})})})}function GE(t){let e=Kt();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=Ar(r.input_tokens),e.outputTokens=Ar(r.output_tokens),e.cacheReadInputTokens=Ar(r.cache_read_input_tokens),e.cacheCreationInputTokens=Ar(r.cache_creation_input_tokens)),e.totalCostUsd=Ar(t.total_cost_usd),e.numTurns=Ar(t.num_turns),e.durationMs=Ar(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var pg,fg,mg,UE,gg=S(()=>{"use strict";F();bn();ss();pg=16e3,fg=5e3,mg=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),UE="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 KE}from"node:child_process";import{existsSync as HE}from"node:fs";function qE(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function yg(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: ${or(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=zE(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=kg(o.content);console.log(`[claude] tool_result (error)${i?`: ${or(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)} ${or(JSON.stringify(e),200)}`),e}function YE(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(or(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(or(r.trim().split(`
719
719
  `).slice(-5).join(`
720
- `),500)),n.join(" \u2014 ")}function VE(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 kg(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function zE(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=${or(r,80)}`}return""}function or(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function Ke(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function XE(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=Ke(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:Ke(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 JE(t,e,r,n){let o=Kt(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=Ke(i.input_tokens),o.outputTokens=Ke(i.output_tokens),o.cacheReadInputTokens=Ke(i.cache_read_input_tokens),o.cacheCreationInputTokens=Ke(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=Ke(t?.total_cost_usd),o.numTurns=t&&Ke(t.num_turns)>0?Ke(t.num_turns):r,o.durationMs=Ke(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}function ZE(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:or(c,wg)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,p=QE(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?or(kg(s.content),wg):"";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 QE(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 $n,Dt,WE,Po,wg,bn=S(()=>{"use strict";F();gg();ss();$n=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Dt=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},WE=5e3;Po=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return hg(this.binary,e);if(e.signal?.aborted)throw new Dt;let r=["-p",qE(e.prompt),"--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",is(kn(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=XE(f.rate_limit_info);g&&(!l||g.utilization>l.utilization)&&(l=g);return}if(f.type==="assistant"){let g=f.message;typeof g?.model=="string"&&(c=g.model);let h=g?.usage;h&&(a+=1,s.input+=Ke(h.input_tokens),s.output+=Ke(h.output_tokens),s.cacheRead+=Ke(h.cache_read_input_tokens),s.cacheCreate+=Ke(h.cache_creation_input_tokens))}}},p=e.role,d=e.onActivity,m=f=>{if(d)for(let g of ZE(f,e.workspaceDir))try{d(g)}catch{}};return d?.({ts:Date.now(),kind:"start",text:`${p} job started`}),console.log(`[claude] spawn ${this.binary} role=${p}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((f,g)=>{let h=KE(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{},CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:"1800000"}});h.stdout.setEncoding("utf-8"),h.stderr.setEncoding("utf-8");let k=!1,w=null,$=()=>{k=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${p}`),h.kill("SIGTERM"),w=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),h.kill("SIGKILL")},WE)};e.signal?.addEventListener("abort",$,{once:!0});let x=()=>{w&&clearTimeout(w),e.signal?.removeEventListener("abort",$)},T="";h.stdout.on("data",v=>{n.push(v),T+=v;let b;for(;(b=T.indexOf(`
720
+ `),500)),n.join(" \u2014 ")}function VE(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 kg(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function zE(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=${or(r,80)}`}return""}function or(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function Ke(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function XE(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=Ke(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:Ke(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 JE(t,e,r,n){let o=Kt(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=Ke(i.input_tokens),o.outputTokens=Ke(i.output_tokens),o.cacheReadInputTokens=Ke(i.cache_read_input_tokens),o.cacheCreationInputTokens=Ke(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=Ke(t?.total_cost_usd),o.numTurns=t&&Ke(t.num_turns)>0?Ke(t.num_turns):r,o.durationMs=Ke(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}function ZE(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:or(c,wg)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,p=QE(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?or(kg(s.content),wg):"";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 QE(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 $n,Dt,WE,Po,wg,bn=S(()=>{"use strict";F();gg();ss();$n=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Dt=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},WE=5e3;Po=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return hg(this.binary,e);if(e.signal?.aborted)throw new Dt;let r=["-p",qE(e.prompt),"--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",is(kn(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=XE(f.rate_limit_info);g&&(!l||g.utilization>l.utilization)&&(l=g);return}if(f.type==="assistant"){let g=f.message;typeof g?.model=="string"&&(c=g.model);let h=g?.usage;h&&(a+=1,s.input+=Ke(h.input_tokens),s.output+=Ke(h.output_tokens),s.cacheRead+=Ke(h.cache_read_input_tokens),s.cacheCreate+=Ke(h.cache_creation_input_tokens))}}},p=e.role,d=e.onActivity,m=f=>{if(d)for(let g of ZE(f,e.workspaceDir))try{d(g)}catch{}};return d?.({ts:Date.now(),kind:"start",text:`${p} job started`}),console.log(`[claude] spawn ${this.binary} role=${p}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((f,g)=>{let h=KE(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{},CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:"1800000"}});h.stdout.setEncoding("utf-8"),h.stderr.setEncoding("utf-8");let k=!1,y=null,$=()=>{k=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${p}`),h.kill("SIGTERM"),y=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),h.kill("SIGKILL")},WE)};e.signal?.addEventListener("abort",$,{once:!0});let x=()=>{y&&clearTimeout(y),e.signal?.removeEventListener("abort",$)},T="";h.stdout.on("data",v=>{n.push(v),T+=v;let b;for(;(b=T.indexOf(`
721
721
  `))!==-1;){let R=T.slice(0,b).trim();if(T=T.slice(b+1),R){let A=yg(R);u(A),A&&m(A)}}}),h.stderr.on("data",v=>{n.push(v),o.push(v);for(let b of v.split(`
722
722
  `)){let R=b.trim();R&&console.warn(`[claude:stderr] ${R}`)}}),h.on("error",v=>{x(),g(v)}),h.on("close",v=>{if(x(),k){g(new Dt);return}if(T.trim()){let R=yg(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,A=typeof i?.subtype=="string"?i.subtype:void 0,G=typeof i?.result=="string"?i.result:void 0;g(new $n(YE(v,i,o.join("")),{code:v,apiErrorStatus:R,subtype:A,resultText:G,retryAfterMs:VE(i)}));return}console.log("[claude] exit code=0"),f({artifactPaths:[],log:n.join(""),usage:JE(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("/")&&HE(n))}};wg=200});import{mkdirSync as eT,writeFileSync as vn}from"node:fs";import{dirname as tT,join as xn}from"node:path";function bg(t,e,r){let n=xn(t,e);eT(tT(n),{recursive:!0}),vn(n,r)}function rT(t,e,r){return`# ${t} \u2014 Estimate
723
723
 
@@ -836,14 +836,14 @@ ${b.content}
836
836
  ### \`${ar(v.key)}\`${A}
837
837
 
838
838
  ${R}
839
- `;if(!l(G))break;f=!0}let g=$e(e),h=ms(i,v=>v.startsWith("task::")&&v!==g).slice(0,aI),k=!1;for(let v of h){let b=o.events.get(ar(v.key));if(!b)continue;let R=[...b.files].filter(y=>!m.has(y.key)&&(!y.entityId||!o.orphanedEntities.has(y.entityId))).sort((y,B)=>(B.churn??0)-(y.churn??0)||(y.key<B.key?-1:1)).slice(0,3).map(y=>`\`${ar(y.key)}\``).join(", "),A="",G=b.links?.solution??[`tasks/${b.taskKey}/PLAN.md`,`tasks/${b.taskKey}/SOLUTION.md`].find(y=>jl(gs(n,y)))??`tasks/${b.taskKey}/PLAN.md`,J=gs(n,G);if(jl(J))try{A=`
840
- > ${Cy(J,"utf-8").trim().slice(0,lI).replace(/\n+/g," ").trim()}\u2026
841
- > _(full text: \`${G}\`)_`}catch{}let P=`${k?"":`
839
+ `;if(!l(G))break;f=!0}let g=$e(e),h=ms(i,v=>v.startsWith("task::")&&v!==g).slice(0,aI),k=!1;for(let v of h){let b=o.events.get(ar(v.key));if(!b)continue;let R=[...b.files].filter(w=>!m.has(w.key)&&(!w.entityId||!o.orphanedEntities.has(w.entityId))).sort((w,U)=>(U.churn??0)-(w.churn??0)||(w.key<U.key?-1:1)).slice(0,3).map(w=>`\`${ar(w.key)}\``).join(", "),A="",G=b.links?.solution??[`tasks/${b.taskKey}/PLAN.md`,`tasks/${b.taskKey}/SOLUTION.md`].find(w=>jl(gs(n,w)))??`tasks/${b.taskKey}/PLAN.md`,V=gs(n,G);if(jl(V))try{A=`
840
+ > ${Cy(V,"utf-8").trim().slice(0,lI).replace(/\n+/g," ").trim()}\u2026
841
+ > _(full text: \`${G}\`)_`}catch{}let C=`${k?"":`
842
842
  ## Related past tasks
843
843
  `}
844
- - **${b.taskKey}**${b.title?` \u2014 ${b.title}`:""}${b.date?` (${b.date})`:""}, ${hs(v)}. Files: ${R||"\u2014"}.${A}`;if(!l(P))break;k=!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)},$=ms(i,v=>v.startsWith("code:")),x=$.filter(w).slice(0,cI);if(x.length>0){let v=["","## Files likely involved",""];for(let b of x){let R=`- \`${ar(b.key)}\` \u2014 ${hs(b)}`;if(c+_l(v.join(`
844
+ - **${b.taskKey}**${b.title?` \u2014 ${b.title}`:""}${b.date?` (${b.date})`:""}, ${hs(v)}. Files: ${R||"\u2014"}.${A}`;if(!l(C))break;k=!0}let y=v=>{if(m.has(v.key))return!1;let b=o.nodes.get(v.key)?.entityId;return!b||!o.orphanedEntities.has(b)},$=ms(i,v=>v.startsWith("code:")),x=$.filter(y).slice(0,cI);if(x.length>0){let v=["","## Files likely involved",""];for(let b of x){let R=`- \`${ar(b.key)}\` \u2014 ${hs(b)}`;if(c+_l(v.join(`
845
845
  `))+_l(R)>s)break;v.push(R)}v.length>3&&l(v.join(`
846
- `))}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=>`- \`${ar(b.key)}\` \u2014 ${hs(b)}${m.has(b.key)?" (changed since the map was built)":" (file gone)"}`)];l(v.join(`
846
+ `))}let T=$.filter(v=>!y(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=>`- \`${ar(b.key)}\` \u2014 ${hs(b)}${m.has(b.key)?" (changed since the map was built)":" (file gone)"}`)];l(v.join(`
847
847
  `))}return a.length<=1?null:a.join(`
848
848
  `)+`
849
849
  `}var aI,cI,lI,Ay=S(()=>{"use strict";F();aI=5,cI=300,lI=400});var Oy={};We(Oy,{assembleContextPack:()=>mI});import{createHash as dI}from"node:crypto";import{existsSync as _y,readFileSync as jy}from"node:fs";import{join as Ny}from"node:path";function pI(t){return dI("sha1").update(`blob ${t.length}\0`).update(t).digest("hex")}function fI(t,e,r){let n=new Set;for(let o of e.keys()){let i=te(o);if(i?.level!=="code")continue;let s=t.nodes.get(o);if(!s?.contentHash)continue;let a=r.get(i.repo);if(!a)continue;let c=Ny(a,i.path);try{if(!_y(c)){n.add(o);continue}pI(jy(c)).startsWith(s.contentHash)||n.add(o)}catch{}}return n}function mI(t){let e=$y(t.contextDir);if(e.empty)return null;let r="",n=Ny(t.contextDir,`tasks/${t.taskKey}/task.md`);if(_y(n))try{r=jy(n,"utf-8")}catch{r=""}let o=Ey({taskKey:t.taskKey,title:t.title,text:r,model:e});if(o.size===0)return null;let i=Iy(e,o),s=t.repoDirs?fI(e,i,t.repoDirs):new Set;return Py({taskKey:t.taskKey,title:t.title,contextDir:t.contextDir,model:e,activated:i,staleKeys:s,...t.budgetTokens!==void 0?{budgetTokens:t.budgetTokens}:{}})}var Ly=S(()=>{"use strict";F();vy();Ty();Ry();Ay()});var My={};We(My,{SKILLS_DIR:()=>Nl,loadSkills:()=>TI,materializeSkills:()=>II,renderSkillsBlock:()=>RI});import{cpSync as hI,existsSync as gI,mkdirSync as yI,readFileSync as wI,readdirSync as kI}from"node:fs";import{dirname as bI,join as Cn}from"node:path";import{fileURLToPath as $I}from"node:url";import{parse as vI}from"yaml";function SI(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
@@ -859,17 +859,17 @@ ${R}
859
859
  `):"";return`${r}${t.body}
860
860
  ${n}`}function ZI(t,e,r,n){let o=Ca(e,r);if(o.length===0)return{roles:[],files:[]};let i=Ll(t,Ml);zI(i,{recursive:!0});let s=[];for(let a of o)XI(Ll(i,`${a.name}.md`),JI(a,n)),s.push(`${Ml}/${a.name}.md`);return{roles:o,files:s}}function QI(t,e){return t.roles.length===0?"":["## The panel \u2014 run these critics first","","This project reviews through a panel of roles. Each is available to you as a","subagent with its own narrow view and its own reading list:","",t.roles.map(n=>`- **${n.name}** \u2014 ${n.description}`).join(`
861
861
  `),"","Delegate to **every** role above, one at a time, giving each the change under","review. Then do your own job on what comes back:","",`1. Save each role's findings verbatim as \`${e}/<role>.md\`.`,"2. **Deduplicate.** Two roles reporting the same defect is one finding, not two.","3. **Filter.** A finding earns a round-trip only if it is a real defect, a"," regression or a convention the project actually enforces. Taste-level notes"," go in the summary, never in the remarks.","4. **Decide.** The verdict is yours, not a vote: a role can be wrong, and you"," are the one who read the code. When you overrule a role, say why in the"," summary.","","A role that returns nothing is a normal outcome \u2014 do not manufacture findings","to justify the panel.",""].join(`
862
- `)}var Ml,zy=S(()=>{"use strict";F();Ml=".claude/agents"});var Jy={};We(Jy,{COUNCIL_ANSWER_PATH:()=>Xy,readCouncilVerdict:()=>rR});import{readFileSync as eR}from"node:fs";import{join as tR}from"node:path";function rR(t){let e;try{e=eR(tR(t,Xy),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var Xy,Zy=S(()=>{"use strict";Xy="meta/council-answer.json"});var ew={};We(ew,{QUEUE_PLAN_PATH:()=>Qy,readQueuePlan:()=>iR});import{readFileSync as nR}from"node:fs";import{join as oR}from"node:path";function iR(t){let e;try{e=nR(oR(t,Qy),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var Qy,tw=S(()=>{"use strict";Qy="meta/queue-plan.json"});import{mkdirSync as rw,readFileSync as ys,readdirSync as sR,writeFileSync as nw}from"node:fs";import{homedir as aR}from"node:os";import{dirname as cR,join as It}from"node:path";function uR(t){let e=Buffer.from(t,"utf-8");if(e.length<=ws)return t;let r=Math.floor(ws/4),n=ws-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}
862
+ `)}var Ml,zy=S(()=>{"use strict";F();Ml=".claude/agents"});var Jy={};We(Jy,{COUNCIL_ANSWER_PATH:()=>Xy,readCouncilVerdict:()=>rR});import{readFileSync as eR}from"node:fs";import{join as tR}from"node:path";function rR(t){let e;try{e=eR(tR(t,Xy),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var Xy,Zy=S(()=>{"use strict";Xy="meta/council-answer.json"});var ew={};We(ew,{QUEUE_PLAN_PATH:()=>Qy,readQueuePlan:()=>iR});import{readFileSync as nR}from"node:fs";import{join as oR}from"node:path";function iR(t){let e;try{e=nR(oR(t,Qy),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var Qy,tw=S(()=>{"use strict";Qy="meta/queue-plan.json"});import{mkdirSync as rw,readFileSync as ys,readdirSync as sR,writeFileSync as nw}from"node:fs";import{homedir as aR}from"node:os";import{dirname as cR,join as Tt}from"node:path";function uR(t){let e=Buffer.from(t,"utf-8");if(e.length<=ws)return t;let r=Math.floor(ws/4),n=ws-r,o=e.subarray(0,r).toString("utf-8"),i=e.subarray(e.length-n).toString("utf-8"),s=e.length-r-n;return`${o}
863
863
 
864
864
  \u2026 [${s} bytes elided \u2014 log capped at ${ws} bytes for upload] \u2026
865
865
 
866
- ${i}`}function dR(){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 Oo(t={}){let e=Le(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,n=e.sandboxId,o=e.llm,i=ag(t.profile,e.sandboxId,!!z("SANDBOX_CONFIG")),s=It(aR(),".codepipe","logs"),a=si("SANDBOX_LOG",i,s);if(a.enabled){let P=new Qr(a);ai(P),console.log(`[log] file logging \u2192 ${P.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${qe} (protocol ${pt})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=$g(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=Tg();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let u=new wn(e.hubUrl,e.token),p=!1,d=new AbortController,m=new Map,f=null,g=null,h=!1,k=()=>{let P=u.openControlSocket();return f=P,P.on("open",()=>{console.log("[ws] connected");let y={type:"sandbox_hello",platformVersion:qe,protocolVersion:pt};P.send(JSON.stringify(y))}),P.on("message",y=>{let B=y.toString("utf-8"),_=null;try{let W=JSON.parse(B);W&&typeof W=="object"&&(_=W)}catch{}if(_&&_.type==="hello"){let W=_;g=Wn(W.protocolVersion);let Y=g?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${W.platformVersion} (protocol ${W.protocolVersion}) \u2014 ${Y}`),g&&(h=!1);return}if(_&&_.type==="pause_job"){let W=typeof _.jobId=="string"?_.jobId:"",Y=W?m.get(W):void 0;Y?(console.warn(`[ws] pause_job ${W} \u2014 aborting agent`),Y.paused=!0,Y.abort.abort()):console.log(`[ws] pause_job ${W} \u2014 not a running job, ignoring`),W&&P.send(JSON.stringify({type:"job_paused",jobId:W}));return}if(_&&(_.type==="chat_user_message"||_.type==="chat_finalize")){let W=typeof _.jobId=="string"?_.jobId:"",Y=W?m.get(W):void 0;if(Y?.chatInbox)if(_.type==="chat_user_message"){let de=typeof _.text=="string"?_.text:"";de.trim()&&Y.chatInbox.push({kind:"user",text:de})}else Y.chatInbox.finalize();else console.log(`[ws] ${String(_.type)} ${W} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${B}`)}),P.on("close",(y,B)=>{console.log(`[ws] closed code=${y} reason=${B?.toString()||""}`),f===P&&(f=null),!p&&setTimeout(k,2e3)}),P.on("error",y=>console.warn(`[ws] error: ${y.message}`)),P},w=k(),$=async P=>{for(;!p;){if(g===!1){h||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${qe}, protocol ${pt}) \u2014 not claiming jobs until versions align.`),h=!0),await new Promise(y=>setTimeout(y,5e3));continue}try{let y=await u.claim(d.signal,P);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:${P}] ${y.status} \u2014 backoff 5s`),await new Promise(_=>setTimeout(_,5e3));continue}let B=await y.json();await x(u,B)}catch(y){if(d.signal.aborted)break;let B=y instanceof Error?y.message:String(y);console.warn(`[claim:${P}] error: ${B} \u2014 backoff 5s`),await new Promise(_=>setTimeout(_,5e3))}}};async function x(P,y){let B={abort:new AbortController,paused:!1};y.role==="chat"&&(B.chatInbox=dR()),m.set(y.jobId,B);let _=!1,W=null,Y=null,de=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),lt=async()=>{try{await P.heartbeat(y.jobId)==="claim_lost"&&(_=!0,console.warn(`[job] ${y.jobId} claim lost \u2014 HUB sweeper took it`))}catch(M){let ie=M instanceof Error?M.message:String(M);console.warn(`[job] ${y.jobId} heartbeat error: ${ie}`)}};lt();let ut=setInterval(()=>{lt()},de),L=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 U=[],O=null,q=400,K=25,E=500,I=()=>{if(O&&(clearTimeout(O),O=null),U.length===0)return;let M=U.splice(0,U.length),ie=f;if(!ie||ie.readyState!==ie.OPEN)return;let Re={type:"agent_activity",jobId:y.jobId,taskId:y.taskId,projectId:y.projectId,role:y.role,phase:y.phase,events:M};try{ie.send(JSON.stringify(Re))}catch{}},re=M=>{U.push(M),U.length>E&&U.shift(),U.length>=K?I():O||(O=setTimeout(I,q))},ne=y.role==="analysis"&&y.taskId.startsWith("draft::")?y.taskId.slice(7):null,Gt=new Set,j=null;try{if(!c){_||await P.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:L,finishedAt:new Date().toISOString()});return}if(!vg(o,y.provider??null)){_||await P.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${y.provider??"claude"}"`},startedAt:L,finishedAt:new Date().toISOString()});return}let M=yy(y.jobId);console.log(`[job] ${y.jobId} workspace=${M.dir}`);let ie=T(y,r);W=ie.gitCreds,Y=ie.contextGitCreds;let Re=W?.env,pr=ie.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:ie.claudeOauthToken}:void 0,Ae=[],se=null,Os=null;try{let N=y.role==="build"?"clone":"worktree";Ae=await ty(M.dir,y.projectId,y.projectRepos,N,Re,n);let D=await ry(M.dir,y.projectId,y.contextRepo,"worktree",Re,n);Os=D,se=D?.workspacePath??null}catch(N){let D=N instanceof Error?N.message:String(N);console.warn(`[job] ${y.jobId} materialize failed: ${D}`),_||await P.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${D}`},startedAt:L,finishedAt:new Date().toISOString()}),M.dispose();return}let Bn=y.model;y.role==="build"&&y.modelDiscovery&&!iy(se)&&(Bn=y.modelDiscovery,console.log(`[job] ${y.jobId} BUILD discovery (no steps in ${Cl}) \u2014 model=${Bn}`));let au=async()=>{if(!y.deliveries||y.deliveries.length===0)return[];let N=y.contextRepo?.cloneUrl;if(!N||!Re)throw new Error(N?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let D=[];for(let Q of y.deliveries){let Z=Ae.find(le=>le.name===Q.name);if(Z){if(y.role==="implement"&&Q.baseSha&&Q.baseSha!==Z.baseSha){let le=await Zg(Z,Q.deliveryRef,Q.deliverySha,Q.baseSha,N,Re);console.log(`[job] ${y.jobId} ${Z.name}: base moved ${Q.baseSha.slice(0,10)} \u2192 ${Z.baseSha.slice(0,10)} \u2014 re-applied delivery ${Q.deliverySha.slice(0,10)} (${le.length} conflicted file(s))`),le.length>0&&D.push(`- **${Z.name}**:`,...le.map(Qe=>` - \`${Qe}\``));continue}await Jg(Z,Q.deliveryRef,Q.deliverySha,N,Re),console.log(`[job] ${y.jobId} ${Z.name}: checked out delivery ${Q.deliverySha.slice(0,10)} for ${y.role}`)}}return D},Ls=[];if(y.role==="build"||y.role==="implement"||y.role==="code-review")try{Ls=await au()}catch(N){let D=N instanceof Error?N.message:String(N);console.warn(`[job] ${y.jobId} delivery checkout failed: ${D}`),_||await P.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${D}`},startedAt:L,finishedAt:new Date().toISOString()}),M.dispose();return}let Ms=y.role==="resolve-conflict"?y.metadata?.taskBranchByRepo??{}:{},cu="";if(y.role==="resolve-conflict"){if(!Ae.some(N=>Ms[N.name])){let N="resolve-conflict job carries no task branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${y.jobId} ${N}`),_||await P.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:N},startedAt:L,finishedAt:new Date().toISOString()}),M.dispose();return}try{let N=[];for(let D of Ae){let Q=Ms[D.name];if(!Q)continue;let Z=await Rl(D,Q,Re);console.log(`[job] ${y.jobId} ${D.name}: merged ${Q} into ${D.ref} \u2014 ${Z.length} conflicted file(s)`),Z.length>0?N.push(`- **${D.name}**:`,...Z.map(le=>` - \`${le}\``)):N.push(`- **${D.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}cu=`
866
+ ${i}`}function dR(){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 Oo(t={}){let e=Le(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,n=e.sandboxId,o=e.llm,i=ag(t.profile,e.sandboxId,!!X("SANDBOX_CONFIG")),s=Tt(aR(),".codepipe","logs"),a=si("SANDBOX_LOG",i,s);if(a.enabled){let C=new Qr(a);ai(C),console.log(`[log] file logging \u2192 ${C.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${qe} (protocol ${ut})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=$g(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=Tg();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let u=new wn(e.hubUrl,e.token),p=!1,d=new AbortController,m=new Map,f=null,g=null,h=!1,k=()=>{let C=u.openControlSocket();return f=C,C.on("open",()=>{console.log("[ws] connected");let w={type:"sandbox_hello",platformVersion:qe,protocolVersion:ut};C.send(JSON.stringify(w))}),C.on("message",w=>{let U=w.toString("utf-8"),_=null;try{let H=JSON.parse(U);H&&typeof H=="object"&&(_=H)}catch{}if(_&&_.type==="hello"){let H=_;g=Wn(H.protocolVersion);let z=g?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${H.platformVersion} (protocol ${H.protocolVersion}) \u2014 ${z}`),g&&(h=!1);return}if(_&&_.type==="pause_job"){let H=typeof _.jobId=="string"?_.jobId:"",z=H?m.get(H):void 0;z?(console.warn(`[ws] pause_job ${H} \u2014 aborting agent`),z.paused=!0,z.abort.abort()):console.log(`[ws] pause_job ${H} \u2014 not a running job, ignoring`),H&&C.send(JSON.stringify({type:"job_paused",jobId:H}));return}if(_&&(_.type==="chat_user_message"||_.type==="chat_finalize")){let H=typeof _.jobId=="string"?_.jobId:"",z=H?m.get(H):void 0;if(z?.chatInbox)if(_.type==="chat_user_message"){let de=typeof _.text=="string"?_.text:"";de.trim()&&z.chatInbox.push({kind:"user",text:de})}else z.chatInbox.finalize();else console.log(`[ws] ${String(_.type)} ${H} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${U}`)}),C.on("close",(w,U)=>{console.log(`[ws] closed code=${w} reason=${U?.toString()||""}`),f===C&&(f=null),!p&&setTimeout(k,2e3)}),C.on("error",w=>console.warn(`[ws] error: ${w.message}`)),C},y=k(),$=async C=>{for(;!p;){if(g===!1){h||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${qe}, protocol ${ut}) \u2014 not claiming jobs until versions align.`),h=!0),await new Promise(w=>setTimeout(w,5e3));continue}try{let w=await u.claim(d.signal,C);if(w.status===204)continue;if(w.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(!w.ok){console.warn(`[claim:${C}] ${w.status} \u2014 backoff 5s`),await new Promise(_=>setTimeout(_,5e3));continue}let U=await w.json();await x(u,U)}catch(w){if(d.signal.aborted)break;let U=w instanceof Error?w.message:String(w);console.warn(`[claim:${C}] error: ${U} \u2014 backoff 5s`),await new Promise(_=>setTimeout(_,5e3))}}};async function x(C,w){let U={abort:new AbortController,paused:!1};w.role==="chat"&&(U.chatInbox=dR()),m.set(w.jobId,U);let _=!1,H=null,z=null,de=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),Rt=async()=>{try{await C.heartbeat(w.jobId)==="claim_lost"&&(_=!0,console.warn(`[job] ${w.jobId} claim lost \u2014 HUB sweeper took it`))}catch(L){let ie=L instanceof Error?L.message:String(L);console.warn(`[job] ${w.jobId} heartbeat error: ${ie}`)}};Rt();let kt=setInterval(()=>{Rt()},de),M=new Date().toISOString();console.log(`[job] ${w.jobId} claimed \u2014 role=${w.role} task=${w.taskId} phase=${w.phase}`),console.log(`[job] ${w.jobId} prompt (${w.prompt.length} chars):`),console.log(v(w.prompt," \u2502 "));let B=[],O=null,q=400,K=25,E=500,I=()=>{if(O&&(clearTimeout(O),O=null),B.length===0)return;let L=B.splice(0,B.length),ie=f;if(!ie||ie.readyState!==ie.OPEN)return;let Re={type:"agent_activity",jobId:w.jobId,taskId:w.taskId,projectId:w.projectId,role:w.role,phase:w.phase,events:L};try{ie.send(JSON.stringify(Re))}catch{}},re=L=>{B.push(L),B.length>E&&B.shift(),B.length>=K?I():O||(O=setTimeout(I,q))},ne=w.role==="analysis"&&w.taskId.startsWith("draft::")?w.taskId.slice(7):null,Gt=new Set,j=null;try{if(!c){_||await C.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:M,finishedAt:new Date().toISOString()});return}if(!vg(o,w.provider??null)){_||await C.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${w.provider??"claude"}"`},startedAt:M,finishedAt:new Date().toISOString()});return}let L=yy(w.jobId);console.log(`[job] ${w.jobId} workspace=${L.dir}`);let ie=T(w,r);H=ie.gitCreds,z=ie.contextGitCreds;let Re=H?.env,pr=ie.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:ie.claudeOauthToken}:void 0,Ae=[],se=null,Os=null;try{let N=w.role==="build"?"clone":"worktree";Ae=await ty(L.dir,w.projectId,w.projectRepos,N,Re,n);let D=await ry(L.dir,w.projectId,w.contextRepo,"worktree",Re,n);Os=D,se=D?.workspacePath??null}catch(N){let D=N instanceof Error?N.message:String(N);console.warn(`[job] ${w.jobId} materialize failed: ${D}`),_||await C.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${D}`},startedAt:M,finishedAt:new Date().toISOString()}),L.dispose();return}let Bn=w.model;w.role==="build"&&w.modelDiscovery&&!iy(se)&&(Bn=w.modelDiscovery,console.log(`[job] ${w.jobId} BUILD discovery (no steps in ${Cl}) \u2014 model=${Bn}`));let au=async()=>{if(!w.deliveries||w.deliveries.length===0)return[];let N=w.contextRepo?.cloneUrl;if(!N||!Re)throw new Error(N?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let D=[];for(let Q of w.deliveries){let Z=Ae.find(le=>le.name===Q.name);if(Z){if(w.role==="implement"&&Q.baseSha&&Q.baseSha!==Z.baseSha){let le=await Zg(Z,Q.deliveryRef,Q.deliverySha,Q.baseSha,N,Re);console.log(`[job] ${w.jobId} ${Z.name}: base moved ${Q.baseSha.slice(0,10)} \u2192 ${Z.baseSha.slice(0,10)} \u2014 re-applied delivery ${Q.deliverySha.slice(0,10)} (${le.length} conflicted file(s))`),le.length>0&&D.push(`- **${Z.name}**:`,...le.map(Qe=>` - \`${Qe}\``));continue}await Jg(Z,Q.deliveryRef,Q.deliverySha,N,Re),console.log(`[job] ${w.jobId} ${Z.name}: checked out delivery ${Q.deliverySha.slice(0,10)} for ${w.role}`)}}return D},Ls=[];if(w.role==="build"||w.role==="implement"||w.role==="code-review")try{Ls=await au()}catch(N){let D=N instanceof Error?N.message:String(N);console.warn(`[job] ${w.jobId} delivery checkout failed: ${D}`),_||await C.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${D}`},startedAt:M,finishedAt:new Date().toISOString()}),L.dispose();return}let Ms=w.role==="resolve-conflict"?w.metadata?.taskBranchByRepo??{}:{},cu="";if(w.role==="resolve-conflict"){if(!Ae.some(N=>Ms[N.name])){let N="resolve-conflict job carries no task branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${w.jobId} ${N}`),_||await C.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:N},startedAt:M,finishedAt:new Date().toISOString()}),L.dispose();return}try{let N=[];for(let D of Ae){let Q=Ms[D.name];if(!Q)continue;let Z=await Rl(D,Q,Re);console.log(`[job] ${w.jobId} ${D.name}: merged ${Q} into ${D.ref} \u2014 ${Z.length} conflicted file(s)`),Z.length>0?N.push(`- **${D.name}**:`,...Z.map(le=>` - \`${le}\``)):N.push(`- **${D.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}cu=`
867
867
 
868
868
  ## Conflicts to resolve
869
869
 
870
870
  `+(N.length>0?N.join(`
871
871
  `):"(no task branches to merge)")+`
872
- `}catch(N){let D=N instanceof Error?N.message:String(N);console.warn(`[job] ${y.jobId} conflict merge failed: ${D}`),_||await P.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${D}`},startedAt:L,finishedAt:new Date().toISOString()}),M.dispose();return}}let Ds=null;if(y.contextPack&&se)try{let{assembleContextPack:N}=await Promise.resolve().then(()=>(Ly(),Oy)),D=N({contextDir:se,taskKey:String(y.metadata?.trackerIssueKey??y.taskId.split(":")[1]??""),title:String(y.metadata?.taskTitle??""),repoDirs:new Map(Ae.map(Q=>[Q.name,Q.workspacePath]))});D?(rw(It(M.dir,"meta"),{recursive:!0}),nw(It(M.dir,"meta","context-pack.md"),D),Ds=D,console.log(`[job] ${y.jobId} context pack: ${D.length} chars \u2192 meta/context-pack.md`)):console.log(`[job] ${y.jobId} context pack: model empty or no signal \u2014 skipped`)}catch(N){let D=N instanceof Error?N.message:String(N);console.warn(`[job] ${y.jobId} context pack failed (non-fatal): ${D}`)}let lu="",Wo=null,Us=null;try{let{loadSkills:N,materializeSkills:D,renderSkillsBlock:Q}=await Promise.resolve().then(()=>(Dy(),My)),Z=y.skills??{bundled:!0,context:!0,repo:!0},le=N({contextDir:se,repoDirs:Ae.map(et=>et.workspacePath),sources:Z});for(let et of le.errors)console.warn(`[job] ${y.jobId} skill ${et.source}: ${et.error}`);let Qe=D(M.dir,le.skills),he=["implement","rework","testing"].includes(y.role)?La(Oa(R(se,y.taskId))):[];lu=Q(le.skills,he),Qe.length>0&&console.log(`[job] ${y.jobId} skills: ${le.skills.map(et=>et.name).join(", ")}`);let{parseMarketplaces:Ue,enabledPluginsSetting:Or}=await Promise.resolve().then(()=>(F(),Id)),{sources:Lr,errors:Gn}=Ue(Z.marketplaces??[]);for(let et of Gn)console.warn(`[job] ${y.jobId} marketplace ${et}`);if(Lr.length>0&&(Z.plugins??[]).length>0){let{seedMarketplaces:et}=await Promise.resolve().then(()=>(Ky(),Gy)),Mr=await et(Lr);for(let ee of Mr.errors)console.warn(`[job] ${y.jobId} marketplace ${ee.repo}: ${ee.error}`);let{enabled:Dr,unknown:Ur}=Or(Z.plugins??[],Mr.ready);for(let ee of Ur)console.warn(`[job] ${y.jobId} plugin ${ee}: no such marketplace in this project`);Mr.dir&&Object.keys(Dr).length>0&&(Wo=Mr.dir,Us={enabledPlugins:Dr},console.log(`[job] ${y.jobId} plugins: ${Object.keys(Dr).join(", ")}`))}}catch(N){let D=N instanceof Error?N.message:String(N);console.warn(`[job] ${y.jobId} skills unavailable (non-fatal): ${D}`)}let uu="";if(["code-review","council","analyze","testing"].includes(y.role))try{let{loadRoles:N}=await Promise.resolve().then(()=>(Yy(),qy)),{materializeRoleAgents:D,renderRolesBlock:Q}=await Promise.resolve().then(()=>(zy(),Vy)),Z=N(se);for(let Ue of Z.errors)console.warn(`[job] ${y.jobId} role ${Ue.file}: ${Ue.error}`);let le=y.role==="council"?"council":y.role==="analyze"?"plan_review":"code_review",Qe=y.role==="council"?"council":y.role==="analyze"?"plan-review":y.role==="testing"?"testing":"code-review",he=D(M.dir,Z.roles,le,se);uu=Q(he,Qe),console.log(`[job] ${y.jobId} review panel: ${he.roles.length>0?he.roles.map(Ue=>Ue.name).join(", "):"(no roles)"}`)}catch(N){let D=N instanceof Error?N.message:String(N);console.warn(`[job] ${y.jobId} review panel unavailable (non-fatal): ${D}`)}let Wk=Ls.length>0?`
872
+ `}catch(N){let D=N instanceof Error?N.message:String(N);console.warn(`[job] ${w.jobId} conflict merge failed: ${D}`),_||await C.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${D}`},startedAt:M,finishedAt:new Date().toISOString()}),L.dispose();return}}let Ds=null;if(w.contextPack&&se)try{let{assembleContextPack:N}=await Promise.resolve().then(()=>(Ly(),Oy)),D=N({contextDir:se,taskKey:String(w.metadata?.trackerIssueKey??w.taskId.split(":")[1]??""),title:String(w.metadata?.taskTitle??""),repoDirs:new Map(Ae.map(Q=>[Q.name,Q.workspacePath]))});D?(rw(Tt(L.dir,"meta"),{recursive:!0}),nw(Tt(L.dir,"meta","context-pack.md"),D),Ds=D,console.log(`[job] ${w.jobId} context pack: ${D.length} chars \u2192 meta/context-pack.md`)):console.log(`[job] ${w.jobId} context pack: model empty or no signal \u2014 skipped`)}catch(N){let D=N instanceof Error?N.message:String(N);console.warn(`[job] ${w.jobId} context pack failed (non-fatal): ${D}`)}let lu="",Wo=null,Us=null;try{let{loadSkills:N,materializeSkills:D,renderSkillsBlock:Q}=await Promise.resolve().then(()=>(Dy(),My)),Z=w.skills??{bundled:!0,context:!0,repo:!0},le=N({contextDir:se,repoDirs:Ae.map(et=>et.workspacePath),sources:Z});for(let et of le.errors)console.warn(`[job] ${w.jobId} skill ${et.source}: ${et.error}`);let Qe=D(L.dir,le.skills),he=["implement","rework","testing"].includes(w.role)?La(Oa(R(se,w.taskId))):[];lu=Q(le.skills,he),Qe.length>0&&console.log(`[job] ${w.jobId} skills: ${le.skills.map(et=>et.name).join(", ")}`);let{parseMarketplaces:Ue,enabledPluginsSetting:Or}=await Promise.resolve().then(()=>(F(),Id)),{sources:Lr,errors:Gn}=Ue(Z.marketplaces??[]);for(let et of Gn)console.warn(`[job] ${w.jobId} marketplace ${et}`);if(Lr.length>0&&(Z.plugins??[]).length>0){let{seedMarketplaces:et}=await Promise.resolve().then(()=>(Ky(),Gy)),Mr=await et(Lr);for(let ee of Mr.errors)console.warn(`[job] ${w.jobId} marketplace ${ee.repo}: ${ee.error}`);let{enabled:Dr,unknown:Ur}=Or(Z.plugins??[],Mr.ready);for(let ee of Ur)console.warn(`[job] ${w.jobId} plugin ${ee}: no such marketplace in this project`);Mr.dir&&Object.keys(Dr).length>0&&(Wo=Mr.dir,Us={enabledPlugins:Dr},console.log(`[job] ${w.jobId} plugins: ${Object.keys(Dr).join(", ")}`))}}catch(N){let D=N instanceof Error?N.message:String(N);console.warn(`[job] ${w.jobId} skills unavailable (non-fatal): ${D}`)}let uu="";if(["code-review","council","analyze","testing"].includes(w.role))try{let{loadRoles:N}=await Promise.resolve().then(()=>(Yy(),qy)),{materializeRoleAgents:D,renderRolesBlock:Q}=await Promise.resolve().then(()=>(zy(),Vy)),Z=N(se);for(let Ue of Z.errors)console.warn(`[job] ${w.jobId} role ${Ue.file}: ${Ue.error}`);let le=w.role==="council"?"council":w.role==="analyze"?"plan_review":"code_review",Qe=w.role==="council"?"council":w.role==="analyze"?"plan-review":w.role==="testing"?"testing":"code-review",he=D(L.dir,Z.roles,le,se);uu=Q(he,Qe),console.log(`[job] ${w.jobId} review panel: ${he.roles.length>0?he.roles.map(Ue=>Ue.name).join(", "):"(no roles)"}`)}catch(N){let D=N instanceof Error?N.message:String(N);console.warn(`[job] ${w.jobId} review panel unavailable (non-fatal): ${D}`)}let Wk=Ls.length>0?`
873
873
 
874
874
  ## Base branch moved \u2014 conflicts to resolve
875
875
 
@@ -877,61 +877,61 @@ The base branch advanced since the previous iteration; its delivery was re-appli
877
877
 
878
878
  `+Ls.join(`
879
879
  `)+`
880
- `:"",du=A(b(y.prompt,Ae,se),se,y.taskId).replace(/\{\{rolesBlock\}\}/g,uu).replace(/\{\{skillsBlock\}\}/g,lu)+cu+Wk,Fn=[...Ae.map(N=>N.workspacePath),...se?[se]:[]];if(Fn.length>0&&console.log(`[job] ${y.jobId} --add-dir: ${Fn.join(", ")}`),_g("agent-request")){let N=is(kn(y.metadata??{})),D=jg(y.projectId,y.jobId,"agent-request",[`# Agent request \u2014 job ${y.jobId}`,"",`- project: ${y.projectId}`,`- task: ${y.taskId}`,`- role: ${y.role}`,`- model: ${Bn??"(backend default)"}`,`- add-dirs:${Fn.length>0?"":" (none)"}`,...Fn.map(Q=>` - ${Q}`),"","## Append-system-prompt (language directive)","","```",N,"```","","## Prompt","",du,"",...Ds?["## Context pack (meta/context-pack.md)","",Ds]:["## Context pack","","(not generated for this job)"],""].join(`
881
- `));D&&console.log(`[debug] ${y.jobId} agent request \u2192 ${D}`)}ne&&(j=setInterval(()=>{let D=f;if(!D||D.readyState!==D.OPEN)return;let Q;try{Q=sR(It(M.dir,"drafts")).filter(Z=>Z.endsWith(".json")).sort()}catch{return}for(let Z of Q){if(Gt.has(Z))continue;if(Gt.size>=Ka)break;let le;try{let he=JSON.parse(ys(It(M.dir,"drafts",Z),"utf-8")),Ue=typeof he.localRef=="string"?he.localRef:"",Or=typeof he.title=="string"?he.title:"",Lr=typeof he.body=="string"?he.body:"";if(!Ue||!Or)continue;le={localRef:Ue,title:Or,body:Lr,...he.isEpic===!0?{isEpic:!0}:{},...Array.isArray(he.links)?{links:he.links}:{}}}catch{continue}Gt.add(Z);let Qe={type:"child_draft",jobId:y.jobId,projectId:y.projectId,draftId:ne,child:le};try{D.send(JSON.stringify(Qe))}catch{}}},1500));try{let N={workspaceDir:M.dir,role:y.role,prompt:du,addDirs:Fn,metadata:y.metadata??{},...Bn?{model:Bn}:{},...pr||Wo?{env:{...pr??{},...Wo?{CLAUDE_CODE_PLUGIN_SEED_DIR:Wo}:{}}}:{},...Us?{settings:Us}:{},signal:B.abort.signal,onActivity:re},D=B.chatInbox?await c.run({...N,interactive:{inbox:B.chatInbox.iterable}}):await Rg(c,N,{jobId:y.jobId,policy:l,onBeforeRetry:async()=>{M.clean();for(let ee of Ae)try{await Yg(ee);let Ee=Ms[ee.name];y.role==="resolve-conflict"&&Ee&&await Rl(ee,Ee,Re)}catch(Ee){let Kn=Ee instanceof Error?Ee.message:String(Ee);console.warn(`[job] ${y.jobId} worktree reset failed (${ee.name}): ${Kn}`)}try{await au()}catch(ee){let Ee=ee instanceof Error?ee.message:String(ee);console.warn(`[job] ${y.jobId} delivery re-checkout failed: ${Ee}`)}},aborted:()=>_||B.paused}),Q=[];if(lR.has(y.role)&&Ae.length>0){let ee=y.metadata??{},Ee=typeof ee.commitMessage=="string"?ee.commitMessage:`${y.taskId}: changes`,Kn=y.contextRepo?.cloneUrl,pu=Y?.env;if(!Kn||!pu)throw new Error("delivery requested but "+(Kn?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let qk=y.taskId.includes(":")?y.taskId.slice(y.taskId.indexOf(":")+1):y.taskId;for(let Ct of Ae){let Hn=await Vg(Ct,Ee);if(!Hn){console.log(`[job] ${y.jobId} ${Ct.name}: no changes \u2014 no delivery`);continue}let Bs=`codepipe/deliveries/${qk}/${y.jobId}/${Ct.name}`;await zg(Ct,Hn,Bs,Kn,pu),Q.push({name:Ct.name,deliveryRef:Bs,deliverySha:Hn,baseSha:Ct.baseSha}),console.log(`[job] ${y.jobId} ${Ct.name}: delivered ${Hn.slice(0,10)} \u2192 ${Bs}`);let fu=await Xg(Ct,Hn);if(fu.trim().length>0){let Yk=It("display",`${Ct.name}.diff`),mu=It(M.dir,Yk);rw(cR(mu),{recursive:!0}),nw(mu,fu)}}}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 Z;y.role==="build"&&(Z=ay(M.dir),console.log(`[job] ${y.jobId} build verdict: ok=${Z.ok}`+(Z.failedStep?` failedStep=${Z.failedStep}`:"")));let le;y.role==="code-review"&&(le=uy(M.dir),console.log(`[job] ${y.jobId} review verdict: approved=${le.approved}`));let Qe;if(y.role==="council"){let{readCouncilVerdict:ee}=await Promise.resolve().then(()=>(Zy(),Jy));Qe=ee(M.dir)??void 0,console.log(`[job] ${y.jobId} council: ${Qe?"answered":"no verdict \u2014 task stops for a human"}`)}let he;if(y.role==="testing"){try{let ee=ys(It(M.dir,"meta","test-result.json"),"utf-8");he=JSON.parse(ee)}catch{he=void 0}console.log(`[job] ${y.jobId} test verdict: ${he?"written":"none \u2014 proceeding to the PR"}`)}let Ue;if(y.role==="observer"){let{readQueuePlan:ee}=await Promise.resolve().then(()=>(tw(),ew));Ue=ee(M.dir)??void 0,console.log(`[job] ${y.jobId} queue plan: ${Ue?"produced":"none \u2014 batch keeps the staged order"}`)}let Or=D.artifactPaths.length>0?D.artifactPaths:M.listFiles(),Lr=Array.from(new Set(Or)),Gn;if(Os)try{let ee=y.role==="index"?["adr/SOURCES.md"]:y.role==="backfill"?["adr"]:[],Ee=await ny(Os,ee);Ee.length>0&&(Gn=Ee,console.log(`[job] ${y.jobId} captured ${Ee.length} knowledge file(s) for Context Repo`))}catch(ee){let Ee=ee instanceof Error?ee.message:String(ee);console.warn(`[job] ${y.jobId} knowledge capture failed (non-fatal): ${Ee}`)}let{artifacts:et,omitted:Mr,dropped:Dr}=fy(M.dir,Lr);for(let ee of Mr)console.warn(`[job] ${y.jobId} artifact ${ee.path} (${ee.bytes} bytes) exceeded upload budget \u2014 content omitted`);Dr.length>0&&console.warn(`[job] ${y.jobId} artifact listing truncated: ${Dr.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let Ur={jobId:y.jobId,status:"succeeded",artifacts:et,...Gn?{contextWrites:Gn}:{},...Q.length>0?{deliveries:Q}:{},log:uR(D.log),startedAt:L,finishedAt:new Date().toISOString(),usage:D.usage,...D.rateLimit?{rateLimit:D.rateLimit}:{},...Z?{build:Z}:{},...le?{review:le}:{},...Ue!==void 0?{queuePlan:Ue}:{},...Qe!==void 0?{council:Qe}:{},...he!==void 0?{test:he}:{}};if(_||B.paused)console.warn(`[job] ${y.jobId} skipping result upload \u2014 ${B.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await P.submitResult(Ur),console.log(`[job] ${y.jobId} done \u2014 uploaded ${Ur.artifacts.length} artifact(s):`);for(let ee of Ur.artifacts){let Ee=Buffer.from(ee.contentBase64,"base64").length;console.log(` \xB7 ${ee.path} (${Ee} bytes)`)}Ur.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(N){let D=N instanceof Error?N.message:String(N);if(B.paused)console.log(`[job] ${y.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(_)console.warn(`[job] ${y.jobId} failed after claim lost (${D}) \u2014 skipping result upload`);else{let Q=Ig(N),Z=N instanceof sr,le=N instanceof Ut;console.warn(Q?`[job] ${y.jobId} failed: ${D} (Claude auth \u2014 token invalid/expired)`:Z?`[job] ${y.jobId} failed: ${D} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:le?`[job] ${y.jobId} failed: ${D} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${y.jobId} failed: ${D}`),await P.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:D},startedAt:L,finishedAt:new Date().toISOString(),...Q?{authError:!0}:{},...Z?{buildInconclusive:!0}:{},...le?{reviewInconclusive:!0}:{}})}}finally{M.dispose()}}finally{clearInterval(ut),j&&clearInterval(j),I(),B.chatInbox?.close(),m.delete(y.jobId),W?.cleanup(),Y?.cleanup()}}function T(P,y){if(!P.credBundle)return{gitCreds:null,contextGitCreds:null};if(!y)return console.warn(`[job] ${P.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let B;try{B=JSON.parse(un(y,P.credBundle).toString("utf-8"))}catch(de){return console.warn(`[job] ${P.jobId} failed to open credBundle: ${de instanceof Error?de.message:String(de)}`),{gitCreds:null,contextGitCreds:null}}let _=Tl(B);_&&console.log(`[job] ${P.jobId} cred bundle opened \u2014 git creds configured`);let W=Bg(B,P.contextRepo.cloneUrl),Y={gitCreds:_,contextGitCreds:W};return B.claudeOauthToken&&(Y.claudeOauthToken=B.claudeOauthToken),Y}function v(P,y){return P.split(`
882
- `).map(B=>y+B).join(`
883
- `)}function b(P,y,B){let _=y[0]?.workspacePath??"";return P.replace(/\{\{codeDir\}\}/g,_).replace(/\{\{codeRoot\}\}/g,_?_.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,B??"")}function R(P,y){let B=y.includes("::")?"":y.split(":",2)[1]??"";if(!P||!B)return"";for(let _ of["PLAN.md","SOLUTION.md"])try{return ys(It(P,"tasks",B,_),"utf-8")}catch{}return""}function A(P,y,B){let _=P,W=B.includes("::")?"":B.split(":",2)[1]??"",Y=de=>{if(!y||!W)return"";try{return ys(It(y,"tasks",W,de),"utf-8").trim()}catch{return""}};if(_.includes("{{planMd}}")||_.includes("{{solutionMd}}")){let de=Y("PLAN.md")||Y("SOLUTION.md")||"(PLAN.md missing \u2014 proceed from the task description)";_=_.replace(/\{\{planMd\}\}/g,()=>de),_=_.replace(/\{\{solutionMd\}\}/g,()=>de)}if(_.includes("{{taskDescription}}")){let de=Y("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";_=_.replace(/\{\{taskDescription\}\}/g,()=>de)}return _}let G=P=>{if(p)return;p=!0,console.log(`
884
- [${P}] shutting down`),d.abort();let y=[...m.keys()];for(let W of m.values())W.abort.abort();let B=new AbortController,_=setTimeout(()=>B.abort(),3e3);(async()=>(await Promise.all(y.map(async W=>{try{await u.releaseJob(W,`sandbox ${P}`,B.signal),console.log(`[${P}] released job ${W}`)}catch(Y){let de=Y instanceof Error?Y.message:String(Y);console.warn(`[${P}] release failed: ${de} (sweeper will reclaim)`)}})),clearTimeout(_),w.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>G("SIGINT")),process.on("SIGTERM",()=>G("SIGTERM"));let J=[$("implementation")];e.planningLane!==!1?J.push($("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(J)}var ws,lR,ow=S(()=>{"use strict";F();at();Va();xg();ss();Cg();Ng();Be();os();Fg();$l();oy();sy();cy();dy();my();ky();ws=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),lR=new Set(["implement","resolve-conflict"])});var Pn=S(()=>{"use strict";lg();ow();os()});import{cancel as pR,isCancel as sw,log as ze,password as fR,text as mR}from"@clack/prompts";function hR(t){return sw(t)&&(pR("aborted"),process.exit(1)),typeof t=="string"?t:""}function aw(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function gR(t){let e=sc({redirectUri:ic,challenge:t.challenge,state:t.state});ze.message(`Open this URL, approve the access, and paste the code shown:
880
+ `:"",du=A(b(w.prompt,Ae,se),se,w.taskId).replace(/\{\{rolesBlock\}\}/g,uu).replace(/\{\{skillsBlock\}\}/g,lu)+cu+Wk,Fn=[...Ae.map(N=>N.workspacePath),...se?[se]:[]];if(Fn.length>0&&console.log(`[job] ${w.jobId} --add-dir: ${Fn.join(", ")}`),_g("agent-request")){let N=is(kn(w.metadata??{})),D=jg(w.projectId,w.jobId,"agent-request",[`# Agent request \u2014 job ${w.jobId}`,"",`- project: ${w.projectId}`,`- task: ${w.taskId}`,`- role: ${w.role}`,`- model: ${Bn??"(backend default)"}`,`- add-dirs:${Fn.length>0?"":" (none)"}`,...Fn.map(Q=>` - ${Q}`),"","## Append-system-prompt (language directive)","","```",N,"```","","## Prompt","",du,"",...Ds?["## Context pack (meta/context-pack.md)","",Ds]:["## Context pack","","(not generated for this job)"],""].join(`
881
+ `));D&&console.log(`[debug] ${w.jobId} agent request \u2192 ${D}`)}ne&&(j=setInterval(()=>{let D=f;if(!D||D.readyState!==D.OPEN)return;let Q;try{Q=sR(Tt(L.dir,"drafts")).filter(Z=>Z.endsWith(".json")).sort()}catch{return}for(let Z of Q){if(Gt.has(Z))continue;if(Gt.size>=Ka)break;let le;try{let he=JSON.parse(ys(Tt(L.dir,"drafts",Z),"utf-8")),Ue=typeof he.localRef=="string"?he.localRef:"",Or=typeof he.title=="string"?he.title:"",Lr=typeof he.body=="string"?he.body:"";if(!Ue||!Or)continue;le={localRef:Ue,title:Or,body:Lr,...he.isEpic===!0?{isEpic:!0}:{},...Array.isArray(he.links)?{links:he.links}:{}}}catch{continue}Gt.add(Z);let Qe={type:"child_draft",jobId:w.jobId,projectId:w.projectId,draftId:ne,child:le};try{D.send(JSON.stringify(Qe))}catch{}}},1500));try{let N={workspaceDir:L.dir,role:w.role,prompt:du,addDirs:Fn,metadata:w.metadata??{},...Bn?{model:Bn}:{},...pr||Wo?{env:{...pr??{},...Wo?{CLAUDE_CODE_PLUGIN_SEED_DIR:Wo}:{}}}:{},...Us?{settings:Us}:{},signal:U.abort.signal,onActivity:re},D=U.chatInbox?await c.run({...N,interactive:{inbox:U.chatInbox.iterable}}):await Rg(c,N,{jobId:w.jobId,policy:l,onBeforeRetry:async()=>{L.clean();for(let ee of Ae)try{await Yg(ee);let Ee=Ms[ee.name];w.role==="resolve-conflict"&&Ee&&await Rl(ee,Ee,Re)}catch(Ee){let Kn=Ee instanceof Error?Ee.message:String(Ee);console.warn(`[job] ${w.jobId} worktree reset failed (${ee.name}): ${Kn}`)}try{await au()}catch(ee){let Ee=ee instanceof Error?ee.message:String(ee);console.warn(`[job] ${w.jobId} delivery re-checkout failed: ${Ee}`)}},aborted:()=>_||U.paused}),Q=[];if(lR.has(w.role)&&Ae.length>0){let ee=w.metadata??{},Ee=typeof ee.commitMessage=="string"?ee.commitMessage:`${w.taskId}: changes`,Kn=w.contextRepo?.cloneUrl,pu=z?.env;if(!Kn||!pu)throw new Error("delivery requested but "+(Kn?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let qk=w.taskId.includes(":")?w.taskId.slice(w.taskId.indexOf(":")+1):w.taskId;for(let Ct of Ae){let Hn=await Vg(Ct,Ee);if(!Hn){console.log(`[job] ${w.jobId} ${Ct.name}: no changes \u2014 no delivery`);continue}let Bs=`codepipe/deliveries/${qk}/${w.jobId}/${Ct.name}`;await zg(Ct,Hn,Bs,Kn,pu),Q.push({name:Ct.name,deliveryRef:Bs,deliverySha:Hn,baseSha:Ct.baseSha}),console.log(`[job] ${w.jobId} ${Ct.name}: delivered ${Hn.slice(0,10)} \u2192 ${Bs}`);let fu=await Xg(Ct,Hn);if(fu.trim().length>0){let Yk=Tt("display",`${Ct.name}.diff`),mu=Tt(L.dir,Yk);rw(cR(mu),{recursive:!0}),nw(mu,fu)}}}if(w.role==="resolve-conflict"&&Q.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's SOLUTION.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let Z;w.role==="build"&&(Z=ay(L.dir),console.log(`[job] ${w.jobId} build verdict: ok=${Z.ok}`+(Z.failedStep?` failedStep=${Z.failedStep}`:"")));let le;w.role==="code-review"&&(le=uy(L.dir),console.log(`[job] ${w.jobId} review verdict: approved=${le.approved}`));let Qe;if(w.role==="council"){let{readCouncilVerdict:ee}=await Promise.resolve().then(()=>(Zy(),Jy));Qe=ee(L.dir)??void 0,console.log(`[job] ${w.jobId} council: ${Qe?"answered":"no verdict \u2014 task stops for a human"}`)}let he;if(w.role==="testing"){try{let ee=ys(Tt(L.dir,"meta","test-result.json"),"utf-8");he=JSON.parse(ee)}catch{he=void 0}console.log(`[job] ${w.jobId} test verdict: ${he?"written":"none \u2014 proceeding to the PR"}`)}let Ue;if(w.role==="observer"){let{readQueuePlan:ee}=await Promise.resolve().then(()=>(tw(),ew));Ue=ee(L.dir)??void 0,console.log(`[job] ${w.jobId} queue plan: ${Ue?"produced":"none \u2014 batch keeps the staged order"}`)}let Or=D.artifactPaths.length>0?D.artifactPaths:L.listFiles(),Lr=Array.from(new Set(Or)),Gn;if(Os)try{let ee=w.role==="index"?["adr/SOURCES.md"]:w.role==="backfill"?["adr"]:[],Ee=await ny(Os,ee);Ee.length>0&&(Gn=Ee,console.log(`[job] ${w.jobId} captured ${Ee.length} knowledge file(s) for Context Repo`))}catch(ee){let Ee=ee instanceof Error?ee.message:String(ee);console.warn(`[job] ${w.jobId} knowledge capture failed (non-fatal): ${Ee}`)}let{artifacts:et,omitted:Mr,dropped:Dr}=fy(L.dir,Lr);for(let ee of Mr)console.warn(`[job] ${w.jobId} artifact ${ee.path} (${ee.bytes} bytes) exceeded upload budget \u2014 content omitted`);Dr.length>0&&console.warn(`[job] ${w.jobId} artifact listing truncated: ${Dr.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let Ur={jobId:w.jobId,status:"succeeded",artifacts:et,...Gn?{contextWrites:Gn}:{},...Q.length>0?{deliveries:Q}:{},log:uR(D.log),startedAt:M,finishedAt:new Date().toISOString(),usage:D.usage,...D.rateLimit?{rateLimit:D.rateLimit}:{},...Z?{build:Z}:{},...le?{review:le}:{},...Ue!==void 0?{queuePlan:Ue}:{},...Qe!==void 0?{council:Qe}:{},...he!==void 0?{test:he}:{}};if(_||U.paused)console.warn(`[job] ${w.jobId} skipping result upload \u2014 ${U.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await C.submitResult(Ur),console.log(`[job] ${w.jobId} done \u2014 uploaded ${Ur.artifacts.length} artifact(s):`);for(let ee of Ur.artifacts){let Ee=Buffer.from(ee.contentBase64,"base64").length;console.log(` \xB7 ${ee.path} (${Ee} bytes)`)}Ur.artifacts.length===0&&console.warn(`[job] ${w.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(N){let D=N instanceof Error?N.message:String(N);if(U.paused)console.log(`[job] ${w.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(_)console.warn(`[job] ${w.jobId} failed after claim lost (${D}) \u2014 skipping result upload`);else{let Q=Ig(N),Z=N instanceof sr,le=N instanceof Ut;console.warn(Q?`[job] ${w.jobId} failed: ${D} (Claude auth \u2014 token invalid/expired)`:Z?`[job] ${w.jobId} failed: ${D} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:le?`[job] ${w.jobId} failed: ${D} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${w.jobId} failed: ${D}`),await C.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:D},startedAt:M,finishedAt:new Date().toISOString(),...Q?{authError:!0}:{},...Z?{buildInconclusive:!0}:{},...le?{reviewInconclusive:!0}:{}})}}finally{L.dispose()}}finally{clearInterval(kt),j&&clearInterval(j),I(),U.chatInbox?.close(),m.delete(w.jobId),H?.cleanup(),z?.cleanup()}}function T(C,w){if(!C.credBundle)return{gitCreds:null,contextGitCreds:null};if(!w)return console.warn(`[job] ${C.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let U;try{U=JSON.parse(un(w,C.credBundle).toString("utf-8"))}catch(de){return console.warn(`[job] ${C.jobId} failed to open credBundle: ${de instanceof Error?de.message:String(de)}`),{gitCreds:null,contextGitCreds:null}}let _=Tl(U);_&&console.log(`[job] ${C.jobId} cred bundle opened \u2014 git creds configured`);let H=Bg(U,C.contextRepo.cloneUrl),z={gitCreds:_,contextGitCreds:H};return U.claudeOauthToken&&(z.claudeOauthToken=U.claudeOauthToken),z}function v(C,w){return C.split(`
882
+ `).map(U=>w+U).join(`
883
+ `)}function b(C,w,U){let _=w[0]?.workspacePath??"";return C.replace(/\{\{codeDir\}\}/g,_).replace(/\{\{codeRoot\}\}/g,_?_.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,U??"")}function R(C,w){let U=w.includes("::")?"":w.split(":",2)[1]??"";if(!C||!U)return"";for(let _ of["PLAN.md","SOLUTION.md"])try{return ys(Tt(C,"tasks",U,_),"utf-8")}catch{}return""}function A(C,w,U){let _=C,H=U.includes("::")?"":U.split(":",2)[1]??"",z=de=>{if(!w||!H)return"";try{return ys(Tt(w,"tasks",H,de),"utf-8").trim()}catch{return""}};if(_.includes("{{planMd}}")||_.includes("{{solutionMd}}")){let de=z("PLAN.md")||z("SOLUTION.md")||"(PLAN.md missing \u2014 proceed from the task description)";_=_.replace(/\{\{planMd\}\}/g,()=>de),_=_.replace(/\{\{solutionMd\}\}/g,()=>de)}if(_.includes("{{taskDescription}}")){let de=z("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";_=_.replace(/\{\{taskDescription\}\}/g,()=>de)}return _}let G=C=>{if(p)return;p=!0,console.log(`
884
+ [${C}] shutting down`),d.abort();let w=[...m.keys()];for(let H of m.values())H.abort.abort();let U=new AbortController,_=setTimeout(()=>U.abort(),3e3);(async()=>(await Promise.all(w.map(async H=>{try{await u.releaseJob(H,`sandbox ${C}`,U.signal),console.log(`[${C}] released job ${H}`)}catch(z){let de=z instanceof Error?z.message:String(z);console.warn(`[${C}] release failed: ${de} (sweeper will reclaim)`)}})),clearTimeout(_),y.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>G("SIGINT")),process.on("SIGTERM",()=>G("SIGTERM"));let V=[$("implementation")];e.planningLane!==!1?V.push($("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(V)}var ws,lR,ow=S(()=>{"use strict";F();at();Va();xg();ss();Cg();Ng();Be();os();Fg();$l();oy();sy();cy();dy();my();ky();ws=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),lR=new Set(["implement","resolve-conflict"])});var Pn=S(()=>{"use strict";lg();ow();os()});import{cancel as pR,isCancel as sw,log as ze,password as fR,text as mR}from"@clack/prompts";function hR(t){return sw(t)&&(pR("aborted"),process.exit(1)),typeof t=="string"?t:""}function aw(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function gR(t){let e=sc({redirectUri:ic,challenge:t.challenge,state:t.state});ze.message(`Open this URL, approve the access, and paste the code shown:
885
885
  ${e}`);let r=await mR({message:"Authorization code \u2014 blank to skip"});if(sw(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=jp(r,t.state);return await ac({code:n,verifier:t.verifier,state:t.state,redirectUri:ic})}catch(n){return ze.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function yR(t){if(qa()?.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=pi(),n;try{n=await Np({...r,openUrl:Sr,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 gR(r);if(s===null)return null;n=s}let o=await Ot(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 ${aw(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function cw(t){ze.message(`Claude \u2014 the pipeline's agents run on your Claude subscription.
886
886
  In another terminal:
887
887
  1. install Claude Code \u2014 https://claude.com/claude-code
888
888
  2. run \`claude setup-token\`
889
889
  3. paste the token it prints (starts with sk-ant-) below`+(t.farm?`
890
- Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=hR(await fR({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 Ot(e);return r==="invalid"?(ze.warn("Claude refused this token. Run `claude setup-token` again and paste the new one."),cw(t)):(ze.success(`Claude: ${aw(e)} \u2014 ${r==="valid"?"verified":"check inconclusive, saved"}.`),e)}var lw,uw=S(()=>{"use strict";fi();rn();pe();lc();lw={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:yR,promptManual:cw,validate:Ot}});function dw(t){return lw}async function pw(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var fw=S(()=>{"use strict";uw()});async function An(t,e,r){return e.host==="github"?kR(t,e,r):e.host==="gitlab"?ER(t,e,r):IR(t,e,r)}async function mw(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 bt(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 Xe(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await gw(e.gitlabToken,t):o}}return e.bitbucket?(await Ft(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await yw(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 bt(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 Xe(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 yw(t,e){let r=!1;try{r=(await Ft(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 bt(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(wR+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 kR(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 bR(n,e,r),i=await $R(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=cn(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await vR(n,o.owner,o.name,a.path,i)||await xR(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 bR(t,e,r){let n=await bt(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 Dl(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 bt(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 Dl(t,e){let{status:r,data:n}=await bt(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function $R(t,e,r){let{data:n}=await bt(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function vR(t,e,r,n,o){let{status:i,data:s}=await bt(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function xR(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 bt(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Xe(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(SR+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 ER(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 Xe(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 Xe(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 Xe(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 Xe(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=cn(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let m=(await Xe(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 Xe(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 Ft(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(TR+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 IR(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 Ft(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 yw(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 Ft(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=cn(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await Ft(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 Ft(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 wR,SR,TR,Lo=S(()=>{"use strict";Er();wR="https://api.github.com";SR="https://gitlab.com/api/v4";TR="https://api.bitbucket.org/2.0"});function He(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=RR[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 RR,ks=S(()=>{"use strict";RR={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as CR}from"node:crypto";import{existsSync as ww,mkdirSync as PR,readFileSync as kw,readdirSync as AR,rmSync as bs,writeFileSync as _R}from"node:fs";import{homedir as jR}from"node:os";import{dirname as NR,join as Ul}from"node:path";function bw(){return Ul(jR(),".codepipe","init-drafts")}function Bl(t){let e=CR("sha256").update(t).digest("hex").slice(0,16);return Ul(bw(),`${e}.json`)}function $w(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=OR)}function vw(t){let e=Bl(t);if(!ww(e))return null;try{let r=JSON.parse(kw(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:$w(r.savedAt)?(bs(e,{force:!0}),null):r}catch{return null}}function Fl(t){bs(Bl(t),{force:!0})}function xw(){let t=bw();if(ww(t))for(let e of AR(t)){let r=Ul(t,e);try{let n=JSON.parse(kw(r,"utf-8"));$w(n.savedAt)&&bs(r,{force:!0})}catch{bs(r,{force:!0})}}}var OR,_n,Sw=S(()=>{"use strict";OR=24*60*60*1e3;_n=class{constructor(e,r){this.cwd=e;this.answers=r?.answers?{...r.answers}:{}}answers;get(e){return this.answers[e]}set(e,r){this.answers[e]=r,this.persist()}delete(e){delete this.answers[e],this.persist()}async ask(e,r){if(e in this.answers)return this.answers[e];let n=await r();return this.set(e,n),n}clear(){Fl(this.cwd)}persist(){let e=Bl(this.cwd);PR(NR(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};_R(e,JSON.stringify(r,null,2)+`
890
+ Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=hR(await fR({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 Ot(e);return r==="invalid"?(ze.warn("Claude refused this token. Run `claude setup-token` again and paste the new one."),cw(t)):(ze.success(`Claude: ${aw(e)} \u2014 ${r==="valid"?"verified":"check inconclusive, saved"}.`),e)}var lw,uw=S(()=>{"use strict";fi();rn();pe();lc();lw={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:yR,promptManual:cw,validate:Ot}});function dw(t){return lw}async function pw(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var fw=S(()=>{"use strict";uw()});async function An(t,e,r){return e.host==="github"?kR(t,e,r):e.host==="gitlab"?ER(t,e,r):IR(t,e,r)}async function mw(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 wt(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 Xe(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await gw(e.gitlabToken,t):o}}return e.bitbucket?(await Ft(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await yw(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 wt(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 Xe(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 yw(t,e){let r=!1;try{r=(await Ft(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 wt(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(wR+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 kR(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 bR(n,e,r),i=await $R(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=cn(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await vR(n,o.owner,o.name,a.path,i)||await xR(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 bR(t,e,r){let n=await wt(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 Dl(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 wt(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 Dl(t,e){let{status:r,data:n}=await wt(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function $R(t,e,r){let{data:n}=await wt(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function vR(t,e,r,n,o){let{status:i,data:s}=await wt(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function xR(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 wt(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Xe(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(SR+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 ER(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 Xe(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 Xe(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 Xe(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 Xe(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=cn(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let m=(await Xe(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 Xe(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 Ft(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(TR+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 IR(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 Ft(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 yw(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 Ft(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=cn(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await Ft(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 Ft(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 wR,SR,TR,Lo=S(()=>{"use strict";Er();wR="https://api.github.com";SR="https://gitlab.com/api/v4";TR="https://api.bitbucket.org/2.0"});function He(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=RR[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 RR,ks=S(()=>{"use strict";RR={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as CR}from"node:crypto";import{existsSync as ww,mkdirSync as PR,readFileSync as kw,readdirSync as AR,rmSync as bs,writeFileSync as _R}from"node:fs";import{homedir as jR}from"node:os";import{dirname as NR,join as Ul}from"node:path";function bw(){return Ul(jR(),".codepipe","init-drafts")}function Bl(t){let e=CR("sha256").update(t).digest("hex").slice(0,16);return Ul(bw(),`${e}.json`)}function $w(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=OR)}function vw(t){let e=Bl(t);if(!ww(e))return null;try{let r=JSON.parse(kw(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:$w(r.savedAt)?(bs(e,{force:!0}),null):r}catch{return null}}function Fl(t){bs(Bl(t),{force:!0})}function xw(){let t=bw();if(ww(t))for(let e of AR(t)){let r=Ul(t,e);try{let n=JSON.parse(kw(r,"utf-8"));$w(n.savedAt)&&bs(r,{force:!0})}catch{bs(r,{force:!0})}}}var OR,_n,Sw=S(()=>{"use strict";OR=24*60*60*1e3;_n=class{constructor(e,r){this.cwd=e;this.answers=r?.answers?{...r.answers}:{}}answers;get(e){return this.answers[e]}set(e,r){this.answers[e]=r,this.persist()}delete(e){delete this.answers[e],this.persist()}async ask(e,r){if(e in this.answers)return this.answers[e];let n=await r();return this.set(e,n),n}clear(){Fl(this.cwd)}persist(){let e=Bl(this.cwd);PR(NR(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};_R(e,JSON.stringify(r,null,2)+`
891
891
  `,{mode:384})}}});function Ew(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 Tw(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 Iw=S(()=>{"use strict"});import{existsSync as LR}from"node:fs";import{join as MR}from"node:path";import{simpleGit as DR}from"simple-git";function GR(t){let e=t.split("/");return e[e.length-1]??t}function Rw(t){if(t.filter(r=>!BR.test(GR(r))).length>UR)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(FR.has(n))return!0}return!1}async function KR(t){try{let r=(await DR(t).raw(["ls-files"])).split(`
892
- `).map(n=>n.trim()).filter(Boolean);return Rw(r)}catch{return!1}}async function HR(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)?Rw(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function Cw(t,e){for(let r of t)try{let n=e.localRoot!=null?MR(e.localRoot,r.mountAs??r.name):null;if(n&&LR(n)?await KR(n):await HR(r,e.tokens))return!0}catch{}return!1}var UR,BR,FR,Pw=S(()=>{"use strict";UR=3,BR=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,FR=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as Aw}from"node:fs";import{join as _w}from"node:path";import{simpleGit as jw}from"simple-git";async function Do(t,e,r={}){let n=r.log??WR,o=[];for(let i of e){let s=_w(t,i.mountAs),a=ri(i);if(!Aw(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 jw().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let p=Mo(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(!Aw(_w(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=jw(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!qR(l,a)){n.warn(`${i.mountAs}/ origin (${Mo(l)||"none"}) != expected (${Mo(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:Mo(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=Mo(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 qR(t,e){return Nw(t)===Nw(e)}function Nw(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function Mo(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function Ow(t={}){let e=Pe();e||(console.error("no .codepipe/ workspace found in this directory or any parent. run `codepipe init` first."),process.exit(1)),console.log(`codepipe sync \u2014 project ${e.spec.projectId} (${e.spec.repos.length} repos)`);let r=await Do(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 WR,$s=S(()=>{"use strict";rt();WR={info:t=>console.log(t),warn:t=>console.warn(t)}});import{simpleGit as YR}from"simple-git";async function Lw(t,e,r){return t.host==="github"?VR(t,e,r):t.host==="gitlab"?zR(t,e,r):XR(t,e,r)}function Gl(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 VR(t,e,r){let n=e.githubToken;if(!n)throw new Error("GitHub token required to create a github-hosted mirror");let o=await bt(n,"GET",`/repos/${t.owner}/${encodeURIComponent(t.repoName)}`);if(o.status===200&&o.data){if(o.data.private!==!0)throw Gl(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 Dl(n,t.owner);r.info(`creating mirror ${t.owner}/${t.repoName} (github, ${i?"org":"user"})`);let s=await bt(n,"POST",i?`/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(!s.data)throw new Error(`GitHub: could not create ${t.owner}/${t.repoName}`);let a=s.data.owner?.login;if(a&&a.toLowerCase()!==t.owner.toLowerCase())throw new Error(`GitHub created the mirror under "${a}", not "${t.owner}" \u2014 the token cannot create repositories in "${t.owner}". Delete ${a}/${t.repoName} and re-run with an owner the token can create in`);return{spec:t,sshUrl:s.data.ssh_url,created:!0}}async function zR(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 Xe(n,"GET",`/projects/${o}`);if(i.status===200&&i.data){if(i.data.visibility!=="private")throw Gl(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 Xe(n,"GET","/user")).data?.username!==t.owner){let l=await Xe(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 Xe(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 XR(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 Ft(n,"GET",o);if(s.status===200&&s.data){if(s.data.is_private!==!0)throw Gl(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 Ft(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 Mw(t,e,r){let n=YR(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(`
893
- `).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 Dw(t){return`${t}-codepipe-mirror`}var Uw=S(()=>{"use strict";Lo()});var Hw={};We(Hw,{ensureEmbeddedWorker:()=>xs,spawnWorkerProcess:()=>Ss,upCommand:()=>Es,workerChildEnv:()=>Kw,workerStartArgs:()=>Gw});import{spawn as Fw}from"node:child_process";import{existsSync as Bw}from"node:fs";import{homedir as JR,hostname as ZR}from"node:os";import{join as vs}from"node:path";async function QR(t,e,r){let n=Le(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${kt(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 th(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 ${kt(e)} still holds its token.
894
- 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`),Kd(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function eC(t,e,r){let n=Le(e)!==null;if(!await QR(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 Vi(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof H&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof H&&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 H?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 Pr({hub:t.hubUrl,token:o,name:r.name??`${ZR()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function tC(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=Ge(r.sealPublicKey);if(!V(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=oi(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 xs(t,e,r){await eC(t,e,r),tC(t.projectId,e)}function Gw(t){return[...t?["--profile",t]:[],"worker","start"]}function Kw(t){let e={...t};for(let r of Ya)delete e[r];return e}function Ss(t){let e=Fw(process.execPath,[t.entry,...Gw(t.profile)],{stdio:["ignore","pipe","pipe"],env:Kw(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
895
- `))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function rC(t,e){let r=process.cwd(),n=vs(r,ht);if(Vr(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(Bw(n)){console.warn(`[up] ${n} exists but is not this project's workspace \u2014 the context stays under ~/.codepipe/profiles`);return}let o;try{o=await oe(t.hubUrl,t.cliToken,t.projectId)}catch(u){console.warn(`[up] could not fetch the project summary (${u instanceof Error?u.message:String(u)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await Kl(r);if(!Rd(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=V(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await ns({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=vs(JR(),".codepipe",e?vs("profiles",e,"context-config"):"context-config");if(gi(c.contextDir,l,a),!Bw(vs(c.contextDir,"project.yaml"))){sn(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};lo(c.contextDir,Et(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 Es(t){let{cfg:e,profile:r}=Xr(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 rC(e,r),await xs(e,r,t);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(m,f)=>{let g=h=>k=>{for(let w of k.toString("utf-8").split(`
896
- `))w.length>0&&h.write(`${f} ${w}
892
+ `).map(n=>n.trim()).filter(Boolean);return Rw(r)}catch{return!1}}async function HR(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)?Rw(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function Cw(t,e){for(let r of t)try{let n=e.localRoot!=null?MR(e.localRoot,r.mountAs??r.name):null;if(n&&LR(n)?await KR(n):await HR(r,e.tokens))return!0}catch{}return!1}var UR,BR,FR,Pw=S(()=>{"use strict";UR=3,BR=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,FR=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as Aw}from"node:fs";import{join as _w}from"node:path";import{simpleGit as jw}from"simple-git";async function Do(t,e,r={}){let n=r.log??WR,o=[];for(let i of e){let s=_w(t,i.mountAs),a=ri(i);if(!Aw(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 jw().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let p=Mo(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(!Aw(_w(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=jw(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!qR(l,a)){n.warn(`${i.mountAs}/ origin (${Mo(l)||"none"}) != expected (${Mo(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:Mo(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=Mo(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 qR(t,e){return Nw(t)===Nw(e)}function Nw(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function Mo(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function Ow(t={}){let e=Pe();e||(console.error("no .codepipe/ workspace found in this directory or any parent. run `codepipe init` first."),process.exit(1)),console.log(`codepipe sync \u2014 project ${e.spec.projectId} (${e.spec.repos.length} repos)`);let r=await Do(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 WR,$s=S(()=>{"use strict";rt();WR={info:t=>console.log(t),warn:t=>console.warn(t)}});import{simpleGit as YR}from"simple-git";async function Lw(t,e,r){return t.host==="github"?VR(t,e,r):t.host==="gitlab"?zR(t,e,r):XR(t,e,r)}function Gl(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 VR(t,e,r){let n=e.githubToken;if(!n)throw new Error("GitHub token required to create a github-hosted mirror");let o=await wt(n,"GET",`/repos/${t.owner}/${encodeURIComponent(t.repoName)}`);if(o.status===200&&o.data){if(o.data.private!==!0)throw Gl(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 Dl(n,t.owner);r.info(`creating mirror ${t.owner}/${t.repoName} (github, ${i?"org":"user"})`);let s=await wt(n,"POST",i?`/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(!s.data)throw new Error(`GitHub: could not create ${t.owner}/${t.repoName}`);let a=s.data.owner?.login;if(a&&a.toLowerCase()!==t.owner.toLowerCase())throw new Error(`GitHub created the mirror under "${a}", not "${t.owner}" \u2014 the token cannot create repositories in "${t.owner}". Delete ${a}/${t.repoName} and re-run with an owner the token can create in`);return{spec:t,sshUrl:s.data.ssh_url,created:!0}}async function zR(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 Xe(n,"GET",`/projects/${o}`);if(i.status===200&&i.data){if(i.data.visibility!=="private")throw Gl(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 Xe(n,"GET","/user")).data?.username!==t.owner){let l=await Xe(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 Xe(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 XR(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 Ft(n,"GET",o);if(s.status===200&&s.data){if(s.data.is_private!==!0)throw Gl(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 Ft(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 Mw(t,e,r){let n=YR(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(`
893
+ `).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 Dw(t){return`${t}-codepipe-mirror`}var Uw=S(()=>{"use strict";Lo()});var Hw={};We(Hw,{ensureEmbeddedWorker:()=>xs,spawnWorkerProcess:()=>Ss,upCommand:()=>Es,workerChildEnv:()=>Kw,workerStartArgs:()=>Gw});import{spawn as Fw}from"node:child_process";import{existsSync as Bw}from"node:fs";import{homedir as JR,hostname as ZR}from"node:os";import{join as vs}from"node:path";async function QR(t,e,r){let n=Le(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${yt(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 th(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 ${yt(e)} still holds its token.
894
+ 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`),Kd(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function eC(t,e,r){let n=Le(e)!==null;if(!await QR(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 Vi(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 Pr({hub:t.hubUrl,token:o,name:r.name??`${ZR()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function tC(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=Ge(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=oi(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 xs(t,e,r){await eC(t,e,r),tC(t.projectId,e)}function Gw(t){return[...t?["--profile",t]:[],"worker","start"]}function Kw(t){let e={...t};for(let r of Ya)delete e[r];return e}function Ss(t){let e=Fw(process.execPath,[t.entry,...Gw(t.profile)],{stdio:["ignore","pipe","pipe"],env:Kw(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
895
+ `))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function rC(t,e){let r=process.cwd(),n=vs(r,ft);if(Vr(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(Bw(n)){console.warn(`[up] ${n} exists but is not this project's workspace \u2014 the context stays under ~/.codepipe/profiles`);return}let o;try{o=await oe(t.hubUrl,t.cliToken,t.projectId)}catch(u){console.warn(`[up] could not fetch the project summary (${u instanceof Error?u.message:String(u)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await Kl(r);if(!Rd(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 ns({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=vs(JR(),".codepipe",e?vs("profiles",e,"context-config"):"context-config");if(gi(c.contextDir,l,a),!Bw(vs(c.contextDir,"project.yaml"))){sn(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};lo(c.contextDir,St(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 Es(t){let{cfg:e,profile:r}=Xr(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 rC(e,r),await xs(e,r,t);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(m,f)=>{let g=h=>k=>{for(let y of k.toString("utf-8").split(`
896
+ `))y.length>0&&h.write(`${f} ${y}
897
897
  `)};m.stdout?.on("data",g(process.stdout)),m.stderr?.on("data",g(process.stderr))},i=(m,f)=>{let g=Fw(process.execPath,[n,...f],{stdio:["ignore","pipe","pipe"],env:process.env});return o(g,m),g};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=Ss({entry:n,profile:r,onLine:m=>process.stdout.write(`[worker] ${m}
898
898
  `)}),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,u=m=>{if(!l){l=!0,console.log(`
899
- [up] ${m} \u2014 stopping both roles`);for(let{child:f}of c)f.exitCode===null&&f.kill(m);setTimeout(()=>{for(let{name:f,child:g}of c)g.exitCode===null&&(console.warn(`[up] ${f} did not stop \u2014 SIGKILL`),g.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:m,child:f})=>new Promise(g=>{f.on("exit",(h,k)=>g({name:m,code:h??(k?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 Ts=S(()=>{"use strict";at();Pn();Fe();Lt();wl();Er();je();pe();rt();Uo()});import{existsSync as _r,mkdirSync as qw,readFileSync as Is,readdirSync as nC,writeFileSync as Yw}from"node:fs";import{join as Je,resolve as Vw}from"node:path";import{setTimeout as Hl}from"node:timers/promises";import{cancel as zw,confirm as Bo,intro as Xw,isCancel as Yl,log as C,multiselect as oC,outro as Wl,password as Fo,select as ct,spinner as Vl,text as we}from"@clack/prompts";import{simpleGit as Cs}from"simple-git";function me(t){zw(t),process.exit(1)}function ye(t){return Yl(t)&&me("aborted"),t}function ce(t){return Yl(t)&&me("aborted"),typeof t=="string"?t:""}async function Jw(t={}){Xw("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();xw();let r=vw(e),n,o=!1;r&&Object.keys(r.answers).length>0?ye(await Bo({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 _n(e,r),o=!0):(Fl(e),n=new _n(e)):n=new _n(e);let i=t.force===!0?null:await Kl(e),s=await n.ask("target",async()=>ye(await ct({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 sC(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||Qw(e,t.force===!0));let c=await n.ask("hubUrl",async()=>ce(await we({message:"HUB URL",placeholder:dt,initialValue:z("HUB_URL")??dt,validate:j=>j.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>jn()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>Nn(c,l)),d=null;s==="farm"&&(d=await iC(c,u));let m=a?aC(a.parsed.repoName):"",f=await n.ask("projectId",async()=>ce(await we({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:j=>Ht.test(j.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await n.ask("projectName",async()=>ce(await we({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:j=>j.trim().length>0?void 0:"required"})).trim()),h=await n.ask("language",()=>yC()),k=await n.ask("automationLevel",async()=>ye(await ct({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()=>ye(await ct({message:"how much access should CodePipe have to your repositories?",options:[{value:"no",label:"read and write \u2014 branches and pull requests go into your repositories"},{value:"yes",label:"read only \u2014 CodePipe mirrors them and works in the mirrors",hint:"a mirror is a full copy of the history, in the account you choose next"}],initialValue:"no"}))))==="yes",x=await n.ask("trackerProvider",async()=>ye(await ct({message:"task tracker",options:[{value:"internal",label:"built-in \u2014 CodePipe tracks tasks itself (no external tracker needed)"},{value:"youtrack",label:"YouTrack \u2014 connect an existing YouTrack project"}],initialValue:"internal"}))),T=x==="internal",v=null,b,R=!0;if(T){let j,M=Vl();M.start("checking task-key prefixes on your account\u2026");try{j=await rh(c,u,{excludeProjectId:f}),M.stop("prefixes checked")}catch{M.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 ie=Ga(Fa(g),j);b=await n.ask("trackerPrefix",async()=>ce(await we({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:ie,initialValue:ie,validate:Re=>{let pr=Re.trim();if(!br.test(pr))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(j.has(pr.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else v=await n.ask("youtrack",()=>ck()),b=await n.ask("youtrackProjectKey",async()=>ce(await we({message:"YouTrack project key",placeholder:"DEV",validate:j=>j.trim().length>0?void 0:"required"})).trim()),R=await n.ask("youtrackWrites",async()=>ye(await Bo({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let A=n.get("tokens")??{},G=()=>n.set("tokens",A),J=await n.ask("repos",()=>dC(A,l,a,{onCred:G,initial:n.get("reposPartial")??[],onProgress:j=>n.set("reposPartial",j)}));n.delete("reposPartial");let P=await pC(await n.ask("contextRepo",()=>ik(f,J,A,l)),f,J,A,l,G,j=>n.set("contextRepo",j)),{spec:y,mode:B}=P,_;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)."),_=await n.ask("assigneeLogin",async()=>ce(await we({message:"your YouTrack login (the assignee value)",...v?.login?{initialValue:v.login}:{},validate:j=>j.trim().length>0?void 0:"required"})).trim()));let W=await n.ask("llmProvider",async()=>{for(;;){if(ye(await ct({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.")}}),Y=W==="claude"?await n.ask("claudeToken",()=>pw(dw("claude"),{farm:s==="farm"})):"",de;if(Y){let j=await Ap(Y);if(j){let M=pa(j);M&&(de=M,C.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${M} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let lt={projectId:f,name:g,automationLevel:k,repos:J,trackerProvider:x,youtrackProjectKey:b,language:h},ut={host:y.host,owner:y.owner},L="",U="";if($){let j=ye(await n.ask("mirrorHost",async()=>ye(await ct({message:"where should the mirrors live?",options:[{value:y.host,label:`${y.host} (same as the Context Repo)`},...["github","gitlab","bitbucket"].filter(ie=>ie!==y.host).map(ie=>({value:ie,label:ie}))],initialValue:y.host})))),M=ce(await n.ask("mirrorOwner",async()=>ye(await we({message:`account for the mirrors (${j})`,...j===y.host?{placeholder:y.owner,defaultValue:y.owner}:{}})))).trim();if(ut={host:j,owner:M||(j===y.host?y.owner:"")},!ut.owner){zw("mirrors need an account to live in");return}L=ce(await n.ask("mirrorToken",async()=>ye(await Fo({message:`token that may CREATE and PUSH repositories in ${ut.owner} (${ut.host})`})))).trim(),ut.host==="bitbucket"&&(U=ce(await n.ask("mirrorEmail",async()=>ye(await we({message:"Atlassian account email for that token",...A.bitbucket?.email?{placeholder:A.bitbucket.email,defaultValue:A.bitbucket.email}:{}})))).trim())}C.step(`${B==="attach"?"attaching to":"provisioning"} Context Repo ${y.owner}/${y.name} (${y.host})\u2026`);let O;try{O=await An(lt,y,{...sk(A),youtrackWrites:R,...v?{trackerUrl:v.url}:{},mode:B,log:{info:j=>C.message(j),warn:j=>C.warn(j)}})}catch(j){me(`Context Repo provisioning failed: ${j instanceof Error?j.message:String(j)}`)}lt.contextRepo=O,C.success(`Context Repo ready: ${O.owner}/${O.name}@${O.branch}`),C.step(`registering project on ${c}\u2026`);let q;try{q=await tr(c,u,lt)}catch(j){if(j instanceof H&&j.status===409){C.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{q=await oe(c,u,f)}catch(M){throw M instanceof H&&me(`HUB \u2192 ${M.status} ${M.message}`),M}}else if(j instanceof H&&j.status===401)n.delete("cliToken"),me("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(j instanceof H)me(`HUB \u2192 ${j.status} ${j.message}`);else throw j}let K=q.contextRepo??O;C.success(`project ${q.projectId} ready (${q.provisioningStatus})`);let E=v?{url:v.url,token:v.token}:void 0;if(s==="farm"){let j=d,M={...A,...Y?{claude:{oauthToken:Y}}:{},...E?{youtrack:E}:{}},ie=A.github?.token;if(K.host==="github"&&ie)try{let se=Vh(`devpipe-${f}`);await zh(K,ie,se.publicKey,`devpipe-${f}`),M.contextSsh={privateKey:se.privateKey},C.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(se){C.warn(`could not set up Context Repo SSH deploy key (${se instanceof Error?se.message:String(se)}); the farm will fall back to the token path.`)}let Re={projectId:f,config:{hubUrl:c,cliToken:u,projectId:f},secrets:M,contextRepo:K,projectConfig:Et(lt,R,v?.url,_||void 0,W,de)},pr=Mt(j.farm.publicKey,JSON.stringify(Re));C.step(`handing project ${f} to farm ${j.farm.name}\u2026`);let Ae;try{Ae=await Yi(c,u,j.farm.farmId,{projectId:f,sealedBundle:pr})}catch(se){throw se instanceof H&&me(se.status===409?`farm ${j.farm.name} is offline \u2014 start it and re-run.`:se.status===504?`farm ${j.farm.name} did not respond in time.`:`HUB \u2192 ${se.status} ${se.message}`),se}Ae.ok||me(`farm rejected provisioning: ${Ae.error??"unknown error"}`),await ql(c,u,f,K,ie,q.repos,null,A),n.clear(),Wl(`done. project ${f} is now hosted on farm ${j.farm.name} (daemon ${Ae.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}ak(A),await rk(e,K.cloneUrl,K.branch),ok(e),a&&await lC(e);{let j=Je(e,ht);sn(j);let M=Et(lt,R,v?.url,_||void 0,W,de),ie=lo(j,M);ie.length>0&&C.success(`local project config \u2192 .codepipe/{${ie.join(", ")}}`),Zt(f,M,{info:Re=>C.message(Re),warn:Re=>C.warn(Re)})}await nk(e,q.repos);let I=!1;if($&&(I=await uC(e,Je(e,ht),q.repos,{host:ut.host,owner:ut.owner,token:L,...U?{email:U}:{}}),I)){let j=Je(e,ht);Zt(f,{projectYaml:Is(Je(j,"project.yaml"),"utf-8"),regimenYaml:Is(Je(j,"regimen.yaml"),"utf-8")},{info:M=>C.message(M),warn:M=>C.warn(M)})}let re={hubUrl:c,cliToken:u,projectId:f,...A,...Y?{claude:{oauthToken:Y}}:{},...E?{youtrack:E}:{},...I?{mirrorWrite:{token:L,...U?{email:U}:{}}}:{}};ae(re),Nt({hubUrl:c,cliToken:u,projectId:f,accountEmail:p},f),C.success(`secrets \u2192 ${xt(f)}`),await ql(c,u,f,K,A.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,q.repos,e,A),n.clear();let ne=`${c}/?project=${encodeURIComponent(f)}`;Sr(ne),Wl(`done. your project on the dashboard (sign in there to work with it):
899
+ [up] ${m} \u2014 stopping both roles`);for(let{child:f}of c)f.exitCode===null&&f.kill(m);setTimeout(()=>{for(let{name:f,child:g}of c)g.exitCode===null&&(console.warn(`[up] ${f} did not stop \u2014 SIGKILL`),g.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:m,child:f})=>new Promise(g=>{f.on("exit",(h,k)=>g({name:m,code:h??(k?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 Ts=S(()=>{"use strict";at();Pn();Fe();Lt();wl();Er();je();pe();rt();Uo()});import{existsSync as _r,mkdirSync as qw,readFileSync as Is,readdirSync as nC,writeFileSync as Yw}from"node:fs";import{join as Je,resolve as Vw}from"node:path";import{setTimeout as Hl}from"node:timers/promises";import{cancel as zw,confirm as Bo,intro as Xw,isCancel as Yl,log as P,multiselect as oC,outro as Wl,password as Fo,select as ct,spinner as Vl,text as we}from"@clack/prompts";import{simpleGit as Cs}from"simple-git";function me(t){zw(t),process.exit(1)}function ye(t){return Yl(t)&&me("aborted"),t}function ce(t){return Yl(t)&&me("aborted"),typeof t=="string"?t:""}async function Jw(t={}){Xw("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();xw();let r=vw(e),n,o=!1;r&&Object.keys(r.answers).length>0?ye(await Bo({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(P.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new _n(e,r),o=!0):(Fl(e),n=new _n(e)):n=new _n(e);let i=t.force===!0?null:await Kl(e),s=await n.ask("target",async()=>ye(await ct({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 sC(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||Qw(e,t.force===!0));let c=await n.ask("hubUrl",async()=>ce(await we({message:"HUB URL",placeholder:lt,initialValue:X("HUB_URL")??lt,validate:j=>j.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>jn()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>Nn(c,l)),d=null;s==="farm"&&(d=await iC(c,u));let m=a?aC(a.parsed.repoName):"",f=await n.ask("projectId",async()=>ce(await we({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:j=>Ht.test(j.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await n.ask("projectName",async()=>ce(await we({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:j=>j.trim().length>0?void 0:"required"})).trim()),h=await n.ask("language",()=>yC()),k=await n.ask("automationLevel",async()=>ye(await ct({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()=>ye(await ct({message:"how much access should CodePipe have to your repositories?",options:[{value:"no",label:"read and write \u2014 branches and pull requests go into your repositories"},{value:"yes",label:"read only \u2014 CodePipe mirrors them and works in the mirrors",hint:"a mirror is a full copy of the history, in the account you choose next"}],initialValue:"no"}))))==="yes",x=await n.ask("trackerProvider",async()=>ye(await ct({message:"task tracker",options:[{value:"internal",label:"built-in \u2014 CodePipe tracks tasks itself (no external tracker needed)"},{value:"youtrack",label:"YouTrack \u2014 connect an existing YouTrack project"}],initialValue:"internal"}))),T=x==="internal",v=null,b,R=!0;if(T){let j,L=Vl();L.start("checking task-key prefixes on your account\u2026");try{j=await rh(c,u,{excludeProjectId:f}),L.stop("prefixes checked")}catch{L.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 ie=Ga(Fa(g),j);b=await n.ask("trackerPrefix",async()=>ce(await we({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:ie,initialValue:ie,validate:Re=>{let pr=Re.trim();if(!br.test(pr))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(j.has(pr.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else v=await n.ask("youtrack",()=>ck()),b=await n.ask("youtrackProjectKey",async()=>ce(await we({message:"YouTrack project key",placeholder:"DEV",validate:j=>j.trim().length>0?void 0:"required"})).trim()),R=await n.ask("youtrackWrites",async()=>ye(await Bo({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let A=n.get("tokens")??{},G=()=>n.set("tokens",A),V=await n.ask("repos",()=>dC(A,l,a,{onCred:G,initial:n.get("reposPartial")??[],onProgress:j=>n.set("reposPartial",j)}));n.delete("reposPartial");let C=null,w="",U="";if($){let j=ye(await n.ask("mirrorHost",async()=>ye(await ct({message:"where should the mirrors live? (your Context Repo will default there too)",options:["github","gitlab","bitbucket"].map(ie=>({value:ie,label:ie===V[0]?.host?`${ie} (same as your repositories)`:ie})),initialValue:V[0]?.host??"github"})))),L=ce(await n.ask("mirrorOwner",async()=>ye(await we({message:`account for the mirrors (${j})`})))).trim();if(!L){zw("mirrors need an account to live in");return}C={host:j,owner:L},w=ce(await n.ask("mirrorToken",async()=>ye(await Fo({message:`token that may CREATE and PUSH repositories in ${L} (${j})`})))).trim(),j==="bitbucket"&&(U=ce(await n.ask("mirrorEmail",async()=>ye(await we({message:"Atlassian account email for that token",...A.bitbucket?.email?{placeholder:A.bitbucket.email,defaultValue:A.bitbucket.email}:{}})))).trim())}let _=await pC(await n.ask("contextRepo",()=>ik(f,V,A,l,C??void 0)),f,V,A,l,G,j=>n.set("contextRepo",j),C??void 0),{spec:H,mode:z}=_,de;T||(P.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),de=await n.ask("assigneeLogin",async()=>ce(await we({message:"your YouTrack login (the assignee value)",...v?.login?{initialValue:v.login}:{},validate:j=>j.trim().length>0?void 0:"required"})).trim()));let Rt=await n.ask("llmProvider",async()=>{for(;;){if(ye(await ct({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.")}}),kt=Rt==="claude"?await n.ask("claudeToken",()=>pw(dw("claude"),{farm:s==="farm"})):"",M;if(kt){let j=await Ap(kt);if(j){let L=pa(j);L&&(M=L,P.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 B={projectId:f,name:g,automationLevel:k,repos:V,trackerProvider:x,youtrackProjectKey:b,language:h};P.step(`${z==="attach"?"attaching to":"provisioning"} Context Repo ${H.owner}/${H.name} (${H.host})\u2026`);let O;try{O=await An(B,H,{...sk(A),youtrackWrites:R,...v?{trackerUrl:v.url}:{},mode:z,log:{info:j=>P.message(j),warn:j=>P.warn(j)}})}catch(j){me(`Context Repo provisioning failed: ${j instanceof Error?j.message:String(j)}`)}B.contextRepo=O,P.success(`Context Repo ready: ${O.owner}/${O.name}@${O.branch}`),P.step(`registering project on ${c}\u2026`);let q;try{q=await tr(c,u,B)}catch(j){if(j instanceof W&&j.status===409){P.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{q=await oe(c,u,f)}catch(L){throw L instanceof W&&me(`HUB \u2192 ${L.status} ${L.message}`),L}}else if(j instanceof W&&j.status===401)n.delete("cliToken"),me("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(j instanceof W)me(`HUB \u2192 ${j.status} ${j.message}`);else throw j}let K=q.contextRepo??O;P.success(`project ${q.projectId} ready (${q.provisioningStatus})`);let E=v?{url:v.url,token:v.token}:void 0;if(s==="farm"){let j=d,L={...A,...kt?{claude:{oauthToken:kt}}:{},...E?{youtrack:E}:{}},ie=A.github?.token;if(K.host==="github"&&ie)try{let se=Vh(`devpipe-${f}`);await zh(K,ie,se.publicKey,`devpipe-${f}`),L.contextSsh={privateKey:se.privateKey},P.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(se){P.warn(`could not set up Context Repo SSH deploy key (${se instanceof Error?se.message:String(se)}); the farm will fall back to the token path.`)}let Re={projectId:f,config:{hubUrl:c,cliToken:u,projectId:f},secrets:L,contextRepo:K,projectConfig:St(B,R,v?.url,de||void 0,Rt,M)},pr=Mt(j.farm.publicKey,JSON.stringify(Re));P.step(`handing project ${f} to farm ${j.farm.name}\u2026`);let Ae;try{Ae=await Yi(c,u,j.farm.farmId,{projectId:f,sealedBundle:pr})}catch(se){throw se instanceof W&&me(se.status===409?`farm ${j.farm.name} is offline \u2014 start it and re-run.`:se.status===504?`farm ${j.farm.name} did not respond in time.`:`HUB \u2192 ${se.status} ${se.message}`),se}Ae.ok||me(`farm rejected provisioning: ${Ae.error??"unknown error"}`),await ql(c,u,f,K,ie,q.repos,null,A),n.clear(),Wl(`done. project ${f} is now hosted on farm ${j.farm.name} (daemon ${Ae.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}ak(A),await rk(e,K.cloneUrl,K.branch),ok(e),a&&await lC(e);{let j=Je(e,ft);sn(j);let L=St(B,R,v?.url,de||void 0,Rt,M),ie=lo(j,L);ie.length>0&&P.success(`local project config \u2192 .codepipe/{${ie.join(", ")}}`),Zt(f,L,{info:Re=>P.message(Re),warn:Re=>P.warn(Re)})}await nk(e,q.repos);let I=!1;if($&&C&&(I=await uC(e,Je(e,ft),q.repos,{host:C.host,owner:C.owner,token:w,...U?{email:U}:{}}),I)){let j=Je(e,ft);Zt(f,{projectYaml:Is(Je(j,"project.yaml"),"utf-8"),regimenYaml:Is(Je(j,"regimen.yaml"),"utf-8")},{info:L=>P.message(L),warn:L=>P.warn(L)})}let re={hubUrl:c,cliToken:u,projectId:f,...A,...kt?{claude:{oauthToken:kt}}:{},...E?{youtrack:E}:{},...I?{mirrorWrite:{token:w,...U?{email:U}:{}}}:{}};ae(re),Nt({hubUrl:c,cliToken:u,projectId:f,accountEmail:p},f),P.success(`secrets \u2192 ${vt(f)}`),await ql(c,u,f,K,A.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,q.repos,e,A),n.clear();let ne=`${c}/?project=${encodeURIComponent(f)}`;Sr(ne),Wl(`done. your project on the dashboard (sign in there to work with it):
900
900
  ${ne}
901
- 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:Gt}=await Promise.resolve().then(()=>(Ts(),Hw));await Gt({profile:void 0})}async function ql(t,e,r,n,o,i=[],s=null,a={}){let c=await Tw(n,o),l=!1;if(!c)try{l=await Cw(i,{localRoot:s,tokens:a})}catch{l=!1}let u=Ew({indexExists:c,localClones:s!==null,reposNonEmpty:l}),p=await oC({message:u.message,options:u.options,initialValues:u.initialValues,required:!1});if(Yl(p))return;let d=new Set(p);if(d.has("map")&&s!==null)try{let m=Pe(s);if(!m)throw new Error("workspace not found");let{bootstrapWorkspaceModel:f}=await Promise.resolve().then(()=>(Ro(),es)),g=await f(m,void 0,{onLog:h=>C.message(h)});C.success(`project map ready: ${g.events} task events mined from history`)}catch(m){C.warn(`could not build the project map: ${m instanceof Error?m.message:String(m)}. Registration is not affected \u2014 run \`codepipe model bootstrap\` later.`)}if(d.has("backfill"))try{let{jobId:m}=await Io(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 Io(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 iC(t,e){let r;try{r=await Zm(t,e)}catch(c){throw c instanceof H&&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=ye(await ct({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=Wi(i.farmId,i.publicKey)}catch(c){me(c instanceof Error?c.message:String(c))}return ye(await Bo({message:`confirm farm ${i.name} cred-channel fingerprint:
901
+ 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:Gt}=await Promise.resolve().then(()=>(Ts(),Hw));await Gt({profile:void 0})}async function ql(t,e,r,n,o,i=[],s=null,a={}){let c=await Tw(n,o),l=!1;if(!c)try{l=await Cw(i,{localRoot:s,tokens:a})}catch{l=!1}let u=Ew({indexExists:c,localClones:s!==null,reposNonEmpty:l}),p=await oC({message:u.message,options:u.options,initialValues:u.initialValues,required:!1});if(Yl(p))return;let d=new Set(p);if(d.has("map")&&s!==null)try{let m=Pe(s);if(!m)throw new Error("workspace not found");let{bootstrapWorkspaceModel:f}=await Promise.resolve().then(()=>(Ro(),es)),g=await f(m,void 0,{onLog:h=>P.message(h)});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 Io(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 Io(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 iC(t,e){let r;try{r=await Zm(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=ye(await ct({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=Wi(i.farmId,i.publicKey)}catch(c){me(c instanceof Error?c.message:String(c))}return ye(await Bo({message:`confirm farm ${i.name} cred-channel fingerprint:
902
902
  ${s}
903
- (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||me("farm fingerprint not confirmed \u2014 aborting."),Hi(i.farmId,s),{farm:i,fingerprint:s}}async function Zw(t){Xw(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();Qw(e,t.force===!0);let r=ce(await we({message:"HUB URL",initialValue:z("HUB_URL")??dt,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await jn(),{cliToken:o,accountEmail:i}=await Nn(r,n);C.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await oe(r,o,t.projectId)}catch(d){throw d instanceof H&&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 ck(),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 Rs(d,l,m?.owner??s.contextRepo.owner,n,m?.repoName)}ak(l),await rk(e,s.contextRepo.cloneUrl,s.contextRepo.branch),ok(e);{let d=Je(e,ht);sn(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=Et(m,!0,c?.url,void 0,s.llmProvider??Ye),g=lo(d,f);g.length>0&&C.success(`local project config \u2192 .codepipe/{${g.join(", ")}} (defaults \u2014 review and adjust)`),Zt(t.projectId,f,{info:h=>C.message(h),warn:h=>C.warn(h)})}await nk(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};ae(p),Nt({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),C.success(`secrets \u2192 ${xt(t.projectId)}`),await ql(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),Wl("done.")}function Qw(t,e){if(!_r(t)){qw(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=nC(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 Kl(t){if(!_r(Je(t,".git")))return null;try{let e=He(await ek(t));return e?{parsed:e,defaultBranch:await tk(t)}:null}catch{return null}}async function ek(t){try{return(await Cs(t).remote(["get-url","origin"])||"").toString().trim()}catch{return""}}async function sC(t,e){if(!_r(Je(t,".git")))return null;let r=await e.ask("inPlaceOrigin",async()=>{let o=await ek(t);return C.warn(o?`this folder is a git checkout, but its origin (${o}) is not a github.com / gitlab.com / bitbucket.org URL`:"this folder is a git checkout without an `origin` remote"),ce(await we({message:"clone URL of this repository \u2014 blank if this folder is not the project repo",placeholder:"git@github.com:acme/api.git",validate:i=>!i||!i.trim()||He(i)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim()}),n=r?He(r):null;return n?{parsed:n,defaultBranch:await tk(t)}:null}async function tk(t){let e=Cs(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 aC(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Ht.test(e)?e:""}function cC(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function lC(t){let e=Je(t,".gitignore"),r=_r(e)?Is(e,"utf-8"):"";if(cC(r))return;if(!ye(await Bo({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(`
903
+ (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||me("farm fingerprint not confirmed \u2014 aborting."),Hi(i.farmId,s),{farm:i,fingerprint:s}}async function Zw(t){Xw(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();Qw(e,t.force===!0);let r=ce(await we({message:"HUB URL",initialValue:X("HUB_URL")??lt,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await jn(),{cliToken:o,accountEmail:i}=await Nn(r,n);P.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await oe(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 ck(),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 Rs(d,l,m?.owner??s.contextRepo.owner,n,m?.repoName)}ak(l),await rk(e,s.contextRepo.cloneUrl,s.contextRepo.branch),ok(e);{let d=Je(e,ft);sn(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=St(m,!0,c?.url,void 0,s.llmProvider??Ye),g=lo(d,f);g.length>0&&P.success(`local project config \u2192 .codepipe/{${g.join(", ")}} (defaults \u2014 review and adjust)`),Zt(t.projectId,f,{info:h=>P.message(h),warn:h=>P.warn(h)})}await nk(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};ae(p),Nt({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),P.success(`secrets \u2192 ${vt(t.projectId)}`),await ql(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),Wl("done.")}function Qw(t,e){if(!_r(t)){qw(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=nC(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 Kl(t){if(!_r(Je(t,".git")))return null;try{let e=He(await ek(t));return e?{parsed:e,defaultBranch:await tk(t)}:null}catch{return null}}async function ek(t){try{return(await Cs(t).remote(["get-url","origin"])||"").toString().trim()}catch{return""}}async function sC(t,e){if(!_r(Je(t,".git")))return null;let r=await e.ask("inPlaceOrigin",async()=>{let o=await ek(t);return P.warn(o?`this folder is a git checkout, but its origin (${o}) is not a github.com / gitlab.com / bitbucket.org URL`:"this folder is a git checkout without an `origin` remote"),ce(await we({message:"clone URL of this repository \u2014 blank if this folder is not the project repo",placeholder:"git@github.com:acme/api.git",validate:i=>!i||!i.trim()||He(i)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim()}),n=r?He(r):null;return n?{parsed:n,defaultBranch:await tk(t)}:null}async function tk(t){let e=Cs(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 aC(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Ht.test(e)?e:""}function cC(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function lC(t){let e=Je(t,".gitignore"),r=_r(e)?Is(e,"utf-8"):"";if(cC(r))return;if(!ye(await Bo({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(`
904
904
  `)?"":`
905
905
  `;Yw(e,r+o+`
906
906
  # codepipe workspace (added by \`codepipe init\`)
907
907
  .codepipe/
908
- `),C.success(`.codepipe/ added to ${Vw(e)}`)}async function jn(){let t="";try{t=(await Cs().raw(["config","--global","user.email"])||"").trim()}catch{}return ce(await we({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function Nn(t,e){C.step(`connecting account ${e}`);let r;try{r=await nh(t,e)}catch(s){throw s instanceof To&&me(`${e} is not authorized on this HUB yet.
908
+ `),P.success(`.codepipe/ added to ${Vw(e)}`)}async function jn(){let t="";try{t=(await Cs().raw(["config","--global","user.email"])||"").trim()}catch{}return ce(await we({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function Nn(t,e){P.step(`connecting account ${e}`);let r;try{r=await nh(t,e)}catch(s){throw s instanceof To&&me(`${e} is not authorized on this HUB yet.
909
909
  Sign up at ${t} (registration form on the login screen),
910
910
  wait for the operator to approve it by email, then re-run
911
- \`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&&(Sr(r.authorizeUrl),C.message(`a browser tab was opened to confirm this CLI:
911
+ \`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&&(Sr(r.authorizeUrl),P.message(`a browser tab was opened to confirm this CLI:
912
912
  ${r.authorizeUrl}
913
913
  `+(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
914
- 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 oh(t,r.requestId)}catch(a){C.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await Hl(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"&&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,C.message(`email confirmed. waiting for the operator to approve your account\u2026
915
- (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await Hl(5e3);continue}await Hl(2e3)}me("bootstrap timed out")}async function rk(t,e,r){let n=Je(t,ht);if(_r(Je(n,".git"))){C.message(`${n} already cloned \u2014 skipping`);return}_r(n)&&me(`${n} exists but is not a git repo \u2014 remove it and re-run`),qw(n,{recursive:!0}),C.step(`cloning Context Repo \u2192 ${n}`);try{await Cs().clone(e,n,["--branch",r]),C.success(`cloned ${e}`)}catch(o){me(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function uC(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:Dw(a.repoName)};try{let l=await Lw(c,i,o);await Mw(Je(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)zf(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 nk(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 Do(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 ok(t){let e=Je(t,ht,".gitignore"),r="";if(_r(e)&&(r=Is(e,"utf-8")),Ww.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
914
+ 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 oh(t,r.requestId)}catch(a){P.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await Hl(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
915
+ (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await Hl(5e3);continue}await Hl(2e3)}me("bootstrap timed out")}async function rk(t,e,r){let n=Je(t,ft);if(_r(Je(n,".git"))){P.message(`${n} already cloned \u2014 skipping`);return}_r(n)&&me(`${n} exists but is not a git repo \u2014 remove it and re-run`),qw(n,{recursive:!0}),P.step(`cloning Context Repo \u2192 ${n}`);try{await Cs().clone(e,n,["--branch",r]),P.success(`cloned ${e}`)}catch(o){me(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function uC(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:Dw(a.repoName)};try{let l=await Lw(c,i,o);await Mw(Je(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)zf(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 nk(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 Do(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 ok(t){let e=Je(t,ft,".gitignore"),r="";if(_r(e)&&(r=Is(e,"utf-8")),Ww.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
916
916
  `)||r.length===0?"":`
917
917
  `,i=Ww.join(`
918
918
  `)+`
919
919
  `;Yw(e,r+o+(r?`
920
- `:"")+i),C.message(`appended runtime entries to ${Vw(e)}`)}async function dC(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;await Rs(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(;ye(await Bo({message:o.length===0?"Add a project repository?":`Project repositories: ${o.map(m=>m.name).join(", ")}. Add another one?`,initialValue:o.length===0}));){let a=ce(await we({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:m=>!m||!m.trim()||He(m)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!a)continue;let c=He(a);C.message(`${c.host}: ${c.owner}/${c.repoName}`),await Rs(c.host,t,c.owner,e,c.repoName),i?.();let l=ce(await we({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:m=>m.trim().length>0?void 0:"required"})).trim(),u=ce(await we({message:"default branch (optional)",placeholder:"main"})).trim(),p=ce(await we({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),d={name:l,host:c.host,owner:c.owner,repoName:c.repoName};u&&(d.defaultBranch=u),p&&p!==l&&(d.mountAs=p),o.push(d),n.onProgress?.(o)}return o}async function ik(t,e,r,n){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 o=ye(await ct({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));o==="attach"&&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 i=e[0]?.host,s=e[0]?.owner,a;if(i&&s){let c=ce(await we({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:vt(t),validate:u=>{let p=(u??"").trim();if(!p)return"required";if(!He(p)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(p))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),l=He(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await fC(),l=ce(await we({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=ce(await we({message:"Context Repo name",placeholder:vt(t),initialValue:vt(t),validate:p=>p.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:o}}function sk(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??Zr()}}async function pC(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await Rs(c.host,n,c.owner,o),i?.();let u=Vl();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let p=await mw(c,sk(n),{explain:l==="attach"});if(p.found===!0)return u.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(p.found==="unknown")return u.stop(`could not check ${c.owner}/${c.name} (${p.detail}) \u2014 continuing`,1),a;if(l==="create")return u.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;u.stop(p.detail,1);let d=ye(await ct({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(d==="abort"&&me("aborted"),d==="create")return a={spec:c,mode:"create"},s(a),a;a=await ik(e,r,n,o),s(a)}}async function fC(){return ye(await ct({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Ps(t,e){let r=Vl();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 ak(t){go(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),yo(t.gitlab?.token??process.env.GITLAB_TOKEN),wo(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Rs(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await mC(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 hC(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 gC();i?e.gitlab=i:C.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function mC(t){for(;;){let e=ce(await Fo({message:`GitHub PAT \u2014 blank to skip
920
+ `:"")+i),P.message(`appended runtime entries to ${Vw(e)}`)}async function dC(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;await Rs(s.host,t,s.owner,e,s.repoName),i?.(),o.push({name:s.repoName,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:a,mountAs:"."}),n.onProgress?.(o),P.success(`added this repository: ${s.host}: ${s.owner}/${s.repoName} (this folder, default branch ${a})`)}for(;ye(await Bo({message:o.length===0?"Add a project repository?":`Project repositories: ${o.map(m=>m.name).join(", ")}. Add another one?`,initialValue:o.length===0}));){let a=ce(await we({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:m=>!m||!m.trim()||He(m)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!a)continue;let c=He(a);P.message(`${c.host}: ${c.owner}/${c.repoName}`),await Rs(c.host,t,c.owner,e,c.repoName),i?.();let l=ce(await we({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:m=>m.trim().length>0?void 0:"required"})).trim(),u=ce(await we({message:"default branch (optional)",placeholder:"main"})).trim(),p=ce(await we({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),d={name:l,host:c.host,owner:c.owner,repoName:c.repoName};u&&(d.defaultBranch=u),p&&p!==l&&(d.mountAs=p),o.push(d),n.onProgress?.(o)}return o}async function ik(t,e,r,n,o){P.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let i=ye(await ct({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));i==="attach"&&P.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let s=o?.host??e[0]?.host,a=o?.owner??e[0]?.owner,c;if(s&&a){let l=ce(await we({message:`Context Repo \u2014 a name (hosted at ${s}: ${a}/<name>) or a full clone URL`,initialValue:$t(t),validate:p=>{let d=(p??"").trim();if(!d)return"required";if(!He(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=He(l);c=u?{host:u.host,owner:u.owner,name:u.repoName}:{host:s,owner:a,name:l}}else{let l=await fC(),u=ce(await we({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:d=>d.trim().length>0?void 0:"required"})).trim(),p=ce(await we({message:"Context Repo name",placeholder:$t(t),initialValue:$t(t),validate:d=>d.trim().length>0?void 0:"required"})).trim();c={host:l,owner:u,name:p}}return{spec:c,mode:i}}function sk(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??Zr()}}async function pC(t,e,r,n,o,i,s,a){let c=t;for(;;){let{spec:l,mode:u}=c;await Rs(l.host,n,l.owner,o),i?.();let p=Vl();p.start(`checking ${l.owner}/${l.name} on ${l.host}\u2026`);let d=await mw(l,sk(n),{explain:u==="attach"});if(d.found===!0)return p.stop(`${l.owner}/${l.name} found${u==="create"?" \u2014 existing repo will be reused":""}`),c;if(d.found==="unknown")return p.stop(`could not check ${l.owner}/${l.name} (${d.detail}) \u2014 continuing`,1),c;if(u==="create")return p.stop(`${l.owner}/${l.name} not found \u2014 will be created`),c;p.stop(d.detail,1);let m=ye(await ct({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 ik(e,r,n,o,a),s(c)}}async function fC(){return ye(await ct({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Ps(t,e){let r=Vl();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 ak(t){go(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),yo(t.gitlab?.token??process.env.GITLAB_TOKEN),wo(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Rs(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await mC(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 hC(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 gC();i?e.gitlab=i:P.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function mC(t){for(;;){let e=ce(await Fo({message:`GitHub PAT \u2014 blank to skip
921
921
  classic PAT: 'repo' + 'workflow'
922
922
  fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
923
923
  if org: approve token in org Settings \u2192 Personal access tokens.
924
- (Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo.)`})).trim();if(!e)return;if(await Ps("GitHub",()=>Wt(e,t?{owner:t}:void 0)))return{token:e};C.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function hC(t,e,r){for(C.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
924
+ (Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo.)`})).trim();if(!e)return;if(await Ps("GitHub",()=>Wt(e,t?{owner:t}:void 0)))return{token:e};P.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function hC(t,e,r){for(P.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
925
925
  How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
926
926
  'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes:
927
927
  read:repository:bitbucket + write:repository:bitbucket +
928
928
  read:pullrequest:bitbucket + write:pullrequest:bitbucket
929
929
  \u2014 write scopes do NOT include read: pick BOTH scopes of each pair
930
930
  (+ admin:repository:bitbucket if this token will provision the Context Repo).
931
- The token is shown ONCE \u2014 copy it right away.`);;){let n=ce(await we({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:i=>!i||!i.trim()||i.includes("@")?void 0:"must be an email"})).trim();if(!n)return;let o=ce(await Fo({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 Ps("Bitbucket",async()=>{let i=await qt(n,o,t);if(t&&r){let s=await di(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 gC(){for(;;){let t=ce(await Fo({message:`GitLab PAT \u2014 blank to skip
932
- scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Ps("GitLab",()=>Yt(t))){let e=await Qd(t);return e&&C.warn(e),{token:t}}C.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function yC(){let t="__other__",e=async()=>ce(await we({message:"language name (in English, e.g. Ukrainian)",validate:s=>{let a=s.trim();if(a.length===0)return"required";if(a.length>40)return`\u2264 ${40} chars`}})).trim(),r=ye(await ct({message:"project language",options:[...Hr.map(s=>({value:s,label:s==="English"?"English (default)":s})),{value:t,label:"other\u2026"}],initialValue:"English"})),n=r===t?await e():r;if(n==="English")return{primary:n,context:n,tasks:n,docs:n,code_comments:n,chat:ve};let o=[{key:"context",label:"context documents (knowledge, ADRs, task artifacts)",initial:n},{key:"tasks",label:"tracker issues the agent drafts",initial:n},{key:"docs",label:"documentation in the project repos",initial:n},{key:"code_comments",label:"code comments",initial:n},{key:"chat",label:"chat with the agent",initial:ve}],i={primary:n};for(let s of o){let a=new Set,c=[s.initial,n,"English",ve].filter(u=>a.has(u)?!1:(a.add(u),!0)).map(u=>({value:u,label:u===ve?"auto \u2014 mirror the language of the user's material":u}));c.push({value:t,label:"other\u2026"});let l=ye(await ct({message:`language for ${s.label}`,options:c,initialValue:s.initial}));i[s.key]=l===t?await e():l}return i}async function ck(){for(;;){let t=ce(await we({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let n=r.trim();if(!n)return"required";if(!n.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=ce(await Fo({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Ps("YouTrack",()=>Xt({baseUrl:t,token:e}))){let r=await fp({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}C.warn("re-enter the YouTrack URL / token.")}}var Ww,Uo=S(()=>{"use strict";Be();F();at();fw();fi();Fe();Lt();Er();rn();Lo();yl();ks();Vt();xr();Sw();je();Iw();Pw();Jc();Ti();pe();$s();Pc();Uw();rt();Ww=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});F();Be();Fe();import{Command as SP}from"commander";Fe();pe();async function Wd(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=gt(e);r&&!t.force&&(console.error(`already configured at ${zr(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");Nt({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...V(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};ae(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${zr(e)}`)}Va();Fe();import{homedir as kl}from"node:os";import{join as Co}from"node:path";Be();F();import{existsSync as Wh,rmSync as lE}from"node:fs";import{join as Cr}from"node:path";import{simpleGit as uE}from"simple-git";import"ws";Be();pe();import{createHash as k$}from"node:crypto";import{existsSync as b$,readFileSync as $$}from"node:fs";import{homedir as v$,hostname as za}from"node:os";import{join as x$}from"node:path";function zd(t){return k$("sha256").update(t).digest("hex").slice(0,12)}function S$(){let t=z("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=x$(v$(),".claude","credentials.json");if(!b$(e))return;let r=JSON.parse($$(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 Xd(t){let e=S$(),r=z("ACCOUNT_ID")?.trim(),n=z("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=Jr(t);return o?{accountId:`acct-${zd(o)}`,label:n||za(),...e?{email:e}:{}}:{accountId:`acct-${zd(`host:${za()}`)}`,label:n||za(),...e?{email:e}:{}}}Be();rn();pe();lc();async function Op(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(z("ORIGIN")==="farm"||z("CLAUDE_AUTOLOGIN")!=="1"){s("autologin_disabled");return}let a;try{a=await cc(pi())}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 Ot(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=V(t.projectId);if(!u){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"no secrets file for this project on the CLI"}),n.warn("[agent-auth] no secrets file for this project \u2014 token not saved");return}u.claude={oauthToken:c.oauthToken},ae(u),n.info(`[agent-auth] Claude token replaced (${c.oauthToken.slice(0,12)}\u2026, ${c.oauthToken.length} chars)`),i({type:"agent_login_result",projectId:t.projectId,ok:!0,...l==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}}),o()}catch(c){let l=c instanceof Error?c.message:String(c);i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:l}),n.warn(`[agent-auth] browser authorization failed: ${l}`)}finally{a.close()}}Be();function Lp(t,e){let r=t.find(n=>n.kind==="claude");return r?.present===!0&&r.ok===!1?z("ORIGIN")==="farm"||z("CLAUDE_AUTOLOGIN")!=="1"||e?"none":"open":r?.ok===!0?"rearm":"none"}function Mp(t,e){return`${t.replace(/\/$/,"")}/?project=${encodeURIComponent(e)}`}fi();import{existsSync as X$}from"node:fs";import{join as J$}from"node:path";import{simpleGit as Z$}from"simple-git";async function Dp(t,e){if(!X$(J$(t,".git")))return{status:"skipped"};let r=Z$(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${Q$(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 Q$(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as dc,readFileSync as Kp,readdirSync as rv,watch as nv}from"node:fs";import{join as co}from"node:path";F();import{existsSync as Up,readFileSync as Bp,readdirSync as ev,statSync as tv}from"node:fs";import{join as uc}from"node:path";import{parse as Fp}from"yaml";function mi(t){let e=uc(t,"actions"),r=[],n=[];if(!Up(e))return{defs:r,errors:n};let o;try{o=ev(e).sort()}catch{return{defs:r,errors:n}}let i=new Set;for(let s of o){if(!/\.(yml|yaml)$/i.test(s))continue;let a=uc(e,s);try{if(!tv(a).isFile())continue;let c=ya(s,Fp(Bp(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 Gp(t){let e={},r=uc(t,"project.yaml");if(!Up(r))return e;let n;try{n=Fp(Bp(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))!Ve.test(i)||_t(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var hi=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,co(this.contextDir,"prompts"),co(this.contextDir,"actions")];for(let n of r)if(dc(n))try{let o=nv(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=mi(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=co(this.contextDir,e);if(!dc(r))return null;try{return Kp(r,"utf-8")}catch{return null}}readPrompts(){let e=co(this.contextDir,"prompts"),r={};if(!dc(e))return r;let n;try{n=rv(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=Kp(co(e,o),"utf-8")}catch{}}return r}};st();import{existsSync as kc,readFileSync as Xp,readdirSync as gv}from"node:fs";import{join as Jp}from"node:path";import{simpleGit as yv}from"simple-git";var wv=/^(\d{4})-(.+)\.md$/,kv="0000-template.md";function bv(t){let e=t.split(`
931
+ The token is shown ONCE \u2014 copy it right away.`);;){let n=ce(await we({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:i=>!i||!i.trim()||i.includes("@")?void 0:"must be an email"})).trim();if(!n)return;let o=ce(await Fo({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 Ps("Bitbucket",async()=>{let i=await qt(n,o,t);if(t&&r){let s=await di(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 gC(){for(;;){let t=ce(await Fo({message:`GitLab PAT \u2014 blank to skip
932
+ scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Ps("GitLab",()=>Yt(t))){let e=await Qd(t);return e&&P.warn(e),{token:t}}P.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function yC(){let t="__other__",e=async()=>ce(await we({message:"language name (in English, e.g. Ukrainian)",validate:s=>{let a=s.trim();if(a.length===0)return"required";if(a.length>40)return`\u2264 ${40} chars`}})).trim(),r=ye(await ct({message:"project language",options:[...Hr.map(s=>({value:s,label:s==="English"?"English (default)":s})),{value:t,label:"other\u2026"}],initialValue:"English"})),n=r===t?await e():r;if(n==="English")return{primary:n,context:n,tasks:n,docs:n,code_comments:n,chat:ve};let o=[{key:"context",label:"context documents (knowledge, ADRs, task artifacts)",initial:n},{key:"tasks",label:"tracker issues the agent drafts",initial:n},{key:"docs",label:"documentation in the project repos",initial:n},{key:"code_comments",label:"code comments",initial:n},{key:"chat",label:"chat with the agent",initial:ve}],i={primary:n};for(let s of o){let a=new Set,c=[s.initial,n,"English",ve].filter(u=>a.has(u)?!1:(a.add(u),!0)).map(u=>({value:u,label:u===ve?"auto \u2014 mirror the language of the user's material":u}));c.push({value:t,label:"other\u2026"});let l=ye(await ct({message:`language for ${s.label}`,options:c,initialValue:s.initial}));i[s.key]=l===t?await e():l}return i}async function ck(){for(;;){let t=ce(await we({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let n=r.trim();if(!n)return"required";if(!n.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=ce(await Fo({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Ps("YouTrack",()=>Xt({baseUrl:t,token:e}))){let r=await fp({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}P.warn("re-enter the YouTrack URL / token.")}}var Ww,Uo=S(()=>{"use strict";Be();F();at();fw();fi();Fe();Lt();Er();rn();Lo();yl();ks();Vt();xr();Sw();je();Iw();Pw();Jc();Ti();pe();$s();Pc();Uw();rt();Ww=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});F();Be();Fe();import{Command as SP}from"commander";Fe();pe();async function Wd(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=mt(e);r&&!t.force&&(console.error(`already configured at ${zr(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");Nt({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...Y(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};ae(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${zr(e)}`)}Va();Fe();import{homedir as kl}from"node:os";import{join as Co}from"node:path";Be();F();import{existsSync as Wh,rmSync as lE}from"node:fs";import{join as Cr}from"node:path";import{simpleGit as uE}from"simple-git";import"ws";Be();pe();import{createHash as k$}from"node:crypto";import{existsSync as b$,readFileSync as $$}from"node:fs";import{homedir as v$,hostname as za}from"node:os";import{join as x$}from"node:path";function zd(t){return k$("sha256").update(t).digest("hex").slice(0,12)}function S$(){let t=X("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=x$(v$(),".claude","credentials.json");if(!b$(e))return;let r=JSON.parse($$(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 Xd(t){let e=S$(),r=X("ACCOUNT_ID")?.trim(),n=X("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=Jr(t);return o?{accountId:`acct-${zd(o)}`,label:n||za(),...e?{email:e}:{}}:{accountId:`acct-${zd(`host:${za()}`)}`,label:n||za(),...e?{email:e}:{}}}Be();rn();pe();lc();async function Op(t,e,r,n,o){let i=c=>{e.readyState===e.OPEN&&e.send(JSON.stringify(c))},s=c=>i({type:"agent_login_url",requestId:r.requestId,projectId:t.projectId,error:c});if(X("ORIGIN")==="farm"||X("CLAUDE_AUTOLOGIN")!=="1"){s("autologin_disabled");return}let a;try{a=await cc(pi())}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 Ot(c.oauthToken);if(l==="invalid"){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"token rejected (401) \u2014 previous token kept"}),n.warn("[agent-auth] new Claude token rejected (401) \u2014 previous token kept");return}let u=Y(t.projectId);if(!u){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"no secrets file for this project on the CLI"}),n.warn("[agent-auth] no secrets file for this project \u2014 token not saved");return}u.claude={oauthToken:c.oauthToken},ae(u),n.info(`[agent-auth] Claude token replaced (${c.oauthToken.slice(0,12)}\u2026, ${c.oauthToken.length} chars)`),i({type:"agent_login_result",projectId:t.projectId,ok:!0,...l==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}}),o()}catch(c){let l=c instanceof Error?c.message:String(c);i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:l}),n.warn(`[agent-auth] browser authorization failed: ${l}`)}finally{a.close()}}Be();function Lp(t,e){let r=t.find(n=>n.kind==="claude");return r?.present===!0&&r.ok===!1?X("ORIGIN")==="farm"||X("CLAUDE_AUTOLOGIN")!=="1"||e?"none":"open":r?.ok===!0?"rearm":"none"}function Mp(t,e){return`${t.replace(/\/$/,"")}/?project=${encodeURIComponent(e)}`}fi();import{existsSync as X$}from"node:fs";import{join as J$}from"node:path";import{simpleGit as Z$}from"simple-git";async function Dp(t,e){if(!X$(J$(t,".git")))return{status:"skipped"};let r=Z$(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${Q$(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 Q$(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as dc,readFileSync as Kp,readdirSync as rv,watch as nv}from"node:fs";import{join as co}from"node:path";F();import{existsSync as Up,readFileSync as Bp,readdirSync as ev,statSync as tv}from"node:fs";import{join as uc}from"node:path";import{parse as Fp}from"yaml";function mi(t){let e=uc(t,"actions"),r=[],n=[];if(!Up(e))return{defs:r,errors:n};let o;try{o=ev(e).sort()}catch{return{defs:r,errors:n}}let i=new Set;for(let s of o){if(!/\.(yml|yaml)$/i.test(s))continue;let a=uc(e,s);try{if(!tv(a).isFile())continue;let c=ya(s,Fp(Bp(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 Gp(t){let e={},r=uc(t,"project.yaml");if(!Up(r))return e;let n;try{n=Fp(Bp(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))!Ve.test(i)||_t(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var hi=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,co(this.contextDir,"prompts"),co(this.contextDir,"actions")];for(let n of r)if(dc(n))try{let o=nv(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=mi(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=co(this.contextDir,e);if(!dc(r))return null;try{return Kp(r,"utf-8")}catch{return null}}readPrompts(){let e=co(this.contextDir,"prompts"),r={};if(!dc(e))return r;let n;try{n=rv(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=Kp(co(e,o),"utf-8")}catch{}}return r}};st();import{existsSync as kc,readFileSync as Xp,readdirSync as gv}from"node:fs";import{join as Jp}from"node:path";import{simpleGit as yv}from"simple-git";var wv=/^(\d{4})-(.+)\.md$/,kv="0000-template.md";function bv(t){let e=t.split(`
933
933
  `),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 $v(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
934
- `),a=s.findIndex(k=>k.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 k=m;k<s.length;k++){let w=(s[k]??"").trim();if(w===""){m=k+1;continue}let $=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(w);if(!$)break;let x=($[1]??"").trim().toLowerCase(),T=($[2]??"").trim(),v=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(w);v&&(d=parseInt(v[1]??"",10)),x==="tasks"&&(p=T),l.has(x)||u.push(w),m=k+1}let f=p?p.includes(n)?p:`${p}, ${n}`:n,g=s.slice(m).join(`
934
+ `),a=s.findIndex(k=>k.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 k=m;k<s.length;k++){let y=(s[k]??"").trim();if(y===""){m=k+1;continue}let $=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(y);if(!$)break;let x=($[1]??"").trim().toLowerCase(),T=($[2]??"").trim(),v=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(y);v&&(d=parseInt(v[1]??"",10)),x==="tasks"&&(p=T),l.has(x)||u.push(y),m=k+1}let f=p?p.includes(n)?p:`${p}, ${n}`:n,g=s.slice(m).join(`
935
935
  `).replace(/^\n+/,""),h=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${f}`,...u,"",g].join(`
936
936
  `);return{content:h.endsWith(`
937
937
  `)?h:h+`
@@ -939,11 +939,11 @@ starting codepipe up \u2014 the CLI daemon and an agent worker, with their logs
939
939
 
940
940
  - **Status:** superseded by ADR-${r}`):n}function xv(t){let e=["# ADR index","","<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->",""];if(t.length===0)e.push("(no accepted ADRs yet)");else for(let r of[...t].sort((n,o)=>n.num-o.num)){let n=String(r.num).padStart(4,"0"),o=[r.header.status||"accepted",r.header.date].filter(Boolean).join(", ");e.push(`- [ADR-${n} \u2014 ${r.header.title||r.file}](${r.file}) \u2014 ${o}`)}return e.join(`
941
941
  `)+`
942
- `}async function Zp(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=h=>o==="staging"?`adr/DRAFT-${h}.md`:`tasks/${e}/adr/DRAFT-${h}.md`,s=[],a=[];for(let h of r){let k=xe(t,i(h));if(!kc(k)){a.push(h);continue}s.push({slug:h,content:Xp(k,"utf-8")})}let c=Jp(t,"adr"),l=new Map;if(kc(c))for(let h of gv(c)){let k=wv.exec(h);!k||h===kv||l.set(h,{num:parseInt(k[1]??"",10),slug:k[2]??"",content:Xp(Jp(c,h),"utf-8")})}let u=Math.max(0,...[...l.values()].map(h=>h.num))+1,p=new Map,d=[],m=[];for(let h of s){if([...l.entries()].find(([,v])=>v.slug===h.slug&&v.content.includes(e))){m.push(h.slug);continue}let w=u++,$=`${String(w).padStart(4,"0")}-${h.slug}.md`,{content:x,supersedes:T}=$v(h.content,w,h.slug,e,n);if(p.set($,x),l.set($,{num:w,slug:h.slug,content:x}),d.push(`adr/${$}`),T!==null){let v=[...l.keys()].find(b=>b.startsWith(`${String(T).padStart(4,"0")}-`));if(v&&v!==$){let b=vv(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 h of s)kc(xe(t,`adr/DRAFT-${h.slug}.md`))&&f.push({path:`adr/DRAFT-${h.slug}.md`,content:"",deleted:!0});if(d.length===0&&f.length===0)return{promoted:d,skipped:m,missing:a};if(d.length>0){let h=[...l.entries()].map(([k,w])=>({num:w.num,file:k,header:bv(w.content)}));p.set("INDEX.md",xv(h))}for(let[h,k]of p.entries())f.push({path:`adr/${h}`,content:k});let g=d.length>0?`adr(${e}): promote ${s.map(h=>h.slug).join(", ")}`:`adr(${e}): drop stale staged ${m.join(", ")}`;return await Te(t,f,g),{promoted:d,skipped:m,missing:a}}st();Lt();F();import{existsSync as Qp,readFileSync as Sv}from"node:fs";import{join as ef}from"node:path";function Ev(t){for(let e of[ft,Br]){let r=ef(t,e);if(Qp(r))try{return Ks(Sv(r,"utf-8"))}catch{return 0}}return 0}function Tv(t,e,r,n=6){let o=e<n,i=o?Hs(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function bi(t,e){return Tv(e,Ev(t),r=>Qp(ef(t,r)))}F();Vt();import{existsSync as pf,mkdirSync as ex,mkdtempSync as tx,rmSync as ff,writeFileSync as mf}from"node:fs";import{tmpdir as rx}from"node:os";import{dirname as nx,join as vi}from"node:path";import{simpleGit as xc}from"simple-git";Er();function ox(t){return`codepipe/context-migration-v${t}`}function ix(t){let e=Ws(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 \`${ft}\` stamp (renamed from \`${Br}\``,"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(`
943
- `)}async function hf(t,e,r,n){let o=xc(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=bi(t,e);if(!i.outdated)return i;let s=ox(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 sx(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=en(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:ix(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 sx(t,e,r,n,o,i,s){let a=xc(t),c=tx(vi(rx(),"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(cn(l,u).map(g=>[g.path,g.content])),d=0;for(let g of n.missingPaths){if(g===ft)continue;let h=p.get(g);if(h==null){s.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let k=vi(c,g);pf(k)||(ex(nx(k),{recursive:!0}),mf(k,h),d++)}mf(vi(c,ft),qn(n.currentVersion)),d++;let m=vi(c,Br);pf(m)&&(ff(m,{force:!0}),d++);let f=xc(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(()=>{}),ff(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{existsSync as ax,readFileSync as cx,writeFileSync as lx}from"node:fs";import{homedir as ux}from"node:os";import{join as gf}from"node:path";import{parseDocument as dx}from"yaml";function px(t){let e={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(e.default_branch=t.defaultBranch),e}function fx(t,e){let r=dx(t);return r.set("repos",e.map(px)),r.toString()}function mx(t,e){let r=[gf(ux(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(gf(e,"project.yaml")),r}function mo(t,e,r){let n=[],o=[];for(let i of mx(t,r))if(ax(i))try{let s=cx(i,"utf-8"),a=fx(s,e);a!==s&&(lx(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}ho();at();pe();function Ex(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}),r}function Pf(t,e,r,n){let o=Ex(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=oi(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=Mt(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}at();pe();Vt();xr();rn();Ti();function Nf(t){let e=V(t);if(!e)return null;if(!e.sealKey){let r=Ei();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},ae(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:Ge(e.sealKey.publicKey)}}async function Of(t,e,r,n){let o;try{o=JSON.parse(un(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=V(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 Wt(o.token);return i.github={token:o.token},dn(i,()=>{process.env.GH_TOKEN=o.token,Af(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Yt(o.token);return i.gitlab={token:o.token},dn(i,()=>{process.env.GITLAB_TOKEN=o.token,_f(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 qt(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},dn(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,jf(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 Xt({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},dn(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 Ot(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},dn(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},dn(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 dn(t,e){ae(t),e()}F();F();import{spawn as Tx}from"node:child_process";var Ix=124,Lf=16*1024,Mf=4e3;function Rx(t,e,r,n,o,i){let s={...t},a=(c,l)=>{_t(c)||(s[c]=l)};for(let[c,l]of Object.entries(e))a(c,l);for(let[c,l]of Object.entries(r))a(c,l);for(let[c,l]of Object.entries(n??{}))a(c,l);for(let[c,l]of Object.entries(o))s[c]=l;for(let[c,l]of Object.entries(i))s[`INPUT_${c}`]=String(l);return s}async function Df(t){let{def:e,onEvent:r}=t,n=Rx(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
942
+ `}async function Zp(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=h=>o==="staging"?`adr/DRAFT-${h}.md`:`tasks/${e}/adr/DRAFT-${h}.md`,s=[],a=[];for(let h of r){let k=xe(t,i(h));if(!kc(k)){a.push(h);continue}s.push({slug:h,content:Xp(k,"utf-8")})}let c=Jp(t,"adr"),l=new Map;if(kc(c))for(let h of gv(c)){let k=wv.exec(h);!k||h===kv||l.set(h,{num:parseInt(k[1]??"",10),slug:k[2]??"",content:Xp(Jp(c,h),"utf-8")})}let u=Math.max(0,...[...l.values()].map(h=>h.num))+1,p=new Map,d=[],m=[];for(let h of s){if([...l.entries()].find(([,v])=>v.slug===h.slug&&v.content.includes(e))){m.push(h.slug);continue}let y=u++,$=`${String(y).padStart(4,"0")}-${h.slug}.md`,{content:x,supersedes:T}=$v(h.content,y,h.slug,e,n);if(p.set($,x),l.set($,{num:y,slug:h.slug,content:x}),d.push(`adr/${$}`),T!==null){let v=[...l.keys()].find(b=>b.startsWith(`${String(T).padStart(4,"0")}-`));if(v&&v!==$){let b=vv(p.get(v)??l.get(v).content,y);p.set(v,b),l.set(v,{...l.get(v),content:b})}}}let f=[];if(o==="staging")for(let h of s)kc(xe(t,`adr/DRAFT-${h.slug}.md`))&&f.push({path:`adr/DRAFT-${h.slug}.md`,content:"",deleted:!0});if(d.length===0&&f.length===0)return{promoted:d,skipped:m,missing:a};if(d.length>0){let h=[...l.entries()].map(([k,y])=>({num:y.num,file:k,header:bv(y.content)}));p.set("INDEX.md",xv(h))}for(let[h,k]of p.entries())f.push({path:`adr/${h}`,content:k});let g=d.length>0?`adr(${e}): promote ${s.map(h=>h.slug).join(", ")}`:`adr(${e}): drop stale staged ${m.join(", ")}`;return await Te(t,f,g),{promoted:d,skipped:m,missing:a}}st();Lt();F();import{existsSync as Qp,readFileSync as Sv}from"node:fs";import{join as ef}from"node:path";function Ev(t){for(let e of[dt,Br]){let r=ef(t,e);if(Qp(r))try{return Ks(Sv(r,"utf-8"))}catch{return 0}}return 0}function Tv(t,e,r,n=6){let o=e<n,i=o?Hs(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function bi(t,e){return Tv(e,Ev(t),r=>Qp(ef(t,r)))}F();Vt();import{existsSync as pf,mkdirSync as ex,mkdtempSync as tx,rmSync as ff,writeFileSync as mf}from"node:fs";import{tmpdir as rx}from"node:os";import{dirname as nx,join as vi}from"node:path";import{simpleGit as xc}from"simple-git";Er();function ox(t){return`codepipe/context-migration-v${t}`}function ix(t){let e=Ws(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 \`${dt}\` stamp (renamed from \`${Br}\``,"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(`
943
+ `)}async function hf(t,e,r,n){let o=xc(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=bi(t,e);if(!i.outdated)return i;let s=ox(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 sx(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=en(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:ix(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 sx(t,e,r,n,o,i,s){let a=xc(t),c=tx(vi(rx(),"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(cn(l,u).map(g=>[g.path,g.content])),d=0;for(let g of n.missingPaths){if(g===dt)continue;let h=p.get(g);if(h==null){s.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let k=vi(c,g);pf(k)||(ex(nx(k),{recursive:!0}),mf(k,h),d++)}mf(vi(c,dt),qn(n.currentVersion)),d++;let m=vi(c,Br);pf(m)&&(ff(m,{force:!0}),d++);let f=xc(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(()=>{}),ff(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{existsSync as ax,readFileSync as cx,writeFileSync as lx}from"node:fs";import{homedir as ux}from"node:os";import{join as gf}from"node:path";import{parseDocument as dx}from"yaml";function px(t){let e={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(e.default_branch=t.defaultBranch),e}function fx(t,e){let r=dx(t);return r.set("repos",e.map(px)),r.toString()}function mx(t,e){let r=[gf(ux(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(gf(e,"project.yaml")),r}function mo(t,e,r){let n=[],o=[];for(let i of mx(t,r))if(ax(i))try{let s=cx(i,"utf-8"),a=fx(s,e);a!==s&&(lx(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}ho();at();pe();function Ex(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}),r}function Pf(t,e,r,n){let o=Ex(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=oi(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=Mt(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}at();pe();Vt();xr();rn();Ti();function Nf(t){let e=Y(t);if(!e)return null;if(!e.sealKey){let r=Ei();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},ae(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:Ge(e.sealKey.publicKey)}}async function Of(t,e,r,n){let o;try{o=JSON.parse(un(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 Wt(o.token);return i.github={token:o.token},dn(i,()=>{process.env.GH_TOKEN=o.token,Af(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Yt(o.token);return i.gitlab={token:o.token},dn(i,()=>{process.env.GITLAB_TOKEN=o.token,_f(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 qt(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},dn(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,jf(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 Xt({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},dn(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 Ot(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},dn(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},dn(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 dn(t,e){ae(t),e()}F();F();import{spawn as Tx}from"node:child_process";var Ix=124,Lf=16*1024,Mf=4e3;function Rx(t,e,r,n,o,i){let s={...t},a=(c,l)=>{_t(c)||(s[c]=l)};for(let[c,l]of Object.entries(e))a(c,l);for(let[c,l]of Object.entries(r))a(c,l);for(let[c,l]of Object.entries(n??{}))a(c,l);for(let[c,l]of Object.entries(o))s[c]=l;for(let[c,l]of Object.entries(i))s[`INPUT_${c}`]=String(l);return s}async function Df(t){let{def:e,onEvent:r}=t,n=Rx(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
944
944
  `,o.length>Lf&&(o=o.slice(o.length-Lf))},s=(a,c)=>{let l=c.length>Mf?c.slice(0,Mf)+"\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 Cx(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 Cx(t,e,r,n,o){return new Promise(i=>{let s=Tx("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??ga)*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 h;for(;(h=f.indexOf(`
945
945
  `))!==-1;)o(m,f.slice(0,h).replace(/\r$/,"")),f=f.slice(h+1)},flush:()=>{f.length>0&&o(m,f.replace(/\r$/,"")),f=""}}},p=u("stdout"),d=u("stderr");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?Ix:m??(f?1:0))})})}st();st();import{existsSync as Px,readFileSync as Ax,statSync as Uf}from"node:fs";var Bf=2*1024*1024;function _x(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function Ff(t,e){let r=xe(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!Px(r)||!Uf(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=Uf(r);if(n>Bf)throw new Error(`file too large: ${e} is ${n} bytes (limit ${Bf})`);let o=Ax(r);return _x(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}pe();F();import{existsSync as jx,readFileSync as Nx,writeFileSync as Ox}from"node:fs";import{join as Lx}from"node:path";import{parseDocument as Mx}from"yaml";async function Gf(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=Ea(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=Lx(t,o);if(!jx(s))throw new Error(`${o} not found in context repo (${t})`);let a=Mx(Nx(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);Ox(s,a.toString()),n.push(o)}return{files:n}}Pc();import{existsSync as Ac,readFileSync as _c,writeFileSync as Dx}from"node:fs";import{join as Ri}from"node:path";import{parseDocument as jc}from"yaml";async function Xf(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=Ri(t,"project.yaml");if(!Ac(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=jc(_c(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=Ri(t,"regimen.yaml");if(!Ac(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=jc(_c(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)Dx(Ri(t,i.path),i.content);return{files:r.map(i=>i.path)}}function Ci(t){if(!t)return"Stage";try{let e=Ri(t,"project.yaml");if(!Ac(e))return"Stage";let n=jc(_c(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}Vt();xi();ho();F();st();import{existsSync as aS,readFileSync as cS}from"node:fs";import{join as Fm}from"node:path";import{simpleGit as Yc}from"simple-git";F();import{existsSync as Jf,readFileSync as Zf,readdirSync as Ux}from"node:fs";import{join as Nc}from"node:path";import{simpleGit as Bx}from"simple-git";function Fx(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(`
946
- `)){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 Gx(t,e){let r=Nc(t,`tasks/${e}/annotations`);if(!Jf(r))return[];let n=[];for(let o of Ux(r).sort())if(o.endsWith(".md")){try{let i=Fx(o,Zf(Nc(r,o),"utf-8"));i&&n.push(i)}catch{}if(n.length>=ea)break}return n}var Kx=12;async function Qf(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=Bx(o),p=[];for(let d of Gx(e,r)){if(d.repo!==n)continue;let m=ge("code",n,d.path);if(!a.has(m))continue;let f=l.get(m);if(!f)continue;let g=(await u.raw(["rev-parse",`${i}:${d.path}`]).catch(()=>"")).trim().slice(0,Kx),h=Vs(f),k=Nc(e,h),w=p.find(R=>R.path===h),$=w?.content??(Jf(k)?Zf(k,"utf-8"):null),x=`<!-- ${r}${g?`:${g}`:""} -->`;if($?.includes(x))continue;let T=$??`---
946
+ `)){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 Gx(t,e){let r=Nc(t,`tasks/${e}/annotations`);if(!Jf(r))return[];let n=[];for(let o of Ux(r).sort())if(o.endsWith(".md")){try{let i=Fx(o,Zf(Nc(r,o),"utf-8"));i&&n.push(i)}catch{}if(n.length>=ea)break}return n}var Kx=12;async function Qf(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=Bx(o),p=[];for(let d of Gx(e,r)){if(d.repo!==n)continue;let m=ge("code",n,d.path);if(!a.has(m))continue;let f=l.get(m);if(!f)continue;let g=(await u.raw(["rev-parse",`${i}:${d.path}`]).catch(()=>"")).trim().slice(0,Kx),h=Vs(f),k=Nc(e,h),y=p.find(R=>R.path===h),$=y?.content??(Jf(k)?Zf(k,"utf-8"):null),x=`<!-- ${r}${g?`:${g}`:""} -->`;if($?.includes(x))continue;let T=$??`---
947
947
  entityId: ${f}
948
948
  ---
949
949
 
@@ -951,8 +951,8 @@ entityId: ${f}
951
951
 
952
952
  Append-only. Keyed by entityId \u2014 never by path; entries survive renames.
953
953
  `,v=["",`## ${s} \u2014 ${r}`,x,"",d.body,""].join(`
954
- `),b=T+v;w?w.content=b:p.push({path:h,content:b})}return p}Bc();Kc();_i();Wc();bo();async function lS(t,e){let n=await Yc(t).raw(["diff","--numstat",`${e}^`,e]).catch(()=>""),o=[];for(let i of n.split(`
955
- `)){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 uS(t,e){let n=[`tasks/${e}/PLAN.md`,`tasks/${e}/SOLUTION.md`].find(i=>aS(Fm(t,i)));if(!n)return{};let o=Fm(t,n);try{let i=cS(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 Gm(t){let{contextDir:e,repoDir:r,repoName:n,taskKey:o,commitSha:i}=t,s=fn(e),a=Ir([...s.ignore,...pn]),c=await lS(r,i),l=(await Yc(r).raw(["show","-s","--format=%cs",i])).trim(),u=null,p=new Map;try{u=Fc(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=ge("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=uS(e,o),f=Pi(e,o),g=f?.origin==="pipeline"?f.files.filter(T=>te(T.key)?.repo!==n):[],h=f?.origin==="pipeline"?f.commits:[],k={modelFormatVersion:2,taskKey:o,origin:"pipeline",...f?.title?{title:f.title}:{},...l?{date:l}:{},commits:[...new Set([...h,i])],files:[...g,...d],links:{...f?.origin==="pipeline"?f.links:{},...m}};k.links&&Object.keys(k.links).length===0&&delete k.links;let w=[...Ni(e).filter(T=>T.taskKey!==o),k],$=Om(Lm(e),w,o,s.cochange.halfLifeDays),x=await Qf({contextDir:e,taskKey:o,repoName:n,repoDir:r,commitSha:i,date:l,touchedKeys:new Set(d.map(T=>T.key)),identity:u}).catch(()=>[]);await Te(e,[{path:mr(o),content:Gr(k)},{path:fr,content:Oi($)},...x],`model: task event ${o}`);{let{rebuildSearchIndex:T}=await Promise.resolve().then(()=>(vo(),$o));await T(e).catch(()=>{})}return{recorded:!0}}async function Km(t){let e=new Set([t.fallbackTaskKey]);try{let r=Yc(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(`
954
+ `),b=T+v;y?y.content=b:p.push({path:h,content:b})}return p}Bc();Kc();_i();Wc();bo();async function lS(t,e){let n=await Yc(t).raw(["diff","--numstat",`${e}^`,e]).catch(()=>""),o=[];for(let i of n.split(`
955
+ `)){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 uS(t,e){let n=[`tasks/${e}/PLAN.md`,`tasks/${e}/SOLUTION.md`].find(i=>aS(Fm(t,i)));if(!n)return{};let o=Fm(t,n);try{let i=cS(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 Gm(t){let{contextDir:e,repoDir:r,repoName:n,taskKey:o,commitSha:i}=t,s=fn(e),a=Ir([...s.ignore,...pn]),c=await lS(r,i),l=(await Yc(r).raw(["show","-s","--format=%cs",i])).trim(),u=null,p=new Map;try{u=Fc(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=ge("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=uS(e,o),f=Pi(e,o),g=f?.origin==="pipeline"?f.files.filter(T=>te(T.key)?.repo!==n):[],h=f?.origin==="pipeline"?f.commits:[],k={modelFormatVersion:2,taskKey:o,origin:"pipeline",...f?.title?{title:f.title}:{},...l?{date:l}:{},commits:[...new Set([...h,i])],files:[...g,...d],links:{...f?.origin==="pipeline"?f.links:{},...m}};k.links&&Object.keys(k.links).length===0&&delete k.links;let y=[...Ni(e).filter(T=>T.taskKey!==o),k],$=Om(Lm(e),y,o,s.cochange.halfLifeDays),x=await Qf({contextDir:e,taskKey:o,repoName:n,repoDir:r,commitSha:i,date:l,touchedKeys:new Set(d.map(T=>T.key)),identity:u}).catch(()=>[]);await Te(e,[{path:mr(o),content:Gr(k)},{path:fr,content:Oi($)},...x],`model: task event ${o}`);{let{rebuildSearchIndex:T}=await Promise.resolve().then(()=>(vo(),$o));await T(e).catch(()=>{})}return{recorded:!0}}async function Km(t){let e=new Set([t.fallbackTaskKey]);try{let r=Yc(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(`
956
956
  `)){let s=i.trim();s&&e.add(s)}}catch{}for(let r of[...e].sort())await dS(t.contextDir,r,t.prUrl)}async function dS(t,e,r){let n=Pi(t,e);if(!n||n.origin!=="pipeline"||n.links?.pr===r)return;let o={...n,links:{...n.links??{},pr:r}};await Te(t,[{path:mr(e),content:Gr(o)}],`model: pr link for ${e}`)}xr();import{existsSync as qm,readFileSync as Ym}from"node:fs";import{join as Vm}from"node:path";import{parseDocument as zm}from"yaml";xr();var xo=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return Sp(this.cfg,e)}getIssue(e,r){return Ep(this.cfg,e,r??Ci(this.contextDir))}listComments(e,r){return Tp(this.cfg,e,r)}downloadAttachment(e){return xp(this.cfg,e)}updateStatus(e,r){return mp(this.cfg,e,r,Ci(this.contextDir))}addComment(e,r,n){return hp(this.cfg,e,r)}createIssue(e){return wp(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,Ci(this.contextDir))}editIssue(e,r){return gp(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return kp(this.cfg,e,r,n)}fetchStateFields(e){return Rp(this.cfg,e)}};F();st();import{existsSync as wS,readFileSync as kS}from"node:fs";import{randomBytes as bS}from"node:crypto";import{existsSync as Vc,readFileSync as pS,readdirSync as fS}from"node:fs";F();st();function Bi(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=yS(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:mS(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:gS(hS(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 Hm(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),Vc(xe(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 Fi(t,e,r){if(r.length===0)return;let n=Bi(t,e,r),o=r.map(i=>i.issue.key);await Te(t,n,`sync(${o.join(", ")}): task data`)}function mS(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(`
957
957
  `)}function hS(t,e,r){let n=new Map,o=xe(t,`tasks/${e}/comments.jsonl`);if(Vc(o))for(let i of pS(o,"utf-8").split(`
958
958
  `)){let s=i.trim();if(s)try{let a=JSON.parse(s);a&&typeof a.id=="string"&&n.set(a.id,a)}catch{}}for(let i of r){if(n.has(i.id))continue;let s={id:i.id,author:i.author,origin:"youtrack",body:i.body,createdAt:new Date(i.createdAt).toISOString()},a=kr(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function gS(t){return t.map(e=>JSON.stringify(e)).join(`
@@ -960,22 +960,22 @@ Append-only. Keyed by entityId \u2014 never by path; entries survive renames.
960
960
  `:"")}function yS(t,e,r){let n=[],o=xe(t,`tasks/${e}/attachments`);if(Vc(o))for(let i of fS(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}$i();var So=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await uo(this.contextDir);let r=e.columns??[];return cf(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>fo(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=po(this.contextDir,e);return r?fo(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return Wm(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 uo(this.contextDir),!po(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${bS(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=kr(r);s&&(i.parsedCommand=s);let c=[...Wm(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
961
961
  `)+`
962
962
  `;return await Te(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 lf(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:ti.statusColumns}]}async mutateRecord(e,r,n){let o=po(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=fo(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:qr(e),content:vc(i)},...Bi(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await Te(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:ro,status:r.targetStatus,links:[],created:n,updated:n},i=fo(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:qr(e),content:vc(o)},...Bi(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}};function Wm(t,e){let r=xe(t,`tasks/${e}/comments.jsonl`);if(!wS(r))return[];let n=[];for(let o of kS(r,"utf-8").split(`
963
- `)){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}$i();function zc(t){if(!t)return"youtrack";try{let e=Vm(t,"project.yaml");return qm(e)&&zm(Ym(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function Tt(t){let e=zc(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=sf(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=$S(n);return i?{ok:!0,kind:e,provider:new So(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=pp();return r?{ok:!0,kind:e,provider:new xo(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function $S(t){try{let e=Vm(t,"project.yaml");if(!qm(e))return null;let r=zm(Ym(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var Gi=new Map;async function Eo(t,e){let n=(Gi.get(t)??Promise.resolve()).catch(()=>{}).then(e);Gi.set(t,n);try{return await n}finally{Gi.get(t)===n&&Gi.delete(t)}}function Ki(t,e){return so(t.split(":",2)[0]??"",e)}async function Xm(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;Tr(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return X("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Eo(`${i}/${r.name}`,async()=>{let s=await er(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir),{commit:c,pushed:l,baseMoved:u}=await bf(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 Gm({contextDir:t.contextDir,repoDir:a,repoName:r.name,taskKey:p,commitSha:c}).catch(d=>{Tr(`[model] task event for ${p} failed: ${d instanceof Error?d.message:String(d)}`)})}return fe({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,pushed:l,...typeof u=="number"&&u>0?{baseMoved:u}:{},...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"push_branch":{if(!r)return X("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Eo(`${i}/${r.name}`,async()=>{let s=await er(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir);return await $f(s,a,{branchName:e.branchName,force:e.force}),fe({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"create_pr":{if(!r)return X("no repo spec");let{spec:i,host:s}=Ki(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 Km({contextDir:t.contextDir,repoDir:_e(l,r.name,t.baseDir),branchName:e.branchName,baseBranch:e.baseBranch,fallbackTaskKey:c,prUrl:a.url}).catch(u=>{Tr(`[model] pr link for ${c} failed: ${u instanceof Error?u.message:String(u)}`)})}return fe({url:a.url,number:a.number,host:s.name})}case"merge_pr":{if(!r)return X("no repo spec");let{spec:i,host:s}=Ki(e.taskId,r),a=await s.mergePR(i,e.prNumber,e.mergeMethod,e.deleteBranch);return fe({prNumber:e.prNumber,host:s.name,...a.mergedSha?{mergedSha:a.mergedSha}:{}})}case"close_pr":{if(!r)return X("no repo spec");let{spec:i,host:s}=Ki(e.taskId,r);return await s.closePR(i,e.prNumber,e.comment),fe({prNumber:e.prNumber,host:s.name})}case"rewrite_cluster_branch":{if(!r)return X("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Eo(`${i}/${r.name}`,async()=>{let s=await er(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir),{commit:c,dropped:l}=await vf(s,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:r.defaultBranch});return fe({branch:e.branchName,commit:c,dropped:l,pushed:l>0})})}case"merge_branch":{if(!r)return X("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Eo(`${i}/${r.name}`,async()=>{let s=await er(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir),{mergedSha:c}=await xf(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return fe({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return X("no repo spec");let i=t.cloneUrlOverride??Si(r),a=(await Sf(i)).filter(u=>Ef(u,e.issueKey)),c=en(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 fe({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return X("no repo spec");let{spec:i,host:s}=Ki(e.taskId,r);return await s.addPRComment(i,e.prNumber,e.body),fe({prNumber:e.prNumber,host:s.name})}case"tracker_status":{let i=Tt({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),fe({issueId:t.trackerIssueId,newStatus:e.newStatus})):X("no tracker_issue_id provided"):X(i.error)}case"tracker_comment":{let i=Tt({contextDir:t.contextDir});if(!i.ok)return X(i.error);if(!t.trackerIssueId)return X("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return fe({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Tt({contextDir:t.contextDir});if(!i.ok)return X(i.error);if(!e.projectKey)return X("no projectKey in create_tracker_issue action");let{id:s,key:a}=await i.provider.createIssue({projectKey:e.projectKey,title:e.title,body:e.body,targetStatus:e.targetStatus});return fe({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Tt({contextDir:t.contextDir});if(!i.ok)return X(i.error);let s=0;for(let a of e.links)try{await i.provider.applyLink(a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return X(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return fe({applied:s})}case"set_project_setting":{if(!t.contextDir)return X("no context repo clone on this CLI");let i=await Gf(t.contextDir,e.edits);return fe({files:i.files})}case"set_prompt_override":{if(!t.contextDir)return X("no context repo clone on this CLI");if(!Pa(e.role))return X(`unknown prompt operation: ${e.role}`);let i=Aa(e.role);return await Te(t.contextDir,[e.content===null?{path:i,content:"",deleted:!0}:{path:i,content:e.content}],e.commitMessage),t.requestConfigReport?.(),fe({path:i,reset:e.content===null})}case"tracker_edit":{let i=Tt({contextDir:t.contextDir});if(!i.ok)return X(i.error);if(!t.contextDir)return X("no context repo clone on this CLI");await i.provider.editIssue(e.issueKey,{...e.title!==void 0?{title:e.title}:{},...e.body!==void 0?{body:e.body}:{}});let s=await i.provider.getIssue(e.issueKey);return s&&await Fi(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),fe({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return X("no context repo clone on this CLI");let i=await Xf(t.contextDir,e);return fe({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return X("no context repo clone on this CLI");let i=await Vf(t.contextDir,e);return fe({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),fe({reported:!0})):X("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return X("no context repo clone on this CLI");let i=await t.refreshContextStatus();return fe({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return X("no project workspace on this CLI");if(!r)return X("no repo spec");if(!t.onRunActivity)return X("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=mi(t.contextDir),c=s.find(m=>m.id===e.actionId);if(!c){let m=a.find(f=>f.file===`actions/${e.actionId}.yml`);return X(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=wa(c,e.input);if(!l.ok)return X(l.error);let u=Gp(t.contextDir),p=V(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),Eo(`${e.projectId}/${r.name}`,async()=>{await er(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=_e(e.projectId,r.name,t.baseDir),f=await Df({cwd:m,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:g=>i(e.runId,g)});return fe({runId:e.runId,status:f.status,exitCode:f.exitCode,...f.failedStep?{failedStep:f.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return X("no context repo clone on this CLI");let i=Ff(t.contextDir,e.path);return fe({path:e.path,...i})}case"search_model":{if(!t.contextDir)return X("no context repo clone on this CLI");let{searchModelIndex:i}=await Promise.resolve().then(()=>(vo(),$o)),s=await i(t.contextDir,e.q,e.limit);return fe({hits:s})}case"model_drift":return X("model_drift requires a local workspace (handled by the daemon)");case"model_bootstrap":return X("model_bootstrap requires a local workspace (handled by the daemon)");default:return X(`unsupported action type: ${e.type}`)}}catch(i){return X(i instanceof Error?i.message:String(i))}}function fe(t){return{status:"done",result:t}}function X(t){return{status:"failed",error:t}}at();Jc();je();pe();import{existsSync as dh,readFileSync as ph}from"node:fs";import{join as fh}from"node:path";async function mh(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=Ge(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Wi(e.farmId,e.farmPublicKey);let s=V(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await oe(t.hubUrl,t.cliToken,t.projectId),c;if(r){let d=fh(r,"project.yaml"),m=fh(r,"regimen.yaml");dh(d)&&dh(m)?c={projectYaml:ph(d,"utf-8"),regimenYaml:ph(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=Mt(e.farmPublicKey,JSON.stringify(l));Hi(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let p=await Yi(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:u});return p.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...p.daemonStatus?{daemonStatus:p.daemonStatus}:{}}:o(p.error??"farm provisioning failed")}catch(i){return o(i instanceof Error?i.message:String(i))}}F();at();Be();at();import{homedir as jS}from"node:os";import{existsSync as NS,mkdirSync as OS,readFileSync as LS,writeFileSync as MS}from"node:fs";import{dirname as DS,join as US}from"node:path";function el(){return z("RUNNER_PINS")??US(jS(),".codepipe","runner-pins.json")}function hh(){let t=el();if(!NS(t))return{};try{return JSON.parse(LS(t,"utf-8"))}catch{return{}}}function BS(t){let e=el();OS(DS(e),{recursive:!0}),MS(e,JSON.stringify(t,null,2)+`
964
- `,{mode:384})}function FS(t){return hh()[t]}function tl(t,e){let r=hh();r[t]=e,BS(r)}function gh(t,e){let r=Ge(e),n=FS(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 ${el()}.`);return r}je();pe();var wh=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function yh(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:wh(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 GS={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:wh(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)=>yh(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>yh(t,e,r,"remove-token")},kh={api:GS,fetchProject:oe,provisionOnRunner:Qm,teardownOnRunner:eh};async function bh(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(Ge(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");gh(e.runnerId,e.runnerPublicKey);let i=V(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 $h(t,e,r,n=kh){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 bh(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:[Ma(e.runnerId)]},c=Mt(e.runnerPublicKey,JSON.stringify(a));tl(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 vh(t,e,r,n=kh){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 bh(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=Mt(e.runnerPublicKey,JSON.stringify(c));tl(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle for ${s.owner}/${s.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let u=await n.teardownOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:l,owner:s.owner,repo:s.repoName});return{type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:u.ok,...u.error?{error:u.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}je();F();at();pe();var xh=16*1024;function KS(t){return Ve.test(t)?_t(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Ve}`}function Sh(t,e,r,n){let o=KS(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(un(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>xh)return{ok:!1,detail:`secret value too large (max ${xh} chars)`};try{return Bd(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function Eh(t,e){try{return Fd(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)}}}rn();pe();Vt();var zi=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}=so(o,a.repoSpec);try{let u=await l.getPullRequest(c,a.number);n.push({number:a.number,url:a.url,state:u.state,merged:u.merged,ci:u.ci,mergeable:u.mergeable})}catch(u){if(u instanceof vr){this.log.warn(`[track] task=${e} pr=${a.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${a.url} fetch failed: ${u instanceof Error?u.message:String(u)}`);return}}let i=n.map(a=>`${a.number}:${a.state}:${a.merged?1:0}:${a.ci}:${a.mergeable}`).join("|");if(this.lastSig.get(e)===i)return;for(let a=0;a<n.length;a++){let c=n[a];if(c.ci!=="failed")continue;let{spec:l,host:u}=so(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=HS(n);this.log.info(`[track] task=${e} snapshot signalled${s?` \u2192 ${s}`:""} (${n.length} PR(s))`)}};function HS(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}F();var Xi=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??(()=>Tt({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}:{},x=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,A]=await Promise.all([b.length>0?r.listIssues({projectKey:e.projectKey,columns:b,...$,...x}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...$})]),G=new Map;for(let J of[...R,...A])G.set(J.id,J);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,...$,...x})}}catch($){let x=$ instanceof Error?$.message:String($);x.includes("stage_field")?this.log.warn(`[yt-sync] CONFIGURATION ERROR \u2014 ${x}`):this.log.warn(`[yt-sync] listIssues failed: ${x}`);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 x=await Rh(r,$.id,e.sinceMs,this.log);x&&i.set($.id,x)}let c=[];for(let $ of e.offBoardIssueIds){if(s.has($))continue;let x=await Rh(r,$,e.sinceMs,this.log);if(x&&x.length>0&&i.set($,x),e.requireAssignee||x&&x.length>0){let T=await Ih(r,$,e.stageField,this.log);if(T)c.push(T);else if(x&&x.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 Hm(this.options.contextDir,d,$=>Ih(r,$,e.stageField,this.log)));try{await Fi(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let $ of p)this.shippedAttachments.add($)}catch($){let x=$ instanceof Error?$.message:String($);this.abandonTick(`context task sync failed: ${x}`);return}let m=this.options.isSelfComment??(()=>!1),f=[],g=[];for(let[$,x]of i){let T=x.filter(b=>!m(b.id));if(T.length===0)continue;f.push({issueId:$,comments:T.map(WS)});let v=T.flatMap(b=>{let R=kr(b.body);return R?[{commentId:b.id,author:b.author,name:R.name,args:R.args,createdAt:b.createdAt}]:[]});v.length>0&&g.push({issueId:$,commands:v})}let h={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Th),commentsBatch:f,...g.length>0?{commandsBatch:g}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(Th)}:{},observedAtMs:n};this.send(h);let k=f.reduce(($,x)=>$+x.comments.length,0),w=g.reduce(($,x)=>$+x.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${k} 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=qS(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 Th(t){let{description:e,...r}=t;return r}function WS(t){let{body:e,...r}=t;return r}function qS(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 Ih(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 Rh(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 dE(t,e){let r=t.repos.filter(i=>i.mirror);if(r.length===0)return[];let{mirrorLag:n}=await Promise.resolve().then(()=>(ol(),nl)),o=[];for(let i of r){let s=i.mountAs==="."?t.root:Cr(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 hl="npm i -g @code-partner/codepipe@latest";function ts(t,e={}){let r=e.log??{info:h=>console.log(h),warn:h=>console.warn(h)};r.info(`codepipe-cli v${qe} (protocol ${pt})`);let n=h=>e.onEvent?.(h),o=e.workspace;o?.contextDir&&Wp(o.contextDir,r);let i=Hh("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Hh("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let h=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(h)&&h>0?h*1e3:6e5})(),c=!1,l=!1,u=!1,p=new Set,d=!1,m=new Set,f=g();function g(){let h=qi(t.hubUrl,t.cliToken),k=null,w=new zi(i,L=>{h.readyState===h.OPEN&&h.send(JSON.stringify(L))},r),$=new Xi(s,L=>{h.readyState===h.OPEN&&h.send(JSON.stringify(L))},r,{contextDir:o?.contextDir??null,isSelfComment:L=>m.has(L)}),x=null,T=async()=>{try{let L={trackerProvider:zc(o?.contextDir??null)};try{let E=await oe(t.hubUrl,t.cliToken,t.projectId);L={...L,repos:E.repos,contextRepo:E.contextRepo}}catch(E){r.warn(`[readiness] could not fetch project summary for push checks: ${E instanceof Error?E.message:String(E)}`)}let U=await Pp(t.projectId,L),O=o?await dE(o,r):[];if(h.readyState!==h.OPEN)return;let q={type:"cli_readiness",projectId:t.projectId,ready:U.ready,checks:U.checks,creds:U.creds,secretNames:Gd(t.projectId),...o?{mirrors:O}:{},checkedAt:U.checkedAt};if(h.send(JSON.stringify(q)),U.ready)r.info("[readiness] ready");else{let E=U.checks.filter(I=>!I.ok).map(I=>`${I.name}(${I.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${E.join(", ")}`)}let K=Lp(U.creds,u);if(K==="open"){u=!0;let E=Mp(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${E}`),Sr(E)}else K==="rearm"&&(u=!1)}catch(L){r.warn(`[readiness] check failed: ${L instanceof Error?L.message:String(L)}`)}},v=()=>{T(),x=setInterval(()=>void T(),a),typeof x.unref=="function"&&x.unref()},b=()=>{x&&(clearInterval(x),x=null)},R=150,A=new Map,G=L=>{let U=A.get(L);if(!U||(U.timer&&clearTimeout(U.timer),A.delete(L),U.events.length===0||h.readyState!==h.OPEN))return;let O={type:"run_activity",projectId:t.projectId,runId:L,events:U.events};h.send(JSON.stringify(O))},J=(L,U)=>{let O=A.get(L);if(O||(O={events:[],timer:null},A.set(L,O)),O.events.push(U),U.kind==="result"){G(L);return}O.timer||(O.timer=setTimeout(()=>G(L),R),O.timer.unref?.())},P=o?.contextDir?new hi(o.contextDir,t.projectId,L=>{h.readyState===h.OPEN&&h.send(JSON.stringify(L))},r):null,y=async()=>{let L=o?.contextDir;if(!L)throw new Error("no context repo clone on this CLI");let U;try{U=(await oe(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let O=await hf(L,t.projectId,U,r);return h.readyState===h.OPEN&&h.send(JSON.stringify(O)),O},B=null,_=async()=>{let L=o?.contextDir;if(L)try{let{readContextIndexHub:U,collectSearchRows:O}=await Promise.resolve().then(()=>(vo(),$o));if(U(L)!=="metadata")return;let q=O(L);h.readyState===h.OPEN&&(h.send(JSON.stringify({type:"model_index",projectId:t.projectId,rows:q})),r.info(`[model] tier-2 index snapshot pushed (${q.length} rows)`))}catch(U){r.warn(`[model] tier-2 index push failed (non-fatal): ${U instanceof Error?U.message:String(U)}`)}},W=()=>{B&&clearTimeout(B),B=setTimeout(()=>void _(),5e3)},Y=null,de=async L=>{if(o?.contextDir)try{let{rebuildWorkspaceModelIfStale:U}=await Promise.resolve().then(()=>(Ro(),es));(await U({root:o.root,contextDir:o.contextDir,repos:o.repos},{fetch:L,onLog:q=>r.info(q)})).rebuilt.length>0&&W()}catch(U){r.warn(`[model] release-path rebuild failed (non-fatal): ${U instanceof Error?U.message:String(U)}`)}},lt=L=>{Y&&clearTimeout(Y),Y=setTimeout(()=>void de(L),6e4)},ut=setInterval(()=>void de(!0),6*36e5);return h.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let L=Xd(t.projectId),U=z("ORIGIN")==="farm"?"farm":"local",O=z("FARM_ID"),q=t.accountEmail??L.email,K;try{let I=Nf(t.projectId);I&&(K=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:qe,protocolVersion:pt,accountId:L.accountId,accountLabel:L.label,origin:U,inFlightActionIds:[...p],...q?{accountEmail:q}:{},...U==="farm"&&O?{farmId:O}:{},...K?{sealPublicKey:K}:{}};h.send(JSON.stringify(E))}),h.on("message",async L=>{let U=L.toString("utf-8");if(U==="pong"||U==="ping")return;let O;try{O=JSON.parse(U)}catch{return}if(!O||typeof O!="object")return;let q=O.type;if(q==="registered"){let E=O;if(E.ok){if(r.info(`[ws] registered for project ${E.projectId}`),n({kind:"registered",projectId:E.projectId??t.projectId}),w.start(),P?.start(),v(),gl(t,o,r),o?.contextDir){try{let I=bi(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(", ")})`:"")),l||(l=!0,y().catch(()=>{})))}catch(I){r.warn(`[ctx] context-format detect failed (non-fatal): ${I instanceof Error?I.message:String(I)}`)}_(),lt(!0)}}else r.warn(`[ws] register rejected: ${E.reason??"unknown"}`),n({kind:"register_rejected",reason:E.reason??"unknown"}),c=!0,h.close();return}if(q==="hello"){let E=O;k=Wn(E.protocolVersion);let I=k?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${E.platformVersion} (protocol ${E.protocolVersion}) \u2014 ${I}`),k||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${qe}, protocol ${pt}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${hl}`),n({kind:"incompatible",hubVersion:typeof E.platformVersion=="string"?E.platformVersion:null,hubProtocol:typeof E.protocolVersion=="number"?E.protocolVersion:null,updateCommand:hl}));return}if(q==="tracking_targets"){w.setTargets(O.targets);return}if(q==="youtrack_sync_request"){$.setRequest(O);return}if(q==="youtrack_force_sync"){$.forceSync();return}if(q==="sync_local"){await mE(O,o,h,r);return}if(q==="provision_repo"){let E=O;r.info(`[repo] provision_repo: ${E.repo.name} (${E.repo.host}:${E.repo.owner}/${E.repo.repoName})`),await pE(t,o,E.repo,r),await gl(t,o,r);return}if(q==="remove_repo"){let E=O;r.info(`[repo] remove_repo: ${E.repoName}${E.purge?" (purge)":""}`),await gl(t,o,r),E.purge&&fE(t,o,E.repoName,r);return}if(q==="context_write"){await hE(O,o,h,r);return}if(q==="adr_promote"){await gE(O,o,h,r);return}if(q==="cred_update"){let E=O,I=V(t.projectId),re=I?.sealKey?await Of(t.projectId,E.kind,E.sealed,I.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},ne={type:"cred_update_result",updateId:E.updateId,projectId:t.projectId,ok:re.ok,...re.detail?{detail:re.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(ne)),re.ok?(r.info(`[cred] ${E.kind} replaced${re.detail?` \u2014 ${re.detail}`:""}`),T()):r.warn(`[cred] ${E.kind} replacement rejected: ${re.detail??"unknown"}`);return}if(q==="readiness_check"){r.info("[readiness] on-demand check requested"),T();return}if(q==="agent_login_start"){Op(t,h,O,r,T);return}if(q==="move_to_farm"){let E=O;r.info(`[farm-move] request to move ${t.projectId} onto farm ${E.farmName} (${E.farmId})`);let I=await mh(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(q==="gh_runner_setup"){let E=O;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${E.runnerName} (${E.runnerId})`);let I=await $h(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(q==="gh_runner_teardown"){let E=O;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${E.runnerName} (${E.runnerId})`);let I=await vh(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(q==="tracker_fields_request"){let E=O,I={type:"tracker_fields_result",requestId:E.requestId,projectId:t.projectId,ok:!1},re=Tt({contextDir:o?.contextDir??null});if(!re.ok)I.error=re.error;else try{I.fields=await re.provider.fetchStateFields(E.projectKey),I.ok=!0}catch(ne){I.error=ne instanceof Error?ne.message:String(ne)}h.readyState===h.OPEN&&h.send(JSON.stringify(I)),I.ok||r.warn(`[yt-fields] listing failed: ${I.error??"unknown"}`);return}if(q==="project_secret_update"||q==="project_secret_delete"){let E=O,I;if(E.type==="project_secret_update"){let ne=V(t.projectId);I=ne?.sealKey?Sh(t.projectId,E.name,E.sealed,ne.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else I=Eh(t.projectId,E.name);let re={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(re)),I.ok?(r.info(`[secret] ${E.name} ${E.type==="project_secret_update"?"saved":"deleted"}`+(I.detail?` \u2014 ${I.detail}`:"")),T()):r.warn(`[secret] ${E.name} rejected: ${I.detail??"unknown"}`);return}if(q==="sandbox_keys"){let E=V(t.projectId);if(!E){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let I=Jr(t.projectId),re=Pf(O,E,I,r);for(let ne of re)h.readyState===h.OPEN&&h.send(JSON.stringify(ne));return}if(q!=="dispatch_action")return;let K=O;if(k===!1){let E=`refused: HUB protocol incompatible with CLI v${qe} (protocol ${pt})`;h.send(JSON.stringify({type:"action_result",actionId:K.actionId,status:"failed",error:E})),r.warn(`[exec] ${K.actionId} (${K.action.type}) \u2192 REFUSED: ${E}`),r.warn(`[exec] update the CLI to clear this: ${hl}`),n({kind:"action",actionId:K.actionId,actionType:K.action.type,ok:!1,error:E});return}if(K.action.type==="model_drift"){p.add(K.actionId);try{let E,I=o?.repos.find(re=>re.name===K.action.repoName);if(!o?.contextDir||!I)E={status:"failed",error:"no local workspace/repo clone on this CLI"};else try{let{computeDriftReport:re}=await Promise.resolve().then(()=>(Kh(),Gh)),ne=I.mountAs==="."?o.root:Cr(o.root,I.mountAs);E={status:"done",result:{report:await re(ne,o.contextDir,I.name)}}}catch(re){E={status:"failed",error:re instanceof Error?re.message:String(re)}}h.send(JSON.stringify({type:"action_result",actionId:K.actionId,...E}))}finally{p.delete(K.actionId)}return}if(K.action.type==="model_bootstrap"){p.add(K.actionId);try{let E;if(!o?.contextDir)E={status:"failed",error:"no Context Repo clone on this CLI"};else if(d)E={status:"failed",error:"model bootstrap is already running"};else{d=!0;try{let I=await oe(t.hubUrl,t.cliToken,t.projectId),{bootstrapDaemonModel:re}=await Promise.resolve().then(()=>(Ro(),es)),ne=await re(t.projectId,{root:o.root,contextDir:o.contextDir},I.repos,Gt=>r.info(`[model] ${Gt}`));r.info(`[model] bootstrap done: ${ne.repos} repos, ${ne.events} task events`),W(),E={status:"done",result:{repos:ne.repos,events:ne.events}}}catch(I){E={status:"failed",error:I instanceof Error?I.message:String(I)},r.warn(`[model] bootstrap failed: ${E.error}`)}finally{d=!1}}h.readyState===h.OPEN&&h.send(JSON.stringify({type:"action_result",actionId:K.actionId,...E}))}finally{p.delete(K.actionId)}return}p.add(K.actionId);try{let E=await Xm({action:K.action,repo:K.repo,trackerIssueId:K.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:P?()=>P.reportNow():void 0,refreshContextStatus:o?.contextDir?y:void 0,onRunActivity:J}).catch(ne=>({status:"failed",error:ne instanceof Error?ne.message:String(ne)}));K.action.type==="tracker_comment"&&E.status==="done"&&"result"in E&&typeof E.result?.commentId=="string"&&m.add(E.result.commentId),h.send(JSON.stringify({type:"action_result",actionId:K.actionId,...E}));let I=E.status!=="failed",re=!I&&"error"in E?E.error:void 0;I?r.info(`[exec] ${K.actionId} (${K.action.type}) \u2192 done`):r.warn(`[exec] ${K.actionId} (${K.action.type}) \u2192 FAILED: ${re??"?"}`),n({kind:"action",actionId:K.actionId,actionType:K.action.type,ok:I,...re?{error:re}:{}}),I&&["apply_delivery","context_write","create_pr"].includes(K.action.type)&&W(),I&&["merge_pr","merge_branch"].includes(K.action.type)&&lt(!0)}finally{p.delete(K.actionId)}}),h.on("close",(L,U)=>{let O=U?.toString("utf-8")??"";if(r.info(`[ws] closed code=${L}${O?` reason=${O}`:""}`),w.stop(),$.stop(),P?.stop(),b(),clearInterval(ut),Y&&clearTimeout(Y),B&&clearTimeout(B),O==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:L}),!c&&setTimeout(()=>{f=g()},2e3)}),h.on("error",L=>r.warn(`[ws] error: ${L.message}`)),h}return{stop(){c=!0,f.close()}}}async function gl(t,e,r){try{let n=await oe(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=mo(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 pE(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?Cr(e.root,o):_e(t.projectId,r.name);if(Wh(Cr(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await uE().clone(e?Si(r):Ic(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 fE(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?Cr(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(!Wh(Cr(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{lE(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 mE(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=Cr(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Dp(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 hE(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 Te(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 gE(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 Zp(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 Hh(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}je();pe();Lt();wl();rt();Ti();async function ng(t={profile:void 0}){let{cfg:e,profile:r}=Xr(t.profile),n=V(e.projectId);n&&io(n),go(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),yo(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),wo(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=Co(kl(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=si("CLI_LOG",i,o);if(s.enabled){let d=new Qr(s);ai(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=Vr(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=Co(kl(),".codepipe",r?Co("profiles",r,"context"):"context");if(await Qc(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await tg(()=>ns({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 Qc(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=Co(kl(),".codepipe",r?Co("profiles",r,"context-config"):"context-config");gi(a.contextDir,m,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=ts(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(`
965
- [${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}Pn();Fe();je();async function iw(t={profile:void 0}){let e=nt(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=qi(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 oe(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`)")}Uo();import{readFileSync as wC}from"node:fs";F();Fe();Lt();Lo();Er();Vt();xr();je();pe();function be(t){throw new Error(t)}function Ie(t,e){return(typeof t!="string"||t.trim().length===0)&&be(`config: '${e}' must be a non-empty string`),t.trim()}function Go(t,e){if(t==null)return;typeof t!="string"&&be(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function kC(t){(!t||typeof t!="object")&&be("config: expected a JSON object");let e=t,r=Ie(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||be("config: 'hubUrl' must start with http(s)://");let n=Ie(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&be("config: 'project' is required");let i=o,s=Ie(i.id,"project.id");Ht.test(s)||be("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=Ie(i.name,"project.name"),c=Ie(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&be("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||be("config: 'project.repos' must be an array");let u=l.map((w,$)=>{(!w||typeof w!="object")&&be(`config: project.repos[${$}] must be an object`);let x=w,T=Ie(x.host,`project.repos[${$}].host`);T!=="github"&&T!=="bitbucket"&&T!=="gitlab"&&be(`config: project.repos[${$}].host must be 'github', 'bitbucket' or 'gitlab'`);let v={name:Ie(x.name,`project.repos[${$}].name`),host:T,owner:Ie(x.owner,`project.repos[${$}].owner`),repoName:Ie(x.repoName,`project.repos[${$}].repoName`)},b=Go(x.defaultBranch,`project.repos[${$}].defaultBranch`);b&&(v.defaultBranch=b);let R=Go(x.mountAs,`project.repos[${$}].mountAs`);return R&&(v.mountAs=R),v}),p=i.contextRepo;(!p||typeof p!="object")&&be("config: 'project.contextRepo' is required");let d=p,m=Go(d.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&be("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:m,owner:Ie(d.owner,"project.contextRepo.owner"),name:Go(d.name,"project.contextRepo.name")??vt(s)},g={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:f}},h=Go(i.youtrackProjectKey,"project.youtrackProjectKey");if(h&&(g.project.youtrackProjectKey=h),i.index!==void 0&&(typeof i.index!="boolean"&&be("config: 'project.index' must be a boolean"),g.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&be("config: 'project.youtrackWrites' must be a boolean"),g.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let w=Ie(i.llmProvider,"project.llmProvider");w==="codex"&&be(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),w!=="claude"&&be("config: 'project.llmProvider' must be 'claude'"),g.project.llmProvider=w}let k=e.secrets;if(k!==void 0){(typeof k!="object"||k===null)&&be("config: 'secrets' must be an object");let w=k,$={};if(w.github){let x=w.github;$.github={token:Ie(x.token,"secrets.github.token")}}if(w.bitbucket){let x=w.bitbucket;$.bitbucket={email:Ie(x.email,"secrets.bitbucket.email"),apiToken:Ie(x.apiToken,"secrets.bitbucket.apiToken")}}if(w.gitlab){let x=w.gitlab;$.gitlab={token:Ie(x.token,"secrets.gitlab.token")}}if(w.youtrack){let x=w.youtrack;$.youtrack={url:Ie(x.url,"secrets.youtrack.url").replace(/\/$/,""),token:Ie(x.token,"secrets.youtrack.token")}}if(w.contextWrite){let x=w.contextWrite;$.contextWrite={token:Ie(x.token,"secrets.contextWrite.token")}}g.secrets=$}return g}async function bC(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function $C(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await Wt(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 qt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await di(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 Yt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Xt({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 bC():wC(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){be(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=kC(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 $C(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 An(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??Zr(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){be(`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 tr(o,i,a)}catch(d){if(d instanceof H&&d.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await oe(o,i,s.id);else if(d instanceof H)be(`HUB \u2192 ${d.status} ${d.message}`);else throw d}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let p={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(ae(p),Nt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${xt(s.id)}`),Zt(s.id,Et(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,s.llmProvider??Ye),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await Io(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`)}Fe();pe();import{cancel as uk,intro as dk,isCancel as pk,log as zl,outro as vC,password as fk}from"@clack/prompts";async function xC(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function mk(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await xC(),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"),zl.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await fk({message:"Claude OAuth token"});pk(i)&&(uk("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Hd({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${ii()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=nt(t.profile);if(!e){dk(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),zl.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await fk({message:"Claude OAuth token"});pk(i)&&(uk("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=V(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},ae(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(zl.success("Claude OAuth token saved."),vC("It will be sealed into job bundles when a SANDBOX (re)connects."))}Ro();F();Fe();Lt();Lo();Er();ks();je();pe();import{cancel as SC,confirm as EC,intro as TC,isCancel as hk,log as Me,outro as IC,select as gk,text as lr}from"@clack/prompts";function yk(t){SC(t),process.exit(1)}function On(t){return hk(t)&&yk("aborted"),t}function Ko(t){return hk(t)&&yk("aborted"),typeof t=="string"?t:""}async function RC(t,e){let r=On(await gk({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=Ko(await lr({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=Ko(await lr({message:"Context Repo name",placeholder:vt(t),initialValue:vt(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=nt(t.profile);TC(`codepipe project add \u2192 ${e.hubUrl}`);let r=On(await lr({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>Ht.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=On(await lr({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=On(await gk({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=On(await lr({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=On(await EC({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=Ko(await lr({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:k=>!k||!k.trim()||He(k)?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=He(d);Me.message(`${m.host}: ${m.owner}/${m.repoName}`);let f=Ko(await lr({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:k=>k.trim().length>0?void 0:"required"})).trim(),g=Ko(await lr({message:"default branch (optional)",placeholder:"main"})).trim(),h={name:f,host:m.host,owner:m.owner,repoName:m.repoName};g&&(h.defaultBranch=g),a.push(h)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await RC(r,a),u=V(e.projectId);Me.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await An(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??Zr(),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 tr(e.hubUrl,e.cliToken,c);Me.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),Zt(r,Et(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}`),IC("done")}catch(d){d instanceof H?(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)}}Pn();Fe();je();pe();rt();Uo();import{existsSync as CC,rmSync as PC}from"node:fs";import{confirm as AC,intro as _C,isCancel as jC,log as ur,outro as NC,spinner as OC}from"@clack/prompts";function Rt(t){ur.error(t),process.exit(1)}var kk=t=>t.trim().replace(/\/+$/,"");async function bk(t){_C("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Pe()?.spec.projectId??void 0;e||Rt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=gt(e);r||Rt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=kk(r.hubUrl),o=r.projectId,i=kk(t.hub);i.startsWith("http")||Rt("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&Rt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let k=OC();k.start(`reading project ${o} from ${n}\u2026`);try{l=await oe(n,r.cliToken,o),k.stop(`read project ${o} (${l.name})`)}catch(w){throw k.stop("could not read the source project",1),w instanceof H&&Rt(`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||Rt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=V(o),p=(t.account??r.accountEmail??await jn()).trim().toLowerCase();if(ur.message(`move project '${o}'
963
+ `)){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}$i();function zc(t){if(!t)return"youtrack";try{let e=Vm(t,"project.yaml");return qm(e)&&zm(Ym(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function Et(t){let e=zc(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=sf(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=$S(n);return i?{ok:!0,kind:e,provider:new So(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=pp();return r?{ok:!0,kind:e,provider:new xo(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function $S(t){try{let e=Vm(t,"project.yaml");if(!qm(e))return null;let r=zm(Ym(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var Gi=new Map;async function Eo(t,e){let n=(Gi.get(t)??Promise.resolve()).catch(()=>{}).then(e);Gi.set(t,n);try{return await n}finally{Gi.get(t)===n&&Gi.delete(t)}}function Ki(t,e){return so(t.split(":",2)[0]??"",e)}async function Xm(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;Tr(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return J("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Eo(`${i}/${r.name}`,async()=>{let s=await er(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir),{commit:c,pushed:l,baseMoved:u}=await bf(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 Gm({contextDir:t.contextDir,repoDir:a,repoName:r.name,taskKey:p,commitSha:c}).catch(d=>{Tr(`[model] task event for ${p} failed: ${d instanceof Error?d.message:String(d)}`)})}return fe({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 J("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Eo(`${i}/${r.name}`,async()=>{let s=await er(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir);return await $f(s,a,{branchName:e.branchName,force:e.force}),fe({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"create_pr":{if(!r)return J("no repo spec");let{spec:i,host:s}=Ki(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 Km({contextDir:t.contextDir,repoDir:_e(l,r.name,t.baseDir),branchName:e.branchName,baseBranch:e.baseBranch,fallbackTaskKey:c,prUrl:a.url}).catch(u=>{Tr(`[model] pr link for ${c} failed: ${u instanceof Error?u.message:String(u)}`)})}return fe({url:a.url,number:a.number,host:s.name})}case"merge_pr":{if(!r)return J("no repo spec");let{spec:i,host:s}=Ki(e.taskId,r),a=await s.mergePR(i,e.prNumber,e.mergeMethod,e.deleteBranch);return fe({prNumber:e.prNumber,host:s.name,...a.mergedSha?{mergedSha:a.mergedSha}:{}})}case"close_pr":{if(!r)return J("no repo spec");let{spec:i,host:s}=Ki(e.taskId,r);return await s.closePR(i,e.prNumber,e.comment),fe({prNumber:e.prNumber,host:s.name})}case"rewrite_cluster_branch":{if(!r)return J("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Eo(`${i}/${r.name}`,async()=>{let s=await er(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir),{commit:c,dropped:l}=await vf(s,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:r.defaultBranch});return fe({branch:e.branchName,commit:c,dropped:l,pushed:l>0})})}case"merge_branch":{if(!r)return J("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Eo(`${i}/${r.name}`,async()=>{let s=await er(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir),{mergedSha:c}=await xf(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return fe({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return J("no repo spec");let i=t.cloneUrlOverride??Si(r),a=(await Sf(i)).filter(u=>Ef(u,e.issueKey)),c=en(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 fe({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return J("no repo spec");let{spec:i,host:s}=Ki(e.taskId,r);return await s.addPRComment(i,e.prNumber,e.body),fe({prNumber:e.prNumber,host:s.name})}case"tracker_status":{let i=Et({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),fe({issueId:t.trackerIssueId,newStatus:e.newStatus})):J("no tracker_issue_id provided"):J(i.error)}case"tracker_comment":{let i=Et({contextDir:t.contextDir});if(!i.ok)return J(i.error);if(!t.trackerIssueId)return J("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return fe({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Et({contextDir:t.contextDir});if(!i.ok)return J(i.error);if(!e.projectKey)return J("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 fe({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Et({contextDir:t.contextDir});if(!i.ok)return J(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 J(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return fe({applied:s})}case"set_project_setting":{if(!t.contextDir)return J("no context repo clone on this CLI");let i=await Gf(t.contextDir,e.edits);return fe({files:i.files})}case"set_prompt_override":{if(!t.contextDir)return J("no context repo clone on this CLI");if(!Pa(e.role))return J(`unknown prompt operation: ${e.role}`);let i=Aa(e.role);return await Te(t.contextDir,[e.content===null?{path:i,content:"",deleted:!0}:{path:i,content:e.content}],e.commitMessage),t.requestConfigReport?.(),fe({path:i,reset:e.content===null})}case"tracker_edit":{let i=Et({contextDir:t.contextDir});if(!i.ok)return J(i.error);if(!t.contextDir)return J("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 Fi(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),fe({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return J("no context repo clone on this CLI");let i=await Xf(t.contextDir,e);return fe({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return J("no context repo clone on this CLI");let i=await Vf(t.contextDir,e);return fe({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),fe({reported:!0})):J("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return J("no context repo clone on this CLI");let i=await t.refreshContextStatus();return fe({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return J("no project workspace on this CLI");if(!r)return J("no repo spec");if(!t.onRunActivity)return J("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=mi(t.contextDir),c=s.find(m=>m.id===e.actionId);if(!c){let m=a.find(f=>f.file===`actions/${e.actionId}.yml`);return J(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=wa(c,e.input);if(!l.ok)return J(l.error);let u=Gp(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),Eo(`${e.projectId}/${r.name}`,async()=>{await er(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=_e(e.projectId,r.name,t.baseDir),f=await Df({cwd:m,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:g=>i(e.runId,g)});return fe({runId:e.runId,status:f.status,exitCode:f.exitCode,...f.failedStep?{failedStep:f.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return J("no context repo clone on this CLI");let i=Ff(t.contextDir,e.path);return fe({path:e.path,...i})}case"search_model":{if(!t.contextDir)return J("no context repo clone on this CLI");let{searchModelIndex:i}=await Promise.resolve().then(()=>(vo(),$o)),s=await i(t.contextDir,e.q,e.limit);return fe({hits:s})}case"model_drift":return J("model_drift requires a local workspace (handled by the daemon)");case"model_bootstrap":return J("model_bootstrap requires a local workspace (handled by the daemon)");default:return J(`unsupported action type: ${e.type}`)}}catch(i){return J(i instanceof Error?i.message:String(i))}}function fe(t){return{status:"done",result:t}}function J(t){return{status:"failed",error:t}}at();Jc();je();pe();import{existsSync as dh,readFileSync as ph}from"node:fs";import{join as fh}from"node:path";async function mh(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=Ge(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Wi(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 oe(t.hubUrl,t.cliToken,t.projectId),c;if(r){let d=fh(r,"project.yaml"),m=fh(r,"regimen.yaml");dh(d)&&dh(m)?c={projectYaml:ph(d,"utf-8"),regimenYaml:ph(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=Mt(e.farmPublicKey,JSON.stringify(l));Hi(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let p=await Yi(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:u});return p.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...p.daemonStatus?{daemonStatus:p.daemonStatus}:{}}:o(p.error??"farm provisioning failed")}catch(i){return o(i instanceof Error?i.message:String(i))}}F();at();Be();at();import{homedir as jS}from"node:os";import{existsSync as NS,mkdirSync as OS,readFileSync as LS,writeFileSync as MS}from"node:fs";import{dirname as DS,join as US}from"node:path";function el(){return X("RUNNER_PINS")??US(jS(),".codepipe","runner-pins.json")}function hh(){let t=el();if(!NS(t))return{};try{return JSON.parse(LS(t,"utf-8"))}catch{return{}}}function BS(t){let e=el();OS(DS(e),{recursive:!0}),MS(e,JSON.stringify(t,null,2)+`
964
+ `,{mode:384})}function FS(t){return hh()[t]}function tl(t,e){let r=hh();r[t]=e,BS(r)}function gh(t,e){let r=Ge(e),n=FS(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 ${el()}.`);return r}je();pe();var wh=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function yh(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:wh(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 GS={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:wh(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)=>yh(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>yh(t,e,r,"remove-token")},kh={api:GS,fetchProject:oe,provisionOnRunner:Qm,teardownOnRunner:eh};async function bh(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(Ge(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");gh(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 $h(t,e,r,n=kh){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 bh(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:[Ma(e.runnerId)]},c=Mt(e.runnerPublicKey,JSON.stringify(a));tl(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 vh(t,e,r,n=kh){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 bh(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=Mt(e.runnerPublicKey,JSON.stringify(c));tl(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle for ${s.owner}/${s.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let u=await n.teardownOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:l,owner:s.owner,repo:s.repoName});return{type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:u.ok,...u.error?{error:u.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}je();F();at();pe();var xh=16*1024;function KS(t){return Ve.test(t)?_t(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Ve}`}function Sh(t,e,r,n){let o=KS(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(un(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>xh)return{ok:!1,detail:`secret value too large (max ${xh} chars)`};try{return Bd(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function Eh(t,e){try{return Fd(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)}}}rn();pe();Vt();var zi=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}=so(o,a.repoSpec);try{let u=await l.getPullRequest(c,a.number);n.push({number:a.number,url:a.url,state:u.state,merged:u.merged,ci:u.ci,mergeable:u.mergeable})}catch(u){if(u instanceof vr){this.log.warn(`[track] task=${e} pr=${a.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${a.url} fetch failed: ${u instanceof Error?u.message:String(u)}`);return}}let i=n.map(a=>`${a.number}:${a.state}:${a.merged?1:0}:${a.ci}:${a.mergeable}`).join("|");if(this.lastSig.get(e)===i)return;for(let a=0;a<n.length;a++){let c=n[a];if(c.ci!=="failed")continue;let{spec:l,host:u}=so(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=HS(n);this.log.info(`[track] task=${e} snapshot signalled${s?` \u2192 ${s}`:""} (${n.length} PR(s))`)}};function HS(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}F();var Xi=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??(()=>Et({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}:{},x=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,A]=await Promise.all([b.length>0?r.listIssues({projectKey:e.projectKey,columns:b,...$,...x}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...$})]),G=new Map;for(let V of[...R,...A])G.set(V.id,V);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,...$,...x})}}catch($){let x=$ instanceof Error?$.message:String($);x.includes("stage_field")?this.log.warn(`[yt-sync] CONFIGURATION ERROR \u2014 ${x}`):this.log.warn(`[yt-sync] listIssues failed: ${x}`);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 x=await Rh(r,$.id,e.sinceMs,this.log);x&&i.set($.id,x)}let c=[];for(let $ of e.offBoardIssueIds){if(s.has($))continue;let x=await Rh(r,$,e.sinceMs,this.log);if(x&&x.length>0&&i.set($,x),e.requireAssignee||x&&x.length>0){let T=await Ih(r,$,e.stageField,this.log);if(T)c.push(T);else if(x&&x.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 Hm(this.options.contextDir,d,$=>Ih(r,$,e.stageField,this.log)));try{await Fi(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let $ of p)this.shippedAttachments.add($)}catch($){let x=$ instanceof Error?$.message:String($);this.abandonTick(`context task sync failed: ${x}`);return}let m=this.options.isSelfComment??(()=>!1),f=[],g=[];for(let[$,x]of i){let T=x.filter(b=>!m(b.id));if(T.length===0)continue;f.push({issueId:$,comments:T.map(WS)});let v=T.flatMap(b=>{let R=kr(b.body);return R?[{commentId:b.id,author:b.author,name:R.name,args:R.args,createdAt:b.createdAt}]:[]});v.length>0&&g.push({issueId:$,commands:v})}let h={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Th),commentsBatch:f,...g.length>0?{commandsBatch:g}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(Th)}:{},observedAtMs:n};this.send(h);let k=f.reduce(($,x)=>$+x.comments.length,0),y=g.reduce(($,x)=>$+x.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${k} commands=${y} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let p=`${s.id}:${u.id}`;if(this.shippedAttachments.has(p))continue;let d;try{d=await n.downloadAttachment(u.url)}catch(f){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${f instanceof Error?f.message:String(f)}`);continue}let m=qS(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 Th(t){let{description:e,...r}=t;return r}function WS(t){let{body:e,...r}=t;return r}function qS(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 Ih(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 Rh(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 dE(t,e){let r=t.repos.filter(i=>i.mirror);if(r.length===0)return[];let{mirrorLag:n}=await Promise.resolve().then(()=>(ol(),nl)),o=[];for(let i of r){let s=i.mountAs==="."?t.root:Cr(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 hl="npm i -g @code-partner/codepipe@latest";function ts(t,e={}){let r=e.log??{info:h=>console.log(h),warn:h=>console.warn(h)};r.info(`codepipe-cli v${qe} (protocol ${ut})`);let n=h=>e.onEvent?.(h),o=e.workspace;o?.contextDir&&Wp(o.contextDir,r);let i=Hh("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Hh("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let h=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(h)&&h>0?h*1e3:6e5})(),c=!1,l=!1,u=!1,p=new Set,d=!1,m=new Set,f=g();function g(){let h=qi(t.hubUrl,t.cliToken),k=null,y=new zi(i,M=>{h.readyState===h.OPEN&&h.send(JSON.stringify(M))},r),$=new Xi(s,M=>{h.readyState===h.OPEN&&h.send(JSON.stringify(M))},r,{contextDir:o?.contextDir??null,isSelfComment:M=>m.has(M)}),x=null,T=async()=>{try{let M={trackerProvider:zc(o?.contextDir??null)};try{let E=await oe(t.hubUrl,t.cliToken,t.projectId);M={...M,repos:E.repos,contextRepo:E.contextRepo}}catch(E){r.warn(`[readiness] could not fetch project summary for push checks: ${E instanceof Error?E.message:String(E)}`)}let B=await Pp(t.projectId,M),O=o?await dE(o,r):[];if(h.readyState!==h.OPEN)return;let q={type:"cli_readiness",projectId:t.projectId,ready:B.ready,checks:B.checks,creds:B.creds,secretNames:Gd(t.projectId),...o?{mirrors:O}:{},checkedAt:B.checkedAt};if(h.send(JSON.stringify(q)),B.ready)r.info("[readiness] ready");else{let E=B.checks.filter(I=>!I.ok).map(I=>`${I.name}(${I.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${E.join(", ")}`)}let K=Lp(B.creds,u);if(K==="open"){u=!0;let E=Mp(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${E}`),Sr(E)}else K==="rearm"&&(u=!1)}catch(M){r.warn(`[readiness] check failed: ${M instanceof Error?M.message:String(M)}`)}},v=()=>{T(),x=setInterval(()=>void T(),a),typeof x.unref=="function"&&x.unref()},b=()=>{x&&(clearInterval(x),x=null)},R=150,A=new Map,G=M=>{let B=A.get(M);if(!B||(B.timer&&clearTimeout(B.timer),A.delete(M),B.events.length===0||h.readyState!==h.OPEN))return;let O={type:"run_activity",projectId:t.projectId,runId:M,events:B.events};h.send(JSON.stringify(O))},V=(M,B)=>{let O=A.get(M);if(O||(O={events:[],timer:null},A.set(M,O)),O.events.push(B),B.kind==="result"){G(M);return}O.timer||(O.timer=setTimeout(()=>G(M),R),O.timer.unref?.())},C=o?.contextDir?new hi(o.contextDir,t.projectId,M=>{h.readyState===h.OPEN&&h.send(JSON.stringify(M))},r):null,w=async()=>{let M=o?.contextDir;if(!M)throw new Error("no context repo clone on this CLI");let B;try{B=(await oe(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let O=await hf(M,t.projectId,B,r);return h.readyState===h.OPEN&&h.send(JSON.stringify(O)),O},U=null,_=async()=>{let M=o?.contextDir;if(M)try{let{readContextIndexHub:B,collectSearchRows:O}=await Promise.resolve().then(()=>(vo(),$o));if(B(M)!=="metadata")return;let q=O(M);h.readyState===h.OPEN&&(h.send(JSON.stringify({type:"model_index",projectId:t.projectId,rows:q})),r.info(`[model] tier-2 index snapshot pushed (${q.length} rows)`))}catch(B){r.warn(`[model] tier-2 index push failed (non-fatal): ${B instanceof Error?B.message:String(B)}`)}},H=()=>{U&&clearTimeout(U),U=setTimeout(()=>void _(),5e3)},z=null,de=async M=>{if(o?.contextDir)try{let{rebuildWorkspaceModelIfStale:B}=await Promise.resolve().then(()=>(Ro(),es));(await B({root:o.root,contextDir:o.contextDir,repos:o.repos},{fetch:M,onLog:q=>r.info(q)})).rebuilt.length>0&&H()}catch(B){r.warn(`[model] release-path rebuild failed (non-fatal): ${B instanceof Error?B.message:String(B)}`)}},Rt=M=>{z&&clearTimeout(z),z=setTimeout(()=>void de(M),6e4)},kt=setInterval(()=>void de(!0),6*36e5);return h.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let M=Xd(t.projectId),B=X("ORIGIN")==="farm"?"farm":"local",O=X("FARM_ID"),q=t.accountEmail??M.email,K;try{let I=Nf(t.projectId);I&&(K=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:qe,protocolVersion:ut,accountId:M.accountId,accountLabel:M.label,origin:B,inFlightActionIds:[...p],...q?{accountEmail:q}:{},...B==="farm"&&O?{farmId:O}:{},...K?{sealPublicKey:K}:{}};h.send(JSON.stringify(E))}),h.on("message",async M=>{let B=M.toString("utf-8");if(B==="pong"||B==="ping")return;let O;try{O=JSON.parse(B)}catch{return}if(!O||typeof O!="object")return;let q=O.type;if(q==="registered"){let E=O;if(E.ok){if(r.info(`[ws] registered for project ${E.projectId}`),n({kind:"registered",projectId:E.projectId??t.projectId}),y.start(),C?.start(),v(),gl(t,o,r),o?.contextDir){try{let I=bi(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(", ")})`:"")),l||(l=!0,w().catch(()=>{})))}catch(I){r.warn(`[ctx] context-format detect failed (non-fatal): ${I instanceof Error?I.message:String(I)}`)}_(),Rt(!0)}}else r.warn(`[ws] register rejected: ${E.reason??"unknown"}`),n({kind:"register_rejected",reason:E.reason??"unknown"}),c=!0,h.close();return}if(q==="hello"){let E=O;k=Wn(E.protocolVersion);let I=k?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${E.platformVersion} (protocol ${E.protocolVersion}) \u2014 ${I}`),k||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${qe}, protocol ${ut}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${hl}`),n({kind:"incompatible",hubVersion:typeof E.platformVersion=="string"?E.platformVersion:null,hubProtocol:typeof E.protocolVersion=="number"?E.protocolVersion:null,updateCommand:hl}));return}if(q==="tracking_targets"){y.setTargets(O.targets);return}if(q==="youtrack_sync_request"){$.setRequest(O);return}if(q==="youtrack_force_sync"){$.forceSync();return}if(q==="sync_local"){await mE(O,o,h,r);return}if(q==="provision_repo"){let E=O;r.info(`[repo] provision_repo: ${E.repo.name} (${E.repo.host}:${E.repo.owner}/${E.repo.repoName})`),await pE(t,o,E.repo,r),await gl(t,o,r);return}if(q==="remove_repo"){let E=O;r.info(`[repo] remove_repo: ${E.repoName}${E.purge?" (purge)":""}`),await gl(t,o,r),E.purge&&fE(t,o,E.repoName,r);return}if(q==="context_write"){await hE(O,o,h,r);return}if(q==="adr_promote"){await gE(O,o,h,r);return}if(q==="cred_update"){let E=O,I=Y(t.projectId),re=I?.sealKey?await Of(t.projectId,E.kind,E.sealed,I.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},ne={type:"cred_update_result",updateId:E.updateId,projectId:t.projectId,ok:re.ok,...re.detail?{detail:re.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(ne)),re.ok?(r.info(`[cred] ${E.kind} replaced${re.detail?` \u2014 ${re.detail}`:""}`),T()):r.warn(`[cred] ${E.kind} replacement rejected: ${re.detail??"unknown"}`);return}if(q==="readiness_check"){r.info("[readiness] on-demand check requested"),T();return}if(q==="agent_login_start"){Op(t,h,O,r,T);return}if(q==="move_to_farm"){let E=O;r.info(`[farm-move] request to move ${t.projectId} onto farm ${E.farmName} (${E.farmId})`);let I=await mh(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(q==="gh_runner_setup"){let E=O;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${E.runnerName} (${E.runnerId})`);let I=await $h(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(q==="gh_runner_teardown"){let E=O;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${E.runnerName} (${E.runnerId})`);let I=await vh(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(q==="tracker_fields_request"){let E=O,I={type:"tracker_fields_result",requestId:E.requestId,projectId:t.projectId,ok:!1},re=Et({contextDir:o?.contextDir??null});if(!re.ok)I.error=re.error;else try{I.fields=await re.provider.fetchStateFields(E.projectKey),I.ok=!0}catch(ne){I.error=ne instanceof Error?ne.message:String(ne)}h.readyState===h.OPEN&&h.send(JSON.stringify(I)),I.ok||r.warn(`[yt-fields] listing failed: ${I.error??"unknown"}`);return}if(q==="project_secret_update"||q==="project_secret_delete"){let E=O,I;if(E.type==="project_secret_update"){let ne=Y(t.projectId);I=ne?.sealKey?Sh(t.projectId,E.name,E.sealed,ne.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else I=Eh(t.projectId,E.name);let re={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(re)),I.ok?(r.info(`[secret] ${E.name} ${E.type==="project_secret_update"?"saved":"deleted"}`+(I.detail?` \u2014 ${I.detail}`:"")),T()):r.warn(`[secret] ${E.name} rejected: ${I.detail??"unknown"}`);return}if(q==="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=Jr(t.projectId),re=Pf(O,E,I,r);for(let ne of re)h.readyState===h.OPEN&&h.send(JSON.stringify(ne));return}if(q!=="dispatch_action")return;let K=O;if(k===!1){let E=`refused: HUB protocol incompatible with CLI v${qe} (protocol ${ut})`;h.send(JSON.stringify({type:"action_result",actionId:K.actionId,status:"failed",error:E})),r.warn(`[exec] ${K.actionId} (${K.action.type}) \u2192 REFUSED: ${E}`),r.warn(`[exec] update the CLI to clear this: ${hl}`),n({kind:"action",actionId:K.actionId,actionType:K.action.type,ok:!1,error:E});return}if(K.action.type==="model_drift"){p.add(K.actionId);try{let E,I=o?.repos.find(re=>re.name===K.action.repoName);if(!o?.contextDir||!I)E={status:"failed",error:"no local workspace/repo clone on this CLI"};else try{let{computeDriftReport:re}=await Promise.resolve().then(()=>(Kh(),Gh)),ne=I.mountAs==="."?o.root:Cr(o.root,I.mountAs);E={status:"done",result:{report:await re(ne,o.contextDir,I.name)}}}catch(re){E={status:"failed",error:re instanceof Error?re.message:String(re)}}h.send(JSON.stringify({type:"action_result",actionId:K.actionId,...E}))}finally{p.delete(K.actionId)}return}if(K.action.type==="model_bootstrap"){p.add(K.actionId);try{let E;if(!o?.contextDir)E={status:"failed",error:"no Context Repo clone on this CLI"};else if(d)E={status:"failed",error:"model bootstrap is already running"};else{d=!0;try{let I=await oe(t.hubUrl,t.cliToken,t.projectId),{bootstrapDaemonModel:re}=await Promise.resolve().then(()=>(Ro(),es)),ne=await re(t.projectId,{root:o.root,contextDir:o.contextDir},I.repos,Gt=>r.info(`[model] ${Gt}`));r.info(`[model] bootstrap done: ${ne.repos} repos, ${ne.events} task events`),H(),E={status:"done",result:{repos:ne.repos,events:ne.events}}}catch(I){E={status:"failed",error:I instanceof Error?I.message:String(I)},r.warn(`[model] bootstrap failed: ${E.error}`)}finally{d=!1}}h.readyState===h.OPEN&&h.send(JSON.stringify({type:"action_result",actionId:K.actionId,...E}))}finally{p.delete(K.actionId)}return}p.add(K.actionId);try{let E=await Xm({action:K.action,repo:K.repo,trackerIssueId:K.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:C?()=>C.reportNow():void 0,refreshContextStatus:o?.contextDir?w:void 0,onRunActivity:V}).catch(ne=>({status:"failed",error:ne instanceof Error?ne.message:String(ne)}));K.action.type==="tracker_comment"&&E.status==="done"&&"result"in E&&typeof E.result?.commentId=="string"&&m.add(E.result.commentId),h.send(JSON.stringify({type:"action_result",actionId:K.actionId,...E}));let I=E.status!=="failed",re=!I&&"error"in E?E.error:void 0;I?r.info(`[exec] ${K.actionId} (${K.action.type}) \u2192 done`):r.warn(`[exec] ${K.actionId} (${K.action.type}) \u2192 FAILED: ${re??"?"}`),n({kind:"action",actionId:K.actionId,actionType:K.action.type,ok:I,...re?{error:re}:{}}),I&&["apply_delivery","context_write","create_pr"].includes(K.action.type)&&H(),I&&["merge_pr","merge_branch"].includes(K.action.type)&&Rt(!0)}finally{p.delete(K.actionId)}}),h.on("close",(M,B)=>{let O=B?.toString("utf-8")??"";if(r.info(`[ws] closed code=${M}${O?` reason=${O}`:""}`),y.stop(),$.stop(),C?.stop(),b(),clearInterval(kt),z&&clearTimeout(z),U&&clearTimeout(U),O==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:M}),!c&&setTimeout(()=>{f=g()},2e3)}),h.on("error",M=>r.warn(`[ws] error: ${M.message}`)),h}return{stop(){c=!0,f.close()}}}async function gl(t,e,r){try{let n=await oe(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=mo(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 pE(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?Cr(e.root,o):_e(t.projectId,r.name);if(Wh(Cr(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await uE().clone(e?Si(r):Ic(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 fE(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?Cr(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(!Wh(Cr(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{lE(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 mE(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=Cr(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Dp(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 hE(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 Te(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 gE(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 Zp(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 Hh(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}je();pe();Lt();wl();rt();Ti();async function ng(t={profile:void 0}){let{cfg:e,profile:r}=Xr(t.profile),n=Y(e.projectId);n&&io(n),go(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),yo(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),wo(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=Co(kl(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=si("CLI_LOG",i,o);if(s.enabled){let d=new Qr(s);ai(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=Vr(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=Co(kl(),".codepipe",r?Co("profiles",r,"context"):"context");if(await Qc(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await tg(()=>ns({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 Qc(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=Co(kl(),".codepipe",r?Co("profiles",r,"context-config"):"context-config");gi(a.contextDir,m,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=ts(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(`
965
+ [${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}Pn();Fe();je();async function iw(t={profile:void 0}){let e=nt(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=qi(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 oe(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`)")}Uo();import{readFileSync as wC}from"node:fs";F();Fe();Lt();Lo();Er();Vt();xr();je();pe();function be(t){throw new Error(t)}function Ie(t,e){return(typeof t!="string"||t.trim().length===0)&&be(`config: '${e}' must be a non-empty string`),t.trim()}function Go(t,e){if(t==null)return;typeof t!="string"&&be(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function kC(t){(!t||typeof t!="object")&&be("config: expected a JSON object");let e=t,r=Ie(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||be("config: 'hubUrl' must start with http(s)://");let n=Ie(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&be("config: 'project' is required");let i=o,s=Ie(i.id,"project.id");Ht.test(s)||be("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=Ie(i.name,"project.name"),c=Ie(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&be("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||be("config: 'project.repos' must be an array");let u=l.map((y,$)=>{(!y||typeof y!="object")&&be(`config: project.repos[${$}] must be an object`);let x=y,T=Ie(x.host,`project.repos[${$}].host`);T!=="github"&&T!=="bitbucket"&&T!=="gitlab"&&be(`config: project.repos[${$}].host must be 'github', 'bitbucket' or 'gitlab'`);let v={name:Ie(x.name,`project.repos[${$}].name`),host:T,owner:Ie(x.owner,`project.repos[${$}].owner`),repoName:Ie(x.repoName,`project.repos[${$}].repoName`)},b=Go(x.defaultBranch,`project.repos[${$}].defaultBranch`);b&&(v.defaultBranch=b);let R=Go(x.mountAs,`project.repos[${$}].mountAs`);return R&&(v.mountAs=R),v}),p=i.contextRepo;(!p||typeof p!="object")&&be("config: 'project.contextRepo' is required");let d=p,m=Go(d.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&be("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:m,owner:Ie(d.owner,"project.contextRepo.owner"),name:Go(d.name,"project.contextRepo.name")??$t(s)},g={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:f}},h=Go(i.youtrackProjectKey,"project.youtrackProjectKey");if(h&&(g.project.youtrackProjectKey=h),i.index!==void 0&&(typeof i.index!="boolean"&&be("config: 'project.index' must be a boolean"),g.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&be("config: 'project.youtrackWrites' must be a boolean"),g.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let y=Ie(i.llmProvider,"project.llmProvider");y==="codex"&&be(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),y!=="claude"&&be("config: 'project.llmProvider' must be 'claude'"),g.project.llmProvider=y}let k=e.secrets;if(k!==void 0){(typeof k!="object"||k===null)&&be("config: 'secrets' must be an object");let y=k,$={};if(y.github){let x=y.github;$.github={token:Ie(x.token,"secrets.github.token")}}if(y.bitbucket){let x=y.bitbucket;$.bitbucket={email:Ie(x.email,"secrets.bitbucket.email"),apiToken:Ie(x.apiToken,"secrets.bitbucket.apiToken")}}if(y.gitlab){let x=y.gitlab;$.gitlab={token:Ie(x.token,"secrets.gitlab.token")}}if(y.youtrack){let x=y.youtrack;$.youtrack={url:Ie(x.url,"secrets.youtrack.url").replace(/\/$/,""),token:Ie(x.token,"secrets.youtrack.token")}}if(y.contextWrite){let x=y.contextWrite;$.contextWrite={token:Ie(x.token,"secrets.contextWrite.token")}}g.secrets=$}return g}async function bC(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function $C(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await Wt(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 qt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await di(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 Yt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Xt({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 bC():wC(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){be(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=kC(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 $C(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 An(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??Zr(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){be(`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 tr(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 oe(o,i,s.id);else if(d instanceof W)be(`HUB \u2192 ${d.status} ${d.message}`);else throw d}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let p={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(ae(p),Nt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${vt(s.id)}`),Zt(s.id,St(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,s.llmProvider??Ye),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await Io(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`)}Fe();pe();import{cancel as uk,intro as dk,isCancel as pk,log as zl,outro as vC,password as fk}from"@clack/prompts";async function xC(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function mk(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await xC(),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"),zl.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await fk({message:"Claude OAuth token"});pk(i)&&(uk("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Hd({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${ii()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=nt(t.profile);if(!e){dk(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),zl.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await fk({message:"Claude OAuth token"});pk(i)&&(uk("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=Y(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},ae(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(zl.success("Claude OAuth token saved."),vC("It will be sealed into job bundles when a SANDBOX (re)connects."))}Ro();F();Fe();Lt();Lo();Er();ks();je();pe();import{cancel as SC,confirm as EC,intro as TC,isCancel as hk,log as Me,outro as IC,select as gk,text as lr}from"@clack/prompts";function yk(t){SC(t),process.exit(1)}function On(t){return hk(t)&&yk("aborted"),t}function Ko(t){return hk(t)&&yk("aborted"),typeof t=="string"?t:""}async function RC(t,e){let r=On(await gk({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=Ko(await lr({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=Ko(await lr({message:"Context Repo name",placeholder:$t(t),initialValue:$t(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function wk(t={profile:void 0}){let e=nt(t.profile);TC(`codepipe project add \u2192 ${e.hubUrl}`);let r=On(await lr({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>Ht.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=On(await lr({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=On(await gk({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=On(await lr({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=On(await EC({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=Ko(await lr({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:k=>!k||!k.trim()||He(k)?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=He(d);Me.message(`${m.host}: ${m.owner}/${m.repoName}`);let f=Ko(await lr({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:k=>k.trim().length>0?void 0:"required"})).trim(),g=Ko(await lr({message:"default branch (optional)",placeholder:"main"})).trim(),h={name:f,host:m.host,owner:m.owner,repoName:m.repoName};g&&(h.defaultBranch=g),a.push(h)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await RC(r,a),u=Y(e.projectId);Me.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await An(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??Zr(),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 tr(e.hubUrl,e.cliToken,c);Me.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),Zt(r,St(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}`),IC("done")}catch(d){d instanceof W?(Me.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&Me.message(JSON.stringify(d.payload,null,2))):Me.error(d instanceof Error?d.message:String(d)),process.exit(1)}}Pn();Fe();je();pe();rt();Uo();import{existsSync as CC,rmSync as PC}from"node:fs";import{confirm as AC,intro as _C,isCancel as jC,log as ur,outro as NC,spinner as OC}from"@clack/prompts";function It(t){ur.error(t),process.exit(1)}var kk=t=>t.trim().replace(/\/+$/,"");async function bk(t){_C("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Pe()?.spec.projectId??void 0;e||It("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=mt(e);r||It(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=kk(r.hubUrl),o=r.projectId,i=kk(t.hub);i.startsWith("http")||It("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&It(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let k=OC();k.start(`reading project ${o} from ${n}\u2026`);try{l=await oe(n,r.cliToken,o),k.stop(`read project ${o} (${l.name})`)}catch(y){throw k.stop("could not read the source project",1),y instanceof W&&It(`source HUB ${n} \u2192 ${y.status} ${y.message}. The source HUB must be reachable with a valid token to move a project.`),y}}l.contextRepo||It(`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 jn()).trim().toLowerCase();if(ur.message(`move project '${o}'
966
966
  from : ${n} (profile ${e})
967
967
  to : ${i} (profile ${s}, project ${a}, account ${p})
968
968
  \u2022 the source registration on the old HUB is left intact (non-destructive)
969
969
  \u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
970
- `+(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 k=await AC({message:"Continue?",initialValue:!0});(jC(k)||!k)&&Rt("aborted")}!c&&a===o&&ur.warn(`source and destination share the same project id, so they share one secrets file (${xt(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 Nn(i,p),f={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:m,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};ur.step(`registering project on ${i}\u2026`);let g;try{g=await tr(i,d,f)}catch(k){if(k instanceof H&&k.status===409){ur.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{g=await oe(i,d,a)}catch(w){throw w instanceof H&&Rt(`target HUB \u2192 ${w.status} ${w.message}`),w}}else if(k instanceof H&&k.status===403)Rt(`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(k instanceof H)Rt(`target HUB \u2192 ${k.status} ${k.message}`);else throw k}ur.success(`project ${g.projectId} ready on ${i} (${g.provisioningStatus})`),Nt({hubUrl:i,cliToken:d,projectId:a,accountEmail:m},s);let h={...u??{},hubUrl:i,cliToken:d,projectId:a};if(delete h.sandboxPins,ae(h),ur.success(`profile '${s}' \u2192 ${xt(a)}`),c){let k=kt(s);CC(k)&&(PC(k),ur.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}NC(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}Fe();import{existsSync as Xl,rmSync as LC,statSync as MC}from"node:fs";import{join as As,relative as DC,resolve as UC}from"node:path";import{cancel as BC,intro as vk,isCancel as FC,log as Se,outro as xk,text as jr}from"@clack/prompts";import{simpleGit as Sk}from"simple-git";ks();je();ho();pe();rt();function Ze(t){BC(t),process.exit(1)}function Nr(t){return FC(t)&&Ze("aborted"),typeof t=="string"?t:""}async function $k(t){try{let e=await Sk(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function GC(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function KC(t,e){let r=V(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(GC(r,e)){Se.message(`reusing existing ${e} credentials`);return}if(Se.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=Nr(await jr({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=Nr(await jr({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=Nr(await jr({message:`${e} access token (read access to the repo)`,validate:o=>o.trim()?void 0:"required"})).trim();e==="github"?r.github={token:n}:r.gitlab={token:n}}ae(r),Se.success(`saved ${e} credentials`)}async function Ek(t){let e=nt(t.profile);vk(`codepipe repo add \u2192 project ${e.projectId}`);let r=Pe()??void 0,n;try{n=(await oe(e.hubUrl,e.cliToken,e.projectId)).repos}catch(w){Ze(`could not read project from HUB: ${w instanceof Error?w.message:String(w)}`)}let o=t.target?.trim();if(!o){let w=await $k(process.cwd());w?(o=process.cwd(),Se.message(`using the current directory (${w})`)):o=Nr(await jr({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(Xl(o)&&MC(o).isDirectory()){i=UC(o);let w=await $k(i);w||Ze(`${i} is not a git repository (no origin remote)`);let $=He(w);$||Ze(`origin ${w} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=$,s=w,Se.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let w=He(o);w||Ze(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=w,s=o,Se.message(`${a}: ${c}/${l}`)}let u=Nr(await jr({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)&&Ze(`a repo named "${u}" is already registered`);let p=Nr(await jr({message:"default branch (optional)",placeholder:"main"})).trim(),d=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let w=DC(r.root,i);d=w===""?".":w}let m=Nr(await jr({message:"mount_as (directory relative to the workspace root)",placeholder:d,initialValue:d})).trim()||d;n.some(w=>(w.mountAs??w.name)===m)&&Ze(`mount_as "${m}" is already used by another repo`),await KC(e,a);let f={name:u,host:a,owner:c,repoName:l,mountAs:m,...p?{defaultBranch:p}:{}};if(!i){let w=r?As(r.root,m):_e(e.projectId,u);if(Xl(As(w,".git")))Se.message(`already cloned at ${w}`);else{Se.info(`cloning ${s} \u2192 ${w} \u2026`);try{await Sk().clone(s,w),Se.success(`cloned into ${w}`)}catch($){Ze(`clone failed: ${$ instanceof Error?$.message.trim():String($)}
971
- check that your ${a} credentials grant read access to ${c}/${l}`)}}}let g;try{g=await ch(e.hubUrl,e.cliToken,e.projectId,f)}catch(w){w instanceof H&&Ze(`HUB \u2192 ${w.status} ${w.message}`),Ze(w instanceof Error?w.message:String(w))}let{updated:h,errors:k}=mo(e.projectId,g.repos,r?.contextDir);for(let w of h)Se.message(`updated ${w}`);for(let w of k)Se.warn(`could not update ${w.path}: ${w.error}`);Se.success(`added "${u}" \u2014 project now has ${g.repos.length} repo(s)`),xk("done")}async function Tk(t){let e=nt(t.profile);vk(`codepipe repo remove \u2192 project ${e.projectId}`);let r=Pe()??void 0,n;try{let c=(await oe(e.hubUrl,e.cliToken,e.projectId)).repos.find(l=>l.name===t.name);n=c?c.mountAs??c.name:void 0}catch{}let o;try{o=await lh(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof H&&(a.status===404&&Ze(`no repo named "${t.name}" in this project`),Ze(`HUB \u2192 ${a.status} ${a.message}`)),Ze(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=mo(e.projectId,o.repos,r?.contextDir);for(let a of i)Se.message(`updated ${a}`);for(let a of s)Se.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")Se.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?As(r.root,n):_e(e.projectId,t.name);if(Xl(As(a,".git")))try{LC(a,{recursive:!0,force:!0}),Se.message(`deleted local clone ${a}`)}catch(c){Se.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else Se.message(`no local clone found to purge (${a})`)}Se.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),xk("done")}async function Ik(t){let e=nt(t.profile),r;try{r=(await oe(e.hubUrl,e.cliToken,e.projectId)).repos}catch(n){console.error(`could not read project from HUB: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(r.length===0){console.log(`project ${e.projectId} has no repos yet \u2014 add one with \`codepipe repo add\``);return}console.log(`project ${e.projectId} \u2014 ${r.length} repo(s):`);for(let n of r){let o=n.mountAs??n.name,i=n.defaultBranch?` @${n.defaultBranch}`:"";console.log(` ${n.name} ${n.host}:${n.owner}/${n.repoName}${i} \u2192 ${o}`)}}$s();F();Fe();je();rt();rt();import{existsSync as Rk}from"node:fs";import{join as Jl}from"node:path";import{simpleGit as Zl}from"simple-git";var HC=60;async function Ck(t){let{cfg:e}=Xr(t.profile),r=Vr(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 uh(e.hubUrl,e.cliToken,e.projectId);if(s.length===0){console.log("[pull] nothing ready yet");return}for(let a of s)await WC(r.root,r.spec.repos,a,n);await zC(r.contextDir)};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??HC)*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 WC(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(!to(o.branchName)){n.has(s)||(n.add(s),console.warn(`[pull] ${r.taskKey} ${i.mountAs}: refusing suspicious branch name`));continue}let a=Jl(t,i.mountAs);if(!Rk(Jl(a,".git")))continue;let c=Zl(a);try{let l=await VC(c,o.branchName);await c.fetch(await qC(c,i),`refs/heads/${o.branchName}`);let u=(await c.revparse(["FETCH_HEAD"])).trim();if(l===u)continue;if(await YC(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(`
970
+ `+(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 k=await AC({message:"Continue?",initialValue:!0});(jC(k)||!k)&&It("aborted")}!c&&a===o&&ur.warn(`source and destination share the same project id, so they share one secrets file (${vt(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 Nn(i,p),f={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:m,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};ur.step(`registering project on ${i}\u2026`);let g;try{g=await tr(i,d,f)}catch(k){if(k instanceof W&&k.status===409){ur.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{g=await oe(i,d,a)}catch(y){throw y instanceof W&&It(`target HUB \u2192 ${y.status} ${y.message}`),y}}else if(k instanceof W&&k.status===403)It(`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(k instanceof W)It(`target HUB \u2192 ${k.status} ${k.message}`);else throw k}ur.success(`project ${g.projectId} ready on ${i} (${g.provisioningStatus})`),Nt({hubUrl:i,cliToken:d,projectId:a,accountEmail:m},s);let h={...u??{},hubUrl:i,cliToken:d,projectId:a};if(delete h.sandboxPins,ae(h),ur.success(`profile '${s}' \u2192 ${vt(a)}`),c){let k=yt(s);CC(k)&&(PC(k),ur.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}NC(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}Fe();import{existsSync as Xl,rmSync as LC,statSync as MC}from"node:fs";import{join as As,relative as DC,resolve as UC}from"node:path";import{cancel as BC,intro as vk,isCancel as FC,log as Se,outro as xk,text as jr}from"@clack/prompts";import{simpleGit as Sk}from"simple-git";ks();je();ho();pe();rt();function Ze(t){BC(t),process.exit(1)}function Nr(t){return FC(t)&&Ze("aborted"),typeof t=="string"?t:""}async function $k(t){try{let e=await Sk(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function GC(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function KC(t,e){let r=Y(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(GC(r,e)){Se.message(`reusing existing ${e} credentials`);return}if(Se.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=Nr(await jr({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=Nr(await jr({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=Nr(await jr({message:`${e} access token (read access to the repo)`,validate:o=>o.trim()?void 0:"required"})).trim();e==="github"?r.github={token:n}:r.gitlab={token:n}}ae(r),Se.success(`saved ${e} credentials`)}async function Ek(t){let e=nt(t.profile);vk(`codepipe repo add \u2192 project ${e.projectId}`);let r=Pe()??void 0,n;try{n=(await oe(e.hubUrl,e.cliToken,e.projectId)).repos}catch(y){Ze(`could not read project from HUB: ${y instanceof Error?y.message:String(y)}`)}let o=t.target?.trim();if(!o){let y=await $k(process.cwd());y?(o=process.cwd(),Se.message(`using the current directory (${y})`)):o=Nr(await jr({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(Xl(o)&&MC(o).isDirectory()){i=UC(o);let y=await $k(i);y||Ze(`${i} is not a git repository (no origin remote)`);let $=He(y);$||Ze(`origin ${y} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=$,s=y,Se.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let y=He(o);y||Ze(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=y,s=o,Se.message(`${a}: ${c}/${l}`)}let u=Nr(await jr({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:y=>y.trim()?void 0:"required"})).trim();n.some(y=>y.name===u)&&Ze(`a repo named "${u}" is already registered`);let p=Nr(await jr({message:"default branch (optional)",placeholder:"main"})).trim(),d=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let y=DC(r.root,i);d=y===""?".":y}let m=Nr(await jr({message:"mount_as (directory relative to the workspace root)",placeholder:d,initialValue:d})).trim()||d;n.some(y=>(y.mountAs??y.name)===m)&&Ze(`mount_as "${m}" is already used by another repo`),await KC(e,a);let f={name:u,host:a,owner:c,repoName:l,mountAs:m,...p?{defaultBranch:p}:{}};if(!i){let y=r?As(r.root,m):_e(e.projectId,u);if(Xl(As(y,".git")))Se.message(`already cloned at ${y}`);else{Se.info(`cloning ${s} \u2192 ${y} \u2026`);try{await Sk().clone(s,y),Se.success(`cloned into ${y}`)}catch($){Ze(`clone failed: ${$ instanceof Error?$.message.trim():String($)}
971
+ check that your ${a} credentials grant read access to ${c}/${l}`)}}}let g;try{g=await ch(e.hubUrl,e.cliToken,e.projectId,f)}catch(y){y instanceof W&&Ze(`HUB \u2192 ${y.status} ${y.message}`),Ze(y instanceof Error?y.message:String(y))}let{updated:h,errors:k}=mo(e.projectId,g.repos,r?.contextDir);for(let y of h)Se.message(`updated ${y}`);for(let y of k)Se.warn(`could not update ${y.path}: ${y.error}`);Se.success(`added "${u}" \u2014 project now has ${g.repos.length} repo(s)`),xk("done")}async function Tk(t){let e=nt(t.profile);vk(`codepipe repo remove \u2192 project ${e.projectId}`);let r=Pe()??void 0,n;try{let c=(await oe(e.hubUrl,e.cliToken,e.projectId)).repos.find(l=>l.name===t.name);n=c?c.mountAs??c.name:void 0}catch{}let o;try{o=await lh(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof W&&(a.status===404&&Ze(`no repo named "${t.name}" in this project`),Ze(`HUB \u2192 ${a.status} ${a.message}`)),Ze(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=mo(e.projectId,o.repos,r?.contextDir);for(let a of i)Se.message(`updated ${a}`);for(let a of s)Se.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")Se.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?As(r.root,n):_e(e.projectId,t.name);if(Xl(As(a,".git")))try{LC(a,{recursive:!0,force:!0}),Se.message(`deleted local clone ${a}`)}catch(c){Se.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else Se.message(`no local clone found to purge (${a})`)}Se.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),xk("done")}async function Ik(t){let e=nt(t.profile),r;try{r=(await oe(e.hubUrl,e.cliToken,e.projectId)).repos}catch(n){console.error(`could not read project from HUB: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(r.length===0){console.log(`project ${e.projectId} has no repos yet \u2014 add one with \`codepipe repo add\``);return}console.log(`project ${e.projectId} \u2014 ${r.length} repo(s):`);for(let n of r){let o=n.mountAs??n.name,i=n.defaultBranch?` @${n.defaultBranch}`:"";console.log(` ${n.name} ${n.host}:${n.owner}/${n.repoName}${i} \u2192 ${o}`)}}$s();F();Fe();je();rt();rt();import{existsSync as Rk}from"node:fs";import{join as Jl}from"node:path";import{simpleGit as Zl}from"simple-git";var HC=60;async function Ck(t){let{cfg:e}=Xr(t.profile),r=Vr(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 uh(e.hubUrl,e.cliToken,e.projectId);if(s.length===0){console.log("[pull] nothing ready yet");return}for(let a of s)await WC(r.root,r.spec.repos,a,n);await zC(r.contextDir)};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??HC)*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 WC(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(!to(o.branchName)){n.has(s)||(n.add(s),console.warn(`[pull] ${r.taskKey} ${i.mountAs}: refusing suspicious branch name`));continue}let a=Jl(t,i.mountAs);if(!Rk(Jl(a,".git")))continue;let c=Zl(a);try{let l=await VC(c,o.branchName);await c.fetch(await qC(c,i),`refs/heads/${o.branchName}`);let u=(await c.revparse(["FETCH_HEAD"])).trim();if(l===u)continue;if(await YC(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(`
972
972
  `)[0]:String(l)))}}}async function qC(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 ri(e)}async function YC(t,e,r){try{return(await t.raw(["worktree","list","--porcelain"])).split(`
973
973
  `).some(o=>o.trim()===`branch refs/heads/${r}`)}catch{try{return(await Zl(e).revparse(["--abbrev-ref","HEAD"])).trim()===r}catch{return!1}}}async function VC(t,e){try{return(await t.revparse([e])).trim()}catch{return null}}async function zC(t){if(!(!t||!Rk(Jl(t,".git"))))try{await Zl(t).pull(["--ff-only"])}catch(e){console.warn(`[pull] context repo not updated \u2014 ${e instanceof Error?e.message.split(`
974
- `)[0]:String(e)}`)}}Ts();import{existsSync as Nk,mkdirSync as XC,readFileSync as JC,writeFileSync as ZC}from"node:fs";import{homedir as QC}from"node:os";import{dirname as eP,join as Ok}from"node:path";import*as Mn from"node:readline";je();xi();pe();rt();$s();Ts();var _s=Ok(QC(),".codepipe","history"),Pk=["/help","/status","/tasks","/task","/sync","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Lk=500,Ak=40;async function Mk(t={}){let e=Pe();e||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let r=V(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)),io(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=Mn.createInterface({input:process.stdin,output:process.stdout,completer:tP,history:gP(),removeHistoryDuplicates:!0}),o={ws:e,secrets:r,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};wf(i=>dr(o,i)),o.daemon=ts({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:i=>dr(o,i),warn:i=>dr(o,i)},onEvent:i=>pP(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 xs(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=Ss({entry:s,profile:t.profile,onLine:c=>dr(o,`[worker] ${c}`)});a.on("exit",(c,l)=>{o.workerExited=!0,!tu&&Ln(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.`)}eu(o),n.prompt(),n.on("line",async i=>{let s=i.trim();if(s.length>0)try{if(await rP(o,s)){jk(o);return}}catch(a){console.error(a instanceof Error?a.message:String(a))}o.unread=0,eu(o),n.prompt()}),n.on("close",()=>{jk(o)})}function tP(t){let e=Pk.filter(r=>r.startsWith(t));return[e.length?e:Pk,t]}async function rP(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return nP(),!1;case"/status":return await oP(t),!1;case"/tasks":return await iP(t,n),!1;case"/task":return await sP(t,n),!1;case"/sync":return await aP(t),!1;case"/logs":return fP(t,n),!1;case"/monitor":return mP(t),!1;case"/approve":return await _k(t,n,"approve"),!1;case"/merge":return await _k(t,n,"merge"),!1;case"/login":return cP(t,n),!1;case"/secret":return lP(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function nP(){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(`
974
+ `)[0]:String(e)}`)}}Ts();import{existsSync as Nk,mkdirSync as XC,readFileSync as JC,writeFileSync as ZC}from"node:fs";import{homedir as QC}from"node:os";import{dirname as eP,join as Ok}from"node:path";import*as Mn from"node:readline";je();xi();pe();rt();$s();Ts();var _s=Ok(QC(),".codepipe","history"),Pk=["/help","/status","/tasks","/task","/sync","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Lk=500,Ak=40;async function Mk(t={}){let e=Pe();e||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let r=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)),io(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=Mn.createInterface({input:process.stdin,output:process.stdout,completer:tP,history:gP(),removeHistoryDuplicates:!0}),o={ws:e,secrets:r,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};wf(i=>dr(o,i)),o.daemon=ts({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:i=>dr(o,i),warn:i=>dr(o,i)},onEvent:i=>pP(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 xs(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=Ss({entry:s,profile:t.profile,onLine:c=>dr(o,`[worker] ${c}`)});a.on("exit",(c,l)=>{o.workerExited=!0,!tu&&Ln(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.`)}eu(o),n.prompt(),n.on("line",async i=>{let s=i.trim();if(s.length>0)try{if(await rP(o,s)){jk(o);return}}catch(a){console.error(a instanceof Error?a.message:String(a))}o.unread=0,eu(o),n.prompt()}),n.on("close",()=>{jk(o)})}function tP(t){let e=Pk.filter(r=>r.startsWith(t));return[e.length?e:Pk,t]}async function rP(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return nP(),!1;case"/status":return await oP(t),!1;case"/tasks":return await iP(t,n),!1;case"/task":return await sP(t,n),!1;case"/sync":return await aP(t),!1;case"/logs":return fP(t,n),!1;case"/monitor":return mP(t),!1;case"/approve":return await _k(t,n,"approve"),!1;case"/merge":return await _k(t,n,"merge"),!1;case"/login":return cP(t,n),!1;case"/secret":return lP(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function nP(){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(`
975
975
  `))}async function oP(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=Nk(Ok(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function iP(t,e){let r=hP(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){ru(n)}}async function sP(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await sh(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){ru(n)}}async function aP(t){let e=await Do(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 _k(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await ah(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){ru(o)}}function cP(t,e){let r=e.join(" ").trim();if(!r){console.log("usage: /login <claude-oauth-token>"),console.log(" get one with `claude setup-token`, then paste it here."),console.log(" (this line is scrubbed from history; takes effect on next SANDBOX reconnect)");return}t.secrets.claude={oauthToken:r},ae(t.secrets),console.log(" Claude OAuth token saved. It will be sealed into job bundles for SANDBOXes."),console.log(" Re-seal happens when a SANDBOX (re)connects; restart it if you need it now.")}function lP(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(`
976
976
  `)}`:" (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}uP(t.secrets,n,i),ae(t.secrets),io(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}dP(t.secrets,n),ae(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function uP(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 dP(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 pP(t,e){switch(e.kind){case"connected":t.connection="connecting",dr(t,"[hub] connected");break;case"registered":t.connection="registered",dr(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Ln(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",dr(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Ln(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Ln(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?dr(t,`[hub] action ${e.actionType} done`):Ln(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function dr(t,e){t.logBuffer.push(e),t.logBuffer.length>Lk&&t.logBuffer.shift(),t.follow&&Ln(t,e)}function fP(t,e){let r=e[0];if(r==="follow"||r==="on"){Ql(t,!0);return}if(r==="off"){Ql(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(Lk,Number(r)||Ak)):Ak,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 mP(t){Ql(t,!t.follow)}function Ql(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Ln(t,e){Mn.cursorTo(process.stdout,0),Mn.clearLine(process.stdout,0),process.stdout.write(e+`
977
977
  `),t.unread+=1,eu(t),t.rl.prompt(!0)}function eu(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var tu=!1;function jk(t){if(tu)return;tu=!0,yP(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
978
978
  bye.`),setTimeout(()=>process.exit(0),150);return}console.log(`
979
- 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 hP(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function ru(t){t instanceof H?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function gP(){if(!Nk(_s))return[];try{return JC(_s,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function yP(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{XC(eP(_s),{recursive:!0}),ZC(_s,r.slice().reverse().join(`
979
+ 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 hP(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function ru(t){t instanceof W?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function gP(){if(!Nk(_s))return[];try{return JC(_s,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function yP(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{XC(eP(_s),{recursive:!0}),ZC(_s,r.slice().reverse().join(`
980
980
  `)+`
981
- `)}catch{}}Pn();F();Be();Pn();Fe();je();Uo();import{hostname as wP}from"node:os";import{cancel as kP,confirm as Dk,intro as bP,isCancel as Fk,log as Dn,multiselect as $P,outro as Uk,password as vP,select as nu,text as ou}from"@clack/prompts";function Ho(t){kP(t),process.exit(1)}function Un(t){return Fk(t)&&Ho("aborted"),t}function js(t){return Fk(t)&&Ho("aborted"),typeof t=="string"?t:""}function Ns(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Bk(t,e){try{let{secret:r}=await Vi(t,e);return r}catch(r){throw r instanceof H&&r.status===404&&Ho("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 xP(t,e){if(Un(await nu({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 Zc(t,e);if(o.length>0)return Un(await $P({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}));Dn.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Dn.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return js(await ou({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 iu(t){bP("codepipe worker \u2014 set up this machine as a runner");let e=Le(t.profile);e&&(Dn.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Un(await Dk({message:"re-register this worker?",initialValue:!1}))||Ho("keeping the existing registration"));let r=gt(t.profile)??gt(),n=js(await ou({message:"HUB URL",placeholder:dt,initialValue:z("HUB_URL")??r?.hubUrl??dt,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=Un(await nu({message:"how to authorize the registration?",options:[...o?[{value:"local",label:"this machine's CLI account (recommended \u2014 no token hand-off)"}]:[],{value:"login",label:"log in by email (magic-link, like codepipe init)"},{value:"paste",label:"paste a registration token from the dashboard"}],initialValue:o?"local":"login"})),s,a=null;if(i==="local")a=r.cliToken,s=await Bk(n,a),Dn.success("account-issued registration token minted");else if(i==="login"){let d=await jn();a=(await Nn(n,d)).cliToken,s=await Bk(n,a),Dn.success("account-issued registration token minted")}else s=js(await vP({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||Ho("a registration token is required");let c=await xP(n,a),l=js(await ou({message:"worker name",initialValue:wP(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=Un(await nu({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 Pr({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Dn.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Un(await Dk({message:"start the claim-loop now?",initialValue:!0}))){Uk("registered. start later with `codepipe worker`.");return}Uk("starting the claim-loop\u2026"),await Oo(t.profile?{profile:t.profile}:{})}function EP(){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 z("PROFILE")}var ke=EP();_d(ke);var De=new SP;De.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(qe).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{Ns()?await Mk({profile:ke}):await Es({profile:ke})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});De.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await lk({configPath:t.config,skipVerify:t.skipVerify===!0}):await Jw({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 Wd({...t,profile:ke})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await Zw({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 ng({profile:ke})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});De.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await Ow({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 mk({profile:ke,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await iw({profile:ke})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});De.command("pull").description("Fetch finished task branches into your local clones (no checkout switch)").option("--profile <name>","Config profile").option("--watch","Keep pulling instead of exiting after one pass").option("--interval <sec>","Watch interval in seconds (default 60, minimum 10)",t=>parseInt(t,10)).action(async t=>{if(t.interval!==void 0&&!Number.isFinite(t.interval))throw new Error("--interval expects a number of seconds");await Ck({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 Es({profile:ke,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Gk=De.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Gk.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??z("HUB_URL")??gt(ke)?.hubUrl??dt,r=t.token??z("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Ns()){await iu({profile:ke});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let n=z("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??z("WORKER_NAME"),i=t.llm??z("WORKER_LLM");await Pr({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...ke?{profile:ke}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Gk.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!Le(ke)&&Ns()){await iu({profile:ke});return}await Oo(ke?{profile:ke}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Kk=De.command("project").description("Manage CodePipe projects");Kk.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await wk({profile:ke})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Kk.command("move").description("Repoint an already-initialised project at another HUB (no full init wizard)").requiredOption("--hub <url>","Destination HUB base URL").option("--from-profile <id>","Source profile to move (defaults to --profile / the cwd workspace)").option("--to-profile <id>","Destination profile to write (defaults to the source profile \u2014 in place)").option("--project <id>","Destination project id (defaults to the source project id)").option("--account <email>","Destination account email (defaults to the source account, else prompts)").option("--yes","Skip the confirmation prompt",!1).action(async t=>{try{await bk({...t,cliProfile:ke})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var su=De.command("repo").description("Manage the project's git repositories");su.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 Ek({profile:ke,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});su.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 Tk({profile:ke,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});su.command("list").description("List the project's repos").action(async()=>{try{await Ik({profile:ke})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Hk=De.command("model").description("Project map (model/ in the Context Repo)");Hk.command("build").description("Build the project map from the local repo clones' git history").option("--repo <name>","Build only this repo (logical name)").action(async t=>{try{await ll({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Hk.command("bootstrap").description("Build the map and mine task events from the whole git history (cold start)").option("--repo <name>","Bootstrap only this repo (logical name)").action(async t=>{try{await ul({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.parseAsync();
981
+ `)}catch{}}Pn();F();Be();Pn();Fe();je();Uo();import{hostname as wP}from"node:os";import{cancel as kP,confirm as Dk,intro as bP,isCancel as Fk,log as Dn,multiselect as $P,outro as Uk,password as vP,select as nu,text as ou}from"@clack/prompts";function Ho(t){kP(t),process.exit(1)}function Un(t){return Fk(t)&&Ho("aborted"),t}function js(t){return Fk(t)&&Ho("aborted"),typeof t=="string"?t:""}function Ns(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Bk(t,e){try{let{secret:r}=await Vi(t,e);return r}catch(r){throw r instanceof W&&r.status===404&&Ho("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 xP(t,e){if(Un(await nu({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 Zc(t,e);if(o.length>0)return Un(await $P({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}));Dn.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Dn.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return js(await ou({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 iu(t){bP("codepipe worker \u2014 set up this machine as a runner");let e=Le(t.profile);e&&(Dn.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Un(await Dk({message:"re-register this worker?",initialValue:!1}))||Ho("keeping the existing registration"));let r=mt(t.profile)??mt(),n=js(await ou({message:"HUB URL",placeholder:lt,initialValue:X("HUB_URL")??r?.hubUrl??lt,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=Un(await nu({message:"how to authorize the registration?",options:[...o?[{value:"local",label:"this machine's CLI account (recommended \u2014 no token hand-off)"}]:[],{value:"login",label:"log in by email (magic-link, like codepipe init)"},{value:"paste",label:"paste a registration token from the dashboard"}],initialValue:o?"local":"login"})),s,a=null;if(i==="local")a=r.cliToken,s=await Bk(n,a),Dn.success("account-issued registration token minted");else if(i==="login"){let d=await jn();a=(await Nn(n,d)).cliToken,s=await Bk(n,a),Dn.success("account-issued registration token minted")}else s=js(await vP({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||Ho("a registration token is required");let c=await xP(n,a),l=js(await ou({message:"worker name",initialValue:wP(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=Un(await nu({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 Pr({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Dn.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Un(await Dk({message:"start the claim-loop now?",initialValue:!0}))){Uk("registered. start later with `codepipe worker`.");return}Uk("starting the claim-loop\u2026"),await Oo(t.profile?{profile:t.profile}:{})}function EP(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return X("PROFILE")}var ke=EP();_d(ke);var De=new SP;De.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(qe).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{Ns()?await Mk({profile:ke}):await Es({profile:ke})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});De.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await lk({configPath:t.config,skipVerify:t.skipVerify===!0}):await Jw({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 Wd({...t,profile:ke})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await Zw({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 ng({profile:ke})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});De.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await Ow({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 mk({profile:ke,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await iw({profile:ke})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});De.command("pull").description("Fetch finished task branches into your local clones (no checkout switch)").option("--profile <name>","Config profile").option("--watch","Keep pulling instead of exiting after one pass").option("--interval <sec>","Watch interval in seconds (default 60, minimum 10)",t=>parseInt(t,10)).action(async t=>{if(t.interval!==void 0&&!Number.isFinite(t.interval))throw new Error("--interval expects a number of seconds");await Ck({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 Es({profile:ke,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Gk=De.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Gk.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??X("HUB_URL")??mt(ke)?.hubUrl??lt,r=t.token??X("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Ns()){await iu({profile:ke});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let n=X("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??X("WORKER_NAME"),i=t.llm??X("WORKER_LLM");await Pr({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...ke?{profile:ke}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Gk.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!Le(ke)&&Ns()){await iu({profile:ke});return}await Oo(ke?{profile:ke}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Kk=De.command("project").description("Manage CodePipe projects");Kk.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await wk({profile:ke})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Kk.command("move").description("Repoint an already-initialised project at another HUB (no full init wizard)").requiredOption("--hub <url>","Destination HUB base URL").option("--from-profile <id>","Source profile to move (defaults to --profile / the cwd workspace)").option("--to-profile <id>","Destination profile to write (defaults to the source profile \u2014 in place)").option("--project <id>","Destination project id (defaults to the source project id)").option("--account <email>","Destination account email (defaults to the source account, else prompts)").option("--yes","Skip the confirmation prompt",!1).action(async t=>{try{await bk({...t,cliProfile:ke})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var su=De.command("repo").description("Manage the project's git repositories");su.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 Ek({profile:ke,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});su.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 Tk({profile:ke,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});su.command("list").description("List the project's repos").action(async()=>{try{await Ik({profile:ke})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Hk=De.command("model").description("Project map (model/ in the Context Repo)");Hk.command("build").description("Build the project map from the local repo clones' git history").option("--repo <name>","Build only this repo (logical name)").action(async t=>{try{await ll({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Hk.command("bootstrap").description("Build the map and mine task events from the whole git history (cold start)").option("--repo <name>","Bootstrap only this repo (logical name)").action(async t=>{try{await ul({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.parseAsync();