@code-partner/codepipe 0.9.1 → 0.9.2-dev.216.ge6e181d
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.
- package/dist/index.js +159 -158
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1,55 +1,55 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Kk=Object.defineProperty;var v=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ir=(t,e)=>{for(var r in e)Kk(t,r,{get:e[r],enumerable:!0})};var Ue,ct,Es=v(()=>{"use strict";Ue="0.9.2-dev.216.ge6e181d",ct="https://hub.dev.codepipe.dev"});function Ao(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Hk&&t<=lt}var lt,Hk,kl=v(()=>{"use strict";Es();lt=4,Hk=4});var wl=v(()=>{"use strict";Es()});function Po(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
|
|
5
|
+
`}function $l(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 vl(t,e=bl){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 xl(t,e=bl){return e.filter(r=>r.version>t)}var ut,Nn,bl,Sl=v(()=>{"use strict";ut=".codepipe-context.yaml",Nn=".devpipe-context.yaml",bl=[{version:1,summary:"ADR section: adr/ scaffold (README, template, derived INDEX) + the format-version stamp itself",addedPaths:["adr/README.md","adr/0000-template.md","adr/INDEX.md",ut]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[ut]},{version:3,summary:"Custom project actions (the RUN tab): actions/ scaffold with the format README",addedPaths:["actions/README.md"]},{version:4,summary:"Project map: model/ scaffold with the format README (facts/ vs derived/ layout)",addedPaths:["model/README.md"]}]});function _o(t){return`model/facts/identity/${t}.yaml`}function Pr(t){return`model/facts/events/${t}.yaml`}function Tl(t){return`model/facts/annotations/${t}.md`}function El(t){return`model/derived/correlates/${t}.yaml`}function Rl(t){return`model/derived/touched/${t}.yaml`}function Wk(t){return t===""?"root":t.replace(/\//g,"-")}function Il(t,e){return`model/derived/structure/${t}/${Wk(e)}.yaml`}function As(t){return typeof t=="string"&&Yk.test(t)}function Q(t){if(typeof t!="string")return null;let e=t.indexOf(":");if(e<=0)return null;let r=t.indexOf(":",e+1);if(r<0)return null;let n=t.slice(0,e);if(!qk.includes(n))return null;let o=t.slice(e+1,r),i=t.slice(r+1);return o===""&&!Vk.includes(n)||i===""?null:{level:n,repo:o,path:i}}function ve(t){return`task::${t}`}function pe(t,e,r){return`${t}:${e}:${r}`}function jo(t){let e=[];return dt(t)?(No(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),typeof t.repo!="string"&&e.push("repo: missing (empty string = cross-repo)"),typeof t.builtFromCommit!="string"&&e.push("builtFromCommit: missing"),Array.isArray(t.edges)?t.edges.forEach((r,n)=>{if(!dt(r)){e.push(`edges[${n}]: not an object`);return}Cl.includes(r.kind)||e.push(`edges[${n}].kind: unknown "${String(r.kind)}"`),Q(r.from)||e.push(`edges[${n}].from: malformed nodeKey`),Q(r.to)||e.push(`edges[${n}].to: malformed nodeKey`),r.weight!==void 0&&!(typeof r.weight=="number"&&Number.isFinite(r.weight))&&e.push(`edges[${n}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}):{ok:!1,errors:["edge sheet: not an object"]}}function zk(t){return{...t,edges:Cr(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function _r(t){return Nr(zk(t))}function dt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function No(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function ze(t){return typeof t=="string"&&t.length>0}function Ct(t){let e=[];if(!dt(t))return{ok:!1,errors:["shard: not an object"]};No(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),ze(t.repo)||e.push("repo: missing or empty"),ze(t.builtFromCommit)||e.push("builtFromCommit: missing or empty");let r=typeof t.repo=="string"?t.repo:"",n=new Set;return Array.isArray(t.nodes)?t.nodes.forEach((o,i)=>{if(!dt(o)){e.push(`nodes[${i}]: not an object`);return}let s=Q(o.key);if(!s){e.push(`nodes[${i}].key: malformed nodeKey (${JSON.stringify(o.key??null)})`);return}o.level!==s.level&&e.push(`nodes[${i}]: level "${String(o.level)}" does not match key prefix "${s.level}"`),r&&s.repo!==r&&e.push(`nodes[${i}].key: repo "${s.repo}" mixed into shard of repo "${r}"`);let a=o.key;n.has(a)&&e.push(`nodes[${i}].key: duplicate "${a}"`),n.add(a),o.entityId!==void 0&&!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(!dt(o)){e.push(`edges[${i}]: not an object`);return}Cl.includes(o.kind)||e.push(`edges[${i}].kind: unknown "${String(o.kind)}"`),(!ze(o.to)||!Q(o.to))&&e.push(`edges[${i}].to: malformed nodeKey`),(!ze(o.from)||!n.has(o.from))&&e.push(`edges[${i}].from: "${String(o.from)}" is not a node of this shard`),o.weight!==void 0&&!(typeof o.weight=="number"&&Number.isFinite(o.weight))&&e.push(`edges[${i}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}}function Oo(t){let e=[];if(!dt(t))return{ok:!1,errors:["identity: not an object"]};if(No(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),ze(t.repo)||e.push("repo: missing or empty"),t.builtFromCommit!==void 0&&!ze(t.builtFromCommit)&&e.push("builtFromCommit: not a non-empty string"),!Array.isArray(t.entities))e.push("entities: not an array");else{let r=new Set;t.entities.forEach((n,o)=>{if(!dt(n)){e.push(`entities[${o}]: not an object`);return}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)})`),Q(n.currentKey)||e.push(`entities[${o}].currentKey: malformed nodeKey`),n.status!=="active"&&n.status!=="orphaned"&&e.push(`entities[${o}].status: expected active|orphaned`),ze(n.firstSeen)||e.push(`entities[${o}].firstSeen: missing`),ze(n.lastSeen)||e.push(`entities[${o}].lastSeen: missing`),n.aliases!==void 0&&(Array.isArray(n.aliases)?n.aliases.forEach((i,s)=>{(!dt(i)||!Q(i.key)||!ze(i.until))&&e.push(`entities[${o}].aliases[${s}]: malformed`)}):e.push(`entities[${o}].aliases: not an array`))})}return e.length?{ok:!1,errors:e}:{ok:!0,value:t}}function At(t){let e=[];return dt(t)?(No(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),ze(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=>!ze(r)))&&e.push("commits: not an array of non-empty strings"),Array.isArray(t.files)?t.files.forEach((r,n)=>{if(!dt(r)||!Q(r.key)){e.push(`files[${n}].key: malformed nodeKey`);return}r.entityId!==void 0&&!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 Cr(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function Jk(t){return{...t,nodes:Cr(t.nodes,e=>e.key),edges:Cr(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function Xk(t){return{...t,entities:Cr(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:Cr(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function Qk(t){let e=t.links?{...t.links,...t.links.adr?{adr:[...t.links.adr].sort()}:{},...t.links.tasks?{tasks:[...t.links.tasks].sort()}:{}}:void 0;return{...t,commits:[...t.commits].sort(),files:Cr(t.files,r=>r.key),...e?{links:e}:{}}}function On(t){return Zk.test(t)?t:JSON.stringify(t)}function Nl(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 Ol(t){return t===null||["boolean","number","string"].includes(typeof t)}function Rs(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function Dl(t,e,r){if(Array.isArray(t)){for(let n of t)if(Ol(n))r.push(`${e}- ${Nl(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=Rs(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([i,s],a)=>{let c=a===0?`${e}- `:`${e} `;Is(i,s,c,`${e} `,r)})}}return}for(let[n,o]of Rs(t))Is(n,o,e,e,r)}function Is(t,e,r,n,o){if(Ol(e))o.push(`${r}${On(t)}: ${Nl(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${On(t)}: []`):(o.push(`${r}${On(t)}:`),Dl(e,`${n} `,o));else{let i=Rs(e);if(i.length===0)o.push(`${r}${On(t)}: {}`);else{o.push(`${r}${On(t)}:`);for(let[s,a]of i)Is(s,a,`${n} `,`${n} `,o)}}}function Nr(t){let e=[];return Dl(t,"",e),e.join(`
|
|
6
6
|
`)+`
|
|
7
|
-
`}function Nl(t){return Nr(Hk(t))}function Ol(t){return Nr(Wk(t))}function Nn(t){return Nr(qk(t))}var Es,Ar,Bk,El,Fk,Gk,Je,Rl,Il,Cl,Is,Al,jr,Yk,Cs=x(()=>{"use strict";Es="model/derived/INDEX.yaml",Ar="model/derived/relates.yaml";Bk=["system","container","component","code","task","adr"],El=["contains","touched_by","correlates","relates","references","depends_on"],Fk=/^e_[0-9a-f]{8}$/;Gk=["system","task","adr"];Je={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};Rl=2,Il=5,Cl=50,Is=2e3,Al={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},jr={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};Yk=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});var Dl=x(()=>{"use strict"});var Vk,cI,Ll=x(()=>{"use strict";Vk=[{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"]}],cI=Vk.flatMap(t=>t.phases)});function rr(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Ml,As=x(()=>{"use strict";Ml=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"]});function Ul(t,e){return e.toLowerCase().includes(t.toLowerCase())}function Gl(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||Jk.every(o=>e.some(i=>Ul(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 zk){let i=n.find(s=>Ul(o,s.id));if(i)return i.id}return n[0].id}var pt,Bl,Xe,On,Fl,Ps,_s,zk,Jk,js=x(()=>{"use strict";pt="claude",Bl=[pt],Xe="opus",On="sonnet",Fl="haiku",Ps=[Xe,On,Fl],_s={analyze:Xe,implement:Xe,"resolve-conflict":Xe,rework:Xe,estimate:On,build:On,"code-review":Xe,draft:On,index:Xe,backfill:Xe,analysis:Xe,chat:Xe},zk=[Xe,On,Fl],Jk=Array.from(new Set(Object.values(_s)))});function Pt(t){return Xk.has(t)?!0:Qk.some(e=>t.startsWith(e))}function No(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function nr(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function Ns(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function Yl(t,e){let r=No(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=nr(r.id,"id")??n;if(!Kl.test(o))throw new Error(`id must match ${Kl} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=nr(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=No(r.env,"env");s={};for(let[d,f]of Object.entries(p)){if(!Be.test(d))throw new Error(`env name "${d}" must match ${Be}`);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>Hl)throw new Error(`too many params (max ${Hl})`);let p=new Set;a=c.map((d,f)=>Zk(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>Wl)throw new Error(`too many steps (max ${Wl})`);let u=l.map((p,d)=>{let f=No(p,`steps[${d}]`),m=nr(f.run,`steps[${d}].run`);if(!m||m.trim().length===0)throw new Error(`steps[${d}].run is required`);let h=nr(f.name,`steps[${d}].name`),g=Ns(f.timeout_sec,`steps[${d}].timeout_sec`);if(g!==void 0&&(!Number.isInteger(g)||g<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:m,...h?{name:h}:{},...g!==void 0?{timeout_sec:g}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function Zk(t,e,r){let n=No(t,`params[${e}]`),o=nr(n.name,`params[${e}].name`);if(!o||!Be.test(o))throw new Error(`params[${e}].name must match ${Be}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let f=n.enum;if(!Array.isArray(f)||f.length===0||!f.every(m=>typeof m=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=f}let a=nr(n.label,`params[${e}].label`),c=nr(n.help,`params[${e}].help`),l=n.required===!0,u=Ns(n.min,`params[${e}].min`),p=Ns(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 Vl(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 Be,Xk,Qk,ql,Kl,Hl,Wl,Os=x(()=>{"use strict";Be=/^[A-Z][A-Z0-9_]*$/,Xk=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),Qk=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];ql=600,Kl=/^[a-z0-9-]+$/,Hl=32,Wl=64});var or,zl,Dn,Ds=x(()=>{"use strict";or="auto",zl=["primary","context","tasks","docs","code_comments","chat"],Dn=["English","Russian","German","Spanish","French","Portuguese","Italian","Chinese","Japanese","Korean"]});function Zl(t=rw){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...Zl(r.groups));return e}function nw(t,e){let r=JSON.stringify(e);return Zl().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function eu(t){let e=nw(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>Jl)return{ok:!1,error:`${e.id} must have \u2264 ${Jl} entries`};let s={};for(let[a,c]of i){if(!Be.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Be}`};if(Pt(a))return{ok:!1,error:`${e.id}: name "${a}" is reserved`};if(typeof c!="string")return{ok:!1,error:`${e.id}: value of "${a}" must be a string`};if(c.length>Xl)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${Xl} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var ew,tw,Jl,Xl,Ql,rw,tu=x(()=>{"use strict";Os();As();js();Cs();Ds();ew={primary:"Primary language",context:"Context documents",tasks:"Tracker issues",docs:"Repo documentation",code_comments:"Code comments",chat:"Agent chat"},tw={primary:"The project's main language (agent status notes ride it). Empty \u21D2 auto.",context:"Knowledge, ADRs and task artifacts in the Context Repo. Empty \u21D2 auto.",tasks:"Issue titles/bodies the agent drafts. Empty \u21D2 auto.",docs:"Documentation changes in the project repos. Empty \u21D2 auto.",code_comments:"New code comments the agent writes. Empty \u21D2 auto.",chat:"The interactive task-drafting chat. Empty/auto \u21D2 mirror the user's messages."},Jl=64,Xl=2e3,Ql=2e3,rw=[{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:[...Bl],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:[...Ps],help:"Overrides the recommended defaults for every role not listed below."},...Ml.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Ps],help:`recommended: ${_s[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:Ql,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:Ql,help:`e.g. "implementation details, bullet list of what was done, in the tracker's language". 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:"language",label:"Language",help:"Languages the agent writes in, per area. Empty \u21D2 auto: mirror the language of the user's material.",fields:zl.map(t=>({id:`language.${t}`,file:"project.yaml",path:["language",t],type:"string",label:ew[t],nullable:!0,maxLength:40,suggestions:t==="chat"?[or,...Dn]:[...Dn],help:tw[t]}))},{id:"context.model",label:"Project map",help:"Parameters of the project map (built from git history by the CLI). Empty fields keep the defaults.",fields:[{id:"context.model.enabled",file:"regimen.yaml",path:["context","model","enabled"],type:"boolean",label:"Enable in the pipeline",nullable:!1,help:"When on, agents are asked to record intent annotations and (once available) receive an assembled context pack. Off \u21D2 the pipeline ignores the map entirely."},{id:"context.index.hub",file:"regimen.yaml",path:["context","index","hub"],type:"enum",label:"Search index on the server",nullable:!0,suggestions:["off","metadata"],help:"off (default): search runs on your machine, nothing is uploaded. metadata: paths, labels and task texts (never code) are mirrored to the server so search and structure stay available while your machine is offline. Switching back to off deletes the mirrored rows."},{id:"context.model.issue_key_pattern",file:"regimen.yaml",path:["context","model","issue_key_pattern"],type:"string",label:"Issue-key pattern (regex)",nullable:!0,maxLength:200,help:"Regex that finds tracker issue keys in commit subjects when mining task events from history. Empty \u21D2 derived from the tracker project key (e.g. DEV-\\d+)."},{id:"context.model.cochange.window_commits",file:"regimen.yaml",path:["context","model","cochange","window_commits"],type:"number",label:"History window (commits)",nullable:!0,min:50,max:5e4,help:`How many commits back from the build commit are mined. Default ${Je.windowCommits}.`},{id:"context.model.cochange.commit_file_cap",file:"regimen.yaml",path:["context","model","cochange","commit_file_cap"],type:"number",label:"Commit size cap (files)",nullable:!0,min:2,max:500,help:`Commits touching more files are ignored as noise. Default ${Je.commitFileCap}.`},{id:"context.model.cochange.support_min",file:"regimen.yaml",path:["context","model","cochange","support_min"],type:"number",label:"Minimum co-occurrences",nullable:!0,min:1,max:100,help:`A pair of files must change together at least this many times. Default ${Je.supportMin}.`},{id:"context.model.cochange.jaccard_min_pct",file:"regimen.yaml",path:["context","model","cochange","jaccard_min_pct"],type:"number",label:"Minimum Jaccard (%)",nullable:!0,min:0,max:100,help:`Overlap threshold: |A\u2229B| / |A\u222AB| of the files' commit sets, in percent. Default ${Je.jaccardMinPct}.`},{id:"context.model.cochange.half_life_days",file:"regimen.yaml",path:["context","model","cochange","half_life_days"],type:"number",label:"Time-decay half-life (days)",nullable:!0,min:1,max:3650,help:`A commit this old counts half as much. Default ${Je.halfLifeDays} (~9 months).`},{id:"context.model.cochange.top_k",file:"regimen.yaml",path:["context","model","cochange","top_k"],type:"number",label:"Edges per file (top-k)",nullable:!0,min:1,max:64,help:`Only the k strongest co-change edges of a file survive \u2014 bounds graph density whatever the thresholds. Default ${Je.topK}.`}]},{id:"implementation",label:"Implementation",help:"How a dependency cluster is serialized into branches and PRs.",fields:[{id:"implementation.mode",file:"regimen.yaml",path:["implementation","mode"],type:"enum",label:"Implementation mode",nullable:!0,suggestions:["cluster-pr","sequential","parallel"],help:"cluster-pr (the standard mode) \u2014 one shared branch and a single PR per dependency cluster; a lone task is a cluster of one. sequential / parallel are DEPRECATED and will be removed \u2014 migrate to cluster-pr. Clearing removes the key from regimen.yaml but keeps the mode already stored for the project (it is not reset to the default)."}]}]});var ru=x(()=>{"use strict"});var nu=x(()=>{"use strict"});var ou=x(()=>{"use strict"});function iu(t){return`codepipe-host-${t}`}var su=x(()=>{"use strict"});function au(t){return!(!t||t.length>250||!/^[A-Za-z0-9._/-]+$/.test(t)||/^[-/.]/.test(t)||/[/.]$/.test(t)||t.endsWith(".lock")||t.includes("..")||t.includes("//")||t.includes("/."))}function $t(t){return`${t}${ow}`}var ir,ow,cu=x(()=>{"use strict";ir=/^[a-z][a-z0-9-]{1,30}$/,ow="-codepipe-ctx"});var lu=x(()=>{"use strict"});var uu=x(()=>{"use strict"});function Or(t){for(let e of iw){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var iw,du=x(()=>{"use strict";iw=[{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 pu=x(()=>{"use strict"});var fu=x(()=>{"use strict"});var mu=x(()=>{"use strict"});function gu(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function yu(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=gu(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Dr.test(r))return r;let n=gu(t);return Dr.test(n)?n:Ls}function ku(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 Mn(t){return`tasks/${t}/issue.yaml`}var hu,Do,Ls,Dr,Ms,EI,Lo,Ln,wu=x(()=>{"use strict";hu=["bug","feature","epic"],Do="feature",Ls="TASK",Dr=/^[A-Z][A-Z0-9]{1,9}$/;Ms={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},EI=Ms.backlog,Lo="tracker/config.yaml",Ln="tracker/counter"});var bu=x(()=>{"use strict"});function Lr(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 Mo(t){switch(t){case Un.gitlab:return"oauth2";case Un.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Un,sr,$u=x(()=>{"use strict";Un={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};sr="x-bitbucket-api-token-auth"});var vu=x(()=>{"use strict"});var xu=x(()=>{"use strict";bu();$u();vu()});var Su,G=x(()=>{"use strict";gl();hl();$l();Cs();Dl();Ll();As();js();tu();Ds();Os();ru();nu();ou();su();cu();lu();uu();du();pu();fu();mu();wu();xu();Su=20});function V(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var _e=x(()=>{"use strict"});import{existsSync as Tu,renameSync as sw}from"node:fs";function ar(t,e,r=n=>console.error(n)){if(Tu(e)||!Tu(t))return!1;try{return sw(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 Uo=x(()=>{"use strict"});import{existsSync as Bo,readFileSync as Eu,readdirSync as aw,writeFileSync as cw}from"node:fs";import{dirname as lw,join as _t}from"node:path";import{parse as uw}from"yaml";function dw(t=process.cwd()){let e=t;for(;;){if(Bo(_t(e,ft,"project.yaml")))return e;if(Bo(_t(e,Us,"project.yaml")))return ar(_t(e,Us),_t(e,ft))&&fw(e),e;let r=lw(e);if(r===e)return null;e=r}}function pw(t){let e=_t(t,ft);return Bo(e)?e:_t(t,Us)}function fw(t){let e=_t(t,".gitignore");if(!Bo(e))return;let r=Eu(e,"utf-8"),n=r.split(/\r?\n/).map(o=>{let i=o.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?o.replace(".devpipe",".codepipe"):o}).join(`
|
|
8
|
-
`);n!==r&&
|
|
9
|
-
`,{mode:384})}function
|
|
10
|
-
`,{mode:384})}function
|
|
11
|
-
`,{mode:384})}function Ur(t){let e=W(t)?.claude?.oauthToken;return e||
|
|
7
|
+
`}function Ll(t){return Nr(Jk(t))}function Ml(t){return Nr(Xk(t))}function Dn(t){return Nr(Qk(t))}var Cs,Ar,qk,Cl,Yk,Vk,Je,Al,Pl,_l,Ps,jl,jr,Zk,_s=v(()=>{"use strict";Cs="model/derived/INDEX.yaml",Ar="model/derived/relates.yaml";qk=["system","container","component","code","task","adr"],Cl=["contains","touched_by","correlates","relates","references","depends_on"],Yk=/^e_[0-9a-f]{8}$/;Vk=["system","task","adr"];Je={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};Al=2,Pl=5,_l=50,Ps=2e3,jl={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},jr={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};Zk=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});var Ul=v(()=>{"use strict"});var ew,yI,Bl=v(()=>{"use strict";ew=[{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"]}],yI=ew.flatMap(t=>t.phases)});function rr(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Fl,js=v(()=>{"use strict";Fl=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"]});function Gl(t,e){return e.toLowerCase().includes(t.toLowerCase())}function Wl(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||rw.every(o=>e.some(i=>Gl(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 tw){let i=n.find(s=>Gl(o,s.id));if(i)return i.id}return n[0].id}var pt,Kl,Xe,Ln,Hl,Ns,Os,tw,rw,Ds=v(()=>{"use strict";pt="claude",Kl=[pt],Xe="opus",Ln="sonnet",Hl="haiku",Ns=[Xe,Ln,Hl],Os={analyze:Xe,implement:Xe,"resolve-conflict":Xe,rework:Xe,estimate:Ln,build:Ln,"code-review":Xe,draft:Ln,index:Xe,backfill:Xe,analysis:Xe,chat:Xe},tw=[Xe,Ln,Hl],rw=Array.from(new Set(Object.values(Os)))});function Pt(t){return nw.has(t)?!0:ow.some(e=>t.startsWith(e))}function Do(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function nr(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function Ls(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function Jl(t,e){let r=Do(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=nr(r.id,"id")??n;if(!ql.test(o))throw new Error(`id must match ${ql} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=nr(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=Do(r.env,"env");s={};for(let[d,f]of Object.entries(p)){if(!Be.test(d))throw new Error(`env name "${d}" must match ${Be}`);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>Yl)throw new Error(`too many params (max ${Yl})`);let p=new Set;a=c.map((d,f)=>iw(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>Vl)throw new Error(`too many steps (max ${Vl})`);let u=l.map((p,d)=>{let f=Do(p,`steps[${d}]`),m=nr(f.run,`steps[${d}].run`);if(!m||m.trim().length===0)throw new Error(`steps[${d}].run is required`);let h=nr(f.name,`steps[${d}].name`),g=Ls(f.timeout_sec,`steps[${d}].timeout_sec`);if(g!==void 0&&(!Number.isInteger(g)||g<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:m,...h?{name:h}:{},...g!==void 0?{timeout_sec:g}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function iw(t,e,r){let n=Do(t,`params[${e}]`),o=nr(n.name,`params[${e}].name`);if(!o||!Be.test(o))throw new Error(`params[${e}].name must match ${Be}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let f=n.enum;if(!Array.isArray(f)||f.length===0||!f.every(m=>typeof m=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=f}let a=nr(n.label,`params[${e}].label`),c=nr(n.help,`params[${e}].help`),l=n.required===!0,u=Ls(n.min,`params[${e}].min`),p=Ls(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 Xl(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 Be,nw,ow,zl,ql,Yl,Vl,Ms=v(()=>{"use strict";Be=/^[A-Z][A-Z0-9_]*$/,nw=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),ow=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];zl=600,ql=/^[a-z0-9-]+$/,Yl=32,Vl=64});var or,Ql,Mn,Us=v(()=>{"use strict";or="auto",Ql=["primary","context","tasks","docs","code_comments","chat"],Mn=["English","Russian","German","Spanish","French","Portuguese","Italian","Chinese","Japanese","Korean"]});function ru(t=cw){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...ru(r.groups));return e}function lw(t,e){let r=JSON.stringify(e);return ru().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function nu(t){let e=lw(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>Zl)return{ok:!1,error:`${e.id} must have \u2264 ${Zl} entries`};let s={};for(let[a,c]of i){if(!Be.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Be}`};if(Pt(a))return{ok:!1,error:`${e.id}: name "${a}" is reserved`};if(typeof c!="string")return{ok:!1,error:`${e.id}: value of "${a}" must be a string`};if(c.length>eu)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${eu} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var sw,aw,Zl,eu,tu,cw,ou=v(()=>{"use strict";Ms();js();Ds();_s();Us();sw={primary:"Primary language",context:"Context documents",tasks:"Tracker issues",docs:"Repo documentation",code_comments:"Code comments",chat:"Agent chat"},aw={primary:"The project's main language (agent status notes ride it). Empty \u21D2 auto.",context:"Knowledge, ADRs and task artifacts in the Context Repo. Empty \u21D2 auto.",tasks:"Issue titles/bodies the agent drafts. Empty \u21D2 auto.",docs:"Documentation changes in the project repos. Empty \u21D2 auto.",code_comments:"New code comments the agent writes. Empty \u21D2 auto.",chat:"The interactive task-drafting chat. Empty/auto \u21D2 mirror the user's messages."},Zl=64,eu=2e3,tu=2e3,cw=[{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:[...Kl],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:[...Ns],help:"Overrides the recommended defaults for every role not listed below."},...Fl.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Ns],help:`recommended: ${Os[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:tu,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:tu,help:`e.g. "implementation details, bullet list of what was done, in the tracker's language". 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:"language",label:"Language",help:"Languages the agent writes in, per area. Empty \u21D2 auto: mirror the language of the user's material.",fields:Ql.map(t=>({id:`language.${t}`,file:"project.yaml",path:["language",t],type:"string",label:sw[t],nullable:!0,maxLength:40,suggestions:t==="chat"?[or,...Mn]:[...Mn],help:aw[t]}))},{id:"context.model",label:"Project map",help:"Parameters of the project map (built from git history by the CLI). Empty fields keep the defaults.",fields:[{id:"context.model.enabled",file:"regimen.yaml",path:["context","model","enabled"],type:"boolean",label:"Enable in the pipeline",nullable:!1,help:"When on, agents are asked to record intent annotations and (once available) receive an assembled context pack. Off \u21D2 the pipeline ignores the map entirely."},{id:"context.index.hub",file:"regimen.yaml",path:["context","index","hub"],type:"enum",label:"Search index on the server",nullable:!0,suggestions:["off","metadata"],help:"off (default): search runs on your machine, nothing is uploaded. metadata: paths, labels and task texts (never code) are mirrored to the server so search and structure stay available while your machine is offline. Switching back to off deletes the mirrored rows."},{id:"context.model.issue_key_pattern",file:"regimen.yaml",path:["context","model","issue_key_pattern"],type:"string",label:"Issue-key pattern (regex)",nullable:!0,maxLength:200,help:"Regex that finds tracker issue keys in commit subjects when mining task events from history. Empty \u21D2 derived from the tracker project key (e.g. DEV-\\d+)."},{id:"context.model.cochange.window_commits",file:"regimen.yaml",path:["context","model","cochange","window_commits"],type:"number",label:"History window (commits)",nullable:!0,min:50,max:5e4,help:`How many commits back from the build commit are mined. Default ${Je.windowCommits}.`},{id:"context.model.cochange.commit_file_cap",file:"regimen.yaml",path:["context","model","cochange","commit_file_cap"],type:"number",label:"Commit size cap (files)",nullable:!0,min:2,max:500,help:`Commits touching more files are ignored as noise. Default ${Je.commitFileCap}.`},{id:"context.model.cochange.support_min",file:"regimen.yaml",path:["context","model","cochange","support_min"],type:"number",label:"Minimum co-occurrences",nullable:!0,min:1,max:100,help:`A pair of files must change together at least this many times. Default ${Je.supportMin}.`},{id:"context.model.cochange.jaccard_min_pct",file:"regimen.yaml",path:["context","model","cochange","jaccard_min_pct"],type:"number",label:"Minimum Jaccard (%)",nullable:!0,min:0,max:100,help:`Overlap threshold: |A\u2229B| / |A\u222AB| of the files' commit sets, in percent. Default ${Je.jaccardMinPct}.`},{id:"context.model.cochange.half_life_days",file:"regimen.yaml",path:["context","model","cochange","half_life_days"],type:"number",label:"Time-decay half-life (days)",nullable:!0,min:1,max:3650,help:`A commit this old counts half as much. Default ${Je.halfLifeDays} (~9 months).`},{id:"context.model.cochange.top_k",file:"regimen.yaml",path:["context","model","cochange","top_k"],type:"number",label:"Edges per file (top-k)",nullable:!0,min:1,max:64,help:`Only the k strongest co-change edges of a file survive \u2014 bounds graph density whatever the thresholds. Default ${Je.topK}.`}]},{id:"context.job_logs",label:"Job transcripts",help:"Whether the raw agent transcript of each job is kept in the Context Repo.",fields:[{id:"context.job_logs.enabled",file:"regimen.yaml",path:["context","job_logs","enabled"],type:"boolean",label:"Keep transcripts in the Context Repo",nullable:!1,help:"Off (default): the transcript is discarded after the run \u2014 nothing lands in the Context Repo. On: each job's raw transcript is committed as tasks/<KEY>/logs/job-<id>.jsonl for post-mortem debugging."}]},{id:"implementation",label:"Implementation",help:"How a dependency cluster is serialized into branches and PRs.",fields:[{id:"implementation.mode",file:"regimen.yaml",path:["implementation","mode"],type:"enum",label:"Implementation mode",nullable:!0,suggestions:["cluster-pr","sequential","parallel"],help:"cluster-pr (the standard mode) \u2014 one shared branch and a single PR per dependency cluster; a lone task is a cluster of one. sequential / parallel are DEPRECATED and will be removed \u2014 migrate to cluster-pr. Clearing removes the key from regimen.yaml but keeps the mode already stored for the project (it is not reset to the default)."}]}]});var iu=v(()=>{"use strict"});var su=v(()=>{"use strict"});var au=v(()=>{"use strict"});function cu(t){return`codepipe-host-${t}`}var lu=v(()=>{"use strict"});function uu(t){return!(!t||t.length>250||!/^[A-Za-z0-9._/-]+$/.test(t)||/^[-/.]/.test(t)||/[/.]$/.test(t)||t.endsWith(".lock")||t.includes("..")||t.includes("//")||t.includes("/."))}function $t(t){return`${t}${uw}`}var ir,uw,du=v(()=>{"use strict";ir=/^[a-z][a-z0-9-]{1,30}$/,uw="-codepipe-ctx"});var pu=v(()=>{"use strict"});var fu=v(()=>{"use strict"});function Or(t){for(let e of dw){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var dw,mu=v(()=>{"use strict";dw=[{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 gu=v(()=>{"use strict"});var hu=v(()=>{"use strict"});var yu=v(()=>{"use strict"});function ku(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function bu(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=ku(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Dr.test(r))return r;let n=ku(t);return Dr.test(n)?n:Bs}function $u(t,e){let r=new Set([...e].map(n=>n.toUpperCase()));if(!r.has(t.toUpperCase()))return t;for(let n=1;n<1e4;n++){let o=String(n),i=t.slice(0,10-o.length)+o;if(!r.has(i.toUpperCase()))return i}return t}function Bn(t){return`tasks/${t}/issue.yaml`}var wu,Mo,Bs,Dr,Fs,OI,Uo,Un,vu=v(()=>{"use strict";wu=["bug","feature","epic"],Mo="feature",Bs="TASK",Dr=/^[A-Z][A-Z0-9]{1,9}$/;Fs={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},OI=Fs.backlog,Uo="tracker/config.yaml",Un="tracker/counter"});var xu=v(()=>{"use strict"});function Lr(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 Bo(t){switch(t){case Fn.gitlab:return"oauth2";case Fn.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Fn,sr,Su=v(()=>{"use strict";Fn={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};sr="x-bitbucket-api-token-auth"});var Tu=v(()=>{"use strict"});var Eu=v(()=>{"use strict";xu();Su();Tu()});var Ru,G=v(()=>{"use strict";kl();wl();Sl();_s();Ul();Bl();js();Ds();ou();Us();Ms();iu();su();au();lu();du();pu();fu();mu();gu();hu();yu();vu();Eu();Ru=20});function V(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var _e=v(()=>{"use strict"});import{existsSync as Iu,renameSync as pw}from"node:fs";function ar(t,e,r=n=>console.error(n)){if(Iu(e)||!Iu(t))return!1;try{return pw(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 Fo=v(()=>{"use strict"});import{existsSync as Go,readFileSync as Cu,readdirSync as fw,writeFileSync as mw}from"node:fs";import{dirname as gw,join as _t}from"node:path";import{parse as hw}from"yaml";function yw(t=process.cwd()){let e=t;for(;;){if(Go(_t(e,ft,"project.yaml")))return e;if(Go(_t(e,Gs,"project.yaml")))return ar(_t(e,Gs),_t(e,ft))&&ww(e),e;let r=gw(e);if(r===e)return null;e=r}}function kw(t){let e=_t(t,ft);return Go(e)?e:_t(t,Gs)}function ww(t){let e=_t(t,".gitignore");if(!Go(e))return;let r=Cu(e,"utf-8"),n=r.split(/\r?\n/).map(o=>{let i=o.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?o.replace(".devpipe",".codepipe"):o}).join(`
|
|
8
|
+
`);n!==r&&mw(e,n)}function Se(t=process.cwd()){let e=yw(t);if(!e)return null;let r=kw(e),n=bw(Cu(_t(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function Au(t,e,r){return fw(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 Ko(t,e=process.cwd()){try{let r=Se(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function bw(t){let e=hw(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 Pu(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}var ft,Gs,mt=v(()=>{"use strict";Fo();ft=".codepipe",Gs=".devpipe"});import{homedir as _u}from"node:os";import{mkdirSync as $w,readFileSync as vw,writeFileSync as xw,existsSync as Ks}from"node:fs";import{dirname as Nu,join as Ho,resolve as Sw}from"node:path";import{fileURLToPath as Tw}from"node:url";function Ou(t){let e=Ho(ju,".env");if(Ks(e)&&process.loadEnvFile(e),t){let r=Ho(ju,"profiles",t,".env");Ks(r)&&process.loadEnvFile(r)}}function Mr(t){let e=V("CONFIG");return e||(t?Ho(_u(),".codepipe","profiles",t,"config.json"):Ho(_u(),".codepipe","config.json"))}function Qe(t){let e=Mr(t);if(!Ks(e))return null;let r=vw(e,"utf-8");return JSON.parse(r)}function vt(t,e){let r=Mr(e);$w(Nu(r),{recursive:!0}),xw(r,JSON.stringify(t,null,2)+`
|
|
9
|
+
`,{mode:384})}function Wo(t){if(t)return{cfg:Fe(t),profile:t};let e;try{e=Se()?.spec.projectId||void 0}catch{}if(e){let r=Qe(e);if(r)return console.log(`[profile] ${e} \u2014 resolved from this folder's workspace`),{cfg:r,profile:e};console.error(`this folder is the workspace of project '${e}', but that CLI profile is not initialised on this machine \u2014 run \`codepipe init\` here (or pass --profile).`),process.exit(1)}return{cfg:Fe(void 0),profile:void 0}}function Fe(t){let e=Qe(t);if(!e){let r=t?`codepipe init --profile ${t} --hub <url> --token <token> --project ${t}`:"codepipe init --hub <url> --token <token> --project <id>";console.error(t?`CLI profile '${t}' is not initialised. run \`${r}\` first.`:`CLI is not initialised. run \`${r}\` first.`),process.exit(1)}return e.projectId||(console.error(`config at ${Mr(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var ju,Le=v(()=>{"use strict";_e();mt();ju=Sw(Nu(Tw(import.meta.url)),"..")});import{homedir as Uu}from"node:os";import{existsSync as Bu,mkdirSync as Fu,readFileSync as Gu,writeFileSync as Ku}from"node:fs";import{dirname as Hu,join as Wu}from"node:path";function qu(t,e,r){let n=W(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},oe(n)}function Yu(t,e){let r=W(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],oe(r),!0)}function Vu(t){return Object.keys(W(t)?.secrets??{}).sort()}function qo(t,e,r){let n=W(t);if(!n)return"mismatch";let o=n.sandboxPins??{},i=o[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(o[e]=r,n.sandboxPins=o,oe(n),"pinned")}function zu(t,e){let r=W(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],oe(r),!0):!1}function gt(t){return Wu(Uu(),".codepipe","secrets",`${t}.json`)}function W(t){let e=gt(t);return Bu(e)?JSON.parse(Gu(e,"utf-8")):null}function oe(t){let e=gt(t.projectId);Fu(Hu(e),{recursive:!0}),Ku(e,JSON.stringify(t,null,2)+`
|
|
10
|
+
`,{mode:384})}function Yo(){return Wu(Uu(),".codepipe","shared.json")}function Hs(){let t=Yo();return Bu(t)?JSON.parse(Gu(t,"utf-8")):null}function Ju(t){let e=Yo();Fu(Hu(e),{recursive:!0}),Ku(e,JSON.stringify(t,null,2)+`
|
|
11
|
+
`,{mode:384})}function Ur(t){let e=W(t)?.claude?.oauthToken;return e||Hs()?.claude?.oauthToken}function Gn(t){let e={GH_TOKEN:t.github?.token,BITBUCKET_EMAIL:t.bitbucket?.email,BITBUCKET_API_TOKEN:t.bitbucket?.apiToken,GITLAB_TOKEN:t.gitlab?.token,YOUTRACK_URL:t.youtrack?.url,YOUTRACK_TOKEN:t.youtrack?.token};for(let r of Ws){let n=e[r];n&&!process.env[r]&&(process.env[r]=n)}}function Br(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var Ws,ue=v(()=>{"use strict";Ws=["GH_TOKEN","BITBUCKET_EMAIL","BITBUCKET_API_TOKEN","GITLAB_TOKEN","YOUTRACK_URL","YOUTRACK_TOKEN"]});import{appendFileSync as Ew,existsSync as Qu,mkdirSync as Rw,renameSync as Zu,statSync as Iw,unlinkSync as Cw}from"node:fs";import{Writable as Aw}from"node:stream";import{join as Pw}from"node:path";function Vo(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=_w(process.env[`${t}_MAX_BYTES`]??String(ed.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):ed.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function _w(t){let e=t.trim().match(/^(\d+)\s*([kmg]?)b?$/i);if(!e)return Number(t)||0;let r=Number(e[1]),n=(e[2]??"").toLowerCase();return n==="g"?r*1024**3:n==="m"?r*1024**2:n==="k"?r*1024:r}function zo(t){let e={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},r=(n,o)=>(...i)=>{n(...i);try{t.writeLine(jw(o,i))}catch{}};return console.log=r(e.log,"INFO"),console.warn=r(e.warn,"WARN"),console.error=r(e.error,"ERROR"),()=>{console.log=e.log,console.warn=e.warn,console.error=e.error}}function jw(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:Nw(o)).join(" ");return`${r} ${t} ${n}`}function Nw(t){try{return JSON.stringify(t)}catch{return String(t)}}var ed,Fr,qs=v(()=>{"use strict";ed={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},Fr=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&Rw(e.dir,{recursive:!0}),this.currentPath=Pw(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
|
|
12
12
|
`)?e:e+`
|
|
13
|
-
`;
|
|
14
|
-
`+t.slice(t.length-e)}async function jt(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),Vo);try{let i;try{i=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new Ge(`cannot reach api.github.com (${l instanceof Error?l.message:String(l)})`)}if(i.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(zo(i.status))throw new Ge(`api.github.com \u2192 ${i.status} ${i.statusText}`);if(!i.ok)throw new Error(`GitHub \u2192 ${i.status} ${i.statusText}`);let a=(await i.json()).login??"ok",c=i.headers.get("x-oauth-scopes");if(c!==null&&e&&!c.split(",").map(u=>u.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${c||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let l;try{let u=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});u.ok&&(l=(await u.json()).type)}catch{}if(l==="Organization"){let u=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});if(u.status===403)throw new Error(`token cannot access org "${e.owner}" (403) \u2014 for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens; for classic PATs: verify 'repo' or 'admin:org' scope`);if(u.status===404)throw new Error(`org "${e.owner}" not found or not visible to this token \u2014 check the org name; for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens`);if(!u.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${u.status} ${u.statusText}`)}}return a}finally{clearTimeout(o)}}async function Jo(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),Vo);try{let s;try{s=await fetch(n,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},signal:o.signal})}catch(c){throw new Ge(`cannot reach api.github.com (${c instanceof Error?c.message:String(c)})`)}if(s.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(s.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(zo(s.status))throw new Ge(`api.github.com \u2192 ${s.status} ${s.statusText}`);if(!s.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${s.status} ${s.statusText}`);if((await s.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}finally{clearTimeout(i)}}async function Nt(t,e,r){let n=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",o=new AbortController,i=setTimeout(()=>o.abort(),Vo);try{let s;try{s=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new Ge(`cannot reach api.bitbucket.org (${c instanceof Error?c.message:String(c)})`)}if(s.ok)return t;if(s.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;if(zo(s.status))throw new Ge(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await Ow(s);throw s.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${a})`):s.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${a})`):s.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${a})`):new Error(`Bitbucket \u2192 ${s.status} ${s.statusText}${a}`)}finally{clearTimeout(i)}}async function Ow(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function Xo(t,e,r,n){let o;try{o=await fetch(`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}/${encodeURIComponent(n)}/pullrequests?pagelen=1`,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch{return}if(o.status!==403)return;let i={};try{i=await o.json()}catch{}let s=i.error?.detail?.granted;if(Array.isArray(s)){let c=rd.filter(l=>!s.includes(l));return c.length===0?void 0:`token lacks scope(s) ${c.join(", ")} \u2014 the pipeline would fail at PR time; re-create the API token with all of: ${rd.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function Ot(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Vo);try{let n;try{n=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"},signal:e.signal})}catch(i){throw new Ge(`cannot reach gitlab.com (${i instanceof Error?i.message:String(i)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(zo(n.status))throw new Ge(`gitlab.com \u2192 ${n.status} ${n.statusText}`);if(!n.ok)throw new Error(`GitLab \u2192 ${n.status} ${n.statusText}`);return(await n.json()).username??"ok"}finally{clearTimeout(r)}}async function nd(t){try{let e=await fetch("https://gitlab.com/api/v4/personal_access_tokens/self",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}});if(!e.ok)return;let n=(await e.json()).scopes??[];return n.length>0&&!n.includes("api")?`GitLab token scopes [${n.join(", ")}] lack 'api' \u2014 CodePipe can read and push, but cannot create a Context Repo or scaffold its files`:void 0}catch{return}}function Dw(t){switch(t){case"running":case"pending":case"created":case"waiting_for_resource":case"preparing":case"scheduled":return"running";case"success":return"success";case"failed":case"canceled":case"cancelled":return"failed";default:return"none"}}function Ws(t,e,r){let n=t.host==="github"?"set GH_TOKEN or GITHUB_TOKEN in the CLI env":t.host==="bitbucket"?"set BITBUCKET_EMAIL + BITBUCKET_API_TOKEN in the CLI env":t.host==="gitlab"?"set GITLAB_TOKEN in the CLI env":`no adapter implementation for host '${t.host}'`;return`cannot ${r} PR ${t.owner}/${t.repoName}#${e}: MockGitHost is active (write operations are not allowed) \u2014 ${n}`}function Ze(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new Ys(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new qs(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new Vs(e)}return new zs}var cr,Ge,Vo,rd,qs,Ys,Vs,zs,Dt=x(()=>{"use strict";cr=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},Ge=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},Vo=5e3;rd=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];qs=class{constructor(e,r){this.email=e;this.apiToken=r}name="bitbucket";authHeader(){return"Basic "+Buffer.from(`${this.email}:${this.apiToken}`).toString("base64")}async createPullRequest(e,r){let n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json"},body:JSON.stringify({title:r.title,description:r.body,source:{branch:{name:r.branchName}},destination:{branch:{name:r.baseBranch}}})});if(!n.ok)throw new Error(`bitbucket pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.links?.html?.href??"",number:o.id}}async findOpenPrByBranch(e,r){let n=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${n}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!o.ok)return null;let s=(await o.json()).values?.[0];return s?{url:s.links?.html?.href??"",number:s.id}:null}async getPullRequest(e,r){let n=`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(o.status===404)throw new cr(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){let i=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:o})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:n}})});if(!o.ok)throw new Error(`bitbucket comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},Ys=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json"},body:JSON.stringify({title:r.title,body:r.body,head:r.branchName,base:r.baseBranch})});if(!n.ok)throw new Error(`github pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.html_url,number:o.number}}async findOpenPrByBranch(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls?state=open&head=${encodeURIComponent(`${e.owner}:${r}`)}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.html_url,number:i.number}:null}async getPullRequest(e,r){let n=`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(o.status===404)throw new cr(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),a=!1,c=!1,l=!1;if(i.ok){let u=await i.json();for(let p of u.check_runs??[])l=!0,p.status!=="completed"?a=!0:p.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(p.conclusion)&&(c=!0)}if(s.ok){let u=await s.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${o}/pulls/${r}`,{headers:n});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${o}/actions/runs?head_sha=${a}&per_page=20`,{headers:n});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],u=[];for(let p of l.filter(d=>d.conclusion&&i.includes(d.conclusion))){let d=await fetch(`${o}/actions/runs/${p.id}/jobs?per_page=50`,{headers:n});if(!d.ok)continue;let f=(await d.json()).jobs??[];for(let m of f.filter(h=>h.conclusion==="failure")){let h=await fetch(`${o}/actions/jobs/${m.id}/logs`,{headers:n});if(!h.ok)continue;let g=await h.text();u.push(`### CI job: ${m.name}
|
|
15
|
-
|
|
16
|
-
${
|
|
17
|
-
|
|
18
|
-
`),16e3)}catch{return}}async mergePR(e,r,n,o){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},
|
|
19
|
-
`)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function Bw(t,e,r){return new Promise((n,o)=>{let i=Lt.connect({host:t,port:e,servername:t,rejectUnauthorized:!1},()=>{let s=i.getPeerCertificate(!0),a=new Set;for(;s?.issuerCertificate&&s.issuerCertificate!==s&&s.fingerprint256&&!a.has(s.fingerprint256);)a.add(s.fingerprint256),s=s.issuerCertificate;let c=s?.raw?new sd(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function Js(t,e,r){return new Promise(n=>{let o=Lt.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{o.end(),n(!0)});o.on("error",()=>n(!1)),o.setTimeout(r,()=>{o.destroy(),n(!1)})})}async function Fw(t){try{let e=await fetch(t);return e.ok?new sd(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function dd(t,e=443,r=cd){let n=`${t}:${e}`,o=id.get(n);if(o)return o;let i=Gw(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return id.set(n,i),i}async function Gw(t,e,r){if(!ad)return!1;let n=8e3;if(await Js(t,e,n))return!0;let o=await Bw(t,e,n),i=Lt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=Uw(o);if(!c)break;let l=await Fw(c);if(!l)break;if(s.push(l.toString()),Lt.setDefaultCACertificates([...i,...s]),await Js(t,e,n))return r(`[tls] completed certificate chain for ${t} via AIA (+${s.length} intermediate cert(s))`),!0;if(l.subject===l.issuer)break;o=l}return Js(t,e,n)}var ad,od,id,cd,pd=x(()=>{"use strict";_e();ad=typeof Lt.getCACertificates=="function"&&typeof Lt.setDefaultCACertificates=="function",od=!1,id=new Map,cd=t=>console.warn(t)});function hd(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function Ke(t,e,r){ld();let n={Authorization:`Bearer ${t.token}`,Accept:"application/json"};r?.body&&(n["Content-Type"]="application/json");let o=t.baseUrl+e,i={...r,headers:{...n,...r?.headers??{}}};try{return await fetch(o,i)}catch(s){if(ud(s)&&await dd(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function Kw(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Hw(){let t=Number(process.env.YOUTRACK_WRITE_RETRIES);return{attempts:Number.isFinite(t)&&t>=1?Math.floor(t):6,baseMs:1e3,capMs:15e3}}async function Xs(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=Hw(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await Ke(t,r,n)}catch(u){a=new Error(`${e}: ${u instanceof Error?u.message:String(u)}`)}if(l){if(l.ok)return l;let u=await l.text();if(c<o&&Kw(l.status,u)){await fd(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await fd(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Mt(t){let e;try{e=await Ke(t,"/api/users/me?fields=login,fullName")}catch(n){throw new Error(`cannot reach ${t.baseUrl} (${n instanceof Error?n.message:String(n)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the YouTrack PAT)");if(!e.ok)throw new Error(`YouTrack \u2192 ${e.status} ${e.statusText}`);let r=await e.json();return r.login??r.fullName??"ok"}async function yd(t){try{let e=await Ke(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function Ww(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=md.get(o);if(i)return i;let s=await Ke(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!s.ok)throw new Error(`yt resolveStateId ${e}: ${s.status} ${await s.text()}`);let c=(await s.json()).customFields.find(u=>u.name===n);if(!c)throw new Error(`yt: issue ${e} has no ${n} custom field`);let l=c.projectCustomField.bundle.values.find(u=>u.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${n} bundle for ${e}`);return md.set(o,l.id),l.id}async function kd(t,e,r,n=Fn){let o=await Ww(t,e,r,n);await Xs(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:n,$type:"StateIssueCustomField",value:{id:o,$type:"StateBundleElement"}}]})})}async function wd(t,e,r){return await(await Xs(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function bd(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await Xs(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function $d(t,e){let r=gd.get(e);if(r)return r;let n=await Ke(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!n.ok)throw new Error(`yt resolveProjectId: ${n.status} ${await n.text()}`);let i=(await n.json()).find(s=>s.shortName===e);if(!i)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return gd.set(e,i.id),i.id}async function vd(t,e,r,n,o,i=Fn){let s=await $d(t,e),a=await Ke(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:s},summary:r,description:n,customFields:[{name:i,$type:"StateIssueCustomField",value:{name:o,$type:"StateBundleElement"}}]})});if(!a.ok)throw new Error(`yt createIssue: ${a.status} ${await a.text()}`);let c=await a.json();return{id:c.id,key:c.idReadable}}async function xd(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await Ke(t,"/api/commands",{method:"POST",body:JSON.stringify({query:o,issues:[{idReadable:e}]})});if(!i.ok)throw new Error(`yt applyIssueLink (${o} on ${e}): ${i.status} ${await i.text()}`)}function Ed(t){if(!t||t.length===0)return;let e=[];for(let r of t)!r.url||!r.name||e.push({id:r.id,name:r.name,url:r.url,...r.mimeType?{mimeType:r.mimeType}:{},...typeof r.size=="number"?{size:r.size}:{}});return e.length>0?e:void 0}async function Rd(t,e){let r=e.startsWith("http")?e:t.baseUrl+e,n=await fetch(r,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok)throw new Error(`yt downloadAttachment ${e}: ${n.status}`);return Buffer.from(await n.arrayBuffer())}async function Id(t,e){let r=e.stageField??Fn,n=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let c=e.columns.map(l=>`{${l}}`).join(", ");n.push(`${r}: ${c}`)}if(e.updatedSince){let c=new Date(e.updatedSince).toISOString().slice(0,10);n.push(`updated: ${c} .. *`)}e.assignee?n.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&n.push("has: Assignee");let o=n.join(" "),i=`/api/issues?query=${encodeURIComponent(o)}&fields=${Td}&$top=200`,s=await Ke(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>Pd(c,r))}async function Cd(t,e,r=Fn){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Td}`,o=await Ke(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Pd(await o.json(),r)}async function Ad(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${Yw}&$top=500`,o=await Ke(t,n);if(!o.ok)throw new Error(`yt listComments ${e}: ${o.status} ${await o.text()}`);return(await o.json()).filter(s=>s.created>r).map(s=>{let a={id:s.id,issueId:e,author:s.author?.login??"unknown",body:s.text??"",createdAt:new Date(s.created).toISOString()},c=Ed(s.attachments);return c&&(a.attachments=c),a})}function Vw(t){if(!t||t.length===0)return;let e=[];for(let r of t){if(r.direction!=="INWARD")continue;let n=r.linkType?.name==="Depend"?"depends_on":r.linkType?.name==="Subtask"?"subtask":null;if(n)for(let o of r.issues??[])o.idReadable&&e.push({type:n,targetKey:o.idReadable})}return e.length>0?e:void 0}function Pd(t,e=Fn){let r=t.customFields??[],n=r.find(l=>l.name===e),o=r.find(l=>l.name==="Assignee"),i=r.find(l=>l.name==="Type"),s={id:t.id,key:t.idReadable,title:t.summary,status:n?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(s.description=t.description),o?.value?.login&&(s.assignee=o.value.login),i?.value?.name&&(s.issueType=i.value.name),t.tags&&t.tags.length>0&&(s.tags=t.tags.map(l=>l.name));let a=Ed(t.attachments);a&&(s.attachments=a);let c=Vw(t.links);return c&&(s.links=c),s}async function _d(t,e){let r=await zw(t,e);return r.length>0?r:Jw(t,e)}async function zw(t,e){let r=await $d(t,e),n=await Ke(t,`/api/admin/projects/${encodeURIComponent(r)}/customFields?fields=$type,field(name),bundle(values(name,archived))&$top=100`);if(!n.ok)return[];let o=await n.json(),i=[];for(let s of o)s.$type==="StateProjectCustomField"&&s.field?.name&&i.push({name:s.field.name,values:jd(s.bundle)});return i}async function Jw(t,e){let r=`project: ${e}`,n=await Ke(t,`/api/issues?query=${encodeURIComponent(r)}&fields=customFields(name,$type,projectCustomField(bundle(values(name,archived))))&$top=1`);if(!n.ok)throw new Error(`yt fetchProjectStateFields ${e}: ${n.status} ${await n.text()}`);let o=await n.json(),i=[];for(let s of o[0]?.customFields??[])s.$type==="StateIssueCustomField"&&s.name&&i.push({name:s.name,values:jd(s.projectCustomField?.bundle)});return i}function jd(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var fd,Fn,md,gd,Sd,qw,Td,Yw,lr=x(()=>{"use strict";pd();fd=t=>new Promise(e=>setTimeout(e,t));Fn="Stage",md=new Map;gd=new Map;Sd="attachments(id,name,url,size,mimeType)",qw="links(direction,linkType(name),issues(idReadable))",Td=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Sd},${qw}`,Yw=`id,text,created,author(login),${Sd}`});function et(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function Gr(t){return t instanceof Ge}async function Nd(t,e){let r=W(t),n=[],o=[],i=()=>Date.now();if(e?.trackerProvider==="internal")n.push({name:"tracker",ok:!0,detail:"built-in tracker"});else if(r?.youtrack?.url&&r.youtrack.token)try{let c=await Mt({baseUrl:r.youtrack.url,token:r.youtrack.token});n.push({name:"youtrack",ok:!0}),o.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"youtrack",ok:!1,detail:et(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:et(c),checkedAt:i()})}else n.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),o.push({kind:"youtrack",present:!1,checkedAt:i()});let s=!1;if(r?.github?.token){s=!0;try{let c=await jt(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){Gr(c)?(n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"github",ok:!1,detail:et(c)}),o.push({kind:"github",present:!0,ok:!1,detail:et(c),checkedAt:i()}))}}else o.push({kind:"github",present:!1,checkedAt:i()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){s=!0;try{let c=await Nt(r.bitbucket.email,r.bitbucket.apiToken);n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){Gr(c)?(n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"bitbucket",ok:!1,detail:et(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:et(c),checkedAt:i()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Ot(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){Gr(c)?(n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"gitlab",ok:!1,detail:et(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:et(c),checkedAt:i()}))}}else o.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||n.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let u of e?.repos??[])if(u.host==="github")try{await Jo(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){Gr(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:et(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await Jo(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){Gr(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:et(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Jo(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){Gr(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:i()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:et(l),checkedAt:i()})}else o.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:i()})}else o.push({kind:"contextWrite",present:!1,checkedAt:i()});let a=Ur(t);if(!a)n.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),o.push({kind:"claude",present:!1,checkedAt:i()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:i()});else{let c=await Ut(a);if(c==="invalid"){let l="Claude token rejected (401) \u2014 refresh via `claude setup-token`";n.push({name:"claude",ok:!1,detail:l}),o.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function Ut(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});return n.status===200?"valid":n.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}async function Od(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1000",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});if(n.status!==200)return null;let i=(await n.json())?.data;if(!Array.isArray(i))return null;let s=[];for(let a of i){let c=a?.id;if(typeof c!="string"||c.trim().length===0)continue;let l=a?.created_at;s.push({id:c,...typeof l=="string"?{createdAt:l}:{}})}return s}catch{return null}finally{clearTimeout(r)}}var Kr=x(()=>{"use strict";ue();Dt();lr()});import Xw from"node:http";import Qs from"node:crypto";function Qo(){let t=Zs(Qs.randomBytes(32)),e=Zs(Qs.createHash("sha256").update(t).digest()),r=Zs(Qs.randomBytes(32));return{verifier:t,challenge:e,state:r}}function ta(t){let e=new URL(Qw);return e.search=new URLSearchParams({response_type:"code",client_id:Dd,redirect_uri:t.redirectUri,scope:eb,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function rb(t,e){let r=t.get("error");if(r)throw new Error(`oauth-error: ${r}`);if(t.get("state")!==e)throw new Error("state-mismatch");let n=t.get("code");if(!n)throw new Error("no-code");return n}function Ld(t,e){let[r,n]=t.trim().split("#");if(!r)throw new Error("no-code");if(n!==void 0&&n!==e)throw new Error("state-mismatch");return r}function nb(t){let e=t,r=e?.access_token;if(!r||typeof r!="string")throw new Error(`no access_token in response: ${JSON.stringify(t)}`);return{oauthToken:r,...typeof e.refresh_token=="string"?{refreshToken:e.refresh_token}:{},...typeof e.expires_in=="number"?{expiresIn:e.expires_in}:{}}}async function ra(t){let e=await fetch(Zw,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:t.code,state:t.state,redirect_uri:t.redirectUri,client_id:Dd,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return nb(await e.json())}async function na(t){let e=t.timeoutMs??tb,r=Xw.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=ta({redirectUri:o,challenge:t.challenge,state:t.state}),s,a=new Promise((l,u)=>{s=setTimeout(()=>u(new Error("no-callback")),e),r.on("request",(p,d)=>{let f=new URL(p.url??"/",o);if(f.pathname!=="/callback"){d.statusCode=404,d.end();return}clearTimeout(s),d.setHeader("content-type","text/html"),d.end("<h3>Authorized \u2014 you can close this tab.</h3>");try{l(rb(f.searchParams,t.state))}catch(m){u(m)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>ra({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function Md(t){let e=await na(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
|
|
20
|
-
${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var
|
|
21
|
-
${l.trim()}`)}}let i=
|
|
22
|
-
${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function pr(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function fr(t,e){let{contextRepoCloneUrl:r,deliveryRef:n,deliverySha:o,baseSha:i,commitMessage:s}=e;await t.raw(["fetch",r,`+refs/heads/${n}:refs/codepipe-delivery`]);let a=(await t.revparse(["refs/codepipe-delivery"])).trim();o&&a!==o&&dr(`[git] delivery ${n} resolved ${a.slice(0,10)} (expected ${o.slice(0,10)})`);let c=(await t.raw(["rev-parse","refs/codepipe-delivery^{tree}"])).trim();if(await pr(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await pr(t,i))throw new Error(`apply_delivery: base commit ${i.slice(0,10)} unavailable \u2014 cannot re-parent the delivery`);let l=(await t.raw([...
|
|
23
|
-
${y.trim()}`)}}let h=(await t.revparse(["HEAD"])).trim(),g=r.push!==!1;if(g){let w=p?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push(w)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:h,pushed:g}}async function
|
|
24
|
-
${
|
|
13
|
+
`;Ew(this.currentPath,r,"utf-8")}asWritable(){return new Aw({write:(e,r,n)=>{try{let o=typeof e=="string"?e:e.toString("utf-8");for(let i of o.split(/\r?\n/))i&&this.writeLine(i);n()}catch(o){n(o)}}})}rotateIfNeeded(){if(!(this.cfg.maxBytes<=0||!Qu(this.currentPath)||Iw(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;Qu(n)&&(r>=this.cfg.maxFiles?Cw(n):Zu(n,`${this.currentPath}.${r+1}`))}Zu(this.currentPath,`${this.currentPath}.1`)}}}});import{createHash as Ow}from"node:crypto";import{existsSync as Dw,readFileSync as Lw}from"node:fs";import{homedir as Mw,hostname as Ys}from"node:os";import{join as Uw}from"node:path";function td(t){return Ow("sha256").update(t).digest("hex").slice(0,12)}function Bw(){let t=V("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=Uw(Mw(),".claude","credentials.json");if(!Dw(e))return;let r=JSON.parse(Lw(e,"utf-8")),n=[r.email,r.account?.email,r.user?.email];for(let o of n)if(typeof o=="string"&&o.includes("@"))return o.trim().toLowerCase()}catch{}}function rd(t){let e=Bw(),r=V("ACCOUNT_ID")?.trim(),n=V("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=Ur(t);return o?{accountId:`acct-${td(o)}`,label:n||Ys(),...e?{email:e}:{}}:{accountId:`acct-${td(`host:${Ys()}`)}`,label:n||Ys(),...e?{email:e}:{}}}var nd=v(()=>{"use strict";_e();ue()});function Xo(t){return t===429||t>=500}function od(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
|
|
14
|
+
`+t.slice(t.length-e)}async function jt(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),Jo);try{let i;try{i=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new Ge(`cannot reach api.github.com (${l instanceof Error?l.message:String(l)})`)}if(i.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(Xo(i.status))throw new Ge(`api.github.com \u2192 ${i.status} ${i.statusText}`);if(!i.ok)throw new Error(`GitHub \u2192 ${i.status} ${i.statusText}`);let a=(await i.json()).login??"ok",c=i.headers.get("x-oauth-scopes");if(c!==null&&e&&!c.split(",").map(u=>u.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${c||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let l;try{let u=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});u.ok&&(l=(await u.json()).type)}catch{}if(l==="Organization"){let u=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});if(u.status===403)throw new Error(`token cannot access org "${e.owner}" (403) \u2014 for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens; for classic PATs: verify 'repo' or 'admin:org' scope`);if(u.status===404)throw new Error(`org "${e.owner}" not found or not visible to this token \u2014 check the org name; for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens`);if(!u.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${u.status} ${u.statusText}`)}}return a}finally{clearTimeout(o)}}async function Qo(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),Jo);try{let s;try{s=await fetch(n,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},signal:o.signal})}catch(c){throw new Ge(`cannot reach api.github.com (${c instanceof Error?c.message:String(c)})`)}if(s.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(s.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(Xo(s.status))throw new Ge(`api.github.com \u2192 ${s.status} ${s.statusText}`);if(!s.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${s.status} ${s.statusText}`);if((await s.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}finally{clearTimeout(i)}}async function Nt(t,e,r){let n=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",o=new AbortController,i=setTimeout(()=>o.abort(),Jo);try{let s;try{s=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new Ge(`cannot reach api.bitbucket.org (${c instanceof Error?c.message:String(c)})`)}if(s.ok)return t;if(s.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;if(Xo(s.status))throw new Ge(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await Fw(s);throw s.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${a})`):s.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${a})`):s.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${a})`):new Error(`Bitbucket \u2192 ${s.status} ${s.statusText}${a}`)}finally{clearTimeout(i)}}async function Fw(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function Zo(t,e,r,n){let o;try{o=await fetch(`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}/${encodeURIComponent(n)}/pullrequests?pagelen=1`,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch{return}if(o.status!==403)return;let i={};try{i=await o.json()}catch{}let s=i.error?.detail?.granted;if(Array.isArray(s)){let c=id.filter(l=>!s.includes(l));return c.length===0?void 0:`token lacks scope(s) ${c.join(", ")} \u2014 the pipeline would fail at PR time; re-create the API token with all of: ${id.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function Ot(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Jo);try{let n;try{n=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"},signal:e.signal})}catch(i){throw new Ge(`cannot reach gitlab.com (${i instanceof Error?i.message:String(i)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(Xo(n.status))throw new Ge(`gitlab.com \u2192 ${n.status} ${n.statusText}`);if(!n.ok)throw new Error(`GitLab \u2192 ${n.status} ${n.statusText}`);return(await n.json()).username??"ok"}finally{clearTimeout(r)}}async function sd(t){try{let e=await fetch("https://gitlab.com/api/v4/personal_access_tokens/self",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}});if(!e.ok)return;let n=(await e.json()).scopes??[];return n.length>0&&!n.includes("api")?`GitLab token scopes [${n.join(", ")}] lack 'api' \u2014 CodePipe can read and push, but cannot create a Context Repo or scaffold its files`:void 0}catch{return}}function Gw(t){switch(t){case"running":case"pending":case"created":case"waiting_for_resource":case"preparing":case"scheduled":return"running";case"success":return"success";case"failed":case"canceled":case"cancelled":return"failed";default:return"none"}}function Vs(t,e,r){let n=t.host==="github"?"set GH_TOKEN or GITHUB_TOKEN in the CLI env":t.host==="bitbucket"?"set BITBUCKET_EMAIL + BITBUCKET_API_TOKEN in the CLI env":t.host==="gitlab"?"set GITLAB_TOKEN in the CLI env":`no adapter implementation for host '${t.host}'`;return`cannot ${r} PR ${t.owner}/${t.repoName}#${e}: MockGitHost is active (write operations are not allowed) \u2014 ${n}`}function Ze(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new Js(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new zs(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new Xs(e)}return new Qs}var cr,Ge,Jo,id,zs,Js,Xs,Qs,Dt=v(()=>{"use strict";cr=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},Ge=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},Jo=5e3;id=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];zs=class{constructor(e,r){this.email=e;this.apiToken=r}name="bitbucket";authHeader(){return"Basic "+Buffer.from(`${this.email}:${this.apiToken}`).toString("base64")}async createPullRequest(e,r){let n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json"},body:JSON.stringify({title:r.title,description:r.body,source:{branch:{name:r.branchName}},destination:{branch:{name:r.baseBranch}}})});if(!n.ok)throw new Error(`bitbucket pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.links?.html?.href??"",number:o.id}}async findOpenPrByBranch(e,r){let n=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${n}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!o.ok)return null;let s=(await o.json()).values?.[0];return s?{url:s.links?.html?.href??"",number:s.id}:null}async getPullRequest(e,r){let n=`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(o.status===404)throw new cr(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){let i=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:o})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:n}})});if(!o.ok)throw new Error(`bitbucket comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},Js=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json"},body:JSON.stringify({title:r.title,body:r.body,head:r.branchName,base:r.baseBranch})});if(!n.ok)throw new Error(`github pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.html_url,number:o.number}}async findOpenPrByBranch(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls?state=open&head=${encodeURIComponent(`${e.owner}:${r}`)}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.html_url,number:i.number}:null}async getPullRequest(e,r){let n=`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(o.status===404)throw new cr(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),a=!1,c=!1,l=!1;if(i.ok){let u=await i.json();for(let p of u.check_runs??[])l=!0,p.status!=="completed"?a=!0:p.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(p.conclusion)&&(c=!0)}if(s.ok){let u=await s.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${o}/pulls/${r}`,{headers:n});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${o}/actions/runs?head_sha=${a}&per_page=20`,{headers:n});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],u=[];for(let p of l.filter(d=>d.conclusion&&i.includes(d.conclusion))){let d=await fetch(`${o}/actions/runs/${p.id}/jobs?per_page=50`,{headers:n});if(!d.ok)continue;let f=(await d.json()).jobs??[];for(let m of f.filter(h=>h.conclusion==="failure")){let h=await fetch(`${o}/actions/jobs/${m.id}/logs`,{headers:n});if(!h.ok)continue;let g=await h.text();u.push(`### CI job: ${m.name}
|
|
15
|
+
|
|
16
|
+
${od(g,8e3)}`)}}return u.length===0?void 0:od(u.join(`
|
|
17
|
+
|
|
18
|
+
`),16e3)}catch{return}}async mergePR(e,r,n,o){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},Xs=class{constructor(e){this.token=e}name="gitlab";pid(e){return encodeURIComponent(`${e.owner}/${e.repoName}`)}headers(e=!1){let r={"PRIVATE-TOKEN":this.token,"User-Agent":"codepipe-cli"};return e&&(r["Content-Type"]="application/json"),r}async createPullRequest(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({source_branch:r.branchName,target_branch:r.baseBranch,title:r.title,description:r.body})});if(!n.ok)throw new Error(`gitlab mr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.web_url??"",number:o.iid}}async findOpenPrByBranch(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests?state=opened&source_branch=${encodeURIComponent(r)}`,{headers:this.headers()});if(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.web_url??"",number:i.iid}:null}async getPullRequest(e,r){let n=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,o=await fetch(n,{method:"GET",headers:this.headers()});if(o.status===404)throw new cr(`GitLab MR not found: ${e.owner}/${e.repoName}!${r}`);if(o.status>=400)throw new Error(`gitlab GET merge_requests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="merged")return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed"||i.state==="locked")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=Gw(i.head_pipeline?.status??i.pipeline?.status),a=i.merge_status==="cannot_be_merged"||i.has_conflicts===!0?"conflict":i.merge_status==="can_be_merged"&&i.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:s,mergeable:a}}async mergePR(e,r,n,o){let i=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,s,a=await fetch(i,{headers:this.headers()});if(a.ok){let u=await a.json().catch(()=>null);s=u?.sha??u?.diff_refs?.head_sha}let c=await fetch(`${i}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:n==="squash",should_remove_source_branch:o,...s?{sha:s}:{}})});if(!c.ok)throw new Error(`gitlab merge MR !${r}: ${c.status} ${await c.text()}`);let l=await c.json().catch(()=>null);return l?.merge_commit_sha?{mergedSha:l.merge_commit_sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`gitlab comment MR !${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!o.ok)throw new Error(`gitlab close MR !${r}: ${o.status} ${await o.text()}`)}};Qs=class{name="mock";async createPullRequest(e,r){let n=Math.floor(Math.random()*9e3)+1e3;return{url:`https://example.com/${e.owner}/${e.repoName}/pull-requests/${n}`,number:n}}async getPullRequest(e,r){return{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){throw new Error(Vs(e,r,"merge"))}async closePR(e,r,n){throw new Error(Vs(e,r,"close"))}async addPRComment(e,r,n){throw new Error(Vs(e,r,"comment"))}}});import{X509Certificate as ld}from"node:crypto";import{readFileSync as Kw}from"node:fs";import Lt from"node:tls";function Hw(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function pd(t=dd){if(ad)return;ad=!0;let e=V("EXTRA_CA_FILE");if(!(!e||!ud))try{let r=Hw(Kw(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Lt.setDefaultCACertificates([...Lt.getCACertificates(),...r]),t(`[tls] trusting ${r.length} extra CA cert(s) from ${e}`)}catch(r){t(`[tls] failed to load CODEPIPE_EXTRA_CA_FILE ${e}: ${r instanceof Error?r.message:String(r)}`)}}function fd(t){let e=t&&typeof t=="object"&&"cause"in t?t.cause?.code:void 0;return e==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||e==="UNABLE_TO_GET_ISSUER_CERT_LOCALLY"||e==="UNABLE_TO_GET_ISSUER_CERT"}function Ww(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
|
|
19
|
+
`)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function qw(t,e,r){return new Promise((n,o)=>{let i=Lt.connect({host:t,port:e,servername:t,rejectUnauthorized:!1},()=>{let s=i.getPeerCertificate(!0),a=new Set;for(;s?.issuerCertificate&&s.issuerCertificate!==s&&s.fingerprint256&&!a.has(s.fingerprint256);)a.add(s.fingerprint256),s=s.issuerCertificate;let c=s?.raw?new ld(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function Zs(t,e,r){return new Promise(n=>{let o=Lt.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{o.end(),n(!0)});o.on("error",()=>n(!1)),o.setTimeout(r,()=>{o.destroy(),n(!1)})})}async function Yw(t){try{let e=await fetch(t);return e.ok?new ld(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function md(t,e=443,r=dd){let n=`${t}:${e}`,o=cd.get(n);if(o)return o;let i=Vw(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return cd.set(n,i),i}async function Vw(t,e,r){if(!ud)return!1;let n=8e3;if(await Zs(t,e,n))return!0;let o=await qw(t,e,n),i=Lt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=Ww(o);if(!c)break;let l=await Yw(c);if(!l)break;if(s.push(l.toString()),Lt.setDefaultCACertificates([...i,...s]),await Zs(t,e,n))return r(`[tls] completed certificate chain for ${t} via AIA (+${s.length} intermediate cert(s))`),!0;if(l.subject===l.issuer)break;o=l}return Zs(t,e,n)}var ud,ad,cd,dd,gd=v(()=>{"use strict";_e();ud=typeof Lt.getCACertificates=="function"&&typeof Lt.setDefaultCACertificates=="function",ad=!1,cd=new Map,dd=t=>console.warn(t)});function wd(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function Ke(t,e,r){pd();let n={Authorization:`Bearer ${t.token}`,Accept:"application/json"};r?.body&&(n["Content-Type"]="application/json");let o=t.baseUrl+e,i={...r,headers:{...n,...r?.headers??{}}};try{return await fetch(o,i)}catch(s){if(fd(s)&&await md(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function zw(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Jw(){let t=Number(process.env.YOUTRACK_WRITE_RETRIES);return{attempts:Number.isFinite(t)&&t>=1?Math.floor(t):6,baseMs:1e3,capMs:15e3}}async function ea(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=Jw(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await Ke(t,r,n)}catch(u){a=new Error(`${e}: ${u instanceof Error?u.message:String(u)}`)}if(l){if(l.ok)return l;let u=await l.text();if(c<o&&zw(l.status,u)){await hd(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await hd(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Mt(t){let e;try{e=await Ke(t,"/api/users/me?fields=login,fullName")}catch(n){throw new Error(`cannot reach ${t.baseUrl} (${n instanceof Error?n.message:String(n)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the YouTrack PAT)");if(!e.ok)throw new Error(`YouTrack \u2192 ${e.status} ${e.statusText}`);let r=await e.json();return r.login??r.fullName??"ok"}async function bd(t){try{let e=await Ke(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function Xw(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=yd.get(o);if(i)return i;let s=await Ke(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!s.ok)throw new Error(`yt resolveStateId ${e}: ${s.status} ${await s.text()}`);let c=(await s.json()).customFields.find(u=>u.name===n);if(!c)throw new Error(`yt: issue ${e} has no ${n} custom field`);let l=c.projectCustomField.bundle.values.find(u=>u.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${n} bundle for ${e}`);return yd.set(o,l.id),l.id}async function $d(t,e,r,n=Kn){let o=await Xw(t,e,r,n);await ea(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:n,$type:"StateIssueCustomField",value:{id:o,$type:"StateBundleElement"}}]})})}async function vd(t,e,r){return await(await ea(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function xd(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await ea(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function Sd(t,e){let r=kd.get(e);if(r)return r;let n=await Ke(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!n.ok)throw new Error(`yt resolveProjectId: ${n.status} ${await n.text()}`);let i=(await n.json()).find(s=>s.shortName===e);if(!i)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return kd.set(e,i.id),i.id}async function Td(t,e,r,n,o,i=Kn){let s=await Sd(t,e),a=await Ke(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:s},summary:r,description:n,customFields:[{name:i,$type:"StateIssueCustomField",value:{name:o,$type:"StateBundleElement"}}]})});if(!a.ok)throw new Error(`yt createIssue: ${a.status} ${await a.text()}`);let c=await a.json();return{id:c.id,key:c.idReadable}}async function Ed(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await Ke(t,"/api/commands",{method:"POST",body:JSON.stringify({query:o,issues:[{idReadable:e}]})});if(!i.ok)throw new Error(`yt applyIssueLink (${o} on ${e}): ${i.status} ${await i.text()}`)}function Cd(t){if(!t||t.length===0)return;let e=[];for(let r of t)!r.url||!r.name||e.push({id:r.id,name:r.name,url:r.url,...r.mimeType?{mimeType:r.mimeType}:{},...typeof r.size=="number"?{size:r.size}:{}});return e.length>0?e:void 0}async function Ad(t,e){let r=e.startsWith("http")?e:t.baseUrl+e,n=await fetch(r,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok)throw new Error(`yt downloadAttachment ${e}: ${n.status}`);return Buffer.from(await n.arrayBuffer())}async function Pd(t,e){let r=e.stageField??Kn,n=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let c=e.columns.map(l=>`{${l}}`).join(", ");n.push(`${r}: ${c}`)}if(e.updatedSince){let c=new Date(e.updatedSince).toISOString().slice(0,10);n.push(`updated: ${c} .. *`)}e.assignee?n.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&n.push("has: Assignee");let o=n.join(" "),i=`/api/issues?query=${encodeURIComponent(o)}&fields=${Id}&$top=200`,s=await Ke(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>Nd(c,r))}async function _d(t,e,r=Kn){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Id}`,o=await Ke(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Nd(await o.json(),r)}async function jd(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${Zw}&$top=500`,o=await Ke(t,n);if(!o.ok)throw new Error(`yt listComments ${e}: ${o.status} ${await o.text()}`);return(await o.json()).filter(s=>s.created>r).map(s=>{let a={id:s.id,issueId:e,author:s.author?.login??"unknown",body:s.text??"",createdAt:new Date(s.created).toISOString()},c=Cd(s.attachments);return c&&(a.attachments=c),a})}function eb(t){if(!t||t.length===0)return;let e=[];for(let r of t){if(r.direction!=="INWARD")continue;let n=r.linkType?.name==="Depend"?"depends_on":r.linkType?.name==="Subtask"?"subtask":null;if(n)for(let o of r.issues??[])o.idReadable&&e.push({type:n,targetKey:o.idReadable})}return e.length>0?e:void 0}function Nd(t,e=Kn){let r=t.customFields??[],n=r.find(l=>l.name===e),o=r.find(l=>l.name==="Assignee"),i=r.find(l=>l.name==="Type"),s={id:t.id,key:t.idReadable,title:t.summary,status:n?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(s.description=t.description),o?.value?.login&&(s.assignee=o.value.login),i?.value?.name&&(s.issueType=i.value.name),t.tags&&t.tags.length>0&&(s.tags=t.tags.map(l=>l.name));let a=Cd(t.attachments);a&&(s.attachments=a);let c=eb(t.links);return c&&(s.links=c),s}async function Od(t,e){let r=await tb(t,e);return r.length>0?r:rb(t,e)}async function tb(t,e){let r=await Sd(t,e),n=await Ke(t,`/api/admin/projects/${encodeURIComponent(r)}/customFields?fields=$type,field(name),bundle(values(name,archived))&$top=100`);if(!n.ok)return[];let o=await n.json(),i=[];for(let s of o)s.$type==="StateProjectCustomField"&&s.field?.name&&i.push({name:s.field.name,values:Dd(s.bundle)});return i}async function rb(t,e){let r=`project: ${e}`,n=await Ke(t,`/api/issues?query=${encodeURIComponent(r)}&fields=customFields(name,$type,projectCustomField(bundle(values(name,archived))))&$top=1`);if(!n.ok)throw new Error(`yt fetchProjectStateFields ${e}: ${n.status} ${await n.text()}`);let o=await n.json(),i=[];for(let s of o[0]?.customFields??[])s.$type==="StateIssueCustomField"&&s.name&&i.push({name:s.name,values:Dd(s.projectCustomField?.bundle)});return i}function Dd(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var hd,Kn,yd,kd,Rd,Qw,Id,Zw,lr=v(()=>{"use strict";gd();hd=t=>new Promise(e=>setTimeout(e,t));Kn="Stage",yd=new Map;kd=new Map;Rd="attachments(id,name,url,size,mimeType)",Qw="links(direction,linkType(name),issues(idReadable))",Id=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Rd},${Qw}`,Zw=`id,text,created,author(login),${Rd}`});function et(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function Gr(t){return t instanceof Ge}async function Ld(t,e){let r=W(t),n=[],o=[],i=()=>Date.now();if(e?.trackerProvider==="internal")n.push({name:"tracker",ok:!0,detail:"built-in tracker"});else if(r?.youtrack?.url&&r.youtrack.token)try{let c=await Mt({baseUrl:r.youtrack.url,token:r.youtrack.token});n.push({name:"youtrack",ok:!0}),o.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"youtrack",ok:!1,detail:et(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:et(c),checkedAt:i()})}else n.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),o.push({kind:"youtrack",present:!1,checkedAt:i()});let s=!1;if(r?.github?.token){s=!0;try{let c=await jt(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){Gr(c)?(n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"github",ok:!1,detail:et(c)}),o.push({kind:"github",present:!0,ok:!1,detail:et(c),checkedAt:i()}))}}else o.push({kind:"github",present:!1,checkedAt:i()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){s=!0;try{let c=await Nt(r.bitbucket.email,r.bitbucket.apiToken);n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){Gr(c)?(n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"bitbucket",ok:!1,detail:et(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:et(c),checkedAt:i()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Ot(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){Gr(c)?(n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"gitlab",ok:!1,detail:et(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:et(c),checkedAt:i()}))}}else o.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||n.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let u of e?.repos??[])if(u.host==="github")try{await Qo(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){Gr(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:et(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await Qo(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){Gr(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:et(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Qo(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){Gr(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:i()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:et(l),checkedAt:i()})}else o.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:i()})}else o.push({kind:"contextWrite",present:!1,checkedAt:i()});let a=Ur(t);if(!a)n.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),o.push({kind:"claude",present:!1,checkedAt:i()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:i()});else{let c=await Ut(a);if(c==="invalid"){let l="Claude token rejected (401) \u2014 refresh via `claude setup-token`";n.push({name:"claude",ok:!1,detail:l}),o.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function Ut(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});return n.status===200?"valid":n.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}async function Md(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1000",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});if(n.status!==200)return null;let i=(await n.json())?.data;if(!Array.isArray(i))return null;let s=[];for(let a of i){let c=a?.id;if(typeof c!="string"||c.trim().length===0)continue;let l=a?.created_at;s.push({id:c,...typeof l=="string"?{createdAt:l}:{}})}return s}catch{return null}finally{clearTimeout(r)}}var Kr=v(()=>{"use strict";ue();Dt();lr()});import nb from"node:http";import ta from"node:crypto";function ei(){let t=ra(ta.randomBytes(32)),e=ra(ta.createHash("sha256").update(t).digest()),r=ra(ta.randomBytes(32));return{verifier:t,challenge:e,state:r}}function oa(t){let e=new URL(ob);return e.search=new URLSearchParams({response_type:"code",client_id:Ud,redirect_uri:t.redirectUri,scope:sb,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function cb(t,e){let r=t.get("error");if(r)throw new Error(`oauth-error: ${r}`);if(t.get("state")!==e)throw new Error("state-mismatch");let n=t.get("code");if(!n)throw new Error("no-code");return n}function Bd(t,e){let[r,n]=t.trim().split("#");if(!r)throw new Error("no-code");if(n!==void 0&&n!==e)throw new Error("state-mismatch");return r}function lb(t){let e=t,r=e?.access_token;if(!r||typeof r!="string")throw new Error(`no access_token in response: ${JSON.stringify(t)}`);return{oauthToken:r,...typeof e.refresh_token=="string"?{refreshToken:e.refresh_token}:{},...typeof e.expires_in=="number"?{expiresIn:e.expires_in}:{}}}async function ia(t){let e=await fetch(ib,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:t.code,state:t.state,redirect_uri:t.redirectUri,client_id:Ud,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return lb(await e.json())}async function sa(t){let e=t.timeoutMs??ab,r=nb.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=oa({redirectUri:o,challenge:t.challenge,state:t.state}),s,a=new Promise((l,u)=>{s=setTimeout(()=>u(new Error("no-callback")),e),r.on("request",(p,d)=>{let f=new URL(p.url??"/",o);if(f.pathname!=="/callback"){d.statusCode=404,d.end();return}clearTimeout(s),d.setHeader("content-type","text/html"),d.end("<h3>Authorized \u2014 you can close this tab.</h3>");try{l(cb(f.searchParams,t.state))}catch(m){u(m)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>ia({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function Fd(t){let e=await sa(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
|
|
20
|
+
${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var Ud,ob,ib,na,sb,ab,ra,aa=v(()=>{"use strict";Ud="9d1c250a-e61b-44d9-88ed-5944d1962f5e",ob="https://platform.claude.com/oauth/authorize",ib="https://platform.claude.com/v1/oauth/token",na="https://platform.claude.com/oauth/code/callback",sb="org:create_api_key user:profile user:inference",ab=12e4,ra=t=>Buffer.from(t).toString("base64url")});async function Gd(t,e,r,n,o){let i=c=>{e.readyState===e.OPEN&&e.send(JSON.stringify(c))},s=c=>i({type:"agent_login_url",requestId:r.requestId,projectId:t.projectId,error:c});if(V("ORIGIN")==="farm"||V("CLAUDE_AUTOLOGIN")==="0"){s("autologin_disabled");return}let a;try{a=await sa(ei())}catch(c){s(`listener failed: ${c instanceof Error?c.message:String(c)}`);return}i({type:"agent_login_url",requestId:r.requestId,projectId:t.projectId,authUrl:a.authUrl}),n.info(`[agent-auth] authorize Claude in a browser on THIS machine: ${a.authUrl}`),n.info(`[agent-auth] waiting for the redirect on ${a.redirectUri} \u2026`);try{let c=await a.waitForToken(),l=await Ut(c.oauthToken);if(l==="invalid"){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"token rejected (401) \u2014 previous token kept"}),n.warn("[agent-auth] new Claude token rejected (401) \u2014 previous token kept");return}let u=W(t.projectId);if(!u){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"no secrets file for this project on the CLI"}),n.warn("[agent-auth] no secrets file for this project \u2014 token not saved");return}u.claude={oauthToken:c.oauthToken},oe(u),n.info(`[agent-auth] Claude token replaced (${c.oauthToken.slice(0,12)}\u2026, ${c.oauthToken.length} chars)`),i({type:"agent_login_result",projectId:t.projectId,ok:!0,...l==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}}),o()}catch(c){let l=c instanceof Error?c.message:String(c);i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:l}),n.warn(`[agent-auth] browser authorization failed: ${l}`)}finally{a.close()}}var Kd=v(()=>{"use strict";_e();Kr();ue();aa()});function Hd(t,e){let r=t.find(n=>n.kind==="claude");return r?.present===!0&&r.ok===!1?V("ORIGIN")==="farm"||V("CLAUDE_AUTOLOGIN")==="0"||e?"none":"open":r?.ok===!0?"rearm":"none"}function Wd(t,e){return`${t.replace(/\/$/,"")}/?project=${encodeURIComponent(e)}`}var qd=v(()=>{"use strict";_e()});import{spawn as ub}from"node:child_process";function ur(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=ub(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var ti=v(()=>{"use strict"});import{setTimeout as db}from"node:timers/promises";import pb from"ws";function ri(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new pb(r)}async function Bt(t,e,r){return tt(t,e,"/projects",r)}async function Yd(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new K(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function ni(t,e,r,n){return tt(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function Vd(t,e,r,n){return tt(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function zd(t,e,r,n){return tt(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function Jd(t,e){let r=await fetch(`${t}/sandbox/me`,{headers:{Authorization:`Bearer ${e}`}});if(r.ok)return"ok";if(r.status===401)return"unknown";if(r.status===404)return"unsupported";throw new K(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function oi(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new K(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function ca(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new K(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function Xd(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await ca(t,e),a=new Set;for(let c of s)c.id!==r.excludeProjectId&&c.trackerProvider==="internal"&&c.youtrackProjectKey&&a.add(c.youtrackProjectKey.toUpperCase());return a}catch(s){o=s,i<n-1&&await db(r.delayMs??1500)}throw o}async function Qd(t,e){let r=await fetch(`${t}/cli/bootstrap-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})});if(r.status===403){let n;try{n=(await r.json()).error}catch{}if(n==="registration_required")throw new Hn(e)}if(!r.ok)throw new K(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function Zd(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new K(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function ep(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new K(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function tp(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new K(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function la(t,e,r,n){return tt(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function rp(t,e,r,n,o){return tt(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function np(t,e,r,n,o){return tt(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function op(t,e,r,n,o){return tt(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function Wn(t,e,r,n){return tt(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function ua(t,e,r,n){await tt(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function ip(t,e,r,n){return tt(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function sp(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/repos/${encodeURIComponent(n)}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new K(o.status,s,a)}return s}async function ne(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new K(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function tt(t,e,r,n){let o=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new K(o.status,s,a)}return s}var K,Hn,Re=v(()=>{"use strict";K=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};Hn=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});function cp(t){ap=t}function dr(t,e="info"){ap(t,e)}var ap,ii=v(()=>{"use strict";ap=t=>console.log(t)});import{homedir as fb,tmpdir as mb}from"node:os";import{existsSync as gb,mkdirSync as hb,mkdtempSync as yb,rmSync as kb}from"node:fs";import{join as qn}from"node:path";import{simpleGit as si}from"simple-git";function Te(t,e,r){let n=r??qn(fb(),".codepipe","repos");return qn(n,t,e)}async function xt(t,e,r={}){let n=Te(t,e.name,r.baseDir),o=r.cloneUrlOverride??Vn(e);if(!gb(qn(n,".git"))){hb(n,{recursive:!0});let a=si();dr(`[git] clone ${o} \u2192 ${n}`);try{await a.clone(o,n)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${o}
|
|
21
|
+
${l.trim()}`)}}let i=si(n);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
|
|
22
|
+
${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function pr(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function fr(t,e){let{contextRepoCloneUrl:r,deliveryRef:n,deliverySha:o,baseSha:i,commitMessage:s}=e;await t.raw(["fetch",r,`+refs/heads/${n}:refs/codepipe-delivery`]);let a=(await t.revparse(["refs/codepipe-delivery"])).trim();o&&a!==o&&dr(`[git] delivery ${n} resolved ${a.slice(0,10)} (expected ${o.slice(0,10)})`);let c=(await t.raw(["rev-parse","refs/codepipe-delivery^{tree}"])).trim();if(await pr(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await pr(t,i))throw new Error(`apply_delivery: base commit ${i.slice(0,10)} unavailable \u2014 cannot re-parent the delivery`);let l=(await t.raw([...ai,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function Yn(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await pr(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await pr(t,o)){let s=(await t.revparse([o])).trim();return await t.raw(["update-ref",n,s]).catch(()=>{}),s}let i=await r();return await t.raw(["update-ref",n,i]).catch(()=>{}),i}async function lp(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:u,force:p}=r,d=await Yn(t,i,()=>fr(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));p&&await t.raw(["branch","-D",a]).catch(()=>{});let f=`origin/${c}`;if(await pr(t,f)||(f=`origin/${u??c}`),(await t.revparse([f])).trim()===s)await t.raw(["branch","-f",a,d]),await t.checkout(a);else{await t.checkout(["-B",a,f]);try{await t.raw([...ai,"cherry-pick",d])}catch(w){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let y=w instanceof Error?w.message:String(w);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
|
|
23
|
+
${y.trim()}`)}}let h=(await t.revparse(["HEAD"])).trim(),g=r.push!==!1;if(g){let w=p?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push(w)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:h,pushed:g}}async function up(t,e,r){let n=r.force?["--force-with-lease","-u","origin",r.branchName]:["-u","origin",r.branchName];return await t.push(n),{pushed:!0}}async function dp(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,u=await Yn(t,i,()=>fr(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:c}));return await t.raw(["branch","-f",a,u]),l&&await t.push(["--force-with-lease","-u","origin",a]),{commit:u,pushed:l}}async function pp(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,baseRef:a,branchName:c,commitMessage:l,defaultBranch:u}=r,p=await Yn(t,i,()=>fr(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));await t.fetch().catch(()=>{});let d=`origin/${a}`;if(await pr(t,d)||(d=`origin/${u??a}`),(await t.revparse([d])).trim()===s)return await t.raw(["branch","-f",c,p]),{commit:p,branch:c};let m=yb(qn(mb(),"codepipe-apply-")),h=qn(m,"wt");try{await t.raw(["worktree","add","--detach",h,d]);let g=si(h);try{await g.raw([...ai,"cherry-pick",p])}catch(y){await g.raw(["cherry-pick","--abort"]).catch(()=>{});let x=y instanceof Error?y.message:String(y);throw new Error(`cherry-pick of ${i.slice(0,10)} onto ${a} hit conflicts
|
|
24
|
+
${x.trim()}`)}let w=(await g.revparse(["HEAD"])).trim();return await t.raw(["branch","-f",c,w]),{commit:w,branch:c}}finally{await t.raw(["worktree","remove","--force",h]).catch(()=>{}),kb(m,{recursive:!0,force:!0}),await t.raw(["worktree","prune"]).catch(()=>{})}}async function fp(t,e,r){let{branchName:n,dropTaskKeys:o}=r,i=`origin/${n}`;if(!await pr(t,i))throw new Error(`rewrite_cluster_branch: ${i} not found upstream`);let s=`origin/${r.defaultBranch??"main"}`,a=(await t.raw(["merge-base",i,s])).trim(),c=(await t.raw(["rev-list","--reverse",`${a}..${i}`])).split(`
|
|
25
25
|
`).map(f=>f.trim()).filter(f=>f.length>0),l=new Set(o.map(f=>f.toUpperCase())),u=[],p=0;for(let f of c)(await t.raw(["show","-s","--format=%(trailers:key=CodePipe-Task,valueonly)",f])).split(`
|
|
26
|
-
`).map(g=>g.trim().toUpperCase()).filter(g=>g.length>0).some(g=>l.has(g))?p++:u.push(f);if(p===0)return{commit:(await t.revparse([i])).trim(),dropped:0};await t.checkout(["-B",n,a]);for(let f of u)try{await t.raw([...
|
|
27
|
-
${h.trim()}`)}let d=(await t.revparse(["HEAD"])).trim();return await t.push(["--force-with-lease","-u","origin",n]),{commit:d,dropped:p}}async function
|
|
28
|
-
`).map(r=>r.trim()).filter(r=>r.length>0).map(r=>r.split(/\s+/)[1]??"").filter(r=>r.startsWith("refs/heads/")).map(r=>r.slice(11))}function
|
|
29
|
-
`)}async function
|
|
26
|
+
`).map(g=>g.trim().toUpperCase()).filter(g=>g.length>0).some(g=>l.has(g))?p++:u.push(f);if(p===0)return{commit:(await t.revparse([i])).trim(),dropped:0};await t.checkout(["-B",n,a]);for(let f of u)try{await t.raw([...ai,"cherry-pick","--allow-empty","--keep-redundant-commits",f])}catch(m){await t.raw(["cherry-pick","--abort"]).catch(()=>{}),await t.checkout(["-B",n,i]).catch(()=>{});let h=m instanceof Error?m.message:String(m);throw new Error(`rewrite_cluster_branch: replaying ${f.slice(0,10)} after dropping ${o.join(", ")} hit conflicts
|
|
27
|
+
${h.trim()}`)}let d=(await t.revparse(["HEAD"])).trim();return await t.push(["--force-with-lease","-u","origin",n]),{commit:d,dropped:p}}async function mp(t,e,r){let{branchName:n,baseBranch:o,mergeMethod:i,deleteBranch:s}=r,a=`origin/${n}`;return i==="squash"?(await t.raw(["merge","--squash",a]),await t.commit(`Merge branch '${n}'`)):i==="rebase"?(await t.checkout(["-B",n,a]),await t.rebase([o]),await t.checkout(o),await t.merge(["--ff-only",n])):await t.merge(["--no-ff",a,"-m",`Merge branch '${n}'`]),await t.push(["origin",o]),s&&await t.push(["origin","--delete",n]).catch(()=>{}),{mergedSha:(await t.revparse(["HEAD"])).trim()}}function Vn(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}async function gp(t){return(await si().listRemote(["--heads",t])).split(`
|
|
28
|
+
`).map(r=>r.trim()).filter(r=>r.length>0).map(r=>r.split(/\s+/)[1]??"").filter(r=>r.startsWith("refs/heads/")).map(r=>r.slice(11))}function hp(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}var ai,mr=v(()=>{"use strict";ii();ai=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{existsSync as li,readFileSync as wb,writeFileSync as bb}from"node:fs";import{join as hr}from"node:path";import{simpleGit as ci}from"simple-git";function kp(t){return hr(t,$b)}function yr(t){let e=kp(t);if(!li(e))return{};try{return JSON.parse(wb(e,"utf-8"))}catch{return{}}}function pa(t,e){bb(kp(t),JSON.stringify(e,null,2)+`
|
|
29
|
+
`)}async function wp(t,e,r,n,o){let i;try{i=await la(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(d){return{ok:!1,message:`claim failed: ${d instanceof Error?d.message:String(d)}`}}let s=[];for(let d of i.repos){let f=t.spec.repos.find(w=>w.name===d.repoName);if(!f)return{ok:!1,message:`repo "${d.repoName}" not in project.yaml \u2014 run /sync`};let m=hr(t.root,f.mountAs);if(!li(hr(m,".git")))return{ok:!1,message:`${f.mountAs}/ not cloned \u2014 run /sync first`};if(!(await ci(m).status()).isClean())return{ok:!1,message:`${f.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:d,spec:f,dir:m})}let a=[];for(let d of s){let f=ci(d.dir),m=await vb(f),h=d.claimRepo;try{await f.fetch()}catch(y){return await da(a,o),{ok:!1,message:`fetch failed in ${d.spec.mountAs}: ${gr(y)}`}}let g=`origin/${h.baseRef}`,w;try{w=await fr(f,{contextRepoCloneUrl:h.contextRepoCloneUrl,deliveryRef:h.deliveryRef,deliverySha:h.deliverySha,baseSha:h.baseSha,commitMessage:h.commitMessage})}catch(y){return await da(a,o),{ok:!1,message:`fetch delivery failed in ${d.spec.mountAs}: ${gr(y)}`}}a.push({git:f,dir:d.dir,mountAs:d.spec.mountAs,originalRef:m,branch:h.branchName,baseSha:g,deliveryCommit:w,startPoint:g})}let c=[];for(let d of a)try{if(n==="apply"){await d.git.checkout(["-B",d.branch,d.startPoint]),await d.git.raw([...yp,"cherry-pick",d.deliveryCommit]);let f=(await d.git.revparse(["HEAD"])).trim();c.push({mountAs:d.mountAs,branch:d.branch,baseSha:d.baseSha,appliedSha:f})}else await d.git.checkout(["--detach",d.startPoint]),await d.git.raw([...yp,"cherry-pick","--no-commit",d.deliveryCommit]),await d.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:d.mountAs,branch:d.branch,baseSha:d.baseSha})}catch(f){return await d.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await da(a,o),{ok:!1,message:`apply failed in ${d.mountAs}: ${gr(f)} (rolled back all repos)`}}let l=yr(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},pa(t.contextDir,l);let u=c.map(d=>d.mountAs).join(", "),p=n==="apply"?`review, push branch '${i.repos[0]?.branchName}', then: /applied ${r} --pr <url>`:`review with 'git diff', commit & push yourself, then: /applied ${r} --pr <url>`;return{ok:!0,message:`${n==="apply"?"applied":"unstashed"} ${r} in ${u}
|
|
30
30
|
${p}
|
|
31
|
-
or: /abort ${r} --reason "..."`}}async function
|
|
31
|
+
or: /abort ${r} --reason "..."`}}async function bp(t,e,r){let n=[];for(let c of e.repos){let l=t.repos.find(p=>p.name===c.repoName);if(!l)return{ok:!1,message:`repo "${c.repoName}" not in project.yaml \u2014 run /sync`};let u=hr(t.root,l.mountAs);if(!li(hr(u,".git")))return{ok:!1,message:`${l.mountAs}/ not cloned \u2014 run /sync first`};n.push({git:ci(u),dir:u,spec:l,cr:c})}let o=[],i=[];for(let c of n)try{let{commit:l}=await pp(c.git,c.dir,{contextRepoCloneUrl:c.cr.contextRepoCloneUrl,deliveryRef:c.cr.deliveryRef,deliverySha:c.cr.deliverySha,baseSha:c.cr.baseSha,baseRef:c.cr.baseRef,branchName:c.cr.branchName,commitMessage:c.cr.commitMessage,defaultBranch:c.spec.defaultBranch});r.info(`[apply] ${e.taskKey}: ${c.cr.branchName} \u2192 ${c.spec.mountAs} (${l.slice(0,10)})`),o.push({git:c.git,branch:c.cr.branchName}),i.push({mountAs:c.spec.mountAs,branch:c.cr.branchName,baseSha:`origin/${c.cr.baseRef}`,appliedSha:l})}catch(l){for(let u of o)await u.git.raw(["branch","-D",u.branch]).catch(()=>{});return{ok:!1,message:`auto-apply failed in ${c.spec.mountAs}: ${gr(l)}`}}try{await la(t.hubUrl,t.cliToken,t.projectId,e.taskKey)}catch(c){return{ok:!1,message:`branch created but claim failed: ${gr(c)} \u2014 retried on the next reconnect`,branches:o.map(l=>l.branch)}}let s=yr(t.contextDir);s[e.taskKey]={mode:"apply",claimedAt:new Date().toISOString(),repos:i},pa(t.contextDir,s);let a=i.map(c=>`${c.branch} (${c.mountAs})`).join(", ");return{ok:!0,branches:i.map(c=>c.branch),message:`branch created locally without touching your checkout: ${a}
|
|
32
32
|
review, push, then: /applied ${e.taskKey} --pr <url>
|
|
33
|
-
or: /abort ${e.taskKey} --reason "..."`}}function
|
|
33
|
+
or: /abort ${e.taskKey} --reason "..."`}}function fa(t,e){let r=yr(t);r[e]&&(delete r[e],pa(t,r))}async function da(t,e){for(let r of t)try{await r.git.raw(["cherry-pick","--quit"]).catch(()=>{}),await r.git.checkout(["-f",r.originalRef]),await r.git.reset(["--hard",r.originalRef]),await r.git.raw(["branch","-D",r.branch]).catch(()=>{})}catch(n){e.warn(`rollback failed in ${r.mountAs}: ${gr(n)} \u2014 check manually`)}}async function $p(t,e,r){let o=yr(t.contextDir)[e];if(o){for(let i of o.repos){let s=hr(t.root,i.mountAs);if(!li(hr(s,".git")))continue;let a=ci(s),c=t.spec.repos.find(u=>u.mountAs===i.mountAs),l=c?`origin/${c.defaultBranch}`:i.baseSha;try{await a.checkout(["-f",l]),await a.reset(["--hard",l]),await a.raw(["branch","-D",i.branch]).catch(()=>{})}catch(u){r.warn(`rollback failed in ${i.mountAs}: ${gr(u)} \u2014 check manually`)}}fa(t.contextDir,e)}}async function vb(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function gr(t){return t instanceof Error?t.message.trim():String(t)}var yp,$b,ma=v(()=>{"use strict";Re();mr();yp=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],$b="apply-queue.json"});import{existsSync as xb}from"node:fs";import{join as Sb}from"node:path";import{simpleGit as Tb}from"simple-git";async function vp(t,e){if(!xb(Sb(t,".git")))return{status:"skipped"};let r=Tb(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${Eb(o)}`}}let n=await r.status();if(!n.isClean())return{status:"warn",reason:"uncommitted changes \u2014 working copy left as-is"};if(n.current!==e)return{status:"warn",reason:`on '${n.current??"detached HEAD"}', not '${e}' \u2014 not fast-forwarded`};try{await r.merge(["--ff-only",`origin/${e}`])}catch{return{status:"warn",reason:`'${e}' can't fast-forward to origin (diverged) \u2014 not updated`}}return{status:"updated"}}function Eb(t){return t instanceof Error?t.message.trim():String(t)}var xp=v(()=>{"use strict"});import{existsSync as Sp,readFileSync as Tp,readdirSync as Rb,statSync as Ib}from"node:fs";import{join as ga}from"node:path";import{parse as Ep}from"yaml";function ui(t){let e=ga(t,"actions"),r=[],n=[];if(!Sp(e))return{defs:r,errors:n};let o;try{o=Rb(e).sort()}catch{return{defs:r,errors:n}}let i=new Set;for(let s of o){if(!/\.(yml|yaml)$/i.test(s))continue;let a=ga(e,s);try{if(!Ib(a).isFile())continue;let c=Jl(s,Ep(Tp(a,"utf-8")));if(i.has(c.id))throw new Error(`duplicate action id "${c.id}"`);i.add(c.id),r.push(c)}catch(c){n.push({file:`actions/${s}`,error:c instanceof Error?c.message:String(c)})}}return{defs:r,errors:n}}function Rp(t){let e={},r=ga(t,"project.yaml");if(!Sp(r))return e;let n;try{n=Ep(Tp(r,"utf-8"))}catch{return e}if(!n||typeof n!="object")return e;let o=n.variables;if(!o||typeof o!="object"||Array.isArray(o))return e;for(let[i,s]of Object.entries(o))!Be.test(i)||Pt(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var ha=v(()=>{"use strict";G()});import{existsSync as ya,readFileSync as Ip,readdirSync as Cb,watch as Ab}from"node:fs";import{join as zn}from"node:path";var di,Cp=v(()=>{"use strict";ha();di=class{constructor(e,r,n,o,i=6e4){this.contextDir=e;this.projectId=r;this.send=n;this.log=o;this.intervalMs=i}timer=null;watchers=[];debounce=null;started=!1;start(){this.started||(this.started=!0,this.report(),this.timer=setInterval(()=>this.report(),this.intervalMs),this.timer.unref?.(),this.installWatcher())}stop(){this.started=!1,this.timer&&clearInterval(this.timer),this.timer=null,this.debounce&&clearTimeout(this.debounce),this.debounce=null;for(let e of this.watchers)try{e.close()}catch{}this.watchers=[]}installWatcher(){let e=()=>{this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>this.report(),500),this.debounce.unref?.()},r=[this.contextDir,zn(this.contextDir,"prompts"),zn(this.contextDir,"actions")];for(let n of r)if(ya(n))try{let o=Ab(n,e);o.on("error",i=>{this.log.warn(`[config] fs.watch failed on ${n} \u2014 falling back to periodic reporting: ${i instanceof Error?i.message:String(i)}`);try{o.close()}catch{}}),this.watchers.push(o)}catch{}}reportNow(){this.report()}report(){try{this.send(this.read())}catch(e){this.log.warn(`[config] report failed: ${e instanceof Error?e.message:String(e)}`)}}read(){let e=ui(this.contextDir);return{type:"config_observation",projectId:this.projectId,projectYaml:this.readFile("project.yaml"),regimenYaml:this.readFile("regimen.yaml"),prompts:this.readPrompts(),actions:e.defs,actionErrors:e.errors}}readFile(e){let r=zn(this.contextDir,e);if(!ya(r))return null;try{return Ip(r,"utf-8")}catch{return null}}readPrompts(){let e=zn(this.contextDir,"prompts"),r={};if(!ya(e))return r;let n;try{n=Cb(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=Ip(zn(e,o),"utf-8")}catch{}}return r}}});import{existsSync as Ft,mkdirSync as Ap,readFileSync as ka,writeFileSync as Hr}from"node:fs";import{homedir as Pb}from"node:os";import{join as ht}from"node:path";import{simpleGit as _b}from"simple-git";function Jn(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=ht(t,o);Ft(s)||(Hr(s,i),r.push(o))}return r}function kr(t,e,r){let n=ht(Pb(),".codepipe","profiles",t,"context-config");return Ap(n,{recursive:!0}),Hr(ht(n,"project.yaml"),e.projectYaml),Hr(ht(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function pi(t,e,r){if(Ft(e))for(let n of Wr){let o=ht(e,n),i=ht(t,n);if(!(!Ft(o)||Ft(i)))try{Hr(i,ka(o)),r.info(`[config] seeded local ${n} from the provisioning bundle`)}catch(s){r.warn(`[config] could not seed ${n}: ${s instanceof Error?s.message:String(s)}`)}}}function qr(t){let e=ht(t,".gitignore"),r=Ft(e)?ka(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(Wr.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
|
|
34
34
|
`)?"":`
|
|
35
|
-
`;return Hr(e,r+i+
|
|
35
|
+
`;return Hr(e,r+i+jb.join(`
|
|
36
36
|
`)+`
|
|
37
|
-
`),!0}async function
|
|
38
|
-
`).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;qr(t),await r.raw(["rm","--cached","--quiet","--",...n]),await r.add([".gitignore"]),await r.commit("chore(context): move project config out of the Context Repo"),await
|
|
39
|
-
`)){let c=a.trim();if(c)try{let l=JSON.parse(c);if(typeof l.id!="string")continue;o.has(l.id)||o.set(l.id,{raw:c,createdAt:typeof l.createdAt=="string"?l.createdAt:""})}catch{}}let i=[...o.values()].sort((s,a)=>s.createdAt.localeCompare(a.createdAt)).map(s=>s.raw);
|
|
37
|
+
`),!0}async function Pp(t,e){try{if(!Ft(ht(t,".git")))return;let r=_b(t),n=(await r.raw(["ls-files","--",...Wr])).split(`
|
|
38
|
+
`).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;qr(t),await r.raw(["rm","--cached","--quiet","--",...n]),await r.add([".gitignore"]),await r.commit("chore(context): move project config out of the Context Repo"),await $a(t),e.info(`[config] migrated ${n.join(", ")} out of the Context Repo \u2014 the local copies are now the config`)}catch(r){e.warn(`[config] context-config migration failed (will retry on next start): ${r instanceof Error?r.message:String(r)}`)}}function wa(t){let e=new Map;for(let r of Wr){let n=ht(t,r);Ft(n)&&e.set(r,ka(n))}return e}function ba(t,e){Ap(t,{recursive:!0});for(let[r,n]of e){let o=ht(t,r);Ft(o)||Hr(o,n)}}var Wr,jb,St=v(()=>{"use strict";rt();Wr=["project.yaml","regimen.yaml"];jb=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as Nb,mkdirSync as Ob,rmSync as Db,writeFileSync as va}from"node:fs";import{dirname as Lb,isAbsolute as Mb,join as Np,normalize as gi}from"node:path";import{simpleGit as Op}from"simple-git";async function xa(t,e){let r=gi(t),o=(mi.get(r)??Promise.resolve()).catch(()=>{}).then(e);mi.set(r,o);try{return await o}finally{mi.get(r)===o&&mi.delete(r)}}async function Ie(t,e,r){return xa(t,()=>Sa(t,e,r))}async function Sa(t,e,r){if(!Nb(Np(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=he(t,a.path);if(a.deleted){Db(c,{force:!0});continue}Ob(Lb(c),{recursive:!0}),a.encoding==="base64"?va(c,Buffer.from(a.content,"base64")):va(c,a.content)}let n=Op(t),o=e.filter(a=>!a.deleted).map(a=>a.path),i=e.filter(a=>a.deleted).map(a=>a.path);for(let a=0;a<o.length;a+=fi)await n.raw(["add","-A","-f","--",...o.slice(a,a+fi)]);for(let a=0;a<i.length;a+=fi)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...i.slice(a,a+fi)]);await n.raw(["reset","-q","--",...Wr]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await $a(t))}async function $a(t){let e=Op(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=_p;n++){try{await e.push();return}catch(i){r=i}await e.fetch().catch(()=>{});let o=(await e.revparse(["--abbrev-ref","HEAD"])).trim();try{await e.rebase([`origin/${o}`])}catch{let i=await Gb(e);if(i.length>0&&i.every(a=>Ub.has(a)||jp.test(a)||Bb.test(a))){for(let a of i)jp.test(a)?await Fb(e,t,a):await e.raw(["checkout","--theirs","--",a]);await e.add(i),await e.raw(["-c","core.editor=true","rebase","--continue"])}else throw await e.rebase(["--abort"]).catch(()=>{}),new Error(`context push: rebase conflict in ${i.join(", ")||"unknown files"} \u2014 concurrent writers edited the same entry; resolve manually in the Context Repo`)}}throw new Error(`context push failed after ${_p} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function Fb(t,e,r){let n=async s=>await t.raw(["show",`:${s}:${r}`]).catch(()=>""),o=new Map;for(let s of[await n(2),await n(3)])for(let a of s.split(`
|
|
39
|
+
`)){let c=a.trim();if(c)try{let l=JSON.parse(c);if(typeof l.id!="string")continue;o.has(l.id)||o.set(l.id,{raw:c,createdAt:typeof l.createdAt=="string"?l.createdAt:""})}catch{}}let i=[...o.values()].sort((s,a)=>s.createdAt.localeCompare(a.createdAt)).map(s=>s.raw);va(he(e,r),i.join(`
|
|
40
40
|
`)+(i.length>0?`
|
|
41
|
-
`:""))}async function
|
|
42
|
-
`).map(r=>r.trim()).filter(Boolean)}function he(t,e){if(
|
|
43
|
-
`),r=e.find(i=>i.startsWith("# ")),n=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",o=i=>{let s=new RegExp(`^-\\s*\\*\\*${i}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=s.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:n,status:o("Status"),date:o("Date")}}function
|
|
44
|
-
`),a=s.findIndex(w=>w.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),u=[],p="",d=null,f=a>=0?a+1:0;for(let w=f;w<s.length;w++){let y=(s[w]??"").trim();if(y===""){f=w+1;continue}let
|
|
41
|
+
`:""))}async function Gb(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
|
|
42
|
+
`).map(r=>r.trim()).filter(Boolean)}function he(t,e){if(Mb(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=gi(Np(t,e)),n=gi(t+"/");if(r!==gi(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var _p,Ub,Bb,jp,fi,mi,rt=v(()=>{"use strict";St();_p=3,Ub=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),Bb=/^model\/derived\//,jp=/^tasks\/[^/]+\/comments\.jsonl$/,fi=500,mi=new Map});import{existsSync as Ta,readFileSync as Dp,readdirSync as Kb}from"node:fs";import{join as Lp}from"node:path";import{simpleGit as Hb}from"simple-git";function Yb(t){let e=t.split(`
|
|
43
|
+
`),r=e.find(i=>i.startsWith("# ")),n=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",o=i=>{let s=new RegExp(`^-\\s*\\*\\*${i}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=s.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:n,status:o("Status"),date:o("Date")}}function Vb(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
|
|
44
|
+
`),a=s.findIndex(w=>w.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),u=[],p="",d=null,f=a>=0?a+1:0;for(let w=f;w<s.length;w++){let y=(s[w]??"").trim();if(y===""){f=w+1;continue}let x=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(y);if(!x)break;let T=(x[1]??"").trim().toLowerCase(),R=(x[2]??"").trim(),E=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(y);E&&(d=parseInt(E[1]??"",10)),T==="tasks"&&(p=R),l.has(T)||u.push(y),f=w+1}let m=p?p.includes(n)?p:`${p}, ${n}`:n,h=s.slice(f).join(`
|
|
45
45
|
`).replace(/^\n+/,""),g=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${m}`,...u,"",h].join(`
|
|
46
46
|
`);return{content:g.endsWith(`
|
|
47
47
|
`)?g:g+`
|
|
48
|
-
`,supersedes:d}}function
|
|
48
|
+
`,supersedes:d}}function zb(t,e){let r=String(e).padStart(4,"0"),n=t.replace(/^(-\s*\*\*Status:\*\*).*$/im,`$1 superseded by ADR-${r}`);return n===t?t.replace(/^(# .*)$/m,`$1
|
|
49
49
|
|
|
50
|
-
- **Status:** superseded by ADR-${r}`):n}function
|
|
50
|
+
- **Status:** superseded by ADR-${r}`):n}function Jb(t){let e=["# ADR index","","<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->",""];if(t.length===0)e.push("(no accepted ADRs yet)");else for(let r of[...t].sort((n,o)=>n.num-o.num)){let n=String(r.num).padStart(4,"0"),o=[r.header.status||"accepted",r.header.date].filter(Boolean).join(", ");e.push(`- [ADR-${n} \u2014 ${r.header.title||r.file}](${r.file}) \u2014 ${o}`)}return e.join(`
|
|
51
51
|
`)+`
|
|
52
|
-
`}async function
|
|
52
|
+
`}async function Mp(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await Hb(t).pull(void 0,void 0,["--rebase"])}catch{}let i=g=>o==="staging"?`adr/DRAFT-${g}.md`:`tasks/${e}/adr/DRAFT-${g}.md`,s=[],a=[];for(let g of r){let w=he(t,i(g));if(!Ta(w)){a.push(g);continue}s.push({slug:g,content:Dp(w,"utf-8")})}let c=Lp(t,"adr"),l=new Map;if(Ta(c))for(let g of Kb(c)){let w=Wb.exec(g);!w||g===qb||l.set(g,{num:parseInt(w[1]??"",10),slug:w[2]??"",content:Dp(Lp(c,g),"utf-8")})}let u=Math.max(0,...[...l.values()].map(g=>g.num))+1,p=new Map,d=[],f=[];for(let g of s){if([...l.entries()].find(([,E])=>E.slug===g.slug&&E.content.includes(e))){f.push(g.slug);continue}let y=u++,x=`${String(y).padStart(4,"0")}-${g.slug}.md`,{content:T,supersedes:R}=Vb(g.content,y,g.slug,e,n);if(p.set(x,T),l.set(x,{num:y,slug:g.slug,content:T}),d.push(`adr/${x}`),R!==null){let E=[...l.keys()].find(b=>b.startsWith(`${String(R).padStart(4,"0")}-`));if(E&&E!==x){let b=zb(p.get(E)??l.get(E).content,y);p.set(E,b),l.set(E,{...l.get(E),content:b})}}}let m=[];if(o==="staging")for(let g of s)Ta(he(t,`adr/DRAFT-${g.slug}.md`))&&m.push({path:`adr/DRAFT-${g.slug}.md`,content:"",deleted:!0});if(d.length===0&&m.length===0)return{promoted:d,skipped:f,missing:a};if(d.length>0){let g=[...l.entries()].map(([w,y])=>({num:y.num,file:w,header:Yb(y.content)}));p.set("INDEX.md",Jb(g))}for(let[g,w]of p.entries())m.push({path:`adr/${g}`,content:w});let h=d.length>0?`adr(${e}): promote ${s.map(g=>g.slug).join(", ")}`:`adr(${e}): drop stale staged ${f.join(", ")}`;return await Ie(t,m,h),{promoted:d,skipped:f,missing:a}}var Wb,qb,Up=v(()=>{"use strict";rt();Wb=/^(\d{4})-(.+)\.md$/,qb="0000-template.md"});import{existsSync as Bp,readFileSync as Qb}from"node:fs";import{join as Fp}from"node:path";function Zb(t){for(let e of[ut,Nn]){let r=Fp(t,e);if(Bp(r))try{return $l(Qb(r,"utf-8"))}catch{return 0}}return 0}function e$(t,e,r,n=4){let o=e<n,i=o?vl(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function hi(t,e){return e$(e,Zb(t),r=>Bp(Fp(t,r)))}var Ea=v(()=>{"use strict";G()});import{existsSync as Gt,readFileSync as Yr,readdirSync as Kp}from"node:fs";import{join as Ra}from"node:path";import{simpleGit as Hp}from"simple-git";import{parse as Wp}from"yaml";function qp(t){try{let e=he(t,Uo);if(!Gt(e))return null;let r=Wp(Yr(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!Dr.test(n)?null:{prefix:n}}catch{return null}}function Yp(t){return`# Built-in tracker configuration \u2014 shared by every team member.
|
|
53
53
|
# The issue-key prefix (<PREFIX>-<N>). Fixed at project init: changing it
|
|
54
54
|
# later would orphan existing tasks/<KEY>/ directories.
|
|
55
55
|
prefix: ${t}
|
|
@@ -57,15 +57,15 @@ prefix: ${t}
|
|
|
57
57
|
# Statuses are the built-in default set for now:
|
|
58
58
|
# Backlog | To Do | In Progress | Review | Done | Rejected
|
|
59
59
|
# A configurable status set / pipeline mapping is a planned extension.
|
|
60
|
-
`}function
|
|
61
|
-
`}function
|
|
60
|
+
`}function Ia(t=0){return`${t}
|
|
61
|
+
`}function t$(t){return t==="depends_on"||t==="subtask"}function r$(t){let e;try{e=Wp(t)}catch{return null}if(!e||typeof e!="object")return null;let r=e;if(typeof r.key!="string"||r.key.length===0||typeof r.title!="string"||r.title.length===0)return null;let n=wu.includes(r.type)?r.type:Mo,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;t$(l.type)&&typeof l.target=="string"&&l.target&&o.push({type:l.type,targetKey:l.target})}let i=typeof r.created=="string"?r.created:new Date(0).toISOString(),s=typeof r.updated=="string"?r.updated:i,a=typeof r.assignee=="string"&&r.assignee.trim().length>0?r.assignee.trim():void 0;return{key:r.key,title:r.title,type:n,status:typeof r.status=="string"&&r.status?r.status:"Backlog",...a?{assignee:a}:{},links:o,created:i,updated:s}}function Ca(t){let e=[`key: ${t.key}`,`title: ${JSON.stringify(t.title)}`,`type: ${t.type}`,`status: ${JSON.stringify(t.status)}`];if(t.assignee&&e.push(`assignee: ${JSON.stringify(t.assignee)}`),t.links.length>0){e.push("links:");for(let r of t.links)e.push(` - type: ${r.type}`,` target: ${r.targetKey}`)}return e.push(`created: ${t.created}`,`updated: ${t.updated}`),e.join(`
|
|
62
62
|
`)+`
|
|
63
|
-
`}function
|
|
63
|
+
`}function Qn(t,e){let r=he(t,Bn(e));return Gt(r)?r$(Yr(r,"utf-8")):null}function Vp(t){let e=Ra(t,"tasks");if(!Gt(e))return[];let r=[];for(let n of Kp(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=Qn(t,n.name);o&&r.push(o)}return r}function n$(t,e){let r=he(t,`tasks/${e}/task.md`);if(!Gt(r))return;let n=Yr(r,"utf-8").split(`
|
|
64
64
|
`),o=n.indexOf("---");if(o<0)return;let i=n.slice(o+1),s=i.lastIndexOf("## Attachments");s>=0&&i.slice(s+1).every(u=>u.trim()===""||/^- \[[^\]]*\]\(attachments\/[^)]*\)$/.test(u.trim()))&&(i=i.slice(0,s));let a=i.join(`
|
|
65
|
-
`).trim();if(!(!a||a==="_(no description)_"))return a}function
|
|
65
|
+
`).trim();if(!(!a||a==="_(no description)_"))return a}function Zn(t,e,r={}){let n=r.withDescription?n$(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:o$(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function o$(t){return t.charAt(0).toUpperCase()+t.slice(1)}function i$(t){let e=he(t,Un);if(!Gt(e))return 0;let r=Number.parseInt(Yr(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function s$(t,e){let r=Ra(t,"tasks");if(!Gt(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of Kp(r,{withFileTypes:!0})){if(!i.isDirectory())continue;let s=n.exec(i.name);if(!s)continue;let a=Number.parseInt(s[1],10);Number.isFinite(a)&&a>o&&(o=a)}return o}function a$(t,e){return Math.max(i$(t),s$(t,e))+1}async function zp(t,e,r,n){return xa(t,()=>c$(t,e,r,n))}async function c$(t,e,r,n){if(!Gt(Ra(t,".git")))throw new Error(`context repo clone not found at ${t}`);await Xn(t);let o=null;for(let i=0;i<Gp;i++){let s=a$(t,e),a=`${e}-${s}`,c=[...r(a),{path:Un,content:Ia(s)}];try{return await Sa(t,c,n(a)),a}catch(l){if(o=l,await u$(t,n(a)),await Xn(t),l$(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${Gp} attempts: ${o instanceof Error?o.message:String(o)}`)}function l$(t,e){for(let r of e){let n=he(t,r.path);if(!Gt(n)||(r.encoding==="base64"?Yr(n).toString("base64"):Yr(n,"utf-8"))!==r.content)return!1}return!0}async function Xn(t){let e=Hp(t);try{await e.fetch()}catch{return}try{let r=(await e.revparse(["--abbrev-ref","HEAD"])).trim();await e.rebase([`origin/${r}`])}catch{await e.rebase(["--abort"]).catch(()=>{})}}async function u$(t,e){let r=Hp(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
|
|
66
66
|
`)[0]||!(await r.raw(["log","@{u}..HEAD","--pretty=%s"]).catch(()=>"")).trim().split(`
|
|
67
67
|
`).some(i=>i.trim()===e.split(`
|
|
68
|
-
`)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var
|
|
68
|
+
`)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var Gp,yi=v(()=>{"use strict";G();rt();Gp=5});function Vr(t,e,r,n){return[{path:"README.md",content:v$(t,e)},{path:".gitignore",content:h$()},{path:"CLAUDE.md",content:k$(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:y$()},{path:"knowledge/README.md",content:w$()},{path:"knowledge/build.yaml",content:$$()},{path:"actions/README.md",content:b$()},{path:"model/README.md",content:d$()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:g$()},{path:"adr/README.md",content:p$()},{path:"adr/0000-template.md",content:f$()},{path:"adr/INDEX.md",content:m$()},{path:ut,content:Po()},...t.trackerProvider==="internal"?[{path:Uo,content:Yp(t.youtrackProjectKey??Bs)},{path:Un,content:Ia()}]:[]]}function d$(){return`# model/ \u2014 the project map
|
|
69
69
|
|
|
70
70
|
A graph of the project built from **git history and task artifacts**: files
|
|
71
71
|
and directories connected by the fact of changing together and the fact of
|
|
@@ -92,7 +92,7 @@ asset \u2014 treat it like \`knowledge/\`.
|
|
|
92
92
|
|
|
93
93
|
Every YAML file carries \`modelFormatVersion\`; a reader that meets a
|
|
94
94
|
different version treats it as "rebuild needed", not as an error.
|
|
95
|
-
`}function
|
|
95
|
+
`}function p$(){return`# ADR \u2014 architecture decision records
|
|
96
96
|
|
|
97
97
|
Accepted architectural decisions of this project \u2014 its **framework**. The
|
|
98
98
|
agent reads this section (start with \`INDEX.md\`) at the beginning of every
|
|
@@ -120,7 +120,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
|
|
|
120
120
|
canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
|
|
121
121
|
is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
|
|
122
122
|
open a PR to this repository.
|
|
123
|
-
`}function
|
|
123
|
+
`}function f$(){return`# ADR-NNNN: <title>
|
|
124
124
|
|
|
125
125
|
- **Status:** accepted | superseded by ADR-NNNN
|
|
126
126
|
- **Date:** YYYY-MM-DD
|
|
@@ -142,12 +142,12 @@ What becomes easier, what becomes harder, what future tasks must keep doing.
|
|
|
142
142
|
## Alternatives considered
|
|
143
143
|
|
|
144
144
|
- **<alternative>** \u2014 why it was rejected.
|
|
145
|
-
`}function
|
|
145
|
+
`}function m$(){return`# ADR index
|
|
146
146
|
|
|
147
147
|
<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->
|
|
148
148
|
|
|
149
149
|
(no accepted ADRs yet)
|
|
150
|
-
`}function
|
|
150
|
+
`}function g$(){return`# Audit
|
|
151
151
|
|
|
152
152
|
Pipeline event logs. Naming is per-writer: each codepipe
|
|
153
153
|
project appends only to its own file \u2014
|
|
@@ -156,14 +156,14 @@ project appends only to its own file \u2014
|
|
|
156
156
|
|
|
157
157
|
\u2014 so several team members' CLIs never contend on one file. Do not create a
|
|
158
158
|
shared aggregate here.
|
|
159
|
-
`}function yt(t,e,r,n,o="auto",i=pt,s){let a=t.trackerProvider==="internal";return{projectYaml:a?
|
|
159
|
+
`}function yt(t,e,r,n,o="auto",i=pt,s){let a=t.trackerProvider==="internal";return{projectYaml:a?x$(t,o):S$(t,r,n,o),regimenYaml:T$(t.automationLevel,a?!0:e,a,i,s)}}function h$(){return`# codepipe project config is local to each member's workspace
|
|
160
160
|
project.yaml
|
|
161
161
|
regimen.yaml
|
|
162
162
|
|
|
163
163
|
# codepipe runtime
|
|
164
164
|
session.log
|
|
165
165
|
apply-queue.json
|
|
166
|
-
`}function
|
|
166
|
+
`}function y$(){return`# Index prompt
|
|
167
167
|
|
|
168
168
|
You are the **Indexer** agent on the CodePipe pipeline. Your one job is to build a
|
|
169
169
|
navigation map of this project's repositories and save it to the Context Repo, so
|
|
@@ -220,7 +220,7 @@ current working directory; write nothing else under the Context Repo.
|
|
|
220
220
|
Keep both durable and skimmable \u2014 they are read at the start of every future
|
|
221
221
|
task. Prefer structure (headings, bullet lists) over prose. If a repository is
|
|
222
222
|
empty or unavailable, say so briefly rather than inventing content.
|
|
223
|
-
`}function
|
|
223
|
+
`}function k$(t){return`# Project context for the CodePipe agent
|
|
224
224
|
|
|
225
225
|
Instructions for AI agents working on **${t.name}** tasks. Claude Code
|
|
226
226
|
auto-loads this file when the Context Repo is mounted. Keep it short and
|
|
@@ -248,7 +248,7 @@ project's architectural invariants: read them at the start of a task and treat
|
|
|
248
248
|
them as binding. New or changed decisions do **not** go here directly \u2014 during
|
|
249
249
|
analysis you draft them as task artifacts, and they are promoted into \`adr/\`
|
|
250
250
|
only after the analysis is approved.
|
|
251
|
-
`}function
|
|
251
|
+
`}function w$(){return`# Knowledge
|
|
252
252
|
|
|
253
253
|
Durable, reusable notes about this project \u2014 the CodePipe agent's long-lived
|
|
254
254
|
**memory** across tasks. Architectural decisions, domain rules,
|
|
@@ -265,7 +265,7 @@ Keep each note in its own file \u2014 never grow one shared aggregate \u2014 so
|
|
|
265
265
|
concurrent commits touch different files and rebase cleanly. \`INDEX.md\` is
|
|
266
266
|
REGENERATED from the entries by the index job: don't hand-edit it, and treat
|
|
267
267
|
any merge conflict in it as noise (either side converges on the next run).
|
|
268
|
-
`}function
|
|
268
|
+
`}function b$(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
|
|
269
269
|
|
|
270
270
|
One \`<id>.yml\` per action. Every file here appears as a button on the
|
|
271
271
|
project's **RUN** tab; an action with \`params\` opens a small wizard first.
|
|
@@ -304,7 +304,7 @@ steps:
|
|
|
304
304
|
Parameter values are passed to the commands **only as env vars** \u2014 reference
|
|
305
305
|
them as \`$INPUT_<NAME>\` in \`run\`; they are never substituted into the
|
|
306
306
|
command text itself.
|
|
307
|
-
`}function
|
|
307
|
+
`}function $$(){return`# BUILD phase config. Discovered & maintained by the agent.
|
|
308
308
|
# Steps run in a rootless Podman container in the SANDBOX, before the PR.
|
|
309
309
|
# Success = every step exits 0. Credentials are NOT available inside the container.
|
|
310
310
|
#
|
|
@@ -320,7 +320,7 @@ command text itself.
|
|
|
320
320
|
# - name: test
|
|
321
321
|
# run: npm test
|
|
322
322
|
# timeout_sec: 600 # per-step timeout (optional, default 600)
|
|
323
|
-
`}function
|
|
323
|
+
`}function v$(t,e){return`# ${e.name}
|
|
324
324
|
|
|
325
325
|
Context Repo for the **${t.name}** project (CodePipe).
|
|
326
326
|
|
|
@@ -346,7 +346,7 @@ PRs to this repository (and the agent also writes to \`knowledge/\` and
|
|
|
346
346
|
pipeline \u2014 don't edit them by hand.
|
|
347
347
|
|
|
348
348
|
Automation level: **${t.automationLevel}**.
|
|
349
|
-
`}function
|
|
349
|
+
`}function x$(t,e="auto"){return`# Project description for CodePipe.
|
|
350
350
|
id: ${t.projectId}
|
|
351
351
|
name: ${t.name}
|
|
352
352
|
|
|
@@ -367,24 +367,24 @@ apply:
|
|
|
367
367
|
# Branch (must keep the <TASK_ID> placeholder).
|
|
368
368
|
branch:
|
|
369
369
|
pattern: codepipe/<TASK_ID>
|
|
370
|
-
${
|
|
370
|
+
${Jp(t)}
|
|
371
371
|
repos:
|
|
372
|
-
${
|
|
373
|
-
`}function
|
|
372
|
+
${Xp(t)}
|
|
373
|
+
`}function Jp(t){let e=t.language;return!e||Object.keys(e).length===0?"":`
|
|
374
374
|
# Languages the agent writes in, per area. \`auto\` = mirror the language of
|
|
375
375
|
# the user's material. Also editable from the dashboard: project card \u2192
|
|
376
376
|
# Settings \u2192 Language.
|
|
377
377
|
language:
|
|
378
378
|
${Object.entries(e).map(([n,o])=>` ${n}: ${o}`).join(`
|
|
379
379
|
`)}
|
|
380
|
-
`}function
|
|
380
|
+
`}function Xp(t){return t.repos.length===0?` [] # add repos here
|
|
381
381
|
`:t.repos.map(e=>` - name: ${e.name}
|
|
382
382
|
host: ${e.host}
|
|
383
383
|
owner: ${e.owner}
|
|
384
384
|
repo: ${e.repoName}
|
|
385
385
|
mount_as: ${e.mountAs??e.name}`+(e.defaultBranch?`
|
|
386
386
|
default_branch: ${e.defaultBranch}`:"")).join(`
|
|
387
|
-
`)}function
|
|
387
|
+
`)}function S$(t,e,r,n="auto"){let o=e?`
|
|
388
388
|
tracker_url: ${e}`:`
|
|
389
389
|
# tracker_url: https://your.youtrack.cloud`,i=r?`require_assignee: true
|
|
390
390
|
assignee: ${r}`:`require_assignee: false
|
|
@@ -432,7 +432,7 @@ ${Object.entries(e).map(([n,o])=>` ${n}: ${o}`).join(`
|
|
|
432
432
|
# non-empty assignee. assignee only takes effect when require_assignee=true.
|
|
433
433
|
${i}`:` # project_key: \u2026
|
|
434
434
|
# tracker_url: https://your.youtrack.cloud
|
|
435
|
-
poll_interval_sec: 60`,a=
|
|
435
|
+
poll_interval_sec: 60`,a=Xp(t);return`# Project description for CodePipe.
|
|
436
436
|
id: ${t.projectId}
|
|
437
437
|
name: ${t.name}
|
|
438
438
|
|
|
@@ -460,10 +460,10 @@ apply:
|
|
|
460
460
|
# Branch (must keep the <TASK_ID> placeholder).
|
|
461
461
|
branch:
|
|
462
462
|
pattern: codepipe/<TASK_ID>
|
|
463
|
-
${
|
|
463
|
+
${Jp(t)}
|
|
464
464
|
repos:
|
|
465
465
|
${a}
|
|
466
|
-
`}function
|
|
466
|
+
`}function T$(t,e,r=!1,n=pt,o){let i=t==="full",s=e?"true":"false",a=o?` # Model selection. This project's Claude subscription did not include every
|
|
467
467
|
# model in the recommended per-role split, so CodePipe set a single default
|
|
468
468
|
# your subscription can serve for all roles. Tune per role later from the
|
|
469
469
|
# dashboard (Project Settings \u2192 llm.models) or by editing this file.
|
|
@@ -614,11 +614,11 @@ ${a}
|
|
|
614
614
|
# # While this key stays commented out, the project keeps its current mode \u2014
|
|
615
615
|
# # only new projects start on cluster-pr. Uncomment and set a value to switch.
|
|
616
616
|
# mode: cluster-pr
|
|
617
|
-
`}var wr=
|
|
618
|
-
`)}async function Qp(t,e,r,n){let o=Ra(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=mi(t,e);if(!i.outdated)return i;let s=S$(i.currentVersion),a=r?.branch??(await o.revparse(["--abbrev-ref","HEAD"]).catch(()=>"main")).trim();try{await o.fetch().catch(()=>{}),(await o.raw(["ls-remote","--heads","origin",s]).catch(()=>"")).trim().length===0?await E$(t,e,r,i,s,a,n):n.info(`[ctx] migration branch ${s} already on origin \u2014 reusing`)}catch(l){return n.warn(`[ctx] context migration branch failed (will retry next start): ${l instanceof Error?l.message:String(l)}`),i}if(!r)return i;let c={name:r.name,host:r.host,owner:r.owner,repoName:r.name};try{let l=Ze(c),u=await l.findOpenPrByBranch?.(c,s)??null;if(u)return n.info(`[ctx] migration PR already open: ${u.url}`),{...i,migrationPrUrl:u.url};let p=await l.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:s,baseBranch:a,title:`CodePipe: context format v${i.templateVersion} \u2192 v${i.currentVersion}`,body:T$(i)});return n.info(`[ctx] migration PR opened: ${p.url}`),{...i,migrationPrUrl:p.url}}catch(l){return n.warn(`[ctx] migration PR create/find failed (branch pushed, badge without link): ${l instanceof Error?l.message:String(l)}`),i}}async function E$(t,e,r,n,o,i,s){let a=Ra(t),c=$$(hi(v$(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",o,c,`origin/${i}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},u={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},p=new Map(Vr(l,u).map(h=>[h.path,h.content])),d=0;for(let h of n.missingPaths){if(h===ut)continue;let g=p.get(h);if(g==null){s.warn(`[ctx] migration: no template for ${h} \u2014 skipped`);continue}let w=hi(c,h);zp(w)||(b$(x$(w),{recursive:!0}),Xp(w,g),d++)}Xp(hi(c,ut),Co(n.currentVersion)),d++;let f=hi(c,_n);zp(f)&&(Jp(f,{force:!0}),d++);let m=Ra(c);await m.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await m.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await m.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${d} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),Jp(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}var Zp=x(()=>{"use strict";G();Dt();xa();wr()});import{existsSync as R$,readFileSync as I$,writeFileSync as C$}from"node:fs";import{homedir as A$}from"node:os";import{join as ef}from"node:path";import{parseDocument as P$}from"yaml";function _$(t){let e={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(e.default_branch=t.defaultBranch),e}function j$(t,e){let r=P$(t);return r.set("repos",e.map(_$)),r.toString()}function N$(t,e){let r=[ef(A$(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(ef(e,"project.yaml")),r}function Qn(t,e,r){let n=[],o=[];for(let i of N$(t,r))if(R$(i))try{let s=I$(i,"utf-8"),a=j$(s,e);a!==s&&(C$(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}var Ia=x(()=>{"use strict"});import{createCipheriv as O$,createDecipheriv as D$,createHash as L$,createPrivateKey as M$,createPublicKey as Ca,diffieHellman as tf,generateKeyPairSync as rf,hkdfSync as nf,randomBytes as U$}from"node:crypto";function yi(){let{publicKey:t,privateKey:e}=rf("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function je(t){let e=Buffer.from(t,"base64");return(L$("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function Tt(t,e){let r=Ca({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=rf("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=tf({privateKey:o,publicKey:r}),c=Buffer.from(nf("sha256",a,Buffer.concat([i,s]),of,32)),l=U$(12),u=O$("aes-256-gcm",c,l),p=typeof e=="string"?Buffer.from(e,"utf-8"):e,d=Buffer.concat([u.update(p),u.final()]),f=u.getAuthTag(),m={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:f.toString("base64"),ct:d.toString("base64")};return Buffer.from(JSON.stringify(m),"utf-8").toString("base64")}function zr(t,e){let r=JSON.parse(Buffer.from(e,"base64").toString("utf-8"));if(r.v!==1)throw new Error(`sealedbox: unsupported envelope version ${r.v}`);let n=M$({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=Ca({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=Ca(n).export({type:"spki",format:"der"}),a=tf({privateKey:n,publicKey:o}),c=Buffer.from(nf("sha256",a,Buffer.concat([i,s]),of,32)),l=D$("aes-256-gcm",c,Buffer.from(r.iv,"base64"));return l.setAuthTag(Buffer.from(r.tag,"base64")),Buffer.concat([l.update(Buffer.from(r.ct,"base64")),l.final()])}var of,He=x(()=>{"use strict";of=Buffer.from("devpipe-sealedbox-v1","utf-8")});function B$(t,e){let r={};t.github?.token&&(r.github={token:t.github.token}),t.bitbucket?.apiToken&&(r.bitbucket={apiToken:t.bitbucket.apiToken}),t.gitlab?.token&&(r.gitlab={token:t.gitlab.token});let n=e??t.claude?.oauthToken;return n&&(r.claudeOauthToken=n),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),r}function sf(t,e,r,n){let o=B$(e,r);t.sandboxes.length>0&&!o.claudeOauthToken&&n.warn("[cred] no Claude OAuth token set \u2014 agent jobs will fail in the SANDBOX. Set one with `codepipe login` (per project) or `make farm-config` (shared farm token)."),t.sandboxes.length>0&&!o.contextWrite&&(o.github||o.gitlab||o.bitbucket)&&n.warn("[cred] no dedicated contextWrite token \u2014 SANDBOX pushes deliveries with the project token of the context repo's host (broader scope than necessary). Set secrets.contextWrite.token (a token scoped to the Context Repo only) to tighten. NOTE (GitHub): the push token MUST have the `workflow` scope, else delivery pushes that carry `.github/workflows/*` are rejected.");let i=JSON.stringify(o),s=[];for(let a of t.sandboxes){let c=Ho(t.projectId,a.sandboxId,a.fingerprint);if(c==="mismatch"){n.warn(`[cred] SANDBOX ${a.name} (${a.sandboxId}) key fingerprint CHANGED \u2014 refusing to seal creds. Expected the pinned key; got ${a.fingerprint}. If this is intentional, clear the pin in the secrets file and re-run.`);continue}c==="pinned"&&n.info(`[cred] pinned SANDBOX ${a.name} (${a.sandboxId}) fingerprint ${a.fingerprint}`);let l;try{l=Tt(a.publicKey,i)}catch(u){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}var af=x(()=>{"use strict";He();ue()});function Zn(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@github.com:"),o(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function eo(t,e=process.env){if(!t)return!1;let r=`https://oauth2:${t}@gitlab.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@gitlab.com:"),o(1,"ssh://git@gitlab.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function to(t,e=process.env){if(!t)return!1;let r=`https://${sr}:${encodeURIComponent(t)}@bitbucket.org/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@bitbucket.org:"),o(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function Aa(t,e,r,n){let o=Number.parseInt(n.GIT_CONFIG_COUNT??"0",10)||0,i=!1;for(let s=0;s<o;s++){let a=n[`GIT_CONFIG_KEY_${s}`];a&&t.test(a)&&(n[`GIT_CONFIG_KEY_${s}`]=`url.${e}.insteadOf`,i=!0)}return i||r()}function cf(t,e=process.env){return Aa(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>Zn(t,e),e)}function lf(t,e=process.env){return Aa(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>eo(t,e),e)}function uf(t,e=process.env){return Aa(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${sr}:${encodeURIComponent(t)}@bitbucket.org/`,()=>to(t,e),e)}var ki=x(()=>{"use strict";G()});function df(t){let e=W(t);if(!e)return null;if(!e.sealKey){let r=yi();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},oe(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:je(e.sealKey.publicKey)}}async function pf(t,e,r,n){let o;try{o=JSON.parse(zr(n,r).toString("utf-8"))}catch(s){return{ok:!1,detail:`cannot open the sealed credential (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}let i=W(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await jt(o.token);return i.github={token:o.token},Jr(i,()=>{process.env.GH_TOKEN=o.token,cf(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Ot(o.token);return i.gitlab={token:o.token},Jr(i,()=>{process.env.GITLAB_TOKEN=o.token,lf(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"bitbucket":{if(!o.email||!o.apiToken)return{ok:!1,detail:"payload needs email + apiToken"};let s=await Nt(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},Jr(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,uf(o.apiToken)}),{ok:!0,detail:`authenticated as ${s}`}}case"youtrack":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=o.url?.trim().replace(/\/$/,"")||i.youtrack?.url;if(!s)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await Mt({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},Jr(i,()=>{process.env.YOUTRACK_URL=s,process.env.YOUTRACK_TOKEN=o.token}),{ok:!0,detail:`authenticated as ${a}`}}case"claude":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Ut(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},Jr(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},Jr(i,()=>{}),{ok:!0,detail:"saved (verified on the next readiness pass)"}):{ok:!1,detail:"payload has no token"};default:return{ok:!1,detail:`unknown credential kind '${e}'`}}}catch(s){return{ok:!1,detail:`${s instanceof Error?s.message:String(s)} \u2014 previous credential kept`}}}function Jr(t,e){oe(t),e()}var ff=x(()=>{"use strict";He();ue();Dt();lr();Kr();ki()});import{spawn as F$}from"node:child_process";function K$(t,e,r,n,o,i){let s={...t},a=(c,l)=>{Pt(c)||(s[c]=l)};for(let[c,l]of Object.entries(e))a(c,l);for(let[c,l]of Object.entries(r))a(c,l);for(let[c,l]of Object.entries(n??{}))a(c,l);for(let[c,l]of Object.entries(o))s[c]=l;for(let[c,l]of Object.entries(i))s[`INPUT_${c}`]=String(l);return s}async function hf(t){let{def:e,onEvent:r}=t,n=K$(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
|
|
619
|
-
`,o.length>
|
|
620
|
-
`))!==-1;)o(f,m.slice(0,g).replace(/\r$/,"")),m=m.slice(g+1)},flush:()=>{m.length>0&&o(f,m.replace(/\r$/,"")),m=""}}},p=u("stdout"),d=u("stderr");s.stdout?.on("data",p.data),s.stderr?.on("data",d.data),s.on("error",f=>{clearTimeout(l),o("stderr",`spawn failed: ${f.message}`),i(127)}),s.on("close",(f,m)=>{clearTimeout(l),p.flush(),d.flush(),i(a?
|
|
621
|
-
`)){let a=/^(\w+):\s*(.+)$/.exec(s.trim());a&&(a[1]==="repo"&&(n=a[2].trim()),a[1]==="path"&&(o=a[2].trim().replace(/^\.\//,"")))}let i=r[2].trim();return!n||!o||!i||o.includes("..")||o.startsWith("/")?null:{repo:n,path:o,body:i,source:t}}function
|
|
617
|
+
`}var wr=v(()=>{"use strict";G();yi()});import{existsSync as Qp,mkdirSync as E$,mkdtempSync as R$,rmSync as Zp,writeFileSync as ef}from"node:fs";import{tmpdir as I$}from"node:os";import{dirname as C$,join as ki}from"node:path";import{simpleGit as Aa}from"simple-git";function A$(t){return`codepipe/context-migration-v${t}`}function P$(t){let e=xl(t.templateVersion),r=[`CodePipe context format migration: **v${t.templateVersion} \u2192 v${t.currentVersion}**.`,"","Additive only \u2014 this PR creates files your context is missing and updates",`the \`${ut}\` stamp (renamed from \`${Nn}\``,"when the legacy file is present). Hand-edited files are never touched.","","## Format changes",""];for(let n of e){r.push(`- **v${n.version}** \u2014 ${n.summary}`);for(let o of n.addedPaths)r.push(` - \`${o}\``)}return r.push("","Merge to apply. CodePipe re-checks the stamp on the next daemon start and","clears the \u201Ccontext outdated\u201D badge.","","_Opened automatically by the CodePipe CLI._"),r.join(`
|
|
618
|
+
`)}async function tf(t,e,r,n){let o=Aa(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=hi(t,e);if(!i.outdated)return i;let s=A$(i.currentVersion),a=r?.branch??(await o.revparse(["--abbrev-ref","HEAD"]).catch(()=>"main")).trim();try{await o.fetch().catch(()=>{}),(await o.raw(["ls-remote","--heads","origin",s]).catch(()=>"")).trim().length===0?await _$(t,e,r,i,s,a,n):n.info(`[ctx] migration branch ${s} already on origin \u2014 reusing`)}catch(l){return n.warn(`[ctx] context migration branch failed (will retry next start): ${l instanceof Error?l.message:String(l)}`),i}if(!r)return i;let c={name:r.name,host:r.host,owner:r.owner,repoName:r.name};try{let l=Ze(c),u=await l.findOpenPrByBranch?.(c,s)??null;if(u)return n.info(`[ctx] migration PR already open: ${u.url}`),{...i,migrationPrUrl:u.url};let p=await l.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:s,baseBranch:a,title:`CodePipe: context format v${i.templateVersion} \u2192 v${i.currentVersion}`,body:P$(i)});return n.info(`[ctx] migration PR opened: ${p.url}`),{...i,migrationPrUrl:p.url}}catch(l){return n.warn(`[ctx] migration PR create/find failed (branch pushed, badge without link): ${l instanceof Error?l.message:String(l)}`),i}}async function _$(t,e,r,n,o,i,s){let a=Aa(t),c=R$(ki(I$(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",o,c,`origin/${i}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},u={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},p=new Map(Vr(l,u).map(h=>[h.path,h.content])),d=0;for(let h of n.missingPaths){if(h===ut)continue;let g=p.get(h);if(g==null){s.warn(`[ctx] migration: no template for ${h} \u2014 skipped`);continue}let w=ki(c,h);Qp(w)||(E$(C$(w),{recursive:!0}),ef(w,g),d++)}ef(ki(c,ut),Po(n.currentVersion)),d++;let f=ki(c,Nn);Qp(f)&&(Zp(f,{force:!0}),d++);let m=Aa(c);await m.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await m.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await m.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${d} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),Zp(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}var rf=v(()=>{"use strict";G();Dt();Ea();wr()});import{existsSync as j$,readFileSync as N$,writeFileSync as O$}from"node:fs";import{homedir as D$}from"node:os";import{join as nf}from"node:path";import{parseDocument as L$}from"yaml";function M$(t){let e={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(e.default_branch=t.defaultBranch),e}function U$(t,e){let r=L$(t);return r.set("repos",e.map(M$)),r.toString()}function B$(t,e){let r=[nf(D$(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(nf(e,"project.yaml")),r}function eo(t,e,r){let n=[],o=[];for(let i of B$(t,r))if(j$(i))try{let s=N$(i,"utf-8"),a=U$(s,e);a!==s&&(O$(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}var Pa=v(()=>{"use strict"});import{createCipheriv as F$,createDecipheriv as G$,createHash as K$,createPrivateKey as H$,createPublicKey as _a,diffieHellman as of,generateKeyPairSync as sf,hkdfSync as af,randomBytes as W$}from"node:crypto";function wi(){let{publicKey:t,privateKey:e}=sf("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function je(t){let e=Buffer.from(t,"base64");return(K$("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function Tt(t,e){let r=_a({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=sf("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=of({privateKey:o,publicKey:r}),c=Buffer.from(af("sha256",a,Buffer.concat([i,s]),cf,32)),l=W$(12),u=F$("aes-256-gcm",c,l),p=typeof e=="string"?Buffer.from(e,"utf-8"):e,d=Buffer.concat([u.update(p),u.final()]),f=u.getAuthTag(),m={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:f.toString("base64"),ct:d.toString("base64")};return Buffer.from(JSON.stringify(m),"utf-8").toString("base64")}function zr(t,e){let r=JSON.parse(Buffer.from(e,"base64").toString("utf-8"));if(r.v!==1)throw new Error(`sealedbox: unsupported envelope version ${r.v}`);let n=H$({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=_a({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=_a(n).export({type:"spki",format:"der"}),a=of({privateKey:n,publicKey:o}),c=Buffer.from(af("sha256",a,Buffer.concat([i,s]),cf,32)),l=G$("aes-256-gcm",c,Buffer.from(r.iv,"base64"));return l.setAuthTag(Buffer.from(r.tag,"base64")),Buffer.concat([l.update(Buffer.from(r.ct,"base64")),l.final()])}var cf,He=v(()=>{"use strict";cf=Buffer.from("devpipe-sealedbox-v1","utf-8")});function q$(t,e){let r={};t.github?.token&&(r.github={token:t.github.token}),t.bitbucket?.apiToken&&(r.bitbucket={apiToken:t.bitbucket.apiToken}),t.gitlab?.token&&(r.gitlab={token:t.gitlab.token});let n=e??t.claude?.oauthToken;return n&&(r.claudeOauthToken=n),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),r}function lf(t,e,r,n){let o=q$(e,r);t.sandboxes.length>0&&!o.claudeOauthToken&&n.warn("[cred] no Claude OAuth token set \u2014 agent jobs will fail in the SANDBOX. Set one with `codepipe login` (per project) or `make farm-config` (shared farm token)."),t.sandboxes.length>0&&!o.contextWrite&&(o.github||o.gitlab||o.bitbucket)&&n.warn("[cred] no dedicated contextWrite token \u2014 SANDBOX pushes deliveries with the project token of the context repo's host (broader scope than necessary). Set secrets.contextWrite.token (a token scoped to the Context Repo only) to tighten. NOTE (GitHub): the push token MUST have the `workflow` scope, else delivery pushes that carry `.github/workflows/*` are rejected.");let i=JSON.stringify(o),s=[];for(let a of t.sandboxes){let c=qo(t.projectId,a.sandboxId,a.fingerprint);if(c==="mismatch"){n.warn(`[cred] SANDBOX ${a.name} (${a.sandboxId}) key fingerprint CHANGED \u2014 refusing to seal creds. Expected the pinned key; got ${a.fingerprint}. If this is intentional, clear the pin in the secrets file and re-run.`);continue}c==="pinned"&&n.info(`[cred] pinned SANDBOX ${a.name} (${a.sandboxId}) fingerprint ${a.fingerprint}`);let l;try{l=Tt(a.publicKey,i)}catch(u){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}var uf=v(()=>{"use strict";He();ue()});function to(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@github.com:"),o(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function ro(t,e=process.env){if(!t)return!1;let r=`https://oauth2:${t}@gitlab.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@gitlab.com:"),o(1,"ssh://git@gitlab.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function no(t,e=process.env){if(!t)return!1;let r=`https://${sr}:${encodeURIComponent(t)}@bitbucket.org/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@bitbucket.org:"),o(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function ja(t,e,r,n){let o=Number.parseInt(n.GIT_CONFIG_COUNT??"0",10)||0,i=!1;for(let s=0;s<o;s++){let a=n[`GIT_CONFIG_KEY_${s}`];a&&t.test(a)&&(n[`GIT_CONFIG_KEY_${s}`]=`url.${e}.insteadOf`,i=!0)}return i||r()}function df(t,e=process.env){return ja(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>to(t,e),e)}function pf(t,e=process.env){return ja(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>ro(t,e),e)}function ff(t,e=process.env){return ja(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${sr}:${encodeURIComponent(t)}@bitbucket.org/`,()=>no(t,e),e)}var bi=v(()=>{"use strict";G()});function mf(t){let e=W(t);if(!e)return null;if(!e.sealKey){let r=wi();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},oe(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:je(e.sealKey.publicKey)}}async function gf(t,e,r,n){let o;try{o=JSON.parse(zr(n,r).toString("utf-8"))}catch(s){return{ok:!1,detail:`cannot open the sealed credential (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}let i=W(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await jt(o.token);return i.github={token:o.token},Jr(i,()=>{process.env.GH_TOKEN=o.token,df(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Ot(o.token);return i.gitlab={token:o.token},Jr(i,()=>{process.env.GITLAB_TOKEN=o.token,pf(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"bitbucket":{if(!o.email||!o.apiToken)return{ok:!1,detail:"payload needs email + apiToken"};let s=await Nt(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},Jr(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,ff(o.apiToken)}),{ok:!0,detail:`authenticated as ${s}`}}case"youtrack":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=o.url?.trim().replace(/\/$/,"")||i.youtrack?.url;if(!s)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await Mt({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},Jr(i,()=>{process.env.YOUTRACK_URL=s,process.env.YOUTRACK_TOKEN=o.token}),{ok:!0,detail:`authenticated as ${a}`}}case"claude":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Ut(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},Jr(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},Jr(i,()=>{}),{ok:!0,detail:"saved (verified on the next readiness pass)"}):{ok:!1,detail:"payload has no token"};default:return{ok:!1,detail:`unknown credential kind '${e}'`}}}catch(s){return{ok:!1,detail:`${s instanceof Error?s.message:String(s)} \u2014 previous credential kept`}}}function Jr(t,e){oe(t),e()}var hf=v(()=>{"use strict";He();ue();Dt();lr();Kr();bi()});import{spawn as Y$}from"node:child_process";function z$(t,e,r,n,o,i){let s={...t},a=(c,l)=>{Pt(c)||(s[c]=l)};for(let[c,l]of Object.entries(e))a(c,l);for(let[c,l]of Object.entries(r))a(c,l);for(let[c,l]of Object.entries(n??{}))a(c,l);for(let[c,l]of Object.entries(o))s[c]=l;for(let[c,l]of Object.entries(i))s[`INPUT_${c}`]=String(l);return s}async function wf(t){let{def:e,onEvent:r}=t,n=z$(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
|
|
619
|
+
`,o.length>yf&&(o=o.slice(o.length-yf))},s=(a,c)=>{let l=c.length>kf?c.slice(0,kf)+"\u2026":c;i(l),r({ts:Date.now(),kind:"log",stream:a,text:l})};r({ts:Date.now(),kind:"start",status:"running"});for(let[a,c]of e.steps.entries()){let l=c.name??`step ${a+1}`;r({ts:Date.now(),kind:"step",stepName:l});let u=await J$(c.run,c.timeout_sec,t.cwd,n,s);if(u!==0)return i(`[${l}] exited with code ${u}`),r({ts:Date.now(),kind:"result",status:"failed",exitCode:u,failedStep:l}),{status:"failed",exitCode:u,failedStep:l,logTail:o}}return r({ts:Date.now(),kind:"result",status:"succeeded",exitCode:0}),{status:"succeeded",exitCode:0,logTail:o}}function J$(t,e,r,n,o){return new Promise(i=>{let s=Y$("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??zl)*1e3,l=setTimeout(()=>{a=!0,o("stderr",`step timed out after ${c/1e3}s \u2014 killing`),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},c);l.unref?.();let u=f=>{let m="";return{data:h=>{m+=h.toString("utf-8");let g;for(;(g=m.indexOf(`
|
|
620
|
+
`))!==-1;)o(f,m.slice(0,g).replace(/\r$/,"")),m=m.slice(g+1)},flush:()=>{m.length>0&&o(f,m.replace(/\r$/,"")),m=""}}},p=u("stdout"),d=u("stderr");s.stdout?.on("data",p.data),s.stderr?.on("data",d.data),s.on("error",f=>{clearTimeout(l),o("stderr",`spawn failed: ${f.message}`),i(127)}),s.on("close",(f,m)=>{clearTimeout(l),p.flush(),d.flush(),i(a?V$:f??(m?1:0))})})}var V$,yf,kf,bf=v(()=>{"use strict";G();V$=124,yf=16*1024,kf=4e3});import{existsSync as X$,readFileSync as Q$,statSync as $f}from"node:fs";function Z$(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function xf(t,e){let r=he(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!X$(r)||!$f(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=$f(r);if(n>vf)throw new Error(`file too large: ${e} is ${n} bytes (limit ${vf})`);let o=Q$(r);return Z$(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}var vf,Sf=v(()=>{"use strict";rt();vf=2*1024*1024});import{existsSync as ev,readFileSync as tv,writeFileSync as rv}from"node:fs";import{join as nv}from"node:path";import{parseDocument as ov}from"yaml";async function Tf(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=nu(o);if(!i.ok)throw new Error(i.error);let s=r.get(o.file)??[];s.push({path:i.field.path,value:i.value}),r.set(o.file,s)}let n=[];for(let[o,i]of r){let s=nv(t,o);if(!ev(s))throw new Error(`${o} not found in context repo (${t})`);let a=ov(tv(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);rv(s,a.toString()),n.push(o)}return{files:n}}var Ef=v(()=>{"use strict";G()});import{existsSync as iv,readFileSync as sv,writeFileSync as av}from"node:fs";import{join as cv}from"node:path";import{isMap as Rf,parseDocument as lv}from"yaml";async function If(t,e){let r=e.repoName?.trim(),n=e.defaultBranch?.trim();if(!r)throw new Error("repoName must be a non-empty string");if(!n||!uu(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=cv(t,"project.yaml");if(!iv(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=lv(sv(o,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>Rf(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!Rf(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),av(o,i.toString()),{repoName:r,defaultBranch:n}}var Cf=v(()=>{"use strict";G()});import{existsSync as Na,readFileSync as Oa,writeFileSync as uv}from"node:fs";import{join as $i}from"node:path";import{parseDocument as Da}from"yaml";async function Af(t,e){let r=[];if(e.stageField!==void 0||e.sourceColumns!==void 0||e.rejectColumns!==void 0||e.doneColumns!==void 0||e.reviewColumns!==void 0||e.statusColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0||e.backlogScope!==void 0){let i=$i(t,"project.yaml");if(!Na(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=Da(Oa(i,"utf-8"));if(e.stageField!==void 0){let a=typeof e.stageField=="string"?e.stageField.trim():"";a&&a!=="Stage"?s.setIn(["youtrack","stage_field"],a):s.deleteIn(["youtrack","stage_field"])}if(e.rejectColumns!==void 0){let a=e.rejectColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","reject_columns"],a):s.deleteIn(["youtrack","reject_columns"])}if(e.doneColumns!==void 0){let a=e.doneColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","done_columns"],a):s.deleteIn(["youtrack","done_columns"])}if(e.reviewColumns!==void 0){let a=e.reviewColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","review_columns"],a):s.deleteIn(["youtrack","review_columns"])}if(e.statusColumns!==void 0){let a=e.statusColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","status_columns"],a):s.deleteIn(["youtrack","status_columns"])}if(e.sourceColumns!==void 0){let a=e.sourceColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);if(a.length===0)throw new Error("source_columns must be a non-empty list of non-empty strings");s.setIn(["youtrack","source_columns"],a)}if(e.backlogColumn!==void 0){let a=typeof e.backlogColumn=="string"?e.backlogColumn.trim():"";a?s.setIn(["youtrack","backlog_column"],a):s.deleteIn(["youtrack","backlog_column"])}if(e.assignee!==void 0){let a=typeof e.assignee=="string"?e.assignee.trim():"";a?s.setIn(["youtrack","assignee"],a):s.deleteIn(["youtrack","assignee"])}e.requireAssignee!==void 0&&s.setIn(["youtrack","require_assignee"],e.requireAssignee===!0),e.backlogScope!==void 0&&(e.backlogScope==="personal"?s.setIn(["youtrack","backlog_scope"],"personal"):e.backlogScope==="shared"?s.setIn(["youtrack","backlog_scope"],"shared"):s.deleteIn(["youtrack","backlog_scope"])),r.push({path:"project.yaml",content:s.toString()})}if(e.reviewStatus!==void 0||e.writes!==void 0){let i=$i(t,"regimen.yaml");if(!Na(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=Da(Oa(i,"utf-8"));if(e.reviewStatus!==void 0){let a=e.reviewStatus.trim();a&&s.setIn(["youtrack","review_status"],a)}if(e.writes!==void 0){let a=e.writes;s.setIn(["youtrack","writes","enabled"],a.enabled===!0),s.setIn(["youtrack","writes","status_changes"],a.statusChanges===!0),s.setIn(["youtrack","writes","pr_comment"],a.prComment===!0),s.setIn(["youtrack","writes","dashboard_mirror"],a.dashboardMirror===!0)}r.push({path:"regimen.yaml",content:s.toString()})}if(r.length===0)return{files:[]};for(let i of r)uv($i(t,i.path),i.content);return{files:r.map(i=>i.path)}}function vi(t){if(!t)return"Stage";try{let e=$i(t,"project.yaml");if(!Na(e))return"Stage";let n=Da(Oa(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}var La=v(()=>{"use strict"});import{existsSync as Pf,readFileSync as _f,readdirSync as dv}from"node:fs";import{join as Ma}from"node:path";import{simpleGit as pv}from"simple-git";function fv(t,e){let r=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/.exec(e);if(!r)return null;let n="",o="";for(let s of r[1].split(`
|
|
621
|
+
`)){let a=/^(\w+):\s*(.+)$/.exec(s.trim());a&&(a[1]==="repo"&&(n=a[2].trim()),a[1]==="path"&&(o=a[2].trim().replace(/^\.\//,"")))}let i=r[2].trim();return!n||!o||!i||o.includes("..")||o.startsWith("/")?null:{repo:n,path:o,body:i,source:t}}function mv(t,e){let r=Ma(t,`tasks/${e}/annotations`);if(!Pf(r))return[];let n=[];for(let o of dv(r).sort())if(o.endsWith(".md")){try{let i=fv(o,_f(Ma(r,o),"utf-8"));i&&n.push(i)}catch{}if(n.length>=Pl)break}return n}async function jf(t){let{contextDir:e,taskKey:r,repoName:n,repoDir:o,commitSha:i,date:s,touchedKeys:a,identity:c}=t;if(!c)return[];let l=new Map(c.entities.filter(d=>d.status==="active").map(d=>[d.currentKey,d.entityId])),u=pv(o),p=[];for(let d of mv(e,r)){if(d.repo!==n)continue;let f=pe("code",n,d.path);if(!a.has(f))continue;let m=l.get(f);if(!m)continue;let h=(await u.raw(["rev-parse",`${i}:${d.path}`]).catch(()=>"")).trim().slice(0,gv),g=Tl(m),w=Ma(e,g),y=p.find(I=>I.path===g),x=y?.content??(Pf(w)?_f(w,"utf-8"):null),T=`<!-- ${r}${h?`:${h}`:""} -->`;if(x?.includes(T))continue;let R=x??`---
|
|
622
622
|
entityId: ${m}
|
|
623
623
|
---
|
|
624
624
|
|
|
@@ -626,35 +626,35 @@ entityId: ${m}
|
|
|
626
626
|
|
|
627
627
|
Append-only. Keyed by entityId \u2014 never by path; entries survive renames.
|
|
628
628
|
`,E=["",`## ${s} \u2014 ${r}`,T,"",d.body,""].join(`
|
|
629
|
-
`),b=R+E;y?y.content=b:p.push({path:g,content:b})}return p}var
|
|
630
|
-
`))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=
|
|
631
|
-
`)){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:
|
|
632
|
-
`))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
|
|
633
|
-
`).map(s=>s.trim()).filter(Boolean),i=[];for(let s of o){let c=(await n.raw(["diff","-M","-C","-z","--name-status","--diff-filter=R",`${s}^`,s]).catch(()=>"")).split("\0");for(let l=0;l+2<c.length;){if(!(c[l]??"").startsWith("R")){l+=1;continue}let p=c[l+1]??"",d=c[l+2]??"";p&&d&&i.push({fromPath:p,toPath:d,commit:s}),l+=3}}return i}function qf(t){let e=new Map,r=new Map;for(let n of t){let o=r.get(n.fromPath)??n.fromPath;r.delete(n.fromPath),r.set(n.toPath,o),e.set(o,{finalPath:n.toPath,commit:n.commit})}for(let[n,o]of e)o.finalPath===n&&e.delete(n);return e}var Yf=x(()=>{"use strict"});function Si(t){return pe("container",t,wv)}function Vf(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function zf(t,e,r,n){let o=[],i=u=>{let p=pe("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:Vf(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,bv)}},s=(u,p)=>{let d=pe("component",t,u),f=n.get(d);return{key:d,level:"component",label:Vf(u),...f?{entityId:f}:{},...p?{aggregate:!0}:{}}},a=(u,p,d)=>{let f=r.filesByDir.get(d)??[],m=r.childDirs.get(d)??[],h=[p,...f.map(i)],g=[...f.map(w=>({kind:"contains",from:p.key,to:pe("code",t,w.path)})),...m.map(w=>({kind:"contains",from:p.key,to:pe("component",t,w)}))];c(u,h,g)},c=(u,p,d)=>{let f={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},m=Ct(f);if(!m.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${m.errors.join("; ")}`);o.push({path:Tl(t,u),content:Nl(f)})},l={key:Si(t),level:"container",label:t,...n.get(Si(t))?{entityId:n.get(Si(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 Jf(t,e){let r=[Si(t)];for(let n of e.components)r.push(pe("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(pe("code",t,o.path));return r.sort()}var wv,bv,Xf=x(()=>{"use strict";G();wv=".";bv=12});import{simpleGit as Zf}from"simple-git";function br(t){let e=new Set,r=[],n=new Set;for(let o of t){let i=o.trim();if(i)if(i.endsWith("/"))e.add(i.slice(0,-1));else if(i.includes("*")){let s=i.replace(/[.*+?^${}()|[\]\\]/g,a=>a==="*"?"\0":`\\${a}`).replace(/\0/g,".*");r.push(new RegExp(`^${s}$`))}else n.add(i)}return o=>{let i=o.split("/"),s=i[i.length-1]??o;if(n.has(o))return!0;for(let a of i)if(e.has(a)||n.has(a))return!0;return r.some(a=>a.test(s))}}async function tm(t,e="HEAD"){let r=Zf(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 ro(t,n)}}async function ro(t,e){let n=await Zf(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 Qf(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function rm(t,e){let r=[...t].sort((m,h)=>m.path<h.path?-1:m.path>h.path?1:0),n=new Map,o=new Map;for(let m of r){let h=Qf(m.path);n.has(h)||n.set(h,[]),n.get(h).push(m);let g=h;for(;g!=="";){let w=Qf(g);o.has(w)||o.set(w,new Set),o.get(w).add(g),g=w}}let i=m=>[...o.get(m)??[]].sort(),s=Math.max(e,1)-1,a=new Set,c=new Set,l=[""];for(;l.length>0;){let m=l.shift(),h=(n.get(m)??[]).length+i(m).length;if(h<=s)s-=h,c.add(m),l.push(...i(m));else{if(m==="")return{components:[],collapsed:new Set,filesByDir:new Map,childDirs:new Map,counts:{component:0,code:0}};a.add(m)}}let u=[],p=new Map,d=new Map,f=0;for(let m of[...c].sort()){let h=n.get(m)??[];p.set(m,h),d.set(m,i(m)),f+=h.length,m!==""&&u.push(m)}for(let m of a)u.push(m);return u.sort(),{components:u,collapsed:a,filesByDir:p,childDirs:d,counts:{component:u.length,code:f}}}var em,no=x(()=>{"use strict";em=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as nm,readFileSync as om}from"node:fs";import{join as im}from"node:path";import{simpleGit as $v}from"simple-git";import{parse as sm}from"yaml";function Qr(t){let e={ignore:em,containerNodeCap:vv,cochange:{...Je},issueKeyPattern:null,enabled:!1},r=im(t,"regimen.yaml");if(!nm(r))return e;let n;try{n=sm(om(r,"utf-8"))}catch{return e}let o=n?.context,i=o&&typeof o=="object"?o.model:void 0;if(!i||typeof i!="object")return e;let s=i,a=Array.isArray(s.ignore)?s.ignore.filter(f=>typeof f=="string"&&f.trim().length>0):e.ignore,c=(f,m)=>typeof f=="number"&&Number.isInteger(f)&&f>0?f:m,l=c(s.container_node_cap,e.containerNodeCap),u=s.cochange&&typeof s.cochange=="object"?s.cochange:{},p={windowCommits:c(u.window_commits,e.cochange.windowCommits),commitFileCap:c(u.commit_file_cap,e.cochange.commitFileCap),supportMin:c(u.support_min,e.cochange.supportMin),jaccardMinPct:typeof u.jaccard_min_pct=="number"&&Number.isInteger(u.jaccard_min_pct)&&u.jaccard_min_pct>=0&&u.jaccard_min_pct<=100?u.jaccard_min_pct:e.cochange.jaccardMinPct,halfLifeDays:c(u.half_life_days,e.cochange.halfLifeDays),topK:c(u.top_k,e.cochange.topK)},d=typeof s.issue_key_pattern=="string"&&s.issue_key_pattern.trim().length>0?s.issue_key_pattern.trim():null;return{ignore:a,containerNodeCap:l,cochange:p,issueKeyPattern:d,enabled:s.enabled===!0}}function Ga(t,e){let r=im(t,Ao(e));if(!nm(r))return null;let n=sm(om(r,"utf-8")),o=jo(n);if(!o.ok)throw new Error(`model: ${Ao(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function Ka(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await tm(r,t.ref??"HEAD"),s=br(o.ignore),a=i.files.filter(y=>!s(y.path)),c=rm(a,o.containerNodeCap),l=Ga(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await $v(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=qf(await Wf(r,l.builtFromCommit,i.commit)),p=new Map((await ro(r,l.builtFromCommit)).map(T=>[T.path,T.blobHash]))):l?.builtFromCommit===i.commit&&(p=new Map(a.map(y=>[y.path,y.blobHash])));let d=new Map(a.map(y=>[y.path,y.blobHash])),f=Kf({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:Jf(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),m=zf(e,i.commit,c,f.byKey),h=br([...o.ignore,...Xr]),g=Gf({repo:e,headTimeSec:i.commitTimeSec,filesets:await Ff(r,i.commit,o.cochange.windowCommits),pathToCurrent:vi(f.table),currentPaths:new Set(a.map(y=>y.path)),ignored:h,settings:o.cochange}),w=[{path:Ao(e),content:Ol(f.table)},...m.files.map(y=>({path:y.path,content:y.content})),{path:xl(e),content:_r({modelFormatVersion:2,repo:e,builtFromCommit:i.commit,edges:g})}];return{repo:e,headCommit:i.commit,files:w,emittedShardPaths:new Set(m.files.map(y=>y.path)),counts:{...m.counts,correlates:g.length},identityTable:f.table,entityByKey:f.byKey}}var vv,Ha=x(()=>{"use strict";G();xi();Hf();Yf();Xf();no();vv=1500});import{existsSync as cm,readFileSync as lm,readdirSync as xv}from"node:fs";import{join as Wa}from"node:path";import{parse as um}from"yaml";function Sv(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 dm(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<Rl)return null;let s=i/Math.min(n.size,o.size),a=Sv(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(s*c*am)/am;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[ve(t.taskKey),ve(e.taskKey)]:[ve(e.taskKey),ve(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function pm(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=dm(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 fm(t,e,r,n){let o=ve(r),i=t.filter(a=>a.from!==o&&a.to!==o),s=e.find(a=>a.taskKey===r);if(s){let a=new Set(s.files.map(c=>c.key));for(let c of e){if(c.taskKey===r||!c.files.some(u=>a.has(u.key)))continue;let l=dm(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 Ti(t){let e=Wa(t,"model/facts/events");if(!cm(e))return[];let r=[];for(let n of xv(e).sort())if(n.endsWith(".yaml"))try{let o=At(um(lm(Wa(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function mm(t){let e=Wa(t,Ar);if(!cm(e))return[];try{let r=Po(um(lm(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function Ei(t){return _r({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var am,qa=x(()=>{"use strict";G();am=1e4});var oo={};Ir(oo,{collectSearchRows:()=>hm,readContextIndexHub:()=>Tv,rebuildSearchIndex:()=>ym,searchIndexPath:()=>Ai,searchModelIndex:()=>Ev,toFtsQuery:()=>km});import{existsSync as en,readFileSync as Zr,readdirSync as Ii}from"node:fs";import{join as nt}from"node:path";import{parse as Ci}from"yaml";function Ai(t){return nt(t,".git","codepipe-model-index.sqlite")}function Tv(t){let e=nt(t,"regimen.yaml");if(!en(e))return"off";try{let n=Ci(Zr(e,"utf-8"))?.context,o=n&&typeof n=="object"?n.index:null;return(o&&typeof o=="object"?o.hub:null)==="metadata"?"metadata":"off"}catch{return"off"}}async function gm(){try{let{createRequire:t}=await import("node:module");return t(import.meta.url)("node:sqlite")}catch{return null}}function Ri(t){return t.length>Is?t.slice(0,Is):t}function Ya(t){if(!en(t))return[];let e=[];for(let r of Ii(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=nt(t,r.name);r.isDirectory()?e.push(...Ya(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function hm(t){let e=[];for(let i of Ya(nt(t,"model/derived/structure"))){let s;try{s=Ci(Zr(i,"utf-8"))}catch{continue}let a=Ct(s);if(a.ok)for(let c of a.value.nodes){let l=Q(c.key);l&&e.push({nodeId:c.key,kind:l.level,text:Ri(`${l.path} ${c.label??""}`.trim())})}}let r=nt(t,"model/facts/events");if(en(r)){for(let i of Ii(r).sort())if(i.endsWith(".yaml"))try{let s=At(Ci(Zr(nt(r,i),"utf-8")));if(!s.ok)continue;let a=s.value,c=[...a.links?.adr??[],...a.links?.tasks??[]].join(" ");e.push({nodeId:`task::${a.taskKey}`,kind:"task",text:Ri(`${a.taskKey} ${a.title??""} ${c}`.trim())})}catch{}}let n=nt(t,"model/facts/annotations");if(en(n)){let i=new Map;for(let s of Ya(nt(t,"model/facts/identity")))try{let a=Ci(Zr(s,"utf-8"));for(let c of a?.entities??[])c.status==="active"&&c.entityId&&c.currentKey&&i.set(c.entityId,c.currentKey)}catch{}for(let s of Ii(n).sort())if(s.endsWith(".md"))try{let a=Zr(nt(n,s),"utf-8"),c=/^---\n[\s\S]*?entityId:\s*(e_[0-9a-f]{8})[\s\S]*?\n---\n?([\s\S]*)$/.exec(a);if(!c)continue;e.push({nodeId:i.get(c[1])??c[1],kind:"annotation",text:Ri(c[2].trim())})}catch{}}let o=nt(t,"adr");if(en(o))for(let i of Ii(o).sort()){let s=/^(\d{4})-/.exec(i)?.[1];if(!(!s||!i.endsWith(".md")))try{let a=Zr(nt(o,i),"utf-8").split(`
|
|
634
|
-
`).slice(0,6);e.push({nodeId:`adr::ADR-${s}`,kind:"adr",text:
|
|
629
|
+
`),b=R+E;y?y.content=b:p.push({path:g,content:b})}return p}var gv,Nf=v(()=>{"use strict";G();gv=12});import{existsSync as Ua,readFileSync as Ba}from"node:fs";import{join as Fa}from"node:path";import{simpleGit as Df}from"simple-git";import{parse as Ga}from"yaml";function Mf(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(hv.source,"g")}function Uf(t){let e=Fa(t,"project.yaml");if(Ua(e))try{let o=Ga(Ba(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=Fa(t,"tracker","config.yaml");if(Ua(r))try{let o=Ga(Ba(r,"utf-8"))?.prefix;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return null}function Bf(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 yv(t,e,r){let o=await Df(t).raw(["log","--numstat","--format=@@@ %H %ct %P %x09%s","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
|
|
630
|
+
`))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)??Lf.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:Bf(c[3]),churn:l+u})}return i}async function kv(t,e){let n=await Df(t).raw(["diff","--numstat",`${e}^1`,e]).catch(()=>""),o=[];for(let i of n.split(`
|
|
631
|
+
`)){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:Bf(s[3]),churn:a+c})}return o}function wv(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){if((t.trackerProjectKey??"").toUpperCase()==="PR")continue;u=`PR-${c.prNumber}`,p=c.subject.replace(Ka,"").replace(Lf,"").replace(/^from\s+/,"").trim()||c.subject}else continue;if(!/^[A-Za-z0-9._-]+$/.test(u))continue;let f=new Map;for(let g of c.files){let w=o.get(g.path)??g.path;s(w)||f.set(w,(f.get(w)??0)+g.churn)}if(f.size===0)continue;let h=a.get(u)??{modelFormatVersion:2,taskKey:u,origin:"bootstrap",title:"",commits:[],files:[]};p&&(h.title=p),c.timeSec>0&&(h.date=new Date(c.timeSec*1e3).toISOString().slice(0,10)),h.commits.push(c.sha);for(let[g,w]of f){let y=pe("code",e,g),x=h.files.find(T=>T.key===y);if(x)x.churn=(x.churn??0)+w;else{let T=i.get(y);h.files.push({key:y,...T?{entityId:T}:{},churn:w})}}if(d.length>0){let g=new Set([...h.links?.tasks??[],...d]);g.delete(u),h.links={...h.links??{},tasks:[...g].sort()}}a.set(u,h)}return a}function Of(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 Ff(t){let e=await yv(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 kv(t.repoDir,r.sha))}return wv({repo:t.repo,issueKeyRe:t.issueKeyRe,commits:e,pathToCurrent:t.pathToCurrent,entityByKey:t.entityByKey,ignored:t.ignored,trackerProjectKey:t.trackerProjectKey??null})}function Gf(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?Of(c,a)??c:a)}let n=[],o=0;for(let[i,s]of[...r.entries()].sort(([a],[c])=>a<c?-1:1)){let a=Of(xi(t,i),s);if(!a){o++;continue}n.push({path:Pr(i),content:Dn(a)})}return{files:n,skippedPipeline:o}}function xi(t,e){let r=Fa(t,Pr(e));if(!Ua(r))return null;try{let n=At(Ga(Ba(r,"utf-8")));return n.ok?n.value:null}catch{return null}}var hv,Ka,Lf,Ha=v(()=>{"use strict";G();hv=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g,Ka=/\(#(\d+)\)\s*$/,Lf=/^Merge pull request #(\d+)\b/});import{simpleGit as bv}from"simple-git";async function Hf(t,e,r){let o=await bv(t).raw(["log","--no-merges","--name-only","--format=@@@ %H %ct","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
|
|
632
|
+
`))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 Si(t){let e=new Map;for(let r of t.entities){if(r.status!=="active"||!r.aliases)continue;let n=Q(r.currentKey);if(n?.level==="code")for(let o of r.aliases){let i=Q(o.key);i?.level==="code"&&e.set(i.path,n.path)}}return e}function Wf(t){let{repo:e,headTimeSec:r,filesets:n,pathToCurrent:o,currentPaths:i,ignored:s,settings:a}=t,c=a.halfLifeDays*86400,l=new Map,u=new Map,p=new Map;for(let w of n){let y=new Set;for(let E of w.files){let b=o.get(E)??E;!i.has(b)||s(b)||y.add(b)}if(y.size<2||y.size>a.commitFileCap)continue;let x=Math.max(0,r-w.timeSec),T=Math.pow(.5,x/c),R=[...y].sort();for(let E of R)l.set(E,(l.get(E)??0)+T);for(let E=0;E<R.length;E++)for(let b=E+1;b<R.length;b++){let I=`${R[E]}\0${R[b]}`;u.set(I,(u.get(I)??0)+T),p.set(I,(p.get(I)??0)+1)}}let d=[],f=a.jaccardMinPct/100;for(let[w,y]of u){if((p.get(w)??0)<a.supportMin)continue;let[x,T]=w.split("\0"),R=(l.get(x)??0)+(l.get(T)??0)-y,E=R>0?y/R:0;E<f||d.push({a:x,b:T,weight:Math.round(E*Kf)/Kf})}let m=new Map;for(let w of d)for(let y of[w.a,w.b])m.has(y)||m.set(y,[]),m.get(y).push(w);let h=new Map;for(let[,w]of m)w.sort((y,x)=>x.weight-y.weight||(y.a<x.a?-1:y.a>x.a?1:y.b<x.b?-1:1)).slice(0,a.topK).forEach(y=>h.set(y,(h.get(y)??0)+1));return[...h.entries()].filter(([,w])=>w===2).map(([w])=>w).map(w=>({kind:"correlates",from:pe("code",e,w.a),to:pe("code",e,w.b),weight:w.weight})).sort((w,y)=>w.from<y.from?-1:w.from>y.from?1:w.to<y.to?-1:1)}var Xr,Kf,Ti=v(()=>{"use strict";G();Xr=["package-lock.json","pnpm-lock.yaml","yarn.lock"];Kf=1e4});import{createHash as $v}from"node:crypto";function xv(t,e,r,n){for(let o=0;;o++){let s=`e_${$v("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(s))return s}}function qf(t){let{repo:e,headCommit:r,headDate:n,prev:o,renameChains:i,prevBlobByPath:s,headBlobByPath:a}=t,c=[...t.currentKeys].sort(),l=new Set(c),u=o?.entities??[],p=new Set(u.map(b=>b.entityId)),d=new Set,f=[],m=new Map,h=(b,I)=>{d.add(I),m.set(I,b.entityId),f.push(b)},g=[];for(let b of u)l.has(b.currentKey)&&!d.has(b.currentKey)?h({...b,status:"active",lastSeen:r},b.currentKey):g.push(b);let w=[],y=[];for(let b of g){let I=Q(b.currentKey),N=I?i.get(I.path):void 0;if(I&&N){let F=pe(I.level,e,N.finalPath);if(l.has(F)&&!d.has(F)){w.push({entity:b,newKey:F,untilCommit:N.commit}),d.add(F);continue}}y.push(b)}let x=[];if(s){let b=new Map;for(let N of c){if(d.has(N))continue;let F=Q(N);if(F?.level!=="code")continue;let C=a.get(F.path);C&&b.set(C,b.has(C)?null:N)}let I=new Map;for(let N of y){let F=Q(N.currentKey);if(F?.level!=="code")continue;let C=s.get(F.path);C&&I.set(C,I.has(C)?null:N)}for(let N of y){let F=Q(N.currentKey),C=F?.level==="code"?s.get(F.path):void 0,k=C?b.get(C):void 0;C&&k&&I.get(C)===N&&!d.has(k)?(w.push({entity:N,newKey:k,untilCommit:r}),d.add(k)):x.push(N)}}else x.push(...y);let T=new Map;for(let b of w){let I=Q(b.entity.currentKey),N=Q(b.newKey);if(I?.level!=="code"||!N)continue;let F=I.path,C=N.path;for(let k=F.lastIndexOf("/");k>0;k=F.lastIndexOf("/",k-1)){let D=F.slice(0,k),A=F.slice(k+1);if(!C.endsWith(`/${A}`))continue;let H=C.slice(0,C.length-A.length-1);if(H===D)continue;let q=`${D}\0${H}`,Z=T.get(q);T.set(q,{count:(Z?.count??0)+1,commit:Z&&Z.commit>b.untilCommit?Z.commit:b.untilCommit})}}let R=[...T.entries()].filter(([,b])=>b.count>=vv).map(([b,I])=>{let[N,F]=b.split("\0");return{from:N,to:F,commit:I.commit}}).sort((b,I)=>I.from.length-b.from.length||(b.from<I.from?-1:1)),E=[];for(let b of x){let I=Q(b.currentKey),N=!1;if(I?.level==="component")for(let F of R){let C=null;if(I.path===F.from?C=F.to:I.path.startsWith(`${F.from}/`)&&(C=F.to+I.path.slice(F.from.length)),C===null)continue;let k=pe("component",e,C);l.has(k)&&!d.has(k)&&(w.push({entity:b,newKey:k,untilCommit:F.commit}),d.add(k),N=!0);break}N||E.push(b)}for(let b of w.sort((I,N)=>I.newKey<N.newKey?-1:1))h({...b.entity,currentKey:b.newKey,aliases:[...b.entity.aliases??[],{key:b.entity.currentKey,until:b.untilCommit}],status:"active",lastSeen:r},b.newKey);for(let b of E)f.push({...b,status:"orphaned"});for(let b of c){if(d.has(b))continue;let I=xv(e,b,r,p);p.add(I),h({entityId:I,currentKey:b,firstSeen:n,lastSeen:r,status:"active"},b)}return{table:{modelFormatVersion:2,repo:e,builtFromCommit:r,entities:f},byKey:m}}var vv,Yf=v(()=>{"use strict";G();vv=5});import{simpleGit as Sv}from"simple-git";async function Vf(t,e,r){let n=Sv(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
|
|
633
|
+
`).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 zf(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 Jf=v(()=>{"use strict"});function Ei(t){return pe("container",t,Tv)}function Xf(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function Qf(t,e,r,n){let o=[],i=u=>{let p=pe("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:Xf(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,Ev)}},s=(u,p)=>{let d=pe("component",t,u),f=n.get(d);return{key:d,level:"component",label:Xf(u),...f?{entityId:f}:{},...p?{aggregate:!0}:{}}},a=(u,p,d)=>{let f=r.filesByDir.get(d)??[],m=r.childDirs.get(d)??[],h=[p,...f.map(i)],g=[...f.map(w=>({kind:"contains",from:p.key,to:pe("code",t,w.path)})),...m.map(w=>({kind:"contains",from:p.key,to:pe("component",t,w)}))];c(u,h,g)},c=(u,p,d)=>{let f={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},m=Ct(f);if(!m.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${m.errors.join("; ")}`);o.push({path:Il(t,u),content:Ll(f)})},l={key:Ei(t),level:"container",label:t,...n.get(Ei(t))?{entityId:n.get(Ei(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 Zf(t,e){let r=[Ei(t)];for(let n of e.components)r.push(pe("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(pe("code",t,o.path));return r.sort()}var Tv,Ev,em=v(()=>{"use strict";G();Tv=".";Ev=12});import{simpleGit as rm}from"simple-git";function br(t){let e=new Set,r=[],n=new Set;for(let o of t){let i=o.trim();if(i)if(i.endsWith("/"))e.add(i.slice(0,-1));else if(i.includes("*")){let s=i.replace(/[.*+?^${}()|[\]\\]/g,a=>a==="*"?"\0":`\\${a}`).replace(/\0/g,".*");r.push(new RegExp(`^${s}$`))}else n.add(i)}return o=>{let i=o.split("/"),s=i[i.length-1]??o;if(n.has(o))return!0;for(let a of i)if(e.has(a)||n.has(a))return!0;return r.some(a=>a.test(s))}}async function om(t,e="HEAD"){let r=rm(t),n=(await r.revparse([e])).trim(),[o,i]=(await r.raw(["show","-s","--format=%cs %ct",n])).trim().split(/\s+/);return{commit:n,commitDate:o??"",commitTimeSec:Number(i??0),files:await oo(t,n)}}async function oo(t,e){let n=await rm(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 tm(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function im(t,e){let r=[...t].sort((m,h)=>m.path<h.path?-1:m.path>h.path?1:0),n=new Map,o=new Map;for(let m of r){let h=tm(m.path);n.has(h)||n.set(h,[]),n.get(h).push(m);let g=h;for(;g!=="";){let w=tm(g);o.has(w)||o.set(w,new Set),o.get(w).add(g),g=w}}let i=m=>[...o.get(m)??[]].sort(),s=Math.max(e,1)-1,a=new Set,c=new Set,l=[""];for(;l.length>0;){let m=l.shift(),h=(n.get(m)??[]).length+i(m).length;if(h<=s)s-=h,c.add(m),l.push(...i(m));else{if(m==="")return{components:[],collapsed:new Set,filesByDir:new Map,childDirs:new Map,counts:{component:0,code:0}};a.add(m)}}let u=[],p=new Map,d=new Map,f=0;for(let m of[...c].sort()){let h=n.get(m)??[];p.set(m,h),d.set(m,i(m)),f+=h.length,m!==""&&u.push(m)}for(let m of a)u.push(m);return u.sort(),{components:u,collapsed:a,filesByDir:p,childDirs:d,counts:{component:u.length,code:f}}}var nm,io=v(()=>{"use strict";nm=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as sm,readFileSync as am}from"node:fs";import{join as cm}from"node:path";import{simpleGit as Rv}from"simple-git";import{parse as lm}from"yaml";function Qr(t){let e={ignore:nm,containerNodeCap:Iv,cochange:{...Je},issueKeyPattern:null,enabled:!1},r=cm(t,"regimen.yaml");if(!sm(r))return e;let n;try{n=lm(am(r,"utf-8"))}catch{return e}let o=n?.context,i=o&&typeof o=="object"?o.model:void 0;if(!i||typeof i!="object")return e;let s=i,a=Array.isArray(s.ignore)?s.ignore.filter(f=>typeof f=="string"&&f.trim().length>0):e.ignore,c=(f,m)=>typeof f=="number"&&Number.isInteger(f)&&f>0?f:m,l=c(s.container_node_cap,e.containerNodeCap),u=s.cochange&&typeof s.cochange=="object"?s.cochange:{},p={windowCommits:c(u.window_commits,e.cochange.windowCommits),commitFileCap:c(u.commit_file_cap,e.cochange.commitFileCap),supportMin:c(u.support_min,e.cochange.supportMin),jaccardMinPct:typeof u.jaccard_min_pct=="number"&&Number.isInteger(u.jaccard_min_pct)&&u.jaccard_min_pct>=0&&u.jaccard_min_pct<=100?u.jaccard_min_pct:e.cochange.jaccardMinPct,halfLifeDays:c(u.half_life_days,e.cochange.halfLifeDays),topK:c(u.top_k,e.cochange.topK)},d=typeof s.issue_key_pattern=="string"&&s.issue_key_pattern.trim().length>0?s.issue_key_pattern.trim():null;return{ignore:a,containerNodeCap:l,cochange:p,issueKeyPattern:d,enabled:s.enabled===!0}}function Wa(t,e){let r=cm(t,_o(e));if(!sm(r))return null;let n=lm(am(r,"utf-8")),o=Oo(n);if(!o.ok)throw new Error(`model: ${_o(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function qa(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await om(r,t.ref??"HEAD"),s=br(o.ignore),a=i.files.filter(y=>!s(y.path)),c=im(a,o.containerNodeCap),l=Wa(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await Rv(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=zf(await Vf(r,l.builtFromCommit,i.commit)),p=new Map((await oo(r,l.builtFromCommit)).map(T=>[T.path,T.blobHash]))):l?.builtFromCommit===i.commit&&(p=new Map(a.map(y=>[y.path,y.blobHash])));let d=new Map(a.map(y=>[y.path,y.blobHash])),f=qf({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:Zf(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),m=Qf(e,i.commit,c,f.byKey),h=br([...o.ignore,...Xr]),g=Wf({repo:e,headTimeSec:i.commitTimeSec,filesets:await Hf(r,i.commit,o.cochange.windowCommits),pathToCurrent:Si(f.table),currentPaths:new Set(a.map(y=>y.path)),ignored:h,settings:o.cochange}),w=[{path:_o(e),content:Ml(f.table)},...m.files.map(y=>({path:y.path,content:y.content})),{path:El(e),content:_r({modelFormatVersion:2,repo:e,builtFromCommit:i.commit,edges:g})}];return{repo:e,headCommit:i.commit,files:w,emittedShardPaths:new Set(m.files.map(y=>y.path)),counts:{...m.counts,correlates:g.length},identityTable:f.table,entityByKey:f.byKey}}var Iv,Ya=v(()=>{"use strict";G();Ti();Yf();Jf();em();io();Iv=1500});import{existsSync as dm,readFileSync as pm,readdirSync as Cv}from"node:fs";import{join as Va}from"node:path";import{parse as fm}from"yaml";function Av(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 mm(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<Al)return null;let s=i/Math.min(n.size,o.size),a=Av(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(s*c*um)/um;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[ve(t.taskKey),ve(e.taskKey)]:[ve(e.taskKey),ve(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function gm(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=mm(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 hm(t,e,r,n){let o=ve(r),i=t.filter(a=>a.from!==o&&a.to!==o),s=e.find(a=>a.taskKey===r);if(s){let a=new Set(s.files.map(c=>c.key));for(let c of e){if(c.taskKey===r||!c.files.some(u=>a.has(u.key)))continue;let l=mm(s,c,n);l&&i.push(l)}}return i.sort((a,c)=>a.from<c.from?-1:a.from>c.from?1:a.to<c.to?-1:1)}function Ri(t){let e=Va(t,"model/facts/events");if(!dm(e))return[];let r=[];for(let n of Cv(e).sort())if(n.endsWith(".yaml"))try{let o=At(fm(pm(Va(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function ym(t){let e=Va(t,Ar);if(!dm(e))return[];try{let r=jo(fm(pm(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function Ii(t){return _r({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var um,za=v(()=>{"use strict";G();um=1e4});var so={};Ir(so,{collectSearchRows:()=>wm,readContextIndexHub:()=>Pv,rebuildSearchIndex:()=>bm,searchIndexPath:()=>_i,searchModelIndex:()=>_v,toFtsQuery:()=>$m});import{existsSync as en,readFileSync as Zr,readdirSync as Ai}from"node:fs";import{join as nt}from"node:path";import{parse as Pi}from"yaml";function _i(t){return nt(t,".git","codepipe-model-index.sqlite")}function Pv(t){let e=nt(t,"regimen.yaml");if(!en(e))return"off";try{let n=Pi(Zr(e,"utf-8"))?.context,o=n&&typeof n=="object"?n.index:null;return(o&&typeof o=="object"?o.hub:null)==="metadata"?"metadata":"off"}catch{return"off"}}async function km(){try{let{createRequire:t}=await import("node:module");return t(import.meta.url)("node:sqlite")}catch{return null}}function Ci(t){return t.length>Ps?t.slice(0,Ps):t}function Ja(t){if(!en(t))return[];let e=[];for(let r of Ai(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=nt(t,r.name);r.isDirectory()?e.push(...Ja(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function wm(t){let e=[];for(let i of Ja(nt(t,"model/derived/structure"))){let s;try{s=Pi(Zr(i,"utf-8"))}catch{continue}let a=Ct(s);if(a.ok)for(let c of a.value.nodes){let l=Q(c.key);l&&e.push({nodeId:c.key,kind:l.level,text:Ci(`${l.path} ${c.label??""}`.trim())})}}let r=nt(t,"model/facts/events");if(en(r)){for(let i of Ai(r).sort())if(i.endsWith(".yaml"))try{let s=At(Pi(Zr(nt(r,i),"utf-8")));if(!s.ok)continue;let a=s.value,c=[...a.links?.adr??[],...a.links?.tasks??[]].join(" ");e.push({nodeId:`task::${a.taskKey}`,kind:"task",text:Ci(`${a.taskKey} ${a.title??""} ${c}`.trim())})}catch{}}let n=nt(t,"model/facts/annotations");if(en(n)){let i=new Map;for(let s of Ja(nt(t,"model/facts/identity")))try{let a=Pi(Zr(s,"utf-8"));for(let c of a?.entities??[])c.status==="active"&&c.entityId&&c.currentKey&&i.set(c.entityId,c.currentKey)}catch{}for(let s of Ai(n).sort())if(s.endsWith(".md"))try{let a=Zr(nt(n,s),"utf-8"),c=/^---\n[\s\S]*?entityId:\s*(e_[0-9a-f]{8})[\s\S]*?\n---\n?([\s\S]*)$/.exec(a);if(!c)continue;e.push({nodeId:i.get(c[1])??c[1],kind:"annotation",text:Ci(c[2].trim())})}catch{}}let o=nt(t,"adr");if(en(o))for(let i of Ai(o).sort()){let s=/^(\d{4})-/.exec(i)?.[1];if(!(!s||!i.endsWith(".md")))try{let a=Zr(nt(o,i),"utf-8").split(`
|
|
634
|
+
`).slice(0,6);e.push({nodeId:`adr::ADR-${s}`,kind:"adr",text:Ci(a.filter(c=>c.trim()).join(" "))})}catch{}}return e}async function bm(t){let e=wm(t),r=await km();if(!r)return{rows:e,indexed:!1};let n=new r.DatabaseSync(_i(t));try{n.exec("DROP TABLE IF EXISTS model_fts"),n.exec("CREATE VIRTUAL TABLE model_fts USING fts5(node_id UNINDEXED, kind UNINDEXED, text)");let o=n.prepare("INSERT INTO model_fts (node_id, kind, text) VALUES (?, ?, ?)");for(let i of e)o.run(i.nodeId,i.kind,i.text)}finally{n.close()}return{rows:e,indexed:!0}}function $m(t){let e=t.match(/[\p{L}\p{N}_./-]+/gu)??[];return e.length===0?null:e.map((r,n)=>`"${r.replace(/"/g,"")}"${n===e.length-1?"*":""}`).join(" ")}async function _v(t,e,r){let n=await km();if(!n)throw new Error("model search needs Node with built-in sqlite (>= 22.13) on this CLI");en(_i(t))||await bm(t);let o=$m(e);if(!o)return[];let i=Math.min(Math.max(r??20,1),_l),s=new n.DatabaseSync(_i(t));try{return s.prepare(`SELECT node_id AS nodeId, kind, snippet(model_fts, 2, '[', ']', '\u2026', 10) AS snippet,
|
|
635
635
|
bm25(model_fts) AS rank
|
|
636
|
-
FROM model_fts WHERE model_fts MATCH ? ORDER BY bm25(model_fts), node_id LIMIT ?`).all(o,i).map(c=>({nodeId:c.nodeId,kind:c.kind,score:-c.rank,snippet:c.snippet}))}finally{s.close()}}var
|
|
637
|
-
`)){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
|
|
638
|
-
`)){let s=i.trim();s&&e.add(s)}}catch{}for(let r of[...e].sort())await
|
|
639
|
-
`)}function
|
|
640
|
-
`)){let s=i.trim();if(s)try{let a=JSON.parse(s);a&&typeof a.id=="string"&&n.set(a.id,a)}catch{}}for(let i of r){if(n.has(i.id))continue;let s={id:i.id,author:i.author,origin:"youtrack",body:i.body,createdAt:new Date(i.createdAt).toISOString()},a=Or(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function
|
|
636
|
+
FROM model_fts WHERE model_fts MATCH ? ORDER BY bm25(model_fts), node_id LIMIT ?`).all(o,i).map(c=>({nodeId:c.nodeId,kind:c.kind,score:-c.rank,snippet:c.snippet}))}finally{s.close()}}var ao=v(()=>{"use strict";G()});var Sm={};Ir(Sm,{attachPrToBranchTasks:()=>Za,attachPrToEvent:()=>xm,recordPipelineEvent:()=>Qa});import{existsSync as jv,readFileSync as Nv}from"node:fs";import{join as vm}from"node:path";import{simpleGit as Xa}from"simple-git";async function Ov(t,e){let n=await Xa(t).raw(["diff","--numstat",`${e}^`,e]).catch(()=>""),o=[];for(let i of n.split(`
|
|
637
|
+
`)){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 Dv(t,e){let n=[`tasks/${e}/PLAN.md`,`tasks/${e}/SOLUTION.md`].find(i=>jv(vm(t,i)));if(!n)return{};let o=vm(t,n);try{let i=Nv(o,"utf-8"),s=[...new Set(i.match(/\bADR-\d{3,4}\b/g)??[])].sort();return{solution:n,...s.length>0?{adr:s}:{}}}catch{return{solution:n}}}async function Qa(t){let{contextDir:e,repoDir:r,repoName:n,taskKey:o,commitSha:i}=t,s=Qr(e),a=br([...s.ignore,...Xr]),c=await Ov(r,i),l=(await Xa(r).raw(["show","-s","--format=%cs",i])).trim(),u=null,p=new Map;try{u=Wa(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 E=pe("code",n,R.path),b=p.get(E);d.push({key:E,...b?{entityId:b}:{},churn:R.churn})}if(d.length===0)return{recorded:!1};let f=Dv(e,o),m=xi(e,o),h=m?.origin==="pipeline"?m.files.filter(R=>Q(R.key)?.repo!==n):[],g=m?.origin==="pipeline"?m.commits:[],w={modelFormatVersion:2,taskKey:o,origin:"pipeline",...m?.title?{title:m.title}:{},...l?{date:l}:{},commits:[...new Set([...g,i])],files:[...h,...d],links:{...m?.origin==="pipeline"?m.links:{},...f}};w.links&&Object.keys(w.links).length===0&&delete w.links;let y=[...Ri(e).filter(R=>R.taskKey!==o),w],x=hm(ym(e),y,o,s.cochange.halfLifeDays),T=await jf({contextDir:e,taskKey:o,repoName:n,repoDir:r,commitSha:i,date:l,touchedKeys:new Set(d.map(R=>R.key)),identity:u}).catch(()=>[]);await Ie(e,[{path:Pr(o),content:Dn(w)},{path:Ar,content:Ii(x)},...T],`model: task event ${o}`);{let{rebuildSearchIndex:R}=await Promise.resolve().then(()=>(ao(),so));await R(e).catch(()=>{})}return{recorded:!0}}async function Za(t){let e=new Set([t.fallbackTaskKey]);try{let r=Xa(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(`
|
|
638
|
+
`)){let s=i.trim();s&&e.add(s)}}catch{}for(let r of[...e].sort())await xm(t.contextDir,r,t.prUrl)}async function xm(t,e,r){let n=xi(t,e);if(!n||n.origin!=="pipeline"||n.links?.pr===r)return;let o={...n,links:{...n.links??{},pr:r}};await Ie(t,[{path:Pr(e),content:Dn(o)}],`model: pr link for ${e}`)}var ec=v(()=>{"use strict";G();rt();Nf();Ha();Ya();Ti();za();io()});var co,tc=v(()=>{"use strict";La();lr();co=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return Pd(this.cfg,e)}getIssue(e,r){return _d(this.cfg,e,r??vi(this.contextDir))}listComments(e,r){return jd(this.cfg,e,r)}downloadAttachment(e){return Ad(this.cfg,e)}updateStatus(e,r){return $d(this.cfg,e,r,vi(this.contextDir))}addComment(e,r,n){return vd(this.cfg,e,r)}createIssue(e){return Td(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,vi(this.contextDir))}editIssue(e,r){return xd(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return Ed(this.cfg,e,r,n)}fetchStateFields(e){return Od(this.cfg,e)}}});import{existsSync as rc,readFileSync as Lv,readdirSync as Mv}from"node:fs";function ji(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=Gv(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:Uv(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:Fv(Bv(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 Tm(t,e,r,n=10){let o=new Set(e.map(c=>c.issue.key)),i=[],s=c=>(c.links??[]).filter(l=>l.type==="subtask").map(l=>l.targetKey);for(let c of e)i.push(...s(c.issue));let a=[];for(;i.length>0&&a.length<n;){let c=i.shift();if(o.has(c)||(o.add(c),rc(he(t,`tasks/${c}/task.md`))))continue;let l=null;try{l=await r(c)}catch{continue}l&&(a.push({issue:l,comments:[],attachments:[]}),i.push(...s(l)))}return a}async function Ni(t,e,r){if(r.length===0)return;let n=ji(t,e,r),o=r.map(i=>i.issue.key);await Ie(t,n,`sync(${o.join(", ")}): task data`)}function Uv(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(`
|
|
639
|
+
`)}function Bv(t,e,r){let n=new Map,o=he(t,`tasks/${e}/comments.jsonl`);if(rc(o))for(let i of Lv(o,"utf-8").split(`
|
|
640
|
+
`)){let s=i.trim();if(s)try{let a=JSON.parse(s);a&&typeof a.id=="string"&&n.set(a.id,a)}catch{}}for(let i of r){if(n.has(i.id))continue;let s={id:i.id,author:i.author,origin:"youtrack",body:i.body,createdAt:new Date(i.createdAt).toISOString()},a=Or(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function Fv(t){return t.map(e=>JSON.stringify(e)).join(`
|
|
641
641
|
`)+(t.length>0?`
|
|
642
|
-
`:"")}function
|
|
643
|
-
`)){let i=o.trim();if(i)try{let s=JSON.parse(i);s&&typeof s.id=="string"&&typeof s.body=="string"&&n.push(s)}catch{}}return n}var
|
|
642
|
+
`:"")}function Gv(t,e,r){let n=[],o=he(t,`tasks/${e}/attachments`);if(rc(o))for(let i of Mv(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}var Oi=v(()=>{"use strict";G();rt()});import{existsSync as Kv,readFileSync as Hv}from"node:fs";import{randomBytes as Wv}from"node:crypto";function Em(t,e){let r=he(t,`tasks/${e}/comments.jsonl`);if(!Kv(r))return[];let n=[];for(let o of Hv(r,"utf-8").split(`
|
|
643
|
+
`)){let i=o.trim();if(i)try{let s=JSON.parse(i);s&&typeof s.id=="string"&&typeof s.body=="string"&&n.push(s)}catch{}}return n}var lo,nc=v(()=>{"use strict";G();rt();Oi();yi();lo=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await Xn(this.contextDir);let r=e.columns??[];return Vp(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>Zn(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=Qn(this.contextDir,e);return r?Zn(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return Em(this.contextDir,e).map(n=>({id:n.id,issueId:e,author:n.author,body:n.body,createdAt:n.createdAt}))}async downloadAttachment(e){throw new Error(`internal tracker: no remote attachments (${e})`)}async updateStatus(e,r){await this.mutateRecord(e,n=>({...n,status:r}))}async addComment(e,r,n){if(await Xn(this.contextDir),!Qn(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${Wv(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=Or(r);s&&(i.parsedCommand=s);let c=[...Em(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
|
|
644
644
|
`)+`
|
|
645
|
-
`;return await Ie(this.contextDir,[{path:`tasks/${e}/comments.jsonl`,content:c}],`tracker(${e}): comment`),{id:i.id}}async createIssue(e){let r=new Date().toISOString(),n=await qp(this.contextDir,this.config.prefix,o=>this.renderNewIssueFiles(o,e,r),o=>`tracker(${o}): create issue`);return{id:n,key:n}}async editIssue(e,r){await this.mutateRecord(e,n=>({...n,...r.title!==void 0?{title:r.title}:{}}),r.body)}async applyLink(e,r,n){let o=r==="subtask_of"?"subtask":"depends_on";await this.mutateRecord(e,i=>{let s=i.links.filter(a=>!(a.type===o&&a.targetKey===n));return s.push({type:o,targetKey:n}),{...i,links:s}})}async fetchStateFields(e){return[{name:"Status",values:Ms.statusColumns}]}async mutateRecord(e,r,n){let o=Jn(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=Xn(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:Mn(e),content:Ea(i)},...Pi(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await Ie(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:Do,status:r.targetStatus,links:[],created:n,updated:n},i=Xn(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:Mn(e),content:Ea(o)},...Pi(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}}});import{existsSync as Sm,readFileSync as Tm}from"node:fs";import{join as Em}from"node:path";import{parseDocument as Rm}from"yaml";function tc(t){if(!t)return"youtrack";try{let e=Em(t,"project.yaml");return Sm(e)&&Rm(Tm(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function kt(t){let e=tc(t.contextDir);if(e==="internal"){let n=t.contextDir;if(!n)return{ok:!1,kind:e,error:"internal tracker: no Context Repo clone on this CLI"};let o=Kp(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=Bv(n);return i?{ok:!0,kind:e,provider:new ao(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=hd();return r?{ok:!0,kind:e,provider:new so(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function Bv(t){try{let e=Em(t,"project.yaml");if(!Sm(e))return null;let r=Rm(Tm(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var Ni=x(()=>{"use strict";lr();Qa();ec();gi();Qa();ec()});async function tn(t,e){let n=(Oi.get(t)??Promise.resolve()).catch(()=>{}).then(e);Oi.set(t,n);try{return await n}finally{Oi.get(t)===n&&Oi.delete(t)}}async function Im(t){let{action:e,repo:r}=t,n="repoName"in e?e.repoName:"-",o="taskId"in e?e.taskId:"draftId"in e?e.draftId:e.projectId;dr(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return J("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return tn(`${i}/${r.name}`,async()=>{let s=await xt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Te(i,r.name,t.baseDir),{commit:c,pushed:l}=await sp(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force,push:e.push});if(t.contextDir){let u=e.taskId.split(":")[1]??"";u&&await za({contextDir:t.contextDir,repoDir:a,repoName:r.name,taskKey:u,commitSha:c}).catch(p=>{dr(`[model] task event for ${u} failed: ${p instanceof Error?p.message:String(p)}`)})}return ce({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,pushed:l,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"push_branch":{if(!r)return J("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return tn(`${i}/${r.name}`,async()=>{let s=await xt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Te(i,r.name,t.baseDir);return await ap(s,a,{branchName:e.branchName,force:e.force}),ce({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"early_branch":{if(!r)return J("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return tn(`${i}/${r.name}`,async()=>{let s=await xt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Te(i,r.name,t.baseDir),{commit:c,pushed:l}=await cp(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return ce({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return J("no repo spec");let i=Ze(r),s=await i.createPullRequest(r,e);if(t.contextDir){let a=e.taskId.split(":")[1]??"",c=e.taskId.split(":",2)[0]??"?";a&&await Ja({contextDir:t.contextDir,repoDir:Te(c,r.name,t.baseDir),branchName:e.branchName,baseBranch:e.baseBranch,fallbackTaskKey:a,prUrl:s.url}).catch(l=>{dr(`[model] pr link for ${a} failed: ${l instanceof Error?l.message:String(l)}`)})}return ce({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return J("no repo spec");let i=Ze(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ce({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return J("no repo spec");let i=Ze(r);return await i.closePR(r,e.prNumber,e.comment),ce({prNumber:e.prNumber,host:i.name})}case"rewrite_cluster_branch":{if(!r)return J("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return tn(`${i}/${r.name}`,async()=>{let s=await xt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Te(i,r.name,t.baseDir),{commit:c,dropped:l}=await up(s,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:r.defaultBranch});return ce({branch:e.branchName,commit:c,dropped:l,pushed:l>0})})}case"merge_branch":{if(!r)return J("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return tn(`${i}/${r.name}`,async()=>{let s=await xt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Te(i,r.name,t.baseDir),{mergedSha:c}=await dp(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ce({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return J("no repo spec");let i=t.cloneUrlOverride??qn(r),a=(await pp(i)).filter(u=>fp(u,e.issueKey)),c=Ze(r),l=null;if(c.findOpenPrByBranch)for(let u of a){let p=await c.findOpenPrByBranch(r,u).catch(()=>null);if(p){l={number:p.number,url:p.url};break}}return ce({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return J("no repo spec");let i=Ze(r);return await i.addPRComment(r,e.prNumber,e.body),ce({prNumber:e.prNumber,host:i.name})}case"tracker_status":{let i=kt({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),ce({issueId:t.trackerIssueId,newStatus:e.newStatus})):J("no tracker_issue_id provided"):J(i.error)}case"tracker_comment":{let i=kt({contextDir:t.contextDir});if(!i.ok)return J(i.error);if(!t.trackerIssueId)return J("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return ce({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=kt({contextDir:t.contextDir});if(!i.ok)return J(i.error);if(!e.projectKey)return J("no projectKey in create_tracker_issue action");let{id:s,key:a}=await i.provider.createIssue({projectKey:e.projectKey,title:e.title,body:e.body,targetStatus:e.targetStatus});return ce({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=kt({contextDir:t.contextDir});if(!i.ok)return J(i.error);let s=0;for(let a of e.links)try{await i.provider.applyLink(a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return J(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return ce({applied:s})}case"set_project_setting":{if(!t.contextDir)return J("no context repo clone on this CLI");let i=await vf(t.contextDir,e.edits);return ce({files:i.files})}case"tracker_edit":{let i=kt({contextDir:t.contextDir});if(!i.ok)return J(i.error);if(!t.contextDir)return J("no context repo clone on this CLI");await i.provider.editIssue(e.issueKey,{...e.title!==void 0?{title:e.title}:{},...e.body!==void 0?{body:e.body}:{}});let s=await i.provider.getIssue(e.issueKey);return s&&await _i(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),ce({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return J("no context repo clone on this CLI");let i=await Rf(t.contextDir,e);return ce({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return J("no context repo clone on this CLI");let i=await Tf(t.contextDir,e);return ce({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ce({reported:!0})):J("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return J("no context repo clone on this CLI");let i=await t.refreshContextStatus();return ce({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return J("no project workspace on this CLI");if(!r)return J("no repo spec");if(!t.onRunActivity)return J("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=ci(t.contextDir),c=s.find(f=>f.id===e.actionId);if(!c){let f=a.find(m=>m.file===`actions/${e.actionId}.yml`);return J(f?`action "${e.actionId}" failed to parse: ${f.error}`:`unknown action "${e.actionId}"`)}let l=Vl(c,e.input);if(!l.ok)return J(l.error);let u=Sp(t.contextDir),p=W(e.projectId),d={};return p?.github?.token&&(d.GH_TOKEN=p.github.token),p?.gitlab?.token&&(d.GITLAB_TOKEN=p.gitlab.token),p?.bitbucket&&(d.BITBUCKET_EMAIL=p.bitbucket.email,d.BITBUCKET_API_TOKEN=p.bitbucket.apiToken),p?.youtrack&&(d.YOUTRACK_URL=p.youtrack.url,d.YOUTRACK_TOKEN=p.youtrack.token),tn(`${e.projectId}/${r.name}`,async()=>{await xt(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let f=Te(e.projectId,r.name,t.baseDir),m=await hf({cwd:f,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:h=>i(e.runId,h)});return ce({runId:e.runId,status:m.status,exitCode:m.exitCode,...m.failedStep?{failedStep:m.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return J("no context repo clone on this CLI");let i=bf(t.contextDir,e.path);return ce({path:e.path,...i})}case"search_model":{if(!t.contextDir)return J("no context repo clone on this CLI");let{searchModelIndex:i}=await Promise.resolve().then(()=>(io(),oo)),s=await i(t.contextDir,e.q,e.limit);return ce({hits:s})}case"model_drift":return J("model_drift requires a local workspace (handled by the daemon)");case"model_bootstrap":return J("model_bootstrap requires a local workspace (handled by the daemon)");case"local_apply":return J("local_apply requires a local workspace (handled by the daemon)");default:return J(`unsupported action type: ${e.type}`)}}catch(i){return J(i instanceof Error?i.message:String(i))}}function ce(t){return{status:"done",result:t}}function J(t){return{status:"failed",error:t}}var Oi,Cm=x(()=>{"use strict";G();fa();yf();$f();ue();xf();Ef();Na();Dt();ni();mr();Xa();Ni();ji();Oi=new Map});import{existsSync as Fv,mkdtempSync as Gv,rmSync as Kv}from"node:fs";import{tmpdir as Hv}from"node:os";import{join as rc}from"node:path";import{simpleGit as Am}from"simple-git";async function Pm(t,e,r){let n=[];for(let a of e){let c=t.repos.find(u=>u.name===a.repoName);if(!c)return{ok:!1,error:`repo "${a.repoName}" not in project.yaml \u2014 run /sync`};let l=rc(t.root,c.mountAs);if(!Fv(rc(l,".git")))return{ok:!1,error:`${c.mountAs}/ not cloned \u2014 run /sync first`};n.push({payload:a,dir:l,mountAs:c.mountAs,defaultBranch:c.defaultBranch})}let o=[];for(let a of n){let c=Am(a.dir),l=a.payload;try{await c.fetch()}catch(f){return{ok:!1,error:`fetch failed in ${a.mountAs}: ${co(f)}`}}let u=`origin/${l.baseRef}`;await Vv(c,u)||(u=`origin/${a.defaultBranch}`);let p;try{p=(await c.revparse([u])).trim()}catch(f){return{ok:!1,error:`base ${u} unavailable in ${a.mountAs}: ${co(f)}`}}let d;try{d=await Wn(c,l.deliverySha,()=>fr(c,{contextRepoCloneUrl:l.contextRepoCloneUrl,deliveryRef:l.deliveryRef,deliverySha:l.deliverySha,baseSha:l.baseSha,commitMessage:l.commitMessage}))}catch(f){return{ok:!1,error:`fetch delivery failed in ${a.mountAs}: ${co(f)}`}}o.push({repoName:l.repoName,mountAs:a.mountAs,git:c,branch:l.branchName,startPoint:p,deliveryCommit:d})}let i=[],s=[];for(let a of o){let c=await zv(a.git,`refs/heads/${a.branch}`);try{let u=(await a.git.revparse([`${a.deliveryCommit}^`])).trim()===a.startPoint?a.deliveryCommit:await qv(a);await a.git.raw(["branch","-f",a.branch,u]),i.push({git:a.git,mountAs:a.mountAs,branch:a.branch,priorSha:c}),s.push({repoName:a.repoName,branch:a.branch,commit:u}),r.info(`[local-apply] ${a.mountAs}: branch ${a.branch} \u2192 ${u.slice(0,10)} (no checkout)`)}catch(l){return await Yv(i,r),{ok:!1,error:`apply failed in ${a.mountAs}: ${co(l)} (rolled back all repos)`}}}return{ok:!0,repos:s}}async function qv(t){let e=Gv(rc(Hv(),"codepipe-local-apply-"));try{await t.git.raw(["worktree","add","--detach",e,t.startPoint]);let r=Am(e);try{await r.raw([...Wv,"cherry-pick",t.deliveryCommit])}catch(n){throw await r.raw(["cherry-pick","--abort"]).catch(()=>{}),n}return(await r.revparse(["HEAD"])).trim()}finally{await t.git.raw(["worktree","remove","--force",e]).catch(()=>{}),Kv(e,{recursive:!0,force:!0}),await t.git.raw(["worktree","prune"]).catch(()=>{})}}async function Yv(t,e){for(let r of t)try{r.priorSha?await r.git.raw(["branch","-f",r.branch,r.priorSha]):await r.git.raw(["branch","-D",r.branch])}catch(n){e.warn(`[local-apply] rollback of ${r.mountAs}#${r.branch} failed: ${co(n)} \u2014 check manually`)}}async function Vv(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function zv(t,e){try{return(await t.raw(["rev-parse","--verify","--quiet",e])).trim()||null}catch{return null}}function co(t){return t instanceof Error?t.message.trim():String(t)}var Wv,_m=x(()=>{"use strict";mr();Wv=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{homedir as Jv}from"node:os";import{existsSync as Xv,mkdirSync as Qv,readFileSync as Zv,writeFileSync as ex}from"node:fs";import{dirname as tx,join as rx}from"node:path";function nc(){return V("FARM_PINS")??rx(Jv(),".codepipe","farm-pins.json")}function jm(){let t=nc();if(!Xv(t))return{};try{return JSON.parse(Zv(t,"utf-8"))}catch{return{}}}function nx(t){let e=nc();Qv(tx(e),{recursive:!0}),ex(e,JSON.stringify(t,null,2)+`
|
|
646
|
-
`,{mode:384})}function
|
|
647
|
-
`,{mode:384})}function fx(t){return Um()[t]}function sc(t,e){let r=Um();r[t]=e,px(r)}function Bm(t,e){let r=je(e),n=fx(t);if(n&&n!==r)throw new Error(`runner host ${t} key fingerprint changed (pinned ${n}, now ${r}) \u2014 refusing to seal. If the runner host was re-registered intentionally, remove its entry from ${ic()}.`);return r}var Fm=x(()=>{"use strict";_e();He()});async function Gm(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:Km(t)});if(!o.ok)throw new Error(`github ${n} for ${e}/${r}: HTTP ${o.status}`);let i=await o.json();if(!i.token)throw new Error(`github ${n} for ${e}/${r}: no token in response`);return i.token}async function Wm(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(je(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Bm(e.runnerId,e.runnerPublicKey);let i=W(t.projectId)?.github?.token;if(!i)throw new Error("no GitHub token stored for this project on this CLI");let a=((await r.fetchProject(t.hubUrl,t.cliToken,t.projectId)).repos??[]).find(c=>c.host==="github"&&c.owner===e.owner&&c.repoName===e.repo);if(!a)throw new Error(`${e.owner}/${e.repo} is not a GitHub repository of this project`);return{githubToken:i,repo:a}}async function qm(t,e,r,n=Hm){let o=i=>({type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repo:s}=await Wm(t,e,n);if(!await n.api.repoHasAdmin(i,s.owner,s.repoName))return o(`the GitHub token lacks admin access on ${s.owner}/${s.repoName} \u2014 replace it (project page \u2192 Tokens \u2192 Replace) with a token that has admin rights on this repository`);let a={projectId:t.projectId,runners:[{owner:s.owner,repo:s.repoName,regToken:await n.api.mintRegistrationToken(i,s.owner,s.repoName)}],labels:[iu(e.runnerId)]},c=Tt(e.runnerPublicKey,JSON.stringify(a));sc(e.runnerId,e.fingerprint),r.info(`[ghr] registration token for ${s.owner}/${s.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let l=await n.provisionOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:c});return{type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:l.ok,...l.runners?{runners:l.runners}:{},...l.error?{error:l.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}async function Ym(t,e,r,n=Hm){let o=i=>({type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repo:s}=await Wm(t,e,n),a={owner:s.owner,repo:s.repoName};try{a.removeToken=await n.api.mintRemoveToken(i,s.owner,s.repoName)}catch(p){r.warn(`[ghr] remove-token for ${s.owner}/${s.repoName} failed (${p instanceof Error?p.message:p}) \u2014 the runner host will force-remove`)}let c={projectId:t.projectId,runners:[a]},l=Tt(e.runnerPublicKey,JSON.stringify(c));sc(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle for ${s.owner}/${s.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let u=await n.teardownOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:l,owner:s.owner,repo:s.repoName});return{type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:u.ok,...u.error?{error:u.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}var Km,mx,Hm,Vm=x(()=>{"use strict";G();He();Fm();Re();ue();Km=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});mx={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Km(t)});if(!n.ok)throw new Error(`github GET /repos/${e}/${r}: HTTP ${n.status}`);return(await n.json()).permissions?.admin===!0},mintRegistrationToken:(t,e,r)=>Gm(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Gm(t,e,r,"remove-token")},Hm={api:mx,fetchProject:ne,provisionOnRunner:Wd,teardownOnRunner:qd}});function gx(t){return Be.test(t)?Pt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Be}`}function Jm(t,e,r,n){let o=gx(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(zr(n,r).toString("utf-8"));if(typeof s.value!="string"||s.value.length===0)return{ok:!1,detail:"payload has no value"};i=s.value}catch(s){return{ok:!1,detail:`cannot open the sealed secret (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}if(i.length>zm)return{ok:!1,detail:`secret value too large (max ${zm} chars)`};try{return Ku(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function Xm(t,e){try{return Hu(t,e)?{ok:!0}:{ok:!0,detail:"no such secret (already absent)"}}catch(r){return{ok:!1,detail:r instanceof Error?r.message:String(r)}}}var zm,Qm=x(()=>{"use strict";G();He();ue();zm=16*1024});function hx(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var Mi,Zm=x(()=>{"use strict";Dt();Mi=class{constructor(e,r,n){this.intervalMs=e;this.send=r;this.log=n}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let n=[];for(let s of r.prs){let a=Ze(s.repoSpec);try{let c=await a.getPullRequest(s.repoSpec,s.number);n.push({number:s.number,url:s.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof cr){this.log.warn(`[track] task=${e} pr=${s.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${s.url} fetch failed: ${c instanceof Error?c.message:String(c)}`);return}}let o=n.map(s=>`${s.number}:${s.state}:${s.merged?1:0}:${s.ci}:${s.mergeable}`).join("|");if(this.lastSig.get(e)===o)return;for(let s=0;s<n.length;s++){let a=n[s];if(a.ci!=="failed")continue;let c=Ze(r.prs[s].repoSpec);if(c.getCiFailureLog)try{let l=await c.getCiFailureLog(r.prs[s].repoSpec,a.number);l&&(a.ciFailureLog=l)}catch(l){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${l instanceof Error?l.message:String(l)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:n}),this.lastSig.set(e,o);let i=hx(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}}});function eg(t){let{description:e,...r}=t;return r}function yx(t){let{body:e,...r}=t;return r}function kx(t){let r=(t.split(/[\\/]/).pop()??t).replace(/[^A-Za-z0-9._-]/g,"_").replace(/^\.+/,"");return r.length>0?r.slice(0,120):"attachment"}async function tg(t,e,r,n){try{return await t.getIssue(e,r)}catch(o){return n.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function rg(t,e,r,n){try{return await t.listComments(e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}var Ui,ng=x(()=>{"use strict";G();ji();Ni();Ui=class t{constructor(e,r,n,o={contextDir:null}){this.intervalMs=e;this.send=r;this.log=n;this.options=o}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;abandonedTicks=0;static MAX_ABANDONED_TICKS=3;setRequest(e){let r=this.request?.projectId;this.request=e,this.log.info(`[yt-sync] request updated: project=${e.projectKey} columns=[${e.sourceColumns.join(",")}] sinceMs=${e.sinceMs} offBoard=${e.offBoardIssueIds.length}`),this.timer||this.start(),r&&r!==e.projectId&&this.log.info(`[yt-sync] project switch ${r} \u2192 ${e.projectId}`)}start(){if(this.timer)return;this.log.info(`[yt-sync] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[yt-sync] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[yt-sync] poller stopped"))}async tickOnce(){await this.tick()}async forceSync(){if(!this.request){this.log.info("[yt-sync] force requested but no sync_request yet \u2014 ignored");return}this.log.info("[yt-sync] force sync requested (manual)"),await this.tick()}async tick(){if(this.running||!this.request)return;let r=(this.options.resolveProvider??(()=>kt({contextDir:this.options.contextDir})))();if(!r.ok){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn(`[yt-sync] tracker provider unavailable (${r.error}) \u2014 poller idle.`));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,r.provider)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let v=e.stageField?{stageField:e.stageField}:{},T=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},E=(e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(E){let b=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[I,N]=await Promise.all([b.length>0?r.listIssues({projectKey:e.projectKey,columns:b,...v,...T}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...v})]),U=new Map;for(let C of[...I,...N])U.set(C.id,C);o=[...U.values()]}else{let b=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:b,...v,...T})}}catch(v){this.log.warn(`[yt-sync] listIssues failed: ${v instanceof Error?v.message:String(v)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let v of o){if(s.add(v.id),a.has(v.status))continue;let T=await rg(r,v.id,e.sinceMs,this.log);T&&i.set(v.id,T)}let c=[];for(let v of e.offBoardIssueIds){if(s.has(v))continue;let T=await rg(r,v,e.sinceMs,this.log);if(T&&T.length>0&&i.set(v,T),e.requireAssignee||T&&T.length>0){let R=await tg(r,v,e.stageField,this.log);if(R)c.push(R);else if(T&&T.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(v=>!a.has(v.status)),{attachmentsByIssue:u,attachmentKeys:p}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let d=[...l,...c].map(v=>({issue:v,comments:i.get(v.id)??[],attachments:u.get(v.id)??[]}));d.push(...await vm(this.options.contextDir,d,v=>tg(r,v,e.stageField,this.log)));try{await _i(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let v of p)this.shippedAttachments.add(v)}catch(v){let T=v instanceof Error?v.message:String(v);this.abandonTick(`context task sync failed: ${T}`);return}let f=this.options.isSelfComment??(()=>!1),m=[],h=[];for(let[v,T]of i){let R=T.filter(b=>!f(b.id));if(R.length===0)continue;m.push({issueId:v,comments:R.map(yx)});let E=R.flatMap(b=>{let I=Or(b.body);return I?[{commentId:b.id,author:b.author,name:I.name,args:I.args,createdAt:b.createdAt}]:[]});E.length>0&&h.push({issueId:v,commands:E})}let g={type:"youtrack_observation",projectId:e.projectId,issues:o.map(eg),commentsBatch:m,...h.length>0?{commandsBatch:h}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(eg)}:{},observedAtMs:n};this.send(g);let w=m.reduce((v,T)=>v+T.comments.length,0),y=h.reduce((v,T)=>v+T.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${w} commands=${y} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let p=`${s.id}:${u.id}`;if(this.shippedAttachments.has(p))continue;let d;try{d=await n.downloadAttachment(u.url)}catch(m){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${m instanceof Error?m.message:String(m)}`);continue}let f=kx(u.name);l.has(f)&&(f=`${u.id}-${f}`),l.add(f),c.push({name:f,contentBase64:d.toString("base64")}),i.push(p)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}}});import{existsSync as og,readFileSync as wx,readdirSync as bx}from"node:fs";import{join as ig}from"node:path";import{simpleGit as $x}from"simple-git";import{parse as vx}from"yaml";function ac(t){let e=new Map,r=ig(t,Es);if(!og(r))return e;let n;try{n=vx(wx(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 xx(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return Nr({modelFormatVersion:2,repos:e})}function sg(t,e){let r=ig(t,e);if(!og(r))return[];let n=[];for(let o of bx(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...sg(t,i)):n.push(i)}return n}async function Bi(t,e,r={}){let n=[],o=0;for(let d of e){n.push(...d.files);let f=`model/derived/structure/${d.repo}`;for(let m of sg(t,f))d.emittedShardPaths.has(m)||(n.push({path:m,content:"",deleted:!0}),o++)}let i=ac(t);for(let d of e)i.set(d.repo,{builtFromCommit:d.headCommit,counts:d.counts});n.push({path:Es,content:xx(i)});let s=Ti(t),a=pm(s,r.halfLifeDays??Je.halfLifeDays);n.push({path:Ar,content:Ei(a)});for(let d of e){let f=[];for(let m of s)for(let h of m.files)Q(h.key)?.repo===d.repo&&f.push({kind:"touched_by",from:ve(m.taskKey),to:h.key,...h.churn!==void 0?{weight:h.churn}:{}});n.push({path:Sl(d.repo),content:_r({modelFormatVersion:2,repo:d.repo,builtFromCommit:d.headCommit,edges:f})})}let c=$x(t),l=(await c.revparse(["HEAD"]).catch(()=>"")).trim(),u=`model: build ${e.map(d=>`${d.repo}@${d.headCommit.slice(0,10)}`).join(", ")}`;await Ie(t,n,u);let p=(await c.revparse(["HEAD"]).catch(()=>"")).trim();if(p!==l){let{rebuildSearchIndex:d}=await Promise.resolve().then(()=>(io(),oo));await d(t).catch(()=>{})}return{committed:p!==l,filesWritten:n.filter(d=>!d.deleted).length,filesDeleted:o}}var ag=x(()=>{"use strict";G();qa();rt()});var Gi={};Ir(Gi,{bootstrapDaemonModel:()=>Tx,bootstrapModelForTargets:()=>mc,bootstrapWorkspaceModel:()=>pg,modelBootstrapCommand:()=>fc,modelBuildCommand:()=>pc,rebuildWorkspaceModelIfStale:()=>Ex});import{existsSync as uc}from"node:fs";import{join as rn}from"node:path";import{cancel as Sx,intro as cg,log as cc,outro as lc}from"@clack/prompts";import{simpleGit as dc}from"simple-git";function Fi(t){Sx(t),process.exit(1)}function lg(t,e,r){let n=t.spec.repos.filter(i=>!e||i.name===e);if(n.length===0)throw new Error(e?`repo "${e}" is not part of this project (see project.yaml)`:"the project has no repos configured");let o=[];for(let i of n){let s=i.mountAs==="."?t.root:rn(t.root,i.mountAs);if(!uc(rn(s,".git"))){r(`${i.name}: no local clone at ${s} \u2014 skipped (run \`codepipe clone\` first)`);continue}o.push({name:i.name,dir:s,defaultBranch:i.defaultBranch||"main"})}if(o.length===0)throw new Error("nothing to do \u2014 no repo clones found");return o}async function ug(t){let e=dc(t.dir),r=`origin/${t.defaultBranch}`;return await e.raw(["rev-parse","--verify",r]).then(()=>!0).catch(()=>!1)?r:"HEAD"}async function dg(t,e,r,n){let o=[];for(let i of e)try{let s=await Ka({repo:i.name,repoDir:i.dir,contextDir:t,settings:r,ref:await ug(i)});o.push(s),n(`${i.name}: ${s.counts.code} files, ${s.counts.component} components, ${s.counts.correlates} co-change edges @ ${s.headCommit.slice(0,10)}`)}catch(s){throw new Error(`${i.name}: ${s instanceof Error?s.message:String(s)}`)}return o}async function pc(t){cg("codepipe model build");let e=Se();e||Fi("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{let r=Qr(e.contextDir),n=lg(e,t.repo,s=>cc.warn(s)),o=await dg(e.contextDir,n,r,s=>cc.info(s)),i=await Bi(e.contextDir,o,{halfLifeDays:r.cochange.halfLifeDays});i.committed?lc(`model updated: ${i.filesWritten} files written, ${i.filesDeleted} stale removed`):lc("model already up to date (no changes)")}catch(r){Fi(r instanceof Error?r.message:String(r))}}async function fc(t){cg("codepipe model bootstrap");let e=Se();e||Fi("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{await pg(e,t.repo,{onLog:r=>cc.info(r)})}catch(r){Fi(r instanceof Error?r.message:String(r))}lc("bootstrap complete")}async function pg(t,e,r){let n=lg(t,e,r.onLog);return mc(t.contextDir,n,r)}async function mc(t,e,r){let n=Qr(t),o=await dg(t,e,n,r.onLog),i=Df(t),s=Of(n.issueKeyPattern,i),a=br([...n.ignore,...Xr]),c=[];for(let p of o){let d=e.find(m=>m.name===p.repo),f=await Mf({repo:p.repo,repoDir:d.dir,headCommit:p.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:s,pathToCurrent:vi(p.identityTable),entityByKey:p.entityByKey,ignored:a});c.push(f),r.onLog(`${p.repo}: ${f.size} task events mined from history`)}let{files:l,skippedPipeline:u}=Uf(t,c);return u>0&&r.onLog(`${u} events already recorded by the live pipeline \u2014 left untouched`),l.length>0&&await Ie(t,l,`model: bootstrap ${l.length} task events from history`),await Bi(t,o,{halfLifeDays:n.cochange.halfLifeDays}),{events:l.length}}async function Tx(t,e,r,n){if(r.length===0)throw new Error("the project has no repos configured");let o=[];for(let s of r){let a=s.mountAs??s.name,c=a==="."?e.root:rn(e.root,a),l=s.defaultBranch||"main";c!==e.contextDir&&uc(rn(c,".git"))?(await dc(c).fetch(["origin",l]).catch(()=>{}),o.push({name:s.name,dir:c,defaultBranch:l})):(n(`${s.name}: materializing clone in the daemon layout`),await xt(t,s),o.push({name:s.name,dir:Te(t,s.name),defaultBranch:l}))}let i=await mc(e.contextDir,o,{onLog:n});return{repos:o.length,events:i.events}}async function Ex(t,e={}){let r=e.onLog??(()=>{}),n=Qr(t.contextDir);if(!n.enabled)return{rebuilt:[],skipped:[]};let o=[],i=[],s=ac(t.contextDir),a=[];for(let c of t.repos){let l=c.mountAs==="."?t.root:rn(t.root,c.mountAs);if(!uc(rn(l,".git")))continue;let u=dc(l),p=c.defaultBranch||"main";e.fetch&&await u.fetch(["origin",p]).catch(()=>{});let d=await ug({name:c.name,dir:l,defaultBranch:p}),f=(await u.revparse([d]).catch(()=>"")).trim();if(f){if(s.get(c.name)?.builtFromCommit===f){i.push(c.name);continue}try{a.push(await Ka({repo:c.name,repoDir:l,contextDir:t.contextDir,settings:n,ref:f})),o.push(c.name)}catch(m){r(`[model] rebuild of ${c.name} failed: ${m instanceof Error?m.message:String(m)}`)}}}return a.length>0&&(await Bi(t.contextDir,a,{halfLifeDays:n.cochange.halfLifeDays}),r(`[model] release-path rebuild: ${o.join(", ")} (skipped up-to-date: ${i.join(", ")||"\u2014"})`)),{rebuilt:o,skipped:i}}var lo=x(()=>{"use strict";rt();ag();Ha();Fa();xi();no();mr();mt()});var mg={};Ir(mg,{computeDriftReport:()=>Px,supersededAdrIds:()=>fg});import{existsSync as gc,readFileSync as hc,readdirSync as yc}from"node:fs";import{join as nn}from"node:path";import{parse as Rx}from"yaml";import{simpleGit as Ix}from"simple-git";function Ax(t,e){let r=nn(t,`model/derived/structure/${e}`),n=[],o="";if(!gc(r))return{nodes:n,builtFromCommit:o};for(let i of yc(r).sort()){if(!i.endsWith(".yaml"))continue;let s;try{let a=Ct(Rx(hc(nn(r,i),"utf-8")));if(!a.ok)continue;s=a.value}catch{continue}o=s.builtFromCommit;for(let a of s.nodes){let c=Q(a.key);!c||c.level!=="code"&&c.level!=="component"||n.push({key:a.key,path:c.path,level:c.level,contentHash:a.contentHash,entityId:a.entityId})}}return{nodes:n,builtFromCommit:o}}function fg(t){let e=new Set,r=nn(t,"adr");if(!gc(r))return e;for(let n of yc(r).sort()){let o=/^(\d{4})-/.exec(n)?.[1];if(!(!o||!n.endsWith(".md")))try{let i=hc(nn(r,n),"utf-8").slice(0,600).toLowerCase();/status[^\n]*superseded/.test(i)&&e.add(`ADR-${o}`)}catch{}}return e}async function Px(t,e,r){let{nodes:n,builtFromCommit:o}=Ax(e,r),i=(await Ix(t).revparse(["HEAD"])).trim(),s=await ro(t,i),a=new Map(s.map(y=>[y.path,y.blobHash])),c=[],l=[],u=new Set,p=[];for(let y of n){if(y.level==="component"){p.push(y);continue}u.add(y.path);let v=a.get(y.path);v?y.contentHash&&v.slice(0,Cx)!==y.contentHash&&c.push(y.key):l.push(y.key)}let d=0,f=new Map,m=new Set;for(let y of s){let v=y.path.lastIndexOf("/"),T=v<0?"":y.path.slice(0,v);f.has(T)||f.set(T,new Set),f.get(T).add(y.path),u.has(y.path)||d++;let R=T;for(;R!==""&&!m.has(R);)m.add(R),R=R.includes("/")?R.slice(0,R.lastIndexOf("/")):""}let h=new Map;for(let y of u){let v=y.lastIndexOf("/"),T=v<0?"":y.slice(0,v);h.has(T)||h.set(T,new Set),h.get(T).add(y)}for(let y of p){if(!m.has(y.path)){l.push(y.key);continue}let v=h.get(y.path)??new Set,T=f.get(y.path)??new Set;(v.size!==T.size||[...v].some(E=>!T.has(E)))&&c.push(y.key)}let g=[],w=fg(e);if(w.size>0){let y=nn(e,"model/facts/annotations"),v=new Map(n.filter(T=>T.entityId).map(T=>[T.entityId,T.key]));if(gc(y))for(let T of yc(y).sort()){if(!T.endsWith(".md"))continue;let R=T.replace(/\.md$/,""),E=v.get(R);if(E)try{(hc(nn(y,T),"utf-8").match(/\bADR-(\d{3,4})\b/g)??[]).map(N=>`ADR-${N.slice(4).padStart(4,"0")}`).some(N=>w.has(N))&&g.push(E)}catch{}}}return{repo:r,builtFromCommit:o,headCommit:i,stale:[...new Set(c)].sort(),orphaned:[...new Set(l)].sort(),superseded:[...new Set(g)].sort(),newFiles:d}}var Cx,gg=x(()=>{"use strict";G();no();Cx=12});import{existsSync as yg,rmSync as _x}from"node:fs";import{join as $r}from"node:path";import{simpleGit as jx}from"simple-git";import"ws";function Ki(t,e={}){let r=e.log??{info:g=>console.log(g),warn:g=>console.warn(g)};r.info(`codepipe-cli v${Ue} (protocol ${lt})`);let n=g=>e.onEvent?.(g),o=e.workspace;o?.contextDir&&Ip(o.contextDir,r);let i=hg("CLI_TRACKING_POLL_INTERVAL_SEC"),s=hg("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let g=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(g)&&g>0?g*1e3:6e5})(),c=!1,l=!1,u=!1,p=new Set,d=!1,f=new Set,m=h();function h(){let g=ei(t.hubUrl,t.cliToken),w=null,y=new Mi(i,_=>{g.readyState===g.OPEN&&g.send(JSON.stringify(_))},r),v=new Ui(s,_=>{g.readyState===g.OPEN&&g.send(JSON.stringify(_))},r,{contextDir:o?.contextDir??null,isSelfComment:_=>f.has(_)}),T=null,R=async()=>{try{let _={trackerProvider:tc(o?.contextDir??null)};try{let O=await ne(t.hubUrl,t.cliToken,t.projectId);_={..._,repos:O.repos,contextRepo:O.contextRepo}}catch(O){r.warn(`[readiness] could not fetch project summary for push checks: ${O instanceof Error?O.message:String(O)}`)}let M=await Nd(t.projectId,_);if(g.readyState!==g.OPEN)return;let L={type:"cli_readiness",projectId:t.projectId,ready:M.ready,checks:M.checks,creds:M.creds,secretNames:Wu(t.projectId),checkedAt:M.checkedAt};if(g.send(JSON.stringify(L)),M.ready)r.info("[readiness] ready");else{let O=M.checks.filter(S=>!S.ok).map(S=>`${S.name}(${S.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${O.join(", ")}`)}let z=Fd(M.creds,u);if(z==="open"){u=!0;let O=Gd(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${O}`),ur(O)}else z==="rearm"&&(u=!1)}catch(_){r.warn(`[readiness] check failed: ${_ instanceof Error?_.message:String(_)}`)}},E=()=>{R(),T=setInterval(()=>void R(),a),typeof T.unref=="function"&&T.unref()},b=()=>{T&&(clearInterval(T),T=null)},I=150,N=new Map,U=_=>{let M=N.get(_);if(!M||(M.timer&&clearTimeout(M.timer),N.delete(_),M.events.length===0||g.readyState!==g.OPEN))return;let L={type:"run_activity",projectId:t.projectId,runId:_,events:M.events};g.send(JSON.stringify(L))},C=(_,M)=>{let L=N.get(_);if(L||(L={events:[],timer:null},N.set(_,L)),L.events.push(M),M.kind==="result"){U(_);return}L.timer||(L.timer=setTimeout(()=>U(_),I),L.timer.unref?.())},k=o?.contextDir?new li(o.contextDir,t.projectId,_=>{g.readyState===g.OPEN&&g.send(JSON.stringify(_))},r):null,D=async()=>{let _=o?.contextDir;if(!_)throw new Error("no context repo clone on this CLI");let M;try{M=(await ne(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let L=await Qp(_,t.projectId,M,r);return g.readyState===g.OPEN&&g.send(JSON.stringify(L)),L},A=null,H=async()=>{let _=o?.contextDir;if(_)try{let{readContextIndexHub:M,collectSearchRows:L}=await Promise.resolve().then(()=>(io(),oo));if(M(_)!=="metadata")return;let z=L(_);g.readyState===g.OPEN&&(g.send(JSON.stringify({type:"model_index",projectId:t.projectId,rows:z})),r.info(`[model] tier-2 index snapshot pushed (${z.length} rows)`))}catch(M){r.warn(`[model] tier-2 index push failed (non-fatal): ${M instanceof Error?M.message:String(M)}`)}},q=()=>{A&&clearTimeout(A),A=setTimeout(()=>void H(),5e3)},Z=null,qe=async _=>{if(o?.contextDir)try{let{rebuildWorkspaceModelIfStale:M}=await Promise.resolve().then(()=>(lo(),Gi));(await M({root:o.root,contextDir:o.contextDir,repos:o.repos},{fetch:_,onLog:z=>r.info(z)})).rebuilt.length>0&&q()}catch(M){r.warn(`[model] release-path rebuild failed (non-fatal): ${M instanceof Error?M.message:String(M)}`)}},Ye=_=>{Z&&clearTimeout(Z),Z=setTimeout(()=>void qe(_),6e4)},ge=setInterval(()=>void qe(!0),6*36e5);return g.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let _=Zu(t.projectId),M=V("ORIGIN")==="farm"?"farm":"local",L=V("FARM_ID"),z=t.accountEmail??_.email,O;try{let $=df(t.projectId);$&&(O=$.publicKey,r.info(`[cred-channel] key fingerprint: ${$.fingerprint}`))}catch($){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${$ instanceof Error?$.message:String($)}`)}let S={type:"register",projectId:t.projectId,platformVersion:Ue,protocolVersion:lt,accountId:_.accountId,accountLabel:_.label,origin:M,inFlightActionIds:[...p],...z?{accountEmail:z}:{},...M==="farm"&&L?{farmId:L}:{},...O?{sealPublicKey:O}:{}};g.send(JSON.stringify(S))}),g.on("message",async _=>{let M=_.toString("utf-8");if(M==="pong"||M==="ping")return;let L;try{L=JSON.parse(M)}catch{return}if(!L||typeof L!="object")return;let z=L.type;if(z==="registered"){let S=L;if(S.ok){if(r.info(`[ws] registered for project ${S.projectId}`),n({kind:"registered",projectId:S.projectId??t.projectId}),y.start(),k?.start(),E(),wc(t,o,r),o?.contextDir){try{let $=mi(o.contextDir,t.projectId);g.readyState===g.OPEN&&g.send(JSON.stringify($)),$.outdated&&(r.warn(`[ctx] context format outdated: v${$.templateVersion} \u2192 v${$.currentVersion}`+($.missingPaths.length>0?` (missing: ${$.missingPaths.join(", ")})`:"")),l||(l=!0,D().catch(()=>{})))}catch($){r.warn(`[ctx] context-format detect failed (non-fatal): ${$ instanceof Error?$.message:String($)}`)}H(),Ye(!0)}}else r.warn(`[ws] register rejected: ${S.reason??"unknown"}`),n({kind:"register_rejected",reason:S.reason??"unknown"}),c=!0,g.close();return}if(z==="hello"){let S=L;w=Io(S.protocolVersion);let $=w?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${S.platformVersion} (protocol ${S.protocolVersion}) \u2014 ${$}`),w||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Ue}, protocol ${lt}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${kc}`),n({kind:"incompatible",hubVersion:typeof S.platformVersion=="string"?S.platformVersion:null,hubProtocol:typeof S.protocolVersion=="number"?S.protocolVersion:null,updateCommand:kc}));return}if(z==="tracking_targets"){y.setTargets(L.targets);return}if(z==="youtrack_sync_request"){v.setRequest(L);return}if(z==="youtrack_force_sync"){v.forceSync();return}if(z==="sync_local"){await Dx(L,o,g,r);return}if(z==="provision_repo"){let S=L;r.info(`[repo] provision_repo: ${S.repo.name} (${S.repo.host}:${S.repo.owner}/${S.repo.repoName})`),await Nx(t,o,S.repo,r),await wc(t,o,r);return}if(z==="remove_repo"){let S=L;r.info(`[repo] remove_repo: ${S.repoName}${S.purge?" (purge)":""}`),await wc(t,o,r),S.purge&&Ox(t,o,S.repoName,r);return}if(z==="context_write"){await Lx(L,o,g,r);return}if(z==="adr_promote"){await Mx(L,o,g,r);return}if(z==="cred_update"){let S=L,$=W(t.projectId),j=$?.sealKey?await pf(t.projectId,S.kind,S.sealed,$.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},Y={type:"cred_update_result",updateId:S.updateId,projectId:t.projectId,ok:j.ok,...j.detail?{detail:j.detail}:{}};g.readyState===g.OPEN&&g.send(JSON.stringify(Y)),j.ok?(r.info(`[cred] ${S.kind} replaced${j.detail?` \u2014 ${j.detail}`:""}`),R()):r.warn(`[cred] ${S.kind} replacement rejected: ${j.detail??"unknown"}`);return}if(z==="readiness_check"){r.info("[readiness] on-demand check requested"),R();return}if(z==="agent_login_start"){Ud(t,g,L,r,R);return}if(z==="move_to_farm"){let S=L;r.info(`[farm-move] request to move ${t.projectId} onto farm ${S.farmName} (${S.farmId})`);let $=await Lm(t,S,o?.contextDir,r);g.readyState===g.OPEN&&g.send(JSON.stringify($)),$.ok?r.info(`[farm-move] done \u2014 farm daemon ${$.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${$.error??"unknown error"}`);return}if(z==="gh_runner_setup"){let S=L;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${S.runnerName} (${S.runnerId})`);let $=await qm(t,S,r);g.readyState===g.OPEN&&g.send(JSON.stringify($)),$.ok?r.info(`[ghr] runners connected on ${S.runnerName}`):r.warn(`[ghr] setup failed: ${$.error??"see per-repo statuses"}`);return}if(z==="gh_runner_teardown"){let S=L;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${S.runnerName} (${S.runnerId})`);let $=await Ym(t,S,r);g.readyState===g.OPEN&&g.send(JSON.stringify($)),$.ok?r.info(`[ghr] runners disconnected from ${S.runnerName}`):r.warn(`[ghr] teardown failed: ${$.error??"unknown error"}`);return}if(z==="tracker_fields_request"){let S=L,$={type:"tracker_fields_result",requestId:S.requestId,projectId:t.projectId,ok:!1},j=kt({contextDir:o?.contextDir??null});if(!j.ok)$.error=j.error;else try{$.fields=await j.provider.fetchStateFields(S.projectKey),$.ok=!0}catch(Y){$.error=Y instanceof Error?Y.message:String(Y)}g.readyState===g.OPEN&&g.send(JSON.stringify($)),$.ok||r.warn(`[yt-fields] listing failed: ${$.error??"unknown"}`);return}if(z==="project_secret_update"||z==="project_secret_delete"){let S=L,$;if(S.type==="project_secret_update"){let Y=W(t.projectId);$=Y?.sealKey?Jm(t.projectId,S.name,S.sealed,Y.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else $=Xm(t.projectId,S.name);let j={type:"project_secret_update_result",updateId:S.updateId,projectId:t.projectId,ok:$.ok,...$.detail?{detail:$.detail}:{}};g.readyState===g.OPEN&&g.send(JSON.stringify(j)),$.ok?(r.info(`[secret] ${S.name} ${S.type==="project_secret_update"?"saved":"deleted"}`+($.detail?` \u2014 ${$.detail}`:"")),R()):r.warn(`[secret] ${S.name} rejected: ${$.detail??"unknown"}`);return}if(z==="auto_apply_local"){let S=L;if(!o?.contextDir){r.warn(`[apply] auto_apply_local for ${S.claim.taskKey} \u2014 no workspace (headless), skipped; task stays in READY_TO_APPLY`);return}let $=await yp({hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId,root:o.root,contextDir:o.contextDir,repos:o.repos},S.claim,r).catch(j=>({ok:!1,message:j instanceof Error?j.message:String(j)}));$.ok?r.info(`[apply] ${S.claim.taskKey}: ${$.message}`):r.warn(`[apply] ${S.claim.taskKey}: ${$.message} \u2014 task stays in READY_TO_APPLY`),n({kind:"local_applied",taskKey:S.claim.taskKey,ok:$.ok,...$.ok?{branches:$.branches??[]}:{error:$.message}});return}if(z==="sandbox_keys"){let S=W(t.projectId);if(!S){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let $=Ur(t.projectId),j=sf(L,S,$,r);for(let Y of j)g.readyState===g.OPEN&&g.send(JSON.stringify(Y));return}if(z!=="dispatch_action")return;let O=L;if(w===!1){let S=`refused: HUB protocol incompatible with CLI v${Ue} (protocol ${lt})`;g.send(JSON.stringify({type:"action_result",actionId:O.actionId,status:"failed",error:S})),r.warn(`[exec] ${O.actionId} (${O.action.type}) \u2192 REFUSED: ${S}`),r.warn(`[exec] update the CLI to clear this: ${kc}`),n({kind:"action",actionId:O.actionId,actionType:O.action.type,ok:!1,error:S});return}if(O.action.type==="model_drift"){p.add(O.actionId);try{let S,$=o?.repos.find(j=>j.name===O.action.repoName);if(!o?.contextDir||!$)S={status:"failed",error:"no local workspace/repo clone on this CLI"};else try{let{computeDriftReport:j}=await Promise.resolve().then(()=>(gg(),mg)),Y=$.mountAs==="."?o.root:$r(o.root,$.mountAs);S={status:"done",result:{report:await j(Y,o.contextDir,$.name)}}}catch(j){S={status:"failed",error:j instanceof Error?j.message:String(j)}}g.send(JSON.stringify({type:"action_result",actionId:O.actionId,...S}))}finally{p.delete(O.actionId)}return}if(O.action.type==="model_bootstrap"){p.add(O.actionId);try{let S;if(!o?.contextDir)S={status:"failed",error:"no Context Repo clone on this CLI"};else if(d)S={status:"failed",error:"model bootstrap is already running"};else{d=!0;try{let $=await ne(t.hubUrl,t.cliToken,t.projectId),{bootstrapDaemonModel:j}=await Promise.resolve().then(()=>(lo(),Gi)),Y=await j(t.projectId,{root:o.root,contextDir:o.contextDir},$.repos,ke=>r.info(`[model] ${ke}`));r.info(`[model] bootstrap done: ${Y.repos} repos, ${Y.events} task events`),q(),S={status:"done",result:{repos:Y.repos,events:Y.events}}}catch($){S={status:"failed",error:$ instanceof Error?$.message:String($)},r.warn(`[model] bootstrap failed: ${S.error}`)}finally{d=!1}}g.readyState===g.OPEN&&g.send(JSON.stringify({type:"action_result",actionId:O.actionId,...S}))}finally{p.delete(O.actionId)}return}if(O.action.type==="local_apply"){p.add(O.actionId);try{let S;if(!o)S={status:"failed",error:"no local workspace on this CLI"};else{let j=await Pm(o,O.action.repos,r);if(S=j.ok?{status:"done",result:{repos:j.repos}}:{status:"failed",error:j.error},j.ok&&o.contextDir){let Y=O.action.taskId.split(":")[1]??"";for(let ke of Y?j.repos:[]){let X=o.repos.find(ee=>ee.name===ke.repoName);if(!X)continue;let{recordPipelineEvent:we}=await Promise.resolve().then(()=>(Xa(),$m));await we({contextDir:o.contextDir,repoDir:$r(o.root,X.mountAs),repoName:ke.repoName,taskKey:Y,commitSha:ke.commit}).catch(ee=>r.warn(`[model] task event for ${Y} failed: ${ee instanceof Error?ee.message:String(ee)}`))}q()}}g.send(JSON.stringify({type:"action_result",actionId:O.actionId,...S}));let $=S.status!=="failed";$?r.info(`[exec] ${O.actionId} (local_apply) \u2192 done`):r.warn(`[exec] ${O.actionId} (local_apply) \u2192 FAILED: ${S.status==="failed"?S.error:"?"}`),n({kind:"action",actionId:O.actionId,actionType:"local_apply",ok:$,...S.status==="failed"?{error:S.error}:{}})}finally{p.delete(O.actionId)}return}p.add(O.actionId);try{let S=await Im({action:O.action,repo:O.repo,trackerIssueId:O.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:k?()=>k.reportNow():void 0,refreshContextStatus:o?.contextDir?D:void 0,onRunActivity:C}).catch(Y=>({status:"failed",error:Y instanceof Error?Y.message:String(Y)}));O.action.type==="tracker_comment"&&S.status==="done"&&"result"in S&&typeof S.result?.commentId=="string"&&f.add(S.result.commentId),g.send(JSON.stringify({type:"action_result",actionId:O.actionId,...S}));let $=S.status!=="failed",j=!$&&"error"in S?S.error:void 0;$?r.info(`[exec] ${O.actionId} (${O.action.type}) \u2192 done`):r.warn(`[exec] ${O.actionId} (${O.action.type}) \u2192 FAILED: ${j??"?"}`),n({kind:"action",actionId:O.actionId,actionType:O.action.type,ok:$,...j?{error:j}:{}}),$&&["apply_delivery","context_write","create_pr"].includes(O.action.type)&&q(),$&&["merge_pr","merge_branch"].includes(O.action.type)&&Ye(!0)}finally{p.delete(O.actionId)}}),g.on("close",(_,M)=>{let L=M?.toString("utf-8")??"";if(r.info(`[ws] closed code=${_}${L?` reason=${L}`:""}`),y.stop(),v.stop(),k?.stop(),b(),clearInterval(ge),Z&&clearTimeout(Z),A&&clearTimeout(A),L==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:_}),!c&&setTimeout(()=>{m=h()},2e3)}),g.on("error",_=>r.warn(`[ws] error: ${_.message}`)),g}return{stop(){c=!0,m.close()}}}async function wc(t,e,r){try{let n=await ne(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=Qn(t.projectId,n.repos,e?.contextDir);for(let s of o)r.info(`[repo] restaged repo set in ${s}`);for(let s of i)r.warn(`[repo] could not restage ${s.path}: ${s.error}`)}catch(n){r.warn(`[repo] repo-set reconcile skipped: ${n instanceof Error?n.message:String(n)}`)}}async function Nx(t,e,r,n){let o=r.mountAs??r.name;if(o==="."){n.info(`[repo] ${r.name} mounts in place (mount_as: .) \u2014 nothing to clone`);return}let i=e?$r(e.root,o):Te(t.projectId,r.name);if(yg($r(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await jx().clone(qn(r),i),n.info(`[repo] cloned ${r.name} \u2192 ${i}`)}catch(s){n.warn(`[repo] clone of ${r.name} failed (will retry lazily): ${s instanceof Error?s.message.trim():String(s)}`)}}function Ox(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?$r(e.root,o):Te(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!yg($r(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{_x(i,{recursive:!0,force:!0}),n.info(`[repo] purged local clone ${i}`)}catch(s){n.warn(`[repo] purge of ${i} failed: ${s instanceof Error?s.message:String(s)}`)}}async function Dx(t,e,r,n){if(!e){n.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let o of t.repos){let i=e.repos.find(l=>l.name===o.repoName),s=$r(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await wp(s,a).catch(l=>({status:"warn",reason:l instanceof Error?l.message:String(l)}));c.status==="updated"?n.info(`[sync] ${o.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?n.info(`[sync] ${o.repoName}: not cloned in workspace \u2014 skipped`):(n.warn(`[sync] ${o.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:o.repoName,reason:c.reason??"sync skipped"})))}}async function Lx(t,e,r,n){let o=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{await Ie(e.contextDir,t.files,t.message),n.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[ctx] context_write ${t.id} failed: ${s}`),o("failed",s)}}async function Mx(t,e,r,n){let o=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[adr] adr_promote ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{let i=t.source??"task",s=await Op(e.contextDir,t.taskKey,t.slugs,void 0,i);if(n.info(`[adr] adr_promote ${t.id}: promoted ${s.promoted.length}, skipped ${s.skipped.length}`+(s.promoted.length>0?` (${s.promoted.join(", ")})`:"")),s.missing.length>0){let a=l=>i==="staging"?`adr/DRAFT-${l}.md`:`tasks/${t.taskKey}/adr/DRAFT-${l}.md`,c=`draft file(s) missing in clone: ${s.missing.map(a).join(", ")}`;n.warn(`[adr] adr_promote ${t.id}: ${c}`),o("failed",c);return}o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[adr] adr_promote ${t.id} failed: ${s}`),o("failed",s)}}function hg(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}var kc,bc=x(()=>{"use strict";_e();G();ed();Bd();Kd();Zo();da();bp();Ep();Dp();rt();St();xa();Zp();Ia();mr();af();ff();Cm();_m();Mm();Vm();Re();Qm();Kr();ue();Zm();ng();Ni();kc="npm i -g @code-partner/codepipe@latest"});import{execFileSync as Ux}from"node:child_process";import{mkdtempSync as Bx,mkdirSync as Fx,readFileSync as kg,rmSync as Gx,writeFileSync as Kx}from"node:fs";import{tmpdir as Hx}from"node:os";import{dirname as Wx,join as wg}from"node:path";function bg(t="codepipe-context"){let e=Bx(wg(Hx(),"codepipe-ssh-")),r=wg(e,"id_ed25519");try{return Ux("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:kg(r,"utf-8"),publicKey:kg(`${r}.pub`,"utf-8").trim()}}finally{Gx(e,{recursive:!0,force:!0})}}async function $g(t,e,r,n="codepipe-context"){let o=await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/keys`,{method:"POST",headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({title:n,key:r,read_only:!1})});if(o.ok)return;let i=await o.text();if(!(o.status===422&&/already in use/i.test(i)))throw new Error(`add deploy key failed: ${o.status} ${i}`)}function vg(t){if(/^git@[^:]+:.+/.test(t))return t;let e=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(e)return`git@${e[1]}:${e[2]}`;let r=t.match(/^https:\/\/(?:[^@/]+@)?([^/]+)\/(.+)$/);return r?`git@${r[1]}:${r[2]}`:t}function xg(t,e){Fx(Wx(t),{recursive:!0});let r=e.endsWith(`
|
|
645
|
+
`;return await Ie(this.contextDir,[{path:`tasks/${e}/comments.jsonl`,content:c}],`tracker(${e}): comment`),{id:i.id}}async createIssue(e){let r=new Date().toISOString(),n=await zp(this.contextDir,this.config.prefix,o=>this.renderNewIssueFiles(o,e,r),o=>`tracker(${o}): create issue`);return{id:n,key:n}}async editIssue(e,r){await this.mutateRecord(e,n=>({...n,...r.title!==void 0?{title:r.title}:{}}),r.body)}async applyLink(e,r,n){let o=r==="subtask_of"?"subtask":"depends_on";await this.mutateRecord(e,i=>{let s=i.links.filter(a=>!(a.type===o&&a.targetKey===n));return s.push({type:o,targetKey:n}),{...i,links:s}})}async fetchStateFields(e){return[{name:"Status",values:Fs.statusColumns}]}async mutateRecord(e,r,n){let o=Qn(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=Zn(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:Bn(e),content:Ca(i)},...ji(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await Ie(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:Mo,status:r.targetStatus,links:[],created:n,updated:n},i=Zn(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:Bn(e),content:Ca(o)},...ji(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}}});import{existsSync as Rm,readFileSync as Im}from"node:fs";import{join as Cm}from"node:path";import{parseDocument as Am}from"yaml";function oc(t){if(!t)return"youtrack";try{let e=Cm(t,"project.yaml");return Rm(e)&&Am(Im(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function kt(t){let e=oc(t.contextDir);if(e==="internal"){let n=t.contextDir;if(!n)return{ok:!1,kind:e,error:"internal tracker: no Context Repo clone on this CLI"};let o=qp(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=qv(n);return i?{ok:!0,kind:e,provider:new lo(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=wd();return r?{ok:!0,kind:e,provider:new co(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function qv(t){try{let e=Cm(t,"project.yaml");if(!Rm(e))return null;let r=Am(Im(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var Di=v(()=>{"use strict";lr();tc();nc();yi();tc();nc()});async function tn(t,e){let n=(Li.get(t)??Promise.resolve()).catch(()=>{}).then(e);Li.set(t,n);try{return await n}finally{Li.get(t)===n&&Li.delete(t)}}async function Pm(t){let{action:e,repo:r}=t,n="repoName"in e?e.repoName:"-",o="taskId"in e?e.taskId:"draftId"in e?e.draftId:e.projectId;dr(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return J("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return tn(`${i}/${r.name}`,async()=>{let s=await xt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Te(i,r.name,t.baseDir),{commit:c,pushed:l}=await lp(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force,push:e.push});if(t.contextDir){let u=e.taskId.split(":")[1]??"";u&&await Qa({contextDir:t.contextDir,repoDir:a,repoName:r.name,taskKey:u,commitSha:c}).catch(p=>{dr(`[model] task event for ${u} failed: ${p instanceof Error?p.message:String(p)}`)})}return ce({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,pushed:l,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"push_branch":{if(!r)return J("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return tn(`${i}/${r.name}`,async()=>{let s=await xt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Te(i,r.name,t.baseDir);return await up(s,a,{branchName:e.branchName,force:e.force}),ce({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"early_branch":{if(!r)return J("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return tn(`${i}/${r.name}`,async()=>{let s=await xt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Te(i,r.name,t.baseDir),{commit:c,pushed:l}=await dp(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return ce({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return J("no repo spec");let i=Ze(r),s=await i.createPullRequest(r,e);if(t.contextDir){let a=e.taskId.split(":")[1]??"",c=e.taskId.split(":",2)[0]??"?";a&&await Za({contextDir:t.contextDir,repoDir:Te(c,r.name,t.baseDir),branchName:e.branchName,baseBranch:e.baseBranch,fallbackTaskKey:a,prUrl:s.url}).catch(l=>{dr(`[model] pr link for ${a} failed: ${l instanceof Error?l.message:String(l)}`)})}return ce({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return J("no repo spec");let i=Ze(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ce({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return J("no repo spec");let i=Ze(r);return await i.closePR(r,e.prNumber,e.comment),ce({prNumber:e.prNumber,host:i.name})}case"rewrite_cluster_branch":{if(!r)return J("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return tn(`${i}/${r.name}`,async()=>{let s=await xt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Te(i,r.name,t.baseDir),{commit:c,dropped:l}=await fp(s,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:r.defaultBranch});return ce({branch:e.branchName,commit:c,dropped:l,pushed:l>0})})}case"merge_branch":{if(!r)return J("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return tn(`${i}/${r.name}`,async()=>{let s=await xt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Te(i,r.name,t.baseDir),{mergedSha:c}=await mp(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ce({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return J("no repo spec");let i=t.cloneUrlOverride??Vn(r),a=(await gp(i)).filter(u=>hp(u,e.issueKey)),c=Ze(r),l=null;if(c.findOpenPrByBranch)for(let u of a){let p=await c.findOpenPrByBranch(r,u).catch(()=>null);if(p){l={number:p.number,url:p.url};break}}return ce({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return J("no repo spec");let i=Ze(r);return await i.addPRComment(r,e.prNumber,e.body),ce({prNumber:e.prNumber,host:i.name})}case"tracker_status":{let i=kt({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),ce({issueId:t.trackerIssueId,newStatus:e.newStatus})):J("no tracker_issue_id provided"):J(i.error)}case"tracker_comment":{let i=kt({contextDir:t.contextDir});if(!i.ok)return J(i.error);if(!t.trackerIssueId)return J("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return ce({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=kt({contextDir:t.contextDir});if(!i.ok)return J(i.error);if(!e.projectKey)return J("no projectKey in create_tracker_issue action");let{id:s,key:a}=await i.provider.createIssue({projectKey:e.projectKey,title:e.title,body:e.body,targetStatus:e.targetStatus});return ce({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=kt({contextDir:t.contextDir});if(!i.ok)return J(i.error);let s=0;for(let a of e.links)try{await i.provider.applyLink(a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return J(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return ce({applied:s})}case"set_project_setting":{if(!t.contextDir)return J("no context repo clone on this CLI");let i=await Tf(t.contextDir,e.edits);return ce({files:i.files})}case"tracker_edit":{let i=kt({contextDir:t.contextDir});if(!i.ok)return J(i.error);if(!t.contextDir)return J("no context repo clone on this CLI");await i.provider.editIssue(e.issueKey,{...e.title!==void 0?{title:e.title}:{},...e.body!==void 0?{body:e.body}:{}});let s=await i.provider.getIssue(e.issueKey);return s&&await Ni(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),ce({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return J("no context repo clone on this CLI");let i=await Af(t.contextDir,e);return ce({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return J("no context repo clone on this CLI");let i=await If(t.contextDir,e);return ce({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ce({reported:!0})):J("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return J("no context repo clone on this CLI");let i=await t.refreshContextStatus();return ce({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return J("no project workspace on this CLI");if(!r)return J("no repo spec");if(!t.onRunActivity)return J("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=ui(t.contextDir),c=s.find(f=>f.id===e.actionId);if(!c){let f=a.find(m=>m.file===`actions/${e.actionId}.yml`);return J(f?`action "${e.actionId}" failed to parse: ${f.error}`:`unknown action "${e.actionId}"`)}let l=Xl(c,e.input);if(!l.ok)return J(l.error);let u=Rp(t.contextDir),p=W(e.projectId),d={};return p?.github?.token&&(d.GH_TOKEN=p.github.token),p?.gitlab?.token&&(d.GITLAB_TOKEN=p.gitlab.token),p?.bitbucket&&(d.BITBUCKET_EMAIL=p.bitbucket.email,d.BITBUCKET_API_TOKEN=p.bitbucket.apiToken),p?.youtrack&&(d.YOUTRACK_URL=p.youtrack.url,d.YOUTRACK_TOKEN=p.youtrack.token),tn(`${e.projectId}/${r.name}`,async()=>{await xt(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let f=Te(e.projectId,r.name,t.baseDir),m=await wf({cwd:f,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:h=>i(e.runId,h)});return ce({runId:e.runId,status:m.status,exitCode:m.exitCode,...m.failedStep?{failedStep:m.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return J("no context repo clone on this CLI");let i=xf(t.contextDir,e.path);return ce({path:e.path,...i})}case"search_model":{if(!t.contextDir)return J("no context repo clone on this CLI");let{searchModelIndex:i}=await Promise.resolve().then(()=>(ao(),so)),s=await i(t.contextDir,e.q,e.limit);return ce({hits:s})}case"model_drift":return J("model_drift requires a local workspace (handled by the daemon)");case"model_bootstrap":return J("model_bootstrap requires a local workspace (handled by the daemon)");case"local_apply":return J("local_apply requires a local workspace (handled by the daemon)");default:return J(`unsupported action type: ${e.type}`)}}catch(i){return J(i instanceof Error?i.message:String(i))}}function ce(t){return{status:"done",result:t}}function J(t){return{status:"failed",error:t}}var Li,_m=v(()=>{"use strict";G();ha();bf();Sf();ue();Ef();Cf();La();Dt();ii();mr();ec();Di();Oi();Li=new Map});import{existsSync as Yv,mkdtempSync as Vv,rmSync as zv}from"node:fs";import{tmpdir as Jv}from"node:os";import{join as ic}from"node:path";import{simpleGit as jm}from"simple-git";async function Nm(t,e,r){let n=[];for(let a of e){let c=t.repos.find(u=>u.name===a.repoName);if(!c)return{ok:!1,error:`repo "${a.repoName}" not in project.yaml \u2014 run /sync`};let l=ic(t.root,c.mountAs);if(!Yv(ic(l,".git")))return{ok:!1,error:`${c.mountAs}/ not cloned \u2014 run /sync first`};n.push({payload:a,dir:l,mountAs:c.mountAs,defaultBranch:c.defaultBranch})}let o=[];for(let a of n){let c=jm(a.dir),l=a.payload;try{await c.fetch()}catch(f){return{ok:!1,error:`fetch failed in ${a.mountAs}: ${uo(f)}`}}let u=`origin/${l.baseRef}`;await ex(c,u)||(u=`origin/${a.defaultBranch}`);let p;try{p=(await c.revparse([u])).trim()}catch(f){return{ok:!1,error:`base ${u} unavailable in ${a.mountAs}: ${uo(f)}`}}let d;try{d=await Yn(c,l.deliverySha,()=>fr(c,{contextRepoCloneUrl:l.contextRepoCloneUrl,deliveryRef:l.deliveryRef,deliverySha:l.deliverySha,baseSha:l.baseSha,commitMessage:l.commitMessage}))}catch(f){return{ok:!1,error:`fetch delivery failed in ${a.mountAs}: ${uo(f)}`}}o.push({repoName:l.repoName,mountAs:a.mountAs,git:c,branch:l.branchName,startPoint:p,deliveryCommit:d})}let i=[],s=[];for(let a of o){let c=await tx(a.git,`refs/heads/${a.branch}`);try{let u=(await a.git.revparse([`${a.deliveryCommit}^`])).trim()===a.startPoint?a.deliveryCommit:await Qv(a);await a.git.raw(["branch","-f",a.branch,u]),i.push({git:a.git,mountAs:a.mountAs,branch:a.branch,priorSha:c}),s.push({repoName:a.repoName,branch:a.branch,commit:u}),r.info(`[local-apply] ${a.mountAs}: branch ${a.branch} \u2192 ${u.slice(0,10)} (no checkout)`)}catch(l){return await Zv(i,r),{ok:!1,error:`apply failed in ${a.mountAs}: ${uo(l)} (rolled back all repos)`}}}return{ok:!0,repos:s}}async function Qv(t){let e=Vv(ic(Jv(),"codepipe-local-apply-"));try{await t.git.raw(["worktree","add","--detach",e,t.startPoint]);let r=jm(e);try{await r.raw([...Xv,"cherry-pick",t.deliveryCommit])}catch(n){throw await r.raw(["cherry-pick","--abort"]).catch(()=>{}),n}return(await r.revparse(["HEAD"])).trim()}finally{await t.git.raw(["worktree","remove","--force",e]).catch(()=>{}),zv(e,{recursive:!0,force:!0}),await t.git.raw(["worktree","prune"]).catch(()=>{})}}async function Zv(t,e){for(let r of t)try{r.priorSha?await r.git.raw(["branch","-f",r.branch,r.priorSha]):await r.git.raw(["branch","-D",r.branch])}catch(n){e.warn(`[local-apply] rollback of ${r.mountAs}#${r.branch} failed: ${uo(n)} \u2014 check manually`)}}async function ex(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function tx(t,e){try{return(await t.raw(["rev-parse","--verify","--quiet",e])).trim()||null}catch{return null}}function uo(t){return t instanceof Error?t.message.trim():String(t)}var Xv,Om=v(()=>{"use strict";mr();Xv=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{homedir as rx}from"node:os";import{existsSync as nx,mkdirSync as ox,readFileSync as ix,writeFileSync as sx}from"node:fs";import{dirname as ax,join as cx}from"node:path";function sc(){return V("FARM_PINS")??cx(rx(),".codepipe","farm-pins.json")}function Dm(){let t=sc();if(!nx(t))return{};try{return JSON.parse(ix(t,"utf-8"))}catch{return{}}}function lx(t){let e=sc();ox(ax(e),{recursive:!0}),sx(e,JSON.stringify(t,null,2)+`
|
|
646
|
+
`,{mode:384})}function ux(t){return Dm()[t]}function Mi(t,e){let r=Dm();r[t]=e,lx(r)}function Ui(t,e){let r=je(e),n=ux(t);if(n&&n!==r)throw new Error(`farm ${t} key fingerprint changed (pinned ${n}, now ${r}) \u2014 refusing to seal. If the farm was re-registered intentionally, remove its entry from ${sc()}.`);return r}var ac=v(()=>{"use strict";_e();He()});import{existsSync as Lm,readFileSync as Mm}from"node:fs";import{join as Um}from"node:path";async function Bm(t,e,r,n){let o=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return o(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=je(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Ui(e.farmId,e.farmPublicKey);let s=W(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await ne(t.hubUrl,t.cliToken,t.projectId),c;if(r){let d=Um(r,"project.yaml"),f=Um(r,"regimen.yaml");Lm(d)&&Lm(f)?c={projectYaml:Mm(d,"utf-8"),regimenYaml:Mm(f,"utf-8")}:n.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},u=Tt(e.farmPublicKey,JSON.stringify(l));Mi(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let p=await ni(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:u});return p.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...p.daemonStatus?{daemonStatus:p.daemonStatus}:{}}:o(p.error??"farm provisioning failed")}catch(i){return o(i instanceof Error?i.message:String(i))}}var Fm=v(()=>{"use strict";He();ac();Re();ue()});import{homedir as dx}from"node:os";import{existsSync as px,mkdirSync as fx,readFileSync as mx,writeFileSync as gx}from"node:fs";import{dirname as hx,join as yx}from"node:path";function cc(){return V("RUNNER_PINS")??yx(dx(),".codepipe","runner-pins.json")}function Gm(){let t=cc();if(!px(t))return{};try{return JSON.parse(mx(t,"utf-8"))}catch{return{}}}function kx(t){let e=cc();fx(hx(e),{recursive:!0}),gx(e,JSON.stringify(t,null,2)+`
|
|
647
|
+
`,{mode:384})}function wx(t){return Gm()[t]}function lc(t,e){let r=Gm();r[t]=e,kx(r)}function Km(t,e){let r=je(e),n=wx(t);if(n&&n!==r)throw new Error(`runner host ${t} key fingerprint changed (pinned ${n}, now ${r}) \u2014 refusing to seal. If the runner host was re-registered intentionally, remove its entry from ${cc()}.`);return r}var Hm=v(()=>{"use strict";_e();He()});async function Wm(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:qm(t)});if(!o.ok)throw new Error(`github ${n} for ${e}/${r}: HTTP ${o.status}`);let i=await o.json();if(!i.token)throw new Error(`github ${n} for ${e}/${r}: no token in response`);return i.token}async function Vm(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(je(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Km(e.runnerId,e.runnerPublicKey);let i=W(t.projectId)?.github?.token;if(!i)throw new Error("no GitHub token stored for this project on this CLI");let a=((await r.fetchProject(t.hubUrl,t.cliToken,t.projectId)).repos??[]).find(c=>c.host==="github"&&c.owner===e.owner&&c.repoName===e.repo);if(!a)throw new Error(`${e.owner}/${e.repo} is not a GitHub repository of this project`);return{githubToken:i,repo:a}}async function zm(t,e,r,n=Ym){let o=i=>({type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repo:s}=await Vm(t,e,n);if(!await n.api.repoHasAdmin(i,s.owner,s.repoName))return o(`the GitHub token lacks admin access on ${s.owner}/${s.repoName} \u2014 replace it (project page \u2192 Tokens \u2192 Replace) with a token that has admin rights on this repository`);let a={projectId:t.projectId,runners:[{owner:s.owner,repo:s.repoName,regToken:await n.api.mintRegistrationToken(i,s.owner,s.repoName)}],labels:[cu(e.runnerId)]},c=Tt(e.runnerPublicKey,JSON.stringify(a));lc(e.runnerId,e.fingerprint),r.info(`[ghr] registration token for ${s.owner}/${s.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let l=await n.provisionOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:c});return{type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:l.ok,...l.runners?{runners:l.runners}:{},...l.error?{error:l.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}async function Jm(t,e,r,n=Ym){let o=i=>({type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repo:s}=await Vm(t,e,n),a={owner:s.owner,repo:s.repoName};try{a.removeToken=await n.api.mintRemoveToken(i,s.owner,s.repoName)}catch(p){r.warn(`[ghr] remove-token for ${s.owner}/${s.repoName} failed (${p instanceof Error?p.message:p}) \u2014 the runner host will force-remove`)}let c={projectId:t.projectId,runners:[a]},l=Tt(e.runnerPublicKey,JSON.stringify(c));lc(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle for ${s.owner}/${s.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let u=await n.teardownOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:l,owner:s.owner,repo:s.repoName});return{type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:u.ok,...u.error?{error:u.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}var qm,bx,Ym,Xm=v(()=>{"use strict";G();He();Hm();Re();ue();qm=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});bx={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:qm(t)});if(!n.ok)throw new Error(`github GET /repos/${e}/${r}: HTTP ${n.status}`);return(await n.json()).permissions?.admin===!0},mintRegistrationToken:(t,e,r)=>Wm(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Wm(t,e,r,"remove-token")},Ym={api:bx,fetchProject:ne,provisionOnRunner:Vd,teardownOnRunner:zd}});function $x(t){return Be.test(t)?Pt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Be}`}function Zm(t,e,r,n){let o=$x(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(zr(n,r).toString("utf-8"));if(typeof s.value!="string"||s.value.length===0)return{ok:!1,detail:"payload has no value"};i=s.value}catch(s){return{ok:!1,detail:`cannot open the sealed secret (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}if(i.length>Qm)return{ok:!1,detail:`secret value too large (max ${Qm} chars)`};try{return qu(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function eg(t,e){try{return Yu(t,e)?{ok:!0}:{ok:!0,detail:"no such secret (already absent)"}}catch(r){return{ok:!1,detail:r instanceof Error?r.message:String(r)}}}var Qm,tg=v(()=>{"use strict";G();He();ue();Qm=16*1024});function vx(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var Bi,rg=v(()=>{"use strict";Dt();Bi=class{constructor(e,r,n){this.intervalMs=e;this.send=r;this.log=n}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let n=[];for(let s of r.prs){let a=Ze(s.repoSpec);try{let c=await a.getPullRequest(s.repoSpec,s.number);n.push({number:s.number,url:s.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof cr){this.log.warn(`[track] task=${e} pr=${s.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${s.url} fetch failed: ${c instanceof Error?c.message:String(c)}`);return}}let o=n.map(s=>`${s.number}:${s.state}:${s.merged?1:0}:${s.ci}:${s.mergeable}`).join("|");if(this.lastSig.get(e)===o)return;for(let s=0;s<n.length;s++){let a=n[s];if(a.ci!=="failed")continue;let c=Ze(r.prs[s].repoSpec);if(c.getCiFailureLog)try{let l=await c.getCiFailureLog(r.prs[s].repoSpec,a.number);l&&(a.ciFailureLog=l)}catch(l){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${l instanceof Error?l.message:String(l)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:n}),this.lastSig.set(e,o);let i=vx(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}}});function ng(t){let{description:e,...r}=t;return r}function xx(t){let{body:e,...r}=t;return r}function Sx(t){let r=(t.split(/[\\/]/).pop()??t).replace(/[^A-Za-z0-9._-]/g,"_").replace(/^\.+/,"");return r.length>0?r.slice(0,120):"attachment"}async function og(t,e,r,n){try{return await t.getIssue(e,r)}catch(o){return n.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function ig(t,e,r,n){try{return await t.listComments(e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}var Fi,sg=v(()=>{"use strict";G();Oi();Di();Fi=class t{constructor(e,r,n,o={contextDir:null}){this.intervalMs=e;this.send=r;this.log=n;this.options=o}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;abandonedTicks=0;static MAX_ABANDONED_TICKS=3;setRequest(e){let r=this.request?.projectId;this.request=e,this.log.info(`[yt-sync] request updated: project=${e.projectKey} columns=[${e.sourceColumns.join(",")}] sinceMs=${e.sinceMs} offBoard=${e.offBoardIssueIds.length}`),this.timer||this.start(),r&&r!==e.projectId&&this.log.info(`[yt-sync] project switch ${r} \u2192 ${e.projectId}`)}start(){if(this.timer)return;this.log.info(`[yt-sync] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[yt-sync] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[yt-sync] poller stopped"))}async tickOnce(){await this.tick()}async forceSync(){if(!this.request){this.log.info("[yt-sync] force requested but no sync_request yet \u2014 ignored");return}this.log.info("[yt-sync] force sync requested (manual)"),await this.tick()}async tick(){if(this.running||!this.request)return;let r=(this.options.resolveProvider??(()=>kt({contextDir:this.options.contextDir})))();if(!r.ok){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn(`[yt-sync] tracker provider unavailable (${r.error}) \u2014 poller idle.`));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,r.provider)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let x=e.stageField?{stageField:e.stageField}:{},T=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},E=(e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(E){let b=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[I,N]=await Promise.all([b.length>0?r.listIssues({projectKey:e.projectKey,columns:b,...x,...T}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...x})]),F=new Map;for(let C of[...I,...N])F.set(C.id,C);o=[...F.values()]}else{let b=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:b,...x,...T})}}catch(x){this.log.warn(`[yt-sync] listIssues failed: ${x instanceof Error?x.message:String(x)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let x of o){if(s.add(x.id),a.has(x.status))continue;let T=await ig(r,x.id,e.sinceMs,this.log);T&&i.set(x.id,T)}let c=[];for(let x of e.offBoardIssueIds){if(s.has(x))continue;let T=await ig(r,x,e.sinceMs,this.log);if(T&&T.length>0&&i.set(x,T),e.requireAssignee||T&&T.length>0){let R=await og(r,x,e.stageField,this.log);if(R)c.push(R);else if(T&&T.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(x=>!a.has(x.status)),{attachmentsByIssue:u,attachmentKeys:p}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let d=[...l,...c].map(x=>({issue:x,comments:i.get(x.id)??[],attachments:u.get(x.id)??[]}));d.push(...await Tm(this.options.contextDir,d,x=>og(r,x,e.stageField,this.log)));try{await Ni(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let x of p)this.shippedAttachments.add(x)}catch(x){let T=x instanceof Error?x.message:String(x);this.abandonTick(`context task sync failed: ${T}`);return}let f=this.options.isSelfComment??(()=>!1),m=[],h=[];for(let[x,T]of i){let R=T.filter(b=>!f(b.id));if(R.length===0)continue;m.push({issueId:x,comments:R.map(xx)});let E=R.flatMap(b=>{let I=Or(b.body);return I?[{commentId:b.id,author:b.author,name:I.name,args:I.args,createdAt:b.createdAt}]:[]});E.length>0&&h.push({issueId:x,commands:E})}let g={type:"youtrack_observation",projectId:e.projectId,issues:o.map(ng),commentsBatch:m,...h.length>0?{commandsBatch:h}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(ng)}:{},observedAtMs:n};this.send(g);let w=m.reduce((x,T)=>x+T.comments.length,0),y=h.reduce((x,T)=>x+T.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${w} commands=${y} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let p=`${s.id}:${u.id}`;if(this.shippedAttachments.has(p))continue;let d;try{d=await n.downloadAttachment(u.url)}catch(m){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${m instanceof Error?m.message:String(m)}`);continue}let f=Sx(u.name);l.has(f)&&(f=`${u.id}-${f}`),l.add(f),c.push({name:f,contentBase64:d.toString("base64")}),i.push(p)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}}});import{existsSync as ag,readFileSync as Tx,readdirSync as Ex}from"node:fs";import{join as cg}from"node:path";import{simpleGit as Rx}from"simple-git";import{parse as Ix}from"yaml";function uc(t){let e=new Map,r=cg(t,Cs);if(!ag(r))return e;let n;try{n=Ix(Tx(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 Cx(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return Nr({modelFormatVersion:2,repos:e})}function lg(t,e){let r=cg(t,e);if(!ag(r))return[];let n=[];for(let o of Ex(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...lg(t,i)):n.push(i)}return n}async function Gi(t,e,r={}){let n=[],o=0;for(let d of e){n.push(...d.files);let f=`model/derived/structure/${d.repo}`;for(let m of lg(t,f))d.emittedShardPaths.has(m)||(n.push({path:m,content:"",deleted:!0}),o++)}let i=uc(t);for(let d of e)i.set(d.repo,{builtFromCommit:d.headCommit,counts:d.counts});n.push({path:Cs,content:Cx(i)});let s=Ri(t),a=gm(s,r.halfLifeDays??Je.halfLifeDays);n.push({path:Ar,content:Ii(a)});for(let d of e){let f=[];for(let m of s)for(let h of m.files)Q(h.key)?.repo===d.repo&&f.push({kind:"touched_by",from:ve(m.taskKey),to:h.key,...h.churn!==void 0?{weight:h.churn}:{}});n.push({path:Rl(d.repo),content:_r({modelFormatVersion:2,repo:d.repo,builtFromCommit:d.headCommit,edges:f})})}let c=Rx(t),l=(await c.revparse(["HEAD"]).catch(()=>"")).trim(),u=`model: build ${e.map(d=>`${d.repo}@${d.headCommit.slice(0,10)}`).join(", ")}`;await Ie(t,n,u);let p=(await c.revparse(["HEAD"]).catch(()=>"")).trim();if(p!==l){let{rebuildSearchIndex:d}=await Promise.resolve().then(()=>(ao(),so));await d(t).catch(()=>{})}return{committed:p!==l,filesWritten:n.filter(d=>!d.deleted).length,filesDeleted:o}}var ug=v(()=>{"use strict";G();za();rt()});var Hi={};Ir(Hi,{bootstrapDaemonModel:()=>Px,bootstrapModelForTargets:()=>yc,bootstrapWorkspaceModel:()=>gg,modelBootstrapCommand:()=>hc,modelBuildCommand:()=>gc,rebuildWorkspaceModelIfStale:()=>_x});import{existsSync as fc}from"node:fs";import{join as rn}from"node:path";import{cancel as Ax,intro as dg,log as dc,outro as pc}from"@clack/prompts";import{simpleGit as mc}from"simple-git";function Ki(t){Ax(t),process.exit(1)}function pg(t,e,r){let n=t.spec.repos.filter(i=>!e||i.name===e);if(n.length===0)throw new Error(e?`repo "${e}" is not part of this project (see project.yaml)`:"the project has no repos configured");let o=[];for(let i of n){let s=i.mountAs==="."?t.root:rn(t.root,i.mountAs);if(!fc(rn(s,".git"))){r(`${i.name}: no local clone at ${s} \u2014 skipped (run \`codepipe clone\` first)`);continue}o.push({name:i.name,dir:s,defaultBranch:i.defaultBranch||"main"})}if(o.length===0)throw new Error("nothing to do \u2014 no repo clones found");return o}async function fg(t){let e=mc(t.dir),r=`origin/${t.defaultBranch}`;return await e.raw(["rev-parse","--verify",r]).then(()=>!0).catch(()=>!1)?r:"HEAD"}async function mg(t,e,r,n){let o=[];for(let i of e)try{let s=await qa({repo:i.name,repoDir:i.dir,contextDir:t,settings:r,ref:await fg(i)});o.push(s),n(`${i.name}: ${s.counts.code} files, ${s.counts.component} components, ${s.counts.correlates} co-change edges @ ${s.headCommit.slice(0,10)}`)}catch(s){throw new Error(`${i.name}: ${s instanceof Error?s.message:String(s)}`)}return o}async function gc(t){dg("codepipe model build");let e=Se();e||Ki("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{let r=Qr(e.contextDir),n=pg(e,t.repo,s=>dc.warn(s)),o=await mg(e.contextDir,n,r,s=>dc.info(s)),i=await Gi(e.contextDir,o,{halfLifeDays:r.cochange.halfLifeDays});i.committed?pc(`model updated: ${i.filesWritten} files written, ${i.filesDeleted} stale removed`):pc("model already up to date (no changes)")}catch(r){Ki(r instanceof Error?r.message:String(r))}}async function hc(t){dg("codepipe model bootstrap");let e=Se();e||Ki("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{await gg(e,t.repo,{onLog:r=>dc.info(r)})}catch(r){Ki(r instanceof Error?r.message:String(r))}pc("bootstrap complete")}async function gg(t,e,r){let n=pg(t,e,r.onLog);return yc(t.contextDir,n,r)}async function yc(t,e,r){let n=Qr(t),o=await mg(t,e,n,r.onLog),i=Uf(t),s=Mf(n.issueKeyPattern,i),a=br([...n.ignore,...Xr]),c=[];for(let p of o){let d=e.find(m=>m.name===p.repo),f=await Ff({repo:p.repo,repoDir:d.dir,headCommit:p.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:s,pathToCurrent:Si(p.identityTable),entityByKey:p.entityByKey,ignored:a,trackerProjectKey:i});c.push(f),r.onLog(`${p.repo}: ${f.size} task events mined from history`)}let{files:l,skippedPipeline:u}=Gf(t,c);return u>0&&r.onLog(`${u} events already recorded by the live pipeline \u2014 left untouched`),l.length>0&&await Ie(t,l,`model: bootstrap ${l.length} task events from history`),await Gi(t,o,{halfLifeDays:n.cochange.halfLifeDays}),{events:l.length}}async function Px(t,e,r,n){if(r.length===0)throw new Error("the project has no repos configured");let o=[];for(let s of r){let a=s.mountAs??s.name,c=a==="."?e.root:rn(e.root,a),l=s.defaultBranch||"main";c!==e.contextDir&&fc(rn(c,".git"))?(await mc(c).fetch(["origin",l]).catch(()=>{}),o.push({name:s.name,dir:c,defaultBranch:l})):(n(`${s.name}: materializing clone in the daemon layout`),await xt(t,s),o.push({name:s.name,dir:Te(t,s.name),defaultBranch:l}))}let i=await yc(e.contextDir,o,{onLog:n});return{repos:o.length,events:i.events}}async function _x(t,e={}){let r=e.onLog??(()=>{}),n=Qr(t.contextDir);if(!n.enabled)return{rebuilt:[],skipped:[]};let o=[],i=[],s=uc(t.contextDir),a=[];for(let c of t.repos){let l=c.mountAs==="."?t.root:rn(t.root,c.mountAs);if(!fc(rn(l,".git")))continue;let u=mc(l),p=c.defaultBranch||"main";e.fetch&&await u.fetch(["origin",p]).catch(()=>{});let d=await fg({name:c.name,dir:l,defaultBranch:p}),f=(await u.revparse([d]).catch(()=>"")).trim();if(f){if(s.get(c.name)?.builtFromCommit===f){i.push(c.name);continue}try{a.push(await qa({repo:c.name,repoDir:l,contextDir:t.contextDir,settings:n,ref:f})),o.push(c.name)}catch(m){r(`[model] rebuild of ${c.name} failed: ${m instanceof Error?m.message:String(m)}`)}}}return a.length>0&&(await Gi(t.contextDir,a,{halfLifeDays:n.cochange.halfLifeDays}),r(`[model] release-path rebuild: ${o.join(", ")} (skipped up-to-date: ${i.join(", ")||"\u2014"})`)),{rebuilt:o,skipped:i}}var po=v(()=>{"use strict";rt();ug();Ya();Ha();Ti();io();mr();mt()});var yg={};Ir(yg,{computeDriftReport:()=>Lx,supersededAdrIds:()=>hg});import{existsSync as kc,readFileSync as wc,readdirSync as bc}from"node:fs";import{join as nn}from"node:path";import{parse as jx}from"yaml";import{simpleGit as Nx}from"simple-git";function Dx(t,e){let r=nn(t,`model/derived/structure/${e}`),n=[],o="";if(!kc(r))return{nodes:n,builtFromCommit:o};for(let i of bc(r).sort()){if(!i.endsWith(".yaml"))continue;let s;try{let a=Ct(jx(wc(nn(r,i),"utf-8")));if(!a.ok)continue;s=a.value}catch{continue}o=s.builtFromCommit;for(let a of s.nodes){let c=Q(a.key);!c||c.level!=="code"&&c.level!=="component"||n.push({key:a.key,path:c.path,level:c.level,contentHash:a.contentHash,entityId:a.entityId})}}return{nodes:n,builtFromCommit:o}}function hg(t){let e=new Set,r=nn(t,"adr");if(!kc(r))return e;for(let n of bc(r).sort()){let o=/^(\d{4})-/.exec(n)?.[1];if(!(!o||!n.endsWith(".md")))try{let i=wc(nn(r,n),"utf-8").slice(0,600).toLowerCase();/status[^\n]*superseded/.test(i)&&e.add(`ADR-${o}`)}catch{}}return e}async function Lx(t,e,r){let{nodes:n,builtFromCommit:o}=Dx(e,r),i=(await Nx(t).revparse(["HEAD"])).trim(),s=await oo(t,i),a=new Map(s.map(y=>[y.path,y.blobHash])),c=[],l=[],u=new Set,p=[];for(let y of n){if(y.level==="component"){p.push(y);continue}u.add(y.path);let x=a.get(y.path);x?y.contentHash&&x.slice(0,Ox)!==y.contentHash&&c.push(y.key):l.push(y.key)}let d=0,f=new Map,m=new Set;for(let y of s){let x=y.path.lastIndexOf("/"),T=x<0?"":y.path.slice(0,x);f.has(T)||f.set(T,new Set),f.get(T).add(y.path),u.has(y.path)||d++;let R=T;for(;R!==""&&!m.has(R);)m.add(R),R=R.includes("/")?R.slice(0,R.lastIndexOf("/")):""}let h=new Map;for(let y of u){let x=y.lastIndexOf("/"),T=x<0?"":y.slice(0,x);h.has(T)||h.set(T,new Set),h.get(T).add(y)}for(let y of p){if(!m.has(y.path)){l.push(y.key);continue}let x=h.get(y.path)??new Set,T=f.get(y.path)??new Set;(x.size!==T.size||[...x].some(E=>!T.has(E)))&&c.push(y.key)}let g=[],w=hg(e);if(w.size>0){let y=nn(e,"model/facts/annotations"),x=new Map(n.filter(T=>T.entityId).map(T=>[T.entityId,T.key]));if(kc(y))for(let T of bc(y).sort()){if(!T.endsWith(".md"))continue;let R=T.replace(/\.md$/,""),E=x.get(R);if(E)try{(wc(nn(y,T),"utf-8").match(/\bADR-(\d{3,4})\b/g)??[]).map(N=>`ADR-${N.slice(4).padStart(4,"0")}`).some(N=>w.has(N))&&g.push(E)}catch{}}}return{repo:r,builtFromCommit:o,headCommit:i,stale:[...new Set(c)].sort(),orphaned:[...new Set(l)].sort(),superseded:[...new Set(g)].sort(),newFiles:d}}var Ox,kg=v(()=>{"use strict";G();io();Ox=12});import{existsSync as bg,rmSync as Mx}from"node:fs";import{join as $r}from"node:path";import{simpleGit as Ux}from"simple-git";import"ws";function Wi(t,e={}){let r=e.log??{info:g=>console.log(g),warn:g=>console.warn(g)};r.info(`codepipe-cli v${Ue} (protocol ${lt})`);let n=g=>e.onEvent?.(g),o=e.workspace;o?.contextDir&&Pp(o.contextDir,r);let i=wg("CLI_TRACKING_POLL_INTERVAL_SEC"),s=wg("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let g=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(g)&&g>0?g*1e3:6e5})(),c=!1,l=!1,u=!1,p=new Set,d=!1,f=new Set,m=h();function h(){let g=ri(t.hubUrl,t.cliToken),w=null,y=new Bi(i,_=>{g.readyState===g.OPEN&&g.send(JSON.stringify(_))},r),x=new Fi(s,_=>{g.readyState===g.OPEN&&g.send(JSON.stringify(_))},r,{contextDir:o?.contextDir??null,isSelfComment:_=>f.has(_)}),T=null,R=async()=>{try{let _={trackerProvider:oc(o?.contextDir??null)};try{let O=await ne(t.hubUrl,t.cliToken,t.projectId);_={..._,repos:O.repos,contextRepo:O.contextRepo}}catch(O){r.warn(`[readiness] could not fetch project summary for push checks: ${O instanceof Error?O.message:String(O)}`)}let M=await Ld(t.projectId,_);if(g.readyState!==g.OPEN)return;let L={type:"cli_readiness",projectId:t.projectId,ready:M.ready,checks:M.checks,creds:M.creds,secretNames:Vu(t.projectId),checkedAt:M.checkedAt};if(g.send(JSON.stringify(L)),M.ready)r.info("[readiness] ready");else{let O=M.checks.filter(S=>!S.ok).map(S=>`${S.name}(${S.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${O.join(", ")}`)}let z=Hd(M.creds,u);if(z==="open"){u=!0;let O=Wd(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${O}`),ur(O)}else z==="rearm"&&(u=!1)}catch(_){r.warn(`[readiness] check failed: ${_ instanceof Error?_.message:String(_)}`)}},E=()=>{R(),T=setInterval(()=>void R(),a),typeof T.unref=="function"&&T.unref()},b=()=>{T&&(clearInterval(T),T=null)},I=150,N=new Map,F=_=>{let M=N.get(_);if(!M||(M.timer&&clearTimeout(M.timer),N.delete(_),M.events.length===0||g.readyState!==g.OPEN))return;let L={type:"run_activity",projectId:t.projectId,runId:_,events:M.events};g.send(JSON.stringify(L))},C=(_,M)=>{let L=N.get(_);if(L||(L={events:[],timer:null},N.set(_,L)),L.events.push(M),M.kind==="result"){F(_);return}L.timer||(L.timer=setTimeout(()=>F(_),I),L.timer.unref?.())},k=o?.contextDir?new di(o.contextDir,t.projectId,_=>{g.readyState===g.OPEN&&g.send(JSON.stringify(_))},r):null,D=async()=>{let _=o?.contextDir;if(!_)throw new Error("no context repo clone on this CLI");let M;try{M=(await ne(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let L=await tf(_,t.projectId,M,r);return g.readyState===g.OPEN&&g.send(JSON.stringify(L)),L},A=null,H=async()=>{let _=o?.contextDir;if(_)try{let{readContextIndexHub:M,collectSearchRows:L}=await Promise.resolve().then(()=>(ao(),so));if(M(_)!=="metadata")return;let z=L(_);g.readyState===g.OPEN&&(g.send(JSON.stringify({type:"model_index",projectId:t.projectId,rows:z})),r.info(`[model] tier-2 index snapshot pushed (${z.length} rows)`))}catch(M){r.warn(`[model] tier-2 index push failed (non-fatal): ${M instanceof Error?M.message:String(M)}`)}},q=()=>{A&&clearTimeout(A),A=setTimeout(()=>void H(),5e3)},Z=null,qe=async _=>{if(o?.contextDir)try{let{rebuildWorkspaceModelIfStale:M}=await Promise.resolve().then(()=>(po(),Hi));(await M({root:o.root,contextDir:o.contextDir,repos:o.repos},{fetch:_,onLog:z=>r.info(z)})).rebuilt.length>0&&q()}catch(M){r.warn(`[model] release-path rebuild failed (non-fatal): ${M instanceof Error?M.message:String(M)}`)}},Ye=_=>{Z&&clearTimeout(Z),Z=setTimeout(()=>void qe(_),6e4)},ge=setInterval(()=>void qe(!0),6*36e5);return g.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let _=rd(t.projectId),M=V("ORIGIN")==="farm"?"farm":"local",L=V("FARM_ID"),z=t.accountEmail??_.email,O;try{let $=mf(t.projectId);$&&(O=$.publicKey,r.info(`[cred-channel] key fingerprint: ${$.fingerprint}`))}catch($){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${$ instanceof Error?$.message:String($)}`)}let S={type:"register",projectId:t.projectId,platformVersion:Ue,protocolVersion:lt,accountId:_.accountId,accountLabel:_.label,origin:M,inFlightActionIds:[...p],...z?{accountEmail:z}:{},...M==="farm"&&L?{farmId:L}:{},...O?{sealPublicKey:O}:{}};g.send(JSON.stringify(S))}),g.on("message",async _=>{let M=_.toString("utf-8");if(M==="pong"||M==="ping")return;let L;try{L=JSON.parse(M)}catch{return}if(!L||typeof L!="object")return;let z=L.type;if(z==="registered"){let S=L;if(S.ok){if(r.info(`[ws] registered for project ${S.projectId}`),n({kind:"registered",projectId:S.projectId??t.projectId}),y.start(),k?.start(),E(),vc(t,o,r),o?.contextDir){try{let $=hi(o.contextDir,t.projectId);g.readyState===g.OPEN&&g.send(JSON.stringify($)),$.outdated&&(r.warn(`[ctx] context format outdated: v${$.templateVersion} \u2192 v${$.currentVersion}`+($.missingPaths.length>0?` (missing: ${$.missingPaths.join(", ")})`:"")),l||(l=!0,D().catch(()=>{})))}catch($){r.warn(`[ctx] context-format detect failed (non-fatal): ${$ instanceof Error?$.message:String($)}`)}H(),Ye(!0)}}else r.warn(`[ws] register rejected: ${S.reason??"unknown"}`),n({kind:"register_rejected",reason:S.reason??"unknown"}),c=!0,g.close();return}if(z==="hello"){let S=L;w=Ao(S.protocolVersion);let $=w?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${S.platformVersion} (protocol ${S.protocolVersion}) \u2014 ${$}`),w||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Ue}, protocol ${lt}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${$c}`),n({kind:"incompatible",hubVersion:typeof S.platformVersion=="string"?S.platformVersion:null,hubProtocol:typeof S.protocolVersion=="number"?S.protocolVersion:null,updateCommand:$c}));return}if(z==="tracking_targets"){y.setTargets(L.targets);return}if(z==="youtrack_sync_request"){x.setRequest(L);return}if(z==="youtrack_force_sync"){x.forceSync();return}if(z==="sync_local"){await Gx(L,o,g,r);return}if(z==="provision_repo"){let S=L;r.info(`[repo] provision_repo: ${S.repo.name} (${S.repo.host}:${S.repo.owner}/${S.repo.repoName})`),await Bx(t,o,S.repo,r),await vc(t,o,r);return}if(z==="remove_repo"){let S=L;r.info(`[repo] remove_repo: ${S.repoName}${S.purge?" (purge)":""}`),await vc(t,o,r),S.purge&&Fx(t,o,S.repoName,r);return}if(z==="context_write"){await Kx(L,o,g,r);return}if(z==="adr_promote"){await Hx(L,o,g,r);return}if(z==="cred_update"){let S=L,$=W(t.projectId),j=$?.sealKey?await gf(t.projectId,S.kind,S.sealed,$.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},Y={type:"cred_update_result",updateId:S.updateId,projectId:t.projectId,ok:j.ok,...j.detail?{detail:j.detail}:{}};g.readyState===g.OPEN&&g.send(JSON.stringify(Y)),j.ok?(r.info(`[cred] ${S.kind} replaced${j.detail?` \u2014 ${j.detail}`:""}`),R()):r.warn(`[cred] ${S.kind} replacement rejected: ${j.detail??"unknown"}`);return}if(z==="readiness_check"){r.info("[readiness] on-demand check requested"),R();return}if(z==="agent_login_start"){Gd(t,g,L,r,R);return}if(z==="move_to_farm"){let S=L;r.info(`[farm-move] request to move ${t.projectId} onto farm ${S.farmName} (${S.farmId})`);let $=await Bm(t,S,o?.contextDir,r);g.readyState===g.OPEN&&g.send(JSON.stringify($)),$.ok?r.info(`[farm-move] done \u2014 farm daemon ${$.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${$.error??"unknown error"}`);return}if(z==="gh_runner_setup"){let S=L;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${S.runnerName} (${S.runnerId})`);let $=await zm(t,S,r);g.readyState===g.OPEN&&g.send(JSON.stringify($)),$.ok?r.info(`[ghr] runners connected on ${S.runnerName}`):r.warn(`[ghr] setup failed: ${$.error??"see per-repo statuses"}`);return}if(z==="gh_runner_teardown"){let S=L;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${S.runnerName} (${S.runnerId})`);let $=await Jm(t,S,r);g.readyState===g.OPEN&&g.send(JSON.stringify($)),$.ok?r.info(`[ghr] runners disconnected from ${S.runnerName}`):r.warn(`[ghr] teardown failed: ${$.error??"unknown error"}`);return}if(z==="tracker_fields_request"){let S=L,$={type:"tracker_fields_result",requestId:S.requestId,projectId:t.projectId,ok:!1},j=kt({contextDir:o?.contextDir??null});if(!j.ok)$.error=j.error;else try{$.fields=await j.provider.fetchStateFields(S.projectKey),$.ok=!0}catch(Y){$.error=Y instanceof Error?Y.message:String(Y)}g.readyState===g.OPEN&&g.send(JSON.stringify($)),$.ok||r.warn(`[yt-fields] listing failed: ${$.error??"unknown"}`);return}if(z==="project_secret_update"||z==="project_secret_delete"){let S=L,$;if(S.type==="project_secret_update"){let Y=W(t.projectId);$=Y?.sealKey?Zm(t.projectId,S.name,S.sealed,Y.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else $=eg(t.projectId,S.name);let j={type:"project_secret_update_result",updateId:S.updateId,projectId:t.projectId,ok:$.ok,...$.detail?{detail:$.detail}:{}};g.readyState===g.OPEN&&g.send(JSON.stringify(j)),$.ok?(r.info(`[secret] ${S.name} ${S.type==="project_secret_update"?"saved":"deleted"}`+($.detail?` \u2014 ${$.detail}`:"")),R()):r.warn(`[secret] ${S.name} rejected: ${$.detail??"unknown"}`);return}if(z==="auto_apply_local"){let S=L;if(!o?.contextDir){r.warn(`[apply] auto_apply_local for ${S.claim.taskKey} \u2014 no workspace (headless), skipped; task stays in READY_TO_APPLY`);return}let $=await bp({hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId,root:o.root,contextDir:o.contextDir,repos:o.repos},S.claim,r).catch(j=>({ok:!1,message:j instanceof Error?j.message:String(j)}));$.ok?r.info(`[apply] ${S.claim.taskKey}: ${$.message}`):r.warn(`[apply] ${S.claim.taskKey}: ${$.message} \u2014 task stays in READY_TO_APPLY`),n({kind:"local_applied",taskKey:S.claim.taskKey,ok:$.ok,...$.ok?{branches:$.branches??[]}:{error:$.message}});return}if(z==="sandbox_keys"){let S=W(t.projectId);if(!S){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let $=Ur(t.projectId),j=lf(L,S,$,r);for(let Y of j)g.readyState===g.OPEN&&g.send(JSON.stringify(Y));return}if(z!=="dispatch_action")return;let O=L;if(w===!1){let S=`refused: HUB protocol incompatible with CLI v${Ue} (protocol ${lt})`;g.send(JSON.stringify({type:"action_result",actionId:O.actionId,status:"failed",error:S})),r.warn(`[exec] ${O.actionId} (${O.action.type}) \u2192 REFUSED: ${S}`),r.warn(`[exec] update the CLI to clear this: ${$c}`),n({kind:"action",actionId:O.actionId,actionType:O.action.type,ok:!1,error:S});return}if(O.action.type==="model_drift"){p.add(O.actionId);try{let S,$=o?.repos.find(j=>j.name===O.action.repoName);if(!o?.contextDir||!$)S={status:"failed",error:"no local workspace/repo clone on this CLI"};else try{let{computeDriftReport:j}=await Promise.resolve().then(()=>(kg(),yg)),Y=$.mountAs==="."?o.root:$r(o.root,$.mountAs);S={status:"done",result:{report:await j(Y,o.contextDir,$.name)}}}catch(j){S={status:"failed",error:j instanceof Error?j.message:String(j)}}g.send(JSON.stringify({type:"action_result",actionId:O.actionId,...S}))}finally{p.delete(O.actionId)}return}if(O.action.type==="model_bootstrap"){p.add(O.actionId);try{let S;if(!o?.contextDir)S={status:"failed",error:"no Context Repo clone on this CLI"};else if(d)S={status:"failed",error:"model bootstrap is already running"};else{d=!0;try{let $=await ne(t.hubUrl,t.cliToken,t.projectId),{bootstrapDaemonModel:j}=await Promise.resolve().then(()=>(po(),Hi)),Y=await j(t.projectId,{root:o.root,contextDir:o.contextDir},$.repos,ke=>r.info(`[model] ${ke}`));r.info(`[model] bootstrap done: ${Y.repos} repos, ${Y.events} task events`),q(),S={status:"done",result:{repos:Y.repos,events:Y.events}}}catch($){S={status:"failed",error:$ instanceof Error?$.message:String($)},r.warn(`[model] bootstrap failed: ${S.error}`)}finally{d=!1}}g.readyState===g.OPEN&&g.send(JSON.stringify({type:"action_result",actionId:O.actionId,...S}))}finally{p.delete(O.actionId)}return}if(O.action.type==="local_apply"){p.add(O.actionId);try{let S;if(!o)S={status:"failed",error:"no local workspace on this CLI"};else{let j=await Nm(o,O.action.repos,r);if(S=j.ok?{status:"done",result:{repos:j.repos}}:{status:"failed",error:j.error},j.ok&&o.contextDir){let Y=O.action.taskId.split(":")[1]??"";for(let ke of Y?j.repos:[]){let X=o.repos.find(te=>te.name===ke.repoName);if(!X)continue;let{recordPipelineEvent:we}=await Promise.resolve().then(()=>(ec(),Sm));await we({contextDir:o.contextDir,repoDir:$r(o.root,X.mountAs),repoName:ke.repoName,taskKey:Y,commitSha:ke.commit}).catch(te=>r.warn(`[model] task event for ${Y} failed: ${te instanceof Error?te.message:String(te)}`))}q()}}g.send(JSON.stringify({type:"action_result",actionId:O.actionId,...S}));let $=S.status!=="failed";$?r.info(`[exec] ${O.actionId} (local_apply) \u2192 done`):r.warn(`[exec] ${O.actionId} (local_apply) \u2192 FAILED: ${S.status==="failed"?S.error:"?"}`),n({kind:"action",actionId:O.actionId,actionType:"local_apply",ok:$,...S.status==="failed"?{error:S.error}:{}})}finally{p.delete(O.actionId)}return}p.add(O.actionId);try{let S=await Pm({action:O.action,repo:O.repo,trackerIssueId:O.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:k?()=>k.reportNow():void 0,refreshContextStatus:o?.contextDir?D:void 0,onRunActivity:C}).catch(Y=>({status:"failed",error:Y instanceof Error?Y.message:String(Y)}));O.action.type==="tracker_comment"&&S.status==="done"&&"result"in S&&typeof S.result?.commentId=="string"&&f.add(S.result.commentId),g.send(JSON.stringify({type:"action_result",actionId:O.actionId,...S}));let $=S.status!=="failed",j=!$&&"error"in S?S.error:void 0;$?r.info(`[exec] ${O.actionId} (${O.action.type}) \u2192 done`):r.warn(`[exec] ${O.actionId} (${O.action.type}) \u2192 FAILED: ${j??"?"}`),n({kind:"action",actionId:O.actionId,actionType:O.action.type,ok:$,...j?{error:j}:{}}),$&&["apply_delivery","context_write","create_pr"].includes(O.action.type)&&q(),$&&["merge_pr","merge_branch"].includes(O.action.type)&&Ye(!0)}finally{p.delete(O.actionId)}}),g.on("close",(_,M)=>{let L=M?.toString("utf-8")??"";if(r.info(`[ws] closed code=${_}${L?` reason=${L}`:""}`),y.stop(),x.stop(),k?.stop(),b(),clearInterval(ge),Z&&clearTimeout(Z),A&&clearTimeout(A),L==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:_}),!c&&setTimeout(()=>{m=h()},2e3)}),g.on("error",_=>r.warn(`[ws] error: ${_.message}`)),g}return{stop(){c=!0,m.close()}}}async function vc(t,e,r){try{let n=await ne(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=eo(t.projectId,n.repos,e?.contextDir);for(let s of o)r.info(`[repo] restaged repo set in ${s}`);for(let s of i)r.warn(`[repo] could not restage ${s.path}: ${s.error}`)}catch(n){r.warn(`[repo] repo-set reconcile skipped: ${n instanceof Error?n.message:String(n)}`)}}async function Bx(t,e,r,n){let o=r.mountAs??r.name;if(o==="."){n.info(`[repo] ${r.name} mounts in place (mount_as: .) \u2014 nothing to clone`);return}let i=e?$r(e.root,o):Te(t.projectId,r.name);if(bg($r(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await Ux().clone(Vn(r),i),n.info(`[repo] cloned ${r.name} \u2192 ${i}`)}catch(s){n.warn(`[repo] clone of ${r.name} failed (will retry lazily): ${s instanceof Error?s.message.trim():String(s)}`)}}function Fx(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?$r(e.root,o):Te(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!bg($r(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{Mx(i,{recursive:!0,force:!0}),n.info(`[repo] purged local clone ${i}`)}catch(s){n.warn(`[repo] purge of ${i} failed: ${s instanceof Error?s.message:String(s)}`)}}async function Gx(t,e,r,n){if(!e){n.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let o of t.repos){let i=e.repos.find(l=>l.name===o.repoName),s=$r(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await vp(s,a).catch(l=>({status:"warn",reason:l instanceof Error?l.message:String(l)}));c.status==="updated"?n.info(`[sync] ${o.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?n.info(`[sync] ${o.repoName}: not cloned in workspace \u2014 skipped`):(n.warn(`[sync] ${o.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:o.repoName,reason:c.reason??"sync skipped"})))}}async function Kx(t,e,r,n){let o=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{await Ie(e.contextDir,t.files,t.message),n.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[ctx] context_write ${t.id} failed: ${s}`),o("failed",s)}}async function Hx(t,e,r,n){let o=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[adr] adr_promote ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{let i=t.source??"task",s=await Mp(e.contextDir,t.taskKey,t.slugs,void 0,i);if(n.info(`[adr] adr_promote ${t.id}: promoted ${s.promoted.length}, skipped ${s.skipped.length}`+(s.promoted.length>0?` (${s.promoted.join(", ")})`:"")),s.missing.length>0){let a=l=>i==="staging"?`adr/DRAFT-${l}.md`:`tasks/${t.taskKey}/adr/DRAFT-${l}.md`,c=`draft file(s) missing in clone: ${s.missing.map(a).join(", ")}`;n.warn(`[adr] adr_promote ${t.id}: ${c}`),o("failed",c);return}o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[adr] adr_promote ${t.id} failed: ${s}`),o("failed",s)}}function wg(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}var $c,xc=v(()=>{"use strict";_e();G();nd();Kd();qd();ti();ma();xp();Cp();Up();rt();St();Ea();rf();Pa();mr();uf();hf();_m();Om();Fm();Xm();Re();tg();Kr();ue();rg();sg();Di();$c="npm i -g @code-partner/codepipe@latest"});import{execFileSync as Wx}from"node:child_process";import{mkdtempSync as qx,mkdirSync as Yx,readFileSync as $g,rmSync as Vx,writeFileSync as zx}from"node:fs";import{tmpdir as Jx}from"node:os";import{dirname as Xx,join as vg}from"node:path";function xg(t="codepipe-context"){let e=qx(vg(Jx(),"codepipe-ssh-")),r=vg(e,"id_ed25519");try{return Wx("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:$g(r,"utf-8"),publicKey:$g(`${r}.pub`,"utf-8").trim()}}finally{Vx(e,{recursive:!0,force:!0})}}async function Sg(t,e,r,n="codepipe-context"){let o=await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/keys`,{method:"POST",headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({title:n,key:r,read_only:!1})});if(o.ok)return;let i=await o.text();if(!(o.status===422&&/already in use/i.test(i)))throw new Error(`add deploy key failed: ${o.status} ${i}`)}function Tg(t){if(/^git@[^:]+:.+/.test(t))return t;let e=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(e)return`git@${e[1]}:${e[2]}`;let r=t.match(/^https:\/\/(?:[^@/]+@)?([^/]+)\/(.+)$/);return r?`git@${r[1]}:${r[2]}`:t}function Eg(t,e){Yx(Xx(t),{recursive:!0});let r=e.endsWith(`
|
|
648
648
|
`)?e:e+`
|
|
649
|
-
`;return
|
|
650
|
-
`,{mode:384})}var
|
|
651
|
-
`}async function
|
|
649
|
+
`;return zx(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var Sc=v(()=>{"use strict"});import{existsSync as Rg,mkdirSync as Ig}from"node:fs";import{dirname as Cg}from"node:path";import{simpleGit as on}from"simple-git";function Qx(t,e,r="x-access-token"){let n=`${encodeURIComponent(r)}:${encodeURIComponent(e)}`,o=t.match(/^git@([^:]+):(.+)$/);if(o)return`https://${n}@${o[1]}/${o[2]}`;let i=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(i)return`https://${n}@${i[1]}/${i[2]}`;let s=t.match(/^https:\/\/(?:[^@/]+@)?(.+)$/);return s?`https://${n}@${s[1]}`:t}function Zx(t,e){return e?.contextWrite?.token?{user:Bo(t),secret:e.contextWrite.token}:t===Fn.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Fn.bitbucket?e?.bitbucket?.apiToken?{user:sr,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function Ag(t,e){let r=e.sleep??(i=>new Promise(s=>setTimeout(s,i))),n=e.initialDelayMs??5e3,o=e.maxDelayMs??6e4;for(;;)try{return await t()}catch(i){if(!(i instanceof qi))throw i;e.log.warn(`[ctx] ${i.message} \u2014 retrying in ${Math.round(n/1e3)}s (the HUB may be deploying)`),await r(n),n=Math.min(n*2,o)}}async function Yi(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await ne(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new qi(c)}let s=i.contextRepo;if(!s)return o.warn("[ctx] project has no Context Repo on HUB \u2014 daemon stays headless (no config report)"),null;let a=Zx(Lr(s.cloneUrl),r);if(a){let c=await eS({ctx:s,contextDir:n,cred:a,log:o});if(c)return c;o.warn("[ctx] token clone/update failed")}if(r?.contextSsh?.privateKey){let c=await tS({ctx:s,contextDir:n,privateKey:r.contextSsh.privateKey,log:o});if(c)return c;o.warn("[ctx] SSH deploy-key clone failed")}return o.warn("[ctx] no usable context-host/contextWrite token or SSH deploy key \u2014 can't clone the Context Repo on the farm; config_observation + artifact commits disabled."),null}async function eS(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=Qx(e.cloneUrl,n.secret,n.user),s=e.branch,a=encodeURIComponent(n.secret),c=l=>l.split(n.secret).join("***").split(a).join("***");try{if(Rg(`${r}/.git`)){let l=on(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=wa(r);await l.reset(["--hard",`origin/${s}`]),ba(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Ig(Cg(r),{recursive:!0}),await on().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await Pg(r)}catch(l){return o.warn(`[ctx] Context Repo clone/update failed: ${c(l instanceof Error?l.message:String(l))}`),null}return{root:r,contextDir:r,repos:[]}}async function tS(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=Eg(i,n),a=Tg(e.cloneUrl),c=e.branch;try{if(Rg(`${r}/.git`)){let l=on(r);await l.addConfig("core.sshCommand",s,!1,"local"),await l.remote(["set-url","origin",a]),await l.fetch("origin",c),await l.checkout(c);let u=wa(r);await l.reset(["--hard",`origin/${c}`]),ba(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Ig(Cg(r),{recursive:!0}),await on().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await on(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await Pg(r),{root:r,contextDir:r,repos:[]}}catch(l){return o.warn(`[ctx] Context Repo ssh clone/update failed: ${l instanceof Error?l.message:String(l)}`),null}}async function Pg(t){let e=on(t);await e.raw(["config","user.email"]).then(n=>n.trim()).catch(()=>"")||(await e.addConfig("user.email","farm@codepipe.local",!1,"local"),await e.addConfig("user.name","CodePipe Farm CLI",!1,"local"))}var qi,Tc=v(()=>{"use strict";G();Re();St();Sc();qi=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as rS}from"node:child_process";function nS(){try{return rS("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function jg(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:nS(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var Ng=v(()=>{"use strict"});import{homedir as sn}from"node:os";import{mkdirSync as oS,readFileSync as Og,writeFileSync as iS,existsSync as Rc}from"node:fs";import{dirname as sS,join as Kt}from"node:path";function aS(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function ot(t){let e=V("SANDBOX_CONFIG");if(e)return e;let r=Kt(sn(),".codepipe","worker");return t?Kt(r,"profiles",t,"config.json"):Kt(r,"config.json")}function Dg(){return Kt(sn(),".devpipe-sandbox","config.json")}function Vi(){ar(Kt(sn(),".devpipe"),Kt(sn(),".codepipe")),V("SANDBOX_CONFIG")||ar(Kt(sn(),".devpipe-sandbox"),Kt(sn(),".codepipe-sandbox"))}function Lg(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function Ae(t){let e=ot(t),r=null;return Rc(e)?r=JSON.parse(Og(e,"utf-8")):!t&&!V("SANDBOX_CONFIG")&&Rc(Dg())&&(r=JSON.parse(Og(Dg(),"utf-8"))),r?(r.planningLane=aS(),r):null}function Mg(t,e){let r=ot(e);oS(sS(r),{recursive:!0}),iS(r,JSON.stringify(t,null,2)+`
|
|
650
|
+
`,{mode:384})}var zi=v(()=>{"use strict";_e();Fo();Rc(".env")&&process.loadEnvFile(".env")});import cS from"ws";var an,Ic=v(()=>{"use strict";an=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};e&&(n.signal=e);let o=r?`${this.hubUrl}/jobs/claim?lane=${encodeURIComponent(r)}`:`${this.hubUrl}/jobs/claim`;return fetch(o,n)}async submitResult(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/jobs/result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});if(!r.ok)throw new Error(`submitResult failed: ${r.status} ${await r.text()}`)}async heartbeat(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e})};r&&(n.signal=r);let o=await fetch(`${this.hubUrl}/jobs/heartbeat`,n);if(o.status===410)return"claim_lost";if(!o.ok)throw new Error(`heartbeat failed: ${o.status} ${await o.text()}`);return"ok"}async releaseJob(e,r,n){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e,reason:r})};n&&(o.signal=n);let i=await fetch(`${this.hubUrl}/jobs/release`,o);if(!i.ok&&i.status!==409&&i.status!==404)throw new Error(`release failed: ${i.status} ${await i.text()}`)}openControlSocket(){if(!this.token)throw new Error("no sandbox token");let e=this.hubUrl.replace(/^http/,"ws")+`/sandbox/connect?token=${encodeURIComponent(this.token)}`;return new cS(e)}}});import{hostname as lS}from"node:os";async function vr(t){Vi();let e=Ae(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${ot(t.profile)}.`),process.exit(1));let r=t.name??lS(),n=jg({projects:t.projects??[],llm:t.llm??null}),o=new an(t.hub.replace(/\/$/,"")),i=wi(),s=je(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});Mg({hubUrl:t.hub.replace(/\/$/,""),sandboxId:a,token:c,name:r,llm:t.llm??null,sealPublicKey:i.publicKey,sealPrivateKey:i.privateKey},t.profile),console.log(`registered as ${a} (${r}) at ${t.hub}`),console.log(`config saved to ${ot(t.profile)}`),console.log(""),console.log(" cred-channel key fingerprint (confirm this on the CLI \u2014 pin-on-register):"),console.log(` ${s}`),console.log("")}var Ug=v(()=>{"use strict";He();Ng();zi();Ic()});function Bg(t){return t?`Write ALL user-visible text \u2014 full replies and the brief status notes you emit between tool calls alike \u2014 in ${t}, regardless of the language the user writes in (the project pinned ${t} for the chat).`:"Write ALL user-visible text \u2014 full replies and the brief status notes you emit between tool calls alike \u2014 in the language of the user's most recent chat message. When the user switches language mid-conversation, switch with them. Judge the language by the human prose only: ignore code snippets, file paths and identifiers. If a message is too short to tell (a bare keyword, pure code), keep the language of the conversation so far."}function Ji(t){return t?`Write ALL user-facing prose \u2014 brief status notes between tool calls, questions, summaries and the bodies of Markdown artifacts you produce for humans \u2014 in ${t} (the project's configured language), unless your prompt pins a different language for a specific output. In-repo content (code, code comments, commit messages) follows the project's existing conventions and any explicit instructions in your prompt.`:"Write ALL user-facing prose \u2014 brief status notes between tool calls, questions, summaries and the bodies of Markdown artifacts you produce for humans \u2014 in the language of the task description and user input embedded in your prompt, NOT the language the surrounding instructions are written in. Judge that language by the human prose only, ignoring code snippets, file paths and identifiers. In-repo content (code, code comments, commit messages) follows the project's existing conventions instead."}function Fg(t){return t?`[Session note: the instructions from the start of this conversation remain in force. Reply in ${t} \u2014 including the brief status notes between tool calls.]`:"[Session note: the instructions from the start of this conversation remain in force. Reply in the language of the user's message above \u2014 including the brief status notes between tool calls. Judge the language by the human prose, ignoring code snippets and identifiers.]"}function cn(t){let e=t?.responseLanguage;if(typeof e!="string")return;let r=e.trim();return r.length>0&&r.toLowerCase()!=="auto"?r:void 0}var Xi=v(()=>{"use strict"});import{spawn as uS}from"node:child_process";function Cc(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function pS(t,e){if(!(typeof t!="string"||!t))return t.startsWith(e)?t.slice(e.length).replace(/^\/+/,"")||t.split("/").pop()||void 0:t.startsWith("/")?t.split("/").pop()||void 0:t}function fS(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function xr(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Ac(t,e){let r=[{type:"text",text:t}];return e&&r.push({type:"text",text:e}),JSON.stringify({type:"user",message:{role:"user",content:r}})+`
|
|
651
|
+
`}async function Wg(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Et;let r=cn(e.metadata),n=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",Bg(r)];e.model&&e.model.trim().length>0&&n.push("--model",e.model.trim());for(let l of e.addDirs??[])n.push("--add-dir",l);let o=e.onActivity,i=l=>{if(o)try{o(l)}catch{}},s=[],a=null,c=l=>{let u=Date.now(),p=l.type;if(p==="assistant"){let d=l.message;for(let f of d?.content??[]){let m=f.type;if(m==="text"){let h=String(f.text??"").trim();h&&i({ts:u,kind:"text",author:"agent",text:Cc(h,Gg)})}else if(m==="tool_use"){let h=String(f.name??""),g=f.input?.file_path??f.input?.path,w=pS(g,e.workspaceDir);i({ts:u,kind:"tool",author:"agent",tool:h,...w?{file:w}:{}})}}return}if(p==="user"){let d=l.message;for(let f of d?.content??[])if(f.type==="tool_result"){let m=f.is_error===!0,h=m?Cc(fS(f.content),200):"";i({ts:u,kind:"tool_result",author:"agent",isError:m,...h?{text:h}:{}})}return}if(p==="result"){a=l;let d=String(l.subtype??"").trim();i({ts:u,kind:"result",author:"agent",...d?{text:d}:{}});return}if(p==="system"){let d=String(l.subtype??"").trim();d&&i({ts:u,kind:"system",author:"agent",text:d})}};return i({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((l,u)=>{let p=uS(t,n,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});p.stdout.setEncoding("utf-8"),p.stderr.setEncoding("utf-8");let d=!1,f=!1,m=null,h=()=>{d=!0,p.kill("SIGTERM"),m=setTimeout(()=>p.kill("SIGKILL"),Kg)};e.signal?.addEventListener("abort",h,{once:!0});let g=null,w=()=>{g&&clearTimeout(g),g=setTimeout(()=>{f=!0,console.warn(`[claude:chat] idle for ${Hg}ms \u2014 ending session`),p.kill("SIGTERM"),m=setTimeout(()=>p.kill("SIGKILL"),Kg)},Hg)},y=()=>{m&&clearTimeout(m),g&&clearTimeout(g),e.signal?.removeEventListener("abort",h)},x=!0,T=b=>{if(!(!x||p.stdin.destroyed))try{p.stdin.write(b)}catch{}};T(Ac(e.prompt)),w(),(async()=>{try{for await(let b of e.interactive.inbox){if(d||!x)break;if(w(),b.kind==="user")i({ts:Date.now(),kind:"text",author:"user",text:Cc(b.text,Gg)}),T(Ac(b.text,Fg(r)));else{T(Ac(dS)),x=!1;try{p.stdin.end()}catch{}break}}}catch{}})();let R="",E=b=>{let I;try{I=JSON.parse(b)}catch{return}c(I)};p.stdout.on("data",b=>{s.push(b),w(),R+=b;let I;for(;(I=R.indexOf(`
|
|
652
652
|
`))!==-1;){let N=R.slice(0,I).trim();R=R.slice(I+1),N&&E(N)}}),p.stderr.on("data",b=>{s.push(b);for(let I of b.split(`
|
|
653
|
-
`)){let N=I.trim();N&&console.warn(`[claude:chat:stderr] ${N}`)}}),p.on("error",b=>{y(),u(b)}),p.on("close",b=>{if(y(),d){u(new Et);return}if(f){u(new Error("chat session ended: idle for too long without a reply"));return}R.trim()&&E(R.trim()),console.log(`[claude:chat] exit code=${b}`),l({artifactPaths:[],log:s.join(""),usage:
|
|
653
|
+
`)){let N=I.trim();N&&console.warn(`[claude:chat:stderr] ${N}`)}}),p.on("error",b=>{y(),u(b)}),p.on("close",b=>{if(y(),d){u(new Et);return}if(f){u(new Error("chat session ended: idle for too long without a reply"));return}R.trim()&&E(R.trim()),console.log(`[claude:chat] exit code=${b}`),l({artifactPaths:[],log:s.join(""),usage:mS(a)})})})}function mS(t){let e=rr();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=xr(r.input_tokens),e.outputTokens=xr(r.output_tokens),e.cacheReadInputTokens=xr(r.cache_read_input_tokens),e.cacheCreationInputTokens=xr(r.cache_creation_input_tokens)),e.totalCostUsd=xr(t.total_cost_usd),e.numTurns=xr(t.num_turns),e.durationMs=xr(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var Gg,Kg,Hg,dS,qg=v(()=>{"use strict";G();ln();Xi();Gg=16e3,Kg=5e3,Hg=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),dS="The user has finished the conversation. Now, based on everything discussed, write the DRAFT.md file in your current working directory following the contract from your instructions (line 1 \u2014 the issue title, \u2264 80 chars; line 2 \u2014 blank; lines 3+ \u2014 the body in Markdown), in the language of the conversation, and end your turn. Write nothing else."});import{spawn as gS}from"node:child_process";import{existsSync as hS}from"node:fs";function kS(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function Yg(t){let e;try{e=JSON.parse(t)}catch{return console.log(`[claude] ${t.slice(0,200)}`),null}let r=e.type;if(r==="system"){let n=e.subtype??"";return console.log(`[claude] system ${n}`),e}if(r==="assistant"){let n=e.message;for(let o of n?.content??[]){let i=o.type;if(i==="text"){let s=String(o.text??"").trim();s&&console.log(`[claude] text: ${Ht(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=$S(s,a);console.log(`[claude] tool_use ${s}${c?` ${c}`:""}`)}}return e}if(r==="user"){let n=e.message;for(let o of n?.content??[])if(o.type==="tool_result")if(o.is_error===!0){let i=zg(o.content);console.log(`[claude] tool_result (error)${i?`: ${Ht(i,200)}`:""}`)}else console.log("[claude] tool_result");return e}if(r==="result"){let n=e.subtype??"",o=e.num_turns,i=e.total_cost_usd;return console.log(`[claude] result ${n} turns=${o} cost=$${i}`),e}return console.log(`[claude] ${String(r)} ${Ht(JSON.stringify(e),200)}`),e}function wS(t,e,r){let n=t===0?["claude reported an error"]:[`claude exited with code ${t}`];if(e){let o=typeof e.result=="string"?e.result.trim():"",i=e.api_error_status,s=e.subtype;o?n.push(Ht(o,500)):typeof s=="string"&&s!=="success"&&n.push(s),typeof i=="number"&&n.push(`(api_status=${i})`)}return n.length===1&&r.trim()&&n.push(Ht(r.trim().split(`
|
|
654
654
|
`).slice(-5).join(`
|
|
655
|
-
`),500)),n.join(" \u2014 ")}function
|
|
656
|
-
`))!==-1;){let I=R.slice(0,b).trim();if(R=R.slice(b+1),I){let N=
|
|
657
|
-
`)){let I=b.trim();I&&console.warn(`[claude:stderr] ${I}`)}}),g.on("error",E=>{T(),h(E)}),g.on("close",E=>{if(T(),w){h(new Et);return}if(R.trim()){let I=
|
|
655
|
+
`),500)),n.join(" \u2014 ")}function bS(t){if(!t)return;let e=t.retry_after;if(typeof e=="number"&&e>0)return Math.round(e*1e3);let r=typeof t.result=="string"?t.result:"",n=/retry[\s-]*after[:\s]*(\d+)|reset[s]?\s+in[:\s]*(\d+)/i.exec(r),o=n?Number(n[1]??n[2]):NaN;return Number.isFinite(o)&&o>0?o*1e3:void 0}function zg(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function $S(t,e){if(!e)return"";if(t==="Write"||t==="Edit"||t==="Read"){let r=e.file_path??e.path;if(typeof r=="string")return`path=${r}`}if(t==="Bash"){let r=e.command;if(typeof r=="string")return`cmd=${Ht(r,80)}`}return""}function Ht(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function Oe(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function vS(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=Oe(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:Oe(e.resetsAt),rateLimitType:typeof e.rateLimitType=="string"?e.rateLimitType:"",utilization:n,isUsingOverage:e.isUsingOverage===!0};return typeof e.surpassedThreshold=="number"&&(o.surpassedThreshold=e.surpassedThreshold),o}function xS(t,e,r,n){let o=rr(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=Oe(i.input_tokens),o.outputTokens=Oe(i.output_tokens),o.cacheReadInputTokens=Oe(i.cache_read_input_tokens),o.cacheCreationInputTokens=Oe(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=Oe(t?.total_cost_usd),o.numTurns=t&&Oe(t.num_turns)>0?Oe(t.num_turns):r,o.durationMs=Oe(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}function SS(t,e){let r=Date.now(),n=t.type;if(n==="system"){let o=String(t.subtype??"").trim();return o?[{ts:r,kind:"system",text:o}]:[]}if(n==="assistant"){let o=t.message,i=[];for(let s of o?.content??[]){let a=s.type;if(a==="text"){let c=String(s.text??"").trim();c&&i.push({ts:r,kind:"text",text:Ht(c,Vg)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,p=TS(u,e);i.push({ts:r,kind:"tool",tool:c,...p?{file:p}:{}})}}return i}if(n==="user"){let o=t.message,i=[];for(let s of o?.content??[])if(s.type==="tool_result"){let a=s.is_error===!0,c=a?Ht(zg(s.content),Vg):"";i.push({ts:r,kind:"tool_result",isError:a,...c?{text:c}:{}})}return i}if(n==="result"){let o=String(t.subtype??"").trim(),i=typeof t.num_turns=="number"?t.num_turns:void 0,s=typeof t.total_cost_usd=="number"?t.total_cost_usd:void 0;return[{ts:r,kind:"result",...o?{text:o}:{},...i!==void 0?{turns:i}:{},...s!==void 0?{costUsd:s}:{}}]}return[]}function TS(t,e){if(!(typeof t!="string"||!t))return t.startsWith(e)?t.slice(e.length).replace(/^\/+/,"")||t.split("/").pop()||void 0:t.startsWith("/")?t.split("/").pop()||void 0:t}var un,Et,yS,mo,Vg,ln=v(()=>{"use strict";G();qg();Xi();un=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Et=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},yS=5e3;mo=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return Wg(this.binary,e);if(e.signal?.aborted)throw new Et;let r=["-p",kS(e.prompt),"--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",Ji(cn(e.metadata))];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let m of e.addDirs??[])r.push("--add-dir",m);let n=[],o=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,u=m=>{if(m){if(m.type==="result"){i=m;return}if(m.type==="rate_limit_event"){let h=vS(m.rate_limit_info);h&&(!l||h.utilization>l.utilization)&&(l=h);return}if(m.type==="assistant"){let h=m.message;typeof h?.model=="string"&&(c=h.model);let g=h?.usage;g&&(a+=1,s.input+=Oe(g.input_tokens),s.output+=Oe(g.output_tokens),s.cacheRead+=Oe(g.cache_read_input_tokens),s.cacheCreate+=Oe(g.cache_creation_input_tokens))}}},p=e.role,d=e.onActivity,f=m=>{if(d)for(let h of SS(m,e.workspaceDir))try{d(h)}catch{}};return d?.({ts:Date.now(),kind:"start",text:`${p} job started`}),console.log(`[claude] spawn ${this.binary} role=${p}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((m,h)=>{let g=gS(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{},CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:"1800000"}});g.stdout.setEncoding("utf-8"),g.stderr.setEncoding("utf-8");let w=!1,y=null,x=()=>{w=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${p}`),g.kill("SIGTERM"),y=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),g.kill("SIGKILL")},yS)};e.signal?.addEventListener("abort",x,{once:!0});let T=()=>{y&&clearTimeout(y),e.signal?.removeEventListener("abort",x)},R="";g.stdout.on("data",E=>{n.push(E),R+=E;let b;for(;(b=R.indexOf(`
|
|
656
|
+
`))!==-1;){let I=R.slice(0,b).trim();if(R=R.slice(b+1),I){let N=Yg(I);u(N),N&&f(N)}}}),g.stderr.on("data",E=>{n.push(E),o.push(E);for(let b of E.split(`
|
|
657
|
+
`)){let I=b.trim();I&&console.warn(`[claude:stderr] ${I}`)}}),g.on("error",E=>{T(),h(E)}),g.on("close",E=>{if(T(),w){h(new Et);return}if(R.trim()){let I=Yg(R.trim());u(I),I&&f(I)}let b=i?.is_error===!0;if(E!==0||b){let I=typeof i?.api_error_status=="number"?i.api_error_status:void 0,N=typeof i?.subtype=="string"?i.subtype:void 0,F=typeof i?.result=="string"?i.result:void 0;h(new un(wS(E,i,o.join("")),{code:E,apiErrorStatus:I,subtype:N,resultText:F,retryAfterMs:bS(i)}));return}console.log("[claude] exit code=0"),m({artifactPaths:[],log:n.join(""),usage:xS(i,s,a,c),...l?{rateLimit:l}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(n=>n.includes("/")&&hS(n))}};Vg=200});import{mkdirSync as ES,writeFileSync as dn}from"node:fs";import{dirname as RS,join as pn}from"node:path";function Jg(t,e,r){let n=pn(t,e);ES(RS(n),{recursive:!0}),dn(n,r)}function IS(t,e,r){return`# ${t} \u2014 Estimate
|
|
658
658
|
|
|
659
659
|
**Title:** ${e}
|
|
660
660
|
|
|
@@ -675,7 +675,7 @@ production-grade estimates.)
|
|
|
675
675
|
${r.split(`
|
|
676
676
|
`).slice(0,8).join(`
|
|
677
677
|
`).trim()||"(empty)"}
|
|
678
|
-
`}function
|
|
678
|
+
`}function CS(t,e,r,n){let o=n?`
|
|
679
679
|
## Reviewer rework instruction
|
|
680
680
|
|
|
681
681
|
> ${n.split(`
|
|
@@ -704,10 +704,10 @@ TBD (mock runner does not yet inspect project code).
|
|
|
704
704
|
${r.split(`
|
|
705
705
|
`).slice(0,8).join(`
|
|
706
706
|
`).trim()||"(empty)"}
|
|
707
|
-
`}function
|
|
707
|
+
`}function AS(t){return`# ${t} \u2014 Open questions
|
|
708
708
|
|
|
709
709
|
(none \u2014 mock runner did not surface ambiguities.)
|
|
710
|
-
`}function
|
|
710
|
+
`}function PS(t,e,r){let n=r?` (rework: ${r.split(`
|
|
711
711
|
`)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
|
|
712
712
|
index 0000000..1111111 100644
|
|
713
713
|
--- a/CHANGELOG.md
|
|
@@ -718,7 +718,7 @@ index 0000000..1111111 100644
|
|
|
718
718
|
+- mock-runner placeholder change for slice 5 testing.
|
|
719
719
|
+
|
|
720
720
|
# Changelog
|
|
721
|
-
`}function
|
|
721
|
+
`}function _S(t,e,r){return`# ${t} \u2014 Diff summary
|
|
722
722
|
|
|
723
723
|
**Title:** ${e}
|
|
724
724
|
${r?`
|
|
@@ -729,143 +729,144 @@ ${r?`
|
|
|
729
729
|
- \`CHANGELOG.md\` \u2014 added entry for ${t}.
|
|
730
730
|
|
|
731
731
|
(Mock-runner output. Replace with claude-headless for production patches.)
|
|
732
|
-
`}var
|
|
733
|
-
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:rr()}}async runInteractive(e){let r=e.onActivity,n=i=>{r?.({ts:Date.now(),kind:"text",author:"agent",text:i}),r?.({ts:Date.now(),kind:"result",author:"agent",text:"success"})};r?.({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),n("Hi! Describe the task you'd like to formulate.");let o="Draft from chat";for await(let i of e.interactive.inbox){if(e.signal?.aborted)throw new Et;if(i.kind==="user")r?.({ts:Date.now(),kind:"text",author:"user",text:i.text}),i.text.trim()&&(o=i.text.trim().slice(0,80)),n(`Got it: **${i.text.trim()}**. Anything else to clarify?`);else break}return
|
|
732
|
+
`}var go,Pc=v(()=>{"use strict";G();ln();go=class{name(){return"mock"}async run(e){if(e.interactive)return this.runInteractive(e);let r=e.metadata??{},n=r.trackerIssueKey??"TASK",o=r.taskTitle??"(unknown task)",i=r.taskDescription??"",s=[];if(e.role==="estimate"){let a=IS(n,o,i);dn(pn(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;dn(pn(e.workspaceDir,"PLAN.md"),CS(n,o,i,a)),s.push("PLAN.md"),dn(pn(e.workspaceDir,"QUESTIONS.md"),AS(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Jg(e.workspaceDir,"changes/sample.patch",PS(n,o,a)),s.push("changes/sample.patch"),Jg(e.workspaceDir,"diff-summary.md",_S(n,o,a)),s.push("diff-summary.md")}else e.role==="rework"&&(dn(pn(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
|
|
733
|
+
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:rr()}}async runInteractive(e){let r=e.onActivity,n=i=>{r?.({ts:Date.now(),kind:"text",author:"agent",text:i}),r?.({ts:Date.now(),kind:"result",author:"agent",text:"success"})};r?.({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),n("Hi! Describe the task you'd like to formulate.");let o="Draft from chat";for await(let i of e.interactive.inbox){if(e.signal?.aborted)throw new Et;if(i.kind==="user")r?.({ts:Date.now(),kind:"text",author:"user",text:i.text}),i.text.trim()&&(o=i.text.trim().slice(0,80)),n(`Got it: **${i.text.trim()}**. Anything else to clarify?`);else break}return dn(pn(e.workspaceDir,"DRAFT.md"),`${o}
|
|
734
734
|
|
|
735
735
|
Produced by the interactive chat (mock runner).
|
|
736
|
-
`),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:rr()}}}});function
|
|
736
|
+
`),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:rr()}}}});function Xg(t){switch(t){case"mock":return new go;case"claude-headless":return new mo;default:return null}}function Qg(t,e){let r=e&&e.trim().length>0?e.trim():pt;return t==="mock"?!0:t==="claude-headless"?r==="claude":!1}var Zg=v(()=>{"use strict";G();ln();Pc();ln();Pc()});function rh(t=process.env){return{maxAttempts:Qi(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:Qi(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:Qi(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:Qi(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function DS(t){if(t instanceof un){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return NS.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&OS.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:jS.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:eh.test(s)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:n??`exit ${t.details.code}`}}let e=t instanceof Error?t.message:String(t);return eh.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function nh(t){if(t instanceof un){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&th.test(n)}let e=t instanceof Error?t.message:String(t);return th.test(e)}function LS(t,e,r){if(typeof r=="number"&&r>0)return Math.min(r,e.maxDelayMs);let n=e.baseDelayMs*2**(t-1),o=Math.min(n,e.maxDelayMs);return Math.round(o/2+Math.random()*(o/2))}async function oh(t,e,r){let n=r.sleep??(s=>new Promise(a=>setTimeout(a,s))),o=Date.now()+r.policy.totalBudgetMs,i="";for(let s=1;;s++)try{return await t.run(e)}catch(a){i=a instanceof Error?a.message:String(a);let c=DS(a),l=s>=r.policy.maxAttempts;if(!c.retryable||l||r.aborted())throw s>1?new Error(`agent failed after ${s} attempts: ${i}`):a;let u=LS(s,r.policy,c.retryAfterMs);if(Date.now()+u>o)throw new Error(`agent failed after ${s} attempts (retry budget exhausted): ${i}`);console.warn(`[job] ${r.jobId} agent attempt ${s}/${r.policy.maxAttempts} failed (retryable: ${c.reason}) \u2014 cleaning workspace, backoff ${u}ms`),await r.onBeforeRetry(),await n(u)}}function Qi(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}var jS,eh,NS,OS,th,ih=v(()=>{"use strict";ln();jS=new Set([429,500,502,503,529]),eh=/(\bETIMEDOUT\b|\bECONNRESET\b|\bECONNREFUSED\b|\bEAI_AGAIN\b|\bEPIPE\b|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,NS=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,OS=new Set(["error_max_turns"]);th=/(not logged in|invalid api key|invalid x-api-key|authentication[ _]error|unauthorized|oauth token (?:expired|revoked|invalid)|token (?:expired|revoked)|please run .{0,20}login|run `?claude\b.{0,20}(?:login|setup-token))/i});import{mkdirSync as MS,writeFileSync as US}from"node:fs";import{homedir as BS}from"node:os";import{join as sh}from"node:path";function ch(t,e=process.env){let r=(e.CODEPIPE_DEBUG??"").trim().toLowerCase();return r?r==="1"||r==="true"||r==="all"?!0:r.split(",").map(n=>n.trim()).includes(t):!1}function lh(t,e,r,n){try{let o=sh(BS(),".codepipe","debug",ah(t));MS(o,{recursive:!0});let i=new Date().toISOString().replace(/[:.]/g,"-"),s=sh(o,`${i}-${ah(e)}-${r}.md`);return US(s,n),s}catch{return null}}var ah,uh=v(()=>{"use strict";ah=t=>t.replace(/[^A-Za-z0-9._-]/g,"_")});import{mkdtempSync as FS,rmSync as GS,writeFileSync as dh}from"node:fs";import{tmpdir as KS}from"node:os";import{join as _c}from"node:path";function Zi(t){return`[url "https://${t}/"]
|
|
737
737
|
insteadOf = git@${t}:
|
|
738
738
|
insteadOf = ssh://git@${t}/
|
|
739
|
-
`}function
|
|
739
|
+
`}function ph(t,e){if(t.length===0)return null;let r=FS(_c(KS(),"devpipe-gitcreds-")),n=_c(r,"credentials"),o=_c(r,"gitconfig");return dh(n,t.join(`
|
|
740
740
|
`)+`
|
|
741
|
-
`,{mode:384}),
|
|
741
|
+
`,{mode:384}),dh(o,`[credential]
|
|
742
742
|
helper = store --file=${n}
|
|
743
|
-
`+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{
|
|
744
|
-
`).map(m=>m.trim()).filter(m=>m.length>0);if(d&&f.length===0)throw await ie(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${d}`);return f}async function
|
|
745
|
-
`).map(l=>l.trim()).filter(l=>l.length>0),c=await Ce(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}function ie(t,e,r){return new Promise((n,o)=>{let i=
|
|
746
|
-
${s.join("").trim()||"(no stderr)"}`))})})}function Ce(t,e,r){return new Promise((n,o)=>{let i=
|
|
747
|
-
${a.join("").trim()||"(no stderr)"}`))})})}function
|
|
748
|
-
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=
|
|
749
|
-
`+e.subarray(e.length-
|
|
750
|
-
\u2026 [${r.length-e} bytes elided]`}var
|
|
743
|
+
`+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{GS(r,{recursive:!0,force:!0})}catch{}}}}function jc(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(HS)),t.bitbucket?.apiToken&&(e.push(`https://${sr}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(WS)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(qS)),ph(e,r)}function fh(t,e){if(t.contextWrite?.token){let r=Lr(e)??"github.com",n=Bo(r);return ph([`https://${n}:${t.contextWrite.token}@${r}`],[Zi(r)])}return jc(t)}var HS,WS,qS,mh=v(()=>{"use strict";G();HS=Zi("github.com"),WS=Zi("bitbucket.org"),qS=Zi("gitlab.com")});import{spawn as hh}from"node:child_process";import{existsSync as es,mkdirSync as ho,readFileSync as YS,rmSync as Nc,symlinkSync as VS}from"node:fs";import{homedir as zS}from"node:os";import{dirname as mn,join as Wt}from"node:path";function yh(t){let e=Wt(zS(),".codepipe-sandbox","repos");return t?Wt(e,t):e}function kh(t,e){let n=(fn.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{fn.get(t)===o&&fn.delete(t)},()=>{fn.get(t)===o&&fn.delete(t)});return fn.set(t,o),n}function gh(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 JS(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 wh(t,e,r,n,o){let i=async c=>{await ie(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await ie(t,["reset","--hard",`origin/${c}`],o),await ie(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!gh(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{es(t)&&Nc(t,{recursive:!0,force:!0}),ho(mn(t),{recursive:!0});try{return await ie(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!gh(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),es(t)&&Nc(t,{recursive:!0,force:!0}),ho(mn(t),{recursive:!0}),await ie(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(es(Wt(t,".git")))try{return await s()}catch(c){if(!JS(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 bh(t){await ie(t.workspacePath,["reset","--hard",t.baseSha]),await ie(t.workspacePath,["clean","-fdx"])}async function $h(t,e){let r=t.workspacePath;await ie(r,["add","-A"]);let n=(await Ce(r,["write-tree"])).trim(),o=(await Ce(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:gn,GIT_AUTHOR_EMAIL:hn,GIT_COMMITTER_NAME:gn,GIT_COMMITTER_EMAIL:hn};return(await Ce(r,["commit-tree",n,"-m",e],i)).trim()}async function vh(t,e,r,n,o){try{await ie(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw Lr(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 xh(t,e){return Ce(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Sh(t,e,r,n,o){await ie(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await ie(t.workspacePath,["checkout","--force",r])}async function Th(t,e,r,n,o,i){let s=t.workspacePath;await ie(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await Ce(s,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=m=>Ce(s,["rev-parse","-q","--verify",`${m}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await Ce(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ie(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(h=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(h)}`)}),await c(n)||await ie(s,["fetch","origin",n],i).catch(()=>{}),!await c(n)))throw new Error(`moved-base apply: delivery base ${n.slice(0,10)} is unreachable \u2014 cannot re-apply the previous iteration onto the fresh ${t.ref}`);let l={...i??process.env,GIT_AUTHOR_NAME:gn,GIT_AUTHOR_EMAIL:hn,GIT_COMMITTER_NAME:gn,GIT_COMMITTER_EMAIL:hn},u=(await Ce(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),p=(await Ce(s,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await ie(s,["cherry-pick","--quit"],l).catch(()=>{});let d=null;try{await ie(s,["cherry-pick","--no-commit",p],l)}catch(m){d=m instanceof Error?m.message:String(m)}let f=(await Ce(s,["diff","--name-only","--diff-filter=U"])).split(`
|
|
744
|
+
`).map(m=>m.trim()).filter(m=>m.length>0);if(d&&f.length===0)throw await ie(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${d}`);return f}async function Oc(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:gn,GIT_AUTHOR_EMAIL:hn,GIT_COMMITTER_NAME:gn,GIT_COMMITTER_EMAIL:hn};(await Ce(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ie(n,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),await ie(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await ie(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await Ce(n,["diff","--name-only","--diff-filter=U"])).split(`
|
|
745
|
+
`).map(l=>l.trim()).filter(l=>l.length>0),c=await Ce(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}function ie(t,e,r){return new Promise((n,o)=>{let i=hh("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}):
|
|
746
|
+
${s.join("").trim()||"(no stderr)"}`))})})}function Ce(t,e,r){return new Promise((n,o)=>{let i=hh("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}):
|
|
747
|
+
${a.join("").trim()||"(no stderr)"}`))})})}function Eh(t,e){es(t)&&Nc(t,{recursive:!0,force:!0}),ho(mn(t),{recursive:!0}),VS(e,t,"dir")}async function Rh(t,e,r){await ie(t,["worktree","prune"]).catch(()=>{}),ho(mn(r),{recursive:!0}),await ie(t,["worktree","add","--detach",r,`origin/${e}`])}async function XS(t,e,r){ho(mn(r),{recursive:!0}),await ie(mn(r),["clone","--quiet","--no-checkout",t,r]),await ie(r,["checkout","--force","--detach",e])}async function Ih(t,e,r,n="worktree",o,i){return r.length===0?[]:kh(e,async()=>{let s=[];for(let a of r){let c=Wt(yh(i),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await wh(c,a.cloneUrl,a.ref,a.defaultBranch,o)}catch(d){throw new Error(`failed to materialize project repo "${a.name}" (${a.cloneUrl}): `+(d instanceof Error?d.message:String(d)))}let u=(await Ce(c,["rev-parse","HEAD"])).trim(),p=Wt(t,"code",a.name);n==="direct"?(Eh(p,c),console.log(`[git] code: linked ${p} \u2192 ${c} @ ${u.slice(0,10)}`)):n==="clone"?(await XS(c,u,p),console.log(`[git] code: clone ${p} \u2190 ${c} @ ${u.slice(0,10)}`)):(await Rh(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 Ch(t,e,r,n="worktree",o,i){if(!r||!r.cloneUrl)return null;let s=r;return kh(e,async()=>{let a=Wt(yh(i),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);try{await wh(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=Wt(t,"context");n==="direct"?(Eh(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await Rh(a,s.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await Ce(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function Ah(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await ie(r,["add","-A",...n]).catch(()=>{});let o;try{o=await Ce(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
|
|
748
|
+
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=YS(Wt(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var fn,gn,hn,Ph=v(()=>{"use strict";G();fn=new Map;gn="CodePipe Agent",hn="codepipe@codepartner.ee"});import{readFileSync as QS}from"node:fs";import{join as ZS}from"node:path";function _h(t){let e=ZS(t,yo),r;try{r=QS(e,"utf-8")}catch{throw new qt(`BUILD produced no ${yo} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new qt(`${yo} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new qt(`${yo} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new qt(`${yo}: "ok" must be a boolean`);let i=o.ok,a=(Array.isArray(o.steps)?o.steps:[]).flatMap(u=>{if(!u||typeof u!="object")return[];let p=u,d=typeof p.name=="string"?p.name:null,f=typeof p.exitCode=="number"?p.exitCode:null;if(d===null||f===null)return[];let m={name:d,exitCode:f};return typeof p.durationMs=="number"&&(m.durationMs=p.durationMs),[m]}),c=typeof o.logTail=="string"?eT(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 eT(t){let e=Buffer.from(t,"utf-8");return e.length<=Dc?t:`\u2026 [${e.length-Dc} bytes elided] \u2026
|
|
749
|
+
`+e.subarray(e.length-Dc).toString("utf-8")}var Dc,qt,yo,jh=v(()=>{"use strict";Dc=8*1024,qt=class extends Error{},yo="meta/build-result.json"});import{readFileSync as tT}from"node:fs";import{join as rT}from"node:path";function Oh(t){let e=rT(t,yn),r;try{r=tT(e,"utf-8")}catch{throw new Rt(`code review produced no ${yn} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(c){throw new Rt(`${yn} is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(!n||typeof n!="object")throw new Rt(`${yn} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new Rt(`${yn}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?Nh(o.remarks,nT):"";if(!i&&s.trim().length===0)throw new Rt(`${yn}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?Nh(o.summary,oT):"";return{approved:i,remarks:s,summary:a}}function Nh(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
|
|
750
|
+
\u2026 [${r.length-e} bytes elided]`}var nT,oT,Rt,yn,Dh=v(()=>{"use strict";nT=16*1024,oT=4*1024,Rt=class extends Error{},yn="meta/review-result.json"});import{readFileSync as iT,statSync as sT}from"node:fs";import{join as Lh}from"node:path";function fT(t){return t.startsWith("meta/")||pT.has(t)}function mT(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 gT(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function Mh(t,e,r){let n=r?.maxBytes??aT,o=r?.totalBytes??cT,i=r?.maxCount??lT,s=e.map((m,h)=>{let g=null;try{g=sT(Lh(t,m)).size}catch{}return{path:m,index:h,size:g}}),a=[...s].sort((m,h)=>{let g=w=>fT(w.path)?0:1;return g(m)!==g(h)?g(m)-g(h):(m.size??0)-(h.size??0)}),c=a.slice(0,i),l=a.slice(i).sort((m,h)=>m.index-h.index).map(m=>m.path),u=new Array(s.length),p=[],d=0;for(let m of c){let h=null;if(m.size!==null&&m.size<=n&&d+m.size<=o)try{h=iT(Lh(t,m.path))}catch{}if(h!==null){d+=h.length,u[m.index]={path:m.path,contentBase64:h.toString("base64")};continue}let g=m.size===null?gT(m.path):mT(m.path,m.size,n,o),w=Buffer.from(g,"utf-8");d+=w.length,u[m.index]={path:m.path,contentBase64:w.toString("base64")},p.push({path:m.path,bytes:m.size??0})}let f=u.filter(m=>m!==void 0);if(l.length>0){let m=l.slice(0,dT),h=`# Artifacts omitted from upload
|
|
751
751
|
|
|
752
752
|
${l.length} file(s) exceeded the SANDBOX artifact count budget (${i}) and were dropped from the listing. The delivered code (git) and the build/review verdicts are unaffected. Usually this means a job left a stray tree in the workspace \u2014 throwaway copies belong in the workspace's \`scratch/\` directory, which is never uploaded.
|
|
753
753
|
|
|
754
754
|
`+m.map(g=>`- ${g}
|
|
755
755
|
`).join("")+(l.length>m.length?`
|
|
756
756
|
\u2026and ${l.length-m.length} more.
|
|
757
|
-
`:"");f.push({path:
|
|
758
|
-
${n}`.match(
|
|
759
|
-
${n}`.split(/[\s,;()[\]{}<>"'!?]+/);for(let f of c){let m=f.replace(/^[`*_]+|[`*_.:]+$/g,"");if(!m||!m.includes("/")&&!m.includes("."))continue;let h=a.get(m)??[];h.length===1&&s(h[0],
|
|
760
|
-
${n}`.match(/[A-Za-z][A-Za-z0-9_-]{3,}/g)??[]){let m=l.get(f.toLowerCase());m&&s(m,
|
|
761
|
-
${n}`),d=[];for(let[f,m]of o.events){if(f===e||!m.title)continue;let h
|
|
762
|
-
`));let u=
|
|
757
|
+
`:"");f.push({path:uT,contentBase64:Buffer.from(h,"utf-8").toString("base64")})}return{artifacts:f,omitted:p,dropped:l}}var aT,cT,lT,uT,dT,pT,Uh=v(()=>{"use strict";aT=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),cT=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),lT=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),uT="artifacts-omitted.md",dT=500,pT=new Set(["QUESTIONS.md","PLAN.md","SOLUTION.md","DRAFT.md","ESTIMATE.md","diff-summary.md","review-result.md","commit-message.txt","pr-description.md"])});import{lstatSync as hT,mkdtempSync as yT,readFileSync as kT,readdirSync as Fh,rmSync as Bh}from"node:fs";import{tmpdir as wT}from"node:os";import{join as ts,relative as bT}from"node:path";function Gh(t){let e=yT(ts(wT(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Bh(e,{recursive:!0,force:!0}),listFiles:()=>Kh(e,e),readFile:r=>kT(ts(e,r),"utf-8"),clean:()=>{for(let r of Fh(e))vT.has(r)||Bh(ts(e,r),{recursive:!0,force:!0})}}}function Kh(t,e){let r=[];for(let n of Fh(e)){let o=ts(e,n),i=hT(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&$T.has(n))continue;r.push(...Kh(t,o))}else r.push(bT(t,o))}return r}var $T,vT,Hh=v(()=>{"use strict";$T=new Set(["code","context","scratch"]),vT=new Set(["code","context"])});import{existsSync as ns,readFileSync as Wh,readdirSync as Lc}from"node:fs";import{join as It}from"node:path";import{parse as xT}from"yaml";function os(t){if(!ns(t))return[];let e=[];for(let r of Lc(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=It(t,r.name);r.isDirectory()?e.push(...os(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function rs(t){try{return xT(Wh(t,"utf-8"))}catch{return null}}function qh(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 os(It(t,"model/derived/structure"))){let s=Ct(rs(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[...os(It(t,"model/derived/correlates")),It(t,"model/derived/relates.yaml")]){if(!ns(i))continue;let s=jo(rs(i));if(s.ok)for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}let n=It(t,"model/facts/events");if(ns(n))for(let i of Lc(n).sort()){if(!i.endsWith(".yaml"))continue;let s=At(rs(It(n,i)));if(!s.ok)continue;let a=s.value;e.events.set(a.taskKey,a);let c=ve(a.taskKey);for(let l of a.files)r(c,l.key,"touched_by",1);for(let l of a.links?.adr??[])r(c,`adr::${l}`,"references",1);for(let l of a.links?.tasks??[])r(c,ve(l),"references",1)}for(let i of os(It(t,"model/facts/identity"))){let s=Oo(rs(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=It(t,"model/facts/annotations");if(ns(o)){for(let i of Lc(o).sort())if(i.endsWith(".md"))try{let s=Wh(It(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 Yh=v(()=>{"use strict";G()});function zh(t){return new Set((t.toLowerCase().match(/[a-zа-я0-9_]{4,}/g)??[]).filter(e=>!/^\d+$/.test(e)))}function AT(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 Jh(t){let{taskKey:e,title:r,text:n,model:o}=t,i=new Map,s=(f,m)=>{(i.get(f)??0)<m&&i.set(f,m)};(o.events.has(e)||o.adjacency.has(ve(e)))&&s(ve(e),Vh);for(let f of`${r}
|
|
758
|
+
${n}`.match(CT)??[]){if(f===e)continue;let m=ve(f);(o.events.has(f)||o.adjacency.has(m))&&s(m,Vh)}let a=new Map;for(let f of o.nodes.keys()){let m=Q(f);if(m?.level!=="code")continue;let h=m.path.slice(m.path.lastIndexOf("/")+1);for(let g of[m.path,h])a.has(g)||a.set(g,[]),a.get(g).push(f)}let c=`${r}
|
|
759
|
+
${n}`.split(/[\s,;()[\]{}<>"'!?]+/);for(let f of c){let m=f.replace(/^[`*_]+|[`*_.:]+$/g,"");if(!m||!m.includes("/")&&!m.includes("."))continue;let h=a.get(m)??[];h.length===1&&s(h[0],ST)}let l=new Map,u=(f,m)=>{let h=f.toLowerCase();!h||h.length<4||l.set(h,l.has(h)&&l.get(h)!==m?null:m)};for(let f of o.nodes.keys()){let m=Q(f);if(!m)continue;let h=m.path.slice(m.path.lastIndexOf("/")+1);m.level==="code"&&u(h.replace(/\.[a-z0-9]+$/i,""),f),m.level==="component"&&u(h,f)}for(let f of`${r}
|
|
760
|
+
${n}`.match(/[A-Za-z][A-Za-z0-9_-]{3,}/g)??[]){let m=l.get(f.toLowerCase());m&&s(m,TT)}let p=zh(`${r}
|
|
761
|
+
${n}`),d=[];for(let[f,m]of o.events){if(f===e||!m.title)continue;let h=AT(p,zh(m.title));h>=RT&&d.push({key:ve(f),score:h})}return d.sort((f,m)=>m.score-f.score||(f.key<m.key?-1:1)).slice(0,IT).forEach(f=>s(f.key,ET)),i}var Vh,ST,TT,ET,RT,IT,CT,Xh=v(()=>{"use strict";G();Vh=1,ST=.9,TT=.7,ET=.5,RT=.15,IT=3,CT=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g});function Qh(t,e,r={}){let n=r.cutoff??jr.activationCutoff,o=r.topK??jr.topKPerNode,i=r.nodeCap??jr.nodeCap,s=new Map;for(let[l,u]of e)s.set(l,{activation:u});let a=[...e].map(([l,u])=>({key:l,activation:u})).sort((l,u)=>u.activation-l.activation||(l.key<u.key?-1:1)),c=new Set;for(;a.length>0;){a.sort((p,d)=>d.activation-p.activation||(p.key<d.key?-1:1));let l=a.shift();if(c.has(l.key)||(s.get(l.key)?.activation??0)>l.activation)continue;if(c.add(l.key),c.size>i)break;let u=[...t.adjacency.get(l.key)??[]].sort((p,d)=>d.weight-p.weight||(p.to<d.to?-1:1)).slice(0,o);for(let p of u){let d=jl[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 Zh=v(()=>{"use strict";G()});import{existsSync as Uc,readFileSync as ey,readdirSync as PT}from"node:fs";import{join as as}from"node:path";function Mc(t){return Math.ceil(t.length/4)}function is(t,e){return[...t.entries()].filter(([r])=>e(r)).map(([r,n])=>({key:r,activation:n.activation,via:n.via})).sort((r,n)=>n.activation-r.activation||(r.key<n.key?-1:1))}function Yt(t){let e=Q(t);return e?(e.level==="task"||e.level==="adr",e.path):t}function ss(t){if(!t.via)return"matched from the task text";let e=Yt(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 OT(t,e){let r=/^ADR-(\d{3,4})$/.exec(e)?.[1];if(!r)return null;let n=as(t,"adr");if(!Uc(n))return null;let o=r.padStart(4,"0");for(let i of PT(n).sort())if(!(!i.startsWith(`${o}-`)||!i.endsWith(".md")))try{return{file:`adr/${i}`,content:ey(as(n,i),"utf-8").trim()}}catch{return null}return null}function ty(t){let{taskKey:e,title:r,contextDir:n,model:o,activated:i}=t,s=t.budgetTokens??jr.budgetTokens,a=[],c=0,l=E=>{let b=Mc(E);return c+b>s?!1:(a.push(E),c+=b,!0)};l([`# Context pack \u2014 ${e}: ${r}`,"","Assembled deterministically from the project map (git history, past","tasks, decisions). No file bodies here \u2014 the paths are ENTRY POINTS","into the repositories; each line says why it made the list."].join(`
|
|
762
|
+
`));let u=is(i,E=>E.startsWith("adr::")),p=!1;for(let E of u){let b=OT(n,Yt(E.key));if(!b)continue;let I=`${p?"":`
|
|
763
763
|
## Governing decisions
|
|
764
764
|
`}
|
|
765
|
-
### ${Yt(E.key)} (\`${b.file}\`, ${
|
|
765
|
+
### ${Yt(E.key)} (\`${b.file}\`, ${ss(E)})
|
|
766
766
|
|
|
767
767
|
${b.content}
|
|
768
|
-
`;if(!l(I))break;p=!0}let d=
|
|
768
|
+
`;if(!l(I))break;p=!0}let d=is(i,E=>o.nodes.get(E)?.entityId!==void 0).filter(E=>o.annotations.has(o.nodes.get(E.key).entityId)),f=t.staleKeys??new Set,m=!1;for(let E of d){let b=o.nodes.get(E.key).entityId,I=o.annotations.get(b),N=f.has(E.key)?" \u2014 \u26A0 the file changed since the map was built":o.orphanedEntities.has(b)?" \u2014 \u26A0 the file no longer exists":"",F=`${m?"":`
|
|
769
769
|
## Why the code is shaped this way (intent notes)
|
|
770
770
|
`}
|
|
771
771
|
### \`${Yt(E.key)}\`${N}
|
|
772
772
|
|
|
773
773
|
${I}
|
|
774
|
-
`;if(!l(
|
|
775
|
-
> ${
|
|
776
|
-
> _(full text: \`${
|
|
774
|
+
`;if(!l(F))break;m=!0}let h=ve(e),g=is(i,E=>E.startsWith("task::")&&E!==h).slice(0,_T),w=!1;for(let E of g){let b=o.events.get(Yt(E.key));if(!b)continue;let I=[...b.files].filter(D=>!f.has(D.key)&&(!D.entityId||!o.orphanedEntities.has(D.entityId))).sort((D,A)=>(A.churn??0)-(D.churn??0)||(D.key<A.key?-1:1)).slice(0,3).map(D=>`\`${Yt(D.key)}\``).join(", "),N="",F=b.links?.solution??[`tasks/${b.taskKey}/PLAN.md`,`tasks/${b.taskKey}/SOLUTION.md`].find(D=>Uc(as(n,D)))??`tasks/${b.taskKey}/PLAN.md`,C=as(n,F);if(Uc(C))try{N=`
|
|
775
|
+
> ${ey(C,"utf-8").trim().slice(0,NT).replace(/\n+/g," ").trim()}\u2026
|
|
776
|
+
> _(full text: \`${F}\`)_`}catch{}let k=`${w?"":`
|
|
777
777
|
## Related past tasks
|
|
778
778
|
`}
|
|
779
|
-
- **${b.taskKey}**${b.title?` \u2014 ${b.title}`:""}${b.date?` (${b.date})`:""}, ${
|
|
780
|
-
`))+
|
|
781
|
-
`))}let R=
|
|
779
|
+
- **${b.taskKey}**${b.title?` \u2014 ${b.title}`:""}${b.date?` (${b.date})`:""}, ${ss(E)}. Files: ${I||"\u2014"}.${N}`;if(!l(k))break;w=!0}let y=E=>{if(f.has(E.key))return!1;let b=o.nodes.get(E.key)?.entityId;return!b||!o.orphanedEntities.has(b)},x=is(i,E=>E.startsWith("code:")),T=x.filter(y).slice(0,jT);if(T.length>0){let E=["","## Files likely involved",""];for(let b of T){let I=`- \`${Yt(b.key)}\` \u2014 ${ss(b)}`;if(c+Mc(E.join(`
|
|
780
|
+
`))+Mc(I)>s)break;E.push(I)}E.length>3&&l(E.join(`
|
|
781
|
+
`))}let R=x.filter(E=>!y(E)).slice(0,10);if(R.length>0){let E=["","## Possibly stale (verify before trusting)","","These entries reference files that changed after the map was built or","no longer exist at their recorded location. Useful as history, wrong","as current fact.","",...R.map(b=>`- \`${Yt(b.key)}\` \u2014 ${ss(b)}${f.has(b.key)?" (changed since the map was built)":" (file gone)"}`)];l(E.join(`
|
|
782
782
|
`))}return a.length<=1?null:a.join(`
|
|
783
783
|
`)+`
|
|
784
|
-
`}var
|
|
784
|
+
`}var _T,jT,NT,ry=v(()=>{"use strict";G();_T=5,jT=300,NT=400});var sy={};Ir(sy,{assembleContextPack:()=>UT});import{createHash as DT}from"node:crypto";import{existsSync as ny,readFileSync as oy}from"node:fs";import{join as iy}from"node:path";function LT(t){return DT("sha1").update(`blob ${t.length}\0`).update(t).digest("hex")}function MT(t,e,r){let n=new Set;for(let o of e.keys()){let i=Q(o);if(i?.level!=="code")continue;let s=t.nodes.get(o);if(!s?.contentHash)continue;let a=r.get(i.repo);if(!a)continue;let c=iy(a,i.path);try{if(!ny(c)){n.add(o);continue}LT(oy(c)).startsWith(s.contentHash)||n.add(o)}catch{}}return n}function UT(t){let e=qh(t.contextDir);if(e.empty)return null;let r="",n=iy(t.contextDir,`tasks/${t.taskKey}/task.md`);if(ny(n))try{r=oy(n,"utf-8")}catch{r=""}let o=Jh({taskKey:t.taskKey,title:t.title,text:r,model:e});if(o.size===0)return null;let i=Qh(e,o),s=t.repoDirs?MT(e,i,t.repoDirs):new Set;return ty({taskKey:t.taskKey,title:t.title,contextDir:t.contextDir,model:e,activated:i,staleKeys:s,...t.budgetTokens!==void 0?{budgetTokens:t.budgetTokens}:{}})}var ay=v(()=>{"use strict";G();Yh();Xh();Zh();ry()});import{mkdirSync as cy,readFileSync as ly,readdirSync as BT,writeFileSync as uy}from"node:fs";import{homedir as FT}from"node:os";import{dirname as GT,join as Vt}from"node:path";function HT(t){let e=Buffer.from(t,"utf-8");if(e.length<=cs)return t;let r=Math.floor(cs/4),n=cs-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}
|
|
785
785
|
|
|
786
|
-
\u2026 [${s} bytes elided \u2014 log capped at ${
|
|
786
|
+
\u2026 [${s} bytes elided \u2014 log capped at ${cs} bytes for upload] \u2026
|
|
787
787
|
|
|
788
|
-
${i}`}function
|
|
788
|
+
${i}`}function WT(){let t=[],e=!1,r=null,n=i=>{if(r){let s=r;r=null,s({value:i,done:!1})}else t.push(i)},o=()=>{if(r){let i=r;r=null,i({value:void 0,done:!0})}};return{push(i){e||n(i)},finalize(){e||(n({kind:"finalize"}),e=!0)},close(){e=!0,t.length=0,o()},iterable:{[Symbol.asyncIterator](){return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):e?Promise.resolve({value:void 0,done:!0}):new Promise(i=>{r=i})}}}}}}async function ko(t={}){Vi();let e=Ae(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,n=e.sandboxId,o=e.llm,i=Lg(t.profile,e.sandboxId,!!V("SANDBOX_CONFIG")),s=Vt(FT(),".codepipe","logs"),a=Vo("SANDBOX_LOG",i,s);if(a.enabled){let C=new Fr(a);zo(C),console.log(`[log] file logging \u2192 ${C.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${Ue} (protocol ${lt})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=Xg(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=rh();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let u=new an(e.hubUrl,e.token),p=!1,d=new AbortController,f=new Map,m=null,h=null,g=!1,w=()=>{let C=u.openControlSocket();return m=C,C.on("open",()=>{console.log("[ws] connected");let k={type:"sandbox_hello",platformVersion:Ue,protocolVersion:lt};C.send(JSON.stringify(k))}),C.on("message",k=>{let D=k.toString("utf-8"),A=null;try{let H=JSON.parse(D);H&&typeof H=="object"&&(A=H)}catch{}if(A&&A.type==="hello"){let H=A;h=Ao(H.protocolVersion);let q=h?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${H.platformVersion} (protocol ${H.protocolVersion}) \u2014 ${q}`),h&&(g=!1);return}if(A&&A.type==="pause_job"){let H=typeof A.jobId=="string"?A.jobId:"",q=H?f.get(H):void 0;q?(console.warn(`[ws] pause_job ${H} \u2014 aborting agent`),q.paused=!0,q.abort.abort()):console.log(`[ws] pause_job ${H} \u2014 not a running job, ignoring`),H&&C.send(JSON.stringify({type:"job_paused",jobId:H}));return}if(A&&(A.type==="chat_user_message"||A.type==="chat_finalize")){let H=typeof A.jobId=="string"?A.jobId:"",q=H?f.get(H):void 0;if(q?.chatInbox)if(A.type==="chat_user_message"){let Z=typeof A.text=="string"?A.text:"";Z.trim()&&q.chatInbox.push({kind:"user",text:Z})}else q.chatInbox.finalize();else console.log(`[ws] ${String(A.type)} ${H} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${D}`)}),C.on("close",(k,D)=>{console.log(`[ws] closed code=${k} reason=${D?.toString()||""}`),m===C&&(m=null),!p&&setTimeout(w,2e3)}),C.on("error",k=>console.warn(`[ws] error: ${k.message}`)),C},y=w(),x=async C=>{for(;!p;){if(h===!1){g||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${Ue}, protocol ${lt}) \u2014 not claiming jobs until versions align.`),g=!0),await new Promise(k=>setTimeout(k,5e3));continue}try{let k=await u.claim(d.signal,C);if(k.status===204)continue;if(k.status===401){console.error("[claim] 401 unauthorized \u2014 the HUB does not know this worker registration. It was removed; re-register with `codepipe up --reregister` (or `codepipe worker register --force`). exiting."),process.exitCode=1,p=!0;break}if(!k.ok){console.warn(`[claim:${C}] ${k.status} \u2014 backoff 5s`),await new Promise(A=>setTimeout(A,5e3));continue}let D=await k.json();await T(u,D)}catch(k){if(d.signal.aborted)break;let D=k instanceof Error?k.message:String(k);console.warn(`[claim:${C}] error: ${D} \u2014 backoff 5s`),await new Promise(A=>setTimeout(A,5e3))}}};async function T(C,k){let D={abort:new AbortController,paused:!1};k.role==="chat"&&(D.chatInbox=WT()),f.set(k.jobId,D);let A=!1,H=null,q=null,Z=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),qe=async()=>{try{await C.heartbeat(k.jobId)==="claim_lost"&&(A=!0,console.warn(`[job] ${k.jobId} claim lost \u2014 HUB sweeper took it`))}catch(X){let we=X instanceof Error?X.message:String(X);console.warn(`[job] ${k.jobId} heartbeat error: ${we}`)}};qe();let Ye=setInterval(()=>{qe()},Z),ge=new Date().toISOString();console.log(`[job] ${k.jobId} claimed \u2014 role=${k.role} task=${k.taskId} phase=${k.phase}`),console.log(`[job] ${k.jobId} prompt (${k.prompt.length} chars):`),console.log(E(k.prompt," \u2502 "));let _=[],M=null,L=400,z=25,O=500,S=()=>{if(M&&(clearTimeout(M),M=null),_.length===0)return;let X=_.splice(0,_.length),we=m;if(!we||we.readyState!==we.OPEN)return;let te={type:"agent_activity",jobId:k.jobId,taskId:k.taskId,projectId:k.projectId,role:k.role,phase:k.phase,events:X};try{we.send(JSON.stringify(te))}catch{}},$=X=>{_.push(X),_.length>O&&_.shift(),_.length>=z?S():M||(M=setTimeout(S,L))},j=k.role==="analysis"&&k.taskId.startsWith("draft::")?k.taskId.slice(7):null,Y=new Set,ke=null;try{if(!c){A||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:ge,finishedAt:new Date().toISOString()});return}if(!Qg(o,k.provider??null)){A||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${k.provider??"claude"}"`},startedAt:ge,finishedAt:new Date().toISOString()});return}let X=Gh(k.jobId);console.log(`[job] ${k.jobId} workspace=${X.dir}`);let we=R(k,r);H=we.gitCreds,q=we.contextGitCreds;let te=H?.env,ul=we.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:we.claudeOauthToken}:void 0,at=[],tr=null,bs=null;try{let B=k.role==="build"?"clone":"worktree";at=await Ih(X.dir,k.projectId,k.projectRepos,B,te,n);let U=await Ch(X.dir,k.projectId,k.contextRepo,"worktree",te,n);bs=U,tr=U?.workspacePath??null}catch(B){let U=B instanceof Error?B.message:String(B);console.warn(`[job] ${k.jobId} materialize failed: ${U}`),A||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${U}`},startedAt:ge,finishedAt:new Date().toISOString()}),X.dispose();return}let dl=async()=>{if(!k.deliveries||k.deliveries.length===0)return[];let B=k.contextRepo?.cloneUrl;if(!B||!te)throw new Error(B?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let U=[];for(let ee of k.deliveries){let re=at.find(be=>be.name===ee.name);if(re){if(k.role==="implement"&&ee.baseSha&&ee.baseSha!==re.baseSha){let be=await Th(re,ee.deliveryRef,ee.deliverySha,ee.baseSha,B,te);console.log(`[job] ${k.jobId} ${re.name}: base moved ${ee.baseSha.slice(0,10)} \u2192 ${re.baseSha.slice(0,10)} \u2014 re-applied delivery ${ee.deliverySha.slice(0,10)} (${be.length} conflicted file(s))`),be.length>0&&U.push(`- **${re.name}**:`,...be.map(Pn=>` - \`${Pn}\``));continue}await Sh(re,ee.deliveryRef,ee.deliverySha,B,te),console.log(`[job] ${k.jobId} ${re.name}: checked out delivery ${ee.deliverySha.slice(0,10)} for ${k.role}`)}}return U},$s=[];if(k.role==="build"||k.role==="implement"||k.role==="code-review")try{$s=await dl()}catch(B){let U=B instanceof Error?B.message:String(B);console.warn(`[job] ${k.jobId} delivery checkout failed: ${U}`),A||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${U}`},startedAt:ge,finishedAt:new Date().toISOString()}),X.dispose();return}let vs=k.role==="resolve-conflict"?k.metadata?.taskBranchByRepo??{}:{},pl="";if(k.role==="resolve-conflict"){if(!at.some(B=>vs[B.name])){let B="resolve-conflict job carries no task branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${k.jobId} ${B}`),A||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:B},startedAt:ge,finishedAt:new Date().toISOString()}),X.dispose();return}try{let B=[];for(let U of at){let ee=vs[U.name];if(!ee)continue;let re=await Oc(U,ee,te);console.log(`[job] ${k.jobId} ${U.name}: merged ${ee} into ${U.ref} \u2014 ${re.length} conflicted file(s)`),re.length>0?B.push(`- **${U.name}**:`,...re.map(be=>` - \`${be}\``)):B.push(`- **${U.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}pl=`
|
|
789
789
|
|
|
790
790
|
## Conflicts to resolve
|
|
791
791
|
|
|
792
792
|
`+(B.length>0?B.join(`
|
|
793
793
|
`):"(no task branches to merge)")+`
|
|
794
|
-
`}catch(B){let
|
|
794
|
+
`}catch(B){let U=B instanceof Error?B.message:String(B);console.warn(`[job] ${k.jobId} conflict merge failed: ${U}`),A||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${U}`},startedAt:ge,finishedAt:new Date().toISOString()}),X.dispose();return}}let xs=null;if(k.contextPack&&tr)try{let{assembleContextPack:B}=await Promise.resolve().then(()=>(ay(),sy)),U=B({contextDir:tr,taskKey:String(k.metadata?.trackerIssueKey??k.taskId.split(":")[1]??""),title:String(k.metadata?.taskTitle??""),repoDirs:new Map(at.map(ee=>[ee.name,ee.workspacePath]))});U?(cy(Vt(X.dir,"meta"),{recursive:!0}),uy(Vt(X.dir,"meta","context-pack.md"),U),xs=U,console.log(`[job] ${k.jobId} context pack: ${U.length} chars \u2192 meta/context-pack.md`)):console.log(`[job] ${k.jobId} context pack: model empty or no signal \u2014 skipped`)}catch(B){let U=B instanceof Error?B.message:String(B);console.warn(`[job] ${k.jobId} context pack failed (non-fatal): ${U}`)}let Bk=$s.length>0?`
|
|
795
795
|
|
|
796
796
|
## Base branch moved \u2014 conflicts to resolve
|
|
797
797
|
|
|
798
798
|
The base branch advanced since the previous iteration; its delivery was re-applied on top of the fresh base. These files now contain git conflict markers (\`<<<<<<<\`) \u2014 resolve them (keep both the base branch's changes and this task's changes) as part of this job:
|
|
799
799
|
|
|
800
|
-
|
|
800
|
+
`+$s.join(`
|
|
801
801
|
`)+`
|
|
802
|
-
`:"",
|
|
802
|
+
`:"",fl=I(b(k.prompt,at,tr),tr,k.taskId)+pl+Bk,An=[...at.map(B=>B.workspacePath),...tr?[tr]:[]];if(An.length>0&&console.log(`[job] ${k.jobId} --add-dir: ${An.join(", ")}`),ch("agent-request")){let B=Ji(cn(k.metadata??{})),U=lh(k.projectId,k.jobId,"agent-request",[`# Agent request \u2014 job ${k.jobId}`,"",`- project: ${k.projectId}`,`- task: ${k.taskId}`,`- role: ${k.role}`,`- model: ${k.model??"(backend default)"}`,`- add-dirs:${An.length>0?"":" (none)"}`,...An.map(ee=>` - ${ee}`),"","## Append-system-prompt (language directive)","","```",B,"```","","## Prompt","",fl,"",...xs?["## Context pack (meta/context-pack.md)","",xs]:["## Context pack","","(not generated for this job)"],""].join(`
|
|
803
|
+
`));U&&console.log(`[debug] ${k.jobId} agent request \u2192 ${U}`)}j&&(ke=setInterval(()=>{let U=m;if(!U||U.readyState!==U.OPEN)return;let ee;try{ee=BT(Vt(X.dir,"drafts")).filter(re=>re.endsWith(".json")).sort()}catch{return}for(let re of ee){if(Y.has(re))continue;if(Y.size>=Ru)break;let be;try{let Ve=JSON.parse(ly(Vt(X.dir,"drafts",re),"utf-8")),Rr=typeof Ve.localRef=="string"?Ve.localRef:"",Io=typeof Ve.title=="string"?Ve.title:"",Ss=typeof Ve.body=="string"?Ve.body:"";if(!Rr||!Io)continue;be={localRef:Rr,title:Io,body:Ss,...Ve.isEpic===!0?{isEpic:!0}:{},...Array.isArray(Ve.links)?{links:Ve.links}:{}}}catch{continue}Y.add(re);let Pn={type:"child_draft",jobId:k.jobId,projectId:k.projectId,draftId:j,child:be};try{U.send(JSON.stringify(Pn))}catch{}}},1500));try{let B={workspaceDir:X.dir,role:k.role,prompt:fl,addDirs:An,metadata:k.metadata??{},...k.model?{model:k.model}:{},...ul?{env:ul}:{},signal:D.abort.signal,onActivity:$},U=D.chatInbox?await c.run({...B,interactive:{inbox:D.chatInbox.iterable}}):await oh(c,B,{jobId:k.jobId,policy:l,onBeforeRetry:async()=>{X.clean();for(let ae of at)try{await bh(ae);let $e=vs[ae.name];k.role==="resolve-conflict"&&$e&&await Oc(ae,$e,te)}catch($e){let _n=$e instanceof Error?$e.message:String($e);console.warn(`[job] ${k.jobId} worktree reset failed (${ae.name}): ${_n}`)}try{await dl()}catch(ae){let $e=ae instanceof Error?ae.message:String(ae);console.warn(`[job] ${k.jobId} delivery re-checkout failed: ${$e}`)}},aborted:()=>A||D.paused}),ee=[];if(KT.has(k.role)&&at.length>0){let ae=k.metadata??{},$e=typeof ae.commitMessage=="string"?ae.commitMessage:`${k.taskId}: changes`,_n=k.contextRepo?.cloneUrl,gl=q?.env;if(!_n||!gl)throw new Error("delivery requested but "+(_n?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let Fk=k.taskId.includes(":")?k.taskId.slice(k.taskId.indexOf(":")+1):k.taskId;for(let bt of at){let jn=await $h(bt,$e);if(!jn){console.log(`[job] ${k.jobId} ${bt.name}: no changes \u2014 no delivery`);continue}let Ts=`codepipe/deliveries/${Fk}/${k.jobId}/${bt.name}`;await vh(bt,jn,Ts,_n,gl),ee.push({name:bt.name,deliveryRef:Ts,deliverySha:jn,baseSha:bt.baseSha}),console.log(`[job] ${k.jobId} ${bt.name}: delivered ${jn.slice(0,10)} \u2192 ${Ts}`);let hl=await xh(bt,jn);if(hl.trim().length>0){let Gk=Vt("display",`${bt.name}.diff`),yl=Vt(X.dir,Gk);cy(GT(yl),{recursive:!0}),uy(yl,hl)}}}if(k.role==="resolve-conflict"&&ee.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's diff-summary.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let re;k.role==="build"&&(re=_h(X.dir),console.log(`[job] ${k.jobId} build verdict: ok=${re.ok}`+(re.failedStep?` failedStep=${re.failedStep}`:"")));let be;k.role==="code-review"&&(be=Oh(X.dir),console.log(`[job] ${k.jobId} review verdict: approved=${be.approved}`));let Pn=U.artifactPaths.length>0?U.artifactPaths:X.listFiles(),Ve=Array.from(new Set(Pn)),Rr;if(bs)try{let ae=k.role==="index"?["adr/SOURCES.md"]:k.role==="backfill"?["adr"]:[],$e=await Ah(bs,ae);$e.length>0&&(Rr=$e,console.log(`[job] ${k.jobId} captured ${$e.length} knowledge file(s) for Context Repo`))}catch(ae){let $e=ae instanceof Error?ae.message:String(ae);console.warn(`[job] ${k.jobId} knowledge capture failed (non-fatal): ${$e}`)}let{artifacts:Io,omitted:Ss,dropped:ml}=Mh(X.dir,Ve);for(let ae of Ss)console.warn(`[job] ${k.jobId} artifact ${ae.path} (${ae.bytes} bytes) exceeded upload budget \u2014 content omitted`);ml.length>0&&console.warn(`[job] ${k.jobId} artifact listing truncated: ${ml.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let Co={jobId:k.jobId,status:"succeeded",artifacts:Io,...Rr?{contextWrites:Rr}:{},...ee.length>0?{deliveries:ee}:{},log:HT(U.log),startedAt:ge,finishedAt:new Date().toISOString(),usage:U.usage,...U.rateLimit?{rateLimit:U.rateLimit}:{},...re?{build:re}:{},...be?{review:be}:{}};if(A||D.paused)console.warn(`[job] ${k.jobId} skipping result upload \u2014 ${D.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await C.submitResult(Co),console.log(`[job] ${k.jobId} done \u2014 uploaded ${Co.artifacts.length} artifact(s):`);for(let ae of Co.artifacts){let $e=Buffer.from(ae.contentBase64,"base64").length;console.log(` \xB7 ${ae.path} (${$e} bytes)`)}Co.artifacts.length===0&&console.warn(`[job] ${k.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(B){let U=B instanceof Error?B.message:String(B);if(D.paused)console.log(`[job] ${k.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(A)console.warn(`[job] ${k.jobId} failed after claim lost (${U}) \u2014 skipping result upload`);else{let ee=nh(B),re=B instanceof qt,be=B instanceof Rt;console.warn(ee?`[job] ${k.jobId} failed: ${U} (Claude auth \u2014 token invalid/expired)`:re?`[job] ${k.jobId} failed: ${U} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:be?`[job] ${k.jobId} failed: ${U} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${k.jobId} failed: ${U}`),await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:U},startedAt:ge,finishedAt:new Date().toISOString(),...ee?{authError:!0}:{},...re?{buildInconclusive:!0}:{},...be?{reviewInconclusive:!0}:{}})}}finally{X.dispose()}}finally{clearInterval(Ye),ke&&clearInterval(ke),S(),D.chatInbox?.close(),f.delete(k.jobId),H?.cleanup(),q?.cleanup()}}function R(C,k){if(!C.credBundle)return{gitCreds:null,contextGitCreds:null};if(!k)return console.warn(`[job] ${C.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let D;try{D=JSON.parse(zr(k,C.credBundle).toString("utf-8"))}catch(Z){return console.warn(`[job] ${C.jobId} failed to open credBundle: ${Z instanceof Error?Z.message:String(Z)}`),{gitCreds:null,contextGitCreds:null}}let A=jc(D);A&&console.log(`[job] ${C.jobId} cred bundle opened \u2014 git creds configured`);let H=fh(D,C.contextRepo.cloneUrl),q={gitCreds:A,contextGitCreds:H};return D.claudeOauthToken&&(q.claudeOauthToken=D.claudeOauthToken),q}function E(C,k){return C.split(`
|
|
803
804
|
`).map(D=>k+D).join(`
|
|
804
|
-
`)}function b(C,k,D){let A=k[0]?.workspacePath??"";return C.replace(/\{\{codeDir\}\}/g,A).replace(/\{\{codeRoot\}\}/g,A?A.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,D??"")}function I(C,k,D){let A=C,H=D.includes("::")?"":D.split(":",2)[1]??"",q=Z=>{if(!k||!H)return"";try{return
|
|
805
|
-
[${C}] shutting down`),d.abort();let k=[...f.keys()];for(let H of f.values())H.abort.abort();let D=new AbortController,A=setTimeout(()=>D.abort(),3e3);(async()=>(await Promise.all(k.map(async H=>{try{await u.releaseJob(H,`sandbox ${C}`,D.signal),console.log(`[${C}] released job ${H}`)}catch(q){let Z=q instanceof Error?q.message:String(q);console.warn(`[${C}] release failed: ${Z} (sweeper will reclaim)`)}})),clearTimeout(A),y.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>N("SIGINT")),process.on("SIGTERM",()=>N("SIGTERM"));let
|
|
806
|
-
${e}`);let r=await
|
|
807
|
-
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=BT(await MT({message:"Claude OAuth token \u2014 blank to skip"})).trim();return e?(e.startsWith("sk-ant-")||it.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`."),e):(it.warn(t.farm?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"")}var ay,cy=x(()=>{"use strict";Zo();Kr();ue();oa();ay={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:KT,promptManual:HT,validate:Ut}});function ly(t){return ay}async function uy(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var dy=x(()=>{"use strict";cy()});async function wn(t,e,r){return e.host==="github"?qT(t,e,r):e.host==="gitlab"?ZT(t,e,r):tE(t,e,r)}async function py(t,e,r={}){let n=r.explain??!0,o=`${t.owner}/${t.name} not found on ${t.host}`;try{if(t.host==="github")return e.githubToken?(await Jt(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await fy(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 zt(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await my(e.gitlabToken,t):o}}return e.bitbucket?(await kn(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await gy(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 fy(t,e){let r=!1;try{r=(await Jt(t,"GET",`/users/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitHub repo ${e.owner}/${e.name} does not exist, or the token cannot see it \u2014 check the name; a fine-grained PAT must be scoped to this repo (and approved in the org)`:`GitHub owner "${e.owner}" not found \u2014 check the org/user spelling`}async function my(t,e){let r=!1;try{r=(await zt(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 gy(t,e){let r=!1;try{r=(await kn(t,"GET",`/workspaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`Bitbucket repo ${e.owner}/${e.name} does not exist in workspace "${e.owner}" (which the credential can see) \u2014 check the repo name, or the API token lacks access to it`:`Bitbucket workspace "${e.owner}" is not visible to this credential \u2014 check the workspace name and the token's read:repository:bitbucket scope`}async function Jt(t,e,r,n){let o={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};n!==void 0&&(o.body=JSON.stringify(n),o.headers["Content-Type"]="application/json");let i=await fetch(WT+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 qT(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 YT(n,e,r),i=await zT(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=Vr(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await JT(n,o.owner,o.name,a.path,i)||await XT(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 YT(t,e,r){let n=await Jt(t,"GET",`/repos/${e.owner}/${encodeURIComponent(e.name)}`);if(n.status===200&&n.data)return r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),{owner:n.data.owner.login,name:n.data.name,sshUrl:n.data.ssh_url};if(r.mode==="attach")throw new Error(`attach: ${await fy(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await VT(t,e.owner),i=o?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${o?"org":"user"})`);let s=await Jt(t,"POST",i,{name:e.name,private:!0,auto_init:!0,description:`CodePipe Context Repo for project ${e.name}`});if(!s.data)throw new Error("GitHub createRepo: empty response");return{owner:s.data.owner.login,name:s.data.name,sshUrl:s.data.ssh_url}}async function VT(t,e){let{status:r,data:n}=await Jt(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function zT(t,e,r){let{data:n}=await Jt(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function JT(t,e,r,n,o){let{status:i,data:s}=await Jt(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function XT(t,e,r,n,o,i,s,a){let c={message:i,content:Buffer.from(o,"utf-8").toString("base64"),branch:s};a&&(c.sha=a),await Jt(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function zt(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(QT+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 ZT(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 zt(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 my(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await zt(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 zt(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 zt(n,"POST","/projects",d);if(!f.data)throw new Error("GitLab create project: empty response");i=f.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Vr(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let f=(await zt(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 zt(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 kn(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(eE+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 tE(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 kn(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 gy(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 kn(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(p.status===404||!p.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);i=p.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Vr(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await kn(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 kn(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 WT,QT,eE,ss=x(()=>{"use strict";wr();WT="https://api.github.com";QT="https://gitlab.com/api/v4";eE="https://api.bitbucket.org/2.0"});function We(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=rE[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 rE,as=x(()=>{"use strict";rE={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as nE}from"node:crypto";import{existsSync as hy,mkdirSync as oE,readFileSync as yy,readdirSync as iE,rmSync as cs,writeFileSync as sE}from"node:fs";import{homedir as aE}from"node:os";import{dirname as cE,join as Mc}from"node:path";function ky(){return Mc(aE(),".codepipe","init-drafts")}function Uc(t){let e=nE("sha256").update(t).digest("hex").slice(0,16);return Mc(ky(),`${e}.json`)}function wy(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=lE)}function by(t){let e=Uc(t);if(!hy(e))return null;try{let r=JSON.parse(yy(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:wy(r.savedAt)?(cs(e,{force:!0}),null):r}catch{return null}}function Bc(t){cs(Uc(t),{force:!0})}function $y(){let t=ky();if(hy(t))for(let e of iE(t)){let r=Mc(t,e);try{let n=JSON.parse(yy(r,"utf-8"));wy(n.savedAt)&&cs(r,{force:!0})}catch{cs(r,{force:!0})}}}var lE,bn,vy=x(()=>{"use strict";lE=24*60*60*1e3;bn=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(){Bc(this.cwd)}persist(){let e=Uc(this.cwd);oE(cE(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};sE(e,JSON.stringify(r,null,2)+`
|
|
808
|
-
`,{mode:384})}}});function
|
|
809
|
-
`).map(n=>n.trim()).filter(Boolean);return
|
|
810
|
-
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`),
|
|
811
|
-
`))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function
|
|
805
|
+
`)}function b(C,k,D){let A=k[0]?.workspacePath??"";return C.replace(/\{\{codeDir\}\}/g,A).replace(/\{\{codeRoot\}\}/g,A?A.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,D??"")}function I(C,k,D){let A=C,H=D.includes("::")?"":D.split(":",2)[1]??"",q=Z=>{if(!k||!H)return"";try{return ly(Vt(k,"tasks",H,Z),"utf-8").trim()}catch{return""}};if(A.includes("{{planMd}}")||A.includes("{{solutionMd}}")){let Z=q("PLAN.md")||q("SOLUTION.md")||"(PLAN.md missing \u2014 proceed from the task description)";A=A.replace(/\{\{planMd\}\}/g,()=>Z),A=A.replace(/\{\{solutionMd\}\}/g,()=>Z)}if(A.includes("{{taskDescription}}")){let Z=q("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";A=A.replace(/\{\{taskDescription\}\}/g,()=>Z)}return A}let N=C=>{if(p)return;p=!0,console.log(`
|
|
806
|
+
[${C}] shutting down`),d.abort();let k=[...f.keys()];for(let H of f.values())H.abort.abort();let D=new AbortController,A=setTimeout(()=>D.abort(),3e3);(async()=>(await Promise.all(k.map(async H=>{try{await u.releaseJob(H,`sandbox ${C}`,D.signal),console.log(`[${C}] released job ${H}`)}catch(q){let Z=q instanceof Error?q.message:String(q);console.warn(`[${C}] release failed: ${Z} (sweeper will reclaim)`)}})),clearTimeout(A),y.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>N("SIGINT")),process.on("SIGTERM",()=>N("SIGTERM"));let F=[x("implementation")];e.planningLane!==!1?F.push(x("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(F)}var cs,KT,dy=v(()=>{"use strict";G();He();qs();Zg();Xi();ih();uh();_e();zi();mh();Ic();Ph();jh();Dh();Uh();Hh();cs=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),KT=new Set(["implement","resolve-conflict"])});var kn=v(()=>{"use strict";Ug();dy();zi()});import{cancel as qT,isCancel as fy,log as it,password as YT,text as VT}from"@clack/prompts";function zT(t){return fy(t)&&(qT("aborted"),process.exit(1)),typeof t=="string"?t:""}function JT(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function XT(t){let e=oa({redirectUri:na,challenge:t.challenge,state:t.state});it.message(`Open this URL, approve the access, and paste the code shown:
|
|
807
|
+
${e}`);let r=await VT({message:"Authorization code \u2014 blank to skip"});if(fy(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=Bd(r,t.state);return await ia({code:n,verifier:t.verifier,state:t.state,redirectUri:na})}catch(n){return it.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function QT(t){if(Hs()?.claude?.oauthToken&&!t.farm)return it.message("Claude: this machine already has a shared OAuth token \u2014 the project will use it (set a project-specific one later with `codepipe login`)."),"";if(process.env.CODEPIPE_CLAUDE_AUTOLOGIN==="0"||!process.stdout.isTTY)return null;it.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=ei(),n;try{n=await Fd({...r,openUrl:ur,log:i=>it.message(i)})}catch(i){it.warn(`Browser sign-in didn't complete (${i instanceof Error?i.message:String(i)}) \u2014 trying the code-paste fallback.`);let s=await XT(r);if(s===null)return null;n=s}let o=await Ut(n.oauthToken);return o==="invalid"?(it.warn("Claude rejected the obtained token (401) \u2014 falling back to manual entry."),null):(it.success(`Claude: logged in \u2014 ${JT(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function ZT(t){it.message("Claude login \u2014 pipeline agents run on your Claude subscription.\n Get a token: install Claude Code (https://claude.com/claude-code), run\n `claude setup-token` in a terminal and paste the result here."+(t.farm?`
|
|
808
|
+
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=zT(await YT({message:"Claude OAuth token \u2014 blank to skip"})).trim();return e?(e.startsWith("sk-ant-")||it.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`."),e):(it.warn(t.farm?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"")}var my,gy=v(()=>{"use strict";ti();Kr();ue();aa();my={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:QT,promptManual:ZT,validate:Ut}});function hy(t){return my}async function yy(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var ky=v(()=>{"use strict";gy()});async function bn(t,e,r){return e.host==="github"?tE(t,e,r):e.host==="gitlab"?cE(t,e,r):uE(t,e,r)}async function wy(t,e,r={}){let n=r.explain??!0,o=`${t.owner}/${t.name} not found on ${t.host}`;try{if(t.host==="github")return e.githubToken?(await Jt(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await by(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 zt(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await $y(e.gitlabToken,t):o}}return e.bitbucket?(await wn(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await vy(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 by(t,e){let r=!1;try{r=(await Jt(t,"GET",`/users/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitHub repo ${e.owner}/${e.name} does not exist, or the token cannot see it \u2014 check the name; a fine-grained PAT must be scoped to this repo (and approved in the org)`:`GitHub owner "${e.owner}" not found \u2014 check the org/user spelling`}async function $y(t,e){let r=!1;try{r=(await zt(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 vy(t,e){let r=!1;try{r=(await wn(t,"GET",`/workspaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`Bitbucket repo ${e.owner}/${e.name} does not exist in workspace "${e.owner}" (which the credential can see) \u2014 check the repo name, or the API token lacks access to it`:`Bitbucket workspace "${e.owner}" is not visible to this credential \u2014 check the workspace name and the token's read:repository:bitbucket scope`}async function Jt(t,e,r,n){let o={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};n!==void 0&&(o.body=JSON.stringify(n),o.headers["Content-Type"]="application/json");let i=await fetch(eE+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 tE(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 rE(n,e,r),i=await oE(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=Vr(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await iE(n,o.owner,o.name,a.path,i)||await sE(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 rE(t,e,r){let n=await Jt(t,"GET",`/repos/${e.owner}/${encodeURIComponent(e.name)}`);if(n.status===200&&n.data)return r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),{owner:n.data.owner.login,name:n.data.name,sshUrl:n.data.ssh_url};if(r.mode==="attach")throw new Error(`attach: ${await by(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await nE(t,e.owner),i=o?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${o?"org":"user"})`);let s=await Jt(t,"POST",i,{name:e.name,private:!0,auto_init:!0,description:`CodePipe Context Repo for project ${e.name}`});if(!s.data)throw new Error("GitHub createRepo: empty response");return{owner:s.data.owner.login,name:s.data.name,sshUrl:s.data.ssh_url}}async function nE(t,e){let{status:r,data:n}=await Jt(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function oE(t,e,r){let{data:n}=await Jt(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function iE(t,e,r,n,o){let{status:i,data:s}=await Jt(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function sE(t,e,r,n,o,i,s,a){let c={message:i,content:Buffer.from(o,"utf-8").toString("base64"),branch:s};a&&(c.sha=a),await Jt(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function zt(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(aE+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 cE(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 zt(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 $y(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await zt(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 zt(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 zt(n,"POST","/projects",d);if(!f.data)throw new Error("GitLab create project: empty response");i=f.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Vr(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let f=(await zt(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 zt(n,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:u}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}async function wn(t,e,r,n){let o={method:e,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${t.apiToken}`).toString("base64"),"User-Agent":"codepipe-cli"}};n?.json!==void 0?(o.body=JSON.stringify(n.json),o.headers["Content-Type"]="application/json"):n?.form&&(o.body=n.form);let i=await fetch(lE+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 uE(t,e,r){let n=r.bitbucket;if(!n)throw new Error("Bitbucket account email + API token required to provision a bitbucket-hosted Context Repo \u2014 provide them during `codepipe init`");let o=`/repositories/${e.owner}/${encodeURIComponent(e.name)}`,i,s=await wn(n,"GET",o);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await vy(n,e)} (attach joins an existing Context Repo and never creates one)`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let p=await wn(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(p.status===404||!p.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);i=p.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Vr(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await wn(n,"GET",`${o}/src/${encodeURIComponent(a)}/${p.path}?format=meta`)).status===404&&l.push(p);if(l.length>0){let p=new URLSearchParams;p.set("message","chore(codepipe): scaffold context repo files"),p.set("branch",a);for(let f of l)p.set(f.path,f.content);if((await wn(n,"POST",`${o}/src`,{form:p})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let u=i.links?.clone?.find(p=>p.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:u??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var eE,aE,lE,ls=v(()=>{"use strict";wr();eE="https://api.github.com";aE="https://gitlab.com/api/v4";lE="https://api.bitbucket.org/2.0"});function We(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=dE[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 dE,us=v(()=>{"use strict";dE={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as pE}from"node:crypto";import{existsSync as xy,mkdirSync as fE,readFileSync as Sy,readdirSync as mE,rmSync as ds,writeFileSync as gE}from"node:fs";import{homedir as hE}from"node:os";import{dirname as yE,join as Bc}from"node:path";function Ty(){return Bc(hE(),".codepipe","init-drafts")}function Fc(t){let e=pE("sha256").update(t).digest("hex").slice(0,16);return Bc(Ty(),`${e}.json`)}function Ey(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=kE)}function Ry(t){let e=Fc(t);if(!xy(e))return null;try{let r=JSON.parse(Sy(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Ey(r.savedAt)?(ds(e,{force:!0}),null):r}catch{return null}}function Gc(t){ds(Fc(t),{force:!0})}function Iy(){let t=Ty();if(xy(t))for(let e of mE(t)){let r=Bc(t,e);try{let n=JSON.parse(Sy(r,"utf-8"));Ey(n.savedAt)&&ds(r,{force:!0})}catch{ds(r,{force:!0})}}}var kE,$n,Cy=v(()=>{"use strict";kE=24*60*60*1e3;$n=class{constructor(e,r){this.cwd=e;this.answers=r?.answers?{...r.answers}:{}}answers;get(e){return this.answers[e]}set(e,r){this.answers[e]=r,this.persist()}delete(e){delete this.answers[e],this.persist()}async ask(e,r){if(e in this.answers)return this.answers[e];let n=await r();return this.set(e,n),n}clear(){Gc(this.cwd)}persist(){let e=Fc(this.cwd);fE(yE(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};gE(e,JSON.stringify(r,null,2)+`
|
|
809
|
+
`,{mode:384})}}});function Ay(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 Py(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 _y=v(()=>{"use strict"});import{existsSync as wE}from"node:fs";import{join as bE}from"node:path";import{simpleGit as $E}from"simple-git";function TE(t){let e=t.split("/");return e[e.length-1]??t}function jy(t){if(t.filter(r=>!xE.test(TE(r))).length>vE)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(SE.has(n))return!0}return!1}async function EE(t){try{let r=(await $E(t).raw(["ls-files"])).split(`
|
|
810
|
+
`).map(n=>n.trim()).filter(Boolean);return jy(r)}catch{return!1}}async function RE(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)?jy(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function Ny(t,e){for(let r of t)try{let n=e.localRoot!=null?bE(e.localRoot,r.mountAs??r.name):null;if(n&&wE(n)?await EE(n):await RE(r,e.tokens))return!0}catch{}return!1}var vE,xE,SE,Oy=v(()=>{"use strict";vE=3,xE=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,SE=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as Dy}from"node:fs";import{join as Ly}from"node:path";import{simpleGit as My}from"simple-git";async function bo(t,e,r={}){let n=r.log??IE,o=[];for(let i of e){let s=Ly(t,i.mountAs),a=Pu(i);if(!Dy(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 My().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let p=wo(u instanceof Error?u.message:String(u));n.warn(`clone failed for ${i.mountAs}: ${p}`),o.push({mountAs:i.mountAs,status:"error",detail:p})}continue}if(!Dy(Ly(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=My(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!CE(l,a)){n.warn(`${i.mountAs}/ origin (${wo(l)||"none"}) != expected (${wo(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:wo(l)});continue}if(r.dryRun){n.info(`would fetch ${i.mountAs}/`),o.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),o.push({mountAs:i.mountAs,status:"fetched"})}catch(u){let p=wo(u instanceof Error?u.message:String(u));n.warn(`fetch failed for ${i.mountAs}: ${p}`),o.push({mountAs:i.mountAs,status:"error",detail:p})}}return o}function CE(t,e){return Uy(t)===Uy(e)}function Uy(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function wo(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function By(t={}){let e=Se();e||(console.error("no .codepipe/ workspace found in this directory or any parent. run `codepipe init` first."),process.exit(1)),console.log(`codepipe sync \u2014 project ${e.spec.projectId} (${e.spec.repos.length} repos)`);let r=await bo(e.root,e.spec.repos,{dryRun:t.dryRun===!0});for(let n of r)console.log(` ${n.mountAs}: ${n.status}${n.detail?` \u2014 ${n.detail}`:""}`)}var IE,ps=v(()=>{"use strict";mt();IE={info:t=>console.log(t),warn:t=>console.warn(t)}});import{spawn as Gy}from"node:child_process";import{existsSync as Fy}from"node:fs";import{homedir as AE,hostname as PE}from"node:os";import{join as fs}from"node:path";async function _E(t,e,r){let n=Ae(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${ot(e)} points at a different HUB (${n.hubUrl}). Re-register it explicitly: codepipe worker register --hub ${t.hubUrl} --token \u2026 --force`);let o;try{o=await Jd(t.hubUrl.replace(/\/$/,""),n.token)}catch(i){return console.warn(`[up] could not verify the worker registration (${i instanceof Error?i.message:String(i)}) \u2014 continuing`),!1}if(o==="unsupported")return console.log(`[up] worker already registered as ${n.sandboxId} (${n.name})`),!1;if(o==="ok")return console.log(`[up] worker already registered as ${n.sandboxId} (${n.name})`),!1;if(!r.reregister)throw new Error(`the HUB no longer knows this worker registration (${n.sandboxId}) \u2014 it was removed on ${t.hubUrl}, but ${ot(e)} still holds its token.
|
|
811
|
+
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`),zu(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function jE(t,e,r){let n=Ae(e)!==null;if(!await _E(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 oi(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof K&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof K&&i.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):i instanceof K?i:new Error(`cannot reach the HUB at ${t.hubUrl} (${i instanceof Error?i.message:String(i)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await vr({hub:t.hubUrl,token:o,name:r.name??`${PE()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function NE(t,e){let r=Ae(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=je(r.sealPublicKey);if(!W(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=qo(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 Kc(t,e,r){await jE(t,e,r),NE(t.projectId,e)}function OE(t){return[...t?["--profile",t]:[],"worker","start"]}function DE(t){let e={...t};for(let r of Ws)delete e[r];return e}function Hc(t){let e=Gy(process.execPath,[t.entry,...OE(t.profile)],{stdio:["ignore","pipe","pipe"],env:DE(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
|
|
812
|
+
`))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function LE(t,e){let r=process.cwd(),n=fs(r,ft);if(Ko(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(Fy(n)){console.warn(`[up] ${n} exists but is not this project's workspace \u2014 the context stays under ~/.codepipe/profiles`);return}let o;try{o=await ne(t.hubUrl,t.cliToken,t.projectId)}catch(u){console.warn(`[up] could not fetch the project summary (${u instanceof Error?u.message:String(u)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await Yc(r);if(!Au(r,i?.parsed??null,o.repos)){console.log(`[up] this folder is neither empty nor a repo of ${t.projectId} \u2014 the context stays under ~/.codepipe/profiles`);return}let s=W(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await Yi({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=fs(AE(),".codepipe",e?fs("profiles",e,"context-config"):"context-config");if(pi(c.contextDir,l,a),!Fy(fs(c.contextDir,"project.yaml"))){qr(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};Jn(c.contextDir,yt(u,!0,s?.youtrack?.url)),console.log("[up] local project config seeded with defaults \u2014 review .codepipe/project.yaml")}console.log(`[up] project context materialized \u2192 ${n}`)}async function Wc(t){let{cfg:e,profile:r}=Wo(t.profile);if(t.debug){let f=typeof t.debug=="string"&&t.debug.trim()?t.debug.trim():"agent-request";process.env.CODEPIPE_DEBUG=f,console.log(`[up] debug logging on (${f}) \u2192 ~/.codepipe/debug/${e.projectId}/`)}await LE(e,r),await Kc(e,r,t);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(f,m)=>{let h=g=>w=>{for(let y of w.toString("utf-8").split(`
|
|
812
813
|
`))y.length>0&&g.write(`${m} ${y}
|
|
813
|
-
`)};f.stdout?.on("data",h(process.stdout)),f.stderr?.on("data",h(process.stderr))},i=(f,m)=>{let h=
|
|
814
|
+
`)};f.stdout?.on("data",h(process.stdout)),f.stderr?.on("data",h(process.stderr))},i=(f,m)=>{let h=Gy(process.execPath,[n,...m],{stdio:["ignore","pipe","pipe"],env:process.env});return o(h,f),h};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=Hc({entry:n,profile:r,onLine:f=>process.stdout.write(`[worker] ${f}
|
|
814
815
|
`)}),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,u=f=>{if(!l){l=!0,console.log(`
|
|
815
|
-
[up] ${f} \u2014 stopping both roles`);for(let{child:m}of c)m.exitCode===null&&m.kill(f);setTimeout(()=>{for(let{name:m,child:h}of c)h.exitCode===null&&(console.warn(`[up] ${m} did not stop \u2014 SIGKILL`),h.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:f,child:m})=>new Promise(h=>{m.on("exit",(g,w)=>h({name:f,code:g??(w?1:0)}))})),d=await Promise.race(p);l||(console.log(`[up] ${d.name} exited (code ${d.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(p),process.exit(d.code)}var
|
|
816
|
+
[up] ${f} \u2014 stopping both roles`);for(let{child:m}of c)m.exitCode===null&&m.kill(f);setTimeout(()=>{for(let{name:m,child:h}of c)h.exitCode===null&&(console.warn(`[up] ${m} did not stop \u2014 SIGKILL`),h.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:f,child:m})=>new Promise(h=>{m.on("exit",(g,w)=>h({name:f,code:g??(w?1:0)}))})),d=await Promise.race(p);l||(console.log(`[up] ${d.name} exited (code ${d.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(p),process.exit(d.code)}var qc=v(()=>{"use strict";He();kn();Le();St();Tc();wr();Re();ue();mt();$o()});var Xy={};Ir(Xy,{replCommand:()=>Xc});import{existsSync as Vy,mkdirSync as ME,readFileSync as UE,writeFileSync as BE}from"node:fs";import{homedir as FE}from"node:os";import{dirname as GE,join as zy}from"node:path";import*as vn from"node:readline";async function Xc(t={}){let e=Se();e||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let r=W(e.spec.projectId);r||(console.error(`no secrets for project ${e.spec.projectId} at ~/.codepipe/secrets/${e.spec.projectId}.json. run \`codepipe init\` or \`codepipe clone\` to set them up.`),process.exit(1)),Gn(r),console.log(`connected to ${r.hubUrl} as project ${e.spec.projectId}`),console.log("the CLI daemon and an embedded agent worker run in this session; /logs and /monitor show their output."),console.log("type /help to list commands. Ctrl+D or /quit to exit.");let n=yr(e.contextDir),o=Object.keys(n);o.length>0&&console.log(`
|
|
816
817
|
\u26A0 unfinished local apply: ${o.map(a=>`${a} (${n[a].repos.map(c=>c.mountAs).join(", ")})`).join("; ")}
|
|
817
|
-
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let i
|
|
818
|
-
`))}async function
|
|
819
|
-
`)}`:" (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}
|
|
820
|
-
`),t.unread+=1,
|
|
818
|
+
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let i=vn.createInterface({input:process.stdin,output:process.stdout,completer:KE,history:lR(),removeHistoryDuplicates:!0}),s={ws:e,secrets:r,connection:"connecting",rl:i,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};cp(a=>Qt(s,a)),s.daemon=Wi({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:a=>Qt(s,a),warn:a=>Qt(s,a)},onEvent:a=>nR(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 Kc(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=Hc({entry:c,profile:t.profile,onLine:u=>Qt(s,`[worker] ${u}`)});l.on("exit",(u,p)=>{s.workerExited=!0,!Jc&&Xt(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.`)}zc(s),i.prompt(),i.on("line",async a=>{let c=a.trim();if(c.length>0)try{if(await HE(s,c)){Yy(s);return}}catch(l){console.error(l instanceof Error?l.message:String(l))}s.unread=0,zc(s),i.prompt()}),i.on("close",()=>{Yy(s)})}function KE(t){let e=Ky.filter(r=>r.startsWith(t));return[e.length?e:Ky,t]}async function HE(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return WE(),!1;case"/status":return await qE(t),!1;case"/tasks":return await YE(t,n),!1;case"/task":return await VE(t,n),!1;case"/sync":return await zE(t),!1;case"/logs":return oR(t,n),!1;case"/monitor":return iR(t),!1;case"/apply":return await Wy(t,n,"apply"),!1;case"/unstash":return await Wy(t,n,"unstash"),!1;case"/applied":return await JE(t,n),!1;case"/abort":return await XE(t,n),!1;case"/approve":return await qy(t,n,"approve"),!1;case"/merge":return await qy(t,n,"merge"),!1;case"/login":return ZE(t,n),!1;case"/secret":return eR(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function WE(){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(`
|
|
819
|
+
`))}async function qE(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=Vy(zy(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function YE(t,e){let r=sR(e,"--phase");try{let n=await ep(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId),o=r?n.filter(i=>i.phase.toLowerCase()===r.toLowerCase()):n;if(o.length===0){console.log(" (no tasks)");return}for(let i of o)console.log(` ${i.key.padEnd(10)} ${i.phase.padEnd(16)} ${i.title}`)}catch(n){vo(n)}}async function VE(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await tp(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r);if(console.log(` ${r}: ${n.task.phase} \u2014 ${n.task.title}`),n.artifacts.length>0){console.log(" artifacts:");for(let o of n.artifacts)console.log(` ${o.path}`)}}catch(n){vo(n)}}async function zE(t){let e=await bo(t.ws.root,t.ws.spec.repos);for(let r of e)console.log(` ${r.mountAs}: ${r.status}${r.detail?` \u2014 ${r.detail}`:""}`)}async function Wy(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await wp(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function JE(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=yr(t.ws.contextDir)[r],i=aR(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?QE(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 rp(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);fa(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){vo(c)}}async function qy(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await op(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){vo(o)}}async function XE(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=cR(e,"--reason")||"local apply aborted";await $p(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await np(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){vo(o)}}function QE(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function ZE(t,e){let r=e.join(" ").trim();if(!r){console.log("usage: /login <claude-oauth-token>"),console.log(" get one with `claude setup-token`, then paste it here."),console.log(" (this line is scrubbed from history; takes effect on next SANDBOX reconnect)");return}t.secrets.claude={oauthToken:r},oe(t.secrets),console.log(" Claude OAuth token saved. It will be sealed into job bundles for SANDBOXes."),console.log(" Re-seal happens when a SANDBOX (re)connects; restart it if you need it now.")}function eR(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(`
|
|
820
|
+
`)}`:" (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}tR(t.secrets,n,i),oe(t.secrets),Gn(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}rR(t.secrets,n),oe(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function tR(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 rR(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 nR(t,e){switch(e.kind){case"connected":t.connection="connecting",Qt(t,"[hub] connected");break;case"registered":t.connection="registered",Qt(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Xt(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",Qt(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Xt(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Xt(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?Qt(t,`[hub] action ${e.actionType} done`):Xt(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break;case"local_applied":e.ok?Xt(t,`[apply] ${e.taskKey}: branch ${(e.branches??[]).join(", ")} created locally (your checkout is untouched) \u2014 review, push, then: /applied ${e.taskKey} --pr <url>`):Xt(t,`[apply] ${e.taskKey}: auto-apply failed \u2014 task stays in READY_TO_APPLY: ${e.error??"?"}`);break}}function Qt(t,e){t.logBuffer.push(e),t.logBuffer.length>Jy&&t.logBuffer.shift(),t.follow&&Xt(t,e)}function oR(t,e){let r=e[0];if(r==="follow"||r==="on"){Vc(t,!0);return}if(r==="off"){Vc(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(Jy,Number(r)||Hy)):Hy,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 iR(t){Vc(t,!t.follow)}function Vc(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Xt(t,e){vn.cursorTo(process.stdout,0),vn.clearLine(process.stdout,0),process.stdout.write(e+`
|
|
821
|
+
`),t.unread+=1,zc(t),t.rl.prompt(!0)}function zc(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}function Yy(t){if(Jc)return;Jc=!0,uR(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
|
|
821
822
|
bye.`),setTimeout(()=>process.exit(0),150);return}console.log(`
|
|
822
|
-
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
|
|
823
|
+
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 sR(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function aR(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 cR(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function vo(t){t instanceof K?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function lR(){if(!Vy(ms))return[];try{return UE(ms,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function uR(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{ME(GE(ms),{recursive:!0}),BE(ms,r.slice().reverse().join(`
|
|
823
824
|
`)+`
|
|
824
|
-
`)}catch{}}var
|
|
825
|
+
`)}catch{}}var ms,Ky,Jy,Hy,Jc,Qc=v(()=>{"use strict";xc();Re();ii();ue();mt();ps();qc();ma();ms=zy(FE(),".codepipe","history"),Ky=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Jy=500,Hy=40;Jc=!1});import{existsSync as xn,mkdirSync as Zy,readFileSync as ek,readdirSync as dR,writeFileSync as tk}from"node:fs";import{join as Sr,resolve as rk}from"node:path";import{setTimeout as Zc}from"node:timers/promises";import{cancel as pR,confirm as Sn,intro as nk,isCancel as rl,log as P,multiselect as fR,outro as el,password as xo,select as st,spinner as nl,text as fe}from"@clack/prompts";import{simpleGit as hs}from"simple-git";function le(t){pR(t),process.exit(1)}function Ee(t){return rl(t)&&le("aborted"),t}function se(t){return rl(t)&&le("aborted"),typeof t=="string"?t:""}async function ok(t={}){nk("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Iy();let r=Ry(e),n,o=!1;r&&Object.keys(r.answers).length>0?Ee(await Sn({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(P.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new $n(e,r),o=!0):(Gc(e),n=new $n(e)):n=new $n(e);let i=t.force===!0?null:await Yc(e),s=await n.ask("target",async()=>Ee(await st({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i,a?P.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):o&&n.get("contextRepo")!==void 0||sk(e,t.force===!0));let c=await n.ask("hubUrl",async()=>se(await fe({message:"HUB URL",placeholder:ct,initialValue:V("HUB_URL")??ct,validate:$=>$.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>Tn()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>En(c,l)),d=null;s==="farm"&&(d=await mR(c,u));let f=a?hR(a.parsed.repoName):"",m=await n.ask("projectId",async()=>se(await fe({message:"project id (slug)",placeholder:f||"acme",...f?{initialValue:f}:{},validate:$=>ir.test($.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),h=await n.ask("projectName",async()=>se(await fe({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:$=>$.trim().length>0?void 0:"required"})).trim()),g=await n.ask("language",()=>TR()),w=await n.ask("automationLevel",async()=>Ee(await st({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),y=s==="farm"?"auto":await n.ask("applyMode",async()=>Ee(await st({message:"how do approved changes reach your repo?",options:[{value:"auto",label:"auto \u2014 CodePipe pushes the branch and opens a PR"},{value:"local",label:"local \u2014 changes wait; you pull them into your checkout via the CLI REPL (/apply or /unstash), no push/PR"}],initialValue:"auto"}))),x=await n.ask("trackerProvider",async()=>Ee(await st({message:"task tracker",options:[{value:"internal",label:"built-in \u2014 CodePipe tracks tasks itself (no external tracker needed)"},{value:"youtrack",label:"YouTrack \u2014 connect an existing YouTrack project"}],initialValue:"internal"}))),T=x==="internal",R=null,E,b=!0;if(T){let $,j=nl();j.start("checking task-key prefixes on your account\u2026");try{$=await Xd(c,u,{excludeProjectId:m}),j.stop("prefixes checked")}catch{j.stop("could not reach the HUB",1),le("Could not verify the task-key prefix against your account \u2014 the HUB is unreachable right now. Prefix uniqueness is required, so init can't continue. Check your connection and re-run `codepipe init` later.")}let Y=$u(bu(h),$);E=await n.ask("trackerPrefix",async()=>se(await fe({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:Y,initialValue:Y,validate:ke=>{let X=ke.trim();if(!Dr.test(X))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if($.has(X.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else R=await n.ask("youtrack",()=>fk()),E=await n.ask("youtrackProjectKey",async()=>se(await fe({message:"YouTrack project key",placeholder:"DEV",validate:$=>$.trim().length>0?void 0:"required"})).trim()),b=await n.ask("youtrackWrites",async()=>Ee(await Sn({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let I=n.get("tokens")??{},N=()=>n.set("tokens",I),F=await n.ask("repos",()=>wR(I,l,a,{onCred:N,initial:n.get("reposPartial")??[],onProgress:$=>n.set("reposPartial",$)}));n.delete("reposPartial");let C=await bR(await n.ask("contextRepo",()=>uk(m,F,I,l)),m,F,I,l,N,$=>n.set("contextRepo",$)),{spec:k,mode:D}=C,A;T||(P.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),A=await n.ask("assigneeLogin",async()=>se(await fe({message:"your YouTrack login (the assignee value)",...R?.login?{initialValue:R.login}:{},validate:$=>$.trim().length>0?void 0:"required"})).trim()));let H=await n.ask("llmProvider",async()=>{for(;;){if(Ee(await st({message:"LLM provider",options:[{value:"claude",label:"Claude",hint:"recommended"},{value:"codex",label:"Codex",hint:"coming soon"}],initialValue:"claude"}))==="claude")return"claude";P.warn("Codex support is coming soon \u2014 pick Claude for now.")}}),q=H==="claude"?await n.ask("claudeToken",()=>yy(hy("claude"),{farm:s==="farm"})):"",Z;if(q){let $=await Md(q);if($){let j=Wl($);j&&(Z=j,P.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${j} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let qe={projectId:m,name:h,automationLevel:w,repos:F,trackerProvider:x,youtrackProjectKey:E,language:g};P.step(`${D==="attach"?"attaching to":"provisioning"} Context Repo ${k.owner}/${k.name} (${k.host})\u2026`);let Ye;try{Ye=await bn(qe,k,{...dk(I),youtrackWrites:b,...R?{trackerUrl:R.url}:{},mode:D,log:{info:$=>P.message($),warn:$=>P.warn($)}})}catch($){le(`Context Repo provisioning failed: ${$ instanceof Error?$.message:String($)}`)}qe.contextRepo=Ye,P.success(`Context Repo ready: ${Ye.owner}/${Ye.name}@${Ye.branch}`),P.step(`registering project on ${c}\u2026`);let ge;try{ge=await Bt(c,u,qe)}catch($){if($ instanceof K&&$.status===409){P.warn(`project ${m} already exists on HUB \u2014 reusing it`);try{ge=await ne(c,u,m)}catch(j){throw j instanceof K&&le(`HUB \u2192 ${j.status} ${j.message}`),j}}else if($ instanceof K&&$.status===401)n.delete("cliToken"),le("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if($ instanceof K)le(`HUB \u2192 ${$.status} ${$.message}`);else throw $}let _=ge.contextRepo??Ye;P.success(`project ${ge.projectId} ready (${ge.provisioningStatus})`);let M=await ER(_),L=R?{url:R.url,token:R.token}:void 0;if(s==="farm"){let $=d,j={...I,...M?{contextWrite:M}:{},...q?{claude:{oauthToken:q}}:{},...L?{youtrack:L}:{}},Y=I.github?.token;if(_.host==="github"&&Y)try{let te=xg(`devpipe-${m}`);await Sg(_,Y,te.publicKey,`devpipe-${m}`),j.contextSsh={privateKey:te.privateKey},P.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(te){P.warn(`could not set up Context Repo SSH deploy key (${te instanceof Error?te.message:String(te)}); the farm will fall back to the token path.`)}let ke={projectId:m,config:{hubUrl:c,cliToken:u,projectId:m},secrets:j,contextRepo:_,projectConfig:yt(qe,b,R?.url,A||void 0,"auto",H,Z)},X=Tt($.farm.publicKey,JSON.stringify(ke));P.step(`handing project ${m} to farm ${$.farm.name}\u2026`);let we;try{we=await ni(c,u,$.farm.farmId,{projectId:m,sealedBundle:X})}catch(te){throw te instanceof K&&le(te.status===409?`farm ${$.farm.name} is offline \u2014 start it and re-run.`:te.status===504?`farm ${$.farm.name} did not respond in time.`:`HUB \u2192 ${te.status} ${te.message}`),te}we.ok||le(`farm rejected provisioning: ${we.error??"unknown error"}`),await tl(c,u,m,_,Y,ge.repos,null,I),n.clear(),el(`done. project ${m} is now hosted on farm ${$.farm.name} (daemon ${we.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}pk(I),await ak(e,_.cloneUrl,_.branch),lk(e),a&&await kR(e);{let $=Sr(e,ft);qr($);let j=yt(qe,b,R?.url,A||void 0,y,H,Z),Y=Jn($,j);Y.length>0&&P.success(`local project config \u2192 .codepipe/{${Y.join(", ")}}`),kr(m,j,{info:ke=>P.message(ke),warn:ke=>P.warn(ke)})}await ck(e,ge.repos);let z={hubUrl:c,cliToken:u,projectId:m,...I,...M?{contextWrite:M}:{},...q?{claude:{oauthToken:q}}:{},...L?{youtrack:L}:{}};oe(z),vt({hubUrl:c,cliToken:u,projectId:m,accountEmail:p},m),P.success(`secrets \u2192 ${gt(m)}`),await tl(c,u,m,_,I.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,ge.repos,e,I),n.clear();let O=`${c}/?project=${encodeURIComponent(m)}`;ur(O),el(`done. your project on the dashboard (sign in there to work with it):
|
|
825
826
|
${O}
|
|
826
|
-
starting codepipe \u2014 the CLI daemon, an agent worker, and a command line. type /help for commands; Ctrl+D or /quit to exit (restart anytime with \`codepipe\` from this folder).`);let{replCommand:S}=await Promise.resolve().then(()=>(
|
|
827
|
+
starting codepipe \u2014 the CLI daemon, an agent worker, and a command line. type /help for commands; Ctrl+D or /quit to exit (restart anytime with \`codepipe\` from this folder).`);let{replCommand:S}=await Promise.resolve().then(()=>(Qc(),Xy));await S({})}async function tl(t,e,r,n,o,i=[],s=null,a={}){let c=await Py(n,o),l=!1;if(!c)try{l=await Ny(i,{localRoot:s,tokens:a})}catch{l=!1}let u=Ay({indexExists:c,localClones:s!==null,reposNonEmpty:l}),p=await fR({message:u.message,options:u.options,initialValues:u.initialValues,required:!1});if(rl(p))return;let d=new Set(p);if(d.has("map")&&s!==null)try{let f=Se(s);if(!f)throw new Error("workspace not found");let{bootstrapWorkspaceModel:m}=await Promise.resolve().then(()=>(po(),Hi)),h=await m(f,void 0,{onLog:g=>P.message(g)});P.success(`project map ready: ${h.events} task events mined from history`)}catch(f){P.warn(`could not build the project map: ${f instanceof Error?f.message:String(f)}. Registration is not affected \u2014 run \`codepipe model bootstrap\` later.`)}if(d.has("backfill"))try{let{jobId:f}=await Wn(t,e,r,{reindex:!1,backfill:!0});P.success(`retrospective architecture analysis queued (job ${f}); decision drafts will appear on the project card for review once a SANDBOX picks up the job.`)}catch(f){P.warn(`could not start the retrospective analysis: ${f instanceof Error?f.message:String(f)}. Registration is not affected.`)}if(d.has("index"))try{let{jobId:f}=await Wn(t,e,r,{reindex:u.reindex});P.success(`indexing queued (job ${f}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(f){P.warn(`could not start indexing: ${f instanceof Error?f.message:String(f)}. You can retry later \u2014 registration is not affected.`)}}async function mR(t,e){let r;try{r=await Yd(t,e)}catch(c){throw c instanceof K&&le(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&le("no farm is available to this account. Farms are assigned by the operator \u2014 ask them to assign one to you (or, if you run your own farm host: `codepipe-farm register --hub <url> --token <token>` and `codepipe-farm start`, then have the operator assign it).");let o=Ee(await st({message:"target farm",options:n.map(c=>({value:c.farmId,label:`${c.name}${c.online?"":" (offline)"} \u2014 ${c.keyFingerprint??"no fingerprint"}`}))})),i=n.find(c=>c.farmId===o),s;try{s=Ui(i.farmId,i.publicKey)}catch(c){le(c instanceof Error?c.message:String(c))}return Ee(await Sn({message:`confirm farm ${i.name} cred-channel fingerprint:
|
|
827
828
|
${s}
|
|
828
|
-
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||le("farm fingerprint not confirmed \u2014 aborting."),
|
|
829
|
+
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||le("farm fingerprint not confirmed \u2014 aborting."),Mi(i.farmId,s),{farm:i,fingerprint:s}}async function ik(t){nk(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();sk(e,t.force===!0);let r=se(await fe({message:"HUB URL",initialValue:V("HUB_URL")??ct,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await Tn(),{cliToken:o,accountEmail:i}=await En(r,n);P.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await ne(r,o,t.projectId)}catch(d){throw d instanceof K&&le(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||le(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await fk(),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 gs(d,l,f?.owner??s.contextRepo.owner,n,f?.repoName)}pk(l),await ak(e,s.contextRepo.cloneUrl,s.contextRepo.branch),lk(e);{let d=Sr(e,ft);qr(d);let f={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.trackerProvider?{trackerProvider:s.trackerProvider}:{},...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{},...s.language?{language:s.language}:{}},m=yt(f,!0,c?.url,void 0,"auto",s.llmProvider??pt),h=Jn(d,m);h.length>0&&P.success(`local project config \u2192 .codepipe/{${h.join(", ")}} (defaults \u2014 review and adjust)`),kr(t.projectId,m,{info:g=>P.message(g),warn:g=>P.warn(g)})}await ck(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};oe(p),vt({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),P.success(`secrets \u2192 ${gt(t.projectId)}`),await tl(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),el("done.")}function sk(t,e){if(!xn(t)){Zy(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=dR(t).filter(o=>!r.has(o));n.length!==0&&(e||le(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function Yc(t){if(!xn(Sr(t,".git")))return null;try{let r=(await hs(t).remote(["get-url","origin"])||"").toString().trim(),n=r?We(r):null;return n?{parsed:n,defaultBranch:await gR(t)}:null}catch{return null}}async function gR(t){let e=hs(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 hR(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return ir.test(e)?e:""}function yR(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function kR(t){let e=Sr(t,".gitignore"),r=xn(e)?ek(e,"utf-8"):"";if(yR(r))return;if(!Ee(await Sn({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){P.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
|
|
829
830
|
`)?"":`
|
|
830
|
-
`;
|
|
831
|
+
`;tk(e,r+o+`
|
|
831
832
|
# codepipe workspace (added by \`codepipe init\`)
|
|
832
833
|
.codepipe/
|
|
833
|
-
`),P.success(`.codepipe/ added to ${
|
|
834
|
+
`),P.success(`.codepipe/ added to ${rk(e)}`)}async function Tn(){let t="";try{t=(await hs().raw(["config","--global","user.email"])||"").trim()}catch{}return se(await fe({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function En(t,e){P.step(`connecting account ${e}`);let r;try{r=await Qd(t,e)}catch(s){throw s instanceof Hn&&le(`${e} is not authorized on this HUB yet.
|
|
834
835
|
Sign up at ${t} (registration form on the login screen),
|
|
835
836
|
wait for the operator to approve it by email, then re-run
|
|
836
837
|
\`codepipe init\` with the same email.`),s}r.accountCreated&&P.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&P.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(ur(r.authorizeUrl),P.message(`a browser tab was opened to confirm this CLI:
|
|
837
838
|
${r.authorizeUrl}
|
|
838
839
|
`+(r.emailSent?" (already signed in to the dashboard there? just click Connect)":` if you're signed in to the CodePipe dashboard, just click Connect \u2014
|
|
839
|
-
otherwise use the emailed link the page offers.`))),r.approvalRequired&&P.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),P.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let n=!1,o=Date.now(),i=o+15*6e4;for(;Date.now()<i;){let s;try{s=await
|
|
840
|
-
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await
|
|
840
|
+
otherwise use the emailed link the page offers.`))),r.approvalRequired&&P.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),P.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let n=!1,o=Date.now(),i=o+15*6e4;for(;Date.now()<i;){let s;try{s=await Zd(t,r.requestId)}catch(a){P.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await Zc(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&P.message(`connected as ${a} (the account confirmed in the browser).`),P.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&le("the HUB rejected this account"),s.status==="expired"&&le("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,P.message(`email confirmed. waiting for the operator to approve your account\u2026
|
|
841
|
+
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await Zc(5e3);continue}await Zc(2e3)}le("bootstrap timed out")}async function ak(t,e,r){let n=Sr(t,ft);if(xn(Sr(n,".git"))){P.message(`${n} already cloned \u2014 skipping`);return}xn(n)&&le(`${n} exists but is not a git repo \u2014 remove it and re-run`),Zy(n,{recursive:!0}),P.step(`cloning Context Repo \u2192 ${n}`);try{await hs().clone(e,n,["--branch",r]),P.success(`cloned ${e}`)}catch(o){le(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function ck(t,e){if(e.length===0)return;P.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(o=>({name:o.name,host:o.host,owner:o.owner,repoName:o.repoName,defaultBranch:o.defaultBranch??"main",mountAs:o.mountAs??o.name})),n=await bo(t,r,{log:{info:o=>P.message(o),warn:o=>P.warn(o)}});for(let o of n)P.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function lk(t){let e=Sr(t,ft,".gitignore"),r="";if(xn(e)&&(r=ek(e,"utf-8")),Qy.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
|
|
841
842
|
`)||r.length===0?"":`
|
|
842
|
-
`,i=
|
|
843
|
+
`,i=Qy.join(`
|
|
843
844
|
`)+`
|
|
844
|
-
`;
|
|
845
|
-
`:"")+i),P.message(`appended runtime entries to ${
|
|
845
|
+
`;tk(e,r+o+(r?`
|
|
846
|
+
`:"")+i),P.message(`appended runtime entries to ${rk(e)}`)}async function wR(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;P.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await gs(s.host,t,s.owner,e,s.repoName),i?.();let c=se(await fe({message:"repo logical name (used inside Context Repo paths)",placeholder:s.repoName,initialValue:s.repoName,validate:u=>u.trim().length>0?void 0:"required"})).trim(),l=se(await fe({message:"default branch",placeholder:a,initialValue:a,validate:u=>u.trim().length>0?void 0:"required"})).trim();o.push({name:c,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:l,mountAs:"."}),n.onProgress?.(o)}for(;Ee(await Sn({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=se(await fe({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:f=>!f||!f.trim()||We(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=We(a);P.message(`${c.host}: ${c.owner}/${c.repoName}`),await gs(c.host,t,c.owner,e,c.repoName),i?.();let l=se(await fe({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:f=>f.trim().length>0?void 0:"required"})).trim(),u=se(await fe({message:"default branch (optional)",placeholder:"main"})).trim(),p=se(await fe({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),d={name:l,host:c.host,owner:c.owner,repoName:c.repoName};u&&(d.defaultBranch=u),p&&p!==l&&(d.mountAs=p),o.push(d),n.onProgress?.(o)}return o}async function uk(t,e,r,n){P.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let o=Ee(await st({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));o==="attach"&&P.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let i=e[0]?.host,s=e[0]?.owner,a;if(i&&s){let c=se(await fe({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:$t(t),validate:u=>{let p=(u??"").trim();if(!p)return"required";if(!We(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=We(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await $R(),l=se(await fe({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=se(await fe({message:"Context Repo name",placeholder:$t(t),initialValue:$t(t),validate:p=>p.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:o}}function dk(t){return{githubToken:t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:t.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:t.bitbucket??Br()}}async function bR(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await gs(c.host,n,c.owner,o),i?.();let u=nl();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let p=await wy(c,dk(n),{explain:l==="attach"});if(p.found===!0)return u.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(p.found==="unknown")return u.stop(`could not check ${c.owner}/${c.name} (${p.detail}) \u2014 continuing`,1),a;if(l==="create")return u.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;u.stop(p.detail,1);let d=Ee(await st({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(d==="abort"&&le("aborted"),d==="create")return a={spec:c,mode:"create"},s(a),a;a=await uk(e,r,n,o),s(a)}}async function $R(){return Ee(await st({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function So(t,e){let r=nl();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 pk(t){to(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),ro(t.gitlab?.token??process.env.GITLAB_TOKEN),no(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function gs(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await vR(r);i?e.github=i:P.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let i=await xR(r,n,o);i?e.bitbucket=i:P.warn("no Bitbucket API token \u2014 git falls back to this machine's SSH keys / BITBUCKET_* env; private repos won't clone over HTTPS and PRs won't open.")}else{let i=await SR();i?e.gitlab=i:P.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function vR(t){for(;;){let e=se(await xo({message:`GitHub PAT \u2014 blank to skip
|
|
846
847
|
classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
|
|
847
848
|
fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
|
|
848
849
|
if org: approve token in org Settings \u2192 Personal access tokens.
|
|
849
850
|
(Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo;
|
|
850
|
-
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await
|
|
851
|
+
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await So("GitHub",()=>jt(e,t?{owner:t}:void 0)))return{token:e};P.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function xR(t,e,r){for(P.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
|
|
851
852
|
How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
|
|
852
853
|
'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes:
|
|
853
854
|
read:repository:bitbucket + write:repository:bitbucket +
|
|
854
855
|
read:pullrequest:bitbucket + write:pullrequest:bitbucket
|
|
855
856
|
\u2014 write scopes do NOT include read: pick BOTH scopes of each pair
|
|
856
857
|
(+ admin:repository:bitbucket if this token will provision the Context Repo).
|
|
857
|
-
The token is shown ONCE \u2014 copy it right away.`);;){let n=se(await fe({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:i=>!i||!i.trim()||i.includes("@")?void 0:"must be an email"})).trim();if(!n)return;let o=se(await
|
|
858
|
-
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await
|
|
858
|
+
The token is shown ONCE \u2014 copy it right away.`);;){let n=se(await fe({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:i=>!i||!i.trim()||i.includes("@")?void 0:"must be an email"})).trim();if(!n)return;let o=se(await xo({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){P.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await So("Bitbucket",async()=>{let i=await Nt(n,o,t);if(t&&r){let s=await Zo(n,o,t,r);if(s)throw new Error(s)}return i}))return{email:n,apiToken:o};P.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function SR(){for(;;){let t=se(await xo({message:`GitLab PAT \u2014 blank to skip
|
|
859
|
+
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await So("GitLab",()=>Ot(t))){let e=await sd(t);return e&&P.warn(e),{token:t}}P.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function TR(){let t="__other__",e=async()=>se(await fe({message:"language name (in English, e.g. Ukrainian)",validate:s=>{let a=s.trim();if(a.length===0)return"required";if(a.length>40)return`\u2264 ${40} chars`}})).trim(),r=Ee(await st({message:"project language",options:[...Mn.map(s=>({value:s,label:s==="English"?"English (default)":s})),{value:t,label:"other\u2026"}],initialValue:"English"})),n=r===t?await e():r;if(n==="English")return{primary:n,context:n,tasks:n,docs:n,code_comments:n,chat:or};let o=[{key:"context",label:"context documents (knowledge, ADRs, task artifacts)",initial:n},{key:"tasks",label:"tracker issues the agent drafts",initial:n},{key:"docs",label:"documentation in the project repos",initial:n},{key:"code_comments",label:"code comments",initial:n},{key:"chat",label:"chat with the agent",initial:or}],i={primary:n};for(let s of o){let a=new Set,c=[s.initial,n,"English",or].filter(u=>a.has(u)?!1:(a.add(u),!0)).map(u=>({value:u,label:u===or?"auto \u2014 mirror the language of the user's material":u}));c.push({value:t,label:"other\u2026"});let l=Ee(await st({message:`language for ${s.label}`,options:c,initialValue:s.initial}));i[s.key]=l===t?await e():l}return i}async function ER(t){if(Ee(await Sn({message:`Issue a separate context-write token (scoped to the Context Repo only)?
|
|
859
860
|
Without it the SANDBOX pushes delivery commits with the project ${t.host}
|
|
860
861
|
credential. A scoped token hardens setups where the SANDBOX runs outside
|
|
861
862
|
your trusted network.`,initialValue:!1})))for(t.host==="github"?P.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
|
|
862
863
|
permissions Contents: Read and write + Workflows: Read and write (Workflows is
|
|
863
864
|
required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):P.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
|
|
864
|
-
(${t.host==="gitlab"?"project access token, 'write_repository' scope":"Bitbucket repository access token, Repositories: Read & write \u2014 the only Bitbucket credential scopeable to a single repo; an account-wide API token would defeat the scoping"}).`);;){let r=se(await
|
|
865
|
-
[${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}yn();Le();Re();async function iy(t={profile:void 0}){let e=Fe(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=ei(e.hubUrl,e.cliToken),n=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let u=l.toString("utf-8");if(s.push(`msg:${u}`),u!=="pong")try{let p=JSON.parse(u);p.type==="registered"?(a=!!p.ok,clearTimeout(c),r.send("ping")):p.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,u)=>{s.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of n.events)console.log(` ${i}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await ne(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=Ae(t.profile);o?o.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${o.sandboxId} (${o.name}), llm=${o.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${o.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}wo();import{readFileSync as wR}from"node:fs";G();Le();St();ss();wr();Dt();lr();Re();ue();function me(t){throw new Error(t)}function xe(t,e){return(typeof t!="string"||t.trim().length===0)&&me(`config: '${e}' must be a non-empty string`),t.trim()}function xo(t,e){if(t==null)return;typeof t!="string"&&me(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function bR(t){(!t||typeof t!="object")&&me("config: expected a JSON object");let e=t,r=xe(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||me("config: 'hubUrl' must start with http(s)://");let n=xe(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&me("config: 'project' is required");let i=o,s=xe(i.id,"project.id");ir.test(s)||me("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=xe(i.name,"project.name"),c=xe(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&me("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||me("config: 'project.repos' must be an array");let u=l.map((y,v)=>{(!y||typeof y!="object")&&me(`config: project.repos[${v}] must be an object`);let T=y,R=xe(T.host,`project.repos[${v}].host`);R!=="github"&&R!=="bitbucket"&&R!=="gitlab"&&me(`config: project.repos[${v}].host must be 'github', 'bitbucket' or 'gitlab'`);let E={name:xe(T.name,`project.repos[${v}].name`),host:R,owner:xe(T.owner,`project.repos[${v}].owner`),repoName:xe(T.repoName,`project.repos[${v}].repoName`)},b=xo(T.defaultBranch,`project.repos[${v}].defaultBranch`);b&&(E.defaultBranch=b);let I=xo(T.mountAs,`project.repos[${v}].mountAs`);return I&&(E.mountAs=I),E}),p=i.contextRepo;(!p||typeof p!="object")&&me("config: 'project.contextRepo' is required");let d=p,f=xo(d.host,"project.contextRepo.host")??"github";f!=="github"&&f!=="bitbucket"&&f!=="gitlab"&&me("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let m={host:f,owner:xe(d.owner,"project.contextRepo.owner"),name:xo(d.name,"project.contextRepo.name")??$t(s)},h={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:m}},g=xo(i.youtrackProjectKey,"project.youtrackProjectKey");if(g&&(h.project.youtrackProjectKey=g),i.index!==void 0&&(typeof i.index!="boolean"&&me("config: 'project.index' must be a boolean"),h.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&me("config: 'project.youtrackWrites' must be a boolean"),h.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let y=xe(i.llmProvider,"project.llmProvider");y==="codex"&&me(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),y!=="claude"&&me("config: 'project.llmProvider' must be 'claude'"),h.project.llmProvider=y}let w=e.secrets;if(w!==void 0){(typeof w!="object"||w===null)&&me("config: 'secrets' must be an object");let y=w,v={};if(y.github){let T=y.github;v.github={token:xe(T.token,"secrets.github.token")}}if(y.bitbucket){let T=y.bitbucket;v.bitbucket={email:xe(T.email,"secrets.bitbucket.email"),apiToken:xe(T.apiToken,"secrets.bitbucket.apiToken")}}if(y.gitlab){let T=y.gitlab;v.gitlab={token:xe(T.token,"secrets.gitlab.token")}}if(y.youtrack){let T=y.youtrack;v.youtrack={url:xe(T.url,"secrets.youtrack.url").replace(/\/$/,""),token:xe(T.token,"secrets.youtrack.token")}}if(y.contextWrite){let T=y.contextWrite;v.contextWrite={token:xe(T.token,"secrets.contextWrite.token")}}h.secrets=v}return h}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 jt(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 Nt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await Xo(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 Ot(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Mt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function ak(t){let e=!t.configPath||t.configPath==="-"?await $R():wR(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){me(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=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 wn(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??Br(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){me(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let u;try{u=await Bt(o,i,a)}catch(d){if(d instanceof K&&d.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await ne(o,i,s.id);else if(d instanceof K)me(`HUB \u2192 ${d.status} ${d.message}`);else throw d}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let p={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(oe(p),vt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${gt(s.id)}`),kr(s.id,yt(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,"auto",s.llmProvider??pt),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await Kn(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`)}Le();ue();import{cancel as ck,intro as lk,isCancel as uk,log as rl,outro as xR,password as dk}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 pk(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){lk("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),rl.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await dk({message:"Claude OAuth token"});uk(i)&&(ck("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Yu({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Wo()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Fe(t.profile);if(!e){lk(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),rl.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await dk({message:"Claude OAuth token"});uk(i)&&(ck("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=W(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},oe(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(rl.success("Claude OAuth token saved."),xR("It will be sealed into job bundles when a SANDBOX (re)connects."))}lo();G();Le();St();ss();wr();as();Re();ue();import{cancel as TR,confirm as ER,intro as RR,isCancel as fk,log as Pe,outro as IR,select as mk,text as Zt}from"@clack/prompts";function gk(t){TR(t),process.exit(1)}function En(t){return fk(t)&&gk("aborted"),t}function So(t){return fk(t)&&gk("aborted"),typeof t=="string"?t:""}async function CR(t,e){let r=En(await mk({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=So(await Zt({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=So(await Zt({message:"Context Repo name",placeholder:$t(t),initialValue:$t(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function hk(t={profile:void 0}){let e=Fe(t.profile);RR(`codepipe project add \u2192 ${e.hubUrl}`);let r=En(await Zt({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>ir.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=En(await Zt({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=En(await mk({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=En(await Zt({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=En(await ER({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=So(await Zt({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()||We(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=We(d);Pe.message(`${f.host}: ${f.owner}/${f.repoName}`);let m=So(await Zt({message:"repo logical name (used inside Context Repo paths)",placeholder:f.repoName,initialValue:f.repoName,validate:w=>w.trim().length>0?void 0:"required"})).trim(),h=So(await Zt({message:"default branch (optional)",placeholder:"main"})).trim(),g={name:m,host:f.host,owner:f.owner,repoName:f.repoName};h&&(g.defaultBranch=h),a.push(g)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await CR(r,a),u=W(e.projectId);Pe.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await wn(c,l,{githubToken:u?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:u?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:u?.bitbucket??Br(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:d=>Pe.message(d),warn:d=>Pe.warn(d)}})}catch(d){Pe.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,Pe.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await Bt(e.hubUrl,e.cliToken,c);Pe.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),kr(r,yt(c,s,u?.youtrack?.url),{info:f=>Pe.message(f),warn:f=>Pe.warn(f)}),d.contextRepo&&(Pe.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),Pe.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&Pe.error(` error: ${d.provisioningError}`),IR("done")}catch(d){d instanceof K?(Pe.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&Pe.message(JSON.stringify(d.payload,null,2))):Pe.error(d instanceof Error?d.message:String(d)),process.exit(1)}}yn();Le();Re();ue();mt();wo();import{existsSync as AR,rmSync as PR}from"node:fs";import{confirm as _R,intro as jR,isCancel as NR,log as er,outro as OR,spinner as DR}from"@clack/prompts";function wt(t){er.error(t),process.exit(1)}var yk=t=>t.trim().replace(/\/+$/,"");async function kk(t){jR("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Se()?.spec.projectId??void 0;e||wt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=Qe(e);r||wt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=yk(r.hubUrl),o=r.projectId,i=yk(t.hub);i.startsWith("http")||wt("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&wt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let w=DR();w.start(`reading project ${o} from ${n}\u2026`);try{l=await ne(n,r.cliToken,o),w.stop(`read project ${o} (${l.name})`)}catch(y){throw w.stop("could not read the source project",1),y instanceof K&&wt(`source HUB ${n} \u2192 ${y.status} ${y.message}. The source HUB must be reachable with a valid token to move a project.`),y}}l.contextRepo||wt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=W(o),p=(t.account??r.accountEmail??await Sn()).trim().toLowerCase();if(er.message(`move project '${o}'
|
|
865
|
+
(${t.host==="gitlab"?"project access token, 'write_repository' scope":"Bitbucket repository access token, Repositories: Read & write \u2014 the only Bitbucket credential scopeable to a single repo; an account-wide API token would defeat the scoping"}).`);;){let r=se(await xo({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await So("contextWrite",()=>RR(r,t)))return{token:r};P.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function RR(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 fk(){for(;;){let t=se(await fe({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let n=r.trim();if(!n)return"required";if(!n.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=se(await xo({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await So("YouTrack",()=>Mt({baseUrl:t,token:e}))){let r=await bd({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}P.warn("re-enter the YouTrack URL / token.")}}var Qy,$o=v(()=>{"use strict";_e();G();He();ky();ti();Le();St();wr();Kr();ls();Sc();us();Dt();lr();Cy();Re();_y();Oy();ac();bi();ue();ps();mt();Qy=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});G();_e();Le();import{Command as sI}from"commander";Fo();import{homedir as Du}from"node:os";import{join as Lu}from"node:path";function Mu(){ar(Lu(Du(),".devpipe"),Lu(Du(),".codepipe"))}Le();ue();async function Xu(t){let e=t.profile??t.project;t.profile&&t.profile!==t.project&&(console.error(`--profile (${t.profile}) must equal --project (${t.project}). Profile id is the project id.`),process.exit(1));let r=Qe(e);r&&!t.force&&(console.error(`already configured at ${Mr(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");vt({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...W(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};oe(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${Mr(e)}`)}qs();Le();xc();Re();ue();St();Tc();mt();bi();import{homedir as Ec}from"node:os";import{join as fo}from"node:path";async function _g(t={profile:void 0}){let{cfg:e,profile:r}=Wo(t.profile),n=W(e.projectId);n&&Gn(n),to(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),ro(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),no(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=fo(Ec(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Vo("CLI_LOG",i,o);if(s.enabled){let d=new Fr(s);zo(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=Ko(e.projectId);if(c&&(a={root:c.root,contextDir:c.contextDir,repos:c.spec.repos},console.log(`[ctx] workspace found at ${c.root} \u2014 using its Context Repo clone`)),!a){let d=fo(Ec(),".codepipe",r?fo("profiles",r,"context"):"context");if(await ua(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await Ag(()=>Yi({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 ua(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let f=fo(Ec(),".codepipe",r?fo("profiles",r,"context-config"):"context-config");pi(a.contextDir,f,{info:m=>console.log(m),warn:m=>console.warn(m)})}}let l=Wi(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(`
|
|
866
|
+
[${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}kn();Le();Re();async function py(t={profile:void 0}){let e=Fe(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=ri(e.hubUrl,e.cliToken),n=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let u=l.toString("utf-8");if(s.push(`msg:${u}`),u!=="pong")try{let p=JSON.parse(u);p.type==="registered"?(a=!!p.ok,clearTimeout(c),r.send("ping")):p.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,u)=>{s.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of n.events)console.log(` ${i}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await ne(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=Ae(t.profile);o?o.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${o.sandboxId} (${o.name}), llm=${o.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${o.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}$o();import{readFileSync as IR}from"node:fs";G();Le();St();ls();wr();Dt();lr();Re();ue();function me(t){throw new Error(t)}function xe(t,e){return(typeof t!="string"||t.trim().length===0)&&me(`config: '${e}' must be a non-empty string`),t.trim()}function To(t,e){if(t==null)return;typeof t!="string"&&me(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function CR(t){(!t||typeof t!="object")&&me("config: expected a JSON object");let e=t,r=xe(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||me("config: 'hubUrl' must start with http(s)://");let n=xe(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&me("config: 'project' is required");let i=o,s=xe(i.id,"project.id");ir.test(s)||me("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=xe(i.name,"project.name"),c=xe(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&me("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||me("config: 'project.repos' must be an array");let u=l.map((y,x)=>{(!y||typeof y!="object")&&me(`config: project.repos[${x}] must be an object`);let T=y,R=xe(T.host,`project.repos[${x}].host`);R!=="github"&&R!=="bitbucket"&&R!=="gitlab"&&me(`config: project.repos[${x}].host must be 'github', 'bitbucket' or 'gitlab'`);let E={name:xe(T.name,`project.repos[${x}].name`),host:R,owner:xe(T.owner,`project.repos[${x}].owner`),repoName:xe(T.repoName,`project.repos[${x}].repoName`)},b=To(T.defaultBranch,`project.repos[${x}].defaultBranch`);b&&(E.defaultBranch=b);let I=To(T.mountAs,`project.repos[${x}].mountAs`);return I&&(E.mountAs=I),E}),p=i.contextRepo;(!p||typeof p!="object")&&me("config: 'project.contextRepo' is required");let d=p,f=To(d.host,"project.contextRepo.host")??"github";f!=="github"&&f!=="bitbucket"&&f!=="gitlab"&&me("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let m={host:f,owner:xe(d.owner,"project.contextRepo.owner"),name:To(d.name,"project.contextRepo.name")??$t(s)},h={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:m}},g=To(i.youtrackProjectKey,"project.youtrackProjectKey");if(g&&(h.project.youtrackProjectKey=g),i.index!==void 0&&(typeof i.index!="boolean"&&me("config: 'project.index' must be a boolean"),h.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&me("config: 'project.youtrackWrites' must be a boolean"),h.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let y=xe(i.llmProvider,"project.llmProvider");y==="codex"&&me(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),y!=="claude"&&me("config: 'project.llmProvider' must be 'claude'"),h.project.llmProvider=y}let w=e.secrets;if(w!==void 0){(typeof w!="object"||w===null)&&me("config: 'secrets' must be an object");let y=w,x={};if(y.github){let T=y.github;x.github={token:xe(T.token,"secrets.github.token")}}if(y.bitbucket){let T=y.bitbucket;x.bitbucket={email:xe(T.email,"secrets.bitbucket.email"),apiToken:xe(T.apiToken,"secrets.bitbucket.apiToken")}}if(y.gitlab){let T=y.gitlab;x.gitlab={token:xe(T.token,"secrets.gitlab.token")}}if(y.youtrack){let T=y.youtrack;x.youtrack={url:xe(T.url,"secrets.youtrack.url").replace(/\/$/,""),token:xe(T.token,"secrets.youtrack.token")}}if(y.contextWrite){let T=y.contextWrite;x.contextWrite={token:xe(T.token,"secrets.contextWrite.token")}}h.secrets=x}return h}async function AR(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function PR(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await jt(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 Nt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await Zo(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 Ot(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Mt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function mk(t){let e=!t.configPath||t.configPath==="-"?await AR():IR(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){me(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=CR(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 PR(n));let a={projectId:s.id,name:s.name,automationLevel:s.automationLevel,repos:s.repos};s.youtrackProjectKey&&(a.youtrackProjectKey=s.youtrackProjectKey),console.log(`provisioning Context Repo ${s.contextRepo.owner}/${s.contextRepo.name} (${s.contextRepo.host})\u2026`);let c=n.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,l;try{l=await bn(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??Br(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){me(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let u;try{u=await Bt(o,i,a)}catch(d){if(d instanceof K&&d.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await ne(o,i,s.id);else if(d instanceof K)me(`HUB \u2192 ${d.status} ${d.message}`);else throw d}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let p={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(oe(p),vt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${gt(s.id)}`),kr(s.id,yt(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,"auto",s.llmProvider??pt),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await Wn(o,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${d}); runs once a SANDBOX claims it.`)}catch(d){console.warn(`could not enqueue index job: ${d instanceof Error?d.message:String(d)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}Le();ue();import{cancel as gk,intro as hk,isCancel as yk,log as ol,outro as _R,password as kk}from"@clack/prompts";async function jR(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function wk(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await jR(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){hk("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),ol.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await kk({message:"Claude OAuth token"});yk(i)&&(gk("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Ju({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Yo()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Fe(t.profile);if(!e){hk(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),ol.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await kk({message:"Claude OAuth token"});yk(i)&&(gk("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=W(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},oe(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(ol.success("Claude OAuth token saved."),_R("It will be sealed into job bundles when a SANDBOX (re)connects."))}po();G();Le();St();ls();wr();us();Re();ue();import{cancel as NR,confirm as OR,intro as DR,isCancel as bk,log as Pe,outro as LR,select as $k,text as Zt}from"@clack/prompts";function vk(t){NR(t),process.exit(1)}function Rn(t){return bk(t)&&vk("aborted"),t}function Eo(t){return bk(t)&&vk("aborted"),typeof t=="string"?t:""}async function MR(t,e){let r=Rn(await $k({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),n=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",o=Eo(await Zt({message:"Context Repo owner (org / group / workspace / user)",placeholder:n||"your-org",initialValue:n,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=Eo(await Zt({message:"Context Repo name",placeholder:$t(t),initialValue:$t(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function xk(t={profile:void 0}){let e=Fe(t.profile);DR(`codepipe project add \u2192 ${e.hubUrl}`);let r=Rn(await Zt({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>ir.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=Rn(await Zt({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=Rn(await $k({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=Rn(await Zt({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Rn(await OR({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=Eo(await Zt({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()||We(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=We(d);Pe.message(`${f.host}: ${f.owner}/${f.repoName}`);let m=Eo(await Zt({message:"repo logical name (used inside Context Repo paths)",placeholder:f.repoName,initialValue:f.repoName,validate:w=>w.trim().length>0?void 0:"required"})).trim(),h=Eo(await Zt({message:"default branch (optional)",placeholder:"main"})).trim(),g={name:m,host:f.host,owner:f.owner,repoName:f.repoName};h&&(g.defaultBranch=h),a.push(g)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await MR(r,a),u=W(e.projectId);Pe.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await bn(c,l,{githubToken:u?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:u?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:u?.bitbucket??Br(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:d=>Pe.message(d),warn:d=>Pe.warn(d)}})}catch(d){Pe.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,Pe.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await Bt(e.hubUrl,e.cliToken,c);Pe.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),kr(r,yt(c,s,u?.youtrack?.url),{info:f=>Pe.message(f),warn:f=>Pe.warn(f)}),d.contextRepo&&(Pe.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),Pe.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&Pe.error(` error: ${d.provisioningError}`),LR("done")}catch(d){d instanceof K?(Pe.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&Pe.message(JSON.stringify(d.payload,null,2))):Pe.error(d instanceof Error?d.message:String(d)),process.exit(1)}}kn();Le();Re();ue();mt();$o();import{existsSync as UR,rmSync as BR}from"node:fs";import{confirm as FR,intro as GR,isCancel as KR,log as er,outro as HR,spinner as WR}from"@clack/prompts";function wt(t){er.error(t),process.exit(1)}var Sk=t=>t.trim().replace(/\/+$/,"");async function Tk(t){GR("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Se()?.spec.projectId??void 0;e||wt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=Qe(e);r||wt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Sk(r.hubUrl),o=r.projectId,i=Sk(t.hub);i.startsWith("http")||wt("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&wt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let w=WR();w.start(`reading project ${o} from ${n}\u2026`);try{l=await ne(n,r.cliToken,o),w.stop(`read project ${o} (${l.name})`)}catch(y){throw w.stop("could not read the source project",1),y instanceof K&&wt(`source HUB ${n} \u2192 ${y.status} ${y.message}. The source HUB must be reachable with a valid token to move a project.`),y}}l.contextRepo||wt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=W(o),p=(t.account??r.accountEmail??await Tn()).trim().toLowerCase();if(er.message(`move project '${o}'
|
|
866
867
|
from : ${n} (profile ${e})
|
|
867
868
|
to : ${i} (profile ${s}, project ${a}, account ${p})
|
|
868
869
|
\u2022 the source registration on the old HUB is left intact (non-destructive)
|
|
869
870
|
\u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
|
|
870
|
-
`+(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
|
|
871
|
-
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let h;try{h=await rp(e.hubUrl,e.cliToken,e.projectId,m)}catch(y){y instanceof K&&Me(`HUB \u2192 ${y.status} ${y.message}`),Me(y instanceof Error?y.message:String(y))}let{updated:g,errors:w}=Qn(e.projectId,h.repos,r?.contextDir);for(let y of g)ye.message(`updated ${y}`);for(let y of w)ye.warn(`could not update ${y.path}: ${y.error}`);ye.success(`added "${u}" \u2014 project now has ${h.repos.length} repo(s)`),$k("done")}async function Sk(t){let e=Fe(t.profile);bk(`codepipe repo remove \u2192 project ${e.projectId}`);let r=Se()??void 0,n;try{let c=(await ne(e.hubUrl,e.cliToken,e.projectId)).repos.find(l=>l.name===t.name);n=c?c.mountAs??c.name:void 0}catch{}let o;try{o=await np(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof K&&(a.status===404&&Me(`no repo named "${t.name}" in this project`),Me(`HUB \u2192 ${a.status} ${a.message}`)),Me(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=Qn(e.projectId,o.repos,r?.contextDir);for(let a of i)ye.message(`updated ${a}`);for(let a of s)ye.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")ye.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?ms(r.root,n):Te(e.projectId,t.name);if(nl(ms(a,".git")))try{LR(a,{recursive:!0,force:!0}),ye.message(`deleted local clone ${a}`)}catch(c){ye.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else ye.message(`no local clone found to purge (${a})`)}ye.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),$k("done")}async function Tk(t){let e=Fe(t.profile),r;try{r=(await ne(e.hubUrl,e.cliToken,e.projectId)).repos}catch(n){console.error(`could not read project from HUB: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(r.length===0){console.log(`project ${e.projectId} has no repos yet \u2014 add one with \`codepipe repo add\``);return}console.log(`project ${e.projectId} \u2014 ${r.length} repo(s):`);for(let n of r){let o=n.mountAs??n.name,i=n.defaultBranch?` @${n.defaultBranch}`:"";console.log(` ${n.name} ${n.host}:${n.owner}/${n.repoName}${i} \u2192 ${o}`)}}ls();Hc();Jc();yn();G();_e();yn();Le();Re();wo();import{hostname as WR}from"node:os";import{cancel as qR,confirm as Ek,intro as YR,isCancel as Ck,log as Rn,multiselect as VR,outro as Rk,password as zR,select as ol,text as il}from"@clack/prompts";function To(t){qR(t),process.exit(1)}function In(t){return Ck(t)&&To("aborted"),t}function gs(t){return Ck(t)&&To("aborted"),typeof t=="string"?t:""}function hs(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Ik(t,e){try{let{secret:r}=await ri(t,e);return r}catch(r){throw r instanceof K&&r.status===404&&To("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(In(await ol({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 ia(t,e);if(o.length>0)return In(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}));Rn.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Rn.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return gs(await il({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 sl(t){YR("codepipe worker \u2014 set up this machine as a runner");let e=Ae(t.profile);e&&(Rn.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),In(await Ek({message:"re-register this worker?",initialValue:!1}))||To("keeping the existing registration"));let r=Qe(t.profile)??Qe(),n=gs(await il({message:"HUB URL",placeholder:ct,initialValue:V("HUB_URL")??r?.hubUrl??ct,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=In(await ol({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 Ik(n,a),Rn.success("account-issued registration token minted");else if(i==="login"){let d=await Sn();a=(await Tn(n,d)).cliToken,s=await Ik(n,a),Rn.success("account-issued registration token minted")}else s=gs(await zR({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||To("a registration token is required");let c=await JR(n,a),l=gs(await il({message:"worker name",initialValue:WR(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=In(await ol({message:"agent backend",options:[{value:"claude-headless",label:"claude-headless \u2014 Claude Code on PATH (the real thing)"},{value:"mock",label:"mock \u2014 deterministic stub (development)"},{value:"",label:"none \u2014 this worker will not claim agent jobs"}],initialValue:"claude-headless"}));if(await vr({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Rn.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!In(await Ek({message:"start the claim-loop now?",initialValue:!0}))){Rk("registered. start later with `codepipe worker`.");return}Rk("starting the claim-loop\u2026"),await ho(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 V("PROFILE")}var de=QR();_u(de);Ou();var De=new XR;De.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Ue).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{hs()?await zc({profile:de}):await Kc({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});De.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await ak({configPath:t.config,skipVerify:t.skipVerify===!0}):await Xy({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","Personal CLI token (issued during `codepipe init`)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await Vu({...t,profile:de})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await Qy({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});De.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await Cg({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});De.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await jy({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("login").description("Set the Claude OAuth token (sealed into job bundles)").option("--token <token>","Provide the token non-interactively").option("--shared","Save to the machine/farm-wide ~/.codepipe/shared.json instead of this project").option("--stdin","Read the token from stdin (for scripted/ssh delivery)").action(async t=>{try{await pk({profile:de,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await iy({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});De.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).action(async t=>{try{await Kc({profile:de,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Ak=De.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Ak.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??V("HUB_URL")??Qe(de)?.hubUrl??ct,r=t.token??V("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&hs()){await sl({profile:de});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let n=V("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??V("WORKER_NAME"),i=t.llm??V("WORKER_LLM");await vr({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...de?{profile:de}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ak.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!Ae(de)&&hs()){await sl({profile:de});return}await ho(de?{profile:de}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Pk=De.command("project").description("Manage CodePipe projects");Pk.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await hk({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Pk.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 kk({...t,cliProfile:de})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var al=De.command("repo").description("Manage the project's git repositories");al.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 xk({profile:de,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});al.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 Sk({profile:de,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});al.command("list").description("List the project's repos").action(async()=>{try{await Tk({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var _k=De.command("model").description("Project map (model/ in the Context Repo)");_k.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 pc({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});_k.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 fc({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.parseAsync();
|
|
871
|
+
`+(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 FR({message:"Continue?",initialValue:!0});(KR(w)||!w)&&wt("aborted")}!c&&a===o&&er.warn(`source and destination share the same project id, so they share one secrets file (${gt(a)}). Running both profiles at the same time will conflict \u2014 pass --project <newId> for a parallel setup, or keep only one active.`);let{cliToken:d,accountEmail:f}=await En(i,p),m={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:f,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};er.step(`registering project on ${i}\u2026`);let h;try{h=await Bt(i,d,m)}catch(w){if(w instanceof K&&w.status===409){er.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{h=await ne(i,d,a)}catch(y){throw y instanceof K&&wt(`target HUB \u2192 ${y.status} ${y.message}`),y}}else if(w instanceof K&&w.status===403)wt(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(w instanceof K)wt(`target HUB \u2192 ${w.status} ${w.message}`);else throw w}er.success(`project ${h.projectId} ready on ${i} (${h.provisioningStatus})`),vt({hubUrl:i,cliToken:d,projectId:a,accountEmail:f},s);let g={...u??{},hubUrl:i,cliToken:d,projectId:a};if(delete g.sandboxPins,oe(g),er.success(`profile '${s}' \u2192 ${gt(a)}`),c){let w=ot(s);UR(w)&&(BR(w),er.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}HR(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}Le();Pa();us();Re();mr();ue();mt();import{existsSync as il,rmSync as qR,statSync as YR}from"node:fs";import{join as ys,relative as VR,resolve as zR}from"node:path";import{cancel as JR,intro as Rk,isCancel as XR,log as ye,outro as Ik,text as Tr}from"@clack/prompts";import{simpleGit as Ck}from"simple-git";function Me(t){JR(t),process.exit(1)}function Er(t){return XR(t)&&Me("aborted"),typeof t=="string"?t:""}async function Ek(t){try{let e=await Ck(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function QR(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function ZR(t,e){let r=W(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(QR(r,e)){ye.message(`reusing existing ${e} credentials`);return}if(ye.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=Er(await Tr({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=Er(await Tr({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=Er(await Tr({message:`${e} access token (read access to the repo)`,validate:o=>o.trim()?void 0:"required"})).trim();e==="github"?r.github={token:n}:r.gitlab={token:n}}oe(r),ye.success(`saved ${e} credentials`)}async function Ak(t){let e=Fe(t.profile);Rk(`codepipe repo add \u2192 project ${e.projectId}`);let r=Se()??void 0,n;try{n=(await ne(e.hubUrl,e.cliToken,e.projectId)).repos}catch(y){Me(`could not read project from HUB: ${y instanceof Error?y.message:String(y)}`)}let o=t.target?.trim();if(!o){let y=await Ek(process.cwd());y?(o=process.cwd(),ye.message(`using the current directory (${y})`)):o=Er(await Tr({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:x=>x.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(il(o)&&YR(o).isDirectory()){i=zR(o);let y=await Ek(i);y||Me(`${i} is not a git repository (no origin remote)`);let x=We(y);x||Me(`origin ${y} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=x,s=y,ye.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let y=We(o);y||Me(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=y,s=o,ye.message(`${a}: ${c}/${l}`)}let u=Er(await Tr({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:y=>y.trim()?void 0:"required"})).trim();n.some(y=>y.name===u)&&Me(`a repo named "${u}" is already registered`);let p=Er(await Tr({message:"default branch (optional)",placeholder:"main"})).trim(),d=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let y=VR(r.root,i);d=y===""?".":y}let f=Er(await Tr({message:"mount_as (directory relative to the workspace root)",placeholder:d,initialValue:d})).trim()||d;n.some(y=>(y.mountAs??y.name)===f)&&Me(`mount_as "${f}" is already used by another repo`),await ZR(e,a);let m={name:u,host:a,owner:c,repoName:l,mountAs:f,...p?{defaultBranch:p}:{}};if(!i){let y=r?ys(r.root,f):Te(e.projectId,u);if(il(ys(y,".git")))ye.message(`already cloned at ${y}`);else{ye.info(`cloning ${s} \u2192 ${y} \u2026`);try{await Ck().clone(s,y),ye.success(`cloned into ${y}`)}catch(x){Me(`clone failed: ${x instanceof Error?x.message.trim():String(x)}
|
|
872
|
+
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let h;try{h=await ip(e.hubUrl,e.cliToken,e.projectId,m)}catch(y){y instanceof K&&Me(`HUB \u2192 ${y.status} ${y.message}`),Me(y instanceof Error?y.message:String(y))}let{updated:g,errors:w}=eo(e.projectId,h.repos,r?.contextDir);for(let y of g)ye.message(`updated ${y}`);for(let y of w)ye.warn(`could not update ${y.path}: ${y.error}`);ye.success(`added "${u}" \u2014 project now has ${h.repos.length} repo(s)`),Ik("done")}async function Pk(t){let e=Fe(t.profile);Rk(`codepipe repo remove \u2192 project ${e.projectId}`);let r=Se()??void 0,n;try{let c=(await ne(e.hubUrl,e.cliToken,e.projectId)).repos.find(l=>l.name===t.name);n=c?c.mountAs??c.name:void 0}catch{}let o;try{o=await sp(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof K&&(a.status===404&&Me(`no repo named "${t.name}" in this project`),Me(`HUB \u2192 ${a.status} ${a.message}`)),Me(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=eo(e.projectId,o.repos,r?.contextDir);for(let a of i)ye.message(`updated ${a}`);for(let a of s)ye.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")ye.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?ys(r.root,n):Te(e.projectId,t.name);if(il(ys(a,".git")))try{qR(a,{recursive:!0,force:!0}),ye.message(`deleted local clone ${a}`)}catch(c){ye.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else ye.message(`no local clone found to purge (${a})`)}ye.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),Ik("done")}async function _k(t){let e=Fe(t.profile),r;try{r=(await ne(e.hubUrl,e.cliToken,e.projectId)).repos}catch(n){console.error(`could not read project from HUB: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(r.length===0){console.log(`project ${e.projectId} has no repos yet \u2014 add one with \`codepipe repo add\``);return}console.log(`project ${e.projectId} \u2014 ${r.length} repo(s):`);for(let n of r){let o=n.mountAs??n.name,i=n.defaultBranch?` @${n.defaultBranch}`:"";console.log(` ${n.name} ${n.host}:${n.owner}/${n.repoName}${i} \u2192 ${o}`)}}ps();qc();Qc();kn();G();_e();kn();Le();Re();$o();import{hostname as eI}from"node:os";import{cancel as tI,confirm as jk,intro as rI,isCancel as Dk,log as In,multiselect as nI,outro as Nk,password as oI,select as sl,text as al}from"@clack/prompts";function Ro(t){tI(t),process.exit(1)}function Cn(t){return Dk(t)&&Ro("aborted"),t}function ks(t){return Dk(t)&&Ro("aborted"),typeof t=="string"?t:""}function ws(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Ok(t,e){try{let{secret:r}=await oi(t,e);return r}catch(r){throw r instanceof K&&r.status===404&&Ro("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 iI(t,e){if(Cn(await sl({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 ca(t,e);if(o.length>0)return Cn(await nI({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}));In.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){In.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return ks(await al({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 cl(t){rI("codepipe worker \u2014 set up this machine as a runner");let e=Ae(t.profile);e&&(In.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Cn(await jk({message:"re-register this worker?",initialValue:!1}))||Ro("keeping the existing registration"));let r=Qe(t.profile)??Qe(),n=ks(await al({message:"HUB URL",placeholder:ct,initialValue:V("HUB_URL")??r?.hubUrl??ct,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=Cn(await sl({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 Ok(n,a),In.success("account-issued registration token minted");else if(i==="login"){let d=await Tn();a=(await En(n,d)).cliToken,s=await Ok(n,a),In.success("account-issued registration token minted")}else s=ks(await oI({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||Ro("a registration token is required");let c=await iI(n,a),l=ks(await al({message:"worker name",initialValue:eI(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=Cn(await sl({message:"agent backend",options:[{value:"claude-headless",label:"claude-headless \u2014 Claude Code on PATH (the real thing)"},{value:"mock",label:"mock \u2014 deterministic stub (development)"},{value:"",label:"none \u2014 this worker will not claim agent jobs"}],initialValue:"claude-headless"}));if(await vr({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),In.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Cn(await jk({message:"start the claim-loop now?",initialValue:!0}))){Nk("registered. start later with `codepipe worker`.");return}Nk("starting the claim-loop\u2026"),await ko(t.profile?{profile:t.profile}:{})}function aI(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return V("PROFILE")}var de=aI();Ou(de);Mu();var De=new sI;De.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Ue).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{ws()?await Xc({profile:de}):await Wc({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});De.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await mk({configPath:t.config,skipVerify:t.skipVerify===!0}):await ok({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","Personal CLI token (issued during `codepipe init`)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await Xu({...t,profile:de})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await ik({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});De.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await _g({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});De.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await By({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("login").description("Set the Claude OAuth token (sealed into job bundles)").option("--token <token>","Provide the token non-interactively").option("--shared","Save to the machine/farm-wide ~/.codepipe/shared.json instead of this project").option("--stdin","Read the token from stdin (for scripted/ssh delivery)").action(async t=>{try{await wk({profile:de,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await py({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});De.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).option("--debug [categories]","Write local debug logs (comma-separated categories; default: agent-request \u2014 the full prompt and context each agent job receives, under ~/.codepipe/debug/)").action(async t=>{try{await Wc({profile:de,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Lk=De.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Lk.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??V("HUB_URL")??Qe(de)?.hubUrl??ct,r=t.token??V("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&ws()){await cl({profile:de});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let n=V("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??V("WORKER_NAME"),i=t.llm??V("WORKER_LLM");await vr({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...de?{profile:de}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Lk.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!Ae(de)&&ws()){await cl({profile:de});return}await ko(de?{profile:de}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Mk=De.command("project").description("Manage CodePipe projects");Mk.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await xk({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Mk.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 Tk({...t,cliProfile:de})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var ll=De.command("repo").description("Manage the project's git repositories");ll.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 Ak({profile:de,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ll.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 Pk({profile:de,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});ll.command("list").description("List the project's repos").action(async()=>{try{await _k({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Uk=De.command("model").description("Project map (model/ in the Context Repo)");Uk.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 gc({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Uk.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 hc({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.parseAsync();
|