@code-partner/codepipe 0.8.2-dev.194.gde701ba → 0.8.2-dev.195.g3b11952

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 +45 -44
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
- var Wy=Object.defineProperty;var b=(t,e)=>()=>(t&&(e=t(t=0)),e);var mo=(t,e)=>{for(var r in e)Wy(t,r,{get:e[r],enumerable:!0})};var Oe,et,ns=b(()=>{"use strict";Oe="0.8.2-dev.194.gde701ba",et="https://hub.dev.codepipe.dev"});function go(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Yy&&t<=tt}var tt,Yy,Uc=b(()=>{"use strict";ns();tt=4,Yy=4});var Bc=b(()=>{"use strict";ns()});function ho(t=4){return`# CodePipe Context Repo format version.
2
+ var Wy=Object.defineProperty;var b=(t,e)=>()=>(t&&(e=t(t=0)),e);var mo=(t,e)=>{for(var r in e)Wy(t,r,{get:e[r],enumerable:!0})};var Oe,et,ns=b(()=>{"use strict";Oe="0.8.2-dev.195.g3b11952",et="https://hub.dev.codepipe.dev"});function go(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Yy&&t<=tt}var tt,Yy,Uc=b(()=>{"use strict";ns();tt=4,Yy=4});var Bc=b(()=>{"use strict";ns()});function ho(t=4){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 Kc(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 Gc(t,e=Fc){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 Hc(t,e=Fc){return e.filter(r=>r.version>t)}var rt,vn,Fc,Wc=b(()=>{"use strict";rt=".codepipe-context.yaml",vn=".devpipe-context.yaml",Fc=[{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",rt]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[rt]},{version:3,summary:"Custom project actions (the RUN tab): actions/ scaffold with the format README",addedPaths:["actions/README.md"]},{version:4,summary:"Project map: model/ scaffold with the format README (facts/ vs derived/ layout)",addedPaths:["model/README.md"]}]});function yo(t){return`model/facts/identity/${t}.yaml`}function Sr(t){return`model/facts/events/${t}.yaml`}function Yc(t){return`model/facts/annotations/${t}.md`}function qc(t){return`model/derived/correlates/${t}.yaml`}function qy(t){return t===""?"root":t.replace(/\//g,"-")}function Vc(t,e){return`model/derived/structure/${t}/${qy(e)}.yaml`}function as(t){return typeof t=="string"&&zy.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(!Vy.includes(n))return null;let o=t.slice(e+1,r),i=t.slice(r+1);return o===""&&!Jy.includes(n)||i===""?null:{level:n,repo:o,path:i}}function ke(t){return`task::${t}`}function le(t,e,r){return`${t}:${e}:${r}`}function ko(t){let e=[];return nt(t)?(bo(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(!nt(r)){e.push(`edges[${n}]: not an object`);return}zc.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 Xy(t){return{...t,edges:vr(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function wo(t){return Cr(Xy(t))}function nt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function bo(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function He(t){return typeof t=="string"&&t.length>0}function $o(t){let e=[];if(!nt(t))return{ok:!1,errors:["shard: not an object"]};bo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),He(t.repo)||e.push("repo: missing or empty"),He(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(!nt(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&&!as(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(!nt(o)){e.push(`edges[${i}]: not an object`);return}zc.includes(o.kind)||e.push(`edges[${i}].kind: unknown "${String(o.kind)}"`),(!He(o.to)||!te(o.to))&&e.push(`edges[${i}].to: malformed nodeKey`),(!He(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 vo(t){let e=[];if(!nt(t))return{ok:!1,errors:["identity: not an object"]};if(bo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),He(t.repo)||e.push("repo: missing or empty"),t.builtFromCommit!==void 0&&!He(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(!nt(n)){e.push(`entities[${o}]: not an object`);return}as(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`),He(n.firstSeen)||e.push(`entities[${o}].firstSeen: missing`),He(n.lastSeen)||e.push(`entities[${o}].lastSeen: missing`),n.aliases!==void 0&&(Array.isArray(n.aliases)?n.aliases.forEach((i,s)=>{(!nt(i)||!te(i.key)||!He(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 Rr(t){let e=[];return nt(t)?(bo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),He(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=>!He(r)))&&e.push("commits: not an array of non-empty strings"),Array.isArray(t.files)?t.files.forEach((r,n)=>{if(!nt(r)||!te(r.key)){e.push(`files[${n}].key: malformed nodeKey`);return}r.entityId!==void 0&&!as(r.entityId)&&e.push(`files[${n}].entityId: malformed`),r.churn!==void 0&&!(typeof r.churn=="number"&&r.churn>=0)&&e.push(`files[${n}].churn: not a non-negative number`)}):e.push("files: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}):{ok:!1,errors:["event: not an object"]}}function vr(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function Qy(t){return{...t,nodes:vr(t.nodes,e=>e.key),edges:vr(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function Zy(t){return{...t,entities:vr(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:vr(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function ek(t){let e=t.links?{...t.links,...t.links.adr?{adr:[...t.links.adr].sort()}:{},...t.links.tasks?{tasks:[...t.links.tasks].sort()}:{}}:void 0;return{...t,commits:[...t.commits].sort(),files:vr(t.files,r=>r.key),...e?{links:e}:{}}}function xn(t){return tk.test(t)?t:JSON.stringify(t)}function Zc(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 el(t){return t===null||["boolean","number","string"].includes(typeof t)}function os(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function tl(t,e,r){if(Array.isArray(t)){for(let n of t)if(el(n))r.push(`${e}- ${Zc(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=os(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([i,s],a)=>{let c=a===0?`${e}- `:`${e} `;is(i,s,c,`${e} `,r)})}}return}for(let[n,o]of os(t))is(n,o,e,e,r)}function is(t,e,r,n,o){if(el(e))o.push(`${r}${xn(t)}: ${Zc(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${xn(t)}: []`):(o.push(`${r}${xn(t)}:`),tl(e,`${n} `,o));else{let i=os(e);if(i.length===0)o.push(`${r}${xn(t)}: {}`);else{o.push(`${r}${xn(t)}:`);for(let[s,a]of i)is(s,a,`${n} `,`${n} `,o)}}}function Cr(t){let e=[];return tl(t,"",e),e.join(`
5
+ `}function Kc(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 Gc(t,e=Fc){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 Hc(t,e=Fc){return e.filter(r=>r.version>t)}var rt,vn,Fc,Wc=b(()=>{"use strict";rt=".codepipe-context.yaml",vn=".devpipe-context.yaml",Fc=[{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",rt]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[rt]},{version:3,summary:"Custom project actions (the RUN tab): actions/ scaffold with the format README",addedPaths:["actions/README.md"]},{version:4,summary:"Project map: model/ scaffold with the format README (facts/ vs derived/ layout)",addedPaths:["model/README.md"]}]});function yo(t){return`model/facts/identity/${t}.yaml`}function Sr(t){return`model/facts/events/${t}.yaml`}function Yc(t){return`model/facts/annotations/${t}.md`}function qc(t){return`model/derived/correlates/${t}.yaml`}function qy(t){return t===""?"root":t.replace(/\//g,"-")}function Vc(t,e){return`model/derived/structure/${t}/${qy(e)}.yaml`}function as(t){return typeof t=="string"&&zy.test(t)}function ee(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(!Vy.includes(n))return null;let o=t.slice(e+1,r),i=t.slice(r+1);return o===""&&!Jy.includes(n)||i===""?null:{level:n,repo:o,path:i}}function ke(t){return`task::${t}`}function le(t,e,r){return`${t}:${e}:${r}`}function ko(t){let e=[];return nt(t)?(bo(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(!nt(r)){e.push(`edges[${n}]: not an object`);return}zc.includes(r.kind)||e.push(`edges[${n}].kind: unknown "${String(r.kind)}"`),ee(r.from)||e.push(`edges[${n}].from: malformed nodeKey`),ee(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 Xy(t){return{...t,edges:vr(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function wo(t){return Cr(Xy(t))}function nt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function bo(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function He(t){return typeof t=="string"&&t.length>0}function $o(t){let e=[];if(!nt(t))return{ok:!1,errors:["shard: not an object"]};bo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),He(t.repo)||e.push("repo: missing or empty"),He(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(!nt(o)){e.push(`nodes[${i}]: not an object`);return}let s=ee(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&&!as(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(!nt(o)){e.push(`edges[${i}]: not an object`);return}zc.includes(o.kind)||e.push(`edges[${i}].kind: unknown "${String(o.kind)}"`),(!He(o.to)||!ee(o.to))&&e.push(`edges[${i}].to: malformed nodeKey`),(!He(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 vo(t){let e=[];if(!nt(t))return{ok:!1,errors:["identity: not an object"]};if(bo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),He(t.repo)||e.push("repo: missing or empty"),t.builtFromCommit!==void 0&&!He(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(!nt(n)){e.push(`entities[${o}]: not an object`);return}as(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)})`),ee(n.currentKey)||e.push(`entities[${o}].currentKey: malformed nodeKey`),n.status!=="active"&&n.status!=="orphaned"&&e.push(`entities[${o}].status: expected active|orphaned`),He(n.firstSeen)||e.push(`entities[${o}].firstSeen: missing`),He(n.lastSeen)||e.push(`entities[${o}].lastSeen: missing`),n.aliases!==void 0&&(Array.isArray(n.aliases)?n.aliases.forEach((i,s)=>{(!nt(i)||!ee(i.key)||!He(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 Rr(t){let e=[];return nt(t)?(bo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),He(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=>!He(r)))&&e.push("commits: not an array of non-empty strings"),Array.isArray(t.files)?t.files.forEach((r,n)=>{if(!nt(r)||!ee(r.key)){e.push(`files[${n}].key: malformed nodeKey`);return}r.entityId!==void 0&&!as(r.entityId)&&e.push(`files[${n}].entityId: malformed`),r.churn!==void 0&&!(typeof r.churn=="number"&&r.churn>=0)&&e.push(`files[${n}].churn: not a non-negative number`)}):e.push("files: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}):{ok:!1,errors:["event: not an object"]}}function vr(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function Qy(t){return{...t,nodes:vr(t.nodes,e=>e.key),edges:vr(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function Zy(t){return{...t,entities:vr(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:vr(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function ek(t){let e=t.links?{...t.links,...t.links.adr?{adr:[...t.links.adr].sort()}:{},...t.links.tasks?{tasks:[...t.links.tasks].sort()}:{}}:void 0;return{...t,commits:[...t.commits].sort(),files:vr(t.files,r=>r.key),...e?{links:e}:{}}}function xn(t){return tk.test(t)?t:JSON.stringify(t)}function Zc(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 el(t){return t===null||["boolean","number","string"].includes(typeof t)}function os(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function tl(t,e,r){if(Array.isArray(t)){for(let n of t)if(el(n))r.push(`${e}- ${Zc(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=os(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([i,s],a)=>{let c=a===0?`${e}- `:`${e} `;is(i,s,c,`${e} `,r)})}}return}for(let[n,o]of os(t))is(n,o,e,e,r)}function is(t,e,r,n,o){if(el(e))o.push(`${r}${xn(t)}: ${Zc(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${xn(t)}: []`):(o.push(`${r}${xn(t)}:`),tl(e,`${n} `,o));else{let i=os(e);if(i.length===0)o.push(`${r}${xn(t)}: {}`);else{o.push(`${r}${xn(t)}:`);for(let[s,a]of i)is(s,a,`${n} `,`${n} `,o)}}}function Cr(t){let e=[];return tl(t,"",e),e.join(`
6
6
  `)+`
7
- `}function rl(t){return Cr(Qy(t))}function nl(t){return Cr(Zy(t))}function Sn(t){return Cr(ek(t))}var ss,xr,Vy,zc,zy,Jy,We,Jc,Xc,Qc,Tr,tk,cs=b(()=>{"use strict";ss="model/derived/INDEX.yaml",xr="model/derived/relates.yaml";Vy=["system","container","component","code","task","adr"],zc=["contains","touched_by","correlates","relates","references","depends_on"],zy=/^e_[0-9a-f]{8}$/;Jy=["system","task","adr"];We={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};Jc=2,Xc=5,Qc={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},Tr={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};tk=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});var ol=b(()=>{"use strict"});var rk,aC,il=b(()=>{"use strict";rk=[{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"]}],aC=rk.flatMap(t=>t.phases)});function Jt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var sl,ls=b(()=>{"use strict";sl=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"]});function al(t,e){return e.toLowerCase().includes(t.toLowerCase())}function ul(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||ok.every(o=>e.some(i=>al(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 nk){let i=n.find(s=>al(o,s.id));if(i)return i.id}return n[0].id}var ot,cl,Ye,Tn,ll,us,ds,nk,ok,ps=b(()=>{"use strict";ot="claude",cl=[ot],Ye="opus",Tn="sonnet",ll="haiku",us=[Ye,Tn,ll],ds={analyze:Ye,implement:Ye,"resolve-conflict":Ye,rework:Ye,estimate:Tn,build:Tn,"code-review":Ye,draft:Tn,index:Ye,backfill:Ye,analysis:Ye,chat:Ye},nk=[Ye,Tn,ll],ok=Array.from(new Set(Object.values(ds)))});function Tt(t){return ik.has(t)?!0:sk.some(e=>t.startsWith(e))}function xo(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Xt(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function fs(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function gl(t,e){let r=xo(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=Xt(r.id,"id")??n;if(!dl.test(o))throw new Error(`id must match ${dl} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=Xt(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=xo(r.env,"env");s={};for(let[d,f]of Object.entries(p)){if(!De.test(d))throw new Error(`env name "${d}" must match ${De}`);if(typeof f!="string"&&typeof f!="number"&&typeof f!="boolean")throw new Error(`env.${d} must be a scalar`);s[d]=String(f)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>pl)throw new Error(`too many params (max ${pl})`);let p=new Set;a=c.map((d,f)=>ak(d,f,p))}let l=r.steps;if(!Array.isArray(l)||l.length===0)throw new Error("steps must be a non-empty list");if(l.length>fl)throw new Error(`too many steps (max ${fl})`);let u=l.map((p,d)=>{let f=xo(p,`steps[${d}]`),m=Xt(f.run,`steps[${d}].run`);if(!m||m.trim().length===0)throw new Error(`steps[${d}].run is required`);let g=Xt(f.name,`steps[${d}].name`),k=fs(f.timeout_sec,`steps[${d}].timeout_sec`);if(k!==void 0&&(!Number.isInteger(k)||k<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:m,...g?{name:g}:{},...k!==void 0?{timeout_sec:k}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function ak(t,e,r){let n=xo(t,`params[${e}]`),o=Xt(n.name,`params[${e}].name`);if(!o||!De.test(o))throw new Error(`params[${e}].name must match ${De}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let f=n.enum;if(!Array.isArray(f)||f.length===0||!f.every(m=>typeof m=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=f}let a=Xt(n.label,`params[${e}].label`),c=Xt(n.help,`params[${e}].help`),l=n.required===!0,u=fs(n.min,`params[${e}].min`),p=fs(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 hl(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 De,ik,sk,ml,dl,pl,fl,ms=b(()=>{"use strict";De=/^[A-Z][A-Z0-9_]*$/,ik=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),sk=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];ml=600,dl=/^[a-z0-9-]+$/,pl=32,fl=64});function bl(t=ck){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...bl(r.groups));return e}function lk(t,e){let r=JSON.stringify(e);return bl().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function $l(t){let e=lk(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>yl)return{ok:!1,error:`${e.id} must have \u2264 ${yl} entries`};let s={};for(let[a,c]of i){if(!De.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${De}`};if(Tt(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>kl)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${kl} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var yl,kl,wl,ck,vl=b(()=>{"use strict";ms();ls();ps();cs();yl=64,kl=2e3,wl=2e3,ck=[{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:[...cl],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:[...us],help:"Overrides the recommended defaults for every role not listed below."},...sl.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...us],help:`recommended: ${ds[t]}`}))]}]},{id:"apply.style",label:"Commits & PRs",help:"Instructions for the AI agent on how to write commit messages and PR descriptions. Empty \u21D2 built-in templates.",fields:[{id:"apply.commit_style",file:"project.yaml",path:["apply","commit_style"],type:"string",label:"Commit message style",nullable:!0,multiline:!0,maxLength:wl,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:wl,help:'e.g. "Russian, implementation details, bullet list of what was done". Empty \u21D2 the default PR body.'}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (on by default; orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on (default), a task taken from Develop waits in the QUEUE for a single Confirm before the pipeline starts \u2014 the Confirm pulls in dependency closure and topologically orders the queue. Off \u21D2 conveyor: the task starts the pipeline immediately."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]},{id:"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.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 ${We.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 ${We.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 ${We.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 ${We.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 ${We.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 ${We.topK}.`}]},{id:"implementation",label:"Implementation",help:"How a dependency cluster is serialized into branches and PRs.",fields:[{id:"implementation.mode",file:"regimen.yaml",path:["implementation","mode"],type:"enum",label:"Implementation mode",nullable:!0,suggestions:["cluster-pr","sequential","parallel"],help:"cluster-pr (default for new projects) \u2014 one shared branch and a single PR per dependency cluster; a lone task is a cluster of one. sequential / parallel are an explicit opt-out of that. Clearing removes the key from regimen.yaml but keeps the mode already stored for the project (it is not reset to the default)."}]}]});var xl=b(()=>{"use strict"});var Sl=b(()=>{"use strict"});var Tl=b(()=>{"use strict"});function Rl(t){return`codepipe-host-${t}`}var Cl=b(()=>{"use strict"});function El(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 ht(t){return`${t}${uk}`}var Qt,uk,Il=b(()=>{"use strict";Qt=/^[a-z][a-z0-9-]{1,30}$/,uk="-codepipe-ctx"});var Al=b(()=>{"use strict"});var Pl=b(()=>{"use strict"});function Er(t){for(let e of dk){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var dk,_l=b(()=>{"use strict";dk=[{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}]});var jl=b(()=>{"use strict"});var Nl=b(()=>{"use strict"});var Ol=b(()=>{"use strict"});function Dl(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function Ml(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=Dl(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Ir.test(r))return r;let n=Dl(t);return Ir.test(n)?n:gs}function Ul(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 Cn(t){return`tasks/${t}/issue.yaml`}var Ll,So,gs,Ir,hs,xC,To,Rn,Bl=b(()=>{"use strict";Ll=["bug","feature","epic"],So="feature",gs="TASK",Ir=/^[A-Z][A-Z0-9]{1,9}$/;hs={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},xC=hs.backlog,To="tracker/config.yaml",Rn="tracker/counter"});var Fl=b(()=>{"use strict"});function Ar(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 Ro(t){switch(t){case En.gitlab:return"oauth2";case En.bitbucket:return"x-token-auth";default:return"x-access-token"}}var En,Zt,Kl=b(()=>{"use strict";En={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Zt="x-bitbucket-api-token-auth"});var Gl=b(()=>{"use strict"});var Hl=b(()=>{"use strict";Fl();Kl();Gl()});var Wl,F=b(()=>{"use strict";Uc();Bc();Wc();cs();ol();il();ls();ps();vl();ms();xl();Sl();Tl();Cl();Il();Al();Pl();_l();jl();Nl();Ol();Bl();Hl();Wl=20});function W(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Ce=b(()=>{"use strict"});import{existsSync as Yl,renameSync as pk}from"node:fs";function er(t,e,r=n=>console.error(n)){if(Yl(e)||!Yl(t))return!1;try{return pk(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(n){return r(`failed to migrate ${t} \u2192 ${e}: ${n instanceof Error?n.message:String(n)} \u2014 continuing with the legacy path untouched`),!1}}var Co=b(()=>{"use strict"});import{existsSync as Eo,readFileSync as ql,readdirSync as fk,writeFileSync as mk}from"node:fs";import{dirname as gk,join as Rt}from"node:path";import{parse as hk}from"yaml";function yk(t=process.cwd()){let e=t;for(;;){if(Eo(Rt(e,it,"project.yaml")))return e;if(Eo(Rt(e,ys,"project.yaml")))return er(Rt(e,ys),Rt(e,it))&&wk(e),e;let r=gk(e);if(r===e)return null;e=r}}function kk(t){let e=Rt(t,it);return Eo(e)?e:Rt(t,ys)}function wk(t){let e=Rt(t,".gitignore");if(!Eo(e))return;let r=ql(e,"utf-8"),n=r.split(/\r?\n/).map(o=>{let i=o.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?o.replace(".devpipe",".codepipe"):o}).join(`
7
+ `}function rl(t){return Cr(Qy(t))}function nl(t){return Cr(Zy(t))}function Sn(t){return Cr(ek(t))}var ss,xr,Vy,zc,zy,Jy,We,Jc,Xc,Qc,Tr,tk,cs=b(()=>{"use strict";ss="model/derived/INDEX.yaml",xr="model/derived/relates.yaml";Vy=["system","container","component","code","task","adr"],zc=["contains","touched_by","correlates","relates","references","depends_on"],zy=/^e_[0-9a-f]{8}$/;Jy=["system","task","adr"];We={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};Jc=2,Xc=5,Qc={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},Tr={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};tk=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});var ol=b(()=>{"use strict"});var rk,cC,il=b(()=>{"use strict";rk=[{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"]}],cC=rk.flatMap(t=>t.phases)});function Jt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var sl,ls=b(()=>{"use strict";sl=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"]});function al(t,e){return e.toLowerCase().includes(t.toLowerCase())}function ul(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||ok.every(o=>e.some(i=>al(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 nk){let i=n.find(s=>al(o,s.id));if(i)return i.id}return n[0].id}var ot,cl,Ye,Tn,ll,us,ds,nk,ok,ps=b(()=>{"use strict";ot="claude",cl=[ot],Ye="opus",Tn="sonnet",ll="haiku",us=[Ye,Tn,ll],ds={analyze:Ye,implement:Ye,"resolve-conflict":Ye,rework:Ye,estimate:Tn,build:Tn,"code-review":Ye,draft:Tn,index:Ye,backfill:Ye,analysis:Ye,chat:Ye},nk=[Ye,Tn,ll],ok=Array.from(new Set(Object.values(ds)))});function Tt(t){return ik.has(t)?!0:sk.some(e=>t.startsWith(e))}function xo(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Xt(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function fs(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function gl(t,e){let r=xo(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=Xt(r.id,"id")??n;if(!dl.test(o))throw new Error(`id must match ${dl} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=Xt(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=xo(r.env,"env");s={};for(let[d,f]of Object.entries(p)){if(!De.test(d))throw new Error(`env name "${d}" must match ${De}`);if(typeof f!="string"&&typeof f!="number"&&typeof f!="boolean")throw new Error(`env.${d} must be a scalar`);s[d]=String(f)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>pl)throw new Error(`too many params (max ${pl})`);let p=new Set;a=c.map((d,f)=>ak(d,f,p))}let l=r.steps;if(!Array.isArray(l)||l.length===0)throw new Error("steps must be a non-empty list");if(l.length>fl)throw new Error(`too many steps (max ${fl})`);let u=l.map((p,d)=>{let f=xo(p,`steps[${d}]`),m=Xt(f.run,`steps[${d}].run`);if(!m||m.trim().length===0)throw new Error(`steps[${d}].run is required`);let g=Xt(f.name,`steps[${d}].name`),k=fs(f.timeout_sec,`steps[${d}].timeout_sec`);if(k!==void 0&&(!Number.isInteger(k)||k<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:m,...g?{name:g}:{},...k!==void 0?{timeout_sec:k}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function ak(t,e,r){let n=xo(t,`params[${e}]`),o=Xt(n.name,`params[${e}].name`);if(!o||!De.test(o))throw new Error(`params[${e}].name must match ${De}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let f=n.enum;if(!Array.isArray(f)||f.length===0||!f.every(m=>typeof m=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=f}let a=Xt(n.label,`params[${e}].label`),c=Xt(n.help,`params[${e}].help`),l=n.required===!0,u=fs(n.min,`params[${e}].min`),p=fs(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 hl(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 De,ik,sk,ml,dl,pl,fl,ms=b(()=>{"use strict";De=/^[A-Z][A-Z0-9_]*$/,ik=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),sk=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];ml=600,dl=/^[a-z0-9-]+$/,pl=32,fl=64});function bl(t=ck){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...bl(r.groups));return e}function lk(t,e){let r=JSON.stringify(e);return bl().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function $l(t){let e=lk(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>yl)return{ok:!1,error:`${e.id} must have \u2264 ${yl} entries`};let s={};for(let[a,c]of i){if(!De.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${De}`};if(Tt(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>kl)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${kl} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var yl,kl,wl,ck,vl=b(()=>{"use strict";ms();ls();ps();cs();yl=64,kl=2e3,wl=2e3,ck=[{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:[...cl],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:[...us],help:"Overrides the recommended defaults for every role not listed below."},...sl.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...us],help:`recommended: ${ds[t]}`}))]}]},{id:"apply.style",label:"Commits & PRs",help:"Instructions for the AI agent on how to write commit messages and PR descriptions. Empty \u21D2 built-in templates.",fields:[{id:"apply.commit_style",file:"project.yaml",path:["apply","commit_style"],type:"string",label:"Commit message style",nullable:!0,multiline:!0,maxLength:wl,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:wl,help:'e.g. "Russian, implementation details, bullet list of what was done". Empty \u21D2 the default PR body.'}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (on by default; orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on (default), a task taken from Develop waits in the QUEUE for a single Confirm before the pipeline starts \u2014 the Confirm pulls in dependency closure and topologically orders the queue. Off \u21D2 conveyor: the task starts the pipeline immediately."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]},{id:"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.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 ${We.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 ${We.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 ${We.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 ${We.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 ${We.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 ${We.topK}.`}]},{id:"implementation",label:"Implementation",help:"How a dependency cluster is serialized into branches and PRs.",fields:[{id:"implementation.mode",file:"regimen.yaml",path:["implementation","mode"],type:"enum",label:"Implementation mode",nullable:!0,suggestions:["cluster-pr","sequential","parallel"],help:"cluster-pr (default for new projects) \u2014 one shared branch and a single PR per dependency cluster; a lone task is a cluster of one. sequential / parallel are an explicit opt-out of that. Clearing removes the key from regimen.yaml but keeps the mode already stored for the project (it is not reset to the default)."}]}]});var xl=b(()=>{"use strict"});var Sl=b(()=>{"use strict"});var Tl=b(()=>{"use strict"});function Rl(t){return`codepipe-host-${t}`}var Cl=b(()=>{"use strict"});function El(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 ht(t){return`${t}${uk}`}var Qt,uk,Il=b(()=>{"use strict";Qt=/^[a-z][a-z0-9-]{1,30}$/,uk="-codepipe-ctx"});var Al=b(()=>{"use strict"});var Pl=b(()=>{"use strict"});function Er(t){for(let e of dk){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var dk,_l=b(()=>{"use strict";dk=[{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}]});var jl=b(()=>{"use strict"});var Nl=b(()=>{"use strict"});var Ol=b(()=>{"use strict"});function Dl(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function Ml(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=Dl(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Ir.test(r))return r;let n=Dl(t);return Ir.test(n)?n:gs}function Ul(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 Cn(t){return`tasks/${t}/issue.yaml`}var Ll,So,gs,Ir,hs,SC,To,Rn,Bl=b(()=>{"use strict";Ll=["bug","feature","epic"],So="feature",gs="TASK",Ir=/^[A-Z][A-Z0-9]{1,9}$/;hs={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},SC=hs.backlog,To="tracker/config.yaml",Rn="tracker/counter"});var Fl=b(()=>{"use strict"});function Ar(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 Ro(t){switch(t){case En.gitlab:return"oauth2";case En.bitbucket:return"x-token-auth";default:return"x-access-token"}}var En,Zt,Kl=b(()=>{"use strict";En={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Zt="x-bitbucket-api-token-auth"});var Gl=b(()=>{"use strict"});var Hl=b(()=>{"use strict";Fl();Kl();Gl()});var Wl,F=b(()=>{"use strict";Uc();Bc();Wc();cs();ol();il();ls();ps();vl();ms();xl();Sl();Tl();Cl();Il();Al();Pl();_l();jl();Nl();Ol();Bl();Hl();Wl=20});function W(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Ce=b(()=>{"use strict"});import{existsSync as Yl,renameSync as pk}from"node:fs";function er(t,e,r=n=>console.error(n)){if(Yl(e)||!Yl(t))return!1;try{return pk(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(n){return r(`failed to migrate ${t} \u2192 ${e}: ${n instanceof Error?n.message:String(n)} \u2014 continuing with the legacy path untouched`),!1}}var Co=b(()=>{"use strict"});import{existsSync as Eo,readFileSync as ql,readdirSync as fk,writeFileSync as mk}from"node:fs";import{dirname as gk,join as Rt}from"node:path";import{parse as hk}from"yaml";function yk(t=process.cwd()){let e=t;for(;;){if(Eo(Rt(e,it,"project.yaml")))return e;if(Eo(Rt(e,ys,"project.yaml")))return er(Rt(e,ys),Rt(e,it))&&wk(e),e;let r=gk(e);if(r===e)return null;e=r}}function kk(t){let e=Rt(t,it);return Eo(e)?e:Rt(t,ys)}function wk(t){let e=Rt(t,".gitignore");if(!Eo(e))return;let r=ql(e,"utf-8"),n=r.split(/\r?\n/).map(o=>{let i=o.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?o.replace(".devpipe",".codepipe"):o}).join(`
8
8
  `);n!==r&&mk(e,n)}function ye(t=process.cwd()){let e=yk(t);if(!e)return null;let r=kk(e),n=bk(ql(Rt(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function Vl(t,e,r){return fk(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 Io(t,e=process.cwd()){try{let r=ye(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function bk(t){let e=hk(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),n=String(e.name??r),o=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of o){if(!s||typeof s!="object")continue;let a=s,c=String(a.repo??a.repoName??""),l=String(a.name??c);if(!l||!c)continue;let u=a.host,p=u==="bitbucket"?"bitbucket":u==="gitlab"?"gitlab":"github";i.push({name:l,host:p,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l)})}return{projectId:r,name:n,repos:i}}function zl(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}var it,ys,st=b(()=>{"use strict";Co();it=".codepipe",ys=".devpipe"});import{homedir as Jl}from"node:os";import{mkdirSync as $k,readFileSync as vk,writeFileSync as xk,existsSync as ks}from"node:fs";import{dirname as Ql,join as Ao,resolve as Sk}from"node:path";import{fileURLToPath as Tk}from"node:url";function Zl(t){let e=Ao(Xl,".env");if(ks(e)&&process.loadEnvFile(e),t){let r=Ao(Xl,"profiles",t,".env");ks(r)&&process.loadEnvFile(r)}}function Pr(t){let e=W("CONFIG");return e||(t?Ao(Jl(),".codepipe","profiles",t,"config.json"):Ao(Jl(),".codepipe","config.json"))}function qe(t){let e=Pr(t);if(!ks(e))return null;let r=vk(e,"utf-8");return JSON.parse(r)}function yt(t,e){let r=Pr(e);$k(Ql(r),{recursive:!0}),xk(r,JSON.stringify(t,null,2)+`
9
9
  `,{mode:384})}function Po(t){if(t)return{cfg:Le(t),profile:t};let e;try{e=ye()?.spec.projectId||void 0}catch{}if(e){let r=qe(e);if(r)return console.log(`[profile] ${e} \u2014 resolved from this folder's workspace`),{cfg:r,profile:e};console.error(`this folder is the workspace of project '${e}', but that CLI profile is not initialised on this machine \u2014 run \`codepipe init\` here (or pass --profile).`),process.exit(1)}return{cfg:Le(void 0),profile:void 0}}function Le(t){let e=qe(t);if(!e){let r=t?`codepipe init --profile ${t} --hub <url> --token <token> --project ${t}`:"codepipe init --hub <url> --token <token> --project <id>";console.error(t?`CLI profile '${t}' is not initialised. run \`${r}\` first.`:`CLI is not initialised. run \`${r}\` first.`),process.exit(1)}return e.projectId||(console.error(`config at ${Pr(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var Xl,Pe=b(()=>{"use strict";Ce();st();Xl=Sk(Ql(Tk(import.meta.url)),"..")});import{homedir as nu}from"node:os";import{existsSync as ou,mkdirSync as iu,readFileSync as su,writeFileSync as au}from"node:fs";import{dirname as cu,join as lu}from"node:path";function uu(t,e,r){let n=H(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},X(n)}function du(t,e){let r=H(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],X(r),!0)}function pu(t){return Object.keys(H(t)?.secrets??{}).sort()}function _o(t,e,r){let n=H(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,X(n),"pinned")}function fu(t,e){let r=H(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],X(r),!0):!1}function at(t){return lu(nu(),".codepipe","secrets",`${t}.json`)}function H(t){let e=at(t);return ou(e)?JSON.parse(su(e,"utf-8")):null}function X(t){let e=at(t.projectId);iu(cu(e),{recursive:!0}),au(e,JSON.stringify(t,null,2)+`
10
10
  `,{mode:384})}function jo(){return lu(nu(),".codepipe","shared.json")}function ws(){let t=jo();return ou(t)?JSON.parse(su(t,"utf-8")):null}function mu(t){let e=jo();iu(cu(e),{recursive:!0}),au(e,JSON.stringify(t,null,2)+`
@@ -622,9 +622,9 @@ Append-only. Keyed by entityId \u2014 never by path; entries survive renames.
622
622
  `),$=R+x;h?h.content=$:p.push({path:k,content:$})}return p}var g$,Jp=b(()=>{"use strict";F();g$=12});import{existsSync as ma,readFileSync as ga}from"node:fs";import{join as ha}from"node:path";import{simpleGit as Qp}from"simple-git";import{parse as ya}from"yaml";function ef(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(h$.source,"g")}function tf(t){let e=ha(t,"project.yaml");if(ma(e))try{let o=ya(ga(e,"utf-8"))?.youtrack,i=o&&typeof o=="object"?o.project_key:null;if(typeof i=="string"&&i.trim())return i.trim()}catch{}let r=ha(t,"tracker","config.yaml");if(ma(r))try{let o=ya(ga(r,"utf-8"))?.prefix;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return null}function rf(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 y$(t,e,r){let o=await Qp(t).raw(["log","--numstat","--format=@@@ %H %ct %P %x09%s","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
623
623
  `))if(a.startsWith("@@@ ")){let c=a.indexOf(" "),l=(c>=0?a.slice(4,c):a.slice(4)).trim().split(/\s+/),u=c>=0?a.slice(c+1):"",p=l[0]??"",d=Number(l[1]??0),f=l.slice(2),m=ka.exec(u)??Zp.exec(u);s={sha:p,timeSec:d,subject:u,files:[],prNumber:m?Number(m[1]):null,isMerge:f.length>1},i.push(s)}else if(a.trim()&&s){let c=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(a);if(!c)continue;let l=c[1]==="-"?0:Number(c[1]),u=c[2]==="-"?0:Number(c[2]);s.files.push({path:rf(c[3]),churn:l+u})}return i}async function k$(t,e){let n=await Qp(t).raw(["diff","--numstat",`${e}^1`,e]).catch(()=>""),o=[];for(let i of n.split(`
624
624
  `)){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:rf(s[3]),churn:a+c})}return o}function w$(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(ka,"").trim();else if(c.prNumber!==null)u=`PR-${c.prNumber}`,p=c.subject.replace(ka,"").replace(Zp,"").replace(/^from\s+/,"").trim()||c.subject;else continue;if(!/^[A-Za-z0-9._-]+$/.test(u))continue;let f=new Map;for(let k of c.files){let w=o.get(k.path)??k.path;s(w)||f.set(w,(f.get(w)??0)+k.churn)}if(f.size===0)continue;let g=a.get(u)??{modelFormatVersion:2,taskKey:u,origin:"bootstrap",title:"",commits:[],files:[]};p&&(g.title=p),c.timeSec>0&&(g.date=new Date(c.timeSec*1e3).toISOString().slice(0,10)),g.commits.push(c.sha);for(let[k,w]of f){let h=le("code",e,k),v=g.files.find(T=>T.key===h);if(v)v.churn=(v.churn??0)+w;else{let T=i.get(h);g.files.push({key:h,...T?{entityId:T}:{},churn:w})}}if(d.length>0){let k=new Set([...g.links?.tasks??[],...d]);k.delete(u),g.links={...g.links??{},tasks:[...k].sort()}}a.set(u,g)}return a}function Xp(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 nf(t){let e=await y$(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 k$(t.repoDir,r.sha))}return w$({repo:t.repo,issueKeyRe:t.issueKeyRe,commits:e,pathToCurrent:t.pathToCurrent,entityByKey:t.entityByKey,ignored:t.ignored})}function of(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?Xp(c,a)??c:a)}let n=[],o=0;for(let[i,s]of[...r.entries()].sort(([a],[c])=>a<c?-1:1)){let a=Xp(li(t,i),s);if(!a){o++;continue}n.push({path:Sr(i),content:Sn(a)})}return{files:n,skippedPipeline:o}}function li(t,e){let r=ha(t,Sr(e));if(!ma(r))return null;try{let n=Rr(ya(ga(r,"utf-8")));return n.ok?n.value:null}catch{return null}}var h$,ka,Zp,wa=b(()=>{"use strict";F();h$=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g,ka=/\(#(\d+)\)\s*$/,Zp=/^Merge pull request #(\d+)\b/});import{simpleGit as b$}from"simple-git";async function af(t,e,r){let o=await b$(t).raw(["log","--no-merges","--name-only","--format=@@@ %H %ct","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
625
- `))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 ui(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 cf(t){let{repo:e,headTimeSec:r,filesets:n,pathToCurrent:o,currentPaths:i,ignored:s,settings:a}=t,c=a.halfLifeDays*86400,l=new Map,u=new Map,p=new Map;for(let w of n){let h=new Set;for(let x of w.files){let $=o.get(x)??x;!i.has($)||s($)||h.add($)}if(h.size<2||h.size>a.commitFileCap)continue;let v=Math.max(0,r-w.timeSec),T=Math.pow(.5,v/c),R=[...h].sort();for(let x of R)l.set(x,(l.get(x)??0)+T);for(let x=0;x<R.length;x++)for(let $=x+1;$<R.length;$++){let _=`${R[x]}\0${R[$]}`;u.set(_,(u.get(_)??0)+T),p.set(_,(p.get(_)??0)+1)}}let d=[],f=a.jaccardMinPct/100;for(let[w,h]of u){if((p.get(w)??0)<a.supportMin)continue;let[v,T]=w.split("\0"),R=(l.get(v)??0)+(l.get(T)??0)-h,x=R>0?h/R:0;x<f||d.push({a:v,b:T,weight:Math.round(x*sf)/sf})}let m=new Map;for(let w of d)for(let h of[w.a,w.b])m.has(h)||m.set(h,[]),m.get(h).push(w);let g=new Map;for(let[,w]of m)w.sort((h,v)=>v.weight-h.weight||(h.a<v.a?-1:h.a>v.a?1:h.b<v.b?-1:1)).slice(0,a.topK).forEach(h=>g.set(h,(g.get(h)??0)+1));return[...g.entries()].filter(([,w])=>w===2).map(([w])=>w).map(w=>({kind:"correlates",from:le("code",e,w.a),to:le("code",e,w.b),weight:w.weight})).sort((w,h)=>w.from<h.from?-1:w.from>h.from?1:w.to<h.to?-1:1)}var Wr,sf,di=b(()=>{"use strict";F();Wr=["package-lock.json","pnpm-lock.yaml","yarn.lock"];sf=1e4});import{createHash as $$}from"node:crypto";function x$(t,e,r,n){for(let o=0;;o++){let s=`e_${$$("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(s))return s}}function lf(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($=>$.entityId)),d=new Set,f=[],m=new Map,g=($,_)=>{d.add(_),m.set(_,$.entityId),f.push($)},k=[];for(let $ of u)l.has($.currentKey)&&!d.has($.currentKey)?g({...$,status:"active",lastSeen:r},$.currentKey):k.push($);let w=[],h=[];for(let $ of k){let _=te($.currentKey),U=_?i.get(_.path):void 0;if(_&&U){let G=le(_.level,e,U.finalPath);if(l.has(G)&&!d.has(G)){w.push({entity:$,newKey:G,untilCommit:U.commit}),d.add(G);continue}}h.push($)}let v=[];if(s){let $=new Map;for(let U of c){if(d.has(U))continue;let G=te(U);if(G?.level!=="code")continue;let P=a.get(G.path);P&&$.set(P,$.has(P)?null:U)}let _=new Map;for(let U of h){let G=te(U.currentKey);if(G?.level!=="code")continue;let P=s.get(G.path);P&&_.set(P,_.has(P)?null:U)}for(let U of h){let G=te(U.currentKey),P=G?.level==="code"?s.get(G.path):void 0,y=P?$.get(P):void 0;P&&y&&_.get(P)===U&&!d.has(y)?(w.push({entity:U,newKey:y,untilCommit:r}),d.add(y)):v.push(U)}}else v.push(...h);let T=new Map;for(let $ of w){let _=te($.entity.currentKey),U=te($.newKey);if(_?.level!=="code"||!U)continue;let G=_.path,P=U.path;for(let y=G.lastIndexOf("/");y>0;y=G.lastIndexOf("/",y-1)){let I=G.slice(0,y),E=G.slice(y+1);if(!P.endsWith(`/${E}`))continue;let C=P.slice(0,P.length-E.length-1);if(C===I)continue;let O=`${I}\0${C}`,j=T.get(O);T.set(O,{count:(j?.count??0)+1,commit:j&&j.commit>$.untilCommit?j.commit:$.untilCommit})}}let R=[...T.entries()].filter(([,$])=>$.count>=v$).map(([$,_])=>{let[U,G]=$.split("\0");return{from:U,to:G,commit:_.commit}}).sort(($,_)=>_.from.length-$.from.length||($.from<_.from?-1:1)),x=[];for(let $ of v){let _=te($.currentKey),U=!1;if(_?.level==="component")for(let G of R){let P=null;if(_.path===G.from?P=G.to:_.path.startsWith(`${G.from}/`)&&(P=G.to+_.path.slice(G.from.length)),P===null)continue;let y=le("component",e,P);l.has(y)&&!d.has(y)&&(w.push({entity:$,newKey:y,untilCommit:G.commit}),d.add(y),U=!0);break}U||x.push($)}for(let $ of w.sort((_,U)=>_.newKey<U.newKey?-1:1))g({...$.entity,currentKey:$.newKey,aliases:[...$.entity.aliases??[],{key:$.entity.currentKey,until:$.untilCommit}],status:"active",lastSeen:r},$.newKey);for(let $ of x)f.push({...$,status:"orphaned"});for(let $ of c){if(d.has($))continue;let _=x$(e,$,r,p);p.add(_),g({entityId:_,currentKey:$,firstSeen:n,lastSeen:r,status:"active"},$)}return{table:{modelFormatVersion:2,repo:e,builtFromCommit:r,entities:f},byKey:m}}var v$,uf=b(()=>{"use strict";F();v$=5});import{simpleGit as S$}from"simple-git";async function df(t,e,r){let n=S$(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
625
+ `))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 ui(t){let e=new Map;for(let r of t.entities){if(r.status!=="active"||!r.aliases)continue;let n=ee(r.currentKey);if(n?.level==="code")for(let o of r.aliases){let i=ee(o.key);i?.level==="code"&&e.set(i.path,n.path)}}return e}function cf(t){let{repo:e,headTimeSec:r,filesets:n,pathToCurrent:o,currentPaths:i,ignored:s,settings:a}=t,c=a.halfLifeDays*86400,l=new Map,u=new Map,p=new Map;for(let w of n){let h=new Set;for(let x of w.files){let $=o.get(x)??x;!i.has($)||s($)||h.add($)}if(h.size<2||h.size>a.commitFileCap)continue;let v=Math.max(0,r-w.timeSec),T=Math.pow(.5,v/c),R=[...h].sort();for(let x of R)l.set(x,(l.get(x)??0)+T);for(let x=0;x<R.length;x++)for(let $=x+1;$<R.length;$++){let _=`${R[x]}\0${R[$]}`;u.set(_,(u.get(_)??0)+T),p.set(_,(p.get(_)??0)+1)}}let d=[],f=a.jaccardMinPct/100;for(let[w,h]of u){if((p.get(w)??0)<a.supportMin)continue;let[v,T]=w.split("\0"),R=(l.get(v)??0)+(l.get(T)??0)-h,x=R>0?h/R:0;x<f||d.push({a:v,b:T,weight:Math.round(x*sf)/sf})}let m=new Map;for(let w of d)for(let h of[w.a,w.b])m.has(h)||m.set(h,[]),m.get(h).push(w);let g=new Map;for(let[,w]of m)w.sort((h,v)=>v.weight-h.weight||(h.a<v.a?-1:h.a>v.a?1:h.b<v.b?-1:1)).slice(0,a.topK).forEach(h=>g.set(h,(g.get(h)??0)+1));return[...g.entries()].filter(([,w])=>w===2).map(([w])=>w).map(w=>({kind:"correlates",from:le("code",e,w.a),to:le("code",e,w.b),weight:w.weight})).sort((w,h)=>w.from<h.from?-1:w.from>h.from?1:w.to<h.to?-1:1)}var Wr,sf,di=b(()=>{"use strict";F();Wr=["package-lock.json","pnpm-lock.yaml","yarn.lock"];sf=1e4});import{createHash as $$}from"node:crypto";function x$(t,e,r,n){for(let o=0;;o++){let s=`e_${$$("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(s))return s}}function lf(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($=>$.entityId)),d=new Set,f=[],m=new Map,g=($,_)=>{d.add(_),m.set(_,$.entityId),f.push($)},k=[];for(let $ of u)l.has($.currentKey)&&!d.has($.currentKey)?g({...$,status:"active",lastSeen:r},$.currentKey):k.push($);let w=[],h=[];for(let $ of k){let _=ee($.currentKey),U=_?i.get(_.path):void 0;if(_&&U){let G=le(_.level,e,U.finalPath);if(l.has(G)&&!d.has(G)){w.push({entity:$,newKey:G,untilCommit:U.commit}),d.add(G);continue}}h.push($)}let v=[];if(s){let $=new Map;for(let U of c){if(d.has(U))continue;let G=ee(U);if(G?.level!=="code")continue;let P=a.get(G.path);P&&$.set(P,$.has(P)?null:U)}let _=new Map;for(let U of h){let G=ee(U.currentKey);if(G?.level!=="code")continue;let P=s.get(G.path);P&&_.set(P,_.has(P)?null:U)}for(let U of h){let G=ee(U.currentKey),P=G?.level==="code"?s.get(G.path):void 0,y=P?$.get(P):void 0;P&&y&&_.get(P)===U&&!d.has(y)?(w.push({entity:U,newKey:y,untilCommit:r}),d.add(y)):v.push(U)}}else v.push(...h);let T=new Map;for(let $ of w){let _=ee($.entity.currentKey),U=ee($.newKey);if(_?.level!=="code"||!U)continue;let G=_.path,P=U.path;for(let y=G.lastIndexOf("/");y>0;y=G.lastIndexOf("/",y-1)){let I=G.slice(0,y),E=G.slice(y+1);if(!P.endsWith(`/${E}`))continue;let C=P.slice(0,P.length-E.length-1);if(C===I)continue;let O=`${I}\0${C}`,j=T.get(O);T.set(O,{count:(j?.count??0)+1,commit:j&&j.commit>$.untilCommit?j.commit:$.untilCommit})}}let R=[...T.entries()].filter(([,$])=>$.count>=v$).map(([$,_])=>{let[U,G]=$.split("\0");return{from:U,to:G,commit:_.commit}}).sort(($,_)=>_.from.length-$.from.length||($.from<_.from?-1:1)),x=[];for(let $ of v){let _=ee($.currentKey),U=!1;if(_?.level==="component")for(let G of R){let P=null;if(_.path===G.from?P=G.to:_.path.startsWith(`${G.from}/`)&&(P=G.to+_.path.slice(G.from.length)),P===null)continue;let y=le("component",e,P);l.has(y)&&!d.has(y)&&(w.push({entity:$,newKey:y,untilCommit:G.commit}),d.add(y),U=!0);break}U||x.push($)}for(let $ of w.sort((_,U)=>_.newKey<U.newKey?-1:1))g({...$.entity,currentKey:$.newKey,aliases:[...$.entity.aliases??[],{key:$.entity.currentKey,until:$.untilCommit}],status:"active",lastSeen:r},$.newKey);for(let $ of x)f.push({...$,status:"orphaned"});for(let $ of c){if(d.has($))continue;let _=x$(e,$,r,p);p.add(_),g({entityId:_,currentKey:$,firstSeen:n,lastSeen:r,status:"active"},$)}return{table:{modelFormatVersion:2,repo:e,builtFromCommit:r,entities:f},byKey:m}}var v$,uf=b(()=>{"use strict";F();v$=5});import{simpleGit as S$}from"simple-git";async function df(t,e,r){let n=S$(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
626
626
  `).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 pf(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 ff=b(()=>{"use strict"});function pi(t){return le("container",t,T$)}function mf(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function gf(t,e,r,n){let o=[],i=u=>{let p=le("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:mf(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,R$)}},s=(u,p)=>{let d=le("component",t,u),f=n.get(d);return{key:d,level:"component",label:mf(u),...f?{entityId:f}:{},...p?{aggregate:!0}:{}}},a=(u,p,d)=>{let f=r.filesByDir.get(d)??[],m=r.childDirs.get(d)??[],g=[p,...f.map(i)],k=[...f.map(w=>({kind:"contains",from:p.key,to:le("code",t,w.path)})),...m.map(w=>({kind:"contains",from:p.key,to:le("component",t,w)}))];c(u,g,k)},c=(u,p,d)=>{let f={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},m=$o(f);if(!m.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${m.errors.join("; ")}`);o.push({path:Vc(t,u),content:rl(f)})},l={key:pi(t),level:"container",label:t,...n.get(pi(t))?{entityId:n.get(pi(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 hf(t,e){let r=[pi(t)];for(let n of e.components)r.push(le("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(le("code",t,o.path));return r.sort()}var T$,R$,yf=b(()=>{"use strict";F();T$=".";R$=12});import{simpleGit as wf}from"simple-git";function fr(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 $f(t,e="HEAD"){let r=wf(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 ba(t,n)}}async function ba(t,e){let n=await wf(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 kf(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function vf(t,e){let r=[...t].sort((m,g)=>m.path<g.path?-1:m.path>g.path?1:0),n=new Map,o=new Map;for(let m of r){let g=kf(m.path);n.has(g)||n.set(g,[]),n.get(g).push(m);let k=g;for(;k!=="";){let w=kf(k);o.has(w)||o.set(w,new Set),o.get(w).add(k),k=w}}let i=m=>[...o.get(m)??[]].sort(),s=Math.max(e,1)-1,a=new Set,c=new Set,l=[""];for(;l.length>0;){let m=l.shift(),g=(n.get(m)??[]).length+i(m).length;if(g<=s)s-=g,c.add(m),l.push(...i(m));else{if(m==="")return{components:[],collapsed:new Set,filesByDir:new Map,childDirs:new Map,counts:{component:0,code:0}};a.add(m)}}let u=[],p=new Map,d=new Map,f=0;for(let m of[...c].sort()){let g=n.get(m)??[];p.set(m,g),d.set(m,i(m)),f+=g.length,m!==""&&u.push(m)}for(let m of a)u.push(m);return u.sort(),{components:u,collapsed:a,filesByDir:p,childDirs:d,counts:{component:u.length,code:f}}}var bf,fi=b(()=>{"use strict";bf=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as xf,readFileSync as Sf}from"node:fs";import{join as Tf}from"node:path";import{simpleGit as C$}from"simple-git";import{parse as Rf}from"yaml";function Wn(t){let e={ignore:bf,containerNodeCap:E$,cochange:{...We},issueKeyPattern:null},r=Tf(t,"regimen.yaml");if(!xf(r))return e;let n;try{n=Rf(Sf(r,"utf-8"))}catch{return e}let o=n?.context,i=o&&typeof o=="object"?o.model:void 0;if(!i||typeof i!="object")return e;let s=i,a=Array.isArray(s.ignore)?s.ignore.filter(f=>typeof f=="string"&&f.trim().length>0):e.ignore,c=(f,m)=>typeof f=="number"&&Number.isInteger(f)&&f>0?f:m,l=c(s.container_node_cap,e.containerNodeCap),u=s.cochange&&typeof s.cochange=="object"?s.cochange:{},p={windowCommits:c(u.window_commits,e.cochange.windowCommits),commitFileCap:c(u.commit_file_cap,e.cochange.commitFileCap),supportMin:c(u.support_min,e.cochange.supportMin),jaccardMinPct:typeof u.jaccard_min_pct=="number"&&Number.isInteger(u.jaccard_min_pct)&&u.jaccard_min_pct>=0&&u.jaccard_min_pct<=100?u.jaccard_min_pct:e.cochange.jaccardMinPct,halfLifeDays:c(u.half_life_days,e.cochange.halfLifeDays),topK:c(u.top_k,e.cochange.topK)},d=typeof s.issue_key_pattern=="string"&&s.issue_key_pattern.trim().length>0?s.issue_key_pattern.trim():null;return{ignore:a,containerNodeCap:l,cochange:p,issueKeyPattern:d}}function $a(t,e){let r=Tf(t,yo(e));if(!xf(r))return null;let n=Rf(Sf(r,"utf-8")),o=vo(n);if(!o.ok)throw new Error(`model: ${yo(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function Cf(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await $f(r),s=fr(o.ignore),a=i.files.filter(h=>!s(h.path)),c=vf(a,o.containerNodeCap),l=$a(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await C$(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=pf(await df(r,l.builtFromCommit,i.commit)),p=new Map((await ba(r,l.builtFromCommit)).map(T=>[T.path,T.blobHash]))):l?.builtFromCommit===i.commit&&(p=new Map(a.map(h=>[h.path,h.blobHash])));let d=new Map(a.map(h=>[h.path,h.blobHash])),f=lf({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:hf(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),m=gf(e,i.commit,c,f.byKey),g=fr([...o.ignore,...Wr]),k=cf({repo:e,headTimeSec:i.commitTimeSec,filesets:await af(r,i.commit,o.cochange.windowCommits),pathToCurrent:ui(f.table),currentPaths:new Set(a.map(h=>h.path)),ignored:g,settings:o.cochange}),w=[{path:yo(e),content:nl(f.table)},...m.files.map(h=>({path:h.path,content:h.content})),{path:qc(e),content:wo({modelFormatVersion:2,repo:e,builtFromCommit:i.commit,edges:k})}];return{repo:e,headCommit:i.commit,files:w,emittedShardPaths:new Set(m.files.map(h=>h.path)),counts:{...m.counts,correlates:k.length},identityTable:f.table,entityByKey:f.byKey}}var E$,va=b(()=>{"use strict";F();di();uf();ff();yf();fi();E$=1500});import{existsSync as If,readFileSync as Af,readdirSync as I$}from"node:fs";import{join as xa}from"node:path";import{parse as Pf}from"yaml";function A$(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 _f(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<Jc)return null;let s=i/Math.min(n.size,o.size),a=A$(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(s*c*Ef)/Ef;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[ke(t.taskKey),ke(e.taskKey)]:[ke(e.taskKey),ke(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function jf(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=_f(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 Nf(t,e,r,n){let o=ke(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=_f(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 mi(t){let e=xa(t,"model/facts/events");if(!If(e))return[];let r=[];for(let n of I$(e).sort())if(n.endsWith(".yaml"))try{let o=Rr(Pf(Af(xa(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function Of(t){let e=xa(t,xr);if(!If(e))return[];try{let r=ko(Pf(Af(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function gi(t){return wo({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var Ef,Sa=b(()=>{"use strict";F();Ef=1e4});var Lf={};mo(Lf,{attachPrToBranchTasks:()=>Ca,attachPrToEvent:()=>Df,recordPipelineEvent:()=>Ra});import{existsSync as P$,readFileSync as _$}from"node:fs";import{join as j$}from"node:path";import{simpleGit as Ta}from"simple-git";async function N$(t,e){let n=await Ta(t).raw(["diff","--numstat",`${e}^`,e]).catch(()=>""),o=[];for(let i of n.split(`
627
- `)){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 O$(t,e){let r=`tasks/${e}/SOLUTION.md`,n=j$(t,r);if(!P$(n))return{};try{let o=_$(n,"utf-8"),i=[...new Set(o.match(/\bADR-\d{3,4}\b/g)??[])].sort();return{solution:r,...i.length>0?{adr:i}:{}}}catch{return{solution:r}}}async function Ra(t){let{contextDir:e,repoDir:r,repoName:n,taskKey:o,commitSha:i}=t,s=Wn(e),a=fr([...s.ignore,...Wr]),c=await N$(r,i),l=(await Ta(r).raw(["show","-s","--format=%cs",i])).trim(),u=null,p=new Map;try{u=$a(e,n),u&&(p=new Map(u.entities.filter(R=>R.status==="active").map(R=>[R.currentKey,R.entityId])))}catch{}let d=[];for(let R of c){if(a(R.path))continue;let x=le("code",n,R.path),$=p.get(x);d.push({key:x,...$?{entityId:$}:{},churn:R.churn})}if(d.length===0)return{recorded:!1};let f=O$(e,o),m=li(e,o),g=m?.origin==="pipeline"?m.files.filter(R=>te(R.key)?.repo!==n):[],k=m?.origin==="pipeline"?m.commits:[],w={modelFormatVersion:2,taskKey:o,origin:"pipeline",...m?.title?{title:m.title}:{},...l?{date:l}:{},commits:[...new Set([...k,i])],files:[...g,...d],links:{...m?.origin==="pipeline"?m.links:{},...f}};w.links&&Object.keys(w.links).length===0&&delete w.links;let h=[...mi(e).filter(R=>R.taskKey!==o),w],v=Nf(Of(e),h,o,s.cochange.halfLifeDays),T=await zp({contextDir:e,taskKey:o,repoName:n,repoDir:r,commitSha:i,date:l,touchedKeys:new Set(d.map(R=>R.key)),identity:u}).catch(()=>[]);return await be(e,[{path:Sr(o),content:Sn(w)},{path:xr,content:gi(v)},...T],`model: task event ${o}`),{recorded:!0}}async function Ca(t){let e=new Set([t.fallbackTaskKey]);try{let r=Ta(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(`
627
+ `)){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 O$(t,e){let r=`tasks/${e}/SOLUTION.md`,n=j$(t,r);if(!P$(n))return{};try{let o=_$(n,"utf-8"),i=[...new Set(o.match(/\bADR-\d{3,4}\b/g)??[])].sort();return{solution:r,...i.length>0?{adr:i}:{}}}catch{return{solution:r}}}async function Ra(t){let{contextDir:e,repoDir:r,repoName:n,taskKey:o,commitSha:i}=t,s=Wn(e),a=fr([...s.ignore,...Wr]),c=await N$(r,i),l=(await Ta(r).raw(["show","-s","--format=%cs",i])).trim(),u=null,p=new Map;try{u=$a(e,n),u&&(p=new Map(u.entities.filter(R=>R.status==="active").map(R=>[R.currentKey,R.entityId])))}catch{}let d=[];for(let R of c){if(a(R.path))continue;let x=le("code",n,R.path),$=p.get(x);d.push({key:x,...$?{entityId:$}:{},churn:R.churn})}if(d.length===0)return{recorded:!1};let f=O$(e,o),m=li(e,o),g=m?.origin==="pipeline"?m.files.filter(R=>ee(R.key)?.repo!==n):[],k=m?.origin==="pipeline"?m.commits:[],w={modelFormatVersion:2,taskKey:o,origin:"pipeline",...m?.title?{title:m.title}:{},...l?{date:l}:{},commits:[...new Set([...k,i])],files:[...g,...d],links:{...m?.origin==="pipeline"?m.links:{},...f}};w.links&&Object.keys(w.links).length===0&&delete w.links;let h=[...mi(e).filter(R=>R.taskKey!==o),w],v=Nf(Of(e),h,o,s.cochange.halfLifeDays),T=await zp({contextDir:e,taskKey:o,repoName:n,repoDir:r,commitSha:i,date:l,touchedKeys:new Set(d.map(R=>R.key)),identity:u}).catch(()=>[]);return await be(e,[{path:Sr(o),content:Sn(w)},{path:xr,content:gi(v)},...T],`model: task event ${o}`),{recorded:!0}}async function Ca(t){let e=new Set([t.fallbackTaskKey]);try{let r=Ta(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(`
628
628
  `)){let s=i.trim();s&&e.add(s)}}catch{}for(let r of[...e].sort())await Df(t.contextDir,r,t.prUrl)}async function Df(t,e,r){let n=li(t,e);if(!n||n.origin!=="pipeline"||n.links?.pr===r)return;let o={...n,links:{...n.links??{},pr:r}};await be(t,[{path:Sr(e),content:Sn(o)}],`model: pr link for ${e}`)}var Ea=b(()=>{"use strict";F();Xe();Jp();wa();va();di();Sa();fi()});var Yn,Ia=b(()=>{"use strict";pa();rr();Yn=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return zu(this.cfg,e)}getIssue(e,r){return Ju(this.cfg,e,r??ci(this.contextDir))}listComments(e,r){return Xu(this.cfg,e,r)}downloadAttachment(e){return Vu(this.cfg,e)}updateStatus(e,r){return Uu(this.cfg,e,r,ci(this.contextDir))}addComment(e,r,n){return Bu(this.cfg,e,r)}createIssue(e){return Gu(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,ci(this.contextDir))}editIssue(e,r){return Fu(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return Hu(this.cfg,e,r,n)}fetchStateFields(e){return Zu(this.cfg,e)}}});import{existsSync as Mf,readFileSync as D$,readdirSync as L$}from"node:fs";function hi(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=F$(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:M$(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:B$(U$(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 yi(t,e,r){if(r.length===0)return;let n=hi(t,e,r),o=r.map(i=>i.issue.key);await be(t,n,`sync(${o.join(", ")}): task data`)}function M$(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(`
629
629
  `)}function U$(t,e,r){let n=new Map,o=ge(t,`tasks/${e}/comments.jsonl`);if(Mf(o))for(let i of D$(o,"utf-8").split(`
630
630
  `)){let s=i.trim();if(s)try{let a=JSON.parse(s);a&&typeof a.id=="string"&&n.set(a.id,a)}catch{}}for(let i of r){if(n.has(i.id))continue;let s={id:i.id,author:i.author,origin:"youtrack",body:i.body,createdAt:new Date(i.createdAt).toISOString()},a=Er(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function B$(t){return t.map(e=>JSON.stringify(e)).join(`
@@ -730,11 +730,11 @@ ${r?`
730
730
  `)+`
731
731
  `,{mode:384}),og(o,`[credential]
732
732
  helper = store --file=${n}
733
- `+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:o,GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{Rx(r,{recursive:!0,force:!0})}catch{}}}}function za(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(Ex)),t.bitbucket?.apiToken&&(e.push(`https://${Zt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(Ix)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(Ax)),ig(e,r)}function sg(t,e){if(t.contextWrite?.token){let r=Ar(e)??"github.com",n=Ro(r);return ig([`https://${n}:${t.contextWrite.token}@${r}`],[Pi(r)])}return za(t)}var Ex,Ix,Ax,ag=b(()=>{"use strict";F();Ex=Pi("github.com"),Ix=Pi("bitbucket.org"),Ax=Pi("gitlab.com")});import{spawn as lg}from"node:child_process";import{existsSync as _i,mkdirSync as Qn,readFileSync as Px,rmSync as Ja,symlinkSync as _x}from"node:fs";import{homedir as jx}from"node:os";import{dirname as rn,join as Ut}from"node:path";function ug(t){let e=Ut(jx(),".codepipe-sandbox","repos");return t?Ut(e,t):e}function dg(t,e){let n=(tn.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{tn.get(t)===o&&tn.delete(t)},()=>{tn.get(t)===o&&tn.delete(t)});return tn.set(t,o),n}function cg(t){let e=t instanceof Error?t.message:String(t);return/couldn't find remote ref/i.test(e)||/Remote branch .* not found/i.test(e)||/unknown revision/i.test(e)}function Nx(t){let e=t instanceof Error?t.message:String(t);return/invalid index-pack output/i.test(e)||/index-pack failed/i.test(e)||/fetch-pack/i.test(e)||/objects[\/\\]pack/i.test(e)||/(loose object .* is corrupt|corrupt loose object|object file .* is empty)/i.test(e)||/did not send all necessary objects/i.test(e)||/(bad object|bad tree object|unable to read (tree|sha1))/i.test(e)||/not a git repository/i.test(e)||/unable to read .*(pack|object)/i.test(e)}async function pg(t,e,r,n,o){let i=async c=>{await ee(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await ee(t,["reset","--hard",`origin/${c}`],o),await ee(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!cg(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{_i(t)&&Ja(t,{recursive:!0,force:!0}),Qn(rn(t),{recursive:!0});try{return await ee(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!cg(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),_i(t)&&Ja(t,{recursive:!0,force:!0}),Qn(rn(t),{recursive:!0}),await ee(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(_i(Ut(t,".git")))try{return await s()}catch(c){if(!Nx(c))throw c;let l=c instanceof Error?c.message:String(c);console.warn(`[git] cache at ${t} looks corrupt (${l}) \u2014 discarding and re-cloning`)}return a()}async function fg(t){await ee(t.workspacePath,["reset","--hard",t.baseSha]),await ee(t.workspacePath,["clean","-fdx"])}async function mg(t,e){let r=t.workspacePath;await ee(r,["add","-A"]);let n=(await $e(r,["write-tree"])).trim(),o=(await $e(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:nn,GIT_AUTHOR_EMAIL:on,GIT_COMMITTER_NAME:nn,GIT_COMMITTER_EMAIL:on};return(await $e(r,["commit-tree",n,"-m",e],i)).trim()}async function gg(t,e,r,n,o){try{await ee(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw Ar(n)==="github.com"&&/without `?workflow`? scope|workflow.*scope/i.test(s)?new Error("delivery push rejected: the Context-Repo push token needs the `workflow` scope (the delivery includes .github/workflows/*). Set secrets.contextWrite.token to a fine-grained PAT on the Context Repo with Contents: write + Workflows: write (or add `workflow` to the project token).\n"+s):i}}async function hg(t,e){return $e(t.workspacePath,["diff","--binary",t.baseSha,e])}async function yg(t,e,r,n,o){await ee(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await ee(t.workspacePath,["checkout","--force",r])}async function kg(t,e,r,n,o,i){let s=t.workspacePath;await ee(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await $e(s,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=m=>$e(s,["rev-parse","-q","--verify",`${m}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await $e(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ee(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(g=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(g)}`)}),await c(n)||await ee(s,["fetch","origin",n],i).catch(()=>{}),!await c(n)))throw new Error(`moved-base apply: delivery base ${n.slice(0,10)} is unreachable \u2014 cannot re-apply the previous iteration onto the fresh ${t.ref}`);let l={...i??process.env,GIT_AUTHOR_NAME:nn,GIT_AUTHOR_EMAIL:on,GIT_COMMITTER_NAME:nn,GIT_COMMITTER_EMAIL:on},u=(await $e(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),p=(await $e(s,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await ee(s,["cherry-pick","--quit"],l).catch(()=>{});let d=null;try{await ee(s,["cherry-pick","--no-commit",p],l)}catch(m){d=m instanceof Error?m.message:String(m)}let f=(await $e(s,["diff","--name-only","--diff-filter=U"])).split(`
734
- `).map(m=>m.trim()).filter(m=>m.length>0);if(d&&f.length===0)throw await ee(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${d}`);return f}async function Xa(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:nn,GIT_AUTHOR_EMAIL:on,GIT_COMMITTER_NAME:nn,GIT_COMMITTER_EMAIL:on};(await $e(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ee(n,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),await ee(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await ee(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await $e(n,["diff","--name-only","--diff-filter=U"])).split(`
735
- `).map(l=>l.trim()).filter(l=>l.length>0),c=await $e(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}function ee(t,e,r){return new Promise((n,o)=>{let i=lg("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[];i.stderr.setEncoding("utf-8"),i.stderr.on("data",a=>s.push(a)),i.on("error",o),i.on("close",a=>{if(a===0)return n();o(new Error(`git ${e[0]} failed (exit ${a}):
733
+ `+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:o,GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{Rx(r,{recursive:!0,force:!0})}catch{}}}}function za(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(Ex)),t.bitbucket?.apiToken&&(e.push(`https://${Zt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(Ix)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(Ax)),ig(e,r)}function sg(t,e){if(t.contextWrite?.token){let r=Ar(e)??"github.com",n=Ro(r);return ig([`https://${n}:${t.contextWrite.token}@${r}`],[Pi(r)])}return za(t)}var Ex,Ix,Ax,ag=b(()=>{"use strict";F();Ex=Pi("github.com"),Ix=Pi("bitbucket.org"),Ax=Pi("gitlab.com")});import{spawn as lg}from"node:child_process";import{existsSync as _i,mkdirSync as Qn,readFileSync as Px,rmSync as Ja,symlinkSync as _x}from"node:fs";import{homedir as jx}from"node:os";import{dirname as rn,join as Ut}from"node:path";function ug(t){let e=Ut(jx(),".codepipe-sandbox","repos");return t?Ut(e,t):e}function dg(t,e){let n=(tn.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{tn.get(t)===o&&tn.delete(t)},()=>{tn.get(t)===o&&tn.delete(t)});return tn.set(t,o),n}function cg(t){let e=t instanceof Error?t.message:String(t);return/couldn't find remote ref/i.test(e)||/Remote branch .* not found/i.test(e)||/unknown revision/i.test(e)}function Nx(t){let e=t instanceof Error?t.message:String(t);return/invalid index-pack output/i.test(e)||/index-pack failed/i.test(e)||/fetch-pack/i.test(e)||/objects[\/\\]pack/i.test(e)||/(loose object .* is corrupt|corrupt loose object|object file .* is empty)/i.test(e)||/did not send all necessary objects/i.test(e)||/(bad object|bad tree object|unable to read (tree|sha1))/i.test(e)||/not a git repository/i.test(e)||/unable to read .*(pack|object)/i.test(e)}async function pg(t,e,r,n,o){let i=async c=>{await te(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await te(t,["reset","--hard",`origin/${c}`],o),await te(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!cg(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{_i(t)&&Ja(t,{recursive:!0,force:!0}),Qn(rn(t),{recursive:!0});try{return await te(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!cg(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),_i(t)&&Ja(t,{recursive:!0,force:!0}),Qn(rn(t),{recursive:!0}),await te(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(_i(Ut(t,".git")))try{return await s()}catch(c){if(!Nx(c))throw c;let l=c instanceof Error?c.message:String(c);console.warn(`[git] cache at ${t} looks corrupt (${l}) \u2014 discarding and re-cloning`)}return a()}async function fg(t){await te(t.workspacePath,["reset","--hard",t.baseSha]),await te(t.workspacePath,["clean","-fdx"])}async function mg(t,e){let r=t.workspacePath;await te(r,["add","-A"]);let n=(await $e(r,["write-tree"])).trim(),o=(await $e(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:nn,GIT_AUTHOR_EMAIL:on,GIT_COMMITTER_NAME:nn,GIT_COMMITTER_EMAIL:on};return(await $e(r,["commit-tree",n,"-m",e],i)).trim()}async function gg(t,e,r,n,o){try{await te(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw Ar(n)==="github.com"&&/without `?workflow`? scope|workflow.*scope/i.test(s)?new Error("delivery push rejected: the Context-Repo push token needs the `workflow` scope (the delivery includes .github/workflows/*). Set secrets.contextWrite.token to a fine-grained PAT on the Context Repo with Contents: write + Workflows: write (or add `workflow` to the project token).\n"+s):i}}async function hg(t,e){return $e(t.workspacePath,["diff","--binary",t.baseSha,e])}async function yg(t,e,r,n,o){await te(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await te(t.workspacePath,["checkout","--force",r])}async function kg(t,e,r,n,o,i){let s=t.workspacePath;await te(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await $e(s,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=m=>$e(s,["rev-parse","-q","--verify",`${m}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await $e(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await te(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(g=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(g)}`)}),await c(n)||await te(s,["fetch","origin",n],i).catch(()=>{}),!await c(n)))throw new Error(`moved-base apply: delivery base ${n.slice(0,10)} is unreachable \u2014 cannot re-apply the previous iteration onto the fresh ${t.ref}`);let l={...i??process.env,GIT_AUTHOR_NAME:nn,GIT_AUTHOR_EMAIL:on,GIT_COMMITTER_NAME:nn,GIT_COMMITTER_EMAIL:on},u=(await $e(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),p=(await $e(s,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await te(s,["cherry-pick","--quit"],l).catch(()=>{});let d=null;try{await te(s,["cherry-pick","--no-commit",p],l)}catch(m){d=m instanceof Error?m.message:String(m)}let f=(await $e(s,["diff","--name-only","--diff-filter=U"])).split(`
734
+ `).map(m=>m.trim()).filter(m=>m.length>0);if(d&&f.length===0)throw await te(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${d}`);return f}async function Xa(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:nn,GIT_AUTHOR_EMAIL:on,GIT_COMMITTER_NAME:nn,GIT_COMMITTER_EMAIL:on};(await $e(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await te(n,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),await te(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await te(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await $e(n,["diff","--name-only","--diff-filter=U"])).split(`
735
+ `).map(l=>l.trim()).filter(l=>l.length>0),c=await $e(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}function te(t,e,r){return new Promise((n,o)=>{let i=lg("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[];i.stderr.setEncoding("utf-8"),i.stderr.on("data",a=>s.push(a)),i.on("error",o),i.on("close",a=>{if(a===0)return n();o(new Error(`git ${e[0]} failed (exit ${a}):
736
736
  ${s.join("").trim()||"(no stderr)"}`))})})}function $e(t,e,r){return new Promise((n,o)=>{let i=lg("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[],a=[];i.stdout.setEncoding("utf-8"),i.stderr.setEncoding("utf-8"),i.stdout.on("data",c=>s.push(c)),i.stderr.on("data",c=>a.push(c)),i.on("error",o),i.on("close",c=>{if(c===0)return n(s.join(""));o(new Error(`git ${e[0]} failed (exit ${c}):
737
- ${a.join("").trim()||"(no stderr)"}`))})})}function wg(t,e){_i(t)&&Ja(t,{recursive:!0,force:!0}),Qn(rn(t),{recursive:!0}),_x(e,t,"dir")}async function bg(t,e,r){await ee(t,["worktree","prune"]).catch(()=>{}),Qn(rn(r),{recursive:!0}),await ee(t,["worktree","add","--detach",r,`origin/${e}`])}async function Ox(t,e,r){Qn(rn(r),{recursive:!0}),await ee(rn(r),["clone","--quiet","--no-checkout",t,r]),await ee(r,["checkout","--force","--detach",e])}async function $g(t,e,r,n="worktree",o,i){return r.length===0?[]:dg(e,async()=>{let s=[];for(let a of r){let c=Ut(ug(i),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await pg(c,a.cloneUrl,a.ref,a.defaultBranch,o)}catch(d){throw new Error(`failed to materialize project repo "${a.name}" (${a.cloneUrl}): `+(d instanceof Error?d.message:String(d)))}let u=(await $e(c,["rev-parse","HEAD"])).trim(),p=Ut(t,"code",a.name);n==="direct"?(wg(p,c),console.log(`[git] code: linked ${p} \u2192 ${c} @ ${u.slice(0,10)}`)):n==="clone"?(await Ox(c,u,p),console.log(`[git] code: clone ${p} \u2190 ${c} @ ${u.slice(0,10)}`)):(await bg(c,l,p),console.log(`[git] code: worktree ${p} \u2190 ${c} @ ${u.slice(0,10)}`)),s.push({name:a.name,workspacePath:p,cachePath:c,ref:l,baseSha:u})}return s})}async function vg(t,e,r,n="worktree",o,i){if(!r||!r.cloneUrl)return null;let s=r;return dg(e,async()=>{let a=Ut(ug(i),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);try{await pg(a,s.cloneUrl,s.ref,void 0,o)}catch(u){throw new Error(`failed to materialize context repo (${s.cloneUrl}): `+(u instanceof Error?u.message:String(u)))}let c=Ut(t,"context");n==="direct"?(wg(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await bg(a,s.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await $e(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function xg(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await ee(r,["add","-A",...n]).catch(()=>{});let o;try{o=await $e(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
737
+ ${a.join("").trim()||"(no stderr)"}`))})})}function wg(t,e){_i(t)&&Ja(t,{recursive:!0,force:!0}),Qn(rn(t),{recursive:!0}),_x(e,t,"dir")}async function bg(t,e,r){await te(t,["worktree","prune"]).catch(()=>{}),Qn(rn(r),{recursive:!0}),await te(t,["worktree","add","--detach",r,`origin/${e}`])}async function Ox(t,e,r){Qn(rn(r),{recursive:!0}),await te(rn(r),["clone","--quiet","--no-checkout",t,r]),await te(r,["checkout","--force","--detach",e])}async function $g(t,e,r,n="worktree",o,i){return r.length===0?[]:dg(e,async()=>{let s=[];for(let a of r){let c=Ut(ug(i),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await pg(c,a.cloneUrl,a.ref,a.defaultBranch,o)}catch(d){throw new Error(`failed to materialize project repo "${a.name}" (${a.cloneUrl}): `+(d instanceof Error?d.message:String(d)))}let u=(await $e(c,["rev-parse","HEAD"])).trim(),p=Ut(t,"code",a.name);n==="direct"?(wg(p,c),console.log(`[git] code: linked ${p} \u2192 ${c} @ ${u.slice(0,10)}`)):n==="clone"?(await Ox(c,u,p),console.log(`[git] code: clone ${p} \u2190 ${c} @ ${u.slice(0,10)}`)):(await bg(c,l,p),console.log(`[git] code: worktree ${p} \u2190 ${c} @ ${u.slice(0,10)}`)),s.push({name:a.name,workspacePath:p,cachePath:c,ref:l,baseSha:u})}return s})}async function vg(t,e,r,n="worktree",o,i){if(!r||!r.cloneUrl)return null;let s=r;return dg(e,async()=>{let a=Ut(ug(i),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);try{await pg(a,s.cloneUrl,s.ref,void 0,o)}catch(u){throw new Error(`failed to materialize context repo (${s.cloneUrl}): `+(u instanceof Error?u.message:String(u)))}let c=Ut(t,"context");n==="direct"?(wg(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await bg(a,s.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await $e(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function xg(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await te(r,["add","-A",...n]).catch(()=>{});let o;try{o=await $e(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
738
738
  `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=Px(Ut(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var tn,nn,on,Sg=b(()=>{"use strict";F();tn=new Map;nn="CodePipe Agent",on="codepipe@codepartner.ee"});import{readFileSync as Dx}from"node:fs";import{join as Lx}from"node:path";function Tg(t){let e=Lx(t,Zn),r;try{r=Dx(e,"utf-8")}catch{throw new Bt(`BUILD produced no ${Zn} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new Bt(`${Zn} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new Bt(`${Zn} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new Bt(`${Zn}: "ok" must be a boolean`);let i=o.ok,a=(Array.isArray(o.steps)?o.steps:[]).flatMap(u=>{if(!u||typeof u!="object")return[];let p=u,d=typeof p.name=="string"?p.name:null,f=typeof p.exitCode=="number"?p.exitCode:null;if(d===null||f===null)return[];let m={name:d,exitCode:f};return typeof p.durationMs=="number"&&(m.durationMs=p.durationMs),[m]}),c=typeof o.logTail=="string"?Mx(o.logTail):"",l={ok:i,steps:a,logTail:c};if(typeof o.failedStep=="string"&&o.failedStep)l.failedStep=o.failedStep;else if(!i){let u=a.find(p=>p.exitCode!==0);u&&(l.failedStep=u.name)}return l}function Mx(t){let e=Buffer.from(t,"utf-8");return e.length<=Qa?t:`\u2026 [${e.length-Qa} bytes elided] \u2026
739
739
  `+e.subarray(e.length-Qa).toString("utf-8")}var Qa,Bt,Zn,Rg=b(()=>{"use strict";Qa=8*1024,Bt=class extends Error{},Zn="meta/build-result.json"});import{readFileSync as Ux}from"node:fs";import{join as Bx}from"node:path";function Eg(t){let e=Bx(t,sn),r;try{r=Ux(e,"utf-8")}catch{throw new $t(`code review produced no ${sn} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(c){throw new $t(`${sn} is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(!n||typeof n!="object")throw new $t(`${sn} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new $t(`${sn}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?Cg(o.remarks,Fx):"";if(!i&&s.trim().length===0)throw new $t(`${sn}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?Cg(o.summary,Kx):"";return{approved:i,remarks:s,summary:a}}function Cg(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
740
740
  \u2026 [${r.length-e} bytes elided]`}var Fx,Kx,$t,sn,Ig=b(()=>{"use strict";Fx=16*1024,Kx=4*1024,$t=class extends Error{},sn="meta/review-result.json"});import{readFileSync as Gx,statSync as Hx}from"node:fs";import{join as Ag}from"node:path";function Xx(t){return t.startsWith("meta/")||Jx.has(t)}function Qx(t,e,r,n){return`[codepipe] artifact omitted from upload: ${t} was ${e} bytes, exceeds the SANDBOX upload budget (per-artifact ${r} / total ${n}). The delivered code (git) and the build/review verdict are unaffected \u2014 only this display/durability copy was dropped.`}function Zx(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function Pg(t,e,r){let n=r?.maxBytes??Wx,o=r?.totalBytes??Yx,i=r?.maxCount??qx,s=e.map((m,g)=>{let k=null;try{k=Hx(Ag(t,m)).size}catch{}return{path:m,index:g,size:k}}),a=[...s].sort((m,g)=>{let k=w=>Xx(w.path)?0:1;return k(m)!==k(g)?k(m)-k(g):(m.size??0)-(g.size??0)}),c=a.slice(0,i),l=a.slice(i).sort((m,g)=>m.index-g.index).map(m=>m.path),u=new Array(s.length),p=[],d=0;for(let m of c){let g=null;if(m.size!==null&&m.size<=n&&d+m.size<=o)try{g=Gx(Ag(t,m.path))}catch{}if(g!==null){d+=g.length,u[m.index]={path:m.path,contentBase64:g.toString("base64")};continue}let k=m.size===null?Zx(m.path):Qx(m.path,m.size,n,o),w=Buffer.from(k,"utf-8");d+=w.length,u[m.index]={path:m.path,contentBase64:w.toString("base64")},p.push({path:m.path,bytes:m.size??0})}let f=u.filter(m=>m!==void 0);if(l.length>0){let m=l.slice(0,zx),g=`# Artifacts omitted from upload
@@ -744,11 +744,12 @@ ${l.length} file(s) exceeded the SANDBOX artifact count budget (${i}) and were d
744
744
  `+m.map(k=>`- ${k}
745
745
  `).join("")+(l.length>m.length?`
746
746
  \u2026and ${l.length-m.length} more.
747
- `:"");f.push({path:Vx,contentBase64:Buffer.from(g,"utf-8").toString("base64")})}return{artifacts:f,omitted:p,dropped:l}}var Wx,Yx,qx,Vx,zx,Jx,_g=b(()=>{"use strict";Wx=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),Yx=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),qx=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),Vx="artifacts-omitted.md",zx=500,Jx=new Set(["QUESTIONS.md","SOLUTION.md","DRAFT.md","ESTIMATE.md","diff-summary.md","review-result.md","commit-message.txt","pr-description.md"])});import{lstatSync as eS,mkdtempSync as tS,readFileSync as rS,readdirSync as Ng,rmSync as jg}from"node:fs";import{tmpdir as nS}from"node:os";import{join as ji,relative as oS}from"node:path";function Og(t){let e=tS(ji(nS(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>jg(e,{recursive:!0,force:!0}),listFiles:()=>Dg(e,e),readFile:r=>rS(ji(e,r),"utf-8"),clean:()=>{for(let r of Ng(e))sS.has(r)||jg(ji(e,r),{recursive:!0,force:!0})}}}function Dg(t,e){let r=[];for(let n of Ng(e)){let o=ji(e,n),i=eS(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&iS.has(n))continue;r.push(...Dg(t,o))}else r.push(oS(t,o))}return r}var iS,sS,Lg=b(()=>{"use strict";iS=new Set(["code","context","scratch"]),sS=new Set(["code","context"])});import{existsSync as Oi,readFileSync as Mg,readdirSync as Za}from"node:fs";import{join as vt}from"node:path";import{parse as aS}from"yaml";function Di(t){if(!Oi(t))return[];let e=[];for(let r of Za(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=vt(t,r.name);r.isDirectory()?e.push(...Di(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function Ni(t){try{return aS(Mg(t,"utf-8"))}catch{return null}}function Ug(t){let e={nodes:new Map,adjacency:new Map,events:new Map,annotations:new Map,keyByEntity:new Map,orphanedEntities:new Set,empty:!0},r=(i,s,a,c)=>{e.adjacency.has(i)||e.adjacency.set(i,[]),e.adjacency.has(s)||e.adjacency.set(s,[]),e.adjacency.get(i).push({to:s,kind:a,weight:c}),e.adjacency.get(s).push({to:i,kind:a,weight:c})};for(let i of Di(vt(t,"model/derived/structure"))){let s=$o(Ni(i));if(s.ok){for(let a of s.value.nodes)e.nodes.set(a.key,a);for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}}for(let i of[...Di(vt(t,"model/derived/correlates")),vt(t,"model/derived/relates.yaml")]){if(!Oi(i))continue;let s=ko(Ni(i));if(s.ok)for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}let n=vt(t,"model/facts/events");if(Oi(n))for(let i of Za(n).sort()){if(!i.endsWith(".yaml"))continue;let s=Rr(Ni(vt(n,i)));if(!s.ok)continue;let a=s.value;e.events.set(a.taskKey,a);let c=ke(a.taskKey);for(let l of a.files)r(c,l.key,"touched_by",1);for(let l of a.links?.adr??[])r(c,`adr::${l}`,"references",1);for(let l of a.links?.tasks??[])r(c,ke(l),"references",1)}for(let i of Di(vt(t,"model/facts/identity"))){let s=vo(Ni(i));if(s.ok)for(let a of s.value.entities)a.status==="orphaned"?e.orphanedEntities.add(a.entityId):e.keyByEntity.set(a.entityId,a.currentKey)}let o=vt(t,"model/facts/annotations");if(Oi(o)){for(let i of Za(o).sort())if(i.endsWith(".md"))try{let s=Mg(vt(o,i),"utf-8"),a=/^---\n[\s\S]*?entityId:\s*(e_[0-9a-f]{8})[\s\S]*?\n---\n?([\s\S]*)$/.exec(s);a&&e.annotations.set(a[1],a[2].trim())}catch{}}return e.empty=e.nodes.size===0&&e.events.size===0,e}var Bg=b(()=>{"use strict";F()});function Kg(t){return new Set((t.toLowerCase().match(/[a-zа-я0-9_]{4,}/g)??[]).filter(e=>!/^\d+$/.test(e)))}function fS(t,e){if(t.size===0||e.size===0)return 0;let r=0;for(let n of t)e.has(n)&&r++;return r/(t.size+e.size-r)}function Gg(t){let{taskKey:e,title:r,text:n,model:o}=t,i=new Map,s=(p,d)=>{(i.get(p)??0)<d&&i.set(p,d)};(o.events.has(e)||o.adjacency.has(ke(e)))&&s(ke(e),Fg);for(let p of`${r}
748
- ${n}`.match(pS)??[]){if(p===e)continue;let d=ke(p);(o.events.has(p)||o.adjacency.has(d))&&s(d,Fg)}let a=new Map;for(let p of o.nodes.keys()){let d=te(p);if(d?.level!=="code")continue;let f=d.path.slice(d.path.lastIndexOf("/")+1);for(let m of[d.path,f])a.has(m)||a.set(m,[]),a.get(m).push(p)}let c=`${r}
749
- ${n}`.split(/[\s,;()[\]{}<>"'!?]+/);for(let p of c){let d=p.replace(/^[`*_]+|[`*_.:]+$/g,"");if(!d||!d.includes("/")&&!d.includes("."))continue;let f=a.get(d)??[];f.length===1&&s(f[0],cS)}let l=Kg(`${r}
750
- ${n}`),u=[];for(let[p,d]of o.events){if(p===e||!d.title)continue;let f=fS(l,Kg(d.title));f>=uS&&u.push({key:ke(p),score:f})}return u.sort((p,d)=>d.score-p.score||(p.key<d.key?-1:1)).slice(0,dS).forEach(p=>s(p.key,lS)),i}var Fg,cS,lS,uS,dS,pS,Hg=b(()=>{"use strict";F();Fg=1,cS=.9,lS=.5,uS=.15,dS=3,pS=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g});function Wg(t,e,r={}){let n=r.cutoff??Tr.activationCutoff,o=r.topK??Tr.topKPerNode,i=r.nodeCap??Tr.nodeCap,s=new Map;for(let[l,u]of e)s.set(l,{activation:u});let a=[...e].map(([l,u])=>({key:l,activation:u})).sort((l,u)=>u.activation-l.activation||(l.key<u.key?-1:1)),c=new Set;for(;a.length>0;){a.sort((p,d)=>d.activation-p.activation||(p.key<d.key?-1:1));let l=a.shift();if(c.has(l.key)||(s.get(l.key)?.activation??0)>l.activation)continue;if(c.add(l.key),c.size>i)break;let u=[...t.adjacency.get(l.key)??[]].sort((p,d)=>d.weight-p.weight||(p.to<d.to?-1:1)).slice(0,o);for(let p of u){let d=Qc[p.kind]??.3,f=l.activation*d*Math.min(p.weight,1);if(f<n)continue;let m=s.get(p.to);(!m||m.activation<f)&&(s.set(p.to,{activation:f,via:{from:l.key,kind:p.kind}}),a.push({key:p.to,activation:f}))}}return s}var Yg=b(()=>{"use strict";F()});import{existsSync as qg,readFileSync as Vg,readdirSync as mS}from"node:fs";import{join as tc}from"node:path";function ec(t){return Math.ceil(t.length/4)}function Li(t,e){return[...t.entries()].filter(([r])=>e(r)).map(([r,n])=>({key:r,activation:n.activation,via:n.via})).sort((r,n)=>n.activation-r.activation||(r.key<n.key?-1:1))}function Ft(t){let e=te(t);return e?(e.level==="task"||e.level==="adr",e.path):t}function Mi(t){if(!t.via)return"matched from the task text";let e=Ft(t.via.from);switch(t.via.kind){case"touched_by":return t.via.from.startsWith("task::")?`touched by ${e}`:`touches ${e}`;case"correlates":return`co-changes with ${e}`;case"relates":return`related to ${e} (shared files)`;case"references":return`referenced by ${e}`;case"contains":return`contained in ${e}`;default:return`linked to ${e}`}}function kS(t,e){let r=/^ADR-(\d{3,4})$/.exec(e)?.[1];if(!r)return null;let n=tc(t,"adr");if(!qg(n))return null;let o=r.padStart(4,"0");for(let i of mS(n).sort())if(!(!i.startsWith(`${o}-`)||!i.endsWith(".md")))try{return{file:`adr/${i}`,content:Vg(tc(n,i),"utf-8").trim()}}catch{return null}return null}function zg(t){let{taskKey:e,title:r,contextDir:n,model:o,activated:i}=t,s=t.budgetTokens??Tr.budgetTokens,a=[],c=0,l=R=>{let x=ec(R);return c+x>s?!1:(a.push(R),c+=x,!0)};l([`# Context pack \u2014 ${e}: ${r}`,"","Assembled deterministically from the project map (git history, past","tasks, decisions). No file bodies here \u2014 the paths are ENTRY POINTS","into the repositories; each line says why it made the list."].join(`
751
- `));let u=Li(i,R=>R.startsWith("adr::")),p=!1;for(let R of u){let x=kS(n,Ft(R.key));if(!x)continue;let $=`${p?"":`
747
+ `:"");f.push({path:Vx,contentBase64:Buffer.from(g,"utf-8").toString("base64")})}return{artifacts:f,omitted:p,dropped:l}}var Wx,Yx,qx,Vx,zx,Jx,_g=b(()=>{"use strict";Wx=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),Yx=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),qx=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),Vx="artifacts-omitted.md",zx=500,Jx=new Set(["QUESTIONS.md","SOLUTION.md","DRAFT.md","ESTIMATE.md","diff-summary.md","review-result.md","commit-message.txt","pr-description.md"])});import{lstatSync as eS,mkdtempSync as tS,readFileSync as rS,readdirSync as Ng,rmSync as jg}from"node:fs";import{tmpdir as nS}from"node:os";import{join as ji,relative as oS}from"node:path";function Og(t){let e=tS(ji(nS(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>jg(e,{recursive:!0,force:!0}),listFiles:()=>Dg(e,e),readFile:r=>rS(ji(e,r),"utf-8"),clean:()=>{for(let r of Ng(e))sS.has(r)||jg(ji(e,r),{recursive:!0,force:!0})}}}function Dg(t,e){let r=[];for(let n of Ng(e)){let o=ji(e,n),i=eS(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&iS.has(n))continue;r.push(...Dg(t,o))}else r.push(oS(t,o))}return r}var iS,sS,Lg=b(()=>{"use strict";iS=new Set(["code","context","scratch"]),sS=new Set(["code","context"])});import{existsSync as Oi,readFileSync as Mg,readdirSync as Za}from"node:fs";import{join as vt}from"node:path";import{parse as aS}from"yaml";function Di(t){if(!Oi(t))return[];let e=[];for(let r of Za(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=vt(t,r.name);r.isDirectory()?e.push(...Di(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function Ni(t){try{return aS(Mg(t,"utf-8"))}catch{return null}}function Ug(t){let e={nodes:new Map,adjacency:new Map,events:new Map,annotations:new Map,keyByEntity:new Map,orphanedEntities:new Set,empty:!0},r=(i,s,a,c)=>{e.adjacency.has(i)||e.adjacency.set(i,[]),e.adjacency.has(s)||e.adjacency.set(s,[]),e.adjacency.get(i).push({to:s,kind:a,weight:c}),e.adjacency.get(s).push({to:i,kind:a,weight:c})};for(let i of Di(vt(t,"model/derived/structure"))){let s=$o(Ni(i));if(s.ok){for(let a of s.value.nodes)e.nodes.set(a.key,a);for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}}for(let i of[...Di(vt(t,"model/derived/correlates")),vt(t,"model/derived/relates.yaml")]){if(!Oi(i))continue;let s=ko(Ni(i));if(s.ok)for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}let n=vt(t,"model/facts/events");if(Oi(n))for(let i of Za(n).sort()){if(!i.endsWith(".yaml"))continue;let s=Rr(Ni(vt(n,i)));if(!s.ok)continue;let a=s.value;e.events.set(a.taskKey,a);let c=ke(a.taskKey);for(let l of a.files)r(c,l.key,"touched_by",1);for(let l of a.links?.adr??[])r(c,`adr::${l}`,"references",1);for(let l of a.links?.tasks??[])r(c,ke(l),"references",1)}for(let i of Di(vt(t,"model/facts/identity"))){let s=vo(Ni(i));if(s.ok)for(let a of s.value.entities)a.status==="orphaned"?e.orphanedEntities.add(a.entityId):e.keyByEntity.set(a.entityId,a.currentKey)}let o=vt(t,"model/facts/annotations");if(Oi(o)){for(let i of Za(o).sort())if(i.endsWith(".md"))try{let s=Mg(vt(o,i),"utf-8"),a=/^---\n[\s\S]*?entityId:\s*(e_[0-9a-f]{8})[\s\S]*?\n---\n?([\s\S]*)$/.exec(s);a&&e.annotations.set(a[1],a[2].trim())}catch{}}return e.empty=e.nodes.size===0&&e.events.size===0,e}var Bg=b(()=>{"use strict";F()});function Kg(t){return new Set((t.toLowerCase().match(/[a-zа-я0-9_]{4,}/g)??[]).filter(e=>!/^\d+$/.test(e)))}function mS(t,e){if(t.size===0||e.size===0)return 0;let r=0;for(let n of t)e.has(n)&&r++;return r/(t.size+e.size-r)}function Gg(t){let{taskKey:e,title:r,text:n,model:o}=t,i=new Map,s=(f,m)=>{(i.get(f)??0)<m&&i.set(f,m)};(o.events.has(e)||o.adjacency.has(ke(e)))&&s(ke(e),Fg);for(let f of`${r}
748
+ ${n}`.match(fS)??[]){if(f===e)continue;let m=ke(f);(o.events.has(f)||o.adjacency.has(m))&&s(m,Fg)}let a=new Map;for(let f of o.nodes.keys()){let m=ee(f);if(m?.level!=="code")continue;let g=m.path.slice(m.path.lastIndexOf("/")+1);for(let k of[m.path,g])a.has(k)||a.set(k,[]),a.get(k).push(f)}let c=`${r}
749
+ ${n}`.split(/[\s,;()[\]{}<>"'!?]+/);for(let f of c){let m=f.replace(/^[`*_]+|[`*_.:]+$/g,"");if(!m||!m.includes("/")&&!m.includes("."))continue;let g=a.get(m)??[];g.length===1&&s(g[0],cS)}let l=new Map,u=(f,m)=>{let g=f.toLowerCase();!g||g.length<4||l.set(g,l.has(g)&&l.get(g)!==m?null:m)};for(let f of o.nodes.keys()){let m=ee(f);if(!m)continue;let g=m.path.slice(m.path.lastIndexOf("/")+1);m.level==="code"&&u(g.replace(/\.[a-z0-9]+$/i,""),f),m.level==="component"&&u(g,f)}for(let f of`${r}
750
+ ${n}`.match(/[A-Za-z][A-Za-z0-9_-]{3,}/g)??[]){let m=l.get(f.toLowerCase());m&&s(m,lS)}let p=Kg(`${r}
751
+ ${n}`),d=[];for(let[f,m]of o.events){if(f===e||!m.title)continue;let g=mS(p,Kg(m.title));g>=dS&&d.push({key:ke(f),score:g})}return d.sort((f,m)=>m.score-f.score||(f.key<m.key?-1:1)).slice(0,pS).forEach(f=>s(f.key,uS)),i}var Fg,cS,lS,uS,dS,pS,fS,Hg=b(()=>{"use strict";F();Fg=1,cS=.9,lS=.7,uS=.5,dS=.15,pS=3,fS=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g});function Wg(t,e,r={}){let n=r.cutoff??Tr.activationCutoff,o=r.topK??Tr.topKPerNode,i=r.nodeCap??Tr.nodeCap,s=new Map;for(let[l,u]of e)s.set(l,{activation:u});let a=[...e].map(([l,u])=>({key:l,activation:u})).sort((l,u)=>u.activation-l.activation||(l.key<u.key?-1:1)),c=new Set;for(;a.length>0;){a.sort((p,d)=>d.activation-p.activation||(p.key<d.key?-1:1));let l=a.shift();if(c.has(l.key)||(s.get(l.key)?.activation??0)>l.activation)continue;if(c.add(l.key),c.size>i)break;let u=[...t.adjacency.get(l.key)??[]].sort((p,d)=>d.weight-p.weight||(p.to<d.to?-1:1)).slice(0,o);for(let p of u){let d=Qc[p.kind]??.3,f=l.activation*d*Math.min(p.weight,1);if(f<n)continue;let m=s.get(p.to);(!m||m.activation<f)&&(s.set(p.to,{activation:f,via:{from:l.key,kind:p.kind}}),a.push({key:p.to,activation:f}))}}return s}var Yg=b(()=>{"use strict";F()});import{existsSync as qg,readFileSync as Vg,readdirSync as gS}from"node:fs";import{join as tc}from"node:path";function ec(t){return Math.ceil(t.length/4)}function Li(t,e){return[...t.entries()].filter(([r])=>e(r)).map(([r,n])=>({key:r,activation:n.activation,via:n.via})).sort((r,n)=>n.activation-r.activation||(r.key<n.key?-1:1))}function Ft(t){let e=ee(t);return e?(e.level==="task"||e.level==="adr",e.path):t}function Mi(t){if(!t.via)return"matched from the task text";let e=Ft(t.via.from);switch(t.via.kind){case"touched_by":return t.via.from.startsWith("task::")?`touched by ${e}`:`touches ${e}`;case"correlates":return`co-changes with ${e}`;case"relates":return`related to ${e} (shared files)`;case"references":return`referenced by ${e}`;case"contains":return`contained in ${e}`;default:return`linked to ${e}`}}function wS(t,e){let r=/^ADR-(\d{3,4})$/.exec(e)?.[1];if(!r)return null;let n=tc(t,"adr");if(!qg(n))return null;let o=r.padStart(4,"0");for(let i of gS(n).sort())if(!(!i.startsWith(`${o}-`)||!i.endsWith(".md")))try{return{file:`adr/${i}`,content:Vg(tc(n,i),"utf-8").trim()}}catch{return null}return null}function zg(t){let{taskKey:e,title:r,contextDir:n,model:o,activated:i}=t,s=t.budgetTokens??Tr.budgetTokens,a=[],c=0,l=R=>{let x=ec(R);return c+x>s?!1:(a.push(R),c+=x,!0)};l([`# Context pack \u2014 ${e}: ${r}`,"","Assembled deterministically from the project map (git history, past","tasks, decisions). No file bodies here \u2014 the paths are ENTRY POINTS","into the repositories; each line says why it made the list."].join(`
752
+ `));let u=Li(i,R=>R.startsWith("adr::")),p=!1;for(let R of u){let x=wS(n,Ft(R.key));if(!x)continue;let $=`${p?"":`
752
753
  ## Governing decisions
753
754
  `}
754
755
  ### ${Ft(R.key)} (\`${x.file}\`, ${Mi(R)})
@@ -760,21 +761,21 @@ ${x.content}
760
761
  ### \`${Ft(R.key)}\`
761
762
 
762
763
  ${$}
763
- `;if(!l(_))break;f=!0}let m=ke(e),g=Li(i,R=>R.startsWith("task::")&&R!==m).slice(0,gS),k=!1;for(let R of g){let x=o.events.get(Ft(R.key));if(!x)continue;let $=[...x.files].filter(y=>!y.entityId||!o.orphanedEntities.has(y.entityId)).sort((y,I)=>(I.churn??0)-(y.churn??0)||(y.key<I.key?-1:1)).slice(0,3).map(y=>`\`${Ft(y.key)}\``).join(", "),_="",U=x.links?.solution??`tasks/${x.taskKey}/SOLUTION.md`,G=tc(n,U);if(qg(G))try{_=`
764
- > ${Vg(G,"utf-8").trim().slice(0,yS).replace(/\n+/g," ").trim()}\u2026
764
+ `;if(!l(_))break;f=!0}let m=ke(e),g=Li(i,R=>R.startsWith("task::")&&R!==m).slice(0,hS),k=!1;for(let R of g){let x=o.events.get(Ft(R.key));if(!x)continue;let $=[...x.files].filter(y=>!y.entityId||!o.orphanedEntities.has(y.entityId)).sort((y,I)=>(I.churn??0)-(y.churn??0)||(y.key<I.key?-1:1)).slice(0,3).map(y=>`\`${Ft(y.key)}\``).join(", "),_="",U=x.links?.solution??`tasks/${x.taskKey}/SOLUTION.md`,G=tc(n,U);if(qg(G))try{_=`
765
+ > ${Vg(G,"utf-8").trim().slice(0,kS).replace(/\n+/g," ").trim()}\u2026
765
766
  > _(full text: \`${U}\`)_`}catch{}let P=`${k?"":`
766
767
  ## Related past tasks
767
768
  `}
768
- - **${x.taskKey}**${x.title?` \u2014 ${x.title}`:""}${x.date?` (${x.date})`:""}, ${Mi(R)}. Files: ${$||"\u2014"}.${_}`;if(!l(P))break;k=!0}let w=R=>{let x=o.nodes.get(R.key)?.entityId;return!x||!o.orphanedEntities.has(x)},h=Li(i,R=>R.startsWith("code:")),v=h.filter(w).slice(0,hS);if(v.length>0){let R=["","## Files likely involved",""];for(let x of v){let $=`- \`${Ft(x.key)}\` \u2014 ${Mi(x)}`;if(c+ec(R.join(`
769
+ - **${x.taskKey}**${x.title?` \u2014 ${x.title}`:""}${x.date?` (${x.date})`:""}, ${Mi(R)}. Files: ${$||"\u2014"}.${_}`;if(!l(P))break;k=!0}let w=R=>{let x=o.nodes.get(R.key)?.entityId;return!x||!o.orphanedEntities.has(x)},h=Li(i,R=>R.startsWith("code:")),v=h.filter(w).slice(0,yS);if(v.length>0){let R=["","## Files likely involved",""];for(let x of v){let $=`- \`${Ft(x.key)}\` \u2014 ${Mi(x)}`;if(c+ec(R.join(`
769
770
  `))+ec($)>s)break;R.push($)}R.length>3&&l(R.join(`
770
771
  `))}let T=h.filter(R=>!w(R)).slice(0,10);if(T.length>0){let R=["","## Possibly stale (verify before trusting)","","These entries reference files that no longer exist at their recorded","location. Useful as history, wrong as current fact.","",...T.map(x=>`- \`${Ft(x.key)}\` \u2014 ${Mi(x)}`)];l(R.join(`
771
772
  `))}return a.length<=1?null:a.join(`
772
773
  `)+`
773
- `}var gS,hS,yS,Jg=b(()=>{"use strict";F();gS=5,hS=40,yS=400});var Xg={};mo(Xg,{assembleContextPack:()=>vS});import{existsSync as wS,readFileSync as bS}from"node:fs";import{join as $S}from"node:path";function vS(t){let e=Ug(t.contextDir);if(e.empty)return null;let r="",n=$S(t.contextDir,`tasks/${t.taskKey}/task.md`);if(wS(n))try{r=bS(n,"utf-8")}catch{r=""}let o=Gg({taskKey:t.taskKey,title:t.title,text:r,model:e});if(o.size===0)return null;let i=Wg(e,o);return zg({taskKey:t.taskKey,title:t.title,contextDir:t.contextDir,model:e,activated:i,...t.budgetTokens!==void 0?{budgetTokens:t.budgetTokens}:{}})}var Qg=b(()=>{"use strict";Bg();Hg();Yg();Jg()});import{mkdirSync as Zg,readFileSync as eh,readdirSync as xS,writeFileSync as th}from"node:fs";import{homedir as SS}from"node:os";import{dirname as TS,join as Kt}from"node:path";function CS(t){let e=Buffer.from(t,"utf-8");if(e.length<=Ui)return t;let r=Math.floor(Ui/4),n=Ui-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}
774
+ `}var hS,yS,kS,Jg=b(()=>{"use strict";F();hS=5,yS=300,kS=400});var Xg={};mo(Xg,{assembleContextPack:()=>xS});import{existsSync as bS,readFileSync as $S}from"node:fs";import{join as vS}from"node:path";function xS(t){let e=Ug(t.contextDir);if(e.empty)return null;let r="",n=vS(t.contextDir,`tasks/${t.taskKey}/task.md`);if(bS(n))try{r=$S(n,"utf-8")}catch{r=""}let o=Gg({taskKey:t.taskKey,title:t.title,text:r,model:e});if(o.size===0)return null;let i=Wg(e,o);return zg({taskKey:t.taskKey,title:t.title,contextDir:t.contextDir,model:e,activated:i,...t.budgetTokens!==void 0?{budgetTokens:t.budgetTokens}:{}})}var Qg=b(()=>{"use strict";Bg();Hg();Yg();Jg()});import{mkdirSync as Zg,readFileSync as eh,readdirSync as SS,writeFileSync as th}from"node:fs";import{homedir as TS}from"node:os";import{dirname as RS,join as Kt}from"node:path";function ES(t){let e=Buffer.from(t,"utf-8");if(e.length<=Ui)return t;let r=Math.floor(Ui/4),n=Ui-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}
774
775
 
775
776
  \u2026 [${s} bytes elided \u2014 log capped at ${Ui} bytes for upload] \u2026
776
777
 
777
- ${i}`}function ES(){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 eo(t={}){Ei();let e=xe(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=Lm(t.profile,e.sandboxId,!!W("SANDBOX_CONFIG")),s=Kt(SS(),".codepipe","logs"),a=No("SANDBOX_LOG",i,s);if(a.enabled){let P=new Nr(a);Oo(P),console.log(`[log] file logging \u2192 ${P.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${Oe} (protocol ${tt})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=zm(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=eg();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let u=new Jr(e.hubUrl,e.token),p=!1,d=new AbortController,f=new Map,m=null,g=null,k=!1,w=()=>{let P=u.openControlSocket();return m=P,P.on("open",()=>{console.log("[ws] connected");let y={type:"sandbox_hello",platformVersion:Oe,protocolVersion:tt};P.send(JSON.stringify(y))}),P.on("message",y=>{let I=y.toString("utf-8"),E=null;try{let C=JSON.parse(I);C&&typeof C=="object"&&(E=C)}catch{}if(E&&E.type==="hello"){let C=E;g=go(C.protocolVersion);let O=g?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${C.platformVersion} (protocol ${C.protocolVersion}) \u2014 ${O}`),g&&(k=!1);return}if(E&&E.type==="pause_job"){let C=typeof E.jobId=="string"?E.jobId:"",O=C?f.get(C):void 0;O?(console.warn(`[ws] pause_job ${C} \u2014 aborting agent`),O.paused=!0,O.abort.abort()):console.log(`[ws] pause_job ${C} \u2014 not a running job, ignoring`),C&&P.send(JSON.stringify({type:"job_paused",jobId:C}));return}if(E&&(E.type==="chat_user_message"||E.type==="chat_finalize")){let C=typeof E.jobId=="string"?E.jobId:"",O=C?f.get(C):void 0;if(O?.chatInbox)if(E.type==="chat_user_message"){let j=typeof E.text=="string"?E.text:"";j.trim()&&O.chatInbox.push({kind:"user",text:j})}else O.chatInbox.finalize();else console.log(`[ws] ${String(E.type)} ${C} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${I}`)}),P.on("close",(y,I)=>{console.log(`[ws] closed code=${y} reason=${I?.toString()||""}`),m===P&&(m=null),!p&&setTimeout(w,2e3)}),P.on("error",y=>console.warn(`[ws] error: ${y.message}`)),P},h=w(),v=async P=>{for(;!p;){if(g===!1){k||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${Oe}, protocol ${tt}) \u2014 not claiming jobs until versions align.`),k=!0),await new Promise(y=>setTimeout(y,5e3));continue}try{let y=await u.claim(d.signal,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(E=>setTimeout(E,5e3));continue}let I=await y.json();await T(u,I)}catch(y){if(d.signal.aborted)break;let I=y instanceof Error?y.message:String(y);console.warn(`[claim:${P}] error: ${I} \u2014 backoff 5s`),await new Promise(E=>setTimeout(E,5e3))}}};async function T(P,y){let I={abort:new AbortController,paused:!1};y.role==="chat"&&(I.chatInbox=ES()),f.set(y.jobId,I);let E=!1,C=null,O=null,j=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),S=async()=>{try{await P.heartbeat(y.jobId)==="claim_lost"&&(E=!0,console.warn(`[job] ${y.jobId} claim lost \u2014 HUB sweeper took it`))}catch(q){let Z=q instanceof Error?q.message:String(q);console.warn(`[job] ${y.jobId} heartbeat error: ${Z}`)}};S();let A=setInterval(()=>{S()},j),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(x(y.prompt," \u2502 "));let V=[],Re=null,wr=400,br=25,pt=500,D=()=>{if(Re&&(clearTimeout(Re),Re=null),V.length===0)return;let q=V.splice(0,V.length),Z=m;if(!Z||Z.readyState!==Z.OPEN)return;let ft={type:"agent_activity",jobId:y.jobId,taskId:y.taskId,projectId:y.projectId,role:y.role,phase:y.phase,events:q};try{Z.send(JSON.stringify(ft))}catch{}},ce=q=>{V.push(q),V.length>pt&&V.shift(),V.length>=br?D():Re||(Re=setTimeout(D,wr))},Ne=y.role==="analysis"&&y.taskId.startsWith("draft::")?y.taskId.slice(7):null,Ke=new Set,St=null;try{if(!c){E||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(!Jm(o,y.provider??null)){E||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 q=Og(y.jobId);console.log(`[job] ${y.jobId} workspace=${q.dir}`);let Z=R(y,r);C=Z.gitCreds,O=Z.contextGitCreds;let ft=C?.env,_c=Z.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:Z.claudeOauthToken}:void 0,mt=[],zt=null,Xi=null;try{let M=y.role==="build"?"clone":"worktree";mt=await $g(q.dir,y.projectId,y.projectRepos,M,ft,n);let B=await vg(q.dir,y.projectId,y.contextRepo,"worktree",ft,n);Xi=B,zt=B?.workspacePath??null}catch(M){let B=M instanceof Error?M.message:String(M);console.warn(`[job] ${y.jobId} materialize failed: ${B}`),E||await P.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${B}`},startedAt:L,finishedAt:new Date().toISOString()}),q.dispose();return}let jc=async()=>{if(!y.deliveries||y.deliveries.length===0)return[];let M=y.contextRepo?.cloneUrl;if(!M||!ft)throw new Error(M?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let B=[];for(let J of y.deliveries){let z=mt.find(fe=>fe.name===J.name);if(z){if(y.role==="implement"&&J.baseSha&&J.baseSha!==z.baseSha){let fe=await kg(z,J.deliveryRef,J.deliverySha,J.baseSha,M,ft);console.log(`[job] ${y.jobId} ${z.name}: base moved ${J.baseSha.slice(0,10)} \u2192 ${z.baseSha.slice(0,10)} \u2014 re-applied delivery ${J.deliverySha.slice(0,10)} (${fe.length} conflicted file(s))`),fe.length>0&&B.push(`- **${z.name}**:`,...fe.map(wn=>` - \`${wn}\``));continue}await yg(z,J.deliveryRef,J.deliverySha,M,ft),console.log(`[job] ${y.jobId} ${z.name}: checked out delivery ${J.deliverySha.slice(0,10)} for ${y.role}`)}}return B},Qi=[];if(y.role==="build"||y.role==="implement"||y.role==="code-review")try{Qi=await jc()}catch(M){let B=M instanceof Error?M.message:String(M);console.warn(`[job] ${y.jobId} delivery checkout failed: ${B}`),E||await P.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${B}`},startedAt:L,finishedAt:new Date().toISOString()}),q.dispose();return}let Zi=y.role==="resolve-conflict"?y.metadata?.taskBranchByRepo??{}:{},Nc="";if(y.role==="resolve-conflict"){if(!mt.some(M=>Zi[M.name])){let M="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} ${M}`),E||await P.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:M},startedAt:L,finishedAt:new Date().toISOString()}),q.dispose();return}try{let M=[];for(let B of mt){let J=Zi[B.name];if(!J)continue;let z=await Xa(B,J,ft);console.log(`[job] ${y.jobId} ${B.name}: merged ${J} into ${B.ref} \u2014 ${z.length} conflicted file(s)`),z.length>0?M.push(`- **${B.name}**:`,...z.map(fe=>` - \`${fe}\``)):M.push(`- **${B.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}Nc=`
778
+ ${i}`}function IS(){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 eo(t={}){Ei();let e=xe(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=Lm(t.profile,e.sandboxId,!!W("SANDBOX_CONFIG")),s=Kt(TS(),".codepipe","logs"),a=No("SANDBOX_LOG",i,s);if(a.enabled){let P=new Nr(a);Oo(P),console.log(`[log] file logging \u2192 ${P.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${Oe} (protocol ${tt})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=zm(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=eg();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let u=new Jr(e.hubUrl,e.token),p=!1,d=new AbortController,f=new Map,m=null,g=null,k=!1,w=()=>{let P=u.openControlSocket();return m=P,P.on("open",()=>{console.log("[ws] connected");let y={type:"sandbox_hello",platformVersion:Oe,protocolVersion:tt};P.send(JSON.stringify(y))}),P.on("message",y=>{let I=y.toString("utf-8"),E=null;try{let C=JSON.parse(I);C&&typeof C=="object"&&(E=C)}catch{}if(E&&E.type==="hello"){let C=E;g=go(C.protocolVersion);let O=g?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${C.platformVersion} (protocol ${C.protocolVersion}) \u2014 ${O}`),g&&(k=!1);return}if(E&&E.type==="pause_job"){let C=typeof E.jobId=="string"?E.jobId:"",O=C?f.get(C):void 0;O?(console.warn(`[ws] pause_job ${C} \u2014 aborting agent`),O.paused=!0,O.abort.abort()):console.log(`[ws] pause_job ${C} \u2014 not a running job, ignoring`),C&&P.send(JSON.stringify({type:"job_paused",jobId:C}));return}if(E&&(E.type==="chat_user_message"||E.type==="chat_finalize")){let C=typeof E.jobId=="string"?E.jobId:"",O=C?f.get(C):void 0;if(O?.chatInbox)if(E.type==="chat_user_message"){let j=typeof E.text=="string"?E.text:"";j.trim()&&O.chatInbox.push({kind:"user",text:j})}else O.chatInbox.finalize();else console.log(`[ws] ${String(E.type)} ${C} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${I}`)}),P.on("close",(y,I)=>{console.log(`[ws] closed code=${y} reason=${I?.toString()||""}`),m===P&&(m=null),!p&&setTimeout(w,2e3)}),P.on("error",y=>console.warn(`[ws] error: ${y.message}`)),P},h=w(),v=async P=>{for(;!p;){if(g===!1){k||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${Oe}, protocol ${tt}) \u2014 not claiming jobs until versions align.`),k=!0),await new Promise(y=>setTimeout(y,5e3));continue}try{let y=await u.claim(d.signal,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(E=>setTimeout(E,5e3));continue}let I=await y.json();await T(u,I)}catch(y){if(d.signal.aborted)break;let I=y instanceof Error?y.message:String(y);console.warn(`[claim:${P}] error: ${I} \u2014 backoff 5s`),await new Promise(E=>setTimeout(E,5e3))}}};async function T(P,y){let I={abort:new AbortController,paused:!1};y.role==="chat"&&(I.chatInbox=IS()),f.set(y.jobId,I);let E=!1,C=null,O=null,j=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),S=async()=>{try{await P.heartbeat(y.jobId)==="claim_lost"&&(E=!0,console.warn(`[job] ${y.jobId} claim lost \u2014 HUB sweeper took it`))}catch(q){let Z=q instanceof Error?q.message:String(q);console.warn(`[job] ${y.jobId} heartbeat error: ${Z}`)}};S();let A=setInterval(()=>{S()},j),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(x(y.prompt," \u2502 "));let V=[],Re=null,wr=400,br=25,pt=500,D=()=>{if(Re&&(clearTimeout(Re),Re=null),V.length===0)return;let q=V.splice(0,V.length),Z=m;if(!Z||Z.readyState!==Z.OPEN)return;let ft={type:"agent_activity",jobId:y.jobId,taskId:y.taskId,projectId:y.projectId,role:y.role,phase:y.phase,events:q};try{Z.send(JSON.stringify(ft))}catch{}},ce=q=>{V.push(q),V.length>pt&&V.shift(),V.length>=br?D():Re||(Re=setTimeout(D,wr))},Ne=y.role==="analysis"&&y.taskId.startsWith("draft::")?y.taskId.slice(7):null,Ke=new Set,St=null;try{if(!c){E||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(!Jm(o,y.provider??null)){E||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 q=Og(y.jobId);console.log(`[job] ${y.jobId} workspace=${q.dir}`);let Z=R(y,r);C=Z.gitCreds,O=Z.contextGitCreds;let ft=C?.env,_c=Z.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:Z.claudeOauthToken}:void 0,mt=[],zt=null,Xi=null;try{let M=y.role==="build"?"clone":"worktree";mt=await $g(q.dir,y.projectId,y.projectRepos,M,ft,n);let B=await vg(q.dir,y.projectId,y.contextRepo,"worktree",ft,n);Xi=B,zt=B?.workspacePath??null}catch(M){let B=M instanceof Error?M.message:String(M);console.warn(`[job] ${y.jobId} materialize failed: ${B}`),E||await P.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${B}`},startedAt:L,finishedAt:new Date().toISOString()}),q.dispose();return}let jc=async()=>{if(!y.deliveries||y.deliveries.length===0)return[];let M=y.contextRepo?.cloneUrl;if(!M||!ft)throw new Error(M?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let B=[];for(let J of y.deliveries){let z=mt.find(fe=>fe.name===J.name);if(z){if(y.role==="implement"&&J.baseSha&&J.baseSha!==z.baseSha){let fe=await kg(z,J.deliveryRef,J.deliverySha,J.baseSha,M,ft);console.log(`[job] ${y.jobId} ${z.name}: base moved ${J.baseSha.slice(0,10)} \u2192 ${z.baseSha.slice(0,10)} \u2014 re-applied delivery ${J.deliverySha.slice(0,10)} (${fe.length} conflicted file(s))`),fe.length>0&&B.push(`- **${z.name}**:`,...fe.map(wn=>` - \`${wn}\``));continue}await yg(z,J.deliveryRef,J.deliverySha,M,ft),console.log(`[job] ${y.jobId} ${z.name}: checked out delivery ${J.deliverySha.slice(0,10)} for ${y.role}`)}}return B},Qi=[];if(y.role==="build"||y.role==="implement"||y.role==="code-review")try{Qi=await jc()}catch(M){let B=M instanceof Error?M.message:String(M);console.warn(`[job] ${y.jobId} delivery checkout failed: ${B}`),E||await P.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${B}`},startedAt:L,finishedAt:new Date().toISOString()}),q.dispose();return}let Zi=y.role==="resolve-conflict"?y.metadata?.taskBranchByRepo??{}:{},Nc="";if(y.role==="resolve-conflict"){if(!mt.some(M=>Zi[M.name])){let M="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} ${M}`),E||await P.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:M},startedAt:L,finishedAt:new Date().toISOString()}),q.dispose();return}try{let M=[];for(let B of mt){let J=Zi[B.name];if(!J)continue;let z=await Xa(B,J,ft);console.log(`[job] ${y.jobId} ${B.name}: merged ${J} into ${B.ref} \u2014 ${z.length} conflicted file(s)`),z.length>0?M.push(`- **${B.name}**:`,...z.map(fe=>` - \`${fe}\``)):M.push(`- **${B.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}Nc=`
778
779
 
779
780
  ## Conflicts to resolve
780
781
 
@@ -788,33 +789,33 @@ The base branch advanced since the previous iteration; its delivery was re-appli
788
789
 
789
790
  `+Qi.join(`
790
791
  `)+`
791
- `:"",Ky=_($(y.prompt,mt,zt),zt,y.taskId)+Nc+Fy,es=[...mt.map(M=>M.workspacePath),...zt?[zt]:[]];es.length>0&&console.log(`[job] ${y.jobId} --add-dir: ${es.join(", ")}`),Ne&&(St=setInterval(()=>{let B=m;if(!B||B.readyState!==B.OPEN)return;let J;try{J=xS(Kt(q.dir,"drafts")).filter(z=>z.endsWith(".json")).sort()}catch{return}for(let z of J){if(Ke.has(z))continue;if(Ke.size>=Wl)break;let fe;try{let Ge=JSON.parse(eh(Kt(q.dir,"drafts",z),"utf-8")),$r=typeof Ge.localRef=="string"?Ge.localRef:"",po=typeof Ge.title=="string"?Ge.title:"",ts=typeof Ge.body=="string"?Ge.body:"";if(!$r||!po)continue;fe={localRef:$r,title:po,body:ts,...Ge.isEpic===!0?{isEpic:!0}:{},...Array.isArray(Ge.links)?{links:Ge.links}:{}}}catch{continue}Ke.add(z);let wn={type:"child_draft",jobId:y.jobId,projectId:y.projectId,draftId:Ne,child:fe};try{B.send(JSON.stringify(wn))}catch{}}},1500));try{let M={workspaceDir:q.dir,role:y.role,prompt:Ky,addDirs:es,metadata:y.metadata??{},...y.model?{model:y.model}:{},..._c?{env:_c}:{},signal:I.abort.signal,onActivity:ce},B=I.chatInbox?await c.run({...M,interactive:{inbox:I.chatInbox.iterable}}):await rg(c,M,{jobId:y.jobId,policy:l,onBeforeRetry:async()=>{q.clean();for(let ne of mt)try{await fg(ne);let me=Zi[ne.name];y.role==="resolve-conflict"&&me&&await Xa(ne,me,ft)}catch(me){let bn=me instanceof Error?me.message:String(me);console.warn(`[job] ${y.jobId} worktree reset failed (${ne.name}): ${bn}`)}try{await jc()}catch(ne){let me=ne instanceof Error?ne.message:String(ne);console.warn(`[job] ${y.jobId} delivery re-checkout failed: ${me}`)}},aborted:()=>E||I.paused}),J=[];if(RS.has(y.role)&&mt.length>0){let ne=y.metadata??{},me=typeof ne.commitMessage=="string"?ne.commitMessage:`${y.taskId}: changes`,bn=y.contextRepo?.cloneUrl,Dc=O?.env;if(!bn||!Dc)throw new Error("delivery requested but "+(bn?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let Gy=y.taskId.includes(":")?y.taskId.slice(y.taskId.indexOf(":")+1):y.taskId;for(let gt of mt){let $n=await mg(gt,me);if(!$n){console.log(`[job] ${y.jobId} ${gt.name}: no changes \u2014 no delivery`);continue}let rs=`codepipe/deliveries/${Gy}/${y.jobId}/${gt.name}`;await gg(gt,$n,rs,bn,Dc),J.push({name:gt.name,deliveryRef:rs,deliverySha:$n,baseSha:gt.baseSha}),console.log(`[job] ${y.jobId} ${gt.name}: delivered ${$n.slice(0,10)} \u2192 ${rs}`);let Lc=await hg(gt,$n);if(Lc.trim().length>0){let Hy=Kt("display",`${gt.name}.diff`),Mc=Kt(q.dir,Hy);Zg(TS(Mc),{recursive:!0}),th(Mc,Lc)}}}if(y.role==="resolve-conflict"&&J.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's diff-summary.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let z;y.role==="build"&&(z=Tg(q.dir),console.log(`[job] ${y.jobId} build verdict: ok=${z.ok}`+(z.failedStep?` failedStep=${z.failedStep}`:"")));let fe;y.role==="code-review"&&(fe=Eg(q.dir),console.log(`[job] ${y.jobId} review verdict: approved=${fe.approved}`));let wn=B.artifactPaths.length>0?B.artifactPaths:q.listFiles(),Ge=Array.from(new Set(wn)),$r;if(Xi)try{let ne=y.role==="index"?["adr/SOURCES.md"]:y.role==="backfill"?["adr"]:[],me=await xg(Xi,ne);me.length>0&&($r=me,console.log(`[job] ${y.jobId} captured ${me.length} knowledge file(s) for Context Repo`))}catch(ne){let me=ne instanceof Error?ne.message:String(ne);console.warn(`[job] ${y.jobId} knowledge capture failed (non-fatal): ${me}`)}let{artifacts:po,omitted:ts,dropped:Oc}=Pg(q.dir,Ge);for(let ne of ts)console.warn(`[job] ${y.jobId} artifact ${ne.path} (${ne.bytes} bytes) exceeded upload budget \u2014 content omitted`);Oc.length>0&&console.warn(`[job] ${y.jobId} artifact listing truncated: ${Oc.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let fo={jobId:y.jobId,status:"succeeded",artifacts:po,...$r?{contextWrites:$r}:{},...J.length>0?{deliveries:J}:{},log:CS(B.log),startedAt:L,finishedAt:new Date().toISOString(),usage:B.usage,...B.rateLimit?{rateLimit:B.rateLimit}:{},...z?{build:z}:{},...fe?{review:fe}:{}};if(E||I.paused)console.warn(`[job] ${y.jobId} skipping result upload \u2014 ${I.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await P.submitResult(fo),console.log(`[job] ${y.jobId} done \u2014 uploaded ${fo.artifacts.length} artifact(s):`);for(let ne of fo.artifacts){let me=Buffer.from(ne.contentBase64,"base64").length;console.log(` \xB7 ${ne.path} (${me} bytes)`)}fo.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(M){let B=M instanceof Error?M.message:String(M);if(I.paused)console.log(`[job] ${y.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(E)console.warn(`[job] ${y.jobId} failed after claim lost (${B}) \u2014 skipping result upload`);else{let J=tg(M),z=M instanceof Bt,fe=M instanceof $t;console.warn(J?`[job] ${y.jobId} failed: ${B} (Claude auth \u2014 token invalid/expired)`:z?`[job] ${y.jobId} failed: ${B} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:fe?`[job] ${y.jobId} failed: ${B} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${y.jobId} failed: ${B}`),await P.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:B},startedAt:L,finishedAt:new Date().toISOString(),...J?{authError:!0}:{},...z?{buildInconclusive:!0}:{},...fe?{reviewInconclusive:!0}:{}})}}finally{q.dispose()}}finally{clearInterval(A),St&&clearInterval(St),D(),I.chatInbox?.close(),f.delete(y.jobId),C?.cleanup(),O?.cleanup()}}function R(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 I;try{I=JSON.parse(Gr(y,P.credBundle).toString("utf-8"))}catch(j){return console.warn(`[job] ${P.jobId} failed to open credBundle: ${j instanceof Error?j.message:String(j)}`),{gitCreds:null,contextGitCreds:null}}let E=za(I);E&&console.log(`[job] ${P.jobId} cred bundle opened \u2014 git creds configured`);let C=sg(I,P.contextRepo.cloneUrl),O={gitCreds:E,contextGitCreds:C};return I.claudeOauthToken&&(O.claudeOauthToken=I.claudeOauthToken),O}function x(P,y){return P.split(`
792
+ `:"",Ky=_($(y.prompt,mt,zt),zt,y.taskId)+Nc+Fy,es=[...mt.map(M=>M.workspacePath),...zt?[zt]:[]];es.length>0&&console.log(`[job] ${y.jobId} --add-dir: ${es.join(", ")}`),Ne&&(St=setInterval(()=>{let B=m;if(!B||B.readyState!==B.OPEN)return;let J;try{J=SS(Kt(q.dir,"drafts")).filter(z=>z.endsWith(".json")).sort()}catch{return}for(let z of J){if(Ke.has(z))continue;if(Ke.size>=Wl)break;let fe;try{let Ge=JSON.parse(eh(Kt(q.dir,"drafts",z),"utf-8")),$r=typeof Ge.localRef=="string"?Ge.localRef:"",po=typeof Ge.title=="string"?Ge.title:"",ts=typeof Ge.body=="string"?Ge.body:"";if(!$r||!po)continue;fe={localRef:$r,title:po,body:ts,...Ge.isEpic===!0?{isEpic:!0}:{},...Array.isArray(Ge.links)?{links:Ge.links}:{}}}catch{continue}Ke.add(z);let wn={type:"child_draft",jobId:y.jobId,projectId:y.projectId,draftId:Ne,child:fe};try{B.send(JSON.stringify(wn))}catch{}}},1500));try{let M={workspaceDir:q.dir,role:y.role,prompt:Ky,addDirs:es,metadata:y.metadata??{},...y.model?{model:y.model}:{},..._c?{env:_c}:{},signal:I.abort.signal,onActivity:ce},B=I.chatInbox?await c.run({...M,interactive:{inbox:I.chatInbox.iterable}}):await rg(c,M,{jobId:y.jobId,policy:l,onBeforeRetry:async()=>{q.clean();for(let ne of mt)try{await fg(ne);let me=Zi[ne.name];y.role==="resolve-conflict"&&me&&await Xa(ne,me,ft)}catch(me){let bn=me instanceof Error?me.message:String(me);console.warn(`[job] ${y.jobId} worktree reset failed (${ne.name}): ${bn}`)}try{await jc()}catch(ne){let me=ne instanceof Error?ne.message:String(ne);console.warn(`[job] ${y.jobId} delivery re-checkout failed: ${me}`)}},aborted:()=>E||I.paused}),J=[];if(CS.has(y.role)&&mt.length>0){let ne=y.metadata??{},me=typeof ne.commitMessage=="string"?ne.commitMessage:`${y.taskId}: changes`,bn=y.contextRepo?.cloneUrl,Dc=O?.env;if(!bn||!Dc)throw new Error("delivery requested but "+(bn?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let Gy=y.taskId.includes(":")?y.taskId.slice(y.taskId.indexOf(":")+1):y.taskId;for(let gt of mt){let $n=await mg(gt,me);if(!$n){console.log(`[job] ${y.jobId} ${gt.name}: no changes \u2014 no delivery`);continue}let rs=`codepipe/deliveries/${Gy}/${y.jobId}/${gt.name}`;await gg(gt,$n,rs,bn,Dc),J.push({name:gt.name,deliveryRef:rs,deliverySha:$n,baseSha:gt.baseSha}),console.log(`[job] ${y.jobId} ${gt.name}: delivered ${$n.slice(0,10)} \u2192 ${rs}`);let Lc=await hg(gt,$n);if(Lc.trim().length>0){let Hy=Kt("display",`${gt.name}.diff`),Mc=Kt(q.dir,Hy);Zg(RS(Mc),{recursive:!0}),th(Mc,Lc)}}}if(y.role==="resolve-conflict"&&J.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's diff-summary.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let z;y.role==="build"&&(z=Tg(q.dir),console.log(`[job] ${y.jobId} build verdict: ok=${z.ok}`+(z.failedStep?` failedStep=${z.failedStep}`:"")));let fe;y.role==="code-review"&&(fe=Eg(q.dir),console.log(`[job] ${y.jobId} review verdict: approved=${fe.approved}`));let wn=B.artifactPaths.length>0?B.artifactPaths:q.listFiles(),Ge=Array.from(new Set(wn)),$r;if(Xi)try{let ne=y.role==="index"?["adr/SOURCES.md"]:y.role==="backfill"?["adr"]:[],me=await xg(Xi,ne);me.length>0&&($r=me,console.log(`[job] ${y.jobId} captured ${me.length} knowledge file(s) for Context Repo`))}catch(ne){let me=ne instanceof Error?ne.message:String(ne);console.warn(`[job] ${y.jobId} knowledge capture failed (non-fatal): ${me}`)}let{artifacts:po,omitted:ts,dropped:Oc}=Pg(q.dir,Ge);for(let ne of ts)console.warn(`[job] ${y.jobId} artifact ${ne.path} (${ne.bytes} bytes) exceeded upload budget \u2014 content omitted`);Oc.length>0&&console.warn(`[job] ${y.jobId} artifact listing truncated: ${Oc.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let fo={jobId:y.jobId,status:"succeeded",artifacts:po,...$r?{contextWrites:$r}:{},...J.length>0?{deliveries:J}:{},log:ES(B.log),startedAt:L,finishedAt:new Date().toISOString(),usage:B.usage,...B.rateLimit?{rateLimit:B.rateLimit}:{},...z?{build:z}:{},...fe?{review:fe}:{}};if(E||I.paused)console.warn(`[job] ${y.jobId} skipping result upload \u2014 ${I.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await P.submitResult(fo),console.log(`[job] ${y.jobId} done \u2014 uploaded ${fo.artifacts.length} artifact(s):`);for(let ne of fo.artifacts){let me=Buffer.from(ne.contentBase64,"base64").length;console.log(` \xB7 ${ne.path} (${me} bytes)`)}fo.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(M){let B=M instanceof Error?M.message:String(M);if(I.paused)console.log(`[job] ${y.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(E)console.warn(`[job] ${y.jobId} failed after claim lost (${B}) \u2014 skipping result upload`);else{let J=tg(M),z=M instanceof Bt,fe=M instanceof $t;console.warn(J?`[job] ${y.jobId} failed: ${B} (Claude auth \u2014 token invalid/expired)`:z?`[job] ${y.jobId} failed: ${B} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:fe?`[job] ${y.jobId} failed: ${B} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${y.jobId} failed: ${B}`),await P.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:B},startedAt:L,finishedAt:new Date().toISOString(),...J?{authError:!0}:{},...z?{buildInconclusive:!0}:{},...fe?{reviewInconclusive:!0}:{}})}}finally{q.dispose()}}finally{clearInterval(A),St&&clearInterval(St),D(),I.chatInbox?.close(),f.delete(y.jobId),C?.cleanup(),O?.cleanup()}}function R(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 I;try{I=JSON.parse(Gr(y,P.credBundle).toString("utf-8"))}catch(j){return console.warn(`[job] ${P.jobId} failed to open credBundle: ${j instanceof Error?j.message:String(j)}`),{gitCreds:null,contextGitCreds:null}}let E=za(I);E&&console.log(`[job] ${P.jobId} cred bundle opened \u2014 git creds configured`);let C=sg(I,P.contextRepo.cloneUrl),O={gitCreds:E,contextGitCreds:C};return I.claudeOauthToken&&(O.claudeOauthToken=I.claudeOauthToken),O}function x(P,y){return P.split(`
792
793
  `).map(I=>y+I).join(`
793
794
  `)}function $(P,y,I){let E=y[0]?.workspacePath??"";return P.replace(/\{\{codeDir\}\}/g,E).replace(/\{\{codeRoot\}\}/g,E?E.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,I??"")}function _(P,y,I){let E=P,C=I.includes("::")?"":I.split(":",2)[1]??"",O=j=>{if(!y||!C)return"";try{return eh(Kt(y,"tasks",C,j),"utf-8").trim()}catch{return""}};if(E.includes("{{solutionMd}}")){let j=O("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";E=E.replace(/\{\{solutionMd\}\}/g,()=>j)}if(E.includes("{{taskDescription}}")){let j=O("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";E=E.replace(/\{\{taskDescription\}\}/g,()=>j)}return E}let U=P=>{if(p)return;p=!0,console.log(`
794
- [${P}] shutting down`),d.abort();let y=[...f.keys()];for(let C of f.values())C.abort.abort();let I=new AbortController,E=setTimeout(()=>I.abort(),3e3);(async()=>(await Promise.all(y.map(async C=>{try{await u.releaseJob(C,`sandbox ${P}`,I.signal),console.log(`[${P}] released job ${C}`)}catch(O){let j=O instanceof Error?O.message:String(O);console.warn(`[${P}] release failed: ${j} (sweeper will reclaim)`)}})),clearTimeout(E),h.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>U("SIGINT")),process.on("SIGTERM",()=>U("SIGTERM"));let G=[v("implementation")];e.planningLane!==!1?G.push(v("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(G)}var Ui,RS,rh=b(()=>{"use strict";F();Be();$s();Xm();ng();Ce();Ii();ag();Ha();Sg();Rg();Ig();_g();Lg();Ui=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),RS=new Set(["implement","resolve-conflict"])});var an=b(()=>{"use strict";Um();rh();Ii()});import{cancel as IS,isCancel as oh,log as Ze,password as AS,text as PS}from"@clack/prompts";function _S(t){return oh(t)&&(IS("aborted"),process.exit(1)),typeof t=="string"?t:""}function jS(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function NS(t){let e=js({redirectUri:_s,challenge:t.challenge,state:t.state});Ze.message(`Open this URL, approve the access, and paste the code shown:
795
- ${e}`);let r=await PS({message:"Authorization code \u2014 blank to skip"});if(oh(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=od(r,t.state);return await Ns({code:n,verifier:t.verifier,state:t.state,redirectUri:_s})}catch(n){return Ze.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function OS(t){if(ws()?.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==="0"||!process.stdout.isTTY)return null;Ze.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=Bo(),n;try{n=await id({...r,openUrl:nr,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 NS(r);if(s===null)return null;n=s}let o=await jt(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 ${jS(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function DS(t){Ze.message("Claude login \u2014 pipeline agents run on your Claude subscription.\n Get a token: install Claude Code (https://claude.com/claude-code), run\n `claude setup-token` in a terminal and paste the result here."+(t.farm?`
796
- Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=_S(await AS({message:"Claude OAuth token \u2014 blank to skip"})).trim();return e?(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`."),e):(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`."),"")}var ih,sh=b(()=>{"use strict";Fo();Dr();ie();Ds();ih={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:OS,promptManual:DS,validate:jt}});function ah(t){return ih}async function ch(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var lh=b(()=>{"use strict";sh()});async function ln(t,e,r){return e.host==="github"?MS(t,e,r):e.host==="gitlab"?WS(t,e,r):qS(t,e,r)}async function uh(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 Ht(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await dh(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 Gt(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await ph(e.gitlabToken,t):o}}return e.bitbucket?(await cn(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await fh(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 dh(t,e){let r=!1;try{r=(await Ht(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 ph(t,e){let r=!1;try{r=(await Gt(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 fh(t,e){let r=!1;try{r=(await cn(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 Ht(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(LS+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 MS(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 US(n,e,r),i=await FS(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=Kr(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await KS(n,o.owner,o.name,a.path,i)||await GS(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 US(t,e,r){let n=await Ht(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 dh(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await BS(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 Ht(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 BS(t,e){let{status:r,data:n}=await Ht(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function FS(t,e,r){let{data:n}=await Ht(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function KS(t,e,r,n,o){let{status:i,data:s}=await Ht(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function GS(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 Ht(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Gt(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(HS+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 WS(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 Gt(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 ph(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await Gt(n,"GET","/user"),d={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(p.data?.username!==e.owner){let m=await Gt(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(m.status===404||!m.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);d.namespace_id=m.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let f=await Gt(n,"POST","/projects",d);if(!f.data)throw new Error("GitLab create project: empty response");i=f.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Kr(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let f=(await Gt(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let m of f)l.add(m.path);if(f.length<100)break}let u=c.filter(p=>!l.has(p.path)).map(p=>({action:"create",file_path:p.path,content:p.content}));return u.length>0?await Gt(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 cn(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(YS+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 qS(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 cn(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 fh(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 cn(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=Kr(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await cn(n,"GET",`${o}/src/${encodeURIComponent(a)}/${p.path}?format=meta`)).status===404&&l.push(p);if(l.length>0){let p=new URLSearchParams;p.set("message","chore(codepipe): scaffold context repo files"),p.set("branch",a);for(let f of l)p.set(f.path,f.content);if((await cn(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 LS,HS,YS,Bi=b(()=>{"use strict";pr();LS="https://api.github.com";HS="https://gitlab.com/api/v4";YS="https://api.bitbucket.org/2.0"});function Fe(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=VS[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 VS,Fi=b(()=>{"use strict";VS={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as zS}from"node:crypto";import{existsSync as mh,mkdirSync as JS,readFileSync as gh,readdirSync as XS,rmSync as Ki,writeFileSync as QS}from"node:fs";import{homedir as ZS}from"node:os";import{dirname as eT,join as rc}from"node:path";function hh(){return rc(ZS(),".codepipe","init-drafts")}function nc(t){let e=zS("sha256").update(t).digest("hex").slice(0,16);return rc(hh(),`${e}.json`)}function yh(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=tT)}function kh(t){let e=nc(t);if(!mh(e))return null;try{let r=JSON.parse(gh(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:yh(r.savedAt)?(Ki(e,{force:!0}),null):r}catch{return null}}function oc(t){Ki(nc(t),{force:!0})}function wh(){let t=hh();if(mh(t))for(let e of XS(t)){let r=rc(t,e);try{let n=JSON.parse(gh(r,"utf-8"));yh(n.savedAt)&&Ki(r,{force:!0})}catch{Ki(r,{force:!0})}}}var tT,un,bh=b(()=>{"use strict";tT=24*60*60*1e3;un=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(){oc(this.cwd)}persist(){let e=nc(this.cwd);JS(eT(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};QS(e,JSON.stringify(r,null,2)+`
797
- `,{mode:384})}}});function $h(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 vh(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 xh=b(()=>{"use strict"});import{existsSync as rT}from"node:fs";import{join as nT}from"node:path";import{simpleGit as oT}from"simple-git";function cT(t){let e=t.split("/");return e[e.length-1]??t}function Sh(t){if(t.filter(r=>!sT.test(cT(r))).length>iT)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(aT.has(n))return!0}return!1}async function lT(t){try{let r=(await oT(t).raw(["ls-files"])).split(`
798
- `).map(n=>n.trim()).filter(Boolean);return Sh(r)}catch{return!1}}async function uT(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)?Sh(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function Th(t,e){for(let r of t)try{let n=e.localRoot!=null?nT(e.localRoot,r.mountAs??r.name):null;if(n&&rT(n)?await lT(n):await uT(r,e.tokens))return!0}catch{}return!1}var iT,sT,aT,Rh=b(()=>{"use strict";iT=3,sT=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,aT=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as Ch}from"node:fs";import{join as Eh}from"node:path";import{simpleGit as Ih}from"simple-git";async function ro(t,e,r={}){let n=r.log??dT,o=[];for(let i of e){let s=Eh(t,i.mountAs),a=zl(i);if(!Ch(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 Ih().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let p=to(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(!Ch(Eh(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=Ih(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!pT(l,a)){n.warn(`${i.mountAs}/ origin (${to(l)||"none"}) != expected (${to(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:to(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=to(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 pT(t,e){return Ah(t)===Ah(e)}function Ah(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function to(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function Ph(t={}){let e=ye();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 ro(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 dT,Gi=b(()=>{"use strict";st();dT={info:t=>console.log(t),warn:t=>console.warn(t)}});import{spawn as jh}from"node:child_process";import{existsSync as _h}from"node:fs";import{homedir as fT,hostname as mT}from"node:os";import{join as Hi}from"node:path";async function gT(t,e,r){let n=xe(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${Qe(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 md(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 ${Qe(e)} still holds its token.
799
- 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`),fu(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function hT(t,e,r){let n=xe(e)!==null;if(!await gT(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 Ho(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof K&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof K&&i.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):i instanceof K?i:new Error(`cannot reach the HUB at ${t.hubUrl} (${i instanceof Error?i.message:String(i)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await mr({hub:t.hubUrl,token:o,name:r.name??`${mT()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function yT(t,e){let r=xe(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=Ee(r.sealPublicKey);if(!H(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=_o(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 ic(t,e,r){await hT(t,e,r),yT(t.projectId,e)}function kT(t){return[...t?["--profile",t]:[],"worker","start"]}function wT(t){let e={...t};for(let r of bs)delete e[r];return e}function sc(t){let e=jh(process.execPath,[t.entry,...kT(t.profile)],{stdio:["ignore","pipe","pipe"],env:wT(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
800
- `))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function bT(t,e){let r=process.cwd(),n=Hi(r,it);if(Io(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(_h(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 Q(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 lc(r);if(!Vl(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=H(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await Ci({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=Hi(fT(),".codepipe",e?Hi("profiles",e,"context-config"):"context-config");if(Qo(c.contextDir,l,a),!_h(Hi(c.contextDir,"project.yaml"))){Br(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};Ln(c.contextDir,lt(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 ac(t){let{cfg:e,profile:r}=Po(t.profile);await bT(e,r),await ic(e,r,t);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(f,m)=>{let g=k=>w=>{for(let h of w.toString("utf-8").split(`
795
+ [${P}] shutting down`),d.abort();let y=[...f.keys()];for(let C of f.values())C.abort.abort();let I=new AbortController,E=setTimeout(()=>I.abort(),3e3);(async()=>(await Promise.all(y.map(async C=>{try{await u.releaseJob(C,`sandbox ${P}`,I.signal),console.log(`[${P}] released job ${C}`)}catch(O){let j=O instanceof Error?O.message:String(O);console.warn(`[${P}] release failed: ${j} (sweeper will reclaim)`)}})),clearTimeout(E),h.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>U("SIGINT")),process.on("SIGTERM",()=>U("SIGTERM"));let G=[v("implementation")];e.planningLane!==!1?G.push(v("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(G)}var Ui,CS,rh=b(()=>{"use strict";F();Be();$s();Xm();ng();Ce();Ii();ag();Ha();Sg();Rg();Ig();_g();Lg();Ui=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),CS=new Set(["implement","resolve-conflict"])});var an=b(()=>{"use strict";Um();rh();Ii()});import{cancel as AS,isCancel as oh,log as Ze,password as PS,text as _S}from"@clack/prompts";function jS(t){return oh(t)&&(AS("aborted"),process.exit(1)),typeof t=="string"?t:""}function NS(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function OS(t){let e=js({redirectUri:_s,challenge:t.challenge,state:t.state});Ze.message(`Open this URL, approve the access, and paste the code shown:
796
+ ${e}`);let r=await _S({message:"Authorization code \u2014 blank to skip"});if(oh(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=od(r,t.state);return await Ns({code:n,verifier:t.verifier,state:t.state,redirectUri:_s})}catch(n){return Ze.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function DS(t){if(ws()?.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==="0"||!process.stdout.isTTY)return null;Ze.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=Bo(),n;try{n=await id({...r,openUrl:nr,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 OS(r);if(s===null)return null;n=s}let o=await jt(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 ${NS(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function LS(t){Ze.message("Claude login \u2014 pipeline agents run on your Claude subscription.\n Get a token: install Claude Code (https://claude.com/claude-code), run\n `claude setup-token` in a terminal and paste the result here."+(t.farm?`
797
+ Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=jS(await PS({message:"Claude OAuth token \u2014 blank to skip"})).trim();return e?(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`."),e):(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`."),"")}var ih,sh=b(()=>{"use strict";Fo();Dr();ie();Ds();ih={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:DS,promptManual:LS,validate:jt}});function ah(t){return ih}async function ch(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var lh=b(()=>{"use strict";sh()});async function ln(t,e,r){return e.host==="github"?US(t,e,r):e.host==="gitlab"?YS(t,e,r):VS(t,e,r)}async function uh(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 Ht(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await dh(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 Gt(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await ph(e.gitlabToken,t):o}}return e.bitbucket?(await cn(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await fh(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 dh(t,e){let r=!1;try{r=(await Ht(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 ph(t,e){let r=!1;try{r=(await Gt(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 fh(t,e){let r=!1;try{r=(await cn(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 Ht(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(MS+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 US(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 BS(n,e,r),i=await KS(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=Kr(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await GS(n,o.owner,o.name,a.path,i)||await HS(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 BS(t,e,r){let n=await Ht(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 dh(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await FS(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 Ht(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 FS(t,e){let{status:r,data:n}=await Ht(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function KS(t,e,r){let{data:n}=await Ht(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function GS(t,e,r,n,o){let{status:i,data:s}=await Ht(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function HS(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 Ht(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Gt(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(WS+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 YS(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 Gt(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 ph(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await Gt(n,"GET","/user"),d={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(p.data?.username!==e.owner){let m=await Gt(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(m.status===404||!m.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);d.namespace_id=m.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let f=await Gt(n,"POST","/projects",d);if(!f.data)throw new Error("GitLab create project: empty response");i=f.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Kr(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let f=(await Gt(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let m of f)l.add(m.path);if(f.length<100)break}let u=c.filter(p=>!l.has(p.path)).map(p=>({action:"create",file_path:p.path,content:p.content}));return u.length>0?await Gt(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 cn(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(qS+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 VS(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 cn(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 fh(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 cn(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=Kr(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await cn(n,"GET",`${o}/src/${encodeURIComponent(a)}/${p.path}?format=meta`)).status===404&&l.push(p);if(l.length>0){let p=new URLSearchParams;p.set("message","chore(codepipe): scaffold context repo files"),p.set("branch",a);for(let f of l)p.set(f.path,f.content);if((await cn(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 MS,WS,qS,Bi=b(()=>{"use strict";pr();MS="https://api.github.com";WS="https://gitlab.com/api/v4";qS="https://api.bitbucket.org/2.0"});function Fe(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=zS[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 zS,Fi=b(()=>{"use strict";zS={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as JS}from"node:crypto";import{existsSync as mh,mkdirSync as XS,readFileSync as gh,readdirSync as QS,rmSync as Ki,writeFileSync as ZS}from"node:fs";import{homedir as eT}from"node:os";import{dirname as tT,join as rc}from"node:path";function hh(){return rc(eT(),".codepipe","init-drafts")}function nc(t){let e=JS("sha256").update(t).digest("hex").slice(0,16);return rc(hh(),`${e}.json`)}function yh(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=rT)}function kh(t){let e=nc(t);if(!mh(e))return null;try{let r=JSON.parse(gh(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:yh(r.savedAt)?(Ki(e,{force:!0}),null):r}catch{return null}}function oc(t){Ki(nc(t),{force:!0})}function wh(){let t=hh();if(mh(t))for(let e of QS(t)){let r=rc(t,e);try{let n=JSON.parse(gh(r,"utf-8"));yh(n.savedAt)&&Ki(r,{force:!0})}catch{Ki(r,{force:!0})}}}var rT,un,bh=b(()=>{"use strict";rT=24*60*60*1e3;un=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(){oc(this.cwd)}persist(){let e=nc(this.cwd);XS(tT(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};ZS(e,JSON.stringify(r,null,2)+`
798
+ `,{mode:384})}}});function $h(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 vh(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 xh=b(()=>{"use strict"});import{existsSync as nT}from"node:fs";import{join as oT}from"node:path";import{simpleGit as iT}from"simple-git";function lT(t){let e=t.split("/");return e[e.length-1]??t}function Sh(t){if(t.filter(r=>!aT.test(lT(r))).length>sT)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(cT.has(n))return!0}return!1}async function uT(t){try{let r=(await iT(t).raw(["ls-files"])).split(`
799
+ `).map(n=>n.trim()).filter(Boolean);return Sh(r)}catch{return!1}}async function dT(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)?Sh(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function Th(t,e){for(let r of t)try{let n=e.localRoot!=null?oT(e.localRoot,r.mountAs??r.name):null;if(n&&nT(n)?await uT(n):await dT(r,e.tokens))return!0}catch{}return!1}var sT,aT,cT,Rh=b(()=>{"use strict";sT=3,aT=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,cT=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as Ch}from"node:fs";import{join as Eh}from"node:path";import{simpleGit as Ih}from"simple-git";async function ro(t,e,r={}){let n=r.log??pT,o=[];for(let i of e){let s=Eh(t,i.mountAs),a=zl(i);if(!Ch(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 Ih().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let p=to(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(!Ch(Eh(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=Ih(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!fT(l,a)){n.warn(`${i.mountAs}/ origin (${to(l)||"none"}) != expected (${to(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:to(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=to(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 fT(t,e){return Ah(t)===Ah(e)}function Ah(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function to(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function Ph(t={}){let e=ye();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 ro(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 pT,Gi=b(()=>{"use strict";st();pT={info:t=>console.log(t),warn:t=>console.warn(t)}});import{spawn as jh}from"node:child_process";import{existsSync as _h}from"node:fs";import{homedir as mT,hostname as gT}from"node:os";import{join as Hi}from"node:path";async function hT(t,e,r){let n=xe(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${Qe(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 md(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 ${Qe(e)} still holds its token.
800
+ 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`),fu(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function yT(t,e,r){let n=xe(e)!==null;if(!await hT(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 Ho(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof K&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof K&&i.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):i instanceof K?i:new Error(`cannot reach the HUB at ${t.hubUrl} (${i instanceof Error?i.message:String(i)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await mr({hub:t.hubUrl,token:o,name:r.name??`${gT()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function kT(t,e){let r=xe(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=Ee(r.sealPublicKey);if(!H(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=_o(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 ic(t,e,r){await yT(t,e,r),kT(t.projectId,e)}function wT(t){return[...t?["--profile",t]:[],"worker","start"]}function bT(t){let e={...t};for(let r of bs)delete e[r];return e}function sc(t){let e=jh(process.execPath,[t.entry,...wT(t.profile)],{stdio:["ignore","pipe","pipe"],env:bT(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
801
+ `))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function $T(t,e){let r=process.cwd(),n=Hi(r,it);if(Io(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(_h(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 Q(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 lc(r);if(!Vl(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=H(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await Ci({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=Hi(mT(),".codepipe",e?Hi("profiles",e,"context-config"):"context-config");if(Qo(c.contextDir,l,a),!_h(Hi(c.contextDir,"project.yaml"))){Br(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};Ln(c.contextDir,lt(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 ac(t){let{cfg:e,profile:r}=Po(t.profile);await $T(e,r),await ic(e,r,t);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(f,m)=>{let g=k=>w=>{for(let h of w.toString("utf-8").split(`
801
802
  `))h.length>0&&k.write(`${m} ${h}
802
803
  `)};f.stdout?.on("data",g(process.stdout)),f.stderr?.on("data",g(process.stderr))},i=(f,m)=>{let g=jh(process.execPath,[n,...m],{stdio:["ignore","pipe","pipe"],env:process.env});return o(g,f),g};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=sc({entry:n,profile:r,onLine:f=>process.stdout.write(`[worker] ${f}
803
804
  `)}),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,u=f=>{if(!l){l=!0,console.log(`
804
- [up] ${f} \u2014 stopping both roles`);for(let{child:m}of c)m.exitCode===null&&m.kill(f);setTimeout(()=>{for(let{name:m,child:g}of c)g.exitCode===null&&(console.warn(`[up] ${m} 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:f,child:m})=>new Promise(g=>{m.on("exit",(k,w)=>g({name:f,code:k??(w?1:0)}))})),d=await Promise.race(p);l||(console.log(`[up] ${d.name} exited (code ${d.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(p),process.exit(d.code)}var cc=b(()=>{"use strict";Be();an();Pe();kt();Fa();pr();we();ie();st();no()});var Kh={};mo(Kh,{replCommand:()=>fc});import{existsSync as Uh,mkdirSync as $T,readFileSync as vT,writeFileSync as xT}from"node:fs";import{homedir as ST}from"node:os";import{dirname as TT,join as Bh}from"node:path";import*as dn from"node:readline";async function fc(t={}){let e=ye();e||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let r=H(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)),In(r),console.log(`connected to ${r.hubUrl} as project ${e.spec.projectId}`),console.log("the CLI daemon and an embedded agent worker run in this session; /logs and /monitor show their output."),console.log("type /help to list commands. Ctrl+D or /quit to exit.");let n=ur(e.contextDir),o=Object.keys(n);o.length>0&&console.log(`
805
+ [up] ${f} \u2014 stopping both roles`);for(let{child:m}of c)m.exitCode===null&&m.kill(f);setTimeout(()=>{for(let{name:m,child:g}of c)g.exitCode===null&&(console.warn(`[up] ${m} 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:f,child:m})=>new Promise(g=>{m.on("exit",(k,w)=>g({name:f,code:k??(w?1:0)}))})),d=await Promise.race(p);l||(console.log(`[up] ${d.name} exited (code ${d.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(p),process.exit(d.code)}var cc=b(()=>{"use strict";Be();an();Pe();kt();Fa();pr();we();ie();st();no()});var Kh={};mo(Kh,{replCommand:()=>fc});import{existsSync as Uh,mkdirSync as vT,readFileSync as xT,writeFileSync as ST}from"node:fs";import{homedir as TT}from"node:os";import{dirname as RT,join as Bh}from"node:path";import*as dn from"node:readline";async function fc(t={}){let e=ye();e||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let r=H(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)),In(r),console.log(`connected to ${r.hubUrl} as project ${e.spec.projectId}`),console.log("the CLI daemon and an embedded agent worker run in this session; /logs and /monitor show their output."),console.log("type /help to list commands. Ctrl+D or /quit to exit.");let n=ur(e.contextDir),o=Object.keys(n);o.length>0&&console.log(`
805
806
  \u26A0 unfinished local apply: ${o.map(a=>`${a} (${n[a].repos.map(c=>c.mountAs).join(", ")})`).join("; ")}
806
- finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let i=dn.createInterface({input:process.stdin,output:process.stdout,completer:RT,history:YT(),removeHistoryDuplicates:!0}),s={ws:e,secrets:r,connection:"connecting",rl:i,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};Rd(a=>Yt(s,a)),s.daemon=Ti({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:a=>Yt(s,a),warn:a=>Yt(s,a)},onEvent:a=>BT(s,a),workspace:{root:e.root,contextDir:e.contextDir,repos:e.spec.repos.map(a=>({name:a.name,mountAs:a.mountAs,defaultBranch:a.defaultBranch}))}});try{let a={hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId};await ic(a,t.profile,{profile:t.profile});let c=process.argv[1];if(!c)throw new Error("cannot resolve the codepipe entry script for the worker process");let l=sc({entry:c,profile:t.profile,onLine:u=>Yt(s,`[worker] ${u}`)});l.on("exit",(u,p)=>{s.workerExited=!0,!pc&&Wt(s,`[worker] exited (code ${u??(p?1:0)}) \u2014 agent jobs will NOT run; /quit and restart codepipe to bring it back`)}),s.workerChild=l,console.log("embedded agent worker started \u2014 agent jobs run on this machine.")}catch(a){console.warn(`[worker] could not start the embedded worker (${a instanceof Error?a.message:String(a)}). REPL commands still work; run \`codepipe up --reregister\` if the registration was removed.`)}dc(s),i.prompt(),i.on("line",async a=>{let c=a.trim();if(c.length>0)try{if(await CT(s,c)){Mh(s);return}}catch(l){console.error(l instanceof Error?l.message:String(l))}s.unread=0,dc(s),i.prompt()}),i.on("close",()=>{Mh(s)})}function RT(t){let e=Nh.filter(r=>r.startsWith(t));return[e.length?e:Nh,t]}async function CT(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return ET(),!1;case"/status":return await IT(t),!1;case"/tasks":return await AT(t,n),!1;case"/task":return await PT(t,n),!1;case"/sync":return await _T(t),!1;case"/logs":return FT(t,n),!1;case"/monitor":return KT(t),!1;case"/apply":return await Dh(t,n,"apply"),!1;case"/unstash":return await Dh(t,n,"unstash"),!1;case"/applied":return await jT(t,n),!1;case"/abort":return await NT(t,n),!1;case"/approve":return await Lh(t,n,"approve"),!1;case"/merge":return await Lh(t,n,"merge"),!1;case"/login":return DT(t,n),!1;case"/secret":return LT(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function ET(){console.log(["/help show this list","/status connection, project, embedded worker, siblings","/tasks [--phase P] list tasks (optionally filtered by phase)","/task <key> task detail (phase + artifacts)","/sync clone/fetch project repos per project.yaml","/logs [n|follow|clear] tail last n daemon/worker logs / toggle live / clear buffer","/monitor toggle live daemon/worker log streaming (alias /logs follow)","/apply <key> apply task patch on a new branch + commit (local mode)","/unstash <key> apply task patch uncommitted on base commit","/applied <key> --pr U mark applied; --pr repo=URL for multi-repo","/abort <key> --reason roll back local apply, send task back to agent","/approve <key> merge the task's PR(s) (TRACKING, PR mode)","/merge <key> direct-merge the branch to main (TRACKING, no-PR mode)","/login <token> set the Claude OAuth token (not stored in history)","/secret set <k> <v> set a secret (not stored in history)","/secret list list secret keys (no values)","/secret unset <k> remove a secret","/quit stop the daemon and the worker, exit"].join(`
807
- `))}async function IT(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=Uh(Bh(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function AT(t,e){let r=GT(e,"--phase");try{let n=await kd(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){oo(n)}}async function PT(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await wd(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){oo(n)}}async function _T(t){let e=await ro(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 Dh(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await Ld(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function jT(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=ur(t.ws.contextDir)[r],i=HT(e,"--pr");if(i.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let s=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of i){let l=c.indexOf("="),u,p;if(l>0?(u=c.slice(0,l),p=c.slice(l+1)):(p=c,u=o?.repos.length===1?OT(t,o.repos[0].mountAs):s.length===1?s[0]:""),!u){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${p}`);return}let d=p.match(/(?:pull|pull-requests)\/(\d+)/);if(!d){console.log(` cannot parse PR number from ${p}`);return}a.push({repoName:u,url:p,number:Number(d[1])})}try{let c=await bd(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);Ks(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){oo(c)}}async function Lh(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await vd(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){oo(o)}}async function NT(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=WT(e,"--reason")||"local apply aborted";await Ud(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await $d(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){oo(o)}}function OT(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function DT(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},X(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 LT(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(`
808
- `)}`:" (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}MT(t.secrets,n,i),X(t.secrets),In(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}UT(t.secrets,n),X(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function MT(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 UT(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 BT(t,e){switch(e.kind){case"connected":t.connection="connecting",Yt(t,"[hub] connected");break;case"registered":t.connection="registered",Yt(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Wt(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",Yt(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Wt(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Wt(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?Yt(t,`[hub] action ${e.actionType} done`):Wt(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break;case"local_applied":e.ok?Wt(t,`[apply] ${e.taskKey}: branch ${(e.branches??[]).join(", ")} created locally (your checkout is untouched) \u2014 review, push, then: /applied ${e.taskKey} --pr <url>`):Wt(t,`[apply] ${e.taskKey}: auto-apply failed \u2014 task stays in READY_TO_APPLY: ${e.error??"?"}`);break}}function Yt(t,e){t.logBuffer.push(e),t.logBuffer.length>Fh&&t.logBuffer.shift(),t.follow&&Wt(t,e)}function FT(t,e){let r=e[0];if(r==="follow"||r==="on"){uc(t,!0);return}if(r==="off"){uc(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(Fh,Number(r)||Oh)):Oh,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 KT(t){uc(t,!t.follow)}function uc(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Wt(t,e){dn.cursorTo(process.stdout,0),dn.clearLine(process.stdout,0),process.stdout.write(e+`
809
- `),t.unread+=1,dc(t),t.rl.prompt(!0)}function dc(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}function Mh(t){if(pc)return;pc=!0,qT(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
807
+ finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let i=dn.createInterface({input:process.stdin,output:process.stdout,completer:CT,history:qT(),removeHistoryDuplicates:!0}),s={ws:e,secrets:r,connection:"connecting",rl:i,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};Rd(a=>Yt(s,a)),s.daemon=Ti({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:a=>Yt(s,a),warn:a=>Yt(s,a)},onEvent:a=>FT(s,a),workspace:{root:e.root,contextDir:e.contextDir,repos:e.spec.repos.map(a=>({name:a.name,mountAs:a.mountAs,defaultBranch:a.defaultBranch}))}});try{let a={hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId};await ic(a,t.profile,{profile:t.profile});let c=process.argv[1];if(!c)throw new Error("cannot resolve the codepipe entry script for the worker process");let l=sc({entry:c,profile:t.profile,onLine:u=>Yt(s,`[worker] ${u}`)});l.on("exit",(u,p)=>{s.workerExited=!0,!pc&&Wt(s,`[worker] exited (code ${u??(p?1:0)}) \u2014 agent jobs will NOT run; /quit and restart codepipe to bring it back`)}),s.workerChild=l,console.log("embedded agent worker started \u2014 agent jobs run on this machine.")}catch(a){console.warn(`[worker] could not start the embedded worker (${a instanceof Error?a.message:String(a)}). REPL commands still work; run \`codepipe up --reregister\` if the registration was removed.`)}dc(s),i.prompt(),i.on("line",async a=>{let c=a.trim();if(c.length>0)try{if(await ET(s,c)){Mh(s);return}}catch(l){console.error(l instanceof Error?l.message:String(l))}s.unread=0,dc(s),i.prompt()}),i.on("close",()=>{Mh(s)})}function CT(t){let e=Nh.filter(r=>r.startsWith(t));return[e.length?e:Nh,t]}async function ET(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return IT(),!1;case"/status":return await AT(t),!1;case"/tasks":return await PT(t,n),!1;case"/task":return await _T(t,n),!1;case"/sync":return await jT(t),!1;case"/logs":return KT(t,n),!1;case"/monitor":return GT(t),!1;case"/apply":return await Dh(t,n,"apply"),!1;case"/unstash":return await Dh(t,n,"unstash"),!1;case"/applied":return await NT(t,n),!1;case"/abort":return await OT(t,n),!1;case"/approve":return await Lh(t,n,"approve"),!1;case"/merge":return await Lh(t,n,"merge"),!1;case"/login":return LT(t,n),!1;case"/secret":return MT(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function IT(){console.log(["/help show this list","/status connection, project, embedded worker, siblings","/tasks [--phase P] list tasks (optionally filtered by phase)","/task <key> task detail (phase + artifacts)","/sync clone/fetch project repos per project.yaml","/logs [n|follow|clear] tail last n daemon/worker logs / toggle live / clear buffer","/monitor toggle live daemon/worker log streaming (alias /logs follow)","/apply <key> apply task patch on a new branch + commit (local mode)","/unstash <key> apply task patch uncommitted on base commit","/applied <key> --pr U mark applied; --pr repo=URL for multi-repo","/abort <key> --reason roll back local apply, send task back to agent","/approve <key> merge the task's PR(s) (TRACKING, PR mode)","/merge <key> direct-merge the branch to main (TRACKING, no-PR mode)","/login <token> set the Claude OAuth token (not stored in history)","/secret set <k> <v> set a secret (not stored in history)","/secret list list secret keys (no values)","/secret unset <k> remove a secret","/quit stop the daemon and the worker, exit"].join(`
808
+ `))}async function AT(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=Uh(Bh(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function PT(t,e){let r=HT(e,"--phase");try{let n=await kd(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){oo(n)}}async function _T(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await wd(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){oo(n)}}async function jT(t){let e=await ro(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 Dh(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await Ld(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function NT(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=ur(t.ws.contextDir)[r],i=WT(e,"--pr");if(i.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let s=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of i){let l=c.indexOf("="),u,p;if(l>0?(u=c.slice(0,l),p=c.slice(l+1)):(p=c,u=o?.repos.length===1?DT(t,o.repos[0].mountAs):s.length===1?s[0]:""),!u){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${p}`);return}let d=p.match(/(?:pull|pull-requests)\/(\d+)/);if(!d){console.log(` cannot parse PR number from ${p}`);return}a.push({repoName:u,url:p,number:Number(d[1])})}try{let c=await bd(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);Ks(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){oo(c)}}async function Lh(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await vd(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){oo(o)}}async function OT(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=YT(e,"--reason")||"local apply aborted";await Ud(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await $d(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){oo(o)}}function DT(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function LT(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},X(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 MT(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(`
809
+ `)}`:" (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}UT(t.secrets,n,i),X(t.secrets),In(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}BT(t.secrets,n),X(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function UT(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 BT(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 FT(t,e){switch(e.kind){case"connected":t.connection="connecting",Yt(t,"[hub] connected");break;case"registered":t.connection="registered",Yt(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Wt(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",Yt(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Wt(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Wt(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?Yt(t,`[hub] action ${e.actionType} done`):Wt(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break;case"local_applied":e.ok?Wt(t,`[apply] ${e.taskKey}: branch ${(e.branches??[]).join(", ")} created locally (your checkout is untouched) \u2014 review, push, then: /applied ${e.taskKey} --pr <url>`):Wt(t,`[apply] ${e.taskKey}: auto-apply failed \u2014 task stays in READY_TO_APPLY: ${e.error??"?"}`);break}}function Yt(t,e){t.logBuffer.push(e),t.logBuffer.length>Fh&&t.logBuffer.shift(),t.follow&&Wt(t,e)}function KT(t,e){let r=e[0];if(r==="follow"||r==="on"){uc(t,!0);return}if(r==="off"){uc(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(Fh,Number(r)||Oh)):Oh,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 GT(t){uc(t,!t.follow)}function uc(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Wt(t,e){dn.cursorTo(process.stdout,0),dn.clearLine(process.stdout,0),process.stdout.write(e+`
810
+ `),t.unread+=1,dc(t),t.rl.prompt(!0)}function dc(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}function Mh(t){if(pc)return;pc=!0,VT(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
810
811
  bye.`),setTimeout(()=>process.exit(0),150);return}console.log(`
811
- 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 GT(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function HT(t,e){let r=[];for(let n=0;n<t.length;n++)t[n]===e&&t[n+1]&&r.push(t[n+1]);return r}function WT(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function oo(t){t instanceof K?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function YT(){if(!Uh(Wi))return[];try{return vT(Wi,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function qT(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{$T(TT(Wi),{recursive:!0}),xT(Wi,r.slice().reverse().join(`
812
+ 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 HT(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function WT(t,e){let r=[];for(let n=0;n<t.length;n++)t[n]===e&&t[n+1]&&r.push(t[n+1]);return r}function YT(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function oo(t){t instanceof K?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function qT(){if(!Uh(Wi))return[];try{return xT(Wi,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function VT(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{vT(RT(Wi),{recursive:!0}),ST(Wi,r.slice().reverse().join(`
812
813
  `)+`
813
- `)}catch{}}var Wi,Nh,Fh,Oh,pc,mc=b(()=>{"use strict";Ua();we();Wo();ie();st();Gi();cc();Gs();Wi=Bh(ST(),".codepipe","history"),Nh=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Fh=500,Oh=40;pc=!1});import{existsSync as Gh,readFileSync as VT,readdirSync as zT}from"node:fs";import{join as Hh}from"node:path";import{simpleGit as JT}from"simple-git";import{parse as XT}from"yaml";function QT(t){let e=new Map,r=Hh(t,ss);if(!Gh(r))return e;let n;try{n=XT(VT(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 ZT(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return Cr({modelFormatVersion:2,repos:e})}function Wh(t,e){let r=Hh(t,e);if(!Gh(r))return[];let n=[];for(let o of zT(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...Wh(t,i)):n.push(i)}return n}async function gc(t,e,r={}){let n=[],o=0;for(let p of e){n.push(...p.files);let d=`model/derived/structure/${p.repo}`;for(let f of Wh(t,d))p.emittedShardPaths.has(f)||(n.push({path:f,content:"",deleted:!0}),o++)}let i=QT(t);for(let p of e)i.set(p.repo,{builtFromCommit:p.headCommit,counts:p.counts});n.push({path:ss,content:ZT(i)});let s=jf(mi(t),r.halfLifeDays??We.halfLifeDays);n.push({path:xr,content:gi(s)});let a=JT(t),c=(await a.revparse(["HEAD"]).catch(()=>"")).trim(),l=`model: build ${e.map(p=>`${p.repo}@${p.headCommit.slice(0,10)}`).join(", ")}`;return await be(t,n,l),{committed:(await a.revparse(["HEAD"]).catch(()=>"")).trim()!==c,filesWritten:n.filter(p=>!p.deleted).length,filesDeleted:o}}var Yh=b(()=>{"use strict";F();Sa();Xe()});var Qh={};mo(Qh,{bootstrapWorkspaceModel:()=>Xh,modelBootstrapCommand:()=>wc,modelBuildCommand:()=>kc});import{existsSync as eR}from"node:fs";import{join as qh}from"node:path";import{cancel as tR,intro as Vh,log as yc,outro as hc}from"@clack/prompts";function io(t){tR(t),process.exit(1)}function zh(t,e){let r=t.spec.repos.filter(o=>!e||o.name===e);r.length===0&&io(e?`repo "${e}" is not part of this project (see project.yaml)`:"the project has no repos configured");let n=[];for(let o of r){let i=o.mountAs==="."?t.root:qh(t.root,o.mountAs);if(!eR(qh(i,".git"))){yc.warn(`${o.name}: no local clone at ${i} \u2014 skipped (run \`codepipe clone\` first)`);continue}n.push({name:o.name,dir:i})}return n.length===0&&io("nothing to do \u2014 no repo clones found"),n}async function Jh(t,e,r){let n=[];for(let o of e)try{let i=await Cf({repo:o.name,repoDir:o.dir,contextDir:t.contextDir,settings:r});n.push(i),yc.info(`${o.name}: ${i.counts.code} files, ${i.counts.component} components, ${i.counts.correlates} co-change edges @ ${i.headCommit.slice(0,10)}`)}catch(i){io(`${o.name}: ${i instanceof Error?i.message:String(i)}`)}return n}async function kc(t){Vh("codepipe model build");let e=ye();e||io("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");let r=Wn(e.contextDir),n=await Jh(e,zh(e,t.repo),r),o=await gc(e.contextDir,n,{halfLifeDays:r.cochange.halfLifeDays});o.committed?hc(`model updated: ${o.filesWritten} files written, ${o.filesDeleted} stale removed`):hc("model already up to date (no changes)")}async function wc(t){Vh("codepipe model bootstrap");let e=ye();e||io("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)"),await Xh(e,t.repo,{onLog:r=>yc.info(r)}),hc("bootstrap complete")}async function Xh(t,e,r){let n=Wn(t.contextDir),o=zh(t,e),i=await Jh(t,o,n),s=tf(t.contextDir),a=ef(n.issueKeyPattern,s),c=fr([...n.ignore,...Wr]),l=[];for(let d of i){let f=o.find(g=>g.name===d.repo),m=await nf({repo:d.repo,repoDir:f.dir,headCommit:d.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:a,pathToCurrent:ui(d.identityTable),entityByKey:d.entityByKey,ignored:c});l.push(m),r.onLog(`${d.repo}: ${m.size} task events mined from history`)}let{files:u,skippedPipeline:p}=of(t.contextDir,l);return p>0&&r.onLog(`${p} events already recorded by the live pipeline \u2014 left untouched`),u.length>0&&await be(t.contextDir,u,`model: bootstrap ${u.length} task events from history`),await gc(t.contextDir,i,{halfLifeDays:n.cochange.halfLifeDays}),{events:u.length}}var bc=b(()=>{"use strict";Xe();Yh();va();wa();di();fi();st()});import{existsSync as pn,mkdirSync as ey,readFileSync as ty,readdirSync as rR,writeFileSync as ry}from"node:fs";import{join as hr,resolve as ny}from"node:path";import{setTimeout as $c}from"node:timers/promises";import{cancel as nR,confirm as fn,intro as oy,isCancel as Sc,log as N,multiselect as oR,outro as vc,password as so,select as xt,spinner as Tc,text as de}from"@clack/prompts";import{simpleGit as qi}from"simple-git";function oe(t){nR(t),process.exit(1)}function Se(t){return Sc(t)&&oe("aborted"),t}function re(t){return Sc(t)&&oe("aborted"),typeof t=="string"?t:""}async function iy(t={}){oy("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();wh();let r=kh(e),n,o=!1;r&&Object.keys(r.answers).length>0?Se(await fn({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(N.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new un(e,r),o=!0):(oc(e),n=new un(e)):n=new un(e);let i=t.force===!0?null:await lc(e),s=await n.ask("target",async()=>Se(await xt({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i,a?N.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||ay(e,t.force===!0));let c=await n.ask("hubUrl",async()=>re(await de({message:"HUB URL",placeholder:et,initialValue:W("HUB_URL")??et,validate:D=>D.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>mn()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>gn(c,l)),d=null;s==="farm"&&(d=await iR(c,u));let f=a?aR(a.parsed.repoName):"",m=await n.ask("projectId",async()=>re(await de({message:"project id (slug)",placeholder:f||"acme",...f?{initialValue:f}:{},validate:D=>Qt.test(D.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await n.ask("projectName",async()=>re(await de({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:D=>D.trim().length>0?void 0:"required"})).trim()),k=await n.ask("automationLevel",async()=>Se(await xt({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"}))),w=s==="farm"?"auto":await n.ask("applyMode",async()=>Se(await xt({message:"how do approved changes reach your repo?",options:[{value:"auto",label:"auto \u2014 CodePipe pushes the branch and opens a PR"},{value:"local",label:"local \u2014 changes wait; you pull them into your checkout via the CLI REPL (/apply or /unstash), no push/PR"}],initialValue:"auto"}))),h=await n.ask("trackerProvider",async()=>Se(await xt({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"}))),v=h==="internal",T=null,R,x=!0;if(v){let D,ce=Tc();ce.start("checking task-key prefixes on your account\u2026");try{D=await gd(c,u,{excludeProjectId:m}),ce.stop("prefixes checked")}catch{ce.stop("could not reach the HUB",1),oe("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 Ne=Ul(Ml(g),D);R=await n.ask("trackerPrefix",async()=>re(await de({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:Ne,initialValue:Ne,validate:Ke=>{let St=Ke.trim();if(!Ir.test(St))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(D.has(St.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else T=await n.ask("youtrack",()=>my()),R=await n.ask("youtrackProjectKey",async()=>re(await de({message:"YouTrack project key",placeholder:"DEV",validate:D=>D.trim().length>0?void 0:"required"})).trim()),x=await n.ask("youtrackWrites",async()=>Se(await fn({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let $=n.get("tokens")??{},_=()=>n.set("tokens",$),U=await n.ask("repos",()=>uR($,l,a,{onCred:_,initial:n.get("reposPartial")??[],onProgress:D=>n.set("reposPartial",D)}));n.delete("reposPartial");let G=await dR(await n.ask("contextRepo",()=>dy(m,U,$,l)),m,U,$,l,_,D=>n.set("contextRepo",D)),{spec:P,mode:y}=G,I;v||(N.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),I=await n.ask("assigneeLogin",async()=>re(await de({message:"your YouTrack login (the assignee value)",...T?.login?{initialValue:T.login}:{},validate:D=>D.trim().length>0?void 0:"required"})).trim()));let E=await n.ask("llmProvider",async()=>{for(;;){if(Se(await xt({message:"LLM provider",options:[{value:"claude",label:"Claude",hint:"recommended"},{value:"codex",label:"Codex",hint:"coming soon"}],initialValue:"claude"}))==="claude")return"claude";N.warn("Codex support is coming soon \u2014 pick Claude for now.")}}),C=E==="claude"?await n.ask("claudeToken",()=>ch(ah("claude"),{farm:s==="farm"})):"",O;if(C){let D=await rd(C);if(D){let ce=ul(D);ce&&(O=ce,N.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${ce} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let j={projectId:m,name:g,automationLevel:k,repos:U,trackerProvider:h,youtrackProjectKey:R};N.step(`${y==="attach"?"attaching to":"provisioning"} Context Repo ${P.owner}/${P.name} (${P.host})\u2026`);let S;try{S=await ln(j,P,{...py($),youtrackWrites:x,...T?{trackerUrl:T.url}:{},mode:y,log:{info:D=>N.message(D),warn:D=>N.warn(D)}})}catch(D){oe(`Context Repo provisioning failed: ${D instanceof Error?D.message:String(D)}`)}j.contextRepo=S,N.success(`Context Repo ready: ${S.owner}/${S.name}@${S.branch}`),N.step(`registering project on ${c}\u2026`);let A;try{A=await Nt(c,u,j)}catch(D){if(D instanceof K&&D.status===409){N.warn(`project ${m} already exists on HUB \u2014 reusing it`);try{A=await Q(c,u,m)}catch(ce){throw ce instanceof K&&oe(`HUB \u2192 ${ce.status} ${ce.message}`),ce}}else if(D instanceof K&&D.status===401)n.delete("cliToken"),oe("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(D instanceof K)oe(`HUB \u2192 ${D.status} ${D.message}`);else throw D}let L=A.contextRepo??S;N.success(`project ${A.projectId} ready (${A.provisioningStatus})`);let V=await hR(L),Re=T?{url:T.url,token:T.token}:void 0;if(s==="farm"){let D=d,ce={...$,...V?{contextWrite:V}:{},...C?{claude:{oauthToken:C}}:{},...Re?{youtrack:Re}:{}},Ne=$.github?.token;if(L.host==="github"&&Ne)try{let Z=xm(`devpipe-${m}`);await Sm(L,Ne,Z.publicKey,`devpipe-${m}`),ce.contextSsh={privateKey:Z.privateKey},N.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(Z){N.warn(`could not set up Context Repo SSH deploy key (${Z instanceof Error?Z.message:String(Z)}); the farm will fall back to the token path.`)}let Ke={projectId:m,config:{hubUrl:c,cliToken:u,projectId:m},secrets:ce,contextRepo:L,projectConfig:lt(j,x,T?.url,I||void 0,"auto",E,O)},St=wt(D.farm.publicKey,JSON.stringify(Ke));N.step(`handing project ${m} to farm ${D.farm.name}\u2026`);let q;try{q=await Go(c,u,D.farm.farmId,{projectId:m,sealedBundle:St})}catch(Z){throw Z instanceof K&&oe(Z.status===409?`farm ${D.farm.name} is offline \u2014 start it and re-run.`:Z.status===504?`farm ${D.farm.name} did not respond in time.`:`HUB \u2192 ${Z.status} ${Z.message}`),Z}q.ok||oe(`farm rejected provisioning: ${q.error??"unknown error"}`),await xc(c,u,m,L,Ne,A.repos,null,$),n.clear(),vc(`done. project ${m} is now hosted on farm ${D.farm.name} (daemon ${q.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}fy($),await cy(e,L.cloneUrl,L.branch),uy(e),a&&await lR(e);{let D=hr(e,it);Br(D);let ce=lt(j,x,T?.url,I||void 0,w,E,O),Ne=Ln(D,ce);Ne.length>0&&N.success(`local project config \u2192 .codepipe/{${Ne.join(", ")}}`),dr(m,ce,{info:Ke=>N.message(Ke),warn:Ke=>N.warn(Ke)})}await ly(e,A.repos);let wr={hubUrl:c,cliToken:u,projectId:m,...$,...V?{contextWrite:V}:{},...C?{claude:{oauthToken:C}}:{},...Re?{youtrack:Re}:{}};X(wr),yt({hubUrl:c,cliToken:u,projectId:m,accountEmail:p},m),N.success(`secrets \u2192 ${at(m)}`),await xc(c,u,m,L,$.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,A.repos,e,$),n.clear();let br=`${c}/?project=${encodeURIComponent(m)}`;nr(br),vc(`done. your project on the dashboard (sign in there to work with it):
814
+ `)}catch{}}var Wi,Nh,Fh,Oh,pc,mc=b(()=>{"use strict";Ua();we();Wo();ie();st();Gi();cc();Gs();Wi=Bh(TT(),".codepipe","history"),Nh=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Fh=500,Oh=40;pc=!1});import{existsSync as Gh,readFileSync as zT,readdirSync as JT}from"node:fs";import{join as Hh}from"node:path";import{simpleGit as XT}from"simple-git";import{parse as QT}from"yaml";function ZT(t){let e=new Map,r=Hh(t,ss);if(!Gh(r))return e;let n;try{n=QT(zT(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 eR(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return Cr({modelFormatVersion:2,repos:e})}function Wh(t,e){let r=Hh(t,e);if(!Gh(r))return[];let n=[];for(let o of JT(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...Wh(t,i)):n.push(i)}return n}async function gc(t,e,r={}){let n=[],o=0;for(let p of e){n.push(...p.files);let d=`model/derived/structure/${p.repo}`;for(let f of Wh(t,d))p.emittedShardPaths.has(f)||(n.push({path:f,content:"",deleted:!0}),o++)}let i=ZT(t);for(let p of e)i.set(p.repo,{builtFromCommit:p.headCommit,counts:p.counts});n.push({path:ss,content:eR(i)});let s=jf(mi(t),r.halfLifeDays??We.halfLifeDays);n.push({path:xr,content:gi(s)});let a=XT(t),c=(await a.revparse(["HEAD"]).catch(()=>"")).trim(),l=`model: build ${e.map(p=>`${p.repo}@${p.headCommit.slice(0,10)}`).join(", ")}`;return await be(t,n,l),{committed:(await a.revparse(["HEAD"]).catch(()=>"")).trim()!==c,filesWritten:n.filter(p=>!p.deleted).length,filesDeleted:o}}var Yh=b(()=>{"use strict";F();Sa();Xe()});var Qh={};mo(Qh,{bootstrapWorkspaceModel:()=>Xh,modelBootstrapCommand:()=>wc,modelBuildCommand:()=>kc});import{existsSync as tR}from"node:fs";import{join as qh}from"node:path";import{cancel as rR,intro as Vh,log as yc,outro as hc}from"@clack/prompts";function io(t){rR(t),process.exit(1)}function zh(t,e){let r=t.spec.repos.filter(o=>!e||o.name===e);r.length===0&&io(e?`repo "${e}" is not part of this project (see project.yaml)`:"the project has no repos configured");let n=[];for(let o of r){let i=o.mountAs==="."?t.root:qh(t.root,o.mountAs);if(!tR(qh(i,".git"))){yc.warn(`${o.name}: no local clone at ${i} \u2014 skipped (run \`codepipe clone\` first)`);continue}n.push({name:o.name,dir:i})}return n.length===0&&io("nothing to do \u2014 no repo clones found"),n}async function Jh(t,e,r){let n=[];for(let o of e)try{let i=await Cf({repo:o.name,repoDir:o.dir,contextDir:t.contextDir,settings:r});n.push(i),yc.info(`${o.name}: ${i.counts.code} files, ${i.counts.component} components, ${i.counts.correlates} co-change edges @ ${i.headCommit.slice(0,10)}`)}catch(i){io(`${o.name}: ${i instanceof Error?i.message:String(i)}`)}return n}async function kc(t){Vh("codepipe model build");let e=ye();e||io("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");let r=Wn(e.contextDir),n=await Jh(e,zh(e,t.repo),r),o=await gc(e.contextDir,n,{halfLifeDays:r.cochange.halfLifeDays});o.committed?hc(`model updated: ${o.filesWritten} files written, ${o.filesDeleted} stale removed`):hc("model already up to date (no changes)")}async function wc(t){Vh("codepipe model bootstrap");let e=ye();e||io("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)"),await Xh(e,t.repo,{onLog:r=>yc.info(r)}),hc("bootstrap complete")}async function Xh(t,e,r){let n=Wn(t.contextDir),o=zh(t,e),i=await Jh(t,o,n),s=tf(t.contextDir),a=ef(n.issueKeyPattern,s),c=fr([...n.ignore,...Wr]),l=[];for(let d of i){let f=o.find(g=>g.name===d.repo),m=await nf({repo:d.repo,repoDir:f.dir,headCommit:d.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:a,pathToCurrent:ui(d.identityTable),entityByKey:d.entityByKey,ignored:c});l.push(m),r.onLog(`${d.repo}: ${m.size} task events mined from history`)}let{files:u,skippedPipeline:p}=of(t.contextDir,l);return p>0&&r.onLog(`${p} events already recorded by the live pipeline \u2014 left untouched`),u.length>0&&await be(t.contextDir,u,`model: bootstrap ${u.length} task events from history`),await gc(t.contextDir,i,{halfLifeDays:n.cochange.halfLifeDays}),{events:u.length}}var bc=b(()=>{"use strict";Xe();Yh();va();wa();di();fi();st()});import{existsSync as pn,mkdirSync as ey,readFileSync as ty,readdirSync as nR,writeFileSync as ry}from"node:fs";import{join as hr,resolve as ny}from"node:path";import{setTimeout as $c}from"node:timers/promises";import{cancel as oR,confirm as fn,intro as oy,isCancel as Sc,log as N,multiselect as iR,outro as vc,password as so,select as xt,spinner as Tc,text as de}from"@clack/prompts";import{simpleGit as qi}from"simple-git";function oe(t){oR(t),process.exit(1)}function Se(t){return Sc(t)&&oe("aborted"),t}function re(t){return Sc(t)&&oe("aborted"),typeof t=="string"?t:""}async function iy(t={}){oy("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();wh();let r=kh(e),n,o=!1;r&&Object.keys(r.answers).length>0?Se(await fn({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(N.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new un(e,r),o=!0):(oc(e),n=new un(e)):n=new un(e);let i=t.force===!0?null:await lc(e),s=await n.ask("target",async()=>Se(await xt({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i,a?N.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||ay(e,t.force===!0));let c=await n.ask("hubUrl",async()=>re(await de({message:"HUB URL",placeholder:et,initialValue:W("HUB_URL")??et,validate:D=>D.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>mn()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>gn(c,l)),d=null;s==="farm"&&(d=await sR(c,u));let f=a?cR(a.parsed.repoName):"",m=await n.ask("projectId",async()=>re(await de({message:"project id (slug)",placeholder:f||"acme",...f?{initialValue:f}:{},validate:D=>Qt.test(D.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await n.ask("projectName",async()=>re(await de({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:D=>D.trim().length>0?void 0:"required"})).trim()),k=await n.ask("automationLevel",async()=>Se(await xt({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"}))),w=s==="farm"?"auto":await n.ask("applyMode",async()=>Se(await xt({message:"how do approved changes reach your repo?",options:[{value:"auto",label:"auto \u2014 CodePipe pushes the branch and opens a PR"},{value:"local",label:"local \u2014 changes wait; you pull them into your checkout via the CLI REPL (/apply or /unstash), no push/PR"}],initialValue:"auto"}))),h=await n.ask("trackerProvider",async()=>Se(await xt({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"}))),v=h==="internal",T=null,R,x=!0;if(v){let D,ce=Tc();ce.start("checking task-key prefixes on your account\u2026");try{D=await gd(c,u,{excludeProjectId:m}),ce.stop("prefixes checked")}catch{ce.stop("could not reach the HUB",1),oe("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 Ne=Ul(Ml(g),D);R=await n.ask("trackerPrefix",async()=>re(await de({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:Ne,initialValue:Ne,validate:Ke=>{let St=Ke.trim();if(!Ir.test(St))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(D.has(St.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else T=await n.ask("youtrack",()=>my()),R=await n.ask("youtrackProjectKey",async()=>re(await de({message:"YouTrack project key",placeholder:"DEV",validate:D=>D.trim().length>0?void 0:"required"})).trim()),x=await n.ask("youtrackWrites",async()=>Se(await fn({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let $=n.get("tokens")??{},_=()=>n.set("tokens",$),U=await n.ask("repos",()=>dR($,l,a,{onCred:_,initial:n.get("reposPartial")??[],onProgress:D=>n.set("reposPartial",D)}));n.delete("reposPartial");let G=await pR(await n.ask("contextRepo",()=>dy(m,U,$,l)),m,U,$,l,_,D=>n.set("contextRepo",D)),{spec:P,mode:y}=G,I;v||(N.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),I=await n.ask("assigneeLogin",async()=>re(await de({message:"your YouTrack login (the assignee value)",...T?.login?{initialValue:T.login}:{},validate:D=>D.trim().length>0?void 0:"required"})).trim()));let E=await n.ask("llmProvider",async()=>{for(;;){if(Se(await xt({message:"LLM provider",options:[{value:"claude",label:"Claude",hint:"recommended"},{value:"codex",label:"Codex",hint:"coming soon"}],initialValue:"claude"}))==="claude")return"claude";N.warn("Codex support is coming soon \u2014 pick Claude for now.")}}),C=E==="claude"?await n.ask("claudeToken",()=>ch(ah("claude"),{farm:s==="farm"})):"",O;if(C){let D=await rd(C);if(D){let ce=ul(D);ce&&(O=ce,N.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${ce} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let j={projectId:m,name:g,automationLevel:k,repos:U,trackerProvider:h,youtrackProjectKey:R};N.step(`${y==="attach"?"attaching to":"provisioning"} Context Repo ${P.owner}/${P.name} (${P.host})\u2026`);let S;try{S=await ln(j,P,{...py($),youtrackWrites:x,...T?{trackerUrl:T.url}:{},mode:y,log:{info:D=>N.message(D),warn:D=>N.warn(D)}})}catch(D){oe(`Context Repo provisioning failed: ${D instanceof Error?D.message:String(D)}`)}j.contextRepo=S,N.success(`Context Repo ready: ${S.owner}/${S.name}@${S.branch}`),N.step(`registering project on ${c}\u2026`);let A;try{A=await Nt(c,u,j)}catch(D){if(D instanceof K&&D.status===409){N.warn(`project ${m} already exists on HUB \u2014 reusing it`);try{A=await Q(c,u,m)}catch(ce){throw ce instanceof K&&oe(`HUB \u2192 ${ce.status} ${ce.message}`),ce}}else if(D instanceof K&&D.status===401)n.delete("cliToken"),oe("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(D instanceof K)oe(`HUB \u2192 ${D.status} ${D.message}`);else throw D}let L=A.contextRepo??S;N.success(`project ${A.projectId} ready (${A.provisioningStatus})`);let V=await yR(L),Re=T?{url:T.url,token:T.token}:void 0;if(s==="farm"){let D=d,ce={...$,...V?{contextWrite:V}:{},...C?{claude:{oauthToken:C}}:{},...Re?{youtrack:Re}:{}},Ne=$.github?.token;if(L.host==="github"&&Ne)try{let Z=xm(`devpipe-${m}`);await Sm(L,Ne,Z.publicKey,`devpipe-${m}`),ce.contextSsh={privateKey:Z.privateKey},N.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(Z){N.warn(`could not set up Context Repo SSH deploy key (${Z instanceof Error?Z.message:String(Z)}); the farm will fall back to the token path.`)}let Ke={projectId:m,config:{hubUrl:c,cliToken:u,projectId:m},secrets:ce,contextRepo:L,projectConfig:lt(j,x,T?.url,I||void 0,"auto",E,O)},St=wt(D.farm.publicKey,JSON.stringify(Ke));N.step(`handing project ${m} to farm ${D.farm.name}\u2026`);let q;try{q=await Go(c,u,D.farm.farmId,{projectId:m,sealedBundle:St})}catch(Z){throw Z instanceof K&&oe(Z.status===409?`farm ${D.farm.name} is offline \u2014 start it and re-run.`:Z.status===504?`farm ${D.farm.name} did not respond in time.`:`HUB \u2192 ${Z.status} ${Z.message}`),Z}q.ok||oe(`farm rejected provisioning: ${q.error??"unknown error"}`),await xc(c,u,m,L,Ne,A.repos,null,$),n.clear(),vc(`done. project ${m} is now hosted on farm ${D.farm.name} (daemon ${q.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}fy($),await cy(e,L.cloneUrl,L.branch),uy(e),a&&await uR(e);{let D=hr(e,it);Br(D);let ce=lt(j,x,T?.url,I||void 0,w,E,O),Ne=Ln(D,ce);Ne.length>0&&N.success(`local project config \u2192 .codepipe/{${Ne.join(", ")}}`),dr(m,ce,{info:Ke=>N.message(Ke),warn:Ke=>N.warn(Ke)})}await ly(e,A.repos);let wr={hubUrl:c,cliToken:u,projectId:m,...$,...V?{contextWrite:V}:{},...C?{claude:{oauthToken:C}}:{},...Re?{youtrack:Re}:{}};X(wr),yt({hubUrl:c,cliToken:u,projectId:m,accountEmail:p},m),N.success(`secrets \u2192 ${at(m)}`),await xc(c,u,m,L,$.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,A.repos,e,$),n.clear();let br=`${c}/?project=${encodeURIComponent(m)}`;nr(br),vc(`done. your project on the dashboard (sign in there to work with it):
814
815
  ${br}
815
- starting codepipe \u2014 the CLI daemon, an agent worker, and a command line. type /help for commands; Ctrl+D or /quit to exit (restart anytime with \`codepipe\` from this folder).`);let{replCommand:pt}=await Promise.resolve().then(()=>(mc(),Kh));await pt({})}async function xc(t,e,r,n,o,i=[],s=null,a={}){let c=await vh(n,o),l=!1;if(!c)try{l=await Th(i,{localRoot:s,tokens:a})}catch{l=!1}let u=$h({indexExists:c,localClones:s!==null,reposNonEmpty:l}),p=await oR({message:u.message,options:u.options,initialValues:u.initialValues,required:!1});if(Sc(p))return;let d=new Set(p);if(d.has("map")&&s!==null)try{let f=ye(s);if(!f)throw new Error("workspace not found");let{bootstrapWorkspaceModel:m}=await Promise.resolve().then(()=>(bc(),Qh)),g=await m(f,void 0,{onLog:k=>N.message(k)});N.success(`project map ready: ${g.events} task events mined from history`)}catch(f){N.warn(`could not build the project map: ${f instanceof Error?f.message:String(f)}. Registration is not affected \u2014 run \`codepipe model bootstrap\` later.`)}if(d.has("backfill"))try{let{jobId:f}=await _n(t,e,r,{reindex:!1,backfill:!0});N.success(`retrospective architecture analysis queued (job ${f}); decision drafts will appear on the project card for review once a SANDBOX picks up the job.`)}catch(f){N.warn(`could not start the retrospective analysis: ${f instanceof Error?f.message:String(f)}. Registration is not affected.`)}if(d.has("index"))try{let{jobId:f}=await _n(t,e,r,{reindex:u.reindex});N.success(`indexing queued (job ${f}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(f){N.warn(`could not start indexing: ${f instanceof Error?f.message:String(f)}. You can retry later \u2014 registration is not affected.`)}}async function iR(t,e){let r;try{r=await dd(t,e)}catch(c){throw c instanceof K&&oe(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&oe("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=Se(await xt({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=vi(i.farmId,i.publicKey)}catch(c){oe(c instanceof Error?c.message:String(c))}return Se(await fn({message:`confirm farm ${i.name} cred-channel fingerprint:
816
+ starting codepipe \u2014 the CLI daemon, an agent worker, and a command line. type /help for commands; Ctrl+D or /quit to exit (restart anytime with \`codepipe\` from this folder).`);let{replCommand:pt}=await Promise.resolve().then(()=>(mc(),Kh));await pt({})}async function xc(t,e,r,n,o,i=[],s=null,a={}){let c=await vh(n,o),l=!1;if(!c)try{l=await Th(i,{localRoot:s,tokens:a})}catch{l=!1}let u=$h({indexExists:c,localClones:s!==null,reposNonEmpty:l}),p=await iR({message:u.message,options:u.options,initialValues:u.initialValues,required:!1});if(Sc(p))return;let d=new Set(p);if(d.has("map")&&s!==null)try{let f=ye(s);if(!f)throw new Error("workspace not found");let{bootstrapWorkspaceModel:m}=await Promise.resolve().then(()=>(bc(),Qh)),g=await m(f,void 0,{onLog:k=>N.message(k)});N.success(`project map ready: ${g.events} task events mined from history`)}catch(f){N.warn(`could not build the project map: ${f instanceof Error?f.message:String(f)}. Registration is not affected \u2014 run \`codepipe model bootstrap\` later.`)}if(d.has("backfill"))try{let{jobId:f}=await _n(t,e,r,{reindex:!1,backfill:!0});N.success(`retrospective architecture analysis queued (job ${f}); decision drafts will appear on the project card for review once a SANDBOX picks up the job.`)}catch(f){N.warn(`could not start the retrospective analysis: ${f instanceof Error?f.message:String(f)}. Registration is not affected.`)}if(d.has("index"))try{let{jobId:f}=await _n(t,e,r,{reindex:u.reindex});N.success(`indexing queued (job ${f}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(f){N.warn(`could not start indexing: ${f instanceof Error?f.message:String(f)}. You can retry later \u2014 registration is not affected.`)}}async function sR(t,e){let r;try{r=await dd(t,e)}catch(c){throw c instanceof K&&oe(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&oe("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=Se(await xt({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=vi(i.farmId,i.publicKey)}catch(c){oe(c instanceof Error?c.message:String(c))}return Se(await fn({message:`confirm farm ${i.name} cred-channel fingerprint:
816
817
  ${s}
817
- (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||oe("farm fingerprint not confirmed \u2014 aborting."),$i(i.farmId,s),{farm:i,fingerprint:s}}async function sy(t){oy(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();ay(e,t.force===!0);let r=re(await de({message:"HUB URL",initialValue:W("HUB_URL")??et,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await mn(),{cliToken:o,accountEmail:i}=await gn(r,n);N.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await Q(r,o,t.projectId)}catch(d){throw d instanceof K&&oe(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||oe(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await my(),l={},u=new Set(s.repos.map(d=>d.host));u.add(s.contextRepo.host);for(let d of u){let f=s.repos.find(m=>m.host===d);await Yi(d,l,f?.owner??s.contextRepo.owner,n,f?.repoName)}fy(l),await cy(e,s.contextRepo.cloneUrl,s.contextRepo.branch),uy(e);{let d=hr(e,it);Br(d);let f={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.trackerProvider?{trackerProvider:s.trackerProvider}:{},...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{}},m=lt(f,!0,c?.url,void 0,"auto",s.llmProvider??ot),g=Ln(d,m);g.length>0&&N.success(`local project config \u2192 .codepipe/{${g.join(", ")}} (defaults \u2014 review and adjust)`),dr(t.projectId,m,{info:k=>N.message(k),warn:k=>N.warn(k)})}await ly(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};X(p),yt({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),N.success(`secrets \u2192 ${at(t.projectId)}`),await xc(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),vc("done.")}function ay(t,e){if(!pn(t)){ey(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=rR(t).filter(o=>!r.has(o));n.length!==0&&(e||oe(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function lc(t){if(!pn(hr(t,".git")))return null;try{let r=(await qi(t).remote(["get-url","origin"])||"").toString().trim(),n=r?Fe(r):null;return n?{parsed:n,defaultBranch:await sR(t)}:null}catch{return null}}async function sR(t){let e=qi(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 aR(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Qt.test(e)?e:""}function cR(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function lR(t){let e=hr(t,".gitignore"),r=pn(e)?ty(e,"utf-8"):"";if(cR(r))return;if(!Se(await fn({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){N.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
818
+ (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||oe("farm fingerprint not confirmed \u2014 aborting."),$i(i.farmId,s),{farm:i,fingerprint:s}}async function sy(t){oy(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();ay(e,t.force===!0);let r=re(await de({message:"HUB URL",initialValue:W("HUB_URL")??et,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await mn(),{cliToken:o,accountEmail:i}=await gn(r,n);N.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await Q(r,o,t.projectId)}catch(d){throw d instanceof K&&oe(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||oe(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await my(),l={},u=new Set(s.repos.map(d=>d.host));u.add(s.contextRepo.host);for(let d of u){let f=s.repos.find(m=>m.host===d);await Yi(d,l,f?.owner??s.contextRepo.owner,n,f?.repoName)}fy(l),await cy(e,s.contextRepo.cloneUrl,s.contextRepo.branch),uy(e);{let d=hr(e,it);Br(d);let f={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.trackerProvider?{trackerProvider:s.trackerProvider}:{},...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{}},m=lt(f,!0,c?.url,void 0,"auto",s.llmProvider??ot),g=Ln(d,m);g.length>0&&N.success(`local project config \u2192 .codepipe/{${g.join(", ")}} (defaults \u2014 review and adjust)`),dr(t.projectId,m,{info:k=>N.message(k),warn:k=>N.warn(k)})}await ly(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};X(p),yt({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),N.success(`secrets \u2192 ${at(t.projectId)}`),await xc(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),vc("done.")}function ay(t,e){if(!pn(t)){ey(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=nR(t).filter(o=>!r.has(o));n.length!==0&&(e||oe(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function lc(t){if(!pn(hr(t,".git")))return null;try{let r=(await qi(t).remote(["get-url","origin"])||"").toString().trim(),n=r?Fe(r):null;return n?{parsed:n,defaultBranch:await aR(t)}:null}catch{return null}}async function aR(t){let e=qi(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 cR(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Qt.test(e)?e:""}function lR(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function uR(t){let e=hr(t,".gitignore"),r=pn(e)?ty(e,"utf-8"):"";if(lR(r))return;if(!Se(await fn({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){N.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
818
819
  `)?"":`
819
820
  `;ry(e,r+o+`
820
821
  # codepipe workspace (added by \`codepipe init\`)
@@ -831,30 +832,30 @@ starting codepipe \u2014 the CLI daemon, an agent worker, and a command line. ty
831
832
  `,i=Zh.join(`
832
833
  `)+`
833
834
  `;ry(e,r+o+(r?`
834
- `:"")+i),N.message(`appended runtime entries to ${ny(e)}`)}async function uR(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;N.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await Yi(s.host,t,s.owner,e,s.repoName),i?.();let c=re(await de({message:"repo logical name (used inside Context Repo paths)",placeholder:s.repoName,initialValue:s.repoName,validate:u=>u.trim().length>0?void 0:"required"})).trim(),l=re(await de({message:"default branch",placeholder:a,initialValue:a,validate:u=>u.trim().length>0?void 0:"required"})).trim();o.push({name:c,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:l,mountAs:"."}),n.onProgress?.(o)}for(;Se(await fn({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=re(await de({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:f=>!f||!f.trim()||Fe(f)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!a)continue;let c=Fe(a);N.message(`${c.host}: ${c.owner}/${c.repoName}`),await Yi(c.host,t,c.owner,e,c.repoName),i?.();let l=re(await de({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:f=>f.trim().length>0?void 0:"required"})).trim(),u=re(await de({message:"default branch (optional)",placeholder:"main"})).trim(),p=re(await de({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 dy(t,e,r,n){N.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=Se(await xt({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"&&N.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=re(await de({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:ht(t),validate:u=>{let p=(u??"").trim();if(!p)return"required";if(!Fe(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=Fe(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await pR(),l=re(await de({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=re(await de({message:"Context Repo name",placeholder:ht(t),initialValue:ht(t),validate:p=>p.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:o}}function py(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??jr()}}async function dR(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await Yi(c.host,n,c.owner,o),i?.();let u=Tc();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let p=await uh(c,py(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=Se(await xt({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"&&oe("aborted"),d==="create")return a={spec:c,mode:"create"},s(a),a;a=await dy(e,r,n,o),s(a)}}async function pR(){return Se(await xt({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function ao(t,e){let r=Tc();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 fy(t){Kn(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Gn(t.gitlab?.token??process.env.GITLAB_TOKEN),Hn(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Yi(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await fR(r);i?e.github=i:N.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let i=await mR(r,n,o);i?e.bitbucket=i:N.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 gR();i?e.gitlab=i:N.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function fR(t){for(;;){let e=re(await so({message:`GitHub PAT \u2014 blank to skip
835
+ `:"")+i),N.message(`appended runtime entries to ${ny(e)}`)}async function dR(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;N.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await Yi(s.host,t,s.owner,e,s.repoName),i?.();let c=re(await de({message:"repo logical name (used inside Context Repo paths)",placeholder:s.repoName,initialValue:s.repoName,validate:u=>u.trim().length>0?void 0:"required"})).trim(),l=re(await de({message:"default branch",placeholder:a,initialValue:a,validate:u=>u.trim().length>0?void 0:"required"})).trim();o.push({name:c,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:l,mountAs:"."}),n.onProgress?.(o)}for(;Se(await fn({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=re(await de({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:f=>!f||!f.trim()||Fe(f)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!a)continue;let c=Fe(a);N.message(`${c.host}: ${c.owner}/${c.repoName}`),await Yi(c.host,t,c.owner,e,c.repoName),i?.();let l=re(await de({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:f=>f.trim().length>0?void 0:"required"})).trim(),u=re(await de({message:"default branch (optional)",placeholder:"main"})).trim(),p=re(await de({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 dy(t,e,r,n){N.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=Se(await xt({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"&&N.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=re(await de({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:ht(t),validate:u=>{let p=(u??"").trim();if(!p)return"required";if(!Fe(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=Fe(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await fR(),l=re(await de({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=re(await de({message:"Context Repo name",placeholder:ht(t),initialValue:ht(t),validate:p=>p.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:o}}function py(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??jr()}}async function pR(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await Yi(c.host,n,c.owner,o),i?.();let u=Tc();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let p=await uh(c,py(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=Se(await xt({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"&&oe("aborted"),d==="create")return a={spec:c,mode:"create"},s(a),a;a=await dy(e,r,n,o),s(a)}}async function fR(){return Se(await xt({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function ao(t,e){let r=Tc();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 fy(t){Kn(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Gn(t.gitlab?.token??process.env.GITLAB_TOKEN),Hn(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Yi(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await mR(r);i?e.github=i:N.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let i=await gR(r,n,o);i?e.bitbucket=i:N.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 hR();i?e.gitlab=i:N.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function mR(t){for(;;){let e=re(await so({message:`GitHub PAT \u2014 blank to skip
835
836
  classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
836
837
  fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
837
838
  if org: approve token in org Settings \u2192 Personal access tokens.
838
839
  (Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo;
839
- set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await ao("GitHub",()=>Ct(e,t?{owner:t}:void 0)))return{token:e};N.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function mR(t,e,r){for(N.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
840
+ set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await ao("GitHub",()=>Ct(e,t?{owner:t}:void 0)))return{token:e};N.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function gR(t,e,r){for(N.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
840
841
  How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
841
842
  'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes:
842
843
  read:repository:bitbucket + write:repository:bitbucket +
843
844
  read:pullrequest:bitbucket + write:pullrequest:bitbucket
844
845
  \u2014 write scopes do NOT include read: pick BOTH scopes of each pair
845
846
  (+ admin:repository:bitbucket if this token will provision the Context Repo).
846
- The token is shown ONCE \u2014 copy it right away.`);;){let n=re(await de({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=re(await so({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){N.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await ao("Bitbucket",async()=>{let i=await Et(n,o,t);if(t&&r){let s=await Uo(n,o,t,r);if(s)throw new Error(s)}return i}))return{email:n,apiToken:o};N.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function gR(){for(;;){let t=re(await so({message:`GitLab PAT \u2014 blank to skip
847
- scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await ao("GitLab",()=>It(t))){let e=await Su(t);return e&&N.warn(e),{token:t}}N.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function hR(t){if(Se(await fn({message:`Issue a separate context-write token (scoped to the Context Repo only)?
847
+ The token is shown ONCE \u2014 copy it right away.`);;){let n=re(await de({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=re(await so({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){N.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await ao("Bitbucket",async()=>{let i=await Et(n,o,t);if(t&&r){let s=await Uo(n,o,t,r);if(s)throw new Error(s)}return i}))return{email:n,apiToken:o};N.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function hR(){for(;;){let t=re(await so({message:`GitLab PAT \u2014 blank to skip
848
+ scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await ao("GitLab",()=>It(t))){let e=await Su(t);return e&&N.warn(e),{token:t}}N.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function yR(t){if(Se(await fn({message:`Issue a separate context-write token (scoped to the Context Repo only)?
848
849
  Without it the SANDBOX pushes delivery commits with the project ${t.host}
849
850
  credential. A scoped token hardens setups where the SANDBOX runs outside
850
851
  your trusted network.`,initialValue:!1})))for(t.host==="github"?N.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
851
852
  permissions Contents: Read and write + Workflows: Read and write (Workflows is
852
853
  required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):N.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
853
- (${t.host==="gitlab"?"project access token, 'write_repository' scope":"Bitbucket repository access token, Repositories: Read & write \u2014 the only Bitbucket credential scopeable to a single repo; an account-wide API token would defeat the scoping"}).`);;){let r=re(await so({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await ao("contextWrite",()=>yR(r,t)))return{token:r};N.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function yR(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n;try{n=await fetch(`https://api.github.com/repos/${e.owner}/${e.name}`,{headers:r})}catch(i){throw new Error(`cannot reach api.github.com (${i instanceof Error?i.message:String(i)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the PAT)");if(n.status===404)throw new Error(`token cannot see ${e.owner}/${e.name} (404) \u2014 scope the fine-grained PAT to that repo and approve it in the org, or use a classic PAT with 'repo'`);if(!n.ok)throw new Error(`GitHub \u2192 ${n.status} ${n.statusText}`);let o=await n.json();if(o.permissions&&o.permissions.push===!1)throw new Error(`token has no write access to ${e.owner}/${e.name} \u2014 needs Contents: write`);return o.full_name??`${e.owner}/${e.name}`}async function my(){for(;;){let t=re(await de({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=re(await so({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await ao("YouTrack",()=>_t({baseUrl:t,token:e}))){let r=await Mu({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}N.warn("re-enter the YouTrack URL / token.")}}var Zh,no=b(()=>{"use strict";Ce();F();Be();lh();Fo();Pe();kt();pr();Dr();Bi();Ba();Fi();At();rr();bh();we();xh();Rh();Na();si();ie();Gi();st();Zh=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});F();Ce();Pe();import{Command as JR}from"commander";Co();import{homedir as eu}from"node:os";import{join as tu}from"node:path";function ru(){er(tu(eu(),".devpipe"),tu(eu(),".codepipe"))}Pe();ie();async function gu(t){let e=t.profile??t.project;t.profile&&t.profile!==t.project&&(console.error(`--profile (${t.profile}) must equal --project (${t.project}). Profile id is the project id.`),process.exit(1));let r=qe(e);r&&!t.force&&(console.error(`already configured at ${Pr(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");yt({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...H(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};X(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${Pr(e)}`)}$s();Pe();Ua();we();ie();kt();Fa();st();si();import{homedir as Ka}from"node:os";import{join as zn}from"node:path";async function _m(t={profile:void 0}){let{cfg:e,profile:r}=Po(t.profile),n=H(e.projectId);n&&In(n),Kn(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Gn(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),Hn(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=zn(Ka(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=No("CLI_LOG",i,o);if(s.enabled){let d=new Nr(s);Oo(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=Io(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=zn(Ka(),".codepipe",r?zn("profiles",r,"context"):"context");if(await Us(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await Am(()=>Ci({cfg:e,secrets:n,contextDir:d,log:{info:f=>console.log(f),warn:f=>console.warn(f)}}),{log:{warn:f=>console.warn(f)}}),a||await Us(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let f=zn(Ka(),".codepipe",r?zn("profiles",r,"context-config"):"context-config");Qo(a.contextDir,f,{info:m=>console.log(m),warn:m=>console.warn(m)})}}let l=Ti(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(`
854
- [${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}an();Pe();we();async function nh(t={profile:void 0}){let e=Le(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Ko(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 Q(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=xe(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`)")}no();import{readFileSync as kR}from"node:fs";F();Pe();kt();Bi();pr();At();rr();we();ie();function ue(t){throw new Error(t)}function he(t,e){return(typeof t!="string"||t.trim().length===0)&&ue(`config: '${e}' must be a non-empty string`),t.trim()}function co(t,e){if(t==null)return;typeof t!="string"&&ue(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function wR(t){(!t||typeof t!="object")&&ue("config: expected a JSON object");let e=t,r=he(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||ue("config: 'hubUrl' must start with http(s)://");let n=he(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&ue("config: 'project' is required");let i=o,s=he(i.id,"project.id");Qt.test(s)||ue("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=he(i.name,"project.name"),c=he(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&ue("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||ue("config: 'project.repos' must be an array");let u=l.map((h,v)=>{(!h||typeof h!="object")&&ue(`config: project.repos[${v}] must be an object`);let T=h,R=he(T.host,`project.repos[${v}].host`);R!=="github"&&R!=="bitbucket"&&R!=="gitlab"&&ue(`config: project.repos[${v}].host must be 'github', 'bitbucket' or 'gitlab'`);let x={name:he(T.name,`project.repos[${v}].name`),host:R,owner:he(T.owner,`project.repos[${v}].owner`),repoName:he(T.repoName,`project.repos[${v}].repoName`)},$=co(T.defaultBranch,`project.repos[${v}].defaultBranch`);$&&(x.defaultBranch=$);let _=co(T.mountAs,`project.repos[${v}].mountAs`);return _&&(x.mountAs=_),x}),p=i.contextRepo;(!p||typeof p!="object")&&ue("config: 'project.contextRepo' is required");let d=p,f=co(d.host,"project.contextRepo.host")??"github";f!=="github"&&f!=="bitbucket"&&f!=="gitlab"&&ue("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let m={host:f,owner:he(d.owner,"project.contextRepo.owner"),name:co(d.name,"project.contextRepo.name")??ht(s)},g={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:m}},k=co(i.youtrackProjectKey,"project.youtrackProjectKey");if(k&&(g.project.youtrackProjectKey=k),i.index!==void 0&&(typeof i.index!="boolean"&&ue("config: 'project.index' must be a boolean"),g.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&ue("config: 'project.youtrackWrites' must be a boolean"),g.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let h=he(i.llmProvider,"project.llmProvider");h==="codex"&&ue(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),h!=="claude"&&ue("config: 'project.llmProvider' must be 'claude'"),g.project.llmProvider=h}let w=e.secrets;if(w!==void 0){(typeof w!="object"||w===null)&&ue("config: 'secrets' must be an object");let h=w,v={};if(h.github){let T=h.github;v.github={token:he(T.token,"secrets.github.token")}}if(h.bitbucket){let T=h.bitbucket;v.bitbucket={email:he(T.email,"secrets.bitbucket.email"),apiToken:he(T.apiToken,"secrets.bitbucket.apiToken")}}if(h.gitlab){let T=h.gitlab;v.gitlab={token:he(T.token,"secrets.gitlab.token")}}if(h.youtrack){let T=h.youtrack;v.youtrack={url:he(T.url,"secrets.youtrack.url").replace(/\/$/,""),token:he(T.token,"secrets.youtrack.token")}}if(h.contextWrite){let T=h.contextWrite;v.contextWrite={token:he(T.token,"secrets.contextWrite.token")}}g.secrets=v}return g}async function bR(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function $R(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await Ct(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 Et(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await Uo(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 It(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await _t({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function gy(t){let e=!t.configPath||t.configPath==="-"?await bR():kR(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){ue(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=wR(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 $R(n));let a={projectId:s.id,name:s.name,automationLevel:s.automationLevel,repos:s.repos};s.youtrackProjectKey&&(a.youtrackProjectKey=s.youtrackProjectKey),console.log(`provisioning Context Repo ${s.contextRepo.owner}/${s.contextRepo.name} (${s.contextRepo.host})\u2026`);let c=n.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,l;try{l=await ln(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??jr(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){ue(`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 Nt(o,i,a)}catch(d){if(d instanceof K&&d.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await Q(o,i,s.id);else if(d instanceof K)ue(`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(X(p),yt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${at(s.id)}`),dr(s.id,lt(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,"auto",s.llmProvider??ot),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await _n(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`)}Pe();ie();import{cancel as hy,intro as yy,isCancel as ky,log as Rc,outro as vR,password as wy}from"@clack/prompts";async function xR(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function by(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await xR(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){yy("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Rc.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await wy({message:"Claude OAuth token"});ky(i)&&(hy("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),mu({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${jo()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Le(t.profile);if(!e){yy(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Rc.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await wy({message:"Claude OAuth token"});ky(i)&&(hy("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=H(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},X(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Rc.success("Claude OAuth token saved."),vR("It will be sealed into job bundles when a SANDBOX (re)connects."))}bc();F();Pe();kt();Bi();pr();Fi();we();ie();import{cancel as SR,confirm as TR,intro as RR,isCancel as $y,log as Te,outro as CR,select as vy,text as qt}from"@clack/prompts";function xy(t){SR(t),process.exit(1)}function hn(t){return $y(t)&&xy("aborted"),t}function lo(t){return $y(t)&&xy("aborted"),typeof t=="string"?t:""}async function ER(t,e){let r=hn(await vy({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=lo(await qt({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=lo(await qt({message:"Context Repo name",placeholder:ht(t),initialValue:ht(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function Sy(t={profile:void 0}){let e=Le(t.profile);RR(`codepipe project add \u2192 ${e.hubUrl}`);let r=hn(await qt({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>Qt.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=hn(await qt({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=hn(await vy({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=hn(await qt({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=hn(await TR({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=lo(await qt({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:w=>!w||!w.trim()||Fe(w)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!d)break;let f=Fe(d);Te.message(`${f.host}: ${f.owner}/${f.repoName}`);let m=lo(await qt({message:"repo logical name (used inside Context Repo paths)",placeholder:f.repoName,initialValue:f.repoName,validate:w=>w.trim().length>0?void 0:"required"})).trim(),g=lo(await qt({message:"default branch (optional)",placeholder:"main"})).trim(),k={name:m,host:f.host,owner:f.owner,repoName:f.repoName};g&&(k.defaultBranch=g),a.push(k)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await ER(r,a),u=H(e.projectId);Te.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await ln(c,l,{githubToken:u?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:u?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:u?.bitbucket??jr(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:d=>Te.message(d),warn:d=>Te.warn(d)}})}catch(d){Te.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,Te.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await Nt(e.hubUrl,e.cliToken,c);Te.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),dr(r,lt(c,s,u?.youtrack?.url),{info:f=>Te.message(f),warn:f=>Te.warn(f)}),d.contextRepo&&(Te.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),Te.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&Te.error(` error: ${d.provisioningError}`),CR("done")}catch(d){d instanceof K?(Te.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&Te.message(JSON.stringify(d.payload,null,2))):Te.error(d instanceof Error?d.message:String(d)),process.exit(1)}}an();Pe();we();ie();st();no();import{existsSync as IR,rmSync as AR}from"node:fs";import{confirm as PR,intro as _R,isCancel as jR,log as Vt,outro as NR,spinner as OR}from"@clack/prompts";function dt(t){Vt.error(t),process.exit(1)}var Ty=t=>t.trim().replace(/\/+$/,"");async function Ry(t){_R("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??ye()?.spec.projectId??void 0;e||dt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=qe(e);r||dt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Ty(r.hubUrl),o=r.projectId,i=Ty(t.hub);i.startsWith("http")||dt("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&dt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let w=OR();w.start(`reading project ${o} from ${n}\u2026`);try{l=await Q(n,r.cliToken,o),w.stop(`read project ${o} (${l.name})`)}catch(h){throw w.stop("could not read the source project",1),h instanceof K&&dt(`source HUB ${n} \u2192 ${h.status} ${h.message}. The source HUB must be reachable with a valid token to move a project.`),h}}l.contextRepo||dt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=H(o),p=(t.account??r.accountEmail??await mn()).trim().toLowerCase();if(Vt.message(`move project '${o}'
854
+ (${t.host==="gitlab"?"project access token, 'write_repository' scope":"Bitbucket repository access token, Repositories: Read & write \u2014 the only Bitbucket credential scopeable to a single repo; an account-wide API token would defeat the scoping"}).`);;){let r=re(await so({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await ao("contextWrite",()=>kR(r,t)))return{token:r};N.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function kR(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n;try{n=await fetch(`https://api.github.com/repos/${e.owner}/${e.name}`,{headers:r})}catch(i){throw new Error(`cannot reach api.github.com (${i instanceof Error?i.message:String(i)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the PAT)");if(n.status===404)throw new Error(`token cannot see ${e.owner}/${e.name} (404) \u2014 scope the fine-grained PAT to that repo and approve it in the org, or use a classic PAT with 'repo'`);if(!n.ok)throw new Error(`GitHub \u2192 ${n.status} ${n.statusText}`);let o=await n.json();if(o.permissions&&o.permissions.push===!1)throw new Error(`token has no write access to ${e.owner}/${e.name} \u2014 needs Contents: write`);return o.full_name??`${e.owner}/${e.name}`}async function my(){for(;;){let t=re(await de({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=re(await so({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await ao("YouTrack",()=>_t({baseUrl:t,token:e}))){let r=await Mu({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}N.warn("re-enter the YouTrack URL / token.")}}var Zh,no=b(()=>{"use strict";Ce();F();Be();lh();Fo();Pe();kt();pr();Dr();Bi();Ba();Fi();At();rr();bh();we();xh();Rh();Na();si();ie();Gi();st();Zh=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});F();Ce();Pe();import{Command as XR}from"commander";Co();import{homedir as eu}from"node:os";import{join as tu}from"node:path";function ru(){er(tu(eu(),".devpipe"),tu(eu(),".codepipe"))}Pe();ie();async function gu(t){let e=t.profile??t.project;t.profile&&t.profile!==t.project&&(console.error(`--profile (${t.profile}) must equal --project (${t.project}). Profile id is the project id.`),process.exit(1));let r=qe(e);r&&!t.force&&(console.error(`already configured at ${Pr(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");yt({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...H(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};X(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${Pr(e)}`)}$s();Pe();Ua();we();ie();kt();Fa();st();si();import{homedir as Ka}from"node:os";import{join as zn}from"node:path";async function _m(t={profile:void 0}){let{cfg:e,profile:r}=Po(t.profile),n=H(e.projectId);n&&In(n),Kn(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Gn(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),Hn(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=zn(Ka(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=No("CLI_LOG",i,o);if(s.enabled){let d=new Nr(s);Oo(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=Io(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=zn(Ka(),".codepipe",r?zn("profiles",r,"context"):"context");if(await Us(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await Am(()=>Ci({cfg:e,secrets:n,contextDir:d,log:{info:f=>console.log(f),warn:f=>console.warn(f)}}),{log:{warn:f=>console.warn(f)}}),a||await Us(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let f=zn(Ka(),".codepipe",r?zn("profiles",r,"context-config"):"context-config");Qo(a.contextDir,f,{info:m=>console.log(m),warn:m=>console.warn(m)})}}let l=Ti(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(`
855
+ [${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}an();Pe();we();async function nh(t={profile:void 0}){let e=Le(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Ko(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 Q(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=xe(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`)")}no();import{readFileSync as wR}from"node:fs";F();Pe();kt();Bi();pr();At();rr();we();ie();function ue(t){throw new Error(t)}function he(t,e){return(typeof t!="string"||t.trim().length===0)&&ue(`config: '${e}' must be a non-empty string`),t.trim()}function co(t,e){if(t==null)return;typeof t!="string"&&ue(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function bR(t){(!t||typeof t!="object")&&ue("config: expected a JSON object");let e=t,r=he(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||ue("config: 'hubUrl' must start with http(s)://");let n=he(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&ue("config: 'project' is required");let i=o,s=he(i.id,"project.id");Qt.test(s)||ue("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=he(i.name,"project.name"),c=he(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&ue("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||ue("config: 'project.repos' must be an array");let u=l.map((h,v)=>{(!h||typeof h!="object")&&ue(`config: project.repos[${v}] must be an object`);let T=h,R=he(T.host,`project.repos[${v}].host`);R!=="github"&&R!=="bitbucket"&&R!=="gitlab"&&ue(`config: project.repos[${v}].host must be 'github', 'bitbucket' or 'gitlab'`);let x={name:he(T.name,`project.repos[${v}].name`),host:R,owner:he(T.owner,`project.repos[${v}].owner`),repoName:he(T.repoName,`project.repos[${v}].repoName`)},$=co(T.defaultBranch,`project.repos[${v}].defaultBranch`);$&&(x.defaultBranch=$);let _=co(T.mountAs,`project.repos[${v}].mountAs`);return _&&(x.mountAs=_),x}),p=i.contextRepo;(!p||typeof p!="object")&&ue("config: 'project.contextRepo' is required");let d=p,f=co(d.host,"project.contextRepo.host")??"github";f!=="github"&&f!=="bitbucket"&&f!=="gitlab"&&ue("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let m={host:f,owner:he(d.owner,"project.contextRepo.owner"),name:co(d.name,"project.contextRepo.name")??ht(s)},g={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:m}},k=co(i.youtrackProjectKey,"project.youtrackProjectKey");if(k&&(g.project.youtrackProjectKey=k),i.index!==void 0&&(typeof i.index!="boolean"&&ue("config: 'project.index' must be a boolean"),g.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&ue("config: 'project.youtrackWrites' must be a boolean"),g.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let h=he(i.llmProvider,"project.llmProvider");h==="codex"&&ue(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),h!=="claude"&&ue("config: 'project.llmProvider' must be 'claude'"),g.project.llmProvider=h}let w=e.secrets;if(w!==void 0){(typeof w!="object"||w===null)&&ue("config: 'secrets' must be an object");let h=w,v={};if(h.github){let T=h.github;v.github={token:he(T.token,"secrets.github.token")}}if(h.bitbucket){let T=h.bitbucket;v.bitbucket={email:he(T.email,"secrets.bitbucket.email"),apiToken:he(T.apiToken,"secrets.bitbucket.apiToken")}}if(h.gitlab){let T=h.gitlab;v.gitlab={token:he(T.token,"secrets.gitlab.token")}}if(h.youtrack){let T=h.youtrack;v.youtrack={url:he(T.url,"secrets.youtrack.url").replace(/\/$/,""),token:he(T.token,"secrets.youtrack.token")}}if(h.contextWrite){let T=h.contextWrite;v.contextWrite={token:he(T.token,"secrets.contextWrite.token")}}g.secrets=v}return g}async function $R(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function vR(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await Ct(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 Et(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await Uo(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 It(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await _t({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function gy(t){let e=!t.configPath||t.configPath==="-"?await $R():wR(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){ue(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=bR(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 vR(n));let a={projectId:s.id,name:s.name,automationLevel:s.automationLevel,repos:s.repos};s.youtrackProjectKey&&(a.youtrackProjectKey=s.youtrackProjectKey),console.log(`provisioning Context Repo ${s.contextRepo.owner}/${s.contextRepo.name} (${s.contextRepo.host})\u2026`);let c=n.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,l;try{l=await ln(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??jr(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){ue(`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 Nt(o,i,a)}catch(d){if(d instanceof K&&d.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await Q(o,i,s.id);else if(d instanceof K)ue(`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(X(p),yt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${at(s.id)}`),dr(s.id,lt(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,"auto",s.llmProvider??ot),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await _n(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`)}Pe();ie();import{cancel as hy,intro as yy,isCancel as ky,log as Rc,outro as xR,password as wy}from"@clack/prompts";async function SR(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function by(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await SR(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){yy("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Rc.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await wy({message:"Claude OAuth token"});ky(i)&&(hy("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),mu({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${jo()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Le(t.profile);if(!e){yy(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Rc.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await wy({message:"Claude OAuth token"});ky(i)&&(hy("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=H(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},X(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Rc.success("Claude OAuth token saved."),xR("It will be sealed into job bundles when a SANDBOX (re)connects."))}bc();F();Pe();kt();Bi();pr();Fi();we();ie();import{cancel as TR,confirm as RR,intro as CR,isCancel as $y,log as Te,outro as ER,select as vy,text as qt}from"@clack/prompts";function xy(t){TR(t),process.exit(1)}function hn(t){return $y(t)&&xy("aborted"),t}function lo(t){return $y(t)&&xy("aborted"),typeof t=="string"?t:""}async function IR(t,e){let r=hn(await vy({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=lo(await qt({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=lo(await qt({message:"Context Repo name",placeholder:ht(t),initialValue:ht(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function Sy(t={profile:void 0}){let e=Le(t.profile);CR(`codepipe project add \u2192 ${e.hubUrl}`);let r=hn(await qt({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>Qt.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=hn(await qt({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=hn(await vy({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=hn(await qt({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=hn(await RR({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=lo(await qt({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:w=>!w||!w.trim()||Fe(w)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!d)break;let f=Fe(d);Te.message(`${f.host}: ${f.owner}/${f.repoName}`);let m=lo(await qt({message:"repo logical name (used inside Context Repo paths)",placeholder:f.repoName,initialValue:f.repoName,validate:w=>w.trim().length>0?void 0:"required"})).trim(),g=lo(await qt({message:"default branch (optional)",placeholder:"main"})).trim(),k={name:m,host:f.host,owner:f.owner,repoName:f.repoName};g&&(k.defaultBranch=g),a.push(k)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await IR(r,a),u=H(e.projectId);Te.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await ln(c,l,{githubToken:u?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:u?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:u?.bitbucket??jr(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:d=>Te.message(d),warn:d=>Te.warn(d)}})}catch(d){Te.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,Te.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await Nt(e.hubUrl,e.cliToken,c);Te.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),dr(r,lt(c,s,u?.youtrack?.url),{info:f=>Te.message(f),warn:f=>Te.warn(f)}),d.contextRepo&&(Te.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),Te.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&Te.error(` error: ${d.provisioningError}`),ER("done")}catch(d){d instanceof K?(Te.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&Te.message(JSON.stringify(d.payload,null,2))):Te.error(d instanceof Error?d.message:String(d)),process.exit(1)}}an();Pe();we();ie();st();no();import{existsSync as AR,rmSync as PR}from"node:fs";import{confirm as _R,intro as jR,isCancel as NR,log as Vt,outro as OR,spinner as DR}from"@clack/prompts";function dt(t){Vt.error(t),process.exit(1)}var Ty=t=>t.trim().replace(/\/+$/,"");async function Ry(t){jR("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??ye()?.spec.projectId??void 0;e||dt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=qe(e);r||dt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Ty(r.hubUrl),o=r.projectId,i=Ty(t.hub);i.startsWith("http")||dt("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&dt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let w=DR();w.start(`reading project ${o} from ${n}\u2026`);try{l=await Q(n,r.cliToken,o),w.stop(`read project ${o} (${l.name})`)}catch(h){throw w.stop("could not read the source project",1),h instanceof K&&dt(`source HUB ${n} \u2192 ${h.status} ${h.message}. The source HUB must be reachable with a valid token to move a project.`),h}}l.contextRepo||dt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=H(o),p=(t.account??r.accountEmail??await mn()).trim().toLowerCase();if(Vt.message(`move project '${o}'
855
856
  from : ${n} (profile ${e})
856
857
  to : ${i} (profile ${s}, project ${a}, account ${p})
857
858
  \u2022 the source registration on the old HUB is left intact (non-destructive)
858
859
  \u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
859
- `+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let w=await PR({message:"Continue?",initialValue:!0});(jR(w)||!w)&&dt("aborted")}!c&&a===o&&Vt.warn(`source and destination share the same project id, so they share one secrets file (${at(a)}). Running both profiles at the same time will conflict \u2014 pass --project <newId> for a parallel setup, or keep only one active.`);let{cliToken:d,accountEmail:f}=await gn(i,p),m={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:f,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};Vt.step(`registering project on ${i}\u2026`);let g;try{g=await Nt(i,d,m)}catch(w){if(w instanceof K&&w.status===409){Vt.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{g=await Q(i,d,a)}catch(h){throw h instanceof K&&dt(`target HUB \u2192 ${h.status} ${h.message}`),h}}else if(w instanceof K&&w.status===403)dt(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(w instanceof K)dt(`target HUB \u2192 ${w.status} ${w.message}`);else throw w}Vt.success(`project ${g.projectId} ready on ${i} (${g.provisioningStatus})`),yt({hubUrl:i,cliToken:d,projectId:a,accountEmail:f},s);let k={...u??{},hubUrl:i,cliToken:d,projectId:a};if(delete k.sandboxPins,X(k),Vt.success(`profile '${s}' \u2192 ${at(a)}`),c){let w=Qe(s);IR(w)&&(AR(w),Vt.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}NR(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}Pe();sa();Fi();we();Lr();ie();st();import{existsSync as Cc,rmSync as DR,statSync as LR}from"node:fs";import{join as Vi,relative as MR,resolve as UR}from"node:path";import{cancel as BR,intro as Ey,isCancel as FR,log as pe,outro as Iy,text as yr}from"@clack/prompts";import{simpleGit as Ay}from"simple-git";function je(t){BR(t),process.exit(1)}function kr(t){return FR(t)&&je("aborted"),typeof t=="string"?t:""}async function Cy(t){try{let e=await Ay(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function KR(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function GR(t,e){let r=H(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(KR(r,e)){pe.message(`reusing existing ${e} credentials`);return}if(pe.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=kr(await yr({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=kr(await yr({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=kr(await yr({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}}X(r),pe.success(`saved ${e} credentials`)}async function Py(t){let e=Le(t.profile);Ey(`codepipe repo add \u2192 project ${e.projectId}`);let r=ye()??void 0,n;try{n=(await Q(e.hubUrl,e.cliToken,e.projectId)).repos}catch(h){je(`could not read project from HUB: ${h instanceof Error?h.message:String(h)}`)}let o=t.target?.trim();if(!o){let h=await Cy(process.cwd());h?(o=process.cwd(),pe.message(`using the current directory (${h})`)):o=kr(await yr({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:v=>v.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(Cc(o)&&LR(o).isDirectory()){i=UR(o);let h=await Cy(i);h||je(`${i} is not a git repository (no origin remote)`);let v=Fe(h);v||je(`origin ${h} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=v,s=h,pe.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let h=Fe(o);h||je(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=h,s=o,pe.message(`${a}: ${c}/${l}`)}let u=kr(await yr({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:h=>h.trim()?void 0:"required"})).trim();n.some(h=>h.name===u)&&je(`a repo named "${u}" is already registered`);let p=kr(await yr({message:"default branch (optional)",placeholder:"main"})).trim(),d=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let h=MR(r.root,i);d=h===""?".":h}let f=kr(await yr({message:"mount_as (directory relative to the workspace root)",placeholder:d,initialValue:d})).trim()||d;n.some(h=>(h.mountAs??h.name)===f)&&je(`mount_as "${f}" is already used by another repo`),await GR(e,a);let m={name:u,host:a,owner:c,repoName:l,mountAs:f,...p?{defaultBranch:p}:{}};if(!i){let h=r?Vi(r.root,f):ve(e.projectId,u);if(Cc(Vi(h,".git")))pe.message(`already cloned at ${h}`);else{pe.info(`cloning ${s} \u2192 ${h} \u2026`);try{await Ay().clone(s,h),pe.success(`cloned into ${h}`)}catch(v){je(`clone failed: ${v instanceof Error?v.message.trim():String(v)}
860
- check that your ${a} credentials grant read access to ${c}/${l}`)}}}let g;try{g=await xd(e.hubUrl,e.cliToken,e.projectId,m)}catch(h){h instanceof K&&je(`HUB \u2192 ${h.status} ${h.message}`),je(h instanceof Error?h.message:String(h))}let{updated:k,errors:w}=Fn(e.projectId,g.repos,r?.contextDir);for(let h of k)pe.message(`updated ${h}`);for(let h of w)pe.warn(`could not update ${h.path}: ${h.error}`);pe.success(`added "${u}" \u2014 project now has ${g.repos.length} repo(s)`),Iy("done")}async function _y(t){let e=Le(t.profile);Ey(`codepipe repo remove \u2192 project ${e.projectId}`);let r=ye()??void 0,n;try{let c=(await Q(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 Sd(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof K&&(a.status===404&&je(`no repo named "${t.name}" in this project`),je(`HUB \u2192 ${a.status} ${a.message}`)),je(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=Fn(e.projectId,o.repos,r?.contextDir);for(let a of i)pe.message(`updated ${a}`);for(let a of s)pe.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")pe.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?Vi(r.root,n):ve(e.projectId,t.name);if(Cc(Vi(a,".git")))try{DR(a,{recursive:!0,force:!0}),pe.message(`deleted local clone ${a}`)}catch(c){pe.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else pe.message(`no local clone found to purge (${a})`)}pe.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),Iy("done")}async function jy(t){let e=Le(t.profile),r;try{r=(await Q(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}`)}}Gi();cc();mc();an();F();Ce();an();Pe();we();no();import{hostname as HR}from"node:os";import{cancel as WR,confirm as Ny,intro as YR,isCancel as Ly,log as yn,multiselect as qR,outro as Oy,password as VR,select as Ec,text as Ic}from"@clack/prompts";function uo(t){WR(t),process.exit(1)}function kn(t){return Ly(t)&&uo("aborted"),t}function zi(t){return Ly(t)&&uo("aborted"),typeof t=="string"?t:""}function Ji(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Dy(t,e){try{let{secret:r}=await Ho(t,e);return r}catch(r){throw r instanceof K&&r.status===404&&uo("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 zR(t,e){if(kn(await Ec({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 Ls(t,e);if(o.length>0)return kn(await qR({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}));yn.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){yn.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return zi(await Ic({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 Ac(t){YR("codepipe worker \u2014 set up this machine as a runner");let e=xe(t.profile);e&&(yn.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),kn(await Ny({message:"re-register this worker?",initialValue:!1}))||uo("keeping the existing registration"));let r=qe(t.profile)??qe(),n=zi(await Ic({message:"HUB URL",placeholder:et,initialValue:W("HUB_URL")??r?.hubUrl??et,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=kn(await Ec({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 Dy(n,a),yn.success("account-issued registration token minted");else if(i==="login"){let d=await mn();a=(await gn(n,d)).cliToken,s=await Dy(n,a),yn.success("account-issued registration token minted")}else s=zi(await VR({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||uo("a registration token is required");let c=await zR(n,a),l=zi(await Ic({message:"worker name",initialValue:HR(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=kn(await Ec({message:"agent backend",options:[{value:"claude-headless",label:"claude-headless \u2014 Claude Code on PATH (the real thing)"},{value:"mock",label:"mock \u2014 deterministic stub (development)"},{value:"",label:"none \u2014 this worker will not claim agent jobs"}],initialValue:"claude-headless"}));if(await mr({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),yn.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!kn(await Ny({message:"start the claim-loop now?",initialValue:!0}))){Oy("registered. start later with `codepipe worker`.");return}Oy("starting the claim-loop\u2026"),await eo(t.profile?{profile:t.profile}:{})}function XR(){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 W("PROFILE")}var ae=XR();Zl(ae);ru();var Ae=new JR;Ae.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Oe).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{Ji()?await fc({profile:ae}):await ac({profile:ae})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ae.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 gy({configPath:t.config,skipVerify:t.skipVerify===!0}):await iy({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ae.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 gu({...t,profile:ae})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ae.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 sy({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Ae.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await _m({profile:ae})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ae.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 Ph({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ae.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 by({profile:ae,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ae.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await nh({profile:ae})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ae.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).action(async t=>{try{await ac({profile:ae,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var My=Ae.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");My.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??W("HUB_URL")??qe(ae)?.hubUrl??et,r=t.token??W("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Ji()){await Ac({profile:ae});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=W("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??W("WORKER_NAME"),i=t.llm??W("WORKER_LLM");await mr({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...ae?{profile:ae}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});My.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!xe(ae)&&Ji()){await Ac({profile:ae});return}await eo(ae?{profile:ae}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Uy=Ae.command("project").description("Manage CodePipe projects");Uy.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Sy({profile:ae})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Uy.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 Ry({...t,cliProfile:ae})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Pc=Ae.command("repo").description("Manage the project's git repositories");Pc.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 Py({profile:ae,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Pc.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 _y({profile:ae,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Pc.command("list").description("List the project's repos").action(async()=>{try{await jy({profile:ae})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var By=Ae.command("model").description("Project map (model/ in the Context Repo)");By.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 kc({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});By.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 wc({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ae.parseAsync();
860
+ `+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let w=await _R({message:"Continue?",initialValue:!0});(NR(w)||!w)&&dt("aborted")}!c&&a===o&&Vt.warn(`source and destination share the same project id, so they share one secrets file (${at(a)}). Running both profiles at the same time will conflict \u2014 pass --project <newId> for a parallel setup, or keep only one active.`);let{cliToken:d,accountEmail:f}=await gn(i,p),m={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:f,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};Vt.step(`registering project on ${i}\u2026`);let g;try{g=await Nt(i,d,m)}catch(w){if(w instanceof K&&w.status===409){Vt.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{g=await Q(i,d,a)}catch(h){throw h instanceof K&&dt(`target HUB \u2192 ${h.status} ${h.message}`),h}}else if(w instanceof K&&w.status===403)dt(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(w instanceof K)dt(`target HUB \u2192 ${w.status} ${w.message}`);else throw w}Vt.success(`project ${g.projectId} ready on ${i} (${g.provisioningStatus})`),yt({hubUrl:i,cliToken:d,projectId:a,accountEmail:f},s);let k={...u??{},hubUrl:i,cliToken:d,projectId:a};if(delete k.sandboxPins,X(k),Vt.success(`profile '${s}' \u2192 ${at(a)}`),c){let w=Qe(s);AR(w)&&(PR(w),Vt.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}OR(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}Pe();sa();Fi();we();Lr();ie();st();import{existsSync as Cc,rmSync as LR,statSync as MR}from"node:fs";import{join as Vi,relative as UR,resolve as BR}from"node:path";import{cancel as FR,intro as Ey,isCancel as KR,log as pe,outro as Iy,text as yr}from"@clack/prompts";import{simpleGit as Ay}from"simple-git";function je(t){FR(t),process.exit(1)}function kr(t){return KR(t)&&je("aborted"),typeof t=="string"?t:""}async function Cy(t){try{let e=await Ay(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function GR(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function HR(t,e){let r=H(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(GR(r,e)){pe.message(`reusing existing ${e} credentials`);return}if(pe.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=kr(await yr({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=kr(await yr({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=kr(await yr({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}}X(r),pe.success(`saved ${e} credentials`)}async function Py(t){let e=Le(t.profile);Ey(`codepipe repo add \u2192 project ${e.projectId}`);let r=ye()??void 0,n;try{n=(await Q(e.hubUrl,e.cliToken,e.projectId)).repos}catch(h){je(`could not read project from HUB: ${h instanceof Error?h.message:String(h)}`)}let o=t.target?.trim();if(!o){let h=await Cy(process.cwd());h?(o=process.cwd(),pe.message(`using the current directory (${h})`)):o=kr(await yr({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:v=>v.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(Cc(o)&&MR(o).isDirectory()){i=BR(o);let h=await Cy(i);h||je(`${i} is not a git repository (no origin remote)`);let v=Fe(h);v||je(`origin ${h} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=v,s=h,pe.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let h=Fe(o);h||je(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=h,s=o,pe.message(`${a}: ${c}/${l}`)}let u=kr(await yr({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:h=>h.trim()?void 0:"required"})).trim();n.some(h=>h.name===u)&&je(`a repo named "${u}" is already registered`);let p=kr(await yr({message:"default branch (optional)",placeholder:"main"})).trim(),d=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let h=UR(r.root,i);d=h===""?".":h}let f=kr(await yr({message:"mount_as (directory relative to the workspace root)",placeholder:d,initialValue:d})).trim()||d;n.some(h=>(h.mountAs??h.name)===f)&&je(`mount_as "${f}" is already used by another repo`),await HR(e,a);let m={name:u,host:a,owner:c,repoName:l,mountAs:f,...p?{defaultBranch:p}:{}};if(!i){let h=r?Vi(r.root,f):ve(e.projectId,u);if(Cc(Vi(h,".git")))pe.message(`already cloned at ${h}`);else{pe.info(`cloning ${s} \u2192 ${h} \u2026`);try{await Ay().clone(s,h),pe.success(`cloned into ${h}`)}catch(v){je(`clone failed: ${v instanceof Error?v.message.trim():String(v)}
861
+ check that your ${a} credentials grant read access to ${c}/${l}`)}}}let g;try{g=await xd(e.hubUrl,e.cliToken,e.projectId,m)}catch(h){h instanceof K&&je(`HUB \u2192 ${h.status} ${h.message}`),je(h instanceof Error?h.message:String(h))}let{updated:k,errors:w}=Fn(e.projectId,g.repos,r?.contextDir);for(let h of k)pe.message(`updated ${h}`);for(let h of w)pe.warn(`could not update ${h.path}: ${h.error}`);pe.success(`added "${u}" \u2014 project now has ${g.repos.length} repo(s)`),Iy("done")}async function _y(t){let e=Le(t.profile);Ey(`codepipe repo remove \u2192 project ${e.projectId}`);let r=ye()??void 0,n;try{let c=(await Q(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 Sd(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof K&&(a.status===404&&je(`no repo named "${t.name}" in this project`),je(`HUB \u2192 ${a.status} ${a.message}`)),je(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=Fn(e.projectId,o.repos,r?.contextDir);for(let a of i)pe.message(`updated ${a}`);for(let a of s)pe.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")pe.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?Vi(r.root,n):ve(e.projectId,t.name);if(Cc(Vi(a,".git")))try{LR(a,{recursive:!0,force:!0}),pe.message(`deleted local clone ${a}`)}catch(c){pe.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else pe.message(`no local clone found to purge (${a})`)}pe.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),Iy("done")}async function jy(t){let e=Le(t.profile),r;try{r=(await Q(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}`)}}Gi();cc();mc();an();F();Ce();an();Pe();we();no();import{hostname as WR}from"node:os";import{cancel as YR,confirm as Ny,intro as qR,isCancel as Ly,log as yn,multiselect as VR,outro as Oy,password as zR,select as Ec,text as Ic}from"@clack/prompts";function uo(t){YR(t),process.exit(1)}function kn(t){return Ly(t)&&uo("aborted"),t}function zi(t){return Ly(t)&&uo("aborted"),typeof t=="string"?t:""}function Ji(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Dy(t,e){try{let{secret:r}=await Ho(t,e);return r}catch(r){throw r instanceof K&&r.status===404&&uo("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 JR(t,e){if(kn(await Ec({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 Ls(t,e);if(o.length>0)return kn(await VR({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}));yn.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){yn.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return zi(await Ic({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 Ac(t){qR("codepipe worker \u2014 set up this machine as a runner");let e=xe(t.profile);e&&(yn.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),kn(await Ny({message:"re-register this worker?",initialValue:!1}))||uo("keeping the existing registration"));let r=qe(t.profile)??qe(),n=zi(await Ic({message:"HUB URL",placeholder:et,initialValue:W("HUB_URL")??r?.hubUrl??et,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=kn(await Ec({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 Dy(n,a),yn.success("account-issued registration token minted");else if(i==="login"){let d=await mn();a=(await gn(n,d)).cliToken,s=await Dy(n,a),yn.success("account-issued registration token minted")}else s=zi(await zR({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||uo("a registration token is required");let c=await JR(n,a),l=zi(await Ic({message:"worker name",initialValue:WR(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=kn(await Ec({message:"agent backend",options:[{value:"claude-headless",label:"claude-headless \u2014 Claude Code on PATH (the real thing)"},{value:"mock",label:"mock \u2014 deterministic stub (development)"},{value:"",label:"none \u2014 this worker will not claim agent jobs"}],initialValue:"claude-headless"}));if(await mr({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),yn.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!kn(await Ny({message:"start the claim-loop now?",initialValue:!0}))){Oy("registered. start later with `codepipe worker`.");return}Oy("starting the claim-loop\u2026"),await eo(t.profile?{profile:t.profile}:{})}function QR(){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 W("PROFILE")}var ae=QR();Zl(ae);ru();var Ae=new XR;Ae.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Oe).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{Ji()?await fc({profile:ae}):await ac({profile:ae})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ae.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 gy({configPath:t.config,skipVerify:t.skipVerify===!0}):await iy({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ae.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 gu({...t,profile:ae})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ae.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 sy({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Ae.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await _m({profile:ae})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ae.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 Ph({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ae.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 by({profile:ae,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ae.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await nh({profile:ae})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ae.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).action(async t=>{try{await ac({profile:ae,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var My=Ae.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");My.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??W("HUB_URL")??qe(ae)?.hubUrl??et,r=t.token??W("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Ji()){await Ac({profile:ae});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=W("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??W("WORKER_NAME"),i=t.llm??W("WORKER_LLM");await mr({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...ae?{profile:ae}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});My.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!xe(ae)&&Ji()){await Ac({profile:ae});return}await eo(ae?{profile:ae}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Uy=Ae.command("project").description("Manage CodePipe projects");Uy.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Sy({profile:ae})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Uy.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 Ry({...t,cliProfile:ae})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Pc=Ae.command("repo").description("Manage the project's git repositories");Pc.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 Py({profile:ae,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Pc.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 _y({profile:ae,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Pc.command("list").description("List the project's repos").action(async()=>{try{await jy({profile:ae})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var By=Ae.command("model").description("Project map (model/ in the Context Repo)");By.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 kc({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});By.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 wc({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ae.parseAsync();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@code-partner/codepipe",
3
- "version": "0.8.2-dev.194.gde701ba",
3
+ "version": "0.8.2-dev.195.g3b11952",
4
4
  "description": "CodePipe turns tasks into reviewed pull requests: an AI agent analyzes, implements, and opens a PR under your control.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",