@code-partner/codepipe 0.14.1-dev.297.gf8f1222b → 0.14.1-dev.298.gb3e4ee82

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +222 -228
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,40 +1,40 @@
1
1
  #!/usr/bin/env node
2
- var Dv=Object.defineProperty;var x=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ne=(t,e)=>{for(var r in e)Dv(t,r,{get:e[r],enumerable:!0})};var et,bt,$a=x(()=>{"use strict";et="0.14.1-dev.297.gf8f1222b",bt="https://hub.dev.codepipe.dev"});function mo(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Rd&&t<=kt}var kt,Rd,Td=x(()=>{"use strict";$a();kt=4,Rd=4});var Id=x(()=>{"use strict";$a()});function ho(t=6){return`# CodePipe Context Repo format version.
2
+ var Fv=Object.defineProperty;var x=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ne=(t,e)=>{for(var r in e)Fv(t,r,{get:e[r],enumerable:!0})};var et,bt,$a=x(()=>{"use strict";et="0.14.1-dev.298.gb3e4ee82",bt="https://hub.dev.codepipe.dev"});function ho(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Rd&&t<=kt}var kt,Rd,Td=x(()=>{"use strict";$a();kt=4,Rd=4});var Id=x(()=>{"use strict";$a()});function go(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 Sa(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 Ea(t,e=xa){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 Ra(t,e=xa){return e.filter(r=>r.version>t)}var Cd,vt,ln,xa,Pd=x(()=>{"use strict";Cd=6,vt=".codepipe-context.yaml",ln=".devpipe-context.yaml",xa=[{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",vt]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[vt]},{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 yo(t){return`model/facts/identity/${t}.yaml`}function Ir(t){return`model/facts/events/${t}.yaml`}function Ca(t){return`model/facts/annotations/${t}.md`}function Pa(t){return`model/derived/correlates/${t}.yaml`}function Aa(t){return`model/derived/touched/${t}.yaml`}function Ad(t){return t===""?"root":t.replace(/\//g,"-")}function _a(t,e){return`model/derived/structure/${t}/${Ad(e)}.yaml`}function ki(t){return typeof t=="string"&&jd.test(t)}function ne(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(!_d.includes(n))return null;let o=t.slice(e+1,r),i=t.slice(r+1);return o===""&&!Kv.includes(n)||i===""?null:{level:n,repo:o,path:i}}function Ee(t){return`task::${t}`}function ye(t,e,r){return`${t}:${e}:${r}`}function wo(t){let e=[];return Pt(t)?($i(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(!Pt(r)){e.push(`edges[${n}]: not an object`);return}ja.includes(r.kind)||e.push(`edges[${n}].kind: unknown "${String(r.kind)}"`),ne(r.from)||e.push(`edges[${n}].from: malformed nodeKey`),ne(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 Nd(t){return{...t,edges:un(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function Cr(t){return Ar(Nd(t))}function Pt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function $i(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function $t(t){return typeof t=="string"&&t.length>0}function Wv(t){return t.modelFormatVersion!==2}function Gt(t){let e=[];if(!Pt(t))return{ok:!1,errors:["shard: not an object"]};$i(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),$t(t.repo)||e.push("repo: missing or empty"),$t(t.builtFromCommit)||e.push("builtFromCommit: missing or empty");let r=typeof t.repo=="string"?t.repo:"",n=new Set;return Array.isArray(t.nodes)?t.nodes.forEach((o,i)=>{if(!Pt(o)){e.push(`nodes[${i}]: not an object`);return}let s=ne(o.key);if(!s){e.push(`nodes[${i}].key: malformed nodeKey (${JSON.stringify(o.key??null)})`);return}o.level!==s.level&&e.push(`nodes[${i}]: level "${String(o.level)}" does not match key prefix "${s.level}"`),r&&s.repo!==r&&e.push(`nodes[${i}].key: repo "${s.repo}" mixed into shard of repo "${r}"`);let a=o.key;n.has(a)&&e.push(`nodes[${i}].key: duplicate "${a}"`),n.add(a),o.entityId!==void 0&&!ki(o.entityId)&&e.push(`nodes[${i}].entityId: malformed (${JSON.stringify(o.entityId)})`)}):e.push("nodes: not an array"),Array.isArray(t.edges)?t.edges.forEach((o,i)=>{if(!Pt(o)){e.push(`edges[${i}]: not an object`);return}ja.includes(o.kind)||e.push(`edges[${i}].kind: unknown "${String(o.kind)}"`),(!$t(o.to)||!ne(o.to))&&e.push(`edges[${i}].to: malformed nodeKey`),(!$t(o.from)||!n.has(o.from))&&e.push(`edges[${i}].from: "${String(o.from)}" is not a node of this shard`),o.weight!==void 0&&!(typeof o.weight=="number"&&Number.isFinite(o.weight))&&e.push(`edges[${i}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}}function bo(t){let e=[];if(!Pt(t))return{ok:!1,errors:["identity: not an object"]};if($i(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),$t(t.repo)||e.push("repo: missing or empty"),t.builtFromCommit!==void 0&&!$t(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(!Pt(n)){e.push(`entities[${o}]: not an object`);return}ki(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)})`),ne(n.currentKey)||e.push(`entities[${o}].currentKey: malformed nodeKey`),n.status!=="active"&&n.status!=="orphaned"&&e.push(`entities[${o}].status: expected active|orphaned`),$t(n.firstSeen)||e.push(`entities[${o}].firstSeen: missing`),$t(n.lastSeen)||e.push(`entities[${o}].lastSeen: missing`),n.aliases!==void 0&&(Array.isArray(n.aliases)?n.aliases.forEach((i,s)=>{(!Pt(i)||!ne(i.key)||!$t(i.until))&&e.push(`entities[${o}].aliases[${s}]: malformed`)}):e.push(`entities[${o}].aliases: not an array`))})}return e.length?{ok:!1,errors:e}:{ok:!0,value:t}}function Kt(t){let e=[];return Pt(t)?($i(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),$t(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=>!$t(r)))&&e.push("commits: not an array of non-empty strings"),Array.isArray(t.files)?t.files.forEach((r,n)=>{if(!Pt(r)||!ne(r.key)){e.push(`files[${n}].key: malformed nodeKey`);return}r.entityId!==void 0&&!ki(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 un(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function Od(t){return{...t,nodes:un(t.nodes,e=>e.key),edges:un(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function Ld(t){return{...t,entities:un(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:un(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function Md(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:un(t.files,r=>r.key),...e?{links:e}:{}}}function go(t){return qv.test(t)?t:JSON.stringify(t)}function Dd(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 Ud(t){return t===null||["boolean","number","string"].includes(typeof t)}function Ta(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function Bd(t,e,r){if(Array.isArray(t)){for(let n of t)if(Ud(n))r.push(`${e}- ${Dd(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=Ta(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([i,s],a)=>{let c=a===0?`${e}- `:`${e} `;Ia(i,s,c,`${e} `,r)})}}return}for(let[n,o]of Ta(t))Ia(n,o,e,e,r)}function Ia(t,e,r,n,o){if(Ud(e))o.push(`${r}${go(t)}: ${Dd(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${go(t)}: []`):(o.push(`${r}${go(t)}:`),Bd(e,`${n} `,o));else{let i=Ta(e);if(i.length===0)o.push(`${r}${go(t)}: {}`);else{o.push(`${r}${go(t)}:`);for(let[s,a]of i)Ia(s,a,`${n} `,`${n} `,o)}}}function Ar(t){let e=[];return Bd(t,"",e),e.join(`
5
+ `}function Sa(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 Ea(t,e=xa){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 Ra(t,e=xa){return e.filter(r=>r.version>t)}var Cd,vt,un,xa,Pd=x(()=>{"use strict";Cd=6,vt=".codepipe-context.yaml",un=".devpipe-context.yaml",xa=[{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",vt]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[vt]},{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 wo(t){return`model/facts/identity/${t}.yaml`}function Cr(t){return`model/facts/events/${t}.yaml`}function Ca(t){return`model/facts/annotations/${t}.md`}function Pa(t){return`model/derived/correlates/${t}.yaml`}function Aa(t){return`model/derived/touched/${t}.yaml`}function Ad(t){return t===""?"root":t.replace(/\//g,"-")}function _a(t,e){return`model/derived/structure/${t}/${Ad(e)}.yaml`}function vi(t){return typeof t=="string"&&jd.test(t)}function ne(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(!_d.includes(n))return null;let o=t.slice(e+1,r),i=t.slice(r+1);return o===""&&!qv.includes(n)||i===""?null:{level:n,repo:o,path:i}}function Ee(t){return`task::${t}`}function ye(t,e,r){return`${t}:${e}:${r}`}function bo(t){let e=[];return Pt(t)?(xi(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(!Pt(r)){e.push(`edges[${n}]: not an object`);return}ja.includes(r.kind)||e.push(`edges[${n}].kind: unknown "${String(r.kind)}"`),ne(r.from)||e.push(`edges[${n}].from: malformed nodeKey`),ne(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 Nd(t){return{...t,edges:dn(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function Pr(t){return _r(Nd(t))}function Pt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function xi(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function $t(t){return typeof t=="string"&&t.length>0}function Vv(t){return t.modelFormatVersion!==2}function Gt(t){let e=[];if(!Pt(t))return{ok:!1,errors:["shard: not an object"]};xi(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),$t(t.repo)||e.push("repo: missing or empty"),$t(t.builtFromCommit)||e.push("builtFromCommit: missing or empty");let r=typeof t.repo=="string"?t.repo:"",n=new Set;return Array.isArray(t.nodes)?t.nodes.forEach((o,i)=>{if(!Pt(o)){e.push(`nodes[${i}]: not an object`);return}let s=ne(o.key);if(!s){e.push(`nodes[${i}].key: malformed nodeKey (${JSON.stringify(o.key??null)})`);return}o.level!==s.level&&e.push(`nodes[${i}]: level "${String(o.level)}" does not match key prefix "${s.level}"`),r&&s.repo!==r&&e.push(`nodes[${i}].key: repo "${s.repo}" mixed into shard of repo "${r}"`);let a=o.key;n.has(a)&&e.push(`nodes[${i}].key: duplicate "${a}"`),n.add(a),o.entityId!==void 0&&!vi(o.entityId)&&e.push(`nodes[${i}].entityId: malformed (${JSON.stringify(o.entityId)})`)}):e.push("nodes: not an array"),Array.isArray(t.edges)?t.edges.forEach((o,i)=>{if(!Pt(o)){e.push(`edges[${i}]: not an object`);return}ja.includes(o.kind)||e.push(`edges[${i}].kind: unknown "${String(o.kind)}"`),(!$t(o.to)||!ne(o.to))&&e.push(`edges[${i}].to: malformed nodeKey`),(!$t(o.from)||!n.has(o.from))&&e.push(`edges[${i}].from: "${String(o.from)}" is not a node of this shard`),o.weight!==void 0&&!(typeof o.weight=="number"&&Number.isFinite(o.weight))&&e.push(`edges[${i}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}}function ko(t){let e=[];if(!Pt(t))return{ok:!1,errors:["identity: not an object"]};if(xi(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),$t(t.repo)||e.push("repo: missing or empty"),t.builtFromCommit!==void 0&&!$t(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(!Pt(n)){e.push(`entities[${o}]: not an object`);return}vi(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)})`),ne(n.currentKey)||e.push(`entities[${o}].currentKey: malformed nodeKey`),n.status!=="active"&&n.status!=="orphaned"&&e.push(`entities[${o}].status: expected active|orphaned`),$t(n.firstSeen)||e.push(`entities[${o}].firstSeen: missing`),$t(n.lastSeen)||e.push(`entities[${o}].lastSeen: missing`),n.aliases!==void 0&&(Array.isArray(n.aliases)?n.aliases.forEach((i,s)=>{(!Pt(i)||!ne(i.key)||!$t(i.until))&&e.push(`entities[${o}].aliases[${s}]: malformed`)}):e.push(`entities[${o}].aliases: not an array`))})}return e.length?{ok:!1,errors:e}:{ok:!0,value:t}}function Kt(t){let e=[];return Pt(t)?(xi(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),$t(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=>!$t(r)))&&e.push("commits: not an array of non-empty strings"),Array.isArray(t.files)?t.files.forEach((r,n)=>{if(!Pt(r)||!ne(r.key)){e.push(`files[${n}].key: malformed nodeKey`);return}r.entityId!==void 0&&!vi(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 dn(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function Od(t){return{...t,nodes:dn(t.nodes,e=>e.key),edges:dn(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function Ld(t){return{...t,entities:dn(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:dn(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function Md(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:dn(t.files,r=>r.key),...e?{links:e}:{}}}function yo(t){return zv.test(t)?t:JSON.stringify(t)}function Dd(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 Ud(t){return t===null||["boolean","number","string"].includes(typeof t)}function Ta(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function Bd(t,e,r){if(Array.isArray(t)){for(let n of t)if(Ud(n))r.push(`${e}- ${Dd(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=Ta(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([i,s],a)=>{let c=a===0?`${e}- `:`${e} `;Ia(i,s,c,`${e} `,r)})}}return}for(let[n,o]of Ta(t))Ia(n,o,e,e,r)}function Ia(t,e,r,n,o){if(Ud(e))o.push(`${r}${yo(t)}: ${Dd(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${yo(t)}: []`):(o.push(`${r}${yo(t)}:`),Bd(e,`${n} `,o));else{let i=Ta(e);if(i.length===0)o.push(`${r}${yo(t)}: {}`);else{o.push(`${r}${yo(t)}:`);for(let[s,a]of i)Ia(s,a,`${n} `,`${n} `,o)}}}function _r(t){let e=[];return Bd(t,"",e),e.join(`
6
6
  `)+`
7
- `}function Da(t){return Ar(Od(t))}function Ua(t){return Ar(Ld(t))}function dn(t){return Ar(Md(t))}var Fe,Uv,Bv,Fv,Gv,bi,Tr,_d,ja,jd,Kv,lt,Na,Oa,La,vi,Hv,Ma,Pr,qv,Ba=x(()=>{"use strict";Fe=2,Uv="model",Bv="model/README.md",Fv="model/facts",Gv="model/derived",bi="model/derived/INDEX.yaml",Tr="model/derived/relates.yaml";_d=["system","container","component","code","task","adr"],ja=["contains","touched_by","correlates","relates","references","depends_on"],jd=/^e_[0-9a-f]{8}$/;Kv=["system","task","adr"];lt={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};Na=2,Oa=5,La=50,vi=2e3,Hv=5e4,Ma={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},Pr={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};qv=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});function Yv(t){return t==="DONE"}function Vv(t){return t==="AWAITING_EXTERNAL_FIX"?!1:Fa.indexOf(t)>=Fa.indexOf("IMPLEMENTING")}var Fa,Fd=x(()=>{"use strict";Fa=["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 Xv(t){for(let e of Ga)if(e.phases.includes(t))return e.id;return null}function Jv(t){for(let e of Gd)if(e.phases.includes(t))return e.id;return null}var Ga,zv,Gd,Kd=x(()=>{"use strict";Ga=[{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"]}],zv=Ga.flatMap(t=>t.phases),Gd=[{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 Ha(t){return Wd.includes(t)}function Zv(t){return Hd.includes(t)?"planning":"implementation"}function ut(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Ka,Hd,Wd,Qv,Wa=x(()=>{"use strict";Ka=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat","config","observer","council","testing"],Hd=["draft","analysis","chat","config","observer","council"],Wd=["chat","config"];Qv=1});function qd(t,e){return e.toLowerCase().includes(t.toLowerCase())}function Ya(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||Zd.every(o=>e.some(i=>qd(o,i.id))))return null;let n=[...e].sort((o,i)=>{let s=o.createdAt??"",a=i.createdAt??"";return s!==a?s<a?1:-1:o.id<i.id?1:-1});for(let o of Jd){let i=n.find(s=>qd(o,s.id));if(i)return i.id}return n[0].id}function pn(){return{default:null,roles:{}}}function e$(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():ko[e]??Xd}function t$(t){let e=t?.provider;return typeof e=="string"&&e.trim().length>0?e.trim():tt}function r$(t){let e=pn();if(!t||typeof t!="object")return e;let r=t.llm;if(!r||typeof r!="object")return e;let n=r.provider;typeof n=="string"&&n.trim().length>0&&(e.provider=n.trim());let o=r.models;if(!o||typeof o!="object")return e;for(let[i,s]of Object.entries(o))typeof s!="string"||s.trim().length===0||(i==="default"?e.default=s.trim():e.roles[i]=s.trim());return e}function fn(){return{default:null,roles:{}}}function n$(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():vo[e]}function o$(t){let e=fn();if(!t||typeof t!="object")return e;let r=t.llm;if(!r||typeof r!="object")return e;let n=r.effort;if(!n||typeof n!="object")return e;for(let[o,i]of Object.entries(n))typeof i!="string"||i.trim().length===0||(o==="default"?e.default=i.trim():e.roles[o]=i.trim());return e}function i$(t){return t.default===null&&Object.keys(t.roles).length===0?null:JSON.stringify(t)}function s$(t){if(!t)return fn();try{let e=JSON.parse(t);if(!e||typeof e!="object")return fn();let r=e,n=fn();typeof r.default=="string"&&(n.default=r.default);let o=r.roles;if(o&&typeof o=="object")for(let[i,s]of Object.entries(o))typeof s=="string"&&(n.roles[i]=s);return n}catch{return fn()}}function a$(t){let e=typeof t.provider=="string"&&t.provider.trim().length>0&&t.provider.trim()!==tt;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 c$(t){if(!t)return pn();try{let e=JSON.parse(t);if(!e||typeof e!="object")return pn();let r=e,n=pn();typeof r.provider=="string"&&r.provider.trim().length>0&&(n.provider=r.provider.trim()),typeof r.default=="string"&&(n.default=r.default);let o=r.roles;if(o&&typeof o=="object")for(let[i,s]of Object.entries(o))typeof s=="string"&&(n.roles[i]=s);return n}catch{return pn()}}var tt,qa,Ie,mn,xi,Si,Yd,Vd,zd,Ei,ko,Xd,Jd,Zd,Qd,Ri,vo,Va=x(()=>{"use strict";Wa();tt="claude",qa=[tt],Ie="opus",mn="sonnet",xi="haiku",Si=[Ie,mn,xi],Yd="build-discovery",Vd="code-review-verify",zd=[Yd,Vd],Ei=[...Ka,...zd],ko={analyze:Ie,implement:Ie,"resolve-conflict":Ie,rework:Ie,estimate:mn,build:xi,"build-discovery":Ie,"code-review":Ie,"code-review-verify":mn,draft:mn,index:Ie,backfill:Ie,analysis:Ie,chat:Ie,config:Ie,observer:Ie,council:Ie,testing:Ie},Xd=Ie,Jd=[Ie,mn,xi],Zd=Array.from(new Set(Object.values(ko)));Qd=["low","medium","high","xhigh"],Ri=Qd,vo={build:"low",estimate:"low",draft:"medium",index:"medium","code-review-verify":"medium"}});function Ht(t){return l$.has(t)?!0:u$.some(e=>t.startsWith(e))}function Ti(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function _r(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function Xa(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function Za(t,e){let r=Ti(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=_r(r.id,"id")??n;if(!za.test(o))throw new Error(`id must match ${za} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=_r(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=Ti(r.env,"env");s={};for(let[d,f]of Object.entries(p)){if(!rt.test(d))throw new Error(`env name "${d}" must match ${rt}`);if(typeof f!="string"&&typeof f!="number"&&typeof f!="boolean")throw new Error(`env.${d} must be a scalar`);s[d]=String(f)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>ep)throw new Error(`too many params (max ${ep})`);let p=new Set;a=c.map((d,f)=>d$(d,f,p))}let l=r.steps;if(!Array.isArray(l)||l.length===0)throw new Error("steps must be a non-empty list");if(l.length>tp)throw new Error(`too many steps (max ${tp})`);let u=l.map((p,d)=>{let f=Ti(p,`steps[${d}]`),m=_r(f.run,`steps[${d}].run`);if(!m||m.trim().length===0)throw new Error(`steps[${d}].run is required`);let g=_r(f.name,`steps[${d}].name`),b=Xa(f.timeout_sec,`steps[${d}].timeout_sec`);if(b!==void 0&&(!Number.isInteger(b)||b<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:m,...g?{name:g}:{},...b!==void 0?{timeout_sec:b}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function d$(t,e,r){let n=Ti(t,`params[${e}]`),o=_r(n.name,`params[${e}].name`);if(!o||!rt.test(o))throw new Error(`params[${e}].name must match ${rt}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let f=n.enum;if(!Array.isArray(f)||f.length===0||!f.every(m=>typeof m=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=f}let a=_r(n.label,`params[${e}].label`),c=_r(n.help,`params[${e}].help`),l=n.required===!0,u=Xa(n.min,`params[${e}].min`),p=Xa(n.max,`params[${e}].max`),d=n.default;if(d!=null&&typeof d!="string"&&typeof d!="number"&&typeof d!="boolean")throw new Error(`params[${e}].default must be a scalar`);return{name:o,type:i,...a?{label:a}:{},...c?{help:c}:{},...l?{required:!0}:{},...s?{enum:s}:{},...u!==void 0?{min:u}:{},...p!==void 0?{max:p}:{},...d!=null?{default:d}:{}}}function Qa(t,e){let r=t.params??[],n=new Map(r.map(i=>[i.name,i]));for(let i of Object.keys(e))if(!n.has(i))return{ok:!1,error:`unknown param: ${i}`};let o={};for(let i of r){let s=e[i.name];if(s==null||typeof s=="string"&&s.trim()==="")if(i.default!==void 0)s=i.default;else{if(i.required)return{ok:!1,error:`${i.name} is required`};continue}switch(i.type){case"string":{if(typeof s!="string")return{ok:!1,error:`${i.name} must be a string`};o[i.name]=s;break}case"enum":{if(typeof s!="string"||!(i.enum??[]).includes(s))return{ok:!1,error:`${i.name} must be one of: ${(i.enum??[]).join(", ")}`};o[i.name]=s;break}case"number":{let a=typeof s=="number"?s:typeof s=="string"?Number(s):NaN;if(!Number.isFinite(a))return{ok:!1,error:`${i.name} must be a number`};if(i.min!==void 0&&a<i.min)return{ok:!1,error:`${i.name} must be \u2265 ${i.min}`};if(i.max!==void 0&&a>i.max)return{ok:!1,error:`${i.name} must be \u2264 ${i.max}`};o[i.name]=a;break}case"boolean":{let a=typeof s=="boolean"?s:s==="true"?!0:s==="false"?!1:null;if(a===null)return{ok:!1,error:`${i.name} must be a boolean`};o[i.name]=a;break}}}return{ok:!0,values:o}}var rt,l$,u$,Ja,za,ep,tp,ec=x(()=>{"use strict";rt=/^[A-Z][A-Z0-9_]*$/,l$=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),u$=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];Ja=600,za=/^[a-z0-9-]+$/,ep=32,tp=64});function rp(){return{primary:we,context:we,tasks:we,docs:we,code_comments:we,chat:we,code_review:we,commits:we}}function np(t){return!t||t.trim().length===0||t.trim().toLowerCase()===we}function p$(t){if(typeof t!="string")return we;let e=t.trim().replace(/\s+/g," ");return e.length===0||e.length>40||e.toLowerCase()===we?we:e}function f$(t){let e=rp();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 $o)e[o]=p$(n[o]);return e}function m$(t){return $o.every(e=>np(t[e]))}var we,$o,hn,xo,tc=x(()=>{"use strict";we="auto",$o=["primary","context","tasks","docs","code_comments","chat","code_review","commits"],hn=["English","Russian","German","Spanish","French","Portuguese","Italian","Chinese","Japanese","Korean"],xo=40});function ic(t=op){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...ic(r.groups));return e}function ip(t,e){let r=JSON.stringify(e);return ic().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function sc(t){let e=ip(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.type==="string"&&e.mustContain&&!i.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:e.maxLength!==void 0&&i.length>e.maxLength?{ok:!1,error:`${e.id} must be \u2264 ${e.maxLength} chars`}:{ok:!0,field:e,value:i}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)?{ok:!1,error:`${e.id} must be a number`}:!e.float&&!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}case"string_map":{if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,error:`${e.id} must be a name\u2192value map`};let i=Object.entries(r);if(i.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(i.length>rc)return{ok:!1,error:`${e.id} must have \u2264 ${rc} entries`};let s={};for(let[a,c]of i){if(!rt.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${rt}`};if(Ht(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>nc)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${nc} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var h$,g$,rc,nc,oc,op,sp=x(()=>{"use strict";ec();Va();Ba();tc();h$={primary:"Primary language",context:"Context documents",tasks:"Tracker issues",docs:"Repo documentation",code_comments:"Code comments",chat:"Agent chat",code_review:"Code review comments",commits:"Commits & branches"},g$={primary:"The project's main language (agent status notes ride it). Empty \u21D2 auto.",context:"Knowledge, ADRs and task artifacts in the Context Repo. Empty \u21D2 auto.",tasks:"Issue titles/bodies the agent drafts. Empty \u21D2 auto.",docs:"Documentation changes in the project repos. Empty \u21D2 auto.",code_comments:"New code comments the agent writes. Empty \u21D2 auto.",chat:"The interactive task-drafting chat. Empty/auto \u21D2 mirror the user's messages.",code_review:"Review findings and PR comments. Empty \u21D2 follows the tracker-issues language.",commits:"Commit/PR subject & branch slug. Empty \u21D2 follows the tracker-issues language."},rc=64,nc=2e3,oc=2e3,op=[{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:[...qa],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:[...Si],help:"Overrides the recommended defaults for every role not listed below."},...Ei.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Si],help:`recommended: ${ko[t]}`}))]},{id:"llm.effort",label:"Reasoning effort by role",help:"Reasoning effort per pipeline stage (Claude Code --effort). Empty \u21D2 the mechanical roles run lowered (build/estimate: low; draft/index/code-review-verify: medium) and every other role keeps the backend default.",fields:[{id:"llm.effort.default",file:"regimen.yaml",path:["llm","effort","default"],type:"enum",label:"default (catch-all)",nullable:!0,suggestions:[...Ri],help:"Overrides the recommended lowerings for every role not listed below."},...Ei.map(t=>({id:`llm.effort.${t}`,file:"regimen.yaml",path:["llm","effort",t],type:"enum",label:t,nullable:!0,suggestions:[...Ri],help:vo[t]?`recommended: ${vo[t]}`:"recommended: backend default"}))]}]},{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:oc,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:oc,help:`e.g. "implementation details, bullet list of what was done, in the tracker's language". Empty \u21D2 the default PR body.`}]},{id:"apply.delivery",label:"Delivery & merge",help:"How a finished change reaches the repository: with or without a pull request, and who merges it.",fields:[{id:"apply.pull_request",file:"project.yaml",path:["apply","pull_request"],type:"boolean",label:"Open a pull request",nullable:!1,help:"On (default): the task branch is pushed and a pull request is opened \u2014 the change is reviewable in the git host and keeps a history of review comments. Off: no PR at all; the branch is merged into the default branch directly, and the agent's review remarks live only in the dashboard and the Context Repo."},{id:"apply.done",file:"project.yaml",path:["apply","done"],type:"enum",label:"Task is done when",nullable:!1,suggestions:["merge","branch"],help:"merge (default): the task is finished only once its change lands in the default branch. branch: the task ends at the pushed branch (plus the PR, if enabled) and nothing is merged for you."},{id:"apply.auto_merge",file:"project.yaml",path:["apply","auto_merge"],type:"enum",label:"Auto-merge pull requests",nullable:!1,suggestions:["off","on_ci_green"],help:"Applies to the pull-request path only. off (default): the merge waits for you (Approve on the task card). on_ci_green: as soon as the PR is open, conflict-free and its CI is green, CodePipe merges it \u2014 changes reach the default branch with no further review from you. Requires full automation; branch protection on the host still applies (a refused merge parks the task). Without pull requests, full automation merges the branch itself and this switch does not apply."}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{id:"testing",label:"Testing",help:"An optional phase after code review: writes the test plan you run in the morning and reports what it could verify.",fields:[{id:"testing.enabled",file:"regimen.yaml",path:["testing","enabled"],type:"boolean",nullable:!1,label:"Run the testing phase",help:"Off by default. When on, a task passing code review goes through a test pass before the PR: it derives TESTPLAN.md from the plan's requirements and reports per requirement what it could verify. A requirement it finds broken sends the change back for a fix (bounded below)."},{id:"testing.max_iterations",file:"regimen.yaml",path:["testing","max_iterations"],type:"number",nullable:!0,min:1,max:10,label:"Fix rounds before stopping",help:"How many times a failed test pass may send the change back before the task waits for you. Empty \u21D2 2."}]},{id:"code_review",label:"Code review",help:"One review mechanism for the pipeline's own changes and for developers' branches (the review column); they differ only in where the findings go.",fields:[{id:"code_review.verify_pass",file:"regimen.yaml",path:["code_review","verify_pass"],type:"boolean",nullable:!1,label:"Verifier pass (precision)",help:"On by default. A second, narrow agent checks every finding against the code (real? re-grade) before it costs a rework round or reaches a developer; the findings threshold below keeps small rounds cheap."},{id:"code_review.verify_min_findings",file:"regimen.yaml",path:["code_review","verify_min_findings"],type:"number",nullable:!0,min:1,label:"Verifier threshold (findings)",help:"The verifier runs only when a round carries at least this many actionable findings \u2014 1-2 are cheap to absorb, noise scales with volume. Empty = 3; 1 = verify every round."},{id:"code_review.max_blocking",file:"regimen.yaml",path:["code_review","max_blocking"],type:"number",nullable:!0,label:"Blocking budget (internal)",help:"Max blocker findings that keep their power in the pipeline's own review; the rest are demoted to major, weakest confidence first. Empty = 5."},{id:"code_review.external.max_blocking",file:"regimen.yaml",path:["code_review","external","max_blocking"],type:"number",nullable:!0,label:"Blocking budget (external)",help:"The same budget for a developer's branch review \u2014 tighter by default because a human reads these. Empty = 3."}]},{id:"skills",label:"Skills",help:"Reusable procedures the agent can invoke instead of improvising. Only their names and one-line descriptions sit in the prompt; the steps load when a skill is used.",fields:[{id:"skills.from_bundled",file:"regimen.yaml",path:["skills","from_bundled"],type:"boolean",nullable:!1,label:"Use the skills shipped with CodePipe",help:"On by default. General procedures maintained with the product."},{id:"skills.from_context_repo",file:"regimen.yaml",path:["skills","from_context_repo"],type:"boolean",nullable:!1,label:"Use this project's skills",help:"On by default. Skills the team writes in the context repository under `skills/<name>/SKILL.md`. These override a bundled skill of the same name."},{id:"skills.from_project_repo",file:"regimen.yaml",path:["skills","from_project_repo"],type:"boolean",nullable:!1,label:"Use the code repository's skills",help:"On by default. `.claude/skills/` inside the project repositories \u2014 the skills your developers already use locally. These win over both other sources."}]},{id:"quality",label:"Quality block",help:"Skip the whole quality block (build + code review) when a change touches only safe paths.",fields:[{id:"quality.skip_paths",file:"regimen.yaml",path:["quality","skip_paths"],type:"string_list",nullable:!0,label:"Skip paths (gitignore-style)",help:"When every changed file across all repos matches these globs, build and code review are skipped and the change goes straight to apply. One file outside the list runs both as usual. Use ! to re-include (e.g. !schema/**/*.md). Empty = never skip."}]},{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), the observer's intake plan waits for your APPROVE & START before the batch runs. Off \u21D2 conveyor: the batch starts automatically on the observer's plan. Either way every task passes the observer intake first."},{id:"observer.debounce_seconds",file:"regimen.yaml",path:["observer","debounce_seconds"],type:"number",label:"Intake window (seconds)",nullable:!0,min:5,max:3600,help:"How long the queue collects newly staged tasks before the observer reviews them as one batch. Empty \u21D2 60."},{id:"observer.fast_path",file:"regimen.yaml",path:["observer","fast_path"],type:"boolean",label:"Fast path for trivial tasks",nullable:!1,help:"On by default. A single small task with no links skips the observer's LLM pass and is routed by rules (noted in its journal as routed without review)."}]},{id:"council",label:"Council",help:"Several roles examine the same subject in parallel, each in its own process; a final session weighs their written opinions. Costs several agent runs per use \u2014 off by default, enable per phase.",fields:[{id:"council.questions",file:"regimen.yaml",path:["council","questions"],type:"boolean",nullable:!1,label:"Council on blocking questions",help:"Off (default): an agent's blocking question is answered by a single session, which keeps full automation moving cheaply. On: the council's roles each write an independent opinion first, and the answering session weighs them."},{id:"council.code_review",file:"regimen.yaml",path:["council","code_review"],type:"boolean",nullable:!1,label:"Council on code review",help:"Off (default): one reviewer session judges the change alone. On: the project's critic roles each review the change in their own parallel process first, and the reviewer session weighs their written findings into the verdict. Applies to the internal and the external review; the verifier pass always runs solo."},{id:"council.max_parallel",file:"regimen.yaml",path:["council","max_parallel"],type:"number",nullable:!0,min:1,max:5,label:"Max parallel roles",help:"How many role processes run at once (the rest wait their turn). Empty \u21D2 3; hard ceiling 5."}]},{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:$o.map(t=>({id:`language.${t}`,file:"project.yaml",path:["language",t],type:"string",label:h$[t],nullable:!0,maxLength:40,suggestions:t==="chat"?[we,...hn]:[...hn],help:g$[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:"On by default. Agents are asked to record intent annotations and receive an assembled context pack built from the project map. Off \u21D2 the pipeline ignores the map entirely and behaves exactly as if the feature were absent."},{id:"context.model.pack.idf_penalty",file:"regimen.yaml",path:["context","model","pack","idf_penalty"],type:"boolean",label:"Demote ubiquitous files in the pack",nullable:!1,help:"On by default. Files that reached the pack only through STATISTICAL co-change (not direct task evidence) are ranked down in proportion to how many past tasks touched them, so the budget goes to task-specific paths. Off restores pure activation order."},{id:"context.model.prompt.pack",file:"regimen.yaml",path:["context","model","prompt","pack"],type:"boolean",nullable:!1,label:"Give agents the context pack",help:"On by default. The assembled pack costs up to ~4000 tokens on every task of the analyze / estimate / implement / rework roles. Turning it off keeps the map building and stops the spend \u2014 the way to see what the pack is actually worth on this project."},{id:"context.model.prompt.annotations",file:"regimen.yaml",path:["context","model","prompt","annotations"],type:"boolean",nullable:!1,label:"Ask agents for intent annotations",help:"On by default. Adds the annotations block to the implement and rework prompts \u2014 the layer that records WHY the code is shaped this way. Cheap, and worth accumulating even while the pack is off."},{id:"context.index.hub",file:"regimen.yaml",path:["context","index","hub"],type:"enum",label:"Search index on the server",nullable:!0,suggestions:["off","metadata"],help:"off (default): search runs on your machine, nothing is uploaded. metadata: paths, labels and task texts (never code) are mirrored to the server so search and structure stay available while your machine is offline. Switching back to off deletes the mirrored rows."},{id:"context.model.issue_key_pattern",file:"regimen.yaml",path:["context","model","issue_key_pattern"],type:"string",label:"Issue-key pattern (regex)",nullable:!0,maxLength:200,help:"Regex that finds tracker issue keys in commit subjects when mining task events from history. Empty \u21D2 derived from the tracker project key (e.g. DEV-\\d+)."},{id:"context.model.cochange.window_commits",file:"regimen.yaml",path:["context","model","cochange","window_commits"],type:"number",label:"History window (commits)",nullable:!0,min:50,max:5e4,help:`How many commits back from the build commit are mined. Default ${lt.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 ${lt.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 ${lt.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 ${lt.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 ${lt.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 ${lt.topK}.`}]},{id:"rate_limit",label:"Rate limit",help:"Automatic project pause as the LLM usage window fills up.",fields:[{id:"rate_limit.auto_pause.enabled",file:"project.yaml",path:["rate_limit","auto_pause","enabled"],type:"boolean",nullable:!1,label:"Pause the project near the limit",help:"On (default): when window utilization reaches the threshold, the project is paused (same pause as the manual one) and you get an email \u2014 the remaining window stays available for your own work. Off: agents keep working until the provider actually runs out."},{id:"rate_limit.auto_pause.threshold",file:"project.yaml",path:["rate_limit","auto_pause","threshold"],type:"number",float:!0,nullable:!0,min:.05,max:1,label:"Pause threshold (share of the window)",help:"Fraction of the usage window at which the pause fires; the rest (1 \u2212 threshold) is your manual-work reserve. Empty \u21D2 0.75."}]},{id:"context.job_logs",label:"Job transcripts",help:"Whether the raw agent transcript of each job is kept in the Context Repo.",fields:[{id:"context.job_logs.enabled",file:"regimen.yaml",path:["context","job_logs","enabled"],type:"boolean",label:"Keep transcripts in the Context Repo",nullable:!1,help:"Off (default): the transcript is discarded after the run \u2014 nothing lands in the Context Repo. On: each job's raw transcript is committed as tasks/<KEY>/logs/job-<id>.jsonl for post-mortem debugging."}]}]});var ap=x(()=>{"use strict"});function cp(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 cc(t){let{name:e,body:r,origin:n}=t;if(!ac.test(e))return{ok:!1,error:`role name must match ${ac} (got "${e}")`};if(r.trim().length===0)return{ok:!1,error:"role body is empty \u2014 the body IS the role's prompt"};let o=t.frontmatter;if(o==null||typeof o!="object"||Array.isArray(o))return{ok:!1,error:"missing or malformed frontmatter block"};let i=o,s=i.description;if(typeof s!="string"||s.trim().length===0)return{ok:!1,error:"description is required (one line: what this role looks for)"};if(s.length>300)return{ok:!1,error:"description must be \u2264 300 characters"};let a=cp(i.refs);if(a===null)return{ok:!1,error:"refs must be a list of non-empty paths"};if(a.length>10)return{ok:!1,error:"refs must list at most 10 files \u2014 a role is a narrow view"};for(let f of a)if(f.startsWith("/")||f.includes(".."))return{ok:!1,error:`ref "${f}" must be a path inside the Context Repo`};let c=cp(i.scenarios);if(c===null)return{ok:!1,error:"scenarios must be a list"};let l=[];for(let f of c){if(!Ii.includes(f))return{ok:!1,error:`unknown scenario "${f}" \u2014 one of: ${Ii.join(", ")}`};l.includes(f)||l.push(f)}if(l.length===0)return{ok:!1,error:`scenarios must name at least one of: ${Ii.join(", ")}`};let u=i.model;if(u!==void 0&&(typeof u!="string"||u.trim().length===0))return{ok:!1,error:"model must be a non-empty string when set"};let p=i.provider;if(p!==void 0&&(typeof p!="string"||p.trim().length===0))return{ok:!1,error:"provider must be a non-empty string when set"};let d=i.enabled;return d!==void 0&&typeof d!="boolean"?{ok:!1,error:"enabled must be true or false"}:{ok:!0,role:{name:e,description:s.trim(),...typeof u=="string"?{model:u.trim()}:{},...typeof p=="string"?{provider:p.trim()}:{},refs:a,scenarios:l,enabled:d!==!1,body:r.trim(),origin:n}}}function lc(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 uc(t,e){return t.filter(r=>r.enabled&&r.scenarios.includes(e))}var Ii,ac,Uj,Bj,lp=x(()=>{"use strict";Ii=["plan_review","code_review","council"],ac=/^[a-z][a-z0-9-]{1,39}$/,Uj=10,Bj=300});function dc(t){return up.includes(t)}function pc(t){return`prompts/${t}.md`}var up,dp=x(()=>{"use strict";up=["analysis","analyze","backfill","build","chat","code-review","code-review-external","code-review-fix","code-review-verify","config","council","draft","estimate","implement","index","observer","resolve-conflict","review-comment","rework","testing"]});function mc(t){if(!fc.test(t.name))return{ok:!1,error:`skill directory name must match ${fc}`};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 hc(t,e,r){let n=new Map;for(let o of[...t,...e,...r])n.set(o.name,o);return[...n.values()].sort((o,i)=>o.name<i.name?-1:o.name>i.name?1:0)}function fp(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(!y$.test(n))return{ok:!1,error:`"${t}": expected <owner>/<repo>[@<40-hex sha>]`};let i=pp.find(s=>s.repo.toLowerCase()===n.toLowerCase());return o&&!w$.test(o)?{ok:!1,error:`"${t}": pin to a full 40-character commit sha \u2014 a branch or tag can change under you`}:!i&&!o?{ok:!1,error:`"${t}": a third-party marketplace must be pinned to a commit (<owner>/<repo>@<sha>). Its skills run beside your code with the agent's token.`}:{ok:!0,source:{repo:n,sha:o,name:i?.name??n.replace("/","-").toLowerCase(),official:!!i}}}function b$(t){let e=[],r=[],n=new Set;for(let o of t){if(!o.trim())continue;let i=fp(o);if(!i.ok){r.push(i.error);continue}n.has(i.source.name)||(n.add(i.source.name),e.push(i.source))}return{sources:e,errors:r}}function v$(t,e){let r=new Set(e.map(i=>i.name)),n={},o=[];for(let i of t){let s=i.trim();if(s){if(!k$.test(s)||!r.has(s.slice(s.indexOf("@")+1))){o.push(s);continue}n[s]=!0}}return{enabled:n,unknown:o}}var fc,Kj,pp,y$,w$,k$,mp=x(()=>{"use strict";fc=/^[a-z][a-z0-9-]{1,39}$/,Kj=300;pp=[{repo:"anthropics/skills",name:"anthropic-agent-skills"},{repo:"anthropics/claude-plugins-official",name:"claude-plugins-official"}],y$=/^[A-Za-z0-9][\w.-]*\/[A-Za-z0-9][\w.-]*$/,w$=/^[0-9a-f]{40}$/;k$=/^[A-Za-z0-9][\w.-]*@[A-Za-z0-9][\w.-]*$/});function hp(t,e){if(t==null)return[];if(!Array.isArray(t)||t.length>e)return null;let r=[];for(let n of t){if(typeof n!="string"||n.trim().length===0)return null;r.push(n.trim())}return r}function $$(t,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=hp(n.order,e.length);if(o===null)return{ok:!1,error:"order must be a list of task keys"};for(let m of o)if(!r.has(m))return{ok:!1,error:`order names ${m}, which is not in this batch`};if(new Set(o).size!==o.length)return{ok:!1,error:"order repeats a task key"};let i=e.filter(m=>!o.includes(m));if(o.length>0&&i.length>0)return{ok:!1,error:`order omits ${i.join(", ")}`};let s=n.tasks,a=[];if(s!=null){if(!Array.isArray(s))return{ok:!1,error:"tasks must be a list"};for(let m of s){if(!m||typeof m!="object")return{ok:!1,error:"each task entry must be an object"};let g=m,b=typeof g.taskKey=="string"?g.taskKey.trim():"";if(!r.has(b))return{ok:!1,error:`tasks names ${b||"(empty)"}, which is not in this batch`};let w=hp(g.after,e.length);if(w===null)return{ok:!1,error:`${b}: after must be a list of task keys`};for(let y of w){if(!r.has(y))return{ok:!1,error:`${b}: after names ${y}, not in this batch`};if(y===b)return{ok:!1,error:`${b}: cannot come after itself`}}let v=typeof g.decisions=="string"?g.decisions.trim():"";a.push({taskKey:b,decisions:v.slice(0,4e3),after:w})}}let c=[],l=n.conflicts;if(Array.isArray(l))for(let m of l){if(!m||typeof m!="object")continue;let g=m,b=typeof g.taskKey=="string"?g.taskKey.trim():"",w=typeof g.adr=="string"?g.adr.trim():"",v=typeof g.detail=="string"?g.detail.trim():"";!r.has(b)||!v||c.push({taskKey:b,adr:w,detail:v.slice(0,4e3)})}let u=[],p=n.related;if(Array.isArray(p))for(let m of p){if(!m||typeof m!="object")continue;let g=m,b=typeof g.taskKey=="string"?g.taskKey.trim():"",w=typeof g.detail=="string"?g.detail.trim():"";!b||!w||u.push({taskKey:b,detail:w.slice(0,4e3)})}let d=typeof n.summary=="string"?n.summary.trim().slice(0,4e3):"",f=n.deferBehind===!0;return{ok:!0,plan:{order:o,tasks:a,conflicts:c,related:u,summary:d,deferBehind:f}}}var Wj,qj,gp=x(()=>{"use strict";Wj=4e3,qj=4e3});function x$(t,e){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:"council verdict must be a JSON object"};let r=t,n=r.unresolved===!0,o=typeof r.fork=="string"?r.fork.trim().slice(0,4e3):"";if(n)return o?{ok:!0,verdict:{answers:[],unresolved:!0,fork:o}}:{ok:!1,error:"an unresolved verdict must describe the fork"};let i=r.answers;if(!Array.isArray(i))return{ok:!1,error:"answers must be a list"};if(i.length!==e.length)return{ok:!1,error:`expected ${e.length} answer(s), got ${i.length}`};let s=[];for(let[a,c]of i.entries()){if(!c||typeof c!="object")return{ok:!1,error:`answer ${a+1} must be an object`};let l=c,u=typeof l.answer=="string"?l.answer.trim():"";if(!u)return{ok:!1,error:`answer ${a+1} is empty`};s.push({question:typeof l.question=="string"?l.question.trim():e[a],answer:u.slice(0,4e3),rationale:typeof l.rationale=="string"?l.rationale.trim().slice(0,4e3):""})}return{ok:!0,verdict:{answers:s,unresolved:!1,fork:""}}}var Vj,yp=x(()=>{"use strict";Vj=4e3});function R$(t){let e=t.replace(/^#+\s*/,"").trim();for(let r of S$)if(r.re.test(e))return{kind:r.kind,letter:r.letter};return null}function gc(t){let e=[],r=new Map,n="",o=null,i=null;for(let a of t.split(`
8
- `)){let c=/^#{1,6}\s+(.*)$/.exec(a);if(c){n=c[1].trim(),o=R$(n),i=null;continue}let l=E$.exec(a);if(l&&o){let u=l[1];r.set(u,(r.get(u)??0)+1),i={id:u,kind:o.kind,text:l[2].trim(),section:n},e.push(i);continue}if(i&&a.trim()&&!/^#{1,6}\s/.test(a)&&!/^\s*[-*]\s/.test(a)){i.text=`${i.text}
9
- ${a.trim()}`.trim();continue}a.trim()||(i=null)}let s=[...r.entries()].filter(([,a])=>a>1).map(([a])=>a);return{items:e,structured:e.length>=2&&s.length===0,duplicateIds:s}}function T$(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 I$(t,e){let r=new Map(t.items.map(s=>[s.id,s])),n=e.filter(s=>!s.approved),o=e.filter(s=>s.approved).map(s=>s.id);if(n.length===0)return"";let i=["Rejected plan items:",""];for(let s of n){let a=r.get(s.id),c=a?`${s.id} \u2014 ${a.text.split(`
7
+ `}function Da(t){return _r(Od(t))}function Ua(t){return _r(Ld(t))}function pn(t){return _r(Md(t))}var Fe,Gv,Kv,Hv,Wv,ki,Ir,_d,ja,jd,qv,lt,Na,Oa,La,$i,Yv,Ma,Ar,zv,Ba=x(()=>{"use strict";Fe=2,Gv="model",Kv="model/README.md",Hv="model/facts",Wv="model/derived",ki="model/derived/INDEX.yaml",Ir="model/derived/relates.yaml";_d=["system","container","component","code","task","adr"],ja=["contains","touched_by","correlates","relates","references","depends_on"],jd=/^e_[0-9a-f]{8}$/;qv=["system","task","adr"];lt={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};Na=2,Oa=5,La=50,$i=2e3,Yv=5e4,Ma={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},Ar={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};zv=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});function Xv(t){return t==="DONE"}function Jv(t){return t==="AWAITING_EXTERNAL_FIX"?!1:Fa.indexOf(t)>=Fa.indexOf("IMPLEMENTING")}var Fa,Fd=x(()=>{"use strict";Fa=["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 Qv(t){for(let e of Ga)if(e.phases.includes(t))return e.id;return null}function e$(t){for(let e of Gd)if(e.phases.includes(t))return e.id;return null}var Ga,Zv,Gd,Kd=x(()=>{"use strict";Ga=[{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"]}],Zv=Ga.flatMap(t=>t.phases),Gd=[{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 Ha(t){return Wd.includes(t)}function t$(t){return Hd.includes(t)?"planning":"implementation"}function ut(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Ka,Hd,Wd,r$,Wa=x(()=>{"use strict";Ka=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat","config","observer","council","testing"],Hd=["draft","analysis","chat","config","observer","council"],Wd=["chat","config"];r$=1});function n$(t){return typeof t=="string"&&Jd.includes(t.trim())?t.trim():null}function qd(t,e){return e.toLowerCase().includes(t.toLowerCase())}function Ya(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||tp.every(o=>e.some(i=>qd(o,i.id))))return null;let n=[...e].sort((o,i)=>{let s=o.createdAt??"",a=i.createdAt??"";return s!==a?s<a?1:-1:o.id<i.id?1:-1});for(let o of ep){let i=n.find(s=>qd(o,s.id));if(i)return i.id}return n[0].id}function fn(){return{default:null,roles:{}}}function o$(t,e,r=Zd){let n=t?.roles?.[e];if(typeof n=="string"&&n.trim().length>0)return n.trim();if(t?.default&&t.default.trim().length>0)return t.default.trim();let o=Qd[r]?.[e];return o||(vo[e]??Xd)}function i$(t){let e=t?.provider;return typeof e=="string"&&e.trim().length>0?e.trim():tt}function s$(t){let e=fn();if(!t||typeof t!="object")return e;let r=t.llm;if(!r||typeof r!="object")return e;let n=r.provider;typeof n=="string"&&n.trim().length>0&&(e.provider=n.trim());let o=r.models;if(!o||typeof o!="object")return e;for(let[i,s]of Object.entries(o))typeof s!="string"||s.trim().length===0||(i==="default"?e.default=s.trim():e.roles[i]=s.trim());return e}function mn(){return{default:null,roles:{}}}function a$(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():$o[e]}function c$(t){let e=mn();if(!t||typeof t!="object")return e;let r=t.llm;if(!r||typeof r!="object")return e;let n=r.effort;if(!n||typeof n!="object")return e;for(let[o,i]of Object.entries(n))typeof i!="string"||i.trim().length===0||(o==="default"?e.default=i.trim():e.roles[o]=i.trim());return e}function l$(t){return t.default===null&&Object.keys(t.roles).length===0?null:JSON.stringify(t)}function u$(t){if(!t)return mn();try{let e=JSON.parse(t);if(!e||typeof e!="object")return mn();let r=e,n=mn();typeof r.default=="string"&&(n.default=r.default);let o=r.roles;if(o&&typeof o=="object")for(let[i,s]of Object.entries(o))typeof s=="string"&&(n.roles[i]=s);return n}catch{return mn()}}function d$(t){let e=typeof t.provider=="string"&&t.provider.trim().length>0&&t.provider.trim()!==tt;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 p$(t){if(!t)return fn();try{let e=JSON.parse(t);if(!e||typeof e!="object")return fn();let r=e,n=fn();typeof r.provider=="string"&&r.provider.trim().length>0&&(n.provider=r.provider.trim()),typeof r.default=="string"&&(n.default=r.default);let o=r.roles;if(o&&typeof o=="object")for(let[i,s]of Object.entries(o))typeof s=="string"&&(n.roles[i]=s);return n}catch{return fn()}}var tt,qa,Ie,Ht,hn,Si,Yd,Vd,zd,Ei,vo,Xd,Jd,Zd,Qd,ep,tp,rp,Ri,$o,Va=x(()=>{"use strict";Wa();tt="claude",qa=[tt],Ie="opus",Ht="sonnet",hn="haiku",Si=[Ie,Ht,hn],Yd="build-discovery",Vd="code-review-verify",zd=[Yd,Vd],Ei=[...Ka,...zd],vo={analyze:Ie,implement:Ie,"resolve-conflict":Ie,rework:Ie,estimate:Ht,build:hn,"build-discovery":Ie,"code-review":Ie,"code-review-verify":Ht,draft:Ht,index:Ie,backfill:Ie,analysis:Ie,chat:Ie,config:Ie,observer:Ie,council:Ie,testing:Ie},Xd=Ie,Jd=["express","balanced","full"],Zd="full",Qd={express:{"code-review":Ht,"code-review-verify":hn},balanced:{implement:Ht,"code-review":Ht,"code-review-verify":hn},full:{}};ep=[Ie,Ht,hn],tp=Array.from(new Set(Object.values(vo)));rp=["low","medium","high","xhigh"],Ri=rp,$o={build:"low",estimate:"low",draft:"medium",index:"medium","code-review-verify":"medium"}});function Wt(t){return f$.has(t)?!0:m$.some(e=>t.startsWith(e))}function Ti(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function jr(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function Xa(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function Za(t,e){let r=Ti(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=jr(r.id,"id")??n;if(!za.test(o))throw new Error(`id must match ${za} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=jr(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=Ti(r.env,"env");s={};for(let[d,f]of Object.entries(p)){if(!rt.test(d))throw new Error(`env name "${d}" must match ${rt}`);if(typeof f!="string"&&typeof f!="number"&&typeof f!="boolean")throw new Error(`env.${d} must be a scalar`);s[d]=String(f)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>np)throw new Error(`too many params (max ${np})`);let p=new Set;a=c.map((d,f)=>h$(d,f,p))}let l=r.steps;if(!Array.isArray(l)||l.length===0)throw new Error("steps must be a non-empty list");if(l.length>op)throw new Error(`too many steps (max ${op})`);let u=l.map((p,d)=>{let f=Ti(p,`steps[${d}]`),m=jr(f.run,`steps[${d}].run`);if(!m||m.trim().length===0)throw new Error(`steps[${d}].run is required`);let g=jr(f.name,`steps[${d}].name`),b=Xa(f.timeout_sec,`steps[${d}].timeout_sec`);if(b!==void 0&&(!Number.isInteger(b)||b<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:m,...g?{name:g}:{},...b!==void 0?{timeout_sec:b}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function h$(t,e,r){let n=Ti(t,`params[${e}]`),o=jr(n.name,`params[${e}].name`);if(!o||!rt.test(o))throw new Error(`params[${e}].name must match ${rt}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let f=n.enum;if(!Array.isArray(f)||f.length===0||!f.every(m=>typeof m=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=f}let a=jr(n.label,`params[${e}].label`),c=jr(n.help,`params[${e}].help`),l=n.required===!0,u=Xa(n.min,`params[${e}].min`),p=Xa(n.max,`params[${e}].max`),d=n.default;if(d!=null&&typeof d!="string"&&typeof d!="number"&&typeof d!="boolean")throw new Error(`params[${e}].default must be a scalar`);return{name:o,type:i,...a?{label:a}:{},...c?{help:c}:{},...l?{required:!0}:{},...s?{enum:s}:{},...u!==void 0?{min:u}:{},...p!==void 0?{max:p}:{},...d!=null?{default:d}:{}}}function Qa(t,e){let r=t.params??[],n=new Map(r.map(i=>[i.name,i]));for(let i of Object.keys(e))if(!n.has(i))return{ok:!1,error:`unknown param: ${i}`};let o={};for(let i of r){let s=e[i.name];if(s==null||typeof s=="string"&&s.trim()==="")if(i.default!==void 0)s=i.default;else{if(i.required)return{ok:!1,error:`${i.name} is required`};continue}switch(i.type){case"string":{if(typeof s!="string")return{ok:!1,error:`${i.name} must be a string`};o[i.name]=s;break}case"enum":{if(typeof s!="string"||!(i.enum??[]).includes(s))return{ok:!1,error:`${i.name} must be one of: ${(i.enum??[]).join(", ")}`};o[i.name]=s;break}case"number":{let a=typeof s=="number"?s:typeof s=="string"?Number(s):NaN;if(!Number.isFinite(a))return{ok:!1,error:`${i.name} must be a number`};if(i.min!==void 0&&a<i.min)return{ok:!1,error:`${i.name} must be \u2265 ${i.min}`};if(i.max!==void 0&&a>i.max)return{ok:!1,error:`${i.name} must be \u2264 ${i.max}`};o[i.name]=a;break}case"boolean":{let a=typeof s=="boolean"?s:s==="true"?!0:s==="false"?!1:null;if(a===null)return{ok:!1,error:`${i.name} must be a boolean`};o[i.name]=a;break}}}return{ok:!0,values:o}}var rt,f$,m$,Ja,za,np,op,ec=x(()=>{"use strict";rt=/^[A-Z][A-Z0-9_]*$/,f$=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),m$=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];Ja=600,za=/^[a-z0-9-]+$/,np=32,op=64});function ip(){return{primary:we,context:we,tasks:we,docs:we,code_comments:we,chat:we,code_review:we,commits:we}}function sp(t){return!t||t.trim().length===0||t.trim().toLowerCase()===we}function g$(t){if(typeof t!="string")return we;let e=t.trim().replace(/\s+/g," ");return e.length===0||e.length>40||e.toLowerCase()===we?we:e}function y$(t){let e=ip();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 xo)e[o]=g$(n[o]);return e}function w$(t){return xo.every(e=>sp(t[e]))}var we,xo,gn,So,tc=x(()=>{"use strict";we="auto",xo=["primary","context","tasks","docs","code_comments","chat","code_review","commits"],gn=["English","Russian","German","Spanish","French","Portuguese","Italian","Chinese","Japanese","Korean"],So=40});function ic(t=ap){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...ic(r.groups));return e}function cp(t,e){let r=JSON.stringify(e);return ic().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function sc(t){let e=cp(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.type==="string"&&e.mustContain&&!i.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:e.maxLength!==void 0&&i.length>e.maxLength?{ok:!1,error:`${e.id} must be \u2264 ${e.maxLength} chars`}:{ok:!0,field:e,value:i}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)?{ok:!1,error:`${e.id} must be a number`}:!e.float&&!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}case"string_map":{if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,error:`${e.id} must be a name\u2192value map`};let i=Object.entries(r);if(i.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(i.length>rc)return{ok:!1,error:`${e.id} must have \u2264 ${rc} entries`};let s={};for(let[a,c]of i){if(!rt.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${rt}`};if(Wt(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>nc)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${nc} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var b$,k$,rc,nc,oc,ap,lp=x(()=>{"use strict";ec();Va();Ba();tc();b$={primary:"Primary language",context:"Context documents",tasks:"Tracker issues",docs:"Repo documentation",code_comments:"Code comments",chat:"Agent chat",code_review:"Code review comments",commits:"Commits & branches"},k$={primary:"The project's main language (agent status notes ride it). Empty \u21D2 auto.",context:"Knowledge, ADRs and task artifacts in the Context Repo. Empty \u21D2 auto.",tasks:"Issue titles/bodies the agent drafts. Empty \u21D2 auto.",docs:"Documentation changes in the project repos. Empty \u21D2 auto.",code_comments:"New code comments the agent writes. Empty \u21D2 auto.",chat:"The interactive task-drafting chat. Empty/auto \u21D2 mirror the user's messages.",code_review:"Review findings and PR comments. Empty \u21D2 follows the tracker-issues language.",commits:"Commit/PR subject & branch slug. Empty \u21D2 follows the tracker-issues language."},rc=64,nc=2e3,oc=2e3,ap=[{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:[...qa],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:[...Si],help:"Overrides the recommended defaults for every role not listed below."},...Ei.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Si],help:`recommended: ${vo[t]} (the workflow preset may set a cheaper default \u2014 an explicit value here overrides both)`}))]},{id:"llm.effort",label:"Reasoning effort by role",help:"Reasoning effort per pipeline stage (Claude Code --effort). Empty \u21D2 the mechanical roles run lowered (build/estimate: low; draft/index/code-review-verify: medium) and every other role keeps the backend default.",fields:[{id:"llm.effort.default",file:"regimen.yaml",path:["llm","effort","default"],type:"enum",label:"default (catch-all)",nullable:!0,suggestions:[...Ri],help:"Overrides the recommended lowerings for every role not listed below."},...Ei.map(t=>({id:`llm.effort.${t}`,file:"regimen.yaml",path:["llm","effort",t],type:"enum",label:t,nullable:!0,suggestions:[...Ri],help:$o[t]?`recommended: ${$o[t]}`:"recommended: backend default"}))]}]},{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:oc,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:oc,help:`e.g. "implementation details, bullet list of what was done, in the tracker's language". Empty \u21D2 the default PR body.`}]},{id:"apply.delivery",label:"Delivery & merge",help:"How a finished change reaches the repository: with or without a pull request, and who merges it.",fields:[{id:"apply.pull_request",file:"project.yaml",path:["apply","pull_request"],type:"boolean",label:"Open a pull request",nullable:!1,help:"On (default): the task branch is pushed and a pull request is opened \u2014 the change is reviewable in the git host and keeps a history of review comments. Off: no PR at all; the branch is merged into the default branch directly, and the agent's review remarks live only in the dashboard and the Context Repo."},{id:"apply.done",file:"project.yaml",path:["apply","done"],type:"enum",label:"Task is done when",nullable:!1,suggestions:["merge","branch"],help:"merge (default): the task is finished only once its change lands in the default branch. branch: the task ends at the pushed branch (plus the PR, if enabled) and nothing is merged for you."},{id:"apply.auto_merge",file:"project.yaml",path:["apply","auto_merge"],type:"enum",label:"Auto-merge pull requests",nullable:!1,suggestions:["off","on_ci_green"],help:"Applies to the pull-request path only. off (default): the merge waits for you (Approve on the task card). on_ci_green: as soon as the PR is open, conflict-free and its CI is green, CodePipe merges it \u2014 changes reach the default branch with no further review from you. Requires full automation; branch protection on the host still applies (a refused merge parks the task). Without pull requests, full automation merges the branch itself and this switch does not apply."}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{id:"testing",label:"Testing",help:"An optional phase after code review: writes the test plan you run in the morning and reports what it could verify.",fields:[{id:"testing.enabled",file:"regimen.yaml",path:["testing","enabled"],type:"boolean",nullable:!1,label:"Run the testing phase",help:"Off by default. When on, a task passing code review goes through a test pass before the PR: it derives TESTPLAN.md from the plan's requirements and reports per requirement what it could verify. A requirement it finds broken sends the change back for a fix (bounded below)."},{id:"testing.max_iterations",file:"regimen.yaml",path:["testing","max_iterations"],type:"number",nullable:!0,min:1,max:10,label:"Fix rounds before stopping",help:"How many times a failed test pass may send the change back before the task waits for you. Empty \u21D2 2."}]},{id:"code_review",label:"Code review",help:"One review mechanism for the pipeline's own changes and for developers' branches (the review column); they differ only in where the findings go.",fields:[{id:"code_review.verify_pass",file:"regimen.yaml",path:["code_review","verify_pass"],type:"boolean",nullable:!1,label:"Verifier pass (precision)",help:"On by default. A second, narrow agent checks every finding against the code (real? re-grade) before it costs a rework round or reaches a developer; the findings threshold below keeps small rounds cheap."},{id:"code_review.verify_min_findings",file:"regimen.yaml",path:["code_review","verify_min_findings"],type:"number",nullable:!0,min:1,label:"Verifier threshold (findings)",help:"The verifier runs only when a round carries at least this many actionable findings \u2014 1-2 are cheap to absorb, noise scales with volume. Empty = 3; 1 = verify every round."},{id:"code_review.max_blocking",file:"regimen.yaml",path:["code_review","max_blocking"],type:"number",nullable:!0,label:"Blocking budget (internal)",help:"Max blocker findings that keep their power in the pipeline's own review; the rest are demoted to major, weakest confidence first. Empty = 5."},{id:"code_review.external.max_blocking",file:"regimen.yaml",path:["code_review","external","max_blocking"],type:"number",nullable:!0,label:"Blocking budget (external)",help:"The same budget for a developer's branch review \u2014 tighter by default because a human reads these. Empty = 3."}]},{id:"skills",label:"Skills",help:"Reusable procedures the agent can invoke instead of improvising. Only their names and one-line descriptions sit in the prompt; the steps load when a skill is used.",fields:[{id:"skills.from_bundled",file:"regimen.yaml",path:["skills","from_bundled"],type:"boolean",nullable:!1,label:"Use the skills shipped with CodePipe",help:"On by default. General procedures maintained with the product."},{id:"skills.from_context_repo",file:"regimen.yaml",path:["skills","from_context_repo"],type:"boolean",nullable:!1,label:"Use this project's skills",help:"On by default. Skills the team writes in the context repository under `skills/<name>/SKILL.md`. These override a bundled skill of the same name."},{id:"skills.from_project_repo",file:"regimen.yaml",path:["skills","from_project_repo"],type:"boolean",nullable:!1,label:"Use the code repository's skills",help:"On by default. `.claude/skills/` inside the project repositories \u2014 the skills your developers already use locally. These win over both other sources."}]},{id:"quality",label:"Quality block",help:"Skip the whole quality block (build + code review) when a change touches only safe paths.",fields:[{id:"quality.skip_paths",file:"regimen.yaml",path:["quality","skip_paths"],type:"string_list",nullable:!0,label:"Skip paths (gitignore-style)",help:"When every changed file across all repos matches these globs, build and code review are skipped and the change goes straight to apply. One file outside the list runs both as usual. Use ! to re-include (e.g. !schema/**/*.md). Empty = never skip."}]},{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), the observer's intake plan waits for your APPROVE & START before the batch runs. Off \u21D2 conveyor: the batch starts automatically on the observer's plan. Either way every task passes the observer intake first."},{id:"observer.debounce_seconds",file:"regimen.yaml",path:["observer","debounce_seconds"],type:"number",label:"Intake window (seconds)",nullable:!0,min:5,max:3600,help:"How long the queue collects newly staged tasks before the observer reviews them as one batch. Empty \u21D2 60."},{id:"observer.fast_path",file:"regimen.yaml",path:["observer","fast_path"],type:"boolean",label:"Fast path for trivial tasks",nullable:!1,help:"On by default. A single small task with no links skips the observer's LLM pass and is routed by rules (noted in its journal as routed without review)."}]},{id:"council",label:"Council",help:"Several roles examine the same subject in parallel, each in its own process; a final session weighs their written opinions. Costs several agent runs per use \u2014 off by default, enable per phase.",fields:[{id:"council.questions",file:"regimen.yaml",path:["council","questions"],type:"boolean",nullable:!1,label:"Council on blocking questions",help:"Off (default): an agent's blocking question is answered by a single session, which keeps full automation moving cheaply. On: the council's roles each write an independent opinion first, and the answering session weighs them."},{id:"council.code_review",file:"regimen.yaml",path:["council","code_review"],type:"boolean",nullable:!1,label:"Council on code review",help:"Off (default): one reviewer session judges the change alone. On: the project's critic roles each review the change in their own parallel process first, and the reviewer session weighs their written findings into the verdict. Applies to the internal and the external review; the verifier pass always runs solo."},{id:"council.max_parallel",file:"regimen.yaml",path:["council","max_parallel"],type:"number",nullable:!0,min:1,max:5,label:"Max parallel roles",help:"How many role processes run at once (the rest wait their turn). Empty \u21D2 3; hard ceiling 5."}]},{id:"workflow",label:"Workflow",help:"How much pipeline a task gets. A preset is a set of defaults \u2014 any explicit setting below always wins over it.",fields:[{id:"workflow.preset",file:"regimen.yaml",path:["workflow","preset"],type:"enum",nullable:!1,suggestions:["express","balanced","full"],label:"Preset",help:"express \u2014 no analysis phase, no review: one implementation session on the capable model (cheapest, for small clear tasks). balanced \u2014 every phase, cheaper models for implementation and review. full \u2014 the classic pipeline on the capable model."},{id:"analysis.enabled",file:"regimen.yaml",path:["analysis","enabled"],type:"boolean",nullable:!1,label:"Analysis phase",help:"Whether a task starts with a dedicated analysis pass (plan + open questions) before implementation. Off \u21D2 the implementer works straight from the task text and the context pack; an explicit value here overrides the preset."}]},{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:xo.map(t=>({id:`language.${t}`,file:"project.yaml",path:["language",t],type:"string",label:b$[t],nullable:!0,maxLength:40,suggestions:t==="chat"?[we,...gn]:[...gn],help:k$[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:"On by default. Agents are asked to record intent annotations and receive an assembled context pack built from the project map. Off \u21D2 the pipeline ignores the map entirely and behaves exactly as if the feature were absent."},{id:"context.model.pack.idf_penalty",file:"regimen.yaml",path:["context","model","pack","idf_penalty"],type:"boolean",label:"Demote ubiquitous files in the pack",nullable:!1,help:"On by default. Files that reached the pack only through STATISTICAL co-change (not direct task evidence) are ranked down in proportion to how many past tasks touched them, so the budget goes to task-specific paths. Off restores pure activation order."},{id:"context.model.prompt.pack",file:"regimen.yaml",path:["context","model","prompt","pack"],type:"boolean",nullable:!1,label:"Give agents the context pack",help:"On by default. The assembled pack costs up to ~4000 tokens on every task of the analyze / estimate / implement / rework roles. Turning it off keeps the map building and stops the spend \u2014 the way to see what the pack is actually worth on this project."},{id:"context.model.prompt.annotations",file:"regimen.yaml",path:["context","model","prompt","annotations"],type:"boolean",nullable:!1,label:"Ask agents for intent annotations",help:"On by default. Adds the annotations block to the implement and rework prompts \u2014 the layer that records WHY the code is shaped this way. Cheap, and worth accumulating even while the pack is off."},{id:"context.index.hub",file:"regimen.yaml",path:["context","index","hub"],type:"enum",label:"Search index on the server",nullable:!0,suggestions:["off","metadata"],help:"off (default): search runs on your machine, nothing is uploaded. metadata: paths, labels and task texts (never code) are mirrored to the server so search and structure stay available while your machine is offline. Switching back to off deletes the mirrored rows."},{id:"context.model.issue_key_pattern",file:"regimen.yaml",path:["context","model","issue_key_pattern"],type:"string",label:"Issue-key pattern (regex)",nullable:!0,maxLength:200,help:"Regex that finds tracker issue keys in commit subjects when mining task events from history. Empty \u21D2 derived from the tracker project key (e.g. DEV-\\d+)."},{id:"context.model.cochange.window_commits",file:"regimen.yaml",path:["context","model","cochange","window_commits"],type:"number",label:"History window (commits)",nullable:!0,min:50,max:5e4,help:`How many commits back from the build commit are mined. Default ${lt.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 ${lt.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 ${lt.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 ${lt.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 ${lt.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 ${lt.topK}.`}]},{id:"rate_limit",label:"Rate limit",help:"Automatic project pause as the LLM usage window fills up.",fields:[{id:"rate_limit.auto_pause.enabled",file:"project.yaml",path:["rate_limit","auto_pause","enabled"],type:"boolean",nullable:!1,label:"Pause the project near the limit",help:"On (default): when window utilization reaches the threshold, the project is paused (same pause as the manual one) and you get an email \u2014 the remaining window stays available for your own work. Off: agents keep working until the provider actually runs out."},{id:"rate_limit.auto_pause.threshold",file:"project.yaml",path:["rate_limit","auto_pause","threshold"],type:"number",float:!0,nullable:!0,min:.05,max:1,label:"Pause threshold (share of the window)",help:"Fraction of the usage window at which the pause fires; the rest (1 \u2212 threshold) is your manual-work reserve. Empty \u21D2 0.75."}]},{id:"context.job_logs",label:"Job transcripts",help:"Whether the raw agent transcript of each job is kept in the Context Repo.",fields:[{id:"context.job_logs.enabled",file:"regimen.yaml",path:["context","job_logs","enabled"],type:"boolean",label:"Keep transcripts in the Context Repo",nullable:!1,help:"Off (default): the transcript is discarded after the run \u2014 nothing lands in the Context Repo. On: each job's raw transcript is committed as tasks/<KEY>/logs/job-<id>.jsonl for post-mortem debugging."}]}]});var up=x(()=>{"use strict"});function dp(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 cc(t){let{name:e,body:r,origin:n}=t;if(!ac.test(e))return{ok:!1,error:`role name must match ${ac} (got "${e}")`};if(r.trim().length===0)return{ok:!1,error:"role body is empty \u2014 the body IS the role's prompt"};let o=t.frontmatter;if(o==null||typeof o!="object"||Array.isArray(o))return{ok:!1,error:"missing or malformed frontmatter block"};let i=o,s=i.description;if(typeof s!="string"||s.trim().length===0)return{ok:!1,error:"description is required (one line: what this role looks for)"};if(s.length>300)return{ok:!1,error:"description must be \u2264 300 characters"};let a=dp(i.refs);if(a===null)return{ok:!1,error:"refs must be a list of non-empty paths"};if(a.length>10)return{ok:!1,error:"refs must list at most 10 files \u2014 a role is a narrow view"};for(let f of a)if(f.startsWith("/")||f.includes(".."))return{ok:!1,error:`ref "${f}" must be a path inside the Context Repo`};let c=dp(i.scenarios);if(c===null)return{ok:!1,error:"scenarios must be a list"};let l=[];for(let f of c){if(!Ii.includes(f))return{ok:!1,error:`unknown scenario "${f}" \u2014 one of: ${Ii.join(", ")}`};l.includes(f)||l.push(f)}if(l.length===0)return{ok:!1,error:`scenarios must name at least one of: ${Ii.join(", ")}`};let u=i.model;if(u!==void 0&&(typeof u!="string"||u.trim().length===0))return{ok:!1,error:"model must be a non-empty string when set"};let p=i.provider;if(p!==void 0&&(typeof p!="string"||p.trim().length===0))return{ok:!1,error:"provider must be a non-empty string when set"};let d=i.enabled;return d!==void 0&&typeof d!="boolean"?{ok:!1,error:"enabled must be true or false"}:{ok:!0,role:{name:e,description:s.trim(),...typeof u=="string"?{model:u.trim()}:{},...typeof p=="string"?{provider:p.trim()}:{},refs:a,scenarios:l,enabled:d!==!1,body:r.trim(),origin:n}}}function lc(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 uc(t,e){return t.filter(r=>r.enabled&&r.scenarios.includes(e))}var Ii,ac,Kj,Hj,pp=x(()=>{"use strict";Ii=["plan_review","code_review","council"],ac=/^[a-z][a-z0-9-]{1,39}$/,Kj=10,Hj=300});function dc(t){return fp.includes(t)}function pc(t){return`prompts/${t}.md`}var fp,mp=x(()=>{"use strict";fp=["analysis","analyze","backfill","build","chat","code-review","code-review-external","code-review-fix","code-review-verify","config","council","draft","estimate","implement","implement-direct","index","observer","resolve-conflict","review-comment","rework","testing"]});function mc(t){if(!fc.test(t.name))return{ok:!1,error:`skill directory name must match ${fc}`};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 hc(t,e,r){let n=new Map;for(let o of[...t,...e,...r])n.set(o.name,o);return[...n.values()].sort((o,i)=>o.name<i.name?-1:o.name>i.name?1:0)}function gp(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(!v$.test(n))return{ok:!1,error:`"${t}": expected <owner>/<repo>[@<40-hex sha>]`};let i=hp.find(s=>s.repo.toLowerCase()===n.toLowerCase());return o&&!$$.test(o)?{ok:!1,error:`"${t}": pin to a full 40-character commit sha \u2014 a branch or tag can change under you`}:!i&&!o?{ok:!1,error:`"${t}": a third-party marketplace must be pinned to a commit (<owner>/<repo>@<sha>). Its skills run beside your code with the agent's token.`}:{ok:!0,source:{repo:n,sha:o,name:i?.name??n.replace("/","-").toLowerCase(),official:!!i}}}function x$(t){let e=[],r=[],n=new Set;for(let o of t){if(!o.trim())continue;let i=gp(o);if(!i.ok){r.push(i.error);continue}n.has(i.source.name)||(n.add(i.source.name),e.push(i.source))}return{sources:e,errors:r}}function E$(t,e){let r=new Set(e.map(i=>i.name)),n={},o=[];for(let i of t){let s=i.trim();if(s){if(!S$.test(s)||!r.has(s.slice(s.indexOf("@")+1))){o.push(s);continue}n[s]=!0}}return{enabled:n,unknown:o}}var fc,Yj,hp,v$,$$,S$,yp=x(()=>{"use strict";fc=/^[a-z][a-z0-9-]{1,39}$/,Yj=300;hp=[{repo:"anthropics/skills",name:"anthropic-agent-skills"},{repo:"anthropics/claude-plugins-official",name:"claude-plugins-official"}],v$=/^[A-Za-z0-9][\w.-]*\/[A-Za-z0-9][\w.-]*$/,$$=/^[0-9a-f]{40}$/;S$=/^[A-Za-z0-9][\w.-]*@[A-Za-z0-9][\w.-]*$/});function wp(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 R$(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=wp(n.order,e.length);if(o===null)return{ok:!1,error:"order must be a list of task keys"};for(let m of o)if(!r.has(m))return{ok:!1,error:`order names ${m}, which is not in this batch`};if(new Set(o).size!==o.length)return{ok:!1,error:"order repeats a task key"};let i=e.filter(m=>!o.includes(m));if(o.length>0&&i.length>0)return{ok:!1,error:`order omits ${i.join(", ")}`};let s=n.tasks,a=[];if(s!=null){if(!Array.isArray(s))return{ok:!1,error:"tasks must be a list"};for(let m of s){if(!m||typeof m!="object")return{ok:!1,error:"each task entry must be an object"};let g=m,b=typeof g.taskKey=="string"?g.taskKey.trim():"";if(!r.has(b))return{ok:!1,error:`tasks names ${b||"(empty)"}, which is not in this batch`};let w=wp(g.after,e.length);if(w===null)return{ok:!1,error:`${b}: after must be a list of task keys`};for(let y of w){if(!r.has(y))return{ok:!1,error:`${b}: after names ${y}, not in this batch`};if(y===b)return{ok:!1,error:`${b}: cannot come after itself`}}let v=typeof g.decisions=="string"?g.decisions.trim():"";a.push({taskKey:b,decisions:v.slice(0,4e3),after:w})}}let c=[],l=n.conflicts;if(Array.isArray(l))for(let m of l){if(!m||typeof m!="object")continue;let g=m,b=typeof g.taskKey=="string"?g.taskKey.trim():"",w=typeof g.adr=="string"?g.adr.trim():"",v=typeof g.detail=="string"?g.detail.trim():"";!r.has(b)||!v||c.push({taskKey:b,adr:w,detail:v.slice(0,4e3)})}let u=[],p=n.related;if(Array.isArray(p))for(let m of p){if(!m||typeof m!="object")continue;let g=m,b=typeof g.taskKey=="string"?g.taskKey.trim():"",w=typeof g.detail=="string"?g.detail.trim():"";!b||!w||u.push({taskKey:b,detail:w.slice(0,4e3)})}let d=typeof n.summary=="string"?n.summary.trim().slice(0,4e3):"",f=n.deferBehind===!0;return{ok:!0,plan:{order:o,tasks:a,conflicts:c,related:u,summary:d,deferBehind:f}}}var zj,Xj,bp=x(()=>{"use strict";zj=4e3,Xj=4e3});function T$(t,e){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:"council verdict must be a JSON object"};let r=t,n=r.unresolved===!0,o=typeof r.fork=="string"?r.fork.trim().slice(0,4e3):"";if(n)return o?{ok:!0,verdict:{answers:[],unresolved:!0,fork:o}}:{ok:!1,error:"an unresolved verdict must describe the fork"};let i=r.answers;if(!Array.isArray(i))return{ok:!1,error:"answers must be a list"};if(i.length!==e.length)return{ok:!1,error:`expected ${e.length} answer(s), got ${i.length}`};let s=[];for(let[a,c]of i.entries()){if(!c||typeof c!="object")return{ok:!1,error:`answer ${a+1} must be an object`};let l=c,u=typeof l.answer=="string"?l.answer.trim():"";if(!u)return{ok:!1,error:`answer ${a+1} is empty`};s.push({question:typeof l.question=="string"?l.question.trim():e[a],answer:u.slice(0,4e3),rationale:typeof l.rationale=="string"?l.rationale.trim().slice(0,4e3):""})}return{ok:!0,verdict:{answers:s,unresolved:!1,fork:""}}}var Zj,kp=x(()=>{"use strict";Zj=4e3});function P$(t){let e=t.replace(/^#+\s*/,"").trim();for(let r of I$)if(r.re.test(e))return{kind:r.kind,letter:r.letter};return null}function gc(t){let e=[],r=new Map,n="",o=null,i=null;for(let a of t.split(`
8
+ `)){let c=/^#{1,6}\s+(.*)$/.exec(a);if(c){n=c[1].trim(),o=P$(n),i=null;continue}let l=C$.exec(a);if(l&&o){let u=l[1];r.set(u,(r.get(u)??0)+1),i={id:u,kind:o.kind,text:l[2].trim(),section:n},e.push(i);continue}if(i&&a.trim()&&!/^#{1,6}\s/.test(a)&&!/^\s*[-*]\s/.test(a)){i.text=`${i.text}
9
+ ${a.trim()}`.trim();continue}a.trim()||(i=null)}let s=[...r.entries()].filter(([,a])=>a>1).map(([a])=>a);return{items:e,structured:e.length>=2&&s.length===0,duplicateIds:s}}function A$(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 _$(t,e){let r=new Map(t.items.map(s=>[s.id,s])),n=e.filter(s=>!s.approved),o=e.filter(s=>s.approved).map(s=>s.id);if(n.length===0)return"";let i=["Rejected plan items:",""];for(let s of n){let a=r.get(s.id),c=a?`${s.id} \u2014 ${a.text.split(`
10
10
  `)[0]}`:s.id;i.push(`- **${c}**`),s.remark?.trim()&&i.push(` ${s.remark.trim()}`)}return o.length>0&&i.push("",`Approved and settled: ${o.join(", ")}. Do not revisit these unless a`,"rejected item forces it \u2014 and say so explicitly if it does."),i.join(`
11
- `)}function yc(t){let e=new Set;for(let r of t.items)if(r.kind==="procedure")for(let n of r.text.matchAll(C$))e.add(n[1]);return[...e]}var S$,E$,C$,wp=x(()=>{"use strict";S$=[{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"}],E$=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*(.*)$/;C$=/`([a-z][a-z0-9-]{1,39})`/g});function _$(t){let e=[],r=null;for(let o of t.split(`
12
- `)){let i=A$.exec(o);if(i){r={id:i[1],status:i[2].toLowerCase(),text:i[3].trim()},e.push(r);continue}if(/^#{1,6}\s/.test(o)||/^\s*[-*]\s/.test(o)||!o.trim()){r=null;continue}r&&(r.text=`${r.text}
13
- ${o.trim()}`.trim())}let n={};for(let o of e)n[o.id]=o;return{items:e,byId:n}}function j$(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 P$,A$,bp=x(()=>{"use strict";P$=["done","deviated","partial","dropped"],A$=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*[—:-]?\s*(done|deviated|partial|dropped)\b\s*[—:-]?\s*(.*)$/i});var kp=x(()=>{"use strict"});var vp=x(()=>{"use strict"});var $p=x(()=>{"use strict"});function wc(t){return`codepipe-host-${t}`}function N$(t){let e=t.filter(r=>r!=="self-hosted");return`runs-on: [self-hosted${e.length?", "+e.join(", "):""}]`}var xp=x(()=>{"use strict"});function O$(t){let e=t.toLowerCase(),r="";for(let o of e)r+=Object.prototype.hasOwnProperty.call(Sp,o)?Sp[o]:o;return r.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,50).replace(/-+$/g,"")}function L$(t,e,r){let o=(t&&t.includes("<TASK_ID>")?t:Ep).replace(/<TASK_ID>/g,e.toLowerCase()).replace(/<SLUG>/g,r??"");return o=o.replace(/-{2,}/g,"-").replace(/\/{2,}/g,"/").replace(/-\//g,"/").replace(/\/-/g,"/").replace(/^[-/]+|[-/]+$/g,""),o}function M$(t,e){if(t)return`${t.replace(/\/+$/,"")}/issue/${encodeURIComponent(e)}`}function Qt(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 bc(t){if(!t||typeof t!="object")return null;let e=t,r=typeof e.owner=="string"?e.owner.trim():"",n=typeof e.repo=="string"?e.repo.trim():typeof e.repoName=="string"?e.repoName.trim():"",o=typeof e.host=="string"?e.host.trim():"";return!r||!n||o!=="github"&&o!=="gitlab"&&o!=="bitbucket"?null:{host:o,owner:r,repoName:n}}function kc(t){if(!t.mirror)return t;let{mirror:e,...r}=t;return{...r,host:e.host,owner:e.owner,repoName:e.repoName}}function At(t){return`${t}${Rp}`}var Ep,Qj,Sp,er,Rp,vc=x(()=>{"use strict";Ep="codepipe/<TASK_ID>",Qj=50,Sp={\u0430:"a",\u0431:"b",\u0432:"v",\u0433:"g",\u0434:"d",\u0435:"e",\u0451:"e",\u0436:"zh",\u0437:"z",\u0438:"i",\u0439:"y",\u043A:"k",\u043B:"l",\u043C:"m",\u043D:"n",\u043E:"o",\u043F:"p",\u0440:"r",\u0441:"s",\u0442:"t",\u0443:"u",\u0444:"f",\u0445:"h",\u0446:"c",\u0447:"ch",\u0448:"sh",\u0449:"sch",\u044A:"",\u044B:"y",\u044C:"",\u044D:"e",\u044E:"yu",\u044F:"ya"};er=/^[a-z][a-z0-9-]{1,30}$/,Rp="-codepipe-ctx"});function D$(t){return t==="simple"||t==="gitflow"||t==="release"}function $c(t){return t==="integration"||t==="stable"||t==="release_pattern"}function U$(t){let e=t.endsWith("/*")?t.slice(0,-2):t;return Qt(e)}function B$(t){let e=new Set(xc[t.flow].roles);for(let r of Object.keys(t.branchTypes??{}))$c(r)&&e.add(r);return e}function gn(t){if(t==null)return{config:null,errors:[]};let e=[];if(typeof t!="object"||Array.isArray(t))return{config:null,errors:["git: must be a mapping"]};let r=t,n=r.flow;if(!D$(n))return e.push(`git.flow must be one of simple | gitflow | release (got ${JSON.stringify(n)})`),{config:null,errors:e};let o=n,i={},s=r.branch_types??r.branchTypes;if(s!==void 0)if(typeof s!="object"||s===null||Array.isArray(s))e.push("git.branch_types must be a mapping of role \u2192 name/pattern");else for(let[d,f]of Object.entries(s)){if(!$c(d)){e.push(`git.branch_types: unknown role "${d}"`);continue}if(typeof f!="string"||!Tp(d,f)){e.push(`git.branch_types.${d}: invalid branch name/pattern ${JSON.stringify(f)}`);continue}i[d]=f}let a=new Set(xc[o].roles);for(let d of Object.keys(i))a.add(d);let c={},l=r.branches;if(l!==void 0)if(typeof l!="object"||l===null||Array.isArray(l))e.push("git.branches must be a mapping of role \u2192 branch name");else for(let[d,f]of Object.entries(l)){if(!$c(d)){e.push(`git.branches: unknown role "${d}"`);continue}if(!a.has(d)){e.push(`git.branches.${d}: role not part of flow "${o}"`);continue}if(typeof f!="string"||!Tp(d,f)){e.push(`git.branches.${d}: invalid branch name/pattern ${JSON.stringify(f)}`);continue}c[d]=f}let u,p=r.commit;if(p!==void 0)if(typeof p!="object"||p===null||Array.isArray(p))e.push("git.commit must be a mapping");else{let d=p.subject;d!==void 0&&typeof d!="string"?e.push("git.commit.subject must be a string"):typeof d=="string"?u={subject:d}:u={}}return e.length>0?{config:null,errors:e}:{config:{flow:o,branches:c,...Object.keys(i).length>0?{branchTypes:i}:{},...u?{commit:u}:{}},errors:[]}}function Tp(t,e){return t==="release_pattern"?U$(e):Qt(e)}function F$(t,e,r){let n=r??"main",o=e??t;if(!o)return{flow:"simple",integration:n};let i=B$(o),s=u=>o.branches[u]??o.branchTypes?.[u],a=s("integration")??n,c=i.has("stable")?s("stable"):void 0,l=i.has("release_pattern")?s("release_pattern"):void 0;return{flow:o.flow,integration:a,...c?{stable:c}:{},...l?{releasePattern:l}:{}}}function yn(t){return t.gitFlow?.integration??t.defaultBranch??"main"}function G$(t,e){return e??yn(t)}function Ip(t,e){if(e.endsWith("/*")){let r=e.slice(0,-1);return t.startsWith(r)&&t.length>r.length}return t===e}function Sc(t,e){return e.flow==="simple"?!1:!!(t===e.integration||e.stable&&t===e.stable||e.releasePattern&&Ip(t,e.releasePattern))}function So(t){let e=t.branches??[],r=e.some(s=>/^release\//.test(s)),n=e.includes("develop")||e.includes("dev"),o=r?"release":n?"gitflow":"simple",i={integration:K$(o,t)};if(o!=="simple"){let s=H$(t,i.integration??"");s&&(i.stable=s)}return o==="release"&&(i.release_pattern="release/*"),{flow:o,branches:i}}function K$(t,e){let r=e.branches??[];if(t!=="simple"){if(r.includes("develop"))return"develop";if(r.includes("dev"))return"dev"}return e.defaultBranch??r[0]??""}function H$(t,e){let r=t.branches??[],n=t.defaultBranch;if(n&&(n==="main"||n==="master")&&n!==e)return n;if(r.includes("main")&&e!=="main")return"main";if(r.includes("master")&&e!=="master")return"master"}function Ec(t,e){if(t.flow==="simple")return!1;if(t.flow!==e.flow)return!0;let r=t.branches,n=e.branches;return(r.integration??"")!==(n.integration??"")||(r.stable??"")!==(n.stable??"")||(r.release_pattern??"")!==(n.release_pattern??"")}var xc,Cp=x(()=>{"use strict";vc();xc={simple:{roles:["integration"]},gitflow:{roles:["integration","stable"]},release:{roles:["integration","stable","release_pattern"]}}});function W$(t,e,r=72){let n=(t||Pp).replace(/\{key\}/g,e.key).replace(/\{summary\}/g,e.summary).replace(/\s+/g," ").trim(),o=Number.isFinite(r)&&r>0?Math.floor(r):72;if(n.length<=o)return n;let i=n.slice(0,o),s=i.lastIndexOf(" ");return s>=Math.floor(o/2)?i.slice(0,s).trimEnd():i.trimEnd()}var Pp,n0,Ap=x(()=>{"use strict";Pp="{key}: {summary}",n0=72});function q$(t,e){return`${t}:${e}`}var _p=x(()=>{"use strict"});function jp(t){let e=(t??"").trim();return/^pr_closed_without_merge\b/.test(e)?"blocked":/^(merge_failed|close_failed)\b/.test(e)||/^chain_base_changed\b/.test(e)||/^write action apply_delivery failed: .*hit conflicts/.test(e)?"conflict":/^(build_failed|ci_failed)\b/.test(e)?"loop_exhausted":"error"}function Y$(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.to==="NEEDS_MANUAL")return r}return null}function V$(t,e){if(t==="AWAITING_ANSWER")return{kind:"question"};if(t==="NEEDS_MANUAL"){let n=Y$(e)?.reason,o={kind:jp(n)};return n&&(o.reason=n),o}}var Np=x(()=>{"use strict"});function jr(t){for(let e of Op){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var Op,Lp=x(()=>{"use strict";Op=[{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 Mp=x(()=>{"use strict"});function Dp(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 z$(t,e=Date.now()){return`${Dp((e-t)/1e3)} ago`}function X$(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 Up=x(()=>{"use strict"});var Bp=x(()=>{"use strict"});function Fp(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function Tc(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=Fp(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Nr.test(r))return r;let n=Fp(t);return Nr.test(n)?n:Ci}function Ic(t,e){let r=new Set([...e].map(n=>n.toUpperCase()));if(!r.has(t.toUpperCase()))return t;for(let n=1;n<1e4;n++){let o=String(n),i=t.slice(0,10-o.length)+o;if(!r.has(i.toUpperCase()))return i}return t}function bn(t){return`tasks/${t}/issue.yaml`}var Rc,Eo,Ci,Nr,Pi,J$,Ro,wn,Gp=x(()=>{"use strict";Rc=["bug","feature","epic"],Eo="feature",Ci="TASK",Nr=/^[A-Z][A-Z0-9]{1,9}$/;Pi={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},J$=Pi.backlog,Ro="tracker/config.yaml",wn="tracker/counter"});function To(t){let e=t.split(`
11
+ `)}function yc(t){let e=new Set;for(let r of t.items)if(r.kind==="procedure")for(let n of r.text.matchAll(j$))e.add(n[1]);return[...e]}var I$,C$,j$,vp=x(()=>{"use strict";I$=[{re:/^decisions?$/i,kind:"decision",letter:"D"},{re:/^changes?$/i,kind:"change",letter:"C"},{re:/^assumptions?$/i,kind:"assumption",letter:"A"},{re:/^out of scope$/i,kind:"out_of_scope",letter:"O"},{re:/^test strategy$/i,kind:"test",letter:"T"},{re:/^procedures?$/i,kind:"procedure",letter:"P"}],C$=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*(.*)$/;j$=/`([a-z][a-z0-9-]{1,39})`/g});function L$(t){let e=[],r=null;for(let o of t.split(`
12
+ `)){let i=O$.exec(o);if(i){r={id:i[1],status:i[2].toLowerCase(),text:i[3].trim()},e.push(r);continue}if(/^#{1,6}\s/.test(o)||/^\s*[-*]\s/.test(o)||!o.trim()){r=null;continue}r&&(r.text=`${r.text}
13
+ ${o.trim()}`.trim())}let n={};for(let o of e)n[o.id]=o;return{items:e,byId:n}}function M$(t,e){let r=new Set(t);return{unreported:t.filter(n=>!(n in e.byId)),unknown:e.items.filter(n=>!r.has(n.id)).map(n=>n.id),notDone:e.items.filter(n=>n.status!=="done")}}var N$,O$,$p=x(()=>{"use strict";N$=["done","deviated","partial","dropped"],O$=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*[—:-]?\s*(done|deviated|partial|dropped)\b\s*[—:-]?\s*(.*)$/i});var xp=x(()=>{"use strict"});var Sp=x(()=>{"use strict"});var Ep=x(()=>{"use strict"});function wc(t){return`codepipe-host-${t}`}function D$(t){let e=t.filter(r=>r!=="self-hosted");return`runs-on: [self-hosted${e.length?", "+e.join(", "):""}]`}var Rp=x(()=>{"use strict"});function U$(t){let e=t.toLowerCase(),r="";for(let o of e)r+=Object.prototype.hasOwnProperty.call(Tp,o)?Tp[o]:o;return r.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,50).replace(/-+$/g,"")}function B$(t,e,r){let o=(t&&t.includes("<TASK_ID>")?t:Ip).replace(/<TASK_ID>/g,e.toLowerCase()).replace(/<SLUG>/g,r??"");return o=o.replace(/-{2,}/g,"-").replace(/\/{2,}/g,"/").replace(/-\//g,"/").replace(/\/-/g,"/").replace(/^[-/]+|[-/]+$/g,""),o}function F$(t,e){if(t)return`${t.replace(/\/+$/,"")}/issue/${encodeURIComponent(e)}`}function er(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 bc(t){if(!t||typeof t!="object")return null;let e=t,r=typeof e.owner=="string"?e.owner.trim():"",n=typeof e.repo=="string"?e.repo.trim():typeof e.repoName=="string"?e.repoName.trim():"",o=typeof e.host=="string"?e.host.trim():"";return!r||!n||o!=="github"&&o!=="gitlab"&&o!=="bitbucket"?null:{host:o,owner:r,repoName:n}}function kc(t){if(!t.mirror)return t;let{mirror:e,...r}=t;return{...r,host:e.host,owner:e.owner,repoName:e.repoName}}function At(t){return`${t}${Cp}`}var Ip,n0,Tp,tr,Cp,vc=x(()=>{"use strict";Ip="codepipe/<TASK_ID>",n0=50,Tp={\u0430:"a",\u0431:"b",\u0432:"v",\u0433:"g",\u0434:"d",\u0435:"e",\u0451:"e",\u0436:"zh",\u0437:"z",\u0438:"i",\u0439:"y",\u043A:"k",\u043B:"l",\u043C:"m",\u043D:"n",\u043E:"o",\u043F:"p",\u0440:"r",\u0441:"s",\u0442:"t",\u0443:"u",\u0444:"f",\u0445:"h",\u0446:"c",\u0447:"ch",\u0448:"sh",\u0449:"sch",\u044A:"",\u044B:"y",\u044C:"",\u044D:"e",\u044E:"yu",\u044F:"ya"};tr=/^[a-z][a-z0-9-]{1,30}$/,Cp="-codepipe-ctx"});function G$(t){return t==="simple"||t==="gitflow"||t==="release"}function $c(t){return t==="integration"||t==="stable"||t==="release_pattern"}function K$(t){let e=t.endsWith("/*")?t.slice(0,-2):t;return er(e)}function H$(t){let e=new Set(xc[t.flow].roles);for(let r of Object.keys(t.branchTypes??{}))$c(r)&&e.add(r);return e}function yn(t){if(t==null)return{config:null,errors:[]};let e=[];if(typeof t!="object"||Array.isArray(t))return{config:null,errors:["git: must be a mapping"]};let r=t,n=r.flow;if(!G$(n))return e.push(`git.flow must be one of simple | gitflow | release (got ${JSON.stringify(n)})`),{config:null,errors:e};let o=n,i={},s=r.branch_types??r.branchTypes;if(s!==void 0)if(typeof s!="object"||s===null||Array.isArray(s))e.push("git.branch_types must be a mapping of role \u2192 name/pattern");else for(let[d,f]of Object.entries(s)){if(!$c(d)){e.push(`git.branch_types: unknown role "${d}"`);continue}if(typeof f!="string"||!Pp(d,f)){e.push(`git.branch_types.${d}: invalid branch name/pattern ${JSON.stringify(f)}`);continue}i[d]=f}let a=new Set(xc[o].roles);for(let d of Object.keys(i))a.add(d);let c={},l=r.branches;if(l!==void 0)if(typeof l!="object"||l===null||Array.isArray(l))e.push("git.branches must be a mapping of role \u2192 branch name");else for(let[d,f]of Object.entries(l)){if(!$c(d)){e.push(`git.branches: unknown role "${d}"`);continue}if(!a.has(d)){e.push(`git.branches.${d}: role not part of flow "${o}"`);continue}if(typeof f!="string"||!Pp(d,f)){e.push(`git.branches.${d}: invalid branch name/pattern ${JSON.stringify(f)}`);continue}c[d]=f}let u,p=r.commit;if(p!==void 0)if(typeof p!="object"||p===null||Array.isArray(p))e.push("git.commit must be a mapping");else{let d=p.subject;d!==void 0&&typeof d!="string"?e.push("git.commit.subject must be a string"):typeof d=="string"?u={subject:d}:u={}}return e.length>0?{config:null,errors:e}:{config:{flow:o,branches:c,...Object.keys(i).length>0?{branchTypes:i}:{},...u?{commit:u}:{}},errors:[]}}function Pp(t,e){return t==="release_pattern"?K$(e):er(e)}function W$(t,e,r){let n=r??"main",o=e??t;if(!o)return{flow:"simple",integration:n};let i=H$(o),s=u=>o.branches[u]??o.branchTypes?.[u],a=s("integration")??n,c=i.has("stable")?s("stable"):void 0,l=i.has("release_pattern")?s("release_pattern"):void 0;return{flow:o.flow,integration:a,...c?{stable:c}:{},...l?{releasePattern:l}:{}}}function wn(t){return t.gitFlow?.integration??t.defaultBranch??"main"}function q$(t,e){return e??wn(t)}function Ap(t,e){if(e.endsWith("/*")){let r=e.slice(0,-1);return t.startsWith(r)&&t.length>r.length}return t===e}function Sc(t,e){return e.flow==="simple"?!1:!!(t===e.integration||e.stable&&t===e.stable||e.releasePattern&&Ap(t,e.releasePattern))}function Eo(t){let e=t.branches??[],r=e.some(s=>/^release\//.test(s)),n=e.includes("develop")||e.includes("dev"),o=r?"release":n?"gitflow":"simple",i={integration:Y$(o,t)};if(o!=="simple"){let s=V$(t,i.integration??"");s&&(i.stable=s)}return o==="release"&&(i.release_pattern="release/*"),{flow:o,branches:i}}function Y$(t,e){let r=e.branches??[];if(t!=="simple"){if(r.includes("develop"))return"develop";if(r.includes("dev"))return"dev"}return e.defaultBranch??r[0]??""}function V$(t,e){let r=t.branches??[],n=t.defaultBranch;if(n&&(n==="main"||n==="master")&&n!==e)return n;if(r.includes("main")&&e!=="main")return"main";if(r.includes("master")&&e!=="master")return"master"}function Ec(t,e){if(t.flow==="simple")return!1;if(t.flow!==e.flow)return!0;let r=t.branches,n=e.branches;return(r.integration??"")!==(n.integration??"")||(r.stable??"")!==(n.stable??"")||(r.release_pattern??"")!==(n.release_pattern??"")}var xc,_p=x(()=>{"use strict";vc();xc={simple:{roles:["integration"]},gitflow:{roles:["integration","stable"]},release:{roles:["integration","stable","release_pattern"]}}});function z$(t,e,r=72){let n=(t||jp).replace(/\{key\}/g,e.key).replace(/\{summary\}/g,e.summary).replace(/\s+/g," ").trim(),o=Number.isFinite(r)&&r>0?Math.floor(r):72;if(n.length<=o)return n;let i=n.slice(0,o),s=i.lastIndexOf(" ");return s>=Math.floor(o/2)?i.slice(0,s).trimEnd():i.trimEnd()}var jp,a0,Np=x(()=>{"use strict";jp="{key}: {summary}",a0=72});function X$(t,e){return`${t}:${e}`}var Op=x(()=>{"use strict"});function Lp(t){let e=(t??"").trim();return/^pr_closed_without_merge\b/.test(e)?"blocked":/^(merge_failed|close_failed)\b/.test(e)||/^chain_base_changed\b/.test(e)||/^write action apply_delivery failed: .*hit conflicts/.test(e)?"conflict":/^(build_failed|ci_failed)\b/.test(e)?"loop_exhausted":"error"}function J$(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.to==="NEEDS_MANUAL")return r}return null}function Z$(t,e){if(t==="AWAITING_ANSWER")return{kind:"question"};if(t==="NEEDS_MANUAL"){let n=J$(e)?.reason,o={kind:Lp(n)};return n&&(o.reason=n),o}}var Mp=x(()=>{"use strict"});function Nr(t){for(let e of Dp){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var Dp,Up=x(()=>{"use strict";Dp=[{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 Bp=x(()=>{"use strict"});function Fp(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 Q$(t,e=Date.now()){return`${Fp((e-t)/1e3)} ago`}function ex(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 Gp=x(()=>{"use strict"});var Kp=x(()=>{"use strict"});function Hp(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function Tc(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=Hp(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Or.test(r))return r;let n=Hp(t);return Or.test(n)?n:Ci}function Ic(t,e){let r=new Set([...e].map(n=>n.toUpperCase()));if(!r.has(t.toUpperCase()))return t;for(let n=1;n<1e4;n++){let o=String(n),i=t.slice(0,10-o.length)+o;if(!r.has(i.toUpperCase()))return i}return t}function kn(t){return`tasks/${t}/issue.yaml`}var Rc,Ro,Ci,Or,Pi,tx,To,bn,Wp=x(()=>{"use strict";Rc=["bug","feature","epic"],Ro="feature",Ci="TASK",Or=/^[A-Z][A-Z0-9]{1,9}$/;Pi={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},tx=Pi.backlog,To="tracker/config.yaml",bn="tracker/counter"});function Io(t){let e=t.split(`
14
14
  `),r=e.indexOf("---");if(r<0)return;let n=e.slice(r+1),o=n.lastIndexOf("## Attachments");o>=0&&n.slice(o+1).every(c=>c.trim()===""||/^- \[[^\]]*\]\(attachments\/[^)]*\)$/.test(c.trim()))&&(n=n.slice(0,o));let i=n.join(`
15
- `).trim();if(!(!i||i==="_(no description)_"))return i}function Z$(t){return`{{ancestorExcerpt:${t}}}`}var Ai,Kp=x(()=>{"use strict";Ai=/\{\{ancestorExcerpt:([^}]+)\}\}/g});var Q$,Hp=x(()=>{"use strict";Q$="youtrack"});function Or(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 Io(t){switch(t){case kn.gitlab:return"oauth2";case kn.bitbucket:return"x-token-auth";default:return"x-access-token"}}var kn,Wt,Wp=x(()=>{"use strict";kn={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Wt="x-bitbucket-api-token-auth"});var qp=x(()=>{"use strict"});var Yp=x(()=>{"use strict";Hp();Wp();qp()});var Pc={};Ne(Pc,{ACTION_ID_RE:()=>za,ACTION_STEP_DEFAULT_TIMEOUT_SEC:()=>Ja,ALL_JOB_ROLES:()=>Ka,ALL_MODEL_ROLE_KEYS:()=>Ei,ANALYSIS_MAX_DRAFTS:()=>Cc,ANCESTOR_EXCERPT_RE:()=>Ai,ANCESTOR_EXCERPT_TOKEN:()=>Z$,ANNOTATION_MAX_PER_TASK:()=>Oa,BACKFILL_MAX_DRAFTS:()=>ex,BITBUCKET_API_TOKEN_GIT_USER:()=>Wt,BRANCH_SLUG_MAX_LENGTH:()=>Qj,BUILD_DISCOVERY:()=>Yd,COCHANGE_DEFAULTS:()=>lt,CODEPIPE_COMMANDS:()=>Op,CODE_REVIEW_VERIFY:()=>Vd,COMMIT_STYLE_MAX_LENGTH:()=>oc,CONTEXT_PACK_DECAY:()=>Ma,CONTEXT_PACK_DEFAULTS:()=>Pr,CONTEXT_REPO_SUFFIX:()=>Rp,CONTEXT_STAMP_FILE:()=>vt,CONTEXT_TEMPLATE_CHANGELOG:()=>xa,CONTEXT_TEMPLATE_VERSION:()=>Cd,COUNCIL_MAX_ANSWER:()=>Vj,DEFAULT_BRANCH_PATTERN:()=>Ep,DEFAULT_COMMIT_SUBJECT:()=>Pp,DEFAULT_HUB_URL:()=>bt,DEFAULT_INTERNAL_ISSUE_TYPE:()=>Eo,DEFAULT_INTERNAL_TRACKER_PREFIX:()=>Ci,DEFAULT_LLM_PROVIDER:()=>tt,DEFAULT_REGIMEN_ALIASES:()=>Zd,DEFAULT_SUBJECT_MAX:()=>n0,DEFAULT_TRACKER_PROVIDER:()=>Q$,EFFORT_LEVELS:()=>Qd,EFFORT_LEVEL_SUGGESTIONS:()=>Ri,ENV_NAME_RE:()=>rt,FALLBACK_MODEL:()=>Xd,GIT_FLOW_PRESETS:()=>xc,GIT_HOST_DOMAINS:()=>kn,INTERACTIVE_ROLES:()=>Wd,INTERNAL_ISSUE_TYPES:()=>Rc,INTERNAL_TRACKER_CONFIG_PATH:()=>Ro,INTERNAL_TRACKER_COUNTER_PATH:()=>wn,INTERNAL_TRACKER_DEFAULT_STATUS:()=>J$,INTERNAL_TRACKER_PREFIX_RE:()=>Nr,INTERNAL_TRACKER_STATUSES:()=>Pi,LANE_PHASES:()=>zv,LANE_SEGMENTS:()=>Ga,LANGUAGE_AUTO:()=>we,LANGUAGE_SUGGESTIONS:()=>hn,LANGUAGE_VALUE_MAX_LENGTH:()=>xo,LEGACY_CONTEXT_STAMP_FILE:()=>ln,LLM_PROVIDER_SUGGESTIONS:()=>qa,MIN_SUPPORTED_PROTOCOL:()=>Rd,MODEL_ALIAS_SUGGESTIONS:()=>Si,MODEL_DERIVED_DIR:()=>Gv,MODEL_DERIVED_INDEX_PATH:()=>bi,MODEL_DIR:()=>Uv,MODEL_EDGE_KINDS:()=>ja,MODEL_ENTITY_ID_RE:()=>jd,MODEL_FACTS_DIR:()=>Fv,MODEL_FAMILY_PREFERENCE:()=>Jd,MODEL_HAIKU:()=>xi,MODEL_LEVELS:()=>_d,MODEL_OPUS:()=>Ie,MODEL_README_PATH:()=>Bv,MODEL_RELATES_PATH:()=>Tr,MODEL_SEARCH_MAX_LIMIT:()=>La,MODEL_SEARCH_MAX_ROWS:()=>Hv,MODEL_SEARCH_ROW_TEXT_MAX:()=>vi,MODEL_SONNET:()=>mn,MODEL_SUB_ROLES:()=>zd,OBSERVER_MAX_DECISION:()=>Wj,OBSERVER_MAX_SUMMARY:()=>qj,OFFICIAL_MARKETPLACES:()=>pp,PHASES:()=>Fa,PIPELINE_COLUMNS:()=>Gd,PLANNING_LANE_MAX_JOBS:()=>Qv,PLANNING_ROLES:()=>Hd,PLATFORM_VERSION:()=>et,PROJECT_ID_RE:()=>er,PROJECT_LANGUAGE_SECTIONS:()=>$o,PROJECT_MODEL_FORMAT_VERSION:()=>Fe,PROJECT_SETTINGS_MANIFEST:()=>op,PROMPT_ROLES:()=>up,PROTOCOL_VERSION:()=>kt,RECOMMENDED_ROLE_EFFORT:()=>vo,RECOMMENDED_ROLE_MODELS:()=>ko,RELATES_MIN_OVERLAP:()=>Na,ROLE_MAX_DESCRIPTION:()=>Bj,ROLE_MAX_REFS:()=>Uj,ROLE_NAME_RE:()=>ac,ROLE_SCENARIOS:()=>Ii,SKILL_MAX_DESCRIPTION:()=>Kj,SKILL_NAME_RE:()=>fc,SOLUTION_STATUSES:()=>P$,STRING_MAP_MAX_ENTRIES:()=>rc,STRING_MAP_MAX_VALUE_LENGTH:()=>nc,additionsSince:()=>Ea,ago:()=>z$,attentionFor:()=>V$,autoLanguageConfig:()=>rp,autoModelDefault:()=>Ya,branchMatchesFlow:()=>Sc,canonicalizeModelEdgeSheet:()=>Nd,canonicalizeModelIdentityTable:()=>Ld,canonicalizeModelShard:()=>Od,canonicalizeModelTaskEvent:()=>Md,changesSince:()=>Ra,classifyAttentionReason:()=>jp,compilePlanRework:()=>I$,contextRepoName:()=>At,deserializeEffortConfig:()=>s$,deserializeModelConfig:()=>c$,detectGitFlowPreset:()=>So,effectiveClusterBase:()=>G$,emptyEffortConfig:()=>fn,emptyModelConfig:()=>pn,enabledPluginsSetting:()=>v$,extractLanguageConfig:()=>f$,extractTaskMdBody:()=>To,findSettingField:()=>ip,firstFreeInternalTrackerPrefix:()=>Ic,flattenSettingFields:()=>ic,fmtDuration:()=>Dp,fmtUptime:()=>X$,ghRunnerHostLabel:()=>wc,ghRunnerRunsOnSnippet:()=>N$,gitCloneUrlDomain:()=>Or,gitFlowDiverges:()=>Ec,httpsTokenUser:()=>Io,internalIssueYamlPath:()=>bn,isAllAutoLanguage:()=>m$,isAutoLanguage:()=>np,isBodyEditFrozen:()=>Vv,isInteractiveRole:()=>Ha,isModelEntityId:()=>ki,isPromptRole:()=>dc,isProtocolCompatible:()=>mo,isReservedEnvName:()=>Ht,isTerminalPhase:()=>Yv,isValidBranchName:()=>Qt,jobLane:()=>Zv,laneSegmentForPhase:()=>Xv,makeTaskId:()=>q$,matchesReleasePattern:()=>Ip,mergeRoles:()=>lc,mergeSkills:()=>hc,mismatchedIds:()=>T$,modelAnnotationPath:()=>Ca,modelComponentSlug:()=>Ad,modelCorrelatesPath:()=>Pa,modelEventPath:()=>Ir,modelIdentityPath:()=>yo,modelNodeKey:()=>ye,modelShardNeedsRebuild:()=>Wv,modelStructureShardPath:()=>_a,modelTaskNodeKey:()=>Ee,modelTouchedPath:()=>Aa,parseActionDefinition:()=>Za,parseCodepipeCommand:()=>jr,parseContextStamp:()=>Sa,parseEffortConfig:()=>o$,parseGitConfig:()=>gn,parseMarketplaceSource:()=>fp,parseMarketplaces:()=>b$,parseModelConfig:()=>r$,parseModelNodeKey:()=>ne,parsePlanItems:()=>gc,parseRepoMirror:()=>bc,parseSolutionItems:()=>_$,pipelineColumnForPhase:()=>Jv,pipelineRepoSpec:()=>kc,prescribedSkills:()=>yc,promptOverridePath:()=>pc,renderCommitSubject:()=>W$,renderContextStamp:()=>ho,repoBaseBranch:()=>yn,resolveBranchName:()=>L$,resolveEffortForRole:()=>n$,resolveModelForRole:()=>e$,resolveProvider:()=>t$,resolveRepoFlow:()=>F$,rolesForScenario:()=>uc,serializeEffortConfig:()=>i$,serializeModelConfig:()=>a$,serializeModelEdgeSheet:()=>Cr,serializeModelIdentityTable:()=>Ua,serializeModelShard:()=>Da,serializeModelTaskEvent:()=>dn,serializeModelYaml:()=>Ar,slugify:()=>O$,solutionCoverage:()=>j$,suggestInternalTrackerPrefix:()=>Tc,validateActionInput:()=>Qa,validateCouncilVerdict:()=>x$,validateModelEdgeSheet:()=>wo,validateModelIdentityTable:()=>bo,validateModelShard:()=>Gt,validateModelTaskEvent:()=>Kt,validateObserverPlan:()=>$$,validateRoleDefinition:()=>cc,validateSettingEdit:()=>sc,validateSkill:()=>mc,youtrackIssueUrl:()=>M$,zeroUsage:()=>ut});var Cc,ex,M=x(()=>{"use strict";Td();Id();Pd();Ba();Fd();Kd();Wa();Va();sp();ap();tc();ec();lp();dp();mp();gp();yp();wp();bp();kp();vp();$p();xp();vc();Cp();Ap();_p();Np();Lp();Mp();Up();Bp();Gp();Kp();Yp();Cc=20,ex=15});function ee(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Ye=x(()=>{"use strict"});import{existsSync as tx,readFileSync as rx,readdirSync as nx}from"node:fs";import{dirname as ox,join as Ac}from"node:path";import{parse as ix}from"yaml";function sx(t=process.cwd()){let e=t;for(;;){if(tx(Ac(e,nt,"project.yaml")))return e;let r=ox(e);if(r===e)return null;e=r}}function ax(t){return Ac(t,nt)}function je(t=process.cwd()){let e=sx(t);if(!e)return null;let r=ax(e),n=cx(rx(Ac(r,"project.yaml"),"utf-8"));for(let o of n.gitConfigErrors??[])console.warn(`project.yaml: invalid git config \u2014 ${o}`);return{root:e,contextDir:r,spec:n}}function Vp(t,e,r){return nx(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 vn(t,e=process.cwd()){try{let r=je(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function cx(t){let e=ix(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),n=String(e.name??r),o=Array.isArray(e.repos)?e.repos:[],i=[],s=[];s.push(...gn(e.git).errors.map(a=>`git: ${a}`));for(let a of o){if(!a||typeof a!="object")continue;let c=a,l=String(c.repo??c.repoName??""),u=String(c.name??l);if(!u||!l)continue;let p=c.host,d=p==="bitbucket"?"bitbucket":p==="gitlab"?"gitlab":"github",f=bc(c.mirror);c.git!==void 0&&c.git!==null&&s.push(...gn(c.git).errors.map(m=>`repos[${u}].git: ${m}`)),i.push({name:u,host:d,owner:String(c.owner??""),repoName:l,defaultBranch:String(c.default_branch??c.defaultBranch??"main"),mountAs:String(c.mount_as??c.mountAs??u),...f?{mirror:f}:{}})}return{projectId:r,name:n,repos:i,...s.length>0?{gitConfigErrors:s}:{}}}function zp(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 nt,xt=x(()=>{"use strict";M();nt=".codepipe"});import{homedir as Xp}from"node:os";import{mkdirSync as lx,readFileSync as ux,writeFileSync as dx,existsSync as _c}from"node:fs";import{dirname as Zp,join as _i,resolve as px}from"node:path";import{fileURLToPath as fx}from"node:url";function Qp(t){let e=_i(Jp,".env");if(_c(e)&&process.loadEnvFile(e),t){let r=_i(Jp,"profiles",t,".env");_c(r)&&process.loadEnvFile(r)}}function $n(t){let e=ee("CONFIG");return e||(t?_i(Xp(),".codepipe","profiles",t,"config.json"):_i(Xp(),".codepipe","config.json"))}function St(t){let e=$n(t);if(!_c(e))return null;let r=ux(e,"utf-8");return JSON.parse(r)}function qt(t,e){let r=$n(e);lx(Zp(r),{recursive:!0}),dx(r,JSON.stringify(t,null,2)+`
16
- `,{mode:384})}function xn(t){if(t)return{cfg:dt(t),profile:t};let e;try{e=je()?.spec.projectId||void 0}catch{}if(e){let r=St(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:dt(void 0),profile:void 0}}function dt(t){let e=St(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 ${$n(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var Jp,Ve=x(()=>{"use strict";Ye();xt();Jp=px(Zp(fx(import.meta.url)),"..")});import{homedir as ef}from"node:os";import{existsSync as tf,mkdirSync as rf,readFileSync as nf,writeFileSync as of}from"node:fs";import{dirname as sf,join as af}from"node:path";function cf(t,e,r){let n=X(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},ce(n)}function lf(t,e){let r=X(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],ce(r),!0)}function uf(t){return Object.keys(X(t)?.secrets??{}).sort()}function ji(t,e,r){let n=X(t);if(!n)return"mismatch";let o=n.sandboxPins??{},i=o[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(o[e]=r,n.sandboxPins=o,ce(n),"pinned")}function df(t,e){let r=X(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],ce(r),!0):!1}function _t(t){return af(ef(),".codepipe","secrets",`${t}.json`)}function X(t){let e=_t(t);return tf(e)?JSON.parse(nf(e,"utf-8")):null}function ce(t){let e=_t(t.projectId);rf(sf(e),{recursive:!0}),of(e,JSON.stringify(t,null,2)+`
17
- `,{mode:384})}function Ni(){return af(ef(),".codepipe","shared.json")}function jc(){let t=Ni();return tf(t)?JSON.parse(nf(t,"utf-8")):null}function pf(t){let e=Ni();rf(sf(e),{recursive:!0}),of(e,JSON.stringify(t,null,2)+`
18
- `,{mode:384})}function Sn(t){let e=X(t)?.claude?.oauthToken;return e||jc()?.claude?.oauthToken}function Co(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 Nc){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 Nc,me=x(()=>{"use strict";Nc=["GH_TOKEN","BITBUCKET_EMAIL","BITBUCKET_API_TOKEN","GITLAB_TOKEN","YOUTRACK_URL","YOUTRACK_TOKEN"]});import{appendFileSync as mx,existsSync as mf,mkdirSync as hx,renameSync as hf,statSync as gx,unlinkSync as yx}from"node:fs";import{Writable as wx}from"node:stream";import{join as bx}from"node:path";function Oi(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=kx(process.env[`${t}_MAX_BYTES`]??String(gf.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):gf.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function kx(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 Li(t){let e={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},r=(n,o)=>(...i)=>{n(...i);try{t.writeLine(vx(o,i))}catch{}};return console.log=r(e.log,"INFO"),console.warn=r(e.warn,"WARN"),console.error=r(e.error,"ERROR"),()=>{console.log=e.log,console.warn=e.warn,console.error=e.error}}function vx(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:$x(o)).join(" ");return`${r} ${t} ${n}`}function $x(t){try{return JSON.stringify(t)}catch{return String(t)}}var gf,Rn,Oc=x(()=>{"use strict";gf={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},Rn=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&hx(e.dir,{recursive:!0}),this.currentPath=bx(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
15
+ `).trim();if(!(!i||i==="_(no description)_"))return i}function rx(t){return`{{ancestorExcerpt:${t}}}`}var Ai,qp=x(()=>{"use strict";Ai=/\{\{ancestorExcerpt:([^}]+)\}\}/g});var nx,Yp=x(()=>{"use strict";nx="youtrack"});function Lr(t){let e=t.match(/^git@([^:/]+):/);if(e)return e[1]??null;let r=t.match(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)/);if(r)return r[1]??null;let n=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return n?n[1]??null:null}function Co(t){switch(t){case vn.gitlab:return"oauth2";case vn.bitbucket:return"x-token-auth";default:return"x-access-token"}}var vn,qt,Vp=x(()=>{"use strict";vn={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};qt="x-bitbucket-api-token-auth"});var zp=x(()=>{"use strict"});var Xp=x(()=>{"use strict";Yp();Vp();zp()});var Pc={};Ne(Pc,{ACTION_ID_RE:()=>za,ACTION_STEP_DEFAULT_TIMEOUT_SEC:()=>Ja,ALL_JOB_ROLES:()=>Ka,ALL_MODEL_ROLE_KEYS:()=>Ei,ANALYSIS_MAX_DRAFTS:()=>Cc,ANCESTOR_EXCERPT_RE:()=>Ai,ANCESTOR_EXCERPT_TOKEN:()=>rx,ANNOTATION_MAX_PER_TASK:()=>Oa,BACKFILL_MAX_DRAFTS:()=>ox,BITBUCKET_API_TOKEN_GIT_USER:()=>qt,BRANCH_SLUG_MAX_LENGTH:()=>n0,BUILD_DISCOVERY:()=>Yd,COCHANGE_DEFAULTS:()=>lt,CODEPIPE_COMMANDS:()=>Dp,CODE_REVIEW_VERIFY:()=>Vd,COMMIT_STYLE_MAX_LENGTH:()=>oc,CONTEXT_PACK_DECAY:()=>Ma,CONTEXT_PACK_DEFAULTS:()=>Ar,CONTEXT_REPO_SUFFIX:()=>Cp,CONTEXT_STAMP_FILE:()=>vt,CONTEXT_TEMPLATE_CHANGELOG:()=>xa,CONTEXT_TEMPLATE_VERSION:()=>Cd,COUNCIL_MAX_ANSWER:()=>Zj,DEFAULT_BRANCH_PATTERN:()=>Ip,DEFAULT_COMMIT_SUBJECT:()=>jp,DEFAULT_HUB_URL:()=>bt,DEFAULT_INTERNAL_ISSUE_TYPE:()=>Ro,DEFAULT_INTERNAL_TRACKER_PREFIX:()=>Ci,DEFAULT_LLM_PROVIDER:()=>tt,DEFAULT_REGIMEN_ALIASES:()=>tp,DEFAULT_SUBJECT_MAX:()=>a0,DEFAULT_TRACKER_PROVIDER:()=>nx,DEFAULT_WORKFLOW_PRESET:()=>Zd,EFFORT_LEVELS:()=>rp,EFFORT_LEVEL_SUGGESTIONS:()=>Ri,ENV_NAME_RE:()=>rt,FALLBACK_MODEL:()=>Xd,GIT_FLOW_PRESETS:()=>xc,GIT_HOST_DOMAINS:()=>vn,INTERACTIVE_ROLES:()=>Wd,INTERNAL_ISSUE_TYPES:()=>Rc,INTERNAL_TRACKER_CONFIG_PATH:()=>To,INTERNAL_TRACKER_COUNTER_PATH:()=>bn,INTERNAL_TRACKER_DEFAULT_STATUS:()=>tx,INTERNAL_TRACKER_PREFIX_RE:()=>Or,INTERNAL_TRACKER_STATUSES:()=>Pi,LANE_PHASES:()=>Zv,LANE_SEGMENTS:()=>Ga,LANGUAGE_AUTO:()=>we,LANGUAGE_SUGGESTIONS:()=>gn,LANGUAGE_VALUE_MAX_LENGTH:()=>So,LEGACY_CONTEXT_STAMP_FILE:()=>un,LLM_PROVIDER_SUGGESTIONS:()=>qa,MIN_SUPPORTED_PROTOCOL:()=>Rd,MODEL_ALIAS_SUGGESTIONS:()=>Si,MODEL_DERIVED_DIR:()=>Wv,MODEL_DERIVED_INDEX_PATH:()=>ki,MODEL_DIR:()=>Gv,MODEL_EDGE_KINDS:()=>ja,MODEL_ENTITY_ID_RE:()=>jd,MODEL_FACTS_DIR:()=>Hv,MODEL_FAMILY_PREFERENCE:()=>ep,MODEL_HAIKU:()=>hn,MODEL_LEVELS:()=>_d,MODEL_OPUS:()=>Ie,MODEL_README_PATH:()=>Kv,MODEL_RELATES_PATH:()=>Ir,MODEL_SEARCH_MAX_LIMIT:()=>La,MODEL_SEARCH_MAX_ROWS:()=>Yv,MODEL_SEARCH_ROW_TEXT_MAX:()=>$i,MODEL_SONNET:()=>Ht,MODEL_SUB_ROLES:()=>zd,OBSERVER_MAX_DECISION:()=>zj,OBSERVER_MAX_SUMMARY:()=>Xj,OFFICIAL_MARKETPLACES:()=>hp,PHASES:()=>Fa,PIPELINE_COLUMNS:()=>Gd,PLANNING_LANE_MAX_JOBS:()=>r$,PLANNING_ROLES:()=>Hd,PLATFORM_VERSION:()=>et,PRESET_ROLE_MODELS:()=>Qd,PROJECT_ID_RE:()=>tr,PROJECT_LANGUAGE_SECTIONS:()=>xo,PROJECT_MODEL_FORMAT_VERSION:()=>Fe,PROJECT_SETTINGS_MANIFEST:()=>ap,PROMPT_ROLES:()=>fp,PROTOCOL_VERSION:()=>kt,RECOMMENDED_ROLE_EFFORT:()=>$o,RECOMMENDED_ROLE_MODELS:()=>vo,RELATES_MIN_OVERLAP:()=>Na,ROLE_MAX_DESCRIPTION:()=>Hj,ROLE_MAX_REFS:()=>Kj,ROLE_NAME_RE:()=>ac,ROLE_SCENARIOS:()=>Ii,SKILL_MAX_DESCRIPTION:()=>Yj,SKILL_NAME_RE:()=>fc,SOLUTION_STATUSES:()=>N$,STRING_MAP_MAX_ENTRIES:()=>rc,STRING_MAP_MAX_VALUE_LENGTH:()=>nc,WORKFLOW_PRESETS:()=>Jd,additionsSince:()=>Ea,ago:()=>Q$,attentionFor:()=>Z$,autoLanguageConfig:()=>ip,autoModelDefault:()=>Ya,branchMatchesFlow:()=>Sc,canonicalizeModelEdgeSheet:()=>Nd,canonicalizeModelIdentityTable:()=>Ld,canonicalizeModelShard:()=>Od,canonicalizeModelTaskEvent:()=>Md,changesSince:()=>Ra,classifyAttentionReason:()=>Lp,compilePlanRework:()=>_$,contextRepoName:()=>At,deserializeEffortConfig:()=>u$,deserializeModelConfig:()=>p$,detectGitFlowPreset:()=>Eo,effectiveClusterBase:()=>q$,emptyEffortConfig:()=>mn,emptyModelConfig:()=>fn,enabledPluginsSetting:()=>E$,extractLanguageConfig:()=>y$,extractTaskMdBody:()=>Io,findSettingField:()=>cp,firstFreeInternalTrackerPrefix:()=>Ic,flattenSettingFields:()=>ic,fmtDuration:()=>Fp,fmtUptime:()=>ex,ghRunnerHostLabel:()=>wc,ghRunnerRunsOnSnippet:()=>D$,gitCloneUrlDomain:()=>Lr,gitFlowDiverges:()=>Ec,httpsTokenUser:()=>Co,internalIssueYamlPath:()=>kn,isAllAutoLanguage:()=>w$,isAutoLanguage:()=>sp,isBodyEditFrozen:()=>Jv,isInteractiveRole:()=>Ha,isModelEntityId:()=>vi,isPromptRole:()=>dc,isProtocolCompatible:()=>ho,isReservedEnvName:()=>Wt,isTerminalPhase:()=>Xv,isValidBranchName:()=>er,jobLane:()=>t$,laneSegmentForPhase:()=>Qv,makeTaskId:()=>X$,matchesReleasePattern:()=>Ap,mergeRoles:()=>lc,mergeSkills:()=>hc,mismatchedIds:()=>A$,modelAnnotationPath:()=>Ca,modelComponentSlug:()=>Ad,modelCorrelatesPath:()=>Pa,modelEventPath:()=>Cr,modelIdentityPath:()=>wo,modelNodeKey:()=>ye,modelShardNeedsRebuild:()=>Vv,modelStructureShardPath:()=>_a,modelTaskNodeKey:()=>Ee,modelTouchedPath:()=>Aa,parseActionDefinition:()=>Za,parseCodepipeCommand:()=>Nr,parseContextStamp:()=>Sa,parseEffortConfig:()=>c$,parseGitConfig:()=>yn,parseMarketplaceSource:()=>gp,parseMarketplaces:()=>x$,parseModelConfig:()=>s$,parseModelNodeKey:()=>ne,parsePlanItems:()=>gc,parseRepoMirror:()=>bc,parseSolutionItems:()=>L$,parseWorkflowPreset:()=>n$,pipelineColumnForPhase:()=>e$,pipelineRepoSpec:()=>kc,prescribedSkills:()=>yc,promptOverridePath:()=>pc,renderCommitSubject:()=>z$,renderContextStamp:()=>go,repoBaseBranch:()=>wn,resolveBranchName:()=>B$,resolveEffortForRole:()=>a$,resolveModelForRole:()=>o$,resolveProvider:()=>i$,resolveRepoFlow:()=>W$,rolesForScenario:()=>uc,serializeEffortConfig:()=>l$,serializeModelConfig:()=>d$,serializeModelEdgeSheet:()=>Pr,serializeModelIdentityTable:()=>Ua,serializeModelShard:()=>Da,serializeModelTaskEvent:()=>pn,serializeModelYaml:()=>_r,slugify:()=>U$,solutionCoverage:()=>M$,suggestInternalTrackerPrefix:()=>Tc,validateActionInput:()=>Qa,validateCouncilVerdict:()=>T$,validateModelEdgeSheet:()=>bo,validateModelIdentityTable:()=>ko,validateModelShard:()=>Gt,validateModelTaskEvent:()=>Kt,validateObserverPlan:()=>R$,validateRoleDefinition:()=>cc,validateSettingEdit:()=>sc,validateSkill:()=>mc,youtrackIssueUrl:()=>F$,zeroUsage:()=>ut});var Cc,ox,M=x(()=>{"use strict";Td();Id();Pd();Ba();Fd();Kd();Wa();Va();lp();up();tc();ec();pp();mp();yp();bp();kp();vp();$p();xp();Sp();Ep();Rp();vc();_p();Np();Op();Mp();Up();Bp();Gp();Kp();Wp();qp();Xp();Cc=20,ox=15});function ee(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Ye=x(()=>{"use strict"});import{existsSync as ix,readFileSync as sx,readdirSync as ax}from"node:fs";import{dirname as cx,join as Ac}from"node:path";import{parse as lx}from"yaml";function ux(t=process.cwd()){let e=t;for(;;){if(ix(Ac(e,nt,"project.yaml")))return e;let r=cx(e);if(r===e)return null;e=r}}function dx(t){return Ac(t,nt)}function je(t=process.cwd()){let e=ux(t);if(!e)return null;let r=dx(e),n=px(sx(Ac(r,"project.yaml"),"utf-8"));for(let o of n.gitConfigErrors??[])console.warn(`project.yaml: invalid git config \u2014 ${o}`);return{root:e,contextDir:r,spec:n}}function Jp(t,e,r){return ax(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 $n(t,e=process.cwd()){try{let r=je(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function px(t){let e=lx(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),n=String(e.name??r),o=Array.isArray(e.repos)?e.repos:[],i=[],s=[];s.push(...yn(e.git).errors.map(a=>`git: ${a}`));for(let a of o){if(!a||typeof a!="object")continue;let c=a,l=String(c.repo??c.repoName??""),u=String(c.name??l);if(!u||!l)continue;let p=c.host,d=p==="bitbucket"?"bitbucket":p==="gitlab"?"gitlab":"github",f=bc(c.mirror);c.git!==void 0&&c.git!==null&&s.push(...yn(c.git).errors.map(m=>`repos[${u}].git: ${m}`)),i.push({name:u,host:d,owner:String(c.owner??""),repoName:l,defaultBranch:String(c.default_branch??c.defaultBranch??"main"),mountAs:String(c.mount_as??c.mountAs??u),...f?{mirror:f}:{}})}return{projectId:r,name:n,repos:i,...s.length>0?{gitConfigErrors:s}:{}}}function Zp(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 nt,xt=x(()=>{"use strict";M();nt=".codepipe"});import{homedir as Qp}from"node:os";import{mkdirSync as fx,readFileSync as mx,writeFileSync as hx,existsSync as _c}from"node:fs";import{dirname as tf,join as _i,resolve as gx}from"node:path";import{fileURLToPath as yx}from"node:url";function rf(t){let e=_i(ef,".env");if(_c(e)&&process.loadEnvFile(e),t){let r=_i(ef,"profiles",t,".env");_c(r)&&process.loadEnvFile(r)}}function xn(t){let e=ee("CONFIG");return e||(t?_i(Qp(),".codepipe","profiles",t,"config.json"):_i(Qp(),".codepipe","config.json"))}function St(t){let e=xn(t);if(!_c(e))return null;let r=mx(e,"utf-8");return JSON.parse(r)}function Yt(t,e){let r=xn(e);fx(tf(r),{recursive:!0}),hx(r,JSON.stringify(t,null,2)+`
16
+ `,{mode:384})}function Sn(t){if(t)return{cfg:dt(t),profile:t};let e;try{e=je()?.spec.projectId||void 0}catch{}if(e){let r=St(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:dt(void 0),profile:void 0}}function dt(t){let e=St(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 ${xn(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var ef,Ve=x(()=>{"use strict";Ye();xt();ef=gx(tf(yx(import.meta.url)),"..")});import{homedir as nf}from"node:os";import{existsSync as of,mkdirSync as sf,readFileSync as af,writeFileSync as cf}from"node:fs";import{dirname as lf,join as uf}from"node:path";function df(t,e,r){let n=X(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},ce(n)}function pf(t,e){let r=X(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],ce(r),!0)}function ff(t){return Object.keys(X(t)?.secrets??{}).sort()}function ji(t,e,r){let n=X(t);if(!n)return"mismatch";let o=n.sandboxPins??{},i=o[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(o[e]=r,n.sandboxPins=o,ce(n),"pinned")}function mf(t,e){let r=X(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],ce(r),!0):!1}function _t(t){return uf(nf(),".codepipe","secrets",`${t}.json`)}function X(t){let e=_t(t);return of(e)?JSON.parse(af(e,"utf-8")):null}function ce(t){let e=_t(t.projectId);sf(lf(e),{recursive:!0}),cf(e,JSON.stringify(t,null,2)+`
17
+ `,{mode:384})}function Ni(){return uf(nf(),".codepipe","shared.json")}function jc(){let t=Ni();return of(t)?JSON.parse(af(t,"utf-8")):null}function hf(t){let e=Ni();sf(lf(e),{recursive:!0}),cf(e,JSON.stringify(t,null,2)+`
18
+ `,{mode:384})}function En(t){let e=X(t)?.claude?.oauthToken;return e||jc()?.claude?.oauthToken}function Po(t){let e={GH_TOKEN:t.github?.token,BITBUCKET_EMAIL:t.bitbucket?.email,BITBUCKET_API_TOKEN:t.bitbucket?.apiToken,GITLAB_TOKEN:t.gitlab?.token,YOUTRACK_URL:t.youtrack?.url,YOUTRACK_TOKEN:t.youtrack?.token};for(let r of Nc){let n=e[r];n&&!process.env[r]&&(process.env[r]=n)}}function Rn(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var Nc,me=x(()=>{"use strict";Nc=["GH_TOKEN","BITBUCKET_EMAIL","BITBUCKET_API_TOKEN","GITLAB_TOKEN","YOUTRACK_URL","YOUTRACK_TOKEN"]});import{appendFileSync as wx,existsSync as yf,mkdirSync as bx,renameSync as wf,statSync as kx,unlinkSync as vx}from"node:fs";import{Writable as $x}from"node:stream";import{join as xx}from"node:path";function Oi(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=Sx(process.env[`${t}_MAX_BYTES`]??String(bf.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):bf.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function Sx(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 Li(t){let e={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},r=(n,o)=>(...i)=>{n(...i);try{t.writeLine(Ex(o,i))}catch{}};return console.log=r(e.log,"INFO"),console.warn=r(e.warn,"WARN"),console.error=r(e.error,"ERROR"),()=>{console.log=e.log,console.warn=e.warn,console.error=e.error}}function Ex(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:Rx(o)).join(" ");return`${r} ${t} ${n}`}function Rx(t){try{return JSON.stringify(t)}catch{return String(t)}}var bf,Tn,Oc=x(()=>{"use strict";bf={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},Tn=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&bx(e.dir,{recursive:!0}),this.currentPath=xx(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
19
19
  `)?e:e+`
20
- `;mx(this.currentPath,r,"utf-8")}asWritable(){return new wx({write:(e,r,n)=>{try{let o=typeof e=="string"?e:e.toString("utf-8");for(let i of o.split(/\r?\n/))i&&this.writeLine(i);n()}catch(o){n(o)}}})}rotateIfNeeded(){if(!(this.cfg.maxBytes<=0||!mf(this.currentPath)||gx(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;mf(n)&&(r>=this.cfg.maxFiles?yx(n):hf(n,`${this.currentPath}.${r+1}`))}hf(this.currentPath,`${this.currentPath}.1`)}}}});function Di(t){return t===429||t>=500}function bf(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
21
- `+t.slice(t.length-e)}async function tr(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),Mi);try{let i;try{i=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new pt(`cannot reach api.github.com (${l instanceof Error?l.message:String(l)})`)}if(i.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(Di(i.status))throw new pt(`api.github.com \u2192 ${i.status} ${i.statusText}`);if(!i.ok)throw new Error(`GitHub \u2192 ${i.status} ${i.statusText}`);let a=(await i.json()).login??"ok",c=i.headers.get("x-oauth-scopes");if(c!==null&&e&&!c.split(",").map(u=>u.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${c||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let l;try{let u=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});u.ok&&(l=(await u.json()).type)}catch{}if(l==="Organization"){let u=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});if(u.status===403)throw new Error(`token cannot access org "${e.owner}" (403) \u2014 for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens; for classic PATs: verify 'repo' or 'admin:org' scope`);if(u.status===404)throw new Error(`org "${e.owner}" not found or not visible to this token \u2014 check the org name; for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens`);if(!u.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${u.status} ${u.statusText}`)}}return a}finally{clearTimeout(o)}}async function Ui(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),Mi);try{let s;try{s=await fetch(n,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},signal:o.signal})}catch(c){throw new pt(`cannot reach api.github.com (${c instanceof Error?c.message:String(c)})`)}if(s.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(s.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(Di(s.status))throw new pt(`api.github.com \u2192 ${s.status} ${s.statusText}`);if(!s.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${s.status} ${s.statusText}`);if((await s.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}finally{clearTimeout(i)}}async function rr(t,e,r){let n=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",o=new AbortController,i=setTimeout(()=>o.abort(),Mi);try{let s;try{s=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new pt(`cannot reach api.bitbucket.org (${c instanceof Error?c.message:String(c)})`)}if(s.ok)return t;if(s.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;if(Di(s.status))throw new pt(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await Cx(s);throw s.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${a})`):s.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${a})`):s.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${a})`):new Error(`Bitbucket \u2192 ${s.status} ${s.statusText}${a}`)}finally{clearTimeout(i)}}async function Cx(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function Bi(t,e,r,n){let o;try{o=await fetch(`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}/${encodeURIComponent(n)}/pullrequests?pagelen=1`,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch{return}if(o.status!==403)return;let i={};try{i=await o.json()}catch{}let s=i.error?.detail?.granted;if(Array.isArray(s)){let c=kf.filter(l=>!s.includes(l));return c.length===0?void 0:`token lacks scope(s) ${c.join(", ")} \u2014 the pipeline would fail at PR time; re-create the API token with all of: ${kf.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function nr(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Mi);try{let n;try{n=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"},signal:e.signal})}catch(i){throw new pt(`cannot reach gitlab.com (${i instanceof Error?i.message:String(i)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(Di(n.status))throw new pt(`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 vf(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 Px(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 Mc(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 or(t,e){let r=kc(e);if(!e.mirror)return{spec:r,host:Mr(r)};let n=t?X(t)?.mirrorWrite:void 0;return{spec:r,host:Mr(r,n?.token?{token:n.token,...n.email?{bitbucketEmail:n.email}:{}}:void 0)}}function Mr(t,e){if(t.host==="github"){let r=e?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(r)return new Uc(r)}if(t.host==="bitbucket"){let r=e?.bitbucketEmail??process.env.BITBUCKET_EMAIL,n=e?.token??process.env.BITBUCKET_API_TOKEN;if(r&&n)return new Dc(r,n)}if(t.host==="gitlab"){let r=e?.token??process.env.GITLAB_TOKEN;if(r)return new Bc(r)}return new Fc}var Lr,pt,Mi,kf,Dc,Uc,Bc,Fc,Yt=x(()=>{"use strict";M();me();Lr=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},pt=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},Mi=5e3;kf=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];Dc=class{constructor(e,r){this.email=e;this.apiToken=r}name="bitbucket";authHeader(){return"Basic "+Buffer.from(`${this.email}:${this.apiToken}`).toString("base64")}async createPullRequest(e,r){let n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json"},body:JSON.stringify({title:r.title,description:r.body,source:{branch:{name:r.branchName}},destination:{branch:{name:r.baseBranch}}})});if(!n.ok)throw new Error(`bitbucket pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.links?.html?.href??"",number:o.id}}async findOpenPrByBranch(e,r){let n=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${n}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!o.ok)return null;let s=(await o.json()).values?.[0];return s?{url:s.links?.html?.href??"",number:s.id}:null}async getPullRequest(e,r){let n=`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(o.status===404)throw new Lr(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){let i=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:o})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:n}})});if(!o.ok)throw new Error(`bitbucket comment PR #${r}: ${o.status} ${await o.text()}`)}async addPRInlineComment(e,r,n,o,i){let s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:i},inline:{path:n,to:o}})});if(!s.ok)throw new Error(`bitbucket inline comment PR #${r} ${n}:${o}: ${s.status} ${await s.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},Uc=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json"},body:JSON.stringify({title:r.title,body:r.body,head:r.branchName,base:r.baseBranch})});if(!n.ok)throw new Error(`github pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.html_url,number:o.number}}async findOpenPrByBranch(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls?state=open&head=${encodeURIComponent(`${e.owner}:${r}`)}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.html_url,number:i.number}:null}async getPullRequest(e,r){let n=`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(o.status===404)throw new Lr(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async getBranchCi(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=await fetch(`${o}/commits/${encodeURIComponent(r)}`,{headers:n});if(!i.ok)return null;let s=(await i.json()).sha;return s?{ci:await this.fetchCiStatus(e,s),headSha:s}:null}async fetchCiStatus(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),a=!1,c=!1,l=!1;if(i.ok){let u=await i.json();for(let p of u.check_runs??[])l=!0,p.status!=="completed"?a=!0:p.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(p.conclusion)&&(c=!0)}if(s.ok){let u=await s.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`;try{let i=await fetch(`${o}/pulls/${r}`,{headers:n});if(!i.ok)return;let s=(await i.json()).head?.sha;return s?await this.getCiFailureLogForSha(e,s):void 0}catch{return}}async getCiFailureLogForSha(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${o}/actions/runs?head_sha=${r}&per_page=20`,{headers:n});if(!s.ok)return;let a=(await s.json()).workflow_runs??[],c=[];for(let l of a.filter(u=>u.conclusion&&i.includes(u.conclusion))){let u=await fetch(`${o}/actions/runs/${l.id}/jobs?per_page=50`,{headers:n});if(!u.ok)continue;let p=(await u.json()).jobs??[];for(let d of p.filter(f=>f.conclusion==="failure")){let f=await fetch(`${o}/actions/jobs/${d.id}/logs`,{headers:n});if(!f.ok)continue;let m=await f.text();c.push(`### CI job: ${d.name}
20
+ `;wx(this.currentPath,r,"utf-8")}asWritable(){return new $x({write:(e,r,n)=>{try{let o=typeof e=="string"?e:e.toString("utf-8");for(let i of o.split(/\r?\n/))i&&this.writeLine(i);n()}catch(o){n(o)}}})}rotateIfNeeded(){if(!(this.cfg.maxBytes<=0||!yf(this.currentPath)||kx(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;yf(n)&&(r>=this.cfg.maxFiles?vx(n):wf(n,`${this.currentPath}.${r+1}`))}wf(this.currentPath,`${this.currentPath}.1`)}}}});function Di(t){return t===429||t>=500}function $f(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
21
+ `+t.slice(t.length-e)}async function rr(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),Mi);try{let i;try{i=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new pt(`cannot reach api.github.com (${l instanceof Error?l.message:String(l)})`)}if(i.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(Di(i.status))throw new pt(`api.github.com \u2192 ${i.status} ${i.statusText}`);if(!i.ok)throw new Error(`GitHub \u2192 ${i.status} ${i.statusText}`);let a=(await i.json()).login??"ok",c=i.headers.get("x-oauth-scopes");if(c!==null&&e&&!c.split(",").map(u=>u.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${c||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let l;try{let u=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});u.ok&&(l=(await u.json()).type)}catch{}if(l==="Organization"){let u=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});if(u.status===403)throw new Error(`token cannot access org "${e.owner}" (403) \u2014 for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens; for classic PATs: verify 'repo' or 'admin:org' scope`);if(u.status===404)throw new Error(`org "${e.owner}" not found or not visible to this token \u2014 check the org name; for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens`);if(!u.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${u.status} ${u.statusText}`)}}return a}finally{clearTimeout(o)}}async function Ui(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),Mi);try{let s;try{s=await fetch(n,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},signal:o.signal})}catch(c){throw new pt(`cannot reach api.github.com (${c instanceof Error?c.message:String(c)})`)}if(s.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(s.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(Di(s.status))throw new pt(`api.github.com \u2192 ${s.status} ${s.statusText}`);if(!s.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${s.status} ${s.statusText}`);if((await s.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}finally{clearTimeout(i)}}async function nr(t,e,r){let n=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",o=new AbortController,i=setTimeout(()=>o.abort(),Mi);try{let s;try{s=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new pt(`cannot reach api.bitbucket.org (${c instanceof Error?c.message:String(c)})`)}if(s.ok)return t;if(s.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;if(Di(s.status))throw new pt(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await jx(s);throw s.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${a})`):s.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${a})`):s.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${a})`):new Error(`Bitbucket \u2192 ${s.status} ${s.statusText}${a}`)}finally{clearTimeout(i)}}async function jx(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function Bi(t,e,r,n){let o;try{o=await fetch(`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}/${encodeURIComponent(n)}/pullrequests?pagelen=1`,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch{return}if(o.status!==403)return;let i={};try{i=await o.json()}catch{}let s=i.error?.detail?.granted;if(Array.isArray(s)){let c=xf.filter(l=>!s.includes(l));return c.length===0?void 0:`token lacks scope(s) ${c.join(", ")} \u2014 the pipeline would fail at PR time; re-create the API token with all of: ${xf.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function or(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Mi);try{let n;try{n=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"},signal:e.signal})}catch(i){throw new pt(`cannot reach gitlab.com (${i instanceof Error?i.message:String(i)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(Di(n.status))throw new pt(`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 Sf(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 Nx(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 Mc(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 ir(t,e){let r=kc(e);if(!e.mirror)return{spec:r,host:Dr(r)};let n=t?X(t)?.mirrorWrite:void 0;return{spec:r,host:Dr(r,n?.token?{token:n.token,...n.email?{bitbucketEmail:n.email}:{}}:void 0)}}function Dr(t,e){if(t.host==="github"){let r=e?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(r)return new Uc(r)}if(t.host==="bitbucket"){let r=e?.bitbucketEmail??process.env.BITBUCKET_EMAIL,n=e?.token??process.env.BITBUCKET_API_TOKEN;if(r&&n)return new Dc(r,n)}if(t.host==="gitlab"){let r=e?.token??process.env.GITLAB_TOKEN;if(r)return new Bc(r)}return new Fc}var Mr,pt,Mi,xf,Dc,Uc,Bc,Fc,Vt=x(()=>{"use strict";M();me();Mr=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},pt=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},Mi=5e3;xf=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];Dc=class{constructor(e,r){this.email=e;this.apiToken=r}name="bitbucket";authHeader(){return"Basic "+Buffer.from(`${this.email}:${this.apiToken}`).toString("base64")}async createPullRequest(e,r){let n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json"},body:JSON.stringify({title:r.title,description:r.body,source:{branch:{name:r.branchName}},destination:{branch:{name:r.baseBranch}}})});if(!n.ok)throw new Error(`bitbucket pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.links?.html?.href??"",number:o.id}}async findOpenPrByBranch(e,r){let n=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${n}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!o.ok)return null;let s=(await o.json()).values?.[0];return s?{url:s.links?.html?.href??"",number:s.id}:null}async getPullRequest(e,r){let n=`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(o.status===404)throw new Mr(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){let i=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:o})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:n}})});if(!o.ok)throw new Error(`bitbucket comment PR #${r}: ${o.status} ${await o.text()}`)}async addPRInlineComment(e,r,n,o,i){let s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:i},inline:{path:n,to:o}})});if(!s.ok)throw new Error(`bitbucket inline comment PR #${r} ${n}:${o}: ${s.status} ${await s.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},Uc=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json"},body:JSON.stringify({title:r.title,body:r.body,head:r.branchName,base:r.baseBranch})});if(!n.ok)throw new Error(`github pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.html_url,number:o.number}}async findOpenPrByBranch(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls?state=open&head=${encodeURIComponent(`${e.owner}:${r}`)}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.html_url,number:i.number}:null}async getPullRequest(e,r){let n=`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(o.status===404)throw new Mr(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async getBranchCi(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=await fetch(`${o}/commits/${encodeURIComponent(r)}`,{headers:n});if(!i.ok)return null;let s=(await i.json()).sha;return s?{ci:await this.fetchCiStatus(e,s),headSha:s}:null}async fetchCiStatus(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),a=!1,c=!1,l=!1;if(i.ok){let u=await i.json();for(let p of u.check_runs??[])l=!0,p.status!=="completed"?a=!0:p.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(p.conclusion)&&(c=!0)}if(s.ok){let u=await s.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`;try{let i=await fetch(`${o}/pulls/${r}`,{headers:n});if(!i.ok)return;let s=(await i.json()).head?.sha;return s?await this.getCiFailureLogForSha(e,s):void 0}catch{return}}async getCiFailureLogForSha(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${o}/actions/runs?head_sha=${r}&per_page=20`,{headers:n});if(!s.ok)return;let a=(await s.json()).workflow_runs??[],c=[];for(let l of a.filter(u=>u.conclusion&&i.includes(u.conclusion))){let u=await fetch(`${o}/actions/runs/${l.id}/jobs?per_page=50`,{headers:n});if(!u.ok)continue;let p=(await u.json()).jobs??[];for(let d of p.filter(f=>f.conclusion==="failure")){let f=await fetch(`${o}/actions/jobs/${d.id}/logs`,{headers:n});if(!f.ok)continue;let m=await f.text();c.push(`### CI job: ${d.name}
22
22
 
23
- ${bf(m,8e3)}`)}}return c.length===0?void 0:bf(c.join(`
23
+ ${$f(m,8e3)}`)}}return c.length===0?void 0:$f(c.join(`
24
24
 
25
- `),16e3)}catch{return}}async mergePR(e,r,n,o){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async addPRInlineComment(e,r,n,o,i){let s={Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:s});if(!a.ok)throw new Error(`github PR #${r}: ${a.status} ${await a.text()}`);let c=(await a.json()).head?.sha;if(!c)throw new Error(`github PR #${r}: no head sha`);let l=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/comments`,{method:"POST",headers:{...s,"Content-Type":"application/json"},body:JSON.stringify({body:i,commit_id:c,path:n,line:o,side:"RIGHT"})});if(!l.ok)throw new Error(`github inline comment PR #${r} ${n}:${o}: ${l.status} ${await l.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},Bc=class{constructor(e){this.token=e}name="gitlab";pid(e){return encodeURIComponent(`${e.owner}/${e.repoName}`)}headers(e=!1){let r={"PRIVATE-TOKEN":this.token,"User-Agent":"codepipe-cli"};return e&&(r["Content-Type"]="application/json"),r}async createPullRequest(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({source_branch:r.branchName,target_branch:r.baseBranch,title:r.title,description:r.body})});if(!n.ok)throw new Error(`gitlab mr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.web_url??"",number:o.iid}}async findOpenPrByBranch(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests?state=opened&source_branch=${encodeURIComponent(r)}`,{headers:this.headers()});if(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.web_url??"",number:i.iid}:null}async getPullRequest(e,r){let n=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,o=await fetch(n,{method:"GET",headers:this.headers()});if(o.status===404)throw new Lr(`GitLab MR not found: ${e.owner}/${e.repoName}!${r}`);if(o.status>=400)throw new Error(`gitlab GET merge_requests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="merged")return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed"||i.state==="locked")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=Px(i.head_pipeline?.status??i.pipeline?.status),a=i.merge_status==="cannot_be_merged"||i.has_conflicts===!0?"conflict":i.merge_status==="can_be_merged"&&i.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:s,mergeable:a}}async mergePR(e,r,n,o){let i=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,s,a=await fetch(i,{headers:this.headers()});if(a.ok){let u=await a.json().catch(()=>null);s=u?.sha??u?.diff_refs?.head_sha}let c=await fetch(`${i}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:n==="squash",should_remove_source_branch:o,...s?{sha:s}:{}})});if(!c.ok)throw new Error(`gitlab merge MR !${r}: ${c.status} ${await c.text()}`);let l=await c.json().catch(()=>null);return l?.merge_commit_sha?{mergedSha:l.merge_commit_sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`gitlab comment MR !${r}: ${o.status} ${await o.text()}`)}async addPRInlineComment(e,r,n,o,i){let s=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{headers:this.headers(!1)});if(!s.ok)throw new Error(`gitlab MR !${r}: ${s.status} ${await s.text()}`);let a=(await s.json()).diff_refs;if(!a?.base_sha||!a.head_sha||!a.start_sha)throw new Error(`gitlab MR !${r}: no diff refs`);let c=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/discussions`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:i,position:{position_type:"text",new_path:n,new_line:o,base_sha:a.base_sha,head_sha:a.head_sha,start_sha:a.start_sha}})});if(!c.ok)throw new Error(`gitlab inline comment MR !${r} ${n}:${o}: ${c.status} ${await c.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!o.ok)throw new Error(`gitlab close MR !${r}: ${o.status} ${await o.text()}`)}};Fc=class{name="mock";async createPullRequest(e,r){let n=Math.floor(Math.random()*9e3)+1e3;return{url:`https://example.com/${e.owner}/${e.repoName}/pull-requests/${n}`,number:n}}async getPullRequest(e,r){return{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){throw new Error(Mc(e,r,"merge"))}async closePR(e,r,n){throw new Error(Mc(e,r,"close"))}async addPRComment(e,r,n){throw new Error(Mc(e,r,"comment"))}}});import{X509Certificate as Sf}from"node:crypto";import{readFileSync as Ax}from"node:fs";import ir from"node:tls";function _x(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function Tf(t=Rf){if($f)return;$f=!0;let e=ee("EXTRA_CA_FILE");if(!(!e||!Ef))try{let r=_x(Ax(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}ir.setDefaultCACertificates([...ir.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 If(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 jx(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
26
- `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function Nx(t,e,r){return new Promise((n,o)=>{let i=ir.connect({host:t,port:e,servername:t,rejectUnauthorized:!1},()=>{let s=i.getPeerCertificate(!0),a=new Set;for(;s?.issuerCertificate&&s.issuerCertificate!==s&&s.fingerprint256&&!a.has(s.fingerprint256);)a.add(s.fingerprint256),s=s.issuerCertificate;let c=s?.raw?new Sf(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function Gc(t,e,r){return new Promise(n=>{let o=ir.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 Ox(t){try{let e=await fetch(t);return e.ok?new Sf(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Cf(t,e=443,r=Rf){let n=`${t}:${e}`,o=xf.get(n);if(o)return o;let i=Lx(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return xf.set(n,i),i}async function Lx(t,e,r){if(!Ef)return!1;let n=8e3;if(await Gc(t,e,n))return!0;let o=await Nx(t,e,n),i=ir.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=jx(o);if(!c)break;let l=await Ox(c);if(!l)break;if(s.push(l.toString()),ir.setDefaultCACertificates([...i,...s]),await Gc(t,e,n))return r(`[tls] completed certificate chain for ${t} via AIA (+${s.length} intermediate cert(s))`),!0;if(l.subject===l.issuer)break;o=l}return Gc(t,e,n)}var Ef,$f,xf,Rf,Pf=x(()=>{"use strict";Ye();Ef=typeof ir.getCACertificates=="function"&&typeof ir.setDefaultCACertificates=="function",$f=!1,xf=new Map,Rf=t=>console.warn(t)});function Nf(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function ft(t,e,r){Tf();let n={Authorization:`Bearer ${t.token}`,Accept:"application/json"};r?.body&&(n["Content-Type"]="application/json");let o=t.baseUrl+e,i={...r,headers:{...n,...r?.headers??{}}};try{return await fetch(o,i)}catch(s){if(If(s)&&await Cf(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function Mx(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Dx(){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 Kc(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=Dx(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await ft(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&&Mx(l.status,u)){await Af(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await Af(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function sr(t){let e;try{e=await ft(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 Of(t){try{let e=await ft(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function Ux(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=_f.get(o);if(i)return i;let s=await ft(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!s.ok)throw new Error(`yt resolveStateId ${e}: ${s.status} ${await s.text()}`);let c=(await s.json()).customFields.find(u=>u.name===n);if(!c)throw new Error(`yt: issue ${e} has no ${n} custom field`);let l=c.projectCustomField.bundle.values.find(u=>u.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${n} bundle for ${e}`);return _f.set(o,l.id),l.id}async function Lf(t,e,r,n=Po){let o=await Ux(t,e,r,n);await Kc(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 Mf(t,e,r){return await(await Kc(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function Df(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await Kc(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function Uf(t,e){let r=jf.get(e);if(r)return r;let n=await ft(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!n.ok)throw new Error(`yt resolveProjectId: ${n.status} ${await n.text()}`);let i=(await n.json()).find(s=>s.shortName===e);if(!i)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return jf.set(e,i.id),i.id}async function Bf(t,e,r,n,o,i=Po){let s=await Uf(t,e),a=await ft(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:s},summary:r,description:n,customFields:[{name:i,$type:"StateIssueCustomField",value:{name:o,$type:"StateBundleElement"}}]})});if(!a.ok)throw new Error(`yt createIssue: ${a.status} ${await a.text()}`);let c=await a.json();return{id:c.id,key:c.idReadable}}async function Ff(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await ft(t,"/api/commands",{method:"POST",body:JSON.stringify({query:o,issues:[{idReadable:e}]})});if(!i.ok)throw new Error(`yt applyIssueLink (${o} on ${e}): ${i.status} ${await i.text()}`)}function Hf(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 Wf(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 qf(t,e){let r=e.stageField??Po,n=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let c=e.columns.map(l=>`{${l}}`).join(", ");n.push(`${r}: ${c}`)}if(e.updatedSince){let c=new Date(e.updatedSince).toISOString().slice(0,10);n.push(`updated: ${c} .. *`)}e.assignee?n.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&n.push("has: Assignee");let o=n.join(" "),i=`/api/issues?query=${encodeURIComponent(o)}&fields=${Kf}&$top=200`,s=await ft(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);let a=await s.json();if(e.columns&&e.columns.length>0&&a.length>0&&!a.some(l=>(l.customFields??[]).some(u=>u.name===r))){let l=[...new Set((a[0]?.customFields??[]).map(u=>u.name).filter(u=>!!u))];throw new Error(`youtrack.stage_field "${r}" does not exist in project ${e.projectKey} \u2014 YouTrack ignored the status filter and would have returned unrelated issues. `+(l.length>0?`Fields on the issues: ${l.join(", ")}.`:"The issues carry no custom fields at all."))}return a.map(c=>zf(c,r))}async function Yf(t,e,r=Po){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Kf}`,o=await ft(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return zf(await o.json(),r)}async function Vf(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${Fx}&$top=500`,o=await ft(t,n);if(!o.ok)throw new Error(`yt listComments ${e}: ${o.status} ${await o.text()}`);return(await o.json()).filter(s=>s.created>r).map(s=>{let a={id:s.id,issueId:e,author:s.author?.login??"unknown",body:s.text??"",createdAt:new Date(s.created).toISOString()},c=Hf(s.attachments);return c&&(a.attachments=c),a})}function Gx(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 zf(t,e=Po){let r=t.customFields??[],n=r.find(l=>l.name===e),o=r.find(l=>l.name==="Assignee"),i=r.find(l=>l.name==="Type"),s={id:t.id,key:t.idReadable,title:t.summary,status:n?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(s.description=t.description),o?.value?.login&&(s.assignee=o.value.login),i?.value?.name&&(s.issueType=i.value.name),t.tags&&t.tags.length>0&&(s.tags=t.tags.map(l=>l.name));let a=Hf(t.attachments);a&&(s.attachments=a);let c=Gx(t.links);return c&&(s.links=c),s}async function Xf(t,e){let r=await Kx(t,e);return r.length>0?r:Hx(t,e)}async function Kx(t,e){let r=await Uf(t,e),n=await ft(t,`/api/admin/projects/${encodeURIComponent(r)}/customFields?fields=$type,field(name),bundle(values(name,archived))&$top=100`);if(!n.ok)return[];let o=await n.json(),i=[];for(let s of o)s.$type==="StateProjectCustomField"&&s.field?.name&&i.push({name:s.field.name,values:Jf(s.bundle)});return i}async function Hx(t,e){let r=`project: ${e}`,n=await ft(t,`/api/issues?query=${encodeURIComponent(r)}&fields=customFields(name,$type,projectCustomField(bundle(values(name,archived))))&$top=1`);if(!n.ok)throw new Error(`yt fetchProjectStateFields ${e}: ${n.status} ${await n.text()}`);let o=await n.json(),i=[];for(let s of o[0]?.customFields??[])s.$type==="StateIssueCustomField"&&s.name&&i.push({name:s.name,values:Jf(s.projectCustomField?.bundle)});return i}function Jf(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var Af,Po,_f,jf,Gf,Bx,Kf,Fx,Dr=x(()=>{"use strict";Pf();Af=t=>new Promise(e=>setTimeout(e,t));Po="Stage",_f=new Map;jf=new Map;Gf="attachments(id,name,url,size,mimeType)",Bx="links(direction,linkType(name),issues(idReadable))",Kf=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Gf},${Bx}`,Fx=`id,text,created,author(login),${Gf}`});function Et(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function Tn(t){return t instanceof pt}async function Zf(t,e){let r=X(t),n=[],o=[],i=()=>Date.now();if(e?.trackerProvider==="internal")n.push({name:"tracker",ok:!0,detail:"built-in tracker"});else if(r?.youtrack?.url&&r.youtrack.token)try{let c=await sr({baseUrl:r.youtrack.url,token:r.youtrack.token});n.push({name:"youtrack",ok:!0}),o.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"youtrack",ok:!1,detail:Et(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:Et(c),checkedAt:i()})}else n.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),o.push({kind:"youtrack",present:!1,checkedAt:i()});let s=!1;if(r?.github?.token){s=!0;try{let c=await tr(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){Tn(c)?(n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"github",ok:!1,detail:Et(c)}),o.push({kind:"github",present:!0,ok:!1,detail:Et(c),checkedAt:i()}))}}else o.push({kind:"github",present:!1,checkedAt:i()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){s=!0;try{let c=await rr(r.bitbucket.email,r.bitbucket.apiToken);n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){Tn(c)?(n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"bitbucket",ok:!1,detail:Et(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:Et(c),checkedAt:i()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await nr(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){Tn(c)?(n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"gitlab",ok:!1,detail:Et(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:Et(c),checkedAt:i()}))}}else o.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||n.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let u of e?.repos??[])if(u.host==="github")try{await Ui(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){Tn(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:Et(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await Ui(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){Tn(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:Et(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Ui(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){Tn(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:i()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:Et(l),checkedAt:i()})}else o.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:i()})}else o.push({kind:"contextWrite",present:!1,checkedAt:i()});let a=Sn(t);if(!a)n.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),o.push({kind:"claude",present:!1,checkedAt:i()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:i()});else{let c=await Vt(a);if(c==="invalid"){let l="Claude refused this token \u2014 refresh it with `claude setup-token`";n.push({name:"claude",ok:!1,detail:l}),o.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function Vt(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:Wx,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 Qf(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1000",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});if(n.status!==200)return null;let i=(await n.json())?.data;if(!Array.isArray(i))return null;let s=[];for(let a of i){let c=a?.id;if(typeof c!="string"||c.trim().length===0)continue;let l=a?.created_at;s.push({id:c,...typeof l=="string"?{createdAt:l}:{}})}return s}catch{return null}finally{clearTimeout(r)}}var Wx,In=x(()=>{"use strict";me();Yt();Dr();Wx="claude-haiku-4-5-20251001"});import qx from"node:http";import Hc from"node:crypto";function Fi(){let t=Wc(Hc.randomBytes(32)),e=Wc(Hc.createHash("sha256").update(t).digest()),r=Wc(Hc.randomBytes(32));return{verifier:t,challenge:e,state:r}}function Yc(t){let e=new URL(Yx);return e.search=new URLSearchParams({response_type:"code",client_id:em,redirect_uri:t.redirectUri,scope:zx,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function Jx(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 tm(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 Zx(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 Vc(t){let e=await fetch(Vx,{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:em,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return Zx(await e.json())}async function zc(t){let e=t.timeoutMs??Xx,r=qx.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=Yc({redirectUri:o,challenge:t.challenge,state:t.state}),s,a=new Promise((l,u)=>{s=setTimeout(()=>u(new Error("no-callback")),e),r.on("request",(p,d)=>{let f=new URL(p.url??"/",o);if(f.pathname!=="/callback"){d.statusCode=404,d.end();return}clearTimeout(s),d.setHeader("content-type","text/html"),d.end("<h3>Authorized \u2014 you can close this tab.</h3>");try{l(Jx(f.searchParams,t.state))}catch(m){u(m)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>Vc({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function rm(t){let e=await zc(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
27
- ${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var em,Yx,Vx,qc,zx,Xx,Wc,Xc=x(()=>{"use strict";em="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Yx="https://platform.claude.com/oauth/authorize",Vx="https://platform.claude.com/v1/oauth/token",qc="https://platform.claude.com/oauth/code/callback",zx="org:create_api_key user:profile user:inference",Xx=12e4,Wc=t=>Buffer.from(t).toString("base64url")});import{spawn as Qx}from"node:child_process";function Ur(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=Qx(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var Gi=x(()=>{"use strict"});import{existsSync as ar,mkdirSync as pm,readFileSync as Qc,writeFileSync as Cn}from"node:fs";import{homedir as cS}from"node:os";import{join as jt}from"node:path";import{simpleGit as lS}from"simple-git";function _o(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=jt(t,o);ar(s)||(Cn(s,i),r.push(o))}return r}function cr(t,e,r){let n=jt(cS(),".codepipe","profiles",t,"context-config");return pm(n,{recursive:!0}),Cn(jt(n,"project.yaml"),e.projectYaml),Cn(jt(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function Wi(t,e,r){if(ar(e))for(let n of Pn){let o=jt(e,n),i=jt(t,n);if(!(!ar(o)||ar(i)))try{Cn(i,Qc(o)),r.info(`[config] seeded local ${n} from the provisioning bundle`)}catch(s){r.warn(`[config] could not seed ${n}: ${s instanceof Error?s.message:String(s)}`)}}}function An(t){let e=jt(t,".gitignore"),r=ar(e)?Qc(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(Pn.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
25
+ `),16e3)}catch{return}}async mergePR(e,r,n,o){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async addPRInlineComment(e,r,n,o,i){let s={Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:s});if(!a.ok)throw new Error(`github PR #${r}: ${a.status} ${await a.text()}`);let c=(await a.json()).head?.sha;if(!c)throw new Error(`github PR #${r}: no head sha`);let l=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/comments`,{method:"POST",headers:{...s,"Content-Type":"application/json"},body:JSON.stringify({body:i,commit_id:c,path:n,line:o,side:"RIGHT"})});if(!l.ok)throw new Error(`github inline comment PR #${r} ${n}:${o}: ${l.status} ${await l.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},Bc=class{constructor(e){this.token=e}name="gitlab";pid(e){return encodeURIComponent(`${e.owner}/${e.repoName}`)}headers(e=!1){let r={"PRIVATE-TOKEN":this.token,"User-Agent":"codepipe-cli"};return e&&(r["Content-Type"]="application/json"),r}async createPullRequest(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({source_branch:r.branchName,target_branch:r.baseBranch,title:r.title,description:r.body})});if(!n.ok)throw new Error(`gitlab mr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.web_url??"",number:o.iid}}async findOpenPrByBranch(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests?state=opened&source_branch=${encodeURIComponent(r)}`,{headers:this.headers()});if(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.web_url??"",number:i.iid}:null}async getPullRequest(e,r){let n=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,o=await fetch(n,{method:"GET",headers:this.headers()});if(o.status===404)throw new Mr(`GitLab MR not found: ${e.owner}/${e.repoName}!${r}`);if(o.status>=400)throw new Error(`gitlab GET merge_requests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="merged")return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed"||i.state==="locked")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=Nx(i.head_pipeline?.status??i.pipeline?.status),a=i.merge_status==="cannot_be_merged"||i.has_conflicts===!0?"conflict":i.merge_status==="can_be_merged"&&i.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:s,mergeable:a}}async mergePR(e,r,n,o){let i=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,s,a=await fetch(i,{headers:this.headers()});if(a.ok){let u=await a.json().catch(()=>null);s=u?.sha??u?.diff_refs?.head_sha}let c=await fetch(`${i}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:n==="squash",should_remove_source_branch:o,...s?{sha:s}:{}})});if(!c.ok)throw new Error(`gitlab merge MR !${r}: ${c.status} ${await c.text()}`);let l=await c.json().catch(()=>null);return l?.merge_commit_sha?{mergedSha:l.merge_commit_sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`gitlab comment MR !${r}: ${o.status} ${await o.text()}`)}async addPRInlineComment(e,r,n,o,i){let s=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{headers:this.headers(!1)});if(!s.ok)throw new Error(`gitlab MR !${r}: ${s.status} ${await s.text()}`);let a=(await s.json()).diff_refs;if(!a?.base_sha||!a.head_sha||!a.start_sha)throw new Error(`gitlab MR !${r}: no diff refs`);let c=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/discussions`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:i,position:{position_type:"text",new_path:n,new_line:o,base_sha:a.base_sha,head_sha:a.head_sha,start_sha:a.start_sha}})});if(!c.ok)throw new Error(`gitlab inline comment MR !${r} ${n}:${o}: ${c.status} ${await c.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!o.ok)throw new Error(`gitlab close MR !${r}: ${o.status} ${await o.text()}`)}};Fc=class{name="mock";async createPullRequest(e,r){let n=Math.floor(Math.random()*9e3)+1e3;return{url:`https://example.com/${e.owner}/${e.repoName}/pull-requests/${n}`,number:n}}async getPullRequest(e,r){return{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){throw new Error(Mc(e,r,"merge"))}async closePR(e,r,n){throw new Error(Mc(e,r,"close"))}async addPRComment(e,r,n){throw new Error(Mc(e,r,"comment"))}}});import{X509Certificate as Tf}from"node:crypto";import{readFileSync as Ox}from"node:fs";import sr from"node:tls";function Lx(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function Pf(t=Cf){if(Ef)return;Ef=!0;let e=ee("EXTRA_CA_FILE");if(!(!e||!If))try{let r=Lx(Ox(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}sr.setDefaultCACertificates([...sr.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 Af(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 Mx(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
26
+ `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function Dx(t,e,r){return new Promise((n,o)=>{let i=sr.connect({host:t,port:e,servername:t,rejectUnauthorized:!1},()=>{let s=i.getPeerCertificate(!0),a=new Set;for(;s?.issuerCertificate&&s.issuerCertificate!==s&&s.fingerprint256&&!a.has(s.fingerprint256);)a.add(s.fingerprint256),s=s.issuerCertificate;let c=s?.raw?new Tf(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function Gc(t,e,r){return new Promise(n=>{let o=sr.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 Ux(t){try{let e=await fetch(t);return e.ok?new Tf(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function _f(t,e=443,r=Cf){let n=`${t}:${e}`,o=Rf.get(n);if(o)return o;let i=Bx(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Rf.set(n,i),i}async function Bx(t,e,r){if(!If)return!1;let n=8e3;if(await Gc(t,e,n))return!0;let o=await Dx(t,e,n),i=sr.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=Mx(o);if(!c)break;let l=await Ux(c);if(!l)break;if(s.push(l.toString()),sr.setDefaultCACertificates([...i,...s]),await Gc(t,e,n))return r(`[tls] completed certificate chain for ${t} via AIA (+${s.length} intermediate cert(s))`),!0;if(l.subject===l.issuer)break;o=l}return Gc(t,e,n)}var If,Ef,Rf,Cf,jf=x(()=>{"use strict";Ye();If=typeof sr.getCACertificates=="function"&&typeof sr.setDefaultCACertificates=="function",Ef=!1,Rf=new Map,Cf=t=>console.warn(t)});function Mf(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function ft(t,e,r){Pf();let n={Authorization:`Bearer ${t.token}`,Accept:"application/json"};r?.body&&(n["Content-Type"]="application/json");let o=t.baseUrl+e,i={...r,headers:{...n,...r?.headers??{}}};try{return await fetch(o,i)}catch(s){if(Af(s)&&await _f(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function Fx(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Gx(){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 Kc(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=Gx(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await ft(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&&Fx(l.status,u)){await Nf(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await Nf(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function ar(t){let e;try{e=await ft(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 Df(t){try{let e=await ft(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function Kx(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=Of.get(o);if(i)return i;let s=await ft(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!s.ok)throw new Error(`yt resolveStateId ${e}: ${s.status} ${await s.text()}`);let c=(await s.json()).customFields.find(u=>u.name===n);if(!c)throw new Error(`yt: issue ${e} has no ${n} custom field`);let l=c.projectCustomField.bundle.values.find(u=>u.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${n} bundle for ${e}`);return Of.set(o,l.id),l.id}async function Uf(t,e,r,n=Ao){let o=await Kx(t,e,r,n);await Kc(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 Bf(t,e,r){return await(await Kc(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function Ff(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await Kc(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function Gf(t,e){let r=Lf.get(e);if(r)return r;let n=await ft(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!n.ok)throw new Error(`yt resolveProjectId: ${n.status} ${await n.text()}`);let i=(await n.json()).find(s=>s.shortName===e);if(!i)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return Lf.set(e,i.id),i.id}async function Kf(t,e,r,n,o,i=Ao){let s=await Gf(t,e),a=await ft(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:s},summary:r,description:n,customFields:[{name:i,$type:"StateIssueCustomField",value:{name:o,$type:"StateBundleElement"}}]})});if(!a.ok)throw new Error(`yt createIssue: ${a.status} ${await a.text()}`);let c=await a.json();return{id:c.id,key:c.idReadable}}async function Hf(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await ft(t,"/api/commands",{method:"POST",body:JSON.stringify({query:o,issues:[{idReadable:e}]})});if(!i.ok)throw new Error(`yt applyIssueLink (${o} on ${e}): ${i.status} ${await i.text()}`)}function Yf(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 Vf(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 zf(t,e){let r=e.stageField??Ao,n=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let c=e.columns.map(l=>`{${l}}`).join(", ");n.push(`${r}: ${c}`)}if(e.updatedSince){let c=new Date(e.updatedSince).toISOString().slice(0,10);n.push(`updated: ${c} .. *`)}e.assignee?n.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&n.push("has: Assignee");let o=n.join(" "),i=`/api/issues?query=${encodeURIComponent(o)}&fields=${qf}&$top=200`,s=await ft(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);let a=await s.json();if(e.columns&&e.columns.length>0&&a.length>0&&!a.some(l=>(l.customFields??[]).some(u=>u.name===r))){let l=[...new Set((a[0]?.customFields??[]).map(u=>u.name).filter(u=>!!u))];throw new Error(`youtrack.stage_field "${r}" does not exist in project ${e.projectKey} \u2014 YouTrack ignored the status filter and would have returned unrelated issues. `+(l.length>0?`Fields on the issues: ${l.join(", ")}.`:"The issues carry no custom fields at all."))}return a.map(c=>Zf(c,r))}async function Xf(t,e,r=Ao){let n=`/api/issues/${encodeURIComponent(e)}?fields=${qf}`,o=await ft(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Zf(await o.json(),r)}async function Jf(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${Wx}&$top=500`,o=await ft(t,n);if(!o.ok)throw new Error(`yt listComments ${e}: ${o.status} ${await o.text()}`);return(await o.json()).filter(s=>s.created>r).map(s=>{let a={id:s.id,issueId:e,author:s.author?.login??"unknown",body:s.text??"",createdAt:new Date(s.created).toISOString()},c=Yf(s.attachments);return c&&(a.attachments=c),a})}function qx(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 Zf(t,e=Ao){let r=t.customFields??[],n=r.find(l=>l.name===e),o=r.find(l=>l.name==="Assignee"),i=r.find(l=>l.name==="Type"),s={id:t.id,key:t.idReadable,title:t.summary,status:n?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(s.description=t.description),o?.value?.login&&(s.assignee=o.value.login),i?.value?.name&&(s.issueType=i.value.name),t.tags&&t.tags.length>0&&(s.tags=t.tags.map(l=>l.name));let a=Yf(t.attachments);a&&(s.attachments=a);let c=qx(t.links);return c&&(s.links=c),s}async function Qf(t,e){let r=await Yx(t,e);return r.length>0?r:Vx(t,e)}async function Yx(t,e){let r=await Gf(t,e),n=await ft(t,`/api/admin/projects/${encodeURIComponent(r)}/customFields?fields=$type,field(name),bundle(values(name,archived))&$top=100`);if(!n.ok)return[];let o=await n.json(),i=[];for(let s of o)s.$type==="StateProjectCustomField"&&s.field?.name&&i.push({name:s.field.name,values:em(s.bundle)});return i}async function Vx(t,e){let r=`project: ${e}`,n=await ft(t,`/api/issues?query=${encodeURIComponent(r)}&fields=customFields(name,$type,projectCustomField(bundle(values(name,archived))))&$top=1`);if(!n.ok)throw new Error(`yt fetchProjectStateFields ${e}: ${n.status} ${await n.text()}`);let o=await n.json(),i=[];for(let s of o[0]?.customFields??[])s.$type==="StateIssueCustomField"&&s.name&&i.push({name:s.name,values:em(s.projectCustomField?.bundle)});return i}function em(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var Nf,Ao,Of,Lf,Wf,Hx,qf,Wx,Ur=x(()=>{"use strict";jf();Nf=t=>new Promise(e=>setTimeout(e,t));Ao="Stage",Of=new Map;Lf=new Map;Wf="attachments(id,name,url,size,mimeType)",Hx="links(direction,linkType(name),issues(idReadable))",qf=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Wf},${Hx}`,Wx=`id,text,created,author(login),${Wf}`});function Et(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function In(t){return t instanceof pt}async function tm(t,e){let r=X(t),n=[],o=[],i=()=>Date.now();if(e?.trackerProvider==="internal")n.push({name:"tracker",ok:!0,detail:"built-in tracker"});else if(r?.youtrack?.url&&r.youtrack.token)try{let c=await ar({baseUrl:r.youtrack.url,token:r.youtrack.token});n.push({name:"youtrack",ok:!0}),o.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"youtrack",ok:!1,detail:Et(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:Et(c),checkedAt:i()})}else n.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),o.push({kind:"youtrack",present:!1,checkedAt:i()});let s=!1;if(r?.github?.token){s=!0;try{let c=await rr(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){In(c)?(n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"github",ok:!1,detail:Et(c)}),o.push({kind:"github",present:!0,ok:!1,detail:Et(c),checkedAt:i()}))}}else o.push({kind:"github",present:!1,checkedAt:i()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){s=!0;try{let c=await nr(r.bitbucket.email,r.bitbucket.apiToken);n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){In(c)?(n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"bitbucket",ok:!1,detail:Et(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:Et(c),checkedAt:i()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await or(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){In(c)?(n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"gitlab",ok:!1,detail:Et(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:Et(c),checkedAt:i()}))}}else o.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||n.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let u of e?.repos??[])if(u.host==="github")try{await Ui(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){In(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:Et(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await Ui(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){In(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:Et(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Ui(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){In(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:i()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:Et(l),checkedAt:i()})}else o.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:i()})}else o.push({kind:"contextWrite",present:!1,checkedAt:i()});let a=En(t);if(!a)n.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),o.push({kind:"claude",present:!1,checkedAt:i()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:i()});else{let c=await zt(a);if(c==="invalid"){let l="Claude refused this token \u2014 refresh it with `claude setup-token`";n.push({name:"claude",ok:!1,detail:l}),o.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function zt(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:zx,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 rm(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1000",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});if(n.status!==200)return null;let i=(await n.json())?.data;if(!Array.isArray(i))return null;let s=[];for(let a of i){let c=a?.id;if(typeof c!="string"||c.trim().length===0)continue;let l=a?.created_at;s.push({id:c,...typeof l=="string"?{createdAt:l}:{}})}return s}catch{return null}finally{clearTimeout(r)}}var zx,Cn=x(()=>{"use strict";me();Vt();Ur();zx="claude-haiku-4-5-20251001"});import Xx from"node:http";import Hc from"node:crypto";function Fi(){let t=Wc(Hc.randomBytes(32)),e=Wc(Hc.createHash("sha256").update(t).digest()),r=Wc(Hc.randomBytes(32));return{verifier:t,challenge:e,state:r}}function Yc(t){let e=new URL(Jx);return e.search=new URLSearchParams({response_type:"code",client_id:nm,redirect_uri:t.redirectUri,scope:Qx,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function tS(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 om(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 rS(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 Vc(t){let e=await fetch(Zx,{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:nm,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return rS(await e.json())}async function zc(t){let e=t.timeoutMs??eS,r=Xx.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=Yc({redirectUri:o,challenge:t.challenge,state:t.state}),s,a=new Promise((l,u)=>{s=setTimeout(()=>u(new Error("no-callback")),e),r.on("request",(p,d)=>{let f=new URL(p.url??"/",o);if(f.pathname!=="/callback"){d.statusCode=404,d.end();return}clearTimeout(s),d.setHeader("content-type","text/html"),d.end("<h3>Authorized \u2014 you can close this tab.</h3>");try{l(tS(f.searchParams,t.state))}catch(m){u(m)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>Vc({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function im(t){let e=await zc(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
27
+ ${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var nm,Jx,Zx,qc,Qx,eS,Wc,Xc=x(()=>{"use strict";nm="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Jx="https://platform.claude.com/oauth/authorize",Zx="https://platform.claude.com/v1/oauth/token",qc="https://platform.claude.com/oauth/code/callback",Qx="org:create_api_key user:profile user:inference",eS=12e4,Wc=t=>Buffer.from(t).toString("base64url")});import{spawn as nS}from"node:child_process";function Br(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=nS(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var Gi=x(()=>{"use strict"});import{existsSync as cr,mkdirSync as hm,readFileSync as Qc,writeFileSync as Pn}from"node:fs";import{homedir as pS}from"node:os";import{join as jt}from"node:path";import{simpleGit as fS}from"simple-git";function jo(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=jt(t,o);cr(s)||(Pn(s,i),r.push(o))}return r}function lr(t,e,r){let n=jt(pS(),".codepipe","profiles",t,"context-config");return hm(n,{recursive:!0}),Pn(jt(n,"project.yaml"),e.projectYaml),Pn(jt(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function Wi(t,e,r){if(cr(e))for(let n of An){let o=jt(e,n),i=jt(t,n);if(!(!cr(o)||cr(i)))try{Pn(i,Qc(o)),r.info(`[config] seeded local ${n} from the provisioning bundle`)}catch(s){r.warn(`[config] could not seed ${n}: ${s instanceof Error?s.message:String(s)}`)}}}function _n(t){let e=jt(t,".gitignore"),r=cr(e)?Qc(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(An.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
28
28
  `)?"":`
29
- `;return Cn(e,r+i+uS.join(`
29
+ `;return Pn(e,r+i+mS.join(`
30
30
  `)+`
31
- `),!0}async function fm(t,e){try{if(!ar(jt(t,".git")))return;let r=lS(t),n=(await r.raw(["ls-files","--",...Pn])).split(`
32
- `).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 rl(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 el(t){let e=new Map;for(let r of Pn){let n=jt(t,r);ar(n)&&e.set(r,Qc(n))}return e}function tl(t,e){pm(t,{recursive:!0});for(let[r,n]of e){let o=jt(t,r);ar(o)||Cn(o,n)}}var Pn,uS,zt=x(()=>{"use strict";mt();Pn=["project.yaml","regimen.yaml"];uS=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as dS,mkdirSync as pS,rmSync as fS,writeFileSync as nl}from"node:fs";import{dirname as mS,isAbsolute as hS,join as gm,normalize as Vi}from"node:path";import{simpleGit as ym}from"simple-git";async function ol(t,e){let r=Vi(t),o=(Yi.get(r)??Promise.resolve()).catch(()=>{}).then(e);Yi.set(r,o);try{return await o}finally{Yi.get(r)===o&&Yi.delete(r)}}async function Ce(t,e,r){return ol(t,()=>il(t,e,r))}async function il(t,e,r){if(!dS(gm(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=Re(t,a.path);if(a.deleted){fS(c,{force:!0});continue}pS(mS(c),{recursive:!0}),a.encoding==="base64"?nl(c,Buffer.from(a.content,"base64")):nl(c,a.content)}let n=ym(t),o=e.filter(a=>!a.deleted).map(a=>a.path),i=e.filter(a=>a.deleted).map(a=>a.path);for(let a=0;a<o.length;a+=qi)await n.raw(["add","-A","-f","--",...o.slice(a,a+qi)]);for(let a=0;a<i.length;a+=qi)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...i.slice(a,a+qi)]);await n.raw(["reset","-q","--",...Pn]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await rl(t))}async function rl(t){let e=ym(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=mm;n++){try{await e.push();return}catch(i){r=i}await e.fetch().catch(()=>{});let o=(await e.revparse(["--abbrev-ref","HEAD"])).trim();try{await e.rebase([`origin/${o}`])}catch{let i=await bS(e);if(i.length>0&&i.every(a=>gS.has(a)||hm.test(a)||yS.test(a))){for(let a of i)hm.test(a)?await wS(e,t,a):await e.raw(["checkout","--theirs","--",a]);await e.add(i),await e.raw(["-c","core.editor=true","rebase","--continue"])}else throw await e.rebase(["--abort"]).catch(()=>{}),new Error(`context push: rebase conflict in ${i.join(", ")||"unknown files"} \u2014 concurrent writers edited the same entry; resolve manually in the Context Repo`)}}throw new Error(`context push failed after ${mm} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function wS(t,e,r){let n=async s=>await t.raw(["show",`:${s}:${r}`]).catch(()=>""),o=new Map;for(let s of[await n(2),await n(3)])for(let a of s.split(`
31
+ `),!0}async function gm(t,e){try{if(!cr(jt(t,".git")))return;let r=fS(t),n=(await r.raw(["ls-files","--",...An])).split(`
32
+ `).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;_n(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 rl(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 el(t){let e=new Map;for(let r of An){let n=jt(t,r);cr(n)&&e.set(r,Qc(n))}return e}function tl(t,e){hm(t,{recursive:!0});for(let[r,n]of e){let o=jt(t,r);cr(o)||Pn(o,n)}}var An,mS,Xt=x(()=>{"use strict";mt();An=["project.yaml","regimen.yaml"];mS=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as hS,mkdirSync as gS,rmSync as yS,writeFileSync as nl}from"node:fs";import{dirname as wS,isAbsolute as bS,join as bm,normalize as Vi}from"node:path";import{simpleGit as km}from"simple-git";async function ol(t,e){let r=Vi(t),o=(Yi.get(r)??Promise.resolve()).catch(()=>{}).then(e);Yi.set(r,o);try{return await o}finally{Yi.get(r)===o&&Yi.delete(r)}}async function Ce(t,e,r){return ol(t,()=>il(t,e,r))}async function il(t,e,r){if(!hS(bm(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=Re(t,a.path);if(a.deleted){yS(c,{force:!0});continue}gS(wS(c),{recursive:!0}),a.encoding==="base64"?nl(c,Buffer.from(a.content,"base64")):nl(c,a.content)}let n=km(t),o=e.filter(a=>!a.deleted).map(a=>a.path),i=e.filter(a=>a.deleted).map(a=>a.path);for(let a=0;a<o.length;a+=qi)await n.raw(["add","-A","-f","--",...o.slice(a,a+qi)]);for(let a=0;a<i.length;a+=qi)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...i.slice(a,a+qi)]);await n.raw(["reset","-q","--",...An]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await rl(t))}async function rl(t){let e=km(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=ym;n++){try{await e.push();return}catch(i){r=i}await e.fetch().catch(()=>{});let o=(await e.revparse(["--abbrev-ref","HEAD"])).trim();try{await e.rebase([`origin/${o}`])}catch{let i=await xS(e);if(i.length>0&&i.every(a=>kS.has(a)||wm.test(a)||vS.test(a))){for(let a of i)wm.test(a)?await $S(e,t,a):await e.raw(["checkout","--theirs","--",a]);await e.add(i),await e.raw(["-c","core.editor=true","rebase","--continue"])}else throw await e.rebase(["--abort"]).catch(()=>{}),new Error(`context push: rebase conflict in ${i.join(", ")||"unknown files"} \u2014 concurrent writers edited the same entry; resolve manually in the Context Repo`)}}throw new Error(`context push failed after ${ym} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function $S(t,e,r){let n=async s=>await t.raw(["show",`:${s}:${r}`]).catch(()=>""),o=new Map;for(let s of[await n(2),await n(3)])for(let a of s.split(`
33
33
  `)){let c=a.trim();if(c)try{let l=JSON.parse(c);if(typeof l.id!="string")continue;o.has(l.id)||o.set(l.id,{raw:c,createdAt:typeof l.createdAt=="string"?l.createdAt:""})}catch{}}let i=[...o.values()].sort((s,a)=>s.createdAt.localeCompare(a.createdAt)).map(s=>s.raw);nl(Re(e,r),i.join(`
34
34
  `)+(i.length>0?`
35
- `:""))}async function bS(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
36
- `).map(r=>r.trim()).filter(Boolean)}function Re(t,e){if(hS(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=Vi(gm(t,e)),n=Vi(t+"/");if(r!==Vi(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var mm,gS,yS,hm,qi,Yi,mt=x(()=>{"use strict";zt();mm=3,gS=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),yS=/^model\/derived\//,hm=/^tasks\/[^/]+\/comments\.jsonl$/,qi=500,Yi=new Map});import{cpSync as IS,existsSync as jo,mkdirSync as vm,readFileSync as CS,readdirSync as PS,rmSync as $m,statSync as AS,writeFileSync as _S}from"node:fs";import{join as lr}from"node:path";function _n(t,e,r){let n=lr(t,"skills"),o=lr(e,".claude","skills"),i=lr(o,jS),s=NS(i),a={written:[],removed:[],skipped:[]},c=OS(n);for(let u of s)c.includes(u)||($m(lr(o,u),{recursive:!0,force:!0}),a.removed.push(u));let l=[];for(let u of c){let p=lr(o,u);if(jo(p)&&!s.includes(u)){a.skipped.push(u);continue}vm(o,{recursive:!0}),$m(p,{recursive:!0,force:!0}),IS(lr(n,u),p,{recursive:!0}),l.push(u),a.written.push(u)}(l.length>0||a.removed.length>0||jo(i))&&(vm(o,{recursive:!0}),_S(i,JSON.stringify({managed:l.sort()},null,2)+`
37
- `)),(a.written.length>0||a.removed.length>0)&&r.info(`[skills] context \u2192 .claude/skills: ${a.written.length} written`+(a.removed.length>0?`, ${a.removed.length} removed`:""));for(let u of a.skipped)r.warn(`[skills] "${u}" exists in .claude/skills but is not managed by CodePipe \u2014 your copy wins; rename one of them to get the context version`);return a}function NS(t){if(!jo(t))return[];try{let e=JSON.parse(CS(t,"utf-8"));return Array.isArray(e.managed)?e.managed.filter(r=>typeof r=="string"):[]}catch{return[]}}function OS(t){return jo(t)?PS(t).filter(e=>{if(e.startsWith("."))return!1;let r=lr(t,e);try{return AS(r).isDirectory()&&jo(lr(r,"SKILL.md"))}catch{return!1}}):[]}var jS,zi=x(()=>{"use strict";jS=".codepipe-managed.json"});import{existsSync as ur,readFileSync as jn,readdirSync as Rm}from"node:fs";import{join as al}from"node:path";import{simpleGit as Tm}from"simple-git";import{parse as Im}from"yaml";function Cm(t){try{let e=Re(t,Ro);if(!ur(e))return null;let r=Im(jn(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!Nr.test(n)?null:{prefix:n}}catch{return null}}function Pm(t){return`# Built-in tracker configuration \u2014 shared by every team member.
35
+ `:""))}async function xS(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
36
+ `).map(r=>r.trim()).filter(Boolean)}function Re(t,e){if(bS(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=Vi(bm(t,e)),n=Vi(t+"/");if(r!==Vi(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var ym,kS,vS,wm,qi,Yi,mt=x(()=>{"use strict";Xt();ym=3,kS=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),vS=/^model\/derived\//,wm=/^tasks\/[^/]+\/comments\.jsonl$/,qi=500,Yi=new Map});import{cpSync as _S,existsSync as No,mkdirSync as Sm,readFileSync as jS,readdirSync as NS,rmSync as Em,statSync as OS,writeFileSync as LS}from"node:fs";import{join as ur}from"node:path";function jn(t,e,r){let n=ur(t,"skills"),o=ur(e,".claude","skills"),i=ur(o,MS),s=DS(i),a={written:[],removed:[],skipped:[]},c=US(n);for(let u of s)c.includes(u)||(Em(ur(o,u),{recursive:!0,force:!0}),a.removed.push(u));let l=[];for(let u of c){let p=ur(o,u);if(No(p)&&!s.includes(u)){a.skipped.push(u);continue}Sm(o,{recursive:!0}),Em(p,{recursive:!0,force:!0}),_S(ur(n,u),p,{recursive:!0}),l.push(u),a.written.push(u)}(l.length>0||a.removed.length>0||No(i))&&(Sm(o,{recursive:!0}),LS(i,JSON.stringify({managed:l.sort()},null,2)+`
37
+ `)),(a.written.length>0||a.removed.length>0)&&r.info(`[skills] context \u2192 .claude/skills: ${a.written.length} written`+(a.removed.length>0?`, ${a.removed.length} removed`:""));for(let u of a.skipped)r.warn(`[skills] "${u}" exists in .claude/skills but is not managed by CodePipe \u2014 your copy wins; rename one of them to get the context version`);return a}function DS(t){if(!No(t))return[];try{let e=JSON.parse(jS(t,"utf-8"));return Array.isArray(e.managed)?e.managed.filter(r=>typeof r=="string"):[]}catch{return[]}}function US(t){return No(t)?NS(t).filter(e=>{if(e.startsWith("."))return!1;let r=ur(t,e);try{return OS(r).isDirectory()&&No(ur(r,"SKILL.md"))}catch{return!1}}):[]}var MS,zi=x(()=>{"use strict";MS=".codepipe-managed.json"});import{existsSync as dr,readFileSync as Nn,readdirSync as Cm}from"node:fs";import{join as al}from"node:path";import{simpleGit as Pm}from"simple-git";import{parse as Am}from"yaml";function _m(t){try{let e=Re(t,To);if(!dr(e))return null;let r=Am(Nn(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!Or.test(n)?null:{prefix:n}}catch{return null}}function jm(t){return`# Built-in tracker configuration \u2014 shared by every team member.
38
38
  # The issue-key prefix (<PREFIX>-<N>). Fixed at project init: changing it
39
39
  # later would orphan existing tasks/<KEY>/ directories.
40
40
  prefix: ${t}
@@ -43,12 +43,12 @@ prefix: ${t}
43
43
  # Backlog | To Do | In Progress | Review | Done | Rejected
44
44
  # A configurable status set / pipeline mapping is a planned extension.
45
45
  `}function cl(t=0){return`${t}
46
- `}function US(t){return t==="depends_on"||t==="subtask"}function BS(t){let e;try{e=Im(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=Rc.includes(r.type)?r.type:Eo,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;US(l.type)&&typeof l.target=="string"&&l.target&&o.push({type:l.type,targetKey:l.target})}let i=typeof r.created=="string"?r.created:new Date(0).toISOString(),s=typeof r.updated=="string"?r.updated:i,a=typeof r.assignee=="string"&&r.assignee.trim().length>0?r.assignee.trim():void 0;return{key:r.key,title:r.title,type:n,status:typeof r.status=="string"&&r.status?r.status:"Backlog",...a?{assignee:a}:{},links:o,created:i,updated:s}}function ll(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(`
46
+ `}function KS(t){return t==="depends_on"||t==="subtask"}function HS(t){let e;try{e=Am(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=Rc.includes(r.type)?r.type:Ro,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;KS(l.type)&&typeof l.target=="string"&&l.target&&o.push({type:l.type,targetKey:l.target})}let i=typeof r.created=="string"?r.created:new Date(0).toISOString(),s=typeof r.updated=="string"?r.updated:i,a=typeof r.assignee=="string"&&r.assignee.trim().length>0?r.assignee.trim():void 0;return{key:r.key,title:r.title,type:n,status:typeof r.status=="string"&&r.status?r.status:"Backlog",...a?{assignee:a}:{},links:o,created:i,updated:s}}function ll(t){let e=[`key: ${t.key}`,`title: ${JSON.stringify(t.title)}`,`type: ${t.type}`,`status: ${JSON.stringify(t.status)}`];if(t.assignee&&e.push(`assignee: ${JSON.stringify(t.assignee)}`),t.links.length>0){e.push("links:");for(let r of t.links)e.push(` - type: ${r.type}`,` target: ${r.targetKey}`)}return e.push(`created: ${t.created}`,`updated: ${t.updated}`),e.join(`
47
47
  `)+`
48
- `}function Oo(t,e){let r=Re(t,bn(e));return ur(r)?BS(jn(r,"utf-8")):null}function Am(t){let e=al(t,"tasks");if(!ur(e))return[];let r=[];for(let n of Rm(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=Oo(t,n.name);o&&r.push(o)}return r}function FS(t,e){let r=Re(t,`tasks/${e}/task.md`);if(ur(r))return To(jn(r,"utf-8"))}function Lo(t,e,r={}){let n=r.withDescription?FS(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:GS(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function GS(t){return t.charAt(0).toUpperCase()+t.slice(1)}function KS(t){let e=Re(t,wn);if(!ur(e))return 0;let r=Number.parseInt(jn(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function HS(t,e){let r=al(t,"tasks");if(!ur(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of Rm(r,{withFileTypes:!0})){if(!i.isDirectory())continue;let s=n.exec(i.name);if(!s)continue;let a=Number.parseInt(s[1],10);Number.isFinite(a)&&a>o&&(o=a)}return o}function WS(t,e){return Math.max(KS(t),HS(t,e))+1}async function _m(t,e,r,n){return ol(t,()=>qS(t,e,r,n))}async function qS(t,e,r,n){if(!ur(al(t,".git")))throw new Error(`context repo clone not found at ${t}`);await No(t);let o=null;for(let i=0;i<Em;i++){let s=WS(t,e),a=`${e}-${s}`,c=[...r(a),{path:wn,content:cl(s)}];try{return await il(t,c,n(a)),a}catch(l){if(o=l,await VS(t,n(a)),await No(t),YS(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${Em} attempts: ${o instanceof Error?o.message:String(o)}`)}function YS(t,e){for(let r of e){let n=Re(t,r.path);if(!ur(n)||(r.encoding==="base64"?jn(n).toString("base64"):jn(n,"utf-8"))!==r.content)return!1}return!0}async function No(t){let e=Tm(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 VS(t,e){let r=Tm(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
48
+ `}function Lo(t,e){let r=Re(t,kn(e));return dr(r)?HS(Nn(r,"utf-8")):null}function Nm(t){let e=al(t,"tasks");if(!dr(e))return[];let r=[];for(let n of Cm(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=Lo(t,n.name);o&&r.push(o)}return r}function WS(t,e){let r=Re(t,`tasks/${e}/task.md`);if(dr(r))return Io(Nn(r,"utf-8"))}function Mo(t,e,r={}){let n=r.withDescription?WS(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:qS(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function qS(t){return t.charAt(0).toUpperCase()+t.slice(1)}function YS(t){let e=Re(t,bn);if(!dr(e))return 0;let r=Number.parseInt(Nn(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function VS(t,e){let r=al(t,"tasks");if(!dr(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of Cm(r,{withFileTypes:!0})){if(!i.isDirectory())continue;let s=n.exec(i.name);if(!s)continue;let a=Number.parseInt(s[1],10);Number.isFinite(a)&&a>o&&(o=a)}return o}function zS(t,e){return Math.max(YS(t),VS(t,e))+1}async function Om(t,e,r,n){return ol(t,()=>XS(t,e,r,n))}async function XS(t,e,r,n){if(!dr(al(t,".git")))throw new Error(`context repo clone not found at ${t}`);await Oo(t);let o=null;for(let i=0;i<Im;i++){let s=zS(t,e),a=`${e}-${s}`,c=[...r(a),{path:bn,content:cl(s)}];try{return await il(t,c,n(a)),a}catch(l){if(o=l,await ZS(t,n(a)),await Oo(t),JS(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${Im} attempts: ${o instanceof Error?o.message:String(o)}`)}function JS(t,e){for(let r of e){let n=Re(t,r.path);if(!dr(n)||(r.encoding==="base64"?Nn(n).toString("base64"):Nn(n,"utf-8"))!==r.content)return!1}return!0}async function Oo(t){let e=Pm(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 ZS(t,e){let r=Pm(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
49
49
  `)[0]||!(await r.raw(["log","@{u}..HEAD","--pretty=%s"]).catch(()=>"")).trim().split(`
50
50
  `).some(i=>i.trim()===e.split(`
51
- `)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var Em,Ji=x(()=>{"use strict";M();mt();Em=5});function Nn(t,e,r,n){return[{path:"README.md",content:cE(t,e)},{path:".gitignore",content:eE()},{path:"CLAUDE.md",content:rE(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:tE()},{path:"knowledge/README.md",content:nE()},{path:"knowledge/build.yaml",content:aE()},{path:"actions/README.md",content:oE()},{path:"roles/README.md",content:iE()},{path:"skills/README.md",content:sE()},{path:"model/README.md",content:zS()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:QS()},{path:"adr/README.md",content:XS()},{path:"adr/0000-template.md",content:JS()},{path:"adr/INDEX.md",content:ZS()},{path:vt,content:ho()},...t.trackerProvider==="internal"?[{path:Ro,content:Pm(t.youtrackProjectKey??Ci)},{path:wn,content:cl()}]:[]]}function zS(){return`# model/ \u2014 the project map
51
+ `)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var Im,Ji=x(()=>{"use strict";M();mt();Im=5});function On(t,e,r,n){return[{path:"README.md",content:pE(t,e)},{path:".gitignore",content:oE()},{path:"CLAUDE.md",content:sE(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:iE()},{path:"knowledge/README.md",content:aE()},{path:"knowledge/build.yaml",content:dE()},{path:"actions/README.md",content:cE()},{path:"roles/README.md",content:lE()},{path:"skills/README.md",content:uE()},{path:"model/README.md",content:QS()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:nE()},{path:"adr/README.md",content:eE()},{path:"adr/0000-template.md",content:tE()},{path:"adr/INDEX.md",content:rE()},{path:vt,content:go()},...t.trackerProvider==="internal"?[{path:To,content:jm(t.youtrackProjectKey??Ci)},{path:bn,content:cl()}]:[]]}function QS(){return`# model/ \u2014 the project map
52
52
 
53
53
  A graph of the project built from **git history and task artifacts**: files
54
54
  and directories connected by the fact of changing together and the fact of
@@ -75,7 +75,7 @@ asset \u2014 treat it like \`knowledge/\`.
75
75
 
76
76
  Every YAML file carries \`modelFormatVersion\`; a reader that meets a
77
77
  different version treats it as "rebuild needed", not as an error.
78
- `}function XS(){return`# ADR \u2014 architecture decision records
78
+ `}function eE(){return`# ADR \u2014 architecture decision records
79
79
 
80
80
  Accepted architectural decisions of this project \u2014 its **framework**. The
81
81
  agent reads this section (start with \`INDEX.md\`) at the beginning of every
@@ -103,7 +103,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
103
103
  canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
104
104
  is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
105
105
  open a PR to this repository.
106
- `}function JS(){return`# ADR-NNNN: <title>
106
+ `}function tE(){return`# ADR-NNNN: <title>
107
107
 
108
108
  - **Status:** accepted | superseded by ADR-NNNN
109
109
  - **Date:** YYYY-MM-DD
@@ -125,12 +125,12 @@ What becomes easier, what becomes harder, what future tasks must keep doing.
125
125
  ## Alternatives considered
126
126
 
127
127
  - **<alternative>** \u2014 why it was rejected.
128
- `}function ZS(){return`# ADR index
128
+ `}function rE(){return`# ADR index
129
129
 
130
130
  <!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->
131
131
 
132
132
  (no accepted ADRs yet)
133
- `}function QS(){return`# Audit
133
+ `}function nE(){return`# Audit
134
134
 
135
135
  Pipeline event logs. Naming is per-writer: each codepipe
136
136
  project appends only to its own file \u2014
@@ -139,14 +139,14 @@ project appends only to its own file \u2014
139
139
 
140
140
  \u2014 so several team members' CLIs never contend on one file. Do not create a
141
141
  shared aggregate here.
142
- `}function Nt(t,e,r,n,o=tt,i){let s=t.trackerProvider==="internal";return{projectYaml:s?lE(t):uE(t,r,n),regimenYaml:dE(t.automationLevel,s?!0:e,s,o,i)}}function eE(){return`# codepipe project config is local to each member's workspace
142
+ `}function Nt(t,e,r,n,o=tt,i){let s=t.trackerProvider==="internal";return{projectYaml:s?fE(t):mE(t,r,n),regimenYaml:hE(t.automationLevel,s?!0:e,s,o,i)}}function oE(){return`# codepipe project config is local to each member's workspace
143
143
  project.yaml
144
144
  regimen.yaml
145
145
 
146
146
  # codepipe runtime
147
147
  session.log
148
148
  apply-queue.json
149
- `}function tE(){return`# Index prompt
149
+ `}function iE(){return`# Index prompt
150
150
 
151
151
  You are the **Indexer** agent on the CodePipe pipeline. Your one job is to build a
152
152
  navigation map of this project's repositories and save it to the Context Repo, so
@@ -203,7 +203,7 @@ current working directory; write nothing else under the Context Repo.
203
203
  Keep both durable and skimmable \u2014 they are read at the start of every future
204
204
  task. Prefer structure (headings, bullet lists) over prose. If a repository is
205
205
  empty or unavailable, say so briefly rather than inventing content.
206
- `}function rE(t){return`# Project context for the CodePipe agent
206
+ `}function sE(t){return`# Project context for the CodePipe agent
207
207
 
208
208
  Instructions for AI agents working on **${t.name}** tasks. Claude Code
209
209
  auto-loads this file when the Context Repo is mounted. Keep it short and
@@ -231,7 +231,7 @@ project's architectural invariants: read them at the start of a task and treat
231
231
  them as binding. New or changed decisions do **not** go here directly \u2014 during
232
232
  analysis you draft them as task artifacts, and they are promoted into \`adr/\`
233
233
  only after the analysis is approved.
234
- `}function nE(){return`# Knowledge
234
+ `}function aE(){return`# Knowledge
235
235
 
236
236
  Durable, reusable notes about this project \u2014 the CodePipe agent's long-lived
237
237
  **memory** across tasks. Architectural decisions, domain rules,
@@ -248,7 +248,7 @@ Keep each note in its own file \u2014 never grow one shared aggregate \u2014 so
248
248
  concurrent commits touch different files and rebase cleanly. \`INDEX.md\` is
249
249
  REGENERATED from the entries by the index job: don't hand-edit it, and treat
250
250
  any merge conflict in it as noise (either side converges on the next run).
251
- `}function oE(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
251
+ `}function cE(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
252
252
 
253
253
  One \`<id>.yml\` per action. Every file here appears as a button on the
254
254
  project's **RUN** tab; an action with \`params\` opens a small wizard first.
@@ -287,7 +287,7 @@ steps:
287
287
  Parameter values are passed to the commands **only as env vars** \u2014 reference
288
288
  them as \`$INPUT_<NAME>\` in \`run\`; they are never substituted into the
289
289
  command text itself.
290
- `}function iE(){return`# roles/ \u2014 who reviews your work
290
+ `}function lE(){return`# roles/ \u2014 who reviews your work
291
291
 
292
292
  A **role** is a critic with a narrow view and its own curated context: one
293
293
  \`<name>.md\` per role. Roles review a plan before the work starts, review the
@@ -315,7 +315,7 @@ You are the security critic. \u2026the body is the role's prompt\u2026
315
315
 
316
316
  Keep \`refs\` short and specific: the value of a role is a NARROW view, and
317
317
  "give it everything" is exactly the failure this design avoids.
318
- `}function sE(){return`# skills/ \u2014 procedures the agent can invoke
318
+ `}function uE(){return`# skills/ \u2014 procedures the agent can invoke
319
319
 
320
320
  A **skill** is a directory with a \`SKILL.md\`: a description of when to use it,
321
321
  a body with the steps, and any files the steps need beside it (scripts,
@@ -374,7 +374,7 @@ A third-party marketplace **must** name a full commit sha: its skills run beside
374
374
  your checked-out code with the agent's credentials, and a branch would let that
375
375
  code change between two runs of the same task. Nothing from a marketplace is
376
376
  active until it is listed in \`plugins\`.
377
- `}function aE(){return`# BUILD phase config. Discovered & maintained by the agent.
377
+ `}function dE(){return`# BUILD phase config. Discovered & maintained by the agent.
378
378
  # Steps run in a rootless Podman container in the SANDBOX, before the PR.
379
379
  # Success = every step exits 0. Credentials are NOT available inside the container.
380
380
  #
@@ -390,7 +390,7 @@ active until it is listed in \`plugins\`.
390
390
  # - name: test
391
391
  # run: npm test
392
392
  # timeout_sec: 600 # per-step timeout (optional, default 600)
393
- `}function cE(t,e){return`# ${e.name}
393
+ `}function pE(t,e){return`# ${e.name}
394
394
 
395
395
  Context Repo for the **${t.name}** project (CodePipe).
396
396
 
@@ -416,7 +416,7 @@ PRs to this repository (and the agent also writes to \`knowledge/\` and
416
416
  pipeline \u2014 don't edit them by hand.
417
417
 
418
418
  Automation level: **${t.automationLevel}**.
419
- `}function lE(t){return`# Project description for CodePipe.
419
+ `}function fE(t){return`# Project description for CodePipe.
420
420
  id: ${t.projectId}
421
421
  name: ${t.name}
422
422
 
@@ -441,9 +441,9 @@ adapters:
441
441
  # Branch (must keep the <TASK_ID> placeholder).
442
442
  branch:
443
443
  pattern: codepipe/<TASK_ID>
444
- ${jm()}${Nm(t)}
444
+ ${Lm()}${Mm(t)}
445
445
  repos:
446
- ${Om(t)}
446
+ ${Dm(t)}
447
447
  # A repo may declare a mirror \u2014 a repository CodePipe owns that stands in for
448
448
  # origin for the whole pipeline: task branches, PRs and merges happen there and
449
449
  # your own repository is never written. All-or-nothing: either every repo
@@ -453,7 +453,7 @@ ${Om(t)}
453
453
  # host: github
454
454
  # owner: your-org
455
455
  # repo: <project>-api-mirror
456
- `}function jm(){return`
456
+ `}function Lm(){return`
457
457
  # Git workflow. Omit this whole section for the default single-branch flow
458
458
  # (\`simple\`) \u2014 nothing changes from today. Presets bind branch ROLES to your
459
459
  # real branch names (names differ across projects: develop vs dev, main vs a
@@ -468,21 +468,21 @@ ${Om(t)}
468
468
  # integration: develop
469
469
  # stable: master
470
470
  # # release_pattern: "release/*" # with flow: release
471
- `}function Nm(t){let e=t.language;return!e||Object.keys(e).length===0?"":`
471
+ `}function Mm(t){let e=t.language;return!e||Object.keys(e).length===0?"":`
472
472
  # Languages the agent writes in, per area. \`auto\` = mirror the language of
473
473
  # the user's material. Also editable from the dashboard: project card \u2192
474
474
  # Settings \u2192 Language.
475
475
  language:
476
476
  ${Object.entries(e).map(([n,o])=>` ${n}: ${o}`).join(`
477
477
  `)}
478
- `}function Om(t){return t.repos.length===0?` [] # add repos here
478
+ `}function Dm(t){return t.repos.length===0?` [] # add repos here
479
479
  `:t.repos.map(e=>` - name: ${e.name}
480
480
  host: ${e.host}
481
481
  owner: ${e.owner}
482
482
  repo: ${e.repoName}
483
483
  mount_as: ${e.mountAs??e.name}`+(e.defaultBranch?`
484
484
  default_branch: ${e.defaultBranch}`:"")).join(`
485
- `)}function uE(t,e,r){let n=e?`
485
+ `)}function mE(t,e,r){let n=e?`
486
486
  tracker_url: ${e}`:`
487
487
  # tracker_url: https://your.youtrack.cloud`,o=r?`require_assignee: true
488
488
  assignee: ${r}`:`require_assignee: false
@@ -530,7 +530,7 @@ ${Object.entries(e).map(([n,o])=>` ${n}: ${o}`).join(`
530
530
  # non-empty assignee. assignee only takes effect when require_assignee=true.
531
531
  ${o}`:` # project_key: \u2026
532
532
  # tracker_url: https://your.youtrack.cloud
533
- poll_interval_sec: 60`,s=Om(t);return`# Project description for CodePipe.
533
+ poll_interval_sec: 60`,s=Dm(t);return`# Project description for CodePipe.
534
534
  id: ${t.projectId}
535
535
  name: ${t.name}
536
536
 
@@ -562,64 +562,41 @@ adapters:
562
562
  # Branch (must keep the <TASK_ID> placeholder).
563
563
  branch:
564
564
  pattern: codepipe/<TASK_ID>
565
- ${jm()}${Nm(t)}
565
+ ${Lm()}${Mm(t)}
566
566
  repos:
567
567
  ${s}
568
- `}function dE(t,e,r=!1,n=tt,o){let i=t==="full",s=e?"true":"false",a=o?` # Model selection. This project's Claude subscription did not include every
568
+ `}function hE(t,e,r=!1,n=tt,o){let i=t==="full",s=e?"true":"false",a=o?` # Model selection. This project's Claude subscription did not include every
569
569
  # model in the recommended per-role split, so CodePipe set a single default
570
570
  # your subscription can serve for all roles. Tune per role later from the
571
571
  # dashboard (Project Settings \u2192 llm.models) or by editing this file.
572
572
  models:
573
- default: ${o}`:` # Per-role model selection (Claude cost optimization). Run cheap,
574
- # mechanical roles on a smaller model and architectural / code roles on the
575
- # capable one. Values are aliases (opus | sonnet | haiku) \u2014 Claude Code
576
- # resolves each to the current version of that tier \u2014 or a pinned id
577
- # (e.g. claude-opus-4-8). The per-role values below are the recommended
578
- # defaults and are what applies to each listed role when this whole section
579
- # is omitted. 'default' is a cheap catch-all set on top of them: without this
580
- # section an unlisted role would fall back to its own recommended default,
581
- # but an explicit 'default' overrides those for every role not spelled out.
582
- models:
583
- # Catch-all for any role not listed below (incl. future roles) \u2014 cheap by
584
- # default; the reasoning roles opt into opus explicitly.
585
- default: sonnet
586
- # Architectural analysis of the task.
587
- analyze: opus
588
- # Writing the implementation.
589
- implement: opus
590
- # Resolving merge conflicts coherently is code reasoning.
591
- resolve-conflict: opus
592
- # Re-implementing after rework feedback.
593
- rework: opus
594
- # Informational implementation estimate.
595
- estimate: sonnet
596
- # Driving / repairing the lint/build/test run (BUILD phase) \u2014 mechanical.
597
- build: haiku
598
- # First BUILD of the project: discover build tooling and write
599
- # knowledge/build.yaml (reused for the project's whole life) \u2014 worth opus.
600
- build-discovery: opus
601
- # Reviewing the implemented change before the PR (CODE_REVIEW phase).
602
- code-review: opus
603
- # Verifying existing review findings is narrower than reviewing \u2014 cheaper.
604
- code-review-verify: sonnet
605
- # Drafting a new issue from the Quick-task panel.
606
- draft: sonnet
607
- # One-shot repository indexing at registration.
608
- index: opus
609
- # Retrospective ADR backfill reconstructs decisions from code \u2014 deep reasoning.
610
- backfill: opus
611
- # Decomposing a context into a package of tasks is architectural reasoning.
612
- analysis: opus
613
- # The interactive draft chat reasons about the project and holds a dialogue.
614
- chat: opus
615
- # The project-configuration chat shapes a validated ConfigProposal in a dialogue.
616
- config: opus
617
- # The observer reads a whole batch against accepted decisions \u2014 runs once per batch.
618
- observer: opus
619
- # The council unblocks a task; a wrong answer is paid for by every later phase.
620
- council: opus
621
- # Deriving how a human would check the change is judgement, not transcription.
622
- testing: opus`;return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
573
+ default: ${o}`:` # Per-role model selection. COMMENTED OUT on purpose: models come from
574
+ # the workflow preset above (explicit keys here would override the preset \u2014
575
+ # that is exactly what this section is for when you need it). Values are
576
+ # aliases (opus | sonnet | haiku) \u2014 Claude Code resolves each to the current
577
+ # version of that tier \u2014 or a pinned id (e.g. claude-opus-4-8). 'default'
578
+ # is a catch-all that overrides the preset and the recommended defaults for
579
+ # every role not spelled out.
580
+ # models:
581
+ # default: sonnet
582
+ # analyze: opus # architectural analysis of the task
583
+ # implement: opus # writing the implementation
584
+ # resolve-conflict: opus # resolving merge conflicts is code reasoning
585
+ # rework: opus # re-implementing after rework feedback
586
+ # estimate: sonnet # informational implementation estimate
587
+ # build: haiku # mechanical run of the recorded build steps
588
+ # build-discovery: opus # first BUILD: discover tooling, write build.yaml
589
+ # code-review: opus # reviewing the change before the PR
590
+ # code-review-verify: sonnet # verifying findings is narrower \u2014 cheaper
591
+ # draft: sonnet # drafting a new issue from the Quick-task panel
592
+ # index: opus # one-shot repository indexing at registration
593
+ # backfill: opus # retrospective ADR backfill \u2014 deep reasoning
594
+ # analysis: opus # decomposing a context into a package of tasks
595
+ # chat: opus # the interactive draft chat
596
+ # config: opus # the project-configuration chat
597
+ # observer: opus # reads a whole batch \u2014 runs once per batch
598
+ # council: opus # unblocks a task; a wrong answer compounds
599
+ # testing: opus # deriving how a human would check the change`;return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
623
600
  automation:
624
601
  level: ${t}
625
602
 
@@ -662,6 +639,23 @@ gates:
662
639
  # task starts the pipeline immediately. Orthogonal to automation.level.
663
640
  require_approval: true
664
641
 
642
+ workflow:
643
+ # How much pipeline a task gets. A preset is a LAYER of defaults \u2014 any
644
+ # explicit setting in this file always wins over it.
645
+ # express \u2014 no analysis phase, no review: one implementation session on
646
+ # the capable model (cheapest; for small, clearly-stated tasks).
647
+ # balanced \u2014 every phase, cheaper models for implementation and review.
648
+ # full \u2014 the classic pipeline on the capable model everywhere.
649
+ preset: balanced
650
+
651
+ # The dedicated analysis pass (plan + open questions) before implementation.
652
+ # Absent = the preset decides (express: off). An explicit value overrides the
653
+ # preset. NOTE: the section header stays commented too \u2014 a YAML section with
654
+ # only comments inside parses as null, which the settings editor cannot write
655
+ # a key into.
656
+ # analysis:
657
+ # enabled: true
658
+
665
659
  estimate:
666
660
  # Optional ESTIMATING phase (runs after ANALYZING). Informational only \u2014
667
661
  # nothing downstream depends on it. Off by default; set true to enable.
@@ -779,36 +773,36 @@ ${a}
779
773
  # sandbox quota (how many runners the account may occupy), enforced by the HUB
780
774
  # and sized on the farm. A solo 'codepipe up' runs one worker. (ADR-0030)
781
775
 
782
- `}var Br=x(()=>{"use strict";M();Ji()});function Gm(t){Fm=t}function ht(t,e="info"){Fm(t,e)}var Fm,Qi=x(()=>{"use strict";Fm=t=>console.log(t)});import{homedir as TE,tmpdir as lL}from"node:os";import{existsSync as IE,mkdirSync as CE,mkdtempSync as dL,rmSync as pL}from"node:fs";import{join as dl}from"node:path";import{simpleGit as pl}from"simple-git";function Oe(t,e,r){let n=r??dl(TE(),".codepipe","repos");return dl(n,t,e)}async function dr(t,e,r={}){let n=Oe(t,e.name,r.baseDir),o=r.cloneUrlOverride??ml(e);if(!IE(dl(n,".git"))){CE(n,{recursive:!0});let c=pl();ht(`[git] clone ${o} \u2192 ${n}`);try{await c.clone(o,n)}catch(l){let u=l instanceof Error?l.message:String(l);throw new Error(`git clone failed: ${o}
776
+ `}var Fr=x(()=>{"use strict";M();Ji()});function Wm(t){Hm=t}function ht(t,e="info"){Hm(t,e)}var Hm,Qi=x(()=>{"use strict";Hm=t=>console.log(t)});import{homedir as AE,tmpdir as fL}from"node:os";import{existsSync as _E,mkdirSync as jE,mkdtempSync as hL,rmSync as gL}from"node:fs";import{join as dl}from"node:path";import{simpleGit as pl}from"simple-git";function Oe(t,e,r){let n=r??dl(AE(),".codepipe","repos");return dl(n,t,e)}async function pr(t,e,r={}){let n=Oe(t,e.name,r.baseDir),o=r.cloneUrlOverride??ml(e);if(!_E(dl(n,".git"))){jE(n,{recursive:!0});let c=pl();ht(`[git] clone ${o} \u2192 ${n}`);try{await c.clone(o,n)}catch(l){let u=l instanceof Error?l.message:String(l);throw new Error(`git clone failed: ${o}
783
777
  ${u.trim()}`)}}let i=pl(n),s=(await i.remote(["get-url","origin"]).catch(()=>"")||"").toString().trim();s&&s!==o&&(ht(`[git] ${e.name}: origin ${s} \u2192 ${o} (spec changed)`),await i.remote(["set-url","origin",o]));try{await i.fetch()}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git fetch failed in ${n}
784
- ${l.trim()}`)}let a=e.defaultBranch??"main";return await i.checkout(["-B",a,`origin/${a}`]).catch(()=>{}),i}async function On(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function PE(t,e){let{contextRepoCloneUrl:r,deliveryRef:n,deliverySha:o,baseSha:i,commitMessage:s}=e;await t.raw(["fetch",r,`+refs/heads/${n}:refs/codepipe-delivery`]);let a=(await t.revparse(["refs/codepipe-delivery"])).trim();o&&a!==o&&ht(`[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 On(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await On(t,i))throw new Error(`apply_delivery: base commit ${i.slice(0,10)} unavailable \u2014 cannot re-parent the delivery`);let l=(await t.raw([...fl,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function AE(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await On(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await On(t,o)){let s=(await t.revparse([o])).trim();return await t.raw(["update-ref",n,s]).catch(()=>{}),s}let i=await r();return await t.raw(["update-ref",n,i]).catch(()=>{}),i}async function Hm(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:u,force:p}=r,d=await AE(t,i,()=>PE(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));p&&await t.raw(["branch","-D",a]).catch(()=>{});let f=`origin/${c}`;await On(t,f)||(f=`origin/${u??c}`);let m=(await t.revparse([f])).trim(),g=0;if(m===s)await t.raw(["branch","-f",a,d]),await t.checkout(a);else{g=parseInt((await t.raw(["rev-list","--count",`${s}..${m}`]).catch(()=>"1")).trim(),10)||1,await t.checkout(["-B",a,f]);try{await t.raw([...fl,"cherry-pick",d])}catch(v){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let y=v instanceof Error?v.message:String(v);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
785
- ${y.trim()}`)}}let b=(await t.revparse(["HEAD"])).trim(),w=r.push!==!1;if(w){let v=p?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push(v)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:b,pushed:w,...g>0?{baseMoved:g}:{}}}async function Wm(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 qm(t,e,r){let{branchName:n,dropTaskKeys:o}=r,i=`origin/${n}`;if(!await On(t,i))throw new Error(`rewrite_cluster_branch: ${i} not found upstream`);let s=`origin/${r.defaultBranch??"main"}`,a=(await t.raw(["merge-base",i,s])).trim(),c=(await t.raw(["rev-list","--reverse",`${a}..${i}`])).split(`
778
+ ${l.trim()}`)}let a=e.defaultBranch??"main";return await i.checkout(["-B",a,`origin/${a}`]).catch(()=>{}),i}async function Ln(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function NE(t,e){let{contextRepoCloneUrl:r,deliveryRef:n,deliverySha:o,baseSha:i,commitMessage:s}=e;await t.raw(["fetch",r,`+refs/heads/${n}:refs/codepipe-delivery`]);let a=(await t.revparse(["refs/codepipe-delivery"])).trim();o&&a!==o&&ht(`[git] delivery ${n} resolved ${a.slice(0,10)} (expected ${o.slice(0,10)})`);let c=(await t.raw(["rev-parse","refs/codepipe-delivery^{tree}"])).trim();if(await Ln(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await Ln(t,i))throw new Error(`apply_delivery: base commit ${i.slice(0,10)} unavailable \u2014 cannot re-parent the delivery`);let l=(await t.raw([...fl,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function OE(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await Ln(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await Ln(t,o)){let s=(await t.revparse([o])).trim();return await t.raw(["update-ref",n,s]).catch(()=>{}),s}let i=await r();return await t.raw(["update-ref",n,i]).catch(()=>{}),i}async function Ym(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:u,force:p}=r,d=await OE(t,i,()=>NE(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));p&&await t.raw(["branch","-D",a]).catch(()=>{});let f=`origin/${c}`;await Ln(t,f)||(f=`origin/${u??c}`);let m=(await t.revparse([f])).trim(),g=0;if(m===s)await t.raw(["branch","-f",a,d]),await t.checkout(a);else{g=parseInt((await t.raw(["rev-list","--count",`${s}..${m}`]).catch(()=>"1")).trim(),10)||1,await t.checkout(["-B",a,f]);try{await t.raw([...fl,"cherry-pick",d])}catch(v){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let y=v instanceof Error?v.message:String(v);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
779
+ ${y.trim()}`)}}let b=(await t.revparse(["HEAD"])).trim(),w=r.push!==!1;if(w){let v=p?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push(v)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:b,pushed:w,...g>0?{baseMoved:g}:{}}}async function Vm(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 zm(t,e,r){let{branchName:n,dropTaskKeys:o}=r,i=`origin/${n}`;if(!await Ln(t,i))throw new Error(`rewrite_cluster_branch: ${i} not found upstream`);let s=`origin/${r.defaultBranch??"main"}`,a=(await t.raw(["merge-base",i,s])).trim(),c=(await t.raw(["rev-list","--reverse",`${a}..${i}`])).split(`
786
780
  `).map(f=>f.trim()).filter(f=>f.length>0),l=new Set(o.map(f=>f.toUpperCase())),u=[],p=0;for(let f of c)(await t.raw(["show","-s","--format=%(trailers:key=CodePipe-Task,valueonly)",f])).split(`
787
781
  `).map(b=>b.trim().toUpperCase()).filter(b=>b.length>0).some(b=>l.has(b))?p++:u.push(f);if(p===0)return{commit:(await t.revparse([i])).trim(),dropped:0};await t.checkout(["-B",n,a]);for(let f of u)try{await t.raw([...fl,"cherry-pick","--allow-empty","--keep-redundant-commits",f])}catch(m){await t.raw(["cherry-pick","--abort"]).catch(()=>{}),await t.checkout(["-B",n,i]).catch(()=>{});let g=m instanceof Error?m.message:String(m);throw new Error(`rewrite_cluster_branch: replaying ${f.slice(0,10)} after dropping ${o.join(", ")} hit conflicts
788
- ${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 Ym(t,e,r){let{branchName:n,baseBranch:o,mergeMethod:i,deleteBranch:s}=r,a=`origin/${n}`;return i==="squash"?(await t.raw(["merge","--squash",a]),await t.commit(`Merge branch '${n}'`)):i==="rebase"?(await t.checkout(["-B",n,a]),await t.rebase([o]),await t.checkout(o),await t.merge(["--ff-only",n])):await t.merge(["--no-ff",a,"-m",`Merge branch '${n}'`]),await t.push(["origin",o]),s&&await t.push(["origin","--delete",n]).catch(()=>{}),{mergedSha:(await t.revparse(["HEAD"])).trim()}}function ml(t){return t.mirror?Km(t.mirror.host,t.mirror.owner,t.mirror.repoName):Km(t.host,t.owner,t.repoName)}function Km(t,e,r){return t==="github"?`git@github.com:${e}/${r}.git`:t==="gitlab"?`git@gitlab.com:${e}/${r}.git`:`git@bitbucket.org:${e}/${r}.git`}function Ln(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 es(t){return(await pl().listRemote(["--heads",t])).split(`
789
- `).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 Vm(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}var fl,Mn=x(()=>{"use strict";Qi();fl=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{createCipheriv as _E,createDecipheriv as jE,createHash as NE,createPrivateKey as OE,createPublicKey as hl,diffieHellman as zm,generateKeyPairSync as Xm,hkdfSync as Jm,randomBytes as LE}from"node:crypto";function ts(){let{publicKey:t,privateKey:e}=Xm("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function ze(t){let e=Buffer.from(t,"base64");return(NE("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function Xt(t,e){let r=hl({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=Xm("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=zm({privateKey:o,publicKey:r}),c=Buffer.from(Jm("sha256",a,Buffer.concat([i,s]),Zm,32)),l=LE(12),u=_E("aes-256-gcm",c,l),p=typeof e=="string"?Buffer.from(e,"utf-8"):e,d=Buffer.concat([u.update(p),u.final()]),f=u.getAuthTag(),m={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:f.toString("base64"),ct:d.toString("base64")};return Buffer.from(JSON.stringify(m),"utf-8").toString("base64")}function Dn(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=OE({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=hl({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=hl(n).export({type:"spki",format:"der"}),a=zm({privateKey:n,publicKey:o}),c=Buffer.from(Jm("sha256",a,Buffer.concat([i,s]),Zm,32)),l=jE("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 Zm,gt=x(()=>{"use strict";Zm=Buffer.from("devpipe-sealedbox-v1","utf-8")});function Do(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@github.com:"),o(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function Uo(t,e=process.env){if(!t)return!1;let r=`https://oauth2:${t}@gitlab.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@gitlab.com:"),o(1,"ssh://git@gitlab.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function Bo(t,e=process.env){if(!t)return!1;let r=`https://${Wt}:${encodeURIComponent(t)}@bitbucket.org/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@bitbucket.org:"),o(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function gl(t,e,r,n){let o=Number.parseInt(n.GIT_CONFIG_COUNT??"0",10)||0,i=!1;for(let s=0;s<o;s++){let a=n[`GIT_CONFIG_KEY_${s}`];a&&t.test(a)&&(n[`GIT_CONFIG_KEY_${s}`]=`url.${e}.insteadOf`,i=!0)}return i||r()}function eh(t,e=process.env){return gl(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>Do(t,e),e)}function th(t,e=process.env){return gl(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>Uo(t,e),e)}function rh(t,e=process.env){return gl(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Wt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>Bo(t,e),e)}var rs=x(()=>{"use strict";M()});import{existsSync as fh,readFileSync as mh,writeFileSync as hh}from"node:fs";import{join as gh}from"node:path";import{isMap as ph,parseDocument as yh}from"yaml";async function wh(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||!Qt(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=gh(t,"project.yaml");if(!fh(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=yh(mh(o,"utf-8"));return ns(i,r).set("default_branch",n),hh(o,i.toString()),{repoName:r,defaultBranch:n}}function bh(t,e,r){let n=gh(t,"project.yaml");if(!fh(n))throw new Error(`project.yaml not found in context repo (${t})`);let o=yh(mh(n,"utf-8"));ns(o,e).set("mirror",{host:r.host,owner:r.owner,repo:r.repoName}),hh(n,o.toString())}function ns(t,e){let r=t.get("repos"),o=(r&&typeof r=="object"&&"items"in r?r.items:[]).find(i=>ph(i)&&String(i.get("name")??i.get("repo")??"")===e);if(!ph(o))throw new Error(`repo "${e}" not found in project.yaml repos[]`);return o}var os=x(()=>{"use strict";M()});import{existsSync as vl,readFileSync as $l}from"node:fs";import{join as xl}from"node:path";import{simpleGit as Eh}from"simple-git";import{parse as Sl}from"yaml";function Th(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(rR.source,"g")}function Ih(t){let e=xl(t,"project.yaml");if(vl(e))try{let o=Sl($l(e,"utf-8"))?.youtrack,i=o&&typeof o=="object"?o.project_key:null;if(typeof i=="string"&&i.trim())return i.trim()}catch{}let r=xl(t,"tracker","config.yaml");if(vl(r))try{let o=Sl($l(r,"utf-8"))?.prefix;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return null}function Ch(t){if(t.includes("=>")){let r=t.replace(/\{([^{}]*) => ([^{}]*)\}/g,(o,i,s)=>s).replace(/\/\//g,"/");if(!r.includes("=>"))return r;let n=r.split("=>");return(n[n.length-1]??r).trim()}return t}async function nR(t,e,r){let o=await Eh(t).raw(["log","--numstat","--format=@@@ %H %ct %P %x09%s","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
790
- `))if(a.startsWith("@@@ ")){let c=a.indexOf(" "),l=(c>=0?a.slice(4,c):a.slice(4)).trim().split(/\s+/),u=c>=0?a.slice(c+1):"",p=l[0]??"",d=Number(l[1]??0),f=l.slice(2),m=El.exec(u)??Rh.exec(u);s={sha:p,timeSec:d,subject:u,files:[],prNumber:m?Number(m[1]):null,isMerge:f.length>1},i.push(s)}else if(a.trim()&&s){let c=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(a);if(!c)continue;let l=c[1]==="-"?0:Number(c[1]),u=c[2]==="-"?0:Number(c[2]);s.files.push({path:Ch(c[3]),churn:l+u})}return i}async function oR(t,e){let n=await Eh(t).raw(["diff","--numstat",`${e}^1`,e]).catch(()=>""),o=[];for(let i of n.split(`
791
- `)){let s=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(i);if(!s)continue;let a=s[1]==="-"?0:Number(s[1]),c=s[2]==="-"?0:Number(s[2]);o.push({path:Ch(s[3]),churn:a+c})}return o}function iR(t){let{repo:e,issueKeyRe:r,commits:n,pathToCurrent:o,entityByKey:i,ignored:s}=t,a=new Map;for(let c of[...n].reverse()){let l=[...new Set(c.subject.match(r)??[])],u,p,d=l.slice(1);if(l.length>0)u=l[0],p=c.subject.replace(new RegExp(`^\\s*${u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[:\u2014-]\\s*`),"").replace(El,"").trim();else if(c.prNumber!==null){if((t.trackerProjectKey??"").toUpperCase()==="PR")continue;u=`PR-${c.prNumber}`,p=c.subject.replace(El,"").replace(Rh,"").replace(/^from\s+/,"").trim()||c.subject}else continue;if(!/^[A-Za-z0-9._-]+$/.test(u))continue;let f=new Map;for(let b of c.files){let w=o.get(b.path)??b.path;s(w)||f.set(w,(f.get(w)??0)+b.churn)}if(f.size===0)continue;let g=a.get(u)??{modelFormatVersion:2,taskKey:u,origin:"bootstrap",title:"",commits:[],files:[]};p&&(g.title=p),c.timeSec>0&&(g.date=new Date(c.timeSec*1e3).toISOString().slice(0,10)),g.commits.push(c.sha);for(let[b,w]of f){let v=ye("code",e,b),y=g.files.find(k=>k.key===v);if(y)y.churn=(y.churn??0)+w;else{let k=i.get(v);g.files.push({key:v,...k?{entityId:k}:{},churn:w})}}if(d.length>0){let b=new Set([...g.links?.tasks??[],...d]);b.delete(u),g.links={...g.links??{},tasks:[...b].sort()}}a.set(u,g)}return a}function Sh(t,e){if(!t)return e;if(t.origin==="pipeline")return null;let r=[...new Set([...t.commits,...e.commits])],n=new Map(t.files.map(i=>[i.key,i]));for(let i of e.files)n.has(i.key)||n.set(i.key,i);let o=[...new Set([...t.links?.tasks??[],...e.links?.tasks??[]])].sort();return{...t,commits:r,files:[...n.values()],...o.length>0?{links:{...t.links??{},tasks:o}}:{}}}async function Ph(t){let e=await nR(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 oR(t.repoDir,r.sha))}return iR({repo:t.repo,issueKeyRe:t.issueKeyRe,commits:e,pathToCurrent:t.pathToCurrent,entityByKey:t.entityByKey,ignored:t.ignored,trackerProjectKey:t.trackerProjectKey??null})}function Ah(t,e){let r=new Map;for(let i of e)for(let[s,a]of i){let c=r.get(s);r.set(s,c?Sh(c,a)??c:a)}let n=[],o=0;for(let[i,s]of[...r.entries()].sort(([a],[c])=>a<c?-1:1)){let a=Sh(as(t,i),s);if(!a){o++;continue}n.push({path:Ir(i),content:dn(a)})}return{files:n,skippedPipeline:o}}function as(t,e){let r=xl(t,Ir(e));if(!vl(r))return null;try{let n=Kt(Sl($l(r,"utf-8")));return n.ok?n.value:null}catch{return null}}var rR,El,Rh,Rl=x(()=>{"use strict";M();rR=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g,El=/\(#(\d+)\)\s*$/,Rh=/^Merge pull request #(\d+)\b/});import{simpleGit as sR}from"simple-git";async function jh(t,e,r){let o=await sR(t).raw(["log","--no-merges","--name-only","--format=@@@ %H %ct","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
792
- `))if(a.startsWith("@@@ ")){let[c,l]=a.slice(4).trim().split(/\s+/);s={sha:c??"",timeSec:Number(l??0),files:[]},i.push(s)}else a.trim()&&s&&s.files.push(a.trim());return i}function cs(t){let e=new Map;for(let r of t.entities){if(r.status!=="active"||!r.aliases)continue;let n=ne(r.currentKey);if(n?.level==="code")for(let o of r.aliases){let i=ne(o.key);i?.level==="code"&&e.set(i.path,n.path)}}return e}function Nh(t){let{repo:e,headTimeSec:r,filesets:n,pathToCurrent:o,currentPaths:i,ignored:s,settings:a}=t,c=a.halfLifeDays*86400,l=new Map,u=new Map,p=new Map;for(let w of n){let v=new Set;for(let E of w.files){let $=o.get(E)??E;!i.has($)||s($)||v.add($)}if(v.size<2||v.size>a.commitFileCap)continue;let y=Math.max(0,r-w.timeSec),k=Math.pow(.5,y/c),C=[...v].sort();for(let E of C)l.set(E,(l.get(E)??0)+k);for(let E=0;E<C.length;E++)for(let $=E+1;$<C.length;$++){let A=`${C[E]}\0${C[$]}`;u.set(A,(u.get(A)??0)+k),p.set(A,(p.get(A)??0)+1)}}let d=[],f=a.jaccardMinPct/100;for(let[w,v]of u){if((p.get(w)??0)<a.supportMin)continue;let[y,k]=w.split("\0"),C=(l.get(y)??0)+(l.get(k)??0)-v,E=C>0?v/C:0;E<f||d.push({a:y,b:k,weight:Math.round(E*_h)/_h})}let m=new Map;for(let w of d)for(let v of[w.a,w.b])m.has(v)||m.set(v,[]),m.get(v).push(w);let g=new Map;for(let[,w]of m)w.sort((v,y)=>y.weight-v.weight||(v.a<y.a?-1:v.a>y.a?1:v.b<y.b?-1:1)).slice(0,a.topK).forEach(v=>g.set(v,(g.get(v)??0)+1));return[...g.entries()].filter(([,w])=>w===2).map(([w])=>w).map(w=>({kind:"correlates",from:ye("code",e,w.a),to:ye("code",e,w.b),weight:w.weight})).sort((w,v)=>w.from<v.from?-1:w.from>v.from?1:w.to<v.to?-1:1)}var Bn,_h,ls=x(()=>{"use strict";M();Bn=["package-lock.json","pnpm-lock.yaml","yarn.lock"];_h=1e4});import{createHash as aR}from"node:crypto";function lR(t,e,r,n){for(let o=0;;o++){let s=`e_${aR("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(s))return s}}function Oh(t){let{repo:e,headCommit:r,headDate:n,prev:o,renameChains:i,prevBlobByPath:s,headBlobByPath:a}=t,c=[...t.currentKeys].sort(),l=new Set(c),u=o?.entities??[],p=new Set(u.map($=>$.entityId)),d=new Set,f=[],m=new Map,g=($,A)=>{d.add(A),m.set(A,$.entityId),f.push($)},b=[];for(let $ of u)l.has($.currentKey)&&!d.has($.currentKey)?g({...$,status:"active",lastSeen:r},$.currentKey):b.push($);let w=[],v=[];for(let $ of b){let A=ne($.currentKey),N=A?i.get(A.path):void 0;if(A&&N){let B=ye(A.level,e,N.finalPath);if(l.has(B)&&!d.has(B)){w.push({entity:$,newKey:B,untilCommit:N.commit}),d.add(B);continue}}v.push($)}let y=[];if(s){let $=new Map;for(let N of c){if(d.has(N))continue;let B=ne(N);if(B?.level!=="code")continue;let H=a.get(B.path);H&&$.set(H,$.has(H)?null:N)}let A=new Map;for(let N of v){let B=ne(N.currentKey);if(B?.level!=="code")continue;let H=s.get(B.path);H&&A.set(H,A.has(H)?null:N)}for(let N of v){let B=ne(N.currentKey),H=B?.level==="code"?s.get(B.path):void 0,j=H?$.get(H):void 0;H&&j&&A.get(H)===N&&!d.has(j)?(w.push({entity:N,newKey:j,untilCommit:r}),d.add(j)):y.push(N)}}else y.push(...v);let k=new Map;for(let $ of w){let A=ne($.entity.currentKey),N=ne($.newKey);if(A?.level!=="code"||!N)continue;let B=A.path,H=N.path;for(let j=B.lastIndexOf("/");j>0;j=B.lastIndexOf("/",j-1)){let h=B.slice(0,j),F=B.slice(j+1);if(!H.endsWith(`/${F}`))continue;let L=H.slice(0,H.length-F.length-1);if(L===h)continue;let z=`${h}\0${L}`,te=k.get(z);k.set(z,{count:(te?.count??0)+1,commit:te&&te.commit>$.untilCommit?te.commit:$.untilCommit})}}let C=[...k.entries()].filter(([,$])=>$.count>=cR).map(([$,A])=>{let[N,B]=$.split("\0");return{from:N,to:B,commit:A.commit}}).sort(($,A)=>A.from.length-$.from.length||($.from<A.from?-1:1)),E=[];for(let $ of y){let A=ne($.currentKey),N=!1;if(A?.level==="component")for(let B of C){let H=null;if(A.path===B.from?H=B.to:A.path.startsWith(`${B.from}/`)&&(H=B.to+A.path.slice(B.from.length)),H===null)continue;let j=ye("component",e,H);l.has(j)&&!d.has(j)&&(w.push({entity:$,newKey:j,untilCommit:B.commit}),d.add(j),N=!0);break}N||E.push($)}for(let $ of w.sort((A,N)=>A.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)f.push({...$,status:"orphaned"});for(let $ of c){if(d.has($))continue;let A=lR(e,$,r,p);p.add(A),g({entityId:A,currentKey:$,firstSeen:n,lastSeen:r,status:"active"},$)}return{table:{modelFormatVersion:2,repo:e,builtFromCommit:r,entities:f},byKey:m}}var cR,Lh=x(()=>{"use strict";M();cR=5});import{simpleGit as uR}from"simple-git";async function Mh(t,e,r){let n=uR(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
793
- `).map(s=>s.trim()).filter(Boolean),i=[];for(let s of o){let c=(await n.raw(["diff","-M","-C","-z","--name-status","--diff-filter=R",`${s}^`,s]).catch(()=>"")).split("\0");for(let l=0;l+2<c.length;){if(!(c[l]??"").startsWith("R")){l+=1;continue}let p=c[l+1]??"",d=c[l+2]??"";p&&d&&i.push({fromPath:p,toPath:d,commit:s}),l+=3}}return i}function Dh(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 Uh=x(()=>{"use strict"});function us(t){return ye("container",t,dR)}function Bh(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function Fh(t,e,r,n){let o=[],i=u=>{let p=ye("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:Bh(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,pR)}},s=(u,p)=>{let d=ye("component",t,u),f=n.get(d);return{key:d,level:"component",label:Bh(u),...f?{entityId:f}:{},...p?{aggregate:!0}:{}}},a=(u,p,d)=>{let f=r.filesByDir.get(d)??[],m=r.childDirs.get(d)??[],g=[p,...f.map(i)],b=[...f.map(w=>({kind:"contains",from:p.key,to:ye("code",t,w.path)})),...m.map(w=>({kind:"contains",from:p.key,to:ye("component",t,w)}))];c(u,g,b)},c=(u,p,d)=>{let f={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},m=Gt(f);if(!m.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${m.errors.join("; ")}`);o.push({path:_a(t,u),content:Da(f)})},l={key:us(t),level:"container",label:t,...n.get(us(t))?{entityId:n.get(us(t))}:{}};a("",l,"");for(let u of r.components)r.collapsed.has(u)?c(u,[s(u,!0)],[]):a(u,s(u,!1),u);return o.sort((u,p)=>u.path<p.path?-1:u.path>p.path?1:0),{files:o,counts:r.counts}}function Gh(t,e){let r=[us(t)];for(let n of e.components)r.push(ye("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(ye("code",t,o.path));return r.sort()}var dR,pR,Kh=x(()=>{"use strict";M();dR=".";pR=12});import{simpleGit as Wh}from"simple-git";function Fr(t){let e=new Set,r=[],n=new Set;for(let o of t){let i=o.trim();if(i)if(i.endsWith("/"))e.add(i.slice(0,-1));else if(i.includes("*")){let s=i.replace(/[.*+?^${}()|[\]\\]/g,a=>a==="*"?"\0":`\\${a}`).replace(/\0/g,".*");r.push(new RegExp(`^${s}$`))}else n.add(i)}return o=>{let i=o.split("/"),s=i[i.length-1]??o;if(n.has(o))return!0;for(let a of i)if(e.has(a)||n.has(a))return!0;return r.some(a=>a.test(s))}}async function Yh(t,e="HEAD"){let r=Wh(t),n=(await r.revparse([e])).trim(),[o,i]=(await r.raw(["show","-s","--format=%cs %ct",n])).trim().split(/\s+/);return{commit:n,commitDate:o??"",commitTimeSec:Number(i??0),files:await Fo(t,n)}}async function Fo(t,e){let n=await Wh(t).raw(["ls-tree","-r","-z",e]),o=[];for(let i of n.split("\0")){if(!i)continue;let s=i.indexOf(" ");if(s<0)continue;let[,a,c]=i.slice(0,s).split(/\s+/);a!=="blob"||!c||o.push({path:i.slice(s+1),blobHash:c})}return o.sort((i,s)=>i.path<s.path?-1:i.path>s.path?1:0),o}function Hh(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function Vh(t,e){let r=[...t].sort((m,g)=>m.path<g.path?-1:m.path>g.path?1:0),n=new Map,o=new Map;for(let m of r){let g=Hh(m.path);n.has(g)||n.set(g,[]),n.get(g).push(m);let b=g;for(;b!=="";){let w=Hh(b);o.has(w)||o.set(w,new Set),o.get(w).add(b),b=w}}let i=m=>[...o.get(m)??[]].sort(),s=Math.max(e,1)-1,a=new Set,c=new Set,l=[""];for(;l.length>0;){let m=l.shift(),g=(n.get(m)??[]).length+i(m).length;if(g<=s)s-=g,c.add(m),l.push(...i(m));else{if(m==="")return{components:[],collapsed:new Set,filesByDir:new Map,childDirs:new Map,counts:{component:0,code:0}};a.add(m)}}let u=[],p=new Map,d=new Map,f=0;for(let m of[...c].sort()){let g=n.get(m)??[];p.set(m,g),d.set(m,i(m)),f+=g.length,m!==""&&u.push(m)}for(let m of a)u.push(m);return u.sort(),{components:u,collapsed:a,filesByDir:p,childDirs:d,counts:{component:u.length,code:f}}}var qh,Go=x(()=>{"use strict";qh=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as zh,readFileSync as Xh}from"node:fs";import{join as Jh}from"node:path";import{simpleGit as fR}from"simple-git";import{parse as Zh}from"yaml";function Gr(t){let e={ignore:qh,containerNodeCap:mR,cochange:{...lt},issueKeyPattern:null,enabled:!0},r=Jh(t,"regimen.yaml");if(!zh(r))return e;let n;try{n=Zh(Xh(r,"utf-8"))}catch{return e}let o=n?.context,i=o&&typeof o=="object"?o.model:void 0;if(!i||typeof i!="object")return e;let s=i,a=Array.isArray(s.ignore)?s.ignore.filter(f=>typeof f=="string"&&f.trim().length>0):e.ignore,c=(f,m)=>typeof f=="number"&&Number.isInteger(f)&&f>0?f:m,l=c(s.container_node_cap,e.containerNodeCap),u=s.cochange&&typeof s.cochange=="object"?s.cochange:{},p={windowCommits:c(u.window_commits,e.cochange.windowCommits),commitFileCap:c(u.commit_file_cap,e.cochange.commitFileCap),supportMin:c(u.support_min,e.cochange.supportMin),jaccardMinPct:typeof u.jaccard_min_pct=="number"&&Number.isInteger(u.jaccard_min_pct)&&u.jaccard_min_pct>=0&&u.jaccard_min_pct<=100?u.jaccard_min_pct:e.cochange.jaccardMinPct,halfLifeDays:c(u.half_life_days,e.cochange.halfLifeDays),topK:c(u.top_k,e.cochange.topK)},d=typeof s.issue_key_pattern=="string"&&s.issue_key_pattern.trim().length>0?s.issue_key_pattern.trim():null;return{ignore:a,containerNodeCap:l,cochange:p,issueKeyPattern:d,enabled:s.enabled!==!1}}function Tl(t,e){let r=Jh(t,yo(e));if(!zh(r))return null;let n=Zh(Xh(r,"utf-8")),o=bo(n);if(!o.ok)throw new Error(`model: ${yo(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function Il(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await Yh(r,t.ref??"HEAD"),s=Fr(o.ignore),a=i.files.filter(v=>!s(v.path)),c=Vh(a,o.containerNodeCap),l=Tl(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await fR(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=Dh(await Mh(r,l.builtFromCommit,i.commit)),p=new Map((await Fo(r,l.builtFromCommit)).map(k=>[k.path,k.blobHash]))):l?.builtFromCommit===i.commit&&(p=new Map(a.map(v=>[v.path,v.blobHash])));let d=new Map(a.map(v=>[v.path,v.blobHash])),f=Oh({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:Gh(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),m=Fh(e,i.commit,c,f.byKey),g=Fr([...o.ignore,...Bn]),b=Nh({repo:e,headTimeSec:i.commitTimeSec,filesets:await jh(r,i.commit,o.cochange.windowCommits),pathToCurrent:cs(f.table),currentPaths:new Set(a.map(v=>v.path)),ignored:g,settings:o.cochange}),w=[{path:yo(e),content:Ua(f.table)},...m.files.map(v=>({path:v.path,content:v.content})),{path:Pa(e),content:Cr({modelFormatVersion:2,repo:e,builtFromCommit:i.commit,edges:b})}];return{repo:e,headCommit:i.commit,files:w,emittedShardPaths:new Set(m.files.map(v=>v.path)),counts:{...m.counts,correlates:b.length},identityTable:f.table,entityByKey:f.byKey}}var mR,Cl=x(()=>{"use strict";M();ls();Lh();Uh();Kh();Go();mR=1500});import{existsSync as eg,readFileSync as tg,readdirSync as hR}from"node:fs";import{join as Pl}from"node:path";import{parse as rg}from"yaml";function gR(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 ng(t,e,r){let n=new Set(t.files.map(d=>d.key)),o=new Set(e.files.map(d=>d.key)),i=0;for(let d of n)o.has(d)&&i++;if(i<Na)return null;let s=i/Math.min(n.size,o.size),a=gR(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(s*c*Qh)/Qh;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[Ee(t.taskKey),Ee(e.taskKey)]:[Ee(e.taskKey),Ee(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function og(t,e){let r=new Map(t.map(s=>[s.taskKey,s])),n=new Map;for(let s of t)for(let a of s.files)n.has(a.key)||n.set(a.key,[]),n.get(a.key).push(s.taskKey);let o=new Set,i=[];for(let s of n.values())if(!(s.length<2))for(let a=0;a<s.length;a++)for(let c=a+1;c<s.length;c++){let[l,u]=s[a]<s[c]?[s[a],s[c]]:[s[c],s[a]],p=`${l}\0${u}`;if(o.has(p))continue;o.add(p);let d=ng(r.get(l),r.get(u),e);d&&i.push(d)}return i.sort((s,a)=>s.from<a.from?-1:s.from>a.from?1:s.to<a.to?-1:1)}function ig(t,e,r,n){let o=Ee(r),i=t.filter(a=>a.from!==o&&a.to!==o),s=e.find(a=>a.taskKey===r);if(s){let a=new Set(s.files.map(c=>c.key));for(let c of e){if(c.taskKey===r||!c.files.some(u=>a.has(u.key)))continue;let l=ng(s,c,n);l&&i.push(l)}}return i.sort((a,c)=>a.from<c.from?-1:a.from>c.from?1:a.to<c.to?-1:1)}function ds(t){let e=Pl(t,"model/facts/events");if(!eg(e))return[];let r=[];for(let n of hR(e).sort())if(n.endsWith(".yaml"))try{let o=Kt(rg(tg(Pl(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function sg(t){let e=Pl(t,Tr);if(!eg(e))return[];try{let r=wo(rg(tg(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function ps(t){return Cr({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var Qh,Al=x(()=>{"use strict";M();Qh=1e4});var Ko={};Ne(Ko,{collectSearchRows:()=>cg,readContextIndexHub:()=>yR,rebuildSearchIndex:()=>lg,searchIndexPath:()=>gs,searchModelIndex:()=>wR,toFtsQuery:()=>ug});import{existsSync as Gn,readFileSync as Fn,readdirSync as ms}from"node:fs";import{join as Rt}from"node:path";import{parse as hs}from"yaml";function gs(t){return Rt(t,".git","codepipe-model-index.sqlite")}function yR(t){let e=Rt(t,"regimen.yaml");if(!Gn(e))return"off";try{let n=hs(Fn(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 ag(){try{let{createRequire:t}=await import("node:module");return t(import.meta.url)("node:sqlite")}catch{return null}}function fs(t){return t.length>vi?t.slice(0,vi):t}function _l(t){if(!Gn(t))return[];let e=[];for(let r of ms(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=Rt(t,r.name);r.isDirectory()?e.push(..._l(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function cg(t){let e=[];for(let i of _l(Rt(t,"model/derived/structure"))){let s;try{s=hs(Fn(i,"utf-8"))}catch{continue}let a=Gt(s);if(a.ok)for(let c of a.value.nodes){let l=ne(c.key);l&&e.push({nodeId:c.key,kind:l.level,text:fs(`${l.path} ${c.label??""}`.trim())})}}let r=Rt(t,"model/facts/events");if(Gn(r)){for(let i of ms(r).sort())if(i.endsWith(".yaml"))try{let s=Kt(hs(Fn(Rt(r,i),"utf-8")));if(!s.ok)continue;let a=s.value,c=[...a.links?.adr??[],...a.links?.tasks??[]].join(" ");e.push({nodeId:`task::${a.taskKey}`,kind:"task",text:fs(`${a.taskKey} ${a.title??""} ${c}`.trim())})}catch{}}let n=Rt(t,"model/facts/annotations");if(Gn(n)){let i=new Map;for(let s of _l(Rt(t,"model/facts/identity")))try{let a=hs(Fn(s,"utf-8"));for(let c of a?.entities??[])c.status==="active"&&c.entityId&&c.currentKey&&i.set(c.entityId,c.currentKey)}catch{}for(let s of ms(n).sort())if(s.endsWith(".md"))try{let a=Fn(Rt(n,s),"utf-8"),c=/^---\n[\s\S]*?entityId:\s*(e_[0-9a-f]{8})[\s\S]*?\n---\n?([\s\S]*)$/.exec(a);if(!c)continue;e.push({nodeId:i.get(c[1])??c[1],kind:"annotation",text:fs(c[2].trim())})}catch{}}let o=Rt(t,"adr");if(Gn(o))for(let i of ms(o).sort()){let s=/^(\d{4})-/.exec(i)?.[1];if(!(!s||!i.endsWith(".md")))try{let a=Fn(Rt(o,i),"utf-8").split(`
794
- `).slice(0,6);e.push({nodeId:`adr::ADR-${s}`,kind:"adr",text:fs(a.filter(c=>c.trim()).join(" "))})}catch{}}return e}async function lg(t){let e=cg(t),r=await ag();if(!r)return{rows:e,indexed:!1};let n=new r.DatabaseSync(gs(t));try{n.exec("DROP TABLE IF EXISTS model_fts"),n.exec("CREATE VIRTUAL TABLE model_fts USING fts5(node_id UNINDEXED, kind UNINDEXED, text)");let o=n.prepare("INSERT INTO model_fts (node_id, kind, text) VALUES (?, ?, ?)");for(let i of e)o.run(i.nodeId,i.kind,i.text)}finally{n.close()}return{rows:e,indexed:!0}}function ug(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 wR(t,e,r){let n=await ag();if(!n)throw new Error("model search needs Node with built-in sqlite (>= 22.13) on this CLI");Gn(gs(t))||await lg(t);let o=ug(e);if(!o)return[];let i=Math.min(Math.max(r??20,1),La),s=new n.DatabaseSync(gs(t));try{return s.prepare(`SELECT node_id AS nodeId, kind, snippet(model_fts, 2, '[', ']', '\u2026', 10) AS snippet,
782
+ ${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 Xm(t,e,r){let{branchName:n,baseBranch:o,mergeMethod:i,deleteBranch:s}=r,a=`origin/${n}`;return i==="squash"?(await t.raw(["merge","--squash",a]),await t.commit(`Merge branch '${n}'`)):i==="rebase"?(await t.checkout(["-B",n,a]),await t.rebase([o]),await t.checkout(o),await t.merge(["--ff-only",n])):await t.merge(["--no-ff",a,"-m",`Merge branch '${n}'`]),await t.push(["origin",o]),s&&await t.push(["origin","--delete",n]).catch(()=>{}),{mergedSha:(await t.revparse(["HEAD"])).trim()}}function ml(t){return t.mirror?qm(t.mirror.host,t.mirror.owner,t.mirror.repoName):qm(t.host,t.owner,t.repoName)}function qm(t,e,r){return t==="github"?`git@github.com:${e}/${r}.git`:t==="gitlab"?`git@gitlab.com:${e}/${r}.git`:`git@bitbucket.org:${e}/${r}.git`}function Mn(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 es(t){return(await pl().listRemote(["--heads",t])).split(`
783
+ `).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 Jm(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}var fl,Dn=x(()=>{"use strict";Qi();fl=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{createCipheriv as LE,createDecipheriv as ME,createHash as DE,createPrivateKey as UE,createPublicKey as hl,diffieHellman as Zm,generateKeyPairSync as Qm,hkdfSync as eh,randomBytes as BE}from"node:crypto";function ts(){let{publicKey:t,privateKey:e}=Qm("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function ze(t){let e=Buffer.from(t,"base64");return(DE("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function Jt(t,e){let r=hl({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=Qm("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=Zm({privateKey:o,publicKey:r}),c=Buffer.from(eh("sha256",a,Buffer.concat([i,s]),th,32)),l=BE(12),u=LE("aes-256-gcm",c,l),p=typeof e=="string"?Buffer.from(e,"utf-8"):e,d=Buffer.concat([u.update(p),u.final()]),f=u.getAuthTag(),m={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:f.toString("base64"),ct:d.toString("base64")};return Buffer.from(JSON.stringify(m),"utf-8").toString("base64")}function 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=UE({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=hl({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=hl(n).export({type:"spki",format:"der"}),a=Zm({privateKey:n,publicKey:o}),c=Buffer.from(eh("sha256",a,Buffer.concat([i,s]),th,32)),l=ME("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 th,gt=x(()=>{"use strict";th=Buffer.from("devpipe-sealedbox-v1","utf-8")});function Uo(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@github.com:"),o(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function Bo(t,e=process.env){if(!t)return!1;let r=`https://oauth2:${t}@gitlab.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@gitlab.com:"),o(1,"ssh://git@gitlab.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function Fo(t,e=process.env){if(!t)return!1;let r=`https://${qt}:${encodeURIComponent(t)}@bitbucket.org/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@bitbucket.org:"),o(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function gl(t,e,r,n){let o=Number.parseInt(n.GIT_CONFIG_COUNT??"0",10)||0,i=!1;for(let s=0;s<o;s++){let a=n[`GIT_CONFIG_KEY_${s}`];a&&t.test(a)&&(n[`GIT_CONFIG_KEY_${s}`]=`url.${e}.insteadOf`,i=!0)}return i||r()}function nh(t,e=process.env){return gl(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>Uo(t,e),e)}function oh(t,e=process.env){return gl(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>Bo(t,e),e)}function ih(t,e=process.env){return gl(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${qt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>Fo(t,e),e)}var rs=x(()=>{"use strict";M()});import{existsSync as gh,readFileSync as yh,writeFileSync as wh}from"node:fs";import{join as bh}from"node:path";import{isMap as hh,parseDocument as kh}from"yaml";async function vh(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||!er(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=bh(t,"project.yaml");if(!gh(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=kh(yh(o,"utf-8"));return ns(i,r).set("default_branch",n),wh(o,i.toString()),{repoName:r,defaultBranch:n}}function $h(t,e,r){let n=bh(t,"project.yaml");if(!gh(n))throw new Error(`project.yaml not found in context repo (${t})`);let o=kh(yh(n,"utf-8"));ns(o,e).set("mirror",{host:r.host,owner:r.owner,repo:r.repoName}),wh(n,o.toString())}function ns(t,e){let r=t.get("repos"),o=(r&&typeof r=="object"&&"items"in r?r.items:[]).find(i=>hh(i)&&String(i.get("name")??i.get("repo")??"")===e);if(!hh(o))throw new Error(`repo "${e}" not found in project.yaml repos[]`);return o}var os=x(()=>{"use strict";M()});import{existsSync as vl,readFileSync as $l}from"node:fs";import{join as xl}from"node:path";import{simpleGit as Ih}from"simple-git";import{parse as Sl}from"yaml";function Ph(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(sR.source,"g")}function Ah(t){let e=xl(t,"project.yaml");if(vl(e))try{let o=Sl($l(e,"utf-8"))?.youtrack,i=o&&typeof o=="object"?o.project_key:null;if(typeof i=="string"&&i.trim())return i.trim()}catch{}let r=xl(t,"tracker","config.yaml");if(vl(r))try{let o=Sl($l(r,"utf-8"))?.prefix;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return null}function _h(t){if(t.includes("=>")){let r=t.replace(/\{([^{}]*) => ([^{}]*)\}/g,(o,i,s)=>s).replace(/\/\//g,"/");if(!r.includes("=>"))return r;let n=r.split("=>");return(n[n.length-1]??r).trim()}return t}async function aR(t,e,r){let o=await Ih(t).raw(["log","--numstat","--format=@@@ %H %ct %P %x09%s","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
784
+ `))if(a.startsWith("@@@ ")){let c=a.indexOf(" "),l=(c>=0?a.slice(4,c):a.slice(4)).trim().split(/\s+/),u=c>=0?a.slice(c+1):"",p=l[0]??"",d=Number(l[1]??0),f=l.slice(2),m=El.exec(u)??Ch.exec(u);s={sha:p,timeSec:d,subject:u,files:[],prNumber:m?Number(m[1]):null,isMerge:f.length>1},i.push(s)}else if(a.trim()&&s){let c=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(a);if(!c)continue;let l=c[1]==="-"?0:Number(c[1]),u=c[2]==="-"?0:Number(c[2]);s.files.push({path:_h(c[3]),churn:l+u})}return i}async function cR(t,e){let n=await Ih(t).raw(["diff","--numstat",`${e}^1`,e]).catch(()=>""),o=[];for(let i of n.split(`
785
+ `)){let s=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(i);if(!s)continue;let a=s[1]==="-"?0:Number(s[1]),c=s[2]==="-"?0:Number(s[2]);o.push({path:_h(s[3]),churn:a+c})}return o}function lR(t){let{repo:e,issueKeyRe:r,commits:n,pathToCurrent:o,entityByKey:i,ignored:s}=t,a=new Map;for(let c of[...n].reverse()){let l=[...new Set(c.subject.match(r)??[])],u,p,d=l.slice(1);if(l.length>0)u=l[0],p=c.subject.replace(new RegExp(`^\\s*${u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[:\u2014-]\\s*`),"").replace(El,"").trim();else if(c.prNumber!==null){if((t.trackerProjectKey??"").toUpperCase()==="PR")continue;u=`PR-${c.prNumber}`,p=c.subject.replace(El,"").replace(Ch,"").replace(/^from\s+/,"").trim()||c.subject}else continue;if(!/^[A-Za-z0-9._-]+$/.test(u))continue;let f=new Map;for(let b of c.files){let w=o.get(b.path)??b.path;s(w)||f.set(w,(f.get(w)??0)+b.churn)}if(f.size===0)continue;let g=a.get(u)??{modelFormatVersion:2,taskKey:u,origin:"bootstrap",title:"",commits:[],files:[]};p&&(g.title=p),c.timeSec>0&&(g.date=new Date(c.timeSec*1e3).toISOString().slice(0,10)),g.commits.push(c.sha);for(let[b,w]of f){let v=ye("code",e,b),y=g.files.find(k=>k.key===v);if(y)y.churn=(y.churn??0)+w;else{let k=i.get(v);g.files.push({key:v,...k?{entityId:k}:{},churn:w})}}if(d.length>0){let b=new Set([...g.links?.tasks??[],...d]);b.delete(u),g.links={...g.links??{},tasks:[...b].sort()}}a.set(u,g)}return a}function Th(t,e){if(!t)return e;if(t.origin==="pipeline")return null;let r=[...new Set([...t.commits,...e.commits])],n=new Map(t.files.map(i=>[i.key,i]));for(let i of e.files)n.has(i.key)||n.set(i.key,i);let o=[...new Set([...t.links?.tasks??[],...e.links?.tasks??[]])].sort();return{...t,commits:r,files:[...n.values()],...o.length>0?{links:{...t.links??{},tasks:o}}:{}}}async function jh(t){let e=await aR(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 cR(t.repoDir,r.sha))}return lR({repo:t.repo,issueKeyRe:t.issueKeyRe,commits:e,pathToCurrent:t.pathToCurrent,entityByKey:t.entityByKey,ignored:t.ignored,trackerProjectKey:t.trackerProjectKey??null})}function Nh(t,e){let r=new Map;for(let i of e)for(let[s,a]of i){let c=r.get(s);r.set(s,c?Th(c,a)??c:a)}let n=[],o=0;for(let[i,s]of[...r.entries()].sort(([a],[c])=>a<c?-1:1)){let a=Th(as(t,i),s);if(!a){o++;continue}n.push({path:Cr(i),content:pn(a)})}return{files:n,skippedPipeline:o}}function as(t,e){let r=xl(t,Cr(e));if(!vl(r))return null;try{let n=Kt(Sl($l(r,"utf-8")));return n.ok?n.value:null}catch{return null}}var sR,El,Ch,Rl=x(()=>{"use strict";M();sR=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g,El=/\(#(\d+)\)\s*$/,Ch=/^Merge pull request #(\d+)\b/});import{simpleGit as uR}from"simple-git";async function Lh(t,e,r){let o=await uR(t).raw(["log","--no-merges","--name-only","--format=@@@ %H %ct","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
786
+ `))if(a.startsWith("@@@ ")){let[c,l]=a.slice(4).trim().split(/\s+/);s={sha:c??"",timeSec:Number(l??0),files:[]},i.push(s)}else a.trim()&&s&&s.files.push(a.trim());return i}function cs(t){let e=new Map;for(let r of t.entities){if(r.status!=="active"||!r.aliases)continue;let n=ne(r.currentKey);if(n?.level==="code")for(let o of r.aliases){let i=ne(o.key);i?.level==="code"&&e.set(i.path,n.path)}}return e}function Mh(t){let{repo:e,headTimeSec:r,filesets:n,pathToCurrent:o,currentPaths:i,ignored:s,settings:a}=t,c=a.halfLifeDays*86400,l=new Map,u=new Map,p=new Map;for(let w of n){let v=new Set;for(let E of w.files){let $=o.get(E)??E;!i.has($)||s($)||v.add($)}if(v.size<2||v.size>a.commitFileCap)continue;let y=Math.max(0,r-w.timeSec),k=Math.pow(.5,y/c),C=[...v].sort();for(let E of C)l.set(E,(l.get(E)??0)+k);for(let E=0;E<C.length;E++)for(let $=E+1;$<C.length;$++){let A=`${C[E]}\0${C[$]}`;u.set(A,(u.get(A)??0)+k),p.set(A,(p.get(A)??0)+1)}}let d=[],f=a.jaccardMinPct/100;for(let[w,v]of u){if((p.get(w)??0)<a.supportMin)continue;let[y,k]=w.split("\0"),C=(l.get(y)??0)+(l.get(k)??0)-v,E=C>0?v/C:0;E<f||d.push({a:y,b:k,weight:Math.round(E*Oh)/Oh})}let m=new Map;for(let w of d)for(let v of[w.a,w.b])m.has(v)||m.set(v,[]),m.get(v).push(w);let g=new Map;for(let[,w]of m)w.sort((v,y)=>y.weight-v.weight||(v.a<y.a?-1:v.a>y.a?1:v.b<y.b?-1:1)).slice(0,a.topK).forEach(v=>g.set(v,(g.get(v)??0)+1));return[...g.entries()].filter(([,w])=>w===2).map(([w])=>w).map(w=>({kind:"correlates",from:ye("code",e,w.a),to:ye("code",e,w.b),weight:w.weight})).sort((w,v)=>w.from<v.from?-1:w.from>v.from?1:w.to<v.to?-1:1)}var Fn,Oh,ls=x(()=>{"use strict";M();Fn=["package-lock.json","pnpm-lock.yaml","yarn.lock"];Oh=1e4});import{createHash as dR}from"node:crypto";function fR(t,e,r,n){for(let o=0;;o++){let s=`e_${dR("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(s))return s}}function Dh(t){let{repo:e,headCommit:r,headDate:n,prev:o,renameChains:i,prevBlobByPath:s,headBlobByPath:a}=t,c=[...t.currentKeys].sort(),l=new Set(c),u=o?.entities??[],p=new Set(u.map($=>$.entityId)),d=new Set,f=[],m=new Map,g=($,A)=>{d.add(A),m.set(A,$.entityId),f.push($)},b=[];for(let $ of u)l.has($.currentKey)&&!d.has($.currentKey)?g({...$,status:"active",lastSeen:r},$.currentKey):b.push($);let w=[],v=[];for(let $ of b){let A=ne($.currentKey),N=A?i.get(A.path):void 0;if(A&&N){let B=ye(A.level,e,N.finalPath);if(l.has(B)&&!d.has(B)){w.push({entity:$,newKey:B,untilCommit:N.commit}),d.add(B);continue}}v.push($)}let y=[];if(s){let $=new Map;for(let N of c){if(d.has(N))continue;let B=ne(N);if(B?.level!=="code")continue;let H=a.get(B.path);H&&$.set(H,$.has(H)?null:N)}let A=new Map;for(let N of v){let B=ne(N.currentKey);if(B?.level!=="code")continue;let H=s.get(B.path);H&&A.set(H,A.has(H)?null:N)}for(let N of v){let B=ne(N.currentKey),H=B?.level==="code"?s.get(B.path):void 0,j=H?$.get(H):void 0;H&&j&&A.get(H)===N&&!d.has(j)?(w.push({entity:N,newKey:j,untilCommit:r}),d.add(j)):y.push(N)}}else y.push(...v);let k=new Map;for(let $ of w){let A=ne($.entity.currentKey),N=ne($.newKey);if(A?.level!=="code"||!N)continue;let B=A.path,H=N.path;for(let j=B.lastIndexOf("/");j>0;j=B.lastIndexOf("/",j-1)){let h=B.slice(0,j),F=B.slice(j+1);if(!H.endsWith(`/${F}`))continue;let L=H.slice(0,H.length-F.length-1);if(L===h)continue;let z=`${h}\0${L}`,te=k.get(z);k.set(z,{count:(te?.count??0)+1,commit:te&&te.commit>$.untilCommit?te.commit:$.untilCommit})}}let C=[...k.entries()].filter(([,$])=>$.count>=pR).map(([$,A])=>{let[N,B]=$.split("\0");return{from:N,to:B,commit:A.commit}}).sort(($,A)=>A.from.length-$.from.length||($.from<A.from?-1:1)),E=[];for(let $ of y){let A=ne($.currentKey),N=!1;if(A?.level==="component")for(let B of C){let H=null;if(A.path===B.from?H=B.to:A.path.startsWith(`${B.from}/`)&&(H=B.to+A.path.slice(B.from.length)),H===null)continue;let j=ye("component",e,H);l.has(j)&&!d.has(j)&&(w.push({entity:$,newKey:j,untilCommit:B.commit}),d.add(j),N=!0);break}N||E.push($)}for(let $ of w.sort((A,N)=>A.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)f.push({...$,status:"orphaned"});for(let $ of c){if(d.has($))continue;let A=fR(e,$,r,p);p.add(A),g({entityId:A,currentKey:$,firstSeen:n,lastSeen:r,status:"active"},$)}return{table:{modelFormatVersion:2,repo:e,builtFromCommit:r,entities:f},byKey:m}}var pR,Uh=x(()=>{"use strict";M();pR=5});import{simpleGit as mR}from"simple-git";async function Bh(t,e,r){let n=mR(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
787
+ `).map(s=>s.trim()).filter(Boolean),i=[];for(let s of o){let c=(await n.raw(["diff","-M","-C","-z","--name-status","--diff-filter=R",`${s}^`,s]).catch(()=>"")).split("\0");for(let l=0;l+2<c.length;){if(!(c[l]??"").startsWith("R")){l+=1;continue}let p=c[l+1]??"",d=c[l+2]??"";p&&d&&i.push({fromPath:p,toPath:d,commit:s}),l+=3}}return i}function Fh(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 Gh=x(()=>{"use strict"});function us(t){return ye("container",t,hR)}function Kh(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function Hh(t,e,r,n){let o=[],i=u=>{let p=ye("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:Kh(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,gR)}},s=(u,p)=>{let d=ye("component",t,u),f=n.get(d);return{key:d,level:"component",label:Kh(u),...f?{entityId:f}:{},...p?{aggregate:!0}:{}}},a=(u,p,d)=>{let f=r.filesByDir.get(d)??[],m=r.childDirs.get(d)??[],g=[p,...f.map(i)],b=[...f.map(w=>({kind:"contains",from:p.key,to:ye("code",t,w.path)})),...m.map(w=>({kind:"contains",from:p.key,to:ye("component",t,w)}))];c(u,g,b)},c=(u,p,d)=>{let f={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},m=Gt(f);if(!m.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${m.errors.join("; ")}`);o.push({path:_a(t,u),content:Da(f)})},l={key:us(t),level:"container",label:t,...n.get(us(t))?{entityId:n.get(us(t))}:{}};a("",l,"");for(let u of r.components)r.collapsed.has(u)?c(u,[s(u,!0)],[]):a(u,s(u,!1),u);return o.sort((u,p)=>u.path<p.path?-1:u.path>p.path?1:0),{files:o,counts:r.counts}}function Wh(t,e){let r=[us(t)];for(let n of e.components)r.push(ye("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(ye("code",t,o.path));return r.sort()}var hR,gR,qh=x(()=>{"use strict";M();hR=".";gR=12});import{simpleGit as Vh}from"simple-git";function Gr(t){let e=new Set,r=[],n=new Set;for(let o of t){let i=o.trim();if(i)if(i.endsWith("/"))e.add(i.slice(0,-1));else if(i.includes("*")){let s=i.replace(/[.*+?^${}()|[\]\\]/g,a=>a==="*"?"\0":`\\${a}`).replace(/\0/g,".*");r.push(new RegExp(`^${s}$`))}else n.add(i)}return o=>{let i=o.split("/"),s=i[i.length-1]??o;if(n.has(o))return!0;for(let a of i)if(e.has(a)||n.has(a))return!0;return r.some(a=>a.test(s))}}async function Xh(t,e="HEAD"){let r=Vh(t),n=(await r.revparse([e])).trim(),[o,i]=(await r.raw(["show","-s","--format=%cs %ct",n])).trim().split(/\s+/);return{commit:n,commitDate:o??"",commitTimeSec:Number(i??0),files:await Go(t,n)}}async function Go(t,e){let n=await Vh(t).raw(["ls-tree","-r","-z",e]),o=[];for(let i of n.split("\0")){if(!i)continue;let s=i.indexOf(" ");if(s<0)continue;let[,a,c]=i.slice(0,s).split(/\s+/);a!=="blob"||!c||o.push({path:i.slice(s+1),blobHash:c})}return o.sort((i,s)=>i.path<s.path?-1:i.path>s.path?1:0),o}function Yh(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function Jh(t,e){let r=[...t].sort((m,g)=>m.path<g.path?-1:m.path>g.path?1:0),n=new Map,o=new Map;for(let m of r){let g=Yh(m.path);n.has(g)||n.set(g,[]),n.get(g).push(m);let b=g;for(;b!=="";){let w=Yh(b);o.has(w)||o.set(w,new Set),o.get(w).add(b),b=w}}let i=m=>[...o.get(m)??[]].sort(),s=Math.max(e,1)-1,a=new Set,c=new Set,l=[""];for(;l.length>0;){let m=l.shift(),g=(n.get(m)??[]).length+i(m).length;if(g<=s)s-=g,c.add(m),l.push(...i(m));else{if(m==="")return{components:[],collapsed:new Set,filesByDir:new Map,childDirs:new Map,counts:{component:0,code:0}};a.add(m)}}let u=[],p=new Map,d=new Map,f=0;for(let m of[...c].sort()){let g=n.get(m)??[];p.set(m,g),d.set(m,i(m)),f+=g.length,m!==""&&u.push(m)}for(let m of a)u.push(m);return u.sort(),{components:u,collapsed:a,filesByDir:p,childDirs:d,counts:{component:u.length,code:f}}}var zh,Ko=x(()=>{"use strict";zh=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as Zh,readFileSync as Qh}from"node:fs";import{join as eg}from"node:path";import{simpleGit as yR}from"simple-git";import{parse as tg}from"yaml";function Kr(t){let e={ignore:zh,containerNodeCap:wR,cochange:{...lt},issueKeyPattern:null,enabled:!0},r=eg(t,"regimen.yaml");if(!Zh(r))return e;let n;try{n=tg(Qh(r,"utf-8"))}catch{return e}let o=n?.context,i=o&&typeof o=="object"?o.model:void 0;if(!i||typeof i!="object")return e;let s=i,a=Array.isArray(s.ignore)?s.ignore.filter(f=>typeof f=="string"&&f.trim().length>0):e.ignore,c=(f,m)=>typeof f=="number"&&Number.isInteger(f)&&f>0?f:m,l=c(s.container_node_cap,e.containerNodeCap),u=s.cochange&&typeof s.cochange=="object"?s.cochange:{},p={windowCommits:c(u.window_commits,e.cochange.windowCommits),commitFileCap:c(u.commit_file_cap,e.cochange.commitFileCap),supportMin:c(u.support_min,e.cochange.supportMin),jaccardMinPct:typeof u.jaccard_min_pct=="number"&&Number.isInteger(u.jaccard_min_pct)&&u.jaccard_min_pct>=0&&u.jaccard_min_pct<=100?u.jaccard_min_pct:e.cochange.jaccardMinPct,halfLifeDays:c(u.half_life_days,e.cochange.halfLifeDays),topK:c(u.top_k,e.cochange.topK)},d=typeof s.issue_key_pattern=="string"&&s.issue_key_pattern.trim().length>0?s.issue_key_pattern.trim():null;return{ignore:a,containerNodeCap:l,cochange:p,issueKeyPattern:d,enabled:s.enabled!==!1}}function Tl(t,e){let r=eg(t,wo(e));if(!Zh(r))return null;let n=tg(Qh(r,"utf-8")),o=ko(n);if(!o.ok)throw new Error(`model: ${wo(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function Il(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await Xh(r,t.ref??"HEAD"),s=Gr(o.ignore),a=i.files.filter(v=>!s(v.path)),c=Jh(a,o.containerNodeCap),l=Tl(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await yR(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=Fh(await Bh(r,l.builtFromCommit,i.commit)),p=new Map((await Go(r,l.builtFromCommit)).map(k=>[k.path,k.blobHash]))):l?.builtFromCommit===i.commit&&(p=new Map(a.map(v=>[v.path,v.blobHash])));let d=new Map(a.map(v=>[v.path,v.blobHash])),f=Dh({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:Wh(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),m=Hh(e,i.commit,c,f.byKey),g=Gr([...o.ignore,...Fn]),b=Mh({repo:e,headTimeSec:i.commitTimeSec,filesets:await Lh(r,i.commit,o.cochange.windowCommits),pathToCurrent:cs(f.table),currentPaths:new Set(a.map(v=>v.path)),ignored:g,settings:o.cochange}),w=[{path:wo(e),content:Ua(f.table)},...m.files.map(v=>({path:v.path,content:v.content})),{path:Pa(e),content:Pr({modelFormatVersion:2,repo:e,builtFromCommit:i.commit,edges:b})}];return{repo:e,headCommit:i.commit,files:w,emittedShardPaths:new Set(m.files.map(v=>v.path)),counts:{...m.counts,correlates:b.length},identityTable:f.table,entityByKey:f.byKey}}var wR,Cl=x(()=>{"use strict";M();ls();Uh();Gh();qh();Ko();wR=1500});import{existsSync as ng,readFileSync as og,readdirSync as bR}from"node:fs";import{join as Pl}from"node:path";import{parse as ig}from"yaml";function kR(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 sg(t,e,r){let n=new Set(t.files.map(d=>d.key)),o=new Set(e.files.map(d=>d.key)),i=0;for(let d of n)o.has(d)&&i++;if(i<Na)return null;let s=i/Math.min(n.size,o.size),a=kR(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(s*c*rg)/rg;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[Ee(t.taskKey),Ee(e.taskKey)]:[Ee(e.taskKey),Ee(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function ag(t,e){let r=new Map(t.map(s=>[s.taskKey,s])),n=new Map;for(let s of t)for(let a of s.files)n.has(a.key)||n.set(a.key,[]),n.get(a.key).push(s.taskKey);let o=new Set,i=[];for(let s of n.values())if(!(s.length<2))for(let a=0;a<s.length;a++)for(let c=a+1;c<s.length;c++){let[l,u]=s[a]<s[c]?[s[a],s[c]]:[s[c],s[a]],p=`${l}\0${u}`;if(o.has(p))continue;o.add(p);let d=sg(r.get(l),r.get(u),e);d&&i.push(d)}return i.sort((s,a)=>s.from<a.from?-1:s.from>a.from?1:s.to<a.to?-1:1)}function cg(t,e,r,n){let o=Ee(r),i=t.filter(a=>a.from!==o&&a.to!==o),s=e.find(a=>a.taskKey===r);if(s){let a=new Set(s.files.map(c=>c.key));for(let c of e){if(c.taskKey===r||!c.files.some(u=>a.has(u.key)))continue;let l=sg(s,c,n);l&&i.push(l)}}return i.sort((a,c)=>a.from<c.from?-1:a.from>c.from?1:a.to<c.to?-1:1)}function ds(t){let e=Pl(t,"model/facts/events");if(!ng(e))return[];let r=[];for(let n of bR(e).sort())if(n.endsWith(".yaml"))try{let o=Kt(ig(og(Pl(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function lg(t){let e=Pl(t,Ir);if(!ng(e))return[];try{let r=bo(ig(og(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function ps(t){return Pr({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var rg,Al=x(()=>{"use strict";M();rg=1e4});var Ho={};Ne(Ho,{collectSearchRows:()=>dg,readContextIndexHub:()=>vR,rebuildSearchIndex:()=>pg,searchIndexPath:()=>gs,searchModelIndex:()=>$R,toFtsQuery:()=>fg});import{existsSync as Kn,readFileSync as Gn,readdirSync as ms}from"node:fs";import{join as Rt}from"node:path";import{parse as hs}from"yaml";function gs(t){return Rt(t,".git","codepipe-model-index.sqlite")}function vR(t){let e=Rt(t,"regimen.yaml");if(!Kn(e))return"off";try{let n=hs(Gn(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 ug(){try{let{createRequire:t}=await import("node:module");return t(import.meta.url)("node:sqlite")}catch{return null}}function fs(t){return t.length>$i?t.slice(0,$i):t}function _l(t){if(!Kn(t))return[];let e=[];for(let r of ms(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=Rt(t,r.name);r.isDirectory()?e.push(..._l(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function dg(t){let e=[];for(let i of _l(Rt(t,"model/derived/structure"))){let s;try{s=hs(Gn(i,"utf-8"))}catch{continue}let a=Gt(s);if(a.ok)for(let c of a.value.nodes){let l=ne(c.key);l&&e.push({nodeId:c.key,kind:l.level,text:fs(`${l.path} ${c.label??""}`.trim())})}}let r=Rt(t,"model/facts/events");if(Kn(r)){for(let i of ms(r).sort())if(i.endsWith(".yaml"))try{let s=Kt(hs(Gn(Rt(r,i),"utf-8")));if(!s.ok)continue;let a=s.value,c=[...a.links?.adr??[],...a.links?.tasks??[]].join(" ");e.push({nodeId:`task::${a.taskKey}`,kind:"task",text:fs(`${a.taskKey} ${a.title??""} ${c}`.trim())})}catch{}}let n=Rt(t,"model/facts/annotations");if(Kn(n)){let i=new Map;for(let s of _l(Rt(t,"model/facts/identity")))try{let a=hs(Gn(s,"utf-8"));for(let c of a?.entities??[])c.status==="active"&&c.entityId&&c.currentKey&&i.set(c.entityId,c.currentKey)}catch{}for(let s of ms(n).sort())if(s.endsWith(".md"))try{let a=Gn(Rt(n,s),"utf-8"),c=/^---\n[\s\S]*?entityId:\s*(e_[0-9a-f]{8})[\s\S]*?\n---\n?([\s\S]*)$/.exec(a);if(!c)continue;e.push({nodeId:i.get(c[1])??c[1],kind:"annotation",text:fs(c[2].trim())})}catch{}}let o=Rt(t,"adr");if(Kn(o))for(let i of ms(o).sort()){let s=/^(\d{4})-/.exec(i)?.[1];if(!(!s||!i.endsWith(".md")))try{let a=Gn(Rt(o,i),"utf-8").split(`
788
+ `).slice(0,6);e.push({nodeId:`adr::ADR-${s}`,kind:"adr",text:fs(a.filter(c=>c.trim()).join(" "))})}catch{}}return e}async function pg(t){let e=dg(t),r=await ug();if(!r)return{rows:e,indexed:!1};let n=new r.DatabaseSync(gs(t));try{n.exec("DROP TABLE IF EXISTS model_fts"),n.exec("CREATE VIRTUAL TABLE model_fts USING fts5(node_id UNINDEXED, kind UNINDEXED, text)");let o=n.prepare("INSERT INTO model_fts (node_id, kind, text) VALUES (?, ?, ?)");for(let i of e)o.run(i.nodeId,i.kind,i.text)}finally{n.close()}return{rows:e,indexed:!0}}function fg(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 $R(t,e,r){let n=await ug();if(!n)throw new Error("model search needs Node with built-in sqlite (>= 22.13) on this CLI");Kn(gs(t))||await pg(t);let o=fg(e);if(!o)return[];let i=Math.min(Math.max(r??20,1),La),s=new n.DatabaseSync(gs(t));try{return s.prepare(`SELECT node_id AS nodeId, kind, snippet(model_fts, 2, '[', ']', '\u2026', 10) AS snippet,
795
789
  bm25(model_fts) AS rank
796
- FROM model_fts WHERE model_fts MATCH ? ORDER BY bm25(model_fts), node_id LIMIT ?`).all(o,i).map(c=>({nodeId:c.nodeId,kind:c.kind,score:-c.rank,snippet:c.snippet}))}finally{s.close()}}var Ho=x(()=>{"use strict";M()});var bs={};Ne(bs,{mirrorLag:()=>OR,syncUpstream:()=>NR});import{simpleGit as kg}from"simple-git";async function NR(t,e,r,n){let o=kg(e),i=t.defaultBranch??"main",s=n?.upstream??vg(t);if(!s)return{repo:t.name,upstreamHead:null,updated:!1,error:"repo spec has no host/owner/repo"};try{await o.fetch(s,`+refs/heads/*:${Kr}/*`,["--prune"]);let a=(await o.revparse([`${Kr}/${i}`]).catch(()=>"")).trim()||null;if(!a)return{repo:t.name,upstreamHead:null,updated:!1,error:`upstream has no branch '${i}'`};let c=n?.mirror??(t.mirror?$g(t.mirror):null);if(!c)return{repo:t.name,upstreamHead:a,updated:!1};let l=await LR(o),u=await Ll(o,c),p=[];for(let d of l){if(d==="codepipe"||d.startsWith("codepipe/"))continue;let f=(await o.revparse([`${Kr}/${d}`]).catch(()=>"")).trim();!f||u.get(d)===f||p.push(`+${f}:refs/heads/${d}`)}return p.length===0?{repo:t.name,upstreamHead:a,updated:!1}:(await o.push([c,...p]),r.info(`${t.name}: mirror \u2190 ${p.length} branch(es), ${i} @ ${a.slice(0,10)}`),{repo:t.name,upstreamHead:a,updated:!0})}catch(a){let c=a instanceof Error?a.message.split(`
797
- `)[0]:String(a);return{repo:t.name,upstreamHead:null,updated:!1,error:c}}}async function OR(t,e,r){let n=r?.mirror??(t.mirror?$g(t.mirror):null);if(!n)return null;let o=r?.upstream??vg(t);if(!o)return null;let i=kg(e),s=t.defaultBranch??"main";try{let a=(await Ll(i,n,s)).get(s);if(!a)return null;let c=(await Ll(i,o,s)).get(s);if(!c)return null;if(c===a)return 0;let l=async()=>{let p=await i.raw(["rev-list","--count",`${a}..${c}`]).catch(()=>null);if(p===null)return null;let d=parseInt(p.trim(),10);return Number.isFinite(d)?d:null},u=await l();return u!==null?u:(await i.fetch(o,`+refs/heads/${s}:${Kr}/${s}`),await l())}catch{return null}}function vg(t){return!t.host||!t.owner||!t.repoName?null:t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}function $g(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 LR(t){return(await t.raw(["for-each-ref",Kr,"--format=%(refname)"]).catch(()=>"")).split(`
798
- `).map(r=>r.trim()).filter(r=>r.startsWith(`${Kr}/`)).map(r=>r.slice(Kr.length+1))}async function Ll(t,e,r){let n=r?["--heads",e,r]:["--heads",e],o=await t.listRemote(n),i=new Map;for(let s of o.split(`
799
- `)){let[a,c]=s.trim().split(/\s+/);!a||!c||!/^[0-9a-f]{40}$/.test(a)||c.startsWith("refs/heads/")&&i.set(c.slice(11),a)}return i}var Kr,ks=x(()=>{"use strict";Kr="refs/codepipe/upstream"});import{homedir as MR}from"node:os";import{existsSync as DR,mkdirSync as UR,readFileSync as BR,writeFileSync as FR}from"node:fs";import{dirname as GR,join as KR}from"node:path";function Ml(){return ee("FARM_PINS")??KR(MR(),".codepipe","farm-pins.json")}function Eg(){let t=Ml();if(!DR(t))return{};try{return JSON.parse(BR(t,"utf-8"))}catch{return{}}}function HR(t){let e=Ml();UR(GR(e),{recursive:!0}),FR(e,JSON.stringify(t,null,2)+`
800
- `,{mode:384})}function WR(t){return Eg()[t]}function $s(t,e){let r=Eg();r[t]=e,HR(r)}function xs(t,e){let r=ze(e),n=WR(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 ${Ml()}.`);return r}var Dl=x(()=>{"use strict";Ye();gt()});import{setTimeout as qR}from"node:timers/promises";import YR from"ws";function Ss(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new YR(r)}async function pr(t,e,r){return fr(t,e,"/projects",r)}async function Rg(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new V(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function Es(t,e,r,n){return fr(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function Tg(t,e,r,n){return fr(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function Ig(t,e,r,n){return fr(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function Cg(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 V(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function Rs(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new V(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function Ul(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new V(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function Pg(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await Ul(t,e),a=new Set;for(let c of s)c.id!==r.excludeProjectId&&c.trackerProvider==="internal"&&c.youtrackProjectKey&&a.add(c.youtrackProjectKey.toUpperCase());return a}catch(s){o=s,i<n-1&&await qR(r.delayMs??1500)}throw o}async function Ag(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 zo(e)}if(!r.ok)throw new V(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function _g(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new V(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function jg(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new V(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function Ng(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 V(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function Og(t,e,r,n,o){return fr(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function Xo(t,e,r,n){return fr(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function Bl(t,e,r,n){await fr(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function Lg(t,e,r,n){return fr(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function Mg(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/repos/${encodeURIComponent(n)}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new V(o.status,s,a)}return s}async function se(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new V(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function fr(t,e,r,n){let o=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new V(o.status,s,a)}return s}async function Ts(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/deliverables`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new V(n.status,null,`GET /deliverables HTTP ${n.status}`);return(await n.json()).deliverables}var V,zo,Le=x(()=>{"use strict";V=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};zo=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});import{existsSync as iy,readFileSync as mT,readdirSync as hT}from"node:fs";import{join as sy}from"node:path";import{simpleGit as gT}from"simple-git";import{parse as yT}from"yaml";function js(t){let e=new Map,r=sy(t,bi);if(!iy(r))return e;let n;try{n=yT(mT(r,"utf-8"))}catch{return e}let o=n?.repos;if(!o||typeof o!="object")return e;for(let[i,s]of Object.entries(o)){if(!s||typeof s!="object")continue;let a=s,c=a.counts??{};typeof a.builtFromCommit=="string"&&e.set(i,{builtFromCommit:a.builtFromCommit,counts:{component:typeof c.component=="number"?c.component:0,code:typeof c.code=="number"?c.code:0,correlates:typeof c.correlates=="number"?c.correlates:0}})}return e}function wT(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return Ar({modelFormatVersion:2,repos:e})}function ay(t,e){let r=sy(t,e);if(!iy(r))return[];let n=[];for(let o of hT(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...ay(t,i)):n.push(i)}return n}async function Ns(t,e,r={}){let n=[],o=0;for(let d of e){n.push(...d.files);let f=`model/derived/structure/${d.repo}`;for(let m of ay(t,f))d.emittedShardPaths.has(m)||(n.push({path:m,content:"",deleted:!0}),o++)}let i=js(t);for(let d of e)i.set(d.repo,{builtFromCommit:d.headCommit,counts:d.counts});n.push({path:bi,content:wT(i)});let s=ds(t),a=og(s,r.halfLifeDays??lt.halfLifeDays);n.push({path:Tr,content:ps(a)});for(let d of e){let f=[];for(let m of s)for(let g of m.files)ne(g.key)?.repo===d.repo&&f.push({kind:"touched_by",from:Ee(m.taskKey),to:g.key,...g.churn!==void 0?{weight:g.churn}:{}});n.push({path:Aa(d.repo),content:Cr({modelFormatVersion:2,repo:d.repo,builtFromCommit:d.headCommit,edges:f})})}let c=gT(t),l=(await c.revparse(["HEAD"]).catch(()=>"")).trim(),u=`model: build ${e.map(d=>`${d.repo}@${d.headCommit.slice(0,10)}`).join(", ")}`;await Ce(t,n,u);let p=(await c.revparse(["HEAD"]).catch(()=>"")).trim();if(p!==l){let{rebuildSearchIndex:d}=await Promise.resolve().then(()=>(Ho(),Ko));await d(t).catch(()=>{})}return{committed:p!==l,filesWritten:n.filter(d=>!d.deleted).length,filesDeleted:o}}var cy=x(()=>{"use strict";M();Al();mt()});var Ms={};Ne(Ms,{bootstrapDaemonModel:()=>kT,bootstrapModelForTargets:()=>zl,bootstrapWorkspaceModel:()=>fy,modelBootstrapCommand:()=>Vl,modelBuildCommand:()=>Yl,modelIndexExists:()=>hy,rebuildWorkspaceModelIfStale:()=>$T,shouldAutoBootstrapModel:()=>vT,syncWorkspaceMirrors:()=>my});import{existsSync as Ls}from"node:fs";import{join as mr}from"node:path";import{cancel as bT,intro as ly,log as Hl,outro as Wl}from"@clack/prompts";import{simpleGit as ql}from"simple-git";function Os(t){bT(t),process.exit(1)}function uy(t,e,r){let n=t.spec.repos.filter(i=>!e||i.name===e);if(n.length===0)throw new Error(e?`repo "${e}" is not part of this project (see project.yaml)`:"the project has no repos configured");let o=[];for(let i of n){let s=i.mountAs==="."?t.root:mr(t.root,i.mountAs);if(!Ls(mr(s,".git"))){r(`${i.name}: no local clone at ${s} \u2014 skipped (run \`codepipe clone\` first)`);continue}o.push({name:i.name,dir:s,defaultBranch:i.defaultBranch||"main"})}if(o.length===0)throw new Error("nothing to do \u2014 no repo clones found");return o}async function dy(t){let e=ql(t.dir),r=`origin/${t.defaultBranch}`;return await e.raw(["rev-parse","--verify",r]).then(()=>!0).catch(()=>!1)?r:"HEAD"}async function py(t,e,r,n){let o=[];for(let i of e)try{let s=await Il({repo:i.name,repoDir:i.dir,contextDir:t,settings:r,ref:await dy(i)});o.push(s),n(`${i.name}: ${s.counts.code} files, ${s.counts.component} components, ${s.counts.correlates} co-change edges @ ${s.headCommit.slice(0,10)}`)}catch(s){throw new Error(`${i.name}: ${s instanceof Error?s.message:String(s)}`)}return o}async function Yl(t){ly("codepipe model build");let e=je();e||Os("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{let r=Gr(e.contextDir),n=uy(e,t.repo,s=>Hl.warn(s)),o=await py(e.contextDir,n,r,s=>Hl.info(s)),i=await Ns(e.contextDir,o,{halfLifeDays:r.cochange.halfLifeDays});i.committed?Wl(`model updated: ${i.filesWritten} files written, ${i.filesDeleted} stale removed`):Wl("model already up to date (no changes)")}catch(r){Os(r instanceof Error?r.message:String(r))}}async function Vl(t){ly("codepipe model bootstrap");let e=je();e||Os("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{await fy(e,t.repo,{onLog:r=>Hl.info(r)})}catch(r){Os(r instanceof Error?r.message:String(r))}Wl("bootstrap complete")}async function fy(t,e,r){let n=uy(t,e,r.onLog);return zl(t.contextDir,n,r)}async function zl(t,e,r){let n=Gr(t),o=await py(t,e,n,r.onLog),i=Ih(t),s=Th(n.issueKeyPattern,i),a=Fr([...n.ignore,...Bn]),c=[];for(let p of o){let d=e.find(m=>m.name===p.repo),f=await Ph({repo:p.repo,repoDir:d.dir,headCommit:p.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:s,pathToCurrent:cs(p.identityTable),entityByKey:p.entityByKey,ignored:a,trackerProjectKey:i});c.push(f),r.onLog(`${p.repo}: ${f.size} task events mined from history`)}let{files:l,skippedPipeline:u}=Ah(t,c);return u>0&&r.onLog(`${u} events already recorded by the live pipeline \u2014 left untouched`),l.length>0&&await Ce(t,l,`model: bootstrap ${l.length} task events from history`),await Ns(t,o,{halfLifeDays:n.cochange.halfLifeDays}),{events:l.length}}async function kT(t,e,r,n){if(r.length===0)throw new Error("the project has no repos configured");let o=[];for(let s of r){let a=s.mountAs??s.name,c=a==="."?e.root:mr(e.root,a),l=s.defaultBranch||"main";c!==e.contextDir&&Ls(mr(c,".git"))?(await ql(c).fetch(["origin",l]).catch(()=>{}),o.push({name:s.name,dir:c,defaultBranch:l})):(n(`${s.name}: materializing clone in the daemon layout`),await dr(t,s),o.push({name:s.name,dir:Oe(t,s.name),defaultBranch:l}))}let i=await zl(e.contextDir,o,{onLog:n});return{repos:o.length,events:i.events}}async function my(t,e){let r=new Map;for(let n of t.repos){if(!n.mirror)continue;let o=n.mountAs==="."?t.root:mr(t.root,n.mountAs);if(!Ls(mr(o,".git")))continue;let{syncUpstream:i}=await Promise.resolve().then(()=>(ks(),bs)),s=await i(n,o,{info:a=>e(`[mirror] ${a}`),warn:a=>e(`[mirror] ${a}`)});if(s.error||!s.upstreamHead){e(`[mirror] ${n.name}: sync failed (${s.error??"no upstream head"})`);continue}r.set(n.name,s.upstreamHead)}return r}function hy(t){return js(t).size>0}function vT(t){return Gr(t).enabled&&!hy(t)}async function $T(t,e={}){let r=e.onLog??(()=>{}),n=Gr(t.contextDir),o=await my(t,r);if(!n.enabled)return{rebuilt:[],skipped:[]};let i=[],s=[],a=js(t.contextDir),c=[];for(let l of t.repos){let u=l.mountAs==="."?t.root:mr(t.root,l.mountAs);if(!Ls(mr(u,".git")))continue;let p=ql(u),d=l.defaultBranch||"main",f=null;if(l.mirror){if(f=o.get(l.name)??null,!f){r(`[mirror] ${l.name}: map not rebuilt \u2014 sync did not complete`);continue}}else e.fetch&&await p.fetch(["origin",d]).catch(()=>{});let m=f??await dy({name:l.name,dir:u,defaultBranch:d}),g=(await p.revparse([m]).catch(()=>"")).trim();if(g){if(a.get(l.name)?.builtFromCommit===g){s.push(l.name);continue}try{c.push(await Il({repo:l.name,repoDir:u,contextDir:t.contextDir,settings:n,ref:g})),i.push(l.name)}catch(b){r(`[model] rebuild of ${l.name} failed: ${b instanceof Error?b.message:String(b)}`)}}}return c.length>0&&(await Ns(t.contextDir,c,{halfLifeDays:n.cochange.halfLifeDays}),r(`[model] release-path rebuild: ${i.join(", ")} (skipped up-to-date: ${s.join(", ")||"\u2014"})`)),{rebuilt:i,skipped:s}}var Jo=x(()=>{"use strict";mt();cy();Cl();Rl();ls();Go();Mn();xt()});var yy={};Ne(yy,{computeDriftReport:()=>TT,supersededAdrIds:()=>gy});import{existsSync as Xl,readFileSync as Jl,readdirSync as Zl}from"node:fs";import{join as Kn}from"node:path";import{parse as xT}from"yaml";import{simpleGit as ST}from"simple-git";function RT(t,e){let r=Kn(t,`model/derived/structure/${e}`),n=[],o="";if(!Xl(r))return{nodes:n,builtFromCommit:o};for(let i of Zl(r).sort()){if(!i.endsWith(".yaml"))continue;let s;try{let a=Gt(xT(Jl(Kn(r,i),"utf-8")));if(!a.ok)continue;s=a.value}catch{continue}o=s.builtFromCommit;for(let a of s.nodes){let c=ne(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 gy(t){let e=new Set,r=Kn(t,"adr");if(!Xl(r))return e;for(let n of Zl(r).sort()){let o=/^(\d{4})-/.exec(n)?.[1];if(!(!o||!n.endsWith(".md")))try{let i=Jl(Kn(r,n),"utf-8").slice(0,600).toLowerCase();/status[^\n]*superseded/.test(i)&&e.add(`ADR-${o}`)}catch{}}return e}async function TT(t,e,r){let{nodes:n,builtFromCommit:o}=RT(e,r),i=(await ST(t).revparse(["HEAD"])).trim(),s=await Fo(t,i),a=new Map(s.map(v=>[v.path,v.blobHash])),c=[],l=[],u=new Set,p=[];for(let v of n){if(v.level==="component"){p.push(v);continue}u.add(v.path);let y=a.get(v.path);y?v.contentHash&&y.slice(0,ET)!==v.contentHash&&c.push(v.key):l.push(v.key)}let d=0,f=new Map,m=new Set;for(let v of s){let y=v.path.lastIndexOf("/"),k=y<0?"":v.path.slice(0,y);f.has(k)||f.set(k,new Set),f.get(k).add(v.path),u.has(v.path)||d++;let C=k;for(;C!==""&&!m.has(C);)m.add(C),C=C.includes("/")?C.slice(0,C.lastIndexOf("/")):""}let g=new Map;for(let v of u){let y=v.lastIndexOf("/"),k=y<0?"":v.slice(0,y);g.has(k)||g.set(k,new Set),g.get(k).add(v)}for(let v of p){if(!m.has(v.path)){l.push(v.key);continue}let y=g.get(v.path)??new Set,k=f.get(v.path)??new Set;(y.size!==k.size||[...y].some(E=>!k.has(E)))&&c.push(v.key)}let b=[],w=gy(e);if(w.size>0){let v=Kn(e,"model/facts/annotations"),y=new Map(n.filter(k=>k.entityId).map(k=>[k.entityId,k.key]));if(Xl(v))for(let k of Zl(v).sort()){if(!k.endsWith(".md"))continue;let C=k.replace(/\.md$/,""),E=y.get(C);if(E)try{(Jl(Kn(v,k),"utf-8").match(/\bADR-(\d{3,4})\b/g)??[]).map(N=>`ADR-${N.slice(4).padStart(4,"0")}`).some(N=>w.has(N))&&b.push(E)}catch{}}}return{repo:r,builtFromCommit:o,headCommit:i,stale:[...new Set(c)].sort(),orphaned:[...new Set(l)].sort(),superseded:[...new Set(b)].sort(),newFiles:d}}var ET,wy=x(()=>{"use strict";M();Go();ET=12});import{execFileSync as LT}from"node:child_process";import{mkdtempSync as MT,mkdirSync as DT,readFileSync as ky,rmSync as UT,writeFileSync as BT}from"node:fs";import{tmpdir as FT}from"node:os";import{dirname as GT,join as vy}from"node:path";function $y(t="codepipe-context"){let e=MT(vy(FT(),"codepipe-ssh-")),r=vy(e,"id_ed25519");try{return LT("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:ky(r,"utf-8"),publicKey:ky(`${r}.pub`,"utf-8").trim()}}finally{UT(e,{recursive:!0,force:!0})}}async function xy(t,e,r,n="codepipe-context"){let o=await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/keys`,{method:"POST",headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({title:n,key:r,read_only:!1})});if(o.ok)return;let i=await o.text();if(!(o.status===422&&/already in use/i.test(i)))throw new Error(`add deploy key failed: ${o.status} ${i}`)}function Sy(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 Ey(t,e){DT(GT(t),{recursive:!0});let r=e.endsWith(`
790
+ FROM model_fts WHERE model_fts MATCH ? ORDER BY bm25(model_fts), node_id LIMIT ?`).all(o,i).map(c=>({nodeId:c.nodeId,kind:c.kind,score:-c.rank,snippet:c.snippet}))}finally{s.close()}}var Wo=x(()=>{"use strict";M()});var bs={};Ne(bs,{mirrorLag:()=>UR,syncUpstream:()=>DR});import{simpleGit as xg}from"simple-git";async function DR(t,e,r,n){let o=xg(e),i=t.defaultBranch??"main",s=n?.upstream??Sg(t);if(!s)return{repo:t.name,upstreamHead:null,updated:!1,error:"repo spec has no host/owner/repo"};try{await o.fetch(s,`+refs/heads/*:${Hr}/*`,["--prune"]);let a=(await o.revparse([`${Hr}/${i}`]).catch(()=>"")).trim()||null;if(!a)return{repo:t.name,upstreamHead:null,updated:!1,error:`upstream has no branch '${i}'`};let c=n?.mirror??(t.mirror?Eg(t.mirror):null);if(!c)return{repo:t.name,upstreamHead:a,updated:!1};let l=await BR(o),u=await Ll(o,c),p=[];for(let d of l){if(d==="codepipe"||d.startsWith("codepipe/"))continue;let f=(await o.revparse([`${Hr}/${d}`]).catch(()=>"")).trim();!f||u.get(d)===f||p.push(`+${f}:refs/heads/${d}`)}return p.length===0?{repo:t.name,upstreamHead:a,updated:!1}:(await o.push([c,...p]),r.info(`${t.name}: mirror \u2190 ${p.length} branch(es), ${i} @ ${a.slice(0,10)}`),{repo:t.name,upstreamHead:a,updated:!0})}catch(a){let c=a instanceof Error?a.message.split(`
791
+ `)[0]:String(a);return{repo:t.name,upstreamHead:null,updated:!1,error:c}}}async function UR(t,e,r){let n=r?.mirror??(t.mirror?Eg(t.mirror):null);if(!n)return null;let o=r?.upstream??Sg(t);if(!o)return null;let i=xg(e),s=t.defaultBranch??"main";try{let a=(await Ll(i,n,s)).get(s);if(!a)return null;let c=(await Ll(i,o,s)).get(s);if(!c)return null;if(c===a)return 0;let l=async()=>{let p=await i.raw(["rev-list","--count",`${a}..${c}`]).catch(()=>null);if(p===null)return null;let d=parseInt(p.trim(),10);return Number.isFinite(d)?d:null},u=await l();return u!==null?u:(await i.fetch(o,`+refs/heads/${s}:${Hr}/${s}`),await l())}catch{return null}}function Sg(t){return!t.host||!t.owner||!t.repoName?null:t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}function Eg(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 BR(t){return(await t.raw(["for-each-ref",Hr,"--format=%(refname)"]).catch(()=>"")).split(`
792
+ `).map(r=>r.trim()).filter(r=>r.startsWith(`${Hr}/`)).map(r=>r.slice(Hr.length+1))}async function Ll(t,e,r){let n=r?["--heads",e,r]:["--heads",e],o=await t.listRemote(n),i=new Map;for(let s of o.split(`
793
+ `)){let[a,c]=s.trim().split(/\s+/);!a||!c||!/^[0-9a-f]{40}$/.test(a)||c.startsWith("refs/heads/")&&i.set(c.slice(11),a)}return i}var Hr,ks=x(()=>{"use strict";Hr="refs/codepipe/upstream"});import{homedir as FR}from"node:os";import{existsSync as GR,mkdirSync as KR,readFileSync as HR,writeFileSync as WR}from"node:fs";import{dirname as qR,join as YR}from"node:path";function Ml(){return ee("FARM_PINS")??YR(FR(),".codepipe","farm-pins.json")}function Ig(){let t=Ml();if(!GR(t))return{};try{return JSON.parse(HR(t,"utf-8"))}catch{return{}}}function VR(t){let e=Ml();KR(qR(e),{recursive:!0}),WR(e,JSON.stringify(t,null,2)+`
794
+ `,{mode:384})}function zR(t){return Ig()[t]}function $s(t,e){let r=Ig();r[t]=e,VR(r)}function xs(t,e){let r=ze(e),n=zR(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 ${Ml()}.`);return r}var Dl=x(()=>{"use strict";Ye();gt()});import{setTimeout as XR}from"node:timers/promises";import JR from"ws";function Ss(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new JR(r)}async function fr(t,e,r){return mr(t,e,"/projects",r)}async function Cg(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new V(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function Es(t,e,r,n){return mr(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function Pg(t,e,r,n){return mr(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function Ag(t,e,r,n){return mr(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function _g(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 V(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function Rs(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new V(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function Ul(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new V(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function jg(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await Ul(t,e),a=new Set;for(let c of s)c.id!==r.excludeProjectId&&c.trackerProvider==="internal"&&c.youtrackProjectKey&&a.add(c.youtrackProjectKey.toUpperCase());return a}catch(s){o=s,i<n-1&&await XR(r.delayMs??1500)}throw o}async function Ng(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 Xo(e)}if(!r.ok)throw new V(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function Og(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new V(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function Lg(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new V(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function Mg(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 V(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function Dg(t,e,r,n,o){return mr(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function Jo(t,e,r,n){return mr(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function Bl(t,e,r,n){await mr(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function Ug(t,e,r,n){return mr(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function Bg(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/repos/${encodeURIComponent(n)}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new V(o.status,s,a)}return s}async function se(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new V(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function mr(t,e,r,n){let o=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new V(o.status,s,a)}return s}async function Ts(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/deliverables`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new V(n.status,null,`GET /deliverables HTTP ${n.status}`);return(await n.json()).deliverables}var V,Xo,Le=x(()=>{"use strict";V=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};Xo=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});import{existsSync as cy,readFileSync as wT,readdirSync as bT}from"node:fs";import{join as ly}from"node:path";import{simpleGit as kT}from"simple-git";import{parse as vT}from"yaml";function js(t){let e=new Map,r=ly(t,ki);if(!cy(r))return e;let n;try{n=vT(wT(r,"utf-8"))}catch{return e}let o=n?.repos;if(!o||typeof o!="object")return e;for(let[i,s]of Object.entries(o)){if(!s||typeof s!="object")continue;let a=s,c=a.counts??{};typeof a.builtFromCommit=="string"&&e.set(i,{builtFromCommit:a.builtFromCommit,counts:{component:typeof c.component=="number"?c.component:0,code:typeof c.code=="number"?c.code:0,correlates:typeof c.correlates=="number"?c.correlates:0}})}return e}function $T(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return _r({modelFormatVersion:2,repos:e})}function uy(t,e){let r=ly(t,e);if(!cy(r))return[];let n=[];for(let o of bT(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...uy(t,i)):n.push(i)}return n}async function Ns(t,e,r={}){let n=[],o=0;for(let d of e){n.push(...d.files);let f=`model/derived/structure/${d.repo}`;for(let m of uy(t,f))d.emittedShardPaths.has(m)||(n.push({path:m,content:"",deleted:!0}),o++)}let i=js(t);for(let d of e)i.set(d.repo,{builtFromCommit:d.headCommit,counts:d.counts});n.push({path:ki,content:$T(i)});let s=ds(t),a=ag(s,r.halfLifeDays??lt.halfLifeDays);n.push({path:Ir,content:ps(a)});for(let d of e){let f=[];for(let m of s)for(let g of m.files)ne(g.key)?.repo===d.repo&&f.push({kind:"touched_by",from:Ee(m.taskKey),to:g.key,...g.churn!==void 0?{weight:g.churn}:{}});n.push({path:Aa(d.repo),content:Pr({modelFormatVersion:2,repo:d.repo,builtFromCommit:d.headCommit,edges:f})})}let c=kT(t),l=(await c.revparse(["HEAD"]).catch(()=>"")).trim(),u=`model: build ${e.map(d=>`${d.repo}@${d.headCommit.slice(0,10)}`).join(", ")}`;await Ce(t,n,u);let p=(await c.revparse(["HEAD"]).catch(()=>"")).trim();if(p!==l){let{rebuildSearchIndex:d}=await Promise.resolve().then(()=>(Wo(),Ho));await d(t).catch(()=>{})}return{committed:p!==l,filesWritten:n.filter(d=>!d.deleted).length,filesDeleted:o}}var dy=x(()=>{"use strict";M();Al();mt()});var Ms={};Ne(Ms,{bootstrapDaemonModel:()=>ST,bootstrapModelForTargets:()=>zl,bootstrapWorkspaceModel:()=>gy,modelBootstrapCommand:()=>Vl,modelBuildCommand:()=>Yl,modelIndexExists:()=>wy,rebuildWorkspaceModelIfStale:()=>RT,shouldAutoBootstrapModel:()=>ET,syncWorkspaceMirrors:()=>yy});import{existsSync as Ls}from"node:fs";import{join as hr}from"node:path";import{cancel as xT,intro as py,log as Hl,outro as Wl}from"@clack/prompts";import{simpleGit as ql}from"simple-git";function Os(t){xT(t),process.exit(1)}function fy(t,e,r){let n=t.spec.repos.filter(i=>!e||i.name===e);if(n.length===0)throw new Error(e?`repo "${e}" is not part of this project (see project.yaml)`:"the project has no repos configured");let o=[];for(let i of n){let s=i.mountAs==="."?t.root:hr(t.root,i.mountAs);if(!Ls(hr(s,".git"))){r(`${i.name}: no local clone at ${s} \u2014 skipped (run \`codepipe clone\` first)`);continue}o.push({name:i.name,dir:s,defaultBranch:i.defaultBranch||"main"})}if(o.length===0)throw new Error("nothing to do \u2014 no repo clones found");return o}async function my(t){let e=ql(t.dir),r=`origin/${t.defaultBranch}`;return await e.raw(["rev-parse","--verify",r]).then(()=>!0).catch(()=>!1)?r:"HEAD"}async function hy(t,e,r,n){let o=[];for(let i of e)try{let s=await Il({repo:i.name,repoDir:i.dir,contextDir:t,settings:r,ref:await my(i)});o.push(s),n(`${i.name}: ${s.counts.code} files, ${s.counts.component} components, ${s.counts.correlates} co-change edges @ ${s.headCommit.slice(0,10)}`)}catch(s){throw new Error(`${i.name}: ${s instanceof Error?s.message:String(s)}`)}return o}async function Yl(t){py("codepipe model build");let e=je();e||Os("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{let r=Kr(e.contextDir),n=fy(e,t.repo,s=>Hl.warn(s)),o=await hy(e.contextDir,n,r,s=>Hl.info(s)),i=await Ns(e.contextDir,o,{halfLifeDays:r.cochange.halfLifeDays});i.committed?Wl(`model updated: ${i.filesWritten} files written, ${i.filesDeleted} stale removed`):Wl("model already up to date (no changes)")}catch(r){Os(r instanceof Error?r.message:String(r))}}async function Vl(t){py("codepipe model bootstrap");let e=je();e||Os("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{await gy(e,t.repo,{onLog:r=>Hl.info(r)})}catch(r){Os(r instanceof Error?r.message:String(r))}Wl("bootstrap complete")}async function gy(t,e,r){let n=fy(t,e,r.onLog);return zl(t.contextDir,n,r)}async function zl(t,e,r){let n=Kr(t),o=await hy(t,e,n,r.onLog),i=Ah(t),s=Ph(n.issueKeyPattern,i),a=Gr([...n.ignore,...Fn]),c=[];for(let p of o){let d=e.find(m=>m.name===p.repo),f=await jh({repo:p.repo,repoDir:d.dir,headCommit:p.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:s,pathToCurrent:cs(p.identityTable),entityByKey:p.entityByKey,ignored:a,trackerProjectKey:i});c.push(f),r.onLog(`${p.repo}: ${f.size} task events mined from history`)}let{files:l,skippedPipeline:u}=Nh(t,c);return u>0&&r.onLog(`${u} events already recorded by the live pipeline \u2014 left untouched`),l.length>0&&await Ce(t,l,`model: bootstrap ${l.length} task events from history`),await Ns(t,o,{halfLifeDays:n.cochange.halfLifeDays}),{events:l.length}}async function ST(t,e,r,n){if(r.length===0)throw new Error("the project has no repos configured");let o=[];for(let s of r){let a=s.mountAs??s.name,c=a==="."?e.root:hr(e.root,a),l=s.defaultBranch||"main";c!==e.contextDir&&Ls(hr(c,".git"))?(await ql(c).fetch(["origin",l]).catch(()=>{}),o.push({name:s.name,dir:c,defaultBranch:l})):(n(`${s.name}: materializing clone in the daemon layout`),await pr(t,s),o.push({name:s.name,dir:Oe(t,s.name),defaultBranch:l}))}let i=await zl(e.contextDir,o,{onLog:n});return{repos:o.length,events:i.events}}async function yy(t,e){let r=new Map;for(let n of t.repos){if(!n.mirror)continue;let o=n.mountAs==="."?t.root:hr(t.root,n.mountAs);if(!Ls(hr(o,".git")))continue;let{syncUpstream:i}=await Promise.resolve().then(()=>(ks(),bs)),s=await i(n,o,{info:a=>e(`[mirror] ${a}`),warn:a=>e(`[mirror] ${a}`)});if(s.error||!s.upstreamHead){e(`[mirror] ${n.name}: sync failed (${s.error??"no upstream head"})`);continue}r.set(n.name,s.upstreamHead)}return r}function wy(t){return js(t).size>0}function ET(t){return Kr(t).enabled&&!wy(t)}async function RT(t,e={}){let r=e.onLog??(()=>{}),n=Kr(t.contextDir),o=await yy(t,r);if(!n.enabled)return{rebuilt:[],skipped:[]};let i=[],s=[],a=js(t.contextDir),c=[];for(let l of t.repos){let u=l.mountAs==="."?t.root:hr(t.root,l.mountAs);if(!Ls(hr(u,".git")))continue;let p=ql(u),d=l.defaultBranch||"main",f=null;if(l.mirror){if(f=o.get(l.name)??null,!f){r(`[mirror] ${l.name}: map not rebuilt \u2014 sync did not complete`);continue}}else e.fetch&&await p.fetch(["origin",d]).catch(()=>{});let m=f??await my({name:l.name,dir:u,defaultBranch:d}),g=(await p.revparse([m]).catch(()=>"")).trim();if(g){if(a.get(l.name)?.builtFromCommit===g){s.push(l.name);continue}try{c.push(await Il({repo:l.name,repoDir:u,contextDir:t.contextDir,settings:n,ref:g})),i.push(l.name)}catch(b){r(`[model] rebuild of ${l.name} failed: ${b instanceof Error?b.message:String(b)}`)}}}return c.length>0&&(await Ns(t.contextDir,c,{halfLifeDays:n.cochange.halfLifeDays}),r(`[model] release-path rebuild: ${i.join(", ")} (skipped up-to-date: ${s.join(", ")||"\u2014"})`)),{rebuilt:i,skipped:s}}var Zo=x(()=>{"use strict";mt();dy();Cl();Rl();ls();Ko();Dn();xt()});var ky={};Ne(ky,{computeDriftReport:()=>AT,supersededAdrIds:()=>by});import{existsSync as Xl,readFileSync as Jl,readdirSync as Zl}from"node:fs";import{join as Hn}from"node:path";import{parse as TT}from"yaml";import{simpleGit as IT}from"simple-git";function PT(t,e){let r=Hn(t,`model/derived/structure/${e}`),n=[],o="";if(!Xl(r))return{nodes:n,builtFromCommit:o};for(let i of Zl(r).sort()){if(!i.endsWith(".yaml"))continue;let s;try{let a=Gt(TT(Jl(Hn(r,i),"utf-8")));if(!a.ok)continue;s=a.value}catch{continue}o=s.builtFromCommit;for(let a of s.nodes){let c=ne(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 by(t){let e=new Set,r=Hn(t,"adr");if(!Xl(r))return e;for(let n of Zl(r).sort()){let o=/^(\d{4})-/.exec(n)?.[1];if(!(!o||!n.endsWith(".md")))try{let i=Jl(Hn(r,n),"utf-8").slice(0,600).toLowerCase();/status[^\n]*superseded/.test(i)&&e.add(`ADR-${o}`)}catch{}}return e}async function AT(t,e,r){let{nodes:n,builtFromCommit:o}=PT(e,r),i=(await IT(t).revparse(["HEAD"])).trim(),s=await Go(t,i),a=new Map(s.map(v=>[v.path,v.blobHash])),c=[],l=[],u=new Set,p=[];for(let v of n){if(v.level==="component"){p.push(v);continue}u.add(v.path);let y=a.get(v.path);y?v.contentHash&&y.slice(0,CT)!==v.contentHash&&c.push(v.key):l.push(v.key)}let d=0,f=new Map,m=new Set;for(let v of s){let y=v.path.lastIndexOf("/"),k=y<0?"":v.path.slice(0,y);f.has(k)||f.set(k,new Set),f.get(k).add(v.path),u.has(v.path)||d++;let C=k;for(;C!==""&&!m.has(C);)m.add(C),C=C.includes("/")?C.slice(0,C.lastIndexOf("/")):""}let g=new Map;for(let v of u){let y=v.lastIndexOf("/"),k=y<0?"":v.slice(0,y);g.has(k)||g.set(k,new Set),g.get(k).add(v)}for(let v of p){if(!m.has(v.path)){l.push(v.key);continue}let y=g.get(v.path)??new Set,k=f.get(v.path)??new Set;(y.size!==k.size||[...y].some(E=>!k.has(E)))&&c.push(v.key)}let b=[],w=by(e);if(w.size>0){let v=Hn(e,"model/facts/annotations"),y=new Map(n.filter(k=>k.entityId).map(k=>[k.entityId,k.key]));if(Xl(v))for(let k of Zl(v).sort()){if(!k.endsWith(".md"))continue;let C=k.replace(/\.md$/,""),E=y.get(C);if(E)try{(Jl(Hn(v,k),"utf-8").match(/\bADR-(\d{3,4})\b/g)??[]).map(N=>`ADR-${N.slice(4).padStart(4,"0")}`).some(N=>w.has(N))&&b.push(E)}catch{}}}return{repo:r,builtFromCommit:o,headCommit:i,stale:[...new Set(c)].sort(),orphaned:[...new Set(l)].sort(),superseded:[...new Set(b)].sort(),newFiles:d}}var CT,vy=x(()=>{"use strict";M();Ko();CT=12});import{execFileSync as BT}from"node:child_process";import{mkdtempSync as FT,mkdirSync as GT,readFileSync as xy,rmSync as KT,writeFileSync as HT}from"node:fs";import{tmpdir as WT}from"node:os";import{dirname as qT,join as Sy}from"node:path";function Ey(t="codepipe-context"){let e=FT(Sy(WT(),"codepipe-ssh-")),r=Sy(e,"id_ed25519");try{return BT("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:xy(r,"utf-8"),publicKey:xy(`${r}.pub`,"utf-8").trim()}}finally{KT(e,{recursive:!0,force:!0})}}async function Ry(t,e,r,n="codepipe-context"){let o=await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/keys`,{method:"POST",headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({title:n,key:r,read_only:!1})});if(o.ok)return;let i=await o.text();if(!(o.status===422&&/already in use/i.test(i)))throw new Error(`add deploy key failed: ${o.status} ${i}`)}function Ty(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 Iy(t,e){GT(qT(t),{recursive:!0});let r=e.endsWith(`
801
795
  `)?e:e+`
802
- `;return BT(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var ru=x(()=>{"use strict"});import{existsSync as Ry,mkdirSync as Ty}from"node:fs";import{dirname as Iy}from"node:path";import{simpleGit as Hn}from"simple-git";function KT(t,e,r="x-access-token"){let n=`${encodeURIComponent(r)}:${encodeURIComponent(e)}`,o=t.match(/^git@([^:]+):(.+)$/);if(o)return`https://${n}@${o[1]}/${o[2]}`;let i=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(i)return`https://${n}@${i[1]}/${i[2]}`;let s=t.match(/^https:\/\/(?:[^@/]+@)?(.+)$/);return s?`https://${n}@${s[1]}`:t}function HT(t,e){return e?.contextWrite?.token?{user:Io(t),secret:e.contextWrite.token}:t===kn.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===kn.bitbucket?e?.bitbucket?.apiToken?{user:Wt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function Cy(t,e){let r=e.sleep??(i=>new Promise(s=>setTimeout(s,i))),n=e.initialDelayMs??5e3,o=e.maxDelayMs??6e4;for(;;)try{return await t()}catch(i){if(!(i instanceof Us))throw i;e.log.warn(`[ctx] ${i.message} \u2014 retrying in ${Math.round(n/1e3)}s (the HUB may be deploying)`),await r(n),n=Math.min(n*2,o)}}async function Bs(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await se(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new Us(c)}let s=i.contextRepo;if(!s)return o.warn("[ctx] project has no Context Repo on HUB \u2014 daemon stays headless (no config report)"),null;let a=HT(Or(s.cloneUrl),r);if(a){let c=await WT({ctx:s,contextDir:n,cred:a,log:o});if(c)return c;o.warn("[ctx] token clone/update failed")}if(r?.contextSsh?.privateKey){let c=await qT({ctx:s,contextDir:n,privateKey:r.contextSsh.privateKey,log:o});if(c)return c;o.warn("[ctx] SSH deploy-key clone failed")}return o.warn("[ctx] no usable context-host/contextWrite token or SSH deploy key \u2014 can't clone the Context Repo on the farm; config_observation + artifact commits disabled."),null}async function WT(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=KT(e.cloneUrl,n.secret,n.user),s=e.branch,a=encodeURIComponent(n.secret),c=l=>l.split(n.secret).join("***").split(a).join("***");try{if(Ry(`${r}/.git`)){let l=Hn(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=el(r);await l.reset(["--hard",`origin/${s}`]),tl(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Ty(Iy(r),{recursive:!0}),await Hn().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await Py(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 qT(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=Ey(i,n),a=Sy(e.cloneUrl),c=e.branch;try{if(Ry(`${r}/.git`)){let l=Hn(r);await l.addConfig("core.sshCommand",s,!1,"local"),await l.remote(["set-url","origin",a]),await l.fetch("origin",c),await l.checkout(c);let u=el(r);await l.reset(["--hard",`origin/${c}`]),tl(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Ty(Iy(r),{recursive:!0}),await Hn().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await Hn(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await Py(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 Py(t){let e=Hn(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 Us,nu=x(()=>{"use strict";M();Le();zt();ru();Us=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as YT}from"node:child_process";function VT(){try{return YT("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function _y(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:VT(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var jy=x(()=>{"use strict"});import{homedir as zT}from"node:os";import{mkdirSync as XT,readFileSync as JT,writeFileSync as ZT,existsSync as Ny}from"node:fs";import{dirname as QT,join as iu}from"node:path";function eI(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function Tt(t){let e=ee("SANDBOX_CONFIG");if(e)return e;let r=iu(zT(),".codepipe","worker");return t?iu(r,"profiles",t,"config.json"):iu(r,"config.json")}function Oy(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function Ge(t){let e=Tt(t),r=null;return Ny(e)&&(r=JSON.parse(JT(e,"utf-8"))),r?(r.planningLane=eI(),r):null}function Ly(t,e){let r=Tt(e);XT(QT(r),{recursive:!0}),ZT(r,JSON.stringify(t,null,2)+`
803
- `,{mode:384})}var Fs=x(()=>{"use strict";Ye();Ny(".env")&&process.loadEnvFile(".env")});import tI from"ws";var Wn,su=x(()=>{"use strict";Wn=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};e&&(n.signal=e);let o=r?`${this.hubUrl}/jobs/claim?lane=${encodeURIComponent(r)}`:`${this.hubUrl}/jobs/claim`;return fetch(o,n)}async submitResult(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/jobs/result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});if(!r.ok)throw new Error(`submitResult failed: ${r.status} ${await r.text()}`)}async heartbeat(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e})};r&&(n.signal=r);let o=await fetch(`${this.hubUrl}/jobs/heartbeat`,n);if(o.status===410)return"claim_lost";if(!o.ok)throw new Error(`heartbeat failed: ${o.status} ${await o.text()}`);return"ok"}async releaseJob(e,r,n){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e,reason:r})};n&&(o.signal=n);let i=await fetch(`${this.hubUrl}/jobs/release`,o);if(!i.ok&&i.status!==409&&i.status!==404)throw new Error(`release failed: ${i.status} ${await i.text()}`)}openControlSocket(){if(!this.token)throw new Error("no sandbox token");let e=this.hubUrl.replace(/^http/,"ws")+`/sandbox/connect?token=${encodeURIComponent(this.token)}`;return new tI(e)}}});import{hostname as rI}from"node:os";async function Wr(t){let e=Ge(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Tt(t.profile)}.`),process.exit(1));let r=t.name??rI(),n=_y({projects:t.projects??[],llm:t.llm??null}),o=new Wn(t.hub.replace(/\/$/,"")),i=ts(),s=ze(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});Ly({hubUrl:t.hub.replace(/\/$/,""),sandboxId:a,token:c,name:r,llm:t.llm??null,sealPublicKey:i.publicKey,sealPrivateKey:i.privateKey},t.profile),console.log(`registered as ${a} (${r}) at ${t.hub}`),console.log(`config saved to ${Tt(t.profile)}`),console.log(""),console.log(" cred-channel key fingerprint (confirm this on the CLI \u2014 pin-on-register):"),console.log(` ${s}`),console.log("")}var My=x(()=>{"use strict";gt();jy();Fs();su()});function Dy(t){return t?`Write ALL user-visible text \u2014 full replies and the brief status notes you emit between tool calls alike \u2014 in ${t}, regardless of the language the user writes in (the project pinned ${t} for the chat).`:"Write ALL user-visible text \u2014 full replies and the brief status notes you emit between tool calls alike \u2014 in the language of the user's most recent chat message. When the user switches language mid-conversation, switch with them. Judge the language by the human prose only: ignore code snippets, file paths and identifiers. If a message is too short to tell (a bare keyword, pure code), keep the language of the conversation so far."}function Gs(t){return t?`Write ALL user-facing prose \u2014 brief status notes between tool calls, questions, summaries and the bodies of Markdown artifacts you produce for humans \u2014 in ${t} (the project's configured language), unless your prompt pins a different language for a specific output. In-repo content (code, code comments, commit messages) follows the project's existing conventions and any explicit instructions in your prompt.`:"Write ALL user-facing prose \u2014 brief status notes between tool calls, questions, summaries and the bodies of Markdown artifacts you produce for humans \u2014 in the language of the task description and user input embedded in your prompt, NOT the language the surrounding instructions are written in. Judge that language by the human prose only, ignoring code snippets, file paths and identifiers. In-repo content (code, code comments, commit messages) follows the project's existing conventions instead."}function Uy(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 qn(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 Ks=x(()=>{"use strict"});import{spawn as nI}from"node:child_process";function au(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function iI(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 sI(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function qr(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function cu(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}})+`
804
- `}async function Ky(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new It;let r=qn(e.metadata),n=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",Dy(r)];e.model&&e.model.trim().length>0&&n.push("--model",e.model.trim()),e.effort&&e.effort.trim().length>0&&(await lu(t)?n.push("--effort",e.effort.trim()):console.warn(`[claude] effort '${e.effort.trim()}' requested but this Claude Code does not support --effort \u2014 running at the default effort`));for(let l of e.addDirs??[])n.push("--add-dir",l);let o=e.onActivity,i=l=>{if(o)try{o(l)}catch{}},s=[],a=null,c=l=>{let u=Date.now(),p=l.type;if(p==="assistant"){let d=l.message;for(let f of d?.content??[]){let m=f.type;if(m==="text"){let g=String(f.text??"").trim();g&&i({ts:u,kind:"text",author:"agent",text:au(g,By)})}else if(m==="tool_use"){let g=String(f.name??""),b=f.input?.file_path??f.input?.path,w=iI(b,e.workspaceDir);i({ts:u,kind:"tool",author:"agent",tool:g,...w?{file:w}:{}})}}return}if(p==="user"){let d=l.message;for(let f of d?.content??[])if(f.type==="tool_result"){let m=f.is_error===!0,g=m?au(sI(f.content),200):"";i({ts:u,kind:"tool_result",author:"agent",isError:m,...g?{text:g}:{}})}return}if(p==="result"){a=l;let d=String(l.subtype??"").trim();i({ts:u,kind:"result",author:"agent",...d?{text:d}:{}});return}if(p==="system"){let d=String(l.subtype??"").trim();d&&i({ts:u,kind:"system",author:"agent",text:d})}};return i({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((l,u)=>{let p=nI(t,n,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});p.stdout.setEncoding("utf-8"),p.stderr.setEncoding("utf-8");let d=!1,f=!1,m=null,g=()=>{d=!0,p.kill("SIGTERM"),m=setTimeout(()=>p.kill("SIGKILL"),Fy)};e.signal?.addEventListener("abort",g,{once:!0});let b=null,w=()=>{b&&clearTimeout(b),b=setTimeout(()=>{f=!0,console.warn(`[claude:chat] idle for ${Gy}ms \u2014 ending session`),p.kill("SIGTERM"),m=setTimeout(()=>p.kill("SIGKILL"),Fy)},Gy)},v=()=>{m&&clearTimeout(m),b&&clearTimeout(b),e.signal?.removeEventListener("abort",g)},y=!0,k=$=>{if(!(!y||p.stdin.destroyed))try{p.stdin.write($)}catch{}};k(cu(e.prompt)),w(),(async()=>{try{for await(let $ of e.interactive.inbox){if(d||!y)break;if(w(),$.kind==="user")i({ts:Date.now(),kind:"text",author:"user",text:au($.text,By)}),k(cu($.text,Uy(r)));else{k(cu(oI)),y=!1;try{p.stdin.end()}catch{}break}}}catch{}})();let C="",E=$=>{let A;try{A=JSON.parse($)}catch{return}c(A)};p.stdout.on("data",$=>{s.push($),w(),C+=$;let A;for(;(A=C.indexOf(`
796
+ `;return HT(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var ru=x(()=>{"use strict"});import{existsSync as Cy,mkdirSync as Py}from"node:fs";import{dirname as Ay}from"node:path";import{simpleGit as Wn}from"simple-git";function YT(t,e,r="x-access-token"){let n=`${encodeURIComponent(r)}:${encodeURIComponent(e)}`,o=t.match(/^git@([^:]+):(.+)$/);if(o)return`https://${n}@${o[1]}/${o[2]}`;let i=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(i)return`https://${n}@${i[1]}/${i[2]}`;let s=t.match(/^https:\/\/(?:[^@/]+@)?(.+)$/);return s?`https://${n}@${s[1]}`:t}function VT(t,e){return e?.contextWrite?.token?{user:Co(t),secret:e.contextWrite.token}:t===vn.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===vn.bitbucket?e?.bitbucket?.apiToken?{user:qt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function _y(t,e){let r=e.sleep??(i=>new Promise(s=>setTimeout(s,i))),n=e.initialDelayMs??5e3,o=e.maxDelayMs??6e4;for(;;)try{return await t()}catch(i){if(!(i instanceof Us))throw i;e.log.warn(`[ctx] ${i.message} \u2014 retrying in ${Math.round(n/1e3)}s (the HUB may be deploying)`),await r(n),n=Math.min(n*2,o)}}async function Bs(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await se(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new Us(c)}let s=i.contextRepo;if(!s)return o.warn("[ctx] project has no Context Repo on HUB \u2014 daemon stays headless (no config report)"),null;let a=VT(Lr(s.cloneUrl),r);if(a){let c=await zT({ctx:s,contextDir:n,cred:a,log:o});if(c)return c;o.warn("[ctx] token clone/update failed")}if(r?.contextSsh?.privateKey){let c=await XT({ctx:s,contextDir:n,privateKey:r.contextSsh.privateKey,log:o});if(c)return c;o.warn("[ctx] SSH deploy-key clone failed")}return o.warn("[ctx] no usable context-host/contextWrite token or SSH deploy key \u2014 can't clone the Context Repo on the farm; config_observation + artifact commits disabled."),null}async function zT(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=YT(e.cloneUrl,n.secret,n.user),s=e.branch,a=encodeURIComponent(n.secret),c=l=>l.split(n.secret).join("***").split(a).join("***");try{if(Cy(`${r}/.git`)){let l=Wn(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=el(r);await l.reset(["--hard",`origin/${s}`]),tl(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Py(Ay(r),{recursive:!0}),await Wn().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await jy(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 XT(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=Iy(i,n),a=Ty(e.cloneUrl),c=e.branch;try{if(Cy(`${r}/.git`)){let l=Wn(r);await l.addConfig("core.sshCommand",s,!1,"local"),await l.remote(["set-url","origin",a]),await l.fetch("origin",c),await l.checkout(c);let u=el(r);await l.reset(["--hard",`origin/${c}`]),tl(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Py(Ay(r),{recursive:!0}),await Wn().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await Wn(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await jy(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 jy(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 Us,nu=x(()=>{"use strict";M();Le();Xt();ru();Us=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as JT}from"node:child_process";function ZT(){try{return JT("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function Oy(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:ZT(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var Ly=x(()=>{"use strict"});import{homedir as QT}from"node:os";import{mkdirSync as eI,readFileSync as tI,writeFileSync as rI,existsSync as My}from"node:fs";import{dirname as nI,join as iu}from"node:path";function oI(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function Tt(t){let e=ee("SANDBOX_CONFIG");if(e)return e;let r=iu(QT(),".codepipe","worker");return t?iu(r,"profiles",t,"config.json"):iu(r,"config.json")}function Dy(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function Ge(t){let e=Tt(t),r=null;return My(e)&&(r=JSON.parse(tI(e,"utf-8"))),r?(r.planningLane=oI(),r):null}function Uy(t,e){let r=Tt(e);eI(nI(r),{recursive:!0}),rI(r,JSON.stringify(t,null,2)+`
797
+ `,{mode:384})}var Fs=x(()=>{"use strict";Ye();My(".env")&&process.loadEnvFile(".env")});import iI from"ws";var qn,su=x(()=>{"use strict";qn=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};e&&(n.signal=e);let o=r?`${this.hubUrl}/jobs/claim?lane=${encodeURIComponent(r)}`:`${this.hubUrl}/jobs/claim`;return fetch(o,n)}async submitResult(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/jobs/result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});if(!r.ok)throw new Error(`submitResult failed: ${r.status} ${await r.text()}`)}async heartbeat(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e})};r&&(n.signal=r);let o=await fetch(`${this.hubUrl}/jobs/heartbeat`,n);if(o.status===410)return"claim_lost";if(!o.ok)throw new Error(`heartbeat failed: ${o.status} ${await o.text()}`);return"ok"}async releaseJob(e,r,n){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e,reason:r})};n&&(o.signal=n);let i=await fetch(`${this.hubUrl}/jobs/release`,o);if(!i.ok&&i.status!==409&&i.status!==404)throw new Error(`release failed: ${i.status} ${await i.text()}`)}openControlSocket(){if(!this.token)throw new Error("no sandbox token");let e=this.hubUrl.replace(/^http/,"ws")+`/sandbox/connect?token=${encodeURIComponent(this.token)}`;return new iI(e)}}});import{hostname as sI}from"node:os";async function qr(t){let e=Ge(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Tt(t.profile)}.`),process.exit(1));let r=t.name??sI(),n=Oy({projects:t.projects??[],llm:t.llm??null}),o=new qn(t.hub.replace(/\/$/,"")),i=ts(),s=ze(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});Uy({hubUrl:t.hub.replace(/\/$/,""),sandboxId:a,token:c,name:r,llm:t.llm??null,sealPublicKey:i.publicKey,sealPrivateKey:i.privateKey},t.profile),console.log(`registered as ${a} (${r}) at ${t.hub}`),console.log(`config saved to ${Tt(t.profile)}`),console.log(""),console.log(" cred-channel key fingerprint (confirm this on the CLI \u2014 pin-on-register):"),console.log(` ${s}`),console.log("")}var By=x(()=>{"use strict";gt();Ly();Fs();su()});function Fy(t){return t?`Write ALL user-visible text \u2014 full replies and the brief status notes you emit between tool calls alike \u2014 in ${t}, regardless of the language the user writes in (the project pinned ${t} for the chat).`:"Write ALL user-visible text \u2014 full replies and the brief status notes you emit between tool calls alike \u2014 in the language of the user's most recent chat message. When the user switches language mid-conversation, switch with them. Judge the language by the human prose only: ignore code snippets, file paths and identifiers. If a message is too short to tell (a bare keyword, pure code), keep the language of the conversation so far."}function Gs(t){return t?`Write ALL user-facing prose \u2014 brief status notes between tool calls, questions, summaries and the bodies of Markdown artifacts you produce for humans \u2014 in ${t} (the project's configured language), unless your prompt pins a different language for a specific output. In-repo content (code, code comments, commit messages) follows the project's existing conventions and any explicit instructions in your prompt.`:"Write ALL user-facing prose \u2014 brief status notes between tool calls, questions, summaries and the bodies of Markdown artifacts you produce for humans \u2014 in the language of the task description and user input embedded in your prompt, NOT the language the surrounding instructions are written in. Judge that language by the human prose only, ignoring code snippets, file paths and identifiers. In-repo content (code, code comments, commit messages) follows the project's existing conventions instead."}function Gy(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 Yn(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 Ks=x(()=>{"use strict"});import{spawn as aI}from"node:child_process";function au(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function lI(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 uI(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Yr(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function cu(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}})+`
798
+ `}async function qy(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new It;let r=Yn(e.metadata),n=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",Fy(r)];e.model&&e.model.trim().length>0&&n.push("--model",e.model.trim()),e.effort&&e.effort.trim().length>0&&(await lu(t)?n.push("--effort",e.effort.trim()):console.warn(`[claude] effort '${e.effort.trim()}' requested but this Claude Code does not support --effort \u2014 running at the default effort`));for(let l of e.addDirs??[])n.push("--add-dir",l);let o=e.onActivity,i=l=>{if(o)try{o(l)}catch{}},s=[],a=null,c=l=>{let u=Date.now(),p=l.type;if(p==="assistant"){let d=l.message;for(let f of d?.content??[]){let m=f.type;if(m==="text"){let g=String(f.text??"").trim();g&&i({ts:u,kind:"text",author:"agent",text:au(g,Ky)})}else if(m==="tool_use"){let g=String(f.name??""),b=f.input?.file_path??f.input?.path,w=lI(b,e.workspaceDir);i({ts:u,kind:"tool",author:"agent",tool:g,...w?{file:w}:{}})}}return}if(p==="user"){let d=l.message;for(let f of d?.content??[])if(f.type==="tool_result"){let m=f.is_error===!0,g=m?au(uI(f.content),200):"";i({ts:u,kind:"tool_result",author:"agent",isError:m,...g?{text:g}:{}})}return}if(p==="result"){a=l;let d=String(l.subtype??"").trim();i({ts:u,kind:"result",author:"agent",...d?{text:d}:{}});return}if(p==="system"){let d=String(l.subtype??"").trim();d&&i({ts:u,kind:"system",author:"agent",text:d})}};return i({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((l,u)=>{let p=aI(t,n,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});p.stdout.setEncoding("utf-8"),p.stderr.setEncoding("utf-8");let d=!1,f=!1,m=null,g=()=>{d=!0,p.kill("SIGTERM"),m=setTimeout(()=>p.kill("SIGKILL"),Hy)};e.signal?.addEventListener("abort",g,{once:!0});let b=null,w=()=>{b&&clearTimeout(b),b=setTimeout(()=>{f=!0,console.warn(`[claude:chat] idle for ${Wy}ms \u2014 ending session`),p.kill("SIGTERM"),m=setTimeout(()=>p.kill("SIGKILL"),Hy)},Wy)},v=()=>{m&&clearTimeout(m),b&&clearTimeout(b),e.signal?.removeEventListener("abort",g)},y=!0,k=$=>{if(!(!y||p.stdin.destroyed))try{p.stdin.write($)}catch{}};k(cu(e.prompt)),w(),(async()=>{try{for await(let $ of e.interactive.inbox){if(d||!y)break;if(w(),$.kind==="user")i({ts:Date.now(),kind:"text",author:"user",text:au($.text,Ky)}),k(cu($.text,Gy(r)));else{k(cu(cI)),y=!1;try{p.stdin.end()}catch{}break}}}catch{}})();let C="",E=$=>{let A;try{A=JSON.parse($)}catch{return}c(A)};p.stdout.on("data",$=>{s.push($),w(),C+=$;let A;for(;(A=C.indexOf(`
805
799
  `))!==-1;){let N=C.slice(0,A).trim();C=C.slice(A+1),N&&E(N)}}),p.stderr.on("data",$=>{s.push($);for(let A of $.split(`
806
- `)){let N=A.trim();N&&console.warn(`[claude:chat:stderr] ${N}`)}}),p.on("error",$=>{v(),u($)}),p.on("close",$=>{if(v(),d){u(new It);return}if(f){u(new Error("chat session ended: idle for too long without a reply"));return}C.trim()&&E(C.trim()),console.log(`[claude:chat] exit code=${$}`),l({artifactPaths:[],log:s.join(""),usage:aI(a)})})})}function aI(t){let e=ut();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=qr(r.input_tokens),e.outputTokens=qr(r.output_tokens),e.cacheReadInputTokens=qr(r.cache_read_input_tokens),e.cacheCreationInputTokens=qr(r.cache_creation_input_tokens)),e.totalCostUsd=qr(t.total_cost_usd),e.numTurns=qr(t.num_turns),e.durationMs=qr(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var By,Fy,Gy,oI,Hy=x(()=>{"use strict";M();hr();Ks();By=16e3,Fy=5e3,Gy=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),oI="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{execFile as cI,spawn as lI}from"node:child_process";import{existsSync as uI}from"node:fs";function dI(t,e,r,n){let o=e??"",i=/hit your (session|weekly|usage) limit/i.exec(o);if(t!==429&&!i)return null;let s={};if(/weekly limit/i.test(o)||r?.rateLimitType==="seven_day"?s.kind="weekly":(/session limit/i.test(o)||r?.rateLimitType==="five_hour")&&(s.kind="session"),r&&r.resetsAt>0){let u=Math.round(r.resetsAt*1e3);if(u>n)return s.resetAtMs=u,s}let a=/resets(?:\s+at)?\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)\s*\(UTC\)/i.exec(o);if(a){let u=Number(a[1])%12;a[3].toLowerCase()==="pm"&&(u+=12);let p=a[2]?Number(a[2]):0,d=new Date(n);return d.setUTCHours(u,p,0,0),d.getTime()<=n&&d.setUTCDate(d.getUTCDate()+1),s.resetAtMs=d.getTime(),s}let c=/retry[\s-]*after[:\s]*(\d+)|reset[s]?\s+in[:\s]*(\d+)/i.exec(o),l=c?Number(c[1]??c[2]):NaN;return Number.isFinite(l)&&l>0&&(s.resetAtMs=n+l*1e3),s}function fI(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function lu(t){let e=uu.get(t);return e||(e=new Promise(r=>{cI(t,["--help"],{timeout:15e3},(n,o,i)=>{if(n){uu.delete(t),r(!1);return}r(`${o}
807
- ${i}`.includes("--effort"))})}),uu.set(t,e)),e}function Wy(t){let e;try{e=JSON.parse(t)}catch{return console.log(`[claude] ${t.slice(0,200)}`),null}let r=e.type;if(r==="system"){let n=e.subtype??"";return console.log(`[claude] system ${n}`),e}if(r==="assistant"){let n=e.message;for(let o of n?.content??[]){let i=o.type;if(i==="text"){let s=String(o.text??"").trim();s&&console.log(`[claude] text: ${gr(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=gI(s,a);console.log(`[claude] tool_use ${s}${c?` ${c}`:""}`)}}return e}if(r==="user"){let n=e.message;for(let o of n?.content??[])if(o.type==="tool_result")if(o.is_error===!0){let i=Yy(o.content);console.log(`[claude] tool_result (error)${i?`: ${gr(i,200)}`:""}`)}else console.log("[claude] tool_result");return e}if(r==="result"){let n=e.subtype??"",o=e.num_turns,i=e.total_cost_usd;return console.log(`[claude] result ${n} turns=${o} cost=$${i}`),e}return console.log(`[claude] ${String(r)} ${gr(JSON.stringify(e),200)}`),e}function mI(t,e,r){let n=t===0?["claude reported an error"]:[`claude exited with code ${t}`];if(e){let o=typeof e.result=="string"?e.result.trim():"",i=e.api_error_status,s=e.subtype;o?n.push(gr(o,500)):typeof s=="string"&&s!=="success"&&n.push(s),typeof i=="number"&&n.push(`(api_status=${i})`)}return n.length===1&&r.trim()&&n.push(gr(r.trim().split(`
800
+ `)){let N=A.trim();N&&console.warn(`[claude:chat:stderr] ${N}`)}}),p.on("error",$=>{v(),u($)}),p.on("close",$=>{if(v(),d){u(new It);return}if(f){u(new Error("chat session ended: idle for too long without a reply"));return}C.trim()&&E(C.trim()),console.log(`[claude:chat] exit code=${$}`),l({artifactPaths:[],log:s.join(""),usage:dI(a)})})})}function dI(t){let e=ut();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=Yr(r.input_tokens),e.outputTokens=Yr(r.output_tokens),e.cacheReadInputTokens=Yr(r.cache_read_input_tokens),e.cacheCreationInputTokens=Yr(r.cache_creation_input_tokens)),e.totalCostUsd=Yr(t.total_cost_usd),e.numTurns=Yr(t.num_turns),e.durationMs=Yr(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var Ky,Hy,Wy,cI,Yy=x(()=>{"use strict";M();gr();Ks();Ky=16e3,Hy=5e3,Wy=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),cI="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{execFile as pI,spawn as fI}from"node:child_process";import{existsSync as mI}from"node:fs";function hI(t,e,r,n){let o=e??"",i=/hit your (session|weekly|usage) limit/i.exec(o);if(t!==429&&!i)return null;let s={};if(/weekly limit/i.test(o)||r?.rateLimitType==="seven_day"?s.kind="weekly":(/session limit/i.test(o)||r?.rateLimitType==="five_hour")&&(s.kind="session"),r&&r.resetsAt>0){let u=Math.round(r.resetsAt*1e3);if(u>n)return s.resetAtMs=u,s}let a=/resets(?:\s+at)?\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)\s*\(UTC\)/i.exec(o);if(a){let u=Number(a[1])%12;a[3].toLowerCase()==="pm"&&(u+=12);let p=a[2]?Number(a[2]):0,d=new Date(n);return d.setUTCHours(u,p,0,0),d.getTime()<=n&&d.setUTCDate(d.getUTCDate()+1),s.resetAtMs=d.getTime(),s}let c=/retry[\s-]*after[:\s]*(\d+)|reset[s]?\s+in[:\s]*(\d+)/i.exec(o),l=c?Number(c[1]??c[2]):NaN;return Number.isFinite(l)&&l>0&&(s.resetAtMs=n+l*1e3),s}function yI(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function lu(t){let e=uu.get(t);return e||(e=new Promise(r=>{pI(t,["--help"],{timeout:15e3},(n,o,i)=>{if(n){uu.delete(t),r(!1);return}r(`${o}
801
+ ${i}`.includes("--effort"))})}),uu.set(t,e)),e}function Vy(t){let e;try{e=JSON.parse(t)}catch{return console.log(`[claude] ${t.slice(0,200)}`),null}let r=e.type;if(r==="system"){let n=e.subtype??"";return console.log(`[claude] system ${n}`),e}if(r==="assistant"){let n=e.message;for(let o of n?.content??[]){let i=o.type;if(i==="text"){let s=String(o.text??"").trim();s&&console.log(`[claude] text: ${yr(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=kI(s,a);console.log(`[claude] tool_use ${s}${c?` ${c}`:""}`)}}return e}if(r==="user"){let n=e.message;for(let o of n?.content??[])if(o.type==="tool_result")if(o.is_error===!0){let i=Xy(o.content);console.log(`[claude] tool_result (error)${i?`: ${yr(i,200)}`:""}`)}else console.log("[claude] tool_result");return e}if(r==="result"){let n=e.subtype??"",o=e.num_turns,i=e.total_cost_usd;return console.log(`[claude] result ${n} turns=${o} cost=$${i}`),e}return console.log(`[claude] ${String(r)} ${yr(JSON.stringify(e),200)}`),e}function wI(t,e,r){let n=t===0?["claude reported an error"]:[`claude exited with code ${t}`];if(e){let o=typeof e.result=="string"?e.result.trim():"",i=e.api_error_status,s=e.subtype;o?n.push(yr(o,500)):typeof s=="string"&&s!=="success"&&n.push(s),typeof i=="number"&&n.push(`(api_status=${i})`)}return n.length===1&&r.trim()&&n.push(yr(r.trim().split(`
808
802
  `).slice(-5).join(`
809
- `),500)),n.join(" \u2014 ")}function hI(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 Yy(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function gI(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=${gr(r,80)}`}return""}function gr(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function Xe(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function yI(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=Xe(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:Xe(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 du(t,e,r,n){let o=ut(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=Xe(i.input_tokens),o.outputTokens=Xe(i.output_tokens),o.cacheReadInputTokens=Xe(i.cache_read_input_tokens),o.cacheCreationInputTokens=Xe(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=Xe(t?.total_cost_usd),o.numTurns=t&&Xe(t.num_turns)>0?Xe(t.num_turns):r,o.durationMs=Xe(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}function wI(t,e){let r=Date.now(),n=t.type;if(n==="system"){let o=String(t.subtype??"").trim();return o?[{ts:r,kind:"system",text:o}]:[]}if(n==="assistant"){let o=t.message,i=[];for(let s of o?.content??[]){let a=s.type;if(a==="text"){let c=String(s.text??"").trim();c&&i.push({ts:r,kind:"text",text:gr(c,qy)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,p=bI(u,e);i.push({ts:r,kind:"tool",tool:c,...p?{file:p}:{}})}}return i}if(n==="user"){let o=t.message,i=[];for(let s of o?.content??[])if(s.type==="tool_result"){let a=s.is_error===!0,c=a?gr(Yy(s.content),qy):"";i.push({ts:r,kind:"tool_result",isError:a,...c?{text:c}:{}})}return i}if(n==="result"){let o=String(t.subtype??"").trim(),i=typeof t.num_turns=="number"?t.num_turns:void 0,s=typeof t.total_cost_usd=="number"?t.total_cost_usd:void 0;return[{ts:r,kind:"result",...o?{text:o}:{},...i!==void 0?{turns:i}:{},...s!==void 0?{costUsd:s}:{}}]}return[]}function bI(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 Me,It,pI,uu,Qo,qy,hr=x(()=>{"use strict";M();Hy();Ks();Me=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}};It=class extends Error{usage;constructor(e){super("run aborted by pause"),this.usage=e,this.name="ClaudeAbortError"}},pI=5e3;uu=new Map;Qo=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return Ky(this.binary,e);if(e.signal?.aborted)throw new It;let r=["-p",fI(e.prompt),"--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",Gs(qn(e.metadata))];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());let n=null;e.effort&&e.effort.trim().length>0&&(await lu(this.binary)?(n=e.effort.trim(),r.push("--effort",n)):console.warn(`[claude] effort '${e.effort.trim()}' requested but this Claude Code does not support --effort \u2014 running at the default effort`));for(let g of e.addDirs??[])r.push("--add-dir",g);e.settings&&Object.keys(e.settings).length>0&&r.push("--settings",JSON.stringify(e.settings));let o=[],i=[],s=null,a={input:0,output:0,cacheRead:0,cacheCreate:0},c=0,l="",u=null,p=g=>{if(g){if(g.type==="result"){s=g;return}if(g.type==="rate_limit_event"){let b=yI(g.rate_limit_info);b&&(!u||b.utilization>u.utilization)&&(u=b);return}if(g.type==="assistant"){let b=g.message;typeof b?.model=="string"&&(l=b.model);let w=b?.usage;w&&(c+=1,a.input+=Xe(w.input_tokens),a.output+=Xe(w.output_tokens),a.cacheRead+=Xe(w.cache_read_input_tokens),a.cacheCreate+=Xe(w.cache_creation_input_tokens))}}},d=e.role,f=e.onActivity,m=g=>{if(f)for(let b of wI(g,e.workspaceDir))try{f(b)}catch{}};return f?.({ts:Date.now(),kind:"start",text:`${d} job started`}),console.log(`[claude] spawn ${this.binary} role=${d}`+(e.model?` model=${e.model}`:"")+(n?` effort=${n}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((g,b)=>{let w=lI(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"}});w.stdout.setEncoding("utf-8"),w.stderr.setEncoding("utf-8");let v=!1,y=null,k=()=>{v=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${d}`),w.kill("SIGTERM"),y=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),w.kill("SIGKILL")},pI)};e.signal?.addEventListener("abort",k,{once:!0});let C=()=>{y&&clearTimeout(y),e.signal?.removeEventListener("abort",k)},E="";w.stdout.on("data",$=>{o.push($),E+=$;let A;for(;(A=E.indexOf(`
810
- `))!==-1;){let N=E.slice(0,A).trim();if(E=E.slice(A+1),N){let B=Wy(N);p(B),B&&m(B)}}}),w.stderr.on("data",$=>{o.push($),i.push($);for(let A of $.split(`
811
- `)){let N=A.trim();N&&console.warn(`[claude:stderr] ${N}`)}}),w.on("error",$=>{C(),b($)}),w.on("close",$=>{if(C(),v){b(new It(du(s,a,c,l)));return}if(E.trim()){let N=Wy(E.trim());p(N),N&&m(N)}let A=s?.is_error===!0;if($!==0||A){let N=typeof s?.api_error_status=="number"?s.api_error_status:void 0,B=typeof s?.subtype=="string"?s.subtype:void 0,H=typeof s?.result=="string"?s.result:void 0,j=dI(N,H,u,Date.now());b(new Me(mI($,s,i.join("")),{code:$,apiErrorStatus:N,subtype:B,resultText:H,retryAfterMs:hI(s),...j?{rateLimited:j}:{},usage:du(s,a,c,l)}));return}console.log("[claude] exit code=0"),g({artifactPaths:[],log:o.join(""),usage:du(s,a,c,l),...u?{rateLimit:u}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(n=>n.includes("/")&&uI(n))}};qy=200});import{mkdirSync as kI,writeFileSync as Yr}from"node:fs";import{dirname as vI,join as Vr}from"node:path";function Vy(t,e,r){let n=Vr(t,e);kI(vI(n),{recursive:!0}),Yr(n,r)}function $I(t,e,r){return`# ${t} \u2014 Estimate
803
+ `),500)),n.join(" \u2014 ")}function bI(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 Xy(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function kI(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=${yr(r,80)}`}return""}function yr(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function Xe(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function vI(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=Xe(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:Xe(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 du(t,e,r,n){let o=ut(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=Xe(i.input_tokens),o.outputTokens=Xe(i.output_tokens),o.cacheReadInputTokens=Xe(i.cache_read_input_tokens),o.cacheCreationInputTokens=Xe(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=Xe(t?.total_cost_usd),o.numTurns=t&&Xe(t.num_turns)>0?Xe(t.num_turns):r,o.durationMs=Xe(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}function $I(t,e){let r=Date.now(),n=t.type;if(n==="system"){let o=String(t.subtype??"").trim();return o?[{ts:r,kind:"system",text:o}]:[]}if(n==="assistant"){let o=t.message,i=[];for(let s of o?.content??[]){let a=s.type;if(a==="text"){let c=String(s.text??"").trim();c&&i.push({ts:r,kind:"text",text:yr(c,zy)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,p=xI(u,e);i.push({ts:r,kind:"tool",tool:c,...p?{file:p}:{}})}}return i}if(n==="user"){let o=t.message,i=[];for(let s of o?.content??[])if(s.type==="tool_result"){let a=s.is_error===!0,c=a?yr(Xy(s.content),zy):"";i.push({ts:r,kind:"tool_result",isError:a,...c?{text:c}:{}})}return i}if(n==="result"){let o=String(t.subtype??"").trim(),i=typeof t.num_turns=="number"?t.num_turns:void 0,s=typeof t.total_cost_usd=="number"?t.total_cost_usd:void 0;return[{ts:r,kind:"result",...o?{text:o}:{},...i!==void 0?{turns:i}:{},...s!==void 0?{costUsd:s}:{}}]}return[]}function xI(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 Me,It,gI,uu,ei,zy,gr=x(()=>{"use strict";M();Yy();Ks();Me=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}};It=class extends Error{usage;constructor(e){super("run aborted by pause"),this.usage=e,this.name="ClaudeAbortError"}},gI=5e3;uu=new Map;ei=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return qy(this.binary,e);if(e.signal?.aborted)throw new It;let r=["-p",yI(e.prompt),"--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",Gs(Yn(e.metadata))];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());let n=null;e.effort&&e.effort.trim().length>0&&(await lu(this.binary)?(n=e.effort.trim(),r.push("--effort",n)):console.warn(`[claude] effort '${e.effort.trim()}' requested but this Claude Code does not support --effort \u2014 running at the default effort`));for(let g of e.addDirs??[])r.push("--add-dir",g);e.settings&&Object.keys(e.settings).length>0&&r.push("--settings",JSON.stringify(e.settings));let o=[],i=[],s=null,a={input:0,output:0,cacheRead:0,cacheCreate:0},c=0,l="",u=null,p=g=>{if(g){if(g.type==="result"){s=g;return}if(g.type==="rate_limit_event"){let b=vI(g.rate_limit_info);b&&(!u||b.utilization>u.utilization)&&(u=b);return}if(g.type==="assistant"){let b=g.message;typeof b?.model=="string"&&(l=b.model);let w=b?.usage;w&&(c+=1,a.input+=Xe(w.input_tokens),a.output+=Xe(w.output_tokens),a.cacheRead+=Xe(w.cache_read_input_tokens),a.cacheCreate+=Xe(w.cache_creation_input_tokens))}}},d=e.role,f=e.onActivity,m=g=>{if(f)for(let b of $I(g,e.workspaceDir))try{f(b)}catch{}};return f?.({ts:Date.now(),kind:"start",text:`${d} job started`}),console.log(`[claude] spawn ${this.binary} role=${d}`+(e.model?` model=${e.model}`:"")+(n?` effort=${n}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((g,b)=>{let w=fI(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"}});w.stdout.setEncoding("utf-8"),w.stderr.setEncoding("utf-8");let v=!1,y=null,k=()=>{v=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${d}`),w.kill("SIGTERM"),y=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),w.kill("SIGKILL")},gI)};e.signal?.addEventListener("abort",k,{once:!0});let C=()=>{y&&clearTimeout(y),e.signal?.removeEventListener("abort",k)},E="";w.stdout.on("data",$=>{o.push($),E+=$;let A;for(;(A=E.indexOf(`
804
+ `))!==-1;){let N=E.slice(0,A).trim();if(E=E.slice(A+1),N){let B=Vy(N);p(B),B&&m(B)}}}),w.stderr.on("data",$=>{o.push($),i.push($);for(let A of $.split(`
805
+ `)){let N=A.trim();N&&console.warn(`[claude:stderr] ${N}`)}}),w.on("error",$=>{C(),b($)}),w.on("close",$=>{if(C(),v){b(new It(du(s,a,c,l)));return}if(E.trim()){let N=Vy(E.trim());p(N),N&&m(N)}let A=s?.is_error===!0;if($!==0||A){let N=typeof s?.api_error_status=="number"?s.api_error_status:void 0,B=typeof s?.subtype=="string"?s.subtype:void 0,H=typeof s?.result=="string"?s.result:void 0,j=hI(N,H,u,Date.now());b(new Me(wI($,s,i.join("")),{code:$,apiErrorStatus:N,subtype:B,resultText:H,retryAfterMs:bI(s),...j?{rateLimited:j}:{},usage:du(s,a,c,l)}));return}console.log("[claude] exit code=0"),g({artifactPaths:[],log:o.join(""),usage:du(s,a,c,l),...u?{rateLimit:u}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(n=>n.includes("/")&&mI(n))}};zy=200});import{mkdirSync as SI,writeFileSync as Vr}from"node:fs";import{dirname as EI,join as zr}from"node:path";function Jy(t,e,r){let n=zr(t,e);SI(EI(n),{recursive:!0}),Vr(n,r)}function RI(t,e,r){return`# ${t} \u2014 Estimate
812
806
 
813
807
  **Title:** ${e}
814
808
 
@@ -829,7 +823,7 @@ production-grade estimates.)
829
823
  ${r.split(`
830
824
  `).slice(0,8).join(`
831
825
  `).trim()||"(empty)"}
832
- `}function xI(t,e,r,n){let o=n?`
826
+ `}function TI(t,e,r,n){let o=n?`
833
827
  ## Reviewer rework instruction
834
828
 
835
829
  > ${n.split(`
@@ -858,10 +852,10 @@ TBD (mock runner does not yet inspect project code).
858
852
  ${r.split(`
859
853
  `).slice(0,8).join(`
860
854
  `).trim()||"(empty)"}
861
- `}function SI(t){return`# ${t} \u2014 Open questions
855
+ `}function II(t){return`# ${t} \u2014 Open questions
862
856
 
863
857
  (none \u2014 mock runner did not surface ambiguities.)
864
- `}function EI(t,e,r){let n=r?` (rework: ${r.split(`
858
+ `}function CI(t,e,r){let n=r?` (rework: ${r.split(`
865
859
  `)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
866
860
  index 0000000..1111111 100644
867
861
  --- a/CHANGELOG.md
@@ -872,7 +866,7 @@ index 0000000..1111111 100644
872
866
  +- mock-runner placeholder change for slice 5 testing.
873
867
  +
874
868
  # Changelog
875
- `}function RI(t,e,r){return`# ${t} \u2014 Diff summary
869
+ `}function PI(t,e,r){return`# ${t} \u2014 Diff summary
876
870
 
877
871
  **Title:** ${e}
878
872
  ${r?`
@@ -883,101 +877,101 @@ ${r?`
883
877
  - \`CHANGELOG.md\` \u2014 added entry for ${t}.
884
878
 
885
879
  (Mock-runner output. Replace with claude-headless for production patches.)
886
- `}var ei,pu=x(()=>{"use strict";M();hr();ei=class{name(){return"mock"}async run(e){if(e.interactive)return this.runInteractive(e);let r=e.metadata??{},n=r.trackerIssueKey??"TASK",o=r.taskTitle??"(unknown task)",i=r.taskDescription??"",s=[];if(e.role==="estimate"){let a=$I(n,o,i);Yr(Vr(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Yr(Vr(e.workspaceDir,"PLAN.md"),xI(n,o,i,a)),s.push("PLAN.md"),Yr(Vr(e.workspaceDir,"QUESTIONS.md"),SI(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Vy(e.workspaceDir,"changes/sample.patch",EI(n,o,a)),s.push("changes/sample.patch"),Vy(e.workspaceDir,"SOLUTION.md",RI(n,o,a)),s.push("SOLUTION.md")}else e.role==="rework"&&(Yr(Vr(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
880
+ `}var ti,pu=x(()=>{"use strict";M();gr();ti=class{name(){return"mock"}async run(e){if(e.interactive)return this.runInteractive(e);let r=e.metadata??{},n=r.trackerIssueKey??"TASK",o=r.taskTitle??"(unknown task)",i=r.taskDescription??"",s=[];if(e.role==="estimate"){let a=RI(n,o,i);Vr(zr(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Vr(zr(e.workspaceDir,"PLAN.md"),TI(n,o,i,a)),s.push("PLAN.md"),Vr(zr(e.workspaceDir,"QUESTIONS.md"),II(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Jy(e.workspaceDir,"changes/sample.patch",CI(n,o,a)),s.push("changes/sample.patch"),Jy(e.workspaceDir,"SOLUTION.md",PI(n,o,a)),s.push("SOLUTION.md")}else e.role==="rework"&&(Vr(zr(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
887
881
  `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:ut()}}async runInteractive(e){let r=e.role==="config",n=e.onActivity,o=s=>{n?.({ts:Date.now(),kind:"text",author:"agent",text:s}),n?.({ts:Date.now(),kind:"result",author:"agent",text:"success"})};n?.({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),o(r?"Hi! Describe the configuration change you'd like to make.":"Hi! Describe the task you'd like to formulate.");let i=r?"Config from chat":"Draft from chat";for await(let s of e.interactive.inbox){if(e.signal?.aborted)throw new It;if(s.kind==="user")n?.({ts:Date.now(),kind:"text",author:"user",text:s.text}),s.text.trim()&&(i=s.text.trim().slice(0,80)),o(`Got it: **${s.text.trim()}**. Anything else to clarify?`);else break}if(r){let s={file:"project.yaml",section:["branch"],edits:[{file:"project.yaml",path:["branch","pattern"],value:"codepipe/<TASK_ID>"}],explanation:`Proposed by the interactive config chat (mock runner): ${i}`,diff:[{path:"branch",before:`branch:
888
882
  pattern: <TASK_ID>
889
883
  `,after:`branch:
890
884
  pattern: codepipe/<TASK_ID>
891
- `}]};return Yr(Vr(e.workspaceDir,"PROPOSAL.json"),JSON.stringify(s,null,2)),{artifactPaths:["PROPOSAL.json"],log:"mock config session finalized PROPOSAL.json",usage:ut()}}return Yr(Vr(e.workspaceDir,"DRAFT.md"),`${i}
885
+ `}]};return Vr(zr(e.workspaceDir,"PROPOSAL.json"),JSON.stringify(s,null,2)),{artifactPaths:["PROPOSAL.json"],log:"mock config session finalized PROPOSAL.json",usage:ut()}}return Vr(zr(e.workspaceDir,"DRAFT.md"),`${i}
892
886
 
893
887
  Produced by the interactive chat (mock runner).
894
- `),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:ut()}}}});function zy(t){switch(t){case"mock":return new ei;case"claude-headless":return new Qo;default:return null}}function fu(t,e){let r=e&&e.trim().length>0?e.trim():tt;return t==="mock"?!0:t==="claude-headless"?r==="claude":!1}var Xy=x(()=>{"use strict";M();hr();pu();hr();pu()});var yu={};Ne(yu,{addUsageInto:()=>zr,backoffDelayMs:()=>ew,classifyLLMFailure:()=>Qy,isAuthFailure:()=>hu,loadRetryPolicy:()=>mu,runAgentWithRetry:()=>gu});function mu(t=process.env){return{maxAttempts:Hs(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:Hs(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:Hs(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:Hs(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function Qy(t){if(t instanceof Me){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return II.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&CI.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!1,reason:"api_status=429 (rate limit)",retryAfterMs:i}:TI.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:Jy.test(s)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:n??`exit ${t.details.code}`}}let e=t instanceof Error?t.message:String(t);return Jy.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function hu(t){if(t instanceof Me){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&Zy.test(n)}let e=t instanceof Error?t.message:String(t);return Zy.test(e)}function ew(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 gu(t,e,r){let n=r.sleep??(a=>new Promise(c=>setTimeout(c,a))),o=Date.now()+r.policy.totalBudgetMs,i="",s=[];for(let a=1;;a++)try{let c=await t.run(e);for(let l of s)zr(c.usage,l);return c}catch(c){i=c instanceof Error?c.message:String(c);let l=Qy(c),u=a>=r.policy.maxAttempts;if(!l.retryable||u||r.aborted()){if(c instanceof Me){if(c.details.usage)for(let d of s)zr(c.details.usage,d);throw a>1&&(c.message=`agent failed after ${a} attempts: ${i}`),c}throw a>1?new Error(`agent failed after ${a} attempts: ${i}`):c}let p=ew(a,r.policy,l.retryAfterMs);if(Date.now()+p>o){if(c instanceof Me){if(c.details.usage)for(let d of s)zr(c.details.usage,d);throw c.message=`agent failed after ${a} attempts (retry budget exhausted): ${i}`,c}throw new Error(`agent failed after ${a} attempts (retry budget exhausted): ${i}`)}c instanceof Me&&c.details.usage&&s.push(c.details.usage),console.warn(`[job] ${r.jobId} agent attempt ${a}/${r.policy.maxAttempts} failed (retryable: ${l.reason}) \u2014 cleaning workspace, backoff ${p}ms`),await r.onBeforeRetry(),await n(p)}}function Hs(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}function zr(t,e){t.inputTokens+=e.inputTokens,t.outputTokens+=e.outputTokens,t.cacheReadInputTokens+=e.cacheReadInputTokens,t.cacheCreationInputTokens+=e.cacheCreationInputTokens,t.totalCostUsd+=e.totalCostUsd,t.numTurns+=e.numTurns}var TI,Jy,II,CI,Zy,ti=x(()=>{"use strict";hr();TI=new Set([500,502,503,529]),Jy=/(\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,II=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,CI=new Set(["error_max_turns"]);Zy=/(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 PI,writeFileSync as AI}from"node:fs";import{homedir as _I}from"node:os";import{join as tw}from"node:path";function wu(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 bu(t,e,r,n){try{let o=tw(_I(),".codepipe","debug",rw(t));PI(o,{recursive:!0});let i=new Date().toISOString().replace(/[:.]/g,"-"),s=tw(o,`${i}-${rw(e)}-${r}.md`);return AI(s,n),s}catch{return null}}var rw,nw=x(()=>{"use strict";rw=t=>t.replace(/[^A-Za-z0-9._-]/g,"_")});import{mkdtempSync as jI,rmSync as NI,writeFileSync as ow}from"node:fs";import{tmpdir as OI}from"node:os";import{join as ku}from"node:path";function Ws(t){return`[url "https://${t}/"]
888
+ `),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:ut()}}}});function Zy(t){switch(t){case"mock":return new ti;case"claude-headless":return new ei;default:return null}}function fu(t,e){let r=e&&e.trim().length>0?e.trim():tt;return t==="mock"?!0:t==="claude-headless"?r==="claude":!1}var Qy=x(()=>{"use strict";M();gr();pu();gr();pu()});var yu={};Ne(yu,{addUsageInto:()=>Xr,backoffDelayMs:()=>nw,classifyLLMFailure:()=>rw,isAuthFailure:()=>hu,loadRetryPolicy:()=>mu,runAgentWithRetry:()=>gu});function mu(t=process.env){return{maxAttempts:Hs(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:Hs(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:Hs(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:Hs(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function rw(t){if(t instanceof Me){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return _I.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&jI.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!1,reason:"api_status=429 (rate limit)",retryAfterMs:i}:AI.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:ew.test(s)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:n??`exit ${t.details.code}`}}let e=t instanceof Error?t.message:String(t);return ew.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function hu(t){if(t instanceof Me){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&tw.test(n)}let e=t instanceof Error?t.message:String(t);return tw.test(e)}function nw(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 gu(t,e,r){let n=r.sleep??(a=>new Promise(c=>setTimeout(c,a))),o=Date.now()+r.policy.totalBudgetMs,i="",s=[];for(let a=1;;a++)try{let c=await t.run(e);for(let l of s)Xr(c.usage,l);return c}catch(c){i=c instanceof Error?c.message:String(c);let l=rw(c),u=a>=r.policy.maxAttempts;if(!l.retryable||u||r.aborted()){if(c instanceof Me){if(c.details.usage)for(let d of s)Xr(c.details.usage,d);throw a>1&&(c.message=`agent failed after ${a} attempts: ${i}`),c}throw a>1?new Error(`agent failed after ${a} attempts: ${i}`):c}let p=nw(a,r.policy,l.retryAfterMs);if(Date.now()+p>o){if(c instanceof Me){if(c.details.usage)for(let d of s)Xr(c.details.usage,d);throw c.message=`agent failed after ${a} attempts (retry budget exhausted): ${i}`,c}throw new Error(`agent failed after ${a} attempts (retry budget exhausted): ${i}`)}c instanceof Me&&c.details.usage&&s.push(c.details.usage),console.warn(`[job] ${r.jobId} agent attempt ${a}/${r.policy.maxAttempts} failed (retryable: ${l.reason}) \u2014 cleaning workspace, backoff ${p}ms`),await r.onBeforeRetry(),await n(p)}}function Hs(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}function Xr(t,e){t.inputTokens+=e.inputTokens,t.outputTokens+=e.outputTokens,t.cacheReadInputTokens+=e.cacheReadInputTokens,t.cacheCreationInputTokens+=e.cacheCreationInputTokens,t.totalCostUsd+=e.totalCostUsd,t.numTurns+=e.numTurns}var AI,ew,_I,jI,tw,ri=x(()=>{"use strict";gr();AI=new Set([500,502,503,529]),ew=/(\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,_I=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,jI=new Set(["error_max_turns"]);tw=/(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 NI,writeFileSync as OI}from"node:fs";import{homedir as LI}from"node:os";import{join as ow}from"node:path";function wu(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 bu(t,e,r,n){try{let o=ow(LI(),".codepipe","debug",iw(t));NI(o,{recursive:!0});let i=new Date().toISOString().replace(/[:.]/g,"-"),s=ow(o,`${i}-${iw(e)}-${r}.md`);return OI(s,n),s}catch{return null}}var iw,sw=x(()=>{"use strict";iw=t=>t.replace(/[^A-Za-z0-9._-]/g,"_")});import{mkdtempSync as MI,rmSync as DI,writeFileSync as aw}from"node:fs";import{tmpdir as UI}from"node:os";import{join as ku}from"node:path";function Ws(t){return`[url "https://${t}/"]
895
889
  insteadOf = git@${t}:
896
890
  insteadOf = ssh://git@${t}/
897
- `}function cw(t,e){if(t.length===0)return null;let r=jI(ku(OI(),"devpipe-gitcreds-")),n=ku(r,"credentials"),o=ku(r,"gitconfig");return ow(n,t.join(`
891
+ `}function dw(t,e){if(t.length===0)return null;let r=MI(ku(UI(),"devpipe-gitcreds-")),n=ku(r,"credentials"),o=ku(r,"gitconfig");return aw(n,t.join(`
898
892
  `)+`
899
- `,{mode:384}),ow(o,`[credential]
893
+ `,{mode:384}),aw(o,`[credential]
900
894
  helper = store --file=${n}
901
- `+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{NI(r,{recursive:!0,force:!0})}catch{}}}}function vu(t){let e=[],r=[];if(t.mirrorWrite?.token){let n=t.mirrorWrite.host;(!n||n==="github")&&(e.push(`https://x-access-token:${t.mirrorWrite.token}@github.com`),r.push(iw)),(!n||n==="gitlab")&&(e.push(`https://oauth2:${t.mirrorWrite.token}@gitlab.com`),r.push(aw)),(!n||n==="bitbucket")&&(e.push(`https://${Wt}:${encodeURIComponent(t.mirrorWrite.token)}@bitbucket.org`),r.push(sw))}return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(iw)),t.bitbucket?.apiToken&&(e.push(`https://${Wt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(sw)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(aw)),cw(e,r)}function lw(t,e){if(t.contextWrite?.token){let r=Or(e)??"github.com",n=Io(r);return cw([`https://${n}:${t.contextWrite.token}@${r}`],[Ws(r)])}return vu(t)}var iw,sw,aw,uw=x(()=>{"use strict";M();iw=Ws("github.com"),sw=Ws("bitbucket.org"),aw=Ws("gitlab.com")});import{spawn as pw}from"node:child_process";import{existsSync as qs,mkdirSync as ri,readFileSync as LI,rmSync as $u,symlinkSync as MI}from"node:fs";import{homedir as DI}from"node:os";import{dirname as Vn,join as yr}from"node:path";function fw(t){let e=yr(DI(),".codepipe-sandbox","repos");return t?yr(e,t):e}function mw(t,e){let n=(Yn.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{Yn.get(t)===o&&Yn.delete(t)},()=>{Yn.get(t)===o&&Yn.delete(t)});return Yn.set(t,o),n}function dw(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 UI(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 hw(t,e,r,n,o){let i=async c=>{await ie(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await ie(t,["reset","--hard",`origin/${c}`],o),await ie(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!dw(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{qs(t)&&$u(t,{recursive:!0,force:!0}),ri(Vn(t),{recursive:!0});try{return await ie(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!dw(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),qs(t)&&$u(t,{recursive:!0,force:!0}),ri(Vn(t),{recursive:!0}),await ie(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(qs(yr(t,".git")))try{return await s()}catch(c){if(!UI(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 gw(t){await ie(t.workspacePath,["reset","--hard",t.baseSha]),await ie(t.workspacePath,["clean","-fdx"])}async function yw(t,e){let r=t.workspacePath;await ie(r,["add","-A"]);let n=(await xe(r,["write-tree"])).trim(),o=(await xe(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:zn,GIT_AUTHOR_EMAIL:Xn,GIT_COMMITTER_NAME:zn,GIT_COMMITTER_EMAIL:Xn};return(await xe(r,["commit-tree",n,"-m",e],i)).trim()}async function ww(t,e,r,n,o){try{await ie(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw Or(n)==="github.com"&&/without `?workflow`? scope|workflow.*scope/i.test(s)?new Error("delivery push rejected: the Context-Repo push token needs the `workflow` scope (the delivery includes .github/workflows/*). Set secrets.contextWrite.token to a fine-grained PAT on the Context Repo with Contents: write + Workflows: write (or add `workflow` to the project token).\n"+s):i}}async function bw(t,e){return xe(t.workspacePath,["diff","--binary",t.baseSha,e])}async function kw(t,e){return(await xe(t.workspacePath,["diff","--name-only",t.baseSha,e])).split(`
902
- `).map(n=>n.trim()).filter(n=>n.length>0)}async function vw(t,e,r,n,o){await ie(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await ie(t.workspacePath,["checkout","--force",r])}async function $w(t,e,r,n,o,i){let s=t.workspacePath;await ie(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await xe(s,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=m=>xe(s,["rev-parse","-q","--verify",`${m}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await xe(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ie(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(g=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(g)}`)}),await c(n)||await ie(s,["fetch","origin",n],i).catch(()=>{}),!await c(n)))throw new Error(`moved-base apply: delivery base ${n.slice(0,10)} is unreachable \u2014 cannot re-apply the previous iteration onto the fresh ${t.ref}`);let l={...i??process.env,GIT_AUTHOR_NAME:zn,GIT_AUTHOR_EMAIL:Xn,GIT_COMMITTER_NAME:zn,GIT_COMMITTER_EMAIL:Xn},u=(await xe(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),p=(await xe(s,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await ie(s,["cherry-pick","--quit"],l).catch(()=>{});let d=null;try{await ie(s,["cherry-pick","--no-commit",p],l)}catch(m){d=m instanceof Error?m.message:String(m)}let f=(await xe(s,["diff","--name-only","--diff-filter=U"])).split(`
903
- `).map(m=>m.trim()).filter(m=>m.length>0);if(d&&f.length===0)throw await ie(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${d}`);return f}async function xu(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:zn,GIT_AUTHOR_EMAIL:Xn,GIT_COMMITTER_NAME:zn,GIT_COMMITTER_EMAIL:Xn};(await xe(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ie(n,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),await ie(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await ie(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await xe(n,["diff","--name-only","--diff-filter=U"])).split(`
904
- `).map(l=>l.trim()).filter(l=>l.length>0),c=await xe(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}async function Sw(t,e){return xe(t.workspacePath,["diff","--unified=0",`${xw}..HEAD`],e)}async function Su(t,e,r){await ie(t.workspacePath,["update-ref",xw,e],r)}async function Ew(t,e,r){let n=t.workspacePath,o=[`+refs/heads/${e}:refs/remotes/origin/${e}`,...t.ref!==e?[`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`]:[]];await ie(n,["fetch","--depth=1","origin",...o],r).catch(a=>{console.warn(`[git] review-base ${t.name}: base fetch failed: ${String(a)}`)});let i=()=>xe(n,["merge-base",`origin/${e}`,"HEAD"],r).then(a=>a.trim()||null).catch(()=>null),s=await i();for(let a of[64,256,1024]){if(s)break;await ie(n,["fetch",`--deepen=${a}`,"origin",...o],r).catch(c=>{console.warn(`[git] review-base ${t.name}: --deepen=${a} failed: ${String(c)}`)}),s=await i()}return s||(await xe(n,["rev-parse","--is-shallow-repository"],r)).trim()==="true"&&(await ie(n,["fetch","--unshallow","origin",...o],r).catch(c=>{console.warn(`[git] review-base ${t.name}: --unshallow failed: ${String(c)}`)}),s=await i()),s&&await Su(t,s,r),s}function ie(t,e,r){return new Promise((n,o)=>{let i=pw("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[];i.stderr.setEncoding("utf-8"),i.stderr.on("data",a=>s.push(a)),i.on("error",o),i.on("close",a=>{if(a===0)return n();o(new Error(`git ${e[0]} failed (exit ${a}):
905
- ${s.join("").trim()||"(no stderr)"}`))})})}function xe(t,e,r){return new Promise((n,o)=>{let i=pw("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[],a=[];i.stdout.setEncoding("utf-8"),i.stderr.setEncoding("utf-8"),i.stdout.on("data",c=>s.push(c)),i.stderr.on("data",c=>a.push(c)),i.on("error",o),i.on("close",c=>{if(c===0)return n(s.join(""));o(new Error(`git ${e[0]} failed (exit ${c}):
906
- ${a.join("").trim()||"(no stderr)"}`))})})}function Rw(t,e){qs(t)&&$u(t,{recursive:!0,force:!0}),ri(Vn(t),{recursive:!0}),MI(e,t,"dir")}async function Tw(t,e,r){await ie(t,["worktree","prune"]).catch(()=>{}),ri(Vn(r),{recursive:!0}),await ie(t,["worktree","add","--detach",r,`origin/${e}`])}async function BI(t,e,r){ri(Vn(r),{recursive:!0}),await ie(Vn(r),["clone","--quiet","--no-checkout",t,r]),await ie(r,["checkout","--force","--detach",e])}async function Iw(t,e,r,n="worktree",o,i){return r.length===0?[]:mw(e,async()=>{let s=[];for(let a of r){let c=yr(fw(i),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await hw(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 xe(c,["rev-parse","HEAD"])).trim(),p=yr(t,"code",a.name);n==="direct"?(Rw(p,c),console.log(`[git] code: linked ${p} \u2192 ${c} @ ${u.slice(0,10)}`)):n==="clone"?(await BI(c,u,p),console.log(`[git] code: clone ${p} \u2190 ${c} @ ${u.slice(0,10)}`)):(await Tw(c,l,p),console.log(`[git] code: worktree ${p} \u2190 ${c} @ ${u.slice(0,10)}`)),s.push({name:a.name,workspacePath:p,cachePath:c,ref:l,baseSha:u})}return s})}async function Cw(t,e,r,n="worktree",o,i){if(!r||!r.cloneUrl)return null;let s=r;return mw(e,async()=>{let a=yr(fw(i),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);try{await hw(a,s.cloneUrl,s.ref,void 0,o)}catch(u){throw new Error(`failed to materialize context repo (${s.cloneUrl}): `+(u instanceof Error?u.message:String(u)))}let c=yr(t,"context");n==="direct"?(Rw(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await Tw(a,s.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await xe(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function Pw(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await ie(r,["add","-A",...n]).catch(()=>{});let o;try{o=await xe(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
907
- `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=LI(yr(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var Yn,zn,Xn,xw,Aw=x(()=>{"use strict";M();Yn=new Map;zn="CodePipe Agent",Xn="codepipe@codepartner.ee";xw="refs/worktree/codepipe/review-base"});import{existsSync as FI,readFileSync as GI}from"node:fs";import{join as KI}from"node:path";import{parse as HI}from"yaml";function _w(t){if(!t)return!1;let e=KI(t,Eu);if(!FI(e))return!1;try{let r=HI(GI(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 Eu,jw=x(()=>{"use strict";Eu="knowledge/build.yaml"});import{readFileSync as WI}from"node:fs";import{join as qI}from"node:path";function Nw(t){let e=qI(t,ni),r;try{r=WI(e,"utf-8")}catch{throw new wr(`BUILD produced no ${ni} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new wr(`${ni} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new wr(`${ni} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new wr(`${ni}: "ok" must be a boolean`);let i=o.ok,a=(Array.isArray(o.steps)?o.steps:[]).flatMap(u=>{if(!u||typeof u!="object")return[];let p=u,d=typeof p.name=="string"?p.name:null,f=typeof p.exitCode=="number"?p.exitCode:null;if(d===null||f===null)return[];let m={name:d,exitCode:f};return typeof p.durationMs=="number"&&(m.durationMs=p.durationMs),[m]}),c=typeof o.logTail=="string"?YI(o.logTail):"",l={ok:i,steps:a,logTail:c};if(typeof o.failedStep=="string"&&o.failedStep)l.failedStep=o.failedStep;else if(!i){let u=a.find(p=>p.exitCode!==0);u&&(l.failedStep=u.name)}return l}function YI(t){let e=Buffer.from(t,"utf-8");return e.length<=Ru?t:`\u2026 [${e.length-Ru} bytes elided] \u2026
908
- `+e.subarray(e.length-Ru).toString("utf-8")}var Ru,wr,ni,Ow=x(()=>{"use strict";Ru=8*1024,wr=class extends Error{},ni="meta/build-result.json"});var Lw={};Ne(Lw,{REVIEW_RESULT_PATH:()=>Xr,ReviewVerdictError:()=>Lt,markFindingScope:()=>tC,parseChangedRanges:()=>eC,readCodeReviewResult:()=>Tu});import{readFileSync as VI}from"node:fs";import{join as zI}from"node:path";function Tu(t){let e=zI(t,Xr),r;try{r=VI(e,"utf-8")}catch{throw new Lt(`code review produced no ${Xr} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(l){throw new Lt(`${Xr} is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}if(!n||typeof n!="object")throw new Lt(`${Xr} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new Lt(`${Xr}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?br(o.remarks,XI):"";if(!i&&s.trim().length===0)throw new Lt(`${Xr}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?br(o.summary,JI):"",c=QI(o.findings);return{approved:i,remarks:s,summary:a,...c.length>0?{findings:c}:{}}}function QI(t){if(!Array.isArray(t))return[];let e=[];for(let r of t.slice(0,ZI)){if(!r||typeof r!="object")continue;let n=r,o=typeof n.title=="string"?br(n.title,512).trim():"",i=typeof n.problem=="string"?br(n.problem,Ys).trim():"";if(!o||!i)continue;let s=typeof n.line=="number"&&Number.isInteger(n.line)&&n.line>0?n.line:void 0,a=n.severity==="blocker"||n.severity==="major"||n.severity==="minor"?n.severity:"other",c=typeof n.scenario=="string"&&n.scenario.trim()?br(n.scenario,Ys):void 0;a==="blocker"&&!c&&(console.warn(`[review] blocker "${o.slice(0,80)}" carries no scenario \u2014 demoted to major`),a="major"),e.push({severity:a,title:o,problem:i,...typeof n.repo=="string"&&n.repo?{repo:n.repo}:{},...typeof n.file=="string"&&n.file?{file:br(n.file,1024)}:{},...s!==void 0?{line:s}:{},...c?{scenario:c}:{},...typeof n.suggestion=="string"&&n.suggestion.trim()?{suggestion:br(n.suggestion,Ys)}:{},...n.confidence==="high"||n.confidence==="medium"||n.confidence==="low"?{confidence:n.confidence}:{},...n.rule_source==="adr"||n.rule_source==="convention"||n.rule_source==="build"||n.rule_source==="judgment"?{ruleSource:n.rule_source}:{},...typeof n.out_of_diff_reason=="string"&&n.out_of_diff_reason.trim()?{outOfDiffReason:br(n.out_of_diff_reason,Ys)}:{}})}return e}function br(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
909
- \u2026 [${r.length-e} bytes elided]`}function eC(t){let e=new Map,r=null;for(let n of t.split(`
910
- `)){if(n.startsWith("+++ ")){let o=n.slice(4).trim();r=o==="/dev/null"?null:o.replace(/^b\//,""),r&&!e.has(r)&&e.set(r,[]);continue}if(r&&n.startsWith("@@")){let o=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(n);if(!o)continue;let i=Number(o[1]),s=o[2]!==void 0?Number(o[2]):1,a=s===0?Math.max(1,i):i,c=s===0?Math.max(1,i):i+s-1;e.get(r).push([a,c])}}return e}function tC(t,e,r){for(let n of t.findings??[]){if(!n.file)continue;let o=n.repo??r;if(!o)continue;let i=e.get(o);if(!i)continue;let s=i.get(n.file);if(!s){n.scope="outside";continue}if(n.line===void 0||s.length===0){n.scope="diff";continue}let a=n.line;n.scope=s.some(([c,l])=>a>=c&&a<=l)?"diff":"file"}}var XI,JI,Lt,Xr,Ys,ZI,Iu=x(()=>{"use strict";XI=16*1024,JI=4*1024,Lt=class extends Error{},Xr="meta/review-result.json";Ys=8*1024,ZI=50});import{readFileSync as rC,statSync as nC}from"node:fs";import{join as Mw}from"node:path";function uC(t){return t.startsWith("meta/")||lC.has(t)}function dC(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 pC(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function Dw(t,e,r){let n=r?.maxBytes??oC,o=r?.totalBytes??iC,i=r?.maxCount??sC,s=e.map((m,g)=>{let b=null;try{b=nC(Mw(t,m)).size}catch{}return{path:m,index:g,size:b}}),a=[...s].sort((m,g)=>{let b=w=>uC(w.path)?0:1;return b(m)!==b(g)?b(m)-b(g):(m.size??0)-(g.size??0)}),c=a.slice(0,i),l=a.slice(i).sort((m,g)=>m.index-g.index).map(m=>m.path),u=new Array(s.length),p=[],d=0;for(let m of c){let g=null;if(m.size!==null&&m.size<=n&&d+m.size<=o)try{g=rC(Mw(t,m.path))}catch{}if(g!==null){d+=g.length,u[m.index]={path:m.path,contentBase64:g.toString("base64")};continue}let b=m.size===null?pC(m.path):dC(m.path,m.size,n,o),w=Buffer.from(b,"utf-8");d+=w.length,u[m.index]={path:m.path,contentBase64:w.toString("base64")},p.push({path:m.path,bytes:m.size??0})}let f=u.filter(m=>m!==void 0);if(l.length>0){let m=l.slice(0,cC),g=`# Artifacts omitted from upload
895
+ `+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{DI(r,{recursive:!0,force:!0})}catch{}}}}function vu(t){let e=[],r=[];if(t.mirrorWrite?.token){let n=t.mirrorWrite.host;(!n||n==="github")&&(e.push(`https://x-access-token:${t.mirrorWrite.token}@github.com`),r.push(cw)),(!n||n==="gitlab")&&(e.push(`https://oauth2:${t.mirrorWrite.token}@gitlab.com`),r.push(uw)),(!n||n==="bitbucket")&&(e.push(`https://${qt}:${encodeURIComponent(t.mirrorWrite.token)}@bitbucket.org`),r.push(lw))}return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(cw)),t.bitbucket?.apiToken&&(e.push(`https://${qt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(lw)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(uw)),dw(e,r)}function pw(t,e){if(t.contextWrite?.token){let r=Lr(e)??"github.com",n=Co(r);return dw([`https://${n}:${t.contextWrite.token}@${r}`],[Ws(r)])}return vu(t)}var cw,lw,uw,fw=x(()=>{"use strict";M();cw=Ws("github.com"),lw=Ws("bitbucket.org"),uw=Ws("gitlab.com")});import{spawn as hw}from"node:child_process";import{existsSync as qs,mkdirSync as ni,readFileSync as BI,rmSync as $u,symlinkSync as FI}from"node:fs";import{homedir as GI}from"node:os";import{dirname as zn,join as wr}from"node:path";function gw(t){let e=wr(GI(),".codepipe-sandbox","repos");return t?wr(e,t):e}function yw(t,e){let n=(Vn.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{Vn.get(t)===o&&Vn.delete(t)},()=>{Vn.get(t)===o&&Vn.delete(t)});return Vn.set(t,o),n}function mw(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 KI(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 ww(t,e,r,n,o){let i=async c=>{await ie(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await ie(t,["reset","--hard",`origin/${c}`],o),await ie(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!mw(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{qs(t)&&$u(t,{recursive:!0,force:!0}),ni(zn(t),{recursive:!0});try{return await ie(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!mw(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),qs(t)&&$u(t,{recursive:!0,force:!0}),ni(zn(t),{recursive:!0}),await ie(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(qs(wr(t,".git")))try{return await s()}catch(c){if(!KI(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 bw(t){await ie(t.workspacePath,["reset","--hard",t.baseSha]),await ie(t.workspacePath,["clean","-fdx"])}async function kw(t,e){let r=t.workspacePath;await ie(r,["add","-A"]);let n=(await xe(r,["write-tree"])).trim(),o=(await xe(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:Xn,GIT_AUTHOR_EMAIL:Jn,GIT_COMMITTER_NAME:Xn,GIT_COMMITTER_EMAIL:Jn};return(await xe(r,["commit-tree",n,"-m",e],i)).trim()}async function vw(t,e,r,n,o){try{await ie(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw Lr(n)==="github.com"&&/without `?workflow`? scope|workflow.*scope/i.test(s)?new Error("delivery push rejected: the Context-Repo push token needs the `workflow` scope (the delivery includes .github/workflows/*). Set secrets.contextWrite.token to a fine-grained PAT on the Context Repo with Contents: write + Workflows: write (or add `workflow` to the project token).\n"+s):i}}async function $w(t,e){return xe(t.workspacePath,["diff","--binary",t.baseSha,e])}async function xw(t,e){return(await xe(t.workspacePath,["diff","--name-only",t.baseSha,e])).split(`
896
+ `).map(n=>n.trim()).filter(n=>n.length>0)}async function Sw(t,e,r,n,o){await ie(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await ie(t.workspacePath,["checkout","--force",r])}async function Ew(t,e,r,n,o,i){let s=t.workspacePath;await ie(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await xe(s,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=m=>xe(s,["rev-parse","-q","--verify",`${m}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await xe(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ie(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(g=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(g)}`)}),await c(n)||await ie(s,["fetch","origin",n],i).catch(()=>{}),!await c(n)))throw new Error(`moved-base apply: delivery base ${n.slice(0,10)} is unreachable \u2014 cannot re-apply the previous iteration onto the fresh ${t.ref}`);let l={...i??process.env,GIT_AUTHOR_NAME:Xn,GIT_AUTHOR_EMAIL:Jn,GIT_COMMITTER_NAME:Xn,GIT_COMMITTER_EMAIL:Jn},u=(await xe(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),p=(await xe(s,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await ie(s,["cherry-pick","--quit"],l).catch(()=>{});let d=null;try{await ie(s,["cherry-pick","--no-commit",p],l)}catch(m){d=m instanceof Error?m.message:String(m)}let f=(await xe(s,["diff","--name-only","--diff-filter=U"])).split(`
897
+ `).map(m=>m.trim()).filter(m=>m.length>0);if(d&&f.length===0)throw await ie(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${d}`);return f}async function xu(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:Xn,GIT_AUTHOR_EMAIL:Jn,GIT_COMMITTER_NAME:Xn,GIT_COMMITTER_EMAIL:Jn};(await xe(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ie(n,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),await ie(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await ie(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await xe(n,["diff","--name-only","--diff-filter=U"])).split(`
898
+ `).map(l=>l.trim()).filter(l=>l.length>0),c=await xe(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}async function Tw(t,e){return xe(t.workspacePath,["diff","--unified=0",`${Rw}..HEAD`],e)}async function Su(t,e,r){await ie(t.workspacePath,["update-ref",Rw,e],r)}async function Iw(t,e,r){let n=t.workspacePath,o=[`+refs/heads/${e}:refs/remotes/origin/${e}`,...t.ref!==e?[`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`]:[]];await ie(n,["fetch","--depth=1","origin",...o],r).catch(a=>{console.warn(`[git] review-base ${t.name}: base fetch failed: ${String(a)}`)});let i=()=>xe(n,["merge-base",`origin/${e}`,"HEAD"],r).then(a=>a.trim()||null).catch(()=>null),s=await i();for(let a of[64,256,1024]){if(s)break;await ie(n,["fetch",`--deepen=${a}`,"origin",...o],r).catch(c=>{console.warn(`[git] review-base ${t.name}: --deepen=${a} failed: ${String(c)}`)}),s=await i()}return s||(await xe(n,["rev-parse","--is-shallow-repository"],r)).trim()==="true"&&(await ie(n,["fetch","--unshallow","origin",...o],r).catch(c=>{console.warn(`[git] review-base ${t.name}: --unshallow failed: ${String(c)}`)}),s=await i()),s&&await Su(t,s,r),s}function ie(t,e,r){return new Promise((n,o)=>{let i=hw("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[];i.stderr.setEncoding("utf-8"),i.stderr.on("data",a=>s.push(a)),i.on("error",o),i.on("close",a=>{if(a===0)return n();o(new Error(`git ${e[0]} failed (exit ${a}):
899
+ ${s.join("").trim()||"(no stderr)"}`))})})}function xe(t,e,r){return new Promise((n,o)=>{let i=hw("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[],a=[];i.stdout.setEncoding("utf-8"),i.stderr.setEncoding("utf-8"),i.stdout.on("data",c=>s.push(c)),i.stderr.on("data",c=>a.push(c)),i.on("error",o),i.on("close",c=>{if(c===0)return n(s.join(""));o(new Error(`git ${e[0]} failed (exit ${c}):
900
+ ${a.join("").trim()||"(no stderr)"}`))})})}function Cw(t,e){qs(t)&&$u(t,{recursive:!0,force:!0}),ni(zn(t),{recursive:!0}),FI(e,t,"dir")}async function Pw(t,e,r){await ie(t,["worktree","prune"]).catch(()=>{}),ni(zn(r),{recursive:!0}),await ie(t,["worktree","add","--detach",r,`origin/${e}`])}async function HI(t,e,r){ni(zn(r),{recursive:!0}),await ie(zn(r),["clone","--quiet","--no-checkout",t,r]),await ie(r,["checkout","--force","--detach",e])}async function Aw(t,e,r,n="worktree",o,i){return r.length===0?[]:yw(e,async()=>{let s=[];for(let a of r){let c=wr(gw(i),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await ww(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 xe(c,["rev-parse","HEAD"])).trim(),p=wr(t,"code",a.name);n==="direct"?(Cw(p,c),console.log(`[git] code: linked ${p} \u2192 ${c} @ ${u.slice(0,10)}`)):n==="clone"?(await HI(c,u,p),console.log(`[git] code: clone ${p} \u2190 ${c} @ ${u.slice(0,10)}`)):(await Pw(c,l,p),console.log(`[git] code: worktree ${p} \u2190 ${c} @ ${u.slice(0,10)}`)),s.push({name:a.name,workspacePath:p,cachePath:c,ref:l,baseSha:u})}return s})}async function _w(t,e,r,n="worktree",o,i){if(!r||!r.cloneUrl)return null;let s=r;return yw(e,async()=>{let a=wr(gw(i),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);try{await ww(a,s.cloneUrl,s.ref,void 0,o)}catch(u){throw new Error(`failed to materialize context repo (${s.cloneUrl}): `+(u instanceof Error?u.message:String(u)))}let c=wr(t,"context");n==="direct"?(Cw(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await Pw(a,s.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await xe(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function jw(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await ie(r,["add","-A",...n]).catch(()=>{});let o;try{o=await xe(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
901
+ `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=BI(wr(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var Vn,Xn,Jn,Rw,Nw=x(()=>{"use strict";M();Vn=new Map;Xn="CodePipe Agent",Jn="codepipe@codepartner.ee";Rw="refs/worktree/codepipe/review-base"});import{existsSync as WI,readFileSync as qI}from"node:fs";import{join as YI}from"node:path";import{parse as VI}from"yaml";function Ow(t){if(!t)return!1;let e=YI(t,Eu);if(!WI(e))return!1;try{let r=VI(qI(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 Eu,Lw=x(()=>{"use strict";Eu="knowledge/build.yaml"});import{readFileSync as zI}from"node:fs";import{join as XI}from"node:path";function Mw(t){let e=XI(t,oi),r;try{r=zI(e,"utf-8")}catch{throw new br(`BUILD produced no ${oi} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new br(`${oi} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new br(`${oi} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new br(`${oi}: "ok" must be a boolean`);let i=o.ok,a=(Array.isArray(o.steps)?o.steps:[]).flatMap(u=>{if(!u||typeof u!="object")return[];let p=u,d=typeof p.name=="string"?p.name:null,f=typeof p.exitCode=="number"?p.exitCode:null;if(d===null||f===null)return[];let m={name:d,exitCode:f};return typeof p.durationMs=="number"&&(m.durationMs=p.durationMs),[m]}),c=typeof o.logTail=="string"?JI(o.logTail):"",l={ok:i,steps:a,logTail:c};if(typeof o.failedStep=="string"&&o.failedStep)l.failedStep=o.failedStep;else if(!i){let u=a.find(p=>p.exitCode!==0);u&&(l.failedStep=u.name)}return l}function JI(t){let e=Buffer.from(t,"utf-8");return e.length<=Ru?t:`\u2026 [${e.length-Ru} bytes elided] \u2026
902
+ `+e.subarray(e.length-Ru).toString("utf-8")}var Ru,br,oi,Dw=x(()=>{"use strict";Ru=8*1024,br=class extends Error{},oi="meta/build-result.json"});var Uw={};Ne(Uw,{REVIEW_RESULT_PATH:()=>Jr,ReviewVerdictError:()=>Lt,markFindingScope:()=>iC,parseChangedRanges:()=>oC,readCodeReviewResult:()=>Tu});import{readFileSync as ZI}from"node:fs";import{join as QI}from"node:path";function Tu(t){let e=QI(t,Jr),r;try{r=ZI(e,"utf-8")}catch{throw new Lt(`code review produced no ${Jr} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(l){throw new Lt(`${Jr} is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}if(!n||typeof n!="object")throw new Lt(`${Jr} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new Lt(`${Jr}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?kr(o.remarks,eC):"";if(!i&&s.trim().length===0)throw new Lt(`${Jr}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?kr(o.summary,tC):"",c=nC(o.findings);return{approved:i,remarks:s,summary:a,...c.length>0?{findings:c}:{}}}function nC(t){if(!Array.isArray(t))return[];let e=[];for(let r of t.slice(0,rC)){if(!r||typeof r!="object")continue;let n=r,o=typeof n.title=="string"?kr(n.title,512).trim():"",i=typeof n.problem=="string"?kr(n.problem,Ys).trim():"";if(!o||!i)continue;let s=typeof n.line=="number"&&Number.isInteger(n.line)&&n.line>0?n.line:void 0,a=n.severity==="blocker"||n.severity==="major"||n.severity==="minor"?n.severity:"other",c=typeof n.scenario=="string"&&n.scenario.trim()?kr(n.scenario,Ys):void 0;a==="blocker"&&!c&&(console.warn(`[review] blocker "${o.slice(0,80)}" carries no scenario \u2014 demoted to major`),a="major"),e.push({severity:a,title:o,problem:i,...typeof n.repo=="string"&&n.repo?{repo:n.repo}:{},...typeof n.file=="string"&&n.file?{file:kr(n.file,1024)}:{},...s!==void 0?{line:s}:{},...c?{scenario:c}:{},...typeof n.suggestion=="string"&&n.suggestion.trim()?{suggestion:kr(n.suggestion,Ys)}:{},...n.confidence==="high"||n.confidence==="medium"||n.confidence==="low"?{confidence:n.confidence}:{},...n.rule_source==="adr"||n.rule_source==="convention"||n.rule_source==="build"||n.rule_source==="judgment"?{ruleSource:n.rule_source}:{},...typeof n.out_of_diff_reason=="string"&&n.out_of_diff_reason.trim()?{outOfDiffReason:kr(n.out_of_diff_reason,Ys)}:{}})}return e}function kr(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
903
+ \u2026 [${r.length-e} bytes elided]`}function oC(t){let e=new Map,r=null;for(let n of t.split(`
904
+ `)){if(n.startsWith("+++ ")){let o=n.slice(4).trim();r=o==="/dev/null"?null:o.replace(/^b\//,""),r&&!e.has(r)&&e.set(r,[]);continue}if(r&&n.startsWith("@@")){let o=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(n);if(!o)continue;let i=Number(o[1]),s=o[2]!==void 0?Number(o[2]):1,a=s===0?Math.max(1,i):i,c=s===0?Math.max(1,i):i+s-1;e.get(r).push([a,c])}}return e}function iC(t,e,r){for(let n of t.findings??[]){if(!n.file)continue;let o=n.repo??r;if(!o)continue;let i=e.get(o);if(!i)continue;let s=i.get(n.file);if(!s){n.scope="outside";continue}if(n.line===void 0||s.length===0){n.scope="diff";continue}let a=n.line;n.scope=s.some(([c,l])=>a>=c&&a<=l)?"diff":"file"}}var eC,tC,Lt,Jr,Ys,rC,Iu=x(()=>{"use strict";eC=16*1024,tC=4*1024,Lt=class extends Error{},Jr="meta/review-result.json";Ys=8*1024,rC=50});import{readFileSync as sC,statSync as aC}from"node:fs";import{join as Bw}from"node:path";function mC(t){return t.startsWith("meta/")||fC.has(t)}function hC(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 gC(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function Fw(t,e,r){let n=r?.maxBytes??cC,o=r?.totalBytes??lC,i=r?.maxCount??uC,s=e.map((m,g)=>{let b=null;try{b=aC(Bw(t,m)).size}catch{}return{path:m,index:g,size:b}}),a=[...s].sort((m,g)=>{let b=w=>mC(w.path)?0:1;return b(m)!==b(g)?b(m)-b(g):(m.size??0)-(g.size??0)}),c=a.slice(0,i),l=a.slice(i).sort((m,g)=>m.index-g.index).map(m=>m.path),u=new Array(s.length),p=[],d=0;for(let m of c){let g=null;if(m.size!==null&&m.size<=n&&d+m.size<=o)try{g=sC(Bw(t,m.path))}catch{}if(g!==null){d+=g.length,u[m.index]={path:m.path,contentBase64:g.toString("base64")};continue}let b=m.size===null?gC(m.path):hC(m.path,m.size,n,o),w=Buffer.from(b,"utf-8");d+=w.length,u[m.index]={path:m.path,contentBase64:w.toString("base64")},p.push({path:m.path,bytes:m.size??0})}let f=u.filter(m=>m!==void 0);if(l.length>0){let m=l.slice(0,pC),g=`# Artifacts omitted from upload
911
905
 
912
906
  ${l.length} file(s) exceeded the SANDBOX artifact count budget (${i}) and were dropped from the listing. The delivered code (git) and the build/review verdicts are unaffected. Usually this means a job left a stray tree in the workspace \u2014 throwaway copies belong in the workspace's \`scratch/\` directory, which is never uploaded.
913
907
 
914
908
  `+m.map(b=>`- ${b}
915
909
  `).join("")+(l.length>m.length?`
916
910
  \u2026and ${l.length-m.length} more.
917
- `:"");f.push({path:aC,contentBase64:Buffer.from(g,"utf-8").toString("base64")})}return{artifacts:f,omitted:p,dropped:l}}var oC,iC,sC,aC,cC,lC,Uw=x(()=>{"use strict";oC=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),iC=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),sC=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),aC="artifacts-omitted.md",cC=500,lC=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 fC,mkdtempSync as mC,readFileSync as hC,readdirSync as Fw,rmSync as Bw}from"node:fs";import{tmpdir as gC}from"node:os";import{join as Vs,relative as yC}from"node:path";function Gw(t){let e=mC(Vs(gC(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Bw(e,{recursive:!0,force:!0}),listFiles:()=>Kw(e,e),readFile:r=>hC(Vs(e,r),"utf-8"),clean:()=>{for(let r of Fw(e))bC.has(r)||Bw(Vs(e,r),{recursive:!0,force:!0})}}}function Kw(t,e){let r=[];for(let n of Fw(e)){let o=Vs(e,n),i=fC(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&wC.has(n))continue;r.push(...Kw(t,o))}else r.push(yC(t,o))}return r}var wC,bC,Hw=x(()=>{"use strict";wC=new Set(["code","context","scratch",".claude"]),bC=new Set(["code","context"])});import{readFileSync as kC}from"node:fs";import{join as vC}from"node:path";function RC(t,e){let r=To(t);return r?qw(TC(r),e):""}function Ww(t,e,r={}){let n=r.perAncestorBudget??$C,o=r.totalBudget??xC,i=[...t.matchAll(Ai)];if(i.length===0)return t;let s=i.map(l=>{let u=l[1],p=IC(e,u),d=p!=null?RC(p,n):"";return{key:u,text:d||`(\u0442\u0435\u043B\u043E \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u043E \u2014 \u0441\u043C. tasks/${u}/task.md)`}}),a=o,c=new Map;for(let l of s){let u=Math.max(0,Math.min(l.text.length,a));c.set(l.key,qw(l.text,u)),a-=u}return t.replace(Ai,(l,u)=>c.get(u)??"")}function TC(t){let e=t.split(`
918
- `),r=e.findIndex(a=>EC.test(a));if(r<0)return t;let n=e.slice(0,r).join(`
911
+ `:"");f.push({path:dC,contentBase64:Buffer.from(g,"utf-8").toString("base64")})}return{artifacts:f,omitted:p,dropped:l}}var cC,lC,uC,dC,pC,fC,Gw=x(()=>{"use strict";cC=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),lC=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),uC=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),dC="artifacts-omitted.md",pC=500,fC=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 yC,mkdtempSync as wC,readFileSync as bC,readdirSync as Hw,rmSync as Kw}from"node:fs";import{tmpdir as kC}from"node:os";import{join as Vs,relative as vC}from"node:path";function Ww(t){let e=wC(Vs(kC(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Kw(e,{recursive:!0,force:!0}),listFiles:()=>qw(e,e),readFile:r=>bC(Vs(e,r),"utf-8"),clean:()=>{for(let r of Hw(e))xC.has(r)||Kw(Vs(e,r),{recursive:!0,force:!0})}}}function qw(t,e){let r=[];for(let n of Hw(e)){let o=Vs(e,n),i=yC(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&$C.has(n))continue;r.push(...qw(t,o))}else r.push(vC(t,o))}return r}var $C,xC,Yw=x(()=>{"use strict";$C=new Set(["code","context","scratch",".claude"]),xC=new Set(["code","context"])});import{readFileSync as SC}from"node:fs";import{join as EC}from"node:path";function PC(t,e){let r=Io(t);return r?zw(AC(r),e):""}function Vw(t,e,r={}){let n=r.perAncestorBudget??RC,o=r.totalBudget??TC,i=[...t.matchAll(Ai)];if(i.length===0)return t;let s=i.map(l=>{let u=l[1],p=_C(e,u),d=p!=null?PC(p,n):"";return{key:u,text:d||`(\u0442\u0435\u043B\u043E \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u043E \u2014 \u0441\u043C. tasks/${u}/task.md)`}}),a=o,c=new Map;for(let l of s){let u=Math.max(0,Math.min(l.text.length,a));c.set(l.key,zw(l.text,u)),a-=u}return t.replace(Ai,(l,u)=>c.get(u)??"")}function AC(t){let e=t.split(`
912
+ `),r=e.findIndex(a=>CC.test(a));if(r<0)return t;let n=e.slice(0,r).join(`
919
913
  `).trim(),o=(e[r]??"").match(/^#+/)?.[0].length??1,i=e.length;for(let a=r+1;a<e.length;a++){let c=(e[a]??"").match(/^(#{1,6})\s/);if(c&&(c[1]?.length??0)<=o){i=a;break}}let s=e.slice(r,i).join(`
920
914
  `).trim();return[n,s].filter(Boolean).join(`
921
915
 
922
- `)}function qw(t,e){return t.length<=e?t:t.slice(0,e).trimEnd()+SC}function IC(t,e){if(!t)return null;try{return kC(vC(t,"tasks",e,"task.md"),"utf-8")}catch{return null}}var $C,xC,SC,EC,Yw=x(()=>{"use strict";M();$C=1200,xC=3e3,SC=`
916
+ `)}function zw(t,e){return t.length<=e?t:t.slice(0,e).trimEnd()+IC}function _C(t,e){if(!t)return null;try{return SC(EC(t,"tasks",e,"task.md"),"utf-8")}catch{return null}}var RC,TC,IC,CC,Xw=x(()=>{"use strict";M();RC=1200,TC=3e3,IC=`
923
917
 
924
- \u2026(\u043E\u0431\u0440\u0435\u0437\u0430\u043D\u043E)`,EC=/^#{1,6}\s.*(приёмк|acceptance|критери)/i});import{existsSync as Xs,readFileSync as Vw,readdirSync as Cu}from"node:fs";import{join as Jt}from"node:path";import{parse as CC}from"yaml";function Js(t){if(!Xs(t))return[];let e=[];for(let r of Cu(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=Jt(t,r.name);r.isDirectory()?e.push(...Js(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function zs(t){try{return CC(Vw(t,"utf-8"))}catch{return null}}function zw(t){let e={nodes:new Map,adjacency:new Map,events:new Map,annotations:new Map,keyByEntity:new Map,orphanedEntities:new Set,empty:!0},r=(i,s,a,c)=>{e.adjacency.has(i)||e.adjacency.set(i,[]),e.adjacency.has(s)||e.adjacency.set(s,[]),e.adjacency.get(i).push({to:s,kind:a,weight:c}),e.adjacency.get(s).push({to:i,kind:a,weight:c})};for(let i of Js(Jt(t,"model/derived/structure"))){let s=Gt(zs(i));if(s.ok){for(let a of s.value.nodes)e.nodes.set(a.key,a);for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}}for(let i of[...Js(Jt(t,"model/derived/correlates")),Jt(t,"model/derived/relates.yaml")]){if(!Xs(i))continue;let s=wo(zs(i));if(s.ok)for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}let n=Jt(t,"model/facts/events");if(Xs(n))for(let i of Cu(n).sort()){if(!i.endsWith(".yaml"))continue;let s=Kt(zs(Jt(n,i)));if(!s.ok)continue;let a=s.value;e.events.set(a.taskKey,a);let c=Ee(a.taskKey);for(let l of a.files)r(c,l.key,"touched_by",1);for(let l of a.links?.adr??[])r(c,`adr::${l}`,"references",1);for(let l of a.links?.tasks??[])r(c,Ee(l),"references",1)}for(let i of Js(Jt(t,"model/facts/identity"))){let s=bo(zs(i));if(s.ok)for(let a of s.value.entities)a.status==="orphaned"?e.orphanedEntities.add(a.entityId):e.keyByEntity.set(a.entityId,a.currentKey)}let o=Jt(t,"model/facts/annotations");if(Xs(o)){for(let i of Cu(o).sort())if(i.endsWith(".md"))try{let s=Vw(Jt(o,i),"utf-8"),a=/^---\n[\s\S]*?entityId:\s*(e_[0-9a-f]{8})[\s\S]*?\n---\n?([\s\S]*)$/.exec(s);a&&e.annotations.set(a[1],a[2].trim())}catch{}}return e.empty=e.nodes.size===0&&e.events.size===0,e}var Xw=x(()=>{"use strict";M()});function Zw(t){return new Set((t.toLowerCase().match(/[a-zа-я0-9_]{4,}/g)??[]).filter(e=>!/^\d+$/.test(e)))}function LC(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 Qw(t){let{taskKey:e,title:r,text:n,model:o}=t,i=new Map,s=(f,m)=>{(i.get(f)??0)<m&&i.set(f,m)};(o.events.has(e)||o.adjacency.has(Ee(e)))&&s(Ee(e),Jw);for(let f of`${r}
925
- ${n}`.match(OC)??[]){if(f===e)continue;let m=Ee(f);(o.events.has(f)||o.adjacency.has(m))&&s(m,Jw)}let a=new Map;for(let f of o.nodes.keys()){let m=ne(f);if(m?.level!=="code")continue;let g=m.path.slice(m.path.lastIndexOf("/")+1);for(let b of[m.path,g])a.has(b)||a.set(b,[]),a.get(b).push(f)}let c=`${r}
926
- ${n}`.split(/[\s,;()[\]{}<>"'!?]+/);for(let f of c){let m=f.replace(/^[`*_]+|[`*_.:]+$/g,"");if(!m||!m.includes("/")&&!m.includes("."))continue;let g=a.get(m)??[];g.length===1&&s(g[0],PC)}let l=new Map,u=(f,m)=>{let g=f.toLowerCase();!g||g.length<4||l.set(g,l.has(g)&&l.get(g)!==m?null:m)};for(let f of o.nodes.keys()){let m=ne(f);if(!m)continue;let g=m.path.slice(m.path.lastIndexOf("/")+1);m.level==="code"&&u(g.replace(/\.[a-z0-9]+$/i,""),f),m.level==="component"&&u(g,f)}for(let f of`${r}
927
- ${n}`.match(/[A-Za-z][A-Za-z0-9_-]{3,}/g)??[]){let m=l.get(f.toLowerCase());m&&s(m,AC)}let p=Zw(`${r}
928
- ${n}`),d=[];for(let[f,m]of o.events){if(f===e||!m.title)continue;let g=LC(p,Zw(m.title));g>=jC&&d.push({key:Ee(f),score:g})}return d.sort((f,m)=>m.score-f.score||(f.key<m.key?-1:1)).slice(0,NC).forEach(f=>s(f.key,_C)),i}var Jw,PC,AC,_C,jC,NC,OC,eb=x(()=>{"use strict";M();Jw=1,PC=.9,AC=.7,_C=.5,jC=.15,NC=3,OC=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g});function tb(t,e,r={}){let n=r.cutoff??Pr.activationCutoff,o=r.topK??Pr.topKPerNode,i=r.nodeCap??Pr.nodeCap,s=new Map;for(let[l,u]of e)s.set(l,{activation:u});let a=[...e].map(([l,u])=>({key:l,activation:u})).sort((l,u)=>u.activation-l.activation||(l.key<u.key?-1:1)),c=new Set;for(;a.length>0;){a.sort((p,d)=>d.activation-p.activation||(p.key<d.key?-1:1));let l=a.shift();if(c.has(l.key)||(s.get(l.key)?.activation??0)>l.activation)continue;if(c.add(l.key),c.size>i)break;let u=[...t.adjacency.get(l.key)??[]].sort((p,d)=>d.weight-p.weight||(p.to<d.to?-1:1)).slice(0,o);for(let p of u){let d=Ma[p.kind]??.3,f=l.activation*d*Math.min(p.weight,1);if(f<n)continue;let m=s.get(p.to);(!m||m.activation<f)&&(s.set(p.to,{activation:f,via:{from:l.key,kind:p.kind}}),a.push({key:p.to,activation:f}))}}return s}var rb=x(()=>{"use strict";M()});import{existsSync as Au,readFileSync as nb,readdirSync as MC}from"node:fs";import{join as Zs}from"node:path";function Pu(t){return Math.ceil(t.length/4)}function Jn(t,e,r){let n=o=>o.via?.kind==="correlates"?r?.get(o.key)??1:1;return[...t.entries()].filter(([o])=>e(o)).map(([o,i])=>({key:o,activation:i.activation,via:i.via})).sort((o,i)=>i.activation*n(i)-o.activation*n(o)||(o.key<i.key?-1:1))}function Ct(t){let e=ne(t);return e?(e.level==="task"||e.level==="adr",e.path):t}function oi(t){if(!t.via)return"matched from the task text";let e=Ct(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 ob(t,e){let r=/^ADR-(\d{3,4})$/.exec(e)?.[1];if(!r)return null;let n=Zs(t,"adr");if(!Au(n))return null;let o=r.padStart(4,"0");for(let i of MC(n).sort())if(!(!i.startsWith(`${o}-`)||!i.endsWith(".md")))try{return{file:`adr/${i}`,content:nb(Zs(n,i),"utf-8").trim()}}catch{return null}return null}function ib(t){let{taskKey:e,title:r,contextDir:n,model:o,activated:i}=t,s=t.budgetTokens??Pr.budgetTokens,a=[],c=0,l=E=>{let $=Pu(E);return c+$>s?!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(`
929
- `));let u=Jn(i,E=>E.startsWith("adr::")),p=!1;for(let E of u){let $=ob(n,Ct(E.key));if(!$)continue;let A=`${p?"":`
918
+ \u2026(\u043E\u0431\u0440\u0435\u0437\u0430\u043D\u043E)`,CC=/^#{1,6}\s.*(приёмк|acceptance|критери)/i});import{existsSync as Xs,readFileSync as Jw,readdirSync as Cu}from"node:fs";import{join as Zt}from"node:path";import{parse as jC}from"yaml";function Js(t){if(!Xs(t))return[];let e=[];for(let r of Cu(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=Zt(t,r.name);r.isDirectory()?e.push(...Js(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function zs(t){try{return jC(Jw(t,"utf-8"))}catch{return null}}function Zw(t){let e={nodes:new Map,adjacency:new Map,events:new Map,annotations:new Map,keyByEntity:new Map,orphanedEntities:new Set,empty:!0},r=(i,s,a,c)=>{e.adjacency.has(i)||e.adjacency.set(i,[]),e.adjacency.has(s)||e.adjacency.set(s,[]),e.adjacency.get(i).push({to:s,kind:a,weight:c}),e.adjacency.get(s).push({to:i,kind:a,weight:c})};for(let i of Js(Zt(t,"model/derived/structure"))){let s=Gt(zs(i));if(s.ok){for(let a of s.value.nodes)e.nodes.set(a.key,a);for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}}for(let i of[...Js(Zt(t,"model/derived/correlates")),Zt(t,"model/derived/relates.yaml")]){if(!Xs(i))continue;let s=bo(zs(i));if(s.ok)for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}let n=Zt(t,"model/facts/events");if(Xs(n))for(let i of Cu(n).sort()){if(!i.endsWith(".yaml"))continue;let s=Kt(zs(Zt(n,i)));if(!s.ok)continue;let a=s.value;e.events.set(a.taskKey,a);let c=Ee(a.taskKey);for(let l of a.files)r(c,l.key,"touched_by",1);for(let l of a.links?.adr??[])r(c,`adr::${l}`,"references",1);for(let l of a.links?.tasks??[])r(c,Ee(l),"references",1)}for(let i of Js(Zt(t,"model/facts/identity"))){let s=ko(zs(i));if(s.ok)for(let a of s.value.entities)a.status==="orphaned"?e.orphanedEntities.add(a.entityId):e.keyByEntity.set(a.entityId,a.currentKey)}let o=Zt(t,"model/facts/annotations");if(Xs(o)){for(let i of Cu(o).sort())if(i.endsWith(".md"))try{let s=Jw(Zt(o,i),"utf-8"),a=/^---\n[\s\S]*?entityId:\s*(e_[0-9a-f]{8})[\s\S]*?\n---\n?([\s\S]*)$/.exec(s);a&&e.annotations.set(a[1],a[2].trim())}catch{}}return e.empty=e.nodes.size===0&&e.events.size===0,e}var Qw=x(()=>{"use strict";M()});function tb(t){return new Set((t.toLowerCase().match(/[a-zа-я0-9_]{4,}/g)??[]).filter(e=>!/^\d+$/.test(e)))}function BC(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 rb(t){let{taskKey:e,title:r,text:n,model:o}=t,i=new Map,s=(f,m)=>{(i.get(f)??0)<m&&i.set(f,m)};(o.events.has(e)||o.adjacency.has(Ee(e)))&&s(Ee(e),eb);for(let f of`${r}
919
+ ${n}`.match(UC)??[]){if(f===e)continue;let m=Ee(f);(o.events.has(f)||o.adjacency.has(m))&&s(m,eb)}let a=new Map;for(let f of o.nodes.keys()){let m=ne(f);if(m?.level!=="code")continue;let g=m.path.slice(m.path.lastIndexOf("/")+1);for(let b of[m.path,g])a.has(b)||a.set(b,[]),a.get(b).push(f)}let c=`${r}
920
+ ${n}`.split(/[\s,;()[\]{}<>"'!?]+/);for(let f of c){let m=f.replace(/^[`*_]+|[`*_.:]+$/g,"");if(!m||!m.includes("/")&&!m.includes("."))continue;let g=a.get(m)??[];g.length===1&&s(g[0],NC)}let l=new Map,u=(f,m)=>{let g=f.toLowerCase();!g||g.length<4||l.set(g,l.has(g)&&l.get(g)!==m?null:m)};for(let f of o.nodes.keys()){let m=ne(f);if(!m)continue;let g=m.path.slice(m.path.lastIndexOf("/")+1);m.level==="code"&&u(g.replace(/\.[a-z0-9]+$/i,""),f),m.level==="component"&&u(g,f)}for(let f of`${r}
921
+ ${n}`.match(/[A-Za-z][A-Za-z0-9_-]{3,}/g)??[]){let m=l.get(f.toLowerCase());m&&s(m,OC)}let p=tb(`${r}
922
+ ${n}`),d=[];for(let[f,m]of o.events){if(f===e||!m.title)continue;let g=BC(p,tb(m.title));g>=MC&&d.push({key:Ee(f),score:g})}return d.sort((f,m)=>m.score-f.score||(f.key<m.key?-1:1)).slice(0,DC).forEach(f=>s(f.key,LC)),i}var eb,NC,OC,LC,MC,DC,UC,nb=x(()=>{"use strict";M();eb=1,NC=.9,OC=.7,LC=.5,MC=.15,DC=3,UC=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g});function ob(t,e,r={}){let n=r.cutoff??Ar.activationCutoff,o=r.topK??Ar.topKPerNode,i=r.nodeCap??Ar.nodeCap,s=new Map;for(let[l,u]of e)s.set(l,{activation:u});let a=[...e].map(([l,u])=>({key:l,activation:u})).sort((l,u)=>u.activation-l.activation||(l.key<u.key?-1:1)),c=new Set;for(;a.length>0;){a.sort((p,d)=>d.activation-p.activation||(p.key<d.key?-1:1));let l=a.shift();if(c.has(l.key)||(s.get(l.key)?.activation??0)>l.activation)continue;if(c.add(l.key),c.size>i)break;let u=[...t.adjacency.get(l.key)??[]].sort((p,d)=>d.weight-p.weight||(p.to<d.to?-1:1)).slice(0,o);for(let p of u){let d=Ma[p.kind]??.3,f=l.activation*d*Math.min(p.weight,1);if(f<n)continue;let m=s.get(p.to);(!m||m.activation<f)&&(s.set(p.to,{activation:f,via:{from:l.key,kind:p.kind}}),a.push({key:p.to,activation:f}))}}return s}var ib=x(()=>{"use strict";M()});import{existsSync as Au,readFileSync as sb,readdirSync as FC}from"node:fs";import{join as Zs}from"node:path";function Pu(t){return Math.ceil(t.length/4)}function Zn(t,e,r){let n=o=>o.via?.kind==="correlates"?r?.get(o.key)??1:1;return[...t.entries()].filter(([o])=>e(o)).map(([o,i])=>({key:o,activation:i.activation,via:i.via})).sort((o,i)=>i.activation*n(i)-o.activation*n(o)||(o.key<i.key?-1:1))}function Ct(t){let e=ne(t);return e?(e.level==="task"||e.level==="adr",e.path):t}function ii(t){if(!t.via)return"matched from the task text";let e=Ct(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 ab(t,e){let r=/^ADR-(\d{3,4})$/.exec(e)?.[1];if(!r)return null;let n=Zs(t,"adr");if(!Au(n))return null;let o=r.padStart(4,"0");for(let i of FC(n).sort())if(!(!i.startsWith(`${o}-`)||!i.endsWith(".md")))try{return{file:`adr/${i}`,content:sb(Zs(n,i),"utf-8").trim()}}catch{return null}return null}function cb(t){let{taskKey:e,title:r,contextDir:n,model:o,activated:i}=t,s=t.budgetTokens??Ar.budgetTokens,a=[],c=0,l=E=>{let $=Pu(E);return c+$>s?!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(`
923
+ `));let u=Zn(i,E=>E.startsWith("adr::")),p=!1;for(let E of u){let $=ab(n,Ct(E.key));if(!$)continue;let A=`${p?"":`
930
924
  ## Governing decisions
931
925
  `}
932
- ### ${Ct(E.key)} (\`${$.file}\`, ${oi(E)})
926
+ ### ${Ct(E.key)} (\`${$.file}\`, ${ii(E)})
933
927
 
934
928
  ${$.content}
935
- `;if(!l(A))break;p=!0}let d=Jn(i,E=>o.nodes.get(E)?.entityId!==void 0).filter(E=>o.annotations.has(o.nodes.get(E.key).entityId)),f=t.staleKeys??new Set,m=!1;for(let E of d){let $=o.nodes.get(E.key).entityId,A=o.annotations.get($),N=f.has(E.key)?" \u2014 \u26A0 the file changed since the map was built":o.orphanedEntities.has($)?" \u2014 \u26A0 the file no longer exists":"",B=`${m?"":`
929
+ `;if(!l(A))break;p=!0}let d=Zn(i,E=>o.nodes.get(E)?.entityId!==void 0).filter(E=>o.annotations.has(o.nodes.get(E.key).entityId)),f=t.staleKeys??new Set,m=!1;for(let E of d){let $=o.nodes.get(E.key).entityId,A=o.annotations.get($),N=f.has(E.key)?" \u2014 \u26A0 the file changed since the map was built":o.orphanedEntities.has($)?" \u2014 \u26A0 the file no longer exists":"",B=`${m?"":`
936
930
  ## Why the code is shaped this way (intent notes)
937
931
  `}
938
932
  ### \`${Ct(E.key)}\`${N}
939
933
 
940
934
  ${A}
941
- `;if(!l(B))break;m=!0}let g=Ee(e),b=Jn(i,E=>E.startsWith("task::")&&E!==g).slice(0,DC),w=!1;for(let E of b){let $=o.events.get(Ct(E.key));if(!$)continue;let A=[...$.files].filter(h=>!f.has(h.key)&&(!h.entityId||!o.orphanedEntities.has(h.entityId))).sort((h,F)=>(F.churn??0)-(h.churn??0)||(h.key<F.key?-1:1)).slice(0,3).map(h=>`\`${Ct(h.key)}\``).join(", "),N="",B=$.links?.solution??[`tasks/${$.taskKey}/PLAN.md`,`tasks/${$.taskKey}/SOLUTION.md`].find(h=>Au(Zs(n,h)))??`tasks/${$.taskKey}/PLAN.md`,H=Zs(n,B);if(Au(H))try{N=`
942
- > ${nb(H,"utf-8").trim().slice(0,BC).replace(/\n+/g," ").trim()}\u2026
935
+ `;if(!l(B))break;m=!0}let g=Ee(e),b=Zn(i,E=>E.startsWith("task::")&&E!==g).slice(0,GC),w=!1;for(let E of b){let $=o.events.get(Ct(E.key));if(!$)continue;let A=[...$.files].filter(h=>!f.has(h.key)&&(!h.entityId||!o.orphanedEntities.has(h.entityId))).sort((h,F)=>(F.churn??0)-(h.churn??0)||(h.key<F.key?-1:1)).slice(0,3).map(h=>`\`${Ct(h.key)}\``).join(", "),N="",B=$.links?.solution??[`tasks/${$.taskKey}/PLAN.md`,`tasks/${$.taskKey}/SOLUTION.md`].find(h=>Au(Zs(n,h)))??`tasks/${$.taskKey}/PLAN.md`,H=Zs(n,B);if(Au(H))try{N=`
936
+ > ${sb(H,"utf-8").trim().slice(0,HC).replace(/\n+/g," ").trim()}\u2026
943
937
  > _(full text: \`${B}\`)_`}catch{}let j=`${w?"":`
944
938
  ## Related past tasks
945
939
  `}
946
- - **${$.taskKey}**${$.title?` \u2014 ${$.title}`:""}${$.date?` (${$.date})`:""}, ${oi(E)}. Files: ${A||"\u2014"}.${N}`;if(!l(j))break;w=!0}let v=E=>{if(f.has(E.key))return!1;let $=o.nodes.get(E.key)?.entityId;return!$||!o.orphanedEntities.has($)},y=Jn(i,E=>E.startsWith("code:"),t.fileWeights),k=y.filter(v).slice(0,UC);if(k.length>0){let E=["","## Files likely involved",""];for(let $ of k){let A=`- \`${Ct($.key)}\` \u2014 ${oi($)}`;if(c+Pu(E.join(`
940
+ - **${$.taskKey}**${$.title?` \u2014 ${$.title}`:""}${$.date?` (${$.date})`:""}, ${ii(E)}. Files: ${A||"\u2014"}.${N}`;if(!l(j))break;w=!0}let v=E=>{if(f.has(E.key))return!1;let $=o.nodes.get(E.key)?.entityId;return!$||!o.orphanedEntities.has($)},y=Zn(i,E=>E.startsWith("code:"),t.fileWeights),k=y.filter(v).slice(0,KC);if(k.length>0){let E=["","## Files likely involved",""];for(let $ of k){let A=`- \`${Ct($.key)}\` \u2014 ${ii($)}`;if(c+Pu(E.join(`
947
941
  `))+Pu(A)>s)break;E.push(A)}E.length>3&&l(E.join(`
948
- `))}let C=y.filter(E=>!v(E)).slice(0,10);if(C.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.","",...C.map($=>`- \`${Ct($.key)}\` \u2014 ${oi($)}${f.has($.key)?" (changed since the map was built)":" (file gone)"}`)];l(E.join(`
942
+ `))}let C=y.filter(E=>!v(E)).slice(0,10);if(C.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.","",...C.map($=>`- \`${Ct($.key)}\` \u2014 ${ii($)}${f.has($.key)?" (changed since the map was built)":" (file gone)"}`)];l(E.join(`
949
943
  `))}return a.length<=1?null:a.join(`
950
944
  `)+`
951
- `}function sb(t){let{model:e,activated:r}=t,n=t.staleKeys??new Set,o=t.maxPaths??18,i=1600,s=Jn(r,u=>u.startsWith("adr::")).filter(u=>ob(t.contextDir,Ct(u.key))!==null).slice(0,6).map(u=>Ct(u.key)),a=u=>{if(n.has(u.key))return!1;let p=e.nodes.get(u.key)?.entityId;return!p||!e.orphanedEntities.has(p)},c=Jn(r,u=>u.startsWith("code:"),t.fileWeights).filter(a).slice(0,o);if(s.length===0&&c.length===0)return null;let l=["Top of the pack (the full brief with reasons and decision bodies is in","`meta/context-pack.md` \u2014 still read it):"];if(s.length>0&&l.push("",`Governing decisions: ${s.join(", ")} (bodies under \`adr/\`).`),c.length>0){l.push("","Files most likely involved:");let u=0;for(let p of c){let d=`- \`${Ct(p.key)}\` \u2014 ${oi(p)}`;if(u+d.length>i)break;l.push(d),u+=d.length+1}}return l.join(`
952
- `)}var DC,UC,BC,ab=x(()=>{"use strict";M();DC=5,UC=300,BC=400});var pb={};Ne(pb,{assembleContextPack:()=>WC,computeIdfWeights:()=>db});import{createHash as FC}from"node:crypto";import{existsSync as cb,readFileSync as lb}from"node:fs";import{join as ub}from"node:path";function db(t){let e=new Map,r=t.events.size;if(r<GC)return e;let n=new Map;for(let i of t.events.values()){let s=new Set;for(let a of i.files){let c=a.entityId?`e:${a.entityId}`:`k:${a.key}`;s.has(c)||(s.add(c),n.set(c,(n.get(c)??0)+1))}}let o=Math.log(r+1);for(let[i,s]of n){let a=i.startsWith("e:")?t.keyByEntity.get(i.slice(2))??null:i.slice(2);a&&e.set(a,Math.max(.15,Math.log((r+1)/(s+1))/o))}return e}function KC(t){return FC("sha1").update(`blob ${t.length}\0`).update(t).digest("hex")}function HC(t,e,r){let n=new Set;for(let o of e.keys()){let i=ne(o);if(i?.level!=="code")continue;let s=t.nodes.get(o);if(!s?.contentHash)continue;let a=r.get(i.repo);if(!a)continue;let c=ub(a,i.path);try{if(!cb(c)){n.add(o);continue}KC(lb(c)).startsWith(s.contentHash)||n.add(o)}catch{}}return n}function WC(t){let e=zw(t.contextDir);if(e.empty)return null;let r="",n=ub(t.contextDir,`tasks/${t.taskKey}/task.md`);if(cb(n))try{r=lb(n,"utf-8")}catch{r=""}let o=Qw({taskKey:t.taskKey,title:t.title,text:r,model:e});if(o.size===0)return null;let i=tb(e,o),s=t.repoDirs?HC(e,i,t.repoDirs):new Set,a=t.idfPenalty===!1?new Map:db(e),c=ib({taskKey:t.taskKey,title:t.title,contextDir:t.contextDir,model:e,activated:i,staleKeys:s,fileWeights:a,...t.budgetTokens!==void 0?{budgetTokens:t.budgetTokens}:{}});return c?{markdown:c,top:sb({model:e,activated:i,contextDir:t.contextDir,staleKeys:s,fileWeights:a})}:null}var GC,fb=x(()=>{"use strict";M();Xw();eb();rb();ab();GC=30});var yb={};Ne(yb,{SKILLS_DIR:()=>_u,loadSkills:()=>tP,materializeSkills:()=>rP,renderSkillsBlock:()=>nP,resolveBundledSkillsDir:()=>gb});import{cpSync as qC,existsSync as mb,mkdirSync as YC,readFileSync as VC,readdirSync as hb}from"node:fs";import{dirname as zC,join as kr}from"node:path";import{fileURLToPath as XC}from"node:url";import{parse as JC}from"yaml";function gb(t){for(let e of[t,kr(t,"skills")])try{if(hb(e,{withFileTypes:!0}).some(n=>n.isDirectory()&&mb(kr(e,n.name,"SKILL.md"))))return e}catch{}return t}function QC(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
945
+ `}function lb(t){let{model:e,activated:r}=t,n=t.staleKeys??new Set,o=t.maxPaths??18,i=1600,s=Zn(r,u=>u.startsWith("adr::")).filter(u=>ab(t.contextDir,Ct(u.key))!==null).slice(0,6).map(u=>Ct(u.key)),a=u=>{if(n.has(u.key))return!1;let p=e.nodes.get(u.key)?.entityId;return!p||!e.orphanedEntities.has(p)},c=Zn(r,u=>u.startsWith("code:"),t.fileWeights).filter(a).slice(0,o);if(s.length===0&&c.length===0)return null;let l=["Top of the pack (the full brief with reasons and decision bodies is in","`meta/context-pack.md` \u2014 still read it):"];if(s.length>0&&l.push("",`Governing decisions: ${s.join(", ")} (bodies under \`adr/\`).`),c.length>0){l.push("","Files most likely involved:");let u=0;for(let p of c){let d=`- \`${Ct(p.key)}\` \u2014 ${ii(p)}`;if(u+d.length>i)break;l.push(d),u+=d.length+1}}return l.join(`
946
+ `)}var GC,KC,HC,ub=x(()=>{"use strict";M();GC=5,KC=300,HC=400});var hb={};Ne(hb,{assembleContextPack:()=>zC,computeIdfWeights:()=>mb});import{createHash as WC}from"node:crypto";import{existsSync as db,readFileSync as pb}from"node:fs";import{join as fb}from"node:path";function mb(t){let e=new Map,r=t.events.size;if(r<qC)return e;let n=new Map;for(let i of t.events.values()){let s=new Set;for(let a of i.files){let c=a.entityId?`e:${a.entityId}`:`k:${a.key}`;s.has(c)||(s.add(c),n.set(c,(n.get(c)??0)+1))}}let o=Math.log(r+1);for(let[i,s]of n){let a=i.startsWith("e:")?t.keyByEntity.get(i.slice(2))??null:i.slice(2);a&&e.set(a,Math.max(.15,Math.log((r+1)/(s+1))/o))}return e}function YC(t){return WC("sha1").update(`blob ${t.length}\0`).update(t).digest("hex")}function VC(t,e,r){let n=new Set;for(let o of e.keys()){let i=ne(o);if(i?.level!=="code")continue;let s=t.nodes.get(o);if(!s?.contentHash)continue;let a=r.get(i.repo);if(!a)continue;let c=fb(a,i.path);try{if(!db(c)){n.add(o);continue}YC(pb(c)).startsWith(s.contentHash)||n.add(o)}catch{}}return n}function zC(t){let e=Zw(t.contextDir);if(e.empty)return null;let r="",n=fb(t.contextDir,`tasks/${t.taskKey}/task.md`);if(db(n))try{r=pb(n,"utf-8")}catch{r=""}let o=rb({taskKey:t.taskKey,title:t.title,text:r,model:e});if(o.size===0)return null;let i=ob(e,o),s=t.repoDirs?VC(e,i,t.repoDirs):new Set,a=t.idfPenalty===!1?new Map:mb(e),c=cb({taskKey:t.taskKey,title:t.title,contextDir:t.contextDir,model:e,activated:i,staleKeys:s,fileWeights:a,...t.budgetTokens!==void 0?{budgetTokens:t.budgetTokens}:{}});return c?{markdown:c,top:lb({model:e,activated:i,contextDir:t.contextDir,staleKeys:s,fileWeights:a})}:null}var qC,gb=x(()=>{"use strict";M();Qw();nb();ib();ub();qC=30});var kb={};Ne(kb,{SKILLS_DIR:()=>_u,loadSkills:()=>iP,materializeSkills:()=>sP,renderSkillsBlock:()=>aP,resolveBundledSkillsDir:()=>bb});import{cpSync as XC,existsSync as yb,mkdirSync as JC,readFileSync as ZC,readdirSync as wb}from"node:fs";import{dirname as QC,join as vr}from"node:path";import{fileURLToPath as eP}from"node:url";import{parse as tP}from"yaml";function bb(t){for(let e of[t,vr(t,"skills")])try{if(wb(e,{withFileTypes:!0}).some(n=>n.isDirectory()&&yb(vr(e,n.name,"SKILL.md"))))return e}catch{}return t}function nP(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
953
947
  ---`,3);return r===-1?null:{yaml:e.slice(e.indexOf(`
954
948
  `,3)+1,r),body:e.slice(e.indexOf(`
955
- `,r+1)+1)}}function eP(t,e,r){let n=[],o=[];if(!mb(t))return{skills:n,errors:o};let i;try{i=hb(t,{withFileTypes:!0}).filter(s=>s.isDirectory()).map(s=>s.name).sort()}catch(s){return{skills:n,errors:[{source:r,error:`cannot read: ${String(s)}`}]}}for(let s of i){let a=kr(t,s),c=`${r}/${s}`,l;try{l=VC(kr(a,"SKILL.md"),"utf-8")}catch{o.push({source:c,error:"no SKILL.md in the directory"});continue}let u=QC(l);if(!u){o.push({source:c,error:"SKILL.md has no frontmatter block"});continue}let p;try{p=JC(u.yaml)}catch(f){o.push({source:c,error:`frontmatter is not valid YAML: ${String(f)}`});continue}let d=mc({name:s,frontmatter:p,body:u.body});d.ok?n.push({...d.skill,dir:a,origin:e}):o.push({source:c,error:d.error})}return{skills:n,errors:o}}function tP(t){let e=[],r=(s,a,c)=>{let l=eP(s,a,c);return e.push(...l.errors),l.skills},n=t.sources.bundled?r(ZC,"bundled","bundled"):[],o=t.sources.context&&t.contextDir?r(kr(t.contextDir,"skills"),"context","skills"):[],i=t.sources.repo?t.repoDirs.flatMap(s=>r(kr(s,".claude","skills"),"repo","repo")):[];return{skills:hc(n,o,i),errors:e}}function rP(t,e){if(e.length===0)return[];let r=kr(t,_u);YC(r,{recursive:!0});let n=[];for(let o of e)qC(o.dir,kr(r,o.name),{recursive:!0}),n.push(`${_u}/${o.name}`);return n}function nP(t,e=[]){let r=new Set(t.map(s=>s.name)),n=e.filter(s=>!r.has(s));if(t.length===0&&n.length===0)return"";let o=[];t.length>0&&o.push("## Skills available to you","",...t.map(s=>`- **${s.name}** \u2014 ${s.description}`),"","Only these lines are in context; a skill's steps load when you invoke it.","When one covers what you are about to do, use it: it was written down","because the obvious approach was wrong or costly.","");let i=e.filter(s=>r.has(s));return i.length>0&&o.push("**The approved plan requires this task to follow: "+i.map(s=>`\`${s}\``).join(", ")+".**","This is not a suggestion \u2014 a reviewer approved it as a requirement.",""),n.length>0&&o.push("**The plan prescribes "+n.map(s=>`\`${s}\``).join(", ")+", which is not available here.**","Proceed without it and say so in your result \u2014 do not invent the procedure.",""),o.join(`
956
- `)}var _u,ZC,wb=x(()=>{"use strict";M();_u=".claude/skills";ZC=gb(zC(XC(import.meta.url)))});var $b={};Ne($b,{seedMarketplaces:()=>fP});import{spawn as oP}from"node:child_process";import{cpSync as iP,existsSync as bb,mkdirSync as kb,rmSync as ju,symlinkSync as sP,writeFileSync as aP}from"node:fs";import{homedir as cP}from"node:os";import{join as vr}from"node:path";function vb(){return vr(cP(),".codepipe-sandbox","plugins")}function dP(t){return vr(vb(),"src",`${t.name}@${t.sha||"head"}`)}function ii(t,e){return new Promise((r,n)=>{let o=oP("git",t,{cwd:e,stdio:["ignore","ignore","pipe"],env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"}}),i=[];o.stderr.setEncoding("utf-8"),o.stderr.on("data",s=>i.push(s)),o.on("error",n),o.on("close",s=>{if(s===0)return r();n(new Error(`git ${t[0]} failed (exit ${s}): ${i.join("").trim().slice(0,400)}`))})})}async function pP(t){let e=dP(t);if(bb(vr(e,".claude-plugin","marketplace.json")))return e;ju(e,{recursive:!0,force:!0}),kb(e,{recursive:!0});let r=`https://github.com/${t.repo}.git`;if(t.sha?(await ii(["init","--quiet"],e),await ii(["remote","add","origin",r],e),await ii(["fetch","--quiet","--depth","1","origin",t.sha],e),await ii(["checkout","--quiet","FETCH_HEAD"],e)):await ii(["clone","--quiet","--depth","1",r,e]),!bb(vr(e,".claude-plugin","marketplace.json")))throw ju(e,{recursive:!0,force:!0}),new Error("no .claude-plugin/marketplace.json \u2014 this repository is not a marketplace");return e}async function fP(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 pP(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=vr(vb(),"seed",r.map(a=>`${a.name}@${a.sha||"head"}`).sort().join("_")),i=vr(o,lP);kb(i,{recursive:!0});let s={};for(let a of r){let c=vr(i,a.name);ju(c,{recursive:!0,force:!0}),mP(n.get(a.name),c),s[a.name]={source:{source:"github",repo:a.repo},installLocation:c,...a.sha?{commit:a.sha}:{}}}return aP(vr(o,uP),`${JSON.stringify(s,null,2)}
957
- `),{dir:o,ready:r,errors:e}}function mP(t,e){try{sP(t,e,"dir")}catch{iP(t,e,{recursive:!0,filter:r=>!/(^|\/)\.git(\/|$)/.test(r)})}}var lP,uP,xb=x(()=>{"use strict";lP="marketplaces",uP="known_marketplaces.json"});var Ou={};Ne(Ou,{loadRoles:()=>$P,resolveBundledRolesDir:()=>Rb});import{existsSync as hP,readFileSync as gP,readdirSync as Eb}from"node:fs";import{dirname as yP,join as Nu}from"node:path";import{fileURLToPath as wP}from"node:url";import{parse as bP}from"yaml";function Rb(t){for(let e of[t,Nu(t,"roles")])try{if(Eb(e).some(r=>r.endsWith(".md")))return e}catch{}return t}function vP(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
949
+ `,r+1)+1)}}function oP(t,e,r){let n=[],o=[];if(!yb(t))return{skills:n,errors:o};let i;try{i=wb(t,{withFileTypes:!0}).filter(s=>s.isDirectory()).map(s=>s.name).sort()}catch(s){return{skills:n,errors:[{source:r,error:`cannot read: ${String(s)}`}]}}for(let s of i){let a=vr(t,s),c=`${r}/${s}`,l;try{l=ZC(vr(a,"SKILL.md"),"utf-8")}catch{o.push({source:c,error:"no SKILL.md in the directory"});continue}let u=nP(l);if(!u){o.push({source:c,error:"SKILL.md has no frontmatter block"});continue}let p;try{p=tP(u.yaml)}catch(f){o.push({source:c,error:`frontmatter is not valid YAML: ${String(f)}`});continue}let d=mc({name:s,frontmatter:p,body:u.body});d.ok?n.push({...d.skill,dir:a,origin:e}):o.push({source:c,error:d.error})}return{skills:n,errors:o}}function iP(t){let e=[],r=(s,a,c)=>{let l=oP(s,a,c);return e.push(...l.errors),l.skills},n=t.sources.bundled?r(rP,"bundled","bundled"):[],o=t.sources.context&&t.contextDir?r(vr(t.contextDir,"skills"),"context","skills"):[],i=t.sources.repo?t.repoDirs.flatMap(s=>r(vr(s,".claude","skills"),"repo","repo")):[];return{skills:hc(n,o,i),errors:e}}function sP(t,e){if(e.length===0)return[];let r=vr(t,_u);JC(r,{recursive:!0});let n=[];for(let o of e)XC(o.dir,vr(r,o.name),{recursive:!0}),n.push(`${_u}/${o.name}`);return n}function aP(t,e=[]){let r=new Set(t.map(s=>s.name)),n=e.filter(s=>!r.has(s));if(t.length===0&&n.length===0)return"";let o=[];t.length>0&&o.push("## Skills available to you","",...t.map(s=>`- **${s.name}** \u2014 ${s.description}`),"","Only these lines are in context; a skill's steps load when you invoke it.","When one covers what you are about to do, use it: it was written down","because the obvious approach was wrong or costly.","");let i=e.filter(s=>r.has(s));return i.length>0&&o.push("**The approved plan requires this task to follow: "+i.map(s=>`\`${s}\``).join(", ")+".**","This is not a suggestion \u2014 a reviewer approved it as a requirement.",""),n.length>0&&o.push("**The plan prescribes "+n.map(s=>`\`${s}\``).join(", ")+", which is not available here.**","Proceed without it and say so in your result \u2014 do not invent the procedure.",""),o.join(`
950
+ `)}var _u,rP,vb=x(()=>{"use strict";M();_u=".claude/skills";rP=bb(QC(eP(import.meta.url)))});var Eb={};Ne(Eb,{seedMarketplaces:()=>yP});import{spawn as cP}from"node:child_process";import{cpSync as lP,existsSync as $b,mkdirSync as xb,rmSync as ju,symlinkSync as uP,writeFileSync as dP}from"node:fs";import{homedir as pP}from"node:os";import{join as $r}from"node:path";function Sb(){return $r(pP(),".codepipe-sandbox","plugins")}function hP(t){return $r(Sb(),"src",`${t.name}@${t.sha||"head"}`)}function si(t,e){return new Promise((r,n)=>{let o=cP("git",t,{cwd:e,stdio:["ignore","ignore","pipe"],env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"}}),i=[];o.stderr.setEncoding("utf-8"),o.stderr.on("data",s=>i.push(s)),o.on("error",n),o.on("close",s=>{if(s===0)return r();n(new Error(`git ${t[0]} failed (exit ${s}): ${i.join("").trim().slice(0,400)}`))})})}async function gP(t){let e=hP(t);if($b($r(e,".claude-plugin","marketplace.json")))return e;ju(e,{recursive:!0,force:!0}),xb(e,{recursive:!0});let r=`https://github.com/${t.repo}.git`;if(t.sha?(await si(["init","--quiet"],e),await si(["remote","add","origin",r],e),await si(["fetch","--quiet","--depth","1","origin",t.sha],e),await si(["checkout","--quiet","FETCH_HEAD"],e)):await si(["clone","--quiet","--depth","1",r,e]),!$b($r(e,".claude-plugin","marketplace.json")))throw ju(e,{recursive:!0,force:!0}),new Error("no .claude-plugin/marketplace.json \u2014 this repository is not a marketplace");return e}async function yP(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 gP(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=$r(Sb(),"seed",r.map(a=>`${a.name}@${a.sha||"head"}`).sort().join("_")),i=$r(o,fP);xb(i,{recursive:!0});let s={};for(let a of r){let c=$r(i,a.name);ju(c,{recursive:!0,force:!0}),wP(n.get(a.name),c),s[a.name]={source:{source:"github",repo:a.repo},installLocation:c,...a.sha?{commit:a.sha}:{}}}return dP($r(o,mP),`${JSON.stringify(s,null,2)}
951
+ `),{dir:o,ready:r,errors:e}}function wP(t,e){try{uP(t,e,"dir")}catch{lP(t,e,{recursive:!0,filter:r=>!/(^|\/)\.git(\/|$)/.test(r)})}}var fP,mP,Rb=x(()=>{"use strict";fP="marketplaces",mP="known_marketplaces.json"});var Ou={};Ne(Ou,{loadRoles:()=>RP,resolveBundledRolesDir:()=>Cb});import{existsSync as bP,readFileSync as kP,readdirSync as Ib}from"node:fs";import{dirname as vP,join as Nu}from"node:path";import{fileURLToPath as $P}from"node:url";import{parse as xP}from"yaml";function Cb(t){for(let e of[t,Nu(t,"roles")])try{if(Ib(e).some(r=>r.endsWith(".md")))return e}catch{}return t}function EP(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
958
952
  ---`,3);if(r===-1)return null;let n=e.slice(e.indexOf(`
959
953
  `,3)+1,r),o=e.indexOf(`
960
- `,r+1);return{yaml:n,body:o===-1?"":e.slice(o+1)}}function Sb(t,e,r){let n=[],o=[];if(!hP(t))return{roles:n,errors:o};let i;try{i=Eb(t).sort()}catch(s){return{roles:n,errors:[{file:r,error:`cannot read: ${String(s)}`}]}}for(let s of i){if(!s.endsWith(".md"))continue;let a=`${r}/${s}`,c;try{c=gP(Nu(t,s),"utf-8")}catch(d){o.push({file:a,error:`cannot read: ${String(d)}`});continue}let l=vP(c);if(!l){o.push({file:a,error:"missing frontmatter block (--- \u2026 ---) at the top of the file"});continue}let u;try{u=bP(l.yaml)}catch(d){o.push({file:a,error:`frontmatter is not valid YAML: ${String(d)}`});continue}let p=cc({name:s.slice(0,-3),frontmatter:u,body:l.body,origin:e});p.ok?n.push(p.role):o.push({file:a,error:p.error})}return{roles:n,errors:o}}function $P(t){let e=Sb(kP,"bundled","bundled"),r=t?Sb(Nu(t,"roles"),"project","roles"):{roles:[],errors:[]};return{roles:lc(e.roles,r.roles),errors:[...e.errors,...r.errors]}}var kP,Lu=x(()=>{"use strict";M();kP=Rb(yP(wP(import.meta.url)))});var Mu={};Ne(Mu,{COUNCIL_DEFAULT_MAX_PARALLEL:()=>TP,COUNCIL_DIR:()=>RP,COUNCIL_MAX_PARALLEL_CEILING:()=>Tb,renderCouncilRolePrompt:()=>IP,renderOpinionsBlock:()=>PP,renderReviewOpinionsBlock:()=>AP,renderReviewRolePrompt:()=>CP,runCouncil:()=>_P});import{existsSync as xP,mkdirSync as SP,writeFileSync as EP}from"node:fs";import{join as Qs}from"node:path";function Ib(t,e){return["## Where to read (read-only)","",...e?["The workspace contains the project repos and the Context Repo clone",`(\`${e}\`; start with \`knowledge/INDEX.md\` and \`adr/\`).`]:["The workspace contains the project repos."],...t.refs.length>0&&e?["Read these first:",...t.refs.map(r=>`- \`${Qs(e,r)}\``)]:[]]}function IP(t,e,r,n){return[`# Council role: ${t.name}`,"",t.body,"","## The questions the pipeline is blocked on","",e,"",...Ib(t,r),"","## Your deliverable","",`Write your opinion to \`${n}\`: for EACH question \u2014 your answer,`,"the strongest argument for it, and what would change your mind. You are","ONE role of a council: argue your perspective sharply, do not average.","You never modify code \u2014 this file is your only output."].join(`
961
- `)}function CP(t,e,r,n){return[`# Council role: ${t.name}`,"",t.body,"","## The review subject","","Review the change under `code/`: in each repo, the subject is","`git diff refs/worktree/codepipe/review-base..HEAD` \u2014 the base ref is","pinned, do not diff against a branch tip. A repo with an empty diff is","context, not subject. If the ref is MISSING in a repo (the pin can fail),","say so in your opinion and skip that repo \u2014 never substitute another base:","findings against a wrong diff are worse than no findings.","","## The finding contract","","Every finding names file + line, the concrete failing scenario, and stays","within the diff \u2014 or states explicitly how the change broke an untouched","place. A finding without a scenario is an opinion, not a finding.",...e?["",e.trim()]:[],"",...Ib(t,r),"","## Your deliverable","",`Write your findings to \`${n}\` \u2014 your role's independent view,`,"one section per finding. Returning NOTHING is a normal outcome \u2014 do not","manufacture findings to justify your seat. You are ONE role of a council:","stay inside your perspective, do not average.","You never modify code \u2014 this file is your only output."].join(`
962
- `)}function Cb(t){let e=t.filter(n=>n.ok),r=t.filter(n=>!n.ok);return[...e.map(n=>`- \`${n.artifact}\` \u2014 the ${n.role} role`),...r.length>0?["",`Failed roles (no opinion \u2014 weigh accordingly): ${r.map(n=>n.role).join(", ")}.`]:[]]}function PP(t){return["## The council's opinions (already gathered)","","The council's roles have already examined the questions \u2014 each in its own","context, blind to the others. Read every opinion before answering:","",...Cb(t),"","Weigh, do not vote: agreement between roles is evidence, not a verdict,","and you may overrule any of them \u2014 say so in the rationale when you do."].join(`
963
- `)}function AP(t){return["## The council's findings (already gathered)","","The project's critic roles have already reviewed this change \u2014 each in its","own context, blind to the others. Read every file before your own pass:","",...Cb(t),"","Then do your own job on what they wrote:","","1. **Deduplicate.** Two roles reporting the same defect is one finding, not two.","2. **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.","3. **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 found nothing is a normal outcome \u2014 do not manufacture findings","to justify the council."].join(`
964
- `)}async function _P(t){let e=t.baseInput.workspaceDir;SP(Qs(e,t.artifactDir),{recursive:!0});let r=Math.max(1,Math.min(t.maxParallel,Tb)),n=[...t.roles],o=[],i=ut(),s=null,a=new AbortController,c=t.baseInput.signal,l=()=>a.abort();c?.aborted?a.abort():c?.addEventListener("abort",l,{once:!0});let u=async d=>{let f=`${t.artifactDir}/${d.name}.md`,m=t.runnerFor(d.provider),g=t.promptFor(d,f),b=d.model??t.defaultModel;try{let w=await m.run({...t.baseInput,signal:a.signal,role:"council",prompt:g,...b?{model:b}:{},...t.effort?{effort:t.effort}:{}});zr(i,w.usage),xP(Qs(e,f))?(o.push({role:d.name,ok:!0,artifact:f,usage:w.usage}),t.log(`role ${d.name}: done ($${w.usage.totalCostUsd.toFixed(2)})`)):(o.push({role:d.name,ok:!1,error:`exited ok but wrote no ${f}`,usage:w.usage}),t.log(`role ${d.name}: exited ok but wrote no ${f}`))}catch(w){let v=w instanceof Me?w.details.usage:w instanceof It?w.usage:void 0;v&&zr(i,v),w instanceof Me&&w.details.rateLimited&&!s&&(s=w,a.abort());let y=w instanceof Error?w.message:String(w);o.push({role:d.name,ok:!1,error:y,usage:v??ut()}),t.log(`role ${d.name}: failed \u2014 ${y}`)}},p=Array.from({length:Math.min(r,n.length)},async()=>{for(;n.length>0&&!a.signal.aborted;){let d=n.shift();if(!d)break;await u(d)}});try{await Promise.all(p)}finally{c?.removeEventListener("abort",l)}if(s){let d=s,f=d.details.usage?.model;throw d.details.usage={...i,...f!==void 0?{model:f}:{}},d}return EP(Qs(e,t.artifactDir,"usage.json"),JSON.stringify(o.map(d=>({role:d.role,ok:d.ok,costUsd:d.usage.totalCostUsd,model:d.usage.model})),null,2)),{opinions:o,usage:i}}var RP,Tb,TP,Du=x(()=>{"use strict";M();hr();ti();RP="council",Tb=5,TP=3});var Pb={};Ne(Pb,{ROLE_AGENTS_DIR:()=>Bu,materializeRoleAgents:()=>LP,renderRolesBlock:()=>MP});import{mkdirSync as jP,writeFileSync as NP}from"node:fs";import{join as Uu}from"node:path";function OP(t,e){let r=["---",`name: ${t.name}`,`description: ${t.description}`,...t.model?[`model: ${t.model}`]:[],"---",""].join(`
954
+ `,r+1);return{yaml:n,body:o===-1?"":e.slice(o+1)}}function Tb(t,e,r){let n=[],o=[];if(!bP(t))return{roles:n,errors:o};let i;try{i=Ib(t).sort()}catch(s){return{roles:n,errors:[{file:r,error:`cannot read: ${String(s)}`}]}}for(let s of i){if(!s.endsWith(".md"))continue;let a=`${r}/${s}`,c;try{c=kP(Nu(t,s),"utf-8")}catch(d){o.push({file:a,error:`cannot read: ${String(d)}`});continue}let l=EP(c);if(!l){o.push({file:a,error:"missing frontmatter block (--- \u2026 ---) at the top of the file"});continue}let u;try{u=xP(l.yaml)}catch(d){o.push({file:a,error:`frontmatter is not valid YAML: ${String(d)}`});continue}let p=cc({name:s.slice(0,-3),frontmatter:u,body:l.body,origin:e});p.ok?n.push(p.role):o.push({file:a,error:p.error})}return{roles:n,errors:o}}function RP(t){let e=Tb(SP,"bundled","bundled"),r=t?Tb(Nu(t,"roles"),"project","roles"):{roles:[],errors:[]};return{roles:lc(e.roles,r.roles),errors:[...e.errors,...r.errors]}}var SP,Lu=x(()=>{"use strict";M();SP=Cb(vP($P(import.meta.url)))});var Mu={};Ne(Mu,{COUNCIL_DEFAULT_MAX_PARALLEL:()=>AP,COUNCIL_DIR:()=>PP,COUNCIL_MAX_PARALLEL_CEILING:()=>Pb,renderCouncilRolePrompt:()=>_P,renderOpinionsBlock:()=>NP,renderReviewOpinionsBlock:()=>OP,renderReviewRolePrompt:()=>jP,runCouncil:()=>LP});import{existsSync as TP,mkdirSync as IP,writeFileSync as CP}from"node:fs";import{join as Qs}from"node:path";function Ab(t,e){return["## Where to read (read-only)","",...e?["The workspace contains the project repos and the Context Repo clone",`(\`${e}\`; start with \`knowledge/INDEX.md\` and \`adr/\`).`]:["The workspace contains the project repos."],...t.refs.length>0&&e?["Read these first:",...t.refs.map(r=>`- \`${Qs(e,r)}\``)]:[]]}function _P(t,e,r,n){return[`# Council role: ${t.name}`,"",t.body,"","## The questions the pipeline is blocked on","",e,"",...Ab(t,r),"","## Your deliverable","",`Write your opinion to \`${n}\`: for EACH question \u2014 your answer,`,"the strongest argument for it, and what would change your mind. You are","ONE role of a council: argue your perspective sharply, do not average.","You never modify code \u2014 this file is your only output."].join(`
955
+ `)}function jP(t,e,r,n){return[`# Council role: ${t.name}`,"",t.body,"","## The review subject","","Review the change under `code/`: in each repo, the subject is","`git diff refs/worktree/codepipe/review-base..HEAD` \u2014 the base ref is","pinned, do not diff against a branch tip. A repo with an empty diff is","context, not subject. If the ref is MISSING in a repo (the pin can fail),","say so in your opinion and skip that repo \u2014 never substitute another base:","findings against a wrong diff are worse than no findings.","","## The finding contract","","Every finding names file + line, the concrete failing scenario, and stays","within the diff \u2014 or states explicitly how the change broke an untouched","place. A finding without a scenario is an opinion, not a finding.",...e?["",e.trim()]:[],"",...Ab(t,r),"","## Your deliverable","",`Write your findings to \`${n}\` \u2014 your role's independent view,`,"one section per finding. Returning NOTHING is a normal outcome \u2014 do not","manufacture findings to justify your seat. You are ONE role of a council:","stay inside your perspective, do not average.","You never modify code \u2014 this file is your only output."].join(`
956
+ `)}function _b(t){let e=t.filter(n=>n.ok),r=t.filter(n=>!n.ok);return[...e.map(n=>`- \`${n.artifact}\` \u2014 the ${n.role} role`),...r.length>0?["",`Failed roles (no opinion \u2014 weigh accordingly): ${r.map(n=>n.role).join(", ")}.`]:[]]}function NP(t){return["## The council's opinions (already gathered)","","The council's roles have already examined the questions \u2014 each in its own","context, blind to the others. Read every opinion before answering:","",..._b(t),"","Weigh, do not vote: agreement between roles is evidence, not a verdict,","and you may overrule any of them \u2014 say so in the rationale when you do."].join(`
957
+ `)}function OP(t){return["## The council's findings (already gathered)","","The project's critic roles have already reviewed this change \u2014 each in its","own context, blind to the others. Read every file before your own pass:","",..._b(t),"","Then do your own job on what they wrote:","","1. **Deduplicate.** Two roles reporting the same defect is one finding, not two.","2. **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.","3. **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 found nothing is a normal outcome \u2014 do not manufacture findings","to justify the council."].join(`
958
+ `)}async function LP(t){let e=t.baseInput.workspaceDir;IP(Qs(e,t.artifactDir),{recursive:!0});let r=Math.max(1,Math.min(t.maxParallel,Pb)),n=[...t.roles],o=[],i=ut(),s=null,a=new AbortController,c=t.baseInput.signal,l=()=>a.abort();c?.aborted?a.abort():c?.addEventListener("abort",l,{once:!0});let u=async d=>{let f=`${t.artifactDir}/${d.name}.md`,m=t.runnerFor(d.provider),g=t.promptFor(d,f),b=d.model??t.defaultModel;try{let w=await m.run({...t.baseInput,signal:a.signal,role:"council",prompt:g,...b?{model:b}:{},...t.effort?{effort:t.effort}:{}});Xr(i,w.usage),TP(Qs(e,f))?(o.push({role:d.name,ok:!0,artifact:f,usage:w.usage}),t.log(`role ${d.name}: done ($${w.usage.totalCostUsd.toFixed(2)})`)):(o.push({role:d.name,ok:!1,error:`exited ok but wrote no ${f}`,usage:w.usage}),t.log(`role ${d.name}: exited ok but wrote no ${f}`))}catch(w){let v=w instanceof Me?w.details.usage:w instanceof It?w.usage:void 0;v&&Xr(i,v),w instanceof Me&&w.details.rateLimited&&!s&&(s=w,a.abort());let y=w instanceof Error?w.message:String(w);o.push({role:d.name,ok:!1,error:y,usage:v??ut()}),t.log(`role ${d.name}: failed \u2014 ${y}`)}},p=Array.from({length:Math.min(r,n.length)},async()=>{for(;n.length>0&&!a.signal.aborted;){let d=n.shift();if(!d)break;await u(d)}});try{await Promise.all(p)}finally{c?.removeEventListener("abort",l)}if(s){let d=s,f=d.details.usage?.model;throw d.details.usage={...i,...f!==void 0?{model:f}:{}},d}return CP(Qs(e,t.artifactDir,"usage.json"),JSON.stringify(o.map(d=>({role:d.role,ok:d.ok,costUsd:d.usage.totalCostUsd,model:d.usage.model})),null,2)),{opinions:o,usage:i}}var PP,Pb,AP,Du=x(()=>{"use strict";M();gr();ri();PP="council",Pb=5,AP=3});var jb={};Ne(jb,{ROLE_AGENTS_DIR:()=>Bu,materializeRoleAgents:()=>BP,renderRolesBlock:()=>FP});import{mkdirSync as MP,writeFileSync as DP}from"node:fs";import{join as Uu}from"node:path";function UP(t,e){let r=["---",`name: ${t.name}`,`description: ${t.description}`,...t.model?[`model: ${t.model}`]:[],"---",""].join(`
965
959
  `),n=t.refs.length>0&&e?["","## Read these first","",...t.refs.map(o=>`- \`${Uu(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(`
966
960
  `):"";return`${r}${t.body}
967
- ${n}`}function LP(t,e,r,n){let o=uc(e,r);if(o.length===0)return{roles:[],files:[]};let i=Uu(t,Bu);jP(i,{recursive:!0});let s=[];for(let a of o)NP(Uu(i,`${a.name}.md`),OP(a,n)),s.push(`${Bu}/${a.name}.md`);return{roles:o,files:s}}function MP(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(`
961
+ ${n}`}function BP(t,e,r,n){let o=uc(e,r);if(o.length===0)return{roles:[],files:[]};let i=Uu(t,Bu);MP(i,{recursive:!0});let s=[];for(let a of o)DP(Uu(i,`${a.name}.md`),UP(a,n)),s.push(`${Bu}/${a.name}.md`);return{roles:o,files:s}}function FP(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(`
968
962
  `),"","Delegate to **every** role above \u2014 **in parallel**, all Task calls in one","turn. Give each role the SAME briefing (DEV-651 \u2014 the panel's quality is","the briefing's quality, not the coordinator's mood):","","- the review subject: `git diff refs/worktree/codepipe/review-base..HEAD`"," in each repo under `code/` \u2014 the base ref is pinned, do not diff against"," a branch tip;","- the finding contract: every finding names file + line, the concrete"," failing scenario, and stays within the diff \u2014 or states explicitly how"," the change broke an untouched place;","- established facts the role must not re-derive (the BUILD verdict when"," your prompt carries one).","","The roles are independent read-only views that never wait on each other,","so the panel costs the time of its slowest member, not the sum. Then do","your own job on what comes back:","",`1. Save each role's findings verbatim as \`${e}/<role>.md\`.`,"2. **Deduplicate.** Two roles reporting the same defect is one finding, not two.","3. **Filter.** A finding earns a round-trip only if it is a real defect, a"," regression or a convention the project actually enforces. Taste-level notes"," go in the summary, never in the remarks.","4. **Decide.** The verdict is yours, not a vote: a role can be wrong, and you"," are the one who read the code. When you overrule a role, say why in the"," summary.","","A role that returns nothing is a normal outcome \u2014 do not manufacture findings","to justify the panel.",""].join(`
969
- `)}var Bu,Ab=x(()=>{"use strict";M();Bu=".claude/agents"});var jb={};Ne(jb,{COUNCIL_ANSWER_PATH:()=>_b,readCouncilVerdict:()=>BP});import{readFileSync as DP}from"node:fs";import{join as UP}from"node:path";function BP(t){let e;try{e=DP(UP(t,_b),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var _b,Nb=x(()=>{"use strict";_b="meta/council-answer.json"});var Lb={};Ne(Lb,{QUEUE_PLAN_PATH:()=>Ob,readQueuePlan:()=>KP});import{readFileSync as FP}from"node:fs";import{join as GP}from"node:path";function KP(t){let e;try{e=FP(GP(t,Ob),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var Ob,Mb=x(()=>{"use strict";Ob="meta/queue-plan.json"});import{mkdirSync as Fu,readFileSync as ea,readdirSync as HP,rmSync as WP,writeFileSync as Gu}from"node:fs";import{homedir as qP}from"node:os";import{dirname as Db,join as yt}from"node:path";function VP(t){let e=Buffer.from(t,"utf-8");if(e.length<=ta)return t;let r=Math.floor(ta/4),n=ta-r,o=e.subarray(0,r).toString("utf-8"),i=e.subarray(e.length-n).toString("utf-8"),s=e.length-r-n;return`${o}
963
+ `)}var Bu,Nb=x(()=>{"use strict";M();Bu=".claude/agents"});var Lb={};Ne(Lb,{COUNCIL_ANSWER_PATH:()=>Ob,readCouncilVerdict:()=>HP});import{readFileSync as GP}from"node:fs";import{join as KP}from"node:path";function HP(t){let e;try{e=GP(KP(t,Ob),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var Ob,Mb=x(()=>{"use strict";Ob="meta/council-answer.json"});var Ub={};Ne(Ub,{QUEUE_PLAN_PATH:()=>Db,readQueuePlan:()=>YP});import{readFileSync as WP}from"node:fs";import{join as qP}from"node:path";function YP(t){let e;try{e=WP(qP(t,Db),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var Db,Bb=x(()=>{"use strict";Db="meta/queue-plan.json"});import{mkdirSync as Fu,readFileSync as ea,readdirSync as VP,rmSync as zP,writeFileSync as Gu}from"node:fs";import{homedir as XP}from"node:os";import{dirname as Fb,join as yt}from"node:path";function ZP(t){let e=Buffer.from(t,"utf-8");if(e.length<=ta)return t;let r=Math.floor(ta/4),n=ta-r,o=e.subarray(0,r).toString("utf-8"),i=e.subarray(e.length-n).toString("utf-8"),s=e.length-r-n;return`${o}
970
964
 
971
965
  \u2026 [${s} bytes elided \u2014 log capped at ${ta} bytes for upload] \u2026
972
966
 
973
- ${i}`}function zP(){let t=[],e=!1,r=null,n=i=>{if(r){let s=r;r=null,s({value:i,done:!1})}else t.push(i)},o=()=>{if(r){let i=r;r=null,i({value:void 0,done:!0})}};return{push(i){e||n(i)},finalize(){e||(n({kind:"finalize"}),e=!0)},close(){e=!0,t.length=0,o()},iterable:{[Symbol.asyncIterator](){return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):e?Promise.resolve({value:void 0,done:!0}):new Promise(i=>{r=i})}}}}}}async function si(t={}){let e=Ge(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,n=e.sandboxId,o=e.llm,i=Oy(t.profile,e.sandboxId,!!ee("SANDBOX_CONFIG")),s=yt(qP(),".codepipe","logs"),a=Oi("SANDBOX_LOG",i,s);if(a.enabled){let j=new Rn(a);Li(j),console.log(`[log] file logging \u2192 ${j.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${et} (protocol ${kt})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=zy(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=mu();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let u=new Wn(e.hubUrl,e.token),p=!1,d=new AbortController,f=new Map,m=null,g=null,b=!1,w=()=>{let j=u.openControlSocket();return m=j,j.on("open",()=>{console.log("[ws] connected");let h={type:"sandbox_hello",platformVersion:et,protocolVersion:kt};j.send(JSON.stringify(h))}),j.on("message",h=>{let F=h.toString("utf-8"),L=null;try{let z=JSON.parse(F);z&&typeof z=="object"&&(L=z)}catch{}if(L&&L.type==="hello"){let z=L;g=mo(z.protocolVersion);let te=g?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${z.platformVersion} (protocol ${z.protocolVersion}) \u2014 ${te}`),g&&(b=!1);return}if(L&&L.type==="pause_job"){let z=typeof L.jobId=="string"?L.jobId:"",te=z?f.get(z):void 0;te?(console.warn(`[ws] pause_job ${z} \u2014 aborting agent`),te.paused=!0,te.abort.abort()):console.log(`[ws] pause_job ${z} \u2014 not a running job, ignoring`),z&&j.send(JSON.stringify({type:"job_paused",jobId:z}));return}if(L&&(L.type==="chat_user_message"||L.type==="chat_finalize")){let z=typeof L.jobId=="string"?L.jobId:"",te=z?f.get(z):void 0;if(te?.chatInbox)if(L.type==="chat_user_message"){let ae=typeof L.text=="string"?L.text:"";ae.trim()&&te.chatInbox.push({kind:"user",text:ae})}else te.chatInbox.finalize();else console.log(`[ws] ${String(L.type)} ${z} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${F}`)}),j.on("close",(h,F)=>{console.log(`[ws] closed code=${h} reason=${F?.toString()||""}`),m===j&&(m=null),!p&&setTimeout(w,2e3)}),j.on("error",h=>console.warn(`[ws] error: ${h.message}`)),j},v=w(),y=async j=>{for(;!p;){if(g===!1){b||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${et}, protocol ${kt}) \u2014 not claiming jobs until versions align.`),b=!0),await new Promise(h=>setTimeout(h,5e3));continue}try{let h=await u.claim(d.signal,j);if(h.status===204)continue;if(h.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(!h.ok){console.warn(`[claim:${j}] ${h.status} \u2014 backoff 5s`),await new Promise(L=>setTimeout(L,5e3));continue}let F=await h.json();await k(u,F)}catch(h){if(d.signal.aborted)break;let F=h instanceof Error?h.message:String(h);console.warn(`[claim:${j}] error: ${F} \u2014 backoff 5s`),await new Promise(L=>setTimeout(L,5e3))}}};async function k(j,h){let F={abort:new AbortController,paused:!1};Ha(h.role)&&(F.chatInbox=zP()),f.set(h.jobId,F);let L=!1,z=null,te=null,ae=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),Ut=async()=>{try{await j.heartbeat(h.jobId)==="claim_lost"&&(L=!0,console.warn(`[job] ${h.jobId} claim lost \u2014 HUB sweeper took it`))}catch(R){let S=R instanceof Error?R.message:String(R);console.warn(`[job] ${h.jobId} heartbeat error: ${S}`)}};Ut();let We=setInterval(()=>{Ut()},ae),Ue=new Date().toISOString();console.log(`[job] ${h.jobId} claimed \u2014 role=${h.role} task=${h.taskId} phase=${h.phase}`),console.log(`[job] ${h.jobId} prompt (${h.prompt.length} chars):`),console.log(E(h.prompt," \u2502 "));let Ae=[],Be=null,Te=400,st=25,Bt=500,Ft=()=>{if(Be&&(clearTimeout(Be),Be=null),Ae.length===0)return;let R=Ae.splice(0,Ae.length),S=m;if(!S||S.readyState!==S.OPEN)return;let I={type:"agent_activity",jobId:h.jobId,taskId:h.taskId,projectId:h.projectId,role:h.role,phase:h.phase,events:R};try{S.send(JSON.stringify(I))}catch{}},U=R=>{Ae.push(R),Ae.length>Bt&&Ae.shift(),Ae.length>=st?Ft():Be||(Be=setTimeout(Ft,Te))},G=h.role==="analysis"&&h.taskId.startsWith("draft::")?h.taskId.slice(7):null,D=new Set,T=null;try{if(!c){L||await j.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:Ue,finishedAt:new Date().toISOString()});return}if(!fu(o,h.provider??null)){L||await j.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${h.provider??"claude"}"`},startedAt:Ue,finishedAt:new Date().toISOString()});return}let R=Gw(h.jobId);console.log(`[job] ${h.jobId} workspace=${R.dir}`);let S=C(h,r);z=S.gitCreds,te=S.contextGitCreds;let I=z?.env,J=S.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:S.claudeOauthToken}:void 0,q=[],re=null,ya=null;try{let _=h.role==="build"?"clone":"worktree";q=await Iw(R.dir,h.projectId,h.projectRepos,_,I,n);let O=await Cw(R.dir,h.projectId,h.contextRepo,"worktree",I,n);ya=O,re=O?.workspacePath??null}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${h.jobId} materialize failed: ${O}`),L||await j.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${O}`},startedAt:Ue,finishedAt:new Date().toISOString()}),R.dispose();return}let en=h.model,uo=h.effort;h.role==="build"&&h.modelDiscovery&&!_w(re)&&(en=h.modelDiscovery,uo=h.effortDiscovery,console.log(`[job] ${h.jobId} BUILD discovery (no steps in ${Eu}) \u2014 model=${en}`));let gd=async()=>{if(!h.deliveries||h.deliveries.length===0)return[];let _=h.contextRepo?.cloneUrl;if(!_||!I)throw new Error(_?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let O=[];for(let K of h.deliveries){let W=q.find(Z=>Z.name===K.name);if(W){if(h.role==="implement"&&K.baseSha&&K.baseSha!==W.baseSha){let Z=await $w(W,K.deliveryRef,K.deliverySha,K.baseSha,_,I);console.log(`[job] ${h.jobId} ${W.name}: base moved ${K.baseSha.slice(0,10)} \u2192 ${W.baseSha.slice(0,10)} \u2014 re-applied delivery ${K.deliverySha.slice(0,10)} (${Z.length} conflicted file(s))`),Z.length>0&&O.push(`- **${W.name}**:`,...Z.map(pe=>` - \`${pe}\``));continue}await vw(W,K.deliveryRef,K.deliverySha,_,I),console.log(`[job] ${h.jobId} ${W.name}: checked out delivery ${K.deliverySha.slice(0,10)} for ${h.role}`)}}return O},wa=[];if(h.role==="build"||h.role==="implement"||h.role==="code-review")try{wa=await gd()}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${h.jobId} delivery checkout failed: ${O}`),L||await j.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${O}`},startedAt:Ue,finishedAt:new Date().toISOString()}),R.dispose();return}if(h.role==="code-review"){let _=h.metadata?.externalReview===!0;for(let O of q)try{if(_){let K=h.projectRepos.find(Z=>Z.name===O.name)?.defaultBranch??O.ref,W=await Ew(O,K,I);W?console.log(`[job] ${h.jobId} ${O.name}: review base ${W.slice(0,10)} (merge-base with ${K})`):console.warn(`[job] ${h.jobId} ${O.name}: no merge-base with ${K} \u2014 review base not pinned (agent falls back to manual deepen)`)}else await Su(O,O.baseSha,I),console.log(`[job] ${h.jobId} ${O.name}: review base ${O.baseSha.slice(0,10)} (pre-delivery)`)}catch(K){let W=K instanceof Error?K.message:String(K);console.warn(`[job] ${h.jobId} ${O.name}: review-base pin failed: ${W}`)}}let ba=h.role==="resolve-conflict"?h.metadata?.mergeBranchByRepo??h.metadata?.taskBranchByRepo??{}:{},yd="";if(h.role==="resolve-conflict"){if(!q.some(_=>ba[_.name])){let _="resolve-conflict job carries no branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${h.jobId} ${_}`),L||await j.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:_},startedAt:Ue,finishedAt:new Date().toISOString()}),R.dispose();return}try{let _=[];for(let O of q){let K=ba[O.name];if(!K)continue;let W=await xu(O,K,I);console.log(`[job] ${h.jobId} ${O.name}: merged ${K} into ${O.ref} \u2014 ${W.length} conflicted file(s)`),W.length>0?_.push(`- **${O.name}**:`,...W.map(Z=>` - \`${Z}\``)):_.push(`- **${O.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}yd=`
967
+ ${i}`}function QP(){let t=[],e=!1,r=null,n=i=>{if(r){let s=r;r=null,s({value:i,done:!1})}else t.push(i)},o=()=>{if(r){let i=r;r=null,i({value:void 0,done:!0})}};return{push(i){e||n(i)},finalize(){e||(n({kind:"finalize"}),e=!0)},close(){e=!0,t.length=0,o()},iterable:{[Symbol.asyncIterator](){return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):e?Promise.resolve({value:void 0,done:!0}):new Promise(i=>{r=i})}}}}}}async function ai(t={}){let e=Ge(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,n=e.sandboxId,o=e.llm,i=Dy(t.profile,e.sandboxId,!!ee("SANDBOX_CONFIG")),s=yt(XP(),".codepipe","logs"),a=Oi("SANDBOX_LOG",i,s);if(a.enabled){let j=new Tn(a);Li(j),console.log(`[log] file logging \u2192 ${j.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${et} (protocol ${kt})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=Zy(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=mu();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let u=new qn(e.hubUrl,e.token),p=!1,d=new AbortController,f=new Map,m=null,g=null,b=!1,w=()=>{let j=u.openControlSocket();return m=j,j.on("open",()=>{console.log("[ws] connected");let h={type:"sandbox_hello",platformVersion:et,protocolVersion:kt};j.send(JSON.stringify(h))}),j.on("message",h=>{let F=h.toString("utf-8"),L=null;try{let z=JSON.parse(F);z&&typeof z=="object"&&(L=z)}catch{}if(L&&L.type==="hello"){let z=L;g=ho(z.protocolVersion);let te=g?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${z.platformVersion} (protocol ${z.protocolVersion}) \u2014 ${te}`),g&&(b=!1);return}if(L&&L.type==="pause_job"){let z=typeof L.jobId=="string"?L.jobId:"",te=z?f.get(z):void 0;te?(console.warn(`[ws] pause_job ${z} \u2014 aborting agent`),te.paused=!0,te.abort.abort()):console.log(`[ws] pause_job ${z} \u2014 not a running job, ignoring`),z&&j.send(JSON.stringify({type:"job_paused",jobId:z}));return}if(L&&(L.type==="chat_user_message"||L.type==="chat_finalize")){let z=typeof L.jobId=="string"?L.jobId:"",te=z?f.get(z):void 0;if(te?.chatInbox)if(L.type==="chat_user_message"){let ae=typeof L.text=="string"?L.text:"";ae.trim()&&te.chatInbox.push({kind:"user",text:ae})}else te.chatInbox.finalize();else console.log(`[ws] ${String(L.type)} ${z} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${F}`)}),j.on("close",(h,F)=>{console.log(`[ws] closed code=${h} reason=${F?.toString()||""}`),m===j&&(m=null),!p&&setTimeout(w,2e3)}),j.on("error",h=>console.warn(`[ws] error: ${h.message}`)),j},v=w(),y=async j=>{for(;!p;){if(g===!1){b||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${et}, protocol ${kt}) \u2014 not claiming jobs until versions align.`),b=!0),await new Promise(h=>setTimeout(h,5e3));continue}try{let h=await u.claim(d.signal,j);if(h.status===204)continue;if(h.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(!h.ok){console.warn(`[claim:${j}] ${h.status} \u2014 backoff 5s`),await new Promise(L=>setTimeout(L,5e3));continue}let F=await h.json();await k(u,F)}catch(h){if(d.signal.aborted)break;let F=h instanceof Error?h.message:String(h);console.warn(`[claim:${j}] error: ${F} \u2014 backoff 5s`),await new Promise(L=>setTimeout(L,5e3))}}};async function k(j,h){let F={abort:new AbortController,paused:!1};Ha(h.role)&&(F.chatInbox=QP()),f.set(h.jobId,F);let L=!1,z=null,te=null,ae=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),Ut=async()=>{try{await j.heartbeat(h.jobId)==="claim_lost"&&(L=!0,console.warn(`[job] ${h.jobId} claim lost \u2014 HUB sweeper took it`))}catch(R){let S=R instanceof Error?R.message:String(R);console.warn(`[job] ${h.jobId} heartbeat error: ${S}`)}};Ut();let We=setInterval(()=>{Ut()},ae),Ue=new Date().toISOString();console.log(`[job] ${h.jobId} claimed \u2014 role=${h.role} task=${h.taskId} phase=${h.phase}`),console.log(`[job] ${h.jobId} prompt (${h.prompt.length} chars):`),console.log(E(h.prompt," \u2502 "));let Ae=[],Be=null,Te=400,st=25,Bt=500,Ft=()=>{if(Be&&(clearTimeout(Be),Be=null),Ae.length===0)return;let R=Ae.splice(0,Ae.length),S=m;if(!S||S.readyState!==S.OPEN)return;let I={type:"agent_activity",jobId:h.jobId,taskId:h.taskId,projectId:h.projectId,role:h.role,phase:h.phase,events:R};try{S.send(JSON.stringify(I))}catch{}},U=R=>{Ae.push(R),Ae.length>Bt&&Ae.shift(),Ae.length>=st?Ft():Be||(Be=setTimeout(Ft,Te))},G=h.role==="analysis"&&h.taskId.startsWith("draft::")?h.taskId.slice(7):null,D=new Set,T=null;try{if(!c){L||await j.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:Ue,finishedAt:new Date().toISOString()});return}if(!fu(o,h.provider??null)){L||await j.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${h.provider??"claude"}"`},startedAt:Ue,finishedAt:new Date().toISOString()});return}let R=Ww(h.jobId);console.log(`[job] ${h.jobId} workspace=${R.dir}`);let S=C(h,r);z=S.gitCreds,te=S.contextGitCreds;let I=z?.env,J=S.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:S.claudeOauthToken}:void 0,q=[],re=null,ya=null;try{let _=h.role==="build"?"clone":"worktree";q=await Aw(R.dir,h.projectId,h.projectRepos,_,I,n);let O=await _w(R.dir,h.projectId,h.contextRepo,"worktree",I,n);ya=O,re=O?.workspacePath??null}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${h.jobId} materialize failed: ${O}`),L||await j.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${O}`},startedAt:Ue,finishedAt:new Date().toISOString()}),R.dispose();return}let tn=h.model,po=h.effort;h.role==="build"&&h.modelDiscovery&&!Ow(re)&&(tn=h.modelDiscovery,po=h.effortDiscovery,console.log(`[job] ${h.jobId} BUILD discovery (no steps in ${Eu}) \u2014 model=${tn}`));let gd=async()=>{if(!h.deliveries||h.deliveries.length===0)return[];let _=h.contextRepo?.cloneUrl;if(!_||!I)throw new Error(_?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let O=[];for(let K of h.deliveries){let W=q.find(Z=>Z.name===K.name);if(W){if(h.role==="implement"&&K.baseSha&&K.baseSha!==W.baseSha){let Z=await Ew(W,K.deliveryRef,K.deliverySha,K.baseSha,_,I);console.log(`[job] ${h.jobId} ${W.name}: base moved ${K.baseSha.slice(0,10)} \u2192 ${W.baseSha.slice(0,10)} \u2014 re-applied delivery ${K.deliverySha.slice(0,10)} (${Z.length} conflicted file(s))`),Z.length>0&&O.push(`- **${W.name}**:`,...Z.map(pe=>` - \`${pe}\``));continue}await Sw(W,K.deliveryRef,K.deliverySha,_,I),console.log(`[job] ${h.jobId} ${W.name}: checked out delivery ${K.deliverySha.slice(0,10)} for ${h.role}`)}}return O},wa=[];if(h.role==="build"||h.role==="implement"||h.role==="code-review")try{wa=await gd()}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${h.jobId} delivery checkout failed: ${O}`),L||await j.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${O}`},startedAt:Ue,finishedAt:new Date().toISOString()}),R.dispose();return}if(h.role==="code-review"){let _=h.metadata?.externalReview===!0;for(let O of q)try{if(_){let K=h.projectRepos.find(Z=>Z.name===O.name)?.defaultBranch??O.ref,W=await Iw(O,K,I);W?console.log(`[job] ${h.jobId} ${O.name}: review base ${W.slice(0,10)} (merge-base with ${K})`):console.warn(`[job] ${h.jobId} ${O.name}: no merge-base with ${K} \u2014 review base not pinned (agent falls back to manual deepen)`)}else await Su(O,O.baseSha,I),console.log(`[job] ${h.jobId} ${O.name}: review base ${O.baseSha.slice(0,10)} (pre-delivery)`)}catch(K){let W=K instanceof Error?K.message:String(K);console.warn(`[job] ${h.jobId} ${O.name}: review-base pin failed: ${W}`)}}let ba=h.role==="resolve-conflict"?h.metadata?.mergeBranchByRepo??h.metadata?.taskBranchByRepo??{}:{},yd="";if(h.role==="resolve-conflict"){if(!q.some(_=>ba[_.name])){let _="resolve-conflict job carries no branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${h.jobId} ${_}`),L||await j.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:_},startedAt:Ue,finishedAt:new Date().toISOString()}),R.dispose();return}try{let _=[];for(let O of q){let K=ba[O.name];if(!K)continue;let W=await xu(O,K,I);console.log(`[job] ${h.jobId} ${O.name}: merged ${K} into ${O.ref} \u2014 ${W.length} conflicted file(s)`),W.length>0?_.push(`- **${O.name}**:`,...W.map(Z=>` - \`${Z}\``)):_.push(`- **${O.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}yd=`
974
968
 
975
969
  ## Conflicts to resolve
976
970
 
977
971
  `+(_.length>0?_.join(`
978
972
  `):"(no task branches to merge)")+`
979
- `}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${h.jobId} conflict merge failed: ${O}`),L||await j.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${O}`},startedAt:Ue,finishedAt:new Date().toISOString()}),R.dispose();return}}let ka=null,wd="";if(h.contextPack&&re)try{let{assembleContextPack:_}=await Promise.resolve().then(()=>(fb(),pb)),O=_({contextDir:re,taskKey:String(h.metadata?.trackerIssueKey??h.taskId.split(":")[1]??""),title:String(h.metadata?.taskTitle??""),repoDirs:new Map(q.map(K=>[K.name,K.workspacePath])),idfPenalty:h.contextPackIdf!==!1});O?(Fu(yt(R.dir,"meta"),{recursive:!0}),Gu(yt(R.dir,"meta","context-pack.md"),O.markdown),ka=O.markdown,wd=O.top??"",console.log(`[job] ${h.jobId} context pack: ${O.markdown.length} chars \u2192 meta/context-pack.md`)):console.log(`[job] ${h.jobId} context pack: model empty or no signal \u2014 skipped`)}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${h.jobId} context pack failed (non-fatal): ${O}`)}let bd="",Er=null,po=null;try{let{loadSkills:_,materializeSkills:O,renderSkillsBlock:K}=await Promise.resolve().then(()=>(wb(),yb)),W=h.skills??{bundled:!0,context:!0,repo:!0},Z=_({contextDir:re,repoDirs:q.map(at=>at.workspacePath),sources:W});for(let at of Z.errors)console.warn(`[job] ${h.jobId} skill ${at.source}: ${at.error}`);let pe=O(R.dir,Z.skills),oe=["implement","rework","testing"].includes(h.role)?yc(gc(A(re,h.taskId))):[];bd=K(Z.skills,oe),pe.length>0&&console.log(`[job] ${h.jobId} skills: ${Z.skills.map(at=>at.name).join(", ")}`);let{parseMarketplaces:ge,enabledPluginsSetting:rn}=await Promise.resolve().then(()=>(M(),Pc)),{sources:nn,errors:fo}=ge(W.marketplaces??[]);for(let at of fo)console.warn(`[job] ${h.jobId} marketplace ${at}`);if(nn.length>0&&(W.plugins??[]).length>0){let{seedMarketplaces:at}=await Promise.resolve().then(()=>(xb(),$b)),on=await at(nn);for(let Y of on.errors)console.warn(`[job] ${h.jobId} marketplace ${Y.repo}: ${Y.error}`);let{enabled:sn,unknown:an}=rn(W.plugins??[],on.ready);for(let Y of an)console.warn(`[job] ${h.jobId} plugin ${Y}: no such marketplace in this project`);on.dir&&Object.keys(sn).length>0&&(Er=on.dir,po={enabledPlugins:sn},console.log(`[job] ${h.jobId} plugins: ${Object.keys(sn).join(", ")}`))}}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${h.jobId} skills unavailable (non-fatal): ${O}`)}let kd="",qe=null,vd=h.role==="council"&&Array.isArray(h.metadata?.questions)?h.metadata.questions.filter(_=>typeof _=="string"&&_.trim().length>0):[],Nv=h.metadata?.reviewVerify===!0||h.metadata?.externalReviewVerify===!0;if((h.role==="council"||h.role==="code-review")&&h.council&&!Nv)try{let{loadRoles:_}=await Promise.resolve().then(()=>(Lu(),Ou)),{rolesForScenario:O}=await Promise.resolve().then(()=>(M(),Pc)),K=await Promise.resolve().then(()=>(Du(),Mu)),W=_(re);for(let Z of W.errors)console.warn(`[job] ${h.jobId} role ${Z.file}: ${Z.error}`);if(h.role==="council"&&vd.length>0){let Z=O(W.roles,"council");if(Z.length>=2){let pe=vd.map((oe,ge)=>`${ge+1}. ${oe}`).join(`
980
- `);qe={roles:Z,artifactDir:"council",promptFor:(oe,ge)=>K.renderCouncilRolePrompt(oe,pe,re,ge),opinionsBlock:K.renderOpinionsBlock,onAllFailed:"fail",verdictFile:"meta/council-answer.json"}}}else if(h.role==="code-review"){let Z=O(W.roles,"code_review");if(Z.length>=2){let pe=typeof h.metadata?.buildReportBlock=="string"?h.metadata.buildReportBlock:"";qe={roles:Z,artifactDir:"code-review",promptFor:(oe,ge)=>K.renderReviewRolePrompt(oe,pe,re,ge),opinionsBlock:K.renderReviewOpinionsBlock,onAllFailed:"solo",verdictFile:"meta/review-result.json"}}}qe&&console.log(`[job] ${h.jobId} council convened (${qe.artifactDir}): ${qe.roles.map(Z=>Z.name).join(", ")}`)}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${h.jobId} council roles unavailable (non-fatal, solo): ${O}`)}if((h.role==="council"||h.role==="code-review")&&!qe)console.log(`[job] ${h.jobId} ${h.role}: solo session (no council convened)`);else if(["analyze","testing"].includes(h.role))try{let{loadRoles:_}=await Promise.resolve().then(()=>(Lu(),Ou)),{materializeRoleAgents:O,renderRolesBlock:K}=await Promise.resolve().then(()=>(Ab(),Pb)),W=_(re);for(let ge of W.errors)console.warn(`[job] ${h.jobId} role ${ge.file}: ${ge.error}`);let Z=h.role==="analyze"?"plan_review":"code_review",pe=h.role==="analyze"?"plan-review":"testing",oe=O(R.dir,W.roles,Z,re);kd=K(oe,pe),console.log(`[job] ${h.jobId} review roles: ${oe.roles.length>0?oe.roles.map(ge=>ge.name).join(", "):"(no roles)"}`)}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${h.jobId} review roles unavailable (non-fatal): ${O}`)}let Ov=wa.length>0?`
973
+ `}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${h.jobId} conflict merge failed: ${O}`),L||await j.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${O}`},startedAt:Ue,finishedAt:new Date().toISOString()}),R.dispose();return}}let ka=null,wd="";if(h.contextPack&&re)try{let{assembleContextPack:_}=await Promise.resolve().then(()=>(gb(),hb)),O=_({contextDir:re,taskKey:String(h.metadata?.trackerIssueKey??h.taskId.split(":")[1]??""),title:String(h.metadata?.taskTitle??""),repoDirs:new Map(q.map(K=>[K.name,K.workspacePath])),idfPenalty:h.contextPackIdf!==!1});O?(Fu(yt(R.dir,"meta"),{recursive:!0}),Gu(yt(R.dir,"meta","context-pack.md"),O.markdown),ka=O.markdown,wd=O.top??"",console.log(`[job] ${h.jobId} context pack: ${O.markdown.length} chars \u2192 meta/context-pack.md`)):console.log(`[job] ${h.jobId} context pack: model empty or no signal \u2014 skipped`)}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${h.jobId} context pack failed (non-fatal): ${O}`)}let bd="",Rr=null,fo=null;try{let{loadSkills:_,materializeSkills:O,renderSkillsBlock:K}=await Promise.resolve().then(()=>(vb(),kb)),W=h.skills??{bundled:!0,context:!0,repo:!0},Z=_({contextDir:re,repoDirs:q.map(at=>at.workspacePath),sources:W});for(let at of Z.errors)console.warn(`[job] ${h.jobId} skill ${at.source}: ${at.error}`);let pe=O(R.dir,Z.skills),oe=["implement","rework","testing"].includes(h.role)?yc(gc(A(re,h.taskId))):[];bd=K(Z.skills,oe),pe.length>0&&console.log(`[job] ${h.jobId} skills: ${Z.skills.map(at=>at.name).join(", ")}`);let{parseMarketplaces:ge,enabledPluginsSetting:nn}=await Promise.resolve().then(()=>(M(),Pc)),{sources:on,errors:mo}=ge(W.marketplaces??[]);for(let at of mo)console.warn(`[job] ${h.jobId} marketplace ${at}`);if(on.length>0&&(W.plugins??[]).length>0){let{seedMarketplaces:at}=await Promise.resolve().then(()=>(Rb(),Eb)),sn=await at(on);for(let Y of sn.errors)console.warn(`[job] ${h.jobId} marketplace ${Y.repo}: ${Y.error}`);let{enabled:an,unknown:cn}=nn(W.plugins??[],sn.ready);for(let Y of cn)console.warn(`[job] ${h.jobId} plugin ${Y}: no such marketplace in this project`);sn.dir&&Object.keys(an).length>0&&(Rr=sn.dir,fo={enabledPlugins:an},console.log(`[job] ${h.jobId} plugins: ${Object.keys(an).join(", ")}`))}}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${h.jobId} skills unavailable (non-fatal): ${O}`)}let kd="",qe=null,vd=h.role==="council"&&Array.isArray(h.metadata?.questions)?h.metadata.questions.filter(_=>typeof _=="string"&&_.trim().length>0):[],Mv=h.metadata?.reviewVerify===!0||h.metadata?.externalReviewVerify===!0;if((h.role==="council"||h.role==="code-review")&&h.council&&!Mv)try{let{loadRoles:_}=await Promise.resolve().then(()=>(Lu(),Ou)),{rolesForScenario:O}=await Promise.resolve().then(()=>(M(),Pc)),K=await Promise.resolve().then(()=>(Du(),Mu)),W=_(re);for(let Z of W.errors)console.warn(`[job] ${h.jobId} role ${Z.file}: ${Z.error}`);if(h.role==="council"&&vd.length>0){let Z=O(W.roles,"council");if(Z.length>=2){let pe=vd.map((oe,ge)=>`${ge+1}. ${oe}`).join(`
974
+ `);qe={roles:Z,artifactDir:"council",promptFor:(oe,ge)=>K.renderCouncilRolePrompt(oe,pe,re,ge),opinionsBlock:K.renderOpinionsBlock,onAllFailed:"fail",verdictFile:"meta/council-answer.json"}}}else if(h.role==="code-review"){let Z=O(W.roles,"code_review");if(Z.length>=2){let pe=typeof h.metadata?.buildReportBlock=="string"?h.metadata.buildReportBlock:"";qe={roles:Z,artifactDir:"code-review",promptFor:(oe,ge)=>K.renderReviewRolePrompt(oe,pe,re,ge),opinionsBlock:K.renderReviewOpinionsBlock,onAllFailed:"solo",verdictFile:"meta/review-result.json"}}}qe&&console.log(`[job] ${h.jobId} council convened (${qe.artifactDir}): ${qe.roles.map(Z=>Z.name).join(", ")}`)}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${h.jobId} council roles unavailable (non-fatal, solo): ${O}`)}if((h.role==="council"||h.role==="code-review")&&!qe)console.log(`[job] ${h.jobId} ${h.role}: solo session (no council convened)`);else if(["analyze","testing"].includes(h.role))try{let{loadRoles:_}=await Promise.resolve().then(()=>(Lu(),Ou)),{materializeRoleAgents:O,renderRolesBlock:K}=await Promise.resolve().then(()=>(Nb(),jb)),W=_(re);for(let ge of W.errors)console.warn(`[job] ${h.jobId} role ${ge.file}: ${ge.error}`);let Z=h.role==="analyze"?"plan_review":"code_review",pe=h.role==="analyze"?"plan-review":"testing",oe=O(R.dir,W.roles,Z,re);kd=K(oe,pe),console.log(`[job] ${h.jobId} review roles: ${oe.roles.length>0?oe.roles.map(ge=>ge.name).join(", "):"(no roles)"}`)}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${h.jobId} review roles unavailable (non-fatal): ${O}`)}let Dv=wa.length>0?`
981
975
 
982
976
  ## Base branch moved \u2014 conflicts to resolve
983
977
 
@@ -985,73 +979,73 @@ The base branch advanced since the previous iteration; its delivery was re-appli
985
979
 
986
980
  `+wa.join(`
987
981
  `)+`
988
- `:"",$d=N($(h.prompt,q,re).replace(/\{\{contextPackTop\}\}/g,()=>wd),re,h.taskId).replace(/\{\{skillsBlock\}\}/g,bd)+yd+Ov,wi=$d.replace(/\{\{rolesBlock\}\}/g,()=>kd),tn=[...q.map(_=>_.workspacePath),...re?[re]:[]];if(tn.length>0&&console.log(`[job] ${h.jobId} --add-dir: ${tn.join(", ")}`),wu("agent-request")){let _=Gs(qn(h.metadata??{})),O=bu(h.projectId,h.jobId,"agent-request",[`# Agent request \u2014 job ${h.jobId}`,"",`- project: ${h.projectId}`,`- task: ${h.taskId}`,`- role: ${h.role}`,`- model: ${en??"(backend default)"}`,`- effort: ${uo??"(backend default)"}`,`- add-dirs:${tn.length>0?"":" (none)"}`,...tn.map(K=>` - ${K}`),"","## Append-system-prompt (language directive)","","```",_,"```","","## Prompt","",wi,"",...ka?["## Context pack (meta/context-pack.md)","",ka]:["## Context pack","","(not generated for this job)"],""].join(`
989
- `));O&&console.log(`[debug] ${h.jobId} agent request \u2192 ${O}`)}G&&(T=setInterval(()=>{let O=m;if(!O||O.readyState!==O.OPEN)return;let K;try{K=HP(yt(R.dir,"drafts")).filter(W=>W.endsWith(".json")).sort()}catch{return}for(let W of K){if(D.has(W))continue;if(D.size>=Cc)break;let Z;try{let oe=JSON.parse(ea(yt(R.dir,"drafts",W),"utf-8")),ge=typeof oe.localRef=="string"?oe.localRef:"",rn=typeof oe.title=="string"?oe.title:"",nn=typeof oe.body=="string"?oe.body:"";if(!ge||!rn)continue;Z={localRef:ge,title:rn,body:nn,...oe.isEpic===!0?{isEpic:!0}:{},...Array.isArray(oe.links)?{links:oe.links}:{}}}catch{continue}D.add(W);let pe={type:"child_draft",jobId:h.jobId,projectId:h.projectId,draftId:G,child:Z};try{O.send(JSON.stringify(pe))}catch{}}},1500));let Rr=null,xd=new Map;try{if(qe){let{runCouncil:Y,COUNCIL_DEFAULT_MAX_PARALLEL:de}=await Promise.resolve().then(()=>(Du(),Mu)),_e=await Y({roles:qe.roles,artifactDir:qe.artifactDir,promptFor:qe.promptFor,maxParallel:h.council?.maxParallel??de,defaultModel:en,effort:uo,baseInput:{workspaceDir:R.dir,addDirs:tn,metadata:h.metadata??{},...J||Er?{env:{...J??{},...Er?{CLAUDE_CODE_PLUGIN_SEED_DIR:Er}:{}}}:{},...po?{settings:po}:{},signal:F.abort.signal,onActivity:U},runnerFor:fe=>(fe&&!fu(o,fe)&&console.warn(`[job] ${h.jobId} council role provider "${fe}" not served by backend "${o}" \u2014 using the default backend`),c),log:fe=>console.log(`[job] ${h.jobId} council ${fe}`)});Rr=_e.usage;let Zt=_e.opinions.some(fe=>fe.ok);if(!Zt&&qe.onAllFailed==="fail")throw new Error(`council: every role failed \u2014 ${_e.opinions.map(fe=>`${fe.role}: ${fe.error??"?"}`).join("; ")}`);if(Zt){wi=$d.replace(/\{\{rolesBlock\}\}/g,()=>qe.opinionsBlock(_e.opinions));for(let fe of R.listFiles().filter(ct=>ct.startsWith(`${qe.artifactDir}/`)))xd.set(fe,R.readFile(fe))}else console.warn(`[job] ${h.jobId} council produced no opinions \u2014 proceeding solo (${_e.opinions.map(fe=>`${fe.role}: ${fe.error??"?"}`).join("; ")})`);if(WP(yt(R.dir,qe.verdictFile),{force:!0}),wu("agent-request")){let fe=bu(h.projectId,h.jobId,"agent-request-synthesis",wi);fe&&console.log(`[debug] ${h.jobId} council synthesis request \u2192 ${fe}`)}}let _={workspaceDir:R.dir,role:h.role,prompt:wi,addDirs:tn,metadata:h.metadata??{},...en?{model:en}:{},...uo?{effort:uo}:{},...J||Er?{env:{...J??{},...Er?{CLAUDE_CODE_PLUGIN_SEED_DIR:Er}:{}}}:{},...po?{settings:po}:{},signal:F.abort.signal,onActivity:U},O=F.chatInbox?await c.run({..._,interactive:{inbox:F.chatInbox.iterable}}):await gu(c,_,{jobId:h.jobId,policy:l,onBeforeRetry:async()=>{R.clean();for(let[Y,de]of xd){let _e=yt(R.dir,Y);Fu(Db(_e),{recursive:!0}),Gu(_e,de)}for(let Y of q)try{await gw(Y);let de=ba[Y.name];h.role==="resolve-conflict"&&de&&await xu(Y,de,I)}catch(de){let _e=de instanceof Error?de.message:String(de);console.warn(`[job] ${h.jobId} worktree reset failed (${Y.name}): ${_e}`)}try{await gd()}catch(Y){let de=Y instanceof Error?Y.message:String(Y);console.warn(`[job] ${h.jobId} delivery re-checkout failed: ${de}`)}},aborted:()=>L||F.paused});if(Rr){let{addUsageInto:Y}=await Promise.resolve().then(()=>(ti(),yu));Y(O.usage,Rr)}let K=[];if(YP.has(h.role)&&q.length>0){let Y=h.metadata??{},de=typeof Y.commitMessage=="string"?Y.commitMessage:`${h.taskId}: changes`,_e=h.contextRepo?.cloneUrl,Zt=te?.env;if(!_e||!Zt)throw new Error("delivery requested but "+(_e?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let fe=h.taskId.includes(":")?h.taskId.slice(h.taskId.indexOf(":")+1):h.taskId;for(let ct of q){let cn=await yw(ct,de);if(!cn){console.log(`[job] ${h.jobId} ${ct.name}: no changes \u2014 no delivery`);continue}let va=`codepipe/deliveries/${fe}/${h.jobId}/${ct.name}`;await ww(ct,cn,va,_e,Zt);let Lv=await kw(ct,cn);K.push({name:ct.name,deliveryRef:va,deliverySha:cn,baseSha:ct.baseSha,changedFiles:Lv}),console.log(`[job] ${h.jobId} ${ct.name}: delivered ${cn.slice(0,10)} \u2192 ${va}`);let Sd=await bw(ct,cn);if(Sd.trim().length>0){let Mv=yt("display",`${ct.name}.diff`),Ed=yt(R.dir,Mv);Fu(Db(Ed),{recursive:!0}),Gu(Ed,Sd)}}}if(h.role==="resolve-conflict"&&K.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 W;h.role==="build"&&(W=Nw(R.dir),console.log(`[job] ${h.jobId} build verdict: ok=${W.ok}`+(W.failedStep?` failedStep=${W.failedStep}`:"")));let Z;if(h.role==="code-review"){Z=Tu(R.dir),console.log(`[job] ${h.jobId} review verdict: approved=${Z.approved}`);try{let{parseChangedRanges:Y,markFindingScope:de}=await Promise.resolve().then(()=>(Iu(),Lw)),_e=new Map;for(let Zt of q)try{let fe=await Sw(Zt,I);_e.set(Zt.name,Y(fe))}catch{}de(Z,_e,q.length===1?q[0].name:void 0)}catch(Y){console.warn(`[job] ${h.jobId} finding scope marking failed (non-fatal): ${String(Y)}`)}}let pe;if(h.role==="council"){let{readCouncilVerdict:Y}=await Promise.resolve().then(()=>(Nb(),jb));pe=Y(R.dir)??void 0,console.log(`[job] ${h.jobId} council: ${pe?"answered":"no verdict \u2014 task stops for a human"}`)}let oe;if(h.role==="testing"){try{let Y=ea(yt(R.dir,"meta","test-result.json"),"utf-8");oe=JSON.parse(Y)}catch{oe=void 0}console.log(`[job] ${h.jobId} test verdict: ${oe?"written":"none \u2014 proceeding to the PR"}`)}let ge;if(h.role==="observer"){let{readQueuePlan:Y}=await Promise.resolve().then(()=>(Mb(),Lb));ge=Y(R.dir)??void 0,console.log(`[job] ${h.jobId} queue plan: ${ge?"produced":"none \u2014 batch keeps the staged order"}`)}let rn=O.artifactPaths.length>0?O.artifactPaths:R.listFiles(),nn=Array.from(new Set(rn)),fo;if(ya)try{let Y=h.role==="index"?["adr/SOURCES.md"]:h.role==="backfill"?["adr"]:[],de=await Pw(ya,Y);de.length>0&&(fo=de,console.log(`[job] ${h.jobId} captured ${de.length} knowledge file(s) for Context Repo`))}catch(Y){let de=Y instanceof Error?Y.message:String(Y);console.warn(`[job] ${h.jobId} knowledge capture failed (non-fatal): ${de}`)}let{artifacts:at,omitted:on,dropped:sn}=Dw(R.dir,nn);for(let Y of on)console.warn(`[job] ${h.jobId} artifact ${Y.path} (${Y.bytes} bytes) exceeded upload budget \u2014 content omitted`);sn.length>0&&console.warn(`[job] ${h.jobId} artifact listing truncated: ${sn.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let an={jobId:h.jobId,status:"succeeded",artifacts:at,...fo?{contextWrites:fo}:{},...K.length>0?{deliveries:K}:{},log:VP(O.log),startedAt:Ue,finishedAt:new Date().toISOString(),usage:O.usage,...O.rateLimit?{rateLimit:O.rateLimit}:{},...W?{build:W}:{},...Z?{review:Z}:{},...ge!==void 0?{queuePlan:ge}:{},...pe!==void 0?{council:pe}:{},...oe!==void 0?{test:oe}:{}};if(L||F.paused)console.warn(`[job] ${h.jobId} skipping result upload \u2014 ${F.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await j.submitResult(an),console.log(`[job] ${h.jobId} done \u2014 uploaded ${an.artifacts.length} artifact(s):`);for(let Y of an.artifacts){let de=Buffer.from(Y.contentBase64,"base64").length;console.log(` \xB7 ${Y.path} (${de} bytes)`)}an.artifacts.length===0&&console.warn(`[job] ${h.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(_){let O=_ instanceof Error?_.message:String(_);if(F.paused)console.log(`[job] ${h.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(L)console.warn(`[job] ${h.jobId} failed after claim lost (${O}) \u2014 skipping result upload`);else{let K=hu(_),W=_ instanceof wr,Z=_ instanceof Lt,pe=_ instanceof Me?_.details.rateLimited:void 0;if(Rr&&_ instanceof Me)if(_.details.usage){let{addUsageInto:ge}=await Promise.resolve().then(()=>(ti(),yu));ge(_.details.usage,Rr)}else _.details.usage=Rr;let oe=(_ instanceof Me?_.details.usage:void 0)??Rr??void 0;console.warn(pe?`[job] ${h.jobId} rate-limited (${pe.kind??"unknown window"}`+(pe.resetAtMs?`, resets ${new Date(pe.resetAtMs).toISOString()}`:"")+") \u2014 HUB will hold and auto-resume":K?`[job] ${h.jobId} failed: ${O} (Claude auth \u2014 token invalid/expired)`:W?`[job] ${h.jobId} failed: ${O} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:Z?`[job] ${h.jobId} failed: ${O} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${h.jobId} failed: ${O}`),await j.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:O},startedAt:Ue,finishedAt:new Date().toISOString(),...K?{authError:!0}:{},...W?{buildInconclusive:!0}:{},...Z?{reviewInconclusive:!0}:{},...pe?{rateLimited:pe}:{},...oe?{usage:oe}:{}})}}finally{R.dispose()}}finally{clearInterval(We),T&&clearInterval(T),Ft(),F.chatInbox?.close(),f.delete(h.jobId),z?.cleanup(),te?.cleanup()}}function C(j,h){if(!j.credBundle)return{gitCreds:null,contextGitCreds:null};if(!h)return console.warn(`[job] ${j.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let F;try{F=JSON.parse(Dn(h,j.credBundle).toString("utf-8"))}catch(ae){return console.warn(`[job] ${j.jobId} failed to open credBundle: ${ae instanceof Error?ae.message:String(ae)}`),{gitCreds:null,contextGitCreds:null}}let L=vu(F);L&&console.log(`[job] ${j.jobId} cred bundle opened \u2014 git creds configured`);let z=lw(F,j.contextRepo.cloneUrl),te={gitCreds:L,contextGitCreds:z};return F.claudeOauthToken&&(te.claudeOauthToken=F.claudeOauthToken),te}function E(j,h){return j.split(`
982
+ `:"",$d=N($(h.prompt,q,re).replace(/\{\{contextPackTop\}\}/g,()=>wd),re,h.taskId).replace(/\{\{skillsBlock\}\}/g,bd)+yd+Dv,bi=$d.replace(/\{\{rolesBlock\}\}/g,()=>kd),rn=[...q.map(_=>_.workspacePath),...re?[re]:[]];if(rn.length>0&&console.log(`[job] ${h.jobId} --add-dir: ${rn.join(", ")}`),wu("agent-request")){let _=Gs(Yn(h.metadata??{})),O=bu(h.projectId,h.jobId,"agent-request",[`# Agent request \u2014 job ${h.jobId}`,"",`- project: ${h.projectId}`,`- task: ${h.taskId}`,`- role: ${h.role}`,`- model: ${tn??"(backend default)"}`,`- effort: ${po??"(backend default)"}`,`- add-dirs:${rn.length>0?"":" (none)"}`,...rn.map(K=>` - ${K}`),"","## Append-system-prompt (language directive)","","```",_,"```","","## Prompt","",bi,"",...ka?["## Context pack (meta/context-pack.md)","",ka]:["## Context pack","","(not generated for this job)"],""].join(`
983
+ `));O&&console.log(`[debug] ${h.jobId} agent request \u2192 ${O}`)}G&&(T=setInterval(()=>{let O=m;if(!O||O.readyState!==O.OPEN)return;let K;try{K=VP(yt(R.dir,"drafts")).filter(W=>W.endsWith(".json")).sort()}catch{return}for(let W of K){if(D.has(W))continue;if(D.size>=Cc)break;let Z;try{let oe=JSON.parse(ea(yt(R.dir,"drafts",W),"utf-8")),ge=typeof oe.localRef=="string"?oe.localRef:"",nn=typeof oe.title=="string"?oe.title:"",on=typeof oe.body=="string"?oe.body:"";if(!ge||!nn)continue;Z={localRef:ge,title:nn,body:on,...oe.isEpic===!0?{isEpic:!0}:{},...Array.isArray(oe.links)?{links:oe.links}:{}}}catch{continue}D.add(W);let pe={type:"child_draft",jobId:h.jobId,projectId:h.projectId,draftId:G,child:Z};try{O.send(JSON.stringify(pe))}catch{}}},1500));let Tr=null,xd=new Map;try{if(qe){let{runCouncil:Y,COUNCIL_DEFAULT_MAX_PARALLEL:de}=await Promise.resolve().then(()=>(Du(),Mu)),_e=await Y({roles:qe.roles,artifactDir:qe.artifactDir,promptFor:qe.promptFor,maxParallel:h.council?.maxParallel??de,defaultModel:tn,effort:po,baseInput:{workspaceDir:R.dir,addDirs:rn,metadata:h.metadata??{},...J||Rr?{env:{...J??{},...Rr?{CLAUDE_CODE_PLUGIN_SEED_DIR:Rr}:{}}}:{},...fo?{settings:fo}:{},signal:F.abort.signal,onActivity:U},runnerFor:fe=>(fe&&!fu(o,fe)&&console.warn(`[job] ${h.jobId} council role provider "${fe}" not served by backend "${o}" \u2014 using the default backend`),c),log:fe=>console.log(`[job] ${h.jobId} council ${fe}`)});Tr=_e.usage;let Qt=_e.opinions.some(fe=>fe.ok);if(!Qt&&qe.onAllFailed==="fail")throw new Error(`council: every role failed \u2014 ${_e.opinions.map(fe=>`${fe.role}: ${fe.error??"?"}`).join("; ")}`);if(Qt){bi=$d.replace(/\{\{rolesBlock\}\}/g,()=>qe.opinionsBlock(_e.opinions));for(let fe of R.listFiles().filter(ct=>ct.startsWith(`${qe.artifactDir}/`)))xd.set(fe,R.readFile(fe))}else console.warn(`[job] ${h.jobId} council produced no opinions \u2014 proceeding solo (${_e.opinions.map(fe=>`${fe.role}: ${fe.error??"?"}`).join("; ")})`);if(zP(yt(R.dir,qe.verdictFile),{force:!0}),wu("agent-request")){let fe=bu(h.projectId,h.jobId,"agent-request-synthesis",bi);fe&&console.log(`[debug] ${h.jobId} council synthesis request \u2192 ${fe}`)}}let _={workspaceDir:R.dir,role:h.role,prompt:bi,addDirs:rn,metadata:h.metadata??{},...tn?{model:tn}:{},...po?{effort:po}:{},...J||Rr?{env:{...J??{},...Rr?{CLAUDE_CODE_PLUGIN_SEED_DIR:Rr}:{}}}:{},...fo?{settings:fo}:{},signal:F.abort.signal,onActivity:U},O=F.chatInbox?await c.run({..._,interactive:{inbox:F.chatInbox.iterable}}):await gu(c,_,{jobId:h.jobId,policy:l,onBeforeRetry:async()=>{R.clean();for(let[Y,de]of xd){let _e=yt(R.dir,Y);Fu(Fb(_e),{recursive:!0}),Gu(_e,de)}for(let Y of q)try{await bw(Y);let de=ba[Y.name];h.role==="resolve-conflict"&&de&&await xu(Y,de,I)}catch(de){let _e=de instanceof Error?de.message:String(de);console.warn(`[job] ${h.jobId} worktree reset failed (${Y.name}): ${_e}`)}try{await gd()}catch(Y){let de=Y instanceof Error?Y.message:String(Y);console.warn(`[job] ${h.jobId} delivery re-checkout failed: ${de}`)}},aborted:()=>L||F.paused});if(Tr){let{addUsageInto:Y}=await Promise.resolve().then(()=>(ri(),yu));Y(O.usage,Tr)}let K=[];if(JP.has(h.role)&&q.length>0){let Y=h.metadata??{},de=typeof Y.commitMessage=="string"?Y.commitMessage:`${h.taskId}: changes`,_e=h.contextRepo?.cloneUrl,Qt=te?.env;if(!_e||!Qt)throw new Error("delivery requested but "+(_e?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let fe=h.taskId.includes(":")?h.taskId.slice(h.taskId.indexOf(":")+1):h.taskId;for(let ct of q){let ln=await kw(ct,de);if(!ln){console.log(`[job] ${h.jobId} ${ct.name}: no changes \u2014 no delivery`);continue}let va=`codepipe/deliveries/${fe}/${h.jobId}/${ct.name}`;await vw(ct,ln,va,_e,Qt);let Uv=await xw(ct,ln);K.push({name:ct.name,deliveryRef:va,deliverySha:ln,baseSha:ct.baseSha,changedFiles:Uv}),console.log(`[job] ${h.jobId} ${ct.name}: delivered ${ln.slice(0,10)} \u2192 ${va}`);let Sd=await $w(ct,ln);if(Sd.trim().length>0){let Bv=yt("display",`${ct.name}.diff`),Ed=yt(R.dir,Bv);Fu(Fb(Ed),{recursive:!0}),Gu(Ed,Sd)}}}if(h.role==="resolve-conflict"&&K.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 W;h.role==="build"&&(W=Mw(R.dir),console.log(`[job] ${h.jobId} build verdict: ok=${W.ok}`+(W.failedStep?` failedStep=${W.failedStep}`:"")));let Z;if(h.role==="code-review"){Z=Tu(R.dir),console.log(`[job] ${h.jobId} review verdict: approved=${Z.approved}`);try{let{parseChangedRanges:Y,markFindingScope:de}=await Promise.resolve().then(()=>(Iu(),Uw)),_e=new Map;for(let Qt of q)try{let fe=await Tw(Qt,I);_e.set(Qt.name,Y(fe))}catch{}de(Z,_e,q.length===1?q[0].name:void 0)}catch(Y){console.warn(`[job] ${h.jobId} finding scope marking failed (non-fatal): ${String(Y)}`)}}let pe;if(h.role==="council"){let{readCouncilVerdict:Y}=await Promise.resolve().then(()=>(Mb(),Lb));pe=Y(R.dir)??void 0,console.log(`[job] ${h.jobId} council: ${pe?"answered":"no verdict \u2014 task stops for a human"}`)}let oe;if(h.role==="testing"){try{let Y=ea(yt(R.dir,"meta","test-result.json"),"utf-8");oe=JSON.parse(Y)}catch{oe=void 0}console.log(`[job] ${h.jobId} test verdict: ${oe?"written":"none \u2014 proceeding to the PR"}`)}let ge;if(h.role==="observer"){let{readQueuePlan:Y}=await Promise.resolve().then(()=>(Bb(),Ub));ge=Y(R.dir)??void 0,console.log(`[job] ${h.jobId} queue plan: ${ge?"produced":"none \u2014 batch keeps the staged order"}`)}let nn=O.artifactPaths.length>0?O.artifactPaths:R.listFiles(),on=Array.from(new Set(nn)),mo;if(ya)try{let Y=h.role==="index"?["adr/SOURCES.md"]:h.role==="backfill"?["adr"]:[],de=await jw(ya,Y);de.length>0&&(mo=de,console.log(`[job] ${h.jobId} captured ${de.length} knowledge file(s) for Context Repo`))}catch(Y){let de=Y instanceof Error?Y.message:String(Y);console.warn(`[job] ${h.jobId} knowledge capture failed (non-fatal): ${de}`)}let{artifacts:at,omitted:sn,dropped:an}=Fw(R.dir,on);for(let Y of sn)console.warn(`[job] ${h.jobId} artifact ${Y.path} (${Y.bytes} bytes) exceeded upload budget \u2014 content omitted`);an.length>0&&console.warn(`[job] ${h.jobId} artifact listing truncated: ${an.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let cn={jobId:h.jobId,status:"succeeded",artifacts:at,...mo?{contextWrites:mo}:{},...K.length>0?{deliveries:K}:{},log:ZP(O.log),startedAt:Ue,finishedAt:new Date().toISOString(),usage:O.usage,...O.rateLimit?{rateLimit:O.rateLimit}:{},...W?{build:W}:{},...Z?{review:Z}:{},...ge!==void 0?{queuePlan:ge}:{},...pe!==void 0?{council:pe}:{},...oe!==void 0?{test:oe}:{}};if(L||F.paused)console.warn(`[job] ${h.jobId} skipping result upload \u2014 ${F.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await j.submitResult(cn),console.log(`[job] ${h.jobId} done \u2014 uploaded ${cn.artifacts.length} artifact(s):`);for(let Y of cn.artifacts){let de=Buffer.from(Y.contentBase64,"base64").length;console.log(` \xB7 ${Y.path} (${de} bytes)`)}cn.artifacts.length===0&&console.warn(`[job] ${h.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(_){let O=_ instanceof Error?_.message:String(_);if(F.paused)console.log(`[job] ${h.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(L)console.warn(`[job] ${h.jobId} failed after claim lost (${O}) \u2014 skipping result upload`);else{let K=hu(_),W=_ instanceof br,Z=_ instanceof Lt,pe=_ instanceof Me?_.details.rateLimited:void 0;if(Tr&&_ instanceof Me)if(_.details.usage){let{addUsageInto:ge}=await Promise.resolve().then(()=>(ri(),yu));ge(_.details.usage,Tr)}else _.details.usage=Tr;let oe=(_ instanceof Me?_.details.usage:void 0)??Tr??void 0;console.warn(pe?`[job] ${h.jobId} rate-limited (${pe.kind??"unknown window"}`+(pe.resetAtMs?`, resets ${new Date(pe.resetAtMs).toISOString()}`:"")+") \u2014 HUB will hold and auto-resume":K?`[job] ${h.jobId} failed: ${O} (Claude auth \u2014 token invalid/expired)`:W?`[job] ${h.jobId} failed: ${O} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:Z?`[job] ${h.jobId} failed: ${O} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${h.jobId} failed: ${O}`),await j.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:O},startedAt:Ue,finishedAt:new Date().toISOString(),...K?{authError:!0}:{},...W?{buildInconclusive:!0}:{},...Z?{reviewInconclusive:!0}:{},...pe?{rateLimited:pe}:{},...oe?{usage:oe}:{}})}}finally{R.dispose()}}finally{clearInterval(We),T&&clearInterval(T),Ft(),F.chatInbox?.close(),f.delete(h.jobId),z?.cleanup(),te?.cleanup()}}function C(j,h){if(!j.credBundle)return{gitCreds:null,contextGitCreds:null};if(!h)return console.warn(`[job] ${j.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let F;try{F=JSON.parse(Un(h,j.credBundle).toString("utf-8"))}catch(ae){return console.warn(`[job] ${j.jobId} failed to open credBundle: ${ae instanceof Error?ae.message:String(ae)}`),{gitCreds:null,contextGitCreds:null}}let L=vu(F);L&&console.log(`[job] ${j.jobId} cred bundle opened \u2014 git creds configured`);let z=pw(F,j.contextRepo.cloneUrl),te={gitCreds:L,contextGitCreds:z};return F.claudeOauthToken&&(te.claudeOauthToken=F.claudeOauthToken),te}function E(j,h){return j.split(`
990
984
  `).map(F=>h+F).join(`
991
- `)}function $(j,h,F){let L=h[0]?.workspacePath??"";return j.replace(/\{\{codeDir\}\}/g,L).replace(/\{\{codeRoot\}\}/g,L?L.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,F??"")}function A(j,h){let F=h.includes("::")?"":h.split(":",2)[1]??"";if(!j||!F)return"";for(let L of["PLAN.md","SOLUTION.md"])try{return ea(yt(j,"tasks",F,L),"utf-8")}catch{}return""}function N(j,h,F){let L=j,z=F.includes("::")?"":F.split(":",2)[1]??"",te=ae=>{if(!h||!z)return"";try{return ea(yt(h,"tasks",z,ae),"utf-8").trim()}catch{return""}};if(L.includes("{{planMd}}")||L.includes("{{solutionMd}}")){let ae=te("PLAN.md")||te("SOLUTION.md")||"(PLAN.md missing \u2014 proceed from the task description)";L=L.replace(/\{\{planMd\}\}/g,()=>ae),L=L.replace(/\{\{solutionMd\}\}/g,()=>ae)}if(L.includes("{{taskDescription}}")){let ae=te("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";L=L.replace(/\{\{taskDescription\}\}/g,()=>ae)}return L=Ww(L,h),L}let B=j=>{if(p)return;p=!0,console.log(`
992
- [${j}] shutting down`),d.abort();let h=[...f.keys()];for(let z of f.values())z.abort.abort();let F=new AbortController,L=setTimeout(()=>F.abort(),3e3);(async()=>(await Promise.all(h.map(async z=>{try{await u.releaseJob(z,`sandbox ${j}`,F.signal),console.log(`[${j}] released job ${z}`)}catch(te){let ae=te instanceof Error?te.message:String(te);console.warn(`[${j}] release failed: ${ae} (sweeper will reclaim)`)}})),clearTimeout(L),v.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>B("SIGINT")),process.on("SIGTERM",()=>B("SIGTERM"));let H=[y("implementation")];e.planningLane!==!1?H.push(y("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(H)}var ta,YP,Ub=x(()=>{"use strict";M();gt();Oc();Xy();Ks();ti();hr();nw();Ye();Fs();uw();su();Aw();jw();Ow();Iu();Uw();Hw();Yw();ta=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),YP=new Set(["implement","resolve-conflict"])});var Zn=x(()=>{"use strict";My();Ub();Fs()});import{cancel as XP,isCancel as Fb,log as ot,password as JP,text as ZP}from"@clack/prompts";function QP(t){return Fb(t)&&(XP("aborted"),process.exit(1)),typeof t=="string"?t:""}function Gb(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function eA(t){let e=Yc({redirectUri:qc,challenge:t.challenge,state:t.state});ot.message(`Open this URL, approve the access, and paste the code shown:
993
- ${e}`);let r=await ZP({message:"Authorization code \u2014 blank to skip"});if(Fb(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=tm(r,t.state);return await Vc({code:n,verifier:t.verifier,state:t.state,redirectUri:qc})}catch(n){return ot.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function tA(t){if(jc()?.claude?.oauthToken&&!t.farm)return ot.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;ot.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=Fi(),n;try{n=await rm({...r,openUrl:Ur,log:i=>ot.message(i)})}catch(i){ot.warn(`Browser sign-in didn't complete (${i instanceof Error?i.message:String(i)}) \u2014 trying the code-paste fallback.`);let s=await eA(r);if(s===null)return null;n=s}let o=await Vt(n.oauthToken);return o==="invalid"?(ot.warn("Claude rejected the obtained token (401) \u2014 falling back to manual entry."),null):(ot.success(`Claude: logged in \u2014 ${Gb(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function Kb(t){ot.message(`Claude \u2014 the pipeline's agents run on your Claude subscription.
985
+ `)}function $(j,h,F){let L=h[0]?.workspacePath??"";return j.replace(/\{\{codeDir\}\}/g,L).replace(/\{\{codeRoot\}\}/g,L?L.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,F??"")}function A(j,h){let F=h.includes("::")?"":h.split(":",2)[1]??"";if(!j||!F)return"";for(let L of["PLAN.md","SOLUTION.md"])try{return ea(yt(j,"tasks",F,L),"utf-8")}catch{}return""}function N(j,h,F){let L=j,z=F.includes("::")?"":F.split(":",2)[1]??"",te=ae=>{if(!h||!z)return"";try{return ea(yt(h,"tasks",z,ae),"utf-8").trim()}catch{return""}};if(L.includes("{{planMd}}")||L.includes("{{solutionMd}}")){let ae=te("PLAN.md")||te("SOLUTION.md")||"(PLAN.md missing \u2014 proceed from the task description)";L=L.replace(/\{\{planMd\}\}/g,()=>ae),L=L.replace(/\{\{solutionMd\}\}/g,()=>ae)}if(L.includes("{{taskDescription}}")){let ae=te("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";L=L.replace(/\{\{taskDescription\}\}/g,()=>ae)}return L=Vw(L,h),L}let B=j=>{if(p)return;p=!0,console.log(`
986
+ [${j}] shutting down`),d.abort();let h=[...f.keys()];for(let z of f.values())z.abort.abort();let F=new AbortController,L=setTimeout(()=>F.abort(),3e3);(async()=>(await Promise.all(h.map(async z=>{try{await u.releaseJob(z,`sandbox ${j}`,F.signal),console.log(`[${j}] released job ${z}`)}catch(te){let ae=te instanceof Error?te.message:String(te);console.warn(`[${j}] release failed: ${ae} (sweeper will reclaim)`)}})),clearTimeout(L),v.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>B("SIGINT")),process.on("SIGTERM",()=>B("SIGTERM"));let H=[y("implementation")];e.planningLane!==!1?H.push(y("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(H)}var ta,JP,Gb=x(()=>{"use strict";M();gt();Oc();Qy();Ks();ri();gr();sw();Ye();Fs();fw();su();Nw();Lw();Dw();Iu();Gw();Yw();Xw();ta=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),JP=new Set(["implement","resolve-conflict"])});var Qn=x(()=>{"use strict";By();Gb();Fs()});import{cancel as eA,isCancel as Hb,log as ot,password as tA,text as rA}from"@clack/prompts";function nA(t){return Hb(t)&&(eA("aborted"),process.exit(1)),typeof t=="string"?t:""}function Wb(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function oA(t){let e=Yc({redirectUri:qc,challenge:t.challenge,state:t.state});ot.message(`Open this URL, approve the access, and paste the code shown:
987
+ ${e}`);let r=await rA({message:"Authorization code \u2014 blank to skip"});if(Hb(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=om(r,t.state);return await Vc({code:n,verifier:t.verifier,state:t.state,redirectUri:qc})}catch(n){return ot.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function iA(t){if(jc()?.claude?.oauthToken&&!t.farm)return ot.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;ot.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=Fi(),n;try{n=await im({...r,openUrl:Br,log:i=>ot.message(i)})}catch(i){ot.warn(`Browser sign-in didn't complete (${i instanceof Error?i.message:String(i)}) \u2014 trying the code-paste fallback.`);let s=await oA(r);if(s===null)return null;n=s}let o=await zt(n.oauthToken);return o==="invalid"?(ot.warn("Claude rejected the obtained token (401) \u2014 falling back to manual entry."),null):(ot.success(`Claude: logged in \u2014 ${Wb(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function qb(t){ot.message(`Claude \u2014 the pipeline's agents run on your Claude subscription.
994
988
  In another terminal:
995
989
  1. install Claude Code \u2014 https://claude.com/claude-code
996
990
  2. run \`claude setup-token\`
997
991
  3. paste the token it prints (starts with sk-ant-) below`+(t.farm?`
998
- Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=QP(await JP({message:"Claude OAuth token \u2014 blank to skip"})).trim();if(!e)return ot.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-")||ot.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 Vt(e);return r==="invalid"?(ot.warn("Claude refused this token. Run `claude setup-token` again and paste the new one."),Kb(t)):(ot.success(`Claude: ${Gb(e)} \u2014 ${r==="valid"?"verified":"check inconclusive, saved"}.`),e)}var Hb,Wb=x(()=>{"use strict";Gi();In();me();Xc();Hb={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:tA,promptManual:Kb,validate:Vt}});function qb(t){return Hb}async function Yb(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var Vb=x(()=>{"use strict";Wb()});async function Qn(t,e,r){return e.host==="github"?nA(t,e,r):e.host==="gitlab"?lA(t,e,r):dA(t,e,r)}async function zb(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 it(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Xb(e.githubToken,t):o}:{found:"unknown",detail:"no GitHub token \u2014 existence not checked"};if(t.host==="gitlab"){if(!e.gitlabToken)return{found:"unknown",detail:"no GitLab token \u2014 existence not checked"};let s=encodeURIComponent(`${t.owner}/${t.name}`);return(await Je(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Jb(e.gitlabToken,t):o}}return e.bitbucket?(await Mt(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Zb(e.bitbucket,t):o}:{found:"unknown",detail:"no Bitbucket credentials \u2014 existence not checked"}}catch(i){return{found:"unknown",detail:i instanceof Error?i.message:String(i)}}}async function Xb(t,e){let r=!1;try{r=(await it(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 Jb(t,e){let r=!1;try{r=(await Je(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 Zb(t,e){let r=!1;try{r=(await Mt(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 it(t,e,r,n){let o={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};n!==void 0&&(o.body=JSON.stringify(n),o.headers["Content-Type"]="application/json");let i=await fetch(rA+r,o),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?a.message:s;throw new Error(`GitHub ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function nA(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 oA(n,e,r),i=await iA(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=Nn(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await sA(n,o.owner,o.name,a.path,i)||await aA(n,o.owner,o.name,a.path,a.content,`chore(codepipe): scaffold ${a.path}`,i);return{host:"github",owner:o.owner,name:o.name,cloneUrl:o.sshUrl,branch:i}}async function oA(t,e,r){let n=await it(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 Xb(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Ku(t,e.owner),i=o?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${o?"org":"user"})`);let s=await it(t,"POST",i,{name:e.name,private:!0,auto_init:!0,description:`CodePipe Context Repo for project ${e.name}`});if(!s.data)throw new Error("GitHub createRepo: empty response");return{owner:s.data.owner.login,name:s.data.name,sshUrl:s.data.ssh_url}}async function Ku(t,e){let{status:r,data:n}=await it(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function iA(t,e,r){let{data:n}=await it(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function sA(t,e,r,n,o){let{status:i,data:s}=await it(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function aA(t,e,r,n,o,i,s,a){let c={message:i,content:Buffer.from(o,"utf-8").toString("base64"),branch:s};a&&(c.sha=a),await it(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Je(t,e,r,n){let o={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...n!==void 0?{"Content-Type":"application/json"}:{}}};n!==void 0&&(o.body=JSON.stringify(n));let i=await fetch(cA+r,o),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?JSON.stringify(a.message):s;throw new Error(`GitLab ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function lA(t,e,r){let n=r.gitlabToken;if(!n)throw new Error("GitLab PAT required to provision a gitlab-hosted Context Repo \u2014 set GITLAB_TOKEN or provide it during `codepipe init`");let o=encodeURIComponent(`${e.owner}/${e.name}`),i,s=await Je(n,"GET",`/projects/${o}`);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await Jb(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await Je(n,"GET","/user"),d={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(p.data?.username!==e.owner){let m=await Je(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(m.status===404||!m.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);d.namespace_id=m.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let f=await Je(n,"POST","/projects",d);if(!f.data)throw new Error("GitLab create project: empty response");i=f.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Nn(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let f=(await Je(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let m of f)l.add(m.path);if(f.length<100)break}let u=c.filter(p=>!l.has(p.path)).map(p=>({action:"create",file_path:p.path,content:p.content}));return u.length>0?await Je(n,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:u}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}async function Mt(t,e,r,n){let o={method:e,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${t.apiToken}`).toString("base64"),"User-Agent":"codepipe-cli"}};n?.json!==void 0?(o.body=JSON.stringify(n.json),o.headers["Content-Type"]="application/json"):n?.form&&(o.body=n.form);let i=await fetch(uA+r,o),s=await i.text(),a=null;try{a=s?JSON.parse(s):null}catch{}if(i.status>=400&&i.status!==404)throw new Error(`Bitbucket ${e} ${r} \u2192 ${i.status} ${s}`);return{status:i.status,data:a}}async function dA(t,e,r){let n=r.bitbucket;if(!n)throw new Error("Bitbucket account email + API token required to provision a bitbucket-hosted Context Repo \u2014 provide them during `codepipe init`");let o=`/repositories/${e.owner}/${encodeURIComponent(e.name)}`,i,s=await Mt(n,"GET",o);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await Zb(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 Mt(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(p.status===404||!p.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);i=p.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Nn(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await Mt(n,"GET",`${o}/src/${encodeURIComponent(a)}/${p.path}?format=meta`)).status===404&&l.push(p);if(l.length>0){let p=new URLSearchParams;p.set("message","chore(codepipe): scaffold context repo files"),p.set("branch",a);for(let f of l)p.set(f.path,f.content);if((await Mt(n,"POST",`${o}/src`,{form:p})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let u=i.links?.clone?.find(p=>p.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:u??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var rA,cA,uA,ai=x(()=>{"use strict";Br();rA="https://api.github.com";cA="https://gitlab.com/api/v4";uA="https://api.bitbucket.org/2.0"});function Ze(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=pA[r];if(!o)return null;let i=n.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(i.length<2)return null;let s=i[i.length-1].replace(/\.git$/,"");return s?{host:o,owner:i.slice(0,-1).join("/"),repoName:s}:null}var pA,ra=x(()=>{"use strict";pA={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as fA}from"node:crypto";import{existsSync as Qb,mkdirSync as mA,readFileSync as ek,readdirSync as hA,rmSync as na,writeFileSync as gA}from"node:fs";import{homedir as yA}from"node:os";import{dirname as wA,join as Hu}from"node:path";function tk(){return Hu(yA(),".codepipe","init-drafts")}function Wu(t){let e=fA("sha256").update(t).digest("hex").slice(0,16);return Hu(tk(),`${e}.json`)}function rk(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=bA)}function nk(t){let e=Wu(t);if(!Qb(e))return null;try{let r=JSON.parse(ek(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:rk(r.savedAt)?(na(e,{force:!0}),null):r}catch{return null}}function qu(t){na(Wu(t),{force:!0})}function ok(){let t=tk();if(Qb(t))for(let e of hA(t)){let r=Hu(t,e);try{let n=JSON.parse(ek(r,"utf-8"));rk(n.savedAt)&&na(r,{force:!0})}catch{na(r,{force:!0})}}}var bA,eo,ik=x(()=>{"use strict";bA=24*60*60*1e3;eo=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(){qu(this.cwd)}persist(){let e=Wu(this.cwd);mA(wA(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};gA(e,JSON.stringify(r,null,2)+`
999
- `,{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 ak(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 ck=x(()=>{"use strict"});import{existsSync as kA}from"node:fs";import{join as vA}from"node:path";import{simpleGit as $A}from"simple-git";function RA(t){let e=t.split("/");return e[e.length-1]??t}function lk(t){if(t.filter(r=>!SA.test(RA(r))).length>xA)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(EA.has(n))return!0}return!1}async function TA(t){try{let r=(await $A(t).raw(["ls-files"])).split(`
1000
- `).map(n=>n.trim()).filter(Boolean);return lk(r)}catch{return!1}}async function IA(t,e){if(t.host!=="github")return!1;let r=e.github?.token;if(!r)return!1;let n=t.defaultBranch??"main";try{let o=await fetch(`https://api.github.com/repos/${t.owner}/${t.repoName}/contents/?ref=${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(o.status!==200)return!1;let i=await o.json();return Array.isArray(i)?lk(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function uk(t,e){for(let r of t)try{let n=e.localRoot!=null?vA(e.localRoot,r.mountAs??r.name):null;if(n&&kA(n)?await TA(n):await IA(r,e.tokens))return!0}catch{}return!1}var xA,SA,EA,dk=x(()=>{"use strict";xA=3,SA=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,EA=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as pk}from"node:fs";import{join as fk}from"node:path";import{simpleGit as mk}from"simple-git";async function li(t,e,r={}){let n=r.log??CA,o=[];for(let i of e){let s=fk(t,i.mountAs),a=zp(i);if(!pk(s)){if(r.dryRun){n.info(`would clone ${a} \u2192 ${i.mountAs}/`),o.push({mountAs:i.mountAs,status:"cloned",detail:"(dry-run)"});continue}try{n.info(`cloning ${a} \u2192 ${i.mountAs}/`),await mk().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let p=ci(u instanceof Error?u.message:String(u));n.warn(`clone failed for ${i.mountAs}: ${p}`),o.push({mountAs:i.mountAs,status:"error",detail:p})}continue}if(!pk(fk(s,".git"))){n.warn(`${i.mountAs}/ exists but is not a git repo \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-not-git"});continue}let c=mk(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!PA(l,a)){n.warn(`${i.mountAs}/ origin (${ci(l)||"none"}) != expected (${ci(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:ci(l)});continue}if(r.dryRun){n.info(`would fetch ${i.mountAs}/`),o.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),o.push({mountAs:i.mountAs,status:"fetched"})}catch(u){let p=ci(u instanceof Error?u.message:String(u));n.warn(`fetch failed for ${i.mountAs}: ${p}`),o.push({mountAs:i.mountAs,status:"error",detail:p})}}return o}function PA(t,e){return hk(t)===hk(e)}function hk(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function ci(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function gk(t={}){let e=je();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 li(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 CA,oa=x(()=>{"use strict";xt();CA={info:t=>console.log(t),warn:t=>console.warn(t)}});import{existsSync as Yu,readFileSync as Vu,writeFileSync as yk}from"node:fs";import{join as zu}from"node:path";import{parseDocument as Xu}from"yaml";function wk(t){let e={};return t.branches.integration&&(e.integration=t.branches.integration),t.branches.stable!==void 0&&(e.stable=t.branches.stable),t.branches.release_pattern!==void 0&&(e.release_pattern=t.branches.release_pattern),{flow:t.flow,branches:e}}function bk(t){let{errors:e}=gn(t);if(e.length>0)throw new Error(`invalid git config: ${e.join("; ")}`)}async function kk(t,e){let r=wk(e);bk(r);let n=zu(t,"project.yaml");if(!Yu(n))throw new Error(`project.yaml not found in context repo (${t})`);let o=Xu(Vu(n,"utf-8"));o.set("git",r),yk(n,o.toString())}async function vk(t,e,r){let n=wk(r);bk(n);let o=zu(t,"project.yaml");if(!Yu(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=Xu(Vu(o,"utf-8"));ns(i,e).set("git",n),yk(o,i.toString())}function $k(t){let e=zu(t,"project.yaml");if(!Yu(e))return null;try{let r=Xu(Vu(e,"utf-8")).toJS();return AA(r?.git)}catch{return null}}function AA(t){if(!t||typeof t!="object")return null;let e=t,r=e.flow;if(r!=="simple"&&r!=="gitflow"&&r!=="release")return null;let n=e.branches;if(!n||typeof n!="object")return null;let o=n,i=o.integration;if(typeof i!="string"||!i)return null;let s={flow:r,branches:{integration:i}};return typeof o.stable=="string"&&(s.branches.stable=o.stable),typeof o.release_pattern=="string"&&(s.branches.release_pattern=o.release_pattern),s}var xk=x(()=>{"use strict";M();os()});import{confirm as _A,isCancel as jA}from"@clack/prompts";async function ia(t){let e=So(t.facts),r=t.confirm??NA,n=t.log??(()=>{}),o=t.readProject??$k,i=t.writeProject??kk,s=t.writeOverride??vk;if(!t.contextDir)return e.flow!=="simple"&&n(`git-flow: detected ${to(e)} (no context repo to persist)`),{outcome:"no-context",detected:e};let a=t.contextDir,c=o(a);return c===null?e.flow==="simple"?(n("git-flow: simple (single branch)"),{outcome:"silent-simple",detected:e}):await r(`Detected git-flow: ${to(e)}. Use it?`)?(await i(a,e),n(`git-flow: ${to(e)} (project default)`),{outcome:"wrote-project",detected:e}):(n("git-flow: keeping simple (detection declined)"),{outcome:"declined",detected:e}):Ec(e,c)?await r(`This repo's git-flow (${to(e)}) differs from the project (${to(c)}). Record a per-repo override?`)?(await s(a,t.repoName,e),n(`git-flow: ${to(e)} (per-repo override for "${t.repoName}")`),{outcome:"wrote-override",detected:e}):(n(`git-flow: using the project flow for "${t.repoName}" (override declined)`),{outcome:"declined",detected:e}):{outcome:"match",detected:e}}function to(t){if(t.flow==="simple")return"simple (single branch)";let e=[`integration=${t.branches.integration}`];return t.branches.stable&&e.push(`stable=${t.branches.stable}`),t.branches.release_pattern&&e.push(`release=${t.branches.release_pattern}`),`${t.flow} (${e.join(", ")})`}async function NA(t){let e=await _A({message:t,initialValue:!0});return jA(e)?!1:e===!0}var Ju=x(()=>{"use strict";M();xk()});import{simpleGit as Sk}from"simple-git";async function ui(t,e){let r=Sk(t),n=null;try{n=(await r.raw(["symbolic-ref","--short","refs/remotes/origin/HEAD"])).trim().replace(/^origin\//,"")||null}catch{}!n&&e&&(n=await OA(e));let o=[];try{o=(await r.raw(["for-each-ref","--format=%(refname:short)","refs/remotes/origin"])).split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).map(s=>s.replace(/^origin\//,"")).filter(s=>s!=="HEAD"&&s!=="origin")}catch{o=[]}return{defaultBranch:n,branches:o}}async function OA(t){try{let e=await Sk().listRemote(["--symref",t,"HEAD"]);return/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m.exec(e)?.[1]??null}catch{return null}}var Zu=x(()=>{"use strict"});import{simpleGit as LA}from"simple-git";async function Ek(t,e,r){return t.host==="github"?MA(t,e,r):t.host==="gitlab"?DA(t,e,r):UA(t,e,r)}function Qu(t){return new Error(`${t.owner}/${t.repoName} exists but is PUBLIC \u2014 a mirror holds the repository's full history and must be private. Make it private (or pick another name) and re-run`)}async function MA(t,e,r){let n=e.githubToken;if(!n)throw new Error("GitHub token required to create a github-hosted mirror");let o=await it(n,"GET",`/repos/${t.owner}/${encodeURIComponent(t.repoName)}`);if(o.status===200&&o.data){if(o.data.private!==!0)throw Qu(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:o.data.ssh_url,created:!1}}let i=(await it(n,"GET","/user")).data?.login??"",s=i.toLowerCase()===t.owner.toLowerCase(),a=!s&&await Ku(n,t.owner);if(!s&&!a)throw new Error(`"${t.owner}" is neither the token's account ("${i}") nor an organization it can see \u2014 nothing was created. Use a GitHub username or organization (not an email)`);r.info(`creating mirror ${t.owner}/${t.repoName} (github, ${a?"org":"user"})`);let c=await it(n,"POST",a?`/orgs/${t.owner}/repos`:"/user/repos",{name:t.repoName,private:!0,auto_init:!1,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"});if(!c.data)throw new Error(`GitHub: could not create ${t.owner}/${t.repoName}`);return{spec:t,sshUrl:c.data.ssh_url,created:!0}}async function Rk(t,e,r){try{return t==="github"?(await it(e,"GET","/user")).data?.login??null:t==="gitlab"?(await Je(e,"GET","/user")).data?.username??null:r?(await Mt({email:r,apiToken:e},"GET","/workspaces?role=contributor&pagelen=1")).data?.values?.[0]?.slug??null:null}catch{return null}}async function DA(t,e,r){let n=e.gitlabToken;if(!n)throw new Error("GitLab PAT required to create a gitlab-hosted mirror");let o=encodeURIComponent(`${t.owner}/${t.repoName}`),i=await Je(n,"GET",`/projects/${o}`);if(i.status===200&&i.data){if(i.data.visibility!=="private")throw Qu(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:i.data.ssh_url_to_repo,created:!1}}let s={name:t.repoName,path:t.repoName,visibility:"private",initialize_with_readme:!1,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"};if((await Je(n,"GET","/user")).data?.username!==t.owner){let l=await Je(n,"GET",`/namespaces/${encodeURIComponent(t.owner)}`);if(l.status===404||!l.data)throw new Error(`GitLab namespace "${t.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);s.namespace_id=l.data.id}r.info(`creating mirror ${t.owner}/${t.repoName} (gitlab)`);let c=await Je(n,"POST","/projects",s);if(!c.data)throw new Error(`GitLab: could not create ${t.owner}/${t.repoName}`);return{spec:t,sshUrl:c.data.ssh_url_to_repo,created:!0}}async function UA(t,e,r){let n=e.bitbucket;if(!n)throw new Error("Bitbucket email + API token required to create a bitbucket-hosted mirror");let o=`/repositories/${t.owner}/${encodeURIComponent(t.repoName)}`,i=`git@bitbucket.org:${t.owner}/${t.repoName}.git`,s=await Mt(n,"GET",o);if(s.status===200&&s.data){if(s.data.is_private!==!0)throw Qu(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:i,created:!1}}r.info(`creating mirror ${t.owner}/${t.repoName} (bitbucket)`);let a=await Mt(n,"POST",o,{json:{scm:"git",is_private:!0,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"}});if(a.status===404||!a.data?.slug)throw new Error(`Bitbucket cannot create ${t.owner}/${t.repoName} \u2014 check the workspace and that the credential may create repositories in it`);return{spec:t,sshUrl:i,created:!0}}async function Tk(t,e,r){let n=LA(t);if((await n.raw(["rev-parse","--is-shallow-repository"])).trim()==="true")throw new Error("this clone is shallow \u2014 the mirror would be seeded with partial history. Run `git fetch --unshallow` first");if((await n.listRemote(["--heads",e])).trim().length>0)return r.info("mirror already has branches \u2014 leaving its content alone"),{seeded:!1};r.info("seeding mirror with the repository's branches and tags\u2026");let i=(await n.raw(["for-each-ref","refs/remotes/origin","--format=%(refname)"])).split(`
1001
- `).map(a=>a.trim()).filter(a=>a.length>0&&a!=="refs/remotes/origin/HEAD");if(i.length===0)throw new Error("the local clone has no origin branches to seed from");let s=i.map(a=>`${a}:refs/heads/${a.slice(20)}`);return await n.push([e,...s]),await n.push([e,"--tags"]),{seeded:!0}}function BA(t,e){let r=e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-");return`${t}-${r}-mirror`.replace(/-{2,}/g,"-").replace(/^[-.]+|[-.]+$/g,"")}function FA(t,e,r){return e.mirror?{host:e.mirror.host,owner:e.mirror.owner,repoName:e.mirror.repoName}:{host:r.host,owner:r.owner,repoName:BA(t,e.repoName)}}function Ik(t,e,r){let n=new Map,o=[];for(let i of e){let s=FA(t,i,r),a=`${s.host}:${s.owner.toLowerCase()}/${s.repoName.toLowerCase()}`,c=n.get(a);if(c)throw new Error(`repositories "${c}" and "${i.name}" both map to the mirror ${s.owner}/${s.repoName} \u2014 mirroring them into one repository would merge their histories. Give one an explicit mirror name (mirror.repo in project.yaml) and re-run`);n.set(a,i.name),o.push({repo:i,spec:s})}return o}var Ck=x(()=>{"use strict";ai()});var Nk={};Ne(Nk,{ensureEmbeddedWorker:()=>aa,spawnWorkerProcess:()=>ca,upCommand:()=>la,workerChildEnv:()=>jk,workerStartArgs:()=>_k});import{spawn as Ak}from"node:child_process";import{existsSync as Pk}from"node:fs";import{homedir as GA,hostname as KA}from"node:os";import{join as sa}from"node:path";async function HA(t,e,r){let n=Ge(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${Tt(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 Cg(t.hubUrl.replace(/\/$/,""),n.token)}catch(i){return console.warn(`[up] could not verify the worker registration (${i instanceof Error?i.message:String(i)}) \u2014 continuing`),!1}if(o==="unsupported")return console.log(`[up] worker already registered as ${n.sandboxId} (${n.name})`),!1;if(o==="ok")return console.log(`[up] worker already registered as ${n.sandboxId} (${n.name})`),!1;if(!r.reregister)throw new Error(`the HUB no longer knows this worker registration (${n.sandboxId}) \u2014 it was removed on ${t.hubUrl}, but ${Tt(e)} still holds its token.
1002
- 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`),df(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function WA(t,e,r){let n=Ge(e)!==null;if(!await HA(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 Rs(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof V&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof V&&i.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):i instanceof V?i:new Error(`cannot reach the HUB at ${t.hubUrl} (${i instanceof Error?i.message:String(i)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await Wr({hub:t.hubUrl,token:o,name:r.name??`${KA()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function qA(t,e){let r=Ge(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=ze(r.sealPublicKey);if(!X(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=ji(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 aa(t,e,r){await WA(t,e,r),qA(t.projectId,e)}function _k(t){return[...t?["--profile",t]:[],"worker","start"]}function jk(t){let e={...t};for(let r of Nc)delete e[r];return e}function ca(t){let e=Ak(process.execPath,[t.entry,..._k(t.profile)],{stdio:["ignore","pipe","pipe"],env:jk(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
1003
- `))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function YA(t,e){let r=process.cwd(),n=sa(r,nt);if(vn(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(Pk(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 se(t.hubUrl,t.cliToken,t.projectId)}catch(u){console.warn(`[up] could not fetch the project summary (${u instanceof Error?u.message:String(u)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await ed(r);if(!Vp(r,i?.parsed??null,o.repos)){console.log(`[up] this folder is neither empty nor a repo of ${t.projectId} \u2014 the context stays under ~/.codepipe/profiles`);return}let s=X(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await Bs({cfg:t,secrets:s,contextDir:n,log:a}).catch(()=>null);if(!c?.contextDir){console.warn("[up] could not clone the Context Repo here \u2014 the context stays under ~/.codepipe/profiles");return}let l=sa(GA(),".codepipe",e?sa("profiles",e,"context-config"):"context-config");if(Wi(c.contextDir,l,a),!Pk(sa(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}:{}};_o(c.contextDir,Nt(u,!0,s?.youtrack?.url)),console.log("[up] local project config seeded with defaults \u2014 review .codepipe/project.yaml")}console.log(`[up] project context materialized \u2192 ${n}`)}async function la(t){let{cfg:e,profile:r}=xn(t.profile);if(t.debug){let f=typeof t.debug=="string"&&t.debug.trim()?t.debug.trim():"agent-request";process.env.CODEPIPE_DEBUG=f,console.log(`[up] debug logging on (${f}) \u2192 ~/.codepipe/debug/${e.projectId}/`)}await YA(e,r),await aa(e,r,t);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(f,m)=>{let g=b=>w=>{for(let v of w.toString("utf-8").split(`
992
+ Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=nA(await tA({message:"Claude OAuth token \u2014 blank to skip"})).trim();if(!e)return ot.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-")||ot.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 zt(e);return r==="invalid"?(ot.warn("Claude refused this token. Run `claude setup-token` again and paste the new one."),qb(t)):(ot.success(`Claude: ${Wb(e)} \u2014 ${r==="valid"?"verified":"check inconclusive, saved"}.`),e)}var Yb,Vb=x(()=>{"use strict";Gi();Cn();me();Xc();Yb={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:iA,promptManual:qb,validate:zt}});function zb(t){return Yb}async function Xb(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var Jb=x(()=>{"use strict";Vb()});async function eo(t,e,r){return e.host==="github"?aA(t,e,r):e.host==="gitlab"?fA(t,e,r):hA(t,e,r)}async function Zb(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 it(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Qb(e.githubToken,t):o}:{found:"unknown",detail:"no GitHub token \u2014 existence not checked"};if(t.host==="gitlab"){if(!e.gitlabToken)return{found:"unknown",detail:"no GitLab token \u2014 existence not checked"};let s=encodeURIComponent(`${t.owner}/${t.name}`);return(await Je(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await ek(e.gitlabToken,t):o}}return e.bitbucket?(await Mt(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await tk(e.bitbucket,t):o}:{found:"unknown",detail:"no Bitbucket credentials \u2014 existence not checked"}}catch(i){return{found:"unknown",detail:i instanceof Error?i.message:String(i)}}}async function Qb(t,e){let r=!1;try{r=(await it(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 ek(t,e){let r=!1;try{r=(await Je(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 tk(t,e){let r=!1;try{r=(await Mt(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 it(t,e,r,n){let o={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};n!==void 0&&(o.body=JSON.stringify(n),o.headers["Content-Type"]="application/json");let i=await fetch(sA+r,o),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?a.message:s;throw new Error(`GitHub ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function aA(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 cA(n,e,r),i=await lA(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=On(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await uA(n,o.owner,o.name,a.path,i)||await dA(n,o.owner,o.name,a.path,a.content,`chore(codepipe): scaffold ${a.path}`,i);return{host:"github",owner:o.owner,name:o.name,cloneUrl:o.sshUrl,branch:i}}async function cA(t,e,r){let n=await it(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 Qb(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Ku(t,e.owner),i=o?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${o?"org":"user"})`);let s=await it(t,"POST",i,{name:e.name,private:!0,auto_init:!0,description:`CodePipe Context Repo for project ${e.name}`});if(!s.data)throw new Error("GitHub createRepo: empty response");return{owner:s.data.owner.login,name:s.data.name,sshUrl:s.data.ssh_url}}async function Ku(t,e){let{status:r,data:n}=await it(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function lA(t,e,r){let{data:n}=await it(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function uA(t,e,r,n,o){let{status:i,data:s}=await it(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function dA(t,e,r,n,o,i,s,a){let c={message:i,content:Buffer.from(o,"utf-8").toString("base64"),branch:s};a&&(c.sha=a),await it(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Je(t,e,r,n){let o={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...n!==void 0?{"Content-Type":"application/json"}:{}}};n!==void 0&&(o.body=JSON.stringify(n));let i=await fetch(pA+r,o),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?JSON.stringify(a.message):s;throw new Error(`GitLab ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function fA(t,e,r){let n=r.gitlabToken;if(!n)throw new Error("GitLab PAT required to provision a gitlab-hosted Context Repo \u2014 set GITLAB_TOKEN or provide it during `codepipe init`");let o=encodeURIComponent(`${e.owner}/${e.name}`),i,s=await Je(n,"GET",`/projects/${o}`);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await ek(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await Je(n,"GET","/user"),d={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(p.data?.username!==e.owner){let m=await Je(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(m.status===404||!m.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);d.namespace_id=m.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let f=await Je(n,"POST","/projects",d);if(!f.data)throw new Error("GitLab create project: empty response");i=f.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=On(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let f=(await Je(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let m of f)l.add(m.path);if(f.length<100)break}let u=c.filter(p=>!l.has(p.path)).map(p=>({action:"create",file_path:p.path,content:p.content}));return u.length>0?await Je(n,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:u}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}async function Mt(t,e,r,n){let o={method:e,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${t.apiToken}`).toString("base64"),"User-Agent":"codepipe-cli"}};n?.json!==void 0?(o.body=JSON.stringify(n.json),o.headers["Content-Type"]="application/json"):n?.form&&(o.body=n.form);let i=await fetch(mA+r,o),s=await i.text(),a=null;try{a=s?JSON.parse(s):null}catch{}if(i.status>=400&&i.status!==404)throw new Error(`Bitbucket ${e} ${r} \u2192 ${i.status} ${s}`);return{status:i.status,data:a}}async function hA(t,e,r){let n=r.bitbucket;if(!n)throw new Error("Bitbucket account email + API token required to provision a bitbucket-hosted Context Repo \u2014 provide them during `codepipe init`");let o=`/repositories/${e.owner}/${encodeURIComponent(e.name)}`,i,s=await Mt(n,"GET",o);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await tk(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 Mt(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(p.status===404||!p.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);i=p.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=On(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await Mt(n,"GET",`${o}/src/${encodeURIComponent(a)}/${p.path}?format=meta`)).status===404&&l.push(p);if(l.length>0){let p=new URLSearchParams;p.set("message","chore(codepipe): scaffold context repo files"),p.set("branch",a);for(let f of l)p.set(f.path,f.content);if((await Mt(n,"POST",`${o}/src`,{form:p})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let u=i.links?.clone?.find(p=>p.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:u??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var sA,pA,mA,ci=x(()=>{"use strict";Fr();sA="https://api.github.com";pA="https://gitlab.com/api/v4";mA="https://api.bitbucket.org/2.0"});function Ze(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=gA[r];if(!o)return null;let i=n.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(i.length<2)return null;let s=i[i.length-1].replace(/\.git$/,"");return s?{host:o,owner:i.slice(0,-1).join("/"),repoName:s}:null}var gA,ra=x(()=>{"use strict";gA={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as yA}from"node:crypto";import{existsSync as rk,mkdirSync as wA,readFileSync as nk,readdirSync as bA,rmSync as na,writeFileSync as kA}from"node:fs";import{homedir as vA}from"node:os";import{dirname as $A,join as Hu}from"node:path";function ok(){return Hu(vA(),".codepipe","init-drafts")}function Wu(t){let e=yA("sha256").update(t).digest("hex").slice(0,16);return Hu(ok(),`${e}.json`)}function ik(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=xA)}function sk(t){let e=Wu(t);if(!rk(e))return null;try{let r=JSON.parse(nk(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:ik(r.savedAt)?(na(e,{force:!0}),null):r}catch{return null}}function qu(t){na(Wu(t),{force:!0})}function ak(){let t=ok();if(rk(t))for(let e of bA(t)){let r=Hu(t,e);try{let n=JSON.parse(nk(r,"utf-8"));ik(n.savedAt)&&na(r,{force:!0})}catch{na(r,{force:!0})}}}var xA,to,ck=x(()=>{"use strict";xA=24*60*60*1e3;to=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(){qu(this.cwd)}persist(){let e=Wu(this.cwd);wA($A(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};kA(e,JSON.stringify(r,null,2)+`
993
+ `,{mode:384})}}});function lk(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 uk(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 dk=x(()=>{"use strict"});import{existsSync as SA}from"node:fs";import{join as EA}from"node:path";import{simpleGit as RA}from"simple-git";function PA(t){let e=t.split("/");return e[e.length-1]??t}function pk(t){if(t.filter(r=>!IA.test(PA(r))).length>TA)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(CA.has(n))return!0}return!1}async function AA(t){try{let r=(await RA(t).raw(["ls-files"])).split(`
994
+ `).map(n=>n.trim()).filter(Boolean);return pk(r)}catch{return!1}}async function _A(t,e){if(t.host!=="github")return!1;let r=e.github?.token;if(!r)return!1;let n=t.defaultBranch??"main";try{let o=await fetch(`https://api.github.com/repos/${t.owner}/${t.repoName}/contents/?ref=${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(o.status!==200)return!1;let i=await o.json();return Array.isArray(i)?pk(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function fk(t,e){for(let r of t)try{let n=e.localRoot!=null?EA(e.localRoot,r.mountAs??r.name):null;if(n&&SA(n)?await AA(n):await _A(r,e.tokens))return!0}catch{}return!1}var TA,IA,CA,mk=x(()=>{"use strict";TA=3,IA=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,CA=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as hk}from"node:fs";import{join as gk}from"node:path";import{simpleGit as yk}from"simple-git";async function ui(t,e,r={}){let n=r.log??jA,o=[];for(let i of e){let s=gk(t,i.mountAs),a=Zp(i);if(!hk(s)){if(r.dryRun){n.info(`would clone ${a} \u2192 ${i.mountAs}/`),o.push({mountAs:i.mountAs,status:"cloned",detail:"(dry-run)"});continue}try{n.info(`cloning ${a} \u2192 ${i.mountAs}/`),await yk().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let p=li(u instanceof Error?u.message:String(u));n.warn(`clone failed for ${i.mountAs}: ${p}`),o.push({mountAs:i.mountAs,status:"error",detail:p})}continue}if(!hk(gk(s,".git"))){n.warn(`${i.mountAs}/ exists but is not a git repo \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-not-git"});continue}let c=yk(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!NA(l,a)){n.warn(`${i.mountAs}/ origin (${li(l)||"none"}) != expected (${li(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:li(l)});continue}if(r.dryRun){n.info(`would fetch ${i.mountAs}/`),o.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),o.push({mountAs:i.mountAs,status:"fetched"})}catch(u){let p=li(u instanceof Error?u.message:String(u));n.warn(`fetch failed for ${i.mountAs}: ${p}`),o.push({mountAs:i.mountAs,status:"error",detail:p})}}return o}function NA(t,e){return wk(t)===wk(e)}function wk(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function li(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function bk(t={}){let e=je();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 ui(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 jA,oa=x(()=>{"use strict";xt();jA={info:t=>console.log(t),warn:t=>console.warn(t)}});import{existsSync as Yu,readFileSync as Vu,writeFileSync as kk}from"node:fs";import{join as zu}from"node:path";import{parseDocument as Xu}from"yaml";function vk(t){let e={};return t.branches.integration&&(e.integration=t.branches.integration),t.branches.stable!==void 0&&(e.stable=t.branches.stable),t.branches.release_pattern!==void 0&&(e.release_pattern=t.branches.release_pattern),{flow:t.flow,branches:e}}function $k(t){let{errors:e}=yn(t);if(e.length>0)throw new Error(`invalid git config: ${e.join("; ")}`)}async function xk(t,e){let r=vk(e);$k(r);let n=zu(t,"project.yaml");if(!Yu(n))throw new Error(`project.yaml not found in context repo (${t})`);let o=Xu(Vu(n,"utf-8"));o.set("git",r),kk(n,o.toString())}async function Sk(t,e,r){let n=vk(r);$k(n);let o=zu(t,"project.yaml");if(!Yu(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=Xu(Vu(o,"utf-8"));ns(i,e).set("git",n),kk(o,i.toString())}function Ek(t){let e=zu(t,"project.yaml");if(!Yu(e))return null;try{let r=Xu(Vu(e,"utf-8")).toJS();return OA(r?.git)}catch{return null}}function OA(t){if(!t||typeof t!="object")return null;let e=t,r=e.flow;if(r!=="simple"&&r!=="gitflow"&&r!=="release")return null;let n=e.branches;if(!n||typeof n!="object")return null;let o=n,i=o.integration;if(typeof i!="string"||!i)return null;let s={flow:r,branches:{integration:i}};return typeof o.stable=="string"&&(s.branches.stable=o.stable),typeof o.release_pattern=="string"&&(s.branches.release_pattern=o.release_pattern),s}var Rk=x(()=>{"use strict";M();os()});import{confirm as LA,isCancel as MA}from"@clack/prompts";async function ia(t){let e=Eo(t.facts),r=t.confirm??DA,n=t.log??(()=>{}),o=t.readProject??Ek,i=t.writeProject??xk,s=t.writeOverride??Sk;if(!t.contextDir)return e.flow!=="simple"&&n(`git-flow: detected ${ro(e)} (no context repo to persist)`),{outcome:"no-context",detected:e};let a=t.contextDir,c=o(a);return c===null?e.flow==="simple"?(n("git-flow: simple (single branch)"),{outcome:"silent-simple",detected:e}):await r(`Detected git-flow: ${ro(e)}. Use it?`)?(await i(a,e),n(`git-flow: ${ro(e)} (project default)`),{outcome:"wrote-project",detected:e}):(n("git-flow: keeping simple (detection declined)"),{outcome:"declined",detected:e}):Ec(e,c)?await r(`This repo's git-flow (${ro(e)}) differs from the project (${ro(c)}). Record a per-repo override?`)?(await s(a,t.repoName,e),n(`git-flow: ${ro(e)} (per-repo override for "${t.repoName}")`),{outcome:"wrote-override",detected:e}):(n(`git-flow: using the project flow for "${t.repoName}" (override declined)`),{outcome:"declined",detected:e}):{outcome:"match",detected:e}}function ro(t){if(t.flow==="simple")return"simple (single branch)";let e=[`integration=${t.branches.integration}`];return t.branches.stable&&e.push(`stable=${t.branches.stable}`),t.branches.release_pattern&&e.push(`release=${t.branches.release_pattern}`),`${t.flow} (${e.join(", ")})`}async function DA(t){let e=await LA({message:t,initialValue:!0});return MA(e)?!1:e===!0}var Ju=x(()=>{"use strict";M();Rk()});import{simpleGit as Tk}from"simple-git";async function di(t,e){let r=Tk(t),n=null;try{n=(await r.raw(["symbolic-ref","--short","refs/remotes/origin/HEAD"])).trim().replace(/^origin\//,"")||null}catch{}!n&&e&&(n=await UA(e));let o=[];try{o=(await r.raw(["for-each-ref","--format=%(refname:short)","refs/remotes/origin"])).split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).map(s=>s.replace(/^origin\//,"")).filter(s=>s!=="HEAD"&&s!=="origin")}catch{o=[]}return{defaultBranch:n,branches:o}}async function UA(t){try{let e=await Tk().listRemote(["--symref",t,"HEAD"]);return/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m.exec(e)?.[1]??null}catch{return null}}var Zu=x(()=>{"use strict"});import{simpleGit as BA}from"simple-git";async function Ik(t,e,r){return t.host==="github"?FA(t,e,r):t.host==="gitlab"?GA(t,e,r):KA(t,e,r)}function Qu(t){return new Error(`${t.owner}/${t.repoName} exists but is PUBLIC \u2014 a mirror holds the repository's full history and must be private. Make it private (or pick another name) and re-run`)}async function FA(t,e,r){let n=e.githubToken;if(!n)throw new Error("GitHub token required to create a github-hosted mirror");let o=await it(n,"GET",`/repos/${t.owner}/${encodeURIComponent(t.repoName)}`);if(o.status===200&&o.data){if(o.data.private!==!0)throw Qu(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:o.data.ssh_url,created:!1}}let i=(await it(n,"GET","/user")).data?.login??"",s=i.toLowerCase()===t.owner.toLowerCase(),a=!s&&await Ku(n,t.owner);if(!s&&!a)throw new Error(`"${t.owner}" is neither the token's account ("${i}") nor an organization it can see \u2014 nothing was created. Use a GitHub username or organization (not an email)`);r.info(`creating mirror ${t.owner}/${t.repoName} (github, ${a?"org":"user"})`);let c=await it(n,"POST",a?`/orgs/${t.owner}/repos`:"/user/repos",{name:t.repoName,private:!0,auto_init:!1,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"});if(!c.data)throw new Error(`GitHub: could not create ${t.owner}/${t.repoName}`);return{spec:t,sshUrl:c.data.ssh_url,created:!0}}async function Ck(t,e,r){try{return t==="github"?(await it(e,"GET","/user")).data?.login??null:t==="gitlab"?(await Je(e,"GET","/user")).data?.username??null:r?(await Mt({email:r,apiToken:e},"GET","/workspaces?role=contributor&pagelen=1")).data?.values?.[0]?.slug??null:null}catch{return null}}async function GA(t,e,r){let n=e.gitlabToken;if(!n)throw new Error("GitLab PAT required to create a gitlab-hosted mirror");let o=encodeURIComponent(`${t.owner}/${t.repoName}`),i=await Je(n,"GET",`/projects/${o}`);if(i.status===200&&i.data){if(i.data.visibility!=="private")throw Qu(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:i.data.ssh_url_to_repo,created:!1}}let s={name:t.repoName,path:t.repoName,visibility:"private",initialize_with_readme:!1,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"};if((await Je(n,"GET","/user")).data?.username!==t.owner){let l=await Je(n,"GET",`/namespaces/${encodeURIComponent(t.owner)}`);if(l.status===404||!l.data)throw new Error(`GitLab namespace "${t.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);s.namespace_id=l.data.id}r.info(`creating mirror ${t.owner}/${t.repoName} (gitlab)`);let c=await Je(n,"POST","/projects",s);if(!c.data)throw new Error(`GitLab: could not create ${t.owner}/${t.repoName}`);return{spec:t,sshUrl:c.data.ssh_url_to_repo,created:!0}}async function KA(t,e,r){let n=e.bitbucket;if(!n)throw new Error("Bitbucket email + API token required to create a bitbucket-hosted mirror");let o=`/repositories/${t.owner}/${encodeURIComponent(t.repoName)}`,i=`git@bitbucket.org:${t.owner}/${t.repoName}.git`,s=await Mt(n,"GET",o);if(s.status===200&&s.data){if(s.data.is_private!==!0)throw Qu(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:i,created:!1}}r.info(`creating mirror ${t.owner}/${t.repoName} (bitbucket)`);let a=await Mt(n,"POST",o,{json:{scm:"git",is_private:!0,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"}});if(a.status===404||!a.data?.slug)throw new Error(`Bitbucket cannot create ${t.owner}/${t.repoName} \u2014 check the workspace and that the credential may create repositories in it`);return{spec:t,sshUrl:i,created:!0}}async function Pk(t,e,r){let n=BA(t);if((await n.raw(["rev-parse","--is-shallow-repository"])).trim()==="true")throw new Error("this clone is shallow \u2014 the mirror would be seeded with partial history. Run `git fetch --unshallow` first");if((await n.listRemote(["--heads",e])).trim().length>0)return r.info("mirror already has branches \u2014 leaving its content alone"),{seeded:!1};r.info("seeding mirror with the repository's branches and tags\u2026");let i=(await n.raw(["for-each-ref","refs/remotes/origin","--format=%(refname)"])).split(`
995
+ `).map(a=>a.trim()).filter(a=>a.length>0&&a!=="refs/remotes/origin/HEAD");if(i.length===0)throw new Error("the local clone has no origin branches to seed from");let s=i.map(a=>`${a}:refs/heads/${a.slice(20)}`);return await n.push([e,...s]),await n.push([e,"--tags"]),{seeded:!0}}function HA(t,e){let r=e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-");return`${t}-${r}-mirror`.replace(/-{2,}/g,"-").replace(/^[-.]+|[-.]+$/g,"")}function WA(t,e,r){return e.mirror?{host:e.mirror.host,owner:e.mirror.owner,repoName:e.mirror.repoName}:{host:r.host,owner:r.owner,repoName:HA(t,e.repoName)}}function Ak(t,e,r){let n=new Map,o=[];for(let i of e){let s=WA(t,i,r),a=`${s.host}:${s.owner.toLowerCase()}/${s.repoName.toLowerCase()}`,c=n.get(a);if(c)throw new Error(`repositories "${c}" and "${i.name}" both map to the mirror ${s.owner}/${s.repoName} \u2014 mirroring them into one repository would merge their histories. Give one an explicit mirror name (mirror.repo in project.yaml) and re-run`);n.set(a,i.name),o.push({repo:i,spec:s})}return o}var _k=x(()=>{"use strict";ci()});var Mk={};Ne(Mk,{ensureEmbeddedWorker:()=>aa,spawnWorkerProcess:()=>ca,upCommand:()=>la,workerChildEnv:()=>Lk,workerStartArgs:()=>Ok});import{spawn as Nk}from"node:child_process";import{existsSync as jk}from"node:fs";import{homedir as qA,hostname as YA}from"node:os";import{join as sa}from"node:path";async function VA(t,e,r){let n=Ge(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${Tt(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 _g(t.hubUrl.replace(/\/$/,""),n.token)}catch(i){return console.warn(`[up] could not verify the worker registration (${i instanceof Error?i.message:String(i)}) \u2014 continuing`),!1}if(o==="unsupported")return console.log(`[up] worker already registered as ${n.sandboxId} (${n.name})`),!1;if(o==="ok")return console.log(`[up] worker already registered as ${n.sandboxId} (${n.name})`),!1;if(!r.reregister)throw new Error(`the HUB no longer knows this worker registration (${n.sandboxId}) \u2014 it was removed on ${t.hubUrl}, but ${Tt(e)} still holds its token.
996
+ 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`),mf(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function zA(t,e,r){let n=Ge(e)!==null;if(!await VA(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 Rs(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof V&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof V&&i.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):i instanceof V?i:new Error(`cannot reach the HUB at ${t.hubUrl} (${i instanceof Error?i.message:String(i)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await qr({hub:t.hubUrl,token:o,name:r.name??`${YA()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function XA(t,e){let r=Ge(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=ze(r.sealPublicKey);if(!X(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=ji(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 aa(t,e,r){await zA(t,e,r),XA(t.projectId,e)}function Ok(t){return[...t?["--profile",t]:[],"worker","start"]}function Lk(t){let e={...t};for(let r of Nc)delete e[r];return e}function ca(t){let e=Nk(process.execPath,[t.entry,...Ok(t.profile)],{stdio:["ignore","pipe","pipe"],env:Lk(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
997
+ `))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function JA(t,e){let r=process.cwd(),n=sa(r,nt);if($n(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(jk(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 se(t.hubUrl,t.cliToken,t.projectId)}catch(u){console.warn(`[up] could not fetch the project summary (${u instanceof Error?u.message:String(u)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await ed(r);if(!Jp(r,i?.parsed??null,o.repos)){console.log(`[up] this folder is neither empty nor a repo of ${t.projectId} \u2014 the context stays under ~/.codepipe/profiles`);return}let s=X(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await Bs({cfg:t,secrets:s,contextDir:n,log:a}).catch(()=>null);if(!c?.contextDir){console.warn("[up] could not clone the Context Repo here \u2014 the context stays under ~/.codepipe/profiles");return}let l=sa(qA(),".codepipe",e?sa("profiles",e,"context-config"):"context-config");if(Wi(c.contextDir,l,a),!jk(sa(c.contextDir,"project.yaml"))){_n(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};jo(c.contextDir,Nt(u,!0,s?.youtrack?.url)),console.log("[up] local project config seeded with defaults \u2014 review .codepipe/project.yaml")}console.log(`[up] project context materialized \u2192 ${n}`)}async function la(t){let{cfg:e,profile:r}=Sn(t.profile);if(t.debug){let f=typeof t.debug=="string"&&t.debug.trim()?t.debug.trim():"agent-request";process.env.CODEPIPE_DEBUG=f,console.log(`[up] debug logging on (${f}) \u2192 ~/.codepipe/debug/${e.projectId}/`)}await JA(e,r),await aa(e,r,t);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(f,m)=>{let g=b=>w=>{for(let v of w.toString("utf-8").split(`
1004
998
  `))v.length>0&&b.write(`${m} ${v}
1005
- `)};f.stdout?.on("data",g(process.stdout)),f.stderr?.on("data",g(process.stderr))},i=(f,m)=>{let g=Ak(process.execPath,[n,...m],{stdio:["ignore","pipe","pipe"],env:process.env});return o(g,f),g};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=ca({entry:n,profile:r,onLine:f=>process.stdout.write(`[worker] ${f}
999
+ `)};f.stdout?.on("data",g(process.stdout)),f.stderr?.on("data",g(process.stderr))},i=(f,m)=>{let g=Nk(process.execPath,[n,...m],{stdio:["ignore","pipe","pipe"],env:process.env});return o(g,f),g};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=ca({entry:n,profile:r,onLine:f=>process.stdout.write(`[worker] ${f}
1006
1000
  `)}),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,u=f=>{if(!l){l=!0,console.log(`
1007
- [up] ${f} \u2014 stopping both roles`);for(let{child:m}of c)m.exitCode===null&&m.kill(f);setTimeout(()=>{for(let{name:m,child:g}of c)g.exitCode===null&&(console.warn(`[up] ${m} did not stop \u2014 SIGKILL`),g.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:f,child:m})=>new Promise(g=>{m.on("exit",(b,w)=>g({name:f,code:b??(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 ua=x(()=>{"use strict";gt();Zn();Ve();zt();nu();Br();Le();me();xt();di()});import{existsSync as Jr,mkdirSync as Lk,readFileSync as da,readdirSync as VA,writeFileSync as Mk}from"node:fs";import{join as De,resolve as Dk}from"node:path";import{setTimeout as td}from"node:timers/promises";import{cancel as Uk,confirm as pi,intro as Bk,isCancel as od,log as P,multiselect as zA,outro as rd,password as fi,select as wt,spinner as id,text as ke}from"@clack/prompts";import{simpleGit as ro}from"simple-git";function he(t){Uk(t),process.exit(1)}function be(t){return od(t)&&he("aborted"),t}function le(t){return od(t)&&he("aborted"),typeof t=="string"?t:""}async function Fk(t={}){Bk("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();ok();let r=nk(e),n,o=!1;r&&Object.keys(r.answers).length>0?be(await pi({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(P.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new eo(e,r),o=!0):(qu(e),n=new eo(e)):n=new eo(e);let i=t.force===!0?null:await ed(e),s=await n.ask("target",async()=>be(await wt({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i??(t.force===!0?null:await JA(e,n)),a?P.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):o&&n.get("contextRepo")!==void 0||Kk(e,t.force===!0));let c=await n.ask("hubUrl",async()=>le(await ke({message:"HUB URL",placeholder:bt,initialValue:ee("HUB_URL")??bt,validate:T=>T.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>no()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>oo(c,l)),d=null;s==="farm"&&(d=await XA(c,u));let f=a?e_(a.parsed.repoName):"",m=await n.ask("projectId",async()=>le(await ke({message:"project id (slug)",placeholder:f||"acme",...f?{initialValue:f}:{},validate:T=>er.test(T.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await n.ask("projectName",async()=>le(await ke({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:T=>T.trim().length>0?void 0:"required"})).trim()),b=await n.ask("language",()=>d_()),w=await n.ask("automationLevel",async()=>be(await wt({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),y=(s==="farm"?"no":await n.ask("mirrorChoice",async()=>be(await wt({message:"how much access should CodePipe have to your repositories?",options:[{value:"no",label:"read and write \u2014 branches and pull requests go into your repositories"},{value:"yes",label:"read only \u2014 CodePipe mirrors them and works in the mirrors",hint:"a mirror is a full copy of the history, in the account you choose next"}],initialValue:"no"}))))==="yes";y&&P.message("read-only token tip: if you want CodePipe to review pull requests people open in your repositories, the token also needs PR-comment permission (GitHub: Pull requests write; Bitbucket: pullrequest:write). Code stays read-only either way.");let k=await n.ask("trackerProvider",async()=>be(await wt({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"}))),C=k==="internal",E=null,$,A=!0;if(C){let T,R=id();R.start("checking task-key prefixes on your account\u2026");try{T=await Pg(c,u,{excludeProjectId:m}),R.stop("prefixes checked")}catch{R.stop("could not reach the HUB",1),he("Could not verify the task-key prefix against your account \u2014 the HUB is unreachable right now. Prefix uniqueness is required, so init can't continue. Check your connection and re-run `codepipe init` later.")}let S=Ic(Tc(g),T);$=await n.ask("trackerPrefix",async()=>le(await ke({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:S,initialValue:S,validate:I=>{let J=I.trim();if(!Nr.test(J))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(T.has(J.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else E=await n.ask("youtrack",()=>Zk()),$=await n.ask("youtrackProjectKey",async()=>le(await ke({message:"YouTrack project key",placeholder:"DEV",validate:T=>T.trim().length>0?void 0:"required"})).trim()),A=await n.ask("youtrackWrites",async()=>be(await pi({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let N=n.get("tokens")??{},B=()=>n.set("tokens",N),H=await n.ask("repos",()=>i_(N,l,a,{onCred:B,initial:n.get("reposPartial")??[],onProgress:T=>n.set("reposPartial",T)}));n.delete("reposPartial");let j=null,h="",F="";if(y){let T=be(await n.ask("mirrorHost",async()=>be(await wt({message:"where should the mirrors live? (your Context Repo will default there too)",options:["github","gitlab","bitbucket"].map(q=>({value:q,label:q===H[0]?.host?`${q} (same as your repositories)`:q})),initialValue:H[0]?.host??"github"}))));h=le(await n.ask("mirrorToken",async()=>be(await fi({message:`token that may CREATE and PUSH repositories on ${T}`})))).trim(),T==="bitbucket"&&(F=le(await n.ask("mirrorEmail",async()=>be(await ke({message:"Atlassian account email for that token",...N.bitbucket?.email?{placeholder:N.bitbucket.email,defaultValue:N.bitbucket.email}:{}})))).trim());let R=await Rk(T,h,F||void 0),S=T==="bitbucket"?"workspace slug":"username or organization (not an email)",J=le(await n.ask("mirrorOwnerLogin",async()=>be(await ke({message:`account for the mirrors \u2014 ${T} ${S}`,...R?{placeholder:R,defaultValue:R}:{},validate:q=>{let re=(q??"").trim();if(!re&&!R)return"required";if(re.includes("@"))return`that looks like an email \u2014 a ${T} ${S} is expected`;if(/\s/.test(re))return"no spaces"}})))).trim()||R||"";if(!J||J.includes("@")){Uk("mirrors need a host account to live in (a username/organization, not an email)");return}j={host:T,owner:J}}let L=await s_(await n.ask("contextRepo",()=>zk(m,H,N,l,j??void 0)),m,H,N,l,B,T=>n.set("contextRepo",T),j??void 0),{spec:z,mode:te}=L,ae;C||(P.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),ae=await n.ask("assigneeLogin",async()=>le(await ke({message:"your YouTrack login (the assignee value)",...E?.login?{initialValue:E.login}:{},validate:T=>T.trim().length>0?void 0:"required"})).trim()));let Ut=await n.ask("llmProvider",async()=>{for(;;){if(be(await wt({message:"LLM provider",options:[{value:"claude",label:"Claude",hint:"recommended"},{value:"codex",label:"Codex",hint:"coming soon"}],initialValue:"claude"}))==="claude")return"claude";P.warn("Codex support is coming soon \u2014 pick Claude for now.")}}),We=Ut==="claude"?await n.ask("claudeToken",()=>Yb(qb("claude"),{farm:s==="farm"})):"",Ue;if(We){let T=await Qf(We);if(T){let R=Ya(T);R&&(Ue=R,P.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 Ae={projectId:m,name:g,automationLevel:w,repos:H,trackerProvider:k,youtrackProjectKey:$,language:b};P.step(`${te==="attach"?"attaching to":"provisioning"} Context Repo ${z.owner}/${z.name} (${z.host})\u2026`);let Be;try{Be=await Qn(Ae,z,{...Xk(N),youtrackWrites:A,...E?{trackerUrl:E.url}:{},mode:te,log:{info:T=>P.message(T),warn:T=>P.warn(T)}})}catch(T){he(`Context Repo provisioning failed: ${T instanceof Error?T.message:String(T)}`)}Ae.contextRepo=Be,P.success(`Context Repo ready: ${Be.owner}/${Be.name}@${Be.branch}`),P.step(`registering project on ${c}\u2026`);let Te;try{Te=await pr(c,u,Ae)}catch(T){if(T instanceof V&&T.status===409){P.warn(`project ${m} already exists on HUB \u2014 reusing it`);try{Te=await se(c,u,m)}catch(R){throw R instanceof V&&he(`HUB \u2192 ${R.status} ${R.message}`),R}}else if(T instanceof V&&T.status===401)n.delete("cliToken"),he("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(T instanceof V)he(`HUB \u2192 ${T.status} ${T.message}`);else throw T}let st=Te.contextRepo??Be;P.success(`project ${Te.projectId} ready (${Te.provisioningStatus})`);let Bt=E?{url:E.url,token:E.token}:void 0;if(s==="farm"){let T=d,R={...N,...We?{claude:{oauthToken:We}}:{},...Bt?{youtrack:Bt}:{}},S=N.github?.token;if(st.host==="github"&&S)try{let re=$y(`devpipe-${m}`);await xy(st,S,re.publicKey,`devpipe-${m}`),R.contextSsh={privateKey:re.privateKey},P.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(re){P.warn(`could not set up Context Repo SSH deploy key (${re instanceof Error?re.message:String(re)}); the farm will fall back to the token path.`)}let I={projectId:m,config:{hubUrl:c,cliToken:u,projectId:m},secrets:R,contextRepo:st,projectConfig:Nt(Ae,A,E?.url,ae||void 0,Ut,Ue)},J=Xt(T.farm.publicKey,JSON.stringify(I));P.step(`handing project ${m} to farm ${T.farm.name}\u2026`);let q;try{q=await Es(c,u,T.farm.farmId,{projectId:m,sealedBundle:J})}catch(re){throw re instanceof V&&he(re.status===409?`farm ${T.farm.name} is offline \u2014 start it and re-run.`:re.status===504?`farm ${T.farm.name} did not respond in time.`:`HUB \u2192 ${re.status} ${re.message}`),re}q.ok||he(`farm rejected provisioning: ${q.error??"unknown error"}`),await nd(c,u,m,st,S,Te.repos,null,N),n.clear(),rd(`done. project ${m} is now hosted on farm ${T.farm.name} (daemon ${q.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}Jk(N),await qk(e,st.cloneUrl,st.branch),Vk(e);try{_n(De(e,nt),e,{info:T=>P.message(T),warn:T=>P.warn(T)})}catch(T){P.warn(`skills materialize failed \u2014 ${T instanceof Error?T.message:String(T)}`)}a&&await r_(e);{let T=De(e,nt);An(T);let R=Nt(Ae,A,E?.url,ae||void 0,Ut,Ue),S=_o(T,R);S.length>0&&P.success(`local project config \u2192 .codepipe/{${S.join(", ")}}`),cr(m,R,{info:I=>P.message(I),warn:I=>P.warn(I)})}await Yk(e,Te.repos),await o_(e,Te.repos);let Ft=!1;if(y&&j&&(Ft=await n_(e,De(e,nt),m,Te.repos,{host:j.host,owner:j.owner,token:h,...F?{email:F}:{}}),Ft)){let T=De(e,nt);cr(m,{projectYaml:da(De(T,"project.yaml"),"utf-8"),regimenYaml:da(De(T,"regimen.yaml"),"utf-8")},{info:R=>P.message(R),warn:R=>P.warn(R)})}let U={hubUrl:c,cliToken:u,projectId:m,...N,...We?{claude:{oauthToken:We}}:{},...Bt?{youtrack:Bt}:{},...Ft?{mirrorWrite:{token:h,host:j.host,...F?{email:F}:{}}}:{}};ce(U),qt({hubUrl:c,cliToken:u,projectId:m,accountEmail:p},m),P.success(`secrets \u2192 ${_t(m)}`),await nd(c,u,m,st,N.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,Te.repos,e,N),n.clear();let G=`${c}/?project=${encodeURIComponent(m)}`;Ur(G),rd(`done. your project on the dashboard (sign in there to work with it):
1001
+ [up] ${f} \u2014 stopping both roles`);for(let{child:m}of c)m.exitCode===null&&m.kill(f);setTimeout(()=>{for(let{name:m,child:g}of c)g.exitCode===null&&(console.warn(`[up] ${m} did not stop \u2014 SIGKILL`),g.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:f,child:m})=>new Promise(g=>{m.on("exit",(b,w)=>g({name:f,code:b??(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 ua=x(()=>{"use strict";gt();Qn();Ve();Xt();nu();Fr();Le();me();xt();pi()});import{existsSync as Zr,mkdirSync as Uk,readFileSync as da,readdirSync as ZA,writeFileSync as Bk}from"node:fs";import{join as De,resolve as Fk}from"node:path";import{setTimeout as td}from"node:timers/promises";import{cancel as Gk,confirm as fi,intro as Kk,isCancel as od,log as P,multiselect as QA,outro as rd,password as mi,select as wt,spinner as id,text as ke}from"@clack/prompts";import{simpleGit as no}from"simple-git";function he(t){Gk(t),process.exit(1)}function be(t){return od(t)&&he("aborted"),t}function le(t){return od(t)&&he("aborted"),typeof t=="string"?t:""}async function Hk(t={}){Kk("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();ak();let r=sk(e),n,o=!1;r&&Object.keys(r.answers).length>0?be(await fi({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(P.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new to(e,r),o=!0):(qu(e),n=new to(e)):n=new to(e);let i=t.force===!0?null:await ed(e),s=await n.ask("target",async()=>be(await wt({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i??(t.force===!0?null:await t_(e,n)),a?P.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):o&&n.get("contextRepo")!==void 0||qk(e,t.force===!0));let c=await n.ask("hubUrl",async()=>le(await ke({message:"HUB URL",placeholder:bt,initialValue:ee("HUB_URL")??bt,validate:T=>T.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>oo()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>io(c,l)),d=null;s==="farm"&&(d=await e_(c,u));let f=a?o_(a.parsed.repoName):"",m=await n.ask("projectId",async()=>le(await ke({message:"project id (slug)",placeholder:f||"acme",...f?{initialValue:f}:{},validate:T=>tr.test(T.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await n.ask("projectName",async()=>le(await ke({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:T=>T.trim().length>0?void 0:"required"})).trim()),b=await n.ask("language",()=>h_()),w=await n.ask("automationLevel",async()=>be(await wt({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),y=(s==="farm"?"no":await n.ask("mirrorChoice",async()=>be(await wt({message:"how much access should CodePipe have to your repositories?",options:[{value:"no",label:"read and write \u2014 branches and pull requests go into your repositories"},{value:"yes",label:"read only \u2014 CodePipe mirrors them and works in the mirrors",hint:"a mirror is a full copy of the history, in the account you choose next"}],initialValue:"no"}))))==="yes";y&&P.message("read-only token tip: if you want CodePipe to review pull requests people open in your repositories, the token also needs PR-comment permission (GitHub: Pull requests write; Bitbucket: pullrequest:write). Code stays read-only either way.");let k=await n.ask("trackerProvider",async()=>be(await wt({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"}))),C=k==="internal",E=null,$,A=!0;if(C){let T,R=id();R.start("checking task-key prefixes on your account\u2026");try{T=await jg(c,u,{excludeProjectId:m}),R.stop("prefixes checked")}catch{R.stop("could not reach the HUB",1),he("Could not verify the task-key prefix against your account \u2014 the HUB is unreachable right now. Prefix uniqueness is required, so init can't continue. Check your connection and re-run `codepipe init` later.")}let S=Ic(Tc(g),T);$=await n.ask("trackerPrefix",async()=>le(await ke({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:S,initialValue:S,validate:I=>{let J=I.trim();if(!Or.test(J))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(T.has(J.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else E=await n.ask("youtrack",()=>tv()),$=await n.ask("youtrackProjectKey",async()=>le(await ke({message:"YouTrack project key",placeholder:"DEV",validate:T=>T.trim().length>0?void 0:"required"})).trim()),A=await n.ask("youtrackWrites",async()=>be(await fi({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let N=n.get("tokens")??{},B=()=>n.set("tokens",N),H=await n.ask("repos",()=>l_(N,l,a,{onCred:B,initial:n.get("reposPartial")??[],onProgress:T=>n.set("reposPartial",T)}));n.delete("reposPartial");let j=null,h="",F="";if(y){let T=be(await n.ask("mirrorHost",async()=>be(await wt({message:"where should the mirrors live? (your Context Repo will default there too)",options:["github","gitlab","bitbucket"].map(q=>({value:q,label:q===H[0]?.host?`${q} (same as your repositories)`:q})),initialValue:H[0]?.host??"github"}))));h=le(await n.ask("mirrorToken",async()=>be(await mi({message:`token that may CREATE and PUSH repositories on ${T}`})))).trim(),T==="bitbucket"&&(F=le(await n.ask("mirrorEmail",async()=>be(await ke({message:"Atlassian account email for that token",...N.bitbucket?.email?{placeholder:N.bitbucket.email,defaultValue:N.bitbucket.email}:{}})))).trim());let R=await Ck(T,h,F||void 0),S=T==="bitbucket"?"workspace slug":"username or organization (not an email)",J=le(await n.ask("mirrorOwnerLogin",async()=>be(await ke({message:`account for the mirrors \u2014 ${T} ${S}`,...R?{placeholder:R,defaultValue:R}:{},validate:q=>{let re=(q??"").trim();if(!re&&!R)return"required";if(re.includes("@"))return`that looks like an email \u2014 a ${T} ${S} is expected`;if(/\s/.test(re))return"no spaces"}})))).trim()||R||"";if(!J||J.includes("@")){Gk("mirrors need a host account to live in (a username/organization, not an email)");return}j={host:T,owner:J}}let L=await u_(await n.ask("contextRepo",()=>Zk(m,H,N,l,j??void 0)),m,H,N,l,B,T=>n.set("contextRepo",T),j??void 0),{spec:z,mode:te}=L,ae;C||(P.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),ae=await n.ask("assigneeLogin",async()=>le(await ke({message:"your YouTrack login (the assignee value)",...E?.login?{initialValue:E.login}:{},validate:T=>T.trim().length>0?void 0:"required"})).trim()));let Ut=await n.ask("llmProvider",async()=>{for(;;){if(be(await wt({message:"LLM provider",options:[{value:"claude",label:"Claude",hint:"recommended"},{value:"codex",label:"Codex",hint:"coming soon"}],initialValue:"claude"}))==="claude")return"claude";P.warn("Codex support is coming soon \u2014 pick Claude for now.")}}),We=Ut==="claude"?await n.ask("claudeToken",()=>Xb(zb("claude"),{farm:s==="farm"})):"",Ue;if(We){let T=await rm(We);if(T){let R=Ya(T);R&&(Ue=R,P.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 Ae={projectId:m,name:g,automationLevel:w,repos:H,trackerProvider:k,youtrackProjectKey:$,language:b};P.step(`${te==="attach"?"attaching to":"provisioning"} Context Repo ${z.owner}/${z.name} (${z.host})\u2026`);let Be;try{Be=await eo(Ae,z,{...Qk(N),youtrackWrites:A,...E?{trackerUrl:E.url}:{},mode:te,log:{info:T=>P.message(T),warn:T=>P.warn(T)}})}catch(T){he(`Context Repo provisioning failed: ${T instanceof Error?T.message:String(T)}`)}Ae.contextRepo=Be,P.success(`Context Repo ready: ${Be.owner}/${Be.name}@${Be.branch}`),P.step(`registering project on ${c}\u2026`);let Te;try{Te=await fr(c,u,Ae)}catch(T){if(T instanceof V&&T.status===409){P.warn(`project ${m} already exists on HUB \u2014 reusing it`);try{Te=await se(c,u,m)}catch(R){throw R instanceof V&&he(`HUB \u2192 ${R.status} ${R.message}`),R}}else if(T instanceof V&&T.status===401)n.delete("cliToken"),he("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(T instanceof V)he(`HUB \u2192 ${T.status} ${T.message}`);else throw T}let st=Te.contextRepo??Be;P.success(`project ${Te.projectId} ready (${Te.provisioningStatus})`);let Bt=E?{url:E.url,token:E.token}:void 0;if(s==="farm"){let T=d,R={...N,...We?{claude:{oauthToken:We}}:{},...Bt?{youtrack:Bt}:{}},S=N.github?.token;if(st.host==="github"&&S)try{let re=Ey(`devpipe-${m}`);await Ry(st,S,re.publicKey,`devpipe-${m}`),R.contextSsh={privateKey:re.privateKey},P.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(re){P.warn(`could not set up Context Repo SSH deploy key (${re instanceof Error?re.message:String(re)}); the farm will fall back to the token path.`)}let I={projectId:m,config:{hubUrl:c,cliToken:u,projectId:m},secrets:R,contextRepo:st,projectConfig:Nt(Ae,A,E?.url,ae||void 0,Ut,Ue)},J=Jt(T.farm.publicKey,JSON.stringify(I));P.step(`handing project ${m} to farm ${T.farm.name}\u2026`);let q;try{q=await Es(c,u,T.farm.farmId,{projectId:m,sealedBundle:J})}catch(re){throw re instanceof V&&he(re.status===409?`farm ${T.farm.name} is offline \u2014 start it and re-run.`:re.status===504?`farm ${T.farm.name} did not respond in time.`:`HUB \u2192 ${re.status} ${re.message}`),re}q.ok||he(`farm rejected provisioning: ${q.error??"unknown error"}`),await nd(c,u,m,st,S,Te.repos,null,N),n.clear(),rd(`done. project ${m} is now hosted on farm ${T.farm.name} (daemon ${q.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}ev(N),await zk(e,st.cloneUrl,st.branch),Jk(e);try{jn(De(e,nt),e,{info:T=>P.message(T),warn:T=>P.warn(T)})}catch(T){P.warn(`skills materialize failed \u2014 ${T instanceof Error?T.message:String(T)}`)}a&&await s_(e);{let T=De(e,nt);_n(T);let R=Nt(Ae,A,E?.url,ae||void 0,Ut,Ue),S=jo(T,R);S.length>0&&P.success(`local project config \u2192 .codepipe/{${S.join(", ")}}`),lr(m,R,{info:I=>P.message(I),warn:I=>P.warn(I)})}await Xk(e,Te.repos),await c_(e,Te.repos);let Ft=!1;if(y&&j&&(Ft=await a_(e,De(e,nt),m,Te.repos,{host:j.host,owner:j.owner,token:h,...F?{email:F}:{}}),Ft)){let T=De(e,nt);lr(m,{projectYaml:da(De(T,"project.yaml"),"utf-8"),regimenYaml:da(De(T,"regimen.yaml"),"utf-8")},{info:R=>P.message(R),warn:R=>P.warn(R)})}let U={hubUrl:c,cliToken:u,projectId:m,...N,...We?{claude:{oauthToken:We}}:{},...Bt?{youtrack:Bt}:{},...Ft?{mirrorWrite:{token:h,host:j.host,...F?{email:F}:{}}}:{}};ce(U),Yt({hubUrl:c,cliToken:u,projectId:m,accountEmail:p},m),P.success(`secrets \u2192 ${_t(m)}`),await nd(c,u,m,st,N.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,Te.repos,e,N),n.clear();let G=`${c}/?project=${encodeURIComponent(m)}`;Br(G),rd(`done. your project on the dashboard (sign in there to work with it):
1008
1002
  ${G}
1009
- 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:D}=await Promise.resolve().then(()=>(ua(),Nk));await D({profile:void 0})}async function nd(t,e,r,n,o,i=[],s=null,a={}){let c=await ak(n,o),l=!1;if(!c)try{l=await uk(i,{localRoot:s,tokens:a})}catch{l=!1}let u=sk({indexExists:c,localClones:s!==null,reposNonEmpty:l}),p=await zA({message:u.message,options:u.options,initialValues:u.initialValues,required:!1});if(od(p))return;let d=new Set(p);if(d.has("map")&&s!==null)try{let f=je(s);if(!f)throw new Error("workspace not found");let{bootstrapWorkspaceModel:m}=await Promise.resolve().then(()=>(Jo(),Ms)),g=await m(f,void 0,{onLog:b=>P.message(b)});P.success(`project map ready: ${g.events} task events mined from history`)}catch(f){P.warn(`could not build the project map: ${f instanceof Error?f.message:String(f)}. Registration is not affected \u2014 run \`codepipe model bootstrap\` later.`)}if(d.has("backfill"))try{let{jobId:f}=await Xo(t,e,r,{reindex:!1,backfill:!0});P.success(`retrospective architecture analysis queued (job ${f}); decision drafts will appear on the project card for review once a SANDBOX picks up the job.`)}catch(f){P.warn(`could not start the retrospective analysis: ${f instanceof Error?f.message:String(f)}. Registration is not affected.`)}if(d.has("index"))try{let{jobId:f}=await Xo(t,e,r,{reindex:u.reindex});P.success(`indexing queued (job ${f}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(f){P.warn(`could not start indexing: ${f instanceof Error?f.message:String(f)}. You can retry later \u2014 registration is not affected.`)}}async function XA(t,e){let r;try{r=await Rg(t,e)}catch(c){throw c instanceof V&&he(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&he("no farm is available to this account. Farms are assigned by the operator \u2014 ask them to assign one to you (or, if you run your own farm host: `codepipe-farm register --hub <url> --token <token>` and `codepipe-farm start`, then have the operator assign it).");let o=be(await wt({message:"target farm",options:n.map(c=>({value:c.farmId,label:`${c.name}${c.online?"":" (offline)"} \u2014 ${c.keyFingerprint??"no fingerprint"}`}))})),i=n.find(c=>c.farmId===o),s;try{s=xs(i.farmId,i.publicKey)}catch(c){he(c instanceof Error?c.message:String(c))}return be(await pi({message:`confirm farm ${i.name} cred-channel fingerprint:
1003
+ 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:D}=await Promise.resolve().then(()=>(ua(),Mk));await D({profile:void 0})}async function nd(t,e,r,n,o,i=[],s=null,a={}){let c=await uk(n,o),l=!1;if(!c)try{l=await fk(i,{localRoot:s,tokens:a})}catch{l=!1}let u=lk({indexExists:c,localClones:s!==null,reposNonEmpty:l}),p=await QA({message:u.message,options:u.options,initialValues:u.initialValues,required:!1});if(od(p))return;let d=new Set(p);if(d.has("map")&&s!==null)try{let f=je(s);if(!f)throw new Error("workspace not found");let{bootstrapWorkspaceModel:m}=await Promise.resolve().then(()=>(Zo(),Ms)),g=await m(f,void 0,{onLog:b=>P.message(b)});P.success(`project map ready: ${g.events} task events mined from history`)}catch(f){P.warn(`could not build the project map: ${f instanceof Error?f.message:String(f)}. Registration is not affected \u2014 run \`codepipe model bootstrap\` later.`)}if(d.has("backfill"))try{let{jobId:f}=await Jo(t,e,r,{reindex:!1,backfill:!0});P.success(`retrospective architecture analysis queued (job ${f}); decision drafts will appear on the project card for review once a SANDBOX picks up the job.`)}catch(f){P.warn(`could not start the retrospective analysis: ${f instanceof Error?f.message:String(f)}. Registration is not affected.`)}if(d.has("index"))try{let{jobId:f}=await Jo(t,e,r,{reindex:u.reindex});P.success(`indexing queued (job ${f}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(f){P.warn(`could not start indexing: ${f instanceof Error?f.message:String(f)}. You can retry later \u2014 registration is not affected.`)}}async function e_(t,e){let r;try{r=await Cg(t,e)}catch(c){throw c instanceof V&&he(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&he("no farm is available to this account. Farms are assigned by the operator \u2014 ask them to assign one to you (or, if you run your own farm host: `codepipe-farm register --hub <url> --token <token>` and `codepipe-farm start`, then have the operator assign it).");let o=be(await wt({message:"target farm",options:n.map(c=>({value:c.farmId,label:`${c.name}${c.online?"":" (offline)"} \u2014 ${c.keyFingerprint??"no fingerprint"}`}))})),i=n.find(c=>c.farmId===o),s;try{s=xs(i.farmId,i.publicKey)}catch(c){he(c instanceof Error?c.message:String(c))}return be(await fi({message:`confirm farm ${i.name} cred-channel fingerprint:
1010
1004
  ${s}
1011
- (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||he("farm fingerprint not confirmed \u2014 aborting."),$s(i.farmId,s),{farm:i,fingerprint:s}}async function Gk(t){Bk(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();Kk(e,t.force===!0);let r=le(await ke({message:"HUB URL",initialValue:ee("HUB_URL")??bt,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await no(),{cliToken:o,accountEmail:i}=await oo(r,n);P.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await se(r,o,t.projectId)}catch(d){throw d instanceof V&&he(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||he(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await Zk(),l={},u=new Set(s.repos.map(d=>d.host));u.add(s.contextRepo.host);for(let d of u){let f=s.repos.find(m=>m.host===d);await pa(d,l,f?.owner??s.contextRepo.owner,n,f?.repoName)}Jk(l),await qk(e,s.contextRepo.cloneUrl,s.contextRepo.branch),Vk(e);{let d=De(e,nt);An(d);let f={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.trackerProvider?{trackerProvider:s.trackerProvider}:{},...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{},...s.language?{language:s.language}:{}},m=Nt(f,!0,c?.url,void 0,s.llmProvider??tt),g=_o(d,m);g.length>0&&P.success(`local project config \u2192 .codepipe/{${g.join(", ")}} (defaults \u2014 review and adjust)`),cr(t.projectId,m,{info:b=>P.message(b),warn:b=>P.warn(b)})}await Yk(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};ce(p),qt({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),P.success(`secrets \u2192 ${_t(t.projectId)}`),await nd(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),rd("done.")}function Kk(t,e){if(!Jr(t)){Lk(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=VA(t).filter(o=>!r.has(o));n.length!==0&&(e||he(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function ed(t){if(!Jr(De(t,".git")))return null;try{let e=Ze(await Hk(t));return e?{parsed:e,defaultBranch:await Wk(t)}:null}catch{return null}}async function Hk(t){try{return(await ro(t).remote(["get-url","origin"])||"").toString().trim()}catch{return""}}async function JA(t,e){if(!Jr(De(t,".git")))return null;let r=await e.ask("inPlaceOrigin",async()=>{let o=await Hk(t);return P.warn(o?`this folder is a git checkout, but its origin (${o}) is not a github.com / gitlab.com / bitbucket.org URL`:"this folder is a git checkout without an `origin` remote"),le(await ke({message:"clone URL of this repository \u2014 blank if this folder is not the project repo",placeholder:"git@github.com:acme/api.git",validate:i=>!i||!i.trim()||Ze(i)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim()}),n=r?Ze(r):null;return n?{parsed:n,defaultBranch:await Wk(t)}:null}async function ZA(t){try{let e=await ro().listRemote(["--symref",t,"HEAD"]);return/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m.exec(e)?.[1]??null}catch{return null}}async function QA(t,e){try{return(await ro().listRemote([t,`refs/heads/${e}`])).trim().length>0}catch{return!0}}async function Wk(t){let e=ro(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 e_(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return er.test(e)?e:""}function t_(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function r_(t){let e=De(t,".gitignore"),r=Jr(e)?da(e,"utf-8"):"";if(t_(r))return;if(!be(await pi({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){P.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
1005
+ (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||he("farm fingerprint not confirmed \u2014 aborting."),$s(i.farmId,s),{farm:i,fingerprint:s}}async function Wk(t){Kk(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();qk(e,t.force===!0);let r=le(await ke({message:"HUB URL",initialValue:ee("HUB_URL")??bt,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await oo(),{cliToken:o,accountEmail:i}=await io(r,n);P.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await se(r,o,t.projectId)}catch(d){throw d instanceof V&&he(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||he(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await tv(),l={},u=new Set(s.repos.map(d=>d.host));u.add(s.contextRepo.host);for(let d of u){let f=s.repos.find(m=>m.host===d);await pa(d,l,f?.owner??s.contextRepo.owner,n,f?.repoName)}ev(l),await zk(e,s.contextRepo.cloneUrl,s.contextRepo.branch),Jk(e);{let d=De(e,nt);_n(d);let f={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.trackerProvider?{trackerProvider:s.trackerProvider}:{},...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{},...s.language?{language:s.language}:{}},m=Nt(f,!0,c?.url,void 0,s.llmProvider??tt),g=jo(d,m);g.length>0&&P.success(`local project config \u2192 .codepipe/{${g.join(", ")}} (defaults \u2014 review and adjust)`),lr(t.projectId,m,{info:b=>P.message(b),warn:b=>P.warn(b)})}await Xk(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};ce(p),Yt({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),P.success(`secrets \u2192 ${_t(t.projectId)}`),await nd(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),rd("done.")}function qk(t,e){if(!Zr(t)){Uk(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=ZA(t).filter(o=>!r.has(o));n.length!==0&&(e||he(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function ed(t){if(!Zr(De(t,".git")))return null;try{let e=Ze(await Yk(t));return e?{parsed:e,defaultBranch:await Vk(t)}:null}catch{return null}}async function Yk(t){try{return(await no(t).remote(["get-url","origin"])||"").toString().trim()}catch{return""}}async function t_(t,e){if(!Zr(De(t,".git")))return null;let r=await e.ask("inPlaceOrigin",async()=>{let o=await Yk(t);return P.warn(o?`this folder is a git checkout, but its origin (${o}) is not a github.com / gitlab.com / bitbucket.org URL`:"this folder is a git checkout without an `origin` remote"),le(await ke({message:"clone URL of this repository \u2014 blank if this folder is not the project repo",placeholder:"git@github.com:acme/api.git",validate:i=>!i||!i.trim()||Ze(i)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim()}),n=r?Ze(r):null;return n?{parsed:n,defaultBranch:await Vk(t)}:null}async function r_(t){try{let e=await no().listRemote(["--symref",t,"HEAD"]);return/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m.exec(e)?.[1]??null}catch{return null}}async function n_(t,e){try{return(await no().listRemote([t,`refs/heads/${e}`])).trim().length>0}catch{return!0}}async function Vk(t){let e=no(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 o_(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return tr.test(e)?e:""}function i_(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function s_(t){let e=De(t,".gitignore"),r=Zr(e)?da(e,"utf-8"):"";if(i_(r))return;if(!be(await fi({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){P.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
1012
1006
  `)?"":`
1013
- `;Mk(e,r+o+`
1007
+ `;Bk(e,r+o+`
1014
1008
  # codepipe workspace (added by \`codepipe init\`)
1015
1009
  .codepipe/
1016
- `),P.success(`.codepipe/ added to ${Dk(e)}`)}async function no(){let t="";try{t=(await ro().raw(["config","--global","user.email"])||"").trim()}catch{}return le(await ke({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function oo(t,e){P.step(`connecting account ${e}`);let r;try{r=await Ag(t,e)}catch(s){throw s instanceof zo&&he(`${e} is not authorized on this HUB yet.
1010
+ `),P.success(`.codepipe/ added to ${Fk(e)}`)}async function oo(){let t="";try{t=(await no().raw(["config","--global","user.email"])||"").trim()}catch{}return le(await ke({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function io(t,e){P.step(`connecting account ${e}`);let r;try{r=await Ng(t,e)}catch(s){throw s instanceof Xo&&he(`${e} is not authorized on this HUB yet.
1017
1011
  Sign up at ${t} (registration form on the login screen),
1018
1012
  wait for the operator to approve it by email, then re-run
1019
- \`codepipe init\` with the same email.`),s}r.accountCreated&&P.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&P.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(Ur(r.authorizeUrl),P.message(`a browser tab was opened to confirm this CLI:
1013
+ \`codepipe init\` with the same email.`),s}r.accountCreated&&P.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&P.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(Br(r.authorizeUrl),P.message(`a browser tab was opened to confirm this CLI:
1020
1014
  ${r.authorizeUrl}
1021
1015
  `+(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
1022
- otherwise use the emailed link the page offers.`))),r.approvalRequired&&P.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),P.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let n=!1,o=Date.now(),i=o+15*6e4;for(;Date.now()<i;){let s;try{s=await _g(t,r.requestId)}catch(a){P.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await td(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&P.message(`connected as ${a} (the account confirmed in the browser).`),P.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&he("the HUB rejected this account"),s.status==="expired"&&he("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,P.message(`email confirmed. waiting for the operator to approve your account\u2026
1023
- (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await td(5e3);continue}await td(2e3)}he("bootstrap timed out")}async function qk(t,e,r){let n=De(t,nt);if(Jr(De(n,".git"))){P.message(`${n} already cloned \u2014 skipping`);return}Jr(n)&&he(`${n} exists but is not a git repo \u2014 remove it and re-run`),Lk(n,{recursive:!0}),P.step(`cloning Context Repo \u2192 ${n}`);try{await ro().clone(e,n,["--branch",r]),P.success(`cloned ${e}`)}catch(o){he(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function n_(t,e,r,n,o){if(n.length===0)return!1;P.step(`setting up ${n.length} mirror(s) \u2014 your repositories stay read-only`);let i={info:l=>P.message(` ${l}`),warn:l=>P.warn(` ${l}`)},s={...o.host==="github"?{githubToken:o.token}:{},...o.host==="gitlab"?{gitlabToken:o.token}:{},...o.host==="bitbucket"&&o.email?{bitbucket:{email:o.email,apiToken:o.token}}:{}},a;try{a=Ik(r,n,o)}catch(l){return P.warn(` ${l instanceof Error?l.message:String(l)}`),P.warn("mirroring is all-or-nothing: NO mirrors were recorded and the project keeps working against its own repositories. Fix the cause and re-run `codepipe init`"),!1}let c=[];for(let{repo:l,spec:u}of a)try{let p=await Ek(u,s,i);await Tk(De(t,l.mountAs??l.name),p.sshUrl,i),c.push({repoName:l.name,spec:u})}catch(p){return P.warn(` ${l.name}: mirror not set up \u2014 ${p instanceof Error?p.message:String(p)}`),P.warn("mirroring is all-or-nothing: NO mirrors were recorded and the project keeps working against its own repositories. Fix the cause and re-run `codepipe init`"),!1}for(let l of c)bh(e,l.repoName,l.spec);for(let l of c)P.success(` ${l.repoName} \u2192 ${l.spec.owner}/${l.spec.repoName}`);return!0}async function Yk(t,e){if(e.length===0)return;P.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(o=>({name:o.name,host:o.host,owner:o.owner,repoName:o.repoName,defaultBranch:o.defaultBranch??"main",mountAs:o.mountAs??o.name})),n=await li(t,r,{log:{info:o=>P.message(o),warn:o=>P.warn(o)}});for(let o of n)P.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}async function o_(t,e){let r=De(t,nt);for(let n of e){let o=De(t,n.mountAs??n.name),i;try{i=await ui(o)}catch(s){P.warn(`git-flow detection skipped for "${n.name}": ${s instanceof Error?s.message:String(s)}`);continue}try{await ia({contextDir:r,repoName:n.name,facts:i,log:s=>P.message(s)})}catch(s){throw P.error(`git-flow for "${n.name}" was NOT saved: ${s instanceof Error?s.message:String(s)}`),s}}}function Vk(t){let e=De(t,nt,".gitignore"),r="";if(Jr(e)&&(r=da(e,"utf-8")),Ok.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
1016
+ otherwise use the emailed link the page offers.`))),r.approvalRequired&&P.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),P.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let n=!1,o=Date.now(),i=o+15*6e4;for(;Date.now()<i;){let s;try{s=await Og(t,r.requestId)}catch(a){P.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await td(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&P.message(`connected as ${a} (the account confirmed in the browser).`),P.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&he("the HUB rejected this account"),s.status==="expired"&&he("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,P.message(`email confirmed. waiting for the operator to approve your account\u2026
1017
+ (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await td(5e3);continue}await td(2e3)}he("bootstrap timed out")}async function zk(t,e,r){let n=De(t,nt);if(Zr(De(n,".git"))){P.message(`${n} already cloned \u2014 skipping`);return}Zr(n)&&he(`${n} exists but is not a git repo \u2014 remove it and re-run`),Uk(n,{recursive:!0}),P.step(`cloning Context Repo \u2192 ${n}`);try{await no().clone(e,n,["--branch",r]),P.success(`cloned ${e}`)}catch(o){he(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function a_(t,e,r,n,o){if(n.length===0)return!1;P.step(`setting up ${n.length} mirror(s) \u2014 your repositories stay read-only`);let i={info:l=>P.message(` ${l}`),warn:l=>P.warn(` ${l}`)},s={...o.host==="github"?{githubToken:o.token}:{},...o.host==="gitlab"?{gitlabToken:o.token}:{},...o.host==="bitbucket"&&o.email?{bitbucket:{email:o.email,apiToken:o.token}}:{}},a;try{a=Ak(r,n,o)}catch(l){return P.warn(` ${l instanceof Error?l.message:String(l)}`),P.warn("mirroring is all-or-nothing: NO mirrors were recorded and the project keeps working against its own repositories. Fix the cause and re-run `codepipe init`"),!1}let c=[];for(let{repo:l,spec:u}of a)try{let p=await Ik(u,s,i);await Pk(De(t,l.mountAs??l.name),p.sshUrl,i),c.push({repoName:l.name,spec:u})}catch(p){return P.warn(` ${l.name}: mirror not set up \u2014 ${p instanceof Error?p.message:String(p)}`),P.warn("mirroring is all-or-nothing: NO mirrors were recorded and the project keeps working against its own repositories. Fix the cause and re-run `codepipe init`"),!1}for(let l of c)$h(e,l.repoName,l.spec);for(let l of c)P.success(` ${l.repoName} \u2192 ${l.spec.owner}/${l.spec.repoName}`);return!0}async function Xk(t,e){if(e.length===0)return;P.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(o=>({name:o.name,host:o.host,owner:o.owner,repoName:o.repoName,defaultBranch:o.defaultBranch??"main",mountAs:o.mountAs??o.name})),n=await ui(t,r,{log:{info:o=>P.message(o),warn:o=>P.warn(o)}});for(let o of n)P.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}async function c_(t,e){let r=De(t,nt);for(let n of e){let o=De(t,n.mountAs??n.name),i;try{i=await di(o)}catch(s){P.warn(`git-flow detection skipped for "${n.name}": ${s instanceof Error?s.message:String(s)}`);continue}try{await ia({contextDir:r,repoName:n.name,facts:i,log:s=>P.message(s)})}catch(s){throw P.error(`git-flow for "${n.name}" was NOT saved: ${s instanceof Error?s.message:String(s)}`),s}}}function Jk(t){let e=De(t,nt,".gitignore"),r="";if(Zr(e)&&(r=da(e,"utf-8")),Dk.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
1024
1018
  `)||r.length===0?"":`
1025
- `,i=Ok.join(`
1019
+ `,i=Dk.join(`
1026
1020
  `)+`
1027
- `;Mk(e,r+o+(r?`
1028
- `:"")+i),P.message(`appended runtime entries to ${Dk(e)}`)}async function i_(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;await pa(s.host,t,s.owner,e,s.repoName),i?.(),o.push({name:s.repoName,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:a,mountAs:"."}),n.onProgress?.(o),P.success(`added this repository: ${s.host}: ${s.owner}/${s.repoName} (this folder, default branch ${a})`)}for(;be(await pi({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=le(await ke({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:m=>!m||!m.trim()||Ze(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=Ze(a);P.message(`${c.host}: ${c.owner}/${c.repoName}`),await pa(c.host,t,c.owner,e,c.repoName),i?.();let l=le(await ke({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:m=>m.trim().length>0?void 0:"required"})).trim(),u=await ZA(a),p="";for(;p=le(await ke({message:"default branch",placeholder:u??"main",...u?{initialValue:u}:{}})).trim(),!(!p||!u||p===u||await QA(a,p));)P.warn(`branch "${p}" does not exist in ${c.owner}/${c.repoName} (the repository's default is "${u}")`);let d=le(await ke({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),f={name:l,host:c.host,owner:c.owner,repoName:c.repoName};p&&(f.defaultBranch=p),d&&d!==l&&(f.mountAs=d),o.push(f),n.onProgress?.(o)}return o}async function zk(t,e,r,n,o){P.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let i=be(await wt({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));i==="attach"&&P.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let s=o?.host??e[0]?.host,a=o?.owner??e[0]?.owner,c;if(s&&a){let l=le(await ke({message:`Context Repo \u2014 a name (hosted at ${s}: ${a}/<name>) or a full clone URL`,initialValue:At(t),validate:p=>{let d=(p??"").trim();if(!d)return"required";if(!Ze(d)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(d))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),u=Ze(l);c=u?{host:u.host,owner:u.owner,name:u.repoName}:{host:s,owner:a,name:l}}else{let l=await a_(),u=le(await ke({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:d=>d.trim().length>0?void 0:"required"})).trim(),p=le(await ke({message:"Context Repo name",placeholder:At(t),initialValue:At(t),validate:d=>d.trim().length>0?void 0:"required"})).trim();c={host:l,owner:u,name:p}}return{spec:c,mode:i}}function Xk(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 s_(t,e,r,n,o,i,s,a){let c=t;for(;;){let{spec:l,mode:u}=c;await pa(l.host,n,l.owner,o),i?.();let p=id();p.start(`checking ${l.owner}/${l.name} on ${l.host}\u2026`);let d=await zb(l,Xk(n),{explain:u==="attach"});if(d.found===!0)return p.stop(`${l.owner}/${l.name} found${u==="create"?" \u2014 existing repo will be reused":""}`),c;if(d.found==="unknown")return p.stop(`could not check ${l.owner}/${l.name} (${d.detail}) \u2014 continuing`,1),c;if(u==="create")return p.stop(`${l.owner}/${l.name} not found \u2014 will be created`),c;p.stop(d.detail,1);let f=be(await wt({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(f==="abort"&&he("aborted"),f==="create")return c={spec:l,mode:"create"},s(c),c;c=await zk(e,r,n,o,a),s(c)}}async function a_(){return be(await wt({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function fa(t,e){let r=id();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 Jk(t){Do(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Uo(t.gitlab?.token??process.env.GITLAB_TOKEN),Bo(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function pa(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await c_(r);i?e.github=i:P.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let i=await l_(r,n,o);i?e.bitbucket=i:P.warn("no Bitbucket API token \u2014 git falls back to this machine's SSH keys / BITBUCKET_* env; private repos won't clone over HTTPS and PRs won't open.")}else{let i=await u_();i?e.gitlab=i:P.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function c_(t){for(;;){let e=le(await fi({message:`GitHub PAT \u2014 blank to skip
1021
+ `;Bk(e,r+o+(r?`
1022
+ `:"")+i),P.message(`appended runtime entries to ${Fk(e)}`)}async function l_(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;await pa(s.host,t,s.owner,e,s.repoName),i?.(),o.push({name:s.repoName,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:a,mountAs:"."}),n.onProgress?.(o),P.success(`added this repository: ${s.host}: ${s.owner}/${s.repoName} (this folder, default branch ${a})`)}for(;be(await fi({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=le(await ke({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:m=>!m||!m.trim()||Ze(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=Ze(a);P.message(`${c.host}: ${c.owner}/${c.repoName}`),await pa(c.host,t,c.owner,e,c.repoName),i?.();let l=le(await ke({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:m=>m.trim().length>0?void 0:"required"})).trim(),u=await r_(a),p="";for(;p=le(await ke({message:"default branch",placeholder:u??"main",...u?{initialValue:u}:{}})).trim(),!(!p||!u||p===u||await n_(a,p));)P.warn(`branch "${p}" does not exist in ${c.owner}/${c.repoName} (the repository's default is "${u}")`);let d=le(await ke({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),f={name:l,host:c.host,owner:c.owner,repoName:c.repoName};p&&(f.defaultBranch=p),d&&d!==l&&(f.mountAs=d),o.push(f),n.onProgress?.(o)}return o}async function Zk(t,e,r,n,o){P.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let i=be(await wt({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));i==="attach"&&P.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let s=o?.host??e[0]?.host,a=o?.owner??e[0]?.owner,c;if(s&&a){let l=le(await ke({message:`Context Repo \u2014 a name (hosted at ${s}: ${a}/<name>) or a full clone URL`,initialValue:At(t),validate:p=>{let d=(p??"").trim();if(!d)return"required";if(!Ze(d)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(d))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),u=Ze(l);c=u?{host:u.host,owner:u.owner,name:u.repoName}:{host:s,owner:a,name:l}}else{let l=await d_(),u=le(await ke({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:d=>d.trim().length>0?void 0:"required"})).trim(),p=le(await ke({message:"Context Repo name",placeholder:At(t),initialValue:At(t),validate:d=>d.trim().length>0?void 0:"required"})).trim();c={host:l,owner:u,name:p}}return{spec:c,mode:i}}function Qk(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??Rn()}}async function u_(t,e,r,n,o,i,s,a){let c=t;for(;;){let{spec:l,mode:u}=c;await pa(l.host,n,l.owner,o),i?.();let p=id();p.start(`checking ${l.owner}/${l.name} on ${l.host}\u2026`);let d=await Zb(l,Qk(n),{explain:u==="attach"});if(d.found===!0)return p.stop(`${l.owner}/${l.name} found${u==="create"?" \u2014 existing repo will be reused":""}`),c;if(d.found==="unknown")return p.stop(`could not check ${l.owner}/${l.name} (${d.detail}) \u2014 continuing`,1),c;if(u==="create")return p.stop(`${l.owner}/${l.name} not found \u2014 will be created`),c;p.stop(d.detail,1);let f=be(await wt({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(f==="abort"&&he("aborted"),f==="create")return c={spec:l,mode:"create"},s(c),c;c=await Zk(e,r,n,o,a),s(c)}}async function d_(){return be(await wt({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function fa(t,e){let r=id();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 ev(t){Uo(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Bo(t.gitlab?.token??process.env.GITLAB_TOKEN),Fo(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function pa(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await p_(r);i?e.github=i:P.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let i=await f_(r,n,o);i?e.bitbucket=i:P.warn("no Bitbucket API token \u2014 git falls back to this machine's SSH keys / BITBUCKET_* env; private repos won't clone over HTTPS and PRs won't open.")}else{let i=await m_();i?e.gitlab=i:P.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function p_(t){for(;;){let e=le(await mi({message:`GitHub PAT \u2014 blank to skip
1029
1023
  classic PAT: 'repo' + 'workflow'
1030
1024
  fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
1031
1025
  if org: approve token in org Settings \u2192 Personal access tokens.
1032
- (Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo.)`})).trim();if(!e)return;if(await fa("GitHub",()=>tr(e,t?{owner:t}:void 0)))return{token:e};P.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function l_(t,e,r){for(P.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
1026
+ (Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo.)`})).trim();if(!e)return;if(await fa("GitHub",()=>rr(e,t?{owner:t}:void 0)))return{token:e};P.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function f_(t,e,r){for(P.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
1033
1027
  How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
1034
1028
  'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes:
1035
1029
  read:repository:bitbucket + write:repository:bitbucket +
1036
1030
  read:pullrequest:bitbucket + write:pullrequest:bitbucket
1037
1031
  \u2014 write scopes do NOT include read: pick BOTH scopes of each pair
1038
1032
  (+ admin:repository:bitbucket if this token will provision the Context Repo).
1039
- The token is shown ONCE \u2014 copy it right away.`);;){let n=le(await ke({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:i=>!i||!i.trim()||i.includes("@")?void 0:"must be an email"})).trim();if(!n)return;let o=le(await fi({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){P.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await fa("Bitbucket",async()=>{let i=await rr(n,o,t);if(t&&r){let s=await Bi(n,o,t,r);if(s)throw new Error(s)}return i}))return{email:n,apiToken:o};P.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function u_(){for(;;){let t=le(await fi({message:`GitLab PAT \u2014 blank to skip
1040
- scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await fa("GitLab",()=>nr(t))){let e=await vf(t);return e&&P.warn(e),{token:t}}P.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function d_(){let t="__other__",e=async()=>le(await ke({message:"language name (in English, e.g. Ukrainian)",validate:s=>{let a=s.trim();if(a.length===0)return"required";if(a.length>40)return`\u2264 ${40} chars`}})).trim(),r=be(await wt({message:"project language",options:[...hn.map(s=>({value:s,label:s==="English"?"English (default)":s})),{value:t,label:"other\u2026"}],initialValue:"English"})),n=r===t?await e():r;if(n==="English")return{primary:n,context:n,tasks:n,docs:n,code_comments:n,chat:we};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:we}],i={primary:n};for(let s of o){let a=new Set,c=[s.initial,n,"English",we].filter(u=>a.has(u)?!1:(a.add(u),!0)).map(u=>({value:u,label:u===we?"auto \u2014 mirror the language of the user's material":u}));c.push({value:t,label:"other\u2026"});let l=be(await wt({message:`language for ${s.label}`,options:c,initialValue:s.initial}));i[s.key]=l===t?await e():l}return i}async function Zk(){for(;;){let t=le(await ke({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let n=r.trim();if(!n)return"required";if(!n.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=le(await fi({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await fa("YouTrack",()=>sr({baseUrl:t,token:e}))){let r=await Of({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}P.warn("re-enter the YouTrack URL / token.")}}var Ok,di=x(()=>{"use strict";Ye();M();gt();Vb();Gi();Ve();zt();Br();In();ai();ru();ra();Yt();Dr();ik();Le();ck();dk();Dl();rs();me();oa();os();Ju();Zu();Ck();zi();xt();Ok=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});M();Ye();Ve();import{Command as yj}from"commander";Ve();me();async function ff(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=St(e);r&&!t.force&&(console.error(`already configured at ${$n(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");qt({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...X(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};ce(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${$n(e)}`)}Oc();Ve();import{homedir as ou}from"node:os";import{join as Zo}from"node:path";Ye();M();import{existsSync as by,rmSync as IT}from"node:fs";import{join as Hr}from"node:path";import{simpleGit as CT}from"simple-git";import"ws";Ye();me();import{createHash as xx}from"node:crypto";import{existsSync as Sx,readFileSync as Ex}from"node:fs";import{homedir as Rx,hostname as Lc}from"node:os";import{join as Tx}from"node:path";function yf(t){return xx("sha256").update(t).digest("hex").slice(0,12)}function Ix(){let t=ee("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=Tx(Rx(),".claude","credentials.json");if(!Sx(e))return;let r=JSON.parse(Ex(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 wf(t){let e=Ix(),r=ee("ACCOUNT_ID")?.trim(),n=ee("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=Sn(t);return o?{accountId:`acct-${yf(o)}`,label:n||Lc(),...e?{email:e}:{}}:{accountId:`acct-${yf(`host:${Lc()}`)}`,label:n||Lc(),...e?{email:e}:{}}}Ye();In();me();Xc();async function nm(t,e,r,n,o){let i=c=>{e.readyState===e.OPEN&&e.send(JSON.stringify(c))},s=c=>i({type:"agent_login_url",requestId:r.requestId,projectId:t.projectId,error:c});if(ee("ORIGIN")==="farm"||ee("CLAUDE_AUTOLOGIN")!=="1"){s("autologin_disabled");return}let a;try{a=await zc(Fi())}catch(c){s(`listener failed: ${c instanceof Error?c.message:String(c)}`);return}i({type:"agent_login_url",requestId:r.requestId,projectId:t.projectId,authUrl:a.authUrl}),n.info(`[agent-auth] authorize Claude in a browser on THIS machine: ${a.authUrl}`),n.info(`[agent-auth] waiting for the redirect on ${a.redirectUri} \u2026`);try{let c=await a.waitForToken(),l=await Vt(c.oauthToken);if(l==="invalid"){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"token rejected (401) \u2014 previous token kept"}),n.warn("[agent-auth] new Claude token rejected (401) \u2014 previous token kept");return}let u=X(t.projectId);if(!u){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"no secrets file for this project on the CLI"}),n.warn("[agent-auth] no secrets file for this project \u2014 token not saved");return}u.claude={oauthToken:c.oauthToken},ce(u),n.info(`[agent-auth] Claude token replaced (${c.oauthToken.slice(0,12)}\u2026, ${c.oauthToken.length} chars)`),i({type:"agent_login_result",projectId:t.projectId,ok:!0,...l==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}}),o()}catch(c){let l=c instanceof Error?c.message:String(c);i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:l}),n.warn(`[agent-auth] browser authorization failed: ${l}`)}finally{a.close()}}Ye();function om(t,e){let r=t.find(n=>n.kind==="claude");return r?.present===!0&&r.ok===!1?ee("ORIGIN")==="farm"||ee("CLAUDE_AUTOLOGIN")!=="1"||e?"none":"open":r?.ok===!0?"rearm":"none"}function im(t,e){return`${t.replace(/\/$/,"")}/?project=${encodeURIComponent(e)}`}Gi();import{existsSync as eS}from"node:fs";import{join as tS}from"node:path";import{simpleGit as rS}from"simple-git";async function sm(t,e){if(!eS(tS(t,".git")))return{status:"skipped"};let r=rS(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${nS(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 nS(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as Zc,readFileSync as dm,readdirSync as sS,watch as aS}from"node:fs";import{join as Ao}from"node:path";M();import{existsSync as am,readFileSync as cm,readdirSync as oS,statSync as iS}from"node:fs";import{join as Jc}from"node:path";import{parse as lm}from"yaml";function Ki(t){let e=Jc(t,"actions"),r=[],n=[];if(!am(e))return{defs:r,errors:n};let o;try{o=oS(e).sort()}catch{return{defs:r,errors:n}}let i=new Set;for(let s of o){if(!/\.(yml|yaml)$/i.test(s))continue;let a=Jc(e,s);try{if(!iS(a).isFile())continue;let c=Za(s,lm(cm(a,"utf-8")));if(i.has(c.id))throw new Error(`duplicate action id "${c.id}"`);i.add(c.id),r.push(c)}catch(c){n.push({file:`actions/${s}`,error:c instanceof Error?c.message:String(c)})}}return{defs:r,errors:n}}function um(t){let e={},r=Jc(t,"project.yaml");if(!am(r))return e;let n;try{n=lm(cm(r,"utf-8"))}catch{return e}if(!n||typeof n!="object")return e;let o=n.variables;if(!o||typeof o!="object"||Array.isArray(o))return e;for(let[i,s]of Object.entries(o))!rt.test(i)||Ht(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var Hi=class{constructor(e,r,n,o,i=6e4){this.contextDir=e;this.projectId=r;this.send=n;this.log=o;this.intervalMs=i}timer=null;watchers=[];debounce=null;started=!1;start(){this.started||(this.started=!0,this.report(),this.timer=setInterval(()=>this.report(),this.intervalMs),this.timer.unref?.(),this.installWatcher())}stop(){this.started=!1,this.timer&&clearInterval(this.timer),this.timer=null,this.debounce&&clearTimeout(this.debounce),this.debounce=null;for(let e of this.watchers)try{e.close()}catch{}this.watchers=[]}installWatcher(){let e=()=>{this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>this.report(),500),this.debounce.unref?.()},r=[this.contextDir,Ao(this.contextDir,"prompts"),Ao(this.contextDir,"actions")];for(let n of r)if(Zc(n))try{let o=aS(n,e);o.on("error",i=>{this.log.warn(`[config] fs.watch failed on ${n} \u2014 falling back to periodic reporting: ${i instanceof Error?i.message:String(i)}`);try{o.close()}catch{}}),this.watchers.push(o)}catch{}}reportNow(){this.report()}report(){try{this.send(this.read())}catch(e){this.log.warn(`[config] report failed: ${e instanceof Error?e.message:String(e)}`)}}read(){let e=Ki(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=Ao(this.contextDir,e);if(!Zc(r))return null;try{return dm(r,"utf-8")}catch{return null}}readPrompts(){let e=Ao(this.contextDir,"prompts"),r={};if(!Zc(e))return r;let n;try{n=sS(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=dm(Ao(e,o),"utf-8")}catch{}}return r}};mt();import{existsSync as sl,readFileSync as wm,readdirSync as kS}from"node:fs";import{join as bm}from"node:path";import{simpleGit as vS}from"simple-git";var $S=/^(\d{4})-(.+)\.md$/,xS="0000-template.md";function SS(t){let e=t.split(`
1041
- `),r=e.find(i=>i.startsWith("# ")),n=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",o=i=>{let s=new RegExp(`^-\\s*\\*\\*${i}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=s.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:n,status:o("Status"),date:o("Date")}}function ES(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
1033
+ The token is shown ONCE \u2014 copy it right away.`);;){let n=le(await ke({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:i=>!i||!i.trim()||i.includes("@")?void 0:"must be an email"})).trim();if(!n)return;let o=le(await mi({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){P.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await fa("Bitbucket",async()=>{let i=await nr(n,o,t);if(t&&r){let s=await Bi(n,o,t,r);if(s)throw new Error(s)}return i}))return{email:n,apiToken:o};P.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function m_(){for(;;){let t=le(await mi({message:`GitLab PAT \u2014 blank to skip
1034
+ scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await fa("GitLab",()=>or(t))){let e=await Sf(t);return e&&P.warn(e),{token:t}}P.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function h_(){let t="__other__",e=async()=>le(await ke({message:"language name (in English, e.g. Ukrainian)",validate:s=>{let a=s.trim();if(a.length===0)return"required";if(a.length>40)return`\u2264 ${40} chars`}})).trim(),r=be(await wt({message:"project language",options:[...gn.map(s=>({value:s,label:s==="English"?"English (default)":s})),{value:t,label:"other\u2026"}],initialValue:"English"})),n=r===t?await e():r;if(n==="English")return{primary:n,context:n,tasks:n,docs:n,code_comments:n,chat:we};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:we}],i={primary:n};for(let s of o){let a=new Set,c=[s.initial,n,"English",we].filter(u=>a.has(u)?!1:(a.add(u),!0)).map(u=>({value:u,label:u===we?"auto \u2014 mirror the language of the user's material":u}));c.push({value:t,label:"other\u2026"});let l=be(await wt({message:`language for ${s.label}`,options:c,initialValue:s.initial}));i[s.key]=l===t?await e():l}return i}async function tv(){for(;;){let t=le(await ke({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let n=r.trim();if(!n)return"required";if(!n.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=le(await mi({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await fa("YouTrack",()=>ar({baseUrl:t,token:e}))){let r=await Df({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}P.warn("re-enter the YouTrack URL / token.")}}var Dk,pi=x(()=>{"use strict";Ye();M();gt();Jb();Gi();Ve();Xt();Fr();Cn();ci();ru();ra();Vt();Ur();ck();Le();dk();mk();Dl();rs();me();oa();os();Ju();Zu();_k();zi();xt();Dk=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});M();Ye();Ve();import{Command as vj}from"commander";Ve();me();async function gf(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=St(e);r&&!t.force&&(console.error(`already configured at ${xn(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");Yt({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...X(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};ce(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${xn(e)}`)}Oc();Ve();import{homedir as ou}from"node:os";import{join as Qo}from"node:path";Ye();M();import{existsSync as $y,rmSync as _T}from"node:fs";import{join as Wr}from"node:path";import{simpleGit as jT}from"simple-git";import"ws";Ye();me();import{createHash as Tx}from"node:crypto";import{existsSync as Ix,readFileSync as Cx}from"node:fs";import{homedir as Px,hostname as Lc}from"node:os";import{join as Ax}from"node:path";function kf(t){return Tx("sha256").update(t).digest("hex").slice(0,12)}function _x(){let t=ee("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=Ax(Px(),".claude","credentials.json");if(!Ix(e))return;let r=JSON.parse(Cx(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 vf(t){let e=_x(),r=ee("ACCOUNT_ID")?.trim(),n=ee("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=En(t);return o?{accountId:`acct-${kf(o)}`,label:n||Lc(),...e?{email:e}:{}}:{accountId:`acct-${kf(`host:${Lc()}`)}`,label:n||Lc(),...e?{email:e}:{}}}Ye();Cn();me();Xc();async function sm(t,e,r,n,o){let i=c=>{e.readyState===e.OPEN&&e.send(JSON.stringify(c))},s=c=>i({type:"agent_login_url",requestId:r.requestId,projectId:t.projectId,error:c});if(ee("ORIGIN")==="farm"||ee("CLAUDE_AUTOLOGIN")!=="1"){s("autologin_disabled");return}let a;try{a=await zc(Fi())}catch(c){s(`listener failed: ${c instanceof Error?c.message:String(c)}`);return}i({type:"agent_login_url",requestId:r.requestId,projectId:t.projectId,authUrl:a.authUrl}),n.info(`[agent-auth] authorize Claude in a browser on THIS machine: ${a.authUrl}`),n.info(`[agent-auth] waiting for the redirect on ${a.redirectUri} \u2026`);try{let c=await a.waitForToken(),l=await zt(c.oauthToken);if(l==="invalid"){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"token rejected (401) \u2014 previous token kept"}),n.warn("[agent-auth] new Claude token rejected (401) \u2014 previous token kept");return}let u=X(t.projectId);if(!u){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"no secrets file for this project on the CLI"}),n.warn("[agent-auth] no secrets file for this project \u2014 token not saved");return}u.claude={oauthToken:c.oauthToken},ce(u),n.info(`[agent-auth] Claude token replaced (${c.oauthToken.slice(0,12)}\u2026, ${c.oauthToken.length} chars)`),i({type:"agent_login_result",projectId:t.projectId,ok:!0,...l==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}}),o()}catch(c){let l=c instanceof Error?c.message:String(c);i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:l}),n.warn(`[agent-auth] browser authorization failed: ${l}`)}finally{a.close()}}Ye();function am(t,e){let r=t.find(n=>n.kind==="claude");return r?.present===!0&&r.ok===!1?ee("ORIGIN")==="farm"||ee("CLAUDE_AUTOLOGIN")!=="1"||e?"none":"open":r?.ok===!0?"rearm":"none"}function cm(t,e){return`${t.replace(/\/$/,"")}/?project=${encodeURIComponent(e)}`}Gi();import{existsSync as oS}from"node:fs";import{join as iS}from"node:path";import{simpleGit as sS}from"simple-git";async function lm(t,e){if(!oS(iS(t,".git")))return{status:"skipped"};let r=sS(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${aS(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 aS(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as Zc,readFileSync as mm,readdirSync as uS,watch as dS}from"node:fs";import{join as _o}from"node:path";M();import{existsSync as um,readFileSync as dm,readdirSync as cS,statSync as lS}from"node:fs";import{join as Jc}from"node:path";import{parse as pm}from"yaml";function Ki(t){let e=Jc(t,"actions"),r=[],n=[];if(!um(e))return{defs:r,errors:n};let o;try{o=cS(e).sort()}catch{return{defs:r,errors:n}}let i=new Set;for(let s of o){if(!/\.(yml|yaml)$/i.test(s))continue;let a=Jc(e,s);try{if(!lS(a).isFile())continue;let c=Za(s,pm(dm(a,"utf-8")));if(i.has(c.id))throw new Error(`duplicate action id "${c.id}"`);i.add(c.id),r.push(c)}catch(c){n.push({file:`actions/${s}`,error:c instanceof Error?c.message:String(c)})}}return{defs:r,errors:n}}function fm(t){let e={},r=Jc(t,"project.yaml");if(!um(r))return e;let n;try{n=pm(dm(r,"utf-8"))}catch{return e}if(!n||typeof n!="object")return e;let o=n.variables;if(!o||typeof o!="object"||Array.isArray(o))return e;for(let[i,s]of Object.entries(o))!rt.test(i)||Wt(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var Hi=class{constructor(e,r,n,o,i=6e4){this.contextDir=e;this.projectId=r;this.send=n;this.log=o;this.intervalMs=i}timer=null;watchers=[];debounce=null;started=!1;start(){this.started||(this.started=!0,this.report(),this.timer=setInterval(()=>this.report(),this.intervalMs),this.timer.unref?.(),this.installWatcher())}stop(){this.started=!1,this.timer&&clearInterval(this.timer),this.timer=null,this.debounce&&clearTimeout(this.debounce),this.debounce=null;for(let e of this.watchers)try{e.close()}catch{}this.watchers=[]}installWatcher(){let e=()=>{this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>this.report(),500),this.debounce.unref?.()},r=[this.contextDir,_o(this.contextDir,"prompts"),_o(this.contextDir,"actions")];for(let n of r)if(Zc(n))try{let o=dS(n,e);o.on("error",i=>{this.log.warn(`[config] fs.watch failed on ${n} \u2014 falling back to periodic reporting: ${i instanceof Error?i.message:String(i)}`);try{o.close()}catch{}}),this.watchers.push(o)}catch{}}reportNow(){this.report()}report(){try{this.send(this.read())}catch(e){this.log.warn(`[config] report failed: ${e instanceof Error?e.message:String(e)}`)}}read(){let e=Ki(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=_o(this.contextDir,e);if(!Zc(r))return null;try{return mm(r,"utf-8")}catch{return null}}readPrompts(){let e=_o(this.contextDir,"prompts"),r={};if(!Zc(e))return r;let n;try{n=uS(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=mm(_o(e,o),"utf-8")}catch{}}return r}};mt();import{existsSync as sl,readFileSync as vm,readdirSync as SS}from"node:fs";import{join as $m}from"node:path";import{simpleGit as ES}from"simple-git";var RS=/^(\d{4})-(.+)\.md$/,TS="0000-template.md";function IS(t){let e=t.split(`
1035
+ `),r=e.find(i=>i.startsWith("# ")),n=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",o=i=>{let s=new RegExp(`^-\\s*\\*\\*${i}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=s.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:n,status:o("Status"),date:o("Date")}}function CS(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
1042
1036
  `),a=s.findIndex(w=>w.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),u=[],p="",d=null,f=a>=0?a+1:0;for(let w=f;w<s.length;w++){let v=(s[w]??"").trim();if(v===""){f=w+1;continue}let y=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(v);if(!y)break;let k=(y[1]??"").trim().toLowerCase(),C=(y[2]??"").trim(),E=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(v);E&&(d=parseInt(E[1]??"",10)),k==="tasks"&&(p=C),l.has(k)||u.push(v),f=w+1}let m=p?p.includes(n)?p:`${p}, ${n}`:n,g=s.slice(f).join(`
1043
1037
  `).replace(/^\n+/,""),b=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${m}`,...u,"",g].join(`
1044
1038
  `);return{content:b.endsWith(`
1045
1039
  `)?b:b+`
1046
- `,supersedes:d}}function RS(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
1040
+ `,supersedes:d}}function PS(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
1047
1041
 
1048
- - **Status:** superseded by ADR-${r}`):n}function TS(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(`
1042
+ - **Status:** superseded by ADR-${r}`):n}function AS(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(`
1049
1043
  `)+`
1050
- `}async function km(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await vS(t).pull(void 0,void 0,["--rebase"])}catch{}let i=b=>o==="staging"?`adr/DRAFT-${b}.md`:`tasks/${e}/adr/DRAFT-${b}.md`,s=[],a=[];for(let b of r){let w=Re(t,i(b));if(!sl(w)){a.push(b);continue}s.push({slug:b,content:wm(w,"utf-8")})}let c=bm(t,"adr"),l=new Map;if(sl(c))for(let b of kS(c)){let w=$S.exec(b);!w||b===xS||l.set(b,{num:parseInt(w[1]??"",10),slug:w[2]??"",content:wm(bm(c,b),"utf-8")})}let u=Math.max(0,...[...l.values()].map(b=>b.num))+1,p=new Map,d=[],f=[];for(let b of s){if([...l.entries()].find(([,E])=>E.slug===b.slug&&E.content.includes(e))){f.push(b.slug);continue}let v=u++,y=`${String(v).padStart(4,"0")}-${b.slug}.md`,{content:k,supersedes:C}=ES(b.content,v,b.slug,e,n);if(p.set(y,k),l.set(y,{num:v,slug:b.slug,content:k}),d.push(`adr/${y}`),C!==null){let E=[...l.keys()].find($=>$.startsWith(`${String(C).padStart(4,"0")}-`));if(E&&E!==y){let $=RS(p.get(E)??l.get(E).content,v);p.set(E,$),l.set(E,{...l.get(E),content:$})}}}let m=[];if(o==="staging")for(let b of s)sl(Re(t,`adr/DRAFT-${b.slug}.md`))&&m.push({path:`adr/DRAFT-${b.slug}.md`,content:"",deleted:!0});if(d.length===0&&m.length===0)return{promoted:d,skipped:f,missing:a};if(d.length>0){let b=[...l.entries()].map(([w,v])=>({num:v.num,file:w,header:SS(v.content)}));p.set("INDEX.md",TS(b))}for(let[b,w]of p.entries())m.push({path:`adr/${b}`,content:w});let g=d.length>0?`adr(${e}): promote ${s.map(b=>b.slug).join(", ")}`:`adr(${e}): drop stale staged ${f.join(", ")}`;return await Ce(t,m,g),{promoted:d,skipped:f,missing:a}}mt();zi();zt();M();import{existsSync as xm,readFileSync as LS}from"node:fs";import{join as Sm}from"node:path";function MS(t){for(let e of[vt,ln]){let r=Sm(t,e);if(xm(r))try{return Sa(LS(r,"utf-8"))}catch{return 0}}return 0}function DS(t,e,r,n=6){let o=e<n,i=o?Ea(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function Xi(t,e){return DS(e,MS(t),r=>xm(Sm(t,r)))}M();Yt();import{existsSync as Lm,mkdirSync as pE,mkdtempSync as fE,rmSync as Mm,writeFileSync as Dm}from"node:fs";import{tmpdir as mE}from"node:os";import{dirname as hE,join as Zi}from"node:path";import{simpleGit as ul}from"simple-git";Br();function gE(t){return`codepipe/context-migration-v${t}`}function yE(t){let e=Ra(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 \`${vt}\` stamp (renamed from \`${ln}\``,"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(`
1051
- `)}async function Um(t,e,r,n){let o=ul(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Xi(t,e);if(!i.outdated)return i;let s=gE(i.currentVersion),a=r?.branch??(await o.revparse(["--abbrev-ref","HEAD"]).catch(()=>"main")).trim();try{await o.fetch().catch(()=>{}),(await o.raw(["ls-remote","--heads","origin",s]).catch(()=>"")).trim().length===0?await wE(t,e,r,i,s,a,n):n.info(`[ctx] migration branch ${s} already on origin \u2014 reusing`)}catch(l){return n.warn(`[ctx] context migration branch failed (will retry next start): ${l instanceof Error?l.message:String(l)}`),i}if(!r)return i;let c={name:r.name,host:r.host,owner:r.owner,repoName:r.name};try{let l=Mr(c),u=await l.findOpenPrByBranch?.(c,s)??null;if(u)return n.info(`[ctx] migration PR already open: ${u.url}`),{...i,migrationPrUrl:u.url};let p=await l.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:s,baseBranch:a,title:`CodePipe: context format v${i.templateVersion} \u2192 v${i.currentVersion}`,body:yE(i)});return n.info(`[ctx] migration PR opened: ${p.url}`),{...i,migrationPrUrl:p.url}}catch(l){return n.warn(`[ctx] migration PR create/find failed (branch pushed, badge without link): ${l instanceof Error?l.message:String(l)}`),i}}async function wE(t,e,r,n,o,i,s){let a=ul(t),c=fE(Zi(mE(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",o,c,`origin/${i}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},u={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},p=new Map(Nn(l,u).map(g=>[g.path,g.content])),d=0;for(let g of n.missingPaths){if(g===vt)continue;let b=p.get(g);if(b==null){s.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let w=Zi(c,g);Lm(w)||(pE(hE(w),{recursive:!0}),Dm(w,b),d++)}Dm(Zi(c,vt),ho(n.currentVersion)),d++;let f=Zi(c,ln);Lm(f)&&(Mm(f,{force:!0}),d++);let m=ul(c);await m.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await m.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await m.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${d} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),Mm(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{existsSync as bE,readFileSync as kE,writeFileSync as vE}from"node:fs";import{homedir as $E}from"node:os";import{join as Bm}from"node:path";import{parseDocument as xE}from"yaml";function SE(t,e,r){let n={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(n.default_branch=t.defaultBranch),e!==void 0&&(n.mirror=e),r!==void 0&&(n.git=r),n}function EE(t,e){let r=xE(t),n=new Map,o=new Map,i=r.toJS();for(let s of i?.repos??[]){if(!s||typeof s!="object")continue;let a=typeof s.name=="string"?s.name:String(s.repo??"");a&&(s.mirror!==void 0&&s.mirror!==null&&n.set(a,s.mirror),s.git!==void 0&&s.git!==null&&o.set(a,s.git))}return r.set("repos",e.map(s=>SE(s,n.get(s.name),o.get(s.name)))),r.toString()}function RE(t,e){let r=[Bm($E(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(Bm(e,"project.yaml")),r}function Mo(t,e,r){let n=[],o=[];for(let i of RE(t,r))if(bE(i))try{let s=kE(i,"utf-8"),a=EE(s,e);a!==s&&(vE(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}Mn();gt();me();function ME(t,e){let r={};t.github?.token&&(r.github={token:t.github.token}),t.bitbucket?.apiToken&&(r.bitbucket={apiToken:t.bitbucket.apiToken}),t.gitlab?.token&&(r.gitlab={token:t.gitlab.token});let n=e??t.claude?.oauthToken;return n&&(r.claudeOauthToken=n),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),t.mirrorWrite?.token&&(r.mirrorWrite={token:t.mirrorWrite.token,...t.mirrorWrite.host?{host:t.mirrorWrite.host}:{}}),r}function Qm(t,e,r,n){let o=ME(e,r);t.sandboxes.length>0&&!o.claudeOauthToken&&n.warn("[cred] no Claude OAuth token set \u2014 agent jobs will fail in the SANDBOX. Set one with `codepipe login` (per project) or `make farm-config` (shared farm token)."),t.sandboxes.length>0&&!o.contextWrite&&(o.github||o.gitlab||o.bitbucket)&&n.warn("[cred] no dedicated contextWrite token \u2014 SANDBOX pushes deliveries with the project token of the context repo's host (broader scope than necessary). Set secrets.contextWrite.token (a token scoped to the Context Repo only) to tighten. NOTE (GitHub): the push token MUST have the `workflow` scope, else delivery pushes that carry `.github/workflows/*` are rejected.");let i=JSON.stringify(o),s=[];for(let a of t.sandboxes){let c=ji(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=Xt(a.publicKey,i)}catch(u){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}gt();me();Yt();Dr();In();rs();function nh(t){let e=X(t);if(!e)return null;if(!e.sealKey){let r=ts();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},ce(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:ze(e.sealKey.publicKey)}}async function oh(t,e,r,n){let o;try{o=JSON.parse(Dn(n,r).toString("utf-8"))}catch(s){return{ok:!1,detail:`cannot open the sealed credential (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}let i=X(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await tr(o.token);return i.github={token:o.token},Un(i,()=>{process.env.GH_TOKEN=o.token,eh(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await nr(o.token);return i.gitlab={token:o.token},Un(i,()=>{process.env.GITLAB_TOKEN=o.token,th(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"bitbucket":{if(!o.email||!o.apiToken)return{ok:!1,detail:"payload needs email + apiToken"};let s=await rr(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},Un(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,rh(o.apiToken)}),{ok:!0,detail:`authenticated as ${s}`}}case"youtrack":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=o.url?.trim().replace(/\/$/,"")||i.youtrack?.url;if(!s)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await sr({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},Un(i,()=>{process.env.YOUTRACK_URL=s,process.env.YOUTRACK_TOKEN=o.token}),{ok:!0,detail:`authenticated as ${a}`}}case"claude":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Vt(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},Un(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},Un(i,()=>{}),{ok:!0,detail:"saved (verified on the next readiness pass)"}):{ok:!1,detail:"payload has no token"};default:return{ok:!1,detail:`unknown credential kind '${e}'`}}}catch(s){return{ok:!1,detail:`${s instanceof Error?s.message:String(s)} \u2014 previous credential kept`}}}function Un(t,e){ce(t),e()}M();M();import{spawn as DE}from"node:child_process";var UE=124,ih=16*1024,sh=4e3;function BE(t,e,r,n,o,i){let s={...t},a=(c,l)=>{Ht(c)||(s[c]=l)};for(let[c,l]of Object.entries(e))a(c,l);for(let[c,l]of Object.entries(r))a(c,l);for(let[c,l]of Object.entries(n??{}))a(c,l);for(let[c,l]of Object.entries(o))s[c]=l;for(let[c,l]of Object.entries(i))s[`INPUT_${c}`]=String(l);return s}async function ah(t){let{def:e,onEvent:r}=t,n=BE(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
1052
- `,o.length>ih&&(o=o.slice(o.length-ih))},s=(a,c)=>{let l=c.length>sh?c.slice(0,sh)+"\u2026":c;i(l),r({ts:Date.now(),kind:"log",stream:a,text:l})};r({ts:Date.now(),kind:"start",status:"running"});for(let[a,c]of e.steps.entries()){let l=c.name??`step ${a+1}`;r({ts:Date.now(),kind:"step",stepName:l});let u=await FE(c.run,c.timeout_sec,t.cwd,n,s);if(u!==0)return i(`[${l}] exited with code ${u}`),r({ts:Date.now(),kind:"result",status:"failed",exitCode:u,failedStep:l}),{status:"failed",exitCode:u,failedStep:l,logTail:o}}return r({ts:Date.now(),kind:"result",status:"succeeded",exitCode:0}),{status:"succeeded",exitCode:0,logTail:o}}function FE(t,e,r,n,o){return new Promise(i=>{let s=DE("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??Ja)*1e3,l=setTimeout(()=>{a=!0,o("stderr",`step timed out after ${c/1e3}s \u2014 killing`),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},c);l.unref?.();let u=f=>{let m="";return{data:g=>{m+=g.toString("utf-8");let b;for(;(b=m.indexOf(`
1053
- `))!==-1;)o(f,m.slice(0,b).replace(/\r$/,"")),m=m.slice(b+1)},flush:()=>{m.length>0&&o(f,m.replace(/\r$/,"")),m=""}}},p=u("stdout"),d=u("stderr");s.stdout?.on("data",p.data),s.stderr?.on("data",d.data),s.on("error",f=>{clearTimeout(l),o("stderr",`spawn failed: ${f.message}`),i(127)}),s.on("close",(f,m)=>{clearTimeout(l),p.flush(),d.flush(),i(a?UE:f??(m?1:0))})})}mt();mt();import{existsSync as GE,readFileSync as KE,statSync as ch}from"node:fs";var lh=2*1024*1024;function HE(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function uh(t,e){let r=Re(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!GE(r)||!ch(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=ch(r);if(n>lh)throw new Error(`file too large: ${e} is ${n} bytes (limit ${lh})`);let o=KE(r);return HE(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}me();M();import{existsSync as WE,readFileSync as qE,writeFileSync as YE}from"node:fs";import{join as VE}from"node:path";import{parseDocument as zE}from"yaml";async function dh(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=sc(o);if(!i.ok)throw new Error(i.error);let s=r.get(o.file)??[];s.push({path:i.field.path,value:i.value}),r.set(o.file,s)}let n=[];for(let[o,i]of r){let s=VE(t,o);if(!WE(s))throw new Error(`${o} not found in context repo (${t})`);let a=zE(qE(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);YE(s,a.toString()),n.push(o)}return{files:n}}os();import{existsSync as yl,readFileSync as wl,writeFileSync as XE}from"node:fs";import{join as is}from"node:path";import{parseDocument as bl}from"yaml";async function kh(t,e){let r=[];if(e.stageField!==void 0||e.sourceColumns!==void 0||e.rejectColumns!==void 0||e.doneColumns!==void 0||e.reviewColumns!==void 0||e.statusColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0||e.backlogScope!==void 0){let i=is(t,"project.yaml");if(!yl(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=bl(wl(i,"utf-8"));if(e.stageField!==void 0){let a=typeof e.stageField=="string"?e.stageField.trim():"";a&&a!=="Stage"?s.setIn(["youtrack","stage_field"],a):s.deleteIn(["youtrack","stage_field"])}if(e.rejectColumns!==void 0){let a=e.rejectColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","reject_columns"],a):s.deleteIn(["youtrack","reject_columns"])}if(e.doneColumns!==void 0){let a=e.doneColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","done_columns"],a):s.deleteIn(["youtrack","done_columns"])}if(e.reviewColumns!==void 0){let a=e.reviewColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","review_columns"],a):s.deleteIn(["youtrack","review_columns"])}if(e.statusColumns!==void 0){let a=e.statusColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","status_columns"],a):s.deleteIn(["youtrack","status_columns"])}if(e.sourceColumns!==void 0){let a=e.sourceColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);if(a.length===0)throw new Error("source_columns must be a non-empty list of non-empty strings");s.setIn(["youtrack","source_columns"],a)}if(e.backlogColumn!==void 0){let a=typeof e.backlogColumn=="string"?e.backlogColumn.trim():"";a?s.setIn(["youtrack","backlog_column"],a):s.deleteIn(["youtrack","backlog_column"])}if(e.assignee!==void 0){let a=typeof e.assignee=="string"?e.assignee.trim():"";a?s.setIn(["youtrack","assignee"],a):s.deleteIn(["youtrack","assignee"])}e.requireAssignee!==void 0&&s.setIn(["youtrack","require_assignee"],e.requireAssignee===!0),e.backlogScope!==void 0&&(e.backlogScope==="personal"?s.setIn(["youtrack","backlog_scope"],"personal"):e.backlogScope==="shared"?s.setIn(["youtrack","backlog_scope"],"shared"):s.deleteIn(["youtrack","backlog_scope"])),r.push({path:"project.yaml",content:s.toString()})}if(e.reviewStatus!==void 0||e.writes!==void 0){let i=is(t,"regimen.yaml");if(!yl(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=bl(wl(i,"utf-8"));if(e.reviewStatus!==void 0){let a=e.reviewStatus.trim();a&&s.setIn(["youtrack","review_status"],a)}if(e.writes!==void 0){let a=e.writes;s.setIn(["youtrack","writes","enabled"],a.enabled===!0),s.setIn(["youtrack","writes","status_changes"],a.statusChanges===!0),s.setIn(["youtrack","writes","pr_comment"],a.prComment===!0),s.setIn(["youtrack","writes","dashboard_mirror"],a.dashboardMirror===!0)}r.push({path:"regimen.yaml",content:s.toString()})}if(r.length===0)return{files:[]};for(let i of r)XE(is(t,i.path),i.content);return{files:r.map(i=>i.path)}}function ss(t){if(!t)return"Stage";try{let e=is(t,"project.yaml");if(!yl(e))return"Stage";let n=bl(wl(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}Yt();Qi();Mn();M();mt();import{existsSync as bR,readFileSync as kR}from"node:fs";import{join as dg}from"node:path";import{simpleGit as jl}from"simple-git";M();import{existsSync as vh,readFileSync as $h,readdirSync as JE}from"node:fs";import{join as kl}from"node:path";import{simpleGit as ZE}from"simple-git";function QE(t,e){let r=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/.exec(e);if(!r)return null;let n="",o="";for(let s of r[1].split(`
1054
- `)){let a=/^(\w+):\s*(.+)$/.exec(s.trim());a&&(a[1]==="repo"&&(n=a[2].trim()),a[1]==="path"&&(o=a[2].trim().replace(/^\.\//,"")))}let i=r[2].trim();return!n||!o||!i||o.includes("..")||o.startsWith("/")?null:{repo:n,path:o,body:i,source:t}}function eR(t,e){let r=kl(t,`tasks/${e}/annotations`);if(!vh(r))return[];let n=[];for(let o of JE(r).sort())if(o.endsWith(".md")){try{let i=QE(o,$h(kl(r,o),"utf-8"));i&&n.push(i)}catch{}if(n.length>=Oa)break}return n}var tR=12;async function xh(t){let{contextDir:e,taskKey:r,repoName:n,repoDir:o,commitSha:i,date:s,touchedKeys:a,identity:c}=t;if(!c)return[];let l=new Map(c.entities.filter(d=>d.status==="active").map(d=>[d.currentKey,d.entityId])),u=ZE(o),p=[];for(let d of eR(e,r)){if(d.repo!==n)continue;let f=ye("code",n,d.path);if(!a.has(f))continue;let m=l.get(f);if(!m)continue;let g=(await u.raw(["rev-parse",`${i}:${d.path}`]).catch(()=>"")).trim().slice(0,tR),b=Ca(m),w=kl(e,b),v=p.find(A=>A.path===b),y=v?.content??(vh(w)?$h(w,"utf-8"):null),k=`<!-- ${r}${g?`:${g}`:""} -->`;if(y?.includes(k))continue;let C=y??`---
1044
+ `}async function xm(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await ES(t).pull(void 0,void 0,["--rebase"])}catch{}let i=b=>o==="staging"?`adr/DRAFT-${b}.md`:`tasks/${e}/adr/DRAFT-${b}.md`,s=[],a=[];for(let b of r){let w=Re(t,i(b));if(!sl(w)){a.push(b);continue}s.push({slug:b,content:vm(w,"utf-8")})}let c=$m(t,"adr"),l=new Map;if(sl(c))for(let b of SS(c)){let w=RS.exec(b);!w||b===TS||l.set(b,{num:parseInt(w[1]??"",10),slug:w[2]??"",content:vm($m(c,b),"utf-8")})}let u=Math.max(0,...[...l.values()].map(b=>b.num))+1,p=new Map,d=[],f=[];for(let b of s){if([...l.entries()].find(([,E])=>E.slug===b.slug&&E.content.includes(e))){f.push(b.slug);continue}let v=u++,y=`${String(v).padStart(4,"0")}-${b.slug}.md`,{content:k,supersedes:C}=CS(b.content,v,b.slug,e,n);if(p.set(y,k),l.set(y,{num:v,slug:b.slug,content:k}),d.push(`adr/${y}`),C!==null){let E=[...l.keys()].find($=>$.startsWith(`${String(C).padStart(4,"0")}-`));if(E&&E!==y){let $=PS(p.get(E)??l.get(E).content,v);p.set(E,$),l.set(E,{...l.get(E),content:$})}}}let m=[];if(o==="staging")for(let b of s)sl(Re(t,`adr/DRAFT-${b.slug}.md`))&&m.push({path:`adr/DRAFT-${b.slug}.md`,content:"",deleted:!0});if(d.length===0&&m.length===0)return{promoted:d,skipped:f,missing:a};if(d.length>0){let b=[...l.entries()].map(([w,v])=>({num:v.num,file:w,header:IS(v.content)}));p.set("INDEX.md",AS(b))}for(let[b,w]of p.entries())m.push({path:`adr/${b}`,content:w});let g=d.length>0?`adr(${e}): promote ${s.map(b=>b.slug).join(", ")}`:`adr(${e}): drop stale staged ${f.join(", ")}`;return await Ce(t,m,g),{promoted:d,skipped:f,missing:a}}mt();zi();Xt();M();import{existsSync as Rm,readFileSync as BS}from"node:fs";import{join as Tm}from"node:path";function FS(t){for(let e of[vt,un]){let r=Tm(t,e);if(Rm(r))try{return Sa(BS(r,"utf-8"))}catch{return 0}}return 0}function GS(t,e,r,n=6){let o=e<n,i=o?Ea(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function Xi(t,e){return GS(e,FS(t),r=>Rm(Tm(t,r)))}M();Vt();import{existsSync as Um,mkdirSync as gE,mkdtempSync as yE,rmSync as Bm,writeFileSync as Fm}from"node:fs";import{tmpdir as wE}from"node:os";import{dirname as bE,join as Zi}from"node:path";import{simpleGit as ul}from"simple-git";Fr();function kE(t){return`codepipe/context-migration-v${t}`}function vE(t){let e=Ra(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 \`${vt}\` stamp (renamed from \`${un}\``,"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(`
1045
+ `)}async function Gm(t,e,r,n){let o=ul(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Xi(t,e);if(!i.outdated)return i;let s=kE(i.currentVersion),a=r?.branch??(await o.revparse(["--abbrev-ref","HEAD"]).catch(()=>"main")).trim();try{await o.fetch().catch(()=>{}),(await o.raw(["ls-remote","--heads","origin",s]).catch(()=>"")).trim().length===0?await $E(t,e,r,i,s,a,n):n.info(`[ctx] migration branch ${s} already on origin \u2014 reusing`)}catch(l){return n.warn(`[ctx] context migration branch failed (will retry next start): ${l instanceof Error?l.message:String(l)}`),i}if(!r)return i;let c={name:r.name,host:r.host,owner:r.owner,repoName:r.name};try{let l=Dr(c),u=await l.findOpenPrByBranch?.(c,s)??null;if(u)return n.info(`[ctx] migration PR already open: ${u.url}`),{...i,migrationPrUrl:u.url};let p=await l.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:s,baseBranch:a,title:`CodePipe: context format v${i.templateVersion} \u2192 v${i.currentVersion}`,body:vE(i)});return n.info(`[ctx] migration PR opened: ${p.url}`),{...i,migrationPrUrl:p.url}}catch(l){return n.warn(`[ctx] migration PR create/find failed (branch pushed, badge without link): ${l instanceof Error?l.message:String(l)}`),i}}async function $E(t,e,r,n,o,i,s){let a=ul(t),c=yE(Zi(wE(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",o,c,`origin/${i}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},u={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},p=new Map(On(l,u).map(g=>[g.path,g.content])),d=0;for(let g of n.missingPaths){if(g===vt)continue;let b=p.get(g);if(b==null){s.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let w=Zi(c,g);Um(w)||(gE(bE(w),{recursive:!0}),Fm(w,b),d++)}Fm(Zi(c,vt),go(n.currentVersion)),d++;let f=Zi(c,un);Um(f)&&(Bm(f,{force:!0}),d++);let m=ul(c);await m.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await m.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await m.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${d} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),Bm(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{existsSync as xE,readFileSync as SE,writeFileSync as EE}from"node:fs";import{homedir as RE}from"node:os";import{join as Km}from"node:path";import{parseDocument as TE}from"yaml";function IE(t,e,r){let n={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(n.default_branch=t.defaultBranch),e!==void 0&&(n.mirror=e),r!==void 0&&(n.git=r),n}function CE(t,e){let r=TE(t),n=new Map,o=new Map,i=r.toJS();for(let s of i?.repos??[]){if(!s||typeof s!="object")continue;let a=typeof s.name=="string"?s.name:String(s.repo??"");a&&(s.mirror!==void 0&&s.mirror!==null&&n.set(a,s.mirror),s.git!==void 0&&s.git!==null&&o.set(a,s.git))}return r.set("repos",e.map(s=>IE(s,n.get(s.name),o.get(s.name)))),r.toString()}function PE(t,e){let r=[Km(RE(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(Km(e,"project.yaml")),r}function Do(t,e,r){let n=[],o=[];for(let i of PE(t,r))if(xE(i))try{let s=SE(i,"utf-8"),a=CE(s,e);a!==s&&(EE(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}Dn();gt();me();function FE(t,e){let r={};t.github?.token&&(r.github={token:t.github.token}),t.bitbucket?.apiToken&&(r.bitbucket={apiToken:t.bitbucket.apiToken}),t.gitlab?.token&&(r.gitlab={token:t.gitlab.token});let n=e??t.claude?.oauthToken;return n&&(r.claudeOauthToken=n),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),t.mirrorWrite?.token&&(r.mirrorWrite={token:t.mirrorWrite.token,...t.mirrorWrite.host?{host:t.mirrorWrite.host}:{}}),r}function rh(t,e,r,n){let o=FE(e,r);t.sandboxes.length>0&&!o.claudeOauthToken&&n.warn("[cred] no Claude OAuth token set \u2014 agent jobs will fail in the SANDBOX. Set one with `codepipe login` (per project) or `make farm-config` (shared farm token)."),t.sandboxes.length>0&&!o.contextWrite&&(o.github||o.gitlab||o.bitbucket)&&n.warn("[cred] no dedicated contextWrite token \u2014 SANDBOX pushes deliveries with the project token of the context repo's host (broader scope than necessary). Set secrets.contextWrite.token (a token scoped to the Context Repo only) to tighten. NOTE (GitHub): the push token MUST have the `workflow` scope, else delivery pushes that carry `.github/workflows/*` are rejected.");let i=JSON.stringify(o),s=[];for(let a of t.sandboxes){let c=ji(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=Jt(a.publicKey,i)}catch(u){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}gt();me();Vt();Ur();Cn();rs();function sh(t){let e=X(t);if(!e)return null;if(!e.sealKey){let r=ts();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},ce(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:ze(e.sealKey.publicKey)}}async function ah(t,e,r,n){let o;try{o=JSON.parse(Un(n,r).toString("utf-8"))}catch(s){return{ok:!1,detail:`cannot open the sealed credential (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}let i=X(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await rr(o.token);return i.github={token:o.token},Bn(i,()=>{process.env.GH_TOKEN=o.token,nh(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await or(o.token);return i.gitlab={token:o.token},Bn(i,()=>{process.env.GITLAB_TOKEN=o.token,oh(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"bitbucket":{if(!o.email||!o.apiToken)return{ok:!1,detail:"payload needs email + apiToken"};let s=await nr(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},Bn(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,ih(o.apiToken)}),{ok:!0,detail:`authenticated as ${s}`}}case"youtrack":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=o.url?.trim().replace(/\/$/,"")||i.youtrack?.url;if(!s)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await ar({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},Bn(i,()=>{process.env.YOUTRACK_URL=s,process.env.YOUTRACK_TOKEN=o.token}),{ok:!0,detail:`authenticated as ${a}`}}case"claude":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await zt(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},Bn(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},Bn(i,()=>{}),{ok:!0,detail:"saved (verified on the next readiness pass)"}):{ok:!1,detail:"payload has no token"};default:return{ok:!1,detail:`unknown credential kind '${e}'`}}}catch(s){return{ok:!1,detail:`${s instanceof Error?s.message:String(s)} \u2014 previous credential kept`}}}function Bn(t,e){ce(t),e()}M();M();import{spawn as GE}from"node:child_process";var KE=124,ch=16*1024,lh=4e3;function HE(t,e,r,n,o,i){let s={...t},a=(c,l)=>{Wt(c)||(s[c]=l)};for(let[c,l]of Object.entries(e))a(c,l);for(let[c,l]of Object.entries(r))a(c,l);for(let[c,l]of Object.entries(n??{}))a(c,l);for(let[c,l]of Object.entries(o))s[c]=l;for(let[c,l]of Object.entries(i))s[`INPUT_${c}`]=String(l);return s}async function uh(t){let{def:e,onEvent:r}=t,n=HE(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
1046
+ `,o.length>ch&&(o=o.slice(o.length-ch))},s=(a,c)=>{let l=c.length>lh?c.slice(0,lh)+"\u2026":c;i(l),r({ts:Date.now(),kind:"log",stream:a,text:l})};r({ts:Date.now(),kind:"start",status:"running"});for(let[a,c]of e.steps.entries()){let l=c.name??`step ${a+1}`;r({ts:Date.now(),kind:"step",stepName:l});let u=await WE(c.run,c.timeout_sec,t.cwd,n,s);if(u!==0)return i(`[${l}] exited with code ${u}`),r({ts:Date.now(),kind:"result",status:"failed",exitCode:u,failedStep:l}),{status:"failed",exitCode:u,failedStep:l,logTail:o}}return r({ts:Date.now(),kind:"result",status:"succeeded",exitCode:0}),{status:"succeeded",exitCode:0,logTail:o}}function WE(t,e,r,n,o){return new Promise(i=>{let s=GE("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??Ja)*1e3,l=setTimeout(()=>{a=!0,o("stderr",`step timed out after ${c/1e3}s \u2014 killing`),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},c);l.unref?.();let u=f=>{let m="";return{data:g=>{m+=g.toString("utf-8");let b;for(;(b=m.indexOf(`
1047
+ `))!==-1;)o(f,m.slice(0,b).replace(/\r$/,"")),m=m.slice(b+1)},flush:()=>{m.length>0&&o(f,m.replace(/\r$/,"")),m=""}}},p=u("stdout"),d=u("stderr");s.stdout?.on("data",p.data),s.stderr?.on("data",d.data),s.on("error",f=>{clearTimeout(l),o("stderr",`spawn failed: ${f.message}`),i(127)}),s.on("close",(f,m)=>{clearTimeout(l),p.flush(),d.flush(),i(a?KE:f??(m?1:0))})})}mt();mt();import{existsSync as qE,readFileSync as YE,statSync as dh}from"node:fs";var ph=2*1024*1024;function VE(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function fh(t,e){let r=Re(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!qE(r)||!dh(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=dh(r);if(n>ph)throw new Error(`file too large: ${e} is ${n} bytes (limit ${ph})`);let o=YE(r);return VE(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}me();M();import{existsSync as zE,readFileSync as XE,writeFileSync as JE}from"node:fs";import{join as ZE}from"node:path";import{parseDocument as QE}from"yaml";async function mh(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=sc(o);if(!i.ok)throw new Error(i.error);let s=r.get(o.file)??[];s.push({path:i.field.path,value:i.value}),r.set(o.file,s)}let n=[];for(let[o,i]of r){let s=ZE(t,o);if(!zE(s))throw new Error(`${o} not found in context repo (${t})`);let a=QE(XE(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);JE(s,a.toString()),n.push(o)}return{files:n}}os();import{existsSync as yl,readFileSync as wl,writeFileSync as eR}from"node:fs";import{join as is}from"node:path";import{parseDocument as bl}from"yaml";async function xh(t,e){let r=[];if(e.stageField!==void 0||e.sourceColumns!==void 0||e.rejectColumns!==void 0||e.doneColumns!==void 0||e.reviewColumns!==void 0||e.statusColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0||e.backlogScope!==void 0){let i=is(t,"project.yaml");if(!yl(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=bl(wl(i,"utf-8"));if(e.stageField!==void 0){let a=typeof e.stageField=="string"?e.stageField.trim():"";a&&a!=="Stage"?s.setIn(["youtrack","stage_field"],a):s.deleteIn(["youtrack","stage_field"])}if(e.rejectColumns!==void 0){let a=e.rejectColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","reject_columns"],a):s.deleteIn(["youtrack","reject_columns"])}if(e.doneColumns!==void 0){let a=e.doneColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","done_columns"],a):s.deleteIn(["youtrack","done_columns"])}if(e.reviewColumns!==void 0){let a=e.reviewColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","review_columns"],a):s.deleteIn(["youtrack","review_columns"])}if(e.statusColumns!==void 0){let a=e.statusColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","status_columns"],a):s.deleteIn(["youtrack","status_columns"])}if(e.sourceColumns!==void 0){let a=e.sourceColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);if(a.length===0)throw new Error("source_columns must be a non-empty list of non-empty strings");s.setIn(["youtrack","source_columns"],a)}if(e.backlogColumn!==void 0){let a=typeof e.backlogColumn=="string"?e.backlogColumn.trim():"";a?s.setIn(["youtrack","backlog_column"],a):s.deleteIn(["youtrack","backlog_column"])}if(e.assignee!==void 0){let a=typeof e.assignee=="string"?e.assignee.trim():"";a?s.setIn(["youtrack","assignee"],a):s.deleteIn(["youtrack","assignee"])}e.requireAssignee!==void 0&&s.setIn(["youtrack","require_assignee"],e.requireAssignee===!0),e.backlogScope!==void 0&&(e.backlogScope==="personal"?s.setIn(["youtrack","backlog_scope"],"personal"):e.backlogScope==="shared"?s.setIn(["youtrack","backlog_scope"],"shared"):s.deleteIn(["youtrack","backlog_scope"])),r.push({path:"project.yaml",content:s.toString()})}if(e.reviewStatus!==void 0||e.writes!==void 0){let i=is(t,"regimen.yaml");if(!yl(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=bl(wl(i,"utf-8"));if(e.reviewStatus!==void 0){let a=e.reviewStatus.trim();a&&s.setIn(["youtrack","review_status"],a)}if(e.writes!==void 0){let a=e.writes;s.setIn(["youtrack","writes","enabled"],a.enabled===!0),s.setIn(["youtrack","writes","status_changes"],a.statusChanges===!0),s.setIn(["youtrack","writes","pr_comment"],a.prComment===!0),s.setIn(["youtrack","writes","dashboard_mirror"],a.dashboardMirror===!0)}r.push({path:"regimen.yaml",content:s.toString()})}if(r.length===0)return{files:[]};for(let i of r)eR(is(t,i.path),i.content);return{files:r.map(i=>i.path)}}function ss(t){if(!t)return"Stage";try{let e=is(t,"project.yaml");if(!yl(e))return"Stage";let n=bl(wl(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}Vt();Qi();Dn();M();mt();import{existsSync as xR,readFileSync as SR}from"node:fs";import{join as mg}from"node:path";import{simpleGit as jl}from"simple-git";M();import{existsSync as Sh,readFileSync as Eh,readdirSync as tR}from"node:fs";import{join as kl}from"node:path";import{simpleGit as rR}from"simple-git";function nR(t,e){let r=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/.exec(e);if(!r)return null;let n="",o="";for(let s of r[1].split(`
1048
+ `)){let a=/^(\w+):\s*(.+)$/.exec(s.trim());a&&(a[1]==="repo"&&(n=a[2].trim()),a[1]==="path"&&(o=a[2].trim().replace(/^\.\//,"")))}let i=r[2].trim();return!n||!o||!i||o.includes("..")||o.startsWith("/")?null:{repo:n,path:o,body:i,source:t}}function oR(t,e){let r=kl(t,`tasks/${e}/annotations`);if(!Sh(r))return[];let n=[];for(let o of tR(r).sort())if(o.endsWith(".md")){try{let i=nR(o,Eh(kl(r,o),"utf-8"));i&&n.push(i)}catch{}if(n.length>=Oa)break}return n}var iR=12;async function Rh(t){let{contextDir:e,taskKey:r,repoName:n,repoDir:o,commitSha:i,date:s,touchedKeys:a,identity:c}=t;if(!c)return[];let l=new Map(c.entities.filter(d=>d.status==="active").map(d=>[d.currentKey,d.entityId])),u=rR(o),p=[];for(let d of oR(e,r)){if(d.repo!==n)continue;let f=ye("code",n,d.path);if(!a.has(f))continue;let m=l.get(f);if(!m)continue;let g=(await u.raw(["rev-parse",`${i}:${d.path}`]).catch(()=>"")).trim().slice(0,iR),b=Ca(m),w=kl(e,b),v=p.find(A=>A.path===b),y=v?.content??(Sh(w)?Eh(w,"utf-8"):null),k=`<!-- ${r}${g?`:${g}`:""} -->`;if(y?.includes(k))continue;let C=y??`---
1055
1049
  entityId: ${m}
1056
1050
  ---
1057
1051
 
@@ -1059,35 +1053,35 @@ entityId: ${m}
1059
1053
 
1060
1054
  Append-only. Keyed by entityId \u2014 never by path; entries survive renames.
1061
1055
  `,E=["",`## ${s} \u2014 ${r}`,k,"",d.body,""].join(`
1062
- `),$=C+E;v?v.content=$:p.push({path:b,content:$})}return p}Rl();Cl();ls();Al();Go();async function vR(t,e){let n=await jl(t).raw(["diff","--numstat",`${e}^`,e]).catch(()=>""),o=[];for(let i of n.split(`
1063
- `)){let s=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(i);if(!s)continue;let a=s[1]==="-"?0:Number(s[1]),c=s[2]==="-"?0:Number(s[2]);o.push({path:s[3],churn:a+c})}return o}function $R(t,e){let n=[`tasks/${e}/PLAN.md`,`tasks/${e}/SOLUTION.md`].find(i=>bR(dg(t,i)));if(!n)return{};let o=dg(t,n);try{let i=kR(o,"utf-8"),s=[...new Set(i.match(/\bADR-\d{3,4}\b/g)??[])].sort();return{solution:n,...s.length>0?{adr:s}:{}}}catch{return{solution:n}}}async function pg(t){let{contextDir:e,repoDir:r,repoName:n,taskKey:o,commitSha:i}=t,s=Gr(e),a=Fr([...s.ignore,...Bn]),c=await vR(r,i),l=(await jl(r).raw(["show","-s","--format=%cs",i])).trim(),u=null,p=new Map;try{u=Tl(e,n),u&&(p=new Map(u.entities.filter(C=>C.status==="active").map(C=>[C.currentKey,C.entityId])))}catch{}let d=[];for(let C of c){if(a(C.path))continue;let E=ye("code",n,C.path),$=p.get(E);d.push({key:E,...$?{entityId:$}:{},churn:C.churn})}if(d.length===0)return{recorded:!1};let f=$R(e,o),m=as(e,o),g=m?.origin==="pipeline"?m.files.filter(C=>ne(C.key)?.repo!==n):[],b=m?.origin==="pipeline"?m.commits:[],w={modelFormatVersion:2,taskKey:o,origin:"pipeline",...m?.title?{title:m.title}:{},...l?{date:l}:{},commits:[...new Set([...b,i])],files:[...g,...d],links:{...m?.origin==="pipeline"?m.links:{},...f}};w.links&&Object.keys(w.links).length===0&&delete w.links;let v=[...ds(e).filter(C=>C.taskKey!==o),w],y=ig(sg(e),v,o,s.cochange.halfLifeDays),k=await xh({contextDir:e,taskKey:o,repoName:n,repoDir:r,commitSha:i,date:l,touchedKeys:new Set(d.map(C=>C.key)),identity:u}).catch(()=>[]);await Ce(e,[{path:Ir(o),content:dn(w)},{path:Tr,content:ps(y)},...k],`model: task event ${o}`);{let{rebuildSearchIndex:C}=await Promise.resolve().then(()=>(Ho(),Ko));await C(e).catch(()=>{})}return{recorded:!0}}async function fg(t){let e=new Set([t.fallbackTaskKey]);try{let r=jl(t.repoDir),n=(await r.raw(["rev-parse","--verify",`origin/${t.baseBranch}`]).catch(()=>r.raw(["rev-parse","--verify",t.baseBranch]))).trim(),o=await r.raw(["log","--format=%(trailers:key=CodePipe-Task,valueonly)",`${n}..${t.branchName}`]);for(let i of o.split(`
1064
- `)){let s=i.trim();s&&e.add(s)}}catch{}for(let r of[...e].sort())await xR(t.contextDir,r,t.prUrl)}async function xR(t,e,r){let n=as(t,e);if(!n||n.origin!=="pipeline"||n.links?.pr===r)return;let o={...n,links:{...n.links??{},pr:r}};await Ce(t,[{path:Ir(e),content:dn(o)}],`model: pr link for ${e}`)}Dr();import{existsSync as gg,readFileSync as yg}from"node:fs";import{join as wg}from"node:path";import{parseDocument as bg}from"yaml";Dr();var Wo=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return qf(this.cfg,e)}getIssue(e,r){return Yf(this.cfg,e,r??ss(this.contextDir))}listComments(e,r){return Vf(this.cfg,e,r)}downloadAttachment(e){return Wf(this.cfg,e)}updateStatus(e,r){return Lf(this.cfg,e,r,ss(this.contextDir))}addComment(e,r,n){return Mf(this.cfg,e,r)}createIssue(e){return Bf(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,ss(this.contextDir))}editIssue(e,r){return Df(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return Ff(this.cfg,e,r,n)}fetchStateFields(e){return Xf(this.cfg,e)}};M();mt();import{existsSync as PR,readFileSync as AR}from"node:fs";import{randomBytes as _R}from"node:crypto";import{existsSync as Nl,readFileSync as SR,readdirSync as ER}from"node:fs";M();mt();function ys(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=CR(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:RR(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:IR(TR(t,i,o.comments))});for(let a of o.attachments)n.push({path:`tasks/${i}/attachments/${a.name}`,content:a.contentBase64,encoding:"base64"})}return n}async function mg(t,e,r,n=10){let o=new Set(e.map(c=>c.issue.key)),i=[],s=c=>(c.links??[]).filter(l=>l.type==="subtask").map(l=>l.targetKey);for(let c of e)i.push(...s(c.issue));let a=[];for(;i.length>0&&a.length<n;){let c=i.shift();if(o.has(c)||(o.add(c),Nl(Re(t,`tasks/${c}/task.md`))))continue;let l=null;try{l=await r(c)}catch{continue}l&&(a.push({issue:l,comments:[],attachments:[]}),i.push(...s(l)))}return a}async function ws(t,e,r){if(r.length===0)return;let n=ys(t,e,r),o=r.map(i=>i.issue.key);await Ce(t,n,`sync(${o.join(", ")}): task data`)}function RR(t,e,r){let n=new Date(t.updatedAt).toISOString(),o=[`# ${t.key}: ${t.title}`,"",`- **Project:** \`${e}\``,`- **Tracker status:** ${t.status||"(unknown)"}`,`- **Assignee:** ${t.assignee??"(unassigned)"}`,`- **Updated:** ${n}`,"","---","",t.description??"_(no description)_",""];if(r.length>0){o.push("## Attachments","");for(let i of r)o.push(`- [${i}](attachments/${encodeURI(i)})`);o.push("")}return o.join(`
1065
- `)}function TR(t,e,r){let n=new Map,o=Re(t,`tasks/${e}/comments.jsonl`);if(Nl(o))for(let i of SR(o,"utf-8").split(`
1066
- `)){let s=i.trim();if(s)try{let a=JSON.parse(s);a&&typeof a.id=="string"&&n.set(a.id,a)}catch{}}for(let i of r){if(n.has(i.id))continue;let s={id:i.id,author:i.author,origin:"youtrack",body:i.body,createdAt:new Date(i.createdAt).toISOString()},a=jr(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function IR(t){return t.map(e=>JSON.stringify(e)).join(`
1056
+ `),$=C+E;v?v.content=$:p.push({path:b,content:$})}return p}Rl();Cl();ls();Al();Ko();async function ER(t,e){let n=await jl(t).raw(["diff","--numstat",`${e}^`,e]).catch(()=>""),o=[];for(let i of n.split(`
1057
+ `)){let s=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(i);if(!s)continue;let a=s[1]==="-"?0:Number(s[1]),c=s[2]==="-"?0:Number(s[2]);o.push({path:s[3],churn:a+c})}return o}function RR(t,e){let n=[`tasks/${e}/PLAN.md`,`tasks/${e}/SOLUTION.md`].find(i=>xR(mg(t,i)));if(!n)return{};let o=mg(t,n);try{let i=SR(o,"utf-8"),s=[...new Set(i.match(/\bADR-\d{3,4}\b/g)??[])].sort();return{solution:n,...s.length>0?{adr:s}:{}}}catch{return{solution:n}}}async function hg(t){let{contextDir:e,repoDir:r,repoName:n,taskKey:o,commitSha:i}=t,s=Kr(e),a=Gr([...s.ignore,...Fn]),c=await ER(r,i),l=(await jl(r).raw(["show","-s","--format=%cs",i])).trim(),u=null,p=new Map;try{u=Tl(e,n),u&&(p=new Map(u.entities.filter(C=>C.status==="active").map(C=>[C.currentKey,C.entityId])))}catch{}let d=[];for(let C of c){if(a(C.path))continue;let E=ye("code",n,C.path),$=p.get(E);d.push({key:E,...$?{entityId:$}:{},churn:C.churn})}if(d.length===0)return{recorded:!1};let f=RR(e,o),m=as(e,o),g=m?.origin==="pipeline"?m.files.filter(C=>ne(C.key)?.repo!==n):[],b=m?.origin==="pipeline"?m.commits:[],w={modelFormatVersion:2,taskKey:o,origin:"pipeline",...m?.title?{title:m.title}:{},...l?{date:l}:{},commits:[...new Set([...b,i])],files:[...g,...d],links:{...m?.origin==="pipeline"?m.links:{},...f}};w.links&&Object.keys(w.links).length===0&&delete w.links;let v=[...ds(e).filter(C=>C.taskKey!==o),w],y=cg(lg(e),v,o,s.cochange.halfLifeDays),k=await Rh({contextDir:e,taskKey:o,repoName:n,repoDir:r,commitSha:i,date:l,touchedKeys:new Set(d.map(C=>C.key)),identity:u}).catch(()=>[]);await Ce(e,[{path:Cr(o),content:pn(w)},{path:Ir,content:ps(y)},...k],`model: task event ${o}`);{let{rebuildSearchIndex:C}=await Promise.resolve().then(()=>(Wo(),Ho));await C(e).catch(()=>{})}return{recorded:!0}}async function gg(t){let e=new Set([t.fallbackTaskKey]);try{let r=jl(t.repoDir),n=(await r.raw(["rev-parse","--verify",`origin/${t.baseBranch}`]).catch(()=>r.raw(["rev-parse","--verify",t.baseBranch]))).trim(),o=await r.raw(["log","--format=%(trailers:key=CodePipe-Task,valueonly)",`${n}..${t.branchName}`]);for(let i of o.split(`
1058
+ `)){let s=i.trim();s&&e.add(s)}}catch{}for(let r of[...e].sort())await TR(t.contextDir,r,t.prUrl)}async function TR(t,e,r){let n=as(t,e);if(!n||n.origin!=="pipeline"||n.links?.pr===r)return;let o={...n,links:{...n.links??{},pr:r}};await Ce(t,[{path:Cr(e),content:pn(o)}],`model: pr link for ${e}`)}Ur();import{existsSync as bg,readFileSync as kg}from"node:fs";import{join as vg}from"node:path";import{parseDocument as $g}from"yaml";Ur();var qo=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return zf(this.cfg,e)}getIssue(e,r){return Xf(this.cfg,e,r??ss(this.contextDir))}listComments(e,r){return Jf(this.cfg,e,r)}downloadAttachment(e){return Vf(this.cfg,e)}updateStatus(e,r){return Uf(this.cfg,e,r,ss(this.contextDir))}addComment(e,r,n){return Bf(this.cfg,e,r)}createIssue(e){return Kf(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,ss(this.contextDir))}editIssue(e,r){return Ff(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return Hf(this.cfg,e,r,n)}fetchStateFields(e){return Qf(this.cfg,e)}};M();mt();import{existsSync as NR,readFileSync as OR}from"node:fs";import{randomBytes as LR}from"node:crypto";import{existsSync as Nl,readFileSync as IR,readdirSync as CR}from"node:fs";M();mt();function ys(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=jR(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:PR(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:_R(AR(t,i,o.comments))});for(let a of o.attachments)n.push({path:`tasks/${i}/attachments/${a.name}`,content:a.contentBase64,encoding:"base64"})}return n}async function yg(t,e,r,n=10){let o=new Set(e.map(c=>c.issue.key)),i=[],s=c=>(c.links??[]).filter(l=>l.type==="subtask").map(l=>l.targetKey);for(let c of e)i.push(...s(c.issue));let a=[];for(;i.length>0&&a.length<n;){let c=i.shift();if(o.has(c)||(o.add(c),Nl(Re(t,`tasks/${c}/task.md`))))continue;let l=null;try{l=await r(c)}catch{continue}l&&(a.push({issue:l,comments:[],attachments:[]}),i.push(...s(l)))}return a}async function ws(t,e,r){if(r.length===0)return;let n=ys(t,e,r),o=r.map(i=>i.issue.key);await Ce(t,n,`sync(${o.join(", ")}): task data`)}function PR(t,e,r){let n=new Date(t.updatedAt).toISOString(),o=[`# ${t.key}: ${t.title}`,"",`- **Project:** \`${e}\``,`- **Tracker status:** ${t.status||"(unknown)"}`,`- **Assignee:** ${t.assignee??"(unassigned)"}`,`- **Updated:** ${n}`,"","---","",t.description??"_(no description)_",""];if(r.length>0){o.push("## Attachments","");for(let i of r)o.push(`- [${i}](attachments/${encodeURI(i)})`);o.push("")}return o.join(`
1059
+ `)}function AR(t,e,r){let n=new Map,o=Re(t,`tasks/${e}/comments.jsonl`);if(Nl(o))for(let i of IR(o,"utf-8").split(`
1060
+ `)){let s=i.trim();if(s)try{let a=JSON.parse(s);a&&typeof a.id=="string"&&n.set(a.id,a)}catch{}}for(let i of r){if(n.has(i.id))continue;let s={id:i.id,author:i.author,origin:"youtrack",body:i.body,createdAt:new Date(i.createdAt).toISOString()},a=Nr(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function _R(t){return t.map(e=>JSON.stringify(e)).join(`
1067
1061
  `)+(t.length>0?`
1068
- `:"")}function CR(t,e,r){let n=[],o=Re(t,`tasks/${e}/attachments`);if(Nl(o))for(let i of ER(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}Ji();var qo=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await No(this.contextDir);let r=e.columns??[];return Am(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>Lo(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=Oo(this.contextDir,e);return r?Lo(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return hg(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 No(this.contextDir),!Oo(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${_R(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=jr(r);s&&(i.parsedCommand=s);let c=[...hg(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
1062
+ `:"")}function jR(t,e,r){let n=[],o=Re(t,`tasks/${e}/attachments`);if(Nl(o))for(let i of CR(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}Ji();var Yo=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await Oo(this.contextDir);let r=e.columns??[];return Nm(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>Mo(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=Lo(this.contextDir,e);return r?Mo(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return wg(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 Oo(this.contextDir),!Lo(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${LR(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=Nr(r);s&&(i.parsedCommand=s);let c=[...wg(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
1069
1063
  `)+`
1070
- `;return await Ce(this.contextDir,[{path:`tasks/${e}/comments.jsonl`,content:c}],`tracker(${e}): comment`),{id:i.id}}async createIssue(e){let r=new Date().toISOString(),n=await _m(this.contextDir,this.config.prefix,o=>this.renderNewIssueFiles(o,e,r),o=>`tracker(${o}): create issue`);return{id:n,key:n}}async editIssue(e,r){await this.mutateRecord(e,n=>({...n,...r.title!==void 0?{title:r.title}:{}}),r.body)}async applyLink(e,r,n){let o=r==="subtask_of"?"subtask":"depends_on";await this.mutateRecord(e,i=>{let s=i.links.filter(a=>!(a.type===o&&a.targetKey===n));return s.push({type:o,targetKey:n}),{...i,links:s}})}async fetchStateFields(e){return[{name:"Status",values:Pi.statusColumns}]}async mutateRecord(e,r,n){let o=Oo(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=Lo(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:bn(e),content:ll(i)},...ys(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await Ce(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:Eo,status:r.targetStatus,links:[],created:n,updated:n},i=Lo(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:bn(e),content:ll(o)},...ys(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}};function hg(t,e){let r=Re(t,`tasks/${e}/comments.jsonl`);if(!PR(r))return[];let n=[];for(let o of AR(r,"utf-8").split(`
1071
- `)){let i=o.trim();if(i)try{let s=JSON.parse(i);s&&typeof s.id=="string"&&typeof s.body=="string"&&n.push(s)}catch{}}return n}Ji();function Ol(t){if(!t)return"youtrack";try{let e=wg(t,"project.yaml");return gg(e)&&bg(yg(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function Ot(t){let e=Ol(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=Cm(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=jR(n);return i?{ok:!0,kind:e,provider:new qo(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=Nf();return r?{ok:!0,kind:e,provider:new Wo(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function jR(t){try{let e=wg(t,"project.yaml");if(!gg(e))return null;let r=bg(yg(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var vs=new Map;async function Yo(t,e){let n=(vs.get(t)??Promise.resolve()).catch(()=>{}).then(e);vs.set(t,n);try{return await n}finally{vs.get(t)===n&&vs.delete(t)}}function Vo(t,e){return or(t.split(":",2)[0]??"",e)}function xg(t){let{mirror:e,...r}=t;return{spec:r,host:Mr(r)}}async function Sg(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;ht(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return Q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Yo(`${i}/${r.name}`,async()=>{let s=await dr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Oe(i,r.name,t.baseDir);if(r.mirror){let{syncUpstream:p}=await Promise.resolve().then(()=>(ks(),bs)),d=await p(r,a,{info:f=>ht(`[mirror] ${f}`),warn:f=>ht(`[mirror] WARN ${f}`)});d.error&&ht(`[mirror] ${r.name}: pre-apply sync failed \u2014 ${d.error}`)}let{commit:c,pushed:l,baseMoved:u}=await Hm(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force,push:e.push});if(t.contextDir){let p=e.taskId.split(":")[1]??"";p&&await pg({contextDir:t.contextDir,repoDir:a,repoName:r.name,taskKey:p,commitSha:c}).catch(d=>{ht(`[model] task event for ${p} failed: ${d instanceof Error?d.message:String(d)}`)})}return ue({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,pushed:l,...typeof u=="number"&&u>0?{baseMoved:u}:{},...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"push_branch":{if(!r)return Q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Yo(`${i}/${r.name}`,async()=>{let s=await dr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Oe(i,r.name,t.baseDir);return await Wm(s,a,{branchName:e.branchName,force:e.force}),ue({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"create_pr":{if(!r)return Q("no repo spec");let{spec:i,host:s}=Vo(e.taskId,r),a=await s.createPullRequest(i,e);if(t.contextDir){let c=e.taskId.split(":")[1]??"",l=e.taskId.split(":",2)[0]??"?";c&&await fg({contextDir:t.contextDir,repoDir:Oe(l,r.name,t.baseDir),branchName:e.branchName,baseBranch:e.baseBranch,fallbackTaskKey:c,prUrl:a.url}).catch(u=>{ht(`[model] pr link for ${c} failed: ${u instanceof Error?u.message:String(u)}`)})}return ue({url:a.url,number:a.number,host:s.name})}case"merge_pr":{if(!r)return Q("no repo spec");let{spec:i,host:s}=Vo(e.taskId,r),a=await s.mergePR(i,e.prNumber,e.mergeMethod,e.deleteBranch);return ue({prNumber:e.prNumber,host:s.name,...a.mergedSha?{mergedSha:a.mergedSha}:{}})}case"close_pr":{if(!r)return Q("no repo spec");let{spec:i,host:s}=Vo(e.taskId,r);return await s.closePR(i,e.prNumber,e.comment),ue({prNumber:e.prNumber,host:s.name})}case"rewrite_cluster_branch":{if(!r)return Q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Yo(`${i}/${r.name}`,async()=>{let s=await dr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Oe(i,r.name,t.baseDir),{commit:c,dropped:l}=await qm(s,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:yn(r)});return ue({branch:e.branchName,commit:c,dropped:l,pushed:l>0})})}case"merge_branch":{if(!r)return Q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Yo(`${i}/${r.name}`,async()=>{let s=await dr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Oe(i,r.name,t.baseDir),{mergedSha:c}=await Ym(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ue({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return Q("no repo spec");let i=t.cloneUrlOverride??Ln(r),a=(await es(i)).filter(u=>Vm(u,e.issueKey)),c=Mr(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 ue({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return Q("no repo spec");let{spec:i,host:s}=e.upstream?xg(r):Vo(e.taskId,r);return await s.addPRComment(i,e.prNumber,e.body),ue({prNumber:e.prNumber,host:s.name})}case"add_pr_inline_comment":{if(!r)return Q("no repo spec");let{spec:i,host:s}=e.upstream?xg(r):Vo(e.taskId,r);if(s.addPRInlineComment)try{return await s.addPRInlineComment(i,e.prNumber,e.path,e.line,e.body),ue({prNumber:e.prNumber,inline:!0,host:s.name})}catch(a){ht(`[exec] inline comment ${e.path}:${e.line} failed (${a instanceof Error?a.message.split(`
1064
+ `;return await Ce(this.contextDir,[{path:`tasks/${e}/comments.jsonl`,content:c}],`tracker(${e}): comment`),{id:i.id}}async createIssue(e){let r=new Date().toISOString(),n=await Om(this.contextDir,this.config.prefix,o=>this.renderNewIssueFiles(o,e,r),o=>`tracker(${o}): create issue`);return{id:n,key:n}}async editIssue(e,r){await this.mutateRecord(e,n=>({...n,...r.title!==void 0?{title:r.title}:{}}),r.body)}async applyLink(e,r,n){let o=r==="subtask_of"?"subtask":"depends_on";await this.mutateRecord(e,i=>{let s=i.links.filter(a=>!(a.type===o&&a.targetKey===n));return s.push({type:o,targetKey:n}),{...i,links:s}})}async fetchStateFields(e){return[{name:"Status",values:Pi.statusColumns}]}async mutateRecord(e,r,n){let o=Lo(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=Mo(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:kn(e),content:ll(i)},...ys(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await Ce(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:Ro,status:r.targetStatus,links:[],created:n,updated:n},i=Mo(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:kn(e),content:ll(o)},...ys(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}};function wg(t,e){let r=Re(t,`tasks/${e}/comments.jsonl`);if(!NR(r))return[];let n=[];for(let o of OR(r,"utf-8").split(`
1065
+ `)){let i=o.trim();if(i)try{let s=JSON.parse(i);s&&typeof s.id=="string"&&typeof s.body=="string"&&n.push(s)}catch{}}return n}Ji();function Ol(t){if(!t)return"youtrack";try{let e=vg(t,"project.yaml");return bg(e)&&$g(kg(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function Ot(t){let e=Ol(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=_m(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=MR(n);return i?{ok:!0,kind:e,provider:new Yo(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=Mf();return r?{ok:!0,kind:e,provider:new qo(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function MR(t){try{let e=vg(t,"project.yaml");if(!bg(e))return null;let r=$g(kg(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var vs=new Map;async function Vo(t,e){let n=(vs.get(t)??Promise.resolve()).catch(()=>{}).then(e);vs.set(t,n);try{return await n}finally{vs.get(t)===n&&vs.delete(t)}}function zo(t,e){return ir(t.split(":",2)[0]??"",e)}function Rg(t){let{mirror:e,...r}=t;return{spec:r,host:Dr(r)}}async function Tg(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;ht(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return Q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Vo(`${i}/${r.name}`,async()=>{let s=await pr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Oe(i,r.name,t.baseDir);if(r.mirror){let{syncUpstream:p}=await Promise.resolve().then(()=>(ks(),bs)),d=await p(r,a,{info:f=>ht(`[mirror] ${f}`),warn:f=>ht(`[mirror] WARN ${f}`)});d.error&&ht(`[mirror] ${r.name}: pre-apply sync failed \u2014 ${d.error}`)}let{commit:c,pushed:l,baseMoved:u}=await Ym(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force,push:e.push});if(t.contextDir){let p=e.taskId.split(":")[1]??"";p&&await hg({contextDir:t.contextDir,repoDir:a,repoName:r.name,taskKey:p,commitSha:c}).catch(d=>{ht(`[model] task event for ${p} failed: ${d instanceof Error?d.message:String(d)}`)})}return ue({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,pushed:l,...typeof u=="number"&&u>0?{baseMoved:u}:{},...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"push_branch":{if(!r)return Q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Vo(`${i}/${r.name}`,async()=>{let s=await pr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Oe(i,r.name,t.baseDir);return await Vm(s,a,{branchName:e.branchName,force:e.force}),ue({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"create_pr":{if(!r)return Q("no repo spec");let{spec:i,host:s}=zo(e.taskId,r),a=await s.createPullRequest(i,e);if(t.contextDir){let c=e.taskId.split(":")[1]??"",l=e.taskId.split(":",2)[0]??"?";c&&await gg({contextDir:t.contextDir,repoDir:Oe(l,r.name,t.baseDir),branchName:e.branchName,baseBranch:e.baseBranch,fallbackTaskKey:c,prUrl:a.url}).catch(u=>{ht(`[model] pr link for ${c} failed: ${u instanceof Error?u.message:String(u)}`)})}return ue({url:a.url,number:a.number,host:s.name})}case"merge_pr":{if(!r)return Q("no repo spec");let{spec:i,host:s}=zo(e.taskId,r),a=await s.mergePR(i,e.prNumber,e.mergeMethod,e.deleteBranch);return ue({prNumber:e.prNumber,host:s.name,...a.mergedSha?{mergedSha:a.mergedSha}:{}})}case"close_pr":{if(!r)return Q("no repo spec");let{spec:i,host:s}=zo(e.taskId,r);return await s.closePR(i,e.prNumber,e.comment),ue({prNumber:e.prNumber,host:s.name})}case"rewrite_cluster_branch":{if(!r)return Q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Vo(`${i}/${r.name}`,async()=>{let s=await pr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Oe(i,r.name,t.baseDir),{commit:c,dropped:l}=await zm(s,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:wn(r)});return ue({branch:e.branchName,commit:c,dropped:l,pushed:l>0})})}case"merge_branch":{if(!r)return Q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Vo(`${i}/${r.name}`,async()=>{let s=await pr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Oe(i,r.name,t.baseDir),{mergedSha:c}=await Xm(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ue({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return Q("no repo spec");let i=t.cloneUrlOverride??Mn(r),a=(await es(i)).filter(u=>Jm(u,e.issueKey)),c=Dr(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 ue({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return Q("no repo spec");let{spec:i,host:s}=e.upstream?Rg(r):zo(e.taskId,r);return await s.addPRComment(i,e.prNumber,e.body),ue({prNumber:e.prNumber,host:s.name})}case"add_pr_inline_comment":{if(!r)return Q("no repo spec");let{spec:i,host:s}=e.upstream?Rg(r):zo(e.taskId,r);if(s.addPRInlineComment)try{return await s.addPRInlineComment(i,e.prNumber,e.path,e.line,e.body),ue({prNumber:e.prNumber,inline:!0,host:s.name})}catch(a){ht(`[exec] inline comment ${e.path}:${e.line} failed (${a instanceof Error?a.message.split(`
1072
1066
  `)[0]:String(a)}) \u2014 posting as a plain comment`)}return await s.addPRComment(i,e.prNumber,`\u{1F4CD} \`${e.path}:${e.line}\`
1073
1067
 
1074
- ${e.body}`),ue({prNumber:e.prNumber,inline:!1,host:s.name})}case"tracker_status":{let i=Ot({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),ue({issueId:t.trackerIssueId,newStatus:e.newStatus})):Q("no tracker_issue_id provided"):Q(i.error)}case"tracker_comment":{let i=Ot({contextDir:t.contextDir});if(!i.ok)return Q(i.error);if(!t.trackerIssueId)return Q("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return ue({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Ot({contextDir:t.contextDir});if(!i.ok)return Q(i.error);if(!e.projectKey)return Q("no projectKey in create_tracker_issue action");let{id:s,key:a}=await i.provider.createIssue({projectKey:e.projectKey,title:e.title,body:e.body,targetStatus:e.targetStatus});return ue({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Ot({contextDir:t.contextDir});if(!i.ok)return Q(i.error);let s=0;for(let a of e.links)try{await i.provider.applyLink(a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return Q(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return ue({applied:s})}case"set_project_setting":{if(!t.contextDir)return Q("no context repo clone on this CLI");let i=await dh(t.contextDir,e.edits);return ue({files:i.files})}case"set_prompt_override":{if(!t.contextDir)return Q("no context repo clone on this CLI");if(!dc(e.role))return Q(`unknown prompt operation: ${e.role}`);let i=pc(e.role);return await Ce(t.contextDir,[e.content===null?{path:i,content:"",deleted:!0}:{path:i,content:e.content}],e.commitMessage),t.requestConfigReport?.(),ue({path:i,reset:e.content===null})}case"tracker_edit":{let i=Ot({contextDir:t.contextDir});if(!i.ok)return Q(i.error);if(!t.contextDir)return Q("no context repo clone on this CLI");await i.provider.editIssue(e.issueKey,{...e.title!==void 0?{title:e.title}:{},...e.body!==void 0?{body:e.body}:{}});let s=await i.provider.getIssue(e.issueKey);return s&&await ws(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),ue({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return Q("no context repo clone on this CLI");let i=await kh(t.contextDir,e);return ue({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return Q("no context repo clone on this CLI");let i=await wh(t.contextDir,e);return ue({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ue({reported:!0})):Q("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return Q("no context repo clone on this CLI");let i=await t.refreshContextStatus();return ue({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return Q("no project workspace on this CLI");if(!r)return Q("no repo spec");if(!t.onRunActivity)return Q("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=Ki(t.contextDir),c=s.find(f=>f.id===e.actionId);if(!c){let f=a.find(m=>m.file===`actions/${e.actionId}.yml`);return Q(f?`action "${e.actionId}" failed to parse: ${f.error}`:`unknown action "${e.actionId}"`)}let l=Qa(c,e.input);if(!l.ok)return Q(l.error);let u=um(t.contextDir),p=X(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),Yo(`${e.projectId}/${r.name}`,async()=>{await dr(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let f=Oe(e.projectId,r.name,t.baseDir),m=await ah({cwd:f,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:g=>i(e.runId,g)});return ue({runId:e.runId,status:m.status,exitCode:m.exitCode,...m.failedStep?{failedStep:m.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return Q("no context repo clone on this CLI");let i=uh(t.contextDir,e.path);return ue({path:e.path,...i})}case"search_model":{if(!t.contextDir)return Q("no context repo clone on this CLI");let{searchModelIndex:i}=await Promise.resolve().then(()=>(Ho(),Ko)),s=await i(t.contextDir,e.q,e.limit);return ue({hits:s})}case"model_drift":return Q("model_drift requires a local workspace (handled by the daemon)");case"model_bootstrap":return Q("model_bootstrap requires a local workspace (handled by the daemon)");default:return Q(`unsupported action type: ${e.type}`)}}catch(i){return Q(i instanceof Error?i.message:String(i))}}function ue(t){return{status:"done",result:t}}function Q(t){return{status:"failed",error:t}}gt();Dl();Le();me();import{existsSync as Dg,readFileSync as Ug}from"node:fs";import{join as Bg}from"node:path";async function Fg(t,e,r,n){let o=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return o(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=ze(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");xs(e.farmId,e.farmPublicKey);let s=X(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await se(t.hubUrl,t.cliToken,t.projectId),c;if(r){let d=Bg(r,"project.yaml"),f=Bg(r,"regimen.yaml");Dg(d)&&Dg(f)?c={projectYaml:Ug(d,"utf-8"),regimenYaml:Ug(f,"utf-8")}:n.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},u=Xt(e.farmPublicKey,JSON.stringify(l));$s(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let p=await Es(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:u});return p.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...p.daemonStatus?{daemonStatus:p.daemonStatus}:{}}:o(p.error??"farm provisioning failed")}catch(i){return o(i instanceof Error?i.message:String(i))}}M();gt();Ye();gt();import{homedir as VR}from"node:os";import{existsSync as zR,mkdirSync as XR,readFileSync as JR,writeFileSync as ZR}from"node:fs";import{dirname as QR,join as eT}from"node:path";function Fl(){return ee("RUNNER_PINS")??eT(VR(),".codepipe","runner-pins.json")}function Gg(){let t=Fl();if(!zR(t))return{};try{return JSON.parse(JR(t,"utf-8"))}catch{return{}}}function tT(t){let e=Fl();XR(QR(e),{recursive:!0}),ZR(e,JSON.stringify(t,null,2)+`
1075
- `,{mode:384})}function rT(t){return Gg()[t]}function Gl(t,e){let r=Gg();r[t]=e,tT(r)}function Kg(t,e){let r=ze(e),n=rT(t);if(n&&n!==r)throw new Error(`runner host ${t} key fingerprint changed (pinned ${n}, now ${r}) \u2014 refusing to seal. If the runner host was re-registered intentionally, remove its entry from ${Fl()}.`);return r}Le();me();var Wg=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function Hg(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:Wg(t)});if(!o.ok)throw new Error(`github ${n} for ${e}/${r}: HTTP ${o.status}`);let i=await o.json();if(!i.token)throw new Error(`github ${n} for ${e}/${r}: no token in response`);return i.token}var nT={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Wg(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)=>Hg(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Hg(t,e,r,"remove-token")},qg={api:nT,fetchProject:se,provisionOnRunner:Tg,teardownOnRunner:Ig};async function Yg(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(ze(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Kg(e.runnerId,e.runnerPublicKey);let i=X(t.projectId)?.github?.token;if(!i)throw new Error("no GitHub token stored for this project on this CLI");let a=((await r.fetchProject(t.hubUrl,t.cliToken,t.projectId)).repos??[]).find(c=>c.host==="github"&&c.owner===e.owner&&c.repoName===e.repo);if(!a)throw new Error(`${e.owner}/${e.repo} is not a GitHub repository of this project`);return{githubToken:i,repo:a}}async function Vg(t,e,r,n=qg){let o=i=>({type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repo:s}=await Yg(t,e,n);if(!await n.api.repoHasAdmin(i,s.owner,s.repoName))return o(`the GitHub token lacks admin access on ${s.owner}/${s.repoName} \u2014 replace it (project page \u2192 Tokens \u2192 Replace) with a token that has admin rights on this repository`);let a={projectId:t.projectId,runners:[{owner:s.owner,repo:s.repoName,regToken:await n.api.mintRegistrationToken(i,s.owner,s.repoName)}],labels:[wc(e.runnerId)]},c=Xt(e.runnerPublicKey,JSON.stringify(a));Gl(e.runnerId,e.fingerprint),r.info(`[ghr] registration token for ${s.owner}/${s.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let l=await n.provisionOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:c});return{type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:l.ok,...l.runners?{runners:l.runners}:{},...l.error?{error:l.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}async function zg(t,e,r,n=qg){let o=i=>({type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repo:s}=await Yg(t,e,n),a={owner:s.owner,repo:s.repoName};try{a.removeToken=await n.api.mintRemoveToken(i,s.owner,s.repoName)}catch(p){r.warn(`[ghr] remove-token for ${s.owner}/${s.repoName} failed (${p instanceof Error?p.message:p}) \u2014 the runner host will force-remove`)}let c={projectId:t.projectId,runners:[a]},l=Xt(e.runnerPublicKey,JSON.stringify(c));Gl(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle for ${s.owner}/${s.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let u=await n.teardownOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:l,owner:s.owner,repo:s.repoName});return{type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:u.ok,...u.error?{error:u.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}Le();M();import{existsSync as oT}from"node:fs";import{join as Xg}from"node:path";import{simpleGit as Zg}from"simple-git";async function Kl(t,e,r,n,o){for(let i of r.repos){let s=e.find(u=>u.name===i.repoName);if(!s)continue;let a=`${r.taskKey}:${s.name}:${i.branchName}`;if(!Qt(i.branchName)){n.has(a)||(n.add(a),o.warn(`[pull] ${r.taskKey} ${s.mountAs}: refusing suspicious branch name`));continue}let c=Xg(t,s.mountAs);if(!oT(Xg(c,".git")))continue;let l=Zg(c);try{let u=await aT(l,i.branchName);await l.fetch(await iT(l,s),`refs/heads/${i.branchName}`);let p=(await l.revparse(["FETCH_HEAD"])).trim();if(u===p)continue;if(await sT(l,c,i.branchName)){n.has(a)||(n.add(a),o.info(`[pull] ${r.taskKey} \u2192 ${s.mountAs}: ${i.branchName} is checked out here \u2014 fetched ${p.slice(0,10)}; merge or pull it in that checkout yourself`));continue}await l.raw(["branch","-f",i.branchName,p]),o.info(`[pull] ${r.taskKey} \u2192 ${s.mountAs}: ${i.branchName} ${p.slice(0,10)} (checkout untouched)`)}catch(u){if(n.has(a))continue;n.add(a),o.warn(`[pull] ${r.taskKey} ${s.mountAs}: ${i.branchName} unavailable \u2014 `+(u instanceof Error?u.message.split(`
1076
- `)[0]:String(u)))}}}async function iT(t,e){if(e.mirror)return Jg(e.mirror);try{if((await t.getRemotes(!0)).find(n=>n.name==="origin")?.refs?.fetch)return"origin"}catch{}return e.host&&e.owner&&e.repoName?Jg({host:e.host,owner:e.owner,repoName:e.repoName}):"origin"}function Jg(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 sT(t,e,r){try{return(await t.raw(["worktree","list","--porcelain"])).split(`
1077
- `).some(o=>o.trim()===`branch refs/heads/${r}`)}catch{try{return(await Zg(e).revparse(["--abbrev-ref","HEAD"])).trim()===r}catch{return!1}}}async function aT(t,e){try{return(await t.revparse([e])).trim()}catch{return null}}var Is=class{constructor(e,r,n,o){this.intervalMs=e;this.fetchDeliverables=r;this.workspace=n;this.log=o}timer=null;running=!1;caughtUp=!1;warned=new Set;start(){if(this.timer)return;this.log.info(`[pull] local delivery started (interval=${this.intervalMs}ms)`);let e=()=>void this.runOnce();e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[pull] local delivery stopped"))}poke(){this.runOnce()}async runOnce(){if(!this.running){this.running=!0;try{let e=await this.fetchDeliverables(),r=this.caughtUp?e.filter(n=>n.phase==="TRACKING"||n.phase==="AWAITING_CLUSTER"):e;for(let n of r)await Kl(this.workspace.root,this.workspace.repos,n,this.warned,this.log);this.caughtUp=!0}catch(e){this.log.warn(`[pull] pass failed: ${e instanceof Error?e.message:String(e)}`)}finally{this.running=!1}}}};M();gt();me();var Qg=16*1024;function cT(t){return rt.test(t)?Ht(t)?`secret name "${t}" is reserved`:null:`secret name must match ${rt}`}function ey(t,e,r,n){let o=cT(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(Dn(n,r).toString("utf-8"));if(typeof s.value!="string"||s.value.length===0)return{ok:!1,detail:"payload has no value"};i=s.value}catch(s){return{ok:!1,detail:`cannot open the sealed secret (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}if(i.length>Qg)return{ok:!1,detail:`secret value too large (max ${Qg} chars)`};try{return cf(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function ty(t,e){try{return lf(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)}}}In();me();Yt();var Cs=class{constructor(e,r,n){this.intervalMs=e;this.send=r;this.log=n}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let n=[],o=e.split(":",2)[0]??"";for(let a of r.prs){let{spec:c,host:l}=or(o,a.repoSpec);try{let u=await l.getPullRequest(c,a.number);n.push({number:a.number,repoName:a.repoSpec.name,url:a.url,state:u.state,merged:u.merged,ci:u.ci,mergeable:u.mergeable})}catch(u){if(u instanceof Lr){this.log.warn(`[track] task=${e} pr=${a.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${a.url} fetch failed: ${u instanceof Error?u.message:String(u)}`);return}}let i=n.map(a=>`${a.repoName??""}#${a.number}:${a.state}:${a.merged?1:0}:${a.ci}:${a.mergeable}`).join("|");if(this.lastSig.get(e)===i)return;for(let a=0;a<n.length;a++){let c=n[a];if(c.ci!=="failed")continue;let{spec:l,host:u}=or(o,r.prs[a].repoSpec);if(u.getCiFailureLog)try{let p=await u.getCiFailureLog(l,c.number);p&&(c.ciFailureLog=p)}catch(p){this.log.warn(`[track] task=${e} pr=${c.url} ci-log fetch failed: ${p instanceof Error?p.message:String(p)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:n}),this.lastSig.set(e,i);let s=lT(n);this.log.info(`[track] task=${e} snapshot signalled${s?` \u2192 ${s}`:""} (${n.length} PR(s))`)}};function lT(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}M();Mn();var Ps=class{constructor(e,r,n,o=i=>es(Ln(i))){this.intervalMs=e;this.send=r;this.log=n;this.listBranches=o}projectId="";repos=[];lastSig=new Map;timer=null;running=!1;setRepos(e,r){this.projectId=e,this.repos=r,this.lastSig.clear()}start(){if(this.timer)return;this.log.info(`[branches] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[branches] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs),typeof this.timer.unref=="function"&&this.timer.unref()}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[branches] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let e of this.repos)await this.processRepo(e)}finally{this.running=!1}}}async processRepo(e){let r=e.gitFlow;if(!r||r.flow==="simple")return;let n;try{n=await this.listBranches(e)}catch(s){this.log.warn(`[branches] repo=${e.name} ls-remote failed: ${s instanceof Error?s.message:String(s)}`);return}let o=n.filter(s=>Sc(s,r)).sort(),i=o.join("|");this.lastSig.get(e.name)!==i&&(this.send({type:"branches_observation",projectId:this.projectId,repoName:e.name,branches:o}),this.lastSig.set(e.name,i),this.log.info(`[branches] repo=${e.name} reported ${o.length} base candidate(s)`))}};M();Yt();var As=class{constructor(e,r,n,o=uT,i=dT){this.intervalMs=e;this.send=r;this.log=n;this.read=o;this.readFailureLog=i}projectId="";repos=[];lastSig=new Map;timer=null;running=!1;setRepos(e,r){this.projectId=e,this.repos=r;let n=new Set(r.map(o=>o.name));for(let o of[...this.lastSig.keys()])n.has(o)||this.lastSig.delete(o)}start(){if(this.timer)return;this.log.info(`[branch-ci] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[branch-ci] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs),typeof this.timer.unref=="function"&&this.timer.unref()}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}async tick(){if(!(this.running||!this.projectId)){this.running=!0;try{for(let e of this.repos){let r=yn(e);try{let n=await this.read(this.projectId,e,r);if(!n||n.ci==="none")continue;let o=`${r}:${n.ci}:${n.headSha}`;if(this.lastSig.get(e.name)===o)continue;let i;n.ci==="failed"&&(i=await this.readFailureLog(this.projectId,e,n.headSha).catch(()=>{})),this.send({type:"branch_ci_observed",projectId:this.projectId,repoName:e.name,branch:r,ci:n.ci,headSha:n.headSha,...i?{ciFailureLog:i}:{}}),this.lastSig.set(e.name,o),this.log.info(`[branch-ci] ${e.name}#${r}: ${n.ci} @ ${n.headSha.slice(0,10)}`)}catch(n){this.log.warn(`[branch-ci] ${e.name}#${r}: read failed \u2014 ${n instanceof Error?n.message:String(n)}`)}}}finally{this.running=!1}}}};async function uT(t,e,r){let{spec:n,host:o}=or(t,e);if(!o.getBranchCi)return null;let i=await o.getBranchCi(n,r);return i?{ci:i.ci,headSha:i.headSha}:null}async function dT(t,e,r){let{spec:n,host:o}=or(t,e);if(o.getCiFailureLogForSha)return await o.getCiFailureLogForSha(n,r)}M();var _s=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??(()=>Ot({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 y=e.stageField?{stageField:e.stageField}:{},k=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??[]])],[A,N]=await Promise.all([$.length>0?r.listIssues({projectKey:e.projectKey,columns:$,...y,...k}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...y})]),B=new Map;for(let H of[...A,...N])B.set(H.id,H);o=[...B.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:$,...y,...k})}}catch(y){let k=y instanceof Error?y.message:String(y);k.includes("stage_field")?this.log.warn(`[yt-sync] CONFIGURATION ERROR \u2014 ${k}`):this.log.warn(`[yt-sync] listIssues failed: ${k}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let y of o){if(s.add(y.id),a.has(y.status))continue;let k=await oy(r,y.id,e.sinceMs,this.log);k&&i.set(y.id,k)}let c=[];for(let y of e.offBoardIssueIds){if(s.has(y))continue;let k=await oy(r,y,e.sinceMs,this.log);k&&k.length>0&&i.set(y,k);let C=await ny(r,y,e.stageField,this.log);if(C)c.push(C);else if(k&&k.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}let l=o.filter(y=>!a.has(y.status)),{attachmentsByIssue:u,attachmentKeys:p}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let d=[...l,...c].map(y=>({issue:y,comments:i.get(y.id)??[],attachments:u.get(y.id)??[]}));d.push(...await mg(this.options.contextDir,d,y=>ny(r,y,e.stageField,this.log)));try{await ws(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let y of p)this.shippedAttachments.add(y)}catch(y){let k=y instanceof Error?y.message:String(y);this.abandonTick(`context task sync failed: ${k}`);return}let f=this.options.isSelfComment??(()=>!1),m=[],g=[];for(let[y,k]of i){let C=k.filter($=>!f($.id));if(C.length===0)continue;m.push({issueId:y,comments:C.map(pT)});let E=C.flatMap($=>{let A=jr($.body);return A?[{commentId:$.id,author:$.author,name:A.name,args:A.args,createdAt:$.createdAt}]:[]});E.length>0&&g.push({issueId:y,commands:E})}let b={type:"youtrack_observation",projectId:e.projectId,issues:o.map(ry),commentsBatch:m,...g.length>0?{commandsBatch:g}:{},...c.length>0?{offBoardIssues:c.map(ry)}:{},observedAtMs:n};this.send(b);let w=m.reduce((y,k)=>y+k.comments.length,0),v=g.reduce((y,k)=>y+k.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${w} commands=${v} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let p=`${s.id}:${u.id}`;if(this.shippedAttachments.has(p))continue;let d;try{d=await n.downloadAttachment(u.url)}catch(m){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${m instanceof Error?m.message:String(m)}`);continue}let f=fT(u.name);l.has(f)&&(f=`${u.id}-${f}`),l.add(f),c.push({name:f,contentBase64:d.toString("base64")}),i.push(p)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}};function ry(t){let{description:e,...r}=t;return r}function pT(t){let{body:e,...r}=t;return r}function fT(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 ny(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 oy(t,e,r,n){try{return await t.listComments(e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function PT(t,e){let r=t.repos.filter(i=>i.mirror);if(r.length===0)return[];let{mirrorLag:n}=await Promise.resolve().then(()=>(ks(),bs)),o=[];for(let i of r){let s=i.mountAs==="."?t.root:Hr(t.root,i.mountAs);try{o.push({repo:i.name,behind:await n(i,s)})}catch(a){e.warn(`[mirror] lag for ${i.name} unknown: ${a instanceof Error?a.message:String(a)}`),o.push({repo:i.name,behind:null})}}return o}var Ql="npm i -g @code-partner/codepipe@latest";function Ds(t,e={}){let r=e.log??{info:y=>console.log(y),warn:y=>console.warn(y)};r.info(`codepipe-cli v${et} (protocol ${kt})`);let n=y=>e.onEvent?.(y),o=e.workspace;o?.contextDir&&fm(o.contextDir,r);let i=()=>{if(o?.contextDir)try{_n(o.contextDir,o.root,r)}catch(y){r.warn(`[skills] materialize failed (non-fatal): ${y instanceof Error?y.message:String(y)}`)}};i();let s=tu("CLI_TRACKING_POLL_INTERVAL_SEC"),a=parseInt(process.env.CLI_BRANCH_CI_POLL_INTERVAL_SEC??"300",10),c=Number.isFinite(a)&&a>0?a*1e3:3e5,l=tu("CLI_YOUTRACK_POLL_INTERVAL_SEC"),u=(()=>{let y=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(y)&&y>0?y*1e3:6e5})(),p=!1,d=!1,f=!1,m=new Set,g=!1,b=new Set,w=v();function v(){let y=Ss(t.hubUrl,t.cliToken),k=null,C=new Cs(s,U=>{y.readyState===y.OPEN&&y.send(JSON.stringify(U))},r),E=new Ps(s,U=>{y.readyState===y.OPEN&&y.send(JSON.stringify(U))},r),$=new As(c,U=>{y.readyState===y.OPEN&&y.send(JSON.stringify(U))},r),A=o&&o.repos.length>0?new Is(tu("CLI_LOCAL_PULL_INTERVAL_SEC"),()=>Ts(t.hubUrl,t.cliToken,t.projectId),{root:o.root,repos:o.repos},r):null,N=new _s(l,U=>{y.readyState===y.OPEN&&y.send(JSON.stringify(U))},r,{contextDir:o?.contextDir??null,isSelfComment:U=>b.has(U)}),B=null,H=async()=>{try{let U={trackerProvider:Ol(o?.contextDir??null)};try{let S=await se(t.hubUrl,t.cliToken,t.projectId);U={...U,repos:S.repos,contextRepo:S.contextRepo},E.setRepos(t.projectId,S.repos),$.setRepos(t.projectId,S.repos)}catch(S){r.warn(`[readiness] could not fetch project summary for push checks: ${S instanceof Error?S.message:String(S)}`)}let G=await Zf(t.projectId,U),D=o?await PT(o,r):[];if(i(),y.readyState!==y.OPEN)return;let T={type:"cli_readiness",projectId:t.projectId,ready:G.ready,checks:G.checks,creds:G.creds,secretNames:uf(t.projectId),...o?{mirrors:D}:{},checkedAt:G.checkedAt};if(y.send(JSON.stringify(T)),G.ready)r.info("[readiness] ready");else{let S=G.checks.filter(I=>!I.ok).map(I=>`${I.name}(${I.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${S.join(", ")}`)}let R=om(G.creds,f);if(R==="open"){f=!0;let S=im(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${S}`),Ur(S)}else R==="rearm"&&(f=!1)}catch(U){r.warn(`[readiness] check failed: ${U instanceof Error?U.message:String(U)}`)}},j=()=>{H(),B=setInterval(()=>void H(),u),typeof B.unref=="function"&&B.unref()},h=()=>{B&&(clearInterval(B),B=null)},F=150,L=new Map,z=U=>{let G=L.get(U);if(!G||(G.timer&&clearTimeout(G.timer),L.delete(U),G.events.length===0||y.readyState!==y.OPEN))return;let D={type:"run_activity",projectId:t.projectId,runId:U,events:G.events};y.send(JSON.stringify(D))},te=(U,G)=>{let D=L.get(U);if(D||(D={events:[],timer:null},L.set(U,D)),D.events.push(G),G.kind==="result"){z(U);return}D.timer||(D.timer=setTimeout(()=>z(U),F),D.timer.unref?.())},ae=o?.contextDir?new Hi(o.contextDir,t.projectId,U=>{y.readyState===y.OPEN&&y.send(JSON.stringify(U))},r):null,Ut=async()=>{let U=o?.contextDir;if(!U)throw new Error("no context repo clone on this CLI");let G;try{G=(await se(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let D=await Um(U,t.projectId,G,r);return y.readyState===y.OPEN&&y.send(JSON.stringify(D)),D},We=null,Ue=async()=>{let U=o?.contextDir;if(U)try{let{readContextIndexHub:G,collectSearchRows:D}=await Promise.resolve().then(()=>(Ho(),Ko));if(G(U)!=="metadata")return;let T=D(U);y.readyState===y.OPEN&&(y.send(JSON.stringify({type:"model_index",projectId:t.projectId,rows:T})),r.info(`[model] tier-2 index snapshot pushed (${T.length} rows)`))}catch(G){r.warn(`[model] tier-2 index push failed (non-fatal): ${G instanceof Error?G.message:String(G)}`)}},Ae=()=>{We&&clearTimeout(We),We=setTimeout(()=>void Ue(),5e3)},Be=async()=>{if(!o?.contextDir)throw new Error("no Context Repo clone on this CLI");if(g)throw new Error("model bootstrap is already running");g=!0;try{let U=await se(t.hubUrl,t.cliToken,t.projectId),{bootstrapDaemonModel:G}=await Promise.resolve().then(()=>(Jo(),Ms)),D=await G(t.projectId,{root:o.root,contextDir:o.contextDir},U.repos,T=>r.info(`[model] ${T}`));return r.info(`[model] bootstrap done: ${D.repos} repos, ${D.events} task events`),Ae(),D}finally{g=!1}},Te=null,st=async U=>{if(o?.contextDir)try{let G=await Promise.resolve().then(()=>(Jo(),Ms)),D={root:o.root,contextDir:o.contextDir,repos:o.repos};if(G.shouldAutoBootstrapModel(o.contextDir)){await G.syncWorkspaceMirrors(D,R=>r.info(R));try{await Be()}catch(R){r.warn(`[model] auto-bootstrap failed (non-fatal): ${R instanceof Error?R.message:String(R)}`)}return}(await G.rebuildWorkspaceModelIfStale(D,{fetch:U,onLog:R=>r.info(R)})).rebuilt.length>0&&Ae()}catch(G){r.warn(`[model] release-path rebuild failed (non-fatal): ${G instanceof Error?G.message:String(G)}`)}},Bt=U=>{Te&&clearTimeout(Te),Te=setTimeout(()=>void st(U),6e4)},Ft=setInterval(()=>void st(!0),6*36e5);return y.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let U=wf(t.projectId),G=ee("ORIGIN")==="farm"?"farm":"local",D=ee("FARM_ID"),T=t.accountEmail??U.email,R;try{let I=nh(t.projectId);I&&(R=I.publicKey,r.info(`[cred-channel] key fingerprint: ${I.fingerprint}`))}catch(I){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${I instanceof Error?I.message:String(I)}`)}let S={type:"register",projectId:t.projectId,platformVersion:et,protocolVersion:kt,accountId:U.accountId,accountLabel:U.label,origin:G,inFlightActionIds:[...m],...T?{accountEmail:T}:{},...G==="farm"&&D?{farmId:D}:{},...R?{sealPublicKey:R}:{}};y.send(JSON.stringify(S))}),y.on("message",async U=>{let G=U.toString("utf-8");if(G==="pong"||G==="ping")return;let D;try{D=JSON.parse(G)}catch{return}if(!D||typeof D!="object")return;let T=D.type;if(T==="registered"){let S=D;if(S.ok){if(r.info(`[ws] registered for project ${S.projectId}`),n({kind:"registered",projectId:S.projectId??t.projectId}),C.start(),E.start(),$.start(),A?.start(),ae?.start(),j(),eu(t,o,r),o?.contextDir){try{let I=Xi(o.contextDir,t.projectId);y.readyState===y.OPEN&&y.send(JSON.stringify(I)),I.outdated&&(r.warn(`[ctx] context format outdated: v${I.templateVersion} \u2192 v${I.currentVersion}`+(I.missingPaths.length>0?` (missing: ${I.missingPaths.join(", ")})`:"")),d||(d=!0,Ut().catch(()=>{})))}catch(I){r.warn(`[ctx] context-format detect failed (non-fatal): ${I instanceof Error?I.message:String(I)}`)}Ue(),Bt(!0)}}else r.warn(`[ws] register rejected: ${S.reason??"unknown"}`),n({kind:"register_rejected",reason:S.reason??"unknown"}),p=!0,y.close();return}if(T==="hello"){let S=D;k=mo(S.protocolVersion);let I=k?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${S.platformVersion} (protocol ${S.protocolVersion}) \u2014 ${I}`),k||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${et}, protocol ${kt}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Ql}`),n({kind:"incompatible",hubVersion:typeof S.platformVersion=="string"?S.platformVersion:null,hubProtocol:typeof S.protocolVersion=="number"?S.protocolVersion:null,updateCommand:Ql}));return}if(T==="tracking_targets"){C.setTargets(D.targets),A?.poke();return}if(T==="youtrack_sync_request"){N.setRequest(D);return}if(T==="youtrack_force_sync"){N.forceSync();return}if(T==="sync_local"){await jT(D,o,y,r);return}if(T==="provision_repo"){let S=D;r.info(`[repo] provision_repo: ${S.repo.name} (${S.repo.host}:${S.repo.owner}/${S.repo.repoName})`),await AT(t,o,S.repo,r),await eu(t,o,r);return}if(T==="remove_repo"){let S=D;r.info(`[repo] remove_repo: ${S.repoName}${S.purge?" (purge)":""}`),await eu(t,o,r),S.purge&&_T(t,o,S.repoName,r);return}if(T==="context_write"){await NT(D,o,y,r),i();return}if(T==="adr_promote"){await OT(D,o,y,r),i();return}if(T==="cred_update"){let S=D,I=X(t.projectId),J=I?.sealKey?await oh(t.projectId,S.kind,S.sealed,I.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},q={type:"cred_update_result",updateId:S.updateId,projectId:t.projectId,ok:J.ok,...J.detail?{detail:J.detail}:{}};y.readyState===y.OPEN&&y.send(JSON.stringify(q)),J.ok?(r.info(`[cred] ${S.kind} replaced${J.detail?` \u2014 ${J.detail}`:""}`),H()):r.warn(`[cred] ${S.kind} replacement rejected: ${J.detail??"unknown"}`);return}if(T==="readiness_check"){r.info("[readiness] on-demand check requested"),H();return}if(T==="agent_login_start"){nm(t,y,D,r,H);return}if(T==="move_to_farm"){let S=D;r.info(`[farm-move] request to move ${t.projectId} onto farm ${S.farmName} (${S.farmId})`);let I=await Fg(t,S,o?.contextDir,r);y.readyState===y.OPEN&&y.send(JSON.stringify(I)),I.ok?r.info(`[farm-move] done \u2014 farm daemon ${I.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${I.error??"unknown error"}`);return}if(T==="gh_runner_setup"){let S=D;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${S.runnerName} (${S.runnerId})`);let I=await Vg(t,S,r);y.readyState===y.OPEN&&y.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners connected on ${S.runnerName}`):r.warn(`[ghr] setup failed: ${I.error??"see per-repo statuses"}`);return}if(T==="gh_runner_teardown"){let S=D;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${S.runnerName} (${S.runnerId})`);let I=await zg(t,S,r);y.readyState===y.OPEN&&y.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners disconnected from ${S.runnerName}`):r.warn(`[ghr] teardown failed: ${I.error??"unknown error"}`);return}if(T==="tracker_fields_request"){let S=D,I={type:"tracker_fields_result",requestId:S.requestId,projectId:t.projectId,ok:!1},J=Ot({contextDir:o?.contextDir??null});if(!J.ok)I.error=J.error;else try{I.fields=await J.provider.fetchStateFields(S.projectKey),I.ok=!0}catch(q){I.error=q instanceof Error?q.message:String(q)}y.readyState===y.OPEN&&y.send(JSON.stringify(I)),I.ok||r.warn(`[yt-fields] listing failed: ${I.error??"unknown"}`);return}if(T==="project_secret_update"||T==="project_secret_delete"){let S=D,I;if(S.type==="project_secret_update"){let q=X(t.projectId);I=q?.sealKey?ey(t.projectId,S.name,S.sealed,q.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else I=ty(t.projectId,S.name);let J={type:"project_secret_update_result",updateId:S.updateId,projectId:t.projectId,ok:I.ok,...I.detail?{detail:I.detail}:{}};y.readyState===y.OPEN&&y.send(JSON.stringify(J)),I.ok?(r.info(`[secret] ${S.name} ${S.type==="project_secret_update"?"saved":"deleted"}`+(I.detail?` \u2014 ${I.detail}`:"")),H()):r.warn(`[secret] ${S.name} rejected: ${I.detail??"unknown"}`);return}if(T==="sandbox_keys"){let S=X(t.projectId);if(!S){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let I=Sn(t.projectId),J=Qm(D,S,I,r);for(let q of J)y.readyState===y.OPEN&&y.send(JSON.stringify(q));return}if(T!=="dispatch_action")return;let R=D;if(k===!1){let S=`refused: HUB protocol incompatible with CLI v${et} (protocol ${kt})`;y.send(JSON.stringify({type:"action_result",actionId:R.actionId,status:"failed",error:S})),r.warn(`[exec] ${R.actionId} (${R.action.type}) \u2192 REFUSED: ${S}`),r.warn(`[exec] update the CLI to clear this: ${Ql}`),n({kind:"action",actionId:R.actionId,actionType:R.action.type,ok:!1,error:S});return}if(R.action.type==="model_drift"){m.add(R.actionId);try{let S,I=o?.repos.find(J=>J.name===R.action.repoName);if(!o?.contextDir||!I)S={status:"failed",error:"no local workspace/repo clone on this CLI"};else try{let{computeDriftReport:J}=await Promise.resolve().then(()=>(wy(),yy)),q=I.mountAs==="."?o.root:Hr(o.root,I.mountAs);S={status:"done",result:{report:await J(q,o.contextDir,I.name)}}}catch(J){S={status:"failed",error:J instanceof Error?J.message:String(J)}}y.send(JSON.stringify({type:"action_result",actionId:R.actionId,...S}))}finally{m.delete(R.actionId)}return}if(R.action.type==="model_bootstrap"){m.add(R.actionId);try{let S;try{let I=await Be();S={status:"done",result:{repos:I.repos,events:I.events}}}catch(I){S={status:"failed",error:I instanceof Error?I.message:String(I)},r.warn(`[model] bootstrap failed: ${S.error}`)}y.readyState===y.OPEN&&y.send(JSON.stringify({type:"action_result",actionId:R.actionId,...S}))}finally{m.delete(R.actionId)}return}m.add(R.actionId);try{let S=await Sg({action:R.action,repo:R.repo,trackerIssueId:R.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:ae?()=>ae.reportNow():void 0,refreshContextStatus:o?.contextDir?Ut:void 0,onRunActivity:te}).catch(q=>({status:"failed",error:q instanceof Error?q.message:String(q)}));R.action.type==="tracker_comment"&&S.status==="done"&&"result"in S&&typeof S.result?.commentId=="string"&&b.add(S.result.commentId),y.send(JSON.stringify({type:"action_result",actionId:R.actionId,...S}));let I=S.status!=="failed",J=!I&&"error"in S?S.error:void 0;I?r.info(`[exec] ${R.actionId} (${R.action.type}) \u2192 done`):r.warn(`[exec] ${R.actionId} (${R.action.type}) \u2192 FAILED: ${J??"?"}`),n({kind:"action",actionId:R.actionId,actionType:R.action.type,ok:I,...J?{error:J}:{}}),I&&["apply_delivery","context_write","create_pr"].includes(R.action.type)&&Ae(),I&&["merge_pr","merge_branch"].includes(R.action.type)&&Bt(!0)}finally{m.delete(R.actionId)}}),y.on("close",(U,G)=>{let D=G?.toString("utf-8")??"";if(r.info(`[ws] closed code=${U}${D?` reason=${D}`:""}`),C.stop(),E.stop(),$.stop(),A?.stop(),N.stop(),ae?.stop(),h(),clearInterval(Ft),Te&&clearTimeout(Te),We&&clearTimeout(We),D==="replaced"){p=!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:U}),!p&&setTimeout(()=>{w=v()},2e3)}),y.on("error",U=>r.warn(`[ws] error: ${U.message}`)),y}return{stop(){p=!0,w.close()}}}async function eu(t,e,r){try{let n=await se(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=Mo(t.projectId,n.repos,e?.contextDir);for(let s of o)r.info(`[repo] restaged repo set in ${s}`);for(let s of i)r.warn(`[repo] could not restage ${s.path}: ${s.error}`)}catch(n){r.warn(`[repo] repo-set reconcile skipped: ${n instanceof Error?n.message:String(n)}`)}}async function AT(t,e,r,n){let o=r.mountAs??r.name;if(o==="."){n.info(`[repo] ${r.name} mounts in place (mount_as: .) \u2014 nothing to clone`);return}let i=e?Hr(e.root,o):Oe(t.projectId,r.name);if(by(Hr(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await CT().clone(e?Ln(r):ml(r),i),n.info(`[repo] cloned ${r.name} \u2192 ${i}`)}catch(s){n.warn(`[repo] clone of ${r.name} failed (will retry lazily): ${s instanceof Error?s.message.trim():String(s)}`)}}function _T(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?Hr(e.root,o):Oe(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!by(Hr(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{IT(i,{recursive:!0,force:!0}),n.info(`[repo] purged local clone ${i}`)}catch(s){n.warn(`[repo] purge of ${i} failed: ${s instanceof Error?s.message:String(s)}`)}}async function jT(t,e,r,n){if(!e){n.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let o of t.repos){let i=e.repos.find(l=>l.name===o.repoName),s=Hr(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await sm(s,a).catch(l=>({status:"warn",reason:l instanceof Error?l.message:String(l)}));c.status==="updated"?n.info(`[sync] ${o.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?n.info(`[sync] ${o.repoName}: not cloned in workspace \u2014 skipped`):(n.warn(`[sync] ${o.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:o.repoName,reason:c.reason??"sync skipped"})))}}async function NT(t,e,r,n){let o=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{await Ce(e.contextDir,t.files,t.message),n.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[ctx] context_write ${t.id} failed: ${s}`),o("failed",s)}}async function OT(t,e,r,n){let o=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[adr] adr_promote ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{let i=t.source??"task",s=await km(e.contextDir,t.taskKey,t.slugs,void 0,i);if(n.info(`[adr] adr_promote ${t.id}: promoted ${s.promoted.length}, skipped ${s.skipped.length}`+(s.promoted.length>0?` (${s.promoted.join(", ")})`:"")),s.missing.length>0){let a=l=>i==="staging"?`adr/DRAFT-${l}.md`:`tasks/${t.taskKey}/adr/DRAFT-${l}.md`,c=`draft file(s) missing in clone: ${s.missing.map(a).join(", ")}`;n.warn(`[adr] adr_promote ${t.id}: ${c}`),o("failed",c);return}o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[adr] adr_promote ${t.id} failed: ${s}`),o("failed",s)}}function tu(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}Le();me();zt();nu();xt();rs();async function Ay(t={profile:void 0}){let{cfg:e,profile:r}=xn(t.profile),n=X(e.projectId);n&&Co(n),Do(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Uo(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),Bo(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=Zo(ou(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Oi("CLI_LOG",i,o);if(s.enabled){let d=new Rn(s);Li(d),console.log(`[log] file logging \u2192 ${d.path} (rotate at ${s.maxBytes}B, keep ${s.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let a=null,c=vn(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=Zo(ou(),".codepipe",r?Zo("profiles",r,"context"):"context");if(await Bl(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await Cy(()=>Bs({cfg:e,secrets:n,contextDir:d,log:{info:f=>console.log(f),warn:f=>console.warn(f)}}),{log:{warn:f=>console.warn(f)}}),a||await Bl(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let f=Zo(ou(),".codepipe",r?Zo("profiles",r,"context-config"):"context-config");Wi(a.contextDir,f,{info:m=>console.log(m),warn:m=>console.warn(m)})}}let l=Ds(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(`
1078
- [${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}Zn();Ve();Le();async function Bb(t={profile:void 0}){let e=dt(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Ss(e.hubUrl,e.cliToken),n=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let u=l.toString("utf-8");if(s.push(`msg:${u}`),u!=="pong")try{let p=JSON.parse(u);p.type==="registered"?(a=!!p.ok,clearTimeout(c),r.send("ping")):p.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,u)=>{s.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of n.events)console.log(` ${i}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await se(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=Ge(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`)")}di();import{readFileSync as p_}from"node:fs";M();Ve();zt();ai();Br();Yt();Dr();Le();me();function Se(t){throw new Error(t)}function Pe(t,e){return(typeof t!="string"||t.trim().length===0)&&Se(`config: '${e}' must be a non-empty string`),t.trim()}function mi(t,e){if(t==null)return;typeof t!="string"&&Se(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function f_(t){(!t||typeof t!="object")&&Se("config: expected a JSON object");let e=t,r=Pe(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||Se("config: 'hubUrl' must start with http(s)://");let n=Pe(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&Se("config: 'project' is required");let i=o,s=Pe(i.id,"project.id");er.test(s)||Se("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=Pe(i.name,"project.name"),c=Pe(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&Se("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||Se("config: 'project.repos' must be an array");let u=l.map((v,y)=>{(!v||typeof v!="object")&&Se(`config: project.repos[${y}] must be an object`);let k=v,C=Pe(k.host,`project.repos[${y}].host`);C!=="github"&&C!=="bitbucket"&&C!=="gitlab"&&Se(`config: project.repos[${y}].host must be 'github', 'bitbucket' or 'gitlab'`);let E={name:Pe(k.name,`project.repos[${y}].name`),host:C,owner:Pe(k.owner,`project.repos[${y}].owner`),repoName:Pe(k.repoName,`project.repos[${y}].repoName`)},$=mi(k.defaultBranch,`project.repos[${y}].defaultBranch`);$&&(E.defaultBranch=$);let A=mi(k.mountAs,`project.repos[${y}].mountAs`);return A&&(E.mountAs=A),E}),p=i.contextRepo;(!p||typeof p!="object")&&Se("config: 'project.contextRepo' is required");let d=p,f=mi(d.host,"project.contextRepo.host")??"github";f!=="github"&&f!=="bitbucket"&&f!=="gitlab"&&Se("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let m={host:f,owner:Pe(d.owner,"project.contextRepo.owner"),name:mi(d.name,"project.contextRepo.name")??At(s)},g={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:m}},b=mi(i.youtrackProjectKey,"project.youtrackProjectKey");if(b&&(g.project.youtrackProjectKey=b),i.index!==void 0&&(typeof i.index!="boolean"&&Se("config: 'project.index' must be a boolean"),g.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&Se("config: 'project.youtrackWrites' must be a boolean"),g.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let v=Pe(i.llmProvider,"project.llmProvider");v==="codex"&&Se(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),v!=="claude"&&Se("config: 'project.llmProvider' must be 'claude'"),g.project.llmProvider=v}let w=e.secrets;if(w!==void 0){(typeof w!="object"||w===null)&&Se("config: 'secrets' must be an object");let v=w,y={};if(v.github){let k=v.github;y.github={token:Pe(k.token,"secrets.github.token")}}if(v.bitbucket){let k=v.bitbucket;y.bitbucket={email:Pe(k.email,"secrets.bitbucket.email"),apiToken:Pe(k.apiToken,"secrets.bitbucket.apiToken")}}if(v.gitlab){let k=v.gitlab;y.gitlab={token:Pe(k.token,"secrets.gitlab.token")}}if(v.youtrack){let k=v.youtrack;y.youtrack={url:Pe(k.url,"secrets.youtrack.url").replace(/\/$/,""),token:Pe(k.token,"secrets.youtrack.token")}}if(v.contextWrite){let k=v.contextWrite;y.contextWrite={token:Pe(k.token,"secrets.contextWrite.token")}}g.secrets=y}return g}async function m_(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function h_(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await tr(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${n}`)}if(e.bitbucket){let r=t.project.repos.find(i=>i.host==="bitbucket"),n=r?.owner??(t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:void 0),o=await rr(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await Bi(e.bitbucket.email,e.bitbucket.apiToken,r.owner,r.repoName);if(i)throw new Error(`Bitbucket: ${i}`)}console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await nr(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await sr({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Qk(t){let e=!t.configPath||t.configPath==="-"?await m_():p_(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){Se(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=f_(r),{hubUrl:o,cliToken:i,project:s}=n;console.log(`codepipe init --headless \u2192 ${o} (project=${s.id})`),t.skipVerify||(console.log("verifying credentials\u2026"),await h_(n));let a={projectId:s.id,name:s.name,automationLevel:s.automationLevel,repos:s.repos};s.youtrackProjectKey&&(a.youtrackProjectKey=s.youtrackProjectKey),console.log(`provisioning Context Repo ${s.contextRepo.owner}/${s.contextRepo.name} (${s.contextRepo.host})\u2026`);let c=n.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,l;try{l=await Qn(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??En(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){Se(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let u;try{u=await pr(o,i,a)}catch(d){if(d instanceof V&&d.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await se(o,i,s.id);else if(d instanceof V)Se(`HUB \u2192 ${d.status} ${d.message}`);else throw d}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let p={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(ce(p),qt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${_t(s.id)}`),cr(s.id,Nt(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,s.llmProvider??tt),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await Xo(o,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${d}); runs once a SANDBOX claims it.`)}catch(d){console.warn(`could not enqueue index job: ${d instanceof Error?d.message:String(d)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}Ve();me();import{cancel as ev,intro as tv,isCancel as rv,log as sd,outro as g_,password as nv}from"@clack/prompts";async function y_(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function ov(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await y_(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){tv("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),sd.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await nv({message:"Claude OAuth token"});rv(i)&&(ev("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),pf({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Ni()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=dt(t.profile);if(!e){tv(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),sd.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await nv({message:"Claude OAuth token"});rv(i)&&(ev("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=X(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},ce(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(sd.success("Claude OAuth token saved."),g_("It will be sealed into job bundles when a SANDBOX (re)connects."))}Jo();M();Ve();zt();ai();Br();ra();Le();me();import{cancel as w_,confirm as b_,intro as k_,isCancel as iv,log as Ke,outro as v_,select as sv,text as $r}from"@clack/prompts";function av(t){w_(t),process.exit(1)}function io(t){return iv(t)&&av("aborted"),t}function hi(t){return iv(t)&&av("aborted"),typeof t=="string"?t:""}async function $_(t,e){let r=io(await sv({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),n=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",o=hi(await $r({message:"Context Repo owner (org / group / workspace / user)",placeholder:n||"your-org",initialValue:n,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=hi(await $r({message:"Context Repo name",placeholder:At(t),initialValue:At(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function cv(t={profile:void 0}){let e=dt(t.profile);k_(`codepipe project add \u2192 ${e.hubUrl}`);let r=io(await $r({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>er.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=io(await $r({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=io(await sv({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"})),i=io(await $r({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=io(await b_({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=hi(await $r({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()||Ze(w)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!d)break;let f=Ze(d);Ke.message(`${f.host}: ${f.owner}/${f.repoName}`);let m=hi(await $r({message:"repo logical name (used inside Context Repo paths)",placeholder:f.repoName,initialValue:f.repoName,validate:w=>w.trim().length>0?void 0:"required"})).trim(),g=hi(await $r({message:"default branch (optional)",placeholder:"main"})).trim(),b={name:m,host:f.host,owner:f.owner,repoName:f.repoName};g&&(b.defaultBranch=g),a.push(b)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await $_(r,a),u=X(e.projectId);Ke.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await Qn(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:s,trackerUrl:u?.youtrack?.url,log:{info:d=>Ke.message(d),warn:d=>Ke.warn(d)}})}catch(d){Ke.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,Ke.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await pr(e.hubUrl,e.cliToken,c);Ke.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),cr(r,Nt(c,s,u?.youtrack?.url),{info:f=>Ke.message(f),warn:f=>Ke.warn(f)}),d.contextRepo&&(Ke.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),Ke.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&Ke.error(` error: ${d.provisioningError}`),v_("done")}catch(d){d instanceof V?(Ke.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&Ke.message(JSON.stringify(d.payload,null,2))):Ke.error(d instanceof Error?d.message:String(d)),process.exit(1)}}Zn();Ve();Le();me();xt();di();import{existsSync as x_,rmSync as S_}from"node:fs";import{confirm as E_,intro as R_,isCancel as T_,log as xr,outro as I_,spinner as C_}from"@clack/prompts";function Dt(t){xr.error(t),process.exit(1)}var lv=t=>t.trim().replace(/\/+$/,"");async function uv(t){R_("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??je()?.spec.projectId??void 0;e||Dt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=St(e);r||Dt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=lv(r.hubUrl),o=r.projectId,i=lv(t.hub);i.startsWith("http")||Dt("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&Dt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let w=C_();w.start(`reading project ${o} from ${n}\u2026`);try{l=await se(n,r.cliToken,o),w.stop(`read project ${o} (${l.name})`)}catch(v){throw w.stop("could not read the source project",1),v instanceof V&&Dt(`source HUB ${n} \u2192 ${v.status} ${v.message}. The source HUB must be reachable with a valid token to move a project.`),v}}l.contextRepo||Dt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=X(o),p=(t.account??r.accountEmail??await no()).trim().toLowerCase();if(xr.message(`move project '${o}'
1068
+ ${e.body}`),ue({prNumber:e.prNumber,inline:!1,host:s.name})}case"tracker_status":{let i=Ot({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),ue({issueId:t.trackerIssueId,newStatus:e.newStatus})):Q("no tracker_issue_id provided"):Q(i.error)}case"tracker_comment":{let i=Ot({contextDir:t.contextDir});if(!i.ok)return Q(i.error);if(!t.trackerIssueId)return Q("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return ue({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Ot({contextDir:t.contextDir});if(!i.ok)return Q(i.error);if(!e.projectKey)return Q("no projectKey in create_tracker_issue action");let{id:s,key:a}=await i.provider.createIssue({projectKey:e.projectKey,title:e.title,body:e.body,targetStatus:e.targetStatus});return ue({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Ot({contextDir:t.contextDir});if(!i.ok)return Q(i.error);let s=0;for(let a of e.links)try{await i.provider.applyLink(a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return Q(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return ue({applied:s})}case"set_project_setting":{if(!t.contextDir)return Q("no context repo clone on this CLI");let i=await mh(t.contextDir,e.edits);return ue({files:i.files})}case"set_prompt_override":{if(!t.contextDir)return Q("no context repo clone on this CLI");if(!dc(e.role))return Q(`unknown prompt operation: ${e.role}`);let i=pc(e.role);return await Ce(t.contextDir,[e.content===null?{path:i,content:"",deleted:!0}:{path:i,content:e.content}],e.commitMessage),t.requestConfigReport?.(),ue({path:i,reset:e.content===null})}case"tracker_edit":{let i=Ot({contextDir:t.contextDir});if(!i.ok)return Q(i.error);if(!t.contextDir)return Q("no context repo clone on this CLI");await i.provider.editIssue(e.issueKey,{...e.title!==void 0?{title:e.title}:{},...e.body!==void 0?{body:e.body}:{}});let s=await i.provider.getIssue(e.issueKey);return s&&await ws(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),ue({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return Q("no context repo clone on this CLI");let i=await xh(t.contextDir,e);return ue({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return Q("no context repo clone on this CLI");let i=await vh(t.contextDir,e);return ue({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ue({reported:!0})):Q("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return Q("no context repo clone on this CLI");let i=await t.refreshContextStatus();return ue({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return Q("no project workspace on this CLI");if(!r)return Q("no repo spec");if(!t.onRunActivity)return Q("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=Ki(t.contextDir),c=s.find(f=>f.id===e.actionId);if(!c){let f=a.find(m=>m.file===`actions/${e.actionId}.yml`);return Q(f?`action "${e.actionId}" failed to parse: ${f.error}`:`unknown action "${e.actionId}"`)}let l=Qa(c,e.input);if(!l.ok)return Q(l.error);let u=fm(t.contextDir),p=X(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),Vo(`${e.projectId}/${r.name}`,async()=>{await pr(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let f=Oe(e.projectId,r.name,t.baseDir),m=await uh({cwd:f,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:g=>i(e.runId,g)});return ue({runId:e.runId,status:m.status,exitCode:m.exitCode,...m.failedStep?{failedStep:m.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return Q("no context repo clone on this CLI");let i=fh(t.contextDir,e.path);return ue({path:e.path,...i})}case"search_model":{if(!t.contextDir)return Q("no context repo clone on this CLI");let{searchModelIndex:i}=await Promise.resolve().then(()=>(Wo(),Ho)),s=await i(t.contextDir,e.q,e.limit);return ue({hits:s})}case"model_drift":return Q("model_drift requires a local workspace (handled by the daemon)");case"model_bootstrap":return Q("model_bootstrap requires a local workspace (handled by the daemon)");default:return Q(`unsupported action type: ${e.type}`)}}catch(i){return Q(i instanceof Error?i.message:String(i))}}function ue(t){return{status:"done",result:t}}function Q(t){return{status:"failed",error:t}}gt();Dl();Le();me();import{existsSync as Fg,readFileSync as Gg}from"node:fs";import{join as Kg}from"node:path";async function Hg(t,e,r,n){let o=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return o(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=ze(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");xs(e.farmId,e.farmPublicKey);let s=X(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await se(t.hubUrl,t.cliToken,t.projectId),c;if(r){let d=Kg(r,"project.yaml"),f=Kg(r,"regimen.yaml");Fg(d)&&Fg(f)?c={projectYaml:Gg(d,"utf-8"),regimenYaml:Gg(f,"utf-8")}:n.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},u=Jt(e.farmPublicKey,JSON.stringify(l));$s(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let p=await Es(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:u});return p.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...p.daemonStatus?{daemonStatus:p.daemonStatus}:{}}:o(p.error??"farm provisioning failed")}catch(i){return o(i instanceof Error?i.message:String(i))}}M();gt();Ye();gt();import{homedir as ZR}from"node:os";import{existsSync as QR,mkdirSync as eT,readFileSync as tT,writeFileSync as rT}from"node:fs";import{dirname as nT,join as oT}from"node:path";function Fl(){return ee("RUNNER_PINS")??oT(ZR(),".codepipe","runner-pins.json")}function Wg(){let t=Fl();if(!QR(t))return{};try{return JSON.parse(tT(t,"utf-8"))}catch{return{}}}function iT(t){let e=Fl();eT(nT(e),{recursive:!0}),rT(e,JSON.stringify(t,null,2)+`
1069
+ `,{mode:384})}function sT(t){return Wg()[t]}function Gl(t,e){let r=Wg();r[t]=e,iT(r)}function qg(t,e){let r=ze(e),n=sT(t);if(n&&n!==r)throw new Error(`runner host ${t} key fingerprint changed (pinned ${n}, now ${r}) \u2014 refusing to seal. If the runner host was re-registered intentionally, remove its entry from ${Fl()}.`);return r}Le();me();var Vg=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function Yg(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:Vg(t)});if(!o.ok)throw new Error(`github ${n} for ${e}/${r}: HTTP ${o.status}`);let i=await o.json();if(!i.token)throw new Error(`github ${n} for ${e}/${r}: no token in response`);return i.token}var aT={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Vg(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)=>Yg(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Yg(t,e,r,"remove-token")},zg={api:aT,fetchProject:se,provisionOnRunner:Pg,teardownOnRunner:Ag};async function Xg(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(ze(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");qg(e.runnerId,e.runnerPublicKey);let i=X(t.projectId)?.github?.token;if(!i)throw new Error("no GitHub token stored for this project on this CLI");let a=((await r.fetchProject(t.hubUrl,t.cliToken,t.projectId)).repos??[]).find(c=>c.host==="github"&&c.owner===e.owner&&c.repoName===e.repo);if(!a)throw new Error(`${e.owner}/${e.repo} is not a GitHub repository of this project`);return{githubToken:i,repo:a}}async function Jg(t,e,r,n=zg){let o=i=>({type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repo:s}=await Xg(t,e,n);if(!await n.api.repoHasAdmin(i,s.owner,s.repoName))return o(`the GitHub token lacks admin access on ${s.owner}/${s.repoName} \u2014 replace it (project page \u2192 Tokens \u2192 Replace) with a token that has admin rights on this repository`);let a={projectId:t.projectId,runners:[{owner:s.owner,repo:s.repoName,regToken:await n.api.mintRegistrationToken(i,s.owner,s.repoName)}],labels:[wc(e.runnerId)]},c=Jt(e.runnerPublicKey,JSON.stringify(a));Gl(e.runnerId,e.fingerprint),r.info(`[ghr] registration token for ${s.owner}/${s.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let l=await n.provisionOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:c});return{type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:l.ok,...l.runners?{runners:l.runners}:{},...l.error?{error:l.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}async function Zg(t,e,r,n=zg){let o=i=>({type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repo:s}=await Xg(t,e,n),a={owner:s.owner,repo:s.repoName};try{a.removeToken=await n.api.mintRemoveToken(i,s.owner,s.repoName)}catch(p){r.warn(`[ghr] remove-token for ${s.owner}/${s.repoName} failed (${p instanceof Error?p.message:p}) \u2014 the runner host will force-remove`)}let c={projectId:t.projectId,runners:[a]},l=Jt(e.runnerPublicKey,JSON.stringify(c));Gl(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle for ${s.owner}/${s.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let u=await n.teardownOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:l,owner:s.owner,repo:s.repoName});return{type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:u.ok,...u.error?{error:u.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}Le();M();import{existsSync as cT}from"node:fs";import{join as Qg}from"node:path";import{simpleGit as ty}from"simple-git";async function Kl(t,e,r,n,o){for(let i of r.repos){let s=e.find(u=>u.name===i.repoName);if(!s)continue;let a=`${r.taskKey}:${s.name}:${i.branchName}`;if(!er(i.branchName)){n.has(a)||(n.add(a),o.warn(`[pull] ${r.taskKey} ${s.mountAs}: refusing suspicious branch name`));continue}let c=Qg(t,s.mountAs);if(!cT(Qg(c,".git")))continue;let l=ty(c);try{let u=await dT(l,i.branchName);await l.fetch(await lT(l,s),`refs/heads/${i.branchName}`);let p=(await l.revparse(["FETCH_HEAD"])).trim();if(u===p)continue;if(await uT(l,c,i.branchName)){n.has(a)||(n.add(a),o.info(`[pull] ${r.taskKey} \u2192 ${s.mountAs}: ${i.branchName} is checked out here \u2014 fetched ${p.slice(0,10)}; merge or pull it in that checkout yourself`));continue}await l.raw(["branch","-f",i.branchName,p]),o.info(`[pull] ${r.taskKey} \u2192 ${s.mountAs}: ${i.branchName} ${p.slice(0,10)} (checkout untouched)`)}catch(u){if(n.has(a))continue;n.add(a),o.warn(`[pull] ${r.taskKey} ${s.mountAs}: ${i.branchName} unavailable \u2014 `+(u instanceof Error?u.message.split(`
1070
+ `)[0]:String(u)))}}}async function lT(t,e){if(e.mirror)return ey(e.mirror);try{if((await t.getRemotes(!0)).find(n=>n.name==="origin")?.refs?.fetch)return"origin"}catch{}return e.host&&e.owner&&e.repoName?ey({host:e.host,owner:e.owner,repoName:e.repoName}):"origin"}function ey(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 uT(t,e,r){try{return(await t.raw(["worktree","list","--porcelain"])).split(`
1071
+ `).some(o=>o.trim()===`branch refs/heads/${r}`)}catch{try{return(await ty(e).revparse(["--abbrev-ref","HEAD"])).trim()===r}catch{return!1}}}async function dT(t,e){try{return(await t.revparse([e])).trim()}catch{return null}}var Is=class{constructor(e,r,n,o){this.intervalMs=e;this.fetchDeliverables=r;this.workspace=n;this.log=o}timer=null;running=!1;caughtUp=!1;warned=new Set;start(){if(this.timer)return;this.log.info(`[pull] local delivery started (interval=${this.intervalMs}ms)`);let e=()=>void this.runOnce();e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[pull] local delivery stopped"))}poke(){this.runOnce()}async runOnce(){if(!this.running){this.running=!0;try{let e=await this.fetchDeliverables(),r=this.caughtUp?e.filter(n=>n.phase==="TRACKING"||n.phase==="AWAITING_CLUSTER"):e;for(let n of r)await Kl(this.workspace.root,this.workspace.repos,n,this.warned,this.log);this.caughtUp=!0}catch(e){this.log.warn(`[pull] pass failed: ${e instanceof Error?e.message:String(e)}`)}finally{this.running=!1}}}};M();gt();me();var ry=16*1024;function pT(t){return rt.test(t)?Wt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${rt}`}function ny(t,e,r,n){let o=pT(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(Un(n,r).toString("utf-8"));if(typeof s.value!="string"||s.value.length===0)return{ok:!1,detail:"payload has no value"};i=s.value}catch(s){return{ok:!1,detail:`cannot open the sealed secret (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}if(i.length>ry)return{ok:!1,detail:`secret value too large (max ${ry} chars)`};try{return df(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function oy(t,e){try{return pf(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)}}}Cn();me();Vt();var Cs=class{constructor(e,r,n){this.intervalMs=e;this.send=r;this.log=n}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let n=[],o=e.split(":",2)[0]??"";for(let a of r.prs){let{spec:c,host:l}=ir(o,a.repoSpec);try{let u=await l.getPullRequest(c,a.number);n.push({number:a.number,repoName:a.repoSpec.name,url:a.url,state:u.state,merged:u.merged,ci:u.ci,mergeable:u.mergeable})}catch(u){if(u instanceof Mr){this.log.warn(`[track] task=${e} pr=${a.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${a.url} fetch failed: ${u instanceof Error?u.message:String(u)}`);return}}let i=n.map(a=>`${a.repoName??""}#${a.number}:${a.state}:${a.merged?1:0}:${a.ci}:${a.mergeable}`).join("|");if(this.lastSig.get(e)===i)return;for(let a=0;a<n.length;a++){let c=n[a];if(c.ci!=="failed")continue;let{spec:l,host:u}=ir(o,r.prs[a].repoSpec);if(u.getCiFailureLog)try{let p=await u.getCiFailureLog(l,c.number);p&&(c.ciFailureLog=p)}catch(p){this.log.warn(`[track] task=${e} pr=${c.url} ci-log fetch failed: ${p instanceof Error?p.message:String(p)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:n}),this.lastSig.set(e,i);let s=fT(n);this.log.info(`[track] task=${e} snapshot signalled${s?` \u2192 ${s}`:""} (${n.length} PR(s))`)}};function fT(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}M();Dn();var Ps=class{constructor(e,r,n,o=i=>es(Mn(i))){this.intervalMs=e;this.send=r;this.log=n;this.listBranches=o}projectId="";repos=[];lastSig=new Map;timer=null;running=!1;setRepos(e,r){this.projectId=e,this.repos=r,this.lastSig.clear()}start(){if(this.timer)return;this.log.info(`[branches] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[branches] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs),typeof this.timer.unref=="function"&&this.timer.unref()}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[branches] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let e of this.repos)await this.processRepo(e)}finally{this.running=!1}}}async processRepo(e){let r=e.gitFlow;if(!r||r.flow==="simple")return;let n;try{n=await this.listBranches(e)}catch(s){this.log.warn(`[branches] repo=${e.name} ls-remote failed: ${s instanceof Error?s.message:String(s)}`);return}let o=n.filter(s=>Sc(s,r)).sort(),i=o.join("|");this.lastSig.get(e.name)!==i&&(this.send({type:"branches_observation",projectId:this.projectId,repoName:e.name,branches:o}),this.lastSig.set(e.name,i),this.log.info(`[branches] repo=${e.name} reported ${o.length} base candidate(s)`))}};M();Vt();var As=class{constructor(e,r,n,o=mT,i=hT){this.intervalMs=e;this.send=r;this.log=n;this.read=o;this.readFailureLog=i}projectId="";repos=[];lastSig=new Map;timer=null;running=!1;setRepos(e,r){this.projectId=e,this.repos=r;let n=new Set(r.map(o=>o.name));for(let o of[...this.lastSig.keys()])n.has(o)||this.lastSig.delete(o)}start(){if(this.timer)return;this.log.info(`[branch-ci] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[branch-ci] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs),typeof this.timer.unref=="function"&&this.timer.unref()}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}async tick(){if(!(this.running||!this.projectId)){this.running=!0;try{for(let e of this.repos){let r=wn(e);try{let n=await this.read(this.projectId,e,r);if(!n||n.ci==="none")continue;let o=`${r}:${n.ci}:${n.headSha}`;if(this.lastSig.get(e.name)===o)continue;let i;n.ci==="failed"&&(i=await this.readFailureLog(this.projectId,e,n.headSha).catch(()=>{})),this.send({type:"branch_ci_observed",projectId:this.projectId,repoName:e.name,branch:r,ci:n.ci,headSha:n.headSha,...i?{ciFailureLog:i}:{}}),this.lastSig.set(e.name,o),this.log.info(`[branch-ci] ${e.name}#${r}: ${n.ci} @ ${n.headSha.slice(0,10)}`)}catch(n){this.log.warn(`[branch-ci] ${e.name}#${r}: read failed \u2014 ${n instanceof Error?n.message:String(n)}`)}}}finally{this.running=!1}}}};async function mT(t,e,r){let{spec:n,host:o}=ir(t,e);if(!o.getBranchCi)return null;let i=await o.getBranchCi(n,r);return i?{ci:i.ci,headSha:i.headSha}:null}async function hT(t,e,r){let{spec:n,host:o}=ir(t,e);if(o.getCiFailureLogForSha)return await o.getCiFailureLogForSha(n,r)}M();var _s=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??(()=>Ot({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 y=e.stageField?{stageField:e.stageField}:{},k=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??[]])],[A,N]=await Promise.all([$.length>0?r.listIssues({projectKey:e.projectKey,columns:$,...y,...k}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...y})]),B=new Map;for(let H of[...A,...N])B.set(H.id,H);o=[...B.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:$,...y,...k})}}catch(y){let k=y instanceof Error?y.message:String(y);k.includes("stage_field")?this.log.warn(`[yt-sync] CONFIGURATION ERROR \u2014 ${k}`):this.log.warn(`[yt-sync] listIssues failed: ${k}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let y of o){if(s.add(y.id),a.has(y.status))continue;let k=await ay(r,y.id,e.sinceMs,this.log);k&&i.set(y.id,k)}let c=[];for(let y of e.offBoardIssueIds){if(s.has(y))continue;let k=await ay(r,y,e.sinceMs,this.log);k&&k.length>0&&i.set(y,k);let C=await sy(r,y,e.stageField,this.log);if(C)c.push(C);else if(k&&k.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}let l=o.filter(y=>!a.has(y.status)),{attachmentsByIssue:u,attachmentKeys:p}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let d=[...l,...c].map(y=>({issue:y,comments:i.get(y.id)??[],attachments:u.get(y.id)??[]}));d.push(...await yg(this.options.contextDir,d,y=>sy(r,y,e.stageField,this.log)));try{await ws(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let y of p)this.shippedAttachments.add(y)}catch(y){let k=y instanceof Error?y.message:String(y);this.abandonTick(`context task sync failed: ${k}`);return}let f=this.options.isSelfComment??(()=>!1),m=[],g=[];for(let[y,k]of i){let C=k.filter($=>!f($.id));if(C.length===0)continue;m.push({issueId:y,comments:C.map(gT)});let E=C.flatMap($=>{let A=Nr($.body);return A?[{commentId:$.id,author:$.author,name:A.name,args:A.args,createdAt:$.createdAt}]:[]});E.length>0&&g.push({issueId:y,commands:E})}let b={type:"youtrack_observation",projectId:e.projectId,issues:o.map(iy),commentsBatch:m,...g.length>0?{commandsBatch:g}:{},...c.length>0?{offBoardIssues:c.map(iy)}:{},observedAtMs:n};this.send(b);let w=m.reduce((y,k)=>y+k.comments.length,0),v=g.reduce((y,k)=>y+k.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${w} commands=${v} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let p=`${s.id}:${u.id}`;if(this.shippedAttachments.has(p))continue;let d;try{d=await n.downloadAttachment(u.url)}catch(m){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${m instanceof Error?m.message:String(m)}`);continue}let f=yT(u.name);l.has(f)&&(f=`${u.id}-${f}`),l.add(f),c.push({name:f,contentBase64:d.toString("base64")}),i.push(p)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}};function iy(t){let{description:e,...r}=t;return r}function gT(t){let{body:e,...r}=t;return r}function yT(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 sy(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 ay(t,e,r,n){try{return await t.listComments(e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function NT(t,e){let r=t.repos.filter(i=>i.mirror);if(r.length===0)return[];let{mirrorLag:n}=await Promise.resolve().then(()=>(ks(),bs)),o=[];for(let i of r){let s=i.mountAs==="."?t.root:Wr(t.root,i.mountAs);try{o.push({repo:i.name,behind:await n(i,s)})}catch(a){e.warn(`[mirror] lag for ${i.name} unknown: ${a instanceof Error?a.message:String(a)}`),o.push({repo:i.name,behind:null})}}return o}var Ql="npm i -g @code-partner/codepipe@latest";function Ds(t,e={}){let r=e.log??{info:y=>console.log(y),warn:y=>console.warn(y)};r.info(`codepipe-cli v${et} (protocol ${kt})`);let n=y=>e.onEvent?.(y),o=e.workspace;o?.contextDir&&gm(o.contextDir,r);let i=()=>{if(o?.contextDir)try{jn(o.contextDir,o.root,r)}catch(y){r.warn(`[skills] materialize failed (non-fatal): ${y instanceof Error?y.message:String(y)}`)}};i();let s=tu("CLI_TRACKING_POLL_INTERVAL_SEC"),a=parseInt(process.env.CLI_BRANCH_CI_POLL_INTERVAL_SEC??"300",10),c=Number.isFinite(a)&&a>0?a*1e3:3e5,l=tu("CLI_YOUTRACK_POLL_INTERVAL_SEC"),u=(()=>{let y=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(y)&&y>0?y*1e3:6e5})(),p=!1,d=!1,f=!1,m=new Set,g=!1,b=new Set,w=v();function v(){let y=Ss(t.hubUrl,t.cliToken),k=null,C=new Cs(s,U=>{y.readyState===y.OPEN&&y.send(JSON.stringify(U))},r),E=new Ps(s,U=>{y.readyState===y.OPEN&&y.send(JSON.stringify(U))},r),$=new As(c,U=>{y.readyState===y.OPEN&&y.send(JSON.stringify(U))},r),A=o&&o.repos.length>0?new Is(tu("CLI_LOCAL_PULL_INTERVAL_SEC"),()=>Ts(t.hubUrl,t.cliToken,t.projectId),{root:o.root,repos:o.repos},r):null,N=new _s(l,U=>{y.readyState===y.OPEN&&y.send(JSON.stringify(U))},r,{contextDir:o?.contextDir??null,isSelfComment:U=>b.has(U)}),B=null,H=async()=>{try{let U={trackerProvider:Ol(o?.contextDir??null)};try{let S=await se(t.hubUrl,t.cliToken,t.projectId);U={...U,repos:S.repos,contextRepo:S.contextRepo},E.setRepos(t.projectId,S.repos),$.setRepos(t.projectId,S.repos)}catch(S){r.warn(`[readiness] could not fetch project summary for push checks: ${S instanceof Error?S.message:String(S)}`)}let G=await tm(t.projectId,U),D=o?await NT(o,r):[];if(i(),y.readyState!==y.OPEN)return;let T={type:"cli_readiness",projectId:t.projectId,ready:G.ready,checks:G.checks,creds:G.creds,secretNames:ff(t.projectId),...o?{mirrors:D}:{},checkedAt:G.checkedAt};if(y.send(JSON.stringify(T)),G.ready)r.info("[readiness] ready");else{let S=G.checks.filter(I=>!I.ok).map(I=>`${I.name}(${I.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${S.join(", ")}`)}let R=am(G.creds,f);if(R==="open"){f=!0;let S=cm(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${S}`),Br(S)}else R==="rearm"&&(f=!1)}catch(U){r.warn(`[readiness] check failed: ${U instanceof Error?U.message:String(U)}`)}},j=()=>{H(),B=setInterval(()=>void H(),u),typeof B.unref=="function"&&B.unref()},h=()=>{B&&(clearInterval(B),B=null)},F=150,L=new Map,z=U=>{let G=L.get(U);if(!G||(G.timer&&clearTimeout(G.timer),L.delete(U),G.events.length===0||y.readyState!==y.OPEN))return;let D={type:"run_activity",projectId:t.projectId,runId:U,events:G.events};y.send(JSON.stringify(D))},te=(U,G)=>{let D=L.get(U);if(D||(D={events:[],timer:null},L.set(U,D)),D.events.push(G),G.kind==="result"){z(U);return}D.timer||(D.timer=setTimeout(()=>z(U),F),D.timer.unref?.())},ae=o?.contextDir?new Hi(o.contextDir,t.projectId,U=>{y.readyState===y.OPEN&&y.send(JSON.stringify(U))},r):null,Ut=async()=>{let U=o?.contextDir;if(!U)throw new Error("no context repo clone on this CLI");let G;try{G=(await se(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let D=await Gm(U,t.projectId,G,r);return y.readyState===y.OPEN&&y.send(JSON.stringify(D)),D},We=null,Ue=async()=>{let U=o?.contextDir;if(U)try{let{readContextIndexHub:G,collectSearchRows:D}=await Promise.resolve().then(()=>(Wo(),Ho));if(G(U)!=="metadata")return;let T=D(U);y.readyState===y.OPEN&&(y.send(JSON.stringify({type:"model_index",projectId:t.projectId,rows:T})),r.info(`[model] tier-2 index snapshot pushed (${T.length} rows)`))}catch(G){r.warn(`[model] tier-2 index push failed (non-fatal): ${G instanceof Error?G.message:String(G)}`)}},Ae=()=>{We&&clearTimeout(We),We=setTimeout(()=>void Ue(),5e3)},Be=async()=>{if(!o?.contextDir)throw new Error("no Context Repo clone on this CLI");if(g)throw new Error("model bootstrap is already running");g=!0;try{let U=await se(t.hubUrl,t.cliToken,t.projectId),{bootstrapDaemonModel:G}=await Promise.resolve().then(()=>(Zo(),Ms)),D=await G(t.projectId,{root:o.root,contextDir:o.contextDir},U.repos,T=>r.info(`[model] ${T}`));return r.info(`[model] bootstrap done: ${D.repos} repos, ${D.events} task events`),Ae(),D}finally{g=!1}},Te=null,st=async U=>{if(o?.contextDir)try{let G=await Promise.resolve().then(()=>(Zo(),Ms)),D={root:o.root,contextDir:o.contextDir,repos:o.repos};if(G.shouldAutoBootstrapModel(o.contextDir)){await G.syncWorkspaceMirrors(D,R=>r.info(R));try{await Be()}catch(R){r.warn(`[model] auto-bootstrap failed (non-fatal): ${R instanceof Error?R.message:String(R)}`)}return}(await G.rebuildWorkspaceModelIfStale(D,{fetch:U,onLog:R=>r.info(R)})).rebuilt.length>0&&Ae()}catch(G){r.warn(`[model] release-path rebuild failed (non-fatal): ${G instanceof Error?G.message:String(G)}`)}},Bt=U=>{Te&&clearTimeout(Te),Te=setTimeout(()=>void st(U),6e4)},Ft=setInterval(()=>void st(!0),6*36e5);return y.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let U=vf(t.projectId),G=ee("ORIGIN")==="farm"?"farm":"local",D=ee("FARM_ID"),T=t.accountEmail??U.email,R;try{let I=sh(t.projectId);I&&(R=I.publicKey,r.info(`[cred-channel] key fingerprint: ${I.fingerprint}`))}catch(I){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${I instanceof Error?I.message:String(I)}`)}let S={type:"register",projectId:t.projectId,platformVersion:et,protocolVersion:kt,accountId:U.accountId,accountLabel:U.label,origin:G,inFlightActionIds:[...m],...T?{accountEmail:T}:{},...G==="farm"&&D?{farmId:D}:{},...R?{sealPublicKey:R}:{}};y.send(JSON.stringify(S))}),y.on("message",async U=>{let G=U.toString("utf-8");if(G==="pong"||G==="ping")return;let D;try{D=JSON.parse(G)}catch{return}if(!D||typeof D!="object")return;let T=D.type;if(T==="registered"){let S=D;if(S.ok){if(r.info(`[ws] registered for project ${S.projectId}`),n({kind:"registered",projectId:S.projectId??t.projectId}),C.start(),E.start(),$.start(),A?.start(),ae?.start(),j(),eu(t,o,r),o?.contextDir){try{let I=Xi(o.contextDir,t.projectId);y.readyState===y.OPEN&&y.send(JSON.stringify(I)),I.outdated&&(r.warn(`[ctx] context format outdated: v${I.templateVersion} \u2192 v${I.currentVersion}`+(I.missingPaths.length>0?` (missing: ${I.missingPaths.join(", ")})`:"")),d||(d=!0,Ut().catch(()=>{})))}catch(I){r.warn(`[ctx] context-format detect failed (non-fatal): ${I instanceof Error?I.message:String(I)}`)}Ue(),Bt(!0)}}else r.warn(`[ws] register rejected: ${S.reason??"unknown"}`),n({kind:"register_rejected",reason:S.reason??"unknown"}),p=!0,y.close();return}if(T==="hello"){let S=D;k=ho(S.protocolVersion);let I=k?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${S.platformVersion} (protocol ${S.protocolVersion}) \u2014 ${I}`),k||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${et}, protocol ${kt}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Ql}`),n({kind:"incompatible",hubVersion:typeof S.platformVersion=="string"?S.platformVersion:null,hubProtocol:typeof S.protocolVersion=="number"?S.protocolVersion:null,updateCommand:Ql}));return}if(T==="tracking_targets"){C.setTargets(D.targets),A?.poke();return}if(T==="youtrack_sync_request"){N.setRequest(D);return}if(T==="youtrack_force_sync"){N.forceSync();return}if(T==="sync_local"){await MT(D,o,y,r);return}if(T==="provision_repo"){let S=D;r.info(`[repo] provision_repo: ${S.repo.name} (${S.repo.host}:${S.repo.owner}/${S.repo.repoName})`),await OT(t,o,S.repo,r),await eu(t,o,r);return}if(T==="remove_repo"){let S=D;r.info(`[repo] remove_repo: ${S.repoName}${S.purge?" (purge)":""}`),await eu(t,o,r),S.purge&&LT(t,o,S.repoName,r);return}if(T==="context_write"){await DT(D,o,y,r),i();return}if(T==="adr_promote"){await UT(D,o,y,r),i();return}if(T==="cred_update"){let S=D,I=X(t.projectId),J=I?.sealKey?await ah(t.projectId,S.kind,S.sealed,I.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},q={type:"cred_update_result",updateId:S.updateId,projectId:t.projectId,ok:J.ok,...J.detail?{detail:J.detail}:{}};y.readyState===y.OPEN&&y.send(JSON.stringify(q)),J.ok?(r.info(`[cred] ${S.kind} replaced${J.detail?` \u2014 ${J.detail}`:""}`),H()):r.warn(`[cred] ${S.kind} replacement rejected: ${J.detail??"unknown"}`);return}if(T==="readiness_check"){r.info("[readiness] on-demand check requested"),H();return}if(T==="agent_login_start"){sm(t,y,D,r,H);return}if(T==="move_to_farm"){let S=D;r.info(`[farm-move] request to move ${t.projectId} onto farm ${S.farmName} (${S.farmId})`);let I=await Hg(t,S,o?.contextDir,r);y.readyState===y.OPEN&&y.send(JSON.stringify(I)),I.ok?r.info(`[farm-move] done \u2014 farm daemon ${I.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${I.error??"unknown error"}`);return}if(T==="gh_runner_setup"){let S=D;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${S.runnerName} (${S.runnerId})`);let I=await Jg(t,S,r);y.readyState===y.OPEN&&y.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners connected on ${S.runnerName}`):r.warn(`[ghr] setup failed: ${I.error??"see per-repo statuses"}`);return}if(T==="gh_runner_teardown"){let S=D;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${S.runnerName} (${S.runnerId})`);let I=await Zg(t,S,r);y.readyState===y.OPEN&&y.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners disconnected from ${S.runnerName}`):r.warn(`[ghr] teardown failed: ${I.error??"unknown error"}`);return}if(T==="tracker_fields_request"){let S=D,I={type:"tracker_fields_result",requestId:S.requestId,projectId:t.projectId,ok:!1},J=Ot({contextDir:o?.contextDir??null});if(!J.ok)I.error=J.error;else try{I.fields=await J.provider.fetchStateFields(S.projectKey),I.ok=!0}catch(q){I.error=q instanceof Error?q.message:String(q)}y.readyState===y.OPEN&&y.send(JSON.stringify(I)),I.ok||r.warn(`[yt-fields] listing failed: ${I.error??"unknown"}`);return}if(T==="project_secret_update"||T==="project_secret_delete"){let S=D,I;if(S.type==="project_secret_update"){let q=X(t.projectId);I=q?.sealKey?ny(t.projectId,S.name,S.sealed,q.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else I=oy(t.projectId,S.name);let J={type:"project_secret_update_result",updateId:S.updateId,projectId:t.projectId,ok:I.ok,...I.detail?{detail:I.detail}:{}};y.readyState===y.OPEN&&y.send(JSON.stringify(J)),I.ok?(r.info(`[secret] ${S.name} ${S.type==="project_secret_update"?"saved":"deleted"}`+(I.detail?` \u2014 ${I.detail}`:"")),H()):r.warn(`[secret] ${S.name} rejected: ${I.detail??"unknown"}`);return}if(T==="sandbox_keys"){let S=X(t.projectId);if(!S){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let I=En(t.projectId),J=rh(D,S,I,r);for(let q of J)y.readyState===y.OPEN&&y.send(JSON.stringify(q));return}if(T!=="dispatch_action")return;let R=D;if(k===!1){let S=`refused: HUB protocol incompatible with CLI v${et} (protocol ${kt})`;y.send(JSON.stringify({type:"action_result",actionId:R.actionId,status:"failed",error:S})),r.warn(`[exec] ${R.actionId} (${R.action.type}) \u2192 REFUSED: ${S}`),r.warn(`[exec] update the CLI to clear this: ${Ql}`),n({kind:"action",actionId:R.actionId,actionType:R.action.type,ok:!1,error:S});return}if(R.action.type==="model_drift"){m.add(R.actionId);try{let S,I=o?.repos.find(J=>J.name===R.action.repoName);if(!o?.contextDir||!I)S={status:"failed",error:"no local workspace/repo clone on this CLI"};else try{let{computeDriftReport:J}=await Promise.resolve().then(()=>(vy(),ky)),q=I.mountAs==="."?o.root:Wr(o.root,I.mountAs);S={status:"done",result:{report:await J(q,o.contextDir,I.name)}}}catch(J){S={status:"failed",error:J instanceof Error?J.message:String(J)}}y.send(JSON.stringify({type:"action_result",actionId:R.actionId,...S}))}finally{m.delete(R.actionId)}return}if(R.action.type==="model_bootstrap"){m.add(R.actionId);try{let S;try{let I=await Be();S={status:"done",result:{repos:I.repos,events:I.events}}}catch(I){S={status:"failed",error:I instanceof Error?I.message:String(I)},r.warn(`[model] bootstrap failed: ${S.error}`)}y.readyState===y.OPEN&&y.send(JSON.stringify({type:"action_result",actionId:R.actionId,...S}))}finally{m.delete(R.actionId)}return}m.add(R.actionId);try{let S=await Tg({action:R.action,repo:R.repo,trackerIssueId:R.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:ae?()=>ae.reportNow():void 0,refreshContextStatus:o?.contextDir?Ut:void 0,onRunActivity:te}).catch(q=>({status:"failed",error:q instanceof Error?q.message:String(q)}));R.action.type==="tracker_comment"&&S.status==="done"&&"result"in S&&typeof S.result?.commentId=="string"&&b.add(S.result.commentId),y.send(JSON.stringify({type:"action_result",actionId:R.actionId,...S}));let I=S.status!=="failed",J=!I&&"error"in S?S.error:void 0;I?r.info(`[exec] ${R.actionId} (${R.action.type}) \u2192 done`):r.warn(`[exec] ${R.actionId} (${R.action.type}) \u2192 FAILED: ${J??"?"}`),n({kind:"action",actionId:R.actionId,actionType:R.action.type,ok:I,...J?{error:J}:{}}),I&&["apply_delivery","context_write","create_pr"].includes(R.action.type)&&Ae(),I&&["merge_pr","merge_branch"].includes(R.action.type)&&Bt(!0)}finally{m.delete(R.actionId)}}),y.on("close",(U,G)=>{let D=G?.toString("utf-8")??"";if(r.info(`[ws] closed code=${U}${D?` reason=${D}`:""}`),C.stop(),E.stop(),$.stop(),A?.stop(),N.stop(),ae?.stop(),h(),clearInterval(Ft),Te&&clearTimeout(Te),We&&clearTimeout(We),D==="replaced"){p=!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:U}),!p&&setTimeout(()=>{w=v()},2e3)}),y.on("error",U=>r.warn(`[ws] error: ${U.message}`)),y}return{stop(){p=!0,w.close()}}}async function eu(t,e,r){try{let n=await se(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=Do(t.projectId,n.repos,e?.contextDir);for(let s of o)r.info(`[repo] restaged repo set in ${s}`);for(let s of i)r.warn(`[repo] could not restage ${s.path}: ${s.error}`)}catch(n){r.warn(`[repo] repo-set reconcile skipped: ${n instanceof Error?n.message:String(n)}`)}}async function OT(t,e,r,n){let o=r.mountAs??r.name;if(o==="."){n.info(`[repo] ${r.name} mounts in place (mount_as: .) \u2014 nothing to clone`);return}let i=e?Wr(e.root,o):Oe(t.projectId,r.name);if($y(Wr(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await jT().clone(e?Mn(r):ml(r),i),n.info(`[repo] cloned ${r.name} \u2192 ${i}`)}catch(s){n.warn(`[repo] clone of ${r.name} failed (will retry lazily): ${s instanceof Error?s.message.trim():String(s)}`)}}function LT(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?Wr(e.root,o):Oe(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!$y(Wr(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{_T(i,{recursive:!0,force:!0}),n.info(`[repo] purged local clone ${i}`)}catch(s){n.warn(`[repo] purge of ${i} failed: ${s instanceof Error?s.message:String(s)}`)}}async function MT(t,e,r,n){if(!e){n.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let o of t.repos){let i=e.repos.find(l=>l.name===o.repoName),s=Wr(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await lm(s,a).catch(l=>({status:"warn",reason:l instanceof Error?l.message:String(l)}));c.status==="updated"?n.info(`[sync] ${o.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?n.info(`[sync] ${o.repoName}: not cloned in workspace \u2014 skipped`):(n.warn(`[sync] ${o.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:o.repoName,reason:c.reason??"sync skipped"})))}}async function DT(t,e,r,n){let o=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{await Ce(e.contextDir,t.files,t.message),n.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[ctx] context_write ${t.id} failed: ${s}`),o("failed",s)}}async function UT(t,e,r,n){let o=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[adr] adr_promote ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{let i=t.source??"task",s=await xm(e.contextDir,t.taskKey,t.slugs,void 0,i);if(n.info(`[adr] adr_promote ${t.id}: promoted ${s.promoted.length}, skipped ${s.skipped.length}`+(s.promoted.length>0?` (${s.promoted.join(", ")})`:"")),s.missing.length>0){let a=l=>i==="staging"?`adr/DRAFT-${l}.md`:`tasks/${t.taskKey}/adr/DRAFT-${l}.md`,c=`draft file(s) missing in clone: ${s.missing.map(a).join(", ")}`;n.warn(`[adr] adr_promote ${t.id}: ${c}`),o("failed",c);return}o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[adr] adr_promote ${t.id} failed: ${s}`),o("failed",s)}}function tu(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}Le();me();Xt();nu();xt();rs();async function Ny(t={profile:void 0}){let{cfg:e,profile:r}=Sn(t.profile),n=X(e.projectId);n&&Po(n),Uo(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Bo(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),Fo(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=Qo(ou(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Oi("CLI_LOG",i,o);if(s.enabled){let d=new Tn(s);Li(d),console.log(`[log] file logging \u2192 ${d.path} (rotate at ${s.maxBytes}B, keep ${s.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let a=null,c=$n(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=Qo(ou(),".codepipe",r?Qo("profiles",r,"context"):"context");if(await Bl(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await _y(()=>Bs({cfg:e,secrets:n,contextDir:d,log:{info:f=>console.log(f),warn:f=>console.warn(f)}}),{log:{warn:f=>console.warn(f)}}),a||await Bl(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let f=Qo(ou(),".codepipe",r?Qo("profiles",r,"context-config"):"context-config");Wi(a.contextDir,f,{info:m=>console.log(m),warn:m=>console.warn(m)})}}let l=Ds(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(`
1072
+ [${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}Qn();Ve();Le();async function Kb(t={profile:void 0}){let e=dt(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Ss(e.hubUrl,e.cliToken),n=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let u=l.toString("utf-8");if(s.push(`msg:${u}`),u!=="pong")try{let p=JSON.parse(u);p.type==="registered"?(a=!!p.ok,clearTimeout(c),r.send("ping")):p.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,u)=>{s.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of n.events)console.log(` ${i}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await se(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=Ge(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`)")}pi();import{readFileSync as g_}from"node:fs";M();Ve();Xt();ci();Fr();Vt();Ur();Le();me();function Se(t){throw new Error(t)}function Pe(t,e){return(typeof t!="string"||t.trim().length===0)&&Se(`config: '${e}' must be a non-empty string`),t.trim()}function hi(t,e){if(t==null)return;typeof t!="string"&&Se(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function y_(t){(!t||typeof t!="object")&&Se("config: expected a JSON object");let e=t,r=Pe(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||Se("config: 'hubUrl' must start with http(s)://");let n=Pe(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&Se("config: 'project' is required");let i=o,s=Pe(i.id,"project.id");tr.test(s)||Se("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=Pe(i.name,"project.name"),c=Pe(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&Se("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||Se("config: 'project.repos' must be an array");let u=l.map((v,y)=>{(!v||typeof v!="object")&&Se(`config: project.repos[${y}] must be an object`);let k=v,C=Pe(k.host,`project.repos[${y}].host`);C!=="github"&&C!=="bitbucket"&&C!=="gitlab"&&Se(`config: project.repos[${y}].host must be 'github', 'bitbucket' or 'gitlab'`);let E={name:Pe(k.name,`project.repos[${y}].name`),host:C,owner:Pe(k.owner,`project.repos[${y}].owner`),repoName:Pe(k.repoName,`project.repos[${y}].repoName`)},$=hi(k.defaultBranch,`project.repos[${y}].defaultBranch`);$&&(E.defaultBranch=$);let A=hi(k.mountAs,`project.repos[${y}].mountAs`);return A&&(E.mountAs=A),E}),p=i.contextRepo;(!p||typeof p!="object")&&Se("config: 'project.contextRepo' is required");let d=p,f=hi(d.host,"project.contextRepo.host")??"github";f!=="github"&&f!=="bitbucket"&&f!=="gitlab"&&Se("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let m={host:f,owner:Pe(d.owner,"project.contextRepo.owner"),name:hi(d.name,"project.contextRepo.name")??At(s)},g={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:m}},b=hi(i.youtrackProjectKey,"project.youtrackProjectKey");if(b&&(g.project.youtrackProjectKey=b),i.index!==void 0&&(typeof i.index!="boolean"&&Se("config: 'project.index' must be a boolean"),g.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&Se("config: 'project.youtrackWrites' must be a boolean"),g.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let v=Pe(i.llmProvider,"project.llmProvider");v==="codex"&&Se(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),v!=="claude"&&Se("config: 'project.llmProvider' must be 'claude'"),g.project.llmProvider=v}let w=e.secrets;if(w!==void 0){(typeof w!="object"||w===null)&&Se("config: 'secrets' must be an object");let v=w,y={};if(v.github){let k=v.github;y.github={token:Pe(k.token,"secrets.github.token")}}if(v.bitbucket){let k=v.bitbucket;y.bitbucket={email:Pe(k.email,"secrets.bitbucket.email"),apiToken:Pe(k.apiToken,"secrets.bitbucket.apiToken")}}if(v.gitlab){let k=v.gitlab;y.gitlab={token:Pe(k.token,"secrets.gitlab.token")}}if(v.youtrack){let k=v.youtrack;y.youtrack={url:Pe(k.url,"secrets.youtrack.url").replace(/\/$/,""),token:Pe(k.token,"secrets.youtrack.token")}}if(v.contextWrite){let k=v.contextWrite;y.contextWrite={token:Pe(k.token,"secrets.contextWrite.token")}}g.secrets=y}return g}async function w_(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function b_(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await rr(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${n}`)}if(e.bitbucket){let r=t.project.repos.find(i=>i.host==="bitbucket"),n=r?.owner??(t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:void 0),o=await nr(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await Bi(e.bitbucket.email,e.bitbucket.apiToken,r.owner,r.repoName);if(i)throw new Error(`Bitbucket: ${i}`)}console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await or(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await ar({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function rv(t){let e=!t.configPath||t.configPath==="-"?await w_():g_(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){Se(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=y_(r),{hubUrl:o,cliToken:i,project:s}=n;console.log(`codepipe init --headless \u2192 ${o} (project=${s.id})`),t.skipVerify||(console.log("verifying credentials\u2026"),await b_(n));let a={projectId:s.id,name:s.name,automationLevel:s.automationLevel,repos:s.repos};s.youtrackProjectKey&&(a.youtrackProjectKey=s.youtrackProjectKey),console.log(`provisioning Context Repo ${s.contextRepo.owner}/${s.contextRepo.name} (${s.contextRepo.host})\u2026`);let c=n.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,l;try{l=await eo(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??Rn(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){Se(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let u;try{u=await fr(o,i,a)}catch(d){if(d instanceof V&&d.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await se(o,i,s.id);else if(d instanceof V)Se(`HUB \u2192 ${d.status} ${d.message}`);else throw d}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let p={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(ce(p),Yt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${_t(s.id)}`),lr(s.id,Nt(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,s.llmProvider??tt),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await Jo(o,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${d}); runs once a SANDBOX claims it.`)}catch(d){console.warn(`could not enqueue index job: ${d instanceof Error?d.message:String(d)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}Ve();me();import{cancel as nv,intro as ov,isCancel as iv,log as sd,outro as k_,password as sv}from"@clack/prompts";async function v_(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function av(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await v_(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){ov("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),sd.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await sv({message:"Claude OAuth token"});iv(i)&&(nv("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),hf({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Ni()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=dt(t.profile);if(!e){ov(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),sd.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await sv({message:"Claude OAuth token"});iv(i)&&(nv("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=X(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},ce(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(sd.success("Claude OAuth token saved."),k_("It will be sealed into job bundles when a SANDBOX (re)connects."))}Zo();M();Ve();Xt();ci();Fr();ra();Le();me();import{cancel as $_,confirm as x_,intro as S_,isCancel as cv,log as Ke,outro as E_,select as lv,text as xr}from"@clack/prompts";function uv(t){$_(t),process.exit(1)}function so(t){return cv(t)&&uv("aborted"),t}function gi(t){return cv(t)&&uv("aborted"),typeof t=="string"?t:""}async function R_(t,e){let r=so(await lv({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),n=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",o=gi(await xr({message:"Context Repo owner (org / group / workspace / user)",placeholder:n||"your-org",initialValue:n,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=gi(await xr({message:"Context Repo name",placeholder:At(t),initialValue:At(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function dv(t={profile:void 0}){let e=dt(t.profile);S_(`codepipe project add \u2192 ${e.hubUrl}`);let r=so(await xr({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>tr.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=so(await xr({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=so(await lv({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"})),i=so(await xr({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=so(await x_({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=gi(await xr({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()||Ze(w)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!d)break;let f=Ze(d);Ke.message(`${f.host}: ${f.owner}/${f.repoName}`);let m=gi(await xr({message:"repo logical name (used inside Context Repo paths)",placeholder:f.repoName,initialValue:f.repoName,validate:w=>w.trim().length>0?void 0:"required"})).trim(),g=gi(await xr({message:"default branch (optional)",placeholder:"main"})).trim(),b={name:m,host:f.host,owner:f.owner,repoName:f.repoName};g&&(b.defaultBranch=g),a.push(b)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await R_(r,a),u=X(e.projectId);Ke.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await eo(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??Rn(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:d=>Ke.message(d),warn:d=>Ke.warn(d)}})}catch(d){Ke.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,Ke.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await fr(e.hubUrl,e.cliToken,c);Ke.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),lr(r,Nt(c,s,u?.youtrack?.url),{info:f=>Ke.message(f),warn:f=>Ke.warn(f)}),d.contextRepo&&(Ke.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),Ke.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&Ke.error(` error: ${d.provisioningError}`),E_("done")}catch(d){d instanceof V?(Ke.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&Ke.message(JSON.stringify(d.payload,null,2))):Ke.error(d instanceof Error?d.message:String(d)),process.exit(1)}}Qn();Ve();Le();me();xt();pi();import{existsSync as T_,rmSync as I_}from"node:fs";import{confirm as C_,intro as P_,isCancel as A_,log as Sr,outro as __,spinner as j_}from"@clack/prompts";function Dt(t){Sr.error(t),process.exit(1)}var pv=t=>t.trim().replace(/\/+$/,"");async function fv(t){P_("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??je()?.spec.projectId??void 0;e||Dt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=St(e);r||Dt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=pv(r.hubUrl),o=r.projectId,i=pv(t.hub);i.startsWith("http")||Dt("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&Dt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let w=j_();w.start(`reading project ${o} from ${n}\u2026`);try{l=await se(n,r.cliToken,o),w.stop(`read project ${o} (${l.name})`)}catch(v){throw w.stop("could not read the source project",1),v instanceof V&&Dt(`source HUB ${n} \u2192 ${v.status} ${v.message}. The source HUB must be reachable with a valid token to move a project.`),v}}l.contextRepo||Dt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=X(o),p=(t.account??r.accountEmail??await oo()).trim().toLowerCase();if(Sr.message(`move project '${o}'
1079
1073
  from : ${n} (profile ${e})
1080
1074
  to : ${i} (profile ${s}, project ${a}, account ${p})
1081
1075
  \u2022 the source registration on the old HUB is left intact (non-destructive)
1082
1076
  \u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
1083
- `+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let w=await E_({message:"Continue?",initialValue:!0});(T_(w)||!w)&&Dt("aborted")}!c&&a===o&&xr.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:f}=await oo(i,p),m={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:f,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};xr.step(`registering project on ${i}\u2026`);let g;try{g=await pr(i,d,m)}catch(w){if(w instanceof V&&w.status===409){xr.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{g=await se(i,d,a)}catch(v){throw v instanceof V&&Dt(`target HUB \u2192 ${v.status} ${v.message}`),v}}else if(w instanceof V&&w.status===403)Dt(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(w instanceof V)Dt(`target HUB \u2192 ${w.status} ${w.message}`);else throw w}xr.success(`project ${g.projectId} ready on ${i} (${g.provisioningStatus})`),qt({hubUrl:i,cliToken:d,projectId:a,accountEmail:f},s);let b={...u??{},hubUrl:i,cliToken:d,projectId:a};if(delete b.sandboxPins,ce(b),xr.success(`profile '${s}' \u2192 ${_t(a)}`),c){let w=Tt(s);x_(w)&&(S_(w),xr.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}I_(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}M();Ve();import{existsSync as ad,rmSync as P_,statSync as A_}from"node:fs";import{join as gi,relative as __,resolve as j_}from"node:path";import{cancel as N_,intro as pv,isCancel as O_,log as ve,outro as fv,text as Zr}from"@clack/prompts";import{simpleGit as mv}from"simple-git";Ju();Zu();ra();Le();Mn();me();xt();function Qe(t){N_(t),process.exit(1)}function Qr(t){return O_(t)&&Qe("aborted"),typeof t=="string"?t:""}async function dv(t){try{let e=await mv(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function L_(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function M_(t,e){let r=X(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(L_(r,e)){ve.message(`reusing existing ${e} credentials`);return}if(ve.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=Qr(await Zr({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=Qr(await Zr({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=Qr(await Zr({message:`${e} access token (read access to the repo)`,validate:o=>o.trim()?void 0:"required"})).trim();e==="github"?r.github={token:n}:r.gitlab={token:n}}ce(r),ve.success(`saved ${e} credentials`)}async function hv(t){let e=dt(t.profile);pv(`codepipe repo add \u2192 project ${e.projectId}`);let r=je()??void 0,n;try{n=(await se(e.hubUrl,e.cliToken,e.projectId)).repos}catch(k){Qe(`could not read project from HUB: ${k instanceof Error?k.message:String(k)}`)}let o=t.target?.trim();if(!o){let k=await dv(process.cwd());k?(o=process.cwd(),ve.message(`using the current directory (${k})`)):o=Qr(await Zr({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:C=>C.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(ad(o)&&A_(o).isDirectory()){i=j_(o);let k=await dv(i);k||Qe(`${i} is not a git repository (no origin remote)`);let C=Ze(k);C||Qe(`origin ${k} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=C,s=k,ve.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let k=Ze(o);k||Qe(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=k,s=o,ve.message(`${a}: ${c}/${l}`)}let u=Qr(await Zr({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:k=>k.trim()?void 0:"required"})).trim();n.some(k=>k.name===u)&&Qe(`a repo named "${u}" is already registered`);let p;i&&(p=await ui(i,s));let d=p?So(p).branches.integration:"",f=Qr(await Zr({message:"default branch (optional)",placeholder:d||"main",...d?{initialValue:d}:{}})).trim(),m=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let k=__(r.root,i);m=k===""?".":k}let g=Qr(await Zr({message:"mount_as (directory relative to the workspace root)",placeholder:m,initialValue:m})).trim()||m;n.some(k=>(k.mountAs??k.name)===g)&&Qe(`mount_as "${g}" is already used by another repo`),await M_(e,a);let b={name:u,host:a,owner:c,repoName:l,mountAs:g,...f?{defaultBranch:f}:{}};if(!i){let k=r?gi(r.root,g):Oe(e.projectId,u);if(ad(gi(k,".git")))ve.message(`already cloned at ${k}`);else{ve.info(`cloning ${s} \u2192 ${k} \u2026`);try{await mv().clone(s,k),ve.success(`cloned into ${k}`)}catch(C){Qe(`clone failed: ${C instanceof Error?C.message.trim():String(C)}
1084
- check that your ${a} credentials grant read access to ${c}/${l}`)}}}let w;try{w=await Lg(e.hubUrl,e.cliToken,e.projectId,b)}catch(k){k instanceof V&&Qe(`HUB \u2192 ${k.status} ${k.message}`),Qe(k instanceof Error?k.message:String(k))}let{updated:v,errors:y}=Mo(e.projectId,w.repos,r?.contextDir);for(let k of v)ve.message(`updated ${k}`);for(let k of y)ve.warn(`could not update ${k.path}: ${k.error}`);if(r?.contextDir){if(!p)try{let k=i??gi(r.root,g);p=await ui(k,s)}catch(k){ve.warn(`git-flow detection skipped: ${k instanceof Error?k.message:String(k)}`),p={defaultBranch:null,branches:[]}}try{await ia({contextDir:r.contextDir,repoName:u,facts:p,log:k=>ve.message(k)})}catch(k){Qe(`"${u}" was added, but its git-flow choice was NOT saved: ${k instanceof Error?k.message.trim():String(k)}
1085
- re-run the command or set the git-flow manually in project.yaml`)}}ve.success(`added "${u}" \u2014 project now has ${w.repos.length} repo(s)`),fv("done")}async function gv(t){let e=dt(t.profile);pv(`codepipe repo remove \u2192 project ${e.projectId}`);let r=je()??void 0,n;try{let c=(await se(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 Mg(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof V&&(a.status===404&&Qe(`no repo named "${t.name}" in this project`),Qe(`HUB \u2192 ${a.status} ${a.message}`)),Qe(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=Mo(e.projectId,o.repos,r?.contextDir);for(let a of i)ve.message(`updated ${a}`);for(let a of s)ve.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")ve.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?gi(r.root,n):Oe(e.projectId,t.name);if(ad(gi(a,".git")))try{P_(a,{recursive:!0,force:!0}),ve.message(`deleted local clone ${a}`)}catch(c){ve.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else ve.message(`no local clone found to purge (${a})`)}ve.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),fv("done")}async function yv(t){let e=dt(t.profile),r;try{r=(await se(e.hubUrl,e.cliToken,e.projectId)).repos}catch(n){console.error(`could not read project from HUB: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(r.length===0){console.log(`project ${e.projectId} has no repos yet \u2014 add one with \`codepipe repo add\``);return}console.log(`project ${e.projectId} \u2014 ${r.length} repo(s):`);for(let n of r){let o=n.mountAs??n.name,i=n.defaultBranch?` @${n.defaultBranch}`:"";console.log(` ${n.name} ${n.host}:${n.owner}/${n.repoName}${i} \u2192 ${o}`)}}oa();Ve();zi();Le();import{existsSync as D_}from"node:fs";import{join as U_}from"node:path";import{simpleGit as B_}from"simple-git";xt();var F_=60;async function wv(t){let{cfg:e}=xn(t.profile),r=vn(e.projectId);if(!r)throw new Error(`no workspace for ${e.projectId} here \u2014 run this from the project folder (the one with .codepipe/)`);let n=new Set,o={info:a=>console.log(a),warn:a=>console.warn(a)},i=async()=>{let a=await Ts(e.hubUrl,e.cliToken,e.projectId);if(a.length===0){console.log("[pull] nothing ready yet");return}for(let c of a)await Kl(r.root,r.spec.repos,c,n,o);if(await G_(r.contextDir),r.contextDir)try{_n(r.contextDir,r.root,{info:c=>console.log(`[pull] ${c}`),warn:c=>console.warn(`[pull] ${c}`)})}catch(c){console.warn(`[pull] skills materialize failed \u2014 ${c instanceof Error?c.message:String(c)}`)}};if(!t.watch){await i();return}try{await i()}catch(a){console.warn(`[pull] ${a instanceof Error?a.message:String(a)}`)}let s=Math.max(10,t.intervalSec??F_)*1e3;for(console.log(`[pull] watching \u2014 every ${Math.round(s/1e3)}s, Ctrl+C to stop`);;){await new Promise(a=>setTimeout(a,s));try{await i()}catch(a){console.warn(`[pull] ${a instanceof Error?a.message:String(a)}`)}}}async function G_(t){if(!(!t||!D_(U_(t,".git"))))try{await B_(t).pull(["--ff-only"])}catch(e){console.warn(`[pull] context repo not updated \u2014 ${e instanceof Error?e.message.split(`
1086
- `)[0]:String(e)}`)}}ua();import{existsSync as xv,mkdirSync as K_,readFileSync as H_,writeFileSync as W_}from"node:fs";import{homedir as q_}from"node:os";import{dirname as Y_,join as Sv}from"node:path";import*as ao from"node:readline";Le();Qi();me();xt();oa();ua();var ma=Sv(q_(),".codepipe","history"),bv=["/help","/status","/tasks","/task","/sync","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Ev=500,kv=40;async function Rv(t={}){let e=je();e||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let r=X(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)),Co(r),console.log(`connected to ${r.hubUrl} as project ${e.spec.projectId}`),console.log("the CLI daemon and an embedded agent worker run in this session; /logs and /monitor show their output."),console.log("type /help to list commands. Ctrl+D or /quit to exit."),console.log("");let n=ao.createInterface({input:process.stdin,output:process.stdout,completer:V_,history:lj(),removeHistoryDuplicates:!0}),o={ws:e,secrets:r,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};Gm(i=>Sr(o,i)),o.daemon=Ds({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:i=>Sr(o,i),warn:i=>Sr(o,i)},onEvent:i=>ij(o,i),workspace:{root:e.root,contextDir:e.contextDir,repos:e.spec.repos}});try{let i={hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId};await aa(i,t.profile,{profile:t.profile});let s=process.argv[1];if(!s)throw new Error("cannot resolve the codepipe entry script for the worker process");let a=ca({entry:s,profile:t.profile,onLine:c=>Sr(o,`[worker] ${c}`)});a.on("exit",(c,l)=>{o.workerExited=!0,!ud&&so(o,`[worker] exited (code ${c??(l?1:0)}) \u2014 agent jobs will NOT run; /quit and restart codepipe to bring it back`)}),o.workerChild=a,console.log("embedded agent worker started \u2014 agent jobs run on this machine.")}catch(i){console.warn(`[worker] could not start the embedded worker (${i instanceof Error?i.message:String(i)}). REPL commands still work; run \`codepipe up --reregister\` if the registration was removed.`)}ld(o),n.prompt(),n.on("line",async i=>{let s=i.trim();if(s.length>0)try{if(await z_(o,s)){$v(o);return}}catch(a){console.error(a instanceof Error?a.message:String(a))}o.unread=0,ld(o),n.prompt()}),n.on("close",()=>{$v(o)})}function V_(t){let e=bv.filter(r=>r.startsWith(t));return[e.length?e:bv,t]}async function z_(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return X_(),!1;case"/status":return await J_(t),!1;case"/tasks":return await Z_(t,n),!1;case"/task":return await Q_(t,n),!1;case"/sync":return await ej(t),!1;case"/logs":return sj(t,n),!1;case"/monitor":return aj(t),!1;case"/approve":return await vv(t,n,"approve"),!1;case"/merge":return await vv(t,n,"merge"),!1;case"/login":return tj(t,n),!1;case"/secret":return rj(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function X_(){console.log(["/help show this list","/status connection, project, embedded worker, siblings","/tasks [--phase P] list tasks (optionally filtered by phase)","/task <key> task detail (phase + artifacts)","/sync clone/fetch project repos per project.yaml","/logs [n|follow|clear] tail last n daemon/worker logs / toggle live / clear buffer","/monitor toggle live daemon/worker log streaming (alias /logs follow)","/approve <key> merge the task's PR(s) (TRACKING, PR mode)","/merge <key> direct-merge the branch to main (TRACKING, no-PR mode)","/login <token> set the Claude OAuth token (not stored in history)","/secret set <k> <v> set a secret (not stored in history)","/secret list list secret keys (no values)","/secret unset <k> remove a secret","/quit stop the daemon and the worker, exit"].join(`
1087
- `))}async function J_(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=xv(Sv(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function Z_(t,e){let r=cj(e,"--phase");try{let n=await jg(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId),o=r?n.filter(i=>i.phase.toLowerCase()===r.toLowerCase()):n;if(o.length===0){console.log(" (no tasks)");return}for(let i of o)console.log(` ${i.key.padEnd(10)} ${i.phase.padEnd(16)} ${i.title}`)}catch(n){dd(n)}}async function Q_(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await Ng(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){dd(n)}}async function ej(t){let e=await li(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 vv(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await Og(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){dd(o)}}function tj(t,e){let r=e.join(" ").trim();if(!r){console.log("usage: /login <claude-oauth-token>"),console.log(" get one with `claude setup-token`, then paste it here."),console.log(" (this line is scrubbed from history; takes effect on next SANDBOX reconnect)");return}t.secrets.claude={oauthToken:r},ce(t.secrets),console.log(" Claude OAuth token saved. It will be sealed into job bundles for SANDBOXes."),console.log(" Re-seal happens when a SANDBOX (re)connects; restart it if you need it now.")}function rj(t,e){let[r,n,...o]=e;if(r==="list"){let i=[];t.secrets.github&&i.push("github.token"),t.secrets.bitbucket&&i.push("bitbucket.email","bitbucket.apiToken"),t.secrets.youtrack&&i.push("youtrack.url","youtrack.token"),console.log(i.length?` ${i.join(`
1088
- `)}`:" (none)");return}if(r==="set"){let i=o.join(" ");if(!n||!i){console.log("usage: /secret set <key> <value> (keys: GH_TOKEN, YOUTRACK_URL, YOUTRACK_TOKEN, BITBUCKET_EMAIL, BITBUCKET_API_TOKEN)");return}nj(t.secrets,n,i),ce(t.secrets),Co(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}oj(t.secrets,n),ce(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function nj(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 oj(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 ij(t,e){switch(e.kind){case"connected":t.connection="connecting",Sr(t,"[hub] connected");break;case"registered":t.connection="registered",Sr(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",so(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",Sr(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",so(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":so(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?Sr(t,`[hub] action ${e.actionType} done`):so(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function Sr(t,e){t.logBuffer.push(e),t.logBuffer.length>Ev&&t.logBuffer.shift(),t.follow&&so(t,e)}function sj(t,e){let r=e[0];if(r==="follow"||r==="on"){cd(t,!0);return}if(r==="off"){cd(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(Ev,Number(r)||kv)):kv,o=t.logBuffer.slice(-n);if(o.length===0){console.log(" (no daemon logs buffered yet)");return}for(let i of o)console.log(` ${i}`);console.log(` \u2014 ${o.length} line(s); /monitor for live stream`)}function aj(t){cd(t,!t.follow)}function cd(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function so(t,e){ao.cursorTo(process.stdout,0),ao.clearLine(process.stdout,0),process.stdout.write(e+`
1089
- `),t.unread+=1,ld(t),t.rl.prompt(!0)}function ld(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var ud=!1;function $v(t){if(ud)return;ud=!0,uj(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
1077
+ `+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let w=await C_({message:"Continue?",initialValue:!0});(A_(w)||!w)&&Dt("aborted")}!c&&a===o&&Sr.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:f}=await io(i,p),m={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:f,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};Sr.step(`registering project on ${i}\u2026`);let g;try{g=await fr(i,d,m)}catch(w){if(w instanceof V&&w.status===409){Sr.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{g=await se(i,d,a)}catch(v){throw v instanceof V&&Dt(`target HUB \u2192 ${v.status} ${v.message}`),v}}else if(w instanceof V&&w.status===403)Dt(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(w instanceof V)Dt(`target HUB \u2192 ${w.status} ${w.message}`);else throw w}Sr.success(`project ${g.projectId} ready on ${i} (${g.provisioningStatus})`),Yt({hubUrl:i,cliToken:d,projectId:a,accountEmail:f},s);let b={...u??{},hubUrl:i,cliToken:d,projectId:a};if(delete b.sandboxPins,ce(b),Sr.success(`profile '${s}' \u2192 ${_t(a)}`),c){let w=Tt(s);T_(w)&&(I_(w),Sr.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}__(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}M();Ve();import{existsSync as ad,rmSync as N_,statSync as O_}from"node:fs";import{join as yi,relative as L_,resolve as M_}from"node:path";import{cancel as D_,intro as hv,isCancel as U_,log as ve,outro as gv,text as Qr}from"@clack/prompts";import{simpleGit as yv}from"simple-git";Ju();Zu();ra();Le();Dn();me();xt();function Qe(t){D_(t),process.exit(1)}function en(t){return U_(t)&&Qe("aborted"),typeof t=="string"?t:""}async function mv(t){try{let e=await yv(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function B_(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function F_(t,e){let r=X(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(B_(r,e)){ve.message(`reusing existing ${e} credentials`);return}if(ve.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=en(await Qr({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=en(await Qr({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=en(await Qr({message:`${e} access token (read access to the repo)`,validate:o=>o.trim()?void 0:"required"})).trim();e==="github"?r.github={token:n}:r.gitlab={token:n}}ce(r),ve.success(`saved ${e} credentials`)}async function wv(t){let e=dt(t.profile);hv(`codepipe repo add \u2192 project ${e.projectId}`);let r=je()??void 0,n;try{n=(await se(e.hubUrl,e.cliToken,e.projectId)).repos}catch(k){Qe(`could not read project from HUB: ${k instanceof Error?k.message:String(k)}`)}let o=t.target?.trim();if(!o){let k=await mv(process.cwd());k?(o=process.cwd(),ve.message(`using the current directory (${k})`)):o=en(await Qr({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:C=>C.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(ad(o)&&O_(o).isDirectory()){i=M_(o);let k=await mv(i);k||Qe(`${i} is not a git repository (no origin remote)`);let C=Ze(k);C||Qe(`origin ${k} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=C,s=k,ve.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let k=Ze(o);k||Qe(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=k,s=o,ve.message(`${a}: ${c}/${l}`)}let u=en(await Qr({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:k=>k.trim()?void 0:"required"})).trim();n.some(k=>k.name===u)&&Qe(`a repo named "${u}" is already registered`);let p;i&&(p=await di(i,s));let d=p?Eo(p).branches.integration:"",f=en(await Qr({message:"default branch (optional)",placeholder:d||"main",...d?{initialValue:d}:{}})).trim(),m=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let k=L_(r.root,i);m=k===""?".":k}let g=en(await Qr({message:"mount_as (directory relative to the workspace root)",placeholder:m,initialValue:m})).trim()||m;n.some(k=>(k.mountAs??k.name)===g)&&Qe(`mount_as "${g}" is already used by another repo`),await F_(e,a);let b={name:u,host:a,owner:c,repoName:l,mountAs:g,...f?{defaultBranch:f}:{}};if(!i){let k=r?yi(r.root,g):Oe(e.projectId,u);if(ad(yi(k,".git")))ve.message(`already cloned at ${k}`);else{ve.info(`cloning ${s} \u2192 ${k} \u2026`);try{await yv().clone(s,k),ve.success(`cloned into ${k}`)}catch(C){Qe(`clone failed: ${C instanceof Error?C.message.trim():String(C)}
1078
+ check that your ${a} credentials grant read access to ${c}/${l}`)}}}let w;try{w=await Ug(e.hubUrl,e.cliToken,e.projectId,b)}catch(k){k instanceof V&&Qe(`HUB \u2192 ${k.status} ${k.message}`),Qe(k instanceof Error?k.message:String(k))}let{updated:v,errors:y}=Do(e.projectId,w.repos,r?.contextDir);for(let k of v)ve.message(`updated ${k}`);for(let k of y)ve.warn(`could not update ${k.path}: ${k.error}`);if(r?.contextDir){if(!p)try{let k=i??yi(r.root,g);p=await di(k,s)}catch(k){ve.warn(`git-flow detection skipped: ${k instanceof Error?k.message:String(k)}`),p={defaultBranch:null,branches:[]}}try{await ia({contextDir:r.contextDir,repoName:u,facts:p,log:k=>ve.message(k)})}catch(k){Qe(`"${u}" was added, but its git-flow choice was NOT saved: ${k instanceof Error?k.message.trim():String(k)}
1079
+ re-run the command or set the git-flow manually in project.yaml`)}}ve.success(`added "${u}" \u2014 project now has ${w.repos.length} repo(s)`),gv("done")}async function bv(t){let e=dt(t.profile);hv(`codepipe repo remove \u2192 project ${e.projectId}`);let r=je()??void 0,n;try{let c=(await se(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 Bg(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof V&&(a.status===404&&Qe(`no repo named "${t.name}" in this project`),Qe(`HUB \u2192 ${a.status} ${a.message}`)),Qe(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=Do(e.projectId,o.repos,r?.contextDir);for(let a of i)ve.message(`updated ${a}`);for(let a of s)ve.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")ve.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?yi(r.root,n):Oe(e.projectId,t.name);if(ad(yi(a,".git")))try{N_(a,{recursive:!0,force:!0}),ve.message(`deleted local clone ${a}`)}catch(c){ve.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else ve.message(`no local clone found to purge (${a})`)}ve.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),gv("done")}async function kv(t){let e=dt(t.profile),r;try{r=(await se(e.hubUrl,e.cliToken,e.projectId)).repos}catch(n){console.error(`could not read project from HUB: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(r.length===0){console.log(`project ${e.projectId} has no repos yet \u2014 add one with \`codepipe repo add\``);return}console.log(`project ${e.projectId} \u2014 ${r.length} repo(s):`);for(let n of r){let o=n.mountAs??n.name,i=n.defaultBranch?` @${n.defaultBranch}`:"";console.log(` ${n.name} ${n.host}:${n.owner}/${n.repoName}${i} \u2192 ${o}`)}}oa();Ve();zi();Le();import{existsSync as G_}from"node:fs";import{join as K_}from"node:path";import{simpleGit as H_}from"simple-git";xt();var W_=60;async function vv(t){let{cfg:e}=Sn(t.profile),r=$n(e.projectId);if(!r)throw new Error(`no workspace for ${e.projectId} here \u2014 run this from the project folder (the one with .codepipe/)`);let n=new Set,o={info:a=>console.log(a),warn:a=>console.warn(a)},i=async()=>{let a=await Ts(e.hubUrl,e.cliToken,e.projectId);if(a.length===0){console.log("[pull] nothing ready yet");return}for(let c of a)await Kl(r.root,r.spec.repos,c,n,o);if(await q_(r.contextDir),r.contextDir)try{jn(r.contextDir,r.root,{info:c=>console.log(`[pull] ${c}`),warn:c=>console.warn(`[pull] ${c}`)})}catch(c){console.warn(`[pull] skills materialize failed \u2014 ${c instanceof Error?c.message:String(c)}`)}};if(!t.watch){await i();return}try{await i()}catch(a){console.warn(`[pull] ${a instanceof Error?a.message:String(a)}`)}let s=Math.max(10,t.intervalSec??W_)*1e3;for(console.log(`[pull] watching \u2014 every ${Math.round(s/1e3)}s, Ctrl+C to stop`);;){await new Promise(a=>setTimeout(a,s));try{await i()}catch(a){console.warn(`[pull] ${a instanceof Error?a.message:String(a)}`)}}}async function q_(t){if(!(!t||!G_(K_(t,".git"))))try{await H_(t).pull(["--ff-only"])}catch(e){console.warn(`[pull] context repo not updated \u2014 ${e instanceof Error?e.message.split(`
1080
+ `)[0]:String(e)}`)}}ua();import{existsSync as Rv,mkdirSync as Y_,readFileSync as V_,writeFileSync as z_}from"node:fs";import{homedir as X_}from"node:os";import{dirname as J_,join as Tv}from"node:path";import*as co from"node:readline";Le();Qi();me();xt();oa();ua();var ma=Tv(X_(),".codepipe","history"),$v=["/help","/status","/tasks","/task","/sync","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Iv=500,xv=40;async function Cv(t={}){let e=je();e||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let r=X(e.spec.projectId);r||(console.error(`no secrets for project ${e.spec.projectId} at ~/.codepipe/secrets/${e.spec.projectId}.json. run \`codepipe init\` or \`codepipe clone\` to set them up.`),process.exit(1)),Po(r),console.log(`connected to ${r.hubUrl} as project ${e.spec.projectId}`),console.log("the CLI daemon and an embedded agent worker run in this session; /logs and /monitor show their output."),console.log("type /help to list commands. Ctrl+D or /quit to exit."),console.log("");let n=co.createInterface({input:process.stdin,output:process.stdout,completer:Z_,history:fj(),removeHistoryDuplicates:!0}),o={ws:e,secrets:r,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};Wm(i=>Er(o,i)),o.daemon=Ds({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:i=>Er(o,i),warn:i=>Er(o,i)},onEvent:i=>lj(o,i),workspace:{root:e.root,contextDir:e.contextDir,repos:e.spec.repos}});try{let i={hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId};await aa(i,t.profile,{profile:t.profile});let s=process.argv[1];if(!s)throw new Error("cannot resolve the codepipe entry script for the worker process");let a=ca({entry:s,profile:t.profile,onLine:c=>Er(o,`[worker] ${c}`)});a.on("exit",(c,l)=>{o.workerExited=!0,!ud&&ao(o,`[worker] exited (code ${c??(l?1:0)}) \u2014 agent jobs will NOT run; /quit and restart codepipe to bring it back`)}),o.workerChild=a,console.log("embedded agent worker started \u2014 agent jobs run on this machine.")}catch(i){console.warn(`[worker] could not start the embedded worker (${i instanceof Error?i.message:String(i)}). REPL commands still work; run \`codepipe up --reregister\` if the registration was removed.`)}ld(o),n.prompt(),n.on("line",async i=>{let s=i.trim();if(s.length>0)try{if(await Q_(o,s)){Ev(o);return}}catch(a){console.error(a instanceof Error?a.message:String(a))}o.unread=0,ld(o),n.prompt()}),n.on("close",()=>{Ev(o)})}function Z_(t){let e=$v.filter(r=>r.startsWith(t));return[e.length?e:$v,t]}async function Q_(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return ej(),!1;case"/status":return await tj(t),!1;case"/tasks":return await rj(t,n),!1;case"/task":return await nj(t,n),!1;case"/sync":return await oj(t),!1;case"/logs":return uj(t,n),!1;case"/monitor":return dj(t),!1;case"/approve":return await Sv(t,n,"approve"),!1;case"/merge":return await Sv(t,n,"merge"),!1;case"/login":return ij(t,n),!1;case"/secret":return sj(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function ej(){console.log(["/help show this list","/status connection, project, embedded worker, siblings","/tasks [--phase P] list tasks (optionally filtered by phase)","/task <key> task detail (phase + artifacts)","/sync clone/fetch project repos per project.yaml","/logs [n|follow|clear] tail last n daemon/worker logs / toggle live / clear buffer","/monitor toggle live daemon/worker log streaming (alias /logs follow)","/approve <key> merge the task's PR(s) (TRACKING, PR mode)","/merge <key> direct-merge the branch to main (TRACKING, no-PR mode)","/login <token> set the Claude OAuth token (not stored in history)","/secret set <k> <v> set a secret (not stored in history)","/secret list list secret keys (no values)","/secret unset <k> remove a secret","/quit stop the daemon and the worker, exit"].join(`
1081
+ `))}async function tj(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=Rv(Tv(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function rj(t,e){let r=pj(e,"--phase");try{let n=await Lg(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId),o=r?n.filter(i=>i.phase.toLowerCase()===r.toLowerCase()):n;if(o.length===0){console.log(" (no tasks)");return}for(let i of o)console.log(` ${i.key.padEnd(10)} ${i.phase.padEnd(16)} ${i.title}`)}catch(n){dd(n)}}async function nj(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await Mg(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){dd(n)}}async function oj(t){let e=await ui(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 Sv(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await Dg(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){dd(o)}}function ij(t,e){let r=e.join(" ").trim();if(!r){console.log("usage: /login <claude-oauth-token>"),console.log(" get one with `claude setup-token`, then paste it here."),console.log(" (this line is scrubbed from history; takes effect on next SANDBOX reconnect)");return}t.secrets.claude={oauthToken:r},ce(t.secrets),console.log(" Claude OAuth token saved. It will be sealed into job bundles for SANDBOXes."),console.log(" Re-seal happens when a SANDBOX (re)connects; restart it if you need it now.")}function sj(t,e){let[r,n,...o]=e;if(r==="list"){let i=[];t.secrets.github&&i.push("github.token"),t.secrets.bitbucket&&i.push("bitbucket.email","bitbucket.apiToken"),t.secrets.youtrack&&i.push("youtrack.url","youtrack.token"),console.log(i.length?` ${i.join(`
1082
+ `)}`:" (none)");return}if(r==="set"){let i=o.join(" ");if(!n||!i){console.log("usage: /secret set <key> <value> (keys: GH_TOKEN, YOUTRACK_URL, YOUTRACK_TOKEN, BITBUCKET_EMAIL, BITBUCKET_API_TOKEN)");return}aj(t.secrets,n,i),ce(t.secrets),Po(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}cj(t.secrets,n),ce(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function aj(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 cj(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 lj(t,e){switch(e.kind){case"connected":t.connection="connecting",Er(t,"[hub] connected");break;case"registered":t.connection="registered",Er(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",ao(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",Er(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",ao(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":ao(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?Er(t,`[hub] action ${e.actionType} done`):ao(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function Er(t,e){t.logBuffer.push(e),t.logBuffer.length>Iv&&t.logBuffer.shift(),t.follow&&ao(t,e)}function uj(t,e){let r=e[0];if(r==="follow"||r==="on"){cd(t,!0);return}if(r==="off"){cd(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(Iv,Number(r)||xv)):xv,o=t.logBuffer.slice(-n);if(o.length===0){console.log(" (no daemon logs buffered yet)");return}for(let i of o)console.log(` ${i}`);console.log(` \u2014 ${o.length} line(s); /monitor for live stream`)}function dj(t){cd(t,!t.follow)}function cd(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function ao(t,e){co.cursorTo(process.stdout,0),co.clearLine(process.stdout,0),process.stdout.write(e+`
1083
+ `),t.unread+=1,ld(t),t.rl.prompt(!0)}function ld(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var ud=!1;function Ev(t){if(ud)return;ud=!0,mj(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
1090
1084
  bye.`),setTimeout(()=>process.exit(0),150);return}console.log(`
1091
- 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 cj(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function dd(t){t instanceof V?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function lj(){if(!xv(ma))return[];try{return H_(ma,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function uj(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{K_(Y_(ma),{recursive:!0}),W_(ma,r.slice().reverse().join(`
1085
+ 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 pj(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function dd(t){t instanceof V?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function fj(){if(!Rv(ma))return[];try{return V_(ma,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function mj(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{Y_(J_(ma),{recursive:!0}),z_(ma,r.slice().reverse().join(`
1092
1086
  `)+`
1093
- `)}catch{}}Zn();M();Ye();Zn();Ve();Le();di();import{hostname as dj}from"node:os";import{cancel as pj,confirm as Tv,intro as fj,isCancel as Pv,log as co,multiselect as mj,outro as Iv,password as hj,select as pd,text as fd}from"@clack/prompts";function yi(t){pj(t),process.exit(1)}function lo(t){return Pv(t)&&yi("aborted"),t}function ha(t){return Pv(t)&&yi("aborted"),typeof t=="string"?t:""}function ga(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Cv(t,e){try{let{secret:r}=await Rs(t,e);return r}catch(r){throw r instanceof V&&r.status===404&&yi("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 gj(t,e){if(lo(await pd({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 Ul(t,e);if(o.length>0)return lo(await mj({message:"pick the projects (space to toggle, enter to confirm)",options:o.map(i=>({value:i.id,label:`${i.id} \u2014 ${i.name}`})),required:!0}));co.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){co.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return ha(await fd({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 md(t){fj("codepipe worker \u2014 set up this machine as a runner");let e=Ge(t.profile);e&&(co.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),lo(await Tv({message:"re-register this worker?",initialValue:!1}))||yi("keeping the existing registration"));let r=St(t.profile)??St(),n=ha(await fd({message:"HUB URL",placeholder:bt,initialValue:ee("HUB_URL")??r?.hubUrl??bt,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=lo(await pd({message:"how to authorize the registration?",options:[...o?[{value:"local",label:"this machine's CLI account (recommended \u2014 no token hand-off)"}]:[],{value:"login",label:"log in by email (magic-link, like codepipe init)"},{value:"paste",label:"paste a registration token from the dashboard"}],initialValue:o?"local":"login"})),s,a=null;if(i==="local")a=r.cliToken,s=await Cv(n,a),co.success("account-issued registration token minted");else if(i==="login"){let d=await no();a=(await oo(n,d)).cliToken,s=await Cv(n,a),co.success("account-issued registration token minted")}else s=ha(await hj({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||yi("a registration token is required");let c=await gj(n,a),l=ha(await fd({message:"worker name",initialValue:dj(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=lo(await pd({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 Wr({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),co.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!lo(await Tv({message:"start the claim-loop now?",initialValue:!0}))){Iv("registered. start later with `codepipe worker`.");return}Iv("starting the claim-loop\u2026"),await si(t.profile?{profile:t.profile}:{})}function wj(){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 ee("PROFILE")}var $e=wj();Qp($e);var He=new yj;He.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(et).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{ga()?await Rv({profile:$e}):await la({profile:$e})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});He.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 Qk({configPath:t.config,skipVerify:t.skipVerify===!0}):await Fk({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});He.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 ff({...t,profile:$e})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});He.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 Gk({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});He.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await Ay({profile:$e})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});He.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 gk({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});He.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 ov({profile:$e,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});He.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Bb({profile:$e})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});He.command("pull").description("Fetch finished task branches into your local clones (no checkout switch)").option("--profile <name>","Config profile").option("--watch","Keep pulling instead of exiting after one pass").option("--interval <sec>","Watch interval in seconds (default 60, minimum 10)",t=>parseInt(t,10)).action(async t=>{if(t.interval!==void 0&&!Number.isFinite(t.interval))throw new Error("--interval expects a number of seconds");await wv({profile:t.profile,...t.watch?{watch:!0}:{},...Number.isFinite(t.interval)?{intervalSec:t.interval}:{}})});He.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 la({profile:$e,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Av=He.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Av.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??ee("HUB_URL")??St($e)?.hubUrl??bt,r=t.token??ee("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&ga()){await md({profile:$e});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let n=ee("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??ee("WORKER_NAME"),i=t.llm??ee("WORKER_LLM");await Wr({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...$e?{profile:$e}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Av.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!Ge($e)&&ga()){await md({profile:$e});return}await si($e?{profile:$e}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var _v=He.command("project").description("Manage CodePipe projects");_v.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await cv({profile:$e})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});_v.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 uv({...t,cliProfile:$e})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var hd=He.command("repo").description("Manage the project's git repositories");hd.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 hv({profile:$e,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});hd.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 gv({profile:$e,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});hd.command("list").description("List the project's repos").action(async()=>{try{await yv({profile:$e})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var jv=He.command("model").description("Project map (model/ in the Context Repo)");jv.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)}});jv.command("bootstrap").description("Build the map and mine task events from the whole git history (cold start)").option("--repo <name>","Bootstrap only this repo (logical name)").action(async t=>{try{await Vl({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});He.parseAsync();
1087
+ `)}catch{}}Qn();M();Ye();Qn();Ve();Le();pi();import{hostname as hj}from"node:os";import{cancel as gj,confirm as Pv,intro as yj,isCancel as jv,log as lo,multiselect as wj,outro as Av,password as bj,select as pd,text as fd}from"@clack/prompts";function wi(t){gj(t),process.exit(1)}function uo(t){return jv(t)&&wi("aborted"),t}function ha(t){return jv(t)&&wi("aborted"),typeof t=="string"?t:""}function ga(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function _v(t,e){try{let{secret:r}=await Rs(t,e);return r}catch(r){throw r instanceof V&&r.status===404&&wi("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 kj(t,e){if(uo(await pd({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 Ul(t,e);if(o.length>0)return uo(await wj({message:"pick the projects (space to toggle, enter to confirm)",options:o.map(i=>({value:i.id,label:`${i.id} \u2014 ${i.name}`})),required:!0}));lo.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){lo.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return ha(await fd({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 md(t){yj("codepipe worker \u2014 set up this machine as a runner");let e=Ge(t.profile);e&&(lo.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),uo(await Pv({message:"re-register this worker?",initialValue:!1}))||wi("keeping the existing registration"));let r=St(t.profile)??St(),n=ha(await fd({message:"HUB URL",placeholder:bt,initialValue:ee("HUB_URL")??r?.hubUrl??bt,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=uo(await pd({message:"how to authorize the registration?",options:[...o?[{value:"local",label:"this machine's CLI account (recommended \u2014 no token hand-off)"}]:[],{value:"login",label:"log in by email (magic-link, like codepipe init)"},{value:"paste",label:"paste a registration token from the dashboard"}],initialValue:o?"local":"login"})),s,a=null;if(i==="local")a=r.cliToken,s=await _v(n,a),lo.success("account-issued registration token minted");else if(i==="login"){let d=await oo();a=(await io(n,d)).cliToken,s=await _v(n,a),lo.success("account-issued registration token minted")}else s=ha(await bj({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||wi("a registration token is required");let c=await kj(n,a),l=ha(await fd({message:"worker name",initialValue:hj(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=uo(await pd({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 qr({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),lo.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!uo(await Pv({message:"start the claim-loop now?",initialValue:!0}))){Av("registered. start later with `codepipe worker`.");return}Av("starting the claim-loop\u2026"),await ai(t.profile?{profile:t.profile}:{})}function $j(){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 ee("PROFILE")}var $e=$j();rf($e);var He=new vj;He.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(et).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{ga()?await Cv({profile:$e}):await la({profile:$e})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});He.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 rv({configPath:t.config,skipVerify:t.skipVerify===!0}):await Hk({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});He.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 gf({...t,profile:$e})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});He.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 Wk({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});He.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await Ny({profile:$e})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});He.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 bk({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});He.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 av({profile:$e,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});He.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Kb({profile:$e})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});He.command("pull").description("Fetch finished task branches into your local clones (no checkout switch)").option("--profile <name>","Config profile").option("--watch","Keep pulling instead of exiting after one pass").option("--interval <sec>","Watch interval in seconds (default 60, minimum 10)",t=>parseInt(t,10)).action(async t=>{if(t.interval!==void 0&&!Number.isFinite(t.interval))throw new Error("--interval expects a number of seconds");await vv({profile:t.profile,...t.watch?{watch:!0}:{},...Number.isFinite(t.interval)?{intervalSec:t.interval}:{}})});He.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 la({profile:$e,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Nv=He.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Nv.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??ee("HUB_URL")??St($e)?.hubUrl??bt,r=t.token??ee("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&ga()){await md({profile:$e});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let n=ee("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??ee("WORKER_NAME"),i=t.llm??ee("WORKER_LLM");await qr({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...$e?{profile:$e}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Nv.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!Ge($e)&&ga()){await md({profile:$e});return}await ai($e?{profile:$e}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Ov=He.command("project").description("Manage CodePipe projects");Ov.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await dv({profile:$e})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ov.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 fv({...t,cliProfile:$e})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var hd=He.command("repo").description("Manage the project's git repositories");hd.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 wv({profile:$e,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});hd.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 bv({profile:$e,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});hd.command("list").description("List the project's repos").action(async()=>{try{await kv({profile:$e})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Lv=He.command("model").description("Project map (model/ in the Context Repo)");Lv.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)}});Lv.command("bootstrap").description("Build the map and mine task events from the whole git history (cold start)").option("--repo <name>","Bootstrap only this repo (logical name)").action(async t=>{try{await Vl({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});He.parseAsync();