@code-partner/codepipe 0.11.1-dev.227.g43c2ca7 → 0.11.1-dev.228.g62386c4
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 +177 -177
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,60 +1,45 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Kw=Object.defineProperty;var S=(t,e)=>()=>(t&&(e=t(t=0)),e);var Fe=(t,e)=>{for(var r in e)Kw(t,r,{get:e[r],enumerable:!0})};var Ke,at,Hi=S(()=>{"use strict";Ke="0.11.1-dev.228.g62386c4",at="https://hub.dev.codepipe.dev"});function Yn(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=mu&&t<=ct}var ct,mu,hu=S(()=>{"use strict";Hi();ct=4,mu=4});var gu=S(()=>{"use strict";Hi()});function Vn(t=6){return`# CodePipe Context Repo format version.
|
|
3
3
|
# Bumped by the scaffold / the format-migration PR \u2014 do not edit by hand.
|
|
4
4
|
template_version: ${t}
|
|
5
|
-
`}function
|
|
5
|
+
`}function qi(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 Yi(t,e=Wi){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 Vi(t,e=Wi){return e.filter(r=>r.version>t)}var yu,lt,Hr,Wi,ku=S(()=>{"use strict";yu=6,lt=".codepipe-context.yaml",Hr=".devpipe-context.yaml",Wi=[{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",lt]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[lt]},{version:3,summary:"Custom project actions (the RUN tab): actions/ scaffold with the format README",addedPaths:["actions/README.md"]},{version:4,summary:"Project map: model/ scaffold with the format README (facts/ vs derived/ layout)",addedPaths:["model/README.md"]},{version:5,summary:"Roles: roles/ scaffold with the format README (override a bundled critic by name, or add your own)",addedPaths:["roles/README.md"]},{version:6,summary:"Skills: skills/ scaffold with the format README (procedures the agent invokes instead of improvising)",addedPaths:["skills/README.md"]}]});function Xn(t){return`model/facts/identity/${t}.yaml`}function pr(t){return`model/facts/events/${t}.yaml`}function Ji(t){return`model/facts/annotations/${t}.md`}function Zi(t){return`model/derived/correlates/${t}.yaml`}function Qi(t){return`model/derived/touched/${t}.yaml`}function wu(t){return t===""?"root":t.replace(/\//g,"-")}function ea(t,e){return`model/derived/structure/${t}/${wu(e)}.yaml`}function Vo(t){return typeof t=="string"&&$u.test(t)}function re(t){if(typeof t!="string")return null;let e=t.indexOf(":");if(e<=0)return null;let r=t.indexOf(":",e+1);if(r<0)return null;let n=t.slice(0,e);if(!bu.includes(n))return null;let o=t.slice(e+1,r),s=t.slice(r+1);return o===""&&!Yw.includes(n)||s===""?null:{level:n,repo:o,path:s}}function ge(t){return`task::${t}`}function fe(t,e,r){return`${t}:${e}:${r}`}function Jn(t){let e=[];return kt(t)?(Xo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),typeof t.repo!="string"&&e.push("repo: missing (empty string = cross-repo)"),typeof t.builtFromCommit!="string"&&e.push("builtFromCommit: missing"),Array.isArray(t.edges)?t.edges.forEach((r,n)=>{if(!kt(r)){e.push(`edges[${n}]: not an object`);return}ta.includes(r.kind)||e.push(`edges[${n}].kind: unknown "${String(r.kind)}"`),re(r.from)||e.push(`edges[${n}].from: malformed nodeKey`),re(r.to)||e.push(`edges[${n}].to: malformed nodeKey`),r.weight!==void 0&&!(typeof r.weight=="number"&&Number.isFinite(r.weight))&&e.push(`edges[${n}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}):{ok:!1,errors:["edge sheet: not an object"]}}function vu(t){return{...t,edges:Wr(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function fr(t){return hr(vu(t))}function kt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Xo(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function ut(t){return typeof t=="string"&&t.length>0}function zw(t){return t.modelFormatVersion!==2}function Ct(t){let e=[];if(!kt(t))return{ok:!1,errors:["shard: not an object"]};Xo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),ut(t.repo)||e.push("repo: missing or empty"),ut(t.builtFromCommit)||e.push("builtFromCommit: missing or empty");let r=typeof t.repo=="string"?t.repo:"",n=new Set;return Array.isArray(t.nodes)?t.nodes.forEach((o,s)=>{if(!kt(o)){e.push(`nodes[${s}]: not an object`);return}let i=re(o.key);if(!i){e.push(`nodes[${s}].key: malformed nodeKey (${JSON.stringify(o.key??null)})`);return}o.level!==i.level&&e.push(`nodes[${s}]: level "${String(o.level)}" does not match key prefix "${i.level}"`),r&&i.repo!==r&&e.push(`nodes[${s}].key: repo "${i.repo}" mixed into shard of repo "${r}"`);let a=o.key;n.has(a)&&e.push(`nodes[${s}].key: duplicate "${a}"`),n.add(a),o.entityId!==void 0&&!Vo(o.entityId)&&e.push(`nodes[${s}].entityId: malformed (${JSON.stringify(o.entityId)})`)}):e.push("nodes: not an array"),Array.isArray(t.edges)?t.edges.forEach((o,s)=>{if(!kt(o)){e.push(`edges[${s}]: not an object`);return}ta.includes(o.kind)||e.push(`edges[${s}].kind: unknown "${String(o.kind)}"`),(!ut(o.to)||!re(o.to))&&e.push(`edges[${s}].to: malformed nodeKey`),(!ut(o.from)||!n.has(o.from))&&e.push(`edges[${s}].from: "${String(o.from)}" is not a node of this shard`),o.weight!==void 0&&!(typeof o.weight=="number"&&Number.isFinite(o.weight))&&e.push(`edges[${s}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}}function Zn(t){let e=[];if(!kt(t))return{ok:!1,errors:["identity: not an object"]};if(Xo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),ut(t.repo)||e.push("repo: missing or empty"),t.builtFromCommit!==void 0&&!ut(t.builtFromCommit)&&e.push("builtFromCommit: not a non-empty string"),!Array.isArray(t.entities))e.push("entities: not an array");else{let r=new Set;t.entities.forEach((n,o)=>{if(!kt(n)){e.push(`entities[${o}]: not an object`);return}Vo(n.entityId)?r.has(n.entityId)?e.push(`entities[${o}].entityId: duplicate "${n.entityId}"`):r.add(n.entityId):e.push(`entities[${o}].entityId: malformed (${JSON.stringify(n.entityId??null)})`),re(n.currentKey)||e.push(`entities[${o}].currentKey: malformed nodeKey`),n.status!=="active"&&n.status!=="orphaned"&&e.push(`entities[${o}].status: expected active|orphaned`),ut(n.firstSeen)||e.push(`entities[${o}].firstSeen: missing`),ut(n.lastSeen)||e.push(`entities[${o}].lastSeen: missing`),n.aliases!==void 0&&(Array.isArray(n.aliases)?n.aliases.forEach((s,i)=>{(!kt(s)||!re(s.key)||!ut(s.until))&&e.push(`entities[${o}].aliases[${i}]: malformed`)}):e.push(`entities[${o}].aliases: not an array`))})}return e.length?{ok:!1,errors:e}:{ok:!0,value:t}}function At(t){let e=[];return kt(t)?(Xo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),ut(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=>!ut(r)))&&e.push("commits: not an array of non-empty strings"),Array.isArray(t.files)?t.files.forEach((r,n)=>{if(!kt(r)||!re(r.key)){e.push(`files[${n}].key: malformed nodeKey`);return}r.entityId!==void 0&&!Vo(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 Wr(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function xu(t){return{...t,nodes:Wr(t.nodes,e=>e.key),edges:Wr(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function Su(t){return{...t,entities:Wr(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:Wr(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function Eu(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:Wr(t.files,r=>r.key),...e?{links:e}:{}}}function zn(t){return Xw.test(t)?t:JSON.stringify(t)}function Ru(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 Iu(t){return t===null||["boolean","number","string"].includes(typeof t)}function zi(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function Tu(t,e,r){if(Array.isArray(t)){for(let n of t)if(Iu(n))r.push(`${e}- ${Ru(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=zi(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([s,i],a)=>{let c=a===0?`${e}- `:`${e} `;Xi(s,i,c,`${e} `,r)})}}return}for(let[n,o]of zi(t))Xi(n,o,e,e,r)}function Xi(t,e,r,n,o){if(Iu(e))o.push(`${r}${zn(t)}: ${Ru(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${zn(t)}: []`):(o.push(`${r}${zn(t)}:`),Tu(e,`${n} `,o));else{let s=zi(e);if(s.length===0)o.push(`${r}${zn(t)}: {}`);else{o.push(`${r}${zn(t)}:`);for(let[i,a]of s)Xi(i,a,`${n} `,`${n} `,o)}}}function hr(t){let e=[];return Tu(t,"",e),e.join(`
|
|
6
6
|
`)+`
|
|
7
|
-
`}function oa(t){return hr(Ou(t))}function sa(t){return hr(Lu(t))}function qr(t){return hr(Du(t))}var _e,wb,bb,$b,vb,Yo,dr,_u,Qi,ju,xb,Qe,ea,ta,ra,zo,Sb,na,mr,Rb,ia=v(()=>{"use strict";_e=2,wb="model",bb="model/README.md",$b="model/facts",vb="model/derived",Yo="model/derived/INDEX.yaml",dr="model/derived/relates.yaml";_u=["system","container","component","code","task","adr"],Qi=["contains","touched_by","correlates","relates","references","depends_on"],ju=/^e_[0-9a-f]{8}$/;xb=["system","task","adr"];Qe={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};ea=2,ta=5,ra=50,zo=2e3,Sb=5e4,na={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},mr={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};Rb=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});function Ib(t){return t==="DONE"}function Tb(t){return t==="AWAITING_EXTERNAL_FIX"?!1:aa.indexOf(t)>=aa.indexOf("IMPLEMENTING")}var aa,Fu=v(()=>{"use strict";aa=["BACKLOG","QUEUED","INTAKE","AWAITING_APPROVAL","ANALYZING","ESTIMATING","AWAITING_ANSWER","REVIEW","READY","IMPLEMENTING","BUILD","CODE_REVIEW","TESTING","AWAITING_EXTERNAL_FIX","READY_TO_APPLY","APPLYING","AWAITING_CLUSTER","TRACKING","NEEDS_MANUAL","DONE"]});function Ab(t){for(let e of ca)if(e.phases.includes(t))return e.id;return null}function Pb(t){for(let e of Ku)if(e.phases.includes(t))return e.id;return null}var ca,Cb,Ku,Gu=v(()=>{"use strict";ca=[{id:"intake",label:"Intake",phases:["INTAKE"]},{id:"analysis",label:"Analysis",phases:["ANALYZING","ESTIMATING"]},{id:"ready",label:"Ready",phases:["READY"]},{id:"implementation",label:"Implementation",phases:["IMPLEMENTING","BUILD"]},{id:"delivery",label:"Delivery",phases:["READY_TO_APPLY","APPLYING","AWAITING_CLUSTER"]}],Cb=ca.flatMap(t=>t.phases),Ku=[{id:"review",label:"Review / tracking",phases:["CODE_REVIEW","TESTING","TRACKING"]},{id:"attention",label:"Need your attention",phases:["NEEDS_MANUAL","AWAITING_APPROVAL","AWAITING_EXTERNAL_FIX","AWAITING_ANSWER","REVIEW"]},{id:"backlog",label:"Backlog / queue",phases:["BACKLOG","QUEUED"]}]});function _b(t){return Hu.includes(t)?"planning":"implementation"}function Ft(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var la,Hu,jb,ua=v(()=>{"use strict";la=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat","observer","council","testing"],Hu=["draft","analysis","chat","observer","council"];jb=1});function Wu(t,e){return e.toLowerCase().includes(t.toLowerCase())}function fa(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||Xu.every(o=>e.some(s=>Wu(o,s.id))))return null;let n=[...e].sort((o,s)=>{let i=o.createdAt??"",a=s.createdAt??"";return i!==a?i<a?1:-1:o.id<s.id?1:-1});for(let o of zu){let s=n.find(i=>Wu(o,i.id));if(s)return s.id}return n[0].id}function Yr(){return{default:null,roles:{}}}function Nb(t,e){let r=t?.roles?.[e];return typeof r=="string"&&r.trim().length>0?r.trim():t?.default&&t.default.trim().length>0?t.default.trim():eo[e]??Vu}function Ob(t){let e=t?.provider;return typeof e=="string"&&e.trim().length>0?e.trim():Ge}function Lb(t){let e=Yr();if(!t||typeof t!="object")return e;let r=t.llm;if(!r||typeof r!="object")return e;let n=r.provider;typeof n=="string"&&n.trim().length>0&&(e.provider=n.trim());let o=r.models;if(!o||typeof o!="object")return e;for(let[s,i]of Object.entries(o))typeof i!="string"||i.trim().length===0||(s==="default"?e.default=i.trim():e.roles[s]=i.trim());return e}function Db(t){let e=typeof t.provider=="string"&&t.provider.trim().length>0&&t.provider.trim()!==Ge;if(t.default===null&&Object.keys(t.roles).length===0&&!e)return null;let{provider:r,...n}=t;return JSON.stringify(e?{provider:r.trim(),...n}:n)}function Mb(t){if(!t)return Yr();try{let e=JSON.parse(t);if(!e||typeof e!="object")return Yr();let r=e,n=Yr();typeof r.provider=="string"&&r.provider.trim().length>0&&(n.provider=r.provider.trim()),typeof r.default=="string"&&(n.default=r.default);let o=r.roles;if(o&&typeof o=="object")for(let[s,i]of Object.entries(o))typeof i=="string"&&(n.roles[s]=i);return n}catch{return Yr()}}var Ge,da,Ee,Qn,Jo,Zo,qu,Yu,pa,eo,Vu,zu,Xu,ma=v(()=>{"use strict";ua();Ge="claude",da=[Ge],Ee="opus",Qn="sonnet",Jo="haiku",Zo=[Ee,Qn,Jo],qu="build-discovery",Yu=[qu],pa=[...la,...Yu],eo={analyze:Ee,implement:Ee,"resolve-conflict":Ee,rework:Ee,estimate:Qn,build:Jo,"build-discovery":Ee,"code-review":Ee,draft:Qn,index:Ee,backfill:Ee,analysis:Ee,chat:Ee,observer:Ee,council:Ee,testing:Ee},Vu=Ee,zu=[Ee,Qn,Jo],Xu=Array.from(new Set(Object.values(eo)))});function Pt(t){return Ub.has(t)?!0:Bb.some(e=>t.startsWith(e))}function Qo(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function gr(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function ga(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function ka(t,e){let r=Qo(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=gr(r.id,"id")??n;if(!ha.test(o))throw new Error(`id must match ${ha} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let s=gr(r.title,"title")?.trim()||o,i;if(r.env!==void 0&&r.env!==null){let p=Qo(r.env,"env");i={};for(let[d,m]of Object.entries(p)){if(!He.test(d))throw new Error(`env name "${d}" must match ${He}`);if(typeof m!="string"&&typeof m!="number"&&typeof m!="boolean")throw new Error(`env.${d} must be a scalar`);i[d]=String(m)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>Ju)throw new Error(`too many params (max ${Ju})`);let p=new Set;a=c.map((d,m)=>Fb(d,m,p))}let l=r.steps;if(!Array.isArray(l)||l.length===0)throw new Error("steps must be a non-empty list");if(l.length>Zu)throw new Error(`too many steps (max ${Zu})`);let u=l.map((p,d)=>{let m=Qo(p,`steps[${d}]`),f=gr(m.run,`steps[${d}].run`);if(!f||f.trim().length===0)throw new Error(`steps[${d}].run is required`);let g=gr(m.name,`steps[${d}].name`),h=ga(m.timeout_sec,`steps[${d}].timeout_sec`);if(h!==void 0&&(!Number.isInteger(h)||h<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:f,...g?{name:g}:{},...h!==void 0?{timeout_sec:h}:{}}});return{id:o,title:s,...i?{env:i}:{},...a?{params:a}:{},steps:u}}function Fb(t,e,r){let n=Qo(t,`params[${e}]`),o=gr(n.name,`params[${e}].name`);if(!o||!He.test(o))throw new Error(`params[${e}].name must match ${He}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let s=n.type;if(s!=="string"&&s!=="enum"&&s!=="number"&&s!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let i;if(s==="enum"){let m=n.enum;if(!Array.isArray(m)||m.length===0||!m.every(f=>typeof f=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);i=m}let a=gr(n.label,`params[${e}].label`),c=gr(n.help,`params[${e}].help`),l=n.required===!0,u=ga(n.min,`params[${e}].min`),p=ga(n.max,`params[${e}].max`),d=n.default;if(d!=null&&typeof d!="string"&&typeof d!="number"&&typeof d!="boolean")throw new Error(`params[${e}].default must be a scalar`);return{name:o,type:s,...a?{label:a}:{},...c?{help:c}:{},...l?{required:!0}:{},...i?{enum:i}:{},...u!==void 0?{min:u}:{},...p!==void 0?{max:p}:{},...d!=null?{default:d}:{}}}function wa(t,e){let r=t.params??[],n=new Map(r.map(s=>[s.name,s]));for(let s of Object.keys(e))if(!n.has(s))return{ok:!1,error:`unknown param: ${s}`};let o={};for(let s of r){let i=e[s.name];if(i==null||typeof i=="string"&&i.trim()==="")if(s.default!==void 0)i=s.default;else{if(s.required)return{ok:!1,error:`${s.name} is required`};continue}switch(s.type){case"string":{if(typeof i!="string")return{ok:!1,error:`${s.name} must be a string`};o[s.name]=i;break}case"enum":{if(typeof i!="string"||!(s.enum??[]).includes(i))return{ok:!1,error:`${s.name} must be one of: ${(s.enum??[]).join(", ")}`};o[s.name]=i;break}case"number":{let a=typeof i=="number"?i:typeof i=="string"?Number(i):NaN;if(!Number.isFinite(a))return{ok:!1,error:`${s.name} must be a number`};if(s.min!==void 0&&a<s.min)return{ok:!1,error:`${s.name} must be \u2265 ${s.min}`};if(s.max!==void 0&&a>s.max)return{ok:!1,error:`${s.name} must be \u2264 ${s.max}`};o[s.name]=a;break}case"boolean":{let a=typeof i=="boolean"?i:i==="true"?!0:i==="false"?!1:null;if(a===null)return{ok:!1,error:`${s.name} must be a boolean`};o[s.name]=a;break}}}return{ok:!0,values:o}}var He,Ub,Bb,ya,ha,Ju,Zu,ba=v(()=>{"use strict";He=/^[A-Z][A-Z0-9_]*$/,Ub=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),Bb=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];ya=600,ha=/^[a-z0-9-]+$/,Ju=32,Zu=64});function Qu(){return{primary:ye,context:ye,tasks:ye,docs:ye,code_comments:ye,chat:ye}}function ed(t){return!t||t.trim().length===0||t.trim().toLowerCase()===ye}function Kb(t){if(typeof t!="string")return ye;let e=t.trim().replace(/\s+/g," ");return e.length===0||e.length>40||e.toLowerCase()===ye?ye:e}function Gb(t){let e=Qu();if(!t||typeof t!="object")return e;let r=t.language;if(!r||typeof r!="object"||Array.isArray(r))return e;let n=r;for(let o of to)e[o]=Kb(n[o]);return e}function Hb(t){return to.every(e=>ed(t[e]))}var ye,to,Vr,ro,$a=v(()=>{"use strict";ye="auto",to=["primary","context","tasks","docs","code_comments","chat"],Vr=["English","Russian","German","Spanish","French","Portuguese","Italian","Chinese","Japanese","Korean"],ro=40});function Ea(t=td){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...Ea(r.groups));return e}function rd(t,e){let r=JSON.stringify(e);return Ea().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function Ra(t){let e=rd(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let s=r.trim();return e.type==="string"&&e.mustContain&&!s.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:e.maxLength!==void 0&&s.length>e.maxLength?{ok:!1,error:`${e.id} must be \u2264 ${e.maxLength} chars`}:{ok:!0,field:e,value:s}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let s=r.trim();return e.suggestions?.includes(s)?{ok:!0,field:e,value:s}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let s=r.map(i=>typeof i=="string"?i.trim():"").filter(i=>i.length>0);return s.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:s}}case"string_map":{if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,error:`${e.id} must be a name\u2192value map`};let s=Object.entries(r);if(s.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(s.length>va)return{ok:!1,error:`${e.id} must have \u2264 ${va} entries`};let i={};for(let[a,c]of s){if(!He.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${He}`};if(Pt(a))return{ok:!1,error:`${e.id}: name "${a}" is reserved`};if(typeof c!="string")return{ok:!1,error:`${e.id}: value of "${a}" must be a string`};if(c.length>xa)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${xa} chars`};i[a]=c}return{ok:!0,field:e,value:i}}}}var Wb,qb,va,xa,Sa,td,nd=v(()=>{"use strict";ba();ma();ia();$a();Wb={primary:"Primary language",context:"Context documents",tasks:"Tracker issues",docs:"Repo documentation",code_comments:"Code comments",chat:"Agent chat"},qb={primary:"The project's main language (agent status notes ride it). Empty \u21D2 auto.",context:"Knowledge, ADRs and task artifacts in the Context Repo. Empty \u21D2 auto.",tasks:"Issue titles/bodies the agent drafts. Empty \u21D2 auto.",docs:"Documentation changes in the project repos. Empty \u21D2 auto.",code_comments:"New code comments the agent writes. Empty \u21D2 auto.",chat:"The interactive task-drafting chat. Empty/auto \u21D2 mirror the user's messages."},va=64,xa=2e3,Sa=2e3,td=[{id:"branch",label:"Branch",help:"Task-branch naming.",fields:[{id:"branch.pattern",file:"project.yaml",path:["branch","pattern"],type:"string",label:"Task-branch pattern",nullable:!0,mustContain:"<TASK_ID>",help:"Template for the per-task branch name. Must contain the <TASK_ID> placeholder. Empty \u21D2 default codepipe/<TASK_ID>."}]},{id:"llm",label:"LLM",fields:[{id:"llm.provider",file:"regimen.yaml",path:["llm","provider"],type:"enum",label:"Provider",nullable:!1,suggestions:[...da],help:"LLM backend for this project. Currently only claude is available."}],groups:[{id:"llm.models",label:"Models by role",help:"Model per pipeline stage. Empty \u21D2 the role's recommended default applies.",fields:[{id:"llm.models.default",file:"regimen.yaml",path:["llm","models","default"],type:"model",label:"default (catch-all)",nullable:!0,suggestions:[...Zo],help:"Overrides the recommended defaults for every role not listed below."},...pa.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Zo],help:`recommended: ${eo[t]}`}))]}]},{id:"apply.style",label:"Commits & PRs",help:"Instructions for the AI agent on how to write commit messages and PR descriptions. Empty \u21D2 built-in templates.",fields:[{id:"apply.commit_style",file:"project.yaml",path:["apply","commit_style"],type:"string",label:"Commit message style",nullable:!0,multiline:!0,maxLength:Sa,help:'e.g. "English, imperative mood, first line \u2264 72 chars, start with the issue key". Empty \u21D2 "<KEY>: <task title>".'},{id:"apply.pr_style",file:"project.yaml",path:["apply","pr_style"],type:"string",label:"PR description style",nullable:!0,multiline:!0,maxLength:Sa,help:`e.g. "implementation details, bullet list of what was done, in the tracker's language". Empty \u21D2 the default PR body.`}]},{id:"apply.delivery",label:"Delivery & merge",help:"How a finished change reaches the repository: with or without a pull request, and who merges it.",fields:[{id:"apply.pull_request",file:"project.yaml",path:["apply","pull_request"],type:"boolean",label:"Open a pull request",nullable:!1,help:"On (default): the task branch is pushed and a pull request is opened \u2014 the change is reviewable in the git host and keeps a history of review comments. Off: no PR at all; the branch is merged into the default branch directly, and the agent's review remarks live only in the dashboard and the Context Repo."},{id:"apply.done",file:"project.yaml",path:["apply","done"],type:"enum",label:"Task is done when",nullable:!1,suggestions:["merge","branch"],help:"merge (default): the task is finished only once its change lands in the default branch. branch: the task ends at the pushed branch (plus the PR, if enabled) and nothing is merged for you."},{id:"apply.auto_merge",file:"project.yaml",path:["apply","auto_merge"],type:"enum",label:"Auto-merge pull requests",nullable:!1,suggestions:["off","on_ci_green"],help:"Applies to the pull-request path only. off (default): the merge waits for you (Approve on the task card). on_ci_green: as soon as the PR is open, conflict-free and its CI is green, CodePipe merges it \u2014 changes reach the default branch with no further review from you. Requires full automation; branch protection on the host still applies (a refused merge parks the task). Without pull requests, full automation merges the branch itself and this switch does not apply."}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{id:"testing",label:"Testing",help:"An optional phase after code review: writes the test plan you run in the morning and reports what it could verify.",fields:[{id:"testing.enabled",file:"regimen.yaml",path:["testing","enabled"],type:"boolean",nullable:!1,label:"Run the testing phase",help:"Off by default. When on, a task passing code review goes through a test pass before the PR: it derives TESTPLAN.md from the plan's requirements and reports per requirement what it could verify. A requirement it finds broken sends the change back for a fix (bounded below)."},{id:"testing.max_iterations",file:"regimen.yaml",path:["testing","max_iterations"],type:"number",nullable:!0,min:1,max:10,label:"Fix rounds before stopping",help:"How many times a failed test pass may send the change back before the task waits for you. Empty \u21D2 2."}]},{id:"skills",label:"Skills",help:"Reusable procedures the agent can invoke instead of improvising. Only their names and one-line descriptions sit in the prompt; the steps load when a skill is used.",fields:[{id:"skills.from_bundled",file:"regimen.yaml",path:["skills","from_bundled"],type:"boolean",nullable:!1,label:"Use the skills shipped with CodePipe",help:"On by default. General procedures maintained with the product."},{id:"skills.from_context_repo",file:"regimen.yaml",path:["skills","from_context_repo"],type:"boolean",nullable:!1,label:"Use this project's skills",help:"On by default. Skills the team writes in the context repository under `skills/<name>/SKILL.md`. These override a bundled skill of the same name."},{id:"skills.from_project_repo",file:"regimen.yaml",path:["skills","from_project_repo"],type:"boolean",nullable:!1,label:"Use the code repository's skills",help:"On by default. `.claude/skills/` inside the project repositories \u2014 the skills your developers already use locally. These win over both other sources."}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (on by default; orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on (default), a task taken from Develop waits in the QUEUE for a single Confirm before the pipeline starts \u2014 the Confirm pulls in dependency closure and topologically orders the queue. Off \u21D2 conveyor: the task starts the pipeline immediately."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]},{id:"language",label:"Language",help:"Languages the agent writes in, per area. Empty \u21D2 auto: mirror the language of the user's material.",fields:to.map(t=>({id:`language.${t}`,file:"project.yaml",path:["language",t],type:"string",label:Wb[t],nullable:!0,maxLength:40,suggestions:t==="chat"?[ye,...Vr]:[...Vr],help:qb[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 ${Qe.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 ${Qe.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 ${Qe.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 ${Qe.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 ${Qe.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 ${Qe.topK}.`}]},{id:"context.job_logs",label:"Job transcripts",help:"Whether the raw agent transcript of each job is kept in the Context Repo.",fields:[{id:"context.job_logs.enabled",file:"regimen.yaml",path:["context","job_logs","enabled"],type:"boolean",label:"Keep transcripts in the Context Repo",nullable:!1,help:"Off (default): the transcript is discarded after the run \u2014 nothing lands in the Context Repo. On: each job's raw transcript is committed as tasks/<KEY>/logs/job-<id>.jsonl for post-mortem debugging."}]}]});function od(t){if(t==null)return[];if(!Array.isArray(t))return null;let e=[];for(let r of t){if(typeof r!="string"||r.trim().length===0)return null;e.push(r.trim())}return e}function Ta(t){let{name:e,body:r,origin:n}=t;if(!Ia.test(e))return{ok:!1,error:`role name must match ${Ia} (got "${e}")`};if(r.trim().length===0)return{ok:!1,error:"role body is empty \u2014 the body IS the role's prompt"};let o=t.frontmatter;if(o==null||typeof o!="object"||Array.isArray(o))return{ok:!1,error:"missing or malformed frontmatter block"};let s=o,i=s.description;if(typeof i!="string"||i.trim().length===0)return{ok:!1,error:"description is required (one line: what this role looks for)"};if(i.length>300)return{ok:!1,error:"description must be \u2264 300 characters"};let a=od(s.refs);if(a===null)return{ok:!1,error:"refs must be a list of non-empty paths"};if(a.length>10)return{ok:!1,error:"refs must list at most 10 files \u2014 a role is a narrow view"};for(let d of a)if(d.startsWith("/")||d.includes(".."))return{ok:!1,error:`ref "${d}" must be a path inside the Context Repo`};let c=od(s.scenarios);if(c===null)return{ok:!1,error:"scenarios must be a list"};let l=[];for(let d of c){if(!es.includes(d))return{ok:!1,error:`unknown scenario "${d}" \u2014 one of: ${es.join(", ")}`};l.includes(d)||l.push(d)}if(l.length===0)return{ok:!1,error:`scenarios must name at least one of: ${es.join(", ")}`};let u=s.model;if(u!==void 0&&(typeof u!="string"||u.trim().length===0))return{ok:!1,error:"model must be a non-empty string when set"};let p=s.enabled;return p!==void 0&&typeof p!="boolean"?{ok:!1,error:"enabled must be true or false"}:{ok:!0,role:{name:e,description:i.trim(),...typeof u=="string"?{model:u.trim()}:{},refs:a,scenarios:l,enabled:p!==!1,body:r.trim(),origin:n}}}function Ca(t,e){let r=new Map;for(let n of t)r.set(n.name,n);for(let n of e)r.set(n.name,n);return[...r.values()].sort((n,o)=>n.name<o.name?-1:n.name>o.name?1:0)}function Aa(t,e){return t.filter(r=>r.enabled&&r.scenarios.includes(e))}var es,Ia,PP,_P,sd=v(()=>{"use strict";es=["plan_review","code_review","council"],Ia=/^[a-z][a-z0-9-]{1,39}$/,PP=10,_P=300});function Pa(t){return id.includes(t)}function _a(t){return`prompts/${t}.md`}var id,ad=v(()=>{"use strict";id=["analysis","analyze","backfill","build","chat","code-review","code-review-external","code-review-fix","council","draft","estimate","implement","index","observer","resolve-conflict","rework","testing"]});function Na(t){if(!ja.test(t.name))return{ok:!1,error:`skill directory name must match ${ja}`};if(t.body.trim().length===0)return{ok:!1,error:"SKILL.md has no body \u2014 the body IS the procedure"};let e=t.frontmatter;if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"SKILL.md has no frontmatter block"};let r=e.description;return typeof r!="string"||r.trim().length===0?{ok:!1,error:"description is required \u2014 it is what decides when the skill fires"}:r.length>300?{ok:!1,error:"description must be \u2264 300 characters"}:{ok:!0,skill:{name:t.name,description:r.trim()}}}function Oa(t,e,r){let n=new Map;for(let o of[...t,...e,...r])n.set(o.name,o);return[...n.values()].sort((o,s)=>o.name<s.name?-1:o.name>s.name?1:0)}function ld(t){let e=t.trim(),r=e.lastIndexOf("@"),n=r===-1?e:e.slice(0,r),o=r===-1?"":e.slice(r+1).trim();if(!Yb.test(n))return{ok:!1,error:`"${t}": expected <owner>/<repo>[@<40-hex sha>]`};let s=cd.find(i=>i.repo.toLowerCase()===n.toLowerCase());return o&&!Vb.test(o)?{ok:!1,error:`"${t}": pin to a full 40-character commit sha \u2014 a branch or tag can change under you`}:!s&&!o?{ok:!1,error:`"${t}": a third-party marketplace must be pinned to a commit (<owner>/<repo>@<sha>). Its skills run beside your code with the agent's token.`}:{ok:!0,source:{repo:n,sha:o,name:s?.name??n.replace("/","-").toLowerCase(),official:!!s}}}function zb(t){let e=[],r=[],n=new Set;for(let o of t){if(!o.trim())continue;let s=ld(o);if(!s.ok){r.push(s.error);continue}n.has(s.source.name)||(n.add(s.source.name),e.push(s.source))}return{sources:e,errors:r}}function Jb(t,e){let r=new Set(e.map(s=>s.name)),n={},o=[];for(let s of t){let i=s.trim();if(i){if(!Xb.test(i)||!r.has(i.slice(i.indexOf("@")+1))){o.push(i);continue}n[i]=!0}}return{enabled:n,unknown:o}}var ja,OP,cd,Yb,Vb,Xb,ud=v(()=>{"use strict";ja=/^[a-z][a-z0-9-]{1,39}$/,OP=300;cd=[{repo:"anthropics/skills",name:"anthropic-agent-skills"},{repo:"anthropics/claude-plugins-official",name:"claude-plugins-official"}],Yb=/^[A-Za-z0-9][\w.-]*\/[A-Za-z0-9][\w.-]*$/,Vb=/^[0-9a-f]{40}$/;Xb=/^[A-Za-z0-9][\w.-]*@[A-Za-z0-9][\w.-]*$/});function dd(t,e){if(t==null)return[];if(!Array.isArray(t)||t.length>e)return null;let r=[];for(let n of t){if(typeof n!="string"||n.trim().length===0)return null;r.push(n.trim())}return r}function Zb(t,e){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:"queue plan must be a JSON object"};let r=new Set(e),n=t,o=dd(n.order,e.length);if(o===null)return{ok:!1,error:"order must be a list of task keys"};for(let f of o)if(!r.has(f))return{ok:!1,error:`order names ${f}, which is not in this batch`};if(new Set(o).size!==o.length)return{ok:!1,error:"order repeats a task key"};let s=e.filter(f=>!o.includes(f));if(o.length>0&&s.length>0)return{ok:!1,error:`order omits ${s.join(", ")}`};let i=n.tasks,a=[];if(i!=null){if(!Array.isArray(i))return{ok:!1,error:"tasks must be a list"};for(let f of i){if(!f||typeof f!="object")return{ok:!1,error:"each task entry must be an object"};let g=f,h=typeof g.taskKey=="string"?g.taskKey.trim():"";if(!r.has(h))return{ok:!1,error:`tasks names ${h||"(empty)"}, which is not in this batch`};let w=dd(g.after,e.length);if(w===null)return{ok:!1,error:`${h}: after must be a list of task keys`};for(let x of w){if(!r.has(x))return{ok:!1,error:`${h}: after names ${x}, not in this batch`};if(x===h)return{ok:!1,error:`${h}: cannot come after itself`}}let y=typeof g.decisions=="string"?g.decisions.trim():"";a.push({taskKey:h,decisions:y.slice(0,4e3),after:w})}}let c=[],l=n.conflicts;if(Array.isArray(l))for(let f of l){if(!f||typeof f!="object")continue;let g=f,h=typeof g.taskKey=="string"?g.taskKey.trim():"",w=typeof g.adr=="string"?g.adr.trim():"",y=typeof g.detail=="string"?g.detail.trim():"";!r.has(h)||!y||c.push({taskKey:h,adr:w,detail:y.slice(0,4e3)})}let u=[],p=n.related;if(Array.isArray(p))for(let f of p){if(!f||typeof f!="object")continue;let g=f,h=typeof g.taskKey=="string"?g.taskKey.trim():"",w=typeof g.detail=="string"?g.detail.trim():"";!h||!w||u.push({taskKey:h,detail:w.slice(0,4e3)})}let d=typeof n.summary=="string"?n.summary.trim().slice(0,4e3):"",m=n.deferBehind===!0;return{ok:!0,plan:{order:o,tasks:a,conflicts:c,related:u,summary:d,deferBehind:m}}}var DP,MP,pd=v(()=>{"use strict";DP=4e3,MP=4e3});function Qb(t,e){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:"council verdict must be a JSON object"};let r=t,n=r.unresolved===!0,o=typeof r.fork=="string"?r.fork.trim().slice(0,4e3):"";if(n)return o?{ok:!0,verdict:{answers:[],unresolved:!0,fork:o}}:{ok:!1,error:"an unresolved verdict must describe the fork"};let s=r.answers;if(!Array.isArray(s))return{ok:!1,error:"answers must be a list"};if(s.length!==e.length)return{ok:!1,error:`expected ${e.length} answer(s), got ${s.length}`};let i=[];for(let[a,c]of s.entries()){if(!c||typeof c!="object")return{ok:!1,error:`answer ${a+1} must be an object`};let l=c,u=typeof l.answer=="string"?l.answer.trim():"";if(!u)return{ok:!1,error:`answer ${a+1} is empty`};i.push({question:typeof l.question=="string"?l.question.trim():e[a],answer:u.slice(0,4e3),rationale:typeof l.rationale=="string"?l.rationale.trim().slice(0,4e3):""})}return{ok:!0,verdict:{answers:i,unresolved:!1,fork:""}}}var BP,fd=v(()=>{"use strict";BP=4e3});function r$(t){let e=t.replace(/^#+\s*/,"").trim();for(let r of e$)if(r.re.test(e))return{kind:r.kind,letter:r.letter};return null}function La(t){let e=[],r=new Map,n="",o=null,s=null;for(let a of t.split(`
|
|
8
|
-
`)){let c=/^#{1,6}\s+(.*)$/.exec(a);if(c){n=c[1].trim(),o=
|
|
9
|
-
${a.trim()}`.trim();continue}a.trim()||(s=null)}let i=[...r.entries()].filter(([,a])=>a>1).map(([a])=>a);return{items:e,structured:e.length>=2&&i.length===0,duplicateIds:i}}function
|
|
7
|
+
`}function ia(t){return hr(xu(t))}function aa(t){return hr(Su(t))}function qr(t){return hr(Eu(t))}var _e,Gw,Hw,Ww,qw,Yo,dr,bu,ta,$u,Yw,Qe,ra,na,oa,zo,Vw,sa,mr,Xw,ca=S(()=>{"use strict";_e=2,Gw="model",Hw="model/README.md",Ww="model/facts",qw="model/derived",Yo="model/derived/INDEX.yaml",dr="model/derived/relates.yaml";bu=["system","container","component","code","task","adr"],ta=["contains","touched_by","correlates","relates","references","depends_on"],$u=/^e_[0-9a-f]{8}$/;Yw=["system","task","adr"];Qe={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};ra=2,na=5,oa=50,zo=2e3,Vw=5e4,sa={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},mr={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};Xw=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});function Jw(t){return t==="DONE"}function Zw(t){return t==="AWAITING_EXTERNAL_FIX"?!1:la.indexOf(t)>=la.indexOf("IMPLEMENTING")}var la,Cu=S(()=>{"use strict";la=["BACKLOG","QUEUED","INTAKE","AWAITING_APPROVAL","ANALYZING","ESTIMATING","AWAITING_ANSWER","REVIEW","READY","IMPLEMENTING","BUILD","CODE_REVIEW","TESTING","AWAITING_EXTERNAL_FIX","READY_TO_APPLY","APPLYING","AWAITING_CLUSTER","TRACKING","NEEDS_MANUAL","DONE"]});function eb(t){for(let e of ua)if(e.phases.includes(t))return e.id;return null}function tb(t){for(let e of Au)if(e.phases.includes(t))return e.id;return null}var ua,Qw,Au,Pu=S(()=>{"use strict";ua=[{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"]}],Qw=ua.flatMap(t=>t.phases),Au=[{id:"review",label:"Review / tracking",phases:["CODE_REVIEW","TESTING","TRACKING"]},{id:"attention",label:"Need your attention",phases:["NEEDS_MANUAL","AWAITING_APPROVAL","AWAITING_EXTERNAL_FIX","AWAITING_ANSWER","REVIEW"]},{id:"backlog",label:"Backlog / queue",phases:["BACKLOG","QUEUED"]}]});function rb(t){return _u.includes(t)?"planning":"implementation"}function Ft(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var da,_u,nb,pa=S(()=>{"use strict";da=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat","observer","council","testing"],_u=["draft","analysis","chat","observer","council"];nb=1});function ju(t,e){return e.toLowerCase().includes(t.toLowerCase())}function ha(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||Mu.every(o=>e.some(s=>ju(o,s.id))))return null;let n=[...e].sort((o,s)=>{let i=o.createdAt??"",a=s.createdAt??"";return i!==a?i<a?1:-1:o.id<s.id?1:-1});for(let o of Du){let s=n.find(i=>ju(o,i.id));if(s)return s.id}return n[0].id}function Yr(){return{default:null,roles:{}}}function ob(t,e){let r=t?.roles?.[e];return typeof r=="string"&&r.trim().length>0?r.trim():t?.default&&t.default.trim().length>0?t.default.trim():eo[e]??Lu}function sb(t){let e=t?.provider;return typeof e=="string"&&e.trim().length>0?e.trim():Ge}function ib(t){let e=Yr();if(!t||typeof t!="object")return e;let r=t.llm;if(!r||typeof r!="object")return e;let n=r.provider;typeof n=="string"&&n.trim().length>0&&(e.provider=n.trim());let o=r.models;if(!o||typeof o!="object")return e;for(let[s,i]of Object.entries(o))typeof i!="string"||i.trim().length===0||(s==="default"?e.default=i.trim():e.roles[s]=i.trim());return e}function ab(t){let e=typeof t.provider=="string"&&t.provider.trim().length>0&&t.provider.trim()!==Ge;if(t.default===null&&Object.keys(t.roles).length===0&&!e)return null;let{provider:r,...n}=t;return JSON.stringify(e?{provider:r.trim(),...n}:n)}function cb(t){if(!t)return Yr();try{let e=JSON.parse(t);if(!e||typeof e!="object")return Yr();let r=e,n=Yr();typeof r.provider=="string"&&r.provider.trim().length>0&&(n.provider=r.provider.trim()),typeof r.default=="string"&&(n.default=r.default);let o=r.roles;if(o&&typeof o=="object")for(let[s,i]of Object.entries(o))typeof i=="string"&&(n.roles[s]=i);return n}catch{return Yr()}}var Ge,fa,Ee,Qn,Jo,Zo,Nu,Ou,ma,eo,Lu,Du,Mu,ga=S(()=>{"use strict";pa();Ge="claude",fa=[Ge],Ee="opus",Qn="sonnet",Jo="haiku",Zo=[Ee,Qn,Jo],Nu="build-discovery",Ou=[Nu],ma=[...da,...Ou],eo={analyze:Ee,implement:Ee,"resolve-conflict":Ee,rework:Ee,estimate:Qn,build:Jo,"build-discovery":Ee,"code-review":Ee,draft:Qn,index:Ee,backfill:Ee,analysis:Ee,chat:Ee,observer:Ee,council:Ee,testing:Ee},Lu=Ee,Du=[Ee,Qn,Jo],Mu=Array.from(new Set(Object.values(eo)))});function Pt(t){return lb.has(t)?!0:ub.some(e=>t.startsWith(e))}function Qo(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function gr(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function ka(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function ba(t,e){let r=Qo(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=gr(r.id,"id")??n;if(!ya.test(o))throw new Error(`id must match ${ya} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let s=gr(r.title,"title")?.trim()||o,i;if(r.env!==void 0&&r.env!==null){let p=Qo(r.env,"env");i={};for(let[d,m]of Object.entries(p)){if(!He.test(d))throw new Error(`env name "${d}" must match ${He}`);if(typeof m!="string"&&typeof m!="number"&&typeof m!="boolean")throw new Error(`env.${d} must be a scalar`);i[d]=String(m)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>Uu)throw new Error(`too many params (max ${Uu})`);let p=new Set;a=c.map((d,m)=>db(d,m,p))}let l=r.steps;if(!Array.isArray(l)||l.length===0)throw new Error("steps must be a non-empty list");if(l.length>Bu)throw new Error(`too many steps (max ${Bu})`);let u=l.map((p,d)=>{let m=Qo(p,`steps[${d}]`),f=gr(m.run,`steps[${d}].run`);if(!f||f.trim().length===0)throw new Error(`steps[${d}].run is required`);let g=gr(m.name,`steps[${d}].name`),h=ka(m.timeout_sec,`steps[${d}].timeout_sec`);if(h!==void 0&&(!Number.isInteger(h)||h<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:f,...g?{name:g}:{},...h!==void 0?{timeout_sec:h}:{}}});return{id:o,title:s,...i?{env:i}:{},...a?{params:a}:{},steps:u}}function db(t,e,r){let n=Qo(t,`params[${e}]`),o=gr(n.name,`params[${e}].name`);if(!o||!He.test(o))throw new Error(`params[${e}].name must match ${He}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let s=n.type;if(s!=="string"&&s!=="enum"&&s!=="number"&&s!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let i;if(s==="enum"){let m=n.enum;if(!Array.isArray(m)||m.length===0||!m.every(f=>typeof f=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);i=m}let a=gr(n.label,`params[${e}].label`),c=gr(n.help,`params[${e}].help`),l=n.required===!0,u=ka(n.min,`params[${e}].min`),p=ka(n.max,`params[${e}].max`),d=n.default;if(d!=null&&typeof d!="string"&&typeof d!="number"&&typeof d!="boolean")throw new Error(`params[${e}].default must be a scalar`);return{name:o,type:s,...a?{label:a}:{},...c?{help:c}:{},...l?{required:!0}:{},...i?{enum:i}:{},...u!==void 0?{min:u}:{},...p!==void 0?{max:p}:{},...d!=null?{default:d}:{}}}function $a(t,e){let r=t.params??[],n=new Map(r.map(s=>[s.name,s]));for(let s of Object.keys(e))if(!n.has(s))return{ok:!1,error:`unknown param: ${s}`};let o={};for(let s of r){let i=e[s.name];if(i==null||typeof i=="string"&&i.trim()==="")if(s.default!==void 0)i=s.default;else{if(s.required)return{ok:!1,error:`${s.name} is required`};continue}switch(s.type){case"string":{if(typeof i!="string")return{ok:!1,error:`${s.name} must be a string`};o[s.name]=i;break}case"enum":{if(typeof i!="string"||!(s.enum??[]).includes(i))return{ok:!1,error:`${s.name} must be one of: ${(s.enum??[]).join(", ")}`};o[s.name]=i;break}case"number":{let a=typeof i=="number"?i:typeof i=="string"?Number(i):NaN;if(!Number.isFinite(a))return{ok:!1,error:`${s.name} must be a number`};if(s.min!==void 0&&a<s.min)return{ok:!1,error:`${s.name} must be \u2265 ${s.min}`};if(s.max!==void 0&&a>s.max)return{ok:!1,error:`${s.name} must be \u2264 ${s.max}`};o[s.name]=a;break}case"boolean":{let a=typeof i=="boolean"?i:i==="true"?!0:i==="false"?!1:null;if(a===null)return{ok:!1,error:`${s.name} must be a boolean`};o[s.name]=a;break}}}return{ok:!0,values:o}}var He,lb,ub,wa,ya,Uu,Bu,va=S(()=>{"use strict";He=/^[A-Z][A-Z0-9_]*$/,lb=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),ub=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];wa=600,ya=/^[a-z0-9-]+$/,Uu=32,Bu=64});function Fu(){return{primary:ye,context:ye,tasks:ye,docs:ye,code_comments:ye,chat:ye}}function Ku(t){return!t||t.trim().length===0||t.trim().toLowerCase()===ye}function pb(t){if(typeof t!="string")return ye;let e=t.trim().replace(/\s+/g," ");return e.length===0||e.length>40||e.toLowerCase()===ye?ye:e}function fb(t){let e=Fu();if(!t||typeof t!="object")return e;let r=t.language;if(!r||typeof r!="object"||Array.isArray(r))return e;let n=r;for(let o of to)e[o]=pb(n[o]);return e}function mb(t){return to.every(e=>Ku(t[e]))}var ye,to,Vr,ro,xa=S(()=>{"use strict";ye="auto",to=["primary","context","tasks","docs","code_comments","chat"],Vr=["English","Russian","German","Spanish","French","Portuguese","Italian","Chinese","Japanese","Korean"],ro=40});function Ia(t=Gu){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...Ia(r.groups));return e}function Hu(t,e){let r=JSON.stringify(e);return Ia().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function Ta(t){let e=Hu(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let s=r.trim();return e.type==="string"&&e.mustContain&&!s.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:e.maxLength!==void 0&&s.length>e.maxLength?{ok:!1,error:`${e.id} must be \u2264 ${e.maxLength} chars`}:{ok:!0,field:e,value:s}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let s=r.trim();return e.suggestions?.includes(s)?{ok:!0,field:e,value:s}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let s=r.map(i=>typeof i=="string"?i.trim():"").filter(i=>i.length>0);return s.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:s}}case"string_map":{if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,error:`${e.id} must be a name\u2192value map`};let s=Object.entries(r);if(s.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(s.length>Sa)return{ok:!1,error:`${e.id} must have \u2264 ${Sa} entries`};let i={};for(let[a,c]of s){if(!He.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${He}`};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>Ea)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${Ea} chars`};i[a]=c}return{ok:!0,field:e,value:i}}}}var hb,gb,Sa,Ea,Ra,Gu,Wu=S(()=>{"use strict";va();ga();ca();xa();hb={primary:"Primary language",context:"Context documents",tasks:"Tracker issues",docs:"Repo documentation",code_comments:"Code comments",chat:"Agent chat"},gb={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."},Sa=64,Ea=2e3,Ra=2e3,Gu=[{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:[...fa],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:[...Zo],help:"Overrides the recommended defaults for every role not listed below."},...ma.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Zo],help:`recommended: ${eo[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:Ra,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:Ra,help:`e.g. "implementation details, bullet list of what was done, in the tracker's language". Empty \u21D2 the default PR body.`}]},{id:"apply.delivery",label:"Delivery & merge",help:"How a finished change reaches the repository: with or without a pull request, and who merges it.",fields:[{id:"apply.pull_request",file:"project.yaml",path:["apply","pull_request"],type:"boolean",label:"Open a pull request",nullable:!1,help:"On (default): the task branch is pushed and a pull request is opened \u2014 the change is reviewable in the git host and keeps a history of review comments. Off: no PR at all; the branch is merged into the default branch directly, and the agent's review remarks live only in the dashboard and the Context Repo."},{id:"apply.done",file:"project.yaml",path:["apply","done"],type:"enum",label:"Task is done when",nullable:!1,suggestions:["merge","branch"],help:"merge (default): the task is finished only once its change lands in the default branch. branch: the task ends at the pushed branch (plus the PR, if enabled) and nothing is merged for you."},{id:"apply.auto_merge",file:"project.yaml",path:["apply","auto_merge"],type:"enum",label:"Auto-merge pull requests",nullable:!1,suggestions:["off","on_ci_green"],help:"Applies to the pull-request path only. off (default): the merge waits for you (Approve on the task card). on_ci_green: as soon as the PR is open, conflict-free and its CI is green, CodePipe merges it \u2014 changes reach the default branch with no further review from you. Requires full automation; branch protection on the host still applies (a refused merge parks the task). Without pull requests, full automation merges the branch itself and this switch does not apply."}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{id:"testing",label:"Testing",help:"An optional phase after code review: writes the test plan you run in the morning and reports what it could verify.",fields:[{id:"testing.enabled",file:"regimen.yaml",path:["testing","enabled"],type:"boolean",nullable:!1,label:"Run the testing phase",help:"Off by default. When on, a task passing code review goes through a test pass before the PR: it derives TESTPLAN.md from the plan's requirements and reports per requirement what it could verify. A requirement it finds broken sends the change back for a fix (bounded below)."},{id:"testing.max_iterations",file:"regimen.yaml",path:["testing","max_iterations"],type:"number",nullable:!0,min:1,max:10,label:"Fix rounds before stopping",help:"How many times a failed test pass may send the change back before the task waits for you. Empty \u21D2 2."}]},{id:"skills",label:"Skills",help:"Reusable procedures the agent can invoke instead of improvising. Only their names and one-line descriptions sit in the prompt; the steps load when a skill is used.",fields:[{id:"skills.from_bundled",file:"regimen.yaml",path:["skills","from_bundled"],type:"boolean",nullable:!1,label:"Use the skills shipped with CodePipe",help:"On by default. General procedures maintained with the product."},{id:"skills.from_context_repo",file:"regimen.yaml",path:["skills","from_context_repo"],type:"boolean",nullable:!1,label:"Use this project's skills",help:"On by default. Skills the team writes in the context repository under `skills/<name>/SKILL.md`. These override a bundled skill of the same name."},{id:"skills.from_project_repo",file:"regimen.yaml",path:["skills","from_project_repo"],type:"boolean",nullable:!1,label:"Use the code repository's skills",help:"On by default. `.claude/skills/` inside the project repositories \u2014 the skills your developers already use locally. These win over both other sources."}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (on by default; orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on (default), a task taken from Develop waits in the QUEUE for a single Confirm before the pipeline starts \u2014 the Confirm pulls in dependency closure and topologically orders the queue. Off \u21D2 conveyor: the task starts the pipeline immediately."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]},{id:"language",label:"Language",help:"Languages the agent writes in, per area. Empty \u21D2 auto: mirror the language of the user's material.",fields:to.map(t=>({id:`language.${t}`,file:"project.yaml",path:["language",t],type:"string",label:hb[t],nullable:!0,maxLength:40,suggestions:t==="chat"?[ye,...Vr]:[...Vr],help:gb[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 ${Qe.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 ${Qe.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 ${Qe.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 ${Qe.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 ${Qe.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 ${Qe.topK}.`}]},{id:"context.job_logs",label:"Job transcripts",help:"Whether the raw agent transcript of each job is kept in the Context Repo.",fields:[{id:"context.job_logs.enabled",file:"regimen.yaml",path:["context","job_logs","enabled"],type:"boolean",label:"Keep transcripts in the Context Repo",nullable:!1,help:"Off (default): the transcript is discarded after the run \u2014 nothing lands in the Context Repo. On: each job's raw transcript is committed as tasks/<KEY>/logs/job-<id>.jsonl for post-mortem debugging."}]}]});function qu(t){if(t==null)return[];if(!Array.isArray(t))return null;let e=[];for(let r of t){if(typeof r!="string"||r.trim().length===0)return null;e.push(r.trim())}return e}function Aa(t){let{name:e,body:r,origin:n}=t;if(!Ca.test(e))return{ok:!1,error:`role name must match ${Ca} (got "${e}")`};if(r.trim().length===0)return{ok:!1,error:"role body is empty \u2014 the body IS the role's prompt"};let o=t.frontmatter;if(o==null||typeof o!="object"||Array.isArray(o))return{ok:!1,error:"missing or malformed frontmatter block"};let s=o,i=s.description;if(typeof i!="string"||i.trim().length===0)return{ok:!1,error:"description is required (one line: what this role looks for)"};if(i.length>300)return{ok:!1,error:"description must be \u2264 300 characters"};let a=qu(s.refs);if(a===null)return{ok:!1,error:"refs must be a list of non-empty paths"};if(a.length>10)return{ok:!1,error:"refs must list at most 10 files \u2014 a role is a narrow view"};for(let d of a)if(d.startsWith("/")||d.includes(".."))return{ok:!1,error:`ref "${d}" must be a path inside the Context Repo`};let c=qu(s.scenarios);if(c===null)return{ok:!1,error:"scenarios must be a list"};let l=[];for(let d of c){if(!es.includes(d))return{ok:!1,error:`unknown scenario "${d}" \u2014 one of: ${es.join(", ")}`};l.includes(d)||l.push(d)}if(l.length===0)return{ok:!1,error:`scenarios must name at least one of: ${es.join(", ")}`};let u=s.model;if(u!==void 0&&(typeof u!="string"||u.trim().length===0))return{ok:!1,error:"model must be a non-empty string when set"};let p=s.enabled;return p!==void 0&&typeof p!="boolean"?{ok:!1,error:"enabled must be true or false"}:{ok:!0,role:{name:e,description:i.trim(),...typeof u=="string"?{model:u.trim()}:{},refs:a,scenarios:l,enabled:p!==!1,body:r.trim(),origin:n}}}function Pa(t,e){let r=new Map;for(let n of t)r.set(n.name,n);for(let n of e)r.set(n.name,n);return[...r.values()].sort((n,o)=>n.name<o.name?-1:n.name>o.name?1:0)}function _a(t,e){return t.filter(r=>r.enabled&&r.scenarios.includes(e))}var es,Ca,QA,eP,Yu=S(()=>{"use strict";es=["plan_review","code_review","council"],Ca=/^[a-z][a-z0-9-]{1,39}$/,QA=10,eP=300});function ja(t){return Vu.includes(t)}function Na(t){return`prompts/${t}.md`}var Vu,zu=S(()=>{"use strict";Vu=["analysis","analyze","backfill","build","chat","code-review","code-review-external","code-review-fix","council","draft","estimate","implement","index","observer","resolve-conflict","rework","testing"]});function La(t){if(!Oa.test(t.name))return{ok:!1,error:`skill directory name must match ${Oa}`};if(t.body.trim().length===0)return{ok:!1,error:"SKILL.md has no body \u2014 the body IS the procedure"};let e=t.frontmatter;if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"SKILL.md has no frontmatter block"};let r=e.description;return typeof r!="string"||r.trim().length===0?{ok:!1,error:"description is required \u2014 it is what decides when the skill fires"}:r.length>300?{ok:!1,error:"description must be \u2264 300 characters"}:{ok:!0,skill:{name:t.name,description:r.trim()}}}function Da(t,e,r){let n=new Map;for(let o of[...t,...e,...r])n.set(o.name,o);return[...n.values()].sort((o,s)=>o.name<s.name?-1:o.name>s.name?1:0)}function Ju(t){let e=t.trim(),r=e.lastIndexOf("@"),n=r===-1?e:e.slice(0,r),o=r===-1?"":e.slice(r+1).trim();if(!yb.test(n))return{ok:!1,error:`"${t}": expected <owner>/<repo>[@<40-hex sha>]`};let s=Xu.find(i=>i.repo.toLowerCase()===n.toLowerCase());return o&&!kb.test(o)?{ok:!1,error:`"${t}": pin to a full 40-character commit sha \u2014 a branch or tag can change under you`}:!s&&!o?{ok:!1,error:`"${t}": a third-party marketplace must be pinned to a commit (<owner>/<repo>@<sha>). Its skills run beside your code with the agent's token.`}:{ok:!0,source:{repo:n,sha:o,name:s?.name??n.replace("/","-").toLowerCase(),official:!!s}}}function wb(t){let e=[],r=[],n=new Set;for(let o of t){if(!o.trim())continue;let s=Ju(o);if(!s.ok){r.push(s.error);continue}n.has(s.source.name)||(n.add(s.source.name),e.push(s.source))}return{sources:e,errors:r}}function $b(t,e){let r=new Set(e.map(s=>s.name)),n={},o=[];for(let s of t){let i=s.trim();if(i){if(!bb.test(i)||!r.has(i.slice(i.indexOf("@")+1))){o.push(i);continue}n[i]=!0}}return{enabled:n,unknown:o}}var Oa,nP,Xu,yb,kb,bb,Zu=S(()=>{"use strict";Oa=/^[a-z][a-z0-9-]{1,39}$/,nP=300;Xu=[{repo:"anthropics/skills",name:"anthropic-agent-skills"},{repo:"anthropics/claude-plugins-official",name:"claude-plugins-official"}],yb=/^[A-Za-z0-9][\w.-]*\/[A-Za-z0-9][\w.-]*$/,kb=/^[0-9a-f]{40}$/;bb=/^[A-Za-z0-9][\w.-]*@[A-Za-z0-9][\w.-]*$/});function Qu(t,e){if(t==null)return[];if(!Array.isArray(t)||t.length>e)return null;let r=[];for(let n of t){if(typeof n!="string"||n.trim().length===0)return null;r.push(n.trim())}return r}function vb(t,e){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:"queue plan must be a JSON object"};let r=new Set(e),n=t,o=Qu(n.order,e.length);if(o===null)return{ok:!1,error:"order must be a list of task keys"};for(let f of o)if(!r.has(f))return{ok:!1,error:`order names ${f}, which is not in this batch`};if(new Set(o).size!==o.length)return{ok:!1,error:"order repeats a task key"};let s=e.filter(f=>!o.includes(f));if(o.length>0&&s.length>0)return{ok:!1,error:`order omits ${s.join(", ")}`};let i=n.tasks,a=[];if(i!=null){if(!Array.isArray(i))return{ok:!1,error:"tasks must be a list"};for(let f of i){if(!f||typeof f!="object")return{ok:!1,error:"each task entry must be an object"};let g=f,h=typeof g.taskKey=="string"?g.taskKey.trim():"";if(!r.has(h))return{ok:!1,error:`tasks names ${h||"(empty)"}, which is not in this batch`};let w=Qu(g.after,e.length);if(w===null)return{ok:!1,error:`${h}: after must be a list of task keys`};for(let v of w){if(!r.has(v))return{ok:!1,error:`${h}: after names ${v}, not in this batch`};if(v===h)return{ok:!1,error:`${h}: cannot come after itself`}}let y=typeof g.decisions=="string"?g.decisions.trim():"";a.push({taskKey:h,decisions:y.slice(0,4e3),after:w})}}let c=[],l=n.conflicts;if(Array.isArray(l))for(let f of l){if(!f||typeof f!="object")continue;let g=f,h=typeof g.taskKey=="string"?g.taskKey.trim():"",w=typeof g.adr=="string"?g.adr.trim():"",y=typeof g.detail=="string"?g.detail.trim():"";!r.has(h)||!y||c.push({taskKey:h,adr:w,detail:y.slice(0,4e3)})}let u=[],p=n.related;if(Array.isArray(p))for(let f of p){if(!f||typeof f!="object")continue;let g=f,h=typeof g.taskKey=="string"?g.taskKey.trim():"",w=typeof g.detail=="string"?g.detail.trim():"";!h||!w||u.push({taskKey:h,detail:w.slice(0,4e3)})}let d=typeof n.summary=="string"?n.summary.trim().slice(0,4e3):"",m=n.deferBehind===!0;return{ok:!0,plan:{order:o,tasks:a,conflicts:c,related:u,summary:d,deferBehind:m}}}var sP,iP,ed=S(()=>{"use strict";sP=4e3,iP=4e3});function xb(t,e){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:"council verdict must be a JSON object"};let r=t,n=r.unresolved===!0,o=typeof r.fork=="string"?r.fork.trim().slice(0,4e3):"";if(n)return o?{ok:!0,verdict:{answers:[],unresolved:!0,fork:o}}:{ok:!1,error:"an unresolved verdict must describe the fork"};let s=r.answers;if(!Array.isArray(s))return{ok:!1,error:"answers must be a list"};if(s.length!==e.length)return{ok:!1,error:`expected ${e.length} answer(s), got ${s.length}`};let i=[];for(let[a,c]of s.entries()){if(!c||typeof c!="object")return{ok:!1,error:`answer ${a+1} must be an object`};let l=c,u=typeof l.answer=="string"?l.answer.trim():"";if(!u)return{ok:!1,error:`answer ${a+1} is empty`};i.push({question:typeof l.question=="string"?l.question.trim():e[a],answer:u.slice(0,4e3),rationale:typeof l.rationale=="string"?l.rationale.trim().slice(0,4e3):""})}return{ok:!0,verdict:{answers:i,unresolved:!1,fork:""}}}var cP,td=S(()=>{"use strict";cP=4e3});function Rb(t){let e=t.replace(/^#+\s*/,"").trim();for(let r of Sb)if(r.re.test(e))return{kind:r.kind,letter:r.letter};return null}function Ma(t){let e=[],r=new Map,n="",o=null,s=null;for(let a of t.split(`
|
|
8
|
+
`)){let c=/^#{1,6}\s+(.*)$/.exec(a);if(c){n=c[1].trim(),o=Rb(n),s=null;continue}let l=Eb.exec(a);if(l&&o){let u=l[1];r.set(u,(r.get(u)??0)+1),s={id:u,kind:o.kind,text:l[2].trim(),section:n},e.push(s);continue}if(s&&a.trim()&&!/^#{1,6}\s/.test(a)&&!/^\s*[-*]\s/.test(a)){s.text=`${s.text}
|
|
9
|
+
${a.trim()}`.trim();continue}a.trim()||(s=null)}let i=[...r.entries()].filter(([,a])=>a>1).map(([a])=>a);return{items:e,structured:e.length>=2&&i.length===0,duplicateIds:i}}function Ib(t){let e={decision:"D",change:"C",assumption:"A",out_of_scope:"O",test:"T",procedure:"P"};return t.items.filter(r=>!r.id.startsWith(e[r.kind]))}function Tb(t,e){let r=new Map(t.items.map(i=>[i.id,i])),n=e.filter(i=>!i.approved),o=e.filter(i=>i.approved).map(i=>i.id);if(n.length===0)return"";let s=["Rejected plan items:",""];for(let i of n){let a=r.get(i.id),c=a?`${i.id} \u2014 ${a.text.split(`
|
|
10
10
|
`)[0]}`:i.id;s.push(`- **${c}**`),i.remark?.trim()&&s.push(` ${i.remark.trim()}`)}return o.length>0&&s.push("",`Approved and settled: ${o.join(", ")}. Do not revisit these unless a`,"rejected item forces it \u2014 and say so explicitly if it does."),s.join(`
|
|
11
|
-
`)}function
|
|
12
|
-
`)){let s=
|
|
13
|
-
${o.trim()}`.trim())}let n={};for(let o of e)n[o.id]=o;return{items:e,byId:n}}function l$(t,e){let r=new Set(t);return{unreported:t.filter(n=>!(n in e.byId)),unknown:e.items.filter(n=>!r.has(n.id)).map(n=>n.id),notDone:e.items.filter(n=>n.status!=="done")}}var i$,a$,hd=v(()=>{"use strict";i$=["done","deviated","partial","dropped"],a$=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*[—:-]?\s*(done|deviated|partial|dropped)\b\s*[—:-]?\s*(.*)$/i});var gd=v(()=>{"use strict"});var yd=v(()=>{"use strict"});var kd=v(()=>{"use strict"});function Ma(t){return`codepipe-host-${t}`}function u$(t){let e=t.filter(r=>r!=="self-hosted");return`runs-on: [self-hosted${e.length?", "+e.join(", "):""}]`}var wd=v(()=>{"use strict"});function d$(t,e){return(t&&t.includes("<TASK_ID>")?t:bd).replace(/<TASK_ID>/g,e.toLowerCase())}function p$(t,e){if(t)return`${t.replace(/\/+$/,"")}/issue/${encodeURIComponent(e)}`}function Ua(t){return!(!t||t.length>250||!/^[A-Za-z0-9._/-]+$/.test(t)||/^[-/.]/.test(t)||/[/.]$/.test(t)||t.endsWith(".lock")||t.includes("..")||t.includes("//")||t.includes("/."))}function wt(t){return`${t}${$d}`}var bd,Kt,$d,vd=v(()=>{"use strict";bd="codepipe/<TASK_ID>";Kt=/^[a-z][a-z0-9-]{1,30}$/,$d="-codepipe-ctx"});function f$(t,e){return`${t}:${e}`}var xd=v(()=>{"use strict"});function Sd(t){let e=(t??"").trim();return/^pr_closed_without_merge\b/.test(e)?"blocked":/^(merge_failed|close_failed)\b/.test(e)||/^chain_base_changed\b/.test(e)?"conflict":/^(build_failed|ci_failed)\b/.test(e)?"loop_exhausted":"error"}function m$(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.to==="NEEDS_MANUAL")return r}return null}function h$(t,e){if(t==="AWAITING_ANSWER")return{kind:"question"};if(t==="NEEDS_MANUAL"){let n=m$(e)?.reason,o={kind:Sd(n)};return n&&(o.reason=n),o}}var Ed=v(()=>{"use strict"});function yr(t){for(let e of Rd){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var Rd,Id=v(()=>{"use strict";Rd=[{name:"rework",pattern:/^@(?:codepipe|devpipe)\s+rework:\s*(.+)$/im,description:"Send the task back to ANALYZING with a new instruction.",hasArg:!0},{name:"approve",pattern:/^@(?:codepipe|devpipe)\s+approve\s*$/im,description:"Merge every PR for this task (TRACKING only)."},{name:"reject",pattern:/^@(?:codepipe|devpipe)\s+reject(?::\s*(.+))?\s*$/im,description:"Abandon this task: close any open PR(s) and move it to DONE (reason rejected_and_closed). Valid from any non-terminal phase; from early phases it just skips the task.",hasArg:!0},{name:"merge",pattern:/^@(?:codepipe|devpipe)\s+merge\s*$/im,description:"Merge the task branch into the default branch without a PR (direct apply path, apply.pull_request=false; TRACKING only)."},{name:"rebase",pattern:/^@(?:codepipe|devpipe)\s+rebase\s*$/im,description:"Re-apply the patch on top of the latest base branch and force-push. Use after a PR merge conflict or APPLYING failure."},{name:"update",pattern:/^@(?:codepipe|devpipe)\s+update(?::\s*(.+))?\s*$/im,description:"Update a conflicting PR: resolve conflicts against the current base branch (TRACKING only). Optional `: <instruction>` is forwarded to the agent.",hasArg:!0},{name:"apply",pattern:/^@(?:codepipe|devpipe)\s+apply:\s*(local|auto)\s*$/im,description:"Override apply mode for this task: local (you apply by hand) or auto.",hasArg:!0},{name:"fix",pattern:/^@(?:codepipe|devpipe)\s+fix\s*$/im,description:"Fix the external review remarks on the developer's branch (waiting-for-fix state only)."}]});var Td=v(()=>{"use strict"});function Cd(t){let e=Math.max(1,Math.round(t));if(e<60)return`${e}s`;let r=Math.round(e/60);if(r<60)return`${r}m`;let n=Math.round(r/60);return n<24?`${n}h`:`${Math.round(n/24)}d`}function g$(t,e=Date.now()){return`${Cd((e-t)/1e3)} ago`}function y$(t){let e=Math.floor(t/86400),r=Math.floor(t%86400/3600),n=Math.floor(t%3600/60);return e>0?`${e}d ${r}h`:r>0?`${r}h ${n}m`:`${n}m`}var Ad=v(()=>{"use strict"});var Pd=v(()=>{"use strict"});function _d(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function Fa(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=_d(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(kr.test(r))return r;let n=_d(t);return kr.test(n)?n:ts}function Ka(t,e){let r=new Set([...e].map(n=>n.toUpperCase()));if(!r.has(t.toUpperCase()))return t;for(let n=1;n<1e4;n++){let o=String(n),s=t.slice(0,10-o.length)+o;if(!r.has(s.toUpperCase()))return s}return t}function Xr(t){return`tasks/${t}/issue.yaml`}var Ba,no,ts,kr,rs,k$,oo,zr,jd=v(()=>{"use strict";Ba=["bug","feature","epic"],no="feature",ts="TASK",kr=/^[A-Z][A-Z0-9]{1,9}$/;rs={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},k$=rs.backlog,oo="tracker/config.yaml",zr="tracker/counter"});var w$,Nd=v(()=>{"use strict";w$="youtrack"});function wr(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 so(t){switch(t){case Jr.gitlab:return"oauth2";case Jr.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Jr,Gt,Od=v(()=>{"use strict";Jr={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Gt="x-bitbucket-api-token-auth"});var Ld=v(()=>{"use strict"});var Dd=v(()=>{"use strict";Nd();Od();Ld()});var Md={};Fe(Md,{ACTION_ID_RE:()=>ha,ACTION_STEP_DEFAULT_TIMEOUT_SEC:()=>ya,ALL_JOB_ROLES:()=>la,ALL_MODEL_ROLE_KEYS:()=>pa,ANALYSIS_MAX_DRAFTS:()=>Ga,ANNOTATION_MAX_PER_TASK:()=>ta,BACKFILL_MAX_DRAFTS:()=>b$,BITBUCKET_API_TOKEN_GIT_USER:()=>Gt,BUILD_DISCOVERY:()=>qu,COCHANGE_DEFAULTS:()=>Qe,CODEPIPE_COMMANDS:()=>Rd,COMMIT_STYLE_MAX_LENGTH:()=>Sa,CONTEXT_PACK_DECAY:()=>na,CONTEXT_PACK_DEFAULTS:()=>mr,CONTEXT_REPO_SUFFIX:()=>$d,CONTEXT_STAMP_FILE:()=>lt,CONTEXT_TEMPLATE_CHANGELOG:()=>Gi,CONTEXT_TEMPLATE_VERSION:()=>Cu,COUNCIL_MAX_ANSWER:()=>BP,DEFAULT_BRANCH_PATTERN:()=>bd,DEFAULT_HUB_URL:()=>at,DEFAULT_INTERNAL_ISSUE_TYPE:()=>no,DEFAULT_INTERNAL_TRACKER_PREFIX:()=>ts,DEFAULT_LLM_PROVIDER:()=>Ge,DEFAULT_REGIMEN_ALIASES:()=>Xu,DEFAULT_TRACKER_PROVIDER:()=>w$,ENV_NAME_RE:()=>He,FALLBACK_MODEL:()=>Vu,GIT_HOST_DOMAINS:()=>Jr,INTERNAL_ISSUE_TYPES:()=>Ba,INTERNAL_TRACKER_CONFIG_PATH:()=>oo,INTERNAL_TRACKER_COUNTER_PATH:()=>zr,INTERNAL_TRACKER_DEFAULT_STATUS:()=>k$,INTERNAL_TRACKER_PREFIX_RE:()=>kr,INTERNAL_TRACKER_STATUSES:()=>rs,LANE_PHASES:()=>Cb,LANE_SEGMENTS:()=>ca,LANGUAGE_AUTO:()=>ye,LANGUAGE_SUGGESTIONS:()=>Vr,LANGUAGE_VALUE_MAX_LENGTH:()=>ro,LEGACY_CONTEXT_STAMP_FILE:()=>Hr,LLM_PROVIDER_SUGGESTIONS:()=>da,MIN_SUPPORTED_PROTOCOL:()=>Ru,MODEL_ALIAS_SUGGESTIONS:()=>Zo,MODEL_DERIVED_DIR:()=>vb,MODEL_DERIVED_INDEX_PATH:()=>Yo,MODEL_DIR:()=>wb,MODEL_EDGE_KINDS:()=>Qi,MODEL_ENTITY_ID_RE:()=>ju,MODEL_FACTS_DIR:()=>$b,MODEL_FAMILY_PREFERENCE:()=>zu,MODEL_HAIKU:()=>Jo,MODEL_LEVELS:()=>_u,MODEL_OPUS:()=>Ee,MODEL_README_PATH:()=>bb,MODEL_RELATES_PATH:()=>dr,MODEL_SEARCH_MAX_LIMIT:()=>ra,MODEL_SEARCH_MAX_ROWS:()=>Sb,MODEL_SEARCH_ROW_TEXT_MAX:()=>zo,MODEL_SONNET:()=>Qn,MODEL_SUB_ROLES:()=>Yu,OBSERVER_MAX_DECISION:()=>DP,OBSERVER_MAX_SUMMARY:()=>MP,OFFICIAL_MARKETPLACES:()=>cd,PHASES:()=>aa,PIPELINE_COLUMNS:()=>Ku,PLANNING_LANE_MAX_JOBS:()=>jb,PLANNING_ROLES:()=>Hu,PLATFORM_VERSION:()=>Ke,PROJECT_ID_RE:()=>Kt,PROJECT_LANGUAGE_SECTIONS:()=>to,PROJECT_MODEL_FORMAT_VERSION:()=>_e,PROJECT_SETTINGS_MANIFEST:()=>td,PROMPT_ROLES:()=>id,PROTOCOL_VERSION:()=>ct,RECOMMENDED_ROLE_MODELS:()=>eo,RELATES_MIN_OVERLAP:()=>ea,ROLE_MAX_DESCRIPTION:()=>_P,ROLE_MAX_REFS:()=>PP,ROLE_NAME_RE:()=>Ia,ROLE_SCENARIOS:()=>es,SKILL_MAX_DESCRIPTION:()=>OP,SKILL_NAME_RE:()=>ja,SOLUTION_STATUSES:()=>i$,STRING_MAP_MAX_ENTRIES:()=>va,STRING_MAP_MAX_VALUE_LENGTH:()=>xa,additionsSince:()=>Wi,ago:()=>g$,attentionFor:()=>h$,autoLanguageConfig:()=>Qu,autoModelDefault:()=>fa,canonicalizeModelEdgeSheet:()=>Nu,canonicalizeModelIdentityTable:()=>Lu,canonicalizeModelShard:()=>Ou,canonicalizeModelTaskEvent:()=>Du,changesSince:()=>qi,classifyAttentionReason:()=>Sd,compilePlanRework:()=>o$,contextRepoName:()=>wt,deserializeModelConfig:()=>Mb,emptyModelConfig:()=>Yr,enabledPluginsSetting:()=>Jb,extractLanguageConfig:()=>Gb,findSettingField:()=>rd,firstFreeInternalTrackerPrefix:()=>Ka,flattenSettingFields:()=>Ea,fmtDuration:()=>Cd,fmtUptime:()=>y$,ghRunnerHostLabel:()=>Ma,ghRunnerRunsOnSnippet:()=>u$,gitCloneUrlDomain:()=>wr,httpsTokenUser:()=>so,internalIssueYamlPath:()=>Xr,isAllAutoLanguage:()=>Hb,isAutoLanguage:()=>ed,isBodyEditFrozen:()=>Tb,isModelEntityId:()=>Vo,isPromptRole:()=>Pa,isProtocolCompatible:()=>Yn,isReservedEnvName:()=>Pt,isTerminalPhase:()=>Ib,isValidBranchName:()=>Ua,jobLane:()=>_b,laneSegmentForPhase:()=>Ab,makeTaskId:()=>f$,mergeRoles:()=>Ca,mergeSkills:()=>Oa,mismatchedIds:()=>n$,modelAnnotationPath:()=>zi,modelComponentSlug:()=>Pu,modelCorrelatesPath:()=>Xi,modelEventPath:()=>pr,modelIdentityPath:()=>Xn,modelNodeKey:()=>fe,modelShardNeedsRebuild:()=>Eb,modelStructureShardPath:()=>Zi,modelTaskNodeKey:()=>ge,modelTouchedPath:()=>Ji,parseActionDefinition:()=>ka,parseCodepipeCommand:()=>yr,parseContextStamp:()=>Hi,parseMarketplaceSource:()=>ld,parseMarketplaces:()=>zb,parseModelConfig:()=>Lb,parseModelNodeKey:()=>re,parsePlanItems:()=>La,parseSolutionItems:()=>c$,pipelineColumnForPhase:()=>Pb,prescribedSkills:()=>Da,promptOverridePath:()=>_a,renderContextStamp:()=>Vn,resolveBranchName:()=>d$,resolveModelForRole:()=>Nb,resolveProvider:()=>Ob,rolesForScenario:()=>Aa,serializeModelConfig:()=>Db,serializeModelEdgeSheet:()=>fr,serializeModelIdentityTable:()=>sa,serializeModelShard:()=>oa,serializeModelTaskEvent:()=>qr,serializeModelYaml:()=>hr,solutionCoverage:()=>l$,suggestInternalTrackerPrefix:()=>Fa,validateActionInput:()=>wa,validateCouncilVerdict:()=>Qb,validateModelEdgeSheet:()=>Jn,validateModelIdentityTable:()=>Zn,validateModelShard:()=>Ct,validateModelTaskEvent:()=>At,validateObserverPlan:()=>Zb,validateRoleDefinition:()=>Ta,validateSettingEdit:()=>Ra,validateSkill:()=>Na,youtrackIssueUrl:()=>p$,zeroUsage:()=>Ft});var Ga,b$,F=v(()=>{"use strict";Iu();Tu();Au();ia();Fu();Gu();ua();ma();nd();$a();ba();sd();ad();ud();pd();fd();md();hd();gd();yd();kd();wd();vd();xd();Ed();Id();Td();Ad();Pd();jd();Dd();Ga=20,b$=15});function X(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Le=v(()=>{"use strict"});import{existsSync as $$,readFileSync as v$,readdirSync as x$}from"node:fs";import{dirname as S$,join as Ha}from"node:path";import{parse as E$}from"yaml";function R$(t=process.cwd()){let e=t;for(;;){if($$(Ha(e,_t,"project.yaml")))return e;let r=S$(e);if(r===e)return null;e=r}}function I$(t){return Ha(t,_t)}function Re(t=process.cwd()){let e=R$(t);if(!e)return null;let r=I$(e),n=T$(v$(Ha(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function Ud(t,e,r){return x$(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 ns(t,e=process.cwd()){try{let r=Re(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function T$(t){let e=E$(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),n=String(e.name??r),o=Array.isArray(e.repos)?e.repos:[],s=[];for(let i of o){if(!i||typeof i!="object")continue;let a=i,c=String(a.repo??a.repoName??""),l=String(a.name??c);if(!l||!c)continue;let u=a.host,p=u==="bitbucket"?"bitbucket":u==="gitlab"?"gitlab":"github";s.push({name:l,host:p,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l)})}return{projectId:r,name:n,repos:s}}function Bd(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}var _t,bt=v(()=>{"use strict";_t=".codepipe"});import{homedir as Fd}from"node:os";import{mkdirSync as C$,readFileSync as A$,writeFileSync as P$,existsSync as Wa}from"node:fs";import{dirname as Gd,join as os,resolve as _$}from"node:path";import{fileURLToPath as j$}from"node:url";function Hd(t){let e=os(Kd,".env");if(Wa(e)&&process.loadEnvFile(e),t){let r=os(Kd,"profiles",t,".env");Wa(r)&&process.loadEnvFile(r)}}function Zr(t){let e=X("CONFIG");return e||(t?os(Fd(),".codepipe","profiles",t,"config.json"):os(Fd(),".codepipe","config.json"))}function dt(t){let e=Zr(t);if(!Wa(e))return null;let r=A$(e,"utf-8");return JSON.parse(r)}function jt(t,e){let r=Zr(e);C$(Gd(r),{recursive:!0}),P$(r,JSON.stringify(t,null,2)+`
|
|
14
|
-
`,{mode:384})}function ss(t){if(t)return{cfg:et(t),profile:t};let e;try{e=Re()?.spec.projectId||void 0}catch{}if(e){let r=dt(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:et(void 0),profile:void 0}}function et(t){let e=dt(t);if(!e){let r=t?`codepipe init --profile ${t} --hub <url> --token <token> --project ${t}`:"codepipe init --hub <url> --token <token> --project <id>";console.error(t?`CLI profile '${t}' is not initialised. run \`${r}\` first.`:`CLI is not initialised. run \`${r}\` first.`),process.exit(1)}return e.projectId||(console.error(`config at ${Zr(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var
|
|
15
|
-
`,{mode:384})}function as(){return
|
|
16
|
-
`,{mode:384})}function Qr(t){let e=q(t)?.claude?.oauthToken;return e||
|
|
11
|
+
`)}function Ua(t){let e=new Set;for(let r of t.items)if(r.kind==="procedure")for(let n of r.text.matchAll(Cb))e.add(n[1]);return[...e]}var Sb,Eb,Cb,rd=S(()=>{"use strict";Sb=[{re:/^decisions?$/i,kind:"decision",letter:"D"},{re:/^changes?$/i,kind:"change",letter:"C"},{re:/^assumptions?$/i,kind:"assumption",letter:"A"},{re:/^out of scope$/i,kind:"out_of_scope",letter:"O"},{re:/^test strategy$/i,kind:"test",letter:"T"},{re:/^procedures?$/i,kind:"procedure",letter:"P"}],Eb=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*(.*)$/;Cb=/`([a-z][a-z0-9-]{1,39})`/g});function _b(t){let e=[],r=null;for(let o of t.split(`
|
|
12
|
+
`)){let s=Pb.exec(o);if(s){r={id:s[1],status:s[2].toLowerCase(),text:s[3].trim()},e.push(r);continue}if(/^#{1,6}\s/.test(o)||/^\s*[-*]\s/.test(o)||!o.trim()){r=null;continue}r&&(r.text=`${r.text}
|
|
13
|
+
${o.trim()}`.trim())}let n={};for(let o of e)n[o.id]=o;return{items:e,byId:n}}function jb(t,e){let r=new Set(t);return{unreported:t.filter(n=>!(n in e.byId)),unknown:e.items.filter(n=>!r.has(n.id)).map(n=>n.id),notDone:e.items.filter(n=>n.status!=="done")}}var Ab,Pb,nd=S(()=>{"use strict";Ab=["done","deviated","partial","dropped"],Pb=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*[—:-]?\s*(done|deviated|partial|dropped)\b\s*[—:-]?\s*(.*)$/i});var od=S(()=>{"use strict"});var sd=S(()=>{"use strict"});var id=S(()=>{"use strict"});function Ba(t){return`codepipe-host-${t}`}function Nb(t){let e=t.filter(r=>r!=="self-hosted");return`runs-on: [self-hosted${e.length?", "+e.join(", "):""}]`}var ad=S(()=>{"use strict"});function Ob(t,e){return(t&&t.includes("<TASK_ID>")?t:cd).replace(/<TASK_ID>/g,e.toLowerCase())}function Lb(t,e){if(t)return`${t.replace(/\/+$/,"")}/issue/${encodeURIComponent(e)}`}function Fa(t){return!(!t||t.length>250||!/^[A-Za-z0-9._/-]+$/.test(t)||/^[-/.]/.test(t)||/[/.]$/.test(t)||t.endsWith(".lock")||t.includes("..")||t.includes("//")||t.includes("/."))}function wt(t){return`${t}${ld}`}var cd,Kt,ld,ud=S(()=>{"use strict";cd="codepipe/<TASK_ID>";Kt=/^[a-z][a-z0-9-]{1,30}$/,ld="-codepipe-ctx"});function Db(t,e){return`${t}:${e}`}var dd=S(()=>{"use strict"});function pd(t){let e=(t??"").trim();return/^pr_closed_without_merge\b/.test(e)?"blocked":/^(merge_failed|close_failed)\b/.test(e)||/^chain_base_changed\b/.test(e)?"conflict":/^(build_failed|ci_failed)\b/.test(e)?"loop_exhausted":"error"}function Mb(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.to==="NEEDS_MANUAL")return r}return null}function Ub(t,e){if(t==="AWAITING_ANSWER")return{kind:"question"};if(t==="NEEDS_MANUAL"){let n=Mb(e)?.reason,o={kind:pd(n)};return n&&(o.reason=n),o}}var fd=S(()=>{"use strict"});function yr(t){for(let e of md){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var md,hd=S(()=>{"use strict";md=[{name:"rework",pattern:/^@(?:codepipe|devpipe)\s+rework:\s*(.+)$/im,description:"Send the task back to ANALYZING with a new instruction.",hasArg:!0},{name:"approve",pattern:/^@(?:codepipe|devpipe)\s+approve\s*$/im,description:"Merge every PR for this task (TRACKING only)."},{name:"reject",pattern:/^@(?:codepipe|devpipe)\s+reject(?::\s*(.+))?\s*$/im,description:"Abandon this task: close any open PR(s) and move it to DONE (reason rejected_and_closed). Valid from any non-terminal phase; from early phases it just skips the task.",hasArg:!0},{name:"merge",pattern:/^@(?:codepipe|devpipe)\s+merge\s*$/im,description:"Merge the task branch into the default branch without a PR (direct apply path, apply.pull_request=false; TRACKING only)."},{name:"rebase",pattern:/^@(?:codepipe|devpipe)\s+rebase\s*$/im,description:"Re-apply the patch on top of the latest base branch and force-push. Use after a PR merge conflict or APPLYING failure."},{name:"update",pattern:/^@(?:codepipe|devpipe)\s+update(?::\s*(.+))?\s*$/im,description:"Update a conflicting PR: resolve conflicts against the current base branch (TRACKING only). Optional `: <instruction>` is forwarded to the agent.",hasArg:!0},{name:"apply",pattern:/^@(?:codepipe|devpipe)\s+apply:\s*(local|auto)\s*$/im,description:"Override apply mode for this task: local (you apply by hand) or auto.",hasArg:!0},{name:"fix",pattern:/^@(?:codepipe|devpipe)\s+fix\s*$/im,description:"Fix the external review remarks on the developer's branch (waiting-for-fix state only)."}]});var gd=S(()=>{"use strict"});function yd(t){let e=Math.max(1,Math.round(t));if(e<60)return`${e}s`;let r=Math.round(e/60);if(r<60)return`${r}m`;let n=Math.round(r/60);return n<24?`${n}h`:`${Math.round(n/24)}d`}function Bb(t,e=Date.now()){return`${yd((e-t)/1e3)} ago`}function Fb(t){let e=Math.floor(t/86400),r=Math.floor(t%86400/3600),n=Math.floor(t%3600/60);return e>0?`${e}d ${r}h`:r>0?`${r}h ${n}m`:`${n}m`}var kd=S(()=>{"use strict"});var wd=S(()=>{"use strict"});function bd(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function Ga(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=bd(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(kr.test(r))return r;let n=bd(t);return kr.test(n)?n:ts}function Ha(t,e){let r=new Set([...e].map(n=>n.toUpperCase()));if(!r.has(t.toUpperCase()))return t;for(let n=1;n<1e4;n++){let o=String(n),s=t.slice(0,10-o.length)+o;if(!r.has(s.toUpperCase()))return s}return t}function Xr(t){return`tasks/${t}/issue.yaml`}var Ka,no,ts,kr,rs,Kb,oo,zr,$d=S(()=>{"use strict";Ka=["bug","feature","epic"],no="feature",ts="TASK",kr=/^[A-Z][A-Z0-9]{1,9}$/;rs={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},Kb=rs.backlog,oo="tracker/config.yaml",zr="tracker/counter"});var Gb,vd=S(()=>{"use strict";Gb="youtrack"});function wr(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 so(t){switch(t){case Jr.gitlab:return"oauth2";case Jr.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Jr,Gt,xd=S(()=>{"use strict";Jr={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Gt="x-bitbucket-api-token-auth"});var Sd=S(()=>{"use strict"});var Ed=S(()=>{"use strict";vd();xd();Sd()});var Rd={};Fe(Rd,{ACTION_ID_RE:()=>ya,ACTION_STEP_DEFAULT_TIMEOUT_SEC:()=>wa,ALL_JOB_ROLES:()=>da,ALL_MODEL_ROLE_KEYS:()=>ma,ANALYSIS_MAX_DRAFTS:()=>Wa,ANNOTATION_MAX_PER_TASK:()=>na,BACKFILL_MAX_DRAFTS:()=>Hb,BITBUCKET_API_TOKEN_GIT_USER:()=>Gt,BUILD_DISCOVERY:()=>Nu,COCHANGE_DEFAULTS:()=>Qe,CODEPIPE_COMMANDS:()=>md,COMMIT_STYLE_MAX_LENGTH:()=>Ra,CONTEXT_PACK_DECAY:()=>sa,CONTEXT_PACK_DEFAULTS:()=>mr,CONTEXT_REPO_SUFFIX:()=>ld,CONTEXT_STAMP_FILE:()=>lt,CONTEXT_TEMPLATE_CHANGELOG:()=>Wi,CONTEXT_TEMPLATE_VERSION:()=>yu,COUNCIL_MAX_ANSWER:()=>cP,DEFAULT_BRANCH_PATTERN:()=>cd,DEFAULT_HUB_URL:()=>at,DEFAULT_INTERNAL_ISSUE_TYPE:()=>no,DEFAULT_INTERNAL_TRACKER_PREFIX:()=>ts,DEFAULT_LLM_PROVIDER:()=>Ge,DEFAULT_REGIMEN_ALIASES:()=>Mu,DEFAULT_TRACKER_PROVIDER:()=>Gb,ENV_NAME_RE:()=>He,FALLBACK_MODEL:()=>Lu,GIT_HOST_DOMAINS:()=>Jr,INTERNAL_ISSUE_TYPES:()=>Ka,INTERNAL_TRACKER_CONFIG_PATH:()=>oo,INTERNAL_TRACKER_COUNTER_PATH:()=>zr,INTERNAL_TRACKER_DEFAULT_STATUS:()=>Kb,INTERNAL_TRACKER_PREFIX_RE:()=>kr,INTERNAL_TRACKER_STATUSES:()=>rs,LANE_PHASES:()=>Qw,LANE_SEGMENTS:()=>ua,LANGUAGE_AUTO:()=>ye,LANGUAGE_SUGGESTIONS:()=>Vr,LANGUAGE_VALUE_MAX_LENGTH:()=>ro,LEGACY_CONTEXT_STAMP_FILE:()=>Hr,LLM_PROVIDER_SUGGESTIONS:()=>fa,MIN_SUPPORTED_PROTOCOL:()=>mu,MODEL_ALIAS_SUGGESTIONS:()=>Zo,MODEL_DERIVED_DIR:()=>qw,MODEL_DERIVED_INDEX_PATH:()=>Yo,MODEL_DIR:()=>Gw,MODEL_EDGE_KINDS:()=>ta,MODEL_ENTITY_ID_RE:()=>$u,MODEL_FACTS_DIR:()=>Ww,MODEL_FAMILY_PREFERENCE:()=>Du,MODEL_HAIKU:()=>Jo,MODEL_LEVELS:()=>bu,MODEL_OPUS:()=>Ee,MODEL_README_PATH:()=>Hw,MODEL_RELATES_PATH:()=>dr,MODEL_SEARCH_MAX_LIMIT:()=>oa,MODEL_SEARCH_MAX_ROWS:()=>Vw,MODEL_SEARCH_ROW_TEXT_MAX:()=>zo,MODEL_SONNET:()=>Qn,MODEL_SUB_ROLES:()=>Ou,OBSERVER_MAX_DECISION:()=>sP,OBSERVER_MAX_SUMMARY:()=>iP,OFFICIAL_MARKETPLACES:()=>Xu,PHASES:()=>la,PIPELINE_COLUMNS:()=>Au,PLANNING_LANE_MAX_JOBS:()=>nb,PLANNING_ROLES:()=>_u,PLATFORM_VERSION:()=>Ke,PROJECT_ID_RE:()=>Kt,PROJECT_LANGUAGE_SECTIONS:()=>to,PROJECT_MODEL_FORMAT_VERSION:()=>_e,PROJECT_SETTINGS_MANIFEST:()=>Gu,PROMPT_ROLES:()=>Vu,PROTOCOL_VERSION:()=>ct,RECOMMENDED_ROLE_MODELS:()=>eo,RELATES_MIN_OVERLAP:()=>ra,ROLE_MAX_DESCRIPTION:()=>eP,ROLE_MAX_REFS:()=>QA,ROLE_NAME_RE:()=>Ca,ROLE_SCENARIOS:()=>es,SKILL_MAX_DESCRIPTION:()=>nP,SKILL_NAME_RE:()=>Oa,SOLUTION_STATUSES:()=>Ab,STRING_MAP_MAX_ENTRIES:()=>Sa,STRING_MAP_MAX_VALUE_LENGTH:()=>Ea,additionsSince:()=>Yi,ago:()=>Bb,attentionFor:()=>Ub,autoLanguageConfig:()=>Fu,autoModelDefault:()=>ha,canonicalizeModelEdgeSheet:()=>vu,canonicalizeModelIdentityTable:()=>Su,canonicalizeModelShard:()=>xu,canonicalizeModelTaskEvent:()=>Eu,changesSince:()=>Vi,classifyAttentionReason:()=>pd,compilePlanRework:()=>Tb,contextRepoName:()=>wt,deserializeModelConfig:()=>cb,emptyModelConfig:()=>Yr,enabledPluginsSetting:()=>$b,extractLanguageConfig:()=>fb,findSettingField:()=>Hu,firstFreeInternalTrackerPrefix:()=>Ha,flattenSettingFields:()=>Ia,fmtDuration:()=>yd,fmtUptime:()=>Fb,ghRunnerHostLabel:()=>Ba,ghRunnerRunsOnSnippet:()=>Nb,gitCloneUrlDomain:()=>wr,httpsTokenUser:()=>so,internalIssueYamlPath:()=>Xr,isAllAutoLanguage:()=>mb,isAutoLanguage:()=>Ku,isBodyEditFrozen:()=>Zw,isModelEntityId:()=>Vo,isPromptRole:()=>ja,isProtocolCompatible:()=>Yn,isReservedEnvName:()=>Pt,isTerminalPhase:()=>Jw,isValidBranchName:()=>Fa,jobLane:()=>rb,laneSegmentForPhase:()=>eb,makeTaskId:()=>Db,mergeRoles:()=>Pa,mergeSkills:()=>Da,mismatchedIds:()=>Ib,modelAnnotationPath:()=>Ji,modelComponentSlug:()=>wu,modelCorrelatesPath:()=>Zi,modelEventPath:()=>pr,modelIdentityPath:()=>Xn,modelNodeKey:()=>fe,modelShardNeedsRebuild:()=>zw,modelStructureShardPath:()=>ea,modelTaskNodeKey:()=>ge,modelTouchedPath:()=>Qi,parseActionDefinition:()=>ba,parseCodepipeCommand:()=>yr,parseContextStamp:()=>qi,parseMarketplaceSource:()=>Ju,parseMarketplaces:()=>wb,parseModelConfig:()=>ib,parseModelNodeKey:()=>re,parsePlanItems:()=>Ma,parseSolutionItems:()=>_b,pipelineColumnForPhase:()=>tb,prescribedSkills:()=>Ua,promptOverridePath:()=>Na,renderContextStamp:()=>Vn,resolveBranchName:()=>Ob,resolveModelForRole:()=>ob,resolveProvider:()=>sb,rolesForScenario:()=>_a,serializeModelConfig:()=>ab,serializeModelEdgeSheet:()=>fr,serializeModelIdentityTable:()=>aa,serializeModelShard:()=>ia,serializeModelTaskEvent:()=>qr,serializeModelYaml:()=>hr,solutionCoverage:()=>jb,suggestInternalTrackerPrefix:()=>Ga,validateActionInput:()=>$a,validateCouncilVerdict:()=>xb,validateModelEdgeSheet:()=>Jn,validateModelIdentityTable:()=>Zn,validateModelShard:()=>Ct,validateModelTaskEvent:()=>At,validateObserverPlan:()=>vb,validateRoleDefinition:()=>Aa,validateSettingEdit:()=>Ta,validateSkill:()=>La,youtrackIssueUrl:()=>Lb,zeroUsage:()=>Ft});var Wa,Hb,F=S(()=>{"use strict";hu();gu();ku();ca();Cu();Pu();pa();ga();Wu();xa();va();Yu();zu();Zu();ed();td();rd();nd();od();sd();id();ad();ud();dd();fd();hd();gd();kd();wd();$d();Ed();Wa=20,Hb=15});function X(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Le=S(()=>{"use strict"});import{existsSync as Wb,readFileSync as qb,readdirSync as Yb}from"node:fs";import{dirname as Vb,join as qa}from"node:path";import{parse as zb}from"yaml";function Xb(t=process.cwd()){let e=t;for(;;){if(Wb(qa(e,_t,"project.yaml")))return e;let r=Vb(e);if(r===e)return null;e=r}}function Jb(t){return qa(t,_t)}function Re(t=process.cwd()){let e=Xb(t);if(!e)return null;let r=Jb(e),n=Zb(qb(qa(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function Id(t,e,r){return Yb(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 ns(t,e=process.cwd()){try{let r=Re(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function Zb(t){let e=zb(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),n=String(e.name??r),o=Array.isArray(e.repos)?e.repos:[],s=[];for(let i of o){if(!i||typeof i!="object")continue;let a=i,c=String(a.repo??a.repoName??""),l=String(a.name??c);if(!l||!c)continue;let u=a.host,p=u==="bitbucket"?"bitbucket":u==="gitlab"?"gitlab":"github";s.push({name:l,host:p,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l)})}return{projectId:r,name:n,repos:s}}function Td(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}var _t,bt=S(()=>{"use strict";_t=".codepipe"});import{homedir as Cd}from"node:os";import{mkdirSync as Qb,readFileSync as e$,writeFileSync as t$,existsSync as Ya}from"node:fs";import{dirname as Pd,join as os,resolve as r$}from"node:path";import{fileURLToPath as n$}from"node:url";function _d(t){let e=os(Ad,".env");if(Ya(e)&&process.loadEnvFile(e),t){let r=os(Ad,"profiles",t,".env");Ya(r)&&process.loadEnvFile(r)}}function Zr(t){let e=X("CONFIG");return e||(t?os(Cd(),".codepipe","profiles",t,"config.json"):os(Cd(),".codepipe","config.json"))}function dt(t){let e=Zr(t);if(!Ya(e))return null;let r=e$(e,"utf-8");return JSON.parse(r)}function jt(t,e){let r=Zr(e);Qb(Pd(r),{recursive:!0}),t$(r,JSON.stringify(t,null,2)+`
|
|
14
|
+
`,{mode:384})}function ss(t){if(t)return{cfg:et(t),profile:t};let e;try{e=Re()?.spec.projectId||void 0}catch{}if(e){let r=dt(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:et(void 0),profile:void 0}}function et(t){let e=dt(t);if(!e){let r=t?`codepipe init --profile ${t} --hub <url> --token <token> --project ${t}`:"codepipe init --hub <url> --token <token> --project <id>";console.error(t?`CLI profile '${t}' is not initialised. run \`${r}\` first.`:`CLI is not initialised. run \`${r}\` first.`),process.exit(1)}return e.projectId||(console.error(`config at ${Zr(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var Ad,We=S(()=>{"use strict";Le();bt();Ad=r$(Pd(n$(import.meta.url)),"..")});import{homedir as jd}from"node:os";import{existsSync as Nd,mkdirSync as Od,readFileSync as Ld,writeFileSync as Dd}from"node:fs";import{dirname as Md,join as Ud}from"node:path";function Bd(t,e,r){let n=q(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},se(n)}function Fd(t,e){let r=q(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],se(r),!0)}function Kd(t){return Object.keys(q(t)?.secrets??{}).sort()}function is(t,e,r){let n=q(t);if(!n)return"mismatch";let o=n.sandboxPins??{},s=o[e];return s&&s===r?"ok":s&&s!==r?"mismatch":(o[e]=r,n.sandboxPins=o,se(n),"pinned")}function Gd(t,e){let r=q(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],se(r),!0):!1}function $t(t){return Ud(jd(),".codepipe","secrets",`${t}.json`)}function q(t){let e=$t(t);return Nd(e)?JSON.parse(Ld(e,"utf-8")):null}function se(t){let e=$t(t.projectId);Od(Md(e),{recursive:!0}),Dd(e,JSON.stringify(t,null,2)+`
|
|
15
|
+
`,{mode:384})}function as(){return Ud(jd(),".codepipe","shared.json")}function Va(){let t=as();return Nd(t)?JSON.parse(Ld(t,"utf-8")):null}function Hd(t){let e=as();Od(Md(e),{recursive:!0}),Dd(e,JSON.stringify(t,null,2)+`
|
|
16
|
+
`,{mode:384})}function Qr(t){let e=q(t)?.claude?.oauthToken;return e||Va()?.claude?.oauthToken}function io(t){let e={GH_TOKEN:t.github?.token,BITBUCKET_EMAIL:t.bitbucket?.email,BITBUCKET_API_TOKEN:t.bitbucket?.apiToken,GITLAB_TOKEN:t.gitlab?.token,YOUTRACK_URL:t.youtrack?.url,YOUTRACK_TOKEN:t.youtrack?.token};for(let r of za){let n=e[r];n&&!process.env[r]&&(process.env[r]=n)}}function en(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var za,de=S(()=>{"use strict";za=["GH_TOKEN","BITBUCKET_EMAIL","BITBUCKET_API_TOKEN","GITLAB_TOKEN","YOUTRACK_URL","YOUTRACK_TOKEN"]});import{appendFileSync as o$,existsSync as qd,mkdirSync as s$,renameSync as Yd,statSync as i$,unlinkSync as a$}from"node:fs";import{Writable as c$}from"node:stream";import{join as l$}from"node:path";function cs(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,s=u$(process.env[`${t}_MAX_BYTES`]??String(Vd.maxBytes)),i=process.env[`${t}_MAX_FILES`],a=i?Math.max(1,Number(i)):Vd.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:s,maxFiles:a}}function u$(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 ls(t){let e={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},r=(n,o)=>(...s)=>{n(...s);try{t.writeLine(d$(o,s))}catch{}};return console.log=r(e.log,"INFO"),console.warn=r(e.warn,"WARN"),console.error=r(e.error,"ERROR"),()=>{console.log=e.log,console.warn=e.warn,console.error=e.error}}function d$(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:p$(o)).join(" ");return`${r} ${t} ${n}`}function p$(t){try{return JSON.stringify(t)}catch{return String(t)}}var Vd,tn,Xa=S(()=>{"use strict";Vd={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},tn=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&s$(e.dir,{recursive:!0}),this.currentPath=l$(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
|
|
17
17
|
`)?e:e+`
|
|
18
|
-
`;
|
|
19
|
-
`+t.slice(t.length-e)}async function Ht(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),us);try{let s;try{s=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new tt(`cannot reach api.github.com (${l instanceof Error?l.message:String(l)})`)}if(s.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(ds(s.status))throw new tt(`api.github.com \u2192 ${s.status} ${s.statusText}`);if(!s.ok)throw new Error(`GitHub \u2192 ${s.status} ${s.statusText}`);let a=(await s.json()).login??"ok",c=s.headers.get("x-oauth-scopes");if(c!==null&&e&&!c.split(",").map(u=>u.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${c||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let l;try{let u=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});u.ok&&(l=(await u.json()).type)}catch{}if(l==="Organization"){let u=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});if(u.status===403)throw new Error(`token cannot access org "${e.owner}" (403) \u2014 for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens; for classic PATs: verify 'repo' or 'admin:org' scope`);if(u.status===404)throw new Error(`org "${e.owner}" not found or not visible to this token \u2014 check the org name; for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens`);if(!u.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${u.status} ${u.statusText}`)}}return a}finally{clearTimeout(o)}}async function ps(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,s=setTimeout(()=>o.abort(),us);try{let i;try{i=await fetch(n,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},signal:o.signal})}catch(c){throw new tt(`cannot reach api.github.com (${c instanceof Error?c.message:String(c)})`)}if(i.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(i.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(ds(i.status))throw new tt(`api.github.com \u2192 ${i.status} ${i.statusText}`);if(!i.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${i.status} ${i.statusText}`);if((await i.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}finally{clearTimeout(s)}}async function Wt(t,e,r){let n=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",o=new AbortController,s=setTimeout(()=>o.abort(),us);try{let i;try{i=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new tt(`cannot reach api.bitbucket.org (${c instanceof Error?c.message:String(c)})`)}if(i.ok)return t;if(i.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;if(ds(i.status))throw new tt(`api.bitbucket.org \u2192 ${i.status} ${i.statusText}`);let a=await z$(i);throw i.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${a})`):i.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${a})`):i.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${a})`):new Error(`Bitbucket \u2192 ${i.status} ${i.statusText}${a}`)}finally{clearTimeout(s)}}async function z$(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function fs(t,e,r,n){let o;try{o=await fetch(`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}/${encodeURIComponent(n)}/pullrequests?pagelen=1`,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch{return}if(o.status!==403)return;let s={};try{s=await o.json()}catch{}let i=s.error?.detail?.granted;if(Array.isArray(i)){let c=dp.filter(l=>!i.includes(l));return c.length===0?void 0:`token lacks scope(s) ${c.join(", ")} \u2014 the pipeline would fail at PR time; re-create the API token with all of: ${dp.join(", ")}`}let a=s.error?.message?`: ${s.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function qt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),us);try{let n;try{n=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"},signal:e.signal})}catch(s){throw new tt(`cannot reach gitlab.com (${s instanceof Error?s.message:String(s)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(ds(n.status))throw new tt(`gitlab.com \u2192 ${n.status} ${n.statusText}`);if(!n.ok)throw new Error(`GitLab \u2192 ${n.status} ${n.statusText}`);return(await n.json()).username??"ok"}finally{clearTimeout(r)}}async function pp(t){try{let e=await fetch("https://gitlab.com/api/v4/personal_access_tokens/self",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}});if(!e.ok)return;let n=(await e.json()).scopes??[];return n.length>0&&!n.includes("api")?`GitLab token scopes [${n.join(", ")}] lack 'api' \u2014 CodePipe can read and push, but cannot create a Context Repo or scaffold its files`:void 0}catch{return}}function X$(t){switch(t){case"running":case"pending":case"created":case"waiting_for_resource":case"preparing":case"scheduled":return"running";case"success":return"success";case"failed":case"canceled":case"cancelled":return"failed";default:return"none"}}function Xa(t,e,r){let n=t.host==="github"?"set GH_TOKEN or GITHUB_TOKEN in the CLI env":t.host==="bitbucket"?"set BITBUCKET_EMAIL + BITBUCKET_API_TOKEN in the CLI env":t.host==="gitlab"?"set GITLAB_TOKEN in the CLI env":`no adapter implementation for host '${t.host}'`;return`cannot ${r} PR ${t.owner}/${t.repoName}#${e}: MockGitHost is active (write operations are not allowed) \u2014 ${n}`}function pt(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new Za(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new Ja(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new Qa(e)}return new ec}var br,tt,us,dp,Ja,Za,Qa,ec,Yt=v(()=>{"use strict";br=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},tt=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},us=5e3;dp=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];Ja=class{constructor(e,r){this.email=e;this.apiToken=r}name="bitbucket";authHeader(){return"Basic "+Buffer.from(`${this.email}:${this.apiToken}`).toString("base64")}async createPullRequest(e,r){let n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json"},body:JSON.stringify({title:r.title,description:r.body,source:{branch:{name:r.branchName}},destination:{branch:{name:r.baseBranch}}})});if(!n.ok)throw new Error(`bitbucket pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.links?.html?.href??"",number:o.id}}async findOpenPrByBranch(e,r){let n=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${n}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!o.ok)return null;let i=(await o.json()).values?.[0];return i?{url:i.links?.html?.href??"",number:i.id}:null}async getPullRequest(e,r){let n=`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(o.status===404)throw new br(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let s=await o.json();return s.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:s.state==="DECLINED"||s.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){let s=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",i=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:s,close_source_branch:o})});if(!i.ok)throw new Error(`bitbucket merge PR #${r}: ${i.status} ${await i.text()}`);let a=await i.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:n}})});if(!o.ok)throw new Error(`bitbucket comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},Za=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json"},body:JSON.stringify({title:r.title,body:r.body,head:r.branchName,base:r.baseBranch})});if(!n.ok)throw new Error(`github pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.html_url,number:o.number}}async findOpenPrByBranch(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls?state=open&head=${encodeURIComponent(`${e.owner}:${r}`)}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(!n.ok)return null;let s=(await n.json())[0];return s?{url:s.html_url,number:s.number}:null}async getPullRequest(e,r){let n=`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(o.status===404)throw new br(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${o.status} ${await o.text()}`);let s=await o.json();if(s.state==="closed"&&s.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(s.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let i=s.mergeable===!1||s.mergeable_state==="dirty"?"conflict":s.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:s.head?.sha?await this.fetchCiStatus(e,s.head.sha):"none",mergeable:i}}async fetchCiStatus(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[s,i]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),a=!1,c=!1,l=!1;if(s.ok){let u=await s.json();for(let p of u.check_runs??[])l=!0,p.status!=="completed"?a=!0:p.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(p.conclusion)&&(c=!0)}if(i.ok){let u=await i.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,s=["failure","timed_out","cancelled","action_required","startup_failure"];try{let i=await fetch(`${o}/pulls/${r}`,{headers:n});if(!i.ok)return;let a=(await i.json()).head?.sha;if(!a)return;let c=await fetch(`${o}/actions/runs?head_sha=${a}&per_page=20`,{headers:n});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],u=[];for(let p of l.filter(d=>d.conclusion&&s.includes(d.conclusion))){let d=await fetch(`${o}/actions/runs/${p.id}/jobs?per_page=50`,{headers:n});if(!d.ok)continue;let m=(await d.json()).jobs??[];for(let f of m.filter(g=>g.conclusion==="failure")){let g=await fetch(`${o}/actions/jobs/${f.id}/logs`,{headers:n});if(!g.ok)continue;let h=await g.text();u.push(`### CI job: ${f.name}
|
|
18
|
+
`;o$(this.currentPath,r,"utf-8")}asWritable(){return new c$({write:(e,r,n)=>{try{let o=typeof e=="string"?e:e.toString("utf-8");for(let s of o.split(/\r?\n/))s&&this.writeLine(s);n()}catch(o){n(o)}}})}rotateIfNeeded(){if(!(this.cfg.maxBytes<=0||!qd(this.currentPath)||i$(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;qd(n)&&(r>=this.cfg.maxFiles?a$(n):Yd(n,`${this.currentPath}.${r+1}`))}Yd(this.currentPath,`${this.currentPath}.1`)}}}});function ds(t){return t===429||t>=500}function Jd(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
|
|
19
|
+
`+t.slice(t.length-e)}async function Ht(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),us);try{let s;try{s=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new tt(`cannot reach api.github.com (${l instanceof Error?l.message:String(l)})`)}if(s.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(ds(s.status))throw new tt(`api.github.com \u2192 ${s.status} ${s.statusText}`);if(!s.ok)throw new Error(`GitHub \u2192 ${s.status} ${s.statusText}`);let a=(await s.json()).login??"ok",c=s.headers.get("x-oauth-scopes");if(c!==null&&e&&!c.split(",").map(u=>u.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${c||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let l;try{let u=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});u.ok&&(l=(await u.json()).type)}catch{}if(l==="Organization"){let u=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});if(u.status===403)throw new Error(`token cannot access org "${e.owner}" (403) \u2014 for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens; for classic PATs: verify 'repo' or 'admin:org' scope`);if(u.status===404)throw new Error(`org "${e.owner}" not found or not visible to this token \u2014 check the org name; for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens`);if(!u.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${u.status} ${u.statusText}`)}}return a}finally{clearTimeout(o)}}async function ps(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,s=setTimeout(()=>o.abort(),us);try{let i;try{i=await fetch(n,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},signal:o.signal})}catch(c){throw new tt(`cannot reach api.github.com (${c instanceof Error?c.message:String(c)})`)}if(i.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(i.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(ds(i.status))throw new tt(`api.github.com \u2192 ${i.status} ${i.statusText}`);if(!i.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${i.status} ${i.statusText}`);if((await i.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}finally{clearTimeout(s)}}async function Wt(t,e,r){let n=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",o=new AbortController,s=setTimeout(()=>o.abort(),us);try{let i;try{i=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new tt(`cannot reach api.bitbucket.org (${c instanceof Error?c.message:String(c)})`)}if(i.ok)return t;if(i.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;if(ds(i.status))throw new tt(`api.bitbucket.org \u2192 ${i.status} ${i.statusText}`);let a=await w$(i);throw i.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${a})`):i.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${a})`):i.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${a})`):new Error(`Bitbucket \u2192 ${i.status} ${i.statusText}${a}`)}finally{clearTimeout(s)}}async function w$(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function fs(t,e,r,n){let o;try{o=await fetch(`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}/${encodeURIComponent(n)}/pullrequests?pagelen=1`,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch{return}if(o.status!==403)return;let s={};try{s=await o.json()}catch{}let i=s.error?.detail?.granted;if(Array.isArray(i)){let c=Zd.filter(l=>!i.includes(l));return c.length===0?void 0:`token lacks scope(s) ${c.join(", ")} \u2014 the pipeline would fail at PR time; re-create the API token with all of: ${Zd.join(", ")}`}let a=s.error?.message?`: ${s.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function qt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),us);try{let n;try{n=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"},signal:e.signal})}catch(s){throw new tt(`cannot reach gitlab.com (${s instanceof Error?s.message:String(s)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(ds(n.status))throw new tt(`gitlab.com \u2192 ${n.status} ${n.statusText}`);if(!n.ok)throw new Error(`GitLab \u2192 ${n.status} ${n.statusText}`);return(await n.json()).username??"ok"}finally{clearTimeout(r)}}async function Qd(t){try{let e=await fetch("https://gitlab.com/api/v4/personal_access_tokens/self",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}});if(!e.ok)return;let n=(await e.json()).scopes??[];return n.length>0&&!n.includes("api")?`GitLab token scopes [${n.join(", ")}] lack 'api' \u2014 CodePipe can read and push, but cannot create a Context Repo or scaffold its files`:void 0}catch{return}}function b$(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 Za(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 pt(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new ec(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new Qa(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new tc(e)}return new rc}var br,tt,us,Zd,Qa,ec,tc,rc,Yt=S(()=>{"use strict";br=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},tt=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},us=5e3;Zd=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];Qa=class{constructor(e,r){this.email=e;this.apiToken=r}name="bitbucket";authHeader(){return"Basic "+Buffer.from(`${this.email}:${this.apiToken}`).toString("base64")}async createPullRequest(e,r){let n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json"},body:JSON.stringify({title:r.title,description:r.body,source:{branch:{name:r.branchName}},destination:{branch:{name:r.baseBranch}}})});if(!n.ok)throw new Error(`bitbucket pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.links?.html?.href??"",number:o.id}}async findOpenPrByBranch(e,r){let n=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${n}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!o.ok)return null;let i=(await o.json()).values?.[0];return i?{url:i.links?.html?.href??"",number:i.id}:null}async getPullRequest(e,r){let n=`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(o.status===404)throw new br(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let s=await o.json();return s.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:s.state==="DECLINED"||s.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){let s=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",i=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:s,close_source_branch:o})});if(!i.ok)throw new Error(`bitbucket merge PR #${r}: ${i.status} ${await i.text()}`);let a=await i.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:n}})});if(!o.ok)throw new Error(`bitbucket comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},ec=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json"},body:JSON.stringify({title:r.title,body:r.body,head:r.branchName,base:r.baseBranch})});if(!n.ok)throw new Error(`github pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.html_url,number:o.number}}async findOpenPrByBranch(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls?state=open&head=${encodeURIComponent(`${e.owner}:${r}`)}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(!n.ok)return null;let s=(await n.json())[0];return s?{url:s.html_url,number:s.number}:null}async getPullRequest(e,r){let n=`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(o.status===404)throw new br(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${o.status} ${await o.text()}`);let s=await o.json();if(s.state==="closed"&&s.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(s.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let i=s.mergeable===!1||s.mergeable_state==="dirty"?"conflict":s.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:s.head?.sha?await this.fetchCiStatus(e,s.head.sha):"none",mergeable:i}}async fetchCiStatus(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[s,i]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),a=!1,c=!1,l=!1;if(s.ok){let u=await s.json();for(let p of u.check_runs??[])l=!0,p.status!=="completed"?a=!0:p.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(p.conclusion)&&(c=!0)}if(i.ok){let u=await i.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,s=["failure","timed_out","cancelled","action_required","startup_failure"];try{let i=await fetch(`${o}/pulls/${r}`,{headers:n});if(!i.ok)return;let a=(await i.json()).head?.sha;if(!a)return;let c=await fetch(`${o}/actions/runs?head_sha=${a}&per_page=20`,{headers:n});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],u=[];for(let p of l.filter(d=>d.conclusion&&s.includes(d.conclusion))){let d=await fetch(`${o}/actions/runs/${p.id}/jobs?per_page=50`,{headers:n});if(!d.ok)continue;let m=(await d.json()).jobs??[];for(let f of m.filter(g=>g.conclusion==="failure")){let g=await fetch(`${o}/actions/jobs/${f.id}/logs`,{headers:n});if(!g.ok)continue;let h=await g.text();u.push(`### CI job: ${f.name}
|
|
20
20
|
|
|
21
|
-
${
|
|
21
|
+
${Jd(h,8e3)}`)}}return u.length===0?void 0:Jd(u.join(`
|
|
22
22
|
|
|
23
|
-
`),16e3)}catch{return}}async mergePR(e,r,n,o){let s=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!s.ok)throw new Error(`github merge PR #${r}: ${s.status} ${await s.text()}`);let i=await s.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return i?.sha?{mergedSha:i.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},
|
|
24
|
-
`)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function ev(t,e,r){return new Promise((n,o)=>{let s=Vt.connect({host:t,port:e,servername:t,rejectUnauthorized:!1},()=>{let i=s.getPeerCertificate(!0),a=new Set;for(;i?.issuerCertificate&&i.issuerCertificate!==i&&i.fingerprint256&&!a.has(i.fingerprint256);)a.add(i.fingerprint256),i=i.issuerCertificate;let c=i?.raw?new hp(i.raw):null;s.end(),n(c)});s.on("error",o),s.setTimeout(r,()=>{s.destroy(),o(new Error("tls connect timeout"))})})}function tc(t,e,r){return new Promise(n=>{let o=Vt.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 tv(t){try{let e=await fetch(t);return e.ok?new hp(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function bp(t,e=443,r=yp){let n=`${t}:${e}`,o=mp.get(n);if(o)return o;let s=rv(t,e,r).catch(i=>(r(`[tls] chain repair for ${t} failed: ${i instanceof Error?i.message:String(i)}`),!1));return mp.set(n,s),s}async function rv(t,e,r){if(!gp)return!1;let n=8e3;if(await tc(t,e,n))return!0;let o=await ev(t,e,n),s=Vt.getCACertificates(),i=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=Q$(o);if(!c)break;let l=await tv(c);if(!l)break;if(i.push(l.toString()),Vt.setDefaultCACertificates([...s,...i]),await tc(t,e,n))return r(`[tls] completed certificate chain for ${t} via AIA (+${i.length} intermediate cert(s))`),!0;if(l.subject===l.issuer)break;o=l}return tc(t,e,n)}var gp,fp,mp,yp,$p=v(()=>{"use strict";Le();gp=typeof Vt.getCACertificates=="function"&&typeof Vt.setDefaultCACertificates=="function",fp=!1,mp=new Map,yp=t=>console.warn(t)});function Ep(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function rt(t,e,r){kp();let n={Authorization:`Bearer ${t.token}`,Accept:"application/json"};r?.body&&(n["Content-Type"]="application/json");let o=t.baseUrl+e,s={...r,headers:{...n,...r?.headers??{}}};try{return await fetch(o,s)}catch(i){if(wp(i)&&await bp(new URL(t.baseUrl).host))return await fetch(o,s);throw i}}function nv(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function ov(){let t=Number(process.env.YOUTRACK_WRITE_RETRIES);return{attempts:Number.isFinite(t)&&t>=1?Math.floor(t):6,baseMs:1e3,capMs:15e3}}async function rc(t,e,r,n){let{attempts:o,baseMs:s,capMs:i}=ov(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await rt(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&&nv(l.status,u)){await vp(Math.min(i,s*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await vp(Math.min(i,s*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function zt(t){let e;try{e=await rt(t,"/api/users/me?fields=login,fullName")}catch(n){throw new Error(`cannot reach ${t.baseUrl} (${n instanceof Error?n.message:String(n)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the YouTrack PAT)");if(!e.ok)throw new Error(`YouTrack \u2192 ${e.status} ${e.statusText}`);let r=await e.json();return r.login??r.fullName??"ok"}async function Rp(t){try{let e=await rt(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function sv(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,s=xp.get(o);if(s)return s;let i=await rt(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!i.ok)throw new Error(`yt resolveStateId ${e}: ${i.status} ${await i.text()}`);let c=(await i.json()).customFields.find(u=>u.name===n);if(!c)throw new Error(`yt: issue ${e} has no ${n} custom field`);let l=c.projectCustomField.bundle.values.find(u=>u.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${n} bundle for ${e}`);return xp.set(o,l.id),l.id}async function Ip(t,e,r,n=ao){let o=await sv(t,e,r,n);await rc(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:n,$type:"StateIssueCustomField",value:{id:o,$type:"StateBundleElement"}}]})})}async function Tp(t,e,r){return await(await rc(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function Cp(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await rc(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function Ap(t,e){let r=Sp.get(e);if(r)return r;let n=await rt(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!n.ok)throw new Error(`yt resolveProjectId: ${n.status} ${await n.text()}`);let s=(await n.json()).find(i=>i.shortName===e);if(!s)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return Sp.set(e,s.id),s.id}async function Pp(t,e,r,n,o,s=ao){let i=await Ap(t,e),a=await rt(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:i},summary:r,description:n,customFields:[{name:s,$type:"StateIssueCustomField",value:{name:o,$type:"StateBundleElement"}}]})});if(!a.ok)throw new Error(`yt createIssue: ${a.status} ${await a.text()}`);let c=await a.json();return{id:c.id,key:c.idReadable}}async function _p(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,s=await rt(t,"/api/commands",{method:"POST",body:JSON.stringify({query:o,issues:[{idReadable:e}]})});if(!s.ok)throw new Error(`yt applyIssueLink (${o} on ${e}): ${s.status} ${await s.text()}`)}function Op(t){if(!t||t.length===0)return;let e=[];for(let r of t)!r.url||!r.name||e.push({id:r.id,name:r.name,url:r.url,...r.mimeType?{mimeType:r.mimeType}:{},...typeof r.size=="number"?{size:r.size}:{}});return e.length>0?e:void 0}async function Lp(t,e){let r=e.startsWith("http")?e:t.baseUrl+e,n=await fetch(r,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok)throw new Error(`yt downloadAttachment ${e}: ${n.status}`);return Buffer.from(await n.arrayBuffer())}async function Dp(t,e){let r=e.stageField??ao,n=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let c=e.columns.map(l=>`{${l}}`).join(", ");n.push(`${r}: ${c}`)}if(e.updatedSince){let c=new Date(e.updatedSince).toISOString().slice(0,10);n.push(`updated: ${c} .. *`)}e.assignee?n.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&n.push("has: Assignee");let o=n.join(" "),s=`/api/issues?query=${encodeURIComponent(o)}&fields=${Np}&$top=200`,i=await rt(t,s);if(!i.ok)throw new Error(`yt listIssues: ${i.status} ${await i.text()}`);let a=await i.json();if(e.columns&&e.columns.length>0&&a.length>0&&!a.some(l=>(l.customFields??[]).some(u=>u.name===r))){let l=[...new Set((a[0]?.customFields??[]).map(u=>u.name).filter(u=>!!u))];throw new Error(`youtrack.stage_field "${r}" does not exist in project ${e.projectKey} \u2014 YouTrack ignored the status filter and would have returned unrelated issues. `+(l.length>0?`Fields on the issues: ${l.join(", ")}.`:"The issues carry no custom fields at all."))}return a.map(c=>Bp(c,r))}async function Mp(t,e,r=ao){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Np}`,o=await rt(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Bp(await o.json(),r)}async function Up(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${av}&$top=500`,o=await rt(t,n);if(!o.ok)throw new Error(`yt listComments ${e}: ${o.status} ${await o.text()}`);return(await o.json()).filter(i=>i.created>r).map(i=>{let a={id:i.id,issueId:e,author:i.author?.login??"unknown",body:i.text??"",createdAt:new Date(i.created).toISOString()},c=Op(i.attachments);return c&&(a.attachments=c),a})}function cv(t){if(!t||t.length===0)return;let e=[];for(let r of t){if(r.direction!=="INWARD")continue;let n=r.linkType?.name==="Depend"?"depends_on":r.linkType?.name==="Subtask"?"subtask":null;if(n)for(let o of r.issues??[])o.idReadable&&e.push({type:n,targetKey:o.idReadable})}return e.length>0?e:void 0}function Bp(t,e=ao){let r=t.customFields??[],n=r.find(l=>l.name===e),o=r.find(l=>l.name==="Assignee"),s=r.find(l=>l.name==="Type"),i={id:t.id,key:t.idReadable,title:t.summary,status:n?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(i.description=t.description),o?.value?.login&&(i.assignee=o.value.login),s?.value?.name&&(i.issueType=s.value.name),t.tags&&t.tags.length>0&&(i.tags=t.tags.map(l=>l.name));let a=Op(t.attachments);a&&(i.attachments=a);let c=cv(t.links);return c&&(i.links=c),i}async function Fp(t,e){let r=await lv(t,e);return r.length>0?r:uv(t,e)}async function lv(t,e){let r=await Ap(t,e),n=await rt(t,`/api/admin/projects/${encodeURIComponent(r)}/customFields?fields=$type,field(name),bundle(values(name,archived))&$top=100`);if(!n.ok)return[];let o=await n.json(),s=[];for(let i of o)i.$type==="StateProjectCustomField"&&i.field?.name&&s.push({name:i.field.name,values:Kp(i.bundle)});return s}async function uv(t,e){let r=`project: ${e}`,n=await rt(t,`/api/issues?query=${encodeURIComponent(r)}&fields=customFields(name,$type,projectCustomField(bundle(values(name,archived))))&$top=1`);if(!n.ok)throw new Error(`yt fetchProjectStateFields ${e}: ${n.status} ${await n.text()}`);let o=await n.json(),s=[];for(let i of o[0]?.customFields??[])i.$type==="StateIssueCustomField"&&i.name&&s.push({name:i.name,values:Kp(i.projectCustomField?.bundle)});return s}function Kp(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var vp,ao,xp,Sp,jp,iv,Np,av,$r=v(()=>{"use strict";$p();vp=t=>new Promise(e=>setTimeout(e,t));ao="Stage",xp=new Map;Sp=new Map;jp="attachments(id,name,url,size,mimeType)",iv="links(direction,linkType(name),issues(idReadable))",Np=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${jp},${iv}`,av=`id,text,created,author(login),${jp}`});function ft(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function rn(t){return t instanceof tt}async function Gp(t,e){let r=q(t),n=[],o=[],s=()=>Date.now();if(e?.trackerProvider==="internal")n.push({name:"tracker",ok:!0,detail:"built-in tracker"});else if(r?.youtrack?.url&&r.youtrack.token)try{let c=await zt({baseUrl:r.youtrack.url,token:r.youtrack.token});n.push({name:"youtrack",ok:!0}),o.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:s()})}catch(c){n.push({name:"youtrack",ok:!1,detail:ft(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:ft(c),checkedAt:s()})}else n.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),o.push({kind:"youtrack",present:!1,checkedAt:s()});let i=!1;if(r?.github?.token){i=!0;try{let c=await Ht(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:s()})}catch(c){rn(c)?(n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,detail:"check inconclusive",checkedAt:s()})):(n.push({name:"github",ok:!1,detail:ft(c)}),o.push({kind:"github",present:!0,ok:!1,detail:ft(c),checkedAt:s()}))}}else o.push({kind:"github",present:!1,checkedAt:s()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){i=!0;try{let c=await Wt(r.bitbucket.email,r.bitbucket.apiToken);n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:s()})}catch(c){rn(c)?(n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,detail:"check inconclusive",checkedAt:s()})):(n.push({name:"bitbucket",ok:!1,detail:ft(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:ft(c),checkedAt:s()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:s()});if(r?.gitlab?.token){i=!0;try{let c=await qt(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:s()})}catch(c){rn(c)?(n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,detail:"check inconclusive",checkedAt:s()})):(n.push({name:"gitlab",ok:!1,detail:ft(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:ft(c),checkedAt:s()}))}}else o.push({kind:"gitlab",present:!1,checkedAt:s()});if(i||n.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let u of e?.repos??[])if(u.host==="github")try{await ps(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){rn(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:ft(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await ps(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){rn(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:ft(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await ps(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:s()})}catch(l){rn(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:s()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:ft(l),checkedAt:s()})}else o.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:s()})}else o.push({kind:"contextWrite",present:!1,checkedAt:s()});let a=Qr(t);if(!a)n.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),o.push({kind:"claude",present:!1,checkedAt:s()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:s()});else{let c=await Nt(a);if(c==="invalid"){let l="Claude token cannot run a job (rejected or missing the inference scope) \u2014 refresh via `claude setup-token`";n.push({name:"claude",ok:!1,detail:l}),o.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:s()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:s()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function Nt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),8e3);try{let n=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20","content-type":"application/json"},body:JSON.stringify({model:dv,max_tokens:1,messages:[{role:"user",content:"hi"}]}),signal:e.signal});return n.status===200?"valid":n.status===401||n.status===403?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}async function Hp(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1000",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});if(n.status!==200)return null;let s=(await n.json())?.data;if(!Array.isArray(s))return null;let i=[];for(let a of s){let c=a?.id;if(typeof c!="string"||c.trim().length===0)continue;let l=a?.created_at;i.push({id:c,...typeof l=="string"?{createdAt:l}:{}})}return i}catch{return null}finally{clearTimeout(r)}}var dv,nn=v(()=>{"use strict";de();Yt();$r();dv="claude-haiku-4-5-20251001"});import pv from"node:http";import nc from"node:crypto";function ms(){let t=oc(nc.randomBytes(32)),e=oc(nc.createHash("sha256").update(t).digest()),r=oc(nc.randomBytes(32));return{verifier:t,challenge:e,state:r}}function ic(t){let e=new URL(fv);return e.search=new URLSearchParams({response_type:"code",client_id:Wp,redirect_uri:t.redirectUri,scope:hv,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function yv(t,e){let r=t.get("error");if(r)throw new Error(`oauth-error: ${r}`);if(t.get("state")!==e)throw new Error("state-mismatch");let n=t.get("code");if(!n)throw new Error("no-code");return n}function qp(t,e){let[r,n]=t.trim().split("#");if(!r)throw new Error("no-code");if(n!==void 0&&n!==e)throw new Error("state-mismatch");return r}function kv(t){let e=t,r=e?.access_token;if(!r||typeof r!="string")throw new Error(`no access_token in response: ${JSON.stringify(t)}`);return{oauthToken:r,...typeof e.refresh_token=="string"?{refreshToken:e.refresh_token}:{},...typeof e.expires_in=="number"?{expiresIn:e.expires_in}:{}}}async function ac(t){let e=await fetch(mv,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:t.code,state:t.state,redirect_uri:t.redirectUri,client_id:Wp,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return kv(await e.json())}async function cc(t){let e=t.timeoutMs??gv,r=pv.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,s=ic({redirectUri:o,challenge:t.challenge,state:t.state}),i,a=new Promise((l,u)=>{i=setTimeout(()=>u(new Error("no-callback")),e),r.on("request",(p,d)=>{let m=new URL(p.url??"/",o);if(m.pathname!=="/callback"){d.statusCode=404,d.end();return}clearTimeout(i),d.setHeader("content-type","text/html"),d.end("<h3>Authorized \u2014 you can close this tab.</h3>");try{l(yv(m.searchParams,t.state))}catch(f){u(f)}})});a.catch(()=>{});let c;return{authUrl:s,redirectUri:o,waitForToken(){return c||(c=a.then(l=>ac({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(i),r.close()}}}async function Yp(t){let e=await cc(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
|
|
25
|
-
${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var
|
|
23
|
+
`),16e3)}catch{return}}async mergePR(e,r,n,o){let s=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!s.ok)throw new Error(`github merge PR #${r}: ${s.status} ${await s.text()}`);let i=await s.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return i?.sha?{mergedSha:i.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},tc=class{constructor(e){this.token=e}name="gitlab";pid(e){return encodeURIComponent(`${e.owner}/${e.repoName}`)}headers(e=!1){let r={"PRIVATE-TOKEN":this.token,"User-Agent":"codepipe-cli"};return e&&(r["Content-Type"]="application/json"),r}async createPullRequest(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({source_branch:r.branchName,target_branch:r.baseBranch,title:r.title,description:r.body})});if(!n.ok)throw new Error(`gitlab mr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.web_url??"",number:o.iid}}async findOpenPrByBranch(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests?state=opened&source_branch=${encodeURIComponent(r)}`,{headers:this.headers()});if(!n.ok)return null;let s=(await n.json())[0];return s?{url:s.web_url??"",number:s.iid}:null}async getPullRequest(e,r){let n=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,o=await fetch(n,{method:"GET",headers:this.headers()});if(o.status===404)throw new br(`GitLab MR not found: ${e.owner}/${e.repoName}!${r}`);if(o.status>=400)throw new Error(`gitlab GET merge_requests/${r} \u2192 ${o.status} ${await o.text()}`);let s=await o.json();if(s.state==="merged")return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(s.state==="closed"||s.state==="locked")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let i=b$(s.head_pipeline?.status??s.pipeline?.status),a=s.merge_status==="cannot_be_merged"||s.has_conflicts===!0?"conflict":s.merge_status==="can_be_merged"&&s.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:i,mergeable:a}}async mergePR(e,r,n,o){let s=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,i,a=await fetch(s,{headers:this.headers()});if(a.ok){let u=await a.json().catch(()=>null);i=u?.sha??u?.diff_refs?.head_sha}let c=await fetch(`${s}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:n==="squash",should_remove_source_branch:o,...i?{sha:i}:{}})});if(!c.ok)throw new Error(`gitlab merge MR !${r}: ${c.status} ${await c.text()}`);let l=await c.json().catch(()=>null);return l?.merge_commit_sha?{mergedSha:l.merge_commit_sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`gitlab comment MR !${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!o.ok)throw new Error(`gitlab close MR !${r}: ${o.status} ${await o.text()}`)}};rc=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(Za(e,r,"merge"))}async closePR(e,r,n){throw new Error(Za(e,r,"close"))}async addPRComment(e,r,n){throw new Error(Za(e,r,"comment"))}}});import{X509Certificate as rp}from"node:crypto";import{readFileSync as $$}from"node:fs";import Vt from"node:tls";function v$(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function sp(t=op){if(ep)return;ep=!0;let e=X("EXTRA_CA_FILE");if(!(!e||!np))try{let r=v$($$(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Vt.setDefaultCACertificates([...Vt.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 ip(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 x$(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
|
|
24
|
+
`)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function S$(t,e,r){return new Promise((n,o)=>{let s=Vt.connect({host:t,port:e,servername:t,rejectUnauthorized:!1},()=>{let i=s.getPeerCertificate(!0),a=new Set;for(;i?.issuerCertificate&&i.issuerCertificate!==i&&i.fingerprint256&&!a.has(i.fingerprint256);)a.add(i.fingerprint256),i=i.issuerCertificate;let c=i?.raw?new rp(i.raw):null;s.end(),n(c)});s.on("error",o),s.setTimeout(r,()=>{s.destroy(),o(new Error("tls connect timeout"))})})}function nc(t,e,r){return new Promise(n=>{let o=Vt.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 E$(t){try{let e=await fetch(t);return e.ok?new rp(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function ap(t,e=443,r=op){let n=`${t}:${e}`,o=tp.get(n);if(o)return o;let s=R$(t,e,r).catch(i=>(r(`[tls] chain repair for ${t} failed: ${i instanceof Error?i.message:String(i)}`),!1));return tp.set(n,s),s}async function R$(t,e,r){if(!np)return!1;let n=8e3;if(await nc(t,e,n))return!0;let o=await S$(t,e,n),s=Vt.getCACertificates(),i=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=x$(o);if(!c)break;let l=await E$(c);if(!l)break;if(i.push(l.toString()),Vt.setDefaultCACertificates([...s,...i]),await nc(t,e,n))return r(`[tls] completed certificate chain for ${t} via AIA (+${i.length} intermediate cert(s))`),!0;if(l.subject===l.issuer)break;o=l}return nc(t,e,n)}var np,ep,tp,op,cp=S(()=>{"use strict";Le();np=typeof Vt.getCACertificates=="function"&&typeof Vt.setDefaultCACertificates=="function",ep=!1,tp=new Map,op=t=>console.warn(t)});function pp(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function rt(t,e,r){sp();let n={Authorization:`Bearer ${t.token}`,Accept:"application/json"};r?.body&&(n["Content-Type"]="application/json");let o=t.baseUrl+e,s={...r,headers:{...n,...r?.headers??{}}};try{return await fetch(o,s)}catch(i){if(ip(i)&&await ap(new URL(t.baseUrl).host))return await fetch(o,s);throw i}}function I$(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function T$(){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 oc(t,e,r,n){let{attempts:o,baseMs:s,capMs:i}=T$(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await rt(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&&I$(l.status,u)){await lp(Math.min(i,s*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await lp(Math.min(i,s*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function zt(t){let e;try{e=await rt(t,"/api/users/me?fields=login,fullName")}catch(n){throw new Error(`cannot reach ${t.baseUrl} (${n instanceof Error?n.message:String(n)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the YouTrack PAT)");if(!e.ok)throw new Error(`YouTrack \u2192 ${e.status} ${e.statusText}`);let r=await e.json();return r.login??r.fullName??"ok"}async function fp(t){try{let e=await rt(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function C$(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,s=up.get(o);if(s)return s;let i=await rt(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!i.ok)throw new Error(`yt resolveStateId ${e}: ${i.status} ${await i.text()}`);let c=(await i.json()).customFields.find(u=>u.name===n);if(!c)throw new Error(`yt: issue ${e} has no ${n} custom field`);let l=c.projectCustomField.bundle.values.find(u=>u.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${n} bundle for ${e}`);return up.set(o,l.id),l.id}async function mp(t,e,r,n=ao){let o=await C$(t,e,r,n);await oc(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:n,$type:"StateIssueCustomField",value:{id:o,$type:"StateBundleElement"}}]})})}async function hp(t,e,r){return await(await oc(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function gp(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await oc(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function yp(t,e){let r=dp.get(e);if(r)return r;let n=await rt(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!n.ok)throw new Error(`yt resolveProjectId: ${n.status} ${await n.text()}`);let s=(await n.json()).find(i=>i.shortName===e);if(!s)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return dp.set(e,s.id),s.id}async function kp(t,e,r,n,o,s=ao){let i=await yp(t,e),a=await rt(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:i},summary:r,description:n,customFields:[{name:s,$type:"StateIssueCustomField",value:{name:o,$type:"StateBundleElement"}}]})});if(!a.ok)throw new Error(`yt createIssue: ${a.status} ${await a.text()}`);let c=await a.json();return{id:c.id,key:c.idReadable}}async function wp(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,s=await rt(t,"/api/commands",{method:"POST",body:JSON.stringify({query:o,issues:[{idReadable:e}]})});if(!s.ok)throw new Error(`yt applyIssueLink (${o} on ${e}): ${s.status} ${await s.text()}`)}function vp(t){if(!t||t.length===0)return;let e=[];for(let r of t)!r.url||!r.name||e.push({id:r.id,name:r.name,url:r.url,...r.mimeType?{mimeType:r.mimeType}:{},...typeof r.size=="number"?{size:r.size}:{}});return e.length>0?e:void 0}async function xp(t,e){let r=e.startsWith("http")?e:t.baseUrl+e,n=await fetch(r,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok)throw new Error(`yt downloadAttachment ${e}: ${n.status}`);return Buffer.from(await n.arrayBuffer())}async function Sp(t,e){let r=e.stageField??ao,n=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let c=e.columns.map(l=>`{${l}}`).join(", ");n.push(`${r}: ${c}`)}if(e.updatedSince){let c=new Date(e.updatedSince).toISOString().slice(0,10);n.push(`updated: ${c} .. *`)}e.assignee?n.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&n.push("has: Assignee");let o=n.join(" "),s=`/api/issues?query=${encodeURIComponent(o)}&fields=${$p}&$top=200`,i=await rt(t,s);if(!i.ok)throw new Error(`yt listIssues: ${i.status} ${await i.text()}`);let a=await i.json();if(e.columns&&e.columns.length>0&&a.length>0&&!a.some(l=>(l.customFields??[]).some(u=>u.name===r))){let l=[...new Set((a[0]?.customFields??[]).map(u=>u.name).filter(u=>!!u))];throw new Error(`youtrack.stage_field "${r}" does not exist in project ${e.projectKey} \u2014 YouTrack ignored the status filter and would have returned unrelated issues. `+(l.length>0?`Fields on the issues: ${l.join(", ")}.`:"The issues carry no custom fields at all."))}return a.map(c=>Ip(c,r))}async function Ep(t,e,r=ao){let n=`/api/issues/${encodeURIComponent(e)}?fields=${$p}`,o=await rt(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Ip(await o.json(),r)}async function Rp(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${P$}&$top=500`,o=await rt(t,n);if(!o.ok)throw new Error(`yt listComments ${e}: ${o.status} ${await o.text()}`);return(await o.json()).filter(i=>i.created>r).map(i=>{let a={id:i.id,issueId:e,author:i.author?.login??"unknown",body:i.text??"",createdAt:new Date(i.created).toISOString()},c=vp(i.attachments);return c&&(a.attachments=c),a})}function _$(t){if(!t||t.length===0)return;let e=[];for(let r of t){if(r.direction!=="INWARD")continue;let n=r.linkType?.name==="Depend"?"depends_on":r.linkType?.name==="Subtask"?"subtask":null;if(n)for(let o of r.issues??[])o.idReadable&&e.push({type:n,targetKey:o.idReadable})}return e.length>0?e:void 0}function Ip(t,e=ao){let r=t.customFields??[],n=r.find(l=>l.name===e),o=r.find(l=>l.name==="Assignee"),s=r.find(l=>l.name==="Type"),i={id:t.id,key:t.idReadable,title:t.summary,status:n?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(i.description=t.description),o?.value?.login&&(i.assignee=o.value.login),s?.value?.name&&(i.issueType=s.value.name),t.tags&&t.tags.length>0&&(i.tags=t.tags.map(l=>l.name));let a=vp(t.attachments);a&&(i.attachments=a);let c=_$(t.links);return c&&(i.links=c),i}async function Tp(t,e){let r=await j$(t,e);return r.length>0?r:N$(t,e)}async function j$(t,e){let r=await yp(t,e),n=await rt(t,`/api/admin/projects/${encodeURIComponent(r)}/customFields?fields=$type,field(name),bundle(values(name,archived))&$top=100`);if(!n.ok)return[];let o=await n.json(),s=[];for(let i of o)i.$type==="StateProjectCustomField"&&i.field?.name&&s.push({name:i.field.name,values:Cp(i.bundle)});return s}async function N$(t,e){let r=`project: ${e}`,n=await rt(t,`/api/issues?query=${encodeURIComponent(r)}&fields=customFields(name,$type,projectCustomField(bundle(values(name,archived))))&$top=1`);if(!n.ok)throw new Error(`yt fetchProjectStateFields ${e}: ${n.status} ${await n.text()}`);let o=await n.json(),s=[];for(let i of o[0]?.customFields??[])i.$type==="StateIssueCustomField"&&i.name&&s.push({name:i.name,values:Cp(i.projectCustomField?.bundle)});return s}function Cp(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var lp,ao,up,dp,bp,A$,$p,P$,$r=S(()=>{"use strict";cp();lp=t=>new Promise(e=>setTimeout(e,t));ao="Stage",up=new Map;dp=new Map;bp="attachments(id,name,url,size,mimeType)",A$="links(direction,linkType(name),issues(idReadable))",$p=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${bp},${A$}`,P$=`id,text,created,author(login),${bp}`});function ft(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function rn(t){return t instanceof tt}async function Ap(t,e){let r=q(t),n=[],o=[],s=()=>Date.now();if(e?.trackerProvider==="internal")n.push({name:"tracker",ok:!0,detail:"built-in tracker"});else if(r?.youtrack?.url&&r.youtrack.token)try{let c=await zt({baseUrl:r.youtrack.url,token:r.youtrack.token});n.push({name:"youtrack",ok:!0}),o.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:s()})}catch(c){n.push({name:"youtrack",ok:!1,detail:ft(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:ft(c),checkedAt:s()})}else n.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),o.push({kind:"youtrack",present:!1,checkedAt:s()});let i=!1;if(r?.github?.token){i=!0;try{let c=await Ht(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:s()})}catch(c){rn(c)?(n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,detail:"check inconclusive",checkedAt:s()})):(n.push({name:"github",ok:!1,detail:ft(c)}),o.push({kind:"github",present:!0,ok:!1,detail:ft(c),checkedAt:s()}))}}else o.push({kind:"github",present:!1,checkedAt:s()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){i=!0;try{let c=await Wt(r.bitbucket.email,r.bitbucket.apiToken);n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:s()})}catch(c){rn(c)?(n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,detail:"check inconclusive",checkedAt:s()})):(n.push({name:"bitbucket",ok:!1,detail:ft(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:ft(c),checkedAt:s()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:s()});if(r?.gitlab?.token){i=!0;try{let c=await qt(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:s()})}catch(c){rn(c)?(n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,detail:"check inconclusive",checkedAt:s()})):(n.push({name:"gitlab",ok:!1,detail:ft(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:ft(c),checkedAt:s()}))}}else o.push({kind:"gitlab",present:!1,checkedAt:s()});if(i||n.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let u of e?.repos??[])if(u.host==="github")try{await ps(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){rn(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:ft(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await ps(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){rn(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:ft(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await ps(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:s()})}catch(l){rn(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:s()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:ft(l),checkedAt:s()})}else o.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:s()})}else o.push({kind:"contextWrite",present:!1,checkedAt:s()});let a=Qr(t);if(!a)n.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),o.push({kind:"claude",present:!1,checkedAt:s()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:s()});else{let c=await Nt(a);if(c==="invalid"){let l="Claude token cannot run a job (rejected or missing the inference scope) \u2014 refresh via `claude setup-token`";n.push({name:"claude",ok:!1,detail:l}),o.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:s()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:s()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function Nt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),8e3);try{let n=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20","content-type":"application/json"},body:JSON.stringify({model:O$,max_tokens:1,messages:[{role:"user",content:"hi"}]}),signal:e.signal});return n.status===200?"valid":n.status===401||n.status===403?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}async function Pp(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1000",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});if(n.status!==200)return null;let s=(await n.json())?.data;if(!Array.isArray(s))return null;let i=[];for(let a of s){let c=a?.id;if(typeof c!="string"||c.trim().length===0)continue;let l=a?.created_at;i.push({id:c,...typeof l=="string"?{createdAt:l}:{}})}return i}catch{return null}finally{clearTimeout(r)}}var O$,nn=S(()=>{"use strict";de();Yt();$r();O$="claude-haiku-4-5-20251001"});import L$ from"node:http";import sc from"node:crypto";function ms(){let t=ic(sc.randomBytes(32)),e=ic(sc.createHash("sha256").update(t).digest()),r=ic(sc.randomBytes(32));return{verifier:t,challenge:e,state:r}}function cc(t){let e=new URL(D$);return e.search=new URLSearchParams({response_type:"code",client_id:_p,redirect_uri:t.redirectUri,scope:U$,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function F$(t,e){let r=t.get("error");if(r)throw new Error(`oauth-error: ${r}`);if(t.get("state")!==e)throw new Error("state-mismatch");let n=t.get("code");if(!n)throw new Error("no-code");return n}function jp(t,e){let[r,n]=t.trim().split("#");if(!r)throw new Error("no-code");if(n!==void 0&&n!==e)throw new Error("state-mismatch");return r}function K$(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 lc(t){let e=await fetch(M$,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:t.code,state:t.state,redirect_uri:t.redirectUri,client_id:_p,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return K$(await e.json())}async function uc(t){let e=t.timeoutMs??B$,r=L$.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,s=cc({redirectUri:o,challenge:t.challenge,state:t.state}),i,a=new Promise((l,u)=>{i=setTimeout(()=>u(new Error("no-callback")),e),r.on("request",(p,d)=>{let m=new URL(p.url??"/",o);if(m.pathname!=="/callback"){d.statusCode=404,d.end();return}clearTimeout(i),d.setHeader("content-type","text/html"),d.end("<h3>Authorized \u2014 you can close this tab.</h3>");try{l(F$(m.searchParams,t.state))}catch(f){u(f)}})});a.catch(()=>{});let c;return{authUrl:s,redirectUri:o,waitForToken(){return c||(c=a.then(l=>lc({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(i),r.close()}}}async function Np(t){let e=await uc(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
|
|
25
|
+
${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var _p,D$,M$,ac,U$,B$,ic,dc=S(()=>{"use strict";_p="9d1c250a-e61b-44d9-88ed-5944d1962f5e",D$="https://platform.claude.com/oauth/authorize",M$="https://platform.claude.com/v1/oauth/token",ac="https://platform.claude.com/oauth/code/callback",U$="org:create_api_key user:profile user:inference",B$=12e4,ic=t=>Buffer.from(t).toString("base64url")});import{spawn as G$}from"node:child_process";function vr(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=G$(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var hs=S(()=>{"use strict"});import{setTimeout as H$}from"node:timers/promises";import W$ from"ws";function gs(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new W$(r)}async function Xt(t,e,r){return mt(t,e,"/projects",r)}async function Mp(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new W(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function ys(t,e,r,n){return mt(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function Up(t,e,r,n){return mt(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function Bp(t,e,r,n){return mt(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function Fp(t,e){let r=await fetch(`${t}/sandbox/me`,{headers:{Authorization:`Bearer ${e}`}});if(r.ok)return"ok";if(r.status===401)return"unknown";if(r.status===404)return"unsupported";throw new W(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function ks(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new W(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function pc(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new W(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function Kp(t,e,r={}){let n=r.attempts??3,o;for(let s=0;s<n;s++)try{let i=await pc(t,e),a=new Set;for(let c of i)c.id!==r.excludeProjectId&&c.trackerProvider==="internal"&&c.youtrackProjectKey&&a.add(c.youtrackProjectKey.toUpperCase());return a}catch(i){o=i,s<n-1&&await H$(r.delayMs??1500)}throw o}async function Gp(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 co(e)}if(!r.ok)throw new W(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function Hp(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new W(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function Wp(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new W(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function qp(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new W(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function fc(t,e,r,n){return mt(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function Yp(t,e,r,n,o){return mt(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function Vp(t,e,r,n,o){return mt(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function zp(t,e,r,n,o){return mt(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function lo(t,e,r,n){return mt(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function mc(t,e,r,n){await mt(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function Xp(t,e,r,n){return mt(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function Jp(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/repos/${encodeURIComponent(n)}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}}),s=await o.text(),i=s?JSON.parse(s):null;if(!o.ok){let a=i&&typeof i=="object"&&"error"in i?String(i.error):`HTTP ${o.status}`;throw new W(o.status,i,a)}return i}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 W(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function mt(t,e,r,n){let o=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}),s=await o.text(),i=s?JSON.parse(s):null;if(!o.ok){let a=i&&typeof i=="object"&&"error"in i?String(i.error):`HTTP ${o.status}`;throw new W(o.status,i,a)}return i}var W,co,Te=S(()=>{"use strict";W=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};co=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});function Qp(t){Zp=t}function xr(t,e="info"){Zp(t,e)}var Zp,ws=S(()=>{"use strict";Zp=t=>console.log(t)});import{homedir as q$,tmpdir as Y$}from"node:os";import{existsSync as V$,mkdirSync as z$,mkdtempSync as X$,rmSync as J$}from"node:fs";import{join as uo}from"node:path";import{simpleGit as bs}from"simple-git";function Ie(t,e,r){let n=r??uo(q$(),".codepipe","repos");return uo(n,t,e)}async function Ot(t,e,r={}){let n=Ie(t,e.name,r.baseDir),o=r.cloneUrlOverride??fo(e);if(!V$(uo(n,".git"))){z$(n,{recursive:!0});let a=bs();xr(`[git] clone ${o} \u2192 ${n}`);try{await a.clone(o,n)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${o}
|
|
26
26
|
${l.trim()}`)}}let s=bs(n);try{await s.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
|
|
27
|
-
${c.trim()}`)}let i=e.defaultBranch??"main";return await s.checkout(["-B",i,`origin/${i}`]).catch(()=>{}),s}async function Sr(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function Er(t,e){let{contextRepoCloneUrl:r,deliveryRef:n,deliverySha:o,baseSha:s,commitMessage:i}=e;await t.raw(["fetch",r,`+refs/heads/${n}:refs/codepipe-delivery`]);let a=(await t.revparse(["refs/codepipe-delivery"])).trim();o&&a!==o&&xr(`[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 Sr(t,s)||await t.fetch(["origin",s]).catch(()=>{}),!await Sr(t,s))throw new Error(`apply_delivery: base commit ${s.slice(0,10)} unavailable \u2014 cannot re-parent the delivery`);let l=(await t.raw([...$s,"commit-tree",c,"-p",s,"-m",i])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function po(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await Sr(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await Sr(t,o)){let i=(await t.revparse([o])).trim();return await t.raw(["update-ref",n,i]).catch(()=>{}),i}let s=await r();return await t.raw(["update-ref",n,s]).catch(()=>{}),s}async function
|
|
28
|
-
${y.trim()}`)}}let g=(await t.revparse(["HEAD"])).trim(),h=r.push!==!1;if(h){let w=p?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push(w)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:g,pushed:h}}async function
|
|
29
|
-
${
|
|
27
|
+
${c.trim()}`)}let i=e.defaultBranch??"main";return await s.checkout(["-B",i,`origin/${i}`]).catch(()=>{}),s}async function Sr(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function Er(t,e){let{contextRepoCloneUrl:r,deliveryRef:n,deliverySha:o,baseSha:s,commitMessage:i}=e;await t.raw(["fetch",r,`+refs/heads/${n}:refs/codepipe-delivery`]);let a=(await t.revparse(["refs/codepipe-delivery"])).trim();o&&a!==o&&xr(`[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 Sr(t,s)||await t.fetch(["origin",s]).catch(()=>{}),!await Sr(t,s))throw new Error(`apply_delivery: base commit ${s.slice(0,10)} unavailable \u2014 cannot re-parent the delivery`);let l=(await t.raw([...$s,"commit-tree",c,"-p",s,"-m",i])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function po(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await Sr(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await Sr(t,o)){let i=(await t.revparse([o])).trim();return await t.raw(["update-ref",n,i]).catch(()=>{}),i}let s=await r();return await t.raw(["update-ref",n,s]).catch(()=>{}),s}async function ef(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:s,baseSha:i,branchName:a,baseRef:c,commitMessage:l,defaultBranch:u,force:p}=r,d=await po(t,s,()=>Er(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:s,baseSha:i,commitMessage:l}));p&&await t.raw(["branch","-D",a]).catch(()=>{});let m=`origin/${c}`;if(await Sr(t,m)||(m=`origin/${u??c}`),(await t.revparse([m])).trim()===i)await t.raw(["branch","-f",a,d]),await t.checkout(a);else{await t.checkout(["-B",a,m]);try{await t.raw([...$s,"cherry-pick",d])}catch(w){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let y=w instanceof Error?w.message:String(w);throw new Error(`apply_delivery: cherry-pick of ${s.slice(0,10)} onto ${c} hit conflicts
|
|
28
|
+
${y.trim()}`)}}let g=(await t.revparse(["HEAD"])).trim(),h=r.push!==!1;if(h){let w=p?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push(w)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:g,pushed:h}}async function tf(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 rf(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:s,baseSha:i,branchName:a,commitMessage:c,push:l}=r,u=await po(t,s,()=>Er(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:s,baseSha:i,commitMessage:c}));return await t.raw(["branch","-f",a,u]),l&&await t.push(["--force-with-lease","-u","origin",a]),{commit:u,pushed:l}}async function nf(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:s,baseSha:i,baseRef:a,branchName:c,commitMessage:l,defaultBranch:u}=r,p=await po(t,s,()=>Er(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:s,baseSha:i,commitMessage:l}));await t.fetch().catch(()=>{});let d=`origin/${a}`;if(await Sr(t,d)||(d=`origin/${u??a}`),(await t.revparse([d])).trim()===i)return await t.raw(["branch","-f",c,p]),{commit:p,branch:c};let f=X$(uo(Y$(),"codepipe-apply-")),g=uo(f,"wt");try{await t.raw(["worktree","add","--detach",g,d]);let h=bs(g);try{await h.raw([...$s,"cherry-pick",p])}catch(y){await h.raw(["cherry-pick","--abort"]).catch(()=>{});let v=y instanceof Error?y.message:String(y);throw new Error(`cherry-pick of ${s.slice(0,10)} onto ${a} hit conflicts
|
|
29
|
+
${v.trim()}`)}let w=(await h.revparse(["HEAD"])).trim();return await t.raw(["branch","-f",c,w]),{commit:w,branch:c}}finally{await t.raw(["worktree","remove","--force",g]).catch(()=>{}),J$(f,{recursive:!0,force:!0}),await t.raw(["worktree","prune"]).catch(()=>{})}}async function of(t,e,r){let{branchName:n,dropTaskKeys:o}=r,s=`origin/${n}`;if(!await Sr(t,s))throw new Error(`rewrite_cluster_branch: ${s} not found upstream`);let i=`origin/${r.defaultBranch??"main"}`,a=(await t.raw(["merge-base",s,i])).trim(),c=(await t.raw(["rev-list","--reverse",`${a}..${s}`])).split(`
|
|
30
30
|
`).map(m=>m.trim()).filter(m=>m.length>0),l=new Set(o.map(m=>m.toUpperCase())),u=[],p=0;for(let m of c)(await t.raw(["show","-s","--format=%(trailers:key=CodePipe-Task,valueonly)",m])).split(`
|
|
31
31
|
`).map(h=>h.trim().toUpperCase()).filter(h=>h.length>0).some(h=>l.has(h))?p++:u.push(m);if(p===0)return{commit:(await t.revparse([s])).trim(),dropped:0};await t.checkout(["-B",n,a]);for(let m of u)try{await t.raw([...$s,"cherry-pick","--allow-empty","--keep-redundant-commits",m])}catch(f){await t.raw(["cherry-pick","--abort"]).catch(()=>{}),await t.checkout(["-B",n,s]).catch(()=>{});let g=f instanceof Error?f.message:String(f);throw new Error(`rewrite_cluster_branch: replaying ${m.slice(0,10)} after dropping ${o.join(", ")} hit conflicts
|
|
32
|
-
${g.trim()}`)}let d=(await t.revparse(["HEAD"])).trim();return await t.push(["--force-with-lease","-u","origin",n]),{commit:d,dropped:p}}async function
|
|
33
|
-
`).map(r=>r.trim()).filter(r=>r.length>0).map(r=>r.split(/\s+/)[1]??"").filter(r=>r.startsWith("refs/heads/")).map(r=>r.slice(11))}function
|
|
34
|
-
`)}async function Rf(t,e,r,n,o){let s;try{s=await dc(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(d){return{ok:!1,message:`claim failed: ${d instanceof Error?d.message:String(d)}`}}let i=[];for(let d of s.repos){let m=t.spec.repos.find(w=>w.name===d.repoName);if(!m)return{ok:!1,message:`repo "${d.repoName}" not in project.yaml \u2014 run /sync`};let f=Tr(t.root,m.mountAs);if(!xs(Tr(f,".git")))return{ok:!1,message:`${m.mountAs}/ not cloned \u2014 run /sync first`};if(!(await vs(f).status()).isClean())return{ok:!1,message:`${m.mountAs}/ has uncommitted changes \u2014 commit or stash first`};i.push({claimRepo:d,spec:m,dir:f})}let a=[];for(let d of i){let m=vs(d.dir),f=await Pv(m),g=d.claimRepo;try{await m.fetch()}catch(y){return await fc(a,o),{ok:!1,message:`fetch failed in ${d.spec.mountAs}: ${Ir(y)}`}}let h=`origin/${g.baseRef}`,w;try{w=await Er(m,{contextRepoCloneUrl:g.contextRepoCloneUrl,deliveryRef:g.deliveryRef,deliverySha:g.deliverySha,baseSha:g.baseSha,commitMessage:g.commitMessage})}catch(y){return await fc(a,o),{ok:!1,message:`fetch delivery failed in ${d.spec.mountAs}: ${Ir(y)}`}}a.push({git:m,dir:d.dir,mountAs:d.spec.mountAs,originalRef:f,branch:g.branchName,baseSha:h,deliveryCommit:w,startPoint:h})}let c=[];for(let d of a)try{if(n==="apply"){await d.git.checkout(["-B",d.branch,d.startPoint]),await d.git.raw([...Sf,"cherry-pick",d.deliveryCommit]);let m=(await d.git.revparse(["HEAD"])).trim();c.push({mountAs:d.mountAs,branch:d.branch,baseSha:d.baseSha,appliedSha:m})}else await d.git.checkout(["--detach",d.startPoint]),await d.git.raw([...Sf,"cherry-pick","--no-commit",d.deliveryCommit]),await d.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:d.mountAs,branch:d.branch,baseSha:d.baseSha})}catch(m){return await d.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await fc(a,o),{ok:!1,message:`apply failed in ${d.mountAs}: ${Ir(m)} (rolled back all repos)`}}let l=Cr(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},mc(t.contextDir,l);let u=c.map(d=>d.mountAs).join(", "),p=n==="apply"?`review, push branch '${s.repos[0]?.branchName}', then: /applied ${r} --pr <url>`:`review with 'git diff', commit & push yourself, then: /applied ${r} --pr <url>`;return{ok:!0,message:`${n==="apply"?"applied":"unstashed"} ${r} in ${u}
|
|
35
|
-
${p}
|
|
36
|
-
or: /abort ${r} --reason "..."`}}async function If(t,e,r){let n=[];for(let c of e.repos){let l=t.repos.find(p=>p.name===c.repoName);if(!l)return{ok:!1,message:`repo "${c.repoName}" not in project.yaml \u2014 run /sync`};let u=Tr(t.root,l.mountAs);if(!xs(Tr(u,".git")))return{ok:!1,message:`${l.mountAs}/ not cloned \u2014 run /sync first`};n.push({git:vs(u),dir:u,spec:l,cr:c})}let o=[],s=[];for(let c of n)try{let{commit:l}=await wf(c.git,c.dir,{contextRepoCloneUrl:c.cr.contextRepoCloneUrl,deliveryRef:c.cr.deliveryRef,deliverySha:c.cr.deliverySha,baseSha:c.cr.baseSha,baseRef:c.cr.baseRef,branchName:c.cr.branchName,commitMessage:c.cr.commitMessage,defaultBranch:c.spec.defaultBranch});r.info(`[apply] ${e.taskKey}: ${c.cr.branchName} \u2192 ${c.spec.mountAs} (${l.slice(0,10)})`),o.push({git:c.git,branch:c.cr.branchName}),s.push({mountAs:c.spec.mountAs,branch:c.cr.branchName,baseSha:`origin/${c.cr.baseRef}`,appliedSha:l})}catch(l){for(let u of o)await u.git.raw(["branch","-D",u.branch]).catch(()=>{});return{ok:!1,message:`auto-apply failed in ${c.spec.mountAs}: ${Ir(l)}`}}try{await dc(t.hubUrl,t.cliToken,t.projectId,e.taskKey)}catch(c){return{ok:!1,message:`branch created but claim failed: ${Ir(c)} \u2014 retried on the next reconnect`,branches:o.map(l=>l.branch)}}let i=Cr(t.contextDir);i[e.taskKey]={mode:"apply",claimedAt:new Date().toISOString(),repos:s},mc(t.contextDir,i);let a=s.map(c=>`${c.branch} (${c.mountAs})`).join(", ");return{ok:!0,branches:s.map(c=>c.branch),message:`branch created locally without touching your checkout: ${a}
|
|
37
|
-
review, push, then: /applied ${e.taskKey} --pr <url>
|
|
38
|
-
or: /abort ${e.taskKey} --reason "..."`}}function hc(t,e){let r=Cr(t);r[e]&&(delete r[e],mc(t,r))}async function fc(t,e){for(let r of t)try{await r.git.raw(["cherry-pick","--quit"]).catch(()=>{}),await r.git.checkout(["-f",r.originalRef]),await r.git.reset(["--hard",r.originalRef]),await r.git.raw(["branch","-D",r.branch]).catch(()=>{})}catch(n){e.warn(`rollback failed in ${r.mountAs}: ${Ir(n)} \u2014 check manually`)}}async function Tf(t,e,r){let o=Cr(t.contextDir)[e];if(o){for(let s of o.repos){let i=Tr(t.root,s.mountAs);if(!xs(Tr(i,".git")))continue;let a=vs(i),c=t.spec.repos.find(u=>u.mountAs===s.mountAs),l=c?`origin/${c.defaultBranch}`:s.baseSha;try{await a.checkout(["-f",l]),await a.reset(["--hard",l]),await a.raw(["branch","-D",s.branch]).catch(()=>{})}catch(u){r.warn(`rollback failed in ${s.mountAs}: ${Ir(u)} \u2014 check manually`)}}hc(t.contextDir,e)}}async function Pv(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function Ir(t){return t instanceof Error?t.message.trim():String(t)}var Sf,Av,gc=v(()=>{"use strict";Te();Rr();Sf=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],Av="apply-queue.json"});import{existsSync as _v}from"node:fs";import{join as jv}from"node:path";import{simpleGit as Nv}from"simple-git";async function Cf(t,e){if(!_v(jv(t,".git")))return{status:"skipped"};let r=Nv(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${Ov(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 Ov(t){return t instanceof Error?t.message.trim():String(t)}var Af=v(()=>{"use strict"});import{existsSync as Pf,readFileSync as _f,readdirSync as Lv,statSync as Dv}from"node:fs";import{join as yc}from"node:path";import{parse as jf}from"yaml";function Ss(t){let e=yc(t,"actions"),r=[],n=[];if(!Pf(e))return{defs:r,errors:n};let o;try{o=Lv(e).sort()}catch{return{defs:r,errors:n}}let s=new Set;for(let i of o){if(!/\.(yml|yaml)$/i.test(i))continue;let a=yc(e,i);try{if(!Dv(a).isFile())continue;let c=ka(i,jf(_f(a,"utf-8")));if(s.has(c.id))throw new Error(`duplicate action id "${c.id}"`);s.add(c.id),r.push(c)}catch(c){n.push({file:`actions/${i}`,error:c instanceof Error?c.message:String(c)})}}return{defs:r,errors:n}}function Nf(t){let e={},r=yc(t,"project.yaml");if(!Pf(r))return e;let n;try{n=jf(_f(r,"utf-8"))}catch{return e}if(!n||typeof n!="object")return e;let o=n.variables;if(!o||typeof o!="object"||Array.isArray(o))return e;for(let[s,i]of Object.entries(o))!He.test(s)||Pt(s)||(typeof i=="string"?e[s]=i:(typeof i=="number"||typeof i=="boolean")&&(e[s]=String(i)));return e}var kc=v(()=>{"use strict";F()});import{existsSync as wc,readFileSync as Of,readdirSync as Mv,watch as Uv}from"node:fs";import{join as mo}from"node:path";var Es,Lf=v(()=>{"use strict";kc();Es=class{constructor(e,r,n,o,s=6e4){this.contextDir=e;this.projectId=r;this.send=n;this.log=o;this.intervalMs=s}timer=null;watchers=[];debounce=null;started=!1;start(){this.started||(this.started=!0,this.report(),this.timer=setInterval(()=>this.report(),this.intervalMs),this.timer.unref?.(),this.installWatcher())}stop(){this.started=!1,this.timer&&clearInterval(this.timer),this.timer=null,this.debounce&&clearTimeout(this.debounce),this.debounce=null;for(let e of this.watchers)try{e.close()}catch{}this.watchers=[]}installWatcher(){let e=()=>{this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>this.report(),500),this.debounce.unref?.()},r=[this.contextDir,mo(this.contextDir,"prompts"),mo(this.contextDir,"actions")];for(let n of r)if(wc(n))try{let o=Uv(n,e);o.on("error",s=>{this.log.warn(`[config] fs.watch failed on ${n} \u2014 falling back to periodic reporting: ${s instanceof Error?s.message:String(s)}`);try{o.close()}catch{}}),this.watchers.push(o)}catch{}}reportNow(){this.report()}report(){try{this.send(this.read())}catch(e){this.log.warn(`[config] report failed: ${e instanceof Error?e.message:String(e)}`)}}read(){let e=Ss(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=mo(this.contextDir,e);if(!wc(r))return null;try{return Of(r,"utf-8")}catch{return null}}readPrompts(){let e=mo(this.contextDir,"prompts"),r={};if(!wc(e))return r;let n;try{n=Mv(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let s=o.slice(0,-3);try{r[s]=Of(mo(e,o),"utf-8")}catch{}}return r}}});import{existsSync as Jt,mkdirSync as Df,readFileSync as bc,writeFileSync as on}from"node:fs";import{homedir as Bv}from"node:os";import{join as vt}from"node:path";import{simpleGit as Fv}from"simple-git";function ho(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,s]of n){let i=vt(t,o);Jt(i)||(on(i,s),r.push(o))}return r}function Ar(t,e,r){let n=vt(Bv(),".codepipe","profiles",t,"context-config");return Df(n,{recursive:!0}),on(vt(n,"project.yaml"),e.projectYaml),on(vt(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function Rs(t,e,r){if(Jt(e))for(let n of sn){let o=vt(e,n),s=vt(t,n);if(!(!Jt(o)||Jt(s)))try{on(s,bc(o)),r.info(`[config] seeded local ${n} from the provisioning bundle`)}catch(i){r.warn(`[config] could not seed ${n}: ${i instanceof Error?i.message:String(i)}`)}}}function an(t){let e=vt(t,".gitignore"),r=Jt(e)?bc(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(i=>i.trim()));if(sn.filter(i=>!n.has(i)&&!n.has(`/${i}`)).length===0)return!1;let s=r.length===0||r.endsWith(`
|
|
32
|
+
${g.trim()}`)}let d=(await t.revparse(["HEAD"])).trim();return await t.push(["--force-with-lease","-u","origin",n]),{commit:d,dropped:p}}async function sf(t,e,r){let{branchName:n,baseBranch:o,mergeMethod:s,deleteBranch:i}=r,a=`origin/${n}`;return s==="squash"?(await t.raw(["merge","--squash",a]),await t.commit(`Merge branch '${n}'`)):s==="rebase"?(await t.checkout(["-B",n,a]),await t.rebase([o]),await t.checkout(o),await t.merge(["--ff-only",n])):await t.merge(["--no-ff",a,"-m",`Merge branch '${n}'`]),await t.push(["origin",o]),i&&await t.push(["origin","--delete",n]).catch(()=>{}),{mergedSha:(await t.revparse(["HEAD"])).trim()}}function fo(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 af(t){return(await bs().listRemote(["--heads",t])).split(`
|
|
33
|
+
`).map(r=>r.trim()).filter(r=>r.length>0).map(r=>r.split(/\s+/)[1]??"").filter(r=>r.startsWith("refs/heads/")).map(r=>r.slice(11))}function cf(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}var $s,Rr=S(()=>{"use strict";ws();$s=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{existsSync as Jt,mkdirSync as bf,readFileSync as bc,writeFileSync as on}from"node:fs";import{homedir as uv}from"node:os";import{join as vt}from"node:path";import{simpleGit as dv}from"simple-git";function ho(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,s]of n){let i=vt(t,o);Jt(i)||(on(i,s),r.push(o))}return r}function Ar(t,e,r){let n=vt(uv(),".codepipe","profiles",t,"context-config");return bf(n,{recursive:!0}),on(vt(n,"project.yaml"),e.projectYaml),on(vt(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function Rs(t,e,r){if(Jt(e))for(let n of sn){let o=vt(e,n),s=vt(t,n);if(!(!Jt(o)||Jt(s)))try{on(s,bc(o)),r.info(`[config] seeded local ${n} from the provisioning bundle`)}catch(i){r.warn(`[config] could not seed ${n}: ${i instanceof Error?i.message:String(i)}`)}}}function an(t){let e=vt(t,".gitignore"),r=Jt(e)?bc(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(i=>i.trim()));if(sn.filter(i=>!n.has(i)&&!n.has(`/${i}`)).length===0)return!1;let s=r.length===0||r.endsWith(`
|
|
39
34
|
`)?"":`
|
|
40
|
-
`;return on(e,r+s+
|
|
35
|
+
`;return on(e,r+s+pv.join(`
|
|
41
36
|
`)+`
|
|
42
|
-
`),!0}async function
|
|
43
|
-
`).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;an(t),await r.raw(["rm","--cached","--quiet","--",...n]),await r.add([".gitignore"]),await r.commit("chore(context): move project config out of the Context Repo"),await xc(t),e.info(`[config] migrated ${n.join(", ")} out of the Context Repo \u2014 the local copies are now the config`)}catch(r){e.warn(`[config] context-config migration failed (will retry on next start): ${r instanceof Error?r.message:String(r)}`)}}function $c(t){let e=new Map;for(let r of sn){let n=vt(t,r);Jt(n)&&e.set(r,bc(n))}return e}function vc(t,e){
|
|
37
|
+
`),!0}async function $f(t,e){try{if(!Jt(vt(t,".git")))return;let r=dv(t),n=(await r.raw(["ls-files","--",...sn])).split(`
|
|
38
|
+
`).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;an(t),await r.raw(["rm","--cached","--quiet","--",...n]),await r.add([".gitignore"]),await r.commit("chore(context): move project config out of the Context Repo"),await xc(t),e.info(`[config] migrated ${n.join(", ")} out of the Context Repo \u2014 the local copies are now the config`)}catch(r){e.warn(`[config] context-config migration failed (will retry on next start): ${r instanceof Error?r.message:String(r)}`)}}function $c(t){let e=new Map;for(let r of sn){let n=vt(t,r);Jt(n)&&e.set(r,bc(n))}return e}function vc(t,e){bf(t,{recursive:!0});for(let[r,n]of e){let o=vt(t,r);Jt(o)||on(o,n)}}var sn,pv,Lt=S(()=>{"use strict";nt();sn=["project.yaml","regimen.yaml"];pv=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as fv,mkdirSync as mv,rmSync as hv,writeFileSync as Sc}from"node:fs";import{dirname as gv,isAbsolute as yv,join as Sf,normalize as Cs}from"node:path";import{simpleGit as Ef}from"simple-git";async function Ec(t,e){let r=Cs(t),o=(Ts.get(r)??Promise.resolve()).catch(()=>{}).then(e);Ts.set(r,o);try{return await o}finally{Ts.get(r)===o&&Ts.delete(r)}}async function ve(t,e,r){return Ec(t,()=>Rc(t,e,r))}async function Rc(t,e,r){if(!fv(Sf(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=ke(t,a.path);if(a.deleted){hv(c,{force:!0});continue}mv(gv(c),{recursive:!0}),a.encoding==="base64"?Sc(c,Buffer.from(a.content,"base64")):Sc(c,a.content)}let n=Ef(t),o=e.filter(a=>!a.deleted).map(a=>a.path),s=e.filter(a=>a.deleted).map(a=>a.path);for(let a=0;a<o.length;a+=Is)await n.raw(["add","-A","-f","--",...o.slice(a,a+Is)]);for(let a=0;a<s.length;a+=Is)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...s.slice(a,a+Is)]);await n.raw(["reset","-q","--",...sn]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await xc(t))}async function xc(t){let e=Ef(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=vf;n++){try{await e.push();return}catch(s){r=s}await e.fetch().catch(()=>{});let o=(await e.revparse(["--abbrev-ref","HEAD"])).trim();try{await e.rebase([`origin/${o}`])}catch{let s=await $v(e);if(s.length>0&&s.every(a=>kv.has(a)||xf.test(a)||wv.test(a))){for(let a of s)xf.test(a)?await bv(e,t,a):await e.raw(["checkout","--theirs","--",a]);await e.add(s),await e.raw(["-c","core.editor=true","rebase","--continue"])}else throw await e.rebase(["--abort"]).catch(()=>{}),new Error(`context push: rebase conflict in ${s.join(", ")||"unknown files"} \u2014 concurrent writers edited the same entry; resolve manually in the Context Repo`)}}throw new Error(`context push failed after ${vf} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function bv(t,e,r){let n=async i=>await t.raw(["show",`:${i}:${r}`]).catch(()=>""),o=new Map;for(let i of[await n(2),await n(3)])for(let a of i.split(`
|
|
44
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 s=[...o.values()].sort((i,a)=>i.createdAt.localeCompare(a.createdAt)).map(i=>i.raw);Sc(ke(e,r),s.join(`
|
|
45
40
|
`)+(s.length>0?`
|
|
46
|
-
`:""))}async function
|
|
47
|
-
`).map(r=>r.trim()).filter(Boolean)}function ke(t,e){if(
|
|
48
|
-
`),r=e.find(s=>s.startsWith("# ")),n=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",o=s=>{let i=new RegExp(`^-\\s*\\*\\*${s}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=i.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:n,status:o("Status"),date:o("Date")}}function nx(t,e,r,n,o){let s=String(e).padStart(4,"0"),i=t.split(`
|
|
49
|
-
`),a=i.findIndex(w=>w.startsWith("# ")),c=a>=0&&(i[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),u=[],p="",d=null,m=a>=0?a+1:0;for(let w=m;w<i.length;w++){let y=(i[w]??"").trim();if(y===""){m=w+1;continue}let x=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(y);if(!x)break;let S=(x[1]??"").trim().toLowerCase(),I=(x[2]??"").trim(),E=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(y);E&&(d=parseInt(E[1]??"",10)),S==="tasks"&&(p=I),l.has(S)||u.push(y),m=w+1}let f=p?p.includes(n)?p:`${p}, ${n}`:n,g=i.slice(m).join(`
|
|
50
|
-
`).replace(/^\n+/,""),h=[`# ADR-${s}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${f}`,...u,"",g].join(`
|
|
51
|
-
`);return{content:h.endsWith(`
|
|
52
|
-
`)?h:h+`
|
|
53
|
-
`,supersedes:d}}function ox(t,e){let r=String(e).padStart(4,"0"),n=t.replace(/^(-\s*\*\*Status:\*\*).*$/im,`$1 superseded by ADR-${r}`);return n===t?t.replace(/^(# .*)$/m,`$1
|
|
54
|
-
|
|
55
|
-
- **Status:** superseded by ADR-${r}`):n}function sx(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(`
|
|
56
|
-
`)+`
|
|
57
|
-
`}async function Wf(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await Qv(t).pull(void 0,void 0,["--rebase"])}catch{}let s=h=>o==="staging"?`adr/DRAFT-${h}.md`:`tasks/${e}/adr/DRAFT-${h}.md`,i=[],a=[];for(let h of r){let w=ke(t,s(h));if(!Ic(w)){a.push(h);continue}i.push({slug:h,content:Gf(w,"utf-8")})}let c=Hf(t,"adr"),l=new Map;if(Ic(c))for(let h of Zv(c)){let w=ex.exec(h);!w||h===tx||l.set(h,{num:parseInt(w[1]??"",10),slug:w[2]??"",content:Gf(Hf(c,h),"utf-8")})}let u=Math.max(0,...[...l.values()].map(h=>h.num))+1,p=new Map,d=[],m=[];for(let h of i){if([...l.entries()].find(([,E])=>E.slug===h.slug&&E.content.includes(e))){m.push(h.slug);continue}let y=u++,x=`${String(y).padStart(4,"0")}-${h.slug}.md`,{content:S,supersedes:I}=nx(h.content,y,h.slug,e,n);if(p.set(x,S),l.set(x,{num:y,slug:h.slug,content:S}),d.push(`adr/${x}`),I!==null){let E=[...l.keys()].find($=>$.startsWith(`${String(I).padStart(4,"0")}-`));if(E&&E!==x){let $=ox(p.get(E)??l.get(E).content,y);p.set(E,$),l.set(E,{...l.get(E),content:$})}}}let f=[];if(o==="staging")for(let h of i)Ic(ke(t,`adr/DRAFT-${h.slug}.md`))&&f.push({path:`adr/DRAFT-${h.slug}.md`,content:"",deleted:!0});if(d.length===0&&f.length===0)return{promoted:d,skipped:m,missing:a};if(d.length>0){let h=[...l.entries()].map(([w,y])=>({num:y.num,file:w,header:rx(y.content)}));p.set("INDEX.md",sx(h))}for(let[h,w]of p.entries())f.push({path:`adr/${h}`,content:w});let g=d.length>0?`adr(${e}): promote ${i.map(h=>h.slug).join(", ")}`:`adr(${e}): drop stale staged ${m.join(", ")}`;return await ve(t,f,g),{promoted:d,skipped:m,missing:a}}var ex,tx,qf=v(()=>{"use strict";nt();ex=/^(\d{4})-(.+)\.md$/,tx="0000-template.md"});import{existsSync as Yf,readFileSync as ix}from"node:fs";import{join as Vf}from"node:path";function ax(t){for(let e of[lt,Hr]){let r=Vf(t,e);if(Yf(r))try{return Hi(ix(r,"utf-8"))}catch{return 0}}return 0}function cx(t,e,r,n=6){let o=e<n,s=o?Wi(e).filter(i=>!r(i)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:s}}function As(t,e){return cx(e,ax(t),r=>Yf(Vf(t,r)))}var Tc=v(()=>{"use strict";F()});import{existsSync as Zt,readFileSync as cn,readdirSync as Xf}from"node:fs";import{join as Cc}from"node:path";import{simpleGit as Jf}from"simple-git";import{parse as Zf}from"yaml";function Qf(t){try{let e=ke(t,oo);if(!Zt(e))return null;let r=Zf(cn(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!kr.test(n)?null:{prefix:n}}catch{return null}}function em(t){return`# Built-in tracker configuration \u2014 shared by every team member.
|
|
41
|
+
`:""))}async function $v(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
|
|
42
|
+
`).map(r=>r.trim()).filter(Boolean)}function ke(t,e){if(yv(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=Cs(Sf(t,e)),n=Cs(t+"/");if(r!==Cs(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var vf,kv,wv,xf,Is,Ts,nt=S(()=>{"use strict";Lt();vf=3,kv=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),wv=/^model\/derived\//,xf=/^tasks\/[^/]+\/comments\.jsonl$/,Is=500,Ts=new Map});import{existsSync as Zt,readFileSync as cn,readdirSync as _f}from"node:fs";import{join as Tc}from"node:path";import{simpleGit as jf}from"simple-git";import{parse as Nf}from"yaml";function Of(t){try{let e=ke(t,oo);if(!Zt(e))return null;let r=Nf(cn(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!kr.test(n)?null:{prefix:n}}catch{return null}}function Lf(t){return`# Built-in tracker configuration \u2014 shared by every team member.
|
|
58
43
|
# The issue-key prefix (<PREFIX>-<N>). Fixed at project init: changing it
|
|
59
44
|
# later would orphan existing tasks/<KEY>/ directories.
|
|
60
45
|
prefix: ${t}
|
|
@@ -62,15 +47,15 @@ prefix: ${t}
|
|
|
62
47
|
# Statuses are the built-in default set for now:
|
|
63
48
|
# Backlog | To Do | In Progress | Review | Done | Rejected
|
|
64
49
|
# A configurable status set / pipeline mapping is a planned extension.
|
|
65
|
-
`}function
|
|
66
|
-
`}function
|
|
50
|
+
`}function Cc(t=0){return`${t}
|
|
51
|
+
`}function jv(t){return t==="depends_on"||t==="subtask"}function Nv(t){let e;try{e=Nf(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=Ka.includes(r.type)?r.type:no,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;jv(l.type)&&typeof l.target=="string"&&l.target&&o.push({type:l.type,targetKey:l.target})}let s=typeof r.created=="string"?r.created:new Date(0).toISOString(),i=typeof r.updated=="string"?r.updated:s,a=typeof r.assignee=="string"&&r.assignee.trim().length>0?r.assignee.trim():void 0;return{key:r.key,title:r.title,type:n,status:typeof r.status=="string"&&r.status?r.status:"Backlog",...a?{assignee:a}:{},links:o,created:s,updated:i}}function Ac(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(`
|
|
67
52
|
`)+`
|
|
68
|
-
`}function yo(t,e){let r=ke(t,Xr(e));return Zt(r)?
|
|
53
|
+
`}function yo(t,e){let r=ke(t,Xr(e));return Zt(r)?Nv(cn(r,"utf-8")):null}function Df(t){let e=Tc(t,"tasks");if(!Zt(e))return[];let r=[];for(let n of _f(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=yo(t,n.name);o&&r.push(o)}return r}function Ov(t,e){let r=ke(t,`tasks/${e}/task.md`);if(!Zt(r))return;let n=cn(r,"utf-8").split(`
|
|
69
54
|
`),o=n.indexOf("---");if(o<0)return;let s=n.slice(o+1),i=s.lastIndexOf("## Attachments");i>=0&&s.slice(i+1).every(u=>u.trim()===""||/^- \[[^\]]*\]\(attachments\/[^)]*\)$/.test(u.trim()))&&(s=s.slice(0,i));let a=s.join(`
|
|
70
|
-
`).trim();if(!(!a||a==="_(no description)_"))return a}function ko(t,e,r={}){let n=r.withDescription?
|
|
55
|
+
`).trim();if(!(!a||a==="_(no description)_"))return a}function ko(t,e,r={}){let n=r.withDescription?Ov(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:Lv(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function Lv(t){return t.charAt(0).toUpperCase()+t.slice(1)}function Dv(t){let e=ke(t,zr);if(!Zt(e))return 0;let r=Number.parseInt(cn(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function Mv(t,e){let r=Tc(t,"tasks");if(!Zt(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let s of _f(r,{withFileTypes:!0})){if(!s.isDirectory())continue;let i=n.exec(s.name);if(!i)continue;let a=Number.parseInt(i[1],10);Number.isFinite(a)&&a>o&&(o=a)}return o}function Uv(t,e){return Math.max(Dv(t),Mv(t,e))+1}async function Mf(t,e,r,n){return Ec(t,()=>Bv(t,e,r,n))}async function Bv(t,e,r,n){if(!Zt(Tc(t,".git")))throw new Error(`context repo clone not found at ${t}`);await go(t);let o=null;for(let s=0;s<Pf;s++){let i=Uv(t,e),a=`${e}-${i}`,c=[...r(a),{path:zr,content:Cc(i)}];try{return await Rc(t,c,n(a)),a}catch(l){if(o=l,await Kv(t,n(a)),await go(t),Fv(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${Pf} attempts: ${o instanceof Error?o.message:String(o)}`)}function Fv(t,e){for(let r of e){let n=ke(t,r.path);if(!Zt(n)||(r.encoding==="base64"?cn(n).toString("base64"):cn(n,"utf-8"))!==r.content)return!1}return!0}async function go(t){let e=jf(t);try{await e.fetch()}catch{return}try{let r=(await e.revparse(["--abbrev-ref","HEAD"])).trim();await e.rebase([`origin/${r}`])}catch{await e.rebase(["--abort"]).catch(()=>{})}}async function Kv(t,e){let r=jf(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
|
|
71
56
|
`)[0]||!(await r.raw(["log","@{u}..HEAD","--pretty=%s"]).catch(()=>"")).trim().split(`
|
|
72
57
|
`).some(s=>s.trim()===e.split(`
|
|
73
|
-
`)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var
|
|
58
|
+
`)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var Pf,Ps=S(()=>{"use strict";F();nt();Pf=5});function ln(t,e,r,n){return[{path:"README.md",content:rx(t,e)},{path:".gitignore",content:Vv()},{path:"CLAUDE.md",content:Xv(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:zv()},{path:"knowledge/README.md",content:Jv()},{path:"knowledge/build.yaml",content:tx()},{path:"actions/README.md",content:Zv()},{path:"roles/README.md",content:Qv()},{path:"skills/README.md",content:ex()},{path:"model/README.md",content:Gv()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:Yv()},{path:"adr/README.md",content:Hv()},{path:"adr/0000-template.md",content:Wv()},{path:"adr/INDEX.md",content:qv()},{path:lt,content:Vn()},...t.trackerProvider==="internal"?[{path:oo,content:Lf(t.youtrackProjectKey??ts)},{path:zr,content:Cc()}]:[]]}function Gv(){return`# model/ \u2014 the project map
|
|
74
59
|
|
|
75
60
|
A graph of the project built from **git history and task artifacts**: files
|
|
76
61
|
and directories connected by the fact of changing together and the fact of
|
|
@@ -97,7 +82,7 @@ asset \u2014 treat it like \`knowledge/\`.
|
|
|
97
82
|
|
|
98
83
|
Every YAML file carries \`modelFormatVersion\`; a reader that meets a
|
|
99
84
|
different version treats it as "rebuild needed", not as an error.
|
|
100
|
-
`}function
|
|
85
|
+
`}function Hv(){return`# ADR \u2014 architecture decision records
|
|
101
86
|
|
|
102
87
|
Accepted architectural decisions of this project \u2014 its **framework**. The
|
|
103
88
|
agent reads this section (start with \`INDEX.md\`) at the beginning of every
|
|
@@ -125,7 +110,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
|
|
|
125
110
|
canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
|
|
126
111
|
is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
|
|
127
112
|
open a PR to this repository.
|
|
128
|
-
`}function
|
|
113
|
+
`}function Wv(){return`# ADR-NNNN: <title>
|
|
129
114
|
|
|
130
115
|
- **Status:** accepted | superseded by ADR-NNNN
|
|
131
116
|
- **Date:** YYYY-MM-DD
|
|
@@ -147,12 +132,12 @@ What becomes easier, what becomes harder, what future tasks must keep doing.
|
|
|
147
132
|
## Alternatives considered
|
|
148
133
|
|
|
149
134
|
- **<alternative>** \u2014 why it was rejected.
|
|
150
|
-
`}function
|
|
135
|
+
`}function qv(){return`# ADR index
|
|
151
136
|
|
|
152
137
|
<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->
|
|
153
138
|
|
|
154
139
|
(no accepted ADRs yet)
|
|
155
|
-
`}function
|
|
140
|
+
`}function Yv(){return`# Audit
|
|
156
141
|
|
|
157
142
|
Pipeline event logs. Naming is per-writer: each codepipe
|
|
158
143
|
project appends only to its own file \u2014
|
|
@@ -161,14 +146,14 @@ project appends only to its own file \u2014
|
|
|
161
146
|
|
|
162
147
|
\u2014 so several team members' CLIs never contend on one file. Do not create a
|
|
163
148
|
shared aggregate here.
|
|
164
|
-
`}function xt(t,e,r,n,o="auto",s=Ge,i){let a=t.trackerProvider==="internal";return{projectYaml:a?
|
|
149
|
+
`}function xt(t,e,r,n,o="auto",s=Ge,i){let a=t.trackerProvider==="internal";return{projectYaml:a?nx(t,o):ox(t,r,n,o),regimenYaml:sx(t.automationLevel,a?!0:e,a,s,i)}}function Vv(){return`# codepipe project config is local to each member's workspace
|
|
165
150
|
project.yaml
|
|
166
151
|
regimen.yaml
|
|
167
152
|
|
|
168
153
|
# codepipe runtime
|
|
169
154
|
session.log
|
|
170
155
|
apply-queue.json
|
|
171
|
-
`}function
|
|
156
|
+
`}function zv(){return`# Index prompt
|
|
172
157
|
|
|
173
158
|
You are the **Indexer** agent on the CodePipe pipeline. Your one job is to build a
|
|
174
159
|
navigation map of this project's repositories and save it to the Context Repo, so
|
|
@@ -225,7 +210,7 @@ current working directory; write nothing else under the Context Repo.
|
|
|
225
210
|
Keep both durable and skimmable \u2014 they are read at the start of every future
|
|
226
211
|
task. Prefer structure (headings, bullet lists) over prose. If a repository is
|
|
227
212
|
empty or unavailable, say so briefly rather than inventing content.
|
|
228
|
-
`}function
|
|
213
|
+
`}function Xv(t){return`# Project context for the CodePipe agent
|
|
229
214
|
|
|
230
215
|
Instructions for AI agents working on **${t.name}** tasks. Claude Code
|
|
231
216
|
auto-loads this file when the Context Repo is mounted. Keep it short and
|
|
@@ -253,7 +238,7 @@ project's architectural invariants: read them at the start of a task and treat
|
|
|
253
238
|
them as binding. New or changed decisions do **not** go here directly \u2014 during
|
|
254
239
|
analysis you draft them as task artifacts, and they are promoted into \`adr/\`
|
|
255
240
|
only after the analysis is approved.
|
|
256
|
-
`}function
|
|
241
|
+
`}function Jv(){return`# Knowledge
|
|
257
242
|
|
|
258
243
|
Durable, reusable notes about this project \u2014 the CodePipe agent's long-lived
|
|
259
244
|
**memory** across tasks. Architectural decisions, domain rules,
|
|
@@ -270,7 +255,7 @@ Keep each note in its own file \u2014 never grow one shared aggregate \u2014 so
|
|
|
270
255
|
concurrent commits touch different files and rebase cleanly. \`INDEX.md\` is
|
|
271
256
|
REGENERATED from the entries by the index job: don't hand-edit it, and treat
|
|
272
257
|
any merge conflict in it as noise (either side converges on the next run).
|
|
273
|
-
`}function
|
|
258
|
+
`}function Zv(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
|
|
274
259
|
|
|
275
260
|
One \`<id>.yml\` per action. Every file here appears as a button on the
|
|
276
261
|
project's **RUN** tab; an action with \`params\` opens a small wizard first.
|
|
@@ -309,7 +294,7 @@ steps:
|
|
|
309
294
|
Parameter values are passed to the commands **only as env vars** \u2014 reference
|
|
310
295
|
them as \`$INPUT_<NAME>\` in \`run\`; they are never substituted into the
|
|
311
296
|
command text itself.
|
|
312
|
-
`}function
|
|
297
|
+
`}function Qv(){return`# roles/ \u2014 who reviews your work
|
|
313
298
|
|
|
314
299
|
A **role** is a critic with a narrow view and its own curated context: one
|
|
315
300
|
\`<name>.md\` per role. Roles review a plan before the work starts, review the
|
|
@@ -337,7 +322,7 @@ You are the security critic. \u2026the body is the role's prompt\u2026
|
|
|
337
322
|
|
|
338
323
|
Keep \`refs\` short and specific: the value of a role is a NARROW view, and
|
|
339
324
|
"give it everything" is exactly the failure this design avoids.
|
|
340
|
-
`}function
|
|
325
|
+
`}function ex(){return`# skills/ \u2014 procedures the agent can invoke
|
|
341
326
|
|
|
342
327
|
A **skill** is a directory with a \`SKILL.md\`: a description of when to use it,
|
|
343
328
|
a body with the steps, and any files the steps need beside it (scripts,
|
|
@@ -396,7 +381,7 @@ A third-party marketplace **must** name a full commit sha: its skills run beside
|
|
|
396
381
|
your checked-out code with the agent's credentials, and a branch would let that
|
|
397
382
|
code change between two runs of the same task. Nothing from a marketplace is
|
|
398
383
|
active until it is listed in \`plugins\`.
|
|
399
|
-
`}function
|
|
384
|
+
`}function tx(){return`# BUILD phase config. Discovered & maintained by the agent.
|
|
400
385
|
# Steps run in a rootless Podman container in the SANDBOX, before the PR.
|
|
401
386
|
# Success = every step exits 0. Credentials are NOT available inside the container.
|
|
402
387
|
#
|
|
@@ -412,7 +397,7 @@ active until it is listed in \`plugins\`.
|
|
|
412
397
|
# - name: test
|
|
413
398
|
# run: npm test
|
|
414
399
|
# timeout_sec: 600 # per-step timeout (optional, default 600)
|
|
415
|
-
`}function
|
|
400
|
+
`}function rx(t,e){return`# ${e.name}
|
|
416
401
|
|
|
417
402
|
Context Repo for the **${t.name}** project (CodePipe).
|
|
418
403
|
|
|
@@ -438,7 +423,7 @@ PRs to this repository (and the agent also writes to \`knowledge/\` and
|
|
|
438
423
|
pipeline \u2014 don't edit them by hand.
|
|
439
424
|
|
|
440
425
|
Automation level: **${t.automationLevel}**.
|
|
441
|
-
`}function
|
|
426
|
+
`}function nx(t,e="auto"){return`# Project description for CodePipe.
|
|
442
427
|
id: ${t.projectId}
|
|
443
428
|
name: ${t.name}
|
|
444
429
|
|
|
@@ -465,24 +450,24 @@ apply:
|
|
|
465
450
|
# Branch (must keep the <TASK_ID> placeholder).
|
|
466
451
|
branch:
|
|
467
452
|
pattern: codepipe/<TASK_ID>
|
|
468
|
-
${
|
|
453
|
+
${Uf(t)}
|
|
469
454
|
repos:
|
|
470
|
-
${
|
|
471
|
-
`}function
|
|
455
|
+
${Bf(t)}
|
|
456
|
+
`}function Uf(t){let e=t.language;return!e||Object.keys(e).length===0?"":`
|
|
472
457
|
# Languages the agent writes in, per area. \`auto\` = mirror the language of
|
|
473
458
|
# the user's material. Also editable from the dashboard: project card \u2192
|
|
474
459
|
# Settings \u2192 Language.
|
|
475
460
|
language:
|
|
476
461
|
${Object.entries(e).map(([n,o])=>` ${n}: ${o}`).join(`
|
|
477
462
|
`)}
|
|
478
|
-
`}function
|
|
463
|
+
`}function Bf(t){return t.repos.length===0?` [] # add repos here
|
|
479
464
|
`:t.repos.map(e=>` - name: ${e.name}
|
|
480
465
|
host: ${e.host}
|
|
481
466
|
owner: ${e.owner}
|
|
482
467
|
repo: ${e.repoName}
|
|
483
468
|
mount_as: ${e.mountAs??e.name}`+(e.defaultBranch?`
|
|
484
469
|
default_branch: ${e.defaultBranch}`:"")).join(`
|
|
485
|
-
`)}function
|
|
470
|
+
`)}function ox(t,e,r,n="auto"){let o=e?`
|
|
486
471
|
tracker_url: ${e}`:`
|
|
487
472
|
# tracker_url: https://your.youtrack.cloud`,s=r?`require_assignee: true
|
|
488
473
|
assignee: ${r}`:`require_assignee: false
|
|
@@ -530,7 +515,7 @@ ${Object.entries(e).map(([n,o])=>` ${n}: ${o}`).join(`
|
|
|
530
515
|
# non-empty assignee. assignee only takes effect when require_assignee=true.
|
|
531
516
|
${s}`:` # project_key: \u2026
|
|
532
517
|
# tracker_url: https://your.youtrack.cloud
|
|
533
|
-
poll_interval_sec: 60`,a=
|
|
518
|
+
poll_interval_sec: 60`,a=Bf(t);return`# Project description for CodePipe.
|
|
534
519
|
id: ${t.projectId}
|
|
535
520
|
name: ${t.name}
|
|
536
521
|
|
|
@@ -564,10 +549,10 @@ apply:
|
|
|
564
549
|
# Branch (must keep the <TASK_ID> placeholder).
|
|
565
550
|
branch:
|
|
566
551
|
pattern: codepipe/<TASK_ID>
|
|
567
|
-
${
|
|
552
|
+
${Uf(t)}
|
|
568
553
|
repos:
|
|
569
554
|
${a}
|
|
570
|
-
`}function
|
|
555
|
+
`}function sx(t,e,r=!1,n=Ge,o){let s=t==="full",i=e?"true":"false",a=o?` # Model selection. This project's Claude subscription did not include every
|
|
571
556
|
# model in the recommended per-role split, so CodePipe set a single default
|
|
572
557
|
# your subscription can serve for all roles. Tune per role later from the
|
|
573
558
|
# dashboard (Project Settings \u2192 llm.models) or by editing this file.
|
|
@@ -709,47 +694,36 @@ ${a}
|
|
|
709
694
|
# sandbox quota (how many runners the account may occupy), enforced by the HUB
|
|
710
695
|
# and sized on the farm. A solo 'codepipe up' runs one worker. (ADR-0030)
|
|
711
696
|
|
|
712
|
-
`}var Pr=
|
|
713
|
-
`)}async function cm(t,e,r,n){let o=_c(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let s=As(t,e);if(!s.outdated)return s;let i=Bx(s.currentVersion),a=r?.branch??(await o.revparse(["--abbrev-ref","HEAD"]).catch(()=>"main")).trim();try{await o.fetch().catch(()=>{}),(await o.raw(["ls-remote","--heads","origin",i]).catch(()=>"")).trim().length===0?await Kx(t,e,r,s,i,a,n):n.info(`[ctx] migration branch ${i} already on origin \u2014 reusing`)}catch(l){return n.warn(`[ctx] context migration branch failed (will retry next start): ${l instanceof Error?l.message:String(l)}`),s}if(!r)return s;let c={name:r.name,host:r.host,owner:r.owner,repoName:r.name};try{let l=pt(c),u=await l.findOpenPrByBranch?.(c,i)??null;if(u)return n.info(`[ctx] migration PR already open: ${u.url}`),{...s,migrationPrUrl:u.url};let p=await l.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:i,baseBranch:a,title:`CodePipe: context format v${s.templateVersion} \u2192 v${s.currentVersion}`,body:Fx(s)});return n.info(`[ctx] migration PR opened: ${p.url}`),{...s,migrationPrUrl:p.url}}catch(l){return n.warn(`[ctx] migration PR create/find failed (branch pushed, badge without link): ${l instanceof Error?l.message:String(l)}`),s}}async function Kx(t,e,r,n,o,s,i){let a=_c(t),c=Dx(_s(Mx(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",o,c,`origin/${s}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},u={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},p=new Map(ln(l,u).map(g=>[g.path,g.content])),d=0;for(let g of n.missingPaths){if(g===lt)continue;let h=p.get(g);if(h==null){i.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let w=_s(c,g);sm(w)||(Lx(Ux(w),{recursive:!0}),am(w,h),d++)}am(_s(c,lt),Vn(n.currentVersion)),d++;let m=_s(c,Hr);sm(m)&&(im(m,{force:!0}),d++);let f=_c(c);await f.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await f.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await f.push(["-u","origin",o]),i.info(`[ctx] migration branch ${o} pushed (${d} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),im(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}var lm=v(()=>{"use strict";F();Yt();Tc();Pr()});import{existsSync as Gx,readFileSync as Hx,writeFileSync as Wx}from"node:fs";import{homedir as qx}from"node:os";import{join as um}from"node:path";import{parseDocument as Yx}from"yaml";function Vx(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 zx(t,e){let r=Yx(t);return r.set("repos",e.map(Vx)),r.toString()}function Xx(t,e){let r=[um(qx(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(um(e,"project.yaml")),r}function wo(t,e,r){let n=[],o=[];for(let s of Xx(t,r))if(Gx(s))try{let i=Hx(s,"utf-8"),a=zx(i,e);a!==i&&(Wx(s,a),n.push(s))}catch(i){o.push({path:s,error:i instanceof Error?i.message:String(i)})}return{updated:n,errors:o}}var jc=v(()=>{"use strict"});import{createCipheriv as Jx,createDecipheriv as Zx,createHash as Qx,createPrivateKey as eS,createPublicKey as Nc,diffieHellman as dm,generateKeyPairSync as pm,hkdfSync as fm,randomBytes as tS}from"node:crypto";function js(){let{publicKey:t,privateKey:e}=pm("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function De(t){let e=Buffer.from(t,"base64");return(Qx("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function Dt(t,e){let r=Nc({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=pm("x25519"),s=n.export({type:"spki",format:"der"}),i=r.export({type:"spki",format:"der"}),a=dm({privateKey:o,publicKey:r}),c=Buffer.from(fm("sha256",a,Buffer.concat([s,i]),mm,32)),l=tS(12),u=Jx("aes-256-gcm",c,l),p=typeof e=="string"?Buffer.from(e,"utf-8"):e,d=Buffer.concat([u.update(p),u.final()]),m=u.getAuthTag(),f={v:1,epk:s.toString("base64"),iv:l.toString("base64"),tag:m.toString("base64"),ct:d.toString("base64")};return Buffer.from(JSON.stringify(f),"utf-8").toString("base64")}function un(t,e){let r=JSON.parse(Buffer.from(e,"base64").toString("utf-8"));if(r.v!==1)throw new Error(`sealedbox: unsupported envelope version ${r.v}`);let n=eS({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=Nc({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),s=o.export({type:"spki",format:"der"}),i=Nc(n).export({type:"spki",format:"der"}),a=dm({privateKey:n,publicKey:o}),c=Buffer.from(fm("sha256",a,Buffer.concat([s,i]),mm,32)),l=Zx("aes-256-gcm",c,Buffer.from(r.iv,"base64"));return l.setAuthTag(Buffer.from(r.tag,"base64")),Buffer.concat([l.update(Buffer.from(r.ct,"base64")),l.final()])}var mm,ot=v(()=>{"use strict";mm=Buffer.from("devpipe-sealedbox-v1","utf-8")});function rS(t,e){let r={};t.github?.token&&(r.github={token:t.github.token}),t.bitbucket?.apiToken&&(r.bitbucket={apiToken:t.bitbucket.apiToken}),t.gitlab?.token&&(r.gitlab={token:t.gitlab.token});let n=e??t.claude?.oauthToken;return n&&(r.claudeOauthToken=n),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),r}function hm(t,e,r,n){let o=rS(e,r);t.sandboxes.length>0&&!o.claudeOauthToken&&n.warn("[cred] no Claude OAuth token set \u2014 agent jobs will fail in the SANDBOX. Set one with `codepipe login` (per project) or `make farm-config` (shared farm token)."),t.sandboxes.length>0&&!o.contextWrite&&(o.github||o.gitlab||o.bitbucket)&&n.warn("[cred] no dedicated contextWrite token \u2014 SANDBOX pushes deliveries with the project token of the context repo's host (broader scope than necessary). Set secrets.contextWrite.token (a token scoped to the Context Repo only) to tighten. NOTE (GitHub): the push token MUST have the `workflow` scope, else delivery pushes that carry `.github/workflows/*` are rejected.");let s=JSON.stringify(o),i=[];for(let a of t.sandboxes){let c=is(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=Dt(a.publicKey,s)}catch(u){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}i.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return i}var gm=v(()=>{"use strict";ot();de()});function bo(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(s,i)=>{e[`GIT_CONFIG_KEY_${n+s}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+s}`]=i};return o(0,"git@github.com:"),o(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function $o(t,e=process.env){if(!t)return!1;let r=`https://oauth2:${t}@gitlab.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(s,i)=>{e[`GIT_CONFIG_KEY_${n+s}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+s}`]=i};return o(0,"git@gitlab.com:"),o(1,"ssh://git@gitlab.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function vo(t,e=process.env){if(!t)return!1;let r=`https://${Gt}:${encodeURIComponent(t)}@bitbucket.org/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(s,i)=>{e[`GIT_CONFIG_KEY_${n+s}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+s}`]=i};return o(0,"git@bitbucket.org:"),o(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function Oc(t,e,r,n){let o=Number.parseInt(n.GIT_CONFIG_COUNT??"0",10)||0,s=!1;for(let i=0;i<o;i++){let a=n[`GIT_CONFIG_KEY_${i}`];a&&t.test(a)&&(n[`GIT_CONFIG_KEY_${i}`]=`url.${e}.insteadOf`,s=!0)}return s||r()}function ym(t,e=process.env){return Oc(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>bo(t,e),e)}function km(t,e=process.env){return Oc(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>$o(t,e),e)}function wm(t,e=process.env){return Oc(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Gt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>vo(t,e),e)}var Ns=v(()=>{"use strict";F()});function bm(t){let e=q(t);if(!e)return null;if(!e.sealKey){let r=js();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},se(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:De(e.sealKey.publicKey)}}async function $m(t,e,r,n){let o;try{o=JSON.parse(un(n,r).toString("utf-8"))}catch(i){return{ok:!1,detail:`cannot open the sealed credential (${i instanceof Error?i.message:String(i)}) \u2014 wrong channel key?`}}let s=q(t);if(!s)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!o.token)return{ok:!1,detail:"payload has no token"};let i=await Ht(o.token);return s.github={token:o.token},dn(s,()=>{process.env.GH_TOKEN=o.token,ym(o.token)}),{ok:!0,detail:`authenticated as ${i}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let i=await qt(o.token);return s.gitlab={token:o.token},dn(s,()=>{process.env.GITLAB_TOKEN=o.token,km(o.token)}),{ok:!0,detail:`authenticated as ${i}`}}case"bitbucket":{if(!o.email||!o.apiToken)return{ok:!1,detail:"payload needs email + apiToken"};let i=await Wt(o.email,o.apiToken);return s.bitbucket={email:o.email,apiToken:o.apiToken},dn(s,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,wm(o.apiToken)}),{ok:!0,detail:`authenticated as ${i}`}}case"youtrack":{if(!o.token)return{ok:!1,detail:"payload has no token"};let i=o.url?.trim().replace(/\/$/,"")||s.youtrack?.url;if(!i)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await zt({baseUrl:i,token:o.token});return s.youtrack={url:i,token:o.token},dn(s,()=>{process.env.YOUTRACK_URL=i,process.env.YOUTRACK_TOKEN=o.token}),{ok:!0,detail:`authenticated as ${a}`}}case"claude":{if(!o.token)return{ok:!1,detail:"payload has no token"};let i=await Nt(o.token);return i==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(s.claude={oauthToken:o.token},dn(s,()=>{}),{ok:!0,...i==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(s.contextWrite={token:o.token},dn(s,()=>{}),{ok:!0,detail:"saved (verified on the next readiness pass)"}):{ok:!1,detail:"payload has no token"};default:return{ok:!1,detail:`unknown credential kind '${e}'`}}}catch(i){return{ok:!1,detail:`${i instanceof Error?i.message:String(i)} \u2014 previous credential kept`}}}function dn(t,e){se(t),e()}var vm=v(()=>{"use strict";ot();de();Yt();$r();nn();Ns()});import{spawn as nS}from"node:child_process";function sS(t,e,r,n,o,s){let i={...t},a=(c,l)=>{Pt(c)||(i[c]=l)};for(let[c,l]of Object.entries(e))a(c,l);for(let[c,l]of Object.entries(r))a(c,l);for(let[c,l]of Object.entries(n??{}))a(c,l);for(let[c,l]of Object.entries(o))i[c]=l;for(let[c,l]of Object.entries(s))i[`INPUT_${c}`]=String(l);return i}async function Em(t){let{def:e,onEvent:r}=t,n=sS(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",s=a=>{o+=a+`
|
|
714
|
-
`,o.length>xm&&(o=o.slice(o.length-xm))},i=(a,c)=>{let l=c.length>Sm?c.slice(0,Sm)+"\u2026":c;s(l),r({ts:Date.now(),kind:"log",stream:a,text:l})};r({ts:Date.now(),kind:"start",status:"running"});for(let[a,c]of e.steps.entries()){let l=c.name??`step ${a+1}`;r({ts:Date.now(),kind:"step",stepName:l});let u=await iS(c.run,c.timeout_sec,t.cwd,n,i);if(u!==0)return s(`[${l}] exited with code ${u}`),r({ts:Date.now(),kind:"result",status:"failed",exitCode:u,failedStep:l}),{status:"failed",exitCode:u,failedStep:l,logTail:o}}return r({ts:Date.now(),kind:"result",status:"succeeded",exitCode:0}),{status:"succeeded",exitCode:0,logTail:o}}function iS(t,e,r,n,o){return new Promise(s=>{let i=nS("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??ya)*1e3,l=setTimeout(()=>{a=!0,o("stderr",`step timed out after ${c/1e3}s \u2014 killing`),i.kill("SIGTERM"),setTimeout(()=>i.kill("SIGKILL"),5e3).unref()},c);l.unref?.();let u=m=>{let f="";return{data:g=>{f+=g.toString("utf-8");let h;for(;(h=f.indexOf(`
|
|
715
|
-
`))!==-1;)o(m,f.slice(0,h).replace(/\r$/,"")),f=f.slice(h+1)},flush:()=>{f.length>0&&o(m,f.replace(/\r$/,"")),f=""}}},p=u("stdout"),d=u("stderr");i.stdout?.on("data",p.data),i.stderr?.on("data",d.data),i.on("error",m=>{clearTimeout(l),o("stderr",`spawn failed: ${m.message}`),s(127)}),i.on("close",(m,f)=>{clearTimeout(l),p.flush(),d.flush(),s(a?oS:m??(f?1:0))})})}var oS,xm,Sm,Rm=v(()=>{"use strict";F();oS=124,xm=16*1024,Sm=4e3});import{existsSync as aS,readFileSync as cS,statSync as Im}from"node:fs";function lS(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function Cm(t,e){let r=ke(t,e);if(e.split("/").some(s=>s===".git"))throw new Error(`not a context file: ${e}`);if(!aS(r)||!Im(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=Im(r);if(n>Tm)throw new Error(`file too large: ${e} is ${n} bytes (limit ${Tm})`);let o=cS(r);return lS(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}var Tm,Am=v(()=>{"use strict";nt();Tm=2*1024*1024});import{existsSync as uS,readFileSync as dS,writeFileSync as pS}from"node:fs";import{join as fS}from"node:path";import{parseDocument as mS}from"yaml";async function Pm(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let s=Ra(o);if(!s.ok)throw new Error(s.error);let i=r.get(o.file)??[];i.push({path:s.field.path,value:s.value}),r.set(o.file,i)}let n=[];for(let[o,s]of r){let i=fS(t,o);if(!uS(i))throw new Error(`${o} not found in context repo (${t})`);let a=mS(dS(i,"utf-8"));for(let c of s)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);pS(i,a.toString()),n.push(o)}return{files:n}}var _m=v(()=>{"use strict";F()});import{existsSync as hS,readFileSync as gS,writeFileSync as yS}from"node:fs";import{join as kS}from"node:path";import{isMap as jm,parseDocument as wS}from"yaml";async function Nm(t,e){let r=e.repoName?.trim(),n=e.defaultBranch?.trim();if(!r)throw new Error("repoName must be a non-empty string");if(!n||!Ua(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=kS(t,"project.yaml");if(!hS(o))throw new Error(`project.yaml not found in context repo (${t})`);let s=wS(gS(o,"utf-8")),i=s.get("repos"),c=(i&&typeof i=="object"&&"items"in i?i.items:[]).find(l=>jm(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!jm(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),yS(o,s.toString()),{repoName:r,defaultBranch:n}}var Om=v(()=>{"use strict";F()});import{existsSync as Lc,readFileSync as Dc,writeFileSync as bS}from"node:fs";import{join as Os}from"node:path";import{parseDocument as Mc}from"yaml";async function Lm(t,e){let r=[];if(e.stageField!==void 0||e.sourceColumns!==void 0||e.rejectColumns!==void 0||e.doneColumns!==void 0||e.reviewColumns!==void 0||e.statusColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0||e.backlogScope!==void 0){let s=Os(t,"project.yaml");if(!Lc(s))throw new Error(`project.yaml not found in context repo (${t})`);let i=Mc(Dc(s,"utf-8"));if(e.stageField!==void 0){let a=typeof e.stageField=="string"?e.stageField.trim():"";a&&a!=="Stage"?i.setIn(["youtrack","stage_field"],a):i.deleteIn(["youtrack","stage_field"])}if(e.rejectColumns!==void 0){let a=e.rejectColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?i.setIn(["youtrack","reject_columns"],a):i.deleteIn(["youtrack","reject_columns"])}if(e.doneColumns!==void 0){let a=e.doneColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?i.setIn(["youtrack","done_columns"],a):i.deleteIn(["youtrack","done_columns"])}if(e.reviewColumns!==void 0){let a=e.reviewColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?i.setIn(["youtrack","review_columns"],a):i.deleteIn(["youtrack","review_columns"])}if(e.statusColumns!==void 0){let a=e.statusColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?i.setIn(["youtrack","status_columns"],a):i.deleteIn(["youtrack","status_columns"])}if(e.sourceColumns!==void 0){let a=e.sourceColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);if(a.length===0)throw new Error("source_columns must be a non-empty list of non-empty strings");i.setIn(["youtrack","source_columns"],a)}if(e.backlogColumn!==void 0){let a=typeof e.backlogColumn=="string"?e.backlogColumn.trim():"";a?i.setIn(["youtrack","backlog_column"],a):i.deleteIn(["youtrack","backlog_column"])}if(e.assignee!==void 0){let a=typeof e.assignee=="string"?e.assignee.trim():"";a?i.setIn(["youtrack","assignee"],a):i.deleteIn(["youtrack","assignee"])}e.requireAssignee!==void 0&&i.setIn(["youtrack","require_assignee"],e.requireAssignee===!0),e.backlogScope!==void 0&&(e.backlogScope==="personal"?i.setIn(["youtrack","backlog_scope"],"personal"):e.backlogScope==="shared"?i.setIn(["youtrack","backlog_scope"],"shared"):i.deleteIn(["youtrack","backlog_scope"])),r.push({path:"project.yaml",content:i.toString()})}if(e.reviewStatus!==void 0||e.writes!==void 0){let s=Os(t,"regimen.yaml");if(!Lc(s))throw new Error(`regimen.yaml not found in context repo (${t})`);let i=Mc(Dc(s,"utf-8"));if(e.reviewStatus!==void 0){let a=e.reviewStatus.trim();a&&i.setIn(["youtrack","review_status"],a)}if(e.writes!==void 0){let a=e.writes;i.setIn(["youtrack","writes","enabled"],a.enabled===!0),i.setIn(["youtrack","writes","status_changes"],a.statusChanges===!0),i.setIn(["youtrack","writes","pr_comment"],a.prComment===!0),i.setIn(["youtrack","writes","dashboard_mirror"],a.dashboardMirror===!0)}r.push({path:"regimen.yaml",content:i.toString()})}if(r.length===0)return{files:[]};for(let s of r)bS(Os(t,s.path),s.content);return{files:r.map(s=>s.path)}}function Ls(t){if(!t)return"Stage";try{let e=Os(t,"project.yaml");if(!Lc(e))return"Stage";let n=Mc(Dc(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}var Uc=v(()=>{"use strict"});import{existsSync as Dm,readFileSync as Mm,readdirSync as $S}from"node:fs";import{join as Bc}from"node:path";import{simpleGit as vS}from"simple-git";function xS(t,e){let r=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/.exec(e);if(!r)return null;let n="",o="";for(let i of r[1].split(`
|
|
716
|
-
`)){let a=/^(\w+):\s*(.+)$/.exec(i.trim());a&&(a[1]==="repo"&&(n=a[2].trim()),a[1]==="path"&&(o=a[2].trim().replace(/^\.\//,"")))}let s=r[2].trim();return!n||!o||!s||o.includes("..")||o.startsWith("/")?null:{repo:n,path:o,body:s,source:t}}function SS(t,e){let r=Bc(t,`tasks/${e}/annotations`);if(!Dm(r))return[];let n=[];for(let o of $S(r).sort())if(o.endsWith(".md")){try{let s=xS(o,Mm(Bc(r,o),"utf-8"));s&&n.push(s)}catch{}if(n.length>=ta)break}return n}async function Um(t){let{contextDir:e,taskKey:r,repoName:n,repoDir:o,commitSha:s,date:i,touchedKeys:a,identity:c}=t;if(!c)return[];let l=new Map(c.entities.filter(d=>d.status==="active").map(d=>[d.currentKey,d.entityId])),u=vS(o),p=[];for(let d of SS(e,r)){if(d.repo!==n)continue;let m=fe("code",n,d.path);if(!a.has(m))continue;let f=l.get(m);if(!f)continue;let g=(await u.raw(["rev-parse",`${s}:${d.path}`]).catch(()=>"")).trim().slice(0,ES),h=zi(f),w=Bc(e,h),y=p.find(T=>T.path===h),x=y?.content??(Dm(w)?Mm(w,"utf-8"):null),S=`<!-- ${r}${g?`:${g}`:""} -->`;if(x?.includes(S))continue;let I=x??`---
|
|
697
|
+
`}var Pr=S(()=>{"use strict";F();Ps()});import{createCipheriv as $x,createDecipheriv as vx,createHash as xx,createPrivateKey as Sx,createPublicKey as _c,diffieHellman as qf,generateKeyPairSync as Yf,hkdfSync as Vf,randomBytes as Ex}from"node:crypto";function js(){let{publicKey:t,privateKey:e}=Yf("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function De(t){let e=Buffer.from(t,"base64");return(xx("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function Dt(t,e){let r=_c({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=Yf("x25519"),s=n.export({type:"spki",format:"der"}),i=r.export({type:"spki",format:"der"}),a=qf({privateKey:o,publicKey:r}),c=Buffer.from(Vf("sha256",a,Buffer.concat([s,i]),zf,32)),l=Ex(12),u=$x("aes-256-gcm",c,l),p=typeof e=="string"?Buffer.from(e,"utf-8"):e,d=Buffer.concat([u.update(p),u.final()]),m=u.getAuthTag(),f={v:1,epk:s.toString("base64"),iv:l.toString("base64"),tag:m.toString("base64"),ct:d.toString("base64")};return Buffer.from(JSON.stringify(f),"utf-8").toString("base64")}function un(t,e){let r=JSON.parse(Buffer.from(e,"base64").toString("utf-8"));if(r.v!==1)throw new Error(`sealedbox: unsupported envelope version ${r.v}`);let n=Sx({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=_c({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),s=o.export({type:"spki",format:"der"}),i=_c(n).export({type:"spki",format:"der"}),a=qf({privateKey:n,publicKey:o}),c=Buffer.from(Vf("sha256",a,Buffer.concat([s,i]),zf,32)),l=vx("aes-256-gcm",c,Buffer.from(r.iv,"base64"));return l.setAuthTag(Buffer.from(r.tag,"base64")),Buffer.concat([l.update(Buffer.from(r.ct,"base64")),l.final()])}var zf,ot=S(()=>{"use strict";zf=Buffer.from("devpipe-sealedbox-v1","utf-8")});function bo(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(s,i)=>{e[`GIT_CONFIG_KEY_${n+s}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+s}`]=i};return o(0,"git@github.com:"),o(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function $o(t,e=process.env){if(!t)return!1;let r=`https://oauth2:${t}@gitlab.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(s,i)=>{e[`GIT_CONFIG_KEY_${n+s}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+s}`]=i};return o(0,"git@gitlab.com:"),o(1,"ssh://git@gitlab.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function vo(t,e=process.env){if(!t)return!1;let r=`https://${Gt}:${encodeURIComponent(t)}@bitbucket.org/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(s,i)=>{e[`GIT_CONFIG_KEY_${n+s}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+s}`]=i};return o(0,"git@bitbucket.org:"),o(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function jc(t,e,r,n){let o=Number.parseInt(n.GIT_CONFIG_COUNT??"0",10)||0,s=!1;for(let i=0;i<o;i++){let a=n[`GIT_CONFIG_KEY_${i}`];a&&t.test(a)&&(n[`GIT_CONFIG_KEY_${i}`]=`url.${e}.insteadOf`,s=!0)}return s||r()}function Jf(t,e=process.env){return jc(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>bo(t,e),e)}function Zf(t,e=process.env){return jc(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>$o(t,e),e)}function Qf(t,e=process.env){return jc(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Gt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>vo(t,e),e)}var Ns=S(()=>{"use strict";F()});import{existsSync as pm,readFileSync as fm,readdirSync as Wx}from"node:fs";import{join as Dc}from"node:path";import{simpleGit as qx}from"simple-git";function Yx(t,e){let r=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/.exec(e);if(!r)return null;let n="",o="";for(let i of r[1].split(`
|
|
698
|
+
`)){let a=/^(\w+):\s*(.+)$/.exec(i.trim());a&&(a[1]==="repo"&&(n=a[2].trim()),a[1]==="path"&&(o=a[2].trim().replace(/^\.\//,"")))}let s=r[2].trim();return!n||!o||!s||o.includes("..")||o.startsWith("/")?null:{repo:n,path:o,body:s,source:t}}function Vx(t,e){let r=Dc(t,`tasks/${e}/annotations`);if(!pm(r))return[];let n=[];for(let o of Wx(r).sort())if(o.endsWith(".md")){try{let s=Yx(o,fm(Dc(r,o),"utf-8"));s&&n.push(s)}catch{}if(n.length>=na)break}return n}async function mm(t){let{contextDir:e,taskKey:r,repoName:n,repoDir:o,commitSha:s,date:i,touchedKeys:a,identity:c}=t;if(!c)return[];let l=new Map(c.entities.filter(d=>d.status==="active").map(d=>[d.currentKey,d.entityId])),u=qx(o),p=[];for(let d of Vx(e,r)){if(d.repo!==n)continue;let m=fe("code",n,d.path);if(!a.has(m))continue;let f=l.get(m);if(!f)continue;let g=(await u.raw(["rev-parse",`${s}:${d.path}`]).catch(()=>"")).trim().slice(0,zx),h=Ji(f),w=Dc(e,h),y=p.find(T=>T.path===h),v=y?.content??(pm(w)?fm(w,"utf-8"):null),x=`<!-- ${r}${g?`:${g}`:""} -->`;if(v?.includes(x))continue;let I=v??`---
|
|
717
699
|
entityId: ${f}
|
|
718
700
|
---
|
|
719
701
|
|
|
720
702
|
# Intent log
|
|
721
703
|
|
|
722
704
|
Append-only. Keyed by entityId \u2014 never by path; entries survive renames.
|
|
723
|
-
`,E=["",`## ${i} \u2014 ${r}`,
|
|
724
|
-
`),$=I+E;y?y.content=$:p.push({path:h,content:$})}return p}var
|
|
725
|
-
`))if(a.startsWith("@@@ ")){let c=a.indexOf(" "),l=(c>=0?a.slice(4,c):a.slice(4)).trim().split(/\s+/),u=c>=0?a.slice(c+1):"",p=l[0]??"",d=Number(l[1]??0),m=l.slice(2),f=
|
|
726
|
-
`)){let i=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(s);if(!i)continue;let a=i[1]==="-"?0:Number(i[1]),c=i[2]==="-"?0:Number(i[2]);o.push({path
|
|
727
|
-
`))if(a.startsWith("@@@ ")){let[c,l]=a.slice(4).trim().split(/\s+/);i={sha:c??"",timeSec:Number(l??0),files:[]},s.push(i)}else a.trim()&&i&&i.files.push(a.trim());return s}function Ms(t){let e=new Map;for(let r of t.entities){if(r.status!=="active"||!r.aliases)continue;let n=re(r.currentKey);if(n?.level==="code")for(let o of r.aliases){let s=re(o.key);s?.level==="code"&&e.set(s.path,n.path)}}return e}function
|
|
728
|
-
`).map(i=>i.trim()).filter(Boolean),s=[];for(let i of o){let c=(await n.raw(["diff","-M","-C","-z","--name-status","--diff-filter=R",`${i}^`,i]).catch(()=>"")).split("\0");for(let l=0;l+2<c.length;){if(!(c[l]??"").startsWith("R")){l+=1;continue}let p=c[l+1]??"",d=c[l+2]??"";p&&d&&s.push({fromPath:p,toPath:d,commit:i}),l+=3}}return s}function th(t){let e=new Map,r=new Map;for(let n of t){let o=r.get(n.fromPath)??n.fromPath;r.delete(n.fromPath),r.set(n.toPath,o),e.set(o,{finalPath:n.toPath,commit:n.commit})}for(let[n,o]of e)o.finalPath===n&&e.delete(n);return e}var rh=v(()=>{"use strict"});function Bs(t){return fe("container",t,OS)}function nh(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function oh(t,e,r,n){let o=[],s=u=>{let p=fe("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:nh(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,LS)}},i=(u,p)=>{let d=fe("component",t,u),m=n.get(d);return{key:d,level:"component",label:nh(u),...m?{entityId:m}:{},...p?{aggregate:!0}:{}}},a=(u,p,d)=>{let m=r.filesByDir.get(d)??[],f=r.childDirs.get(d)??[],g=[p,...m.map(s)],h=[...m.map(w=>({kind:"contains",from:p.key,to:fe("code",t,w.path)})),...f.map(w=>({kind:"contains",from:p.key,to:fe("component",t,w)}))];c(u,g,h)},c=(u,p,d)=>{let m={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},f=Ct(m);if(!f.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${f.errors.join("; ")}`);o.push({path:Zi(t,u),content:oa(m)})},l={key:Bs(t),level:"container",label:t,...n.get(Bs(t))?{entityId:n.get(Bs(t))}:{}};a("",l,"");for(let u of r.components)r.collapsed.has(u)?c(u,[i(u,!0)],[]):a(u,i(u,!1),u);return o.sort((u,p)=>u.path<p.path?-1:u.path>p.path?1:0),{files:o,counts:r.counts}}function sh(t,e){let r=[Bs(t)];for(let n of e.components)r.push(fe("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(fe("code",t,o.path));return r.sort()}var OS,LS,ih=v(()=>{"use strict";F();OS=".";LS=12});import{simpleGit as ch}from"simple-git";function _r(t){let e=new Set,r=[],n=new Set;for(let o of t){let s=o.trim();if(s)if(s.endsWith("/"))e.add(s.slice(0,-1));else if(s.includes("*")){let i=s.replace(/[.*+?^${}()|[\]\\]/g,a=>a==="*"?"\0":`\\${a}`).replace(/\0/g,".*");r.push(new RegExp(`^${i}$`))}else n.add(s)}return o=>{let s=o.split("/"),i=s[s.length-1]??o;if(n.has(o))return!0;for(let a of s)if(e.has(a)||n.has(a))return!0;return r.some(a=>a.test(i))}}async function uh(t,e="HEAD"){let r=ch(t),n=(await r.revparse([e])).trim(),[o,s]=(await r.raw(["show","-s","--format=%cs %ct",n])).trim().split(/\s+/);return{commit:n,commitDate:o??"",commitTimeSec:Number(s??0),files:await xo(t,n)}}async function xo(t,e){let n=await ch(t).raw(["ls-tree","-r","-z",e]),o=[];for(let s of n.split("\0")){if(!s)continue;let i=s.indexOf(" ");if(i<0)continue;let[,a,c]=s.slice(0,i).split(/\s+/);a!=="blob"||!c||o.push({path:s.slice(i+1),blobHash:c})}return o.sort((s,i)=>s.path<i.path?-1:s.path>i.path?1:0),o}function ah(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function dh(t,e){let r=[...t].sort((f,g)=>f.path<g.path?-1:f.path>g.path?1:0),n=new Map,o=new Map;for(let f of r){let g=ah(f.path);n.has(g)||n.set(g,[]),n.get(g).push(f);let h=g;for(;h!=="";){let w=ah(h);o.has(w)||o.set(w,new Set),o.get(w).add(h),h=w}}let s=f=>[...o.get(f)??[]].sort(),i=Math.max(e,1)-1,a=new Set,c=new Set,l=[""];for(;l.length>0;){let f=l.shift(),g=(n.get(f)??[]).length+s(f).length;if(g<=i)i-=g,c.add(f),l.push(...s(f));else{if(f==="")return{components:[],collapsed:new Set,filesByDir:new Map,childDirs:new Map,counts:{component:0,code:0}};a.add(f)}}let u=[],p=new Map,d=new Map,m=0;for(let f of[...c].sort()){let g=n.get(f)??[];p.set(f,g),d.set(f,s(f)),m+=g.length,f!==""&&u.push(f)}for(let f of a)u.push(f);return u.sort(),{components:u,collapsed:a,filesByDir:p,childDirs:d,counts:{component:u.length,code:m}}}var lh,So=v(()=>{"use strict";lh=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as ph,readFileSync as fh}from"node:fs";import{join as mh}from"node:path";import{simpleGit as DS}from"simple-git";import{parse as hh}from"yaml";function fn(t){let e={ignore:lh,containerNodeCap:MS,cochange:{...Qe},issueKeyPattern:null,enabled:!1},r=mh(t,"regimen.yaml");if(!ph(r))return e;let n;try{n=hh(fh(r,"utf-8"))}catch{return e}let o=n?.context,s=o&&typeof o=="object"?o.model:void 0;if(!s||typeof s!="object")return e;let i=s,a=Array.isArray(i.ignore)?i.ignore.filter(m=>typeof m=="string"&&m.trim().length>0):e.ignore,c=(m,f)=>typeof m=="number"&&Number.isInteger(m)&&m>0?m:f,l=c(i.container_node_cap,e.containerNodeCap),u=i.cochange&&typeof i.cochange=="object"?i.cochange:{},p={windowCommits:c(u.window_commits,e.cochange.windowCommits),commitFileCap:c(u.commit_file_cap,e.cochange.commitFileCap),supportMin:c(u.support_min,e.cochange.supportMin),jaccardMinPct:typeof u.jaccard_min_pct=="number"&&Number.isInteger(u.jaccard_min_pct)&&u.jaccard_min_pct>=0&&u.jaccard_min_pct<=100?u.jaccard_min_pct:e.cochange.jaccardMinPct,halfLifeDays:c(u.half_life_days,e.cochange.halfLifeDays),topK:c(u.top_k,e.cochange.topK)},d=typeof i.issue_key_pattern=="string"&&i.issue_key_pattern.trim().length>0?i.issue_key_pattern.trim():null;return{ignore:a,containerNodeCap:l,cochange:p,issueKeyPattern:d,enabled:i.enabled===!0}}function Yc(t,e){let r=mh(t,Xn(e));if(!ph(r))return null;let n=hh(fh(r,"utf-8")),o=Zn(n);if(!o.ok)throw new Error(`model: ${Xn(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function Vc(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,s=await uh(r,t.ref??"HEAD"),i=_r(o.ignore),a=s.files.filter(y=>!i(y.path)),c=dh(a,o.containerNodeCap),l=Yc(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==s.commit?await DS(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=th(await eh(r,l.builtFromCommit,s.commit)),p=new Map((await xo(r,l.builtFromCommit)).map(S=>[S.path,S.blobHash]))):l?.builtFromCommit===s.commit&&(p=new Map(a.map(y=>[y.path,y.blobHash])));let d=new Map(a.map(y=>[y.path,y.blobHash])),m=Zm({repo:e,headCommit:s.commit,headDate:s.commitDate,prev:l,currentKeys:sh(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),f=oh(e,s.commit,c,m.byKey),g=_r([...o.ignore,...pn]),h=Jm({repo:e,headTimeSec:s.commitTimeSec,filesets:await Xm(r,s.commit,o.cochange.windowCommits),pathToCurrent:Ms(m.table),currentPaths:new Set(a.map(y=>y.path)),ignored:g,settings:o.cochange}),w=[{path:Xn(e),content:sa(m.table)},...f.files.map(y=>({path:y.path,content:y.content})),{path:Xi(e),content:fr({modelFormatVersion:2,repo:e,builtFromCommit:s.commit,edges:h})}];return{repo:e,headCommit:s.commit,files:w,emittedShardPaths:new Set(f.files.map(y=>y.path)),counts:{...f.counts,correlates:h.length},identityTable:m.table,entityByKey:m.byKey}}var MS,zc=v(()=>{"use strict";F();Us();Qm();rh();ih();So();MS=1500});import{existsSync as yh,readFileSync as kh,readdirSync as US}from"node:fs";import{join as Xc}from"node:path";import{parse as wh}from"yaml";function BS(t,e){if(!t||!e)return null;let r=Date.parse(`${t}T00:00:00Z`),n=Date.parse(`${e}T00:00:00Z`);return!Number.isFinite(r)||!Number.isFinite(n)?null:Math.abs(r-n)/864e5}function bh(t,e,r){let n=new Set(t.files.map(d=>d.key)),o=new Set(e.files.map(d=>d.key)),s=0;for(let d of n)o.has(d)&&s++;if(s<ea)return null;let i=s/Math.min(n.size,o.size),a=BS(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(i*c*gh)/gh;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[ge(t.taskKey),ge(e.taskKey)]:[ge(e.taskKey),ge(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function $h(t,e){let r=new Map(t.map(i=>[i.taskKey,i])),n=new Map;for(let i of t)for(let a of i.files)n.has(a.key)||n.set(a.key,[]),n.get(a.key).push(i.taskKey);let o=new Set,s=[];for(let i of n.values())if(!(i.length<2))for(let a=0;a<i.length;a++)for(let c=a+1;c<i.length;c++){let[l,u]=i[a]<i[c]?[i[a],i[c]]:[i[c],i[a]],p=`${l}\0${u}`;if(o.has(p))continue;o.add(p);let d=bh(r.get(l),r.get(u),e);d&&s.push(d)}return s.sort((i,a)=>i.from<a.from?-1:i.from>a.from?1:i.to<a.to?-1:1)}function vh(t,e,r,n){let o=ge(r),s=t.filter(a=>a.from!==o&&a.to!==o),i=e.find(a=>a.taskKey===r);if(i){let a=new Set(i.files.map(c=>c.key));for(let c of e){if(c.taskKey===r||!c.files.some(u=>a.has(u.key)))continue;let l=bh(i,c,n);l&&s.push(l)}}return s.sort((a,c)=>a.from<c.from?-1:a.from>c.from?1:a.to<c.to?-1:1)}function Fs(t){let e=Xc(t,"model/facts/events");if(!yh(e))return[];let r=[];for(let n of US(e).sort())if(n.endsWith(".yaml"))try{let o=At(wh(kh(Xc(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function xh(t){let e=Xc(t,dr);if(!yh(e))return[];try{let r=Jn(wh(kh(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function Ks(t){return fr({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var gh,Jc=v(()=>{"use strict";F();gh=1e4});var Eo={};Fe(Eo,{collectSearchRows:()=>Eh,readContextIndexHub:()=>FS,rebuildSearchIndex:()=>Rh,searchIndexPath:()=>qs,searchModelIndex:()=>KS,toFtsQuery:()=>Ih});import{existsSync as hn,readFileSync as mn,readdirSync as Hs}from"node:fs";import{join as ht}from"node:path";import{parse as Ws}from"yaml";function qs(t){return ht(t,".git","codepipe-model-index.sqlite")}function FS(t){let e=ht(t,"regimen.yaml");if(!hn(e))return"off";try{let n=Ws(mn(e,"utf-8"))?.context,o=n&&typeof n=="object"?n.index:null;return(o&&typeof o=="object"?o.hub:null)==="metadata"?"metadata":"off"}catch{return"off"}}async function Sh(){try{let{createRequire:t}=await import("node:module");return t(import.meta.url)("node:sqlite")}catch{return null}}function Gs(t){return t.length>zo?t.slice(0,zo):t}function Zc(t){if(!hn(t))return[];let e=[];for(let r of Hs(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=ht(t,r.name);r.isDirectory()?e.push(...Zc(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function Eh(t){let e=[];for(let s of Zc(ht(t,"model/derived/structure"))){let i;try{i=Ws(mn(s,"utf-8"))}catch{continue}let a=Ct(i);if(a.ok)for(let c of a.value.nodes){let l=re(c.key);l&&e.push({nodeId:c.key,kind:l.level,text:Gs(`${l.path} ${c.label??""}`.trim())})}}let r=ht(t,"model/facts/events");if(hn(r)){for(let s of Hs(r).sort())if(s.endsWith(".yaml"))try{let i=At(Ws(mn(ht(r,s),"utf-8")));if(!i.ok)continue;let a=i.value,c=[...a.links?.adr??[],...a.links?.tasks??[]].join(" ");e.push({nodeId:`task::${a.taskKey}`,kind:"task",text:Gs(`${a.taskKey} ${a.title??""} ${c}`.trim())})}catch{}}let n=ht(t,"model/facts/annotations");if(hn(n)){let s=new Map;for(let i of Zc(ht(t,"model/facts/identity")))try{let a=Ws(mn(i,"utf-8"));for(let c of a?.entities??[])c.status==="active"&&c.entityId&&c.currentKey&&s.set(c.entityId,c.currentKey)}catch{}for(let i of Hs(n).sort())if(i.endsWith(".md"))try{let a=mn(ht(n,i),"utf-8"),c=/^---\n[\s\S]*?entityId:\s*(e_[0-9a-f]{8})[\s\S]*?\n---\n?([\s\S]*)$/.exec(a);if(!c)continue;e.push({nodeId:s.get(c[1])??c[1],kind:"annotation",text:Gs(c[2].trim())})}catch{}}let o=ht(t,"adr");if(hn(o))for(let s of Hs(o).sort()){let i=/^(\d{4})-/.exec(s)?.[1];if(!(!i||!s.endsWith(".md")))try{let a=mn(ht(o,s),"utf-8").split(`
|
|
729
|
-
`).slice(0,6);e.push({nodeId:`adr::ADR-${i}`,kind:"adr",text:Gs(a.filter(c=>c.trim()).join(" "))})}catch{}}return e}async function
|
|
705
|
+
`,E=["",`## ${i} \u2014 ${r}`,x,"",d.body,""].join(`
|
|
706
|
+
`),$=I+E;y?y.content=$:p.push({path:h,content:$})}return p}var zx,hm=S(()=>{"use strict";F();zx=12});import{existsSync as Mc,readFileSync as Uc}from"node:fs";import{join as Bc}from"node:path";import{simpleGit as ym}from"simple-git";import{parse as Fc}from"yaml";function wm(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(Xx.source,"g")}function bm(t){let e=Bc(t,"project.yaml");if(Mc(e))try{let o=Fc(Uc(e,"utf-8"))?.youtrack,s=o&&typeof o=="object"?o.project_key:null;if(typeof s=="string"&&s.trim())return s.trim()}catch{}let r=Bc(t,"tracker","config.yaml");if(Mc(r))try{let o=Fc(Uc(r,"utf-8"))?.prefix;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return null}function $m(t){if(t.includes("=>")){let r=t.replace(/\{([^{}]*) => ([^{}]*)\}/g,(o,s,i)=>i).replace(/\/\//g,"/");if(!r.includes("=>"))return r;let n=r.split("=>");return(n[n.length-1]??r).trim()}return t}async function Jx(t,e,r){let o=await ym(t).raw(["log","--numstat","--format=@@@ %H %ct %P %x09%s","-n",String(r),e]),s=[],i=null;for(let a of o.split(`
|
|
707
|
+
`))if(a.startsWith("@@@ ")){let c=a.indexOf(" "),l=(c>=0?a.slice(4,c):a.slice(4)).trim().split(/\s+/),u=c>=0?a.slice(c+1):"",p=l[0]??"",d=Number(l[1]??0),m=l.slice(2),f=Kc.exec(u)??km.exec(u);i={sha:p,timeSec:d,subject:u,files:[],prNumber:f?Number(f[1]):null,isMerge:m.length>1},s.push(i)}else if(a.trim()&&i){let c=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(a);if(!c)continue;let l=c[1]==="-"?0:Number(c[1]),u=c[2]==="-"?0:Number(c[2]);i.files.push({path:$m(c[3]),churn:l+u})}return s}async function Zx(t,e){let n=await ym(t).raw(["diff","--numstat",`${e}^1`,e]).catch(()=>""),o=[];for(let s of n.split(`
|
|
708
|
+
`)){let i=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(s);if(!i)continue;let a=i[1]==="-"?0:Number(i[1]),c=i[2]==="-"?0:Number(i[2]);o.push({path:$m(i[3]),churn:a+c})}return o}function Qx(t){let{repo:e,issueKeyRe:r,commits:n,pathToCurrent:o,entityByKey:s,ignored:i}=t,a=new Map;for(let c of[...n].reverse()){let l=[...new Set(c.subject.match(r)??[])],u,p,d=l.slice(1);if(l.length>0)u=l[0],p=c.subject.replace(new RegExp(`^\\s*${u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[:\u2014-]\\s*`),"").replace(Kc,"").trim();else if(c.prNumber!==null){if((t.trackerProjectKey??"").toUpperCase()==="PR")continue;u=`PR-${c.prNumber}`,p=c.subject.replace(Kc,"").replace(km,"").replace(/^from\s+/,"").trim()||c.subject}else continue;if(!/^[A-Za-z0-9._-]+$/.test(u))continue;let m=new Map;for(let h of c.files){let w=o.get(h.path)??h.path;i(w)||m.set(w,(m.get(w)??0)+h.churn)}if(m.size===0)continue;let g=a.get(u)??{modelFormatVersion:2,taskKey:u,origin:"bootstrap",title:"",commits:[],files:[]};p&&(g.title=p),c.timeSec>0&&(g.date=new Date(c.timeSec*1e3).toISOString().slice(0,10)),g.commits.push(c.sha);for(let[h,w]of m){let y=fe("code",e,h),v=g.files.find(x=>x.key===y);if(v)v.churn=(v.churn??0)+w;else{let x=s.get(y);g.files.push({key:y,...x?{entityId:x}:{},churn:w})}}if(d.length>0){let h=new Set([...g.links?.tasks??[],...d]);h.delete(u),g.links={...g.links??{},tasks:[...h].sort()}}a.set(u,g)}return a}function gm(t,e){if(!t)return e;if(t.origin==="pipeline")return null;let r=[...new Set([...t.commits,...e.commits])],n=new Map(t.files.map(s=>[s.key,s]));for(let s of e.files)n.has(s.key)||n.set(s.key,s);let o=[...new Set([...t.links?.tasks??[],...e.links?.tasks??[]])].sort();return{...t,commits:r,files:[...n.values()],...o.length>0?{links:{...t.links??{},tasks:o}}:{}}}async function vm(t){let e=await Jx(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 Zx(t.repoDir,r.sha))}return Qx({repo:t.repo,issueKeyRe:t.issueKeyRe,commits:e,pathToCurrent:t.pathToCurrent,entityByKey:t.entityByKey,ignored:t.ignored,trackerProjectKey:t.trackerProjectKey??null})}function xm(t,e){let r=new Map;for(let s of e)for(let[i,a]of s){let c=r.get(i);r.set(i,c?gm(c,a)??c:a)}let n=[],o=0;for(let[s,i]of[...r.entries()].sort(([a],[c])=>a<c?-1:1)){let a=gm(Ds(t,s),i);if(!a){o++;continue}n.push({path:pr(s),content:qr(a)})}return{files:n,skippedPipeline:o}}function Ds(t,e){let r=Bc(t,pr(e));if(!Mc(r))return null;try{let n=At(Fc(Uc(r,"utf-8")));return n.ok?n.value:null}catch{return null}}var Xx,Kc,km,Gc=S(()=>{"use strict";F();Xx=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g,Kc=/\(#(\d+)\)\s*$/,km=/^Merge pull request #(\d+)\b/});import{simpleGit as eS}from"simple-git";async function Em(t,e,r){let o=await eS(t).raw(["log","--no-merges","--name-only","--format=@@@ %H %ct","-n",String(r),e]),s=[],i=null;for(let a of o.split(`
|
|
709
|
+
`))if(a.startsWith("@@@ ")){let[c,l]=a.slice(4).trim().split(/\s+/);i={sha:c??"",timeSec:Number(l??0),files:[]},s.push(i)}else a.trim()&&i&&i.files.push(a.trim());return s}function Ms(t){let e=new Map;for(let r of t.entities){if(r.status!=="active"||!r.aliases)continue;let n=re(r.currentKey);if(n?.level==="code")for(let o of r.aliases){let s=re(o.key);s?.level==="code"&&e.set(s.path,n.path)}}return e}function Rm(t){let{repo:e,headTimeSec:r,filesets:n,pathToCurrent:o,currentPaths:s,ignored:i,settings:a}=t,c=a.halfLifeDays*86400,l=new Map,u=new Map,p=new Map;for(let w of n){let y=new Set;for(let E of w.files){let $=o.get(E)??E;!s.has($)||i($)||y.add($)}if(y.size<2||y.size>a.commitFileCap)continue;let v=Math.max(0,r-w.timeSec),x=Math.pow(.5,v/c),I=[...y].sort();for(let E of I)l.set(E,(l.get(E)??0)+x);for(let E=0;E<I.length;E++)for(let $=E+1;$<I.length;$++){let T=`${I[E]}\0${I[$]}`;u.set(T,(u.get(T)??0)+x),p.set(T,(p.get(T)??0)+1)}}let d=[],m=a.jaccardMinPct/100;for(let[w,y]of u){if((p.get(w)??0)<a.supportMin)continue;let[v,x]=w.split("\0"),I=(l.get(v)??0)+(l.get(x)??0)-y,E=I>0?y/I:0;E<m||d.push({a:v,b:x,weight:Math.round(E*Sm)/Sm})}let f=new Map;for(let w of d)for(let y of[w.a,w.b])f.has(y)||f.set(y,[]),f.get(y).push(w);let g=new Map;for(let[,w]of f)w.sort((y,v)=>v.weight-y.weight||(y.a<v.a?-1:y.a>v.a?1:y.b<v.b?-1:1)).slice(0,a.topK).forEach(y=>g.set(y,(g.get(y)??0)+1));return[...g.entries()].filter(([,w])=>w===2).map(([w])=>w).map(w=>({kind:"correlates",from:fe("code",e,w.a),to:fe("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 pn,Sm,Us=S(()=>{"use strict";F();pn=["package-lock.json","pnpm-lock.yaml","yarn.lock"];Sm=1e4});import{createHash as tS}from"node:crypto";function nS(t,e,r,n){for(let o=0;;o++){let i=`e_${tS("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(i))return i}}function Im(t){let{repo:e,headCommit:r,headDate:n,prev:o,renameChains:s,prevBlobByPath:i,headBlobByPath:a}=t,c=[...t.currentKeys].sort(),l=new Set(c),u=o?.entities??[],p=new Set(u.map($=>$.entityId)),d=new Set,m=[],f=new Map,g=($,T)=>{d.add(T),f.set(T,$.entityId),m.push($)},h=[];for(let $ of u)l.has($.currentKey)&&!d.has($.currentKey)?g({...$,status:"active",lastSeen:r},$.currentKey):h.push($);let w=[],y=[];for(let $ of h){let T=re($.currentKey),N=T?s.get(T.path):void 0;if(T&&N){let G=fe(T.level,e,N.finalPath);if(l.has(G)&&!d.has(G)){w.push({entity:$,newKey:G,untilCommit:N.commit}),d.add(G);continue}}y.push($)}let v=[];if(i){let $=new Map;for(let N of c){if(d.has(N))continue;let G=re(N);if(G?.level!=="code")continue;let ee=a.get(G.path);ee&&$.set(ee,$.has(ee)?null:N)}let T=new Map;for(let N of y){let G=re(N.currentKey);if(G?.level!=="code")continue;let ee=i.get(G.path);ee&&T.set(ee,T.has(ee)?null:N)}for(let N of y){let G=re(N.currentKey),ee=G?.level==="code"?i.get(G.path):void 0,C=ee?$.get(ee):void 0;ee&&C&&T.get(ee)===N&&!d.has(C)?(w.push({entity:N,newKey:C,untilCommit:r}),d.add(C)):v.push(N)}}else v.push(...y);let x=new Map;for(let $ of w){let T=re($.entity.currentKey),N=re($.newKey);if(T?.level!=="code"||!N)continue;let G=T.path,ee=N.path;for(let C=G.lastIndexOf("/");C>0;C=G.lastIndexOf("/",C-1)){let k=G.slice(0,C),M=G.slice(C+1);if(!ee.endsWith(`/${M}`))continue;let P=ee.slice(0,ee.length-M.length-1);if(P===k)continue;let H=`${k}\0${P}`,Y=x.get(H);x.set(H,{count:(Y?.count??0)+1,commit:Y&&Y.commit>$.untilCommit?Y.commit:$.untilCommit})}}let I=[...x.entries()].filter(([,$])=>$.count>=rS).map(([$,T])=>{let[N,G]=$.split("\0");return{from:N,to:G,commit:T.commit}}).sort(($,T)=>T.from.length-$.from.length||($.from<T.from?-1:1)),E=[];for(let $ of v){let T=re($.currentKey),N=!1;if(T?.level==="component")for(let G of I){let ee=null;if(T.path===G.from?ee=G.to:T.path.startsWith(`${G.from}/`)&&(ee=G.to+T.path.slice(G.from.length)),ee===null)continue;let C=fe("component",e,ee);l.has(C)&&!d.has(C)&&(w.push({entity:$,newKey:C,untilCommit:G.commit}),d.add(C),N=!0);break}N||E.push($)}for(let $ of w.sort((T,N)=>T.newKey<N.newKey?-1:1))g({...$.entity,currentKey:$.newKey,aliases:[...$.entity.aliases??[],{key:$.entity.currentKey,until:$.untilCommit}],status:"active",lastSeen:r},$.newKey);for(let $ of E)m.push({...$,status:"orphaned"});for(let $ of c){if(d.has($))continue;let T=nS(e,$,r,p);p.add(T),g({entityId:T,currentKey:$,firstSeen:n,lastSeen:r,status:"active"},$)}return{table:{modelFormatVersion:2,repo:e,builtFromCommit:r,entities:m},byKey:f}}var rS,Tm=S(()=>{"use strict";F();rS=5});import{simpleGit as oS}from"simple-git";async function Cm(t,e,r){let n=oS(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
|
|
710
|
+
`).map(i=>i.trim()).filter(Boolean),s=[];for(let i of o){let c=(await n.raw(["diff","-M","-C","-z","--name-status","--diff-filter=R",`${i}^`,i]).catch(()=>"")).split("\0");for(let l=0;l+2<c.length;){if(!(c[l]??"").startsWith("R")){l+=1;continue}let p=c[l+1]??"",d=c[l+2]??"";p&&d&&s.push({fromPath:p,toPath:d,commit:i}),l+=3}}return s}function Am(t){let e=new Map,r=new Map;for(let n of t){let o=r.get(n.fromPath)??n.fromPath;r.delete(n.fromPath),r.set(n.toPath,o),e.set(o,{finalPath:n.toPath,commit:n.commit})}for(let[n,o]of e)o.finalPath===n&&e.delete(n);return e}var Pm=S(()=>{"use strict"});function Bs(t){return fe("container",t,sS)}function _m(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function jm(t,e,r,n){let o=[],s=u=>{let p=fe("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:_m(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,iS)}},i=(u,p)=>{let d=fe("component",t,u),m=n.get(d);return{key:d,level:"component",label:_m(u),...m?{entityId:m}:{},...p?{aggregate:!0}:{}}},a=(u,p,d)=>{let m=r.filesByDir.get(d)??[],f=r.childDirs.get(d)??[],g=[p,...m.map(s)],h=[...m.map(w=>({kind:"contains",from:p.key,to:fe("code",t,w.path)})),...f.map(w=>({kind:"contains",from:p.key,to:fe("component",t,w)}))];c(u,g,h)},c=(u,p,d)=>{let m={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},f=Ct(m);if(!f.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${f.errors.join("; ")}`);o.push({path:ea(t,u),content:ia(m)})},l={key:Bs(t),level:"container",label:t,...n.get(Bs(t))?{entityId:n.get(Bs(t))}:{}};a("",l,"");for(let u of r.components)r.collapsed.has(u)?c(u,[i(u,!0)],[]):a(u,i(u,!1),u);return o.sort((u,p)=>u.path<p.path?-1:u.path>p.path?1:0),{files:o,counts:r.counts}}function Nm(t,e){let r=[Bs(t)];for(let n of e.components)r.push(fe("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(fe("code",t,o.path));return r.sort()}var sS,iS,Om=S(()=>{"use strict";F();sS=".";iS=12});import{simpleGit as Dm}from"simple-git";function _r(t){let e=new Set,r=[],n=new Set;for(let o of t){let s=o.trim();if(s)if(s.endsWith("/"))e.add(s.slice(0,-1));else if(s.includes("*")){let i=s.replace(/[.*+?^${}()|[\]\\]/g,a=>a==="*"?"\0":`\\${a}`).replace(/\0/g,".*");r.push(new RegExp(`^${i}$`))}else n.add(s)}return o=>{let s=o.split("/"),i=s[s.length-1]??o;if(n.has(o))return!0;for(let a of s)if(e.has(a)||n.has(a))return!0;return r.some(a=>a.test(i))}}async function Um(t,e="HEAD"){let r=Dm(t),n=(await r.revparse([e])).trim(),[o,s]=(await r.raw(["show","-s","--format=%cs %ct",n])).trim().split(/\s+/);return{commit:n,commitDate:o??"",commitTimeSec:Number(s??0),files:await xo(t,n)}}async function xo(t,e){let n=await Dm(t).raw(["ls-tree","-r","-z",e]),o=[];for(let s of n.split("\0")){if(!s)continue;let i=s.indexOf(" ");if(i<0)continue;let[,a,c]=s.slice(0,i).split(/\s+/);a!=="blob"||!c||o.push({path:s.slice(i+1),blobHash:c})}return o.sort((s,i)=>s.path<i.path?-1:s.path>i.path?1:0),o}function Lm(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function Bm(t,e){let r=[...t].sort((f,g)=>f.path<g.path?-1:f.path>g.path?1:0),n=new Map,o=new Map;for(let f of r){let g=Lm(f.path);n.has(g)||n.set(g,[]),n.get(g).push(f);let h=g;for(;h!=="";){let w=Lm(h);o.has(w)||o.set(w,new Set),o.get(w).add(h),h=w}}let s=f=>[...o.get(f)??[]].sort(),i=Math.max(e,1)-1,a=new Set,c=new Set,l=[""];for(;l.length>0;){let f=l.shift(),g=(n.get(f)??[]).length+s(f).length;if(g<=i)i-=g,c.add(f),l.push(...s(f));else{if(f==="")return{components:[],collapsed:new Set,filesByDir:new Map,childDirs:new Map,counts:{component:0,code:0}};a.add(f)}}let u=[],p=new Map,d=new Map,m=0;for(let f of[...c].sort()){let g=n.get(f)??[];p.set(f,g),d.set(f,s(f)),m+=g.length,f!==""&&u.push(f)}for(let f of a)u.push(f);return u.sort(),{components:u,collapsed:a,filesByDir:p,childDirs:d,counts:{component:u.length,code:m}}}var Mm,So=S(()=>{"use strict";Mm=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as Fm,readFileSync as Km}from"node:fs";import{join as Gm}from"node:path";import{simpleGit as aS}from"simple-git";import{parse as Hm}from"yaml";function fn(t){let e={ignore:Mm,containerNodeCap:cS,cochange:{...Qe},issueKeyPattern:null,enabled:!1},r=Gm(t,"regimen.yaml");if(!Fm(r))return e;let n;try{n=Hm(Km(r,"utf-8"))}catch{return e}let o=n?.context,s=o&&typeof o=="object"?o.model:void 0;if(!s||typeof s!="object")return e;let i=s,a=Array.isArray(i.ignore)?i.ignore.filter(m=>typeof m=="string"&&m.trim().length>0):e.ignore,c=(m,f)=>typeof m=="number"&&Number.isInteger(m)&&m>0?m:f,l=c(i.container_node_cap,e.containerNodeCap),u=i.cochange&&typeof i.cochange=="object"?i.cochange:{},p={windowCommits:c(u.window_commits,e.cochange.windowCommits),commitFileCap:c(u.commit_file_cap,e.cochange.commitFileCap),supportMin:c(u.support_min,e.cochange.supportMin),jaccardMinPct:typeof u.jaccard_min_pct=="number"&&Number.isInteger(u.jaccard_min_pct)&&u.jaccard_min_pct>=0&&u.jaccard_min_pct<=100?u.jaccard_min_pct:e.cochange.jaccardMinPct,halfLifeDays:c(u.half_life_days,e.cochange.halfLifeDays),topK:c(u.top_k,e.cochange.topK)},d=typeof i.issue_key_pattern=="string"&&i.issue_key_pattern.trim().length>0?i.issue_key_pattern.trim():null;return{ignore:a,containerNodeCap:l,cochange:p,issueKeyPattern:d,enabled:i.enabled===!0}}function Hc(t,e){let r=Gm(t,Xn(e));if(!Fm(r))return null;let n=Hm(Km(r,"utf-8")),o=Zn(n);if(!o.ok)throw new Error(`model: ${Xn(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function Wc(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,s=await Um(r,t.ref??"HEAD"),i=_r(o.ignore),a=s.files.filter(y=>!i(y.path)),c=Bm(a,o.containerNodeCap),l=Hc(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==s.commit?await aS(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=Am(await Cm(r,l.builtFromCommit,s.commit)),p=new Map((await xo(r,l.builtFromCommit)).map(x=>[x.path,x.blobHash]))):l?.builtFromCommit===s.commit&&(p=new Map(a.map(y=>[y.path,y.blobHash])));let d=new Map(a.map(y=>[y.path,y.blobHash])),m=Im({repo:e,headCommit:s.commit,headDate:s.commitDate,prev:l,currentKeys:Nm(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),f=jm(e,s.commit,c,m.byKey),g=_r([...o.ignore,...pn]),h=Rm({repo:e,headTimeSec:s.commitTimeSec,filesets:await Em(r,s.commit,o.cochange.windowCommits),pathToCurrent:Ms(m.table),currentPaths:new Set(a.map(y=>y.path)),ignored:g,settings:o.cochange}),w=[{path:Xn(e),content:aa(m.table)},...f.files.map(y=>({path:y.path,content:y.content})),{path:Zi(e),content:fr({modelFormatVersion:2,repo:e,builtFromCommit:s.commit,edges:h})}];return{repo:e,headCommit:s.commit,files:w,emittedShardPaths:new Set(f.files.map(y=>y.path)),counts:{...f.counts,correlates:h.length},identityTable:m.table,entityByKey:m.byKey}}var cS,qc=S(()=>{"use strict";F();Us();Tm();Pm();Om();So();cS=1500});import{existsSync as qm,readFileSync as Ym,readdirSync as lS}from"node:fs";import{join as Yc}from"node:path";import{parse as Vm}from"yaml";function uS(t,e){if(!t||!e)return null;let r=Date.parse(`${t}T00:00:00Z`),n=Date.parse(`${e}T00:00:00Z`);return!Number.isFinite(r)||!Number.isFinite(n)?null:Math.abs(r-n)/864e5}function zm(t,e,r){let n=new Set(t.files.map(d=>d.key)),o=new Set(e.files.map(d=>d.key)),s=0;for(let d of n)o.has(d)&&s++;if(s<ra)return null;let i=s/Math.min(n.size,o.size),a=uS(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(i*c*Wm)/Wm;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[ge(t.taskKey),ge(e.taskKey)]:[ge(e.taskKey),ge(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function Xm(t,e){let r=new Map(t.map(i=>[i.taskKey,i])),n=new Map;for(let i of t)for(let a of i.files)n.has(a.key)||n.set(a.key,[]),n.get(a.key).push(i.taskKey);let o=new Set,s=[];for(let i of n.values())if(!(i.length<2))for(let a=0;a<i.length;a++)for(let c=a+1;c<i.length;c++){let[l,u]=i[a]<i[c]?[i[a],i[c]]:[i[c],i[a]],p=`${l}\0${u}`;if(o.has(p))continue;o.add(p);let d=zm(r.get(l),r.get(u),e);d&&s.push(d)}return s.sort((i,a)=>i.from<a.from?-1:i.from>a.from?1:i.to<a.to?-1:1)}function Jm(t,e,r,n){let o=ge(r),s=t.filter(a=>a.from!==o&&a.to!==o),i=e.find(a=>a.taskKey===r);if(i){let a=new Set(i.files.map(c=>c.key));for(let c of e){if(c.taskKey===r||!c.files.some(u=>a.has(u.key)))continue;let l=zm(i,c,n);l&&s.push(l)}}return s.sort((a,c)=>a.from<c.from?-1:a.from>c.from?1:a.to<c.to?-1:1)}function Fs(t){let e=Yc(t,"model/facts/events");if(!qm(e))return[];let r=[];for(let n of lS(e).sort())if(n.endsWith(".yaml"))try{let o=At(Vm(Ym(Yc(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function Zm(t){let e=Yc(t,dr);if(!qm(e))return[];try{let r=Jn(Vm(Ym(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function Ks(t){return fr({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var Wm,Vc=S(()=>{"use strict";F();Wm=1e4});var Eo={};Fe(Eo,{collectSearchRows:()=>eh,readContextIndexHub:()=>dS,rebuildSearchIndex:()=>th,searchIndexPath:()=>qs,searchModelIndex:()=>pS,toFtsQuery:()=>rh});import{existsSync as hn,readFileSync as mn,readdirSync as Hs}from"node:fs";import{join as ht}from"node:path";import{parse as Ws}from"yaml";function qs(t){return ht(t,".git","codepipe-model-index.sqlite")}function dS(t){let e=ht(t,"regimen.yaml");if(!hn(e))return"off";try{let n=Ws(mn(e,"utf-8"))?.context,o=n&&typeof n=="object"?n.index:null;return(o&&typeof o=="object"?o.hub:null)==="metadata"?"metadata":"off"}catch{return"off"}}async function Qm(){try{let{createRequire:t}=await import("node:module");return t(import.meta.url)("node:sqlite")}catch{return null}}function Gs(t){return t.length>zo?t.slice(0,zo):t}function zc(t){if(!hn(t))return[];let e=[];for(let r of Hs(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=ht(t,r.name);r.isDirectory()?e.push(...zc(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function eh(t){let e=[];for(let s of zc(ht(t,"model/derived/structure"))){let i;try{i=Ws(mn(s,"utf-8"))}catch{continue}let a=Ct(i);if(a.ok)for(let c of a.value.nodes){let l=re(c.key);l&&e.push({nodeId:c.key,kind:l.level,text:Gs(`${l.path} ${c.label??""}`.trim())})}}let r=ht(t,"model/facts/events");if(hn(r)){for(let s of Hs(r).sort())if(s.endsWith(".yaml"))try{let i=At(Ws(mn(ht(r,s),"utf-8")));if(!i.ok)continue;let a=i.value,c=[...a.links?.adr??[],...a.links?.tasks??[]].join(" ");e.push({nodeId:`task::${a.taskKey}`,kind:"task",text:Gs(`${a.taskKey} ${a.title??""} ${c}`.trim())})}catch{}}let n=ht(t,"model/facts/annotations");if(hn(n)){let s=new Map;for(let i of zc(ht(t,"model/facts/identity")))try{let a=Ws(mn(i,"utf-8"));for(let c of a?.entities??[])c.status==="active"&&c.entityId&&c.currentKey&&s.set(c.entityId,c.currentKey)}catch{}for(let i of Hs(n).sort())if(i.endsWith(".md"))try{let a=mn(ht(n,i),"utf-8"),c=/^---\n[\s\S]*?entityId:\s*(e_[0-9a-f]{8})[\s\S]*?\n---\n?([\s\S]*)$/.exec(a);if(!c)continue;e.push({nodeId:s.get(c[1])??c[1],kind:"annotation",text:Gs(c[2].trim())})}catch{}}let o=ht(t,"adr");if(hn(o))for(let s of Hs(o).sort()){let i=/^(\d{4})-/.exec(s)?.[1];if(!(!i||!s.endsWith(".md")))try{let a=mn(ht(o,s),"utf-8").split(`
|
|
711
|
+
`).slice(0,6);e.push({nodeId:`adr::ADR-${i}`,kind:"adr",text:Gs(a.filter(c=>c.trim()).join(" "))})}catch{}}return e}async function th(t){let e=eh(t),r=await Qm();if(!r)return{rows:e,indexed:!1};let n=new r.DatabaseSync(qs(t));try{n.exec("DROP TABLE IF EXISTS model_fts"),n.exec("CREATE VIRTUAL TABLE model_fts USING fts5(node_id UNINDEXED, kind UNINDEXED, text)");let o=n.prepare("INSERT INTO model_fts (node_id, kind, text) VALUES (?, ?, ?)");for(let s of e)o.run(s.nodeId,s.kind,s.text)}finally{n.close()}return{rows:e,indexed:!0}}function rh(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 pS(t,e,r){let n=await Qm();if(!n)throw new Error("model search needs Node with built-in sqlite (>= 22.13) on this CLI");hn(qs(t))||await th(t);let o=rh(e);if(!o)return[];let s=Math.min(Math.max(r??20,1),oa),i=new n.DatabaseSync(qs(t));try{return i.prepare(`SELECT node_id AS nodeId, kind, snippet(model_fts, 2, '[', ']', '\u2026', 10) AS snippet,
|
|
730
712
|
bm25(model_fts) AS rank
|
|
731
|
-
FROM model_fts WHERE model_fts MATCH ? ORDER BY bm25(model_fts), node_id LIMIT ?`).all(o,s).map(c=>({nodeId:c.nodeId,kind:c.kind,score:-c.rank,snippet:c.snippet}))}finally{i.close()}}var Ro=
|
|
732
|
-
`)){let i=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(s);if(!i)continue;let a=i[1]==="-"?0:Number(i[1]),c=i[2]==="-"?0:Number(i[2]);o.push({path:i[3],churn:a+c})}return o}function
|
|
733
|
-
`)){let i=s.trim();i&&e.add(i)}}catch{}for(let r of[...e].sort())await
|
|
734
|
-
`)}function XS(t,e,r){let n=new Map,o=ke(t,`tasks/${e}/comments.jsonl`);if(ol(o))for(let s of YS(o,"utf-8").split(`
|
|
735
|
-
`)){let i=s.trim();if(i)try{let a=JSON.parse(i);a&&typeof a.id=="string"&&n.set(a.id,a)}catch{}}for(let s of r){if(n.has(s.id))continue;let i={id:s.id,author:s.author,origin:"youtrack",body:s.body,createdAt:new Date(s.createdAt).toISOString()},a=yr(s.body);a&&(i.parsedCommand=a),n.set(s.id,i)}return[...n.values()].sort((s,i)=>s.createdAt.localeCompare(i.createdAt))}function JS(t){return t.map(e=>JSON.stringify(e)).join(`
|
|
736
|
-
`)+(t.length>0?`
|
|
737
|
-
`:"")}function ZS(t,e,r){let n=[],o=ke(t,`tasks/${e}/attachments`);if(ol(o))for(let s of VS(o))n.push(s);for(let s of r)n.includes(s.name)||n.push(s.name);return n}var zs=v(()=>{"use strict";F();nt()});import{existsSync as QS,readFileSync as eE}from"node:fs";import{randomBytes as tE}from"node:crypto";function _h(t,e){let r=ke(t,`tasks/${e}/comments.jsonl`);if(!QS(r))return[];let n=[];for(let o of eE(r,"utf-8").split(`
|
|
738
|
-
`)){let s=o.trim();if(s)try{let i=JSON.parse(s);i&&typeof i.id=="string"&&typeof i.body=="string"&&n.push(i)}catch{}}return n}var To,sl=v(()=>{"use strict";F();nt();zs();Ps();To=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await go(this.contextDir);let r=e.columns??[];return tm(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>ko(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=yo(this.contextDir,e);return r?ko(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return _h(this.contextDir,e).map(n=>({id:n.id,issueId:e,author:n.author,body:n.body,createdAt:n.createdAt}))}async downloadAttachment(e){throw new Error(`internal tracker: no remote attachments (${e})`)}async updateStatus(e,r){await this.mutateRecord(e,n=>({...n,status:r}))}async addComment(e,r,n){if(await go(this.contextDir),!yo(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let s={id:`int-${Date.now().toString(36)}-${tE(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},i=yr(r);i&&(s.parsedCommand=i);let c=[..._h(this.contextDir,e),s].map(l=>JSON.stringify(l)).join(`
|
|
739
|
-
`)+`
|
|
740
|
-
`;return await ve(this.contextDir,[{path:`tasks/${e}/comments.jsonl`,content:c}],`tracker(${e}): comment`),{id:s.id}}async createIssue(e){let r=new Date().toISOString(),n=await rm(this.contextDir,this.config.prefix,o=>this.renderNewIssueFiles(o,e,r),o=>`tracker(${o}): create issue`);return{id:n,key:n}}async editIssue(e,r){await this.mutateRecord(e,n=>({...n,...r.title!==void 0?{title:r.title}:{}}),r.body)}async applyLink(e,r,n){let o=r==="subtask_of"?"subtask":"depends_on";await this.mutateRecord(e,s=>{let i=s.links.filter(a=>!(a.type===o&&a.targetKey===n));return i.push({type:o,targetKey:n}),{...s,links:i}})}async fetchStateFields(e){return[{name:"Status",values:rs.statusColumns}]}async mutateRecord(e,r,n){let o=yo(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let s={...r(o),updated:new Date().toISOString()},i=ko(this.contextDir,s,{withDescription:!0});n!==void 0&&(n.trim().length>0?i.description=n:delete i.description);let a=[{path:Xr(e),content:Pc(s)},...Ys(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])];await ve(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:no,status:r.targetStatus,links:[],created:n,updated:n},s=ko(this.contextDir,o);return r.body.trim().length>0&&(s.description=r.body),[{path:Xr(e),content:Pc(o)},...Ys(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])]}}});import{existsSync as jh,readFileSync as Nh}from"node:fs";import{join as Oh}from"node:path";import{parseDocument as Lh}from"yaml";function il(t){if(!t)return"youtrack";try{let e=Oh(t,"project.yaml");return jh(e)&&Lh(Nh(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function St(t){let e=il(t.contextDir);if(e==="internal"){let n=t.contextDir;if(!n)return{ok:!1,kind:e,error:"internal tracker: no Context Repo clone on this CLI"};let o=Qf(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let s=rE(n);return s?{ok:!0,kind:e,provider:new To(n,s,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=Ep();return r?{ok:!0,kind:e,provider:new Io(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function rE(t){try{let e=Oh(t,"project.yaml");if(!jh(e))return null;let r=Lh(Nh(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var Xs=v(()=>{"use strict";$r();nl();sl();Ps();nl();sl()});async function gn(t,e){let n=(Js.get(t)??Promise.resolve()).catch(()=>{}).then(e);Js.set(t,n);try{return await n}finally{Js.get(t)===n&&Js.delete(t)}}async function Dh(t){let{action:e,repo:r}=t,n="repoName"in e?e.repoName:"-",o="taskId"in e?e.taskId:"draftId"in e?e.draftId:e.projectId;xr(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return V("no repo spec");let s=e.taskId.split(":",2)[0]??"?";return gn(`${s}/${r.name}`,async()=>{let i=await Ot(s,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(s,r.name,t.baseDir),{commit:c,pushed:l}=await gf(i,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force,push:e.push});if(t.contextDir){let u=e.taskId.split(":")[1]??"";u&&await el({contextDir:t.contextDir,repoDir:a,repoName:r.name,taskKey:u,commitSha:c}).catch(p=>{xr(`[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 V("no repo spec");let s=e.taskId.split(":",2)[0]??"?";return gn(`${s}/${r.name}`,async()=>{let i=await Ot(s,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(s,r.name,t.baseDir);return await yf(i,a,{branchName:e.branchName,force:e.force}),ce({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"early_branch":{if(!r)return V("no repo spec");let s=e.taskId.split(":",2)[0]??"?";return gn(`${s}/${r.name}`,async()=>{let i=await Ot(s,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(s,r.name,t.baseDir),{commit:c,pushed:l}=await kf(i,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return ce({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return V("no repo spec");let s=pt(r),i=await s.createPullRequest(r,e);if(t.contextDir){let a=e.taskId.split(":")[1]??"",c=e.taskId.split(":",2)[0]??"?";a&&await tl({contextDir:t.contextDir,repoDir:Ie(c,r.name,t.baseDir),branchName:e.branchName,baseBranch:e.baseBranch,fallbackTaskKey:a,prUrl:i.url}).catch(l=>{xr(`[model] pr link for ${a} failed: ${l instanceof Error?l.message:String(l)}`)})}return ce({url:i.url,number:i.number,host:s.name})}case"merge_pr":{if(!r)return V("no repo spec");let s=pt(r),i=await s.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ce({prNumber:e.prNumber,host:s.name,...i.mergedSha?{mergedSha:i.mergedSha}:{}})}case"close_pr":{if(!r)return V("no repo spec");let s=pt(r);return await s.closePR(r,e.prNumber,e.comment),ce({prNumber:e.prNumber,host:s.name})}case"rewrite_cluster_branch":{if(!r)return V("no repo spec");let s=e.taskId.split(":",2)[0]??"?";return gn(`${s}/${r.name}`,async()=>{let i=await Ot(s,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(s,r.name,t.baseDir),{commit:c,dropped:l}=await bf(i,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:r.defaultBranch});return ce({branch:e.branchName,commit:c,dropped:l,pushed:l>0})})}case"merge_branch":{if(!r)return V("no repo spec");let s=e.taskId.split(":",2)[0]??"?";return gn(`${s}/${r.name}`,async()=>{let i=await Ot(s,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(s,r.name,t.baseDir),{mergedSha:c}=await $f(i,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ce({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return V("no repo spec");let s=t.cloneUrlOverride??fo(r),a=(await vf(s)).filter(u=>xf(u,e.issueKey)),c=pt(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 V("no repo spec");let s=pt(r);return await s.addPRComment(r,e.prNumber,e.body),ce({prNumber:e.prNumber,host:s.name})}case"tracker_status":{let s=St({contextDir:t.contextDir});return s.ok?t.trackerIssueId?(await s.provider.updateStatus(t.trackerIssueId,e.newStatus),ce({issueId:t.trackerIssueId,newStatus:e.newStatus})):V("no tracker_issue_id provided"):V(s.error)}case"tracker_comment":{let s=St({contextDir:t.contextDir});if(!s.ok)return V(s.error);if(!t.trackerIssueId)return V("no tracker_issue_id provided");let i=await s.provider.addComment(t.trackerIssueId,e.body,e.author);return ce({issueId:t.trackerIssueId,commentId:i.id})}case"create_tracker_issue":{let s=St({contextDir:t.contextDir});if(!s.ok)return V(s.error);if(!e.projectKey)return V("no projectKey in create_tracker_issue action");let{id:i,key:a}=await s.provider.createIssue({projectKey:e.projectKey,title:e.title,body:e.body,targetStatus:e.targetStatus});return ce({issueKey:a,issueId:i})}case"apply_tracker_links":{let s=St({contextDir:t.contextDir});if(!s.ok)return V(s.error);let i=0;for(let a of e.links)try{await s.provider.applyLink(a.sourceIssueKey,a.rel,a.targetIssueKey),i++}catch(c){return V(`${c instanceof Error?c.message:String(c)} (applied ${i}/${e.links.length})`)}return ce({applied:i})}case"set_project_setting":{if(!t.contextDir)return V("no context repo clone on this CLI");let s=await Pm(t.contextDir,e.edits);return ce({files:s.files})}case"set_prompt_override":{if(!t.contextDir)return V("no context repo clone on this CLI");if(!Pa(e.role))return V(`unknown prompt operation: ${e.role}`);let s=_a(e.role);return await ve(t.contextDir,[e.content===null?{path:s,content:"",deleted:!0}:{path:s,content:e.content}],e.commitMessage),t.requestConfigReport?.(),ce({path:s,reset:e.content===null})}case"tracker_edit":{let s=St({contextDir:t.contextDir});if(!s.ok)return V(s.error);if(!t.contextDir)return V("no context repo clone on this CLI");await s.provider.editIssue(e.issueKey,{...e.title!==void 0?{title:e.title}:{},...e.body!==void 0?{body:e.body}:{}});let i=await s.provider.getIssue(e.issueKey);return i&&await Vs(t.contextDir,e.projectId,[{issue:i,comments:[],attachments:[]}]),ce({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return V("no context repo clone on this CLI");let s=await Lm(t.contextDir,e);return ce({files:s.files})}case"set_repo_default_branch":{if(!t.contextDir)return V("no context repo clone on this CLI");let s=await Nm(t.contextDir,e);return ce({repoName:s.repoName,defaultBranch:s.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ce({reported:!0})):V("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return V("no context repo clone on this CLI");let s=await t.refreshContextStatus();return ce({outdated:s.outdated,templateVersion:s.templateVersion})}case"run_action":{if(!t.contextDir)return V("no project workspace on this CLI");if(!r)return V("no repo spec");if(!t.onRunActivity)return V("no run-activity stream on this CLI");let s=t.onRunActivity,{defs:i,errors:a}=Ss(t.contextDir),c=i.find(m=>m.id===e.actionId);if(!c){let m=a.find(f=>f.file===`actions/${e.actionId}.yml`);return V(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=wa(c,e.input);if(!l.ok)return V(l.error);let u=Nf(t.contextDir),p=q(e.projectId),d={};return p?.github?.token&&(d.GH_TOKEN=p.github.token),p?.gitlab?.token&&(d.GITLAB_TOKEN=p.gitlab.token),p?.bitbucket&&(d.BITBUCKET_EMAIL=p.bitbucket.email,d.BITBUCKET_API_TOKEN=p.bitbucket.apiToken),p?.youtrack&&(d.YOUTRACK_URL=p.youtrack.url,d.YOUTRACK_TOKEN=p.youtrack.token),gn(`${e.projectId}/${r.name}`,async()=>{await Ot(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=Ie(e.projectId,r.name,t.baseDir),f=await Em({cwd:m,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:g=>s(e.runId,g)});return ce({runId:e.runId,status:f.status,exitCode:f.exitCode,...f.failedStep?{failedStep:f.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return V("no context repo clone on this CLI");let s=Cm(t.contextDir,e.path);return ce({path:e.path,...s})}case"search_model":{if(!t.contextDir)return V("no context repo clone on this CLI");let{searchModelIndex:s}=await Promise.resolve().then(()=>(Ro(),Eo)),i=await s(t.contextDir,e.q,e.limit);return ce({hits:i})}case"model_drift":return V("model_drift requires a local workspace (handled by the daemon)");case"model_bootstrap":return V("model_bootstrap requires a local workspace (handled by the daemon)");case"local_apply":return V("local_apply requires a local workspace (handled by the daemon)");default:return V(`unsupported action type: ${e.type}`)}}catch(s){return V(s instanceof Error?s.message:String(s))}}function ce(t){return{status:"done",result:t}}function V(t){return{status:"failed",error:t}}var Js,Mh=v(()=>{"use strict";F();kc();Rm();nt();Am();de();_m();Om();Uc();Yt();ws();Rr();rl();Xs();zs();Js=new Map});import{existsSync as nE,mkdtempSync as oE,rmSync as sE}from"node:fs";import{tmpdir as iE}from"node:os";import{join as al}from"node:path";import{simpleGit as Uh}from"simple-git";async function Bh(t,e,r){let n=[];for(let a of e){let c=t.repos.find(u=>u.name===a.repoName);if(!c)return{ok:!1,error:`repo "${a.repoName}" not in project.yaml \u2014 run /sync`};let l=al(t.root,c.mountAs);if(!nE(al(l,".git")))return{ok:!1,error:`${c.mountAs}/ not cloned \u2014 run /sync first`};n.push({payload:a,dir:l,mountAs:c.mountAs,defaultBranch:c.defaultBranch})}let o=[];for(let a of n){let c=Uh(a.dir),l=a.payload;try{await c.fetch()}catch(m){return{ok:!1,error:`fetch failed in ${a.mountAs}: ${Co(m)}`}}let u=`origin/${l.baseRef}`;await uE(c,u)||(u=`origin/${a.defaultBranch}`);let p;try{p=(await c.revparse([u])).trim()}catch(m){return{ok:!1,error:`base ${u} unavailable in ${a.mountAs}: ${Co(m)}`}}let d;try{d=await po(c,l.deliverySha,()=>Er(c,{contextRepoCloneUrl:l.contextRepoCloneUrl,deliveryRef:l.deliveryRef,deliverySha:l.deliverySha,baseSha:l.baseSha,commitMessage:l.commitMessage}))}catch(m){return{ok:!1,error:`fetch delivery failed in ${a.mountAs}: ${Co(m)}`}}o.push({repoName:l.repoName,mountAs:a.mountAs,git:c,branch:l.branchName,startPoint:p,deliveryCommit:d})}let s=[],i=[];for(let a of o){let c=await dE(a.git,`refs/heads/${a.branch}`);try{let u=(await a.git.revparse([`${a.deliveryCommit}^`])).trim()===a.startPoint?a.deliveryCommit:await cE(a);await a.git.raw(["branch","-f",a.branch,u]),s.push({git:a.git,mountAs:a.mountAs,branch:a.branch,priorSha:c}),i.push({repoName:a.repoName,branch:a.branch,commit:u}),r.info(`[local-apply] ${a.mountAs}: branch ${a.branch} \u2192 ${u.slice(0,10)} (no checkout)`)}catch(l){return await lE(s,r),{ok:!1,error:`apply failed in ${a.mountAs}: ${Co(l)} (rolled back all repos)`}}}return{ok:!0,repos:i}}async function cE(t){let e=oE(al(iE(),"codepipe-local-apply-"));try{await t.git.raw(["worktree","add","--detach",e,t.startPoint]);let r=Uh(e);try{await r.raw([...aE,"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(()=>{}),sE(e,{recursive:!0,force:!0}),await t.git.raw(["worktree","prune"]).catch(()=>{})}}async function lE(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 uE(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function dE(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 aE,Fh=v(()=>{"use strict";Rr();aE=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{homedir as pE}from"node:os";import{existsSync as fE,mkdirSync as mE,readFileSync as hE,writeFileSync as gE}from"node:fs";import{dirname as yE,join as kE}from"node:path";function cl(){return X("FARM_PINS")??kE(pE(),".codepipe","farm-pins.json")}function Kh(){let t=cl();if(!fE(t))return{};try{return JSON.parse(hE(t,"utf-8"))}catch{return{}}}function wE(t){let e=cl();mE(yE(e),{recursive:!0}),gE(e,JSON.stringify(t,null,2)+`
|
|
741
|
-
`,{mode:384})}function bE(t){return Kh()[t]}function Zs(t,e){let r=Kh();r[t]=e,wE(r)}function Qs(t,e){let r=De(e),n=bE(t);if(n&&n!==r)throw new Error(`farm ${t} key fingerprint changed (pinned ${n}, now ${r}) \u2014 refusing to seal. If the farm was re-registered intentionally, remove its entry from ${cl()}.`);return r}var ll=v(()=>{"use strict";Le();ot()});import{existsSync as Gh,readFileSync as Hh}from"node:fs";import{join as Wh}from"node:path";async function qh(t,e,r,n){let o=s=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:s});try{if(e.projectId!==t.projectId)return o(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let s=De(e.farmPublicKey);if(s!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Qs(e.farmId,e.farmPublicKey);let i=q(t.projectId);if(!i)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await ne(t.hubUrl,t.cliToken,t.projectId),c;if(r){let d=Wh(r,"project.yaml"),m=Wh(r,"regimen.yaml");Gh(d)&&Gh(m)?c={projectYaml:Hh(d,"utf-8"),regimenYaml:Hh(m,"utf-8")}:n.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...i.github?{github:i.github}:{},...i.bitbucket?{bitbucket:i.bitbucket}:{},...i.gitlab?{gitlab:i.gitlab}:{},...i.youtrack?{youtrack:i.youtrack}:{},...i.claude?{claude:i.claude}:{},...i.contextWrite?{contextWrite:i.contextWrite}:{},...i.contextSsh?{contextSsh:i.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},u=Dt(e.farmPublicKey,JSON.stringify(l));Zs(e.farmId,s),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${s}) \u2014 handing off`);let p=await ys(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:u});return p.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...p.daemonStatus?{daemonStatus:p.daemonStatus}:{}}:o(p.error??"farm provisioning failed")}catch(s){return o(s instanceof Error?s.message:String(s))}}var Yh=v(()=>{"use strict";ot();ll();Te();de()});import{homedir as $E}from"node:os";import{existsSync as vE,mkdirSync as xE,readFileSync as SE,writeFileSync as EE}from"node:fs";import{dirname as RE,join as IE}from"node:path";function ul(){return X("RUNNER_PINS")??IE($E(),".codepipe","runner-pins.json")}function Vh(){let t=ul();if(!vE(t))return{};try{return JSON.parse(SE(t,"utf-8"))}catch{return{}}}function TE(t){let e=ul();xE(RE(e),{recursive:!0}),EE(e,JSON.stringify(t,null,2)+`
|
|
742
|
-
`,{mode:384})}function CE(t){return Vh()[t]}function dl(t,e){let r=Vh();r[t]=e,TE(r)}function zh(t,e){let r=De(e),n=CE(t);if(n&&n!==r)throw new Error(`runner host ${t} key fingerprint changed (pinned ${n}, now ${r}) \u2014 refusing to seal. If the runner host was re-registered intentionally, remove its entry from ${ul()}.`);return r}var Xh=v(()=>{"use strict";Le();ot()});async function Jh(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:Zh(t)});if(!o.ok)throw new Error(`github ${n} for ${e}/${r}: HTTP ${o.status}`);let s=await o.json();if(!s.token)throw new Error(`github ${n} for ${e}/${r}: no token in response`);return s.token}async function eg(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(De(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");zh(e.runnerId,e.runnerPublicKey);let s=q(t.projectId)?.github?.token;if(!s)throw new Error("no GitHub token stored for this project on this CLI");let a=((await r.fetchProject(t.hubUrl,t.cliToken,t.projectId)).repos??[]).find(c=>c.host==="github"&&c.owner===e.owner&&c.repoName===e.repo);if(!a)throw new Error(`${e.owner}/${e.repo} is not a GitHub repository of this project`);return{githubToken:s,repo:a}}async function tg(t,e,r,n=Qh){let o=s=>({type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:s});try{let{githubToken:s,repo:i}=await eg(t,e,n);if(!await n.api.repoHasAdmin(s,i.owner,i.repoName))return o(`the GitHub token lacks admin access on ${i.owner}/${i.repoName} \u2014 replace it (project page \u2192 Tokens \u2192 Replace) with a token that has admin rights on this repository`);let a={projectId:t.projectId,runners:[{owner:i.owner,repo:i.repoName,regToken:await n.api.mintRegistrationToken(s,i.owner,i.repoName)}],labels:[Ma(e.runnerId)]},c=Dt(e.runnerPublicKey,JSON.stringify(a));dl(e.runnerId,e.fingerprint),r.info(`[ghr] registration token for ${i.owner}/${i.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let l=await n.provisionOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:c});return{type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:l.ok,...l.runners?{runners:l.runners}:{},...l.error?{error:l.error}:{}}}catch(s){return o(s instanceof Error?s.message:String(s))}}async function rg(t,e,r,n=Qh){let o=s=>({type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:s});try{let{githubToken:s,repo:i}=await eg(t,e,n),a={owner:i.owner,repo:i.repoName};try{a.removeToken=await n.api.mintRemoveToken(s,i.owner,i.repoName)}catch(p){r.warn(`[ghr] remove-token for ${i.owner}/${i.repoName} failed (${p instanceof Error?p.message:p}) \u2014 the runner host will force-remove`)}let c={projectId:t.projectId,runners:[a]},l=Dt(e.runnerPublicKey,JSON.stringify(c));dl(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle for ${i.owner}/${i.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let u=await n.teardownOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:l,owner:i.owner,repo:i.repoName});return{type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:u.ok,...u.error?{error:u.error}:{}}}catch(s){return o(s instanceof Error?s.message:String(s))}}var Zh,AE,Qh,ng=v(()=>{"use strict";F();ot();Xh();Te();de();Zh=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});AE={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Zh(t)});if(!n.ok)throw new Error(`github GET /repos/${e}/${r}: HTTP ${n.status}`);return(await n.json()).permissions?.admin===!0},mintRegistrationToken:(t,e,r)=>Jh(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Jh(t,e,r,"remove-token")},Qh={api:AE,fetchProject:ne,provisionOnRunner:ef,teardownOnRunner:tf}});function PE(t){return He.test(t)?Pt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${He}`}function sg(t,e,r,n){let o=PE(e);if(o)return{ok:!1,detail:o};let s;try{let i=JSON.parse(un(n,r).toString("utf-8"));if(typeof i.value!="string"||i.value.length===0)return{ok:!1,detail:"payload has no value"};s=i.value}catch(i){return{ok:!1,detail:`cannot open the sealed secret (${i instanceof Error?i.message:String(i)}) \u2014 wrong channel key?`}}if(s.length>og)return{ok:!1,detail:`secret value too large (max ${og} chars)`};try{return Zd(t,e,s),{ok:!0}}catch(i){return{ok:!1,detail:i instanceof Error?i.message:String(i)}}}function ig(t,e){try{return Qd(t,e)?{ok:!0}:{ok:!0,detail:"no such secret (already absent)"}}catch(r){return{ok:!1,detail:r instanceof Error?r.message:String(r)}}}var og,ag=v(()=>{"use strict";F();ot();de();og=16*1024});function _E(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var ei,cg=v(()=>{"use strict";Yt();ei=class{constructor(e,r,n){this.intervalMs=e;this.send=r;this.log=n}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let n=[];for(let i of r.prs){let a=pt(i.repoSpec);try{let c=await a.getPullRequest(i.repoSpec,i.number);n.push({number:i.number,url:i.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof br){this.log.warn(`[track] task=${e} pr=${i.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${i.url} fetch failed: ${c instanceof Error?c.message:String(c)}`);return}}let o=n.map(i=>`${i.number}:${i.state}:${i.merged?1:0}:${i.ci}:${i.mergeable}`).join("|");if(this.lastSig.get(e)===o)return;for(let i=0;i<n.length;i++){let a=n[i];if(a.ci!=="failed")continue;let c=pt(r.prs[i].repoSpec);if(c.getCiFailureLog)try{let l=await c.getCiFailureLog(r.prs[i].repoSpec,a.number);l&&(a.ciFailureLog=l)}catch(l){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${l instanceof Error?l.message:String(l)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:n}),this.lastSig.set(e,o);let s=_E(n);this.log.info(`[track] task=${e} snapshot signalled${s?` \u2192 ${s}`:""} (${n.length} PR(s))`)}}});function lg(t){let{description:e,...r}=t;return r}function jE(t){let{body:e,...r}=t;return r}function NE(t){let r=(t.split(/[\\/]/).pop()??t).replace(/[^A-Za-z0-9._-]/g,"_").replace(/^\.+/,"");return r.length>0?r.slice(0,120):"attachment"}async function ug(t,e,r,n){try{return await t.getIssue(e,r)}catch(o){return n.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function dg(t,e,r,n){try{return await t.listComments(e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}var ti,pg=v(()=>{"use strict";F();zs();Xs();ti=class t{constructor(e,r,n,o={contextDir:null}){this.intervalMs=e;this.send=r;this.log=n;this.options=o}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;abandonedTicks=0;static MAX_ABANDONED_TICKS=3;setRequest(e){let r=this.request?.projectId;this.request=e,this.log.info(`[yt-sync] request updated: project=${e.projectKey} columns=[${e.sourceColumns.join(",")}] sinceMs=${e.sinceMs} offBoard=${e.offBoardIssueIds.length}`),this.timer||this.start(),r&&r!==e.projectId&&this.log.info(`[yt-sync] project switch ${r} \u2192 ${e.projectId}`)}start(){if(this.timer)return;this.log.info(`[yt-sync] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[yt-sync] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[yt-sync] poller stopped"))}async tickOnce(){await this.tick()}async forceSync(){if(!this.request){this.log.info("[yt-sync] force requested but no sync_request yet \u2014 ignored");return}this.log.info("[yt-sync] force sync requested (manual)"),await this.tick()}async tick(){if(this.running||!this.request)return;let r=(this.options.resolveProvider??(()=>St({contextDir:this.options.contextDir})))();if(!r.ok){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn(`[yt-sync] tracker provider unavailable (${r.error}) \u2014 poller idle.`));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,r.provider)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let x=e.stageField?{stageField:e.stageField}:{},S=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},E=(e.backlogScope??"personal")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(E){let $=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[T,N]=await Promise.all([$.length>0?r.listIssues({projectKey:e.projectKey,columns:$,...x,...S}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...x})]),G=new Map;for(let ee of[...T,...N])G.set(ee.id,ee);o=[...G.values()]}else{let $=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:$,...x,...S})}}catch(x){let S=x instanceof Error?x.message:String(x);S.includes("stage_field")?this.log.warn(`[yt-sync] CONFIGURATION ERROR \u2014 ${S}`):this.log.warn(`[yt-sync] listIssues failed: ${S}`);return}let s=new Map,i=new Set,a=new Set(e.doneColumns??[]);for(let x of o){if(i.add(x.id),a.has(x.status))continue;let S=await dg(r,x.id,e.sinceMs,this.log);S&&s.set(x.id,S)}let c=[];for(let x of e.offBoardIssueIds){if(i.has(x))continue;let S=await dg(r,x,e.sinceMs,this.log);if(S&&S.length>0&&s.set(x,S),e.requireAssignee||S&&S.length>0){let I=await ug(r,x,e.stageField,this.log);if(I)c.push(I);else if(S&&S.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(x=>!a.has(x.status)),{attachmentsByIssue:u,attachmentKeys:p}=await this.collectAttachments(l,s,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let d=[...l,...c].map(x=>({issue:x,comments:s.get(x.id)??[],attachments:u.get(x.id)??[]}));d.push(...await Ph(this.options.contextDir,d,x=>ug(r,x,e.stageField,this.log)));try{await Vs(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let x of p)this.shippedAttachments.add(x)}catch(x){let S=x instanceof Error?x.message:String(x);this.abandonTick(`context task sync failed: ${S}`);return}let m=this.options.isSelfComment??(()=>!1),f=[],g=[];for(let[x,S]of s){let I=S.filter($=>!m($.id));if(I.length===0)continue;f.push({issueId:x,comments:I.map(jE)});let E=I.flatMap($=>{let T=yr($.body);return T?[{commentId:$.id,author:$.author,name:T.name,args:T.args,createdAt:$.createdAt}]:[]});E.length>0&&g.push({issueId:x,commands:E})}let h={type:"youtrack_observation",projectId:e.projectId,issues:o.map(lg),commentsBatch:f,...g.length>0?{commandsBatch:g}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(lg)}:{},observedAtMs:n};this.send(h);let w=f.reduce((x,S)=>x+S.comments.length,0),y=g.reduce((x,S)=>x+S.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${w} commands=${y} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,s=[];for(let i of e){let a=[...i.attachments??[]];for(let u of r.get(i.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let p=`${i.id}:${u.id}`;if(this.shippedAttachments.has(p))continue;let d;try{d=await n.downloadAttachment(u.url)}catch(f){this.log.warn(`[yt-sync] attachment ${u.name} (${i.id}) download failed: ${f instanceof Error?f.message:String(f)}`);continue}let m=NE(u.name);l.has(m)&&(m=`${u.id}-${m}`),l.add(m),c.push({name:m,contentBase64:d.toString("base64")}),s.push(p)}c.length>0&&o.set(i.id,c)}return{attachmentsByIssue:o,attachmentKeys:s}}}});import{existsSync as fg,readFileSync as OE,readdirSync as LE}from"node:fs";import{join as mg}from"node:path";import{simpleGit as DE}from"simple-git";import{parse as ME}from"yaml";function pl(t){let e=new Map,r=mg(t,Yo);if(!fg(r))return e;let n;try{n=ME(OE(r,"utf-8"))}catch{return e}let o=n?.repos;if(!o||typeof o!="object")return e;for(let[s,i]of Object.entries(o)){if(!i||typeof i!="object")continue;let a=i,c=a.counts??{};typeof a.builtFromCommit=="string"&&e.set(s,{builtFromCommit:a.builtFromCommit,counts:{component:typeof c.component=="number"?c.component:0,code:typeof c.code=="number"?c.code:0,correlates:typeof c.correlates=="number"?c.correlates:0}})}return e}function UE(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return hr({modelFormatVersion:2,repos:e})}function hg(t,e){let r=mg(t,e);if(!fg(r))return[];let n=[];for(let o of LE(r,{withFileTypes:!0})){let s=`${e}/${o.name}`;o.isDirectory()?n.push(...hg(t,s)):n.push(s)}return n}async function ri(t,e,r={}){let n=[],o=0;for(let d of e){n.push(...d.files);let m=`model/derived/structure/${d.repo}`;for(let f of hg(t,m))d.emittedShardPaths.has(f)||(n.push({path:f,content:"",deleted:!0}),o++)}let s=pl(t);for(let d of e)s.set(d.repo,{builtFromCommit:d.headCommit,counts:d.counts});n.push({path:Yo,content:UE(s)});let i=Fs(t),a=$h(i,r.halfLifeDays??Qe.halfLifeDays);n.push({path:dr,content:Ks(a)});for(let d of e){let m=[];for(let f of i)for(let g of f.files)re(g.key)?.repo===d.repo&&m.push({kind:"touched_by",from:ge(f.taskKey),to:g.key,...g.churn!==void 0?{weight:g.churn}:{}});n.push({path:Ji(d.repo),content:fr({modelFormatVersion:2,repo:d.repo,builtFromCommit:d.headCommit,edges:m})})}let c=DE(t),l=(await c.revparse(["HEAD"]).catch(()=>"")).trim(),u=`model: build ${e.map(d=>`${d.repo}@${d.headCommit.slice(0,10)}`).join(", ")}`;await ve(t,n,u);let p=(await c.revparse(["HEAD"]).catch(()=>"")).trim();if(p!==l){let{rebuildSearchIndex:d}=await Promise.resolve().then(()=>(Ro(),Eo));await d(t).catch(()=>{})}return{committed:p!==l,filesWritten:n.filter(d=>!d.deleted).length,filesDeleted:o}}var gg=v(()=>{"use strict";F();Jc();nt()});var oi={};Fe(oi,{bootstrapDaemonModel:()=>FE,bootstrapModelForTargets:()=>wl,bootstrapWorkspaceModel:()=>$g,modelBootstrapCommand:()=>kl,modelBuildCommand:()=>yl,rebuildWorkspaceModelIfStale:()=>KE});import{existsSync as hl}from"node:fs";import{join as yn}from"node:path";import{cancel as BE,intro as yg,log as fl,outro as ml}from"@clack/prompts";import{simpleGit as gl}from"simple-git";function ni(t){BE(t),process.exit(1)}function kg(t,e,r){let n=t.spec.repos.filter(s=>!e||s.name===e);if(n.length===0)throw new Error(e?`repo "${e}" is not part of this project (see project.yaml)`:"the project has no repos configured");let o=[];for(let s of n){let i=s.mountAs==="."?t.root:yn(t.root,s.mountAs);if(!hl(yn(i,".git"))){r(`${s.name}: no local clone at ${i} \u2014 skipped (run \`codepipe clone\` first)`);continue}o.push({name:s.name,dir:i,defaultBranch:s.defaultBranch||"main"})}if(o.length===0)throw new Error("nothing to do \u2014 no repo clones found");return o}async function wg(t){let e=gl(t.dir),r=`origin/${t.defaultBranch}`;return await e.raw(["rev-parse","--verify",r]).then(()=>!0).catch(()=>!1)?r:"HEAD"}async function bg(t,e,r,n){let o=[];for(let s of e)try{let i=await Vc({repo:s.name,repoDir:s.dir,contextDir:t,settings:r,ref:await wg(s)});o.push(i),n(`${s.name}: ${i.counts.code} files, ${i.counts.component} components, ${i.counts.correlates} co-change edges @ ${i.headCommit.slice(0,10)}`)}catch(i){throw new Error(`${s.name}: ${i instanceof Error?i.message:String(i)}`)}return o}async function yl(t){yg("codepipe model build");let e=Re();e||ni("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{let r=fn(e.contextDir),n=kg(e,t.repo,i=>fl.warn(i)),o=await bg(e.contextDir,n,r,i=>fl.info(i)),s=await ri(e.contextDir,o,{halfLifeDays:r.cochange.halfLifeDays});s.committed?ml(`model updated: ${s.filesWritten} files written, ${s.filesDeleted} stale removed`):ml("model already up to date (no changes)")}catch(r){ni(r instanceof Error?r.message:String(r))}}async function kl(t){yg("codepipe model bootstrap");let e=Re();e||ni("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{await $g(e,t.repo,{onLog:r=>fl.info(r)})}catch(r){ni(r instanceof Error?r.message:String(r))}ml("bootstrap complete")}async function $g(t,e,r){let n=kg(t,e,r.onLog);return wl(t.contextDir,n,r)}async function wl(t,e,r){let n=fn(t),o=await bg(t,e,n,r.onLog),s=Wm(t),i=Hm(n.issueKeyPattern,s),a=_r([...n.ignore,...pn]),c=[];for(let p of o){let d=e.find(f=>f.name===p.repo),m=await Ym({repo:p.repo,repoDir:d.dir,headCommit:p.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:i,pathToCurrent:Ms(p.identityTable),entityByKey:p.entityByKey,ignored:a,trackerProjectKey:s});c.push(m),r.onLog(`${p.repo}: ${m.size} task events mined from history`)}let{files:l,skippedPipeline:u}=Vm(t,c);return u>0&&r.onLog(`${u} events already recorded by the live pipeline \u2014 left untouched`),l.length>0&&await ve(t,l,`model: bootstrap ${l.length} task events from history`),await ri(t,o,{halfLifeDays:n.cochange.halfLifeDays}),{events:l.length}}async function FE(t,e,r,n){if(r.length===0)throw new Error("the project has no repos configured");let o=[];for(let i of r){let a=i.mountAs??i.name,c=a==="."?e.root:yn(e.root,a),l=i.defaultBranch||"main";c!==e.contextDir&&hl(yn(c,".git"))?(await gl(c).fetch(["origin",l]).catch(()=>{}),o.push({name:i.name,dir:c,defaultBranch:l})):(n(`${i.name}: materializing clone in the daemon layout`),await Ot(t,i),o.push({name:i.name,dir:Ie(t,i.name),defaultBranch:l}))}let s=await wl(e.contextDir,o,{onLog:n});return{repos:o.length,events:s.events}}async function KE(t,e={}){let r=e.onLog??(()=>{}),n=fn(t.contextDir);if(!n.enabled)return{rebuilt:[],skipped:[]};let o=[],s=[],i=pl(t.contextDir),a=[];for(let c of t.repos){let l=c.mountAs==="."?t.root:yn(t.root,c.mountAs);if(!hl(yn(l,".git")))continue;let u=gl(l),p=c.defaultBranch||"main";e.fetch&&await u.fetch(["origin",p]).catch(()=>{});let d=await wg({name:c.name,dir:l,defaultBranch:p}),m=(await u.revparse([d]).catch(()=>"")).trim();if(m){if(i.get(c.name)?.builtFromCommit===m){s.push(c.name);continue}try{a.push(await Vc({repo:c.name,repoDir:l,contextDir:t.contextDir,settings:n,ref:m})),o.push(c.name)}catch(f){r(`[model] rebuild of ${c.name} failed: ${f instanceof Error?f.message:String(f)}`)}}}return a.length>0&&(await ri(t.contextDir,a,{halfLifeDays:n.cochange.halfLifeDays}),r(`[model] release-path rebuild: ${o.join(", ")} (skipped up-to-date: ${s.join(", ")||"\u2014"})`)),{rebuilt:o,skipped:s}}var Ao=v(()=>{"use strict";nt();gg();zc();qc();Us();So();Rr();bt()});var xg={};Fe(xg,{computeDriftReport:()=>YE,supersededAdrIds:()=>vg});import{existsSync as bl,readFileSync as $l,readdirSync as vl}from"node:fs";import{join as kn}from"node:path";import{parse as GE}from"yaml";import{simpleGit as HE}from"simple-git";function qE(t,e){let r=kn(t,`model/derived/structure/${e}`),n=[],o="";if(!bl(r))return{nodes:n,builtFromCommit:o};for(let s of vl(r).sort()){if(!s.endsWith(".yaml"))continue;let i;try{let a=Ct(GE($l(kn(r,s),"utf-8")));if(!a.ok)continue;i=a.value}catch{continue}o=i.builtFromCommit;for(let a of i.nodes){let c=re(a.key);!c||c.level!=="code"&&c.level!=="component"||n.push({key:a.key,path:c.path,level:c.level,contentHash:a.contentHash,entityId:a.entityId})}}return{nodes:n,builtFromCommit:o}}function vg(t){let e=new Set,r=kn(t,"adr");if(!bl(r))return e;for(let n of vl(r).sort()){let o=/^(\d{4})-/.exec(n)?.[1];if(!(!o||!n.endsWith(".md")))try{let s=$l(kn(r,n),"utf-8").slice(0,600).toLowerCase();/status[^\n]*superseded/.test(s)&&e.add(`ADR-${o}`)}catch{}}return e}async function YE(t,e,r){let{nodes:n,builtFromCommit:o}=qE(e,r),s=(await HE(t).revparse(["HEAD"])).trim(),i=await xo(t,s),a=new Map(i.map(y=>[y.path,y.blobHash])),c=[],l=[],u=new Set,p=[];for(let y of n){if(y.level==="component"){p.push(y);continue}u.add(y.path);let x=a.get(y.path);x?y.contentHash&&x.slice(0,WE)!==y.contentHash&&c.push(y.key):l.push(y.key)}let d=0,m=new Map,f=new Set;for(let y of i){let x=y.path.lastIndexOf("/"),S=x<0?"":y.path.slice(0,x);m.has(S)||m.set(S,new Set),m.get(S).add(y.path),u.has(y.path)||d++;let I=S;for(;I!==""&&!f.has(I);)f.add(I),I=I.includes("/")?I.slice(0,I.lastIndexOf("/")):""}let g=new Map;for(let y of u){let x=y.lastIndexOf("/"),S=x<0?"":y.slice(0,x);g.has(S)||g.set(S,new Set),g.get(S).add(y)}for(let y of p){if(!f.has(y.path)){l.push(y.key);continue}let x=g.get(y.path)??new Set,S=m.get(y.path)??new Set;(x.size!==S.size||[...x].some(E=>!S.has(E)))&&c.push(y.key)}let h=[],w=vg(e);if(w.size>0){let y=kn(e,"model/facts/annotations"),x=new Map(n.filter(S=>S.entityId).map(S=>[S.entityId,S.key]));if(bl(y))for(let S of vl(y).sort()){if(!S.endsWith(".md"))continue;let I=S.replace(/\.md$/,""),E=x.get(I);if(E)try{($l(kn(y,S),"utf-8").match(/\bADR-(\d{3,4})\b/g)??[]).map(N=>`ADR-${N.slice(4).padStart(4,"0")}`).some(N=>w.has(N))&&h.push(E)}catch{}}}return{repo:r,builtFromCommit:o,headCommit:s,stale:[...new Set(c)].sort(),orphaned:[...new Set(l)].sort(),superseded:[...new Set(h)].sort(),newFiles:d}}var WE,Sg=v(()=>{"use strict";F();So();WE=12});import{existsSync as Rg,rmSync as VE}from"node:fs";import{join as jr}from"node:path";import{simpleGit as zE}from"simple-git";import"ws";function si(t,e={}){let r=e.log??{info:h=>console.log(h),warn:h=>console.warn(h)};r.info(`codepipe-cli v${Ke} (protocol ${ct})`);let n=h=>e.onEvent?.(h),o=e.workspace;o?.contextDir&&Mf(o.contextDir,r);let s=Eg("CLI_TRACKING_POLL_INTERVAL_SEC"),i=Eg("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let h=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(h)&&h>0?h*1e3:6e5})(),c=!1,l=!1,u=!1,p=new Set,d=!1,m=new Set,f=g();function g(){let h=gs(t.hubUrl,t.cliToken),w=null,y=new ei(s,_=>{h.readyState===h.OPEN&&h.send(JSON.stringify(_))},r),x=new ti(i,_=>{h.readyState===h.OPEN&&h.send(JSON.stringify(_))},r,{contextDir:o?.contextDir??null,isSelfComment:_=>m.has(_)}),S=null,I=async()=>{try{let _={trackerProvider:il(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 U=await Gp(t.projectId,_);if(h.readyState!==h.OPEN)return;let D={type:"cli_readiness",projectId:t.projectId,ready:U.ready,checks:U.checks,creds:U.creds,secretNames:ep(t.projectId),checkedAt:U.checkedAt};if(h.send(JSON.stringify(D)),U.ready)r.info("[readiness] ready");else{let O=U.checks.filter(b=>!b.ok).map(b=>`${b.name}(${b.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${O.join(", ")}`)}let z=Xp(U.creds,u);if(z==="open"){u=!0;let O=Jp(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${O}`),vr(O)}else z==="rearm"&&(u=!1)}catch(_){r.warn(`[readiness] check failed: ${_ instanceof Error?_.message:String(_)}`)}},E=()=>{I(),S=setInterval(()=>void I(),a),typeof S.unref=="function"&&S.unref()},$=()=>{S&&(clearInterval(S),S=null)},T=150,N=new Map,G=_=>{let U=N.get(_);if(!U||(U.timer&&clearTimeout(U.timer),N.delete(_),U.events.length===0||h.readyState!==h.OPEN))return;let D={type:"run_activity",projectId:t.projectId,runId:_,events:U.events};h.send(JSON.stringify(D))},ee=(_,U)=>{let D=N.get(_);if(D||(D={events:[],timer:null},N.set(_,D)),D.events.push(U),U.kind==="result"){G(_);return}D.timer||(D.timer=setTimeout(()=>G(_),T),D.timer.unref?.())},C=o?.contextDir?new Es(o.contextDir,t.projectId,_=>{h.readyState===h.OPEN&&h.send(JSON.stringify(_))},r):null,k=async()=>{let _=o?.contextDir;if(!_)throw new Error("no context repo clone on this CLI");let U;try{U=(await ne(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let D=await cm(_,t.projectId,U,r);return h.readyState===h.OPEN&&h.send(JSON.stringify(D)),D},M=null,P=async()=>{let _=o?.contextDir;if(_)try{let{readContextIndexHub:U,collectSearchRows:D}=await Promise.resolve().then(()=>(Ro(),Eo));if(U(_)!=="metadata")return;let z=D(_);h.readyState===h.OPEN&&(h.send(JSON.stringify({type:"model_index",projectId:t.projectId,rows:z})),r.info(`[model] tier-2 index snapshot pushed (${z.length} rows)`))}catch(U){r.warn(`[model] tier-2 index push failed (non-fatal): ${U instanceof Error?U.message:String(U)}`)}},H=()=>{M&&clearTimeout(M),M=setTimeout(()=>void P(),5e3)},Y=null,oe=async _=>{if(o?.contextDir)try{let{rebuildWorkspaceModelIfStale:U}=await Promise.resolve().then(()=>(Ao(),oi));(await U({root:o.root,contextDir:o.contextDir,repos:o.repos},{fetch:_,onLog:z=>r.info(z)})).rebuilt.length>0&&H()}catch(U){r.warn(`[model] release-path rebuild failed (non-fatal): ${U instanceof Error?U.message:String(U)}`)}},Ve=_=>{Y&&clearTimeout(Y),Y=setTimeout(()=>void oe(_),6e4)},ze=setInterval(()=>void oe(!0),6*36e5);return h.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let _=cp(t.projectId),U=X("ORIGIN")==="farm"?"farm":"local",D=X("FARM_ID"),z=t.accountEmail??_.email,O;try{let R=bm(t.projectId);R&&(O=R.publicKey,r.info(`[cred-channel] key fingerprint: ${R.fingerprint}`))}catch(R){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${R instanceof Error?R.message:String(R)}`)}let b={type:"register",projectId:t.projectId,platformVersion:Ke,protocolVersion:ct,accountId:_.accountId,accountLabel:_.label,origin:U,inFlightActionIds:[...p],...z?{accountEmail:z}:{},...U==="farm"&&D?{farmId:D}:{},...O?{sealPublicKey:O}:{}};h.send(JSON.stringify(b))}),h.on("message",async _=>{let U=_.toString("utf-8");if(U==="pong"||U==="ping")return;let D;try{D=JSON.parse(U)}catch{return}if(!D||typeof D!="object")return;let z=D.type;if(z==="registered"){let b=D;if(b.ok){if(r.info(`[ws] registered for project ${b.projectId}`),n({kind:"registered",projectId:b.projectId??t.projectId}),y.start(),C?.start(),E(),Sl(t,o,r),o?.contextDir){try{let R=As(o.contextDir,t.projectId);h.readyState===h.OPEN&&h.send(JSON.stringify(R)),R.outdated&&(r.warn(`[ctx] context format outdated: v${R.templateVersion} \u2192 v${R.currentVersion}`+(R.missingPaths.length>0?` (missing: ${R.missingPaths.join(", ")})`:"")),l||(l=!0,k().catch(()=>{})))}catch(R){r.warn(`[ctx] context-format detect failed (non-fatal): ${R instanceof Error?R.message:String(R)}`)}P(),Ve(!0)}}else r.warn(`[ws] register rejected: ${b.reason??"unknown"}`),n({kind:"register_rejected",reason:b.reason??"unknown"}),c=!0,h.close();return}if(z==="hello"){let b=D;w=Yn(b.protocolVersion);let R=w?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${b.platformVersion} (protocol ${b.protocolVersion}) \u2014 ${R}`),w||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Ke}, protocol ${ct}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${xl}`),n({kind:"incompatible",hubVersion:typeof b.platformVersion=="string"?b.platformVersion:null,hubProtocol:typeof b.protocolVersion=="number"?b.protocolVersion:null,updateCommand:xl}));return}if(z==="tracking_targets"){y.setTargets(D.targets);return}if(z==="youtrack_sync_request"){x.setRequest(D);return}if(z==="youtrack_force_sync"){x.forceSync();return}if(z==="sync_local"){await ZE(D,o,h,r);return}if(z==="provision_repo"){let b=D;r.info(`[repo] provision_repo: ${b.repo.name} (${b.repo.host}:${b.repo.owner}/${b.repo.repoName})`),await XE(t,o,b.repo,r),await Sl(t,o,r);return}if(z==="remove_repo"){let b=D;r.info(`[repo] remove_repo: ${b.repoName}${b.purge?" (purge)":""}`),await Sl(t,o,r),b.purge&&JE(t,o,b.repoName,r);return}if(z==="context_write"){await QE(D,o,h,r);return}if(z==="adr_promote"){await eR(D,o,h,r);return}if(z==="cred_update"){let b=D,R=q(t.projectId),B=R?.sealKey?await $m(t.projectId,b.kind,b.sealed,R.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},J={type:"cred_update_result",updateId:b.updateId,projectId:t.projectId,ok:B.ok,...B.detail?{detail:B.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(J)),B.ok?(r.info(`[cred] ${b.kind} replaced${B.detail?` \u2014 ${B.detail}`:""}`),I()):r.warn(`[cred] ${b.kind} replacement rejected: ${B.detail??"unknown"}`);return}if(z==="readiness_check"){r.info("[readiness] on-demand check requested"),I();return}if(z==="agent_login_start"){Vp(t,h,D,r,I);return}if(z==="move_to_farm"){let b=D;r.info(`[farm-move] request to move ${t.projectId} onto farm ${b.farmName} (${b.farmId})`);let R=await qh(t,b,o?.contextDir,r);h.readyState===h.OPEN&&h.send(JSON.stringify(R)),R.ok?r.info(`[farm-move] done \u2014 farm daemon ${R.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${R.error??"unknown error"}`);return}if(z==="gh_runner_setup"){let b=D;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${b.runnerName} (${b.runnerId})`);let R=await tg(t,b,r);h.readyState===h.OPEN&&h.send(JSON.stringify(R)),R.ok?r.info(`[ghr] runners connected on ${b.runnerName}`):r.warn(`[ghr] setup failed: ${R.error??"see per-repo statuses"}`);return}if(z==="gh_runner_teardown"){let b=D;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${b.runnerName} (${b.runnerId})`);let R=await rg(t,b,r);h.readyState===h.OPEN&&h.send(JSON.stringify(R)),R.ok?r.info(`[ghr] runners disconnected from ${b.runnerName}`):r.warn(`[ghr] teardown failed: ${R.error??"unknown error"}`);return}if(z==="tracker_fields_request"){let b=D,R={type:"tracker_fields_result",requestId:b.requestId,projectId:t.projectId,ok:!1},B=St({contextDir:o?.contextDir??null});if(!B.ok)R.error=B.error;else try{R.fields=await B.provider.fetchStateFields(b.projectKey),R.ok=!0}catch(J){R.error=J instanceof Error?J.message:String(J)}h.readyState===h.OPEN&&h.send(JSON.stringify(R)),R.ok||r.warn(`[yt-fields] listing failed: ${R.error??"unknown"}`);return}if(z==="project_secret_update"||z==="project_secret_delete"){let b=D,R;if(b.type==="project_secret_update"){let J=q(t.projectId);R=J?.sealKey?sg(t.projectId,b.name,b.sealed,J.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else R=ig(t.projectId,b.name);let B={type:"project_secret_update_result",updateId:b.updateId,projectId:t.projectId,ok:R.ok,...R.detail?{detail:R.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(B)),R.ok?(r.info(`[secret] ${b.name} ${b.type==="project_secret_update"?"saved":"deleted"}`+(R.detail?` \u2014 ${R.detail}`:"")),I()):r.warn(`[secret] ${b.name} rejected: ${R.detail??"unknown"}`);return}if(z==="auto_apply_local"){let b=D;if(!o?.contextDir){r.warn(`[apply] auto_apply_local for ${b.claim.taskKey} \u2014 no workspace (headless), skipped; task stays in READY_TO_APPLY`);return}let R=await If({hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId,root:o.root,contextDir:o.contextDir,repos:o.repos},b.claim,r).catch(B=>({ok:!1,message:B instanceof Error?B.message:String(B)}));R.ok?r.info(`[apply] ${b.claim.taskKey}: ${R.message}`):r.warn(`[apply] ${b.claim.taskKey}: ${R.message} \u2014 task stays in READY_TO_APPLY`),n({kind:"local_applied",taskKey:b.claim.taskKey,ok:R.ok,...R.ok?{branches:R.branches??[]}:{error:R.message}});return}if(z==="sandbox_keys"){let b=q(t.projectId);if(!b){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let R=Qr(t.projectId),B=hm(D,b,R,r);for(let J of B)h.readyState===h.OPEN&&h.send(JSON.stringify(J));return}if(z!=="dispatch_action")return;let O=D;if(w===!1){let b=`refused: HUB protocol incompatible with CLI v${Ke} (protocol ${ct})`;h.send(JSON.stringify({type:"action_result",actionId:O.actionId,status:"failed",error:b})),r.warn(`[exec] ${O.actionId} (${O.action.type}) \u2192 REFUSED: ${b}`),r.warn(`[exec] update the CLI to clear this: ${xl}`),n({kind:"action",actionId:O.actionId,actionType:O.action.type,ok:!1,error:b});return}if(O.action.type==="model_drift"){p.add(O.actionId);try{let b,R=o?.repos.find(B=>B.name===O.action.repoName);if(!o?.contextDir||!R)b={status:"failed",error:"no local workspace/repo clone on this CLI"};else try{let{computeDriftReport:B}=await Promise.resolve().then(()=>(Sg(),xg)),J=R.mountAs==="."?o.root:jr(o.root,R.mountAs);b={status:"done",result:{report:await B(J,o.contextDir,R.name)}}}catch(B){b={status:"failed",error:B instanceof Error?B.message:String(B)}}h.send(JSON.stringify({type:"action_result",actionId:O.actionId,...b}))}finally{p.delete(O.actionId)}return}if(O.action.type==="model_bootstrap"){p.add(O.actionId);try{let b;if(!o?.contextDir)b={status:"failed",error:"no Context Repo clone on this CLI"};else if(d)b={status:"failed",error:"model bootstrap is already running"};else{d=!0;try{let R=await ne(t.hubUrl,t.cliToken,t.projectId),{bootstrapDaemonModel:B}=await Promise.resolve().then(()=>(Ao(),oi)),J=await B(t.projectId,{root:o.root,contextDir:o.contextDir},R.repos,Pe=>r.info(`[model] ${Pe}`));r.info(`[model] bootstrap done: ${J.repos} repos, ${J.events} task events`),H(),b={status:"done",result:{repos:J.repos,events:J.events}}}catch(R){b={status:"failed",error:R instanceof Error?R.message:String(R)},r.warn(`[model] bootstrap failed: ${b.error}`)}finally{d=!1}}h.readyState===h.OPEN&&h.send(JSON.stringify({type:"action_result",actionId:O.actionId,...b}))}finally{p.delete(O.actionId)}return}if(O.action.type==="local_apply"){p.add(O.actionId);try{let b;if(!o)b={status:"failed",error:"no local workspace on this CLI"};else{let B=await Bh(o,O.action.repos,r);if(b=B.ok?{status:"done",result:{repos:B.repos}}:{status:"failed",error:B.error},B.ok&&o.contextDir){let J=O.action.taskId.split(":")[1]??"";for(let Pe of J?B.repos:[]){let st=o.repos.find(Se=>Se.name===Pe.repoName);if(!st)continue;let{recordPipelineEvent:K}=await Promise.resolve().then(()=>(rl(),Ah));await K({contextDir:o.contextDir,repoDir:jr(o.root,st.mountAs),repoName:Pe.repoName,taskKey:J,commitSha:Pe.commit}).catch(Se=>r.warn(`[model] task event for ${J} failed: ${Se instanceof Error?Se.message:String(Se)}`))}H()}}h.send(JSON.stringify({type:"action_result",actionId:O.actionId,...b}));let R=b.status!=="failed";R?r.info(`[exec] ${O.actionId} (local_apply) \u2192 done`):r.warn(`[exec] ${O.actionId} (local_apply) \u2192 FAILED: ${b.status==="failed"?b.error:"?"}`),n({kind:"action",actionId:O.actionId,actionType:"local_apply",ok:R,...b.status==="failed"?{error:b.error}:{}})}finally{p.delete(O.actionId)}return}p.add(O.actionId);try{let b=await Dh({action:O.action,repo:O.repo,trackerIssueId:O.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:C?()=>C.reportNow():void 0,refreshContextStatus:o?.contextDir?k:void 0,onRunActivity:ee}).catch(J=>({status:"failed",error:J instanceof Error?J.message:String(J)}));O.action.type==="tracker_comment"&&b.status==="done"&&"result"in b&&typeof b.result?.commentId=="string"&&m.add(b.result.commentId),h.send(JSON.stringify({type:"action_result",actionId:O.actionId,...b}));let R=b.status!=="failed",B=!R&&"error"in b?b.error:void 0;R?r.info(`[exec] ${O.actionId} (${O.action.type}) \u2192 done`):r.warn(`[exec] ${O.actionId} (${O.action.type}) \u2192 FAILED: ${B??"?"}`),n({kind:"action",actionId:O.actionId,actionType:O.action.type,ok:R,...B?{error:B}:{}}),R&&["apply_delivery","context_write","create_pr"].includes(O.action.type)&&H(),R&&["merge_pr","merge_branch"].includes(O.action.type)&&Ve(!0)}finally{p.delete(O.actionId)}}),h.on("close",(_,U)=>{let D=U?.toString("utf-8")??"";if(r.info(`[ws] closed code=${_}${D?` reason=${D}`:""}`),y.stop(),x.stop(),C?.stop(),$(),clearInterval(ze),Y&&clearTimeout(Y),M&&clearTimeout(M),D==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:_}),!c&&setTimeout(()=>{f=g()},2e3)}),h.on("error",_=>r.warn(`[ws] error: ${_.message}`)),h}return{stop(){c=!0,f.close()}}}async function Sl(t,e,r){try{let n=await ne(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:s}=wo(t.projectId,n.repos,e?.contextDir);for(let i of o)r.info(`[repo] restaged repo set in ${i}`);for(let i of s)r.warn(`[repo] could not restage ${i.path}: ${i.error}`)}catch(n){r.warn(`[repo] repo-set reconcile skipped: ${n instanceof Error?n.message:String(n)}`)}}async function XE(t,e,r,n){let o=r.mountAs??r.name;if(o==="."){n.info(`[repo] ${r.name} mounts in place (mount_as: .) \u2014 nothing to clone`);return}let s=e?jr(e.root,o):Ie(t.projectId,r.name);if(Rg(jr(s,".git"))){n.info(`[repo] ${r.name} already present at ${s}`);return}try{await zE().clone(fo(r),s),n.info(`[repo] cloned ${r.name} \u2192 ${s}`)}catch(i){n.warn(`[repo] clone of ${r.name} failed (will retry lazily): ${i instanceof Error?i.message.trim():String(i)}`)}}function JE(t,e,r,n){let o=e?.repos.find(i=>i.name===r)?.mountAs??r,s=e?jr(e.root,o):Ie(t.projectId,r);if(e&&s===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Rg(jr(s,".git"))){n.info(`[repo] no local clone to purge for ${r} (${s})`);return}try{VE(s,{recursive:!0,force:!0}),n.info(`[repo] purged local clone ${s}`)}catch(i){n.warn(`[repo] purge of ${s} failed: ${i instanceof Error?i.message:String(i)}`)}}async function ZE(t,e,r,n){if(!e){n.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let o of t.repos){let s=e.repos.find(l=>l.name===o.repoName),i=jr(e.root,s?.mountAs??o.repoName),a=s?.defaultBranch??o.defaultBranch,c=await Cf(i,a).catch(l=>({status:"warn",reason:l instanceof Error?l.message:String(l)}));c.status==="updated"?n.info(`[sync] ${o.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?n.info(`[sync] ${o.repoName}: not cloned in workspace \u2014 skipped`):(n.warn(`[sync] ${o.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:o.repoName,reason:c.reason??"sync skipped"})))}}async function QE(t,e,r,n){let o=(s,i)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:s};i&&(a.error=i),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{await ve(e.contextDir,t.files,t.message),n.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),o("done")}catch(s){let i=s instanceof Error?s.message:String(s);n.warn(`[ctx] context_write ${t.id} failed: ${i}`),o("failed",i)}}async function eR(t,e,r,n){let o=(s,i)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:s};i&&(a.error=i),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[adr] adr_promote ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{let s=t.source??"task",i=await Wf(e.contextDir,t.taskKey,t.slugs,void 0,s);if(n.info(`[adr] adr_promote ${t.id}: promoted ${i.promoted.length}, skipped ${i.skipped.length}`+(i.promoted.length>0?` (${i.promoted.join(", ")})`:"")),i.missing.length>0){let a=l=>s==="staging"?`adr/DRAFT-${l}.md`:`tasks/${t.taskKey}/adr/DRAFT-${l}.md`,c=`draft file(s) missing in clone: ${i.missing.map(a).join(", ")}`;n.warn(`[adr] adr_promote ${t.id}: ${c}`),o("failed",c);return}o("done")}catch(s){let i=s instanceof Error?s.message:String(s);n.warn(`[adr] adr_promote ${t.id} failed: ${i}`),o("failed",i)}}function Eg(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}var xl,El=v(()=>{"use strict";Le();F();lp();zp();Zp();hs();gc();Af();Lf();qf();nt();Lt();Tc();lm();jc();Rr();gm();vm();Mh();Fh();Yh();ng();Te();ag();nn();de();cg();pg();Xs();xl="npm i -g @code-partner/codepipe@latest"});import{execFileSync as tR}from"node:child_process";import{mkdtempSync as rR,mkdirSync as nR,readFileSync as Ig,rmSync as oR,writeFileSync as sR}from"node:fs";import{tmpdir as iR}from"node:os";import{dirname as aR,join as Tg}from"node:path";function Cg(t="codepipe-context"){let e=rR(Tg(iR(),"codepipe-ssh-")),r=Tg(e,"id_ed25519");try{return tR("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Ig(r,"utf-8"),publicKey:Ig(`${r}.pub`,"utf-8").trim()}}finally{oR(e,{recursive:!0,force:!0})}}async function Ag(t,e,r,n="codepipe-context"){let o=await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/keys`,{method:"POST",headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({title:n,key:r,read_only:!1})});if(o.ok)return;let s=await o.text();if(!(o.status===422&&/already in use/i.test(s)))throw new Error(`add deploy key failed: ${o.status} ${s}`)}function Pg(t){if(/^git@[^:]+:.+/.test(t))return t;let e=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(e)return`git@${e[1]}:${e[2]}`;let r=t.match(/^https:\/\/(?:[^@/]+@)?([^/]+)\/(.+)$/);return r?`git@${r[1]}:${r[2]}`:t}function _g(t,e){nR(aR(t),{recursive:!0});let r=e.endsWith(`
|
|
713
|
+
FROM model_fts WHERE model_fts MATCH ? ORDER BY bm25(model_fts), node_id LIMIT ?`).all(o,s).map(c=>({nodeId:c.nodeId,kind:c.kind,score:-c.rank,snippet:c.snippet}))}finally{i.close()}}var Ro=S(()=>{"use strict";F()});var sh={};Fe(sh,{attachPrToBranchTasks:()=>Zc,attachPrToEvent:()=>oh,recordPipelineEvent:()=>Jc});import{existsSync as fS,readFileSync as mS}from"node:fs";import{join as nh}from"node:path";import{simpleGit as Xc}from"simple-git";async function hS(t,e){let n=await Xc(t).raw(["diff","--numstat",`${e}^`,e]).catch(()=>""),o=[];for(let s of n.split(`
|
|
714
|
+
`)){let i=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(s);if(!i)continue;let a=i[1]==="-"?0:Number(i[1]),c=i[2]==="-"?0:Number(i[2]);o.push({path:i[3],churn:a+c})}return o}function gS(t,e){let n=[`tasks/${e}/PLAN.md`,`tasks/${e}/SOLUTION.md`].find(s=>fS(nh(t,s)));if(!n)return{};let o=nh(t,n);try{let s=mS(o,"utf-8"),i=[...new Set(s.match(/\bADR-\d{3,4}\b/g)??[])].sort();return{solution:n,...i.length>0?{adr:i}:{}}}catch{return{solution:n}}}async function Jc(t){let{contextDir:e,repoDir:r,repoName:n,taskKey:o,commitSha:s}=t,i=fn(e),a=_r([...i.ignore,...pn]),c=await hS(r,s),l=(await Xc(r).raw(["show","-s","--format=%cs",s])).trim(),u=null,p=new Map;try{u=Hc(e,n),u&&(p=new Map(u.entities.filter(I=>I.status==="active").map(I=>[I.currentKey,I.entityId])))}catch{}let d=[];for(let I of c){if(a(I.path))continue;let E=fe("code",n,I.path),$=p.get(E);d.push({key:E,...$?{entityId:$}:{},churn:I.churn})}if(d.length===0)return{recorded:!1};let m=gS(e,o),f=Ds(e,o),g=f?.origin==="pipeline"?f.files.filter(I=>re(I.key)?.repo!==n):[],h=f?.origin==="pipeline"?f.commits:[],w={modelFormatVersion:2,taskKey:o,origin:"pipeline",...f?.title?{title:f.title}:{},...l?{date:l}:{},commits:[...new Set([...h,s])],files:[...g,...d],links:{...f?.origin==="pipeline"?f.links:{},...m}};w.links&&Object.keys(w.links).length===0&&delete w.links;let y=[...Fs(e).filter(I=>I.taskKey!==o),w],v=Jm(Zm(e),y,o,i.cochange.halfLifeDays),x=await mm({contextDir:e,taskKey:o,repoName:n,repoDir:r,commitSha:s,date:l,touchedKeys:new Set(d.map(I=>I.key)),identity:u}).catch(()=>[]);await ve(e,[{path:pr(o),content:qr(w)},{path:dr,content:Ks(v)},...x],`model: task event ${o}`);{let{rebuildSearchIndex:I}=await Promise.resolve().then(()=>(Ro(),Eo));await I(e).catch(()=>{})}return{recorded:!0}}async function Zc(t){let e=new Set([t.fallbackTaskKey]);try{let r=Xc(t.repoDir),n=(await r.raw(["rev-parse","--verify",`origin/${t.baseBranch}`]).catch(()=>r.raw(["rev-parse","--verify",t.baseBranch]))).trim(),o=await r.raw(["log","--format=%(trailers:key=CodePipe-Task,valueonly)",`${n}..${t.branchName}`]);for(let s of o.split(`
|
|
715
|
+
`)){let i=s.trim();i&&e.add(i)}}catch{}for(let r of[...e].sort())await oh(t.contextDir,r,t.prUrl)}async function oh(t,e,r){let n=Ds(t,e);if(!n||n.origin!=="pipeline"||n.links?.pr===r)return;let o={...n,links:{...n.links??{},pr:r}};await ve(t,[{path:pr(e),content:qr(o)}],`model: pr link for ${e}`)}var Qc=S(()=>{"use strict";F();nt();hm();Gc();qc();Us();Vc();So()});import{homedir as LS}from"node:os";import{existsSync as DS,mkdirSync as MS,readFileSync as US,writeFileSync as BS}from"node:fs";import{dirname as FS,join as KS}from"node:path";function nl(){return X("FARM_PINS")??KS(LS(),".codepipe","farm-pins.json")}function hh(){let t=nl();if(!DS(t))return{};try{return JSON.parse(US(t,"utf-8"))}catch{return{}}}function GS(t){let e=nl();MS(FS(e),{recursive:!0}),BS(e,JSON.stringify(t,null,2)+`
|
|
716
|
+
`,{mode:384})}function HS(t){return hh()[t]}function Xs(t,e){let r=hh();r[t]=e,GS(r)}function Js(t,e){let r=De(e),n=HS(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 ${nl()}.`);return r}var ol=S(()=>{"use strict";Le();ot()});import{existsSync as Nh,readFileSync as sE,readdirSync as iE}from"node:fs";import{join as Oh}from"node:path";import{simpleGit as aE}from"simple-git";import{parse as cE}from"yaml";function al(t){let e=new Map,r=Oh(t,Yo);if(!Nh(r))return e;let n;try{n=cE(sE(r,"utf-8"))}catch{return e}let o=n?.repos;if(!o||typeof o!="object")return e;for(let[s,i]of Object.entries(o)){if(!i||typeof i!="object")continue;let a=i,c=a.counts??{};typeof a.builtFromCommit=="string"&&e.set(s,{builtFromCommit:a.builtFromCommit,counts:{component:typeof c.component=="number"?c.component:0,code:typeof c.code=="number"?c.code:0,correlates:typeof c.correlates=="number"?c.correlates:0}})}return e}function lE(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return hr({modelFormatVersion:2,repos:e})}function Lh(t,e){let r=Oh(t,e);if(!Nh(r))return[];let n=[];for(let o of iE(r,{withFileTypes:!0})){let s=`${e}/${o.name}`;o.isDirectory()?n.push(...Lh(t,s)):n.push(s)}return n}async function ei(t,e,r={}){let n=[],o=0;for(let d of e){n.push(...d.files);let m=`model/derived/structure/${d.repo}`;for(let f of Lh(t,m))d.emittedShardPaths.has(f)||(n.push({path:f,content:"",deleted:!0}),o++)}let s=al(t);for(let d of e)s.set(d.repo,{builtFromCommit:d.headCommit,counts:d.counts});n.push({path:Yo,content:lE(s)});let i=Fs(t),a=Xm(i,r.halfLifeDays??Qe.halfLifeDays);n.push({path:dr,content:Ks(a)});for(let d of e){let m=[];for(let f of i)for(let g of f.files)re(g.key)?.repo===d.repo&&m.push({kind:"touched_by",from:ge(f.taskKey),to:g.key,...g.churn!==void 0?{weight:g.churn}:{}});n.push({path:Qi(d.repo),content:fr({modelFormatVersion:2,repo:d.repo,builtFromCommit:d.headCommit,edges:m})})}let c=aE(t),l=(await c.revparse(["HEAD"]).catch(()=>"")).trim(),u=`model: build ${e.map(d=>`${d.repo}@${d.headCommit.slice(0,10)}`).join(", ")}`;await ve(t,n,u);let p=(await c.revparse(["HEAD"]).catch(()=>"")).trim();if(p!==l){let{rebuildSearchIndex:d}=await Promise.resolve().then(()=>(Ro(),Eo));await d(t).catch(()=>{})}return{committed:p!==l,filesWritten:n.filter(d=>!d.deleted).length,filesDeleted:o}}var Dh=S(()=>{"use strict";F();Vc();nt()});var ri={};Fe(ri,{bootstrapDaemonModel:()=>dE,bootstrapModelForTargets:()=>ml,bootstrapWorkspaceModel:()=>Kh,modelBootstrapCommand:()=>fl,modelBuildCommand:()=>pl,rebuildWorkspaceModelIfStale:()=>pE});import{existsSync as ul}from"node:fs";import{join as yn}from"node:path";import{cancel as uE,intro as Mh,log as cl,outro as ll}from"@clack/prompts";import{simpleGit as dl}from"simple-git";function ti(t){uE(t),process.exit(1)}function Uh(t,e,r){let n=t.spec.repos.filter(s=>!e||s.name===e);if(n.length===0)throw new Error(e?`repo "${e}" is not part of this project (see project.yaml)`:"the project has no repos configured");let o=[];for(let s of n){let i=s.mountAs==="."?t.root:yn(t.root,s.mountAs);if(!ul(yn(i,".git"))){r(`${s.name}: no local clone at ${i} \u2014 skipped (run \`codepipe clone\` first)`);continue}o.push({name:s.name,dir:i,defaultBranch:s.defaultBranch||"main"})}if(o.length===0)throw new Error("nothing to do \u2014 no repo clones found");return o}async function Bh(t){let e=dl(t.dir),r=`origin/${t.defaultBranch}`;return await e.raw(["rev-parse","--verify",r]).then(()=>!0).catch(()=>!1)?r:"HEAD"}async function Fh(t,e,r,n){let o=[];for(let s of e)try{let i=await Wc({repo:s.name,repoDir:s.dir,contextDir:t,settings:r,ref:await Bh(s)});o.push(i),n(`${s.name}: ${i.counts.code} files, ${i.counts.component} components, ${i.counts.correlates} co-change edges @ ${i.headCommit.slice(0,10)}`)}catch(i){throw new Error(`${s.name}: ${i instanceof Error?i.message:String(i)}`)}return o}async function pl(t){Mh("codepipe model build");let e=Re();e||ti("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{let r=fn(e.contextDir),n=Uh(e,t.repo,i=>cl.warn(i)),o=await Fh(e.contextDir,n,r,i=>cl.info(i)),s=await ei(e.contextDir,o,{halfLifeDays:r.cochange.halfLifeDays});s.committed?ll(`model updated: ${s.filesWritten} files written, ${s.filesDeleted} stale removed`):ll("model already up to date (no changes)")}catch(r){ti(r instanceof Error?r.message:String(r))}}async function fl(t){Mh("codepipe model bootstrap");let e=Re();e||ti("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{await Kh(e,t.repo,{onLog:r=>cl.info(r)})}catch(r){ti(r instanceof Error?r.message:String(r))}ll("bootstrap complete")}async function Kh(t,e,r){let n=Uh(t,e,r.onLog);return ml(t.contextDir,n,r)}async function ml(t,e,r){let n=fn(t),o=await Fh(t,e,n,r.onLog),s=bm(t),i=wm(n.issueKeyPattern,s),a=_r([...n.ignore,...pn]),c=[];for(let p of o){let d=e.find(f=>f.name===p.repo),m=await vm({repo:p.repo,repoDir:d.dir,headCommit:p.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:i,pathToCurrent:Ms(p.identityTable),entityByKey:p.entityByKey,ignored:a,trackerProjectKey:s});c.push(m),r.onLog(`${p.repo}: ${m.size} task events mined from history`)}let{files:l,skippedPipeline:u}=xm(t,c);return u>0&&r.onLog(`${u} events already recorded by the live pipeline \u2014 left untouched`),l.length>0&&await ve(t,l,`model: bootstrap ${l.length} task events from history`),await ei(t,o,{halfLifeDays:n.cochange.halfLifeDays}),{events:l.length}}async function dE(t,e,r,n){if(r.length===0)throw new Error("the project has no repos configured");let o=[];for(let i of r){let a=i.mountAs??i.name,c=a==="."?e.root:yn(e.root,a),l=i.defaultBranch||"main";c!==e.contextDir&&ul(yn(c,".git"))?(await dl(c).fetch(["origin",l]).catch(()=>{}),o.push({name:i.name,dir:c,defaultBranch:l})):(n(`${i.name}: materializing clone in the daemon layout`),await Ot(t,i),o.push({name:i.name,dir:Ie(t,i.name),defaultBranch:l}))}let s=await ml(e.contextDir,o,{onLog:n});return{repos:o.length,events:s.events}}async function pE(t,e={}){let r=e.onLog??(()=>{}),n=fn(t.contextDir);if(!n.enabled)return{rebuilt:[],skipped:[]};let o=[],s=[],i=al(t.contextDir),a=[];for(let c of t.repos){let l=c.mountAs==="."?t.root:yn(t.root,c.mountAs);if(!ul(yn(l,".git")))continue;let u=dl(l),p=c.defaultBranch||"main";e.fetch&&await u.fetch(["origin",p]).catch(()=>{});let d=await Bh({name:c.name,dir:l,defaultBranch:p}),m=(await u.revparse([d]).catch(()=>"")).trim();if(m){if(i.get(c.name)?.builtFromCommit===m){s.push(c.name);continue}try{a.push(await Wc({repo:c.name,repoDir:l,contextDir:t.contextDir,settings:n,ref:m})),o.push(c.name)}catch(f){r(`[model] rebuild of ${c.name} failed: ${f instanceof Error?f.message:String(f)}`)}}}return a.length>0&&(await ei(t.contextDir,a,{halfLifeDays:n.cochange.halfLifeDays}),r(`[model] release-path rebuild: ${o.join(", ")} (skipped up-to-date: ${s.join(", ")||"\u2014"})`)),{rebuilt:o,skipped:s}}var Ao=S(()=>{"use strict";nt();Dh();qc();Gc();Us();So();Rr();bt()});var Hh={};Fe(Hh,{computeDriftReport:()=>yE,supersededAdrIds:()=>Gh});import{existsSync as hl,readFileSync as gl,readdirSync as yl}from"node:fs";import{join as kn}from"node:path";import{parse as fE}from"yaml";import{simpleGit as mE}from"simple-git";function gE(t,e){let r=kn(t,`model/derived/structure/${e}`),n=[],o="";if(!hl(r))return{nodes:n,builtFromCommit:o};for(let s of yl(r).sort()){if(!s.endsWith(".yaml"))continue;let i;try{let a=Ct(fE(gl(kn(r,s),"utf-8")));if(!a.ok)continue;i=a.value}catch{continue}o=i.builtFromCommit;for(let a of i.nodes){let c=re(a.key);!c||c.level!=="code"&&c.level!=="component"||n.push({key:a.key,path:c.path,level:c.level,contentHash:a.contentHash,entityId:a.entityId})}}return{nodes:n,builtFromCommit:o}}function Gh(t){let e=new Set,r=kn(t,"adr");if(!hl(r))return e;for(let n of yl(r).sort()){let o=/^(\d{4})-/.exec(n)?.[1];if(!(!o||!n.endsWith(".md")))try{let s=gl(kn(r,n),"utf-8").slice(0,600).toLowerCase();/status[^\n]*superseded/.test(s)&&e.add(`ADR-${o}`)}catch{}}return e}async function yE(t,e,r){let{nodes:n,builtFromCommit:o}=gE(e,r),s=(await mE(t).revparse(["HEAD"])).trim(),i=await xo(t,s),a=new Map(i.map(y=>[y.path,y.blobHash])),c=[],l=[],u=new Set,p=[];for(let y of n){if(y.level==="component"){p.push(y);continue}u.add(y.path);let v=a.get(y.path);v?y.contentHash&&v.slice(0,hE)!==y.contentHash&&c.push(y.key):l.push(y.key)}let d=0,m=new Map,f=new Set;for(let y of i){let v=y.path.lastIndexOf("/"),x=v<0?"":y.path.slice(0,v);m.has(x)||m.set(x,new Set),m.get(x).add(y.path),u.has(y.path)||d++;let I=x;for(;I!==""&&!f.has(I);)f.add(I),I=I.includes("/")?I.slice(0,I.lastIndexOf("/")):""}let g=new Map;for(let y of u){let v=y.lastIndexOf("/"),x=v<0?"":y.slice(0,v);g.has(x)||g.set(x,new Set),g.get(x).add(y)}for(let y of p){if(!f.has(y.path)){l.push(y.key);continue}let v=g.get(y.path)??new Set,x=m.get(y.path)??new Set;(v.size!==x.size||[...v].some(E=>!x.has(E)))&&c.push(y.key)}let h=[],w=Gh(e);if(w.size>0){let y=kn(e,"model/facts/annotations"),v=new Map(n.filter(x=>x.entityId).map(x=>[x.entityId,x.key]));if(hl(y))for(let x of yl(y).sort()){if(!x.endsWith(".md"))continue;let I=x.replace(/\.md$/,""),E=v.get(I);if(E)try{(gl(kn(y,x),"utf-8").match(/\bADR-(\d{3,4})\b/g)??[]).map(N=>`ADR-${N.slice(4).padStart(4,"0")}`).some(N=>w.has(N))&&h.push(E)}catch{}}}return{repo:r,builtFromCommit:o,headCommit:s,stale:[...new Set(c)].sort(),orphaned:[...new Set(l)].sort(),superseded:[...new Set(h)].sort(),newFiles:d}}var hE,Wh=S(()=>{"use strict";F();So();hE=12});import{execFileSync as EE}from"node:child_process";import{mkdtempSync as RE,mkdirSync as IE,readFileSync as Vh,rmSync as TE,writeFileSync as CE}from"node:fs";import{tmpdir as AE}from"node:os";import{dirname as PE,join as zh}from"node:path";function Xh(t="codepipe-context"){let e=RE(zh(AE(),"codepipe-ssh-")),r=zh(e,"id_ed25519");try{return EE("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Vh(r,"utf-8"),publicKey:Vh(`${r}.pub`,"utf-8").trim()}}finally{TE(e,{recursive:!0,force:!0})}}async function Jh(t,e,r,n="codepipe-context"){let o=await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/keys`,{method:"POST",headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({title:n,key:r,read_only:!1})});if(o.ok)return;let s=await o.text();if(!(o.status===422&&/already in use/i.test(s)))throw new Error(`add deploy key failed: ${o.status} ${s}`)}function Zh(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 Qh(t,e){IE(PE(t),{recursive:!0});let r=e.endsWith(`
|
|
743
717
|
`)?e:e+`
|
|
744
|
-
`;return
|
|
745
|
-
`,{mode:384})}var
|
|
746
|
-
`}async function
|
|
718
|
+
`;return CE(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var bl=S(()=>{"use strict"});import{existsSync as eg,mkdirSync as tg}from"node:fs";import{dirname as rg}from"node:path";import{simpleGit as wn}from"simple-git";function _E(t,e,r="x-access-token"){let n=`${encodeURIComponent(r)}:${encodeURIComponent(e)}`,o=t.match(/^git@([^:]+):(.+)$/);if(o)return`https://${n}@${o[1]}/${o[2]}`;let s=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(s)return`https://${n}@${s[1]}/${s[2]}`;let i=t.match(/^https:\/\/(?:[^@/]+@)?(.+)$/);return i?`https://${n}@${i[1]}`:t}function jE(t,e){return e?.contextWrite?.token?{user:so(t),secret:e.contextWrite.token}:t===Jr.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Jr.bitbucket?e?.bitbucket?.apiToken?{user:Gt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function ng(t,e){let r=e.sleep??(s=>new Promise(i=>setTimeout(i,s))),n=e.initialDelayMs??5e3,o=e.maxDelayMs??6e4;for(;;)try{return await t()}catch(s){if(!(s instanceof oi))throw s;e.log.warn(`[ctx] ${s.message} \u2014 retrying in ${Math.round(n/1e3)}s (the HUB may be deploying)`),await r(n),n=Math.min(n*2,o)}}async function si(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,s;try{s=await ne(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new oi(c)}let i=s.contextRepo;if(!i)return o.warn("[ctx] project has no Context Repo on HUB \u2014 daemon stays headless (no config report)"),null;let a=jE(wr(i.cloneUrl),r);if(a){let c=await NE({ctx:i,contextDir:n,cred:a,log:o});if(c)return c;o.warn("[ctx] token clone/update failed")}if(r?.contextSsh?.privateKey){let c=await OE({ctx:i,contextDir:n,privateKey:r.contextSsh.privateKey,log:o});if(c)return c;o.warn("[ctx] SSH deploy-key clone failed")}return o.warn("[ctx] no usable context-host/contextWrite token or SSH deploy key \u2014 can't clone the Context Repo on the farm; config_observation + artifact commits disabled."),null}async function NE(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,s=_E(e.cloneUrl,n.secret,n.user),i=e.branch,a=encodeURIComponent(n.secret),c=l=>l.split(n.secret).join("***").split(a).join("***");try{if(eg(`${r}/.git`)){let l=wn(r);await l.remote(["set-url","origin",s]),await l.fetch("origin",i),await l.checkout(i);let u=$c(r);await l.reset(["--hard",`origin/${i}`]),vc(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${i}`)}else tg(rg(r),{recursive:!0}),await wn().clone(s,r,["--branch",i]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${i} \u2192 ${r}`);await og(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 OE(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,s=`${r}.deploy-key`,i=Qh(s,n),a=Zh(e.cloneUrl),c=e.branch;try{if(eg(`${r}/.git`)){let l=wn(r);await l.addConfig("core.sshCommand",i,!1,"local"),await l.remote(["set-url","origin",a]),await l.fetch("origin",c),await l.checkout(c);let u=$c(r);await l.reset(["--hard",`origin/${c}`]),vc(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else tg(rg(r),{recursive:!0}),await wn().env({...process.env,GIT_SSH_COMMAND:i}).clone(a,r,["--branch",c]),await wn(r).addConfig("core.sshCommand",i,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await og(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 og(t){let e=wn(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 oi,$l=S(()=>{"use strict";F();Te();Lt();bl();oi=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as LE}from"node:child_process";function DE(){try{return LE("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function ig(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:DE(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var ag=S(()=>{"use strict"});import{homedir as ME}from"node:os";import{mkdirSync as UE,readFileSync as BE,writeFileSync as FE,existsSync as cg}from"node:fs";import{dirname as KE,join as xl}from"node:path";function GE(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function gt(t){let e=X("SANDBOX_CONFIG");if(e)return e;let r=xl(ME(),".codepipe","worker");return t?xl(r,"profiles",t,"config.json"):xl(r,"config.json")}function lg(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function je(t){let e=gt(t),r=null;return cg(e)&&(r=JSON.parse(BE(e,"utf-8"))),r?(r.planningLane=GE(),r):null}function ug(t,e){let r=gt(e);UE(KE(r),{recursive:!0}),FE(r,JSON.stringify(t,null,2)+`
|
|
719
|
+
`,{mode:384})}var ii=S(()=>{"use strict";Le();cg(".env")&&process.loadEnvFile(".env")});import HE from"ws";var bn,Sl=S(()=>{"use strict";bn=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};e&&(n.signal=e);let o=r?`${this.hubUrl}/jobs/claim?lane=${encodeURIComponent(r)}`:`${this.hubUrl}/jobs/claim`;return fetch(o,n)}async submitResult(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/jobs/result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});if(!r.ok)throw new Error(`submitResult failed: ${r.status} ${await r.text()}`)}async heartbeat(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e})};r&&(n.signal=r);let o=await fetch(`${this.hubUrl}/jobs/heartbeat`,n);if(o.status===410)return"claim_lost";if(!o.ok)throw new Error(`heartbeat failed: ${o.status} ${await o.text()}`);return"ok"}async releaseJob(e,r,n){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e,reason:r})};n&&(o.signal=n);let s=await fetch(`${this.hubUrl}/jobs/release`,o);if(!s.ok&&s.status!==409&&s.status!==404)throw new Error(`release failed: ${s.status} ${await s.text()}`)}openControlSocket(){if(!this.token)throw new Error("no sandbox token");let e=this.hubUrl.replace(/^http/,"ws")+`/sandbox/connect?token=${encodeURIComponent(this.token)}`;return new HE(e)}}});import{hostname as WE}from"node:os";async function Nr(t){let e=je(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${gt(t.profile)}.`),process.exit(1));let r=t.name??WE(),n=ig({projects:t.projects??[],llm:t.llm??null}),o=new bn(t.hub.replace(/\/$/,"")),s=js(),i=De(s.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:s.publicKey});ug({hubUrl:t.hub.replace(/\/$/,""),sandboxId:a,token:c,name:r,llm:t.llm??null,sealPublicKey:s.publicKey,sealPrivateKey:s.privateKey},t.profile),console.log(`registered as ${a} (${r}) at ${t.hub}`),console.log(`config saved to ${gt(t.profile)}`),console.log(""),console.log(" cred-channel key fingerprint (confirm this on the CLI \u2014 pin-on-register):"),console.log(` ${i}`),console.log("")}var dg=S(()=>{"use strict";ot();ag();ii();Sl()});function pg(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 ai(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 $n(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 ci=S(()=>{"use strict"});import{spawn as qE}from"node:child_process";function El(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function VE(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 zE(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Or(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Rl(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}})+`
|
|
720
|
+
`}async function yg(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Mt;let r=$n(e.metadata),n=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",pg(r)];e.model&&e.model.trim().length>0&&n.push("--model",e.model.trim());for(let l of e.addDirs??[])n.push("--add-dir",l);let o=e.onActivity,s=l=>{if(o)try{o(l)}catch{}},i=[],a=null,c=l=>{let u=Date.now(),p=l.type;if(p==="assistant"){let d=l.message;for(let m of d?.content??[]){let f=m.type;if(f==="text"){let g=String(m.text??"").trim();g&&s({ts:u,kind:"text",author:"agent",text:El(g,mg)})}else if(f==="tool_use"){let g=String(m.name??""),h=m.input?.file_path??m.input?.path,w=VE(h,e.workspaceDir);s({ts:u,kind:"tool",author:"agent",tool:g,...w?{file:w}:{}})}}return}if(p==="user"){let d=l.message;for(let m of d?.content??[])if(m.type==="tool_result"){let f=m.is_error===!0,g=f?El(zE(m.content),200):"";s({ts:u,kind:"tool_result",author:"agent",isError:f,...g?{text:g}:{}})}return}if(p==="result"){a=l;let d=String(l.subtype??"").trim();s({ts:u,kind:"result",author:"agent",...d?{text:d}:{}});return}if(p==="system"){let d=String(l.subtype??"").trim();d&&s({ts:u,kind:"system",author:"agent",text:d})}};return s({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((l,u)=>{let p=qE(t,n,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});p.stdout.setEncoding("utf-8"),p.stderr.setEncoding("utf-8");let d=!1,m=!1,f=null,g=()=>{d=!0,p.kill("SIGTERM"),f=setTimeout(()=>p.kill("SIGKILL"),hg)};e.signal?.addEventListener("abort",g,{once:!0});let h=null,w=()=>{h&&clearTimeout(h),h=setTimeout(()=>{m=!0,console.warn(`[claude:chat] idle for ${gg}ms \u2014 ending session`),p.kill("SIGTERM"),f=setTimeout(()=>p.kill("SIGKILL"),hg)},gg)},y=()=>{f&&clearTimeout(f),h&&clearTimeout(h),e.signal?.removeEventListener("abort",g)},v=!0,x=$=>{if(!(!v||p.stdin.destroyed))try{p.stdin.write($)}catch{}};x(Rl(e.prompt)),w(),(async()=>{try{for await(let $ of e.interactive.inbox){if(d||!v)break;if(w(),$.kind==="user")s({ts:Date.now(),kind:"text",author:"user",text:El($.text,mg)}),x(Rl($.text,fg(r)));else{x(Rl(YE)),v=!1;try{p.stdin.end()}catch{}break}}}catch{}})();let I="",E=$=>{let T;try{T=JSON.parse($)}catch{return}c(T)};p.stdout.on("data",$=>{i.push($),w(),I+=$;let T;for(;(T=I.indexOf(`
|
|
747
721
|
`))!==-1;){let N=I.slice(0,T).trim();I=I.slice(T+1),N&&E(N)}}),p.stderr.on("data",$=>{i.push($);for(let T of $.split(`
|
|
748
|
-
`)){let N=T.trim();N&&console.warn(`[claude:chat:stderr] ${N}`)}}),p.on("error",$=>{y(),u($)}),p.on("close",$=>{if(y(),d){u(new Mt);return}if(m){u(new Error("chat session ended: idle for too long without a reply"));return}I.trim()&&E(I.trim()),console.log(`[claude:chat] exit code=${$}`),l({artifactPaths:[],log:i.join(""),usage:
|
|
722
|
+
`)){let N=T.trim();N&&console.warn(`[claude:chat:stderr] ${N}`)}}),p.on("error",$=>{y(),u($)}),p.on("close",$=>{if(y(),d){u(new Mt);return}if(m){u(new Error("chat session ended: idle for too long without a reply"));return}I.trim()&&E(I.trim()),console.log(`[claude:chat] exit code=${$}`),l({artifactPaths:[],log:i.join(""),usage:XE(a)})})})}function XE(t){let e=Ft();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=Or(r.input_tokens),e.outputTokens=Or(r.output_tokens),e.cacheReadInputTokens=Or(r.cache_read_input_tokens),e.cacheCreationInputTokens=Or(r.cache_creation_input_tokens)),e.totalCostUsd=Or(t.total_cost_usd),e.numTurns=Or(t.num_turns),e.durationMs=Or(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var mg,hg,gg,YE,kg=S(()=>{"use strict";F();vn();ci();mg=16e3,hg=5e3,gg=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),YE="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 JE}from"node:child_process";import{existsSync as ZE}from"node:fs";function eR(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function wg(t){let e;try{e=JSON.parse(t)}catch{return console.log(`[claude] ${t.slice(0,200)}`),null}let r=e.type;if(r==="system"){let n=e.subtype??"";return console.log(`[claude] system ${n}`),e}if(r==="assistant"){let n=e.message;for(let o of n?.content??[]){let s=o.type;if(s==="text"){let i=String(o.text??"").trim();i&&console.log(`[claude] text: ${Qt(i,200)}`)}else if(s==="tool_use"){let i=String(o.name??""),a=o.input,c=nR(i,a);console.log(`[claude] tool_use ${i}${c?` ${c}`:""}`)}}return e}if(r==="user"){let n=e.message;for(let o of n?.content??[])if(o.type==="tool_result")if(o.is_error===!0){let s=$g(o.content);console.log(`[claude] tool_result (error)${s?`: ${Qt(s,200)}`:""}`)}else console.log("[claude] tool_result");return e}if(r==="result"){let n=e.subtype??"",o=e.num_turns,s=e.total_cost_usd;return console.log(`[claude] result ${n} turns=${o} cost=$${s}`),e}return console.log(`[claude] ${String(r)} ${Qt(JSON.stringify(e),200)}`),e}function tR(t,e,r){let n=t===0?["claude reported an error"]:[`claude exited with code ${t}`];if(e){let o=typeof e.result=="string"?e.result.trim():"",s=e.api_error_status,i=e.subtype;o?n.push(Qt(o,500)):typeof i=="string"&&i!=="success"&&n.push(i),typeof s=="number"&&n.push(`(api_status=${s})`)}return n.length===1&&r.trim()&&n.push(Qt(r.trim().split(`
|
|
749
723
|
`).slice(-5).join(`
|
|
750
|
-
`),500)),n.join(" \u2014 ")}function
|
|
751
|
-
`))!==-1;){let T=I.slice(0,$).trim();if(I=I.slice($+1),T){let N=
|
|
752
|
-
`)){let T=$.trim();T&&console.warn(`[claude:stderr] ${T}`)}}),h.on("error",E=>{
|
|
724
|
+
`),500)),n.join(" \u2014 ")}function rR(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 $g(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function nR(t,e){if(!e)return"";if(t==="Write"||t==="Edit"||t==="Read"){let r=e.file_path??e.path;if(typeof r=="string")return`path=${r}`}if(t==="Bash"){let r=e.command;if(typeof r=="string")return`cmd=${Qt(r,80)}`}return""}function Qt(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function Me(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function oR(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=Me(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:Me(e.resetsAt),rateLimitType:typeof e.rateLimitType=="string"?e.rateLimitType:"",utilization:n,isUsingOverage:e.isUsingOverage===!0};return typeof e.surpassedThreshold=="number"&&(o.surpassedThreshold=e.surpassedThreshold),o}function sR(t,e,r,n){let o=Ft(),s=t&&typeof t.usage=="object"?t.usage:null;s?(o.inputTokens=Me(s.input_tokens),o.outputTokens=Me(s.output_tokens),o.cacheReadInputTokens=Me(s.cache_read_input_tokens),o.cacheCreationInputTokens=Me(s.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=Me(t?.total_cost_usd),o.numTurns=t&&Me(t.num_turns)>0?Me(t.num_turns):r,o.durationMs=Me(t?.duration_ms);let i=typeof t?.model=="string"?t.model:"";return o.model=i||n,o}function iR(t,e){let r=Date.now(),n=t.type;if(n==="system"){let o=String(t.subtype??"").trim();return o?[{ts:r,kind:"system",text:o}]:[]}if(n==="assistant"){let o=t.message,s=[];for(let i of o?.content??[]){let a=i.type;if(a==="text"){let c=String(i.text??"").trim();c&&s.push({ts:r,kind:"text",text:Qt(c,bg)})}else if(a==="tool_use"){let c=String(i.name??""),l=i.input,u=l?.file_path??l?.path??l?.notebook_path,p=aR(u,e);s.push({ts:r,kind:"tool",tool:c,...p?{file:p}:{}})}}return s}if(n==="user"){let o=t.message,s=[];for(let i of o?.content??[])if(i.type==="tool_result"){let a=i.is_error===!0,c=a?Qt($g(i.content),bg):"";s.push({ts:r,kind:"tool_result",isError:a,...c?{text:c}:{}})}return s}if(n==="result"){let o=String(t.subtype??"").trim(),s=typeof t.num_turns=="number"?t.num_turns:void 0,i=typeof t.total_cost_usd=="number"?t.total_cost_usd:void 0;return[{ts:r,kind:"result",...o?{text:o}:{},...s!==void 0?{turns:s}:{},...i!==void 0?{costUsd:i}:{}}]}return[]}function aR(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 xn,Mt,QE,_o,bg,vn=S(()=>{"use strict";F();kg();ci();xn=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Mt=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},QE=5e3;_o=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return yg(this.binary,e);if(e.signal?.aborted)throw new Mt;let r=["-p",eR(e.prompt),"--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",ai($n(e.metadata))];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let f of e.addDirs??[])r.push("--add-dir",f);e.settings&&Object.keys(e.settings).length>0&&r.push("--settings",JSON.stringify(e.settings));let n=[],o=[],s=null,i={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,u=f=>{if(f){if(f.type==="result"){s=f;return}if(f.type==="rate_limit_event"){let g=oR(f.rate_limit_info);g&&(!l||g.utilization>l.utilization)&&(l=g);return}if(f.type==="assistant"){let g=f.message;typeof g?.model=="string"&&(c=g.model);let h=g?.usage;h&&(a+=1,i.input+=Me(h.input_tokens),i.output+=Me(h.output_tokens),i.cacheRead+=Me(h.cache_read_input_tokens),i.cacheCreate+=Me(h.cache_creation_input_tokens))}}},p=e.role,d=e.onActivity,m=f=>{if(d)for(let g of iR(f,e.workspaceDir))try{d(g)}catch{}};return d?.({ts:Date.now(),kind:"start",text:`${p} job started`}),console.log(`[claude] spawn ${this.binary} role=${p}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((f,g)=>{let h=JE(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{},CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:"1800000"}});h.stdout.setEncoding("utf-8"),h.stderr.setEncoding("utf-8");let w=!1,y=null,v=()=>{w=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${p}`),h.kill("SIGTERM"),y=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),h.kill("SIGKILL")},QE)};e.signal?.addEventListener("abort",v,{once:!0});let x=()=>{y&&clearTimeout(y),e.signal?.removeEventListener("abort",v)},I="";h.stdout.on("data",E=>{n.push(E),I+=E;let $;for(;($=I.indexOf(`
|
|
725
|
+
`))!==-1;){let T=I.slice(0,$).trim();if(I=I.slice($+1),T){let N=wg(T);u(N),N&&m(N)}}}),h.stderr.on("data",E=>{n.push(E),o.push(E);for(let $ of E.split(`
|
|
726
|
+
`)){let T=$.trim();T&&console.warn(`[claude:stderr] ${T}`)}}),h.on("error",E=>{x(),g(E)}),h.on("close",E=>{if(x(),w){g(new Mt);return}if(I.trim()){let T=wg(I.trim());u(T),T&&m(T)}let $=s?.is_error===!0;if(E!==0||$){let T=typeof s?.api_error_status=="number"?s.api_error_status:void 0,N=typeof s?.subtype=="string"?s.subtype:void 0,G=typeof s?.result=="string"?s.result:void 0;g(new xn(tR(E,s,o.join("")),{code:E,apiErrorStatus:T,subtype:N,resultText:G,retryAfterMs:rR(s)}));return}console.log("[claude] exit code=0"),f({artifactPaths:[],log:n.join(""),usage:sR(s,i,a,c),...l?{rateLimit:l}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(n=>n.includes("/")&&ZE(n))}};bg=200});import{mkdirSync as cR,writeFileSync as Sn}from"node:fs";import{dirname as lR,join as En}from"node:path";function vg(t,e,r){let n=En(t,e);cR(lR(n),{recursive:!0}),Sn(n,r)}function uR(t,e,r){return`# ${t} \u2014 Estimate
|
|
753
727
|
|
|
754
728
|
**Title:** ${e}
|
|
755
729
|
|
|
@@ -770,7 +744,7 @@ production-grade estimates.)
|
|
|
770
744
|
${r.split(`
|
|
771
745
|
`).slice(0,8).join(`
|
|
772
746
|
`).trim()||"(empty)"}
|
|
773
|
-
`}function
|
|
747
|
+
`}function dR(t,e,r,n){let o=n?`
|
|
774
748
|
## Reviewer rework instruction
|
|
775
749
|
|
|
776
750
|
> ${n.split(`
|
|
@@ -799,10 +773,10 @@ TBD (mock runner does not yet inspect project code).
|
|
|
799
773
|
${r.split(`
|
|
800
774
|
`).slice(0,8).join(`
|
|
801
775
|
`).trim()||"(empty)"}
|
|
802
|
-
`}function
|
|
776
|
+
`}function pR(t){return`# ${t} \u2014 Open questions
|
|
803
777
|
|
|
804
778
|
(none \u2014 mock runner did not surface ambiguities.)
|
|
805
|
-
`}function
|
|
779
|
+
`}function fR(t,e,r){let n=r?` (rework: ${r.split(`
|
|
806
780
|
`)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
|
|
807
781
|
index 0000000..1111111 100644
|
|
808
782
|
--- a/CHANGELOG.md
|
|
@@ -813,7 +787,7 @@ index 0000000..1111111 100644
|
|
|
813
787
|
+- mock-runner placeholder change for slice 5 testing.
|
|
814
788
|
+
|
|
815
789
|
# Changelog
|
|
816
|
-
`}function
|
|
790
|
+
`}function mR(t,e,r){return`# ${t} \u2014 Diff summary
|
|
817
791
|
|
|
818
792
|
**Title:** ${e}
|
|
819
793
|
${r?`
|
|
@@ -824,154 +798,180 @@ ${r?`
|
|
|
824
798
|
- \`CHANGELOG.md\` \u2014 added entry for ${t}.
|
|
825
799
|
|
|
826
800
|
(Mock-runner output. Replace with claude-headless for production patches.)
|
|
827
|
-
`}var jo,
|
|
801
|
+
`}var jo,Il=S(()=>{"use strict";F();vn();jo=class{name(){return"mock"}async run(e){if(e.interactive)return this.runInteractive(e);let r=e.metadata??{},n=r.trackerIssueKey??"TASK",o=r.taskTitle??"(unknown task)",s=r.taskDescription??"",i=[];if(e.role==="estimate"){let a=uR(n,o,s);Sn(En(e.workspaceDir,"ESTIMATE.md"),a),i.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Sn(En(e.workspaceDir,"PLAN.md"),dR(n,o,s,a)),i.push("PLAN.md"),Sn(En(e.workspaceDir,"QUESTIONS.md"),pR(n)),i.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;vg(e.workspaceDir,"changes/sample.patch",fR(n,o,a)),i.push("changes/sample.patch"),vg(e.workspaceDir,"SOLUTION.md",mR(n,o,a)),i.push("SOLUTION.md")}else e.role==="rework"&&(Sn(En(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
|
|
828
802
|
`),i.push("NOTE.md"));return{artifactPaths:i,log:`mock runner produced ${i.length} artifact(s) for role=${e.role}`,usage:Ft()}}async runInteractive(e){let r=e.onActivity,n=s=>{r?.({ts:Date.now(),kind:"text",author:"agent",text:s}),r?.({ts:Date.now(),kind:"result",author:"agent",text:"success"})};r?.({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),n("Hi! Describe the task you'd like to formulate.");let o="Draft from chat";for await(let s of e.interactive.inbox){if(e.signal?.aborted)throw new Mt;if(s.kind==="user")r?.({ts:Date.now(),kind:"text",author:"user",text:s.text}),s.text.trim()&&(o=s.text.trim().slice(0,80)),n(`Got it: **${s.text.trim()}**. Anything else to clarify?`);else break}return Sn(En(e.workspaceDir,"DRAFT.md"),`${o}
|
|
829
803
|
|
|
830
804
|
Produced by the interactive chat (mock runner).
|
|
831
|
-
`),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:Ft()}}}});function
|
|
805
|
+
`),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:Ft()}}}});function xg(t){switch(t){case"mock":return new jo;case"claude-headless":return new _o;default:return null}}function Sg(t,e){let r=e&&e.trim().length>0?e.trim():Ge;return t==="mock"?!0:t==="claude-headless"?r==="claude":!1}var Eg=S(()=>{"use strict";F();vn();Il();vn();Il()});function Tg(t=process.env){return{maxAttempts:li(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:li(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:li(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:li(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function kR(t){if(t instanceof xn){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:s}=t.details,i=o??"";return gR.test(i)?{retryable:!1,reason:"out_of_credits"}:n&&yR.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:s}:hR.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:Rg.test(i)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:n??`exit ${t.details.code}`}}let e=t instanceof Error?t.message:String(t);return Rg.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function Cg(t){if(t instanceof xn){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&Ig.test(n)}let e=t instanceof Error?t.message:String(t);return Ig.test(e)}function wR(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 Ag(t,e,r){let n=r.sleep??(i=>new Promise(a=>setTimeout(a,i))),o=Date.now()+r.policy.totalBudgetMs,s="";for(let i=1;;i++)try{return await t.run(e)}catch(a){s=a instanceof Error?a.message:String(a);let c=kR(a),l=i>=r.policy.maxAttempts;if(!c.retryable||l||r.aborted())throw i>1?new Error(`agent failed after ${i} attempts: ${s}`):a;let u=wR(i,r.policy,c.retryAfterMs);if(Date.now()+u>o)throw new Error(`agent failed after ${i} attempts (retry budget exhausted): ${s}`);console.warn(`[job] ${r.jobId} agent attempt ${i}/${r.policy.maxAttempts} failed (retryable: ${c.reason}) \u2014 cleaning workspace, backoff ${u}ms`),await r.onBeforeRetry(),await n(u)}}function li(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}var hR,Rg,gR,yR,Ig,Pg=S(()=>{"use strict";vn();hR=new Set([429,500,502,503,529]),Rg=/(\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,gR=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,yR=new Set(["error_max_turns"]);Ig=/(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 bR,writeFileSync as $R}from"node:fs";import{homedir as vR}from"node:os";import{join as _g}from"node:path";function Ng(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 Og(t,e,r,n){try{let o=_g(vR(),".codepipe","debug",jg(t));bR(o,{recursive:!0});let s=new Date().toISOString().replace(/[:.]/g,"-"),i=_g(o,`${s}-${jg(e)}-${r}.md`);return $R(i,n),i}catch{return null}}var jg,Lg=S(()=>{"use strict";jg=t=>t.replace(/[^A-Za-z0-9._-]/g,"_")});import{mkdtempSync as xR,rmSync as SR,writeFileSync as Dg}from"node:fs";import{tmpdir as ER}from"node:os";import{join as Tl}from"node:path";function ui(t){return`[url "https://${t}/"]
|
|
832
806
|
insteadOf = git@${t}:
|
|
833
807
|
insteadOf = ssh://git@${t}/
|
|
834
|
-
`}function
|
|
808
|
+
`}function Mg(t,e){if(t.length===0)return null;let r=xR(Tl(ER(),"devpipe-gitcreds-")),n=Tl(r,"credentials"),o=Tl(r,"gitconfig");return Dg(n,t.join(`
|
|
835
809
|
`)+`
|
|
836
|
-
`,{mode:384}),
|
|
810
|
+
`,{mode:384}),Dg(o,`[credential]
|
|
837
811
|
helper = store --file=${n}
|
|
838
|
-
`+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:o,GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{
|
|
839
|
-
`).map(f=>f.trim()).filter(f=>f.length>0);if(d&&m.length===0)throw await ae(i,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${d}`);return m}async function
|
|
840
|
-
`).map(l=>l.trim()).filter(l=>l.length>0),c=await Ce(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(i&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${i}`);return a}function ae(t,e,r){return new Promise((n,o)=>{let s
|
|
841
|
-
${i.join("").trim()||"(no stderr)"}`))})})}function Ce(t,e,r){return new Promise((n,o)=>{let s
|
|
842
|
-
${a.join("").trim()||"(no stderr)"}`))})})}function
|
|
843
|
-
`).map(a=>a.trim()).filter(a=>a.length>0),i=[];for(let a of s)try{let c=
|
|
844
|
-
`+e.subarray(e.length-
|
|
845
|
-
\u2026 [${r.length-e} bytes elided]`}var
|
|
812
|
+
`+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{SR(r,{recursive:!0,force:!0})}catch{}}}}function Cl(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(RR)),t.bitbucket?.apiToken&&(e.push(`https://${Gt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(IR)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(TR)),Mg(e,r)}function Ug(t,e){if(t.contextWrite?.token){let r=wr(e)??"github.com",n=so(r);return Mg([`https://${n}:${t.contextWrite.token}@${r}`],[ui(r)])}return Cl(t)}var RR,IR,TR,Bg=S(()=>{"use strict";F();RR=ui("github.com"),IR=ui("bitbucket.org"),TR=ui("gitlab.com")});import{spawn as Kg}from"node:child_process";import{existsSync as di,mkdirSync as No,readFileSync as CR,rmSync as Al,symlinkSync as AR}from"node:fs";import{homedir as PR}from"node:os";import{dirname as In,join as er}from"node:path";function Gg(t){let e=er(PR(),".codepipe-sandbox","repos");return t?er(e,t):e}function Hg(t,e){let n=(Rn.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{Rn.get(t)===o&&Rn.delete(t)},()=>{Rn.get(t)===o&&Rn.delete(t)});return Rn.set(t,o),n}function Fg(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 _R(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 Wg(t,e,r,n,o){let s=async c=>{await ae(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await ae(t,["reset","--hard",`origin/${c}`],o),await ae(t,["clean","-fdx"],o)},i=async()=>{try{return await s(r),r}catch(c){if(!n||n===r||!Fg(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await s(n),n}},a=async()=>{di(t)&&Al(t,{recursive:!0,force:!0}),No(In(t),{recursive:!0});try{return await ae(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!Fg(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),di(t)&&Al(t,{recursive:!0,force:!0}),No(In(t),{recursive:!0}),await ae(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(di(er(t,".git")))try{return await i()}catch(c){if(!_R(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 qg(t){await ae(t.workspacePath,["reset","--hard",t.baseSha]),await ae(t.workspacePath,["clean","-fdx"])}async function Yg(t,e){let r=t.workspacePath;await ae(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 s={...process.env,GIT_AUTHOR_NAME:Tn,GIT_AUTHOR_EMAIL:Cn,GIT_COMMITTER_NAME:Tn,GIT_COMMITTER_EMAIL:Cn};return(await Ce(r,["commit-tree",n,"-m",e],s)).trim()}async function Vg(t,e,r,n,o){try{await ae(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(s){let i=s instanceof Error?s.message:String(s);throw wr(n)==="github.com"&&/without `?workflow`? scope|workflow.*scope/i.test(i)?new Error("delivery push rejected: the Context-Repo push token needs the `workflow` scope (the delivery includes .github/workflows/*). Set secrets.contextWrite.token to a fine-grained PAT on the Context Repo with Contents: write + Workflows: write (or add `workflow` to the project token).\n"+i):s}}async function zg(t,e){return Ce(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Xg(t,e,r,n,o){await ae(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await ae(t.workspacePath,["checkout","--force",r])}async function Jg(t,e,r,n,o,s){let i=t.workspacePath;await ae(i,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],s);let a=(await Ce(i,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=f=>Ce(i,["rev-parse","-q","--verify",`${f}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await Ce(i,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ae(i,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],s).catch(g=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(g)}`)}),await c(n)||await ae(i,["fetch","origin",n],s).catch(()=>{}),!await c(n)))throw new Error(`moved-base apply: delivery base ${n.slice(0,10)} is unreachable \u2014 cannot re-apply the previous iteration onto the fresh ${t.ref}`);let l={...s??process.env,GIT_AUTHOR_NAME:Tn,GIT_AUTHOR_EMAIL:Cn,GIT_COMMITTER_NAME:Tn,GIT_COMMITTER_EMAIL:Cn},u=(await Ce(i,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),p=(await Ce(i,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await ae(i,["cherry-pick","--quit"],l).catch(()=>{});let d=null;try{await ae(i,["cherry-pick","--no-commit",p],l)}catch(f){d=f instanceof Error?f.message:String(f)}let m=(await Ce(i,["diff","--name-only","--diff-filter=U"])).split(`
|
|
813
|
+
`).map(f=>f.trim()).filter(f=>f.length>0);if(d&&m.length===0)throw await ae(i,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${d}`);return m}async function Pl(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:Tn,GIT_AUTHOR_EMAIL:Cn,GIT_COMMITTER_NAME:Tn,GIT_COMMITTER_EMAIL:Cn};(await Ce(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ae(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 ae(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let i=null;try{await ae(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){i=l instanceof Error?l.message:String(l)}let a=(await Ce(n,["diff","--name-only","--diff-filter=U"])).split(`
|
|
814
|
+
`).map(l=>l.trim()).filter(l=>l.length>0),c=await Ce(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(i&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${i}`);return a}function ae(t,e,r){return new Promise((n,o)=>{let s=Kg("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),i=[];s.stderr.setEncoding("utf-8"),s.stderr.on("data",a=>i.push(a)),s.on("error",o),s.on("close",a=>{if(a===0)return n();o(new Error(`git ${e[0]} failed (exit ${a}):
|
|
815
|
+
${i.join("").trim()||"(no stderr)"}`))})})}function Ce(t,e,r){return new Promise((n,o)=>{let s=Kg("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),i=[],a=[];s.stdout.setEncoding("utf-8"),s.stderr.setEncoding("utf-8"),s.stdout.on("data",c=>i.push(c)),s.stderr.on("data",c=>a.push(c)),s.on("error",o),s.on("close",c=>{if(c===0)return n(i.join(""));o(new Error(`git ${e[0]} failed (exit ${c}):
|
|
816
|
+
${a.join("").trim()||"(no stderr)"}`))})})}function Zg(t,e){di(t)&&Al(t,{recursive:!0,force:!0}),No(In(t),{recursive:!0}),AR(e,t,"dir")}async function Qg(t,e,r){await ae(t,["worktree","prune"]).catch(()=>{}),No(In(r),{recursive:!0}),await ae(t,["worktree","add","--detach",r,`origin/${e}`])}async function jR(t,e,r){No(In(r),{recursive:!0}),await ae(In(r),["clone","--quiet","--no-checkout",t,r]),await ae(r,["checkout","--force","--detach",e])}async function ey(t,e,r,n="worktree",o,s){return r.length===0?[]:Hg(e,async()=>{let i=[];for(let a of r){let c=er(Gg(s),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await Wg(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=er(t,"code",a.name);n==="direct"?(Zg(p,c),console.log(`[git] code: linked ${p} \u2192 ${c} @ ${u.slice(0,10)}`)):n==="clone"?(await jR(c,u,p),console.log(`[git] code: clone ${p} \u2190 ${c} @ ${u.slice(0,10)}`)):(await Qg(c,l,p),console.log(`[git] code: worktree ${p} \u2190 ${c} @ ${u.slice(0,10)}`)),i.push({name:a.name,workspacePath:p,cachePath:c,ref:l,baseSha:u})}return i})}async function ty(t,e,r,n="worktree",o,s){if(!r||!r.cloneUrl)return null;let i=r;return Hg(e,async()=>{let a=er(Gg(s),e,"_context");console.log(`[git] context: ensure ${i.cloneUrl} @ ${i.ref} \u2192 ${a}`);try{await Wg(a,i.cloneUrl,i.ref,void 0,o)}catch(u){throw new Error(`failed to materialize context repo (${i.cloneUrl}): `+(u instanceof Error?u.message:String(u)))}let c=er(t,"context");n==="direct"?(Zg(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await Qg(a,i.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 ry(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await ae(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 s=o.split(`
|
|
817
|
+
`).map(a=>a.trim()).filter(a=>a.length>0),i=[];for(let a of s)try{let c=CR(er(r,a)).toString("base64");i.push({path:a,contentBase64:c})}catch{}return i}var Rn,Tn,Cn,ny=S(()=>{"use strict";F();Rn=new Map;Tn="CodePipe Agent",Cn="codepipe@codepartner.ee"});import{existsSync as NR,readFileSync as OR}from"node:fs";import{join as LR}from"node:path";import{parse as DR}from"yaml";function oy(t){if(!t)return!1;let e=LR(t,_l);if(!NR(e))return!1;try{let r=DR(OR(e,"utf-8"));if(!r||typeof r!="object")return!1;let n=r.steps;return!Array.isArray(n)||n.length===0?!1:n.some(o=>o!=null&&typeof o=="object"&&typeof o.run=="string"&&o.run.trim().length>0)}catch{return!1}}var _l,sy=S(()=>{"use strict";_l="knowledge/build.yaml"});import{readFileSync as MR}from"node:fs";import{join as UR}from"node:path";function iy(t){let e=UR(t,Oo),r;try{r=MR(e,"utf-8")}catch{throw new tr(`BUILD produced no ${Oo} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new tr(`${Oo} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new tr(`${Oo} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new tr(`${Oo}: "ok" must be a boolean`);let s=o.ok,a=(Array.isArray(o.steps)?o.steps:[]).flatMap(u=>{if(!u||typeof u!="object")return[];let p=u,d=typeof p.name=="string"?p.name:null,m=typeof p.exitCode=="number"?p.exitCode:null;if(d===null||m===null)return[];let f={name:d,exitCode:m};return typeof p.durationMs=="number"&&(f.durationMs=p.durationMs),[f]}),c=typeof o.logTail=="string"?BR(o.logTail):"",l={ok:s,steps:a,logTail:c};if(typeof o.failedStep=="string"&&o.failedStep)l.failedStep=o.failedStep;else if(!s){let u=a.find(p=>p.exitCode!==0);u&&(l.failedStep=u.name)}return l}function BR(t){let e=Buffer.from(t,"utf-8");return e.length<=jl?t:`\u2026 [${e.length-jl} bytes elided] \u2026
|
|
818
|
+
`+e.subarray(e.length-jl).toString("utf-8")}var jl,tr,Oo,ay=S(()=>{"use strict";jl=8*1024,tr=class extends Error{},Oo="meta/build-result.json"});import{readFileSync as FR}from"node:fs";import{join as KR}from"node:path";function ly(t){let e=KR(t,An),r;try{r=FR(e,"utf-8")}catch{throw new Ut(`code review produced no ${An} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(c){throw new Ut(`${An} is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(!n||typeof n!="object")throw new Ut(`${An} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new Ut(`${An}: "approved" must be a boolean`);let s=o.approved,i=typeof o.remarks=="string"?cy(o.remarks,GR):"";if(!s&&i.trim().length===0)throw new Ut(`${An}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?cy(o.summary,HR):"";return{approved:s,remarks:i,summary:a}}function cy(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
|
|
819
|
+
\u2026 [${r.length-e} bytes elided]`}var GR,HR,Ut,An,uy=S(()=>{"use strict";GR=16*1024,HR=4*1024,Ut=class extends Error{},An="meta/review-result.json"});import{readFileSync as WR,statSync as qR}from"node:fs";import{join as dy}from"node:path";function QR(t){return t.startsWith("meta/")||ZR.has(t)}function eI(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 tI(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function py(t,e,r){let n=r?.maxBytes??YR,o=r?.totalBytes??VR,s=r?.maxCount??zR,i=e.map((f,g)=>{let h=null;try{h=qR(dy(t,f)).size}catch{}return{path:f,index:g,size:h}}),a=[...i].sort((f,g)=>{let h=w=>QR(w.path)?0:1;return h(f)!==h(g)?h(f)-h(g):(f.size??0)-(g.size??0)}),c=a.slice(0,s),l=a.slice(s).sort((f,g)=>f.index-g.index).map(f=>f.path),u=new Array(i.length),p=[],d=0;for(let f of c){let g=null;if(f.size!==null&&f.size<=n&&d+f.size<=o)try{g=WR(dy(t,f.path))}catch{}if(g!==null){d+=g.length,u[f.index]={path:f.path,contentBase64:g.toString("base64")};continue}let h=f.size===null?tI(f.path):eI(f.path,f.size,n,o),w=Buffer.from(h,"utf-8");d+=w.length,u[f.index]={path:f.path,contentBase64:w.toString("base64")},p.push({path:f.path,bytes:f.size??0})}let m=u.filter(f=>f!==void 0);if(l.length>0){let f=l.slice(0,JR),g=`# Artifacts omitted from upload
|
|
846
820
|
|
|
847
821
|
${l.length} file(s) exceeded the SANDBOX artifact count budget (${s}) and were dropped from the listing. The delivered code (git) and the build/review verdicts are unaffected. Usually this means a job left a stray tree in the workspace \u2014 throwaway copies belong in the workspace's \`scratch/\` directory, which is never uploaded.
|
|
848
822
|
|
|
849
823
|
`+f.map(h=>`- ${h}
|
|
850
824
|
`).join("")+(l.length>f.length?`
|
|
851
825
|
\u2026and ${l.length-f.length} more.
|
|
852
|
-
`:"");m.push({path:
|
|
853
|
-
${n}`.match(
|
|
854
|
-
${n}`.split(/[\s,;()[\]{}<>"'!?]+/);for(let m of c){let f=m.replace(/^[`*_]+|[`*_.:]+$/g,"");if(!f||!f.includes("/")&&!f.includes("."))continue;let g=a.get(f)??[];g.length===1&&i(g[0],
|
|
855
|
-
${n}`.match(/[A-Za-z][A-Za-z0-9_-]{3,}/g)??[]){let f=l.get(m.toLowerCase());f&&i(f,
|
|
856
|
-
${n}`),d=[];for(let[m,f]of o.events){if(m===e||!f.title)continue;let g=
|
|
857
|
-
`));let u=
|
|
826
|
+
`:"");m.push({path:XR,contentBase64:Buffer.from(g,"utf-8").toString("base64")})}return{artifacts:m,omitted:p,dropped:l}}var YR,VR,zR,XR,JR,ZR,fy=S(()=>{"use strict";YR=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),VR=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),zR=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),XR="artifacts-omitted.md",JR=500,ZR=new Set(["QUESTIONS.md","PLAN.md","SOLUTION.md","DRAFT.md","ESTIMATE.md","SOLUTION.md","diff-summary.md","review-result.md","commit-message.txt","pr-description.md"])});import{lstatSync as rI,mkdtempSync as nI,readFileSync as oI,readdirSync as hy,rmSync as my}from"node:fs";import{tmpdir as sI}from"node:os";import{join as pi,relative as iI}from"node:path";function gy(t){let e=nI(pi(sI(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>my(e,{recursive:!0,force:!0}),listFiles:()=>yy(e,e),readFile:r=>oI(pi(e,r),"utf-8"),clean:()=>{for(let r of hy(e))cI.has(r)||my(pi(e,r),{recursive:!0,force:!0})}}}function yy(t,e){let r=[];for(let n of hy(e)){let o=pi(e,n),s=rI(o);if(!s.isSymbolicLink())if(s.isDirectory()){if(e===t&&aI.has(n))continue;r.push(...yy(t,o))}else r.push(iI(t,o))}return r}var aI,cI,ky=S(()=>{"use strict";aI=new Set(["code","context","scratch",".claude"]),cI=new Set(["code","context"])});import{existsSync as mi,readFileSync as wy,readdirSync as Nl}from"node:fs";import{join as Bt}from"node:path";import{parse as lI}from"yaml";function hi(t){if(!mi(t))return[];let e=[];for(let r of Nl(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=Bt(t,r.name);r.isDirectory()?e.push(...hi(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function fi(t){try{return lI(wy(t,"utf-8"))}catch{return null}}function by(t){let e={nodes:new Map,adjacency:new Map,events:new Map,annotations:new Map,keyByEntity:new Map,orphanedEntities:new Set,empty:!0},r=(s,i,a,c)=>{e.adjacency.has(s)||e.adjacency.set(s,[]),e.adjacency.has(i)||e.adjacency.set(i,[]),e.adjacency.get(s).push({to:i,kind:a,weight:c}),e.adjacency.get(i).push({to:s,kind:a,weight:c})};for(let s of hi(Bt(t,"model/derived/structure"))){let i=Ct(fi(s));if(i.ok){for(let a of i.value.nodes)e.nodes.set(a.key,a);for(let a of i.value.edges)r(a.from,a.to,a.kind,a.weight??1)}}for(let s of[...hi(Bt(t,"model/derived/correlates")),Bt(t,"model/derived/relates.yaml")]){if(!mi(s))continue;let i=Jn(fi(s));if(i.ok)for(let a of i.value.edges)r(a.from,a.to,a.kind,a.weight??1)}let n=Bt(t,"model/facts/events");if(mi(n))for(let s of Nl(n).sort()){if(!s.endsWith(".yaml"))continue;let i=At(fi(Bt(n,s)));if(!i.ok)continue;let a=i.value;e.events.set(a.taskKey,a);let c=ge(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,ge(l),"references",1)}for(let s of hi(Bt(t,"model/facts/identity"))){let i=Zn(fi(s));if(i.ok)for(let a of i.value.entities)a.status==="orphaned"?e.orphanedEntities.add(a.entityId):e.keyByEntity.set(a.entityId,a.currentKey)}let o=Bt(t,"model/facts/annotations");if(mi(o)){for(let s of Nl(o).sort())if(s.endsWith(".md"))try{let i=wy(Bt(o,s),"utf-8"),a=/^---\n[\s\S]*?entityId:\s*(e_[0-9a-f]{8})[\s\S]*?\n---\n?([\s\S]*)$/.exec(i);a&&e.annotations.set(a[1],a[2].trim())}catch{}}return e.empty=e.nodes.size===0&&e.events.size===0,e}var $y=S(()=>{"use strict";F()});function xy(t){return new Set((t.toLowerCase().match(/[a-zа-я0-9_]{4,}/g)??[]).filter(e=>!/^\d+$/.test(e)))}function gI(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 Sy(t){let{taskKey:e,title:r,text:n,model:o}=t,s=new Map,i=(m,f)=>{(s.get(m)??0)<f&&s.set(m,f)};(o.events.has(e)||o.adjacency.has(ge(e)))&&i(ge(e),vy);for(let m of`${r}
|
|
827
|
+
${n}`.match(hI)??[]){if(m===e)continue;let f=ge(m);(o.events.has(m)||o.adjacency.has(f))&&i(f,vy)}let a=new Map;for(let m of o.nodes.keys()){let f=re(m);if(f?.level!=="code")continue;let g=f.path.slice(f.path.lastIndexOf("/")+1);for(let h of[f.path,g])a.has(h)||a.set(h,[]),a.get(h).push(m)}let c=`${r}
|
|
828
|
+
${n}`.split(/[\s,;()[\]{}<>"'!?]+/);for(let m of c){let f=m.replace(/^[`*_]+|[`*_.:]+$/g,"");if(!f||!f.includes("/")&&!f.includes("."))continue;let g=a.get(f)??[];g.length===1&&i(g[0],uI)}let l=new Map,u=(m,f)=>{let g=m.toLowerCase();!g||g.length<4||l.set(g,l.has(g)&&l.get(g)!==f?null:f)};for(let m of o.nodes.keys()){let f=re(m);if(!f)continue;let g=f.path.slice(f.path.lastIndexOf("/")+1);f.level==="code"&&u(g.replace(/\.[a-z0-9]+$/i,""),m),f.level==="component"&&u(g,m)}for(let m of`${r}
|
|
829
|
+
${n}`.match(/[A-Za-z][A-Za-z0-9_-]{3,}/g)??[]){let f=l.get(m.toLowerCase());f&&i(f,dI)}let p=xy(`${r}
|
|
830
|
+
${n}`),d=[];for(let[m,f]of o.events){if(m===e||!f.title)continue;let g=gI(p,xy(f.title));g>=fI&&d.push({key:ge(m),score:g})}return d.sort((m,f)=>f.score-m.score||(m.key<f.key?-1:1)).slice(0,mI).forEach(m=>i(m.key,pI)),s}var vy,uI,dI,pI,fI,mI,hI,Ey=S(()=>{"use strict";F();vy=1,uI=.9,dI=.7,pI=.5,fI=.15,mI=3,hI=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g});function Ry(t,e,r={}){let n=r.cutoff??mr.activationCutoff,o=r.topK??mr.topKPerNode,s=r.nodeCap??mr.nodeCap,i=new Map;for(let[l,u]of e)i.set(l,{activation:u});let a=[...e].map(([l,u])=>({key:l,activation:u})).sort((l,u)=>u.activation-l.activation||(l.key<u.key?-1:1)),c=new Set;for(;a.length>0;){a.sort((p,d)=>d.activation-p.activation||(p.key<d.key?-1:1));let l=a.shift();if(c.has(l.key)||(i.get(l.key)?.activation??0)>l.activation)continue;if(c.add(l.key),c.size>s)break;let u=[...t.adjacency.get(l.key)??[]].sort((p,d)=>d.weight-p.weight||(p.to<d.to?-1:1)).slice(0,o);for(let p of u){let d=sa[p.kind]??.3,m=l.activation*d*Math.min(p.weight,1);if(m<n)continue;let f=i.get(p.to);(!f||f.activation<m)&&(i.set(p.to,{activation:m,via:{from:l.key,kind:p.kind}}),a.push({key:p.to,activation:m}))}}return i}var Iy=S(()=>{"use strict";F()});import{existsSync as Ll,readFileSync as Ty,readdirSync as yI}from"node:fs";import{join as ki}from"node:path";function Ol(t){return Math.ceil(t.length/4)}function gi(t,e){return[...t.entries()].filter(([r])=>e(r)).map(([r,n])=>({key:r,activation:n.activation,via:n.via})).sort((r,n)=>n.activation-r.activation||(r.key<n.key?-1:1))}function rr(t){let e=re(t);return e?(e.level==="task"||e.level==="adr",e.path):t}function yi(t){if(!t.via)return"matched from the task text";let e=rr(t.via.from);switch(t.via.kind){case"touched_by":return t.via.from.startsWith("task::")?`touched by ${e}`:`touches ${e}`;case"correlates":return`co-changes with ${e}`;case"relates":return`related to ${e} (shared files)`;case"references":return`referenced by ${e}`;case"contains":return`contained in ${e}`;default:return`linked to ${e}`}}function $I(t,e){let r=/^ADR-(\d{3,4})$/.exec(e)?.[1];if(!r)return null;let n=ki(t,"adr");if(!Ll(n))return null;let o=r.padStart(4,"0");for(let s of yI(n).sort())if(!(!s.startsWith(`${o}-`)||!s.endsWith(".md")))try{return{file:`adr/${s}`,content:Ty(ki(n,s),"utf-8").trim()}}catch{return null}return null}function Cy(t){let{taskKey:e,title:r,contextDir:n,model:o,activated:s}=t,i=t.budgetTokens??mr.budgetTokens,a=[],c=0,l=E=>{let $=Ol(E);return c+$>i?!1:(a.push(E),c+=$,!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(`
|
|
831
|
+
`));let u=gi(s,E=>E.startsWith("adr::")),p=!1;for(let E of u){let $=$I(n,rr(E.key));if(!$)continue;let T=`${p?"":`
|
|
858
832
|
## Governing decisions
|
|
859
833
|
`}
|
|
860
|
-
### ${rr(E.key)} (\`${$.file}\`, ${
|
|
834
|
+
### ${rr(E.key)} (\`${$.file}\`, ${yi(E)})
|
|
861
835
|
|
|
862
836
|
${$.content}
|
|
863
|
-
`;if(!l(T))break;p=!0}let d=
|
|
837
|
+
`;if(!l(T))break;p=!0}let d=gi(s,E=>o.nodes.get(E)?.entityId!==void 0).filter(E=>o.annotations.has(o.nodes.get(E.key).entityId)),m=t.staleKeys??new Set,f=!1;for(let E of d){let $=o.nodes.get(E.key).entityId,T=o.annotations.get($),N=m.has(E.key)?" \u2014 \u26A0 the file changed since the map was built":o.orphanedEntities.has($)?" \u2014 \u26A0 the file no longer exists":"",G=`${f?"":`
|
|
864
838
|
## Why the code is shaped this way (intent notes)
|
|
865
839
|
`}
|
|
866
840
|
### \`${rr(E.key)}\`${N}
|
|
867
841
|
|
|
868
842
|
${T}
|
|
869
|
-
`;if(!l(G))break;f=!0}let g=ge(e),h=
|
|
870
|
-
> ${
|
|
843
|
+
`;if(!l(G))break;f=!0}let g=ge(e),h=gi(s,E=>E.startsWith("task::")&&E!==g).slice(0,kI),w=!1;for(let E of h){let $=o.events.get(rr(E.key));if(!$)continue;let T=[...$.files].filter(k=>!m.has(k.key)&&(!k.entityId||!o.orphanedEntities.has(k.entityId))).sort((k,M)=>(M.churn??0)-(k.churn??0)||(k.key<M.key?-1:1)).slice(0,3).map(k=>`\`${rr(k.key)}\``).join(", "),N="",G=$.links?.solution??[`tasks/${$.taskKey}/PLAN.md`,`tasks/${$.taskKey}/SOLUTION.md`].find(k=>Ll(ki(n,k)))??`tasks/${$.taskKey}/PLAN.md`,ee=ki(n,G);if(Ll(ee))try{N=`
|
|
844
|
+
> ${Ty(ee,"utf-8").trim().slice(0,bI).replace(/\n+/g," ").trim()}\u2026
|
|
871
845
|
> _(full text: \`${G}\`)_`}catch{}let C=`${w?"":`
|
|
872
846
|
## Related past tasks
|
|
873
847
|
`}
|
|
874
|
-
- **${$.taskKey}**${$.title?` \u2014 ${$.title}`:""}${$.date?` (${$.date})`:""}, ${
|
|
875
|
-
`))+
|
|
876
|
-
`))}let I=
|
|
848
|
+
- **${$.taskKey}**${$.title?` \u2014 ${$.title}`:""}${$.date?` (${$.date})`:""}, ${yi(E)}. Files: ${T||"\u2014"}.${N}`;if(!l(C))break;w=!0}let y=E=>{if(m.has(E.key))return!1;let $=o.nodes.get(E.key)?.entityId;return!$||!o.orphanedEntities.has($)},v=gi(s,E=>E.startsWith("code:")),x=v.filter(y).slice(0,wI);if(x.length>0){let E=["","## Files likely involved",""];for(let $ of x){let T=`- \`${rr($.key)}\` \u2014 ${yi($)}`;if(c+Ol(E.join(`
|
|
849
|
+
`))+Ol(T)>i)break;E.push(T)}E.length>3&&l(E.join(`
|
|
850
|
+
`))}let I=v.filter(E=>!y(E)).slice(0,10);if(I.length>0){let E=["","## Possibly stale (verify before trusting)","","These entries reference files that changed after the map was built or","no longer exist at their recorded location. Useful as history, wrong","as current fact.","",...I.map($=>`- \`${rr($.key)}\` \u2014 ${yi($)}${m.has($.key)?" (changed since the map was built)":" (file gone)"}`)];l(E.join(`
|
|
877
851
|
`))}return a.length<=1?null:a.join(`
|
|
878
852
|
`)+`
|
|
879
|
-
`}var
|
|
853
|
+
`}var kI,wI,bI,Ay=S(()=>{"use strict";F();kI=5,wI=300,bI=400});var Ny={};Fe(Ny,{assembleContextPack:()=>EI});import{createHash as vI}from"node:crypto";import{existsSync as Py,readFileSync as _y}from"node:fs";import{join as jy}from"node:path";function xI(t){return vI("sha1").update(`blob ${t.length}\0`).update(t).digest("hex")}function SI(t,e,r){let n=new Set;for(let o of e.keys()){let s=re(o);if(s?.level!=="code")continue;let i=t.nodes.get(o);if(!i?.contentHash)continue;let a=r.get(s.repo);if(!a)continue;let c=jy(a,s.path);try{if(!Py(c)){n.add(o);continue}xI(_y(c)).startsWith(i.contentHash)||n.add(o)}catch{}}return n}function EI(t){let e=by(t.contextDir);if(e.empty)return null;let r="",n=jy(t.contextDir,`tasks/${t.taskKey}/task.md`);if(Py(n))try{r=_y(n,"utf-8")}catch{r=""}let o=Sy({taskKey:t.taskKey,title:t.title,text:r,model:e});if(o.size===0)return null;let s=Ry(e,o),i=t.repoDirs?SI(e,s,t.repoDirs):new Set;return Cy({taskKey:t.taskKey,title:t.title,contextDir:t.contextDir,model:e,activated:s,staleKeys:i,...t.budgetTokens!==void 0?{budgetTokens:t.budgetTokens}:{}})}var Oy=S(()=>{"use strict";F();$y();Ey();Iy();Ay()});var Ly={};Fe(Ly,{SKILLS_DIR:()=>Dl,loadSkills:()=>DI,materializeSkills:()=>MI,renderSkillsBlock:()=>UI});import{cpSync as RI,existsSync as II,mkdirSync as TI,readFileSync as CI,readdirSync as AI}from"node:fs";import{dirname as PI,join as Pn}from"node:path";import{fileURLToPath as _I}from"node:url";import{parse as jI}from"yaml";function OI(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
|
|
880
854
|
---`,3);return r===-1?null:{yaml:e.slice(e.indexOf(`
|
|
881
855
|
`,3)+1,r),body:e.slice(e.indexOf(`
|
|
882
|
-
`,r+1)+1)}}function
|
|
883
|
-
`)}var
|
|
884
|
-
`),{dir:o,ready:r,errors:e}}function
|
|
856
|
+
`,r+1)+1)}}function LI(t,e,r){let n=[],o=[];if(!II(t))return{skills:n,errors:o};let s;try{s=AI(t,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>i.name).sort()}catch(i){return{skills:n,errors:[{source:r,error:`cannot read: ${String(i)}`}]}}for(let i of s){let a=Pn(t,i),c=`${r}/${i}`,l;try{l=CI(Pn(a,"SKILL.md"),"utf-8")}catch{o.push({source:c,error:"no SKILL.md in the directory"});continue}let u=OI(l);if(!u){o.push({source:c,error:"SKILL.md has no frontmatter block"});continue}let p;try{p=jI(u.yaml)}catch(m){o.push({source:c,error:`frontmatter is not valid YAML: ${String(m)}`});continue}let d=La({name:i,frontmatter:p,body:u.body});d.ok?n.push({...d.skill,dir:a,origin:e}):o.push({source:c,error:d.error})}return{skills:n,errors:o}}function DI(t){let e=[],r=(i,a,c)=>{let l=LI(i,a,c);return e.push(...l.errors),l.skills},n=t.sources.bundled?r(NI,"bundled","bundled"):[],o=t.sources.context&&t.contextDir?r(Pn(t.contextDir,"skills"),"context","skills"):[],s=t.sources.repo?t.repoDirs.flatMap(i=>r(Pn(i,".claude","skills"),"repo","repo")):[];return{skills:Da(n,o,s),errors:e}}function MI(t,e){if(e.length===0)return[];let r=Pn(t,Dl);TI(r,{recursive:!0});let n=[];for(let o of e)RI(o.dir,Pn(r,o.name),{recursive:!0}),n.push(`${Dl}/${o.name}`);return n}function UI(t,e=[]){let r=new Set(t.map(i=>i.name)),n=e.filter(i=>!r.has(i));if(t.length===0&&n.length===0)return"";let o=[];t.length>0&&o.push("## Skills available to you","",...t.map(i=>`- **${i.name}** \u2014 ${i.description}`),"","Only these lines are in context; a skill's steps load when you invoke it.","When one covers what you are about to do, use it: it was written down","because the obvious approach was wrong or costly.","");let s=e.filter(i=>r.has(i));return s.length>0&&o.push("**The approved plan requires this task to follow: "+s.map(i=>`\`${i}\``).join(", ")+".**","This is not a suggestion \u2014 a reviewer approved it as a requirement.",""),n.length>0&&o.push("**The plan prescribes "+n.map(i=>`\`${i}\``).join(", ")+", which is not available here.**","Proceed without it and say so in your result \u2014 do not invent the procedure.",""),o.join(`
|
|
857
|
+
`)}var Dl,NI,Dy=S(()=>{"use strict";F();Dl=".claude/skills",NI=PI(_I(import.meta.url))});var Fy={};Fe(Fy,{seedMarketplaces:()=>zI});import{spawn as BI}from"node:child_process";import{cpSync as FI,existsSync as My,mkdirSync as Uy,rmSync as Ml,symlinkSync as KI,writeFileSync as GI}from"node:fs";import{homedir as HI}from"node:os";import{join as nr}from"node:path";function By(){return nr(HI(),".codepipe-sandbox","plugins")}function YI(t){return nr(By(),"src",`${t.name}@${t.sha||"head"}`)}function Lo(t,e){return new Promise((r,n)=>{let o=BI("git",t,{cwd:e,stdio:["ignore","ignore","pipe"],env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"}}),s=[];o.stderr.setEncoding("utf-8"),o.stderr.on("data",i=>s.push(i)),o.on("error",n),o.on("close",i=>{if(i===0)return r();n(new Error(`git ${t[0]} failed (exit ${i}): ${s.join("").trim().slice(0,400)}`))})})}async function VI(t){let e=YI(t);if(My(nr(e,".claude-plugin","marketplace.json")))return e;Ml(e,{recursive:!0,force:!0}),Uy(e,{recursive:!0});let r=`https://github.com/${t.repo}.git`;if(t.sha?(await Lo(["init","--quiet"],e),await Lo(["remote","add","origin",r],e),await Lo(["fetch","--quiet","--depth","1","origin",t.sha],e),await Lo(["checkout","--quiet","FETCH_HEAD"],e)):await Lo(["clone","--quiet","--depth","1",r,e]),!My(nr(e,".claude-plugin","marketplace.json")))throw Ml(e,{recursive:!0,force:!0}),new Error("no .claude-plugin/marketplace.json \u2014 this repository is not a marketplace");return e}async function zI(t){if(t.length===0)return{dir:null,ready:[],errors:[]};let e=[],r=[],n=new Map;for(let a of t)try{n.set(a.name,await VI(a)),r.push(a)}catch(c){e.push({repo:a.repo,error:c instanceof Error?c.message:String(c)})}if(r.length===0)return{dir:null,ready:r,errors:e};let o=nr(By(),"seed",r.map(a=>`${a.name}@${a.sha||"head"}`).sort().join("_")),s=nr(o,WI);Uy(s,{recursive:!0});let i={};for(let a of r){let c=nr(s,a.name);Ml(c,{recursive:!0,force:!0}),XI(n.get(a.name),c),i[a.name]={source:{source:"github",repo:a.repo},installLocation:c,...a.sha?{commit:a.sha}:{}}}return GI(nr(o,qI),`${JSON.stringify(i,null,2)}
|
|
858
|
+
`),{dir:o,ready:r,errors:e}}function XI(t,e){try{KI(t,e,"dir")}catch{FI(t,e,{recursive:!0,filter:r=>!/(^|\/)\.git(\/|$)/.test(r)})}}var WI,qI,Ky=S(()=>{"use strict";WI="marketplaces",qI="known_marketplaces.json"});var Wy={};Fe(Wy,{loadRoles:()=>sT});import{existsSync as JI,readFileSync as ZI,readdirSync as QI}from"node:fs";import{dirname as eT,join as Hy}from"node:path";import{fileURLToPath as tT}from"node:url";import{parse as rT}from"yaml";function oT(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
|
|
885
859
|
---`,3);if(r===-1)return null;let n=e.slice(e.indexOf(`
|
|
886
860
|
`,3)+1,r),o=e.indexOf(`
|
|
887
|
-
`,r+1);return{yaml:n,body:o===-1?"":e.slice(o+1)}}function
|
|
888
|
-
`),n=t.refs.length>0&&e?["","## Read these first","",...t.refs.map(o=>`- \`${
|
|
861
|
+
`,r+1);return{yaml:n,body:o===-1?"":e.slice(o+1)}}function Gy(t,e,r){let n=[],o=[];if(!JI(t))return{roles:n,errors:o};let s;try{s=QI(t).sort()}catch(i){return{roles:n,errors:[{file:r,error:`cannot read: ${String(i)}`}]}}for(let i of s){if(!i.endsWith(".md"))continue;let a=`${r}/${i}`,c;try{c=ZI(Hy(t,i),"utf-8")}catch(d){o.push({file:a,error:`cannot read: ${String(d)}`});continue}let l=oT(c);if(!l){o.push({file:a,error:"missing frontmatter block (--- \u2026 ---) at the top of the file"});continue}let u;try{u=rT(l.yaml)}catch(d){o.push({file:a,error:`frontmatter is not valid YAML: ${String(d)}`});continue}let p=Aa({name:i.slice(0,-3),frontmatter:u,body:l.body,origin:e});p.ok?n.push(p.role):o.push({file:a,error:p.error})}return{roles:n,errors:o}}function sT(t){let e=Gy(nT,"bundled","bundled"),r=t?Gy(Hy(t,"roles"),"project","roles"):{roles:[],errors:[]};return{roles:Pa(e.roles,r.roles),errors:[...e.errors,...r.errors]}}var nT,qy=S(()=>{"use strict";F();nT=eT(tT(import.meta.url))});var Yy={};Fe(Yy,{ROLE_AGENTS_DIR:()=>Bl,materializeRoleAgents:()=>lT,renderRolesBlock:()=>uT});import{mkdirSync as iT,writeFileSync as aT}from"node:fs";import{join as Ul}from"node:path";function cT(t,e){let r=["---",`name: ${t.name}`,`description: ${t.description}`,...t.model?[`model: ${t.model}`]:[],"---",""].join(`
|
|
862
|
+
`),n=t.refs.length>0&&e?["","## Read these first","",...t.refs.map(o=>`- \`${Ul(e,o)}\``),"","They are this role's curated context. If one is missing, say so in a line and continue \u2014","its absence is not an error.",""].join(`
|
|
889
863
|
`):"";return`${r}${t.body}
|
|
890
|
-
${n}`}function
|
|
864
|
+
${n}`}function lT(t,e,r,n){let o=_a(e,r);if(o.length===0)return{roles:[],files:[]};let s=Ul(t,Bl);iT(s,{recursive:!0});let i=[];for(let a of o)aT(Ul(s,`${a.name}.md`),cT(a,n)),i.push(`${Bl}/${a.name}.md`);return{roles:o,files:i}}function uT(t,e){return t.roles.length===0?"":["## The panel \u2014 run these critics first","","This project reviews through a panel of roles. Each is available to you as a","subagent with its own narrow view and its own reading list:","",t.roles.map(n=>`- **${n.name}** \u2014 ${n.description}`).join(`
|
|
891
865
|
`),"","Delegate to **every** role above, one at a time, giving each the change under","review. Then do your own job on what comes back:","",`1. Save each role's findings verbatim as \`${e}/<role>.md\`.`,"2. **Deduplicate.** Two roles reporting the same defect is one finding, not two.","3. **Filter.** A finding earns a round-trip only if it is a real defect, a"," regression or a convention the project actually enforces. Taste-level notes"," go in the summary, never in the remarks.","4. **Decide.** The verdict is yours, not a vote: a role can be wrong, and you"," are the one who read the code. When you overrule a role, say why in the"," summary.","","A role that returns nothing is a normal outcome \u2014 do not manufacture findings","to justify the panel.",""].join(`
|
|
892
|
-
`)}var
|
|
866
|
+
`)}var Bl,Vy=S(()=>{"use strict";F();Bl=".claude/agents"});var Xy={};Fe(Xy,{COUNCIL_ANSWER_PATH:()=>zy,readCouncilVerdict:()=>fT});import{readFileSync as dT}from"node:fs";import{join as pT}from"node:path";function fT(t){let e;try{e=dT(pT(t,zy),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var zy,Jy=S(()=>{"use strict";zy="meta/council-answer.json"});var Qy={};Fe(Qy,{QUEUE_PLAN_PATH:()=>Zy,readQueuePlan:()=>gT});import{readFileSync as mT}from"node:fs";import{join as hT}from"node:path";function gT(t){let e;try{e=mT(hT(t,Zy),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var Zy,ek=S(()=>{"use strict";Zy="meta/queue-plan.json"});import{mkdirSync as tk,readFileSync as wi,readdirSync as yT,writeFileSync as rk}from"node:fs";import{homedir as kT}from"node:os";import{dirname as wT,join as Et}from"node:path";function $T(t){let e=Buffer.from(t,"utf-8");if(e.length<=bi)return t;let r=Math.floor(bi/4),n=bi-r,o=e.subarray(0,r).toString("utf-8"),s=e.subarray(e.length-n).toString("utf-8"),i=e.length-r-n;return`${o}
|
|
893
867
|
|
|
894
|
-
\u2026 [${i} bytes elided \u2014 log capped at ${
|
|
868
|
+
\u2026 [${i} bytes elided \u2014 log capped at ${bi} bytes for upload] \u2026
|
|
895
869
|
|
|
896
|
-
${s}`}function
|
|
870
|
+
${s}`}function vT(){let t=[],e=!1,r=null,n=s=>{if(r){let i=r;r=null,i({value:s,done:!1})}else t.push(s)},o=()=>{if(r){let s=r;r=null,s({value:void 0,done:!0})}};return{push(s){e||n(s)},finalize(){e||(n({kind:"finalize"}),e=!0)},close(){e=!0,t.length=0,o()},iterable:{[Symbol.asyncIterator](){return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):e?Promise.resolve({value:void 0,done:!0}):new Promise(s=>{r=s})}}}}}}async function Do(t={}){let e=je(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,n=e.sandboxId,o=e.llm,s=lg(t.profile,e.sandboxId,!!X("SANDBOX_CONFIG")),i=Et(kT(),".codepipe","logs"),a=cs("SANDBOX_LOG",s,i);if(a.enabled){let C=new tn(a);ls(C),console.log(`[log] file logging \u2192 ${C.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${Ke} (protocol ${ct})`),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=Tg();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let u=new bn(e.hubUrl,e.token),p=!1,d=new AbortController,m=new Map,f=null,g=null,h=!1,w=()=>{let C=u.openControlSocket();return f=C,C.on("open",()=>{console.log("[ws] connected");let k={type:"sandbox_hello",platformVersion:Ke,protocolVersion:ct};C.send(JSON.stringify(k))}),C.on("message",k=>{let M=k.toString("utf-8"),P=null;try{let H=JSON.parse(M);H&&typeof H=="object"&&(P=H)}catch{}if(P&&P.type==="hello"){let H=P;g=Yn(H.protocolVersion);let Y=g?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${H.platformVersion} (protocol ${H.protocolVersion}) \u2014 ${Y}`),g&&(h=!1);return}if(P&&P.type==="pause_job"){let H=typeof P.jobId=="string"?P.jobId:"",Y=H?m.get(H):void 0;Y?(console.warn(`[ws] pause_job ${H} \u2014 aborting agent`),Y.paused=!0,Y.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(P&&(P.type==="chat_user_message"||P.type==="chat_finalize")){let H=typeof P.jobId=="string"?P.jobId:"",Y=H?m.get(H):void 0;if(Y?.chatInbox)if(P.type==="chat_user_message"){let oe=typeof P.text=="string"?P.text:"";oe.trim()&&Y.chatInbox.push({kind:"user",text:oe})}else Y.chatInbox.finalize();else console.log(`[ws] ${String(P.type)} ${H} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${M}`)}),C.on("close",(k,M)=>{console.log(`[ws] closed code=${k} reason=${M?.toString()||""}`),f===C&&(f=null),!p&&setTimeout(w,2e3)}),C.on("error",k=>console.warn(`[ws] error: ${k.message}`)),C},y=w(),v=async C=>{for(;!p;){if(g===!1){h||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${Ke}, protocol ${ct}) \u2014 not claiming jobs until versions align.`),h=!0),await new Promise(k=>setTimeout(k,5e3));continue}try{let k=await u.claim(d.signal,C);if(k.status===204)continue;if(k.status===401){console.error("[claim] 401 unauthorized \u2014 the HUB does not know this worker registration. It was removed; re-register with `codepipe up --reregister` (or `codepipe worker register --force`). exiting."),process.exitCode=1,p=!0;break}if(!k.ok){console.warn(`[claim:${C}] ${k.status} \u2014 backoff 5s`),await new Promise(P=>setTimeout(P,5e3));continue}let M=await k.json();await x(u,M)}catch(k){if(d.signal.aborted)break;let M=k instanceof Error?k.message:String(k);console.warn(`[claim:${C}] error: ${M} \u2014 backoff 5s`),await new Promise(P=>setTimeout(P,5e3))}}};async function x(C,k){let M={abort:new AbortController,paused:!1};k.role==="chat"&&(M.chatInbox=vT()),m.set(k.jobId,M);let P=!1,H=null,Y=null,oe=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),Ve=async()=>{try{await C.heartbeat(k.jobId)==="claim_lost"&&(P=!0,console.warn(`[job] ${k.jobId} claim lost \u2014 HUB sweeper took it`))}catch(K){let Se=K instanceof Error?K.message:String(K);console.warn(`[job] ${k.jobId} heartbeat error: ${Se}`)}};Ve();let ze=setInterval(()=>{Ve()},oe),_=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 U=[],D=null,z=400,O=25,b=500,R=()=>{if(D&&(clearTimeout(D),D=null),U.length===0)return;let K=U.splice(0,U.length),Se=f;if(!Se||Se.readyState!==Se.OPEN)return;let It={type:"agent_activity",jobId:k.jobId,taskId:k.taskId,projectId:k.projectId,role:k.role,phase:k.phase,events:K};try{Se.send(JSON.stringify(It))}catch{}},B=K=>{U.push(K),U.length>b&&U.shift(),U.length>=O?R():D||(D=setTimeout(R,z))},J=k.role==="analysis"&&k.taskId.startsWith("draft::")?k.taskId.slice(7):null,Pe=new Set,st=null;try{if(!c){P||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:_,finishedAt:new Date().toISOString()});return}if(!Sg(o,k.provider??null)){P||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${k.provider??"claude"}"`},startedAt:_,finishedAt:new Date().toISOString()});return}let K=gy(k.jobId);console.log(`[job] ${k.jobId} workspace=${K.dir}`);let Se=I(k,r);H=Se.gitCreds,Y=Se.contextGitCreds;let It=H?.env,su=Se.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:Se.claudeOauthToken}:void 0,it=[],Xe=null,Mi=null;try{let j=k.role==="build"?"clone":"worktree";it=await ey(K.dir,k.projectId,k.projectRepos,j,It,n);let L=await ty(K.dir,k.projectId,k.contextRepo,"worktree",It,n);Mi=L,Xe=L?.workspacePath??null}catch(j){let L=j instanceof Error?j.message:String(j);console.warn(`[job] ${k.jobId} materialize failed: ${L}`),P||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${L}`},startedAt:_,finishedAt:new Date().toISOString()}),K.dispose();return}let Kn=k.model;k.role==="build"&&k.modelDiscovery&&!oy(Xe)&&(Kn=k.modelDiscovery,console.log(`[job] ${k.jobId} BUILD discovery (no steps in ${_l}) \u2014 model=${Kn}`));let iu=async()=>{if(!k.deliveries||k.deliveries.length===0)return[];let j=k.contextRepo?.cloneUrl;if(!j||!It)throw new Error(j?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let L=[];for(let Q of k.deliveries){let Z=it.find(ie=>ie.name===Q.name);if(Z){if(k.role==="implement"&&Q.baseSha&&Q.baseSha!==Z.baseSha){let ie=await Jg(Z,Q.deliveryRef,Q.deliverySha,Q.baseSha,j,It);console.log(`[job] ${k.jobId} ${Z.name}: base moved ${Q.baseSha.slice(0,10)} \u2192 ${Z.baseSha.slice(0,10)} \u2014 re-applied delivery ${Q.deliverySha.slice(0,10)} (${ie.length} conflicted file(s))`),ie.length>0&&L.push(`- **${Z.name}**:`,...ie.map(Je=>` - \`${Je}\``));continue}await Xg(Z,Q.deliveryRef,Q.deliverySha,j,It),console.log(`[job] ${k.jobId} ${Z.name}: checked out delivery ${Q.deliverySha.slice(0,10)} for ${k.role}`)}}return L},Ui=[];if(k.role==="build"||k.role==="implement"||k.role==="code-review")try{Ui=await iu()}catch(j){let L=j instanceof Error?j.message:String(j);console.warn(`[job] ${k.jobId} delivery checkout failed: ${L}`),P||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${L}`},startedAt:_,finishedAt:new Date().toISOString()}),K.dispose();return}let Bi=k.role==="resolve-conflict"?k.metadata?.taskBranchByRepo??{}:{},au="";if(k.role==="resolve-conflict"){if(!it.some(j=>Bi[j.name])){let j="resolve-conflict job carries no task branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${k.jobId} ${j}`),P||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:j},startedAt:_,finishedAt:new Date().toISOString()}),K.dispose();return}try{let j=[];for(let L of it){let Q=Bi[L.name];if(!Q)continue;let Z=await Pl(L,Q,It);console.log(`[job] ${k.jobId} ${L.name}: merged ${Q} into ${L.ref} \u2014 ${Z.length} conflicted file(s)`),Z.length>0?j.push(`- **${L.name}**:`,...Z.map(ie=>` - \`${ie}\``)):j.push(`- **${L.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}au=`
|
|
897
871
|
|
|
898
872
|
## Conflicts to resolve
|
|
899
873
|
|
|
900
874
|
`+(j.length>0?j.join(`
|
|
901
875
|
`):"(no task branches to merge)")+`
|
|
902
|
-
`}catch(j){let L=j instanceof Error?j.message:String(j);console.warn(`[job] ${k.jobId} conflict merge failed: ${L}`),P||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${L}`},startedAt:_,finishedAt:new Date().toISOString()}),K.dispose();return}}let
|
|
876
|
+
`}catch(j){let L=j instanceof Error?j.message:String(j);console.warn(`[job] ${k.jobId} conflict merge failed: ${L}`),P||await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${L}`},startedAt:_,finishedAt:new Date().toISOString()}),K.dispose();return}}let Fi=null;if(k.contextPack&&Xe)try{let{assembleContextPack:j}=await Promise.resolve().then(()=>(Oy(),Ny)),L=j({contextDir:Xe,taskKey:String(k.metadata?.trackerIssueKey??k.taskId.split(":")[1]??""),title:String(k.metadata?.taskTitle??""),repoDirs:new Map(it.map(Q=>[Q.name,Q.workspacePath]))});L?(tk(Et(K.dir,"meta"),{recursive:!0}),rk(Et(K.dir,"meta","context-pack.md"),L),Fi=L,console.log(`[job] ${k.jobId} context pack: ${L.length} chars \u2192 meta/context-pack.md`)):console.log(`[job] ${k.jobId} context pack: model empty or no signal \u2014 skipped`)}catch(j){let L=j instanceof Error?j.message:String(j);console.warn(`[job] ${k.jobId} context pack failed (non-fatal): ${L}`)}let cu="",qo=null,Ki=null;try{let{loadSkills:j,materializeSkills:L,renderSkillsBlock:Q}=await Promise.resolve().then(()=>(Dy(),Ly)),Z=k.skills??{bundled:!0,context:!0,repo:!0},ie=j({contextDir:Xe,repoDirs:it.map(Ze=>Ze.workspacePath),sources:Z});for(let Ze of ie.errors)console.warn(`[job] ${k.jobId} skill ${Ze.source}: ${Ze.error}`);let Je=L(K.dir,ie.skills),pe=["implement","rework","testing"].includes(k.role)?Ua(Ma(T(Xe,k.taskId))):[];cu=Q(ie.skills,pe),Je.length>0&&console.log(`[job] ${k.jobId} skills: ${ie.skills.map(Ze=>Ze.name).join(", ")}`);let{parseMarketplaces:Oe,enabledPluginsSetting:Ur}=await Promise.resolve().then(()=>(F(),Rd)),{sources:Br,errors:Hn}=Oe(Z.marketplaces??[]);for(let Ze of Hn)console.warn(`[job] ${k.jobId} marketplace ${Ze}`);if(Br.length>0&&(Z.plugins??[]).length>0){let{seedMarketplaces:Ze}=await Promise.resolve().then(()=>(Ky(),Fy)),Fr=await Ze(Br);for(let te of Fr.errors)console.warn(`[job] ${k.jobId} marketplace ${te.repo}: ${te.error}`);let{enabled:Kr,unknown:Gr}=Ur(Z.plugins??[],Fr.ready);for(let te of Gr)console.warn(`[job] ${k.jobId} plugin ${te}: no such marketplace in this project`);Fr.dir&&Object.keys(Kr).length>0&&(qo=Fr.dir,Ki={enabledPlugins:Kr},console.log(`[job] ${k.jobId} plugins: ${Object.keys(Kr).join(", ")}`))}}catch(j){let L=j instanceof Error?j.message:String(j);console.warn(`[job] ${k.jobId} skills unavailable (non-fatal): ${L}`)}let lu="";if(["code-review","council","analyze","testing"].includes(k.role))try{let{loadRoles:j}=await Promise.resolve().then(()=>(qy(),Wy)),{materializeRoleAgents:L,renderRolesBlock:Q}=await Promise.resolve().then(()=>(Vy(),Yy)),Z=j(Xe);for(let Oe of Z.errors)console.warn(`[job] ${k.jobId} role ${Oe.file}: ${Oe.error}`);let ie=k.role==="council"?"council":k.role==="analyze"?"plan_review":"code_review",Je=k.role==="council"?"council":k.role==="analyze"?"plan-review":k.role==="testing"?"testing":"code-review",pe=L(K.dir,Z.roles,ie,Xe);lu=Q(pe,Je),console.log(`[job] ${k.jobId} review panel: ${pe.roles.length>0?pe.roles.map(Oe=>Oe.name).join(", "):"(no roles)"}`)}catch(j){let L=j instanceof Error?j.message:String(j);console.warn(`[job] ${k.jobId} review panel unavailable (non-fatal): ${L}`)}let Uw=Ui.length>0?`
|
|
903
877
|
|
|
904
878
|
## Base branch moved \u2014 conflicts to resolve
|
|
905
879
|
|
|
906
880
|
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:
|
|
907
881
|
|
|
908
|
-
`+
|
|
882
|
+
`+Ui.join(`
|
|
909
883
|
`)+`
|
|
910
|
-
`:"",
|
|
911
|
-
`));L&&console.log(`[debug] ${k.jobId} agent request \u2192 ${L}`)}J&&(st=setInterval(()=>{let L=f;if(!L||L.readyState!==L.OPEN)return;let Q;try{Q=
|
|
884
|
+
`:"",uu=N($(k.prompt,it,Xe),Xe,k.taskId).replace(/\{\{rolesBlock\}\}/g,lu).replace(/\{\{skillsBlock\}\}/g,cu)+au+Uw,Gn=[...it.map(j=>j.workspacePath),...Xe?[Xe]:[]];if(Gn.length>0&&console.log(`[job] ${k.jobId} --add-dir: ${Gn.join(", ")}`),Ng("agent-request")){let j=ai($n(k.metadata??{})),L=Og(k.projectId,k.jobId,"agent-request",[`# Agent request \u2014 job ${k.jobId}`,"",`- project: ${k.projectId}`,`- task: ${k.taskId}`,`- role: ${k.role}`,`- model: ${Kn??"(backend default)"}`,`- add-dirs:${Gn.length>0?"":" (none)"}`,...Gn.map(Q=>` - ${Q}`),"","## Append-system-prompt (language directive)","","```",j,"```","","## Prompt","",uu,"",...Fi?["## Context pack (meta/context-pack.md)","",Fi]:["## Context pack","","(not generated for this job)"],""].join(`
|
|
885
|
+
`));L&&console.log(`[debug] ${k.jobId} agent request \u2192 ${L}`)}J&&(st=setInterval(()=>{let L=f;if(!L||L.readyState!==L.OPEN)return;let Q;try{Q=yT(Et(K.dir,"drafts")).filter(Z=>Z.endsWith(".json")).sort()}catch{return}for(let Z of Q){if(Pe.has(Z))continue;if(Pe.size>=Wa)break;let ie;try{let pe=JSON.parse(wi(Et(K.dir,"drafts",Z),"utf-8")),Oe=typeof pe.localRef=="string"?pe.localRef:"",Ur=typeof pe.title=="string"?pe.title:"",Br=typeof pe.body=="string"?pe.body:"";if(!Oe||!Ur)continue;ie={localRef:Oe,title:Ur,body:Br,...pe.isEpic===!0?{isEpic:!0}:{},...Array.isArray(pe.links)?{links:pe.links}:{}}}catch{continue}Pe.add(Z);let Je={type:"child_draft",jobId:k.jobId,projectId:k.projectId,draftId:J,child:ie};try{L.send(JSON.stringify(Je))}catch{}}},1500));try{let j={workspaceDir:K.dir,role:k.role,prompt:uu,addDirs:Gn,metadata:k.metadata??{},...Kn?{model:Kn}:{},...su||qo?{env:{...su??{},...qo?{CLAUDE_CODE_PLUGIN_SEED_DIR:qo}:{}}}:{},...Ki?{settings:Ki}:{},signal:M.abort.signal,onActivity:B},L=M.chatInbox?await c.run({...j,interactive:{inbox:M.chatInbox.iterable}}):await Ag(c,j,{jobId:k.jobId,policy:l,onBeforeRetry:async()=>{K.clean();for(let te of it)try{await qg(te);let $e=Bi[te.name];k.role==="resolve-conflict"&&$e&&await Pl(te,$e,It)}catch($e){let Wn=$e instanceof Error?$e.message:String($e);console.warn(`[job] ${k.jobId} worktree reset failed (${te.name}): ${Wn}`)}try{await iu()}catch(te){let $e=te instanceof Error?te.message:String(te);console.warn(`[job] ${k.jobId} delivery re-checkout failed: ${$e}`)}},aborted:()=>P||M.paused}),Q=[];if(bT.has(k.role)&&it.length>0){let te=k.metadata??{},$e=typeof te.commitMessage=="string"?te.commitMessage:`${k.taskId}: changes`,Wn=k.contextRepo?.cloneUrl,du=Y?.env;if(!Wn||!du)throw new Error("delivery requested but "+(Wn?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let Bw=k.taskId.includes(":")?k.taskId.slice(k.taskId.indexOf(":")+1):k.taskId;for(let Tt of it){let qn=await Yg(Tt,$e);if(!qn){console.log(`[job] ${k.jobId} ${Tt.name}: no changes \u2014 no delivery`);continue}let Gi=`codepipe/deliveries/${Bw}/${k.jobId}/${Tt.name}`;await Vg(Tt,qn,Gi,Wn,du),Q.push({name:Tt.name,deliveryRef:Gi,deliverySha:qn,baseSha:Tt.baseSha}),console.log(`[job] ${k.jobId} ${Tt.name}: delivered ${qn.slice(0,10)} \u2192 ${Gi}`);let pu=await zg(Tt,qn);if(pu.trim().length>0){let Fw=Et("display",`${Tt.name}.diff`),fu=Et(K.dir,Fw);tk(wT(fu),{recursive:!0}),rk(fu,pu)}}}if(k.role==="resolve-conflict"&&Q.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's SOLUTION.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let Z;k.role==="build"&&(Z=iy(K.dir),console.log(`[job] ${k.jobId} build verdict: ok=${Z.ok}`+(Z.failedStep?` failedStep=${Z.failedStep}`:"")));let ie;k.role==="code-review"&&(ie=ly(K.dir),console.log(`[job] ${k.jobId} review verdict: approved=${ie.approved}`));let Je;if(k.role==="council"){let{readCouncilVerdict:te}=await Promise.resolve().then(()=>(Jy(),Xy));Je=te(K.dir)??void 0,console.log(`[job] ${k.jobId} council: ${Je?"answered":"no verdict \u2014 task stops for a human"}`)}let pe;if(k.role==="testing"){try{let te=wi(Et(K.dir,"meta","test-result.json"),"utf-8");pe=JSON.parse(te)}catch{pe=void 0}console.log(`[job] ${k.jobId} test verdict: ${pe?"written":"none \u2014 proceeding to the PR"}`)}let Oe;if(k.role==="observer"){let{readQueuePlan:te}=await Promise.resolve().then(()=>(ek(),Qy));Oe=te(K.dir)??void 0,console.log(`[job] ${k.jobId} queue plan: ${Oe?"produced":"none \u2014 batch keeps the staged order"}`)}let Ur=L.artifactPaths.length>0?L.artifactPaths:K.listFiles(),Br=Array.from(new Set(Ur)),Hn;if(Mi)try{let te=k.role==="index"?["adr/SOURCES.md"]:k.role==="backfill"?["adr"]:[],$e=await ry(Mi,te);$e.length>0&&(Hn=$e,console.log(`[job] ${k.jobId} captured ${$e.length} knowledge file(s) for Context Repo`))}catch(te){let $e=te instanceof Error?te.message:String(te);console.warn(`[job] ${k.jobId} knowledge capture failed (non-fatal): ${$e}`)}let{artifacts:Ze,omitted:Fr,dropped:Kr}=py(K.dir,Br);for(let te of Fr)console.warn(`[job] ${k.jobId} artifact ${te.path} (${te.bytes} bytes) exceeded upload budget \u2014 content omitted`);Kr.length>0&&console.warn(`[job] ${k.jobId} artifact listing truncated: ${Kr.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let Gr={jobId:k.jobId,status:"succeeded",artifacts:Ze,...Hn?{contextWrites:Hn}:{},...Q.length>0?{deliveries:Q}:{},log:$T(L.log),startedAt:_,finishedAt:new Date().toISOString(),usage:L.usage,...L.rateLimit?{rateLimit:L.rateLimit}:{},...Z?{build:Z}:{},...ie?{review:ie}:{},...Oe!==void 0?{queuePlan:Oe}:{},...Je!==void 0?{council:Je}:{},...pe!==void 0?{test:pe}:{}};if(P||M.paused)console.warn(`[job] ${k.jobId} skipping result upload \u2014 ${M.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await C.submitResult(Gr),console.log(`[job] ${k.jobId} done \u2014 uploaded ${Gr.artifacts.length} artifact(s):`);for(let te of Gr.artifacts){let $e=Buffer.from(te.contentBase64,"base64").length;console.log(` \xB7 ${te.path} (${$e} bytes)`)}Gr.artifacts.length===0&&console.warn(`[job] ${k.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(j){let L=j instanceof Error?j.message:String(j);if(M.paused)console.log(`[job] ${k.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(P)console.warn(`[job] ${k.jobId} failed after claim lost (${L}) \u2014 skipping result upload`);else{let Q=Cg(j),Z=j instanceof tr,ie=j instanceof Ut;console.warn(Q?`[job] ${k.jobId} failed: ${L} (Claude auth \u2014 token invalid/expired)`:Z?`[job] ${k.jobId} failed: ${L} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:ie?`[job] ${k.jobId} failed: ${L} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${k.jobId} failed: ${L}`),await C.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:L},startedAt:_,finishedAt:new Date().toISOString(),...Q?{authError:!0}:{},...Z?{buildInconclusive:!0}:{},...ie?{reviewInconclusive:!0}:{}})}}finally{K.dispose()}}finally{clearInterval(ze),st&&clearInterval(st),R(),M.chatInbox?.close(),m.delete(k.jobId),H?.cleanup(),Y?.cleanup()}}function I(C,k){if(!C.credBundle)return{gitCreds:null,contextGitCreds:null};if(!k)return console.warn(`[job] ${C.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let M;try{M=JSON.parse(un(k,C.credBundle).toString("utf-8"))}catch(oe){return console.warn(`[job] ${C.jobId} failed to open credBundle: ${oe instanceof Error?oe.message:String(oe)}`),{gitCreds:null,contextGitCreds:null}}let P=Cl(M);P&&console.log(`[job] ${C.jobId} cred bundle opened \u2014 git creds configured`);let H=Ug(M,C.contextRepo.cloneUrl),Y={gitCreds:P,contextGitCreds:H};return M.claudeOauthToken&&(Y.claudeOauthToken=M.claudeOauthToken),Y}function E(C,k){return C.split(`
|
|
912
886
|
`).map(M=>k+M).join(`
|
|
913
|
-
`)}function $(C,k,M){let P=k[0]?.workspacePath??"";return C.replace(/\{\{codeDir\}\}/g,P).replace(/\{\{codeRoot\}\}/g,P?P.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,M??"")}function T(C,k){let M=k.includes("::")?"":k.split(":",2)[1]??"";if(!C||!M)return"";for(let P of["PLAN.md","SOLUTION.md"])try{return
|
|
914
|
-
[${C}] shutting down`),d.abort();let k=[...m.keys()];for(let H of m.values())H.abort.abort();let M=new AbortController,P=setTimeout(()=>M.abort(),3e3);(async()=>(await Promise.all(k.map(async H=>{try{await u.releaseJob(H,`sandbox ${C}`,M.signal),console.log(`[${C}] released job ${H}`)}catch(Y){let oe=Y instanceof Error?Y.message:String(Y);console.warn(`[${C}] release failed: ${oe} (sweeper will reclaim)`)}})),clearTimeout(P),y.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>G("SIGINT")),process.on("SIGTERM",()=>G("SIGTERM"));let ee=[
|
|
915
|
-
${e}`);let r=await
|
|
887
|
+
`)}function $(C,k,M){let P=k[0]?.workspacePath??"";return C.replace(/\{\{codeDir\}\}/g,P).replace(/\{\{codeRoot\}\}/g,P?P.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,M??"")}function T(C,k){let M=k.includes("::")?"":k.split(":",2)[1]??"";if(!C||!M)return"";for(let P of["PLAN.md","SOLUTION.md"])try{return wi(Et(C,"tasks",M,P),"utf-8")}catch{}return""}function N(C,k,M){let P=C,H=M.includes("::")?"":M.split(":",2)[1]??"",Y=oe=>{if(!k||!H)return"";try{return wi(Et(k,"tasks",H,oe),"utf-8").trim()}catch{return""}};if(P.includes("{{planMd}}")||P.includes("{{solutionMd}}")){let oe=Y("PLAN.md")||Y("SOLUTION.md")||"(PLAN.md missing \u2014 proceed from the task description)";P=P.replace(/\{\{planMd\}\}/g,()=>oe),P=P.replace(/\{\{solutionMd\}\}/g,()=>oe)}if(P.includes("{{taskDescription}}")){let oe=Y("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";P=P.replace(/\{\{taskDescription\}\}/g,()=>oe)}return P}let G=C=>{if(p)return;p=!0,console.log(`
|
|
888
|
+
[${C}] shutting down`),d.abort();let k=[...m.keys()];for(let H of m.values())H.abort.abort();let M=new AbortController,P=setTimeout(()=>M.abort(),3e3);(async()=>(await Promise.all(k.map(async H=>{try{await u.releaseJob(H,`sandbox ${C}`,M.signal),console.log(`[${C}] released job ${H}`)}catch(Y){let oe=Y instanceof Error?Y.message:String(Y);console.warn(`[${C}] release failed: ${oe} (sweeper will reclaim)`)}})),clearTimeout(P),y.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>G("SIGINT")),process.on("SIGTERM",()=>G("SIGTERM"));let ee=[v("implementation")];e.planningLane!==!1?ee.push(v("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(ee)}var bi,bT,nk=S(()=>{"use strict";F();ot();Xa();Eg();ci();Pg();Lg();Le();ii();Bg();Sl();ny();sy();ay();uy();fy();ky();bi=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),bT=new Set(["implement","resolve-conflict"])});var _n=S(()=>{"use strict";dg();nk();ii()});import{cancel as xT,isCancel as sk,log as qe,password as ST,text as ET}from"@clack/prompts";function RT(t){return sk(t)&&(xT("aborted"),process.exit(1)),typeof t=="string"?t:""}function ik(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function IT(t){let e=cc({redirectUri:ac,challenge:t.challenge,state:t.state});qe.message(`Open this URL, approve the access, and paste the code shown:
|
|
889
|
+
${e}`);let r=await ET({message:"Authorization code \u2014 blank to skip"});if(sk(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=jp(r,t.state);return await lc({code:n,verifier:t.verifier,state:t.state,redirectUri:ac})}catch(n){return qe.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function TT(t){if(Va()?.claude?.oauthToken&&!t.farm)return qe.message("Claude: this machine already has a shared OAuth token \u2014 the project will use it (set a project-specific one later with `codepipe login`)."),"";if(process.env.CODEPIPE_CLAUDE_AUTOLOGIN!=="1"||!process.stdout.isTTY)return null;qe.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=ms(),n;try{n=await Np({...r,openUrl:vr,log:s=>qe.message(s)})}catch(s){qe.warn(`Browser sign-in didn't complete (${s instanceof Error?s.message:String(s)}) \u2014 trying the code-paste fallback.`);let i=await IT(r);if(i===null)return null;n=i}let o=await Nt(n.oauthToken);return o==="invalid"?(qe.warn("Claude rejected the obtained token (401) \u2014 falling back to manual entry."),null):(qe.success(`Claude: logged in \u2014 ${ik(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function ak(t){qe.message(`Claude \u2014 the pipeline's agents run on your Claude subscription.
|
|
916
890
|
In another terminal:
|
|
917
891
|
1. install Claude Code \u2014 https://claude.com/claude-code
|
|
918
892
|
2. run \`claude setup-token\`
|
|
919
893
|
3. paste the token it prints (starts with sk-ant-) below`+(t.farm?`
|
|
920
|
-
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=rC(await eC({message:"Claude OAuth token \u2014 blank to skip"})).trim();if(!e)return qe.warn(t.farm?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"";e.startsWith("sk-ant-")||qe.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`.");let r=await Nt(e);return r==="invalid"?(qe.warn("Claude refused this token \u2014 it cannot run a job (expired, or minted without the inference scope). Run `claude setup-token` again and paste the new one."),Bk(t)):(qe.success(`Claude: ${Uk(e)} \u2014 ${r==="valid"?"verified":"check inconclusive, saved"}.`),e)}var Fk,Kk=v(()=>{"use strict";hs();nn();de();lc();Fk={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:oC,promptManual:Bk,validate:Nt}});function Gk(t){return Fk}async function Hk(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var Wk=v(()=>{"use strict";Kk()});async function Nn(t,e,r){return e.host==="github"?iC(t,e,r):e.host==="gitlab"?fC(t,e,r):hC(t,e,r)}async function qk(t,e,r={}){let n=r.explain??!0,o=`${t.owner}/${t.name} not found on ${t.host}`;try{if(t.host==="github")return e.githubToken?(await sr(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Yk(e.githubToken,t):o}:{found:"unknown",detail:"no GitHub token \u2014 existence not checked"};if(t.host==="gitlab"){if(!e.gitlabToken)return{found:"unknown",detail:"no GitLab token \u2014 existence not checked"};let i=encodeURIComponent(`${t.owner}/${t.name}`);return(await or(e.gitlabToken,"GET",`/projects/${i}`)).status!==404?{found:!0}:{found:!1,detail:n?await Vk(e.gitlabToken,t):o}}return e.bitbucket?(await jn(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await zk(e.bitbucket,t):o}:{found:"unknown",detail:"no Bitbucket credentials \u2014 existence not checked"}}catch(s){return{found:"unknown",detail:s instanceof Error?s.message:String(s)}}}async function Yk(t,e){let r=!1;try{r=(await sr(t,"GET",`/users/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitHub repo ${e.owner}/${e.name} does not exist, or the token cannot see it \u2014 check the name; a fine-grained PAT must be scoped to this repo (and approved in the org)`:`GitHub owner "${e.owner}" not found \u2014 check the org/user spelling`}async function Vk(t,e){let r=!1;try{r=(await or(t,"GET",`/namespaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitLab project ${e.owner}/${e.name} does not exist (the namespace "${e.owner}" is visible to the token) \u2014 check the project name, or the token has no access to this specific project`:`GitLab namespace "${e.owner}" is not visible to this token \u2014 check the group/username spelling; a private group answers 404 until the token's owner is a member`}async function zk(t,e){let r=!1;try{r=(await jn(t,"GET",`/workspaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`Bitbucket repo ${e.owner}/${e.name} does not exist in workspace "${e.owner}" (which the credential can see) \u2014 check the repo name, or the API token lacks access to it`:`Bitbucket workspace "${e.owner}" is not visible to this credential \u2014 check the workspace name and the token's read:repository:bitbucket scope`}async function sr(t,e,r,n){let o={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};n!==void 0&&(o.body=JSON.stringify(n),o.headers["Content-Type"]="application/json");let s=await fetch(sC+r,o),i=await s.text(),a=i?JSON.parse(i):null;if(s.status>=400&&s.status!==404){let c=typeof a=="object"&&a&&"message"in a?a.message:i;throw new Error(`GitHub ${e} ${r} \u2192 ${s.status} ${c}`)}return{status:s.status,data:a}}async function iC(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 aC(n,e,r),s=await lC(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${s}`);let i=ln(t,e,r.youtrackWrites,r.trackerUrl);for(let a of i)await uC(n,o.owner,o.name,a.path,s)||await dC(n,o.owner,o.name,a.path,a.content,`chore(codepipe): scaffold ${a.path}`,s);return{host:"github",owner:o.owner,name:o.name,cloneUrl:o.sshUrl,branch:s}}async function aC(t,e,r){let n=await sr(t,"GET",`/repos/${e.owner}/${encodeURIComponent(e.name)}`);if(n.status===200&&n.data)return r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),{owner:n.data.owner.login,name:n.data.name,sshUrl:n.data.ssh_url};if(r.mode==="attach")throw new Error(`attach: ${await Yk(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await cC(t,e.owner),s=o?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${o?"org":"user"})`);let i=await sr(t,"POST",s,{name:e.name,private:!0,auto_init:!0,description:`CodePipe Context Repo for project ${e.name}`});if(!i.data)throw new Error("GitHub createRepo: empty response");return{owner:i.data.owner.login,name:i.data.name,sshUrl:i.data.ssh_url}}async function cC(t,e){let{status:r,data:n}=await sr(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function lC(t,e,r){let{data:n}=await sr(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function uC(t,e,r,n,o){let{status:s,data:i}=await sr(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return s===404||!i?null:i.sha}async function dC(t,e,r,n,o,s,i,a){let c={message:s,content:Buffer.from(o,"utf-8").toString("base64"),branch:i};a&&(c.sha=a),await sr(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function or(t,e,r,n){let o={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...n!==void 0?{"Content-Type":"application/json"}:{}}};n!==void 0&&(o.body=JSON.stringify(n));let s=await fetch(pC+r,o),i=await s.text(),a=i?JSON.parse(i):null;if(s.status>=400&&s.status!==404){let c=typeof a=="object"&&a&&"message"in a?JSON.stringify(a.message):i;throw new Error(`GitLab ${e} ${r} \u2192 ${s.status} ${c}`)}return{status:s.status,data:a}}async function fC(t,e,r){let n=r.gitlabToken;if(!n)throw new Error("GitLab PAT required to provision a gitlab-hosted Context Repo \u2014 set GITLAB_TOKEN or provide it during `codepipe init`");let o=encodeURIComponent(`${e.owner}/${e.name}`),s,i=await or(n,"GET",`/projects/${o}`);if(i.status===200&&i.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),s=i.data;else{if(r.mode==="attach")throw new Error(`attach: ${await Vk(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await or(n,"GET","/user"),d={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(p.data?.username!==e.owner){let f=await or(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(f.status===404||!f.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);d.namespace_id=f.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let m=await or(n,"POST","/projects",d);if(!m.data)throw new Error("GitLab create project: empty response");s=m.data}let a=s.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=ln(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let m=(await or(n,"GET",`/projects/${s.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let f of m)l.add(f.path);if(m.length<100)break}let u=c.filter(p=>!l.has(p.path)).map(p=>({action:"create",file_path:p.path,content:p.content}));return u.length>0?await or(n,"POST",`/projects/${s.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:u}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:s.path,cloneUrl:s.ssh_url_to_repo,branch:a}}async function jn(t,e,r,n){let o={method:e,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${t.apiToken}`).toString("base64"),"User-Agent":"codepipe-cli"}};n?.json!==void 0?(o.body=JSON.stringify(n.json),o.headers["Content-Type"]="application/json"):n?.form&&(o.body=n.form);let s=await fetch(mC+r,o),i=await s.text(),a=null;try{a=i?JSON.parse(i):null}catch{}if(s.status>=400&&s.status!==404)throw new Error(`Bitbucket ${e} ${r} \u2192 ${s.status} ${i}`);return{status:s.status,data:a}}async function hC(t,e,r){let n=r.bitbucket;if(!n)throw new Error("Bitbucket account email + API token required to provision a bitbucket-hosted Context Repo \u2014 provide them during `codepipe init`");let o=`/repositories/${e.owner}/${encodeURIComponent(e.name)}`,s,i=await jn(n,"GET",o);if(i.status===200&&i.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),s=i.data;else{if(r.mode==="attach")throw new Error(`attach: ${await zk(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 jn(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(p.status===404||!p.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);s=p.data}let a=s.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=ln(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await jn(n,"GET",`${o}/src/${encodeURIComponent(a)}/${p.path}?format=meta`)).status===404&&l.push(p);if(l.length>0){let p=new URLSearchParams;p.set("message","chore(codepipe): scaffold context repo files"),p.set("branch",a);for(let m of l)p.set(m.path,m.content);if((await jn(n,"POST",`${o}/src`,{form:p})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let u=s.links?.clone?.find(p=>p.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:s.slug??e.name,cloneUrl:u??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var sC,pC,mC,xi=v(()=>{"use strict";Pr();sC="https://api.github.com";pC="https://gitlab.com/api/v4";mC="https://api.bitbucket.org/2.0"});function Ue(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=gC[r];if(!o)return null;let s=n.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(s.length<2)return null;let i=s[s.length-1].replace(/\.git$/,"");return i?{host:o,owner:s.slice(0,-1).join("/"),repoName:i}:null}var gC,Si=v(()=>{"use strict";gC={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as yC}from"node:crypto";import{existsSync as Xk,mkdirSync as kC,readFileSync as Jk,readdirSync as wC,rmSync as Ei,writeFileSync as bC}from"node:fs";import{homedir as $C}from"node:os";import{dirname as vC,join as Yl}from"node:path";function Zk(){return Yl($C(),".codepipe","init-drafts")}function Vl(t){let e=yC("sha256").update(t).digest("hex").slice(0,16);return Yl(Zk(),`${e}.json`)}function Qk(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=xC)}function ew(t){let e=Vl(t);if(!Xk(e))return null;try{let r=JSON.parse(Jk(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Qk(r.savedAt)?(Ei(e,{force:!0}),null):r}catch{return null}}function zl(t){Ei(Vl(t),{force:!0})}function tw(){let t=Zk();if(Xk(t))for(let e of wC(t)){let r=Yl(t,e);try{let n=JSON.parse(Jk(r,"utf-8"));Qk(n.savedAt)&&Ei(r,{force:!0})}catch{Ei(r,{force:!0})}}}var xC,On,rw=v(()=>{"use strict";xC=24*60*60*1e3;On=class{constructor(e,r){this.cwd=e;this.answers=r?.answers?{...r.answers}:{}}answers;get(e){return this.answers[e]}set(e,r){this.answers[e]=r,this.persist()}delete(e){delete this.answers[e],this.persist()}async ask(e,r){if(e in this.answers)return this.answers[e];let n=await r();return this.set(e,n),n}clear(){zl(this.cwd)}persist(){let e=Vl(this.cwd);kC(vC(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};bC(e,JSON.stringify(r,null,2)+`
|
|
921
|
-
`,{mode:384})}}});function
|
|
922
|
-
`).map(n=>n.trim()).filter(Boolean);return
|
|
923
|
-
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`),
|
|
924
|
-
`))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function
|
|
894
|
+
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=RT(await ST({message:"Claude OAuth token \u2014 blank to skip"})).trim();if(!e)return qe.warn(t.farm?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"";e.startsWith("sk-ant-")||qe.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`.");let r=await Nt(e);return r==="invalid"?(qe.warn("Claude refused this token \u2014 it cannot run a job (expired, or minted without the inference scope). Run `claude setup-token` again and paste the new one."),ak(t)):(qe.success(`Claude: ${ik(e)} \u2014 ${r==="valid"?"verified":"check inconclusive, saved"}.`),e)}var ck,lk=S(()=>{"use strict";hs();nn();de();dc();ck={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:TT,promptManual:ak,validate:Nt}});function uk(t){return ck}async function dk(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var pk=S(()=>{"use strict";lk()});async function Nn(t,e,r){return e.host==="github"?AT(t,e,r):e.host==="gitlab"?DT(t,e,r):UT(t,e,r)}async function fk(t,e,r={}){let n=r.explain??!0,o=`${t.owner}/${t.name} not found on ${t.host}`;try{if(t.host==="github")return e.githubToken?(await sr(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await mk(e.githubToken,t):o}:{found:"unknown",detail:"no GitHub token \u2014 existence not checked"};if(t.host==="gitlab"){if(!e.gitlabToken)return{found:"unknown",detail:"no GitLab token \u2014 existence not checked"};let i=encodeURIComponent(`${t.owner}/${t.name}`);return(await or(e.gitlabToken,"GET",`/projects/${i}`)).status!==404?{found:!0}:{found:!1,detail:n?await hk(e.gitlabToken,t):o}}return e.bitbucket?(await jn(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await gk(e.bitbucket,t):o}:{found:"unknown",detail:"no Bitbucket credentials \u2014 existence not checked"}}catch(s){return{found:"unknown",detail:s instanceof Error?s.message:String(s)}}}async function mk(t,e){let r=!1;try{r=(await sr(t,"GET",`/users/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitHub repo ${e.owner}/${e.name} does not exist, or the token cannot see it \u2014 check the name; a fine-grained PAT must be scoped to this repo (and approved in the org)`:`GitHub owner "${e.owner}" not found \u2014 check the org/user spelling`}async function hk(t,e){let r=!1;try{r=(await or(t,"GET",`/namespaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitLab project ${e.owner}/${e.name} does not exist (the namespace "${e.owner}" is visible to the token) \u2014 check the project name, or the token has no access to this specific project`:`GitLab namespace "${e.owner}" is not visible to this token \u2014 check the group/username spelling; a private group answers 404 until the token's owner is a member`}async function gk(t,e){let r=!1;try{r=(await jn(t,"GET",`/workspaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`Bitbucket repo ${e.owner}/${e.name} does not exist in workspace "${e.owner}" (which the credential can see) \u2014 check the repo name, or the API token lacks access to it`:`Bitbucket workspace "${e.owner}" is not visible to this credential \u2014 check the workspace name and the token's read:repository:bitbucket scope`}async function sr(t,e,r,n){let o={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};n!==void 0&&(o.body=JSON.stringify(n),o.headers["Content-Type"]="application/json");let s=await fetch(CT+r,o),i=await s.text(),a=i?JSON.parse(i):null;if(s.status>=400&&s.status!==404){let c=typeof a=="object"&&a&&"message"in a?a.message:i;throw new Error(`GitHub ${e} ${r} \u2192 ${s.status} ${c}`)}return{status:s.status,data:a}}async function AT(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 PT(n,e,r),s=await jT(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${s}`);let i=ln(t,e,r.youtrackWrites,r.trackerUrl);for(let a of i)await NT(n,o.owner,o.name,a.path,s)||await OT(n,o.owner,o.name,a.path,a.content,`chore(codepipe): scaffold ${a.path}`,s);return{host:"github",owner:o.owner,name:o.name,cloneUrl:o.sshUrl,branch:s}}async function PT(t,e,r){let n=await sr(t,"GET",`/repos/${e.owner}/${encodeURIComponent(e.name)}`);if(n.status===200&&n.data)return r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),{owner:n.data.owner.login,name:n.data.name,sshUrl:n.data.ssh_url};if(r.mode==="attach")throw new Error(`attach: ${await mk(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await _T(t,e.owner),s=o?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${o?"org":"user"})`);let i=await sr(t,"POST",s,{name:e.name,private:!0,auto_init:!0,description:`CodePipe Context Repo for project ${e.name}`});if(!i.data)throw new Error("GitHub createRepo: empty response");return{owner:i.data.owner.login,name:i.data.name,sshUrl:i.data.ssh_url}}async function _T(t,e){let{status:r,data:n}=await sr(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function jT(t,e,r){let{data:n}=await sr(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function NT(t,e,r,n,o){let{status:s,data:i}=await sr(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return s===404||!i?null:i.sha}async function OT(t,e,r,n,o,s,i,a){let c={message:s,content:Buffer.from(o,"utf-8").toString("base64"),branch:i};a&&(c.sha=a),await sr(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function or(t,e,r,n){let o={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...n!==void 0?{"Content-Type":"application/json"}:{}}};n!==void 0&&(o.body=JSON.stringify(n));let s=await fetch(LT+r,o),i=await s.text(),a=i?JSON.parse(i):null;if(s.status>=400&&s.status!==404){let c=typeof a=="object"&&a&&"message"in a?JSON.stringify(a.message):i;throw new Error(`GitLab ${e} ${r} \u2192 ${s.status} ${c}`)}return{status:s.status,data:a}}async function DT(t,e,r){let n=r.gitlabToken;if(!n)throw new Error("GitLab PAT required to provision a gitlab-hosted Context Repo \u2014 set GITLAB_TOKEN or provide it during `codepipe init`");let o=encodeURIComponent(`${e.owner}/${e.name}`),s,i=await or(n,"GET",`/projects/${o}`);if(i.status===200&&i.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),s=i.data;else{if(r.mode==="attach")throw new Error(`attach: ${await hk(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await or(n,"GET","/user"),d={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(p.data?.username!==e.owner){let f=await or(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(f.status===404||!f.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);d.namespace_id=f.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let m=await or(n,"POST","/projects",d);if(!m.data)throw new Error("GitLab create project: empty response");s=m.data}let a=s.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=ln(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let m=(await or(n,"GET",`/projects/${s.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let f of m)l.add(f.path);if(m.length<100)break}let u=c.filter(p=>!l.has(p.path)).map(p=>({action:"create",file_path:p.path,content:p.content}));return u.length>0?await or(n,"POST",`/projects/${s.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:u}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:s.path,cloneUrl:s.ssh_url_to_repo,branch:a}}async function jn(t,e,r,n){let o={method:e,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${t.apiToken}`).toString("base64"),"User-Agent":"codepipe-cli"}};n?.json!==void 0?(o.body=JSON.stringify(n.json),o.headers["Content-Type"]="application/json"):n?.form&&(o.body=n.form);let s=await fetch(MT+r,o),i=await s.text(),a=null;try{a=i?JSON.parse(i):null}catch{}if(s.status>=400&&s.status!==404)throw new Error(`Bitbucket ${e} ${r} \u2192 ${s.status} ${i}`);return{status:s.status,data:a}}async function UT(t,e,r){let n=r.bitbucket;if(!n)throw new Error("Bitbucket account email + API token required to provision a bitbucket-hosted Context Repo \u2014 provide them during `codepipe init`");let o=`/repositories/${e.owner}/${encodeURIComponent(e.name)}`,s,i=await jn(n,"GET",o);if(i.status===200&&i.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),s=i.data;else{if(r.mode==="attach")throw new Error(`attach: ${await gk(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 jn(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(p.status===404||!p.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);s=p.data}let a=s.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=ln(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await jn(n,"GET",`${o}/src/${encodeURIComponent(a)}/${p.path}?format=meta`)).status===404&&l.push(p);if(l.length>0){let p=new URLSearchParams;p.set("message","chore(codepipe): scaffold context repo files"),p.set("branch",a);for(let m of l)p.set(m.path,m.content);if((await jn(n,"POST",`${o}/src`,{form:p})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let u=s.links?.clone?.find(p=>p.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:s.slug??e.name,cloneUrl:u??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var CT,LT,MT,$i=S(()=>{"use strict";Pr();CT="https://api.github.com";LT="https://gitlab.com/api/v4";MT="https://api.bitbucket.org/2.0"});function Ue(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=BT[r];if(!o)return null;let s=n.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(s.length<2)return null;let i=s[s.length-1].replace(/\.git$/,"");return i?{host:o,owner:s.slice(0,-1).join("/"),repoName:i}:null}var BT,vi=S(()=>{"use strict";BT={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as FT}from"node:crypto";import{existsSync as yk,mkdirSync as KT,readFileSync as kk,readdirSync as GT,rmSync as xi,writeFileSync as HT}from"node:fs";import{homedir as WT}from"node:os";import{dirname as qT,join as Fl}from"node:path";function wk(){return Fl(WT(),".codepipe","init-drafts")}function Kl(t){let e=FT("sha256").update(t).digest("hex").slice(0,16);return Fl(wk(),`${e}.json`)}function bk(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=YT)}function $k(t){let e=Kl(t);if(!yk(e))return null;try{let r=JSON.parse(kk(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:bk(r.savedAt)?(xi(e,{force:!0}),null):r}catch{return null}}function Gl(t){xi(Kl(t),{force:!0})}function vk(){let t=wk();if(yk(t))for(let e of GT(t)){let r=Fl(t,e);try{let n=JSON.parse(kk(r,"utf-8"));bk(n.savedAt)&&xi(r,{force:!0})}catch{xi(r,{force:!0})}}}var YT,On,xk=S(()=>{"use strict";YT=24*60*60*1e3;On=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(){Gl(this.cwd)}persist(){let e=Kl(this.cwd);KT(qT(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};HT(e,JSON.stringify(r,null,2)+`
|
|
895
|
+
`,{mode:384})}}});function Sk(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 Ek(t,e){if(t.host!=="github"||!e)return!1;try{return(await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/contents/knowledge/INDEX.md?ref=${encodeURIComponent(t.branch)}`,{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}})).status===200}catch{return!1}}var Rk=S(()=>{"use strict"});import{existsSync as VT}from"node:fs";import{join as zT}from"node:path";import{simpleGit as XT}from"simple-git";function eC(t){let e=t.split("/");return e[e.length-1]??t}function Ik(t){if(t.filter(r=>!ZT.test(eC(r))).length>JT)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(QT.has(n))return!0}return!1}async function tC(t){try{let r=(await XT(t).raw(["ls-files"])).split(`
|
|
896
|
+
`).map(n=>n.trim()).filter(Boolean);return Ik(r)}catch{return!1}}async function rC(t,e){if(t.host!=="github")return!1;let r=e.github?.token;if(!r)return!1;let n=t.defaultBranch??"main";try{let o=await fetch(`https://api.github.com/repos/${t.owner}/${t.repoName}/contents/?ref=${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(o.status!==200)return!1;let s=await o.json();return Array.isArray(s)?Ik(s.map(i=>i.name??"").filter(Boolean)):!1}catch{return!1}}async function Tk(t,e){for(let r of t)try{let n=e.localRoot!=null?zT(e.localRoot,r.mountAs??r.name):null;if(n&&VT(n)?await tC(n):await rC(r,e.tokens))return!0}catch{}return!1}var JT,ZT,QT,Ck=S(()=>{"use strict";JT=3,ZT=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,QT=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as Ak}from"node:fs";import{join as Pk}from"node:path";import{simpleGit as _k}from"simple-git";async function Uo(t,e,r={}){let n=r.log??nC,o=[];for(let s of e){let i=Pk(t,s.mountAs),a=Td(s);if(!Ak(i)){if(r.dryRun){n.info(`would clone ${a} \u2192 ${s.mountAs}/`),o.push({mountAs:s.mountAs,status:"cloned",detail:"(dry-run)"});continue}try{n.info(`cloning ${a} \u2192 ${s.mountAs}/`),await _k().clone(a,i),o.push({mountAs:s.mountAs,status:"cloned"})}catch(u){let p=Mo(u instanceof Error?u.message:String(u));n.warn(`clone failed for ${s.mountAs}: ${p}`),o.push({mountAs:s.mountAs,status:"error",detail:p})}continue}if(!Ak(Pk(i,".git"))){n.warn(`${s.mountAs}/ exists but is not a git repo \u2014 skipping`),o.push({mountAs:s.mountAs,status:"skipped-not-git"});continue}let c=_k(i),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!oC(l,a)){n.warn(`${s.mountAs}/ origin (${Mo(l)||"none"}) != expected (${Mo(a)}) \u2014 skipping`),o.push({mountAs:s.mountAs,status:"skipped-origin-mismatch",detail:Mo(l)});continue}if(r.dryRun){n.info(`would fetch ${s.mountAs}/`),o.push({mountAs:s.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),o.push({mountAs:s.mountAs,status:"fetched"})}catch(u){let p=Mo(u instanceof Error?u.message:String(u));n.warn(`fetch failed for ${s.mountAs}: ${p}`),o.push({mountAs:s.mountAs,status:"error",detail:p})}}return o}function oC(t,e){return jk(t)===jk(e)}function jk(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function Mo(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function Nk(t={}){let e=Re();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 Uo(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 nC,Si=S(()=>{"use strict";bt();nC={info:t=>console.log(t),warn:t=>console.warn(t)}});var Uk={};Fe(Uk,{ensureEmbeddedWorker:()=>Ri,spawnWorkerProcess:()=>Ii,upCommand:()=>Ti,workerChildEnv:()=>Mk,workerStartArgs:()=>Dk});import{spawn as Lk}from"node:child_process";import{existsSync as Ok}from"node:fs";import{homedir as sC,hostname as iC}from"node:os";import{join as Ei}from"node:path";async function aC(t,e,r){let n=je(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${gt(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 Fp(t.hubUrl.replace(/\/$/,""),n.token)}catch(s){return console.warn(`[up] could not verify the worker registration (${s instanceof Error?s.message:String(s)}) \u2014 continuing`),!1}if(o==="unsupported")return console.log(`[up] worker already registered as ${n.sandboxId} (${n.name})`),!1;if(o==="ok")return console.log(`[up] worker already registered as ${n.sandboxId} (${n.name})`),!1;if(!r.reregister)throw new Error(`the HUB no longer knows this worker registration (${n.sandboxId}) \u2014 it was removed on ${t.hubUrl}, but ${gt(e)} still holds its token.
|
|
897
|
+
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`),Gd(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function cC(t,e,r){let n=je(e)!==null;if(!await aC(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 ks(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(s){throw s instanceof W&&s.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):s instanceof W&&s.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):s instanceof W?s:new Error(`cannot reach the HUB at ${t.hubUrl} (${s instanceof Error?s.message:String(s)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await Nr({hub:t.hubUrl,token:o,name:r.name??`${iC()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function lC(t,e){let r=je(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=De(r.sealPublicKey);if(!q(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=is(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 Ri(t,e,r){await cC(t,e,r),lC(t.projectId,e)}function Dk(t){return[...t?["--profile",t]:[],"worker","start"]}function Mk(t){let e={...t};for(let r of za)delete e[r];return e}function Ii(t){let e=Lk(process.execPath,[t.entry,...Dk(t.profile)],{stdio:["ignore","pipe","pipe"],env:Mk(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
|
|
898
|
+
`))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function uC(t,e){let r=process.cwd(),n=Ei(r,_t);if(ns(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(Ok(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 s=await Hl(r);if(!Id(r,s?.parsed??null,o.repos)){console.log(`[up] this folder is neither empty nor a repo of ${t.projectId} \u2014 the context stays under ~/.codepipe/profiles`);return}let i=q(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await si({cfg:t,secrets:i,contextDir:n,log:a}).catch(()=>null);if(!c?.contextDir){console.warn("[up] could not clone the Context Repo here \u2014 the context stays under ~/.codepipe/profiles");return}let l=Ei(sC(),".codepipe",e?Ei("profiles",e,"context-config"):"context-config");if(Rs(c.contextDir,l,a),!Ok(Ei(c.contextDir,"project.yaml"))){an(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};ho(c.contextDir,xt(u,!0,i?.youtrack?.url)),console.log("[up] local project config seeded with defaults \u2014 review .codepipe/project.yaml")}console.log(`[up] project context materialized \u2192 ${n}`)}async function Ti(t){let{cfg:e,profile:r}=ss(t.profile);if(t.debug){let m=typeof t.debug=="string"&&t.debug.trim()?t.debug.trim():"agent-request";process.env.CODEPIPE_DEBUG=m,console.log(`[up] debug logging on (${m}) \u2192 ~/.codepipe/debug/${e.projectId}/`)}await uC(e,r),await Ri(e,r,t);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(m,f)=>{let g=h=>w=>{for(let y of w.toString("utf-8").split(`
|
|
925
899
|
`))y.length>0&&h.write(`${f} ${y}
|
|
926
|
-
`)};m.stdout?.on("data",g(process.stdout)),m.stderr?.on("data",g(process.stderr))},s=(m,f)=>{let g=
|
|
900
|
+
`)};m.stdout?.on("data",g(process.stdout)),m.stderr?.on("data",g(process.stderr))},s=(m,f)=>{let g=Lk(process.execPath,[n,...f],{stdio:["ignore","pipe","pipe"],env:process.env});return o(g,m),g};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let i=s("[cli]",[...r?["--profile",r]:[],"daemon"]),a=Ii({entry:n,profile:r,onLine:m=>process.stdout.write(`[worker] ${m}
|
|
927
901
|
`)}),c=[{name:"daemon",child:i},{name:"worker",child:a}],l=!1,u=m=>{if(!l){l=!0,console.log(`
|
|
928
|
-
[up] ${m} \u2014 stopping both roles`);for(let{child:f}of c)f.exitCode===null&&f.kill(m);setTimeout(()=>{for(let{name:f,child:g}of c)g.exitCode===null&&(console.warn(`[up] ${f} did not stop \u2014 SIGKILL`),g.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:m,child:f})=>new Promise(g=>{f.on("exit",(h,w)=>g({name:m,code:h??(w?1:0)}))})),d=await Promise.race(p);l||(console.log(`[up] ${d.name} exited (code ${d.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(p),process.exit(d.code)}var
|
|
929
|
-
\u26A0 unfinished local apply: ${o.map(a=>`${a} (${n[a].repos.map(c=>c.mountAs).join(", ")})`).join("; ")}
|
|
930
|
-
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let s=Ln.createInterface({input:process.stdin,output:process.stdout,completer:VC,history:mA(),removeHistoryDuplicates:!0}),i={ws:e,secrets:r,connection:"connecting",rl:s,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};hf(a=>ar(i,a)),i.daemon=si({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:a=>ar(i,a),warn:a=>ar(i,a)},onEvent:a=>cA(i,a),workspace:{root:e.root,contextDir:e.contextDir,repos:e.spec.repos.map(a=>({name:a.name,mountAs:a.mountAs,defaultBranch:a.defaultBranch}))}});try{let a={hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId};await Xl(a,t.profile,{profile:t.profile});let c=process.argv[1];if(!c)throw new Error("cannot resolve the codepipe entry script for the worker process");let l=Jl({entry:c,profile:t.profile,onLine:u=>ar(i,`[worker] ${u}`)});l.on("exit",(u,p)=>{i.workerExited=!0,!nu&&ir(i,`[worker] exited (code ${u??(p?1:0)}) \u2014 agent jobs will NOT run; /quit and restart codepipe to bring it back`)}),i.workerChild=l,console.log("embedded agent worker started \u2014 agent jobs run on this machine.")}catch(a){console.warn(`[worker] could not start the embedded worker (${a instanceof Error?a.message:String(a)}). REPL commands still work; run \`codepipe up --reregister\` if the registration was removed.`)}ru(i),s.prompt(),s.on("line",async a=>{let c=a.trim();if(c.length>0)try{if(await zC(i,c)){bw(i);return}}catch(l){console.error(l instanceof Error?l.message:String(l))}i.unread=0,ru(i),s.prompt()}),s.on("close",()=>{bw(i)})}function VC(t){let e=gw.filter(r=>r.startsWith(t));return[e.length?e:gw,t]}async function zC(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return XC(),!1;case"/status":return await JC(t),!1;case"/tasks":return await ZC(t,n),!1;case"/task":return await QC(t,n),!1;case"/sync":return await eA(t),!1;case"/logs":return lA(t,n),!1;case"/monitor":return uA(t),!1;case"/apply":return await kw(t,n,"apply"),!1;case"/unstash":return await kw(t,n,"unstash"),!1;case"/applied":return await tA(t,n),!1;case"/abort":return await rA(t,n),!1;case"/approve":return await ww(t,n,"approve"),!1;case"/merge":return await ww(t,n,"merge"),!1;case"/login":return oA(t,n),!1;case"/secret":return sA(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function XC(){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(`
|
|
931
|
-
`))}async function JC(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=$w(vw(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function ZC(t,e){let r=dA(e,"--phase");try{let n=await af(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId),o=r?n.filter(s=>s.phase.toLowerCase()===r.toLowerCase()):n;if(o.length===0){console.log(" (no tasks)");return}for(let s of o)console.log(` ${s.key.padEnd(10)} ${s.phase.padEnd(16)} ${s.title}`)}catch(n){Fo(n)}}async function QC(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await cf(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r);if(console.log(` ${r}: ${n.task.phase} \u2014 ${n.task.title}`),n.artifacts.length>0){console.log(" artifacts:");for(let o of n.artifacts)console.log(` ${o.path}`)}}catch(n){Fo(n)}}async function eA(t){let e=await Uo(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 kw(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await Rf(t.ws,t.secrets,n,r,{info:s=>console.log(s),warn:s=>console.warn(s)});console.log(` ${o.message}`)}async function tA(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=Cr(t.ws.contextDir)[r],s=pA(e,"--pr");if(s.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let i=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of s){let l=c.indexOf("="),u,p;if(l>0?(u=c.slice(0,l),p=c.slice(l+1)):(p=c,u=o?.repos.length===1?nA(t,o.repos[0].mountAs):i.length===1?i[0]:""),!u){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${p}`);return}let d=p.match(/(?:pull|pull-requests)\/(\d+)/);if(!d){console.log(` cannot parse PR number from ${p}`);return}a.push({repoName:u,url:p,number:Number(d[1])})}try{let c=await lf(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);hc(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){Fo(c)}}async function ww(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await df(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){Fo(o)}}async function rA(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=fA(e,"--reason")||"local apply aborted";await Tf(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await uf(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){Fo(o)}}function nA(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function oA(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},se(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 sA(t,e){let[r,n,...o]=e;if(r==="list"){let s=[];t.secrets.github&&s.push("github.token"),t.secrets.bitbucket&&s.push("bitbucket.email","bitbucket.apiToken"),t.secrets.youtrack&&s.push("youtrack.url","youtrack.token"),console.log(s.length?` ${s.join(`
|
|
932
|
-
`)}`:" (none)");return}if(r==="set"){let s=o.join(" ");if(!n||!s){console.log("usage: /secret set <key> <value> (keys: GH_TOKEN, YOUTRACK_URL, YOUTRACK_TOKEN, BITBUCKET_EMAIL, BITBUCKET_API_TOKEN)");return}iA(t.secrets,n,s),se(t.secrets),io(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}aA(t.secrets,n),se(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function iA(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 aA(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 cA(t,e){switch(e.kind){case"connected":t.connection="connecting",ar(t,"[hub] connected");break;case"registered":t.connection="registered",ar(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",ir(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",ar(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",ir(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":ir(t,`[hub] HUB v${e.hubVersion??"?"} (protocol ${e.hubProtocol??"?"}) is incompatible with this CLI \u2014 WriteActions are refused. Update: ${e.updateCommand}`);break;case"action":e.ok?ar(t,`[hub] action ${e.actionType} done`):ir(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break;case"local_applied":e.ok?ir(t,`[apply] ${e.taskKey}: branch ${(e.branches??[]).join(", ")} created locally (your checkout is untouched) \u2014 review, push, then: /applied ${e.taskKey} --pr <url>`):ir(t,`[apply] ${e.taskKey}: auto-apply failed \u2014 task stays in READY_TO_APPLY: ${e.error??"?"}`);break}}function ar(t,e){t.logBuffer.push(e),t.logBuffer.length>xw&&t.logBuffer.shift(),t.follow&&ir(t,e)}function lA(t,e){let r=e[0];if(r==="follow"||r==="on"){tu(t,!0);return}if(r==="off"){tu(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(xw,Number(r)||yw)):yw,o=t.logBuffer.slice(-n);if(o.length===0){console.log(" (no daemon logs buffered yet)");return}for(let s of o)console.log(` ${s}`);console.log(` \u2014 ${o.length} line(s); /monitor for live stream`)}function uA(t){tu(t,!t.follow)}function tu(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function ir(t,e){Ln.cursorTo(process.stdout,0),Ln.clearLine(process.stdout,0),process.stdout.write(e+`
|
|
933
|
-
`),t.unread+=1,ru(t),t.rl.prompt(!0)}function ru(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}function bw(t){if(nu)return;nu=!0,hA(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
|
|
934
|
-
bye.`),setTimeout(()=>process.exit(0),150);return}console.log(`
|
|
935
|
-
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 dA(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function pA(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 fA(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function Fo(t){t instanceof W?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function mA(){if(!$w(Ti))return[];try{return HC(Ti,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function hA(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{GC(YC(Ti),{recursive:!0}),WC(Ti,r.slice().reverse().join(`
|
|
936
|
-
`)+`
|
|
937
|
-
`)}catch{}}var Ti,gw,xw,yw,nu,su=v(()=>{"use strict";El();Te();ws();de();bt();Ri();Ql();gc();Ti=vw(qC(),".codepipe","history"),gw=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],xw=500,yw=40;nu=!1});import{existsSync as Lr,mkdirSync as Rw,readFileSync as Iw,readdirSync as gA,writeFileSync as Tw}from"node:fs";import{join as cr,resolve as Cw}from"node:path";import{setTimeout as iu}from"node:timers/promises";import{cancel as yA,confirm as Ko,intro as Aw,isCancel as lu,log as A,multiselect as kA,outro as au,password as Ai,select as yt,spinner as uu,text as we}from"@clack/prompts";import{simpleGit as Pi}from"simple-git";function le(t){yA(t),process.exit(1)}function Ae(t){return lu(t)&&le("aborted"),t}function ue(t){return lu(t)&&le("aborted"),typeof t=="string"?t:""}async function Pw(t={}){Aw("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();tw();let r=ew(e),n,o=!1;r&&Object.keys(r.answers).length>0?Ae(await Ko({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(A.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new On(e,r),o=!0):(zl(e),n=new On(e)):n=new On(e);let s=t.force===!0?null:await eu(e),i=await n.ask("target",async()=>Ae(await yt({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;i==="local"&&(a=s??(t.force===!0?null:await bA(e,n)),a?A.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):o&&n.get("contextRepo")!==void 0||jw(e,t.force===!0));let c=await n.ask("hubUrl",async()=>ue(await we({message:"HUB URL",placeholder:at,initialValue:X("HUB_URL")??at,validate:b=>b.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>Dn()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>Mn(c,l)),d=null;i==="farm"&&(d=await wA(c,u));let m=a?$A(a.parsed.repoName):"",f=await n.ask("projectId",async()=>ue(await we({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:b=>Kt.test(b.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await n.ask("projectName",async()=>ue(await we({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:b=>b.trim().length>0?void 0:"required"})).trim()),h=await n.ask("language",()=>AA()),w=await n.ask("automationLevel",async()=>Ae(await yt({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),y=i==="farm"?"auto":await n.ask("applyMode",async()=>Ae(await yt({message:"how do approved changes reach your repo?",options:[{value:"auto",label:"auto \u2014 CodePipe pushes the branch and opens a PR"},{value:"local",label:"local \u2014 changes wait; you pull them into your checkout via the CLI REPL (/apply or /unstash), no push/PR"}],initialValue:"auto"}))),x=await n.ask("trackerProvider",async()=>Ae(await yt({message:"task tracker",options:[{value:"internal",label:"built-in \u2014 CodePipe tracks tasks itself (no external tracker needed)"},{value:"youtrack",label:"YouTrack \u2014 connect an existing YouTrack project"}],initialValue:"internal"}))),S=x==="internal",I=null,E,$=!0;if(S){let b,R=uu();R.start("checking task-key prefixes on your account\u2026");try{b=await nf(c,u,{excludeProjectId:f}),R.stop("prefixes checked")}catch{R.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 B=Ka(Fa(g),b);E=await n.ask("trackerPrefix",async()=>ue(await we({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:B,initialValue:B,validate:J=>{let Pe=J.trim();if(!kr.test(Pe))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(b.has(Pe.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else I=await n.ask("youtrack",()=>Kw()),E=await n.ask("youtrackProjectKey",async()=>ue(await we({message:"YouTrack project key",placeholder:"DEV",validate:b=>b.trim().length>0?void 0:"required"})).trim()),$=await n.ask("youtrackWrites",async()=>Ae(await Ko({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let T=n.get("tokens")??{},N=()=>n.set("tokens",T),G=await n.ask("repos",()=>SA(T,l,a,{onCred:N,initial:n.get("reposPartial")??[],onProgress:b=>n.set("reposPartial",b)}));n.delete("reposPartial");let ee=await EA(await n.ask("contextRepo",()=>Uw(f,G,T,l)),f,G,T,l,N,b=>n.set("contextRepo",b)),{spec:C,mode:k}=ee,M;S||(A.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),M=await n.ask("assigneeLogin",async()=>ue(await we({message:"your YouTrack login (the assignee value)",...I?.login?{initialValue:I.login}:{},validate:b=>b.trim().length>0?void 0:"required"})).trim()));let P=await n.ask("llmProvider",async()=>{for(;;){if(Ae(await yt({message:"LLM provider",options:[{value:"claude",label:"Claude",hint:"recommended"},{value:"codex",label:"Codex",hint:"coming soon"}],initialValue:"claude"}))==="claude")return"claude";A.warn("Codex support is coming soon \u2014 pick Claude for now.")}}),H=P==="claude"?await n.ask("claudeToken",()=>Hk(Gk("claude"),{farm:i==="farm"})):"",Y;if(H){let b=await Hp(H);if(b){let R=fa(b);R&&(Y=R,A.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${R} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let oe={projectId:f,name:g,automationLevel:w,repos:G,trackerProvider:x,youtrackProjectKey:E,language:h};A.step(`${k==="attach"?"attaching to":"provisioning"} Context Repo ${C.owner}/${C.name} (${C.host})\u2026`);let Ve;try{Ve=await Nn(oe,C,{...Bw(T),youtrackWrites:$,...I?{trackerUrl:I.url}:{},mode:k,log:{info:b=>A.message(b),warn:b=>A.warn(b)}})}catch(b){le(`Context Repo provisioning failed: ${b instanceof Error?b.message:String(b)}`)}oe.contextRepo=Ve,A.success(`Context Repo ready: ${Ve.owner}/${Ve.name}@${Ve.branch}`),A.step(`registering project on ${c}\u2026`);let ze;try{ze=await Xt(c,u,oe)}catch(b){if(b instanceof W&&b.status===409){A.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{ze=await ne(c,u,f)}catch(R){throw R instanceof W&&le(`HUB \u2192 ${R.status} ${R.message}`),R}}else if(b instanceof W&&b.status===401)n.delete("cliToken"),le("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(b instanceof W)le(`HUB \u2192 ${b.status} ${b.message}`);else throw b}let _=ze.contextRepo??Ve;A.success(`project ${ze.projectId} ready (${ze.provisioningStatus})`);let U=I?{url:I.url,token:I.token}:void 0;if(i==="farm"){let b=d,R={...T,...H?{claude:{oauthToken:H}}:{},...U?{youtrack:U}:{}},B=T.github?.token;if(_.host==="github"&&B)try{let K=Cg(`devpipe-${f}`);await Ag(_,B,K.publicKey,`devpipe-${f}`),R.contextSsh={privateKey:K.privateKey},A.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(K){A.warn(`could not set up Context Repo SSH deploy key (${K instanceof Error?K.message:String(K)}); the farm will fall back to the token path.`)}let J={projectId:f,config:{hubUrl:c,cliToken:u,projectId:f},secrets:R,contextRepo:_,projectConfig:xt(oe,$,I?.url,M||void 0,"auto",P,Y)},Pe=Dt(b.farm.publicKey,JSON.stringify(J));A.step(`handing project ${f} to farm ${b.farm.name}\u2026`);let st;try{st=await ys(c,u,b.farm.farmId,{projectId:f,sealedBundle:Pe})}catch(K){throw K instanceof W&&le(K.status===409?`farm ${b.farm.name} is offline \u2014 start it and re-run.`:K.status===504?`farm ${b.farm.name} did not respond in time.`:`HUB \u2192 ${K.status} ${K.message}`),K}st.ok||le(`farm rejected provisioning: ${st.error??"unknown error"}`),await cu(c,u,f,_,B,ze.repos,null,T),n.clear(),au(`done. project ${f} is now hosted on farm ${b.farm.name} (daemon ${st.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}Fw(T),await Lw(e,_.cloneUrl,_.branch),Mw(e),a&&await xA(e);{let b=cr(e,_t);an(b);let R=xt(oe,$,I?.url,M||void 0,y,P,Y),B=ho(b,R);B.length>0&&A.success(`local project config \u2192 .codepipe/{${B.join(", ")}}`),Ar(f,R,{info:J=>A.message(J),warn:J=>A.warn(J)})}await Dw(e,ze.repos);let D={hubUrl:c,cliToken:u,projectId:f,...T,...H?{claude:{oauthToken:H}}:{},...U?{youtrack:U}:{}};se(D),jt({hubUrl:c,cliToken:u,projectId:f,accountEmail:p},f),A.success(`secrets \u2192 ${$t(f)}`),await cu(c,u,f,_,T.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,ze.repos,e,T),n.clear();let z=`${c}/?project=${encodeURIComponent(f)}`;vr(z),au(`done. your project on the dashboard (sign in there to work with it):
|
|
902
|
+
[up] ${m} \u2014 stopping both roles`);for(let{child:f}of c)f.exitCode===null&&f.kill(m);setTimeout(()=>{for(let{name:f,child:g}of c)g.exitCode===null&&(console.warn(`[up] ${f} did not stop \u2014 SIGKILL`),g.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:m,child:f})=>new Promise(g=>{f.on("exit",(h,w)=>g({name:m,code:h??(w?1:0)}))})),d=await Promise.race(p);l||(console.log(`[up] ${d.name} exited (code ${d.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(p),process.exit(d.code)}var Ci=S(()=>{"use strict";ot();_n();We();Lt();$l();Pr();Te();de();bt();Bo()});import{existsSync as Lr,mkdirSync as Fk,readFileSync as Kk,readdirSync as dC,writeFileSync as Gk}from"node:fs";import{join as ir,resolve as Hk}from"node:path";import{setTimeout as Wl}from"node:timers/promises";import{cancel as pC,confirm as Fo,intro as Wk,isCancel as Vl,log as A,multiselect as fC,outro as ql,password as Pi,select as yt,spinner as zl,text as we}from"@clack/prompts";import{simpleGit as _i}from"simple-git";function le(t){pC(t),process.exit(1)}function Ae(t){return Vl(t)&&le("aborted"),t}function ue(t){return Vl(t)&&le("aborted"),typeof t=="string"?t:""}async function qk(t={}){Wk("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();vk();let r=$k(e),n,o=!1;r&&Object.keys(r.answers).length>0?Ae(await Fo({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(A.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new On(e,r),o=!0):(Gl(e),n=new On(e)):n=new On(e);let s=t.force===!0?null:await Hl(e),i=await n.ask("target",async()=>Ae(await yt({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;i==="local"&&(a=s??(t.force===!0?null:await hC(e,n)),a?A.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):o&&n.get("contextRepo")!==void 0||Vk(e,t.force===!0));let c=await n.ask("hubUrl",async()=>ue(await we({message:"HUB URL",placeholder:at,initialValue:X("HUB_URL")??at,validate:b=>b.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>Ln()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>Dn(c,l)),d=null;i==="farm"&&(d=await mC(c,u));let m=a?gC(a.parsed.repoName):"",f=await n.ask("projectId",async()=>ue(await we({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:b=>Kt.test(b.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await n.ask("projectName",async()=>ue(await we({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:b=>b.trim().length>0?void 0:"required"})).trim()),h=await n.ask("language",()=>EC()),w=await n.ask("automationLevel",async()=>Ae(await yt({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),y=i==="farm"?"auto":await n.ask("applyMode",async()=>Ae(await yt({message:"how do approved changes reach your repo?",options:[{value:"auto",label:"auto \u2014 CodePipe pushes the branch and opens a PR"},{value:"local",label:"local \u2014 changes wait; you pull them into your checkout via the CLI REPL (/apply or /unstash), no push/PR"}],initialValue:"auto"}))),v=await n.ask("trackerProvider",async()=>Ae(await yt({message:"task tracker",options:[{value:"internal",label:"built-in \u2014 CodePipe tracks tasks itself (no external tracker needed)"},{value:"youtrack",label:"YouTrack \u2014 connect an existing YouTrack project"}],initialValue:"internal"}))),x=v==="internal",I=null,E,$=!0;if(x){let b,R=zl();R.start("checking task-key prefixes on your account\u2026");try{b=await Kp(c,u,{excludeProjectId:f}),R.stop("prefixes checked")}catch{R.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 B=Ha(Ga(g),b);E=await n.ask("trackerPrefix",async()=>ue(await we({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:B,initialValue:B,validate:J=>{let Pe=J.trim();if(!kr.test(Pe))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(b.has(Pe.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else I=await n.ask("youtrack",()=>nw()),E=await n.ask("youtrackProjectKey",async()=>ue(await we({message:"YouTrack project key",placeholder:"DEV",validate:b=>b.trim().length>0?void 0:"required"})).trim()),$=await n.ask("youtrackWrites",async()=>Ae(await Fo({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let T=n.get("tokens")??{},N=()=>n.set("tokens",T),G=await n.ask("repos",()=>wC(T,l,a,{onCred:N,initial:n.get("reposPartial")??[],onProgress:b=>n.set("reposPartial",b)}));n.delete("reposPartial");let ee=await bC(await n.ask("contextRepo",()=>ew(f,G,T,l)),f,G,T,l,N,b=>n.set("contextRepo",b)),{spec:C,mode:k}=ee,M;x||(A.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),M=await n.ask("assigneeLogin",async()=>ue(await we({message:"your YouTrack login (the assignee value)",...I?.login?{initialValue:I.login}:{},validate:b=>b.trim().length>0?void 0:"required"})).trim()));let P=await n.ask("llmProvider",async()=>{for(;;){if(Ae(await yt({message:"LLM provider",options:[{value:"claude",label:"Claude",hint:"recommended"},{value:"codex",label:"Codex",hint:"coming soon"}],initialValue:"claude"}))==="claude")return"claude";A.warn("Codex support is coming soon \u2014 pick Claude for now.")}}),H=P==="claude"?await n.ask("claudeToken",()=>dk(uk("claude"),{farm:i==="farm"})):"",Y;if(H){let b=await Pp(H);if(b){let R=ha(b);R&&(Y=R,A.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${R} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let oe={projectId:f,name:g,automationLevel:w,repos:G,trackerProvider:v,youtrackProjectKey:E,language:h};A.step(`${k==="attach"?"attaching to":"provisioning"} Context Repo ${C.owner}/${C.name} (${C.host})\u2026`);let Ve;try{Ve=await Nn(oe,C,{...tw(T),youtrackWrites:$,...I?{trackerUrl:I.url}:{},mode:k,log:{info:b=>A.message(b),warn:b=>A.warn(b)}})}catch(b){le(`Context Repo provisioning failed: ${b instanceof Error?b.message:String(b)}`)}oe.contextRepo=Ve,A.success(`Context Repo ready: ${Ve.owner}/${Ve.name}@${Ve.branch}`),A.step(`registering project on ${c}\u2026`);let ze;try{ze=await Xt(c,u,oe)}catch(b){if(b instanceof W&&b.status===409){A.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{ze=await ne(c,u,f)}catch(R){throw R instanceof W&&le(`HUB \u2192 ${R.status} ${R.message}`),R}}else if(b instanceof W&&b.status===401)n.delete("cliToken"),le("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(b instanceof W)le(`HUB \u2192 ${b.status} ${b.message}`);else throw b}let _=ze.contextRepo??Ve;A.success(`project ${ze.projectId} ready (${ze.provisioningStatus})`);let U=I?{url:I.url,token:I.token}:void 0;if(i==="farm"){let b=d,R={...T,...H?{claude:{oauthToken:H}}:{},...U?{youtrack:U}:{}},B=T.github?.token;if(_.host==="github"&&B)try{let K=Xh(`devpipe-${f}`);await Jh(_,B,K.publicKey,`devpipe-${f}`),R.contextSsh={privateKey:K.privateKey},A.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(K){A.warn(`could not set up Context Repo SSH deploy key (${K instanceof Error?K.message:String(K)}); the farm will fall back to the token path.`)}let J={projectId:f,config:{hubUrl:c,cliToken:u,projectId:f},secrets:R,contextRepo:_,projectConfig:xt(oe,$,I?.url,M||void 0,"auto",P,Y)},Pe=Dt(b.farm.publicKey,JSON.stringify(J));A.step(`handing project ${f} to farm ${b.farm.name}\u2026`);let st;try{st=await ys(c,u,b.farm.farmId,{projectId:f,sealedBundle:Pe})}catch(K){throw K instanceof W&&le(K.status===409?`farm ${b.farm.name} is offline \u2014 start it and re-run.`:K.status===504?`farm ${b.farm.name} did not respond in time.`:`HUB \u2192 ${K.status} ${K.message}`),K}st.ok||le(`farm rejected provisioning: ${st.error??"unknown error"}`),await Yl(c,u,f,_,B,ze.repos,null,T),n.clear(),ql(`done. project ${f} is now hosted on farm ${b.farm.name} (daemon ${st.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}rw(T),await Jk(e,_.cloneUrl,_.branch),Qk(e),a&&await kC(e);{let b=ir(e,_t);an(b);let R=xt(oe,$,I?.url,M||void 0,y,P,Y),B=ho(b,R);B.length>0&&A.success(`local project config \u2192 .codepipe/{${B.join(", ")}}`),Ar(f,R,{info:J=>A.message(J),warn:J=>A.warn(J)})}await Zk(e,ze.repos);let D={hubUrl:c,cliToken:u,projectId:f,...T,...H?{claude:{oauthToken:H}}:{},...U?{youtrack:U}:{}};se(D),jt({hubUrl:c,cliToken:u,projectId:f,accountEmail:p},f),A.success(`secrets \u2192 ${$t(f)}`),await Yl(c,u,f,_,T.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,ze.repos,e,T),n.clear();let z=`${c}/?project=${encodeURIComponent(f)}`;vr(z),ql(`done. your project on the dashboard (sign in there to work with it):
|
|
938
903
|
${z}
|
|
939
|
-
starting codepipe \u2014 the CLI daemon
|
|
904
|
+
starting codepipe up \u2014 the CLI daemon and an agent worker, with their logs on screen. Ctrl+C to stop (restart anytime with \`codepipe up\` from this folder).`);let{upCommand:O}=await Promise.resolve().then(()=>(Ci(),Uk));await O({profile:void 0})}async function Yl(t,e,r,n,o,s=[],i=null,a={}){let c=await Ek(n,o),l=!1;if(!c)try{l=await Tk(s,{localRoot:i,tokens:a})}catch{l=!1}let u=Sk({indexExists:c,localClones:i!==null,reposNonEmpty:l}),p=await fC({message:u.message,options:u.options,initialValues:u.initialValues,required:!1});if(Vl(p))return;let d=new Set(p);if(d.has("map")&&i!==null)try{let m=Re(i);if(!m)throw new Error("workspace not found");let{bootstrapWorkspaceModel:f}=await Promise.resolve().then(()=>(Ao(),ri)),g=await f(m,void 0,{onLog:h=>A.message(h)});A.success(`project map ready: ${g.events} task events mined from history`)}catch(m){A.warn(`could not build the project map: ${m instanceof Error?m.message:String(m)}. Registration is not affected \u2014 run \`codepipe model bootstrap\` later.`)}if(d.has("backfill"))try{let{jobId:m}=await lo(t,e,r,{reindex:!1,backfill:!0});A.success(`retrospective architecture analysis queued (job ${m}); decision drafts will appear on the project card for review once a SANDBOX picks up the job.`)}catch(m){A.warn(`could not start the retrospective analysis: ${m instanceof Error?m.message:String(m)}. Registration is not affected.`)}if(d.has("index"))try{let{jobId:m}=await lo(t,e,r,{reindex:u.reindex});A.success(`indexing queued (job ${m}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(m){A.warn(`could not start indexing: ${m instanceof Error?m.message:String(m)}. You can retry later \u2014 registration is not affected.`)}}async function mC(t,e){let r;try{r=await Mp(t,e)}catch(c){throw c instanceof W&&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=Ae(await yt({message:"target farm",options:n.map(c=>({value:c.farmId,label:`${c.name}${c.online?"":" (offline)"} \u2014 ${c.keyFingerprint??"no fingerprint"}`}))})),s=n.find(c=>c.farmId===o),i;try{i=Js(s.farmId,s.publicKey)}catch(c){le(c instanceof Error?c.message:String(c))}return Ae(await Fo({message:`confirm farm ${s.name} cred-channel fingerprint:
|
|
940
905
|
${i}
|
|
941
|
-
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||le("farm fingerprint not confirmed \u2014 aborting."),
|
|
906
|
+
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||le("farm fingerprint not confirmed \u2014 aborting."),Xs(s.farmId,i),{farm:s,fingerprint:i}}async function Yk(t){Wk(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();Vk(e,t.force===!0);let r=ue(await we({message:"HUB URL",initialValue:X("HUB_URL")??at,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await Ln(),{cliToken:o,accountEmail:s}=await Dn(r,n);A.step(`fetching project ${t.projectId} from HUB\u2026`);let i;try{i=await ne(r,o,t.projectId)}catch(d){throw d instanceof W&&le(`HUB \u2192 ${d.status} ${d.message}`),d}i.contextRepo||le(`project ${t.projectId} has no Context Repo on HUB`);let c=i.trackerProvider==="internal"?null:await nw(),l={},u=new Set(i.repos.map(d=>d.host));u.add(i.contextRepo.host);for(let d of u){let m=i.repos.find(f=>f.host===d);await Ai(d,l,m?.owner??i.contextRepo.owner,n,m?.repoName)}rw(l),await Jk(e,i.contextRepo.cloneUrl,i.contextRepo.branch),Qk(e);{let d=ir(e,_t);an(d);let m={projectId:t.projectId,name:i.name,automationLevel:i.automationLevel,repos:i.repos,...i.trackerProvider?{trackerProvider:i.trackerProvider}:{},...i.youtrackProjectKey?{youtrackProjectKey:i.youtrackProjectKey}:{},...i.language?{language:i.language}:{}},f=xt(m,!0,c?.url,void 0,"auto",i.llmProvider??Ge),g=ho(d,f);g.length>0&&A.success(`local project config \u2192 .codepipe/{${g.join(", ")}} (defaults \u2014 review and adjust)`),Ar(t.projectId,f,{info:h=>A.message(h),warn:h=>A.warn(h)})}await Zk(e,i.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};se(p),jt({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:s},t.projectId),A.success(`secrets \u2192 ${$t(t.projectId)}`),await Yl(r,o,t.projectId,i.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,i.repos,e,l),ql("done.")}function Vk(t,e){if(!Lr(t)){Fk(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=dC(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 Hl(t){if(!Lr(ir(t,".git")))return null;try{let e=Ue(await zk(t));return e?{parsed:e,defaultBranch:await Xk(t)}:null}catch{return null}}async function zk(t){try{return(await _i(t).remote(["get-url","origin"])||"").toString().trim()}catch{return""}}async function hC(t,e){if(!Lr(ir(t,".git")))return null;let r=await e.ask("inPlaceOrigin",async()=>{let o=await zk(t);return A.warn(o?`this folder is a git checkout, but its origin (${o}) is not a github.com / gitlab.com / bitbucket.org URL`:"this folder is a git checkout without an `origin` remote"),ue(await we({message:"clone URL of this repository \u2014 blank if this folder is not the project repo",placeholder:"git@github.com:acme/api.git",validate:s=>!s||!s.trim()||Ue(s)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim()}),n=r?Ue(r):null;return n?{parsed:n,defaultBranch:await Xk(t)}:null}async function Xk(t){let e=_i(t);try{let n=(await e.raw(["symbolic-ref","--short","refs/remotes/origin/HEAD"])).trim().replace(/^origin\//,"");if(n)return n}catch{}try{let r=(await e.raw(["symbolic-ref","--short","HEAD"])).trim();if(r)return r}catch{}return"main"}function gC(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Kt.test(e)?e:""}function yC(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function kC(t){let e=ir(t,".gitignore"),r=Lr(e)?Kk(e,"utf-8"):"";if(yC(r))return;if(!Ae(await Fo({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){A.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
|
|
942
907
|
`)?"":`
|
|
943
|
-
`;
|
|
908
|
+
`;Gk(e,r+o+`
|
|
944
909
|
# codepipe workspace (added by \`codepipe init\`)
|
|
945
910
|
.codepipe/
|
|
946
|
-
`),A.success(`.codepipe/ added to ${
|
|
911
|
+
`),A.success(`.codepipe/ added to ${Hk(e)}`)}async function Ln(){let t="";try{t=(await _i().raw(["config","--global","user.email"])||"").trim()}catch{}return ue(await we({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function Dn(t,e){A.step(`connecting account ${e}`);let r;try{r=await Gp(t,e)}catch(i){throw i instanceof co&&le(`${e} is not authorized on this HUB yet.
|
|
947
912
|
Sign up at ${t} (registration form on the login screen),
|
|
948
913
|
wait for the operator to approve it by email, then re-run
|
|
949
914
|
\`codepipe init\` with the same email.`),i}r.accountCreated&&A.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&A.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(vr(r.authorizeUrl),A.message(`a browser tab was opened to confirm this CLI:
|
|
950
915
|
${r.authorizeUrl}
|
|
951
916
|
`+(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
|
|
952
|
-
otherwise use the emailed link the page offers.`))),r.approvalRequired&&A.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),A.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let n=!1,o=Date.now(),s=o+15*6e4;for(;Date.now()<s;){let i;try{i=await
|
|
953
|
-
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await
|
|
917
|
+
otherwise use the emailed link the page offers.`))),r.approvalRequired&&A.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),A.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let n=!1,o=Date.now(),s=o+15*6e4;for(;Date.now()<s;){let i;try{i=await Hp(t,r.requestId)}catch(a){A.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await Wl(5e3);continue}if(i.status==="confirmed"&&i.cliToken){let a=i.email??e;return a!==e&&A.message(`connected as ${a} (the account confirmed in the browser).`),A.success("confirmed"),{cliToken:i.cliToken,accountEmail:a}}if(i.status==="rejected"&&le("the HUB rejected this account"),i.status==="expired"&&le("the request expired \u2014 re-run init"),i.status==="waiting_approval"||i.status==="email_confirmed"){n||(n=!0,s=o+24*60*6e4,A.message(`email confirmed. waiting for the operator to approve your account\u2026
|
|
918
|
+
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await Wl(5e3);continue}await Wl(2e3)}le("bootstrap timed out")}async function Jk(t,e,r){let n=ir(t,_t);if(Lr(ir(n,".git"))){A.message(`${n} already cloned \u2014 skipping`);return}Lr(n)&&le(`${n} exists but is not a git repo \u2014 remove it and re-run`),Fk(n,{recursive:!0}),A.step(`cloning Context Repo \u2192 ${n}`);try{await _i().clone(e,n,["--branch",r]),A.success(`cloned ${e}`)}catch(o){le(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function Zk(t,e){if(e.length===0)return;A.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(o=>({name:o.name,host:o.host,owner:o.owner,repoName:o.repoName,defaultBranch:o.defaultBranch??"main",mountAs:o.mountAs??o.name})),n=await Uo(t,r,{log:{info:o=>A.message(o),warn:o=>A.warn(o)}});for(let o of n)A.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function Qk(t){let e=ir(t,_t,".gitignore"),r="";if(Lr(e)&&(r=Kk(e,"utf-8")),Bk.filter(i=>i.startsWith("#")?!1:!r.split(/\r?\n/).includes(i)).length===0)return;let o=r.endsWith(`
|
|
954
919
|
`)||r.length===0?"":`
|
|
955
|
-
`,s=
|
|
920
|
+
`,s=Bk.join(`
|
|
956
921
|
`)+`
|
|
957
|
-
`;
|
|
958
|
-
`:"")+s),A.message(`appended runtime entries to ${
|
|
922
|
+
`;Gk(e,r+o+(r?`
|
|
923
|
+
`:"")+s),A.message(`appended runtime entries to ${Hk(e)}`)}async function wC(t,e,r,n={}){let o=[...n.initial??[]],s=n.onCred;if(r&&o.length===0){let{parsed:i,defaultBranch:a}=r;await Ai(i.host,t,i.owner,e,i.repoName),s?.(),o.push({name:i.repoName,host:i.host,owner:i.owner,repoName:i.repoName,defaultBranch:a,mountAs:"."}),n.onProgress?.(o),A.success(`added this repository: ${i.host}: ${i.owner}/${i.repoName} (this folder, default branch ${a})`)}for(;Ae(await Fo({message:o.length===0?"Add a project repository?":`Project repositories: ${o.map(m=>m.name).join(", ")}. Add another one?`,initialValue:o.length===0}));){let a=ue(await we({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:m=>!m||!m.trim()||Ue(m)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!a)continue;let c=Ue(a);A.message(`${c.host}: ${c.owner}/${c.repoName}`),await Ai(c.host,t,c.owner,e,c.repoName),s?.();let l=ue(await we({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:m=>m.trim().length>0?void 0:"required"})).trim(),u=ue(await we({message:"default branch (optional)",placeholder:"main"})).trim(),p=ue(await we({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),d={name:l,host:c.host,owner:c.owner,repoName:c.repoName};u&&(d.defaultBranch=u),p&&p!==l&&(d.mountAs=p),o.push(d),n.onProgress?.(o)}return o}async function ew(t,e,r,n){A.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let o=Ae(await yt({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));o==="attach"&&A.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let s=e[0]?.host,i=e[0]?.owner,a;if(s&&i){let c=ue(await we({message:`Context Repo \u2014 a name (hosted at ${s}: ${i}/<name>) or a full clone URL`,initialValue:wt(t),validate:u=>{let p=(u??"").trim();if(!p)return"required";if(!Ue(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=Ue(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:s,owner:i,name:c}}else{let c=await $C(),l=ue(await we({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=ue(await we({message:"Context Repo name",placeholder:wt(t),initialValue:wt(t),validate:p=>p.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:o}}function tw(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??en()}}async function bC(t,e,r,n,o,s,i){let a=t;for(;;){let{spec:c,mode:l}=a;await Ai(c.host,n,c.owner,o),s?.();let u=zl();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let p=await fk(c,tw(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=Ae(await yt({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(d==="abort"&&le("aborted"),d==="create")return a={spec:c,mode:"create"},i(a),a;a=await ew(e,r,n,o),i(a)}}async function $C(){return Ae(await yt({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function ji(t,e){let r=zl();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 rw(t){bo(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),$o(t.gitlab?.token??process.env.GITLAB_TOKEN),vo(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Ai(t,e,r,n,o){if(!e[t])if(t==="github"){let s=await vC(r);s?e.github=s:A.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let s=await xC(r,n,o);s?e.bitbucket=s:A.warn("no Bitbucket API token \u2014 git falls back to this machine's SSH keys / BITBUCKET_* env; private repos won't clone over HTTPS and PRs won't open.")}else{let s=await SC();s?e.gitlab=s:A.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function vC(t){for(;;){let e=ue(await Pi({message:`GitHub PAT \u2014 blank to skip
|
|
959
924
|
classic PAT: 'repo' + 'workflow'
|
|
960
925
|
fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
|
|
961
926
|
if org: approve token in org Settings \u2192 Personal access tokens.
|
|
962
|
-
(Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo.)`})).trim();if(!e)return;if(await
|
|
927
|
+
(Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo.)`})).trim();if(!e)return;if(await ji("GitHub",()=>Ht(e,t?{owner:t}:void 0)))return{token:e};A.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function xC(t,e,r){for(A.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
|
|
963
928
|
How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
|
|
964
929
|
'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes:
|
|
965
930
|
read:repository:bitbucket + write:repository:bitbucket +
|
|
966
931
|
read:pullrequest:bitbucket + write:pullrequest:bitbucket
|
|
967
932
|
\u2014 write scopes do NOT include read: pick BOTH scopes of each pair
|
|
968
933
|
(+ admin:repository:bitbucket if this token will provision the Context Repo).
|
|
969
|
-
The token is shown ONCE \u2014 copy it right away.`);;){let n=ue(await we({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:s=>!s||!s.trim()||s.includes("@")?void 0:"must be an email"})).trim();if(!n)return;let o=ue(await
|
|
970
|
-
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await
|
|
971
|
-
[${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}_n();We();Te();async function Dk(t={profile:void 0}){let e=et(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=gs(e.hubUrl,e.cliToken),n=await new Promise(s=>{let i=[],a=!1,c=setTimeout(()=>{i.push("timeout"),r.close(),s({ok:!1,events:i})},5e3);r.on("open",()=>{i.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let u=l.toString("utf-8");if(i.push(`msg:${u}`),u!=="pong")try{let p=JSON.parse(u);p.type==="registered"?(a=!!p.ok,clearTimeout(c),r.send("ping")):p.type}catch{}}),r.on("error",l=>i.push(`error:${l.message}`)),r.on("close",(l,u)=>{i.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),s({ok:a,events:i})}),setTimeout(()=>r.close(),1500)});for(let s of n.events)console.log(` ${s}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let s=await ne(e.hubUrl,e.cliToken,e.projectId);if(s.duplicateIntake){let i=s.duplicateIntake;console.warn(`warning: project \xAB${i.withProjectId}\xBB watches the same YouTrack columns (${i.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=je(t.profile);o?o.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${o.sandboxId} (${o.name}), llm=${o.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${o.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}Bo();import{readFileSync as PA}from"node:fs";F();We();Lt();xi();Pr();Yt();$r();Te();de();function he(t){throw new Error(t)}function xe(t,e){return(typeof t!="string"||t.trim().length===0)&&he(`config: '${e}' must be a non-empty string`),t.trim()}function Go(t,e){if(t==null)return;typeof t!="string"&&he(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function _A(t){(!t||typeof t!="object")&&he("config: expected a JSON object");let e=t,r=xe(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||he("config: 'hubUrl' must start with http(s)://");let n=xe(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&he("config: 'project' is required");let s=o,i=xe(s.id,"project.id");Kt.test(i)||he("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=xe(s.name,"project.name"),c=xe(s.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&he("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=s.repos;Array.isArray(l)||he("config: 'project.repos' must be an array");let u=l.map((y,x)=>{(!y||typeof y!="object")&&he(`config: project.repos[${x}] must be an object`);let S=y,I=xe(S.host,`project.repos[${x}].host`);I!=="github"&&I!=="bitbucket"&&I!=="gitlab"&&he(`config: project.repos[${x}].host must be 'github', 'bitbucket' or 'gitlab'`);let E={name:xe(S.name,`project.repos[${x}].name`),host:I,owner:xe(S.owner,`project.repos[${x}].owner`),repoName:xe(S.repoName,`project.repos[${x}].repoName`)},$=Go(S.defaultBranch,`project.repos[${x}].defaultBranch`);$&&(E.defaultBranch=$);let T=Go(S.mountAs,`project.repos[${x}].mountAs`);return T&&(E.mountAs=T),E}),p=s.contextRepo;(!p||typeof p!="object")&&he("config: 'project.contextRepo' is required");let d=p,m=Go(d.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&he("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:m,owner:xe(d.owner,"project.contextRepo.owner"),name:Go(d.name,"project.contextRepo.name")??wt(i)},g={hubUrl:r,cliToken:n,project:{id:i,name:a,automationLevel:c,repos:u,contextRepo:f}},h=Go(s.youtrackProjectKey,"project.youtrackProjectKey");if(h&&(g.project.youtrackProjectKey=h),s.index!==void 0&&(typeof s.index!="boolean"&&he("config: 'project.index' must be a boolean"),g.project.index=s.index),s.youtrackWrites!==void 0&&(typeof s.youtrackWrites!="boolean"&&he("config: 'project.youtrackWrites' must be a boolean"),g.project.youtrackWrites=s.youtrackWrites),s.llmProvider!==void 0){let y=xe(s.llmProvider,"project.llmProvider");y==="codex"&&he(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),y!=="claude"&&he("config: 'project.llmProvider' must be 'claude'"),g.project.llmProvider=y}let w=e.secrets;if(w!==void 0){(typeof w!="object"||w===null)&&he("config: 'secrets' must be an object");let y=w,x={};if(y.github){let S=y.github;x.github={token:xe(S.token,"secrets.github.token")}}if(y.bitbucket){let S=y.bitbucket;x.bitbucket={email:xe(S.email,"secrets.bitbucket.email"),apiToken:xe(S.apiToken,"secrets.bitbucket.apiToken")}}if(y.gitlab){let S=y.gitlab;x.gitlab={token:xe(S.token,"secrets.gitlab.token")}}if(y.youtrack){let S=y.youtrack;x.youtrack={url:xe(S.url,"secrets.youtrack.url").replace(/\/$/,""),token:xe(S.token,"secrets.youtrack.token")}}if(y.contextWrite){let S=y.contextWrite;x.contextWrite={token:xe(S.token,"secrets.contextWrite.token")}}g.secrets=x}return g}async function jA(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function NA(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await Ht(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${n}`)}if(e.bitbucket){let r=t.project.repos.find(s=>s.host==="bitbucket"),n=r?.owner??(t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:void 0),o=await Wt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let s=await fs(e.bitbucket.email,e.bitbucket.apiToken,r.owner,r.repoName);if(s)throw new Error(`Bitbucket: ${s}`)}console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await qt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await zt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Gw(t){let e=!t.configPath||t.configPath==="-"?await jA():PA(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){he(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=_A(r),{hubUrl:o,cliToken:s,project:i}=n;console.log(`codepipe init --headless \u2192 ${o} (project=${i.id})`),t.skipVerify||(console.log("verifying credentials\u2026"),await NA(n));let a={projectId:i.id,name:i.name,automationLevel:i.automationLevel,repos:i.repos};i.youtrackProjectKey&&(a.youtrackProjectKey=i.youtrackProjectKey),console.log(`provisioning Context Repo ${i.contextRepo.owner}/${i.contextRepo.name} (${i.contextRepo.host})\u2026`);let c=n.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,l;try{l=await Nn(a,i.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??en(),youtrackWrites:i.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){he(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let u;try{u=await Xt(o,s,a)}catch(d){if(d instanceof W&&d.status===409)console.log(`project ${i.id} already exists on HUB \u2014 reusing it`),u=await ne(o,s,i.id);else if(d instanceof W)he(`HUB \u2192 ${d.status} ${d.message}`);else throw d}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let p={hubUrl:o,cliToken:s,projectId:i.id,...n.secrets??{}};if(se(p),jt({hubUrl:o,cliToken:s,projectId:i.id},i.id),console.log(`config + secrets written (profile ${i.id}) \u2192 ${$t(i.id)}`),Ar(i.id,xt(a,i.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,"auto",i.llmProvider??Ge),{info:d=>console.log(d),warn:d=>console.warn(d)}),i.index)try{let{jobId:d}=await lo(o,s,i.id,{reindex:!1});console.log(`index job enqueued (job ${d}); runs once a SANDBOX claims it.`)}catch(d){console.warn(`could not enqueue index job: ${d instanceof Error?d.message:String(d)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${i.id} daemon`)}We();de();import{cancel as Hw,intro as Ww,isCancel as qw,log as du,outro as OA,password as Yw}from"@clack/prompts";async function LA(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Vw(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await LA(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Ww("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),du.message("Run `claude setup-token` and paste the token below (input hidden).");let s=await Yw({message:"Claude OAuth token"});qw(s)&&(Hw("aborted"),process.exit(1)),e=s.trim()}e||(console.error("login: no token provided"),process.exit(1)),rp({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${as()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=et(t.profile);if(!e){Ww(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),du.message("Run `claude setup-token` and paste the token below (input hidden).");let s=await Yw({message:"Claude OAuth token"});qw(s)&&(Hw("aborted"),process.exit(1)),e=s.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=q(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},se(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(du.success("Claude OAuth token saved."),OA("It will be sealed into job bundles when a SANDBOX (re)connects."))}Ao();F();We();Lt();xi();Pr();Si();Te();de();import{cancel as DA,confirm as MA,intro as UA,isCancel as zw,log as Ne,outro as BA,select as Xw,text as lr}from"@clack/prompts";function Jw(t){DA(t),process.exit(1)}function Un(t){return zw(t)&&Jw("aborted"),t}function Ho(t){return zw(t)&&Jw("aborted"),typeof t=="string"?t:""}async function FA(t,e){let r=Un(await Xw({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),n=e.find(i=>i.host===r)?.owner??e[0]?.owner??"",o=Ho(await lr({message:"Context Repo owner (org / group / workspace / user)",placeholder:n||"your-org",initialValue:n,validate:i=>i.trim().length>0?void 0:"required"})).trim(),s=Ho(await lr({message:"Context Repo name",placeholder:wt(t),initialValue:wt(t),validate:i=>i.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:s}}async function Zw(t={profile:void 0}){let e=et(t.profile);UA(`codepipe project add \u2192 ${e.hubUrl}`);let r=Un(await lr({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>Kt.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=Un(await lr({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=Un(await Xw({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"})),s=Un(await lr({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),i=Un(await MA({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=Ho(await lr({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:w=>!w||!w.trim()||Ue(w)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!d)break;let m=Ue(d);Ne.message(`${m.host}: ${m.owner}/${m.repoName}`);let f=Ho(await lr({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:w=>w.trim().length>0?void 0:"required"})).trim(),g=Ho(await lr({message:"default branch (optional)",placeholder:"main"})).trim(),h={name:f,host:m.host,owner:m.owner,repoName:m.repoName};g&&(h.defaultBranch=g),a.push(h)}let c={projectId:r,name:n,automationLevel:o,repos:a};s&&(c.youtrackProjectKey=s);let l=await FA(r,a),u=q(e.projectId);Ne.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await Nn(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??en(),youtrackWrites:i,trackerUrl:u?.youtrack?.url,log:{info:d=>Ne.message(d),warn:d=>Ne.warn(d)}})}catch(d){Ne.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,Ne.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await Xt(e.hubUrl,e.cliToken,c);Ne.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),Ar(r,xt(c,i,u?.youtrack?.url),{info:m=>Ne.message(m),warn:m=>Ne.warn(m)}),d.contextRepo&&(Ne.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),Ne.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&Ne.error(` error: ${d.provisioningError}`),BA("done")}catch(d){d instanceof W?(Ne.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&Ne.message(JSON.stringify(d.payload,null,2))):Ne.error(d instanceof Error?d.message:String(d)),process.exit(1)}}_n();We();Te();de();bt();Bo();import{existsSync as KA,rmSync as GA}from"node:fs";import{confirm as HA,intro as WA,isCancel as qA,log as ur,outro as YA,spinner as VA}from"@clack/prompts";function Rt(t){ur.error(t),process.exit(1)}var Qw=t=>t.trim().replace(/\/+$/,"");async function eb(t){WA("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Re()?.spec.projectId??void 0;e||Rt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=dt(e);r||Rt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Qw(r.hubUrl),o=r.projectId,s=Qw(t.hub);s.startsWith("http")||Rt("--hub must be an http(s):// URL");let i=t.toProfile??e,a=t.project??o,c=i===e;c&&a===o&&s===n&&Rt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let w=VA();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 W&&Rt(`source HUB ${n} \u2192 ${y.status} ${y.message}. The source HUB must be reachable with a valid token to move a project.`),y}}l.contextRepo||Rt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=q(o),p=(t.account??r.accountEmail??await Dn()).trim().toLowerCase();if(ur.message(`move project '${o}'
|
|
934
|
+
The token is shown ONCE \u2014 copy it right away.`);;){let n=ue(await we({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:s=>!s||!s.trim()||s.includes("@")?void 0:"must be an email"})).trim();if(!n)return;let o=ue(await Pi({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){A.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await ji("Bitbucket",async()=>{let s=await Wt(n,o,t);if(t&&r){let i=await fs(n,o,t,r);if(i)throw new Error(i)}return s}))return{email:n,apiToken:o};A.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function SC(){for(;;){let t=ue(await Pi({message:`GitLab PAT \u2014 blank to skip
|
|
935
|
+
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await ji("GitLab",()=>qt(t))){let e=await Qd(t);return e&&A.warn(e),{token:t}}A.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function EC(){let t="__other__",e=async()=>ue(await we({message:"language name (in English, e.g. Ukrainian)",validate:i=>{let a=i.trim();if(a.length===0)return"required";if(a.length>40)return`\u2264 ${40} chars`}})).trim(),r=Ae(await yt({message:"project language",options:[...Vr.map(i=>({value:i,label:i==="English"?"English (default)":i})),{value:t,label:"other\u2026"}],initialValue:"English"})),n=r===t?await e():r;if(n==="English")return{primary:n,context:n,tasks:n,docs:n,code_comments:n,chat:ye};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:ye}],s={primary:n};for(let i of o){let a=new Set,c=[i.initial,n,"English",ye].filter(u=>a.has(u)?!1:(a.add(u),!0)).map(u=>({value:u,label:u===ye?"auto \u2014 mirror the language of the user's material":u}));c.push({value:t,label:"other\u2026"});let l=Ae(await yt({message:`language for ${i.label}`,options:c,initialValue:i.initial}));s[i.key]=l===t?await e():l}return s}async function nw(){for(;;){let t=ue(await we({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let n=r.trim();if(!n)return"required";if(!n.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=ue(await Pi({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await ji("YouTrack",()=>zt({baseUrl:t,token:e}))){let r=await fp({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}A.warn("re-enter the YouTrack URL / token.")}}var Bk,Bo=S(()=>{"use strict";Le();F();ot();pk();hs();We();Lt();Pr();nn();$i();bl();vi();Yt();$r();xk();Te();Rk();Ck();ol();Ns();de();Si();bt();Bk=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});F();Le();We();import{Command as PA}from"commander";We();de();async function Wd(t){let e=t.profile??t.project;t.profile&&t.profile!==t.project&&(console.error(`--profile (${t.profile}) must equal --project (${t.project}). Profile id is the project id.`),process.exit(1));let r=dt(e);r&&!t.force&&(console.error(`already configured at ${Zr(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");jt({hubUrl:n,cliToken:t.token,projectId:t.project},e);let s={...q(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};se(s),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${Zr(e)}`)}Xa();We();import{homedir as vl}from"node:os";import{join as Po}from"node:path";Le();F();import{existsSync as Yh,rmSync as kE}from"node:fs";import{join as jr}from"node:path";import{simpleGit as wE}from"simple-git";import"ws";Le();de();import{createHash as f$}from"node:crypto";import{existsSync as m$,readFileSync as h$}from"node:fs";import{homedir as g$,hostname as Ja}from"node:os";import{join as y$}from"node:path";function zd(t){return f$("sha256").update(t).digest("hex").slice(0,12)}function k$(){let t=X("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=y$(g$(),".claude","credentials.json");if(!m$(e))return;let r=JSON.parse(h$(e,"utf-8")),n=[r.email,r.account?.email,r.user?.email];for(let o of n)if(typeof o=="string"&&o.includes("@"))return o.trim().toLowerCase()}catch{}}function Xd(t){let e=k$(),r=X("ACCOUNT_ID")?.trim(),n=X("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=Qr(t);return o?{accountId:`acct-${zd(o)}`,label:n||Ja(),...e?{email:e}:{}}:{accountId:`acct-${zd(`host:${Ja()}`)}`,label:n||Ja(),...e?{email:e}:{}}}Le();nn();de();dc();async function Op(t,e,r,n,o){let s=c=>{e.readyState===e.OPEN&&e.send(JSON.stringify(c))},i=c=>s({type:"agent_login_url",requestId:r.requestId,projectId:t.projectId,error:c});if(X("ORIGIN")==="farm"||X("CLAUDE_AUTOLOGIN")==="0"){i("autologin_disabled");return}let a;try{a=await uc(ms())}catch(c){i(`listener failed: ${c instanceof Error?c.message:String(c)}`);return}s({type:"agent_login_url",requestId:r.requestId,projectId:t.projectId,authUrl:a.authUrl}),n.info(`[agent-auth] authorize Claude in a browser on THIS machine: ${a.authUrl}`),n.info(`[agent-auth] waiting for the redirect on ${a.redirectUri} \u2026`);try{let c=await a.waitForToken(),l=await Nt(c.oauthToken);if(l==="invalid"){s({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"token rejected (401) \u2014 previous token kept"}),n.warn("[agent-auth] new Claude token rejected (401) \u2014 previous token kept");return}let u=q(t.projectId);if(!u){s({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"no secrets file for this project on the CLI"}),n.warn("[agent-auth] no secrets file for this project \u2014 token not saved");return}u.claude={oauthToken:c.oauthToken},se(u),n.info(`[agent-auth] Claude token replaced (${c.oauthToken.slice(0,12)}\u2026, ${c.oauthToken.length} chars)`),s({type:"agent_login_result",projectId:t.projectId,ok:!0,...l==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}}),o()}catch(c){let l=c instanceof Error?c.message:String(c);s({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:l}),n.warn(`[agent-auth] browser authorization failed: ${l}`)}finally{a.close()}}Le();function Lp(t,e){let r=t.find(n=>n.kind==="claude");return r?.present===!0&&r.ok===!1?X("ORIGIN")==="farm"||X("CLAUDE_AUTOLOGIN")==="0"||e?"none":"open":r?.ok===!0?"rearm":"none"}function Dp(t,e){return`${t.replace(/\/$/,"")}/?project=${encodeURIComponent(e)}`}hs();Te();Rr();import{existsSync as xs,readFileSync as Z$,writeFileSync as Q$}from"node:fs";import{join as Tr}from"node:path";import{simpleGit as vs}from"simple-git";var lf=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],ev="apply-queue.json";function uf(t){return Tr(t,ev)}function Cr(t){let e=uf(t);if(!xs(e))return{};try{return JSON.parse(Z$(e,"utf-8"))}catch{return{}}}function gc(t,e){Q$(uf(t),JSON.stringify(e,null,2)+`
|
|
936
|
+
`)}async function df(t,e,r,n,o){let s;try{s=await fc(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(d){return{ok:!1,message:`claim failed: ${d instanceof Error?d.message:String(d)}`}}let i=[];for(let d of s.repos){let m=t.spec.repos.find(w=>w.name===d.repoName);if(!m)return{ok:!1,message:`repo "${d.repoName}" not in project.yaml \u2014 run /sync`};let f=Tr(t.root,m.mountAs);if(!xs(Tr(f,".git")))return{ok:!1,message:`${m.mountAs}/ not cloned \u2014 run /sync first`};if(!(await vs(f).status()).isClean())return{ok:!1,message:`${m.mountAs}/ has uncommitted changes \u2014 commit or stash first`};i.push({claimRepo:d,spec:m,dir:f})}let a=[];for(let d of i){let m=vs(d.dir),f=await tv(m),g=d.claimRepo;try{await m.fetch()}catch(y){return await hc(a,o),{ok:!1,message:`fetch failed in ${d.spec.mountAs}: ${Ir(y)}`}}let h=`origin/${g.baseRef}`,w;try{w=await Er(m,{contextRepoCloneUrl:g.contextRepoCloneUrl,deliveryRef:g.deliveryRef,deliverySha:g.deliverySha,baseSha:g.baseSha,commitMessage:g.commitMessage})}catch(y){return await hc(a,o),{ok:!1,message:`fetch delivery failed in ${d.spec.mountAs}: ${Ir(y)}`}}a.push({git:m,dir:d.dir,mountAs:d.spec.mountAs,originalRef:f,branch:g.branchName,baseSha:h,deliveryCommit:w,startPoint:h})}let c=[];for(let d of a)try{if(n==="apply"){await d.git.checkout(["-B",d.branch,d.startPoint]),await d.git.raw([...lf,"cherry-pick",d.deliveryCommit]);let m=(await d.git.revparse(["HEAD"])).trim();c.push({mountAs:d.mountAs,branch:d.branch,baseSha:d.baseSha,appliedSha:m})}else await d.git.checkout(["--detach",d.startPoint]),await d.git.raw([...lf,"cherry-pick","--no-commit",d.deliveryCommit]),await d.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:d.mountAs,branch:d.branch,baseSha:d.baseSha})}catch(m){return await d.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await hc(a,o),{ok:!1,message:`apply failed in ${d.mountAs}: ${Ir(m)} (rolled back all repos)`}}let l=Cr(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},gc(t.contextDir,l);let u=c.map(d=>d.mountAs).join(", "),p=n==="apply"?`review, push branch '${s.repos[0]?.branchName}', then: /applied ${r} --pr <url>`:`review with 'git diff', commit & push yourself, then: /applied ${r} --pr <url>`;return{ok:!0,message:`${n==="apply"?"applied":"unstashed"} ${r} in ${u}
|
|
937
|
+
${p}
|
|
938
|
+
or: /abort ${r} --reason "..."`}}async function pf(t,e,r){let n=[];for(let c of e.repos){let l=t.repos.find(p=>p.name===c.repoName);if(!l)return{ok:!1,message:`repo "${c.repoName}" not in project.yaml \u2014 run /sync`};let u=Tr(t.root,l.mountAs);if(!xs(Tr(u,".git")))return{ok:!1,message:`${l.mountAs}/ not cloned \u2014 run /sync first`};n.push({git:vs(u),dir:u,spec:l,cr:c})}let o=[],s=[];for(let c of n)try{let{commit:l}=await nf(c.git,c.dir,{contextRepoCloneUrl:c.cr.contextRepoCloneUrl,deliveryRef:c.cr.deliveryRef,deliverySha:c.cr.deliverySha,baseSha:c.cr.baseSha,baseRef:c.cr.baseRef,branchName:c.cr.branchName,commitMessage:c.cr.commitMessage,defaultBranch:c.spec.defaultBranch});r.info(`[apply] ${e.taskKey}: ${c.cr.branchName} \u2192 ${c.spec.mountAs} (${l.slice(0,10)})`),o.push({git:c.git,branch:c.cr.branchName}),s.push({mountAs:c.spec.mountAs,branch:c.cr.branchName,baseSha:`origin/${c.cr.baseRef}`,appliedSha:l})}catch(l){for(let u of o)await u.git.raw(["branch","-D",u.branch]).catch(()=>{});return{ok:!1,message:`auto-apply failed in ${c.spec.mountAs}: ${Ir(l)}`}}try{await fc(t.hubUrl,t.cliToken,t.projectId,e.taskKey)}catch(c){return{ok:!1,message:`branch created but claim failed: ${Ir(c)} \u2014 retried on the next reconnect`,branches:o.map(l=>l.branch)}}let i=Cr(t.contextDir);i[e.taskKey]={mode:"apply",claimedAt:new Date().toISOString(),repos:s},gc(t.contextDir,i);let a=s.map(c=>`${c.branch} (${c.mountAs})`).join(", ");return{ok:!0,branches:s.map(c=>c.branch),message:`branch created locally without touching your checkout: ${a}
|
|
939
|
+
review, push, then: /applied ${e.taskKey} --pr <url>
|
|
940
|
+
or: /abort ${e.taskKey} --reason "..."`}}function yc(t,e){let r=Cr(t);r[e]&&(delete r[e],gc(t,r))}async function hc(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}: ${Ir(n)} \u2014 check manually`)}}async function ff(t,e,r){let o=Cr(t.contextDir)[e];if(o){for(let s of o.repos){let i=Tr(t.root,s.mountAs);if(!xs(Tr(i,".git")))continue;let a=vs(i),c=t.spec.repos.find(u=>u.mountAs===s.mountAs),l=c?`origin/${c.defaultBranch}`:s.baseSha;try{await a.checkout(["-f",l]),await a.reset(["--hard",l]),await a.raw(["branch","-D",s.branch]).catch(()=>{})}catch(u){r.warn(`rollback failed in ${s.mountAs}: ${Ir(u)} \u2014 check manually`)}}yc(t.contextDir,e)}}async function tv(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function Ir(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as rv}from"node:fs";import{join as nv}from"node:path";import{simpleGit as ov}from"simple-git";async function mf(t,e){if(!rv(nv(t,".git")))return{status:"skipped"};let r=ov(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${sv(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 sv(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as wc,readFileSync as wf,readdirSync as cv,watch as lv}from"node:fs";import{join as mo}from"node:path";F();import{existsSync as hf,readFileSync as gf,readdirSync as iv,statSync as av}from"node:fs";import{join as kc}from"node:path";import{parse as yf}from"yaml";function Ss(t){let e=kc(t,"actions"),r=[],n=[];if(!hf(e))return{defs:r,errors:n};let o;try{o=iv(e).sort()}catch{return{defs:r,errors:n}}let s=new Set;for(let i of o){if(!/\.(yml|yaml)$/i.test(i))continue;let a=kc(e,i);try{if(!av(a).isFile())continue;let c=ba(i,yf(gf(a,"utf-8")));if(s.has(c.id))throw new Error(`duplicate action id "${c.id}"`);s.add(c.id),r.push(c)}catch(c){n.push({file:`actions/${i}`,error:c instanceof Error?c.message:String(c)})}}return{defs:r,errors:n}}function kf(t){let e={},r=kc(t,"project.yaml");if(!hf(r))return e;let n;try{n=yf(gf(r,"utf-8"))}catch{return e}if(!n||typeof n!="object")return e;let o=n.variables;if(!o||typeof o!="object"||Array.isArray(o))return e;for(let[s,i]of Object.entries(o))!He.test(s)||Pt(s)||(typeof i=="string"?e[s]=i:(typeof i=="number"||typeof i=="boolean")&&(e[s]=String(i)));return e}var Es=class{constructor(e,r,n,o,s=6e4){this.contextDir=e;this.projectId=r;this.send=n;this.log=o;this.intervalMs=s}timer=null;watchers=[];debounce=null;started=!1;start(){this.started||(this.started=!0,this.report(),this.timer=setInterval(()=>this.report(),this.intervalMs),this.timer.unref?.(),this.installWatcher())}stop(){this.started=!1,this.timer&&clearInterval(this.timer),this.timer=null,this.debounce&&clearTimeout(this.debounce),this.debounce=null;for(let e of this.watchers)try{e.close()}catch{}this.watchers=[]}installWatcher(){let e=()=>{this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>this.report(),500),this.debounce.unref?.()},r=[this.contextDir,mo(this.contextDir,"prompts"),mo(this.contextDir,"actions")];for(let n of r)if(wc(n))try{let o=lv(n,e);o.on("error",s=>{this.log.warn(`[config] fs.watch failed on ${n} \u2014 falling back to periodic reporting: ${s instanceof Error?s.message:String(s)}`);try{o.close()}catch{}}),this.watchers.push(o)}catch{}}reportNow(){this.report()}report(){try{this.send(this.read())}catch(e){this.log.warn(`[config] report failed: ${e instanceof Error?e.message:String(e)}`)}}read(){let e=Ss(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=mo(this.contextDir,e);if(!wc(r))return null;try{return wf(r,"utf-8")}catch{return null}}readPrompts(){let e=mo(this.contextDir,"prompts"),r={};if(!wc(e))return r;let n;try{n=cv(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let s=o.slice(0,-3);try{r[s]=wf(mo(e,o),"utf-8")}catch{}}return r}};nt();import{existsSync as Ic,readFileSync as Rf,readdirSync as vv}from"node:fs";import{join as If}from"node:path";import{simpleGit as xv}from"simple-git";var Sv=/^(\d{4})-(.+)\.md$/,Ev="0000-template.md";function Rv(t){let e=t.split(`
|
|
941
|
+
`),r=e.find(s=>s.startsWith("# ")),n=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",o=s=>{let i=new RegExp(`^-\\s*\\*\\*${s}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=i.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:n,status:o("Status"),date:o("Date")}}function Iv(t,e,r,n,o){let s=String(e).padStart(4,"0"),i=t.split(`
|
|
942
|
+
`),a=i.findIndex(w=>w.startsWith("# ")),c=a>=0&&(i[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),u=[],p="",d=null,m=a>=0?a+1:0;for(let w=m;w<i.length;w++){let y=(i[w]??"").trim();if(y===""){m=w+1;continue}let v=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(y);if(!v)break;let x=(v[1]??"").trim().toLowerCase(),I=(v[2]??"").trim(),E=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(y);E&&(d=parseInt(E[1]??"",10)),x==="tasks"&&(p=I),l.has(x)||u.push(y),m=w+1}let f=p?p.includes(n)?p:`${p}, ${n}`:n,g=i.slice(m).join(`
|
|
943
|
+
`).replace(/^\n+/,""),h=[`# ADR-${s}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${f}`,...u,"",g].join(`
|
|
944
|
+
`);return{content:h.endsWith(`
|
|
945
|
+
`)?h:h+`
|
|
946
|
+
`,supersedes:d}}function Tv(t,e){let r=String(e).padStart(4,"0"),n=t.replace(/^(-\s*\*\*Status:\*\*).*$/im,`$1 superseded by ADR-${r}`);return n===t?t.replace(/^(# .*)$/m,`$1
|
|
947
|
+
|
|
948
|
+
- **Status:** superseded by ADR-${r}`):n}function Cv(t){let e=["# ADR index","","<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->",""];if(t.length===0)e.push("(no accepted ADRs yet)");else for(let r of[...t].sort((n,o)=>n.num-o.num)){let n=String(r.num).padStart(4,"0"),o=[r.header.status||"accepted",r.header.date].filter(Boolean).join(", ");e.push(`- [ADR-${n} \u2014 ${r.header.title||r.file}](${r.file}) \u2014 ${o}`)}return e.join(`
|
|
949
|
+
`)+`
|
|
950
|
+
`}async function Tf(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await xv(t).pull(void 0,void 0,["--rebase"])}catch{}let s=h=>o==="staging"?`adr/DRAFT-${h}.md`:`tasks/${e}/adr/DRAFT-${h}.md`,i=[],a=[];for(let h of r){let w=ke(t,s(h));if(!Ic(w)){a.push(h);continue}i.push({slug:h,content:Rf(w,"utf-8")})}let c=If(t,"adr"),l=new Map;if(Ic(c))for(let h of vv(c)){let w=Sv.exec(h);!w||h===Ev||l.set(h,{num:parseInt(w[1]??"",10),slug:w[2]??"",content:Rf(If(c,h),"utf-8")})}let u=Math.max(0,...[...l.values()].map(h=>h.num))+1,p=new Map,d=[],m=[];for(let h of i){if([...l.entries()].find(([,E])=>E.slug===h.slug&&E.content.includes(e))){m.push(h.slug);continue}let y=u++,v=`${String(y).padStart(4,"0")}-${h.slug}.md`,{content:x,supersedes:I}=Iv(h.content,y,h.slug,e,n);if(p.set(v,x),l.set(v,{num:y,slug:h.slug,content:x}),d.push(`adr/${v}`),I!==null){let E=[...l.keys()].find($=>$.startsWith(`${String(I).padStart(4,"0")}-`));if(E&&E!==v){let $=Tv(p.get(E)??l.get(E).content,y);p.set(E,$),l.set(E,{...l.get(E),content:$})}}}let f=[];if(o==="staging")for(let h of i)Ic(ke(t,`adr/DRAFT-${h.slug}.md`))&&f.push({path:`adr/DRAFT-${h.slug}.md`,content:"",deleted:!0});if(d.length===0&&f.length===0)return{promoted:d,skipped:m,missing:a};if(d.length>0){let h=[...l.entries()].map(([w,y])=>({num:y.num,file:w,header:Rv(y.content)}));p.set("INDEX.md",Cv(h))}for(let[h,w]of p.entries())f.push({path:`adr/${h}`,content:w});let g=d.length>0?`adr(${e}): promote ${i.map(h=>h.slug).join(", ")}`:`adr(${e}): drop stale staged ${m.join(", ")}`;return await ve(t,f,g),{promoted:d,skipped:m,missing:a}}nt();Lt();F();import{existsSync as Cf,readFileSync as Av}from"node:fs";import{join as Af}from"node:path";function Pv(t){for(let e of[lt,Hr]){let r=Af(t,e);if(Cf(r))try{return qi(Av(r,"utf-8"))}catch{return 0}}return 0}function _v(t,e,r,n=6){let o=e<n,s=o?Yi(e).filter(i=>!r(i)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:s}}function As(t,e){return _v(e,Pv(t),r=>Cf(Af(t,r)))}F();Yt();import{existsSync as Ff,mkdirSync as ix,mkdtempSync as ax,rmSync as Kf,writeFileSync as Gf}from"node:fs";import{tmpdir as cx}from"node:os";import{dirname as lx,join as _s}from"node:path";import{simpleGit as Pc}from"simple-git";Pr();function ux(t){return`codepipe/context-migration-v${t}`}function dx(t){let e=Vi(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 \`${lt}\` stamp (renamed from \`${Hr}\``,"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(`
|
|
951
|
+
`)}async function Hf(t,e,r,n){let o=Pc(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let s=As(t,e);if(!s.outdated)return s;let i=ux(s.currentVersion),a=r?.branch??(await o.revparse(["--abbrev-ref","HEAD"]).catch(()=>"main")).trim();try{await o.fetch().catch(()=>{}),(await o.raw(["ls-remote","--heads","origin",i]).catch(()=>"")).trim().length===0?await px(t,e,r,s,i,a,n):n.info(`[ctx] migration branch ${i} already on origin \u2014 reusing`)}catch(l){return n.warn(`[ctx] context migration branch failed (will retry next start): ${l instanceof Error?l.message:String(l)}`),s}if(!r)return s;let c={name:r.name,host:r.host,owner:r.owner,repoName:r.name};try{let l=pt(c),u=await l.findOpenPrByBranch?.(c,i)??null;if(u)return n.info(`[ctx] migration PR already open: ${u.url}`),{...s,migrationPrUrl:u.url};let p=await l.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:i,baseBranch:a,title:`CodePipe: context format v${s.templateVersion} \u2192 v${s.currentVersion}`,body:dx(s)});return n.info(`[ctx] migration PR opened: ${p.url}`),{...s,migrationPrUrl:p.url}}catch(l){return n.warn(`[ctx] migration PR create/find failed (branch pushed, badge without link): ${l instanceof Error?l.message:String(l)}`),s}}async function px(t,e,r,n,o,s,i){let a=Pc(t),c=ax(_s(cx(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",o,c,`origin/${s}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},u={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},p=new Map(ln(l,u).map(g=>[g.path,g.content])),d=0;for(let g of n.missingPaths){if(g===lt)continue;let h=p.get(g);if(h==null){i.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let w=_s(c,g);Ff(w)||(ix(lx(w),{recursive:!0}),Gf(w,h),d++)}Gf(_s(c,lt),Vn(n.currentVersion)),d++;let m=_s(c,Hr);Ff(m)&&(Kf(m,{force:!0}),d++);let f=Pc(c);await f.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await f.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await f.push(["-u","origin",o]),i.info(`[ctx] migration branch ${o} pushed (${d} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),Kf(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{existsSync as fx,readFileSync as mx,writeFileSync as hx}from"node:fs";import{homedir as gx}from"node:os";import{join as Wf}from"node:path";import{parseDocument as yx}from"yaml";function kx(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 wx(t,e){let r=yx(t);return r.set("repos",e.map(kx)),r.toString()}function bx(t,e){let r=[Wf(gx(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(Wf(e,"project.yaml")),r}function wo(t,e,r){let n=[],o=[];for(let s of bx(t,r))if(fx(s))try{let i=mx(s,"utf-8"),a=wx(i,e);a!==i&&(hx(s,a),n.push(s))}catch(i){o.push({path:s,error:i instanceof Error?i.message:String(i)})}return{updated:n,errors:o}}Rr();ot();de();function Rx(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 Xf(t,e,r,n){let o=Rx(e,r);t.sandboxes.length>0&&!o.claudeOauthToken&&n.warn("[cred] no Claude OAuth token set \u2014 agent jobs will fail in the SANDBOX. Set one with `codepipe login` (per project) or `make farm-config` (shared farm token)."),t.sandboxes.length>0&&!o.contextWrite&&(o.github||o.gitlab||o.bitbucket)&&n.warn("[cred] no dedicated contextWrite token \u2014 SANDBOX pushes deliveries with the project token of the context repo's host (broader scope than necessary). Set secrets.contextWrite.token (a token scoped to the Context Repo only) to tighten. NOTE (GitHub): the push token MUST have the `workflow` scope, else delivery pushes that carry `.github/workflows/*` are rejected.");let s=JSON.stringify(o),i=[];for(let a of t.sandboxes){let c=is(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=Dt(a.publicKey,s)}catch(u){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}i.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return i}ot();de();Yt();$r();nn();Ns();function em(t){let e=q(t);if(!e)return null;if(!e.sealKey){let r=js();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},se(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:De(e.sealKey.publicKey)}}async function tm(t,e,r,n){let o;try{o=JSON.parse(un(n,r).toString("utf-8"))}catch(i){return{ok:!1,detail:`cannot open the sealed credential (${i instanceof Error?i.message:String(i)}) \u2014 wrong channel key?`}}let s=q(t);if(!s)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!o.token)return{ok:!1,detail:"payload has no token"};let i=await Ht(o.token);return s.github={token:o.token},dn(s,()=>{process.env.GH_TOKEN=o.token,Jf(o.token)}),{ok:!0,detail:`authenticated as ${i}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let i=await qt(o.token);return s.gitlab={token:o.token},dn(s,()=>{process.env.GITLAB_TOKEN=o.token,Zf(o.token)}),{ok:!0,detail:`authenticated as ${i}`}}case"bitbucket":{if(!o.email||!o.apiToken)return{ok:!1,detail:"payload needs email + apiToken"};let i=await Wt(o.email,o.apiToken);return s.bitbucket={email:o.email,apiToken:o.apiToken},dn(s,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,Qf(o.apiToken)}),{ok:!0,detail:`authenticated as ${i}`}}case"youtrack":{if(!o.token)return{ok:!1,detail:"payload has no token"};let i=o.url?.trim().replace(/\/$/,"")||s.youtrack?.url;if(!i)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await zt({baseUrl:i,token:o.token});return s.youtrack={url:i,token:o.token},dn(s,()=>{process.env.YOUTRACK_URL=i,process.env.YOUTRACK_TOKEN=o.token}),{ok:!0,detail:`authenticated as ${a}`}}case"claude":{if(!o.token)return{ok:!1,detail:"payload has no token"};let i=await Nt(o.token);return i==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(s.claude={oauthToken:o.token},dn(s,()=>{}),{ok:!0,...i==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(s.contextWrite={token:o.token},dn(s,()=>{}),{ok:!0,detail:"saved (verified on the next readiness pass)"}):{ok:!1,detail:"payload has no token"};default:return{ok:!1,detail:`unknown credential kind '${e}'`}}}catch(i){return{ok:!1,detail:`${i instanceof Error?i.message:String(i)} \u2014 previous credential kept`}}}function dn(t,e){se(t),e()}F();F();import{spawn as Ix}from"node:child_process";var Tx=124,rm=16*1024,nm=4e3;function Cx(t,e,r,n,o,s){let i={...t},a=(c,l)=>{Pt(c)||(i[c]=l)};for(let[c,l]of Object.entries(e))a(c,l);for(let[c,l]of Object.entries(r))a(c,l);for(let[c,l]of Object.entries(n??{}))a(c,l);for(let[c,l]of Object.entries(o))i[c]=l;for(let[c,l]of Object.entries(s))i[`INPUT_${c}`]=String(l);return i}async function om(t){let{def:e,onEvent:r}=t,n=Cx(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",s=a=>{o+=a+`
|
|
952
|
+
`,o.length>rm&&(o=o.slice(o.length-rm))},i=(a,c)=>{let l=c.length>nm?c.slice(0,nm)+"\u2026":c;s(l),r({ts:Date.now(),kind:"log",stream:a,text:l})};r({ts:Date.now(),kind:"start",status:"running"});for(let[a,c]of e.steps.entries()){let l=c.name??`step ${a+1}`;r({ts:Date.now(),kind:"step",stepName:l});let u=await Ax(c.run,c.timeout_sec,t.cwd,n,i);if(u!==0)return s(`[${l}] exited with code ${u}`),r({ts:Date.now(),kind:"result",status:"failed",exitCode:u,failedStep:l}),{status:"failed",exitCode:u,failedStep:l,logTail:o}}return r({ts:Date.now(),kind:"result",status:"succeeded",exitCode:0}),{status:"succeeded",exitCode:0,logTail:o}}function Ax(t,e,r,n,o){return new Promise(s=>{let i=Ix("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??wa)*1e3,l=setTimeout(()=>{a=!0,o("stderr",`step timed out after ${c/1e3}s \u2014 killing`),i.kill("SIGTERM"),setTimeout(()=>i.kill("SIGKILL"),5e3).unref()},c);l.unref?.();let u=m=>{let f="";return{data:g=>{f+=g.toString("utf-8");let h;for(;(h=f.indexOf(`
|
|
953
|
+
`))!==-1;)o(m,f.slice(0,h).replace(/\r$/,"")),f=f.slice(h+1)},flush:()=>{f.length>0&&o(m,f.replace(/\r$/,"")),f=""}}},p=u("stdout"),d=u("stderr");i.stdout?.on("data",p.data),i.stderr?.on("data",d.data),i.on("error",m=>{clearTimeout(l),o("stderr",`spawn failed: ${m.message}`),s(127)}),i.on("close",(m,f)=>{clearTimeout(l),p.flush(),d.flush(),s(a?Tx:m??(f?1:0))})})}nt();nt();import{existsSync as Px,readFileSync as _x,statSync as sm}from"node:fs";var im=2*1024*1024;function jx(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function am(t,e){let r=ke(t,e);if(e.split("/").some(s=>s===".git"))throw new Error(`not a context file: ${e}`);if(!Px(r)||!sm(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=sm(r);if(n>im)throw new Error(`file too large: ${e} is ${n} bytes (limit ${im})`);let o=_x(r);return jx(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}de();F();import{existsSync as Nx,readFileSync as Ox,writeFileSync as Lx}from"node:fs";import{join as Dx}from"node:path";import{parseDocument as Mx}from"yaml";async function cm(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let s=Ta(o);if(!s.ok)throw new Error(s.error);let i=r.get(o.file)??[];i.push({path:s.field.path,value:s.value}),r.set(o.file,i)}let n=[];for(let[o,s]of r){let i=Dx(t,o);if(!Nx(i))throw new Error(`${o} not found in context repo (${t})`);let a=Mx(Ox(i,"utf-8"));for(let c of s)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);Lx(i,a.toString()),n.push(o)}return{files:n}}F();import{existsSync as Ux,readFileSync as Bx,writeFileSync as Fx}from"node:fs";import{join as Kx}from"node:path";import{isMap as lm,parseDocument as Gx}from"yaml";async function um(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||!Fa(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=Kx(t,"project.yaml");if(!Ux(o))throw new Error(`project.yaml not found in context repo (${t})`);let s=Gx(Bx(o,"utf-8")),i=s.get("repos"),c=(i&&typeof i=="object"&&"items"in i?i.items:[]).find(l=>lm(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!lm(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),Fx(o,s.toString()),{repoName:r,defaultBranch:n}}import{existsSync as Nc,readFileSync as Oc,writeFileSync as Hx}from"node:fs";import{join as Os}from"node:path";import{parseDocument as Lc}from"yaml";async function dm(t,e){let r=[];if(e.stageField!==void 0||e.sourceColumns!==void 0||e.rejectColumns!==void 0||e.doneColumns!==void 0||e.reviewColumns!==void 0||e.statusColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0||e.backlogScope!==void 0){let s=Os(t,"project.yaml");if(!Nc(s))throw new Error(`project.yaml not found in context repo (${t})`);let i=Lc(Oc(s,"utf-8"));if(e.stageField!==void 0){let a=typeof e.stageField=="string"?e.stageField.trim():"";a&&a!=="Stage"?i.setIn(["youtrack","stage_field"],a):i.deleteIn(["youtrack","stage_field"])}if(e.rejectColumns!==void 0){let a=e.rejectColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?i.setIn(["youtrack","reject_columns"],a):i.deleteIn(["youtrack","reject_columns"])}if(e.doneColumns!==void 0){let a=e.doneColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?i.setIn(["youtrack","done_columns"],a):i.deleteIn(["youtrack","done_columns"])}if(e.reviewColumns!==void 0){let a=e.reviewColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?i.setIn(["youtrack","review_columns"],a):i.deleteIn(["youtrack","review_columns"])}if(e.statusColumns!==void 0){let a=e.statusColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?i.setIn(["youtrack","status_columns"],a):i.deleteIn(["youtrack","status_columns"])}if(e.sourceColumns!==void 0){let a=e.sourceColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);if(a.length===0)throw new Error("source_columns must be a non-empty list of non-empty strings");i.setIn(["youtrack","source_columns"],a)}if(e.backlogColumn!==void 0){let a=typeof e.backlogColumn=="string"?e.backlogColumn.trim():"";a?i.setIn(["youtrack","backlog_column"],a):i.deleteIn(["youtrack","backlog_column"])}if(e.assignee!==void 0){let a=typeof e.assignee=="string"?e.assignee.trim():"";a?i.setIn(["youtrack","assignee"],a):i.deleteIn(["youtrack","assignee"])}e.requireAssignee!==void 0&&i.setIn(["youtrack","require_assignee"],e.requireAssignee===!0),e.backlogScope!==void 0&&(e.backlogScope==="personal"?i.setIn(["youtrack","backlog_scope"],"personal"):e.backlogScope==="shared"?i.setIn(["youtrack","backlog_scope"],"shared"):i.deleteIn(["youtrack","backlog_scope"])),r.push({path:"project.yaml",content:i.toString()})}if(e.reviewStatus!==void 0||e.writes!==void 0){let s=Os(t,"regimen.yaml");if(!Nc(s))throw new Error(`regimen.yaml not found in context repo (${t})`);let i=Lc(Oc(s,"utf-8"));if(e.reviewStatus!==void 0){let a=e.reviewStatus.trim();a&&i.setIn(["youtrack","review_status"],a)}if(e.writes!==void 0){let a=e.writes;i.setIn(["youtrack","writes","enabled"],a.enabled===!0),i.setIn(["youtrack","writes","status_changes"],a.statusChanges===!0),i.setIn(["youtrack","writes","pr_comment"],a.prComment===!0),i.setIn(["youtrack","writes","dashboard_mirror"],a.dashboardMirror===!0)}r.push({path:"regimen.yaml",content:i.toString()})}if(r.length===0)return{files:[]};for(let s of r)Hx(Os(t,s.path),s.content);return{files:r.map(s=>s.path)}}function Ls(t){if(!t)return"Stage";try{let e=Os(t,"project.yaml");if(!Nc(e))return"Stage";let n=Lc(Oc(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}Yt();ws();Rr();Qc();$r();import{existsSync as ch,readFileSync as lh}from"node:fs";import{join as uh}from"node:path";import{parseDocument as dh}from"yaml";$r();var Io=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return Sp(this.cfg,e)}getIssue(e,r){return Ep(this.cfg,e,r??Ls(this.contextDir))}listComments(e,r){return Rp(this.cfg,e,r)}downloadAttachment(e){return xp(this.cfg,e)}updateStatus(e,r){return mp(this.cfg,e,r,Ls(this.contextDir))}addComment(e,r,n){return hp(this.cfg,e,r)}createIssue(e){return kp(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,Ls(this.contextDir))}editIssue(e,r){return gp(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return wp(this.cfg,e,r,n)}fetchStateFields(e){return Tp(this.cfg,e)}};F();nt();import{existsSync as xS,readFileSync as SS}from"node:fs";import{randomBytes as ES}from"node:crypto";import{existsSync as el,readFileSync as yS,readdirSync as kS}from"node:fs";F();nt();function Ys(t,e,r){let n=[];for(let o of r){let s=o.issue.key,i=vS(t,s,o.attachments);n.push({path:`tasks/${s}/task.md`,content:wS(o.issue,e,i)}),n.push({path:`tasks/${s}/comments.jsonl`,content:$S(bS(t,s,o.comments))});for(let a of o.attachments)n.push({path:`tasks/${s}/attachments/${a.name}`,content:a.contentBase64,encoding:"base64"})}return n}async function ih(t,e,r,n=10){let o=new Set(e.map(c=>c.issue.key)),s=[],i=c=>(c.links??[]).filter(l=>l.type==="subtask").map(l=>l.targetKey);for(let c of e)s.push(...i(c.issue));let a=[];for(;s.length>0&&a.length<n;){let c=s.shift();if(o.has(c)||(o.add(c),el(ke(t,`tasks/${c}/task.md`))))continue;let l=null;try{l=await r(c)}catch{continue}l&&(a.push({issue:l,comments:[],attachments:[]}),s.push(...i(l)))}return a}async function Vs(t,e,r){if(r.length===0)return;let n=Ys(t,e,r),o=r.map(s=>s.issue.key);await ve(t,n,`sync(${o.join(", ")}): task data`)}function wS(t,e,r){let n=new Date(t.updatedAt).toISOString(),o=[`# ${t.key}: ${t.title}`,"",`- **Project:** \`${e}\``,`- **Tracker status:** ${t.status||"(unknown)"}`,`- **Assignee:** ${t.assignee??"(unassigned)"}`,`- **Updated:** ${n}`,"","---","",t.description??"_(no description)_",""];if(r.length>0){o.push("## Attachments","");for(let s of r)o.push(`- [${s}](attachments/${encodeURI(s)})`);o.push("")}return o.join(`
|
|
954
|
+
`)}function bS(t,e,r){let n=new Map,o=ke(t,`tasks/${e}/comments.jsonl`);if(el(o))for(let s of yS(o,"utf-8").split(`
|
|
955
|
+
`)){let i=s.trim();if(i)try{let a=JSON.parse(i);a&&typeof a.id=="string"&&n.set(a.id,a)}catch{}}for(let s of r){if(n.has(s.id))continue;let i={id:s.id,author:s.author,origin:"youtrack",body:s.body,createdAt:new Date(s.createdAt).toISOString()},a=yr(s.body);a&&(i.parsedCommand=a),n.set(s.id,i)}return[...n.values()].sort((s,i)=>s.createdAt.localeCompare(i.createdAt))}function $S(t){return t.map(e=>JSON.stringify(e)).join(`
|
|
956
|
+
`)+(t.length>0?`
|
|
957
|
+
`:"")}function vS(t,e,r){let n=[],o=ke(t,`tasks/${e}/attachments`);if(el(o))for(let s of kS(o))n.push(s);for(let s of r)n.includes(s.name)||n.push(s.name);return n}Ps();var To=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await go(this.contextDir);let r=e.columns??[];return Df(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>ko(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=yo(this.contextDir,e);return r?ko(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return ah(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 go(this.contextDir),!yo(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let s={id:`int-${Date.now().toString(36)}-${ES(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},i=yr(r);i&&(s.parsedCommand=i);let c=[...ah(this.contextDir,e),s].map(l=>JSON.stringify(l)).join(`
|
|
958
|
+
`)+`
|
|
959
|
+
`;return await ve(this.contextDir,[{path:`tasks/${e}/comments.jsonl`,content:c}],`tracker(${e}): comment`),{id:s.id}}async createIssue(e){let r=new Date().toISOString(),n=await Mf(this.contextDir,this.config.prefix,o=>this.renderNewIssueFiles(o,e,r),o=>`tracker(${o}): create issue`);return{id:n,key:n}}async editIssue(e,r){await this.mutateRecord(e,n=>({...n,...r.title!==void 0?{title:r.title}:{}}),r.body)}async applyLink(e,r,n){let o=r==="subtask_of"?"subtask":"depends_on";await this.mutateRecord(e,s=>{let i=s.links.filter(a=>!(a.type===o&&a.targetKey===n));return i.push({type:o,targetKey:n}),{...s,links:i}})}async fetchStateFields(e){return[{name:"Status",values:rs.statusColumns}]}async mutateRecord(e,r,n){let o=yo(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let s={...r(o),updated:new Date().toISOString()},i=ko(this.contextDir,s,{withDescription:!0});n!==void 0&&(n.trim().length>0?i.description=n:delete i.description);let a=[{path:Xr(e),content:Ac(s)},...Ys(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])];await ve(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:no,status:r.targetStatus,links:[],created:n,updated:n},s=ko(this.contextDir,o);return r.body.trim().length>0&&(s.description=r.body),[{path:Xr(e),content:Ac(o)},...Ys(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])]}};function ah(t,e){let r=ke(t,`tasks/${e}/comments.jsonl`);if(!xS(r))return[];let n=[];for(let o of SS(r,"utf-8").split(`
|
|
960
|
+
`)){let s=o.trim();if(s)try{let i=JSON.parse(s);i&&typeof i.id=="string"&&typeof i.body=="string"&&n.push(i)}catch{}}return n}Ps();function tl(t){if(!t)return"youtrack";try{let e=uh(t,"project.yaml");return ch(e)&&dh(lh(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function St(t){let e=tl(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=Of(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let s=RS(n);return s?{ok:!0,kind:e,provider:new To(n,s,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=pp();return r?{ok:!0,kind:e,provider:new Io(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function RS(t){try{let e=uh(t,"project.yaml");if(!ch(e))return null;let r=dh(lh(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var zs=new Map;async function gn(t,e){let n=(zs.get(t)??Promise.resolve()).catch(()=>{}).then(e);zs.set(t,n);try{return await n}finally{zs.get(t)===n&&zs.delete(t)}}async function ph(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;xr(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return V("no repo spec");let s=e.taskId.split(":",2)[0]??"?";return gn(`${s}/${r.name}`,async()=>{let i=await Ot(s,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(s,r.name,t.baseDir),{commit:c,pushed:l}=await ef(i,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force,push:e.push});if(t.contextDir){let u=e.taskId.split(":")[1]??"";u&&await Jc({contextDir:t.contextDir,repoDir:a,repoName:r.name,taskKey:u,commitSha:c}).catch(p=>{xr(`[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 V("no repo spec");let s=e.taskId.split(":",2)[0]??"?";return gn(`${s}/${r.name}`,async()=>{let i=await Ot(s,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(s,r.name,t.baseDir);return await tf(i,a,{branchName:e.branchName,force:e.force}),ce({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"early_branch":{if(!r)return V("no repo spec");let s=e.taskId.split(":",2)[0]??"?";return gn(`${s}/${r.name}`,async()=>{let i=await Ot(s,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(s,r.name,t.baseDir),{commit:c,pushed:l}=await rf(i,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 V("no repo spec");let s=pt(r),i=await s.createPullRequest(r,e);if(t.contextDir){let a=e.taskId.split(":")[1]??"",c=e.taskId.split(":",2)[0]??"?";a&&await Zc({contextDir:t.contextDir,repoDir:Ie(c,r.name,t.baseDir),branchName:e.branchName,baseBranch:e.baseBranch,fallbackTaskKey:a,prUrl:i.url}).catch(l=>{xr(`[model] pr link for ${a} failed: ${l instanceof Error?l.message:String(l)}`)})}return ce({url:i.url,number:i.number,host:s.name})}case"merge_pr":{if(!r)return V("no repo spec");let s=pt(r),i=await s.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ce({prNumber:e.prNumber,host:s.name,...i.mergedSha?{mergedSha:i.mergedSha}:{}})}case"close_pr":{if(!r)return V("no repo spec");let s=pt(r);return await s.closePR(r,e.prNumber,e.comment),ce({prNumber:e.prNumber,host:s.name})}case"rewrite_cluster_branch":{if(!r)return V("no repo spec");let s=e.taskId.split(":",2)[0]??"?";return gn(`${s}/${r.name}`,async()=>{let i=await Ot(s,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(s,r.name,t.baseDir),{commit:c,dropped:l}=await of(i,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 V("no repo spec");let s=e.taskId.split(":",2)[0]??"?";return gn(`${s}/${r.name}`,async()=>{let i=await Ot(s,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(s,r.name,t.baseDir),{mergedSha:c}=await sf(i,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 V("no repo spec");let s=t.cloneUrlOverride??fo(r),a=(await af(s)).filter(u=>cf(u,e.issueKey)),c=pt(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 V("no repo spec");let s=pt(r);return await s.addPRComment(r,e.prNumber,e.body),ce({prNumber:e.prNumber,host:s.name})}case"tracker_status":{let s=St({contextDir:t.contextDir});return s.ok?t.trackerIssueId?(await s.provider.updateStatus(t.trackerIssueId,e.newStatus),ce({issueId:t.trackerIssueId,newStatus:e.newStatus})):V("no tracker_issue_id provided"):V(s.error)}case"tracker_comment":{let s=St({contextDir:t.contextDir});if(!s.ok)return V(s.error);if(!t.trackerIssueId)return V("no tracker_issue_id provided");let i=await s.provider.addComment(t.trackerIssueId,e.body,e.author);return ce({issueId:t.trackerIssueId,commentId:i.id})}case"create_tracker_issue":{let s=St({contextDir:t.contextDir});if(!s.ok)return V(s.error);if(!e.projectKey)return V("no projectKey in create_tracker_issue action");let{id:i,key:a}=await s.provider.createIssue({projectKey:e.projectKey,title:e.title,body:e.body,targetStatus:e.targetStatus});return ce({issueKey:a,issueId:i})}case"apply_tracker_links":{let s=St({contextDir:t.contextDir});if(!s.ok)return V(s.error);let i=0;for(let a of e.links)try{await s.provider.applyLink(a.sourceIssueKey,a.rel,a.targetIssueKey),i++}catch(c){return V(`${c instanceof Error?c.message:String(c)} (applied ${i}/${e.links.length})`)}return ce({applied:i})}case"set_project_setting":{if(!t.contextDir)return V("no context repo clone on this CLI");let s=await cm(t.contextDir,e.edits);return ce({files:s.files})}case"set_prompt_override":{if(!t.contextDir)return V("no context repo clone on this CLI");if(!ja(e.role))return V(`unknown prompt operation: ${e.role}`);let s=Na(e.role);return await ve(t.contextDir,[e.content===null?{path:s,content:"",deleted:!0}:{path:s,content:e.content}],e.commitMessage),t.requestConfigReport?.(),ce({path:s,reset:e.content===null})}case"tracker_edit":{let s=St({contextDir:t.contextDir});if(!s.ok)return V(s.error);if(!t.contextDir)return V("no context repo clone on this CLI");await s.provider.editIssue(e.issueKey,{...e.title!==void 0?{title:e.title}:{},...e.body!==void 0?{body:e.body}:{}});let i=await s.provider.getIssue(e.issueKey);return i&&await Vs(t.contextDir,e.projectId,[{issue:i,comments:[],attachments:[]}]),ce({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return V("no context repo clone on this CLI");let s=await dm(t.contextDir,e);return ce({files:s.files})}case"set_repo_default_branch":{if(!t.contextDir)return V("no context repo clone on this CLI");let s=await um(t.contextDir,e);return ce({repoName:s.repoName,defaultBranch:s.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ce({reported:!0})):V("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return V("no context repo clone on this CLI");let s=await t.refreshContextStatus();return ce({outdated:s.outdated,templateVersion:s.templateVersion})}case"run_action":{if(!t.contextDir)return V("no project workspace on this CLI");if(!r)return V("no repo spec");if(!t.onRunActivity)return V("no run-activity stream on this CLI");let s=t.onRunActivity,{defs:i,errors:a}=Ss(t.contextDir),c=i.find(m=>m.id===e.actionId);if(!c){let m=a.find(f=>f.file===`actions/${e.actionId}.yml`);return V(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=$a(c,e.input);if(!l.ok)return V(l.error);let u=kf(t.contextDir),p=q(e.projectId),d={};return p?.github?.token&&(d.GH_TOKEN=p.github.token),p?.gitlab?.token&&(d.GITLAB_TOKEN=p.gitlab.token),p?.bitbucket&&(d.BITBUCKET_EMAIL=p.bitbucket.email,d.BITBUCKET_API_TOKEN=p.bitbucket.apiToken),p?.youtrack&&(d.YOUTRACK_URL=p.youtrack.url,d.YOUTRACK_TOKEN=p.youtrack.token),gn(`${e.projectId}/${r.name}`,async()=>{await Ot(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=Ie(e.projectId,r.name,t.baseDir),f=await om({cwd:m,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:g=>s(e.runId,g)});return ce({runId:e.runId,status:f.status,exitCode:f.exitCode,...f.failedStep?{failedStep:f.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return V("no context repo clone on this CLI");let s=am(t.contextDir,e.path);return ce({path:e.path,...s})}case"search_model":{if(!t.contextDir)return V("no context repo clone on this CLI");let{searchModelIndex:s}=await Promise.resolve().then(()=>(Ro(),Eo)),i=await s(t.contextDir,e.q,e.limit);return ce({hits:i})}case"model_drift":return V("model_drift requires a local workspace (handled by the daemon)");case"model_bootstrap":return V("model_bootstrap requires a local workspace (handled by the daemon)");case"local_apply":return V("local_apply requires a local workspace (handled by the daemon)");default:return V(`unsupported action type: ${e.type}`)}}catch(s){return V(s instanceof Error?s.message:String(s))}}function ce(t){return{status:"done",result:t}}function V(t){return{status:"failed",error:t}}Rr();import{existsSync as IS,mkdtempSync as TS,rmSync as CS}from"node:fs";import{tmpdir as AS}from"node:os";import{join as rl}from"node:path";import{simpleGit as fh}from"simple-git";var PS=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function mh(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=rl(t.root,c.mountAs);if(!IS(rl(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=fh(a.dir),l=a.payload;try{await c.fetch()}catch(m){return{ok:!1,error:`fetch failed in ${a.mountAs}: ${Co(m)}`}}let u=`origin/${l.baseRef}`;await NS(c,u)||(u=`origin/${a.defaultBranch}`);let p;try{p=(await c.revparse([u])).trim()}catch(m){return{ok:!1,error:`base ${u} unavailable in ${a.mountAs}: ${Co(m)}`}}let d;try{d=await po(c,l.deliverySha,()=>Er(c,{contextRepoCloneUrl:l.contextRepoCloneUrl,deliveryRef:l.deliveryRef,deliverySha:l.deliverySha,baseSha:l.baseSha,commitMessage:l.commitMessage}))}catch(m){return{ok:!1,error:`fetch delivery failed in ${a.mountAs}: ${Co(m)}`}}o.push({repoName:l.repoName,mountAs:a.mountAs,git:c,branch:l.branchName,startPoint:p,deliveryCommit:d})}let s=[],i=[];for(let a of o){let c=await OS(a.git,`refs/heads/${a.branch}`);try{let u=(await a.git.revparse([`${a.deliveryCommit}^`])).trim()===a.startPoint?a.deliveryCommit:await _S(a);await a.git.raw(["branch","-f",a.branch,u]),s.push({git:a.git,mountAs:a.mountAs,branch:a.branch,priorSha:c}),i.push({repoName:a.repoName,branch:a.branch,commit:u}),r.info(`[local-apply] ${a.mountAs}: branch ${a.branch} \u2192 ${u.slice(0,10)} (no checkout)`)}catch(l){return await jS(s,r),{ok:!1,error:`apply failed in ${a.mountAs}: ${Co(l)} (rolled back all repos)`}}}return{ok:!0,repos:i}}async function _S(t){let e=TS(rl(AS(),"codepipe-local-apply-"));try{await t.git.raw(["worktree","add","--detach",e,t.startPoint]);let r=fh(e);try{await r.raw([...PS,"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(()=>{}),CS(e,{recursive:!0,force:!0}),await t.git.raw(["worktree","prune"]).catch(()=>{})}}async function jS(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 NS(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function OS(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)}ot();ol();Te();de();import{existsSync as gh,readFileSync as yh}from"node:fs";import{join as kh}from"node:path";async function wh(t,e,r,n){let o=s=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:s});try{if(e.projectId!==t.projectId)return o(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let s=De(e.farmPublicKey);if(s!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Js(e.farmId,e.farmPublicKey);let i=q(t.projectId);if(!i)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await ne(t.hubUrl,t.cliToken,t.projectId),c;if(r){let d=kh(r,"project.yaml"),m=kh(r,"regimen.yaml");gh(d)&&gh(m)?c={projectYaml:yh(d,"utf-8"),regimenYaml:yh(m,"utf-8")}:n.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...i.github?{github:i.github}:{},...i.bitbucket?{bitbucket:i.bitbucket}:{},...i.gitlab?{gitlab:i.gitlab}:{},...i.youtrack?{youtrack:i.youtrack}:{},...i.claude?{claude:i.claude}:{},...i.contextWrite?{contextWrite:i.contextWrite}:{},...i.contextSsh?{contextSsh:i.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},u=Dt(e.farmPublicKey,JSON.stringify(l));Xs(e.farmId,s),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${s}) \u2014 handing off`);let p=await ys(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:u});return p.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...p.daemonStatus?{daemonStatus:p.daemonStatus}:{}}:o(p.error??"farm provisioning failed")}catch(s){return o(s instanceof Error?s.message:String(s))}}F();ot();Le();ot();import{homedir as WS}from"node:os";import{existsSync as qS,mkdirSync as YS,readFileSync as VS,writeFileSync as zS}from"node:fs";import{dirname as XS,join as JS}from"node:path";function sl(){return X("RUNNER_PINS")??JS(WS(),".codepipe","runner-pins.json")}function bh(){let t=sl();if(!qS(t))return{};try{return JSON.parse(VS(t,"utf-8"))}catch{return{}}}function ZS(t){let e=sl();YS(XS(e),{recursive:!0}),zS(e,JSON.stringify(t,null,2)+`
|
|
961
|
+
`,{mode:384})}function QS(t){return bh()[t]}function il(t,e){let r=bh();r[t]=e,ZS(r)}function $h(t,e){let r=De(e),n=QS(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 ${sl()}.`);return r}Te();de();var xh=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function vh(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:xh(t)});if(!o.ok)throw new Error(`github ${n} for ${e}/${r}: HTTP ${o.status}`);let s=await o.json();if(!s.token)throw new Error(`github ${n} for ${e}/${r}: no token in response`);return s.token}var eE={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:xh(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)=>vh(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>vh(t,e,r,"remove-token")},Sh={api:eE,fetchProject:ne,provisionOnRunner:Up,teardownOnRunner:Bp};async function Eh(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(De(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");$h(e.runnerId,e.runnerPublicKey);let s=q(t.projectId)?.github?.token;if(!s)throw new Error("no GitHub token stored for this project on this CLI");let a=((await r.fetchProject(t.hubUrl,t.cliToken,t.projectId)).repos??[]).find(c=>c.host==="github"&&c.owner===e.owner&&c.repoName===e.repo);if(!a)throw new Error(`${e.owner}/${e.repo} is not a GitHub repository of this project`);return{githubToken:s,repo:a}}async function Rh(t,e,r,n=Sh){let o=s=>({type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:s});try{let{githubToken:s,repo:i}=await Eh(t,e,n);if(!await n.api.repoHasAdmin(s,i.owner,i.repoName))return o(`the GitHub token lacks admin access on ${i.owner}/${i.repoName} \u2014 replace it (project page \u2192 Tokens \u2192 Replace) with a token that has admin rights on this repository`);let a={projectId:t.projectId,runners:[{owner:i.owner,repo:i.repoName,regToken:await n.api.mintRegistrationToken(s,i.owner,i.repoName)}],labels:[Ba(e.runnerId)]},c=Dt(e.runnerPublicKey,JSON.stringify(a));il(e.runnerId,e.fingerprint),r.info(`[ghr] registration token for ${i.owner}/${i.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let l=await n.provisionOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:c});return{type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:l.ok,...l.runners?{runners:l.runners}:{},...l.error?{error:l.error}:{}}}catch(s){return o(s instanceof Error?s.message:String(s))}}async function Ih(t,e,r,n=Sh){let o=s=>({type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:s});try{let{githubToken:s,repo:i}=await Eh(t,e,n),a={owner:i.owner,repo:i.repoName};try{a.removeToken=await n.api.mintRemoveToken(s,i.owner,i.repoName)}catch(p){r.warn(`[ghr] remove-token for ${i.owner}/${i.repoName} failed (${p instanceof Error?p.message:p}) \u2014 the runner host will force-remove`)}let c={projectId:t.projectId,runners:[a]},l=Dt(e.runnerPublicKey,JSON.stringify(c));il(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle for ${i.owner}/${i.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let u=await n.teardownOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:l,owner:i.owner,repo:i.repoName});return{type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:u.ok,...u.error?{error:u.error}:{}}}catch(s){return o(s instanceof Error?s.message:String(s))}}Te();F();ot();de();var Th=16*1024;function tE(t){return He.test(t)?Pt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${He}`}function Ch(t,e,r,n){let o=tE(e);if(o)return{ok:!1,detail:o};let s;try{let i=JSON.parse(un(n,r).toString("utf-8"));if(typeof i.value!="string"||i.value.length===0)return{ok:!1,detail:"payload has no value"};s=i.value}catch(i){return{ok:!1,detail:`cannot open the sealed secret (${i instanceof Error?i.message:String(i)}) \u2014 wrong channel key?`}}if(s.length>Th)return{ok:!1,detail:`secret value too large (max ${Th} chars)`};try{return Bd(t,e,s),{ok:!0}}catch(i){return{ok:!1,detail:i instanceof Error?i.message:String(i)}}}function Ah(t,e){try{return Fd(t,e)?{ok:!0}:{ok:!0,detail:"no such secret (already absent)"}}catch(r){return{ok:!1,detail:r instanceof Error?r.message:String(r)}}}nn();de();Yt();var Zs=class{constructor(e,r,n){this.intervalMs=e;this.send=r;this.log=n}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let n=[];for(let i of r.prs){let a=pt(i.repoSpec);try{let c=await a.getPullRequest(i.repoSpec,i.number);n.push({number:i.number,url:i.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof br){this.log.warn(`[track] task=${e} pr=${i.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${i.url} fetch failed: ${c instanceof Error?c.message:String(c)}`);return}}let o=n.map(i=>`${i.number}:${i.state}:${i.merged?1:0}:${i.ci}:${i.mergeable}`).join("|");if(this.lastSig.get(e)===o)return;for(let i=0;i<n.length;i++){let a=n[i];if(a.ci!=="failed")continue;let c=pt(r.prs[i].repoSpec);if(c.getCiFailureLog)try{let l=await c.getCiFailureLog(r.prs[i].repoSpec,a.number);l&&(a.ciFailureLog=l)}catch(l){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${l instanceof Error?l.message:String(l)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:n}),this.lastSig.set(e,o);let s=rE(n);this.log.info(`[track] task=${e} snapshot signalled${s?` \u2192 ${s}`:""} (${n.length} PR(s))`)}};function rE(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}F();var Qs=class t{constructor(e,r,n,o={contextDir:null}){this.intervalMs=e;this.send=r;this.log=n;this.options=o}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;abandonedTicks=0;static MAX_ABANDONED_TICKS=3;setRequest(e){let r=this.request?.projectId;this.request=e,this.log.info(`[yt-sync] request updated: project=${e.projectKey} columns=[${e.sourceColumns.join(",")}] sinceMs=${e.sinceMs} offBoard=${e.offBoardIssueIds.length}`),this.timer||this.start(),r&&r!==e.projectId&&this.log.info(`[yt-sync] project switch ${r} \u2192 ${e.projectId}`)}start(){if(this.timer)return;this.log.info(`[yt-sync] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[yt-sync] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[yt-sync] poller stopped"))}async tickOnce(){await this.tick()}async forceSync(){if(!this.request){this.log.info("[yt-sync] force requested but no sync_request yet \u2014 ignored");return}this.log.info("[yt-sync] force sync requested (manual)"),await this.tick()}async tick(){if(this.running||!this.request)return;let r=(this.options.resolveProvider??(()=>St({contextDir:this.options.contextDir})))();if(!r.ok){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn(`[yt-sync] tracker provider unavailable (${r.error}) \u2014 poller idle.`));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,r.provider)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let v=e.stageField?{stageField:e.stageField}:{},x=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},E=(e.backlogScope??"personal")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(E){let $=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[T,N]=await Promise.all([$.length>0?r.listIssues({projectKey:e.projectKey,columns:$,...v,...x}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...v})]),G=new Map;for(let ee of[...T,...N])G.set(ee.id,ee);o=[...G.values()]}else{let $=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:$,...v,...x})}}catch(v){let x=v instanceof Error?v.message:String(v);x.includes("stage_field")?this.log.warn(`[yt-sync] CONFIGURATION ERROR \u2014 ${x}`):this.log.warn(`[yt-sync] listIssues failed: ${x}`);return}let s=new Map,i=new Set,a=new Set(e.doneColumns??[]);for(let v of o){if(i.add(v.id),a.has(v.status))continue;let x=await jh(r,v.id,e.sinceMs,this.log);x&&s.set(v.id,x)}let c=[];for(let v of e.offBoardIssueIds){if(i.has(v))continue;let x=await jh(r,v,e.sinceMs,this.log);if(x&&x.length>0&&s.set(v,x),e.requireAssignee||x&&x.length>0){let I=await _h(r,v,e.stageField,this.log);if(I)c.push(I);else if(x&&x.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,s,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let d=[...l,...c].map(v=>({issue:v,comments:s.get(v.id)??[],attachments:u.get(v.id)??[]}));d.push(...await ih(this.options.contextDir,d,v=>_h(r,v,e.stageField,this.log)));try{await Vs(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let v of p)this.shippedAttachments.add(v)}catch(v){let x=v instanceof Error?v.message:String(v);this.abandonTick(`context task sync failed: ${x}`);return}let m=this.options.isSelfComment??(()=>!1),f=[],g=[];for(let[v,x]of s){let I=x.filter($=>!m($.id));if(I.length===0)continue;f.push({issueId:v,comments:I.map(nE)});let E=I.flatMap($=>{let T=yr($.body);return T?[{commentId:$.id,author:$.author,name:T.name,args:T.args,createdAt:$.createdAt}]:[]});E.length>0&&g.push({issueId:v,commands:E})}let h={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Ph),commentsBatch:f,...g.length>0?{commandsBatch:g}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(Ph)}:{},observedAtMs:n};this.send(h);let w=f.reduce((v,x)=>v+x.comments.length,0),y=g.reduce((v,x)=>v+x.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${w} commands=${y} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,s=[];for(let i of e){let a=[...i.attachments??[]];for(let u of r.get(i.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let p=`${i.id}:${u.id}`;if(this.shippedAttachments.has(p))continue;let d;try{d=await n.downloadAttachment(u.url)}catch(f){this.log.warn(`[yt-sync] attachment ${u.name} (${i.id}) download failed: ${f instanceof Error?f.message:String(f)}`);continue}let m=oE(u.name);l.has(m)&&(m=`${u.id}-${m}`),l.add(m),c.push({name:m,contentBase64:d.toString("base64")}),s.push(p)}c.length>0&&o.set(i.id,c)}return{attachmentsByIssue:o,attachmentKeys:s}}};function Ph(t){let{description:e,...r}=t;return r}function nE(t){let{body:e,...r}=t;return r}function oE(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 _h(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 jh(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 kl="npm i -g @code-partner/codepipe@latest";function ni(t,e={}){let r=e.log??{info:h=>console.log(h),warn:h=>console.warn(h)};r.info(`codepipe-cli v${Ke} (protocol ${ct})`);let n=h=>e.onEvent?.(h),o=e.workspace;o?.contextDir&&$f(o.contextDir,r);let s=qh("CLI_TRACKING_POLL_INTERVAL_SEC"),i=qh("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let h=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(h)&&h>0?h*1e3:6e5})(),c=!1,l=!1,u=!1,p=new Set,d=!1,m=new Set,f=g();function g(){let h=gs(t.hubUrl,t.cliToken),w=null,y=new Zs(s,_=>{h.readyState===h.OPEN&&h.send(JSON.stringify(_))},r),v=new Qs(i,_=>{h.readyState===h.OPEN&&h.send(JSON.stringify(_))},r,{contextDir:o?.contextDir??null,isSelfComment:_=>m.has(_)}),x=null,I=async()=>{try{let _={trackerProvider:tl(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 U=await Ap(t.projectId,_);if(h.readyState!==h.OPEN)return;let D={type:"cli_readiness",projectId:t.projectId,ready:U.ready,checks:U.checks,creds:U.creds,secretNames:Kd(t.projectId),checkedAt:U.checkedAt};if(h.send(JSON.stringify(D)),U.ready)r.info("[readiness] ready");else{let O=U.checks.filter(b=>!b.ok).map(b=>`${b.name}(${b.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${O.join(", ")}`)}let z=Lp(U.creds,u);if(z==="open"){u=!0;let O=Dp(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${O}`),vr(O)}else z==="rearm"&&(u=!1)}catch(_){r.warn(`[readiness] check failed: ${_ instanceof Error?_.message:String(_)}`)}},E=()=>{I(),x=setInterval(()=>void I(),a),typeof x.unref=="function"&&x.unref()},$=()=>{x&&(clearInterval(x),x=null)},T=150,N=new Map,G=_=>{let U=N.get(_);if(!U||(U.timer&&clearTimeout(U.timer),N.delete(_),U.events.length===0||h.readyState!==h.OPEN))return;let D={type:"run_activity",projectId:t.projectId,runId:_,events:U.events};h.send(JSON.stringify(D))},ee=(_,U)=>{let D=N.get(_);if(D||(D={events:[],timer:null},N.set(_,D)),D.events.push(U),U.kind==="result"){G(_);return}D.timer||(D.timer=setTimeout(()=>G(_),T),D.timer.unref?.())},C=o?.contextDir?new Es(o.contextDir,t.projectId,_=>{h.readyState===h.OPEN&&h.send(JSON.stringify(_))},r):null,k=async()=>{let _=o?.contextDir;if(!_)throw new Error("no context repo clone on this CLI");let U;try{U=(await ne(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let D=await Hf(_,t.projectId,U,r);return h.readyState===h.OPEN&&h.send(JSON.stringify(D)),D},M=null,P=async()=>{let _=o?.contextDir;if(_)try{let{readContextIndexHub:U,collectSearchRows:D}=await Promise.resolve().then(()=>(Ro(),Eo));if(U(_)!=="metadata")return;let z=D(_);h.readyState===h.OPEN&&(h.send(JSON.stringify({type:"model_index",projectId:t.projectId,rows:z})),r.info(`[model] tier-2 index snapshot pushed (${z.length} rows)`))}catch(U){r.warn(`[model] tier-2 index push failed (non-fatal): ${U instanceof Error?U.message:String(U)}`)}},H=()=>{M&&clearTimeout(M),M=setTimeout(()=>void P(),5e3)},Y=null,oe=async _=>{if(o?.contextDir)try{let{rebuildWorkspaceModelIfStale:U}=await Promise.resolve().then(()=>(Ao(),ri));(await U({root:o.root,contextDir:o.contextDir,repos:o.repos},{fetch:_,onLog:z=>r.info(z)})).rebuilt.length>0&&H()}catch(U){r.warn(`[model] release-path rebuild failed (non-fatal): ${U instanceof Error?U.message:String(U)}`)}},Ve=_=>{Y&&clearTimeout(Y),Y=setTimeout(()=>void oe(_),6e4)},ze=setInterval(()=>void oe(!0),6*36e5);return h.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let _=Xd(t.projectId),U=X("ORIGIN")==="farm"?"farm":"local",D=X("FARM_ID"),z=t.accountEmail??_.email,O;try{let R=em(t.projectId);R&&(O=R.publicKey,r.info(`[cred-channel] key fingerprint: ${R.fingerprint}`))}catch(R){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${R instanceof Error?R.message:String(R)}`)}let b={type:"register",projectId:t.projectId,platformVersion:Ke,protocolVersion:ct,accountId:_.accountId,accountLabel:_.label,origin:U,inFlightActionIds:[...p],...z?{accountEmail:z}:{},...U==="farm"&&D?{farmId:D}:{},...O?{sealPublicKey:O}:{}};h.send(JSON.stringify(b))}),h.on("message",async _=>{let U=_.toString("utf-8");if(U==="pong"||U==="ping")return;let D;try{D=JSON.parse(U)}catch{return}if(!D||typeof D!="object")return;let z=D.type;if(z==="registered"){let b=D;if(b.ok){if(r.info(`[ws] registered for project ${b.projectId}`),n({kind:"registered",projectId:b.projectId??t.projectId}),y.start(),C?.start(),E(),wl(t,o,r),o?.contextDir){try{let R=As(o.contextDir,t.projectId);h.readyState===h.OPEN&&h.send(JSON.stringify(R)),R.outdated&&(r.warn(`[ctx] context format outdated: v${R.templateVersion} \u2192 v${R.currentVersion}`+(R.missingPaths.length>0?` (missing: ${R.missingPaths.join(", ")})`:"")),l||(l=!0,k().catch(()=>{})))}catch(R){r.warn(`[ctx] context-format detect failed (non-fatal): ${R instanceof Error?R.message:String(R)}`)}P(),Ve(!0)}}else r.warn(`[ws] register rejected: ${b.reason??"unknown"}`),n({kind:"register_rejected",reason:b.reason??"unknown"}),c=!0,h.close();return}if(z==="hello"){let b=D;w=Yn(b.protocolVersion);let R=w?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${b.platformVersion} (protocol ${b.protocolVersion}) \u2014 ${R}`),w||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Ke}, protocol ${ct}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${kl}`),n({kind:"incompatible",hubVersion:typeof b.platformVersion=="string"?b.platformVersion:null,hubProtocol:typeof b.protocolVersion=="number"?b.protocolVersion:null,updateCommand:kl}));return}if(z==="tracking_targets"){y.setTargets(D.targets);return}if(z==="youtrack_sync_request"){v.setRequest(D);return}if(z==="youtrack_force_sync"){v.forceSync();return}if(z==="sync_local"){await vE(D,o,h,r);return}if(z==="provision_repo"){let b=D;r.info(`[repo] provision_repo: ${b.repo.name} (${b.repo.host}:${b.repo.owner}/${b.repo.repoName})`),await bE(t,o,b.repo,r),await wl(t,o,r);return}if(z==="remove_repo"){let b=D;r.info(`[repo] remove_repo: ${b.repoName}${b.purge?" (purge)":""}`),await wl(t,o,r),b.purge&&$E(t,o,b.repoName,r);return}if(z==="context_write"){await xE(D,o,h,r);return}if(z==="adr_promote"){await SE(D,o,h,r);return}if(z==="cred_update"){let b=D,R=q(t.projectId),B=R?.sealKey?await tm(t.projectId,b.kind,b.sealed,R.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},J={type:"cred_update_result",updateId:b.updateId,projectId:t.projectId,ok:B.ok,...B.detail?{detail:B.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(J)),B.ok?(r.info(`[cred] ${b.kind} replaced${B.detail?` \u2014 ${B.detail}`:""}`),I()):r.warn(`[cred] ${b.kind} replacement rejected: ${B.detail??"unknown"}`);return}if(z==="readiness_check"){r.info("[readiness] on-demand check requested"),I();return}if(z==="agent_login_start"){Op(t,h,D,r,I);return}if(z==="move_to_farm"){let b=D;r.info(`[farm-move] request to move ${t.projectId} onto farm ${b.farmName} (${b.farmId})`);let R=await wh(t,b,o?.contextDir,r);h.readyState===h.OPEN&&h.send(JSON.stringify(R)),R.ok?r.info(`[farm-move] done \u2014 farm daemon ${R.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${R.error??"unknown error"}`);return}if(z==="gh_runner_setup"){let b=D;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${b.runnerName} (${b.runnerId})`);let R=await Rh(t,b,r);h.readyState===h.OPEN&&h.send(JSON.stringify(R)),R.ok?r.info(`[ghr] runners connected on ${b.runnerName}`):r.warn(`[ghr] setup failed: ${R.error??"see per-repo statuses"}`);return}if(z==="gh_runner_teardown"){let b=D;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${b.runnerName} (${b.runnerId})`);let R=await Ih(t,b,r);h.readyState===h.OPEN&&h.send(JSON.stringify(R)),R.ok?r.info(`[ghr] runners disconnected from ${b.runnerName}`):r.warn(`[ghr] teardown failed: ${R.error??"unknown error"}`);return}if(z==="tracker_fields_request"){let b=D,R={type:"tracker_fields_result",requestId:b.requestId,projectId:t.projectId,ok:!1},B=St({contextDir:o?.contextDir??null});if(!B.ok)R.error=B.error;else try{R.fields=await B.provider.fetchStateFields(b.projectKey),R.ok=!0}catch(J){R.error=J instanceof Error?J.message:String(J)}h.readyState===h.OPEN&&h.send(JSON.stringify(R)),R.ok||r.warn(`[yt-fields] listing failed: ${R.error??"unknown"}`);return}if(z==="project_secret_update"||z==="project_secret_delete"){let b=D,R;if(b.type==="project_secret_update"){let J=q(t.projectId);R=J?.sealKey?Ch(t.projectId,b.name,b.sealed,J.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else R=Ah(t.projectId,b.name);let B={type:"project_secret_update_result",updateId:b.updateId,projectId:t.projectId,ok:R.ok,...R.detail?{detail:R.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(B)),R.ok?(r.info(`[secret] ${b.name} ${b.type==="project_secret_update"?"saved":"deleted"}`+(R.detail?` \u2014 ${R.detail}`:"")),I()):r.warn(`[secret] ${b.name} rejected: ${R.detail??"unknown"}`);return}if(z==="auto_apply_local"){let b=D;if(!o?.contextDir){r.warn(`[apply] auto_apply_local for ${b.claim.taskKey} \u2014 no workspace (headless), skipped; task stays in READY_TO_APPLY`);return}let R=await pf({hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId,root:o.root,contextDir:o.contextDir,repos:o.repos},b.claim,r).catch(B=>({ok:!1,message:B instanceof Error?B.message:String(B)}));R.ok?r.info(`[apply] ${b.claim.taskKey}: ${R.message}`):r.warn(`[apply] ${b.claim.taskKey}: ${R.message} \u2014 task stays in READY_TO_APPLY`),n({kind:"local_applied",taskKey:b.claim.taskKey,ok:R.ok,...R.ok?{branches:R.branches??[]}:{error:R.message}});return}if(z==="sandbox_keys"){let b=q(t.projectId);if(!b){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let R=Qr(t.projectId),B=Xf(D,b,R,r);for(let J of B)h.readyState===h.OPEN&&h.send(JSON.stringify(J));return}if(z!=="dispatch_action")return;let O=D;if(w===!1){let b=`refused: HUB protocol incompatible with CLI v${Ke} (protocol ${ct})`;h.send(JSON.stringify({type:"action_result",actionId:O.actionId,status:"failed",error:b})),r.warn(`[exec] ${O.actionId} (${O.action.type}) \u2192 REFUSED: ${b}`),r.warn(`[exec] update the CLI to clear this: ${kl}`),n({kind:"action",actionId:O.actionId,actionType:O.action.type,ok:!1,error:b});return}if(O.action.type==="model_drift"){p.add(O.actionId);try{let b,R=o?.repos.find(B=>B.name===O.action.repoName);if(!o?.contextDir||!R)b={status:"failed",error:"no local workspace/repo clone on this CLI"};else try{let{computeDriftReport:B}=await Promise.resolve().then(()=>(Wh(),Hh)),J=R.mountAs==="."?o.root:jr(o.root,R.mountAs);b={status:"done",result:{report:await B(J,o.contextDir,R.name)}}}catch(B){b={status:"failed",error:B instanceof Error?B.message:String(B)}}h.send(JSON.stringify({type:"action_result",actionId:O.actionId,...b}))}finally{p.delete(O.actionId)}return}if(O.action.type==="model_bootstrap"){p.add(O.actionId);try{let b;if(!o?.contextDir)b={status:"failed",error:"no Context Repo clone on this CLI"};else if(d)b={status:"failed",error:"model bootstrap is already running"};else{d=!0;try{let R=await ne(t.hubUrl,t.cliToken,t.projectId),{bootstrapDaemonModel:B}=await Promise.resolve().then(()=>(Ao(),ri)),J=await B(t.projectId,{root:o.root,contextDir:o.contextDir},R.repos,Pe=>r.info(`[model] ${Pe}`));r.info(`[model] bootstrap done: ${J.repos} repos, ${J.events} task events`),H(),b={status:"done",result:{repos:J.repos,events:J.events}}}catch(R){b={status:"failed",error:R instanceof Error?R.message:String(R)},r.warn(`[model] bootstrap failed: ${b.error}`)}finally{d=!1}}h.readyState===h.OPEN&&h.send(JSON.stringify({type:"action_result",actionId:O.actionId,...b}))}finally{p.delete(O.actionId)}return}if(O.action.type==="local_apply"){p.add(O.actionId);try{let b;if(!o)b={status:"failed",error:"no local workspace on this CLI"};else{let B=await mh(o,O.action.repos,r);if(b=B.ok?{status:"done",result:{repos:B.repos}}:{status:"failed",error:B.error},B.ok&&o.contextDir){let J=O.action.taskId.split(":")[1]??"";for(let Pe of J?B.repos:[]){let st=o.repos.find(Se=>Se.name===Pe.repoName);if(!st)continue;let{recordPipelineEvent:K}=await Promise.resolve().then(()=>(Qc(),sh));await K({contextDir:o.contextDir,repoDir:jr(o.root,st.mountAs),repoName:Pe.repoName,taskKey:J,commitSha:Pe.commit}).catch(Se=>r.warn(`[model] task event for ${J} failed: ${Se instanceof Error?Se.message:String(Se)}`))}H()}}h.send(JSON.stringify({type:"action_result",actionId:O.actionId,...b}));let R=b.status!=="failed";R?r.info(`[exec] ${O.actionId} (local_apply) \u2192 done`):r.warn(`[exec] ${O.actionId} (local_apply) \u2192 FAILED: ${b.status==="failed"?b.error:"?"}`),n({kind:"action",actionId:O.actionId,actionType:"local_apply",ok:R,...b.status==="failed"?{error:b.error}:{}})}finally{p.delete(O.actionId)}return}p.add(O.actionId);try{let b=await ph({action:O.action,repo:O.repo,trackerIssueId:O.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:C?()=>C.reportNow():void 0,refreshContextStatus:o?.contextDir?k:void 0,onRunActivity:ee}).catch(J=>({status:"failed",error:J instanceof Error?J.message:String(J)}));O.action.type==="tracker_comment"&&b.status==="done"&&"result"in b&&typeof b.result?.commentId=="string"&&m.add(b.result.commentId),h.send(JSON.stringify({type:"action_result",actionId:O.actionId,...b}));let R=b.status!=="failed",B=!R&&"error"in b?b.error:void 0;R?r.info(`[exec] ${O.actionId} (${O.action.type}) \u2192 done`):r.warn(`[exec] ${O.actionId} (${O.action.type}) \u2192 FAILED: ${B??"?"}`),n({kind:"action",actionId:O.actionId,actionType:O.action.type,ok:R,...B?{error:B}:{}}),R&&["apply_delivery","context_write","create_pr"].includes(O.action.type)&&H(),R&&["merge_pr","merge_branch"].includes(O.action.type)&&Ve(!0)}finally{p.delete(O.actionId)}}),h.on("close",(_,U)=>{let D=U?.toString("utf-8")??"";if(r.info(`[ws] closed code=${_}${D?` reason=${D}`:""}`),y.stop(),v.stop(),C?.stop(),$(),clearInterval(ze),Y&&clearTimeout(Y),M&&clearTimeout(M),D==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:_}),!c&&setTimeout(()=>{f=g()},2e3)}),h.on("error",_=>r.warn(`[ws] error: ${_.message}`)),h}return{stop(){c=!0,f.close()}}}async function wl(t,e,r){try{let n=await ne(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:s}=wo(t.projectId,n.repos,e?.contextDir);for(let i of o)r.info(`[repo] restaged repo set in ${i}`);for(let i of s)r.warn(`[repo] could not restage ${i.path}: ${i.error}`)}catch(n){r.warn(`[repo] repo-set reconcile skipped: ${n instanceof Error?n.message:String(n)}`)}}async function bE(t,e,r,n){let o=r.mountAs??r.name;if(o==="."){n.info(`[repo] ${r.name} mounts in place (mount_as: .) \u2014 nothing to clone`);return}let s=e?jr(e.root,o):Ie(t.projectId,r.name);if(Yh(jr(s,".git"))){n.info(`[repo] ${r.name} already present at ${s}`);return}try{await wE().clone(fo(r),s),n.info(`[repo] cloned ${r.name} \u2192 ${s}`)}catch(i){n.warn(`[repo] clone of ${r.name} failed (will retry lazily): ${i instanceof Error?i.message.trim():String(i)}`)}}function $E(t,e,r,n){let o=e?.repos.find(i=>i.name===r)?.mountAs??r,s=e?jr(e.root,o):Ie(t.projectId,r);if(e&&s===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Yh(jr(s,".git"))){n.info(`[repo] no local clone to purge for ${r} (${s})`);return}try{kE(s,{recursive:!0,force:!0}),n.info(`[repo] purged local clone ${s}`)}catch(i){n.warn(`[repo] purge of ${s} failed: ${i instanceof Error?i.message:String(i)}`)}}async function vE(t,e,r,n){if(!e){n.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let o of t.repos){let s=e.repos.find(l=>l.name===o.repoName),i=jr(e.root,s?.mountAs??o.repoName),a=s?.defaultBranch??o.defaultBranch,c=await mf(i,a).catch(l=>({status:"warn",reason:l instanceof Error?l.message:String(l)}));c.status==="updated"?n.info(`[sync] ${o.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?n.info(`[sync] ${o.repoName}: not cloned in workspace \u2014 skipped`):(n.warn(`[sync] ${o.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:o.repoName,reason:c.reason??"sync skipped"})))}}async function xE(t,e,r,n){let o=(s,i)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:s};i&&(a.error=i),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{await ve(e.contextDir,t.files,t.message),n.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),o("done")}catch(s){let i=s instanceof Error?s.message:String(s);n.warn(`[ctx] context_write ${t.id} failed: ${i}`),o("failed",i)}}async function SE(t,e,r,n){let o=(s,i)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:s};i&&(a.error=i),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[adr] adr_promote ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{let s=t.source??"task",i=await Tf(e.contextDir,t.taskKey,t.slugs,void 0,s);if(n.info(`[adr] adr_promote ${t.id}: promoted ${i.promoted.length}, skipped ${i.skipped.length}`+(i.promoted.length>0?` (${i.promoted.join(", ")})`:"")),i.missing.length>0){let a=l=>s==="staging"?`adr/DRAFT-${l}.md`:`tasks/${t.taskKey}/adr/DRAFT-${l}.md`,c=`draft file(s) missing in clone: ${i.missing.map(a).join(", ")}`;n.warn(`[adr] adr_promote ${t.id}: ${c}`),o("failed",c);return}o("done")}catch(s){let i=s instanceof Error?s.message:String(s);n.warn(`[adr] adr_promote ${t.id} failed: ${i}`),o("failed",i)}}function qh(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}Te();de();Lt();$l();bt();Ns();async function sg(t={profile:void 0}){let{cfg:e,profile:r}=ss(t.profile),n=q(e.projectId);n&&io(n),bo(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),$o(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),vo(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=Po(vl(),".codepipe","logs"),s=r?`cli-daemon-${r}`:"cli-daemon",i=cs("CLI_LOG",s,o);if(i.enabled){let d=new tn(i);ls(d),console.log(`[log] file logging \u2192 ${d.path} (rotate at ${i.maxBytes}B, keep ${i.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let a=null,c=ns(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=Po(vl(),".codepipe",r?Po("profiles",r,"context"):"context");if(await mc(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await ng(()=>si({cfg:e,secrets:n,contextDir:d,log:{info:m=>console.log(m),warn:m=>console.warn(m)}}),{log:{warn:m=>console.warn(m)}}),a||await mc(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let m=Po(vl(),".codepipe",r?Po("profiles",r,"context-config"):"context-config");Rs(a.contextDir,m,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=ni(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(`
|
|
962
|
+
[${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}_n();We();Te();async function ok(t={profile:void 0}){let e=et(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=gs(e.hubUrl,e.cliToken),n=await new Promise(s=>{let i=[],a=!1,c=setTimeout(()=>{i.push("timeout"),r.close(),s({ok:!1,events:i})},5e3);r.on("open",()=>{i.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let u=l.toString("utf-8");if(i.push(`msg:${u}`),u!=="pong")try{let p=JSON.parse(u);p.type==="registered"?(a=!!p.ok,clearTimeout(c),r.send("ping")):p.type}catch{}}),r.on("error",l=>i.push(`error:${l.message}`)),r.on("close",(l,u)=>{i.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),s({ok:a,events:i})}),setTimeout(()=>r.close(),1500)});for(let s of n.events)console.log(` ${s}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let s=await ne(e.hubUrl,e.cliToken,e.projectId);if(s.duplicateIntake){let i=s.duplicateIntake;console.warn(`warning: project \xAB${i.withProjectId}\xBB watches the same YouTrack columns (${i.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=je(t.profile);o?o.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${o.sandboxId} (${o.name}), llm=${o.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${o.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}Bo();import{readFileSync as RC}from"node:fs";F();We();Lt();$i();Pr();Yt();$r();Te();de();function he(t){throw new Error(t)}function xe(t,e){return(typeof t!="string"||t.trim().length===0)&&he(`config: '${e}' must be a non-empty string`),t.trim()}function Ko(t,e){if(t==null)return;typeof t!="string"&&he(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function IC(t){(!t||typeof t!="object")&&he("config: expected a JSON object");let e=t,r=xe(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||he("config: 'hubUrl' must start with http(s)://");let n=xe(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&he("config: 'project' is required");let s=o,i=xe(s.id,"project.id");Kt.test(i)||he("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=xe(s.name,"project.name"),c=xe(s.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&he("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=s.repos;Array.isArray(l)||he("config: 'project.repos' must be an array");let u=l.map((y,v)=>{(!y||typeof y!="object")&&he(`config: project.repos[${v}] must be an object`);let x=y,I=xe(x.host,`project.repos[${v}].host`);I!=="github"&&I!=="bitbucket"&&I!=="gitlab"&&he(`config: project.repos[${v}].host must be 'github', 'bitbucket' or 'gitlab'`);let E={name:xe(x.name,`project.repos[${v}].name`),host:I,owner:xe(x.owner,`project.repos[${v}].owner`),repoName:xe(x.repoName,`project.repos[${v}].repoName`)},$=Ko(x.defaultBranch,`project.repos[${v}].defaultBranch`);$&&(E.defaultBranch=$);let T=Ko(x.mountAs,`project.repos[${v}].mountAs`);return T&&(E.mountAs=T),E}),p=s.contextRepo;(!p||typeof p!="object")&&he("config: 'project.contextRepo' is required");let d=p,m=Ko(d.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&he("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:m,owner:xe(d.owner,"project.contextRepo.owner"),name:Ko(d.name,"project.contextRepo.name")??wt(i)},g={hubUrl:r,cliToken:n,project:{id:i,name:a,automationLevel:c,repos:u,contextRepo:f}},h=Ko(s.youtrackProjectKey,"project.youtrackProjectKey");if(h&&(g.project.youtrackProjectKey=h),s.index!==void 0&&(typeof s.index!="boolean"&&he("config: 'project.index' must be a boolean"),g.project.index=s.index),s.youtrackWrites!==void 0&&(typeof s.youtrackWrites!="boolean"&&he("config: 'project.youtrackWrites' must be a boolean"),g.project.youtrackWrites=s.youtrackWrites),s.llmProvider!==void 0){let y=xe(s.llmProvider,"project.llmProvider");y==="codex"&&he(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),y!=="claude"&&he("config: 'project.llmProvider' must be 'claude'"),g.project.llmProvider=y}let w=e.secrets;if(w!==void 0){(typeof w!="object"||w===null)&&he("config: 'secrets' must be an object");let y=w,v={};if(y.github){let x=y.github;v.github={token:xe(x.token,"secrets.github.token")}}if(y.bitbucket){let x=y.bitbucket;v.bitbucket={email:xe(x.email,"secrets.bitbucket.email"),apiToken:xe(x.apiToken,"secrets.bitbucket.apiToken")}}if(y.gitlab){let x=y.gitlab;v.gitlab={token:xe(x.token,"secrets.gitlab.token")}}if(y.youtrack){let x=y.youtrack;v.youtrack={url:xe(x.url,"secrets.youtrack.url").replace(/\/$/,""),token:xe(x.token,"secrets.youtrack.token")}}if(y.contextWrite){let x=y.contextWrite;v.contextWrite={token:xe(x.token,"secrets.contextWrite.token")}}g.secrets=v}return g}async function TC(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function CC(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await Ht(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${n}`)}if(e.bitbucket){let r=t.project.repos.find(s=>s.host==="bitbucket"),n=r?.owner??(t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:void 0),o=await Wt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let s=await fs(e.bitbucket.email,e.bitbucket.apiToken,r.owner,r.repoName);if(s)throw new Error(`Bitbucket: ${s}`)}console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await qt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await zt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function ow(t){let e=!t.configPath||t.configPath==="-"?await TC():RC(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){he(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=IC(r),{hubUrl:o,cliToken:s,project:i}=n;console.log(`codepipe init --headless \u2192 ${o} (project=${i.id})`),t.skipVerify||(console.log("verifying credentials\u2026"),await CC(n));let a={projectId:i.id,name:i.name,automationLevel:i.automationLevel,repos:i.repos};i.youtrackProjectKey&&(a.youtrackProjectKey=i.youtrackProjectKey),console.log(`provisioning Context Repo ${i.contextRepo.owner}/${i.contextRepo.name} (${i.contextRepo.host})\u2026`);let c=n.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,l;try{l=await Nn(a,i.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??en(),youtrackWrites:i.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){he(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let u;try{u=await Xt(o,s,a)}catch(d){if(d instanceof W&&d.status===409)console.log(`project ${i.id} already exists on HUB \u2014 reusing it`),u=await ne(o,s,i.id);else if(d instanceof W)he(`HUB \u2192 ${d.status} ${d.message}`);else throw d}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let p={hubUrl:o,cliToken:s,projectId:i.id,...n.secrets??{}};if(se(p),jt({hubUrl:o,cliToken:s,projectId:i.id},i.id),console.log(`config + secrets written (profile ${i.id}) \u2192 ${$t(i.id)}`),Ar(i.id,xt(a,i.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,"auto",i.llmProvider??Ge),{info:d=>console.log(d),warn:d=>console.warn(d)}),i.index)try{let{jobId:d}=await lo(o,s,i.id,{reindex:!1});console.log(`index job enqueued (job ${d}); runs once a SANDBOX claims it.`)}catch(d){console.warn(`could not enqueue index job: ${d instanceof Error?d.message:String(d)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${i.id} daemon`)}We();de();import{cancel as sw,intro as iw,isCancel as aw,log as Xl,outro as AC,password as cw}from"@clack/prompts";async function PC(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function lw(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await PC(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){iw("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Xl.message("Run `claude setup-token` and paste the token below (input hidden).");let s=await cw({message:"Claude OAuth token"});aw(s)&&(sw("aborted"),process.exit(1)),e=s.trim()}e||(console.error("login: no token provided"),process.exit(1)),Hd({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${as()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=et(t.profile);if(!e){iw(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Xl.message("Run `claude setup-token` and paste the token below (input hidden).");let s=await cw({message:"Claude OAuth token"});aw(s)&&(sw("aborted"),process.exit(1)),e=s.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=q(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},se(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Xl.success("Claude OAuth token saved."),AC("It will be sealed into job bundles when a SANDBOX (re)connects."))}Ao();F();We();Lt();$i();Pr();vi();Te();de();import{cancel as _C,confirm as jC,intro as NC,isCancel as uw,log as Ne,outro as OC,select as dw,text as ar}from"@clack/prompts";function pw(t){_C(t),process.exit(1)}function Mn(t){return uw(t)&&pw("aborted"),t}function Go(t){return uw(t)&&pw("aborted"),typeof t=="string"?t:""}async function LC(t,e){let r=Mn(await dw({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),n=e.find(i=>i.host===r)?.owner??e[0]?.owner??"",o=Go(await ar({message:"Context Repo owner (org / group / workspace / user)",placeholder:n||"your-org",initialValue:n,validate:i=>i.trim().length>0?void 0:"required"})).trim(),s=Go(await ar({message:"Context Repo name",placeholder:wt(t),initialValue:wt(t),validate:i=>i.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:s}}async function fw(t={profile:void 0}){let e=et(t.profile);NC(`codepipe project add \u2192 ${e.hubUrl}`);let r=Mn(await ar({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>Kt.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=Mn(await ar({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=Mn(await dw({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"})),s=Mn(await ar({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),i=Mn(await jC({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=Go(await ar({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()||Ue(w)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!d)break;let m=Ue(d);Ne.message(`${m.host}: ${m.owner}/${m.repoName}`);let f=Go(await ar({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:w=>w.trim().length>0?void 0:"required"})).trim(),g=Go(await ar({message:"default branch (optional)",placeholder:"main"})).trim(),h={name:f,host:m.host,owner:m.owner,repoName:m.repoName};g&&(h.defaultBranch=g),a.push(h)}let c={projectId:r,name:n,automationLevel:o,repos:a};s&&(c.youtrackProjectKey=s);let l=await LC(r,a),u=q(e.projectId);Ne.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await Nn(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??en(),youtrackWrites:i,trackerUrl:u?.youtrack?.url,log:{info:d=>Ne.message(d),warn:d=>Ne.warn(d)}})}catch(d){Ne.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,Ne.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await Xt(e.hubUrl,e.cliToken,c);Ne.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),Ar(r,xt(c,i,u?.youtrack?.url),{info:m=>Ne.message(m),warn:m=>Ne.warn(m)}),d.contextRepo&&(Ne.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),Ne.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&Ne.error(` error: ${d.provisioningError}`),OC("done")}catch(d){d instanceof W?(Ne.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&Ne.message(JSON.stringify(d.payload,null,2))):Ne.error(d instanceof Error?d.message:String(d)),process.exit(1)}}_n();We();Te();de();bt();Bo();import{existsSync as DC,rmSync as MC}from"node:fs";import{confirm as UC,intro as BC,isCancel as FC,log as cr,outro as KC,spinner as GC}from"@clack/prompts";function Rt(t){cr.error(t),process.exit(1)}var mw=t=>t.trim().replace(/\/+$/,"");async function hw(t){BC("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Re()?.spec.projectId??void 0;e||Rt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=dt(e);r||Rt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=mw(r.hubUrl),o=r.projectId,s=mw(t.hub);s.startsWith("http")||Rt("--hub must be an http(s):// URL");let i=t.toProfile??e,a=t.project??o,c=i===e;c&&a===o&&s===n&&Rt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let w=GC();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 W&&Rt(`source HUB ${n} \u2192 ${y.status} ${y.message}. The source HUB must be reachable with a valid token to move a project.`),y}}l.contextRepo||Rt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=q(o),p=(t.account??r.accountEmail??await Ln()).trim().toLowerCase();if(cr.message(`move project '${o}'
|
|
972
963
|
from : ${n} (profile ${e})
|
|
973
964
|
to : ${s} (profile ${i}, project ${a}, account ${p})
|
|
974
965
|
\u2022 the source registration on the old HUB is left intact (non-destructive)
|
|
975
966
|
\u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
|
|
976
|
-
`+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${i}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let w=await
|
|
977
|
-
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let g;try{g=await pf(e.hubUrl,e.cliToken,e.projectId,f)}catch(y){y instanceof W&&Ye(`HUB \u2192 ${y.status} ${y.message}`),Ye(y instanceof Error?y.message:String(y))}let{updated:h,errors:w}=wo(e.projectId,g.repos,r?.contextDir);for(let y of h)be.message(`updated ${y}`);for(let y of w)be.warn(`could not update ${y.path}: ${y.error}`);be.success(`added "${u}" \u2014 project now has ${g.repos.length} repo(s)`),nb("done")}async function ib(t){let e=et(t.profile);rb(`codepipe repo remove \u2192 project ${e.projectId}`);let r=Re()??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 ff(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof W&&(a.status===404&&Ye(`no repo named "${t.name}" in this project`),Ye(`HUB \u2192 ${a.status} ${a.message}`)),Ye(a instanceof Error?a.message:String(a))}let{updated:s,errors:i}=wo(e.projectId,o.repos,r?.contextDir);for(let a of s)be.message(`updated ${a}`);for(let a of i)be.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")be.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?ji(r.root,n):Ie(e.projectId,t.name);if(pu(ji(a,".git")))try{zA(a,{recursive:!0,force:!0}),be.message(`deleted local clone ${a}`)}catch(c){be.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else be.message(`no local clone found to purge (${a})`)}be.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),nb("done")}async function ab(t){let e=et(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,s=n.defaultBranch?` @${n.defaultBranch}`:"";console.log(` ${n.name} ${n.host}:${n.owner}/${n.repoName}${s} \u2192 ${o}`)}}Ri();Ql();su();_n();F();Le();_n();We();Te();Bo();import{hostname as nP}from"node:os";import{cancel as oP,confirm as cb,intro as sP,isCancel as db,log as Bn,multiselect as iP,outro as lb,password as aP,select as fu,text as mu}from"@clack/prompts";function Wo(t){oP(t),process.exit(1)}function Fn(t){return db(t)&&Wo("aborted"),t}function Ni(t){return db(t)&&Wo("aborted"),typeof t=="string"?t:""}function Oi(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function ub(t,e){try{let{secret:r}=await ks(t,e);return r}catch(r){throw r instanceof W&&r.status===404&&Wo("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 cP(t,e){if(Fn(await fu({message:"which projects should this worker serve?",options:[{value:"all",label:"all my projects (recommended \u2014 new projects included automatically)"},{value:"selected",label:"only selected projects"}],initialValue:"all"}))==="all")return[];if(e)try{let o=await uc(t,e);if(o.length>0)return Fn(await iP({message:"pick the projects (space to toggle, enter to confirm)",options:o.map(s=>({value:s.id,label:`${s.id} \u2014 ${s.name}`})),required:!0}));Bn.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Bn.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return Ni(await mu({message:"project ids (comma or space separated)",placeholder:"acme, beta",validate:o=>o.trim().length>0?void 0:"required"})).split(/[\s,]+/).filter(Boolean)}async function hu(t){sP("codepipe worker \u2014 set up this machine as a runner");let e=je(t.profile);e&&(Bn.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Fn(await cb({message:"re-register this worker?",initialValue:!1}))||Wo("keeping the existing registration"));let r=dt(t.profile)??dt(),n=Ni(await mu({message:"HUB URL",placeholder:at,initialValue:X("HUB_URL")??r?.hubUrl??at,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,s=Fn(await fu({message:"how to authorize the registration?",options:[...o?[{value:"local",label:"this machine's CLI account (recommended \u2014 no token hand-off)"}]:[],{value:"login",label:"log in by email (magic-link, like codepipe init)"},{value:"paste",label:"paste a registration token from the dashboard"}],initialValue:o?"local":"login"})),i,a=null;if(s==="local")a=r.cliToken,i=await ub(n,a),Bn.success("account-issued registration token minted");else if(s==="login"){let d=await Dn();a=(await Mn(n,d)).cliToken,i=await ub(n,a),Bn.success("account-issued registration token minted")}else i=Ni(await aP({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),i||Wo("a registration token is required");let c=await cP(n,a),l=Ni(await mu({message:"worker name",initialValue:nP(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=Fn(await fu({message:"agent backend",options:[{value:"claude-headless",label:"claude-headless \u2014 Claude Code on PATH (the real thing)"},{value:"mock",label:"mock \u2014 deterministic stub (development)"},{value:"",label:"none \u2014 this worker will not claim agent jobs"}],initialValue:"claude-headless"}));if(await Nr({hub:n,token:i,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Bn.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Fn(await cb({message:"start the claim-loop now?",initialValue:!0}))){lb("registered. start later with `codepipe worker`.");return}lb("starting the claim-loop\u2026"),await Do(t.profile?{profile:t.profile}:{})}function uP(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return X("PROFILE")}var me=uP();Hd(me);var Be=new lP;Be.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Ke).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{Oi()?await ou({profile:me}):await Zl({profile:me})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Be.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 Gw({configPath:t.config,skipVerify:t.skipVerify===!0}):await Pw({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Be.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","Personal CLI token (issued during `codepipe init`)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await np({...t,profile:me})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Be.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 _w({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Be.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await Mg({profile:me})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Be.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 fw({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Be.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 Vw({profile:me,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Be.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Dk({profile:me})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Be.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).option("--debug [categories]","Write local debug logs (comma-separated categories; default: agent-request \u2014 the full prompt and context each agent job receives, under ~/.codepipe/debug/)").action(async t=>{try{await Zl({profile:me,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var pb=Be.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");pb.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??X("HUB_URL")??dt(me)?.hubUrl??at,r=t.token??X("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Oi()){await hu({profile:me});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let n=X("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??X("WORKER_NAME"),s=t.llm??X("WORKER_LLM");await Nr({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...s?{llm:s}:{},...me?{profile:me}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});pb.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!je(me)&&Oi()){await hu({profile:me});return}await Do(me?{profile:me}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var fb=Be.command("project").description("Manage CodePipe projects");fb.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Zw({profile:me})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});fb.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 eb({...t,cliProfile:me})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var gu=Be.command("repo").description("Manage the project's git repositories");gu.command("add").description("Add a repo to this project (a path to an existing clone, or a clone URL)").argument("[target]","Path to an already-cloned repo, or a repo clone URL").action(async t=>{try{await sb({profile:me,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});gu.command("remove").description("Remove a repo from this project by its logical name").argument("<name>","Logical name of the repo (as shown by `codepipe repo list`)").option("--purge","Also delete the local clone",!1).action(async(t,e)=>{try{await ib({profile:me,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});gu.command("list").description("List the project's repos").action(async()=>{try{await ab({profile:me})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var mb=Be.command("model").description("Project map (model/ in the Context Repo)");mb.command("build").description("Build the project map from the local repo clones' git history").option("--repo <name>","Build only this repo (logical name)").action(async t=>{try{await yl({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});mb.command("bootstrap").description("Build the map and mine task events from the whole git history (cold start)").option("--repo <name>","Bootstrap only this repo (logical name)").action(async t=>{try{await kl({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Be.parseAsync();
|
|
967
|
+
`+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${i}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let w=await UC({message:"Continue?",initialValue:!0});(FC(w)||!w)&&Rt("aborted")}!c&&a===o&&cr.warn(`source and destination share the same project id, so they share one secrets file (${$t(a)}). Running both profiles at the same time will conflict \u2014 pass --project <newId> for a parallel setup, or keep only one active.`);let{cliToken:d,accountEmail:m}=await Dn(s,p),f={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:m,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};cr.step(`registering project on ${s}\u2026`);let g;try{g=await Xt(s,d,f)}catch(w){if(w instanceof W&&w.status===409){cr.warn(`project ${a} already exists on ${s} \u2014 reusing it`);try{g=await ne(s,d,a)}catch(y){throw y instanceof W&&Rt(`target HUB \u2192 ${y.status} ${y.message}`),y}}else if(w instanceof W&&w.status===403)Rt(`project ${a} already exists on ${s} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(w instanceof W)Rt(`target HUB \u2192 ${w.status} ${w.message}`);else throw w}cr.success(`project ${g.projectId} ready on ${s} (${g.provisioningStatus})`),jt({hubUrl:s,cliToken:d,projectId:a,accountEmail:m},i);let h={...u??{},hubUrl:s,cliToken:d,projectId:a};if(delete h.sandboxPins,se(h),cr.success(`profile '${i}' \u2192 ${$t(a)}`),c){let w=gt(i);DC(w)&&(MC(w),cr.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}KC(`done. next: \`codepipe up --profile ${i}\` \u2014 starts the daemon and a worker on ${s}.`)}We();import{existsSync as Jl,rmSync as HC,statSync as WC}from"node:fs";import{join as Ni,relative as qC,resolve as YC}from"node:path";import{cancel as VC,intro as yw,isCancel as zC,log as be,outro as kw,text as Dr}from"@clack/prompts";import{simpleGit as ww}from"simple-git";vi();Te();Rr();de();bt();function Ye(t){VC(t),process.exit(1)}function Mr(t){return zC(t)&&Ye("aborted"),typeof t=="string"?t:""}async function gw(t){try{let e=await ww(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function XC(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function JC(t,e){let r=q(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(XC(r,e)){be.message(`reusing existing ${e} credentials`);return}if(be.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=Mr(await Dr({message:"Atlassian account email (Bitbucket)",validate:s=>s.trim()?void 0:"required"})).trim(),o=Mr(await Dr({message:"Bitbucket API token (scoped)",validate:s=>s.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=Mr(await Dr({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}}se(r),be.success(`saved ${e} credentials`)}async function bw(t){let e=et(t.profile);yw(`codepipe repo add \u2192 project ${e.projectId}`);let r=Re()??void 0,n;try{n=(await ne(e.hubUrl,e.cliToken,e.projectId)).repos}catch(y){Ye(`could not read project from HUB: ${y instanceof Error?y.message:String(y)}`)}let o=t.target?.trim();if(!o){let y=await gw(process.cwd());y?(o=process.cwd(),be.message(`using the current directory (${y})`)):o=Mr(await Dr({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:v=>v.trim()?void 0:"required"})).trim()}let s=null,i,a,c,l;if(Jl(o)&&WC(o).isDirectory()){s=YC(o);let y=await gw(s);y||Ye(`${s} is not a git repository (no origin remote)`);let v=Ue(y);v||Ye(`origin ${y} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=v,i=y,be.message(`${a}: ${c}/${l} (already cloned at ${s})`)}else{let y=Ue(o);y||Ye(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=y,i=o,be.message(`${a}: ${c}/${l}`)}let u=Mr(await Dr({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)&&Ye(`a repo named "${u}" is already registered`);let p=Mr(await Dr({message:"default branch (optional)",placeholder:"main"})).trim(),d=u;if(s&&r&&(s===r.root||s.startsWith(r.root+"/"))){let y=qC(r.root,s);d=y===""?".":y}let m=Mr(await Dr({message:"mount_as (directory relative to the workspace root)",placeholder:d,initialValue:d})).trim()||d;n.some(y=>(y.mountAs??y.name)===m)&&Ye(`mount_as "${m}" is already used by another repo`),await JC(e,a);let f={name:u,host:a,owner:c,repoName:l,mountAs:m,...p?{defaultBranch:p}:{}};if(!s){let y=r?Ni(r.root,m):Ie(e.projectId,u);if(Jl(Ni(y,".git")))be.message(`already cloned at ${y}`);else{be.info(`cloning ${i} \u2192 ${y} \u2026`);try{await ww().clone(i,y),be.success(`cloned into ${y}`)}catch(v){Ye(`clone failed: ${v instanceof Error?v.message.trim():String(v)}
|
|
968
|
+
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let g;try{g=await Xp(e.hubUrl,e.cliToken,e.projectId,f)}catch(y){y instanceof W&&Ye(`HUB \u2192 ${y.status} ${y.message}`),Ye(y instanceof Error?y.message:String(y))}let{updated:h,errors:w}=wo(e.projectId,g.repos,r?.contextDir);for(let y of h)be.message(`updated ${y}`);for(let y of w)be.warn(`could not update ${y.path}: ${y.error}`);be.success(`added "${u}" \u2014 project now has ${g.repos.length} repo(s)`),kw("done")}async function $w(t){let e=et(t.profile);yw(`codepipe repo remove \u2192 project ${e.projectId}`);let r=Re()??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 Jp(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof W&&(a.status===404&&Ye(`no repo named "${t.name}" in this project`),Ye(`HUB \u2192 ${a.status} ${a.message}`)),Ye(a instanceof Error?a.message:String(a))}let{updated:s,errors:i}=wo(e.projectId,o.repos,r?.contextDir);for(let a of s)be.message(`updated ${a}`);for(let a of i)be.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")be.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?Ni(r.root,n):Ie(e.projectId,t.name);if(Jl(Ni(a,".git")))try{HC(a,{recursive:!0,force:!0}),be.message(`deleted local clone ${a}`)}catch(c){be.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else be.message(`no local clone found to purge (${a})`)}be.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),kw("done")}async function vw(t){let e=et(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,s=n.defaultBranch?` @${n.defaultBranch}`:"";console.log(` ${n.name} ${n.host}:${n.owner}/${n.repoName}${s} \u2192 ${o}`)}}Si();Ci();import{existsSync as Tw,mkdirSync as ZC,readFileSync as QC,writeFileSync as eA}from"node:fs";import{homedir as tA}from"node:os";import{dirname as rA,join as Cw}from"node:path";import*as Un from"node:readline";Te();ws();de();bt();Si();Ci();var Oi=Cw(tA(),".codepipe","history"),xw=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Aw=500,Sw=40;async function Pw(t={}){let e=Re();e||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let r=q(e.spec.projectId);r||(console.error(`no secrets for project ${e.spec.projectId} at ~/.codepipe/secrets/${e.spec.projectId}.json. run \`codepipe init\` or \`codepipe clone\` to set them up.`),process.exit(1)),io(r),console.log(`connected to ${r.hubUrl} as project ${e.spec.projectId}`),console.log("the CLI daemon and an embedded agent worker run in this session; /logs and /monitor show their output."),console.log("type /help to list commands. Ctrl+D or /quit to exit.");let n=Cr(e.contextDir),o=Object.keys(n);o.length>0&&console.log(`
|
|
969
|
+
\u26A0 unfinished local apply: ${o.map(a=>`${a} (${n[a].repos.map(c=>c.mountAs).join(", ")})`).join("; ")}
|
|
970
|
+
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let s=Un.createInterface({input:process.stdin,output:process.stdout,completer:nA,history:xA(),removeHistoryDuplicates:!0}),i={ws:e,secrets:r,connection:"connecting",rl:s,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};Qp(a=>ur(i,a)),i.daemon=ni({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:a=>ur(i,a),warn:a=>ur(i,a)},onEvent:a=>yA(i,a),workspace:{root:e.root,contextDir:e.contextDir,repos:e.spec.repos.map(a=>({name:a.name,mountAs:a.mountAs,defaultBranch:a.defaultBranch}))}});try{let a={hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId};await Ri(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=Ii({entry:c,profile:t.profile,onLine:u=>ur(i,`[worker] ${u}`)});l.on("exit",(u,p)=>{i.workerExited=!0,!eu&&lr(i,`[worker] exited (code ${u??(p?1:0)}) \u2014 agent jobs will NOT run; /quit and restart codepipe to bring it back`)}),i.workerChild=l,console.log("embedded agent worker started \u2014 agent jobs run on this machine.")}catch(a){console.warn(`[worker] could not start the embedded worker (${a instanceof Error?a.message:String(a)}). REPL commands still work; run \`codepipe up --reregister\` if the registration was removed.`)}Ql(i),s.prompt(),s.on("line",async a=>{let c=a.trim();if(c.length>0)try{if(await oA(i,c)){Iw(i);return}}catch(l){console.error(l instanceof Error?l.message:String(l))}i.unread=0,Ql(i),s.prompt()}),s.on("close",()=>{Iw(i)})}function nA(t){let e=xw.filter(r=>r.startsWith(t));return[e.length?e:xw,t]}async function oA(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return sA(),!1;case"/status":return await iA(t),!1;case"/tasks":return await aA(t,n),!1;case"/task":return await cA(t,n),!1;case"/sync":return await lA(t),!1;case"/logs":return kA(t,n),!1;case"/monitor":return wA(t),!1;case"/apply":return await Ew(t,n,"apply"),!1;case"/unstash":return await Ew(t,n,"unstash"),!1;case"/applied":return await uA(t,n),!1;case"/abort":return await dA(t,n),!1;case"/approve":return await Rw(t,n,"approve"),!1;case"/merge":return await Rw(t,n,"merge"),!1;case"/login":return fA(t,n),!1;case"/secret":return mA(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function sA(){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(`
|
|
971
|
+
`))}async function iA(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=Tw(Cw(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function aA(t,e){let r=bA(e,"--phase");try{let n=await Wp(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId),o=r?n.filter(s=>s.phase.toLowerCase()===r.toLowerCase()):n;if(o.length===0){console.log(" (no tasks)");return}for(let s of o)console.log(` ${s.key.padEnd(10)} ${s.phase.padEnd(16)} ${s.title}`)}catch(n){Ho(n)}}async function cA(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await qp(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){Ho(n)}}async function lA(t){let e=await Uo(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 Ew(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await df(t.ws,t.secrets,n,r,{info:s=>console.log(s),warn:s=>console.warn(s)});console.log(` ${o.message}`)}async function uA(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=Cr(t.ws.contextDir)[r],s=$A(e,"--pr");if(s.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let i=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of s){let l=c.indexOf("="),u,p;if(l>0?(u=c.slice(0,l),p=c.slice(l+1)):(p=c,u=o?.repos.length===1?pA(t,o.repos[0].mountAs):i.length===1?i[0]:""),!u){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${p}`);return}let d=p.match(/(?:pull|pull-requests)\/(\d+)/);if(!d){console.log(` cannot parse PR number from ${p}`);return}a.push({repoName:u,url:p,number:Number(d[1])})}try{let c=await Yp(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);yc(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){Ho(c)}}async function Rw(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await zp(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){Ho(o)}}async function dA(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=vA(e,"--reason")||"local apply aborted";await ff(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await Vp(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){Ho(o)}}function pA(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function fA(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},se(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 mA(t,e){let[r,n,...o]=e;if(r==="list"){let s=[];t.secrets.github&&s.push("github.token"),t.secrets.bitbucket&&s.push("bitbucket.email","bitbucket.apiToken"),t.secrets.youtrack&&s.push("youtrack.url","youtrack.token"),console.log(s.length?` ${s.join(`
|
|
972
|
+
`)}`:" (none)");return}if(r==="set"){let s=o.join(" ");if(!n||!s){console.log("usage: /secret set <key> <value> (keys: GH_TOKEN, YOUTRACK_URL, YOUTRACK_TOKEN, BITBUCKET_EMAIL, BITBUCKET_API_TOKEN)");return}hA(t.secrets,n,s),se(t.secrets),io(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}gA(t.secrets,n),se(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function hA(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 gA(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 yA(t,e){switch(e.kind){case"connected":t.connection="connecting",ur(t,"[hub] connected");break;case"registered":t.connection="registered",ur(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",lr(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",ur(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",lr(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":lr(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?ur(t,`[hub] action ${e.actionType} done`):lr(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break;case"local_applied":e.ok?lr(t,`[apply] ${e.taskKey}: branch ${(e.branches??[]).join(", ")} created locally (your checkout is untouched) \u2014 review, push, then: /applied ${e.taskKey} --pr <url>`):lr(t,`[apply] ${e.taskKey}: auto-apply failed \u2014 task stays in READY_TO_APPLY: ${e.error??"?"}`);break}}function ur(t,e){t.logBuffer.push(e),t.logBuffer.length>Aw&&t.logBuffer.shift(),t.follow&&lr(t,e)}function kA(t,e){let r=e[0];if(r==="follow"||r==="on"){Zl(t,!0);return}if(r==="off"){Zl(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(Aw,Number(r)||Sw)):Sw,o=t.logBuffer.slice(-n);if(o.length===0){console.log(" (no daemon logs buffered yet)");return}for(let s of o)console.log(` ${s}`);console.log(` \u2014 ${o.length} line(s); /monitor for live stream`)}function wA(t){Zl(t,!t.follow)}function Zl(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function lr(t,e){Un.cursorTo(process.stdout,0),Un.clearLine(process.stdout,0),process.stdout.write(e+`
|
|
973
|
+
`),t.unread+=1,Ql(t),t.rl.prompt(!0)}function Ql(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var eu=!1;function Iw(t){if(eu)return;eu=!0,SA(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
|
|
974
|
+
bye.`),setTimeout(()=>process.exit(0),150);return}console.log(`
|
|
975
|
+
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 bA(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function $A(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 vA(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function Ho(t){t instanceof W?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function xA(){if(!Tw(Oi))return[];try{return QC(Oi,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function SA(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{ZC(rA(Oi),{recursive:!0}),eA(Oi,r.slice().reverse().join(`
|
|
976
|
+
`)+`
|
|
977
|
+
`)}catch{}}_n();F();Le();_n();We();Te();Bo();import{hostname as EA}from"node:os";import{cancel as RA,confirm as _w,intro as IA,isCancel as Ow,log as Bn,multiselect as TA,outro as jw,password as CA,select as tu,text as ru}from"@clack/prompts";function Wo(t){RA(t),process.exit(1)}function Fn(t){return Ow(t)&&Wo("aborted"),t}function Li(t){return Ow(t)&&Wo("aborted"),typeof t=="string"?t:""}function Di(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Nw(t,e){try{let{secret:r}=await ks(t,e);return r}catch(r){throw r instanceof W&&r.status===404&&Wo("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 AA(t,e){if(Fn(await tu({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 pc(t,e);if(o.length>0)return Fn(await TA({message:"pick the projects (space to toggle, enter to confirm)",options:o.map(s=>({value:s.id,label:`${s.id} \u2014 ${s.name}`})),required:!0}));Bn.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Bn.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return Li(await ru({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 nu(t){IA("codepipe worker \u2014 set up this machine as a runner");let e=je(t.profile);e&&(Bn.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Fn(await _w({message:"re-register this worker?",initialValue:!1}))||Wo("keeping the existing registration"));let r=dt(t.profile)??dt(),n=Li(await ru({message:"HUB URL",placeholder:at,initialValue:X("HUB_URL")??r?.hubUrl??at,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,s=Fn(await tu({message:"how to authorize the registration?",options:[...o?[{value:"local",label:"this machine's CLI account (recommended \u2014 no token hand-off)"}]:[],{value:"login",label:"log in by email (magic-link, like codepipe init)"},{value:"paste",label:"paste a registration token from the dashboard"}],initialValue:o?"local":"login"})),i,a=null;if(s==="local")a=r.cliToken,i=await Nw(n,a),Bn.success("account-issued registration token minted");else if(s==="login"){let d=await Ln();a=(await Dn(n,d)).cliToken,i=await Nw(n,a),Bn.success("account-issued registration token minted")}else i=Li(await CA({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),i||Wo("a registration token is required");let c=await AA(n,a),l=Li(await ru({message:"worker name",initialValue:EA(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=Fn(await tu({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 Nr({hub:n,token:i,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Bn.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Fn(await _w({message:"start the claim-loop now?",initialValue:!0}))){jw("registered. start later with `codepipe worker`.");return}jw("starting the claim-loop\u2026"),await Do(t.profile?{profile:t.profile}:{})}function _A(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return X("PROFILE")}var me=_A();_d(me);var Be=new PA;Be.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Ke).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{Di()?await Pw({profile:me}):await Ti({profile:me})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Be.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 ow({configPath:t.config,skipVerify:t.skipVerify===!0}):await qk({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Be.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","Personal CLI token (issued during `codepipe init`)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await Wd({...t,profile:me})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Be.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 Yk({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Be.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await sg({profile:me})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Be.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 Nk({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Be.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 lw({profile:me,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Be.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await ok({profile:me})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Be.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 Ti({profile:me,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Lw=Be.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Lw.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??X("HUB_URL")??dt(me)?.hubUrl??at,r=t.token??X("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Di()){await nu({profile:me});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let n=X("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??X("WORKER_NAME"),s=t.llm??X("WORKER_LLM");await Nr({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...s?{llm:s}:{},...me?{profile:me}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Lw.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!je(me)&&Di()){await nu({profile:me});return}await Do(me?{profile:me}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Dw=Be.command("project").description("Manage CodePipe projects");Dw.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await fw({profile:me})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Dw.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 hw({...t,cliProfile:me})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var ou=Be.command("repo").description("Manage the project's git repositories");ou.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 bw({profile:me,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ou.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 $w({profile:me,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});ou.command("list").description("List the project's repos").action(async()=>{try{await vw({profile:me})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Mw=Be.command("model").description("Project map (model/ in the Context Repo)");Mw.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 pl({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Mw.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 fl({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Be.parseAsync();
|