@code-partner/codepipe 0.3.8 → 0.3.9-dev.118.gfadc68f

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 +178 -130
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,35 +1,54 @@
1
1
  #!/usr/bin/env node
2
- var he="0.3.8",je="https://hub.codepipe.dev";var Ee=4,Qu=4;function Hr(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Qu&&t<=Ee}var Pe=".codepipe-context.yaml",mr=".devpipe-context.yaml",bi=[{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",Pe]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[Pe]},{version:3,summary:"Custom project actions (the RUN tab): actions/ scaffold with the format README",addedPaths:["actions/README.md"]}];function Kr(t=3){return`# CodePipe Context Repo format version.
2
+ var be="0.3.9-dev.118.gfadc68f",Ae="https://hub.dev.codepipe.dev";var _e=4,Up=4;function rn(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Up&&t<=_e}var Ne=".codepipe-context.yaml",wr=".devpipe-context.yaml",Mi=[{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",Ne]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[Ne]},{version:3,summary:"Custom project actions (the RUN tab): actions/ scaffold with the format README",addedPaths:["actions/README.md"]}];function nn(t=3){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 ki(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 $i(t,e=bi){let r=[];for(let n of e)if(!(n.version<=t))for(let o of n.addedPaths)r.includes(o)||r.push(o);return r}function vi(t,e=bi){return e.filter(r=>r.version>t)}var Zu=[{id:"intake",label:"\u041F\u0440\u0438\u0451\u043C\u043A\u0430",phases:["INTAKE"]},{id:"analysis",label:"\u0410\u043D\u0430\u043B\u0438\u0437",phases:["ANALYZING","ESTIMATING"]},{id:"ready",label:"\u0413\u043E\u0442\u043E\u0432\u0430 \u043A \u0440\u0430\u0431\u043E\u0442\u0435",phases:["READY"]},{id:"implementation",label:"\u0420\u0435\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u044F",phases:["IMPLEMENTING","BUILD"]},{id:"delivery",label:"\u0414\u043E\u0441\u0442\u0430\u0432\u043A\u0430",phases:["READY_TO_APPLY","APPLYING"]}],Zy=Zu.flatMap(t=>t.phases);var xi=["estimate","analyze","implement","resolve-conflict","rework","draft","build","index","backfill","analysis","chat"];function gt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Ge="opus",Wr="sonnet",ep="haiku",Zn=[Ge,Wr,ep],Si={analyze:Ge,implement:Ge,"resolve-conflict":Ge,rework:Ge,estimate:Wr,build:Wr,draft:Wr,index:Ge,backfill:Ge,analysis:Ge,chat:Ge};var ye=/^[A-Z][A-Z0-9_]*$/,tp=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),rp=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];function ze(t){return tp.has(t)?!0:rp.some(e=>t.startsWith(e))}var Ii=600,Ri=/^[a-z0-9-]+$/,Ti=32,Ci=64;function qr(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function ht(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function eo(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function ji(t,e){let r=qr(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=ht(r.id,"id")??n;if(!Ri.test(o))throw new Error(`id must match ${Ri} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=ht(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let d=qr(r.env,"env");s={};for(let[u,m]of Object.entries(d)){if(!ye.test(u))throw new Error(`env name "${u}" must match ${ye}`);if(typeof m!="string"&&typeof m!="number"&&typeof m!="boolean")throw new Error(`env.${u} must be a scalar`);s[u]=String(m)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>Ti)throw new Error(`too many params (max ${Ti})`);let d=new Set;a=c.map((u,m)=>np(u,m,d))}let l=r.steps;if(!Array.isArray(l)||l.length===0)throw new Error("steps must be a non-empty list");if(l.length>Ci)throw new Error(`too many steps (max ${Ci})`);let p=l.map((d,u)=>{let m=qr(d,`steps[${u}]`),f=ht(m.run,`steps[${u}].run`);if(!f||f.trim().length===0)throw new Error(`steps[${u}].run is required`);let y=ht(m.name,`steps[${u}].name`),w=eo(m.timeout_sec,`steps[${u}].timeout_sec`);if(w!==void 0&&(!Number.isInteger(w)||w<=0))throw new Error(`steps[${u}].timeout_sec must be a positive integer`);return{run:f,...y?{name:y}:{},...w!==void 0?{timeout_sec:w}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:p}}function np(t,e,r){let n=qr(t,`params[${e}]`),o=ht(n.name,`params[${e}].name`);if(!o||!ye.test(o))throw new Error(`params[${e}].name must match ${ye}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let m=n.enum;if(!Array.isArray(m)||m.length===0||!m.every(f=>typeof f=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=m}let a=ht(n.label,`params[${e}].label`),c=ht(n.help,`params[${e}].help`),l=n.required===!0,p=eo(n.min,`params[${e}].min`),d=eo(n.max,`params[${e}].max`),u=n.default;if(u!=null&&typeof u!="string"&&typeof u!="number"&&typeof u!="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}:{},...p!==void 0?{min:p}:{},...d!==void 0?{max:d}:{},...u!=null?{default:u}:{}}}function Ei(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 Pi=64,Ai=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:[],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:[...Zn],help:"Overrides the recommended defaults for every role not listed below."},...xi.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Zn],help:`recommended: ${Si[t]}`}))]}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (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, a task taken from Develop waits in AWAITING_APPROVAL for a manual Approve before analysis starts. Off \u21D2 intake auto-starts the pipeline."}]},{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."}]}];function _i(t=op){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(..._i(r.groups));return e}function ip(t,e){let r=JSON.stringify(e);return _i().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function Ni(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}"`}:{ok:!0,field:e,value:i}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}case"string_map":{if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,error:`${e.id} must be a name\u2192value map`};let i=Object.entries(r);if(i.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(i.length>Pi)return{ok:!1,error:`${e.id} must have \u2264 ${Pi} entries`};let s={};for(let[a,c]of i){if(!ye.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${ye}`};if(ze(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>Ai)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${Ai} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}function Oi(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("/."))}var yt=/^[a-z][a-z0-9-]{1,30}$/,sp="-codepipe-ctx";function Fe(t){return`${t}${sp}`}var ap=[{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}];function Yr(t){for(let e of ap){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var gr={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function jt(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}var wt="x-bitbucket-api-token-auth";function Vr(t){switch(t){case gr.gitlab:return"oauth2";case gr.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Ui=20;function F(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as Ky}from"commander";import{homedir as Gi}from"node:os";import{mkdirSync as yp,readFileSync as wp,writeFileSync as bp,existsSync as ro}from"node:fs";import{dirname as Hi,join as Xr,resolve as kp}from"node:path";import{fileURLToPath as $p}from"node:url";import{existsSync as Jr,readFileSync as Li,readdirSync as lp,writeFileSync as up}from"node:fs";import{dirname as pp,join as Xe}from"node:path";import{parse as dp}from"yaml";import{existsSync as Di,renameSync as cp}from"node:fs";function bt(t,e,r=n=>console.error(n)){if(Di(e)||!Di(t))return!1;try{return cp(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(n){return r(`failed to migrate ${t} \u2192 ${e}: ${n instanceof Error?n.message:String(n)} \u2014 continuing with the legacy path untouched`),!1}}var Ae=".codepipe",to=".devpipe";function fp(t=process.cwd()){let e=t;for(;;){if(Jr(Xe(e,Ae,"project.yaml")))return e;if(Jr(Xe(e,to,"project.yaml")))return bt(Xe(e,to),Xe(e,Ae))&&gp(e),e;let r=pp(e);if(r===e)return null;e=r}}function mp(t){let e=Xe(t,Ae);return Jr(e)?e:Xe(t,to)}function gp(t){let e=Xe(t,".gitignore");if(!Jr(e))return;let r=Li(e,"utf-8"),n=r.split(/\r?\n/).map(o=>{let i=o.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?o.replace(".devpipe",".codepipe"):o}).join(`
6
- `);n!==r&&up(e,n)}function we(t=process.cwd()){let e=fp(t);if(!e)return null;let r=mp(e),n=hp(Li(Xe(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function Bi(t,e,r){return lp(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 zr(t,e=process.cwd()){try{let r=we(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function hp(t){let e=dp(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),n=String(e.name??r),o=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of o){if(!s||typeof s!="object")continue;let a=s,c=String(a.repo??a.repoName??""),l=String(a.name??c);if(!l||!c)continue;let p=a.host,d=p==="bitbucket"?"bitbucket":p==="gitlab"?"gitlab":"github";i.push({name:l,host:d,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l)})}return{projectId:r,name:n,repos:i}}function Mi(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 Fi=kp(Hi($p(import.meta.url)),"..");function Ki(t){let e=Xr(Fi,".env");if(ro(e)&&process.loadEnvFile(e),t){let r=Xr(Fi,"profiles",t,".env");ro(r)&&process.loadEnvFile(r)}}function Et(t){let e=F("CONFIG");return e||(t?Xr(Gi(),".codepipe","profiles",t,"config.json"):Xr(Gi(),".codepipe","config.json"))}function Re(t){let e=Et(t);if(!ro(e))return null;let r=wp(e,"utf-8");return JSON.parse(r)}function He(t,e){let r=Et(e);yp(Hi(r),{recursive:!0}),bp(r,JSON.stringify(t,null,2)+`
7
- `,{mode:384})}function Qr(t){if(t)return{cfg:be(t),profile:t};let e;try{e=we()?.spec.projectId||void 0}catch{}if(e){let r=Re(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:be(void 0),profile:void 0}}function be(t){let e=Re(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 ${Et(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}import{homedir as Wi}from"node:os";import{join as qi}from"node:path";function Yi(){bt(qi(Wi(),".devpipe"),qi(Wi(),".codepipe"))}import{homedir as Vi}from"node:os";import{existsSync as Ji,mkdirSync as zi,readFileSync as Xi,writeFileSync as Qi}from"node:fs";import{dirname as Zi,join as es}from"node:path";function ts(t,e,r){let n=D(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},J(n)}function rs(t,e){let r=D(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],J(r),!0)}function ns(t){return Object.keys(D(t)?.secrets??{}).sort()}function Zr(t,e,r){let n=D(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,J(n),"pinned")}function os(t,e){let r=D(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],J(r),!0):!1}function _e(t){return es(Vi(),".codepipe","secrets",`${t}.json`)}function D(t){let e=_e(t);return Ji(e)?JSON.parse(Xi(e,"utf-8")):null}function J(t){let e=_e(t.projectId);zi(Zi(e),{recursive:!0}),Qi(e,JSON.stringify(t,null,2)+`
8
- `,{mode:384})}function en(){return es(Vi(),".codepipe","shared.json")}function no(){let t=en();return Ji(t)?JSON.parse(Xi(t,"utf-8")):null}function is(t){let e=en();zi(Zi(e),{recursive:!0}),Qi(e,JSON.stringify(t,null,2)+`
9
- `,{mode:384})}function Pt(t){let e=D(t)?.claude?.oauthToken;return e||no()?.claude?.oauthToken}function hr(t){let e=(r,n)=>{n&&!process.env[r]&&(process.env[r]=n)};e("GH_TOKEN",t.github?.token),e("BITBUCKET_EMAIL",t.bitbucket?.email),e("BITBUCKET_API_TOKEN",t.bitbucket?.apiToken),e("GITLAB_TOKEN",t.gitlab?.token),e("YOUTRACK_URL",t.youtrack?.url),e("YOUTRACK_TOKEN",t.youtrack?.token)}function At(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}async function ss(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=Re(e);r&&!t.force&&(console.error(`already configured at ${Et(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");He({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...D(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};J(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${Et(e)}`)}import{homedir as Uo}from"node:os";import{join as jr}from"node:path";import{appendFileSync as vp,existsSync as as,mkdirSync as xp,renameSync as cs,statSync as Sp,unlinkSync as Rp}from"node:fs";import{Writable as Tp}from"node:stream";import{join as Cp}from"node:path";var ls={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},_t=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&xp(e.dir,{recursive:!0}),this.currentPath=Cp(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
5
+ `}function Gi(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 Fi(t,e=Mi){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 Hi(t,e=Mi){return e.filter(r=>r.version>t)}var Lp=[{id:"intake",label:"\u041F\u0440\u0438\u0451\u043C\u043A\u0430",phases:["INTAKE"]},{id:"analysis",label:"\u0410\u043D\u0430\u043B\u0438\u0437",phases:["ANALYZING","ESTIMATING"]},{id:"ready",label:"\u0413\u043E\u0442\u043E\u0432\u0430 \u043A \u0440\u0430\u0431\u043E\u0442\u0435",phases:["READY"]},{id:"implementation",label:"\u0420\u0435\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u044F",phases:["IMPLEMENTING","BUILD"]},{id:"delivery",label:"\u0414\u043E\u0441\u0442\u0430\u0432\u043A\u0430",phases:["READY_TO_APPLY","APPLYING"]}],Zk=Lp.flatMap(t=>t.phases);var Ki=["estimate","analyze","implement","resolve-conflict","rework","draft","build","index","backfill","analysis","chat"];function wt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var We="opus",on="sonnet",Bp="haiku",go=[We,on,Bp],Wi={analyze:We,implement:We,"resolve-conflict":We,rework:We,estimate:on,build:on,draft:on,index:We,backfill:We,analysis:We,chat:We};var $e=/^[A-Z][A-Z0-9_]*$/,Mp=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),Gp=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];function et(t){return Mp.has(t)?!0:Gp.some(e=>t.startsWith(e))}var Ji=600,Yi=/^[a-z0-9-]+$/,qi=32,Vi=64;function sn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function bt(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function ho(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function zi(t,e){let r=sn(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=bt(r.id,"id")??n;if(!Yi.test(o))throw new Error(`id must match ${Yi} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=bt(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let d=sn(r.env,"env");s={};for(let[u,m]of Object.entries(d)){if(!$e.test(u))throw new Error(`env name "${u}" must match ${$e}`);if(typeof m!="string"&&typeof m!="number"&&typeof m!="boolean")throw new Error(`env.${u} must be a scalar`);s[u]=String(m)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>qi)throw new Error(`too many params (max ${qi})`);let d=new Set;a=c.map((u,m)=>Fp(u,m,d))}let l=r.steps;if(!Array.isArray(l)||l.length===0)throw new Error("steps must be a non-empty list");if(l.length>Vi)throw new Error(`too many steps (max ${Vi})`);let p=l.map((d,u)=>{let m=sn(d,`steps[${u}]`),f=bt(m.run,`steps[${u}].run`);if(!f||f.trim().length===0)throw new Error(`steps[${u}].run is required`);let y=bt(m.name,`steps[${u}].name`),k=ho(m.timeout_sec,`steps[${u}].timeout_sec`);if(k!==void 0&&(!Number.isInteger(k)||k<=0))throw new Error(`steps[${u}].timeout_sec must be a positive integer`);return{run:f,...y?{name:y}:{},...k!==void 0?{timeout_sec:k}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:p}}function Fp(t,e,r){let n=sn(t,`params[${e}]`),o=bt(n.name,`params[${e}].name`);if(!o||!$e.test(o))throw new Error(`params[${e}].name must match ${$e}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let m=n.enum;if(!Array.isArray(m)||m.length===0||!m.every(f=>typeof f=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=m}let a=bt(n.label,`params[${e}].label`),c=bt(n.help,`params[${e}].help`),l=n.required===!0,p=ho(n.min,`params[${e}].min`),d=ho(n.max,`params[${e}].max`),u=n.default;if(u!=null&&typeof u!="string"&&typeof u!="number"&&typeof u!="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}:{},...p!==void 0?{min:p}:{},...d!==void 0?{max:d}:{},...u!=null?{default:u}:{}}}function Xi(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 Qi=64,Zi=2e3,Hp=[{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:[],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:[...go],help:"Overrides the recommended defaults for every role not listed below."},...Ki.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...go],help:`recommended: ${Wi[t]}`}))]}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (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, a task taken from Develop waits in AWAITING_APPROVAL for a manual Approve before analysis starts. Off \u21D2 intake auto-starts the pipeline."}]},{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."}]}];function es(t=Hp){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...es(r.groups));return e}function Kp(t,e){let r=JSON.stringify(e);return es().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function ts(t){let e=Kp(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}"`}:{ok:!0,field:e,value:i}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}case"string_map":{if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,error:`${e.id} must be a name\u2192value map`};let i=Object.entries(r);if(i.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(i.length>Qi)return{ok:!1,error:`${e.id} must have \u2264 ${Qi} entries`};let s={};for(let[a,c]of i){if(!$e.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${$e}`};if(et(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>Zi)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${Zi} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}function rs(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("/."))}var $t=/^[a-z][a-z0-9-]{1,30}$/,Wp="-codepipe-ctx";function Ye(t){return`${t}${Wp}`}var Yp=[{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}];function _t(t){for(let e of Yp){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var ns=["bug","feature","epic"],an="feature",br="TASK",cn=/^[A-Z][A-Z0-9]{1,9}$/,yo={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},fw=yo.backlog,ln="tracker/config.yaml",$r="tracker/counter";function vr(t){return`tasks/${t}/issue.yaml`}var xr={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function Nt(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}var vt="x-bitbucket-api-token-auth";function un(t){switch(t){case xr.gitlab:return"oauth2";case xr.bitbucket:return"x-token-auth";default:return"x-access-token"}}var os=20;function F(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as Kk}from"commander";import{homedir as ls}from"node:os";import{mkdirSync as rd,readFileSync as nd,writeFileSync as od,existsSync as wo}from"node:fs";import{dirname as ps,join as fn,resolve as id}from"node:path";import{fileURLToPath as sd}from"node:url";import{existsSync as pn,readFileSync as ss,readdirSync as Vp,writeFileSync as Jp}from"node:fs";import{dirname as zp,join as tt}from"node:path";import{parse as Xp}from"yaml";import{existsSync as is,renameSync as qp}from"node:fs";function xt(t,e,r=n=>console.error(n)){if(is(e)||!is(t))return!1;try{return qp(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(n){return r(`failed to migrate ${t} \u2192 ${e}: ${n instanceof Error?n.message:String(n)} \u2014 continuing with the legacy path untouched`),!1}}var Oe=".codepipe",ko=".devpipe";function Qp(t=process.cwd()){let e=t;for(;;){if(pn(tt(e,Oe,"project.yaml")))return e;if(pn(tt(e,ko,"project.yaml")))return xt(tt(e,ko),tt(e,Oe))&&ed(e),e;let r=zp(e);if(r===e)return null;e=r}}function Zp(t){let e=tt(t,Oe);return pn(e)?e:tt(t,ko)}function ed(t){let e=tt(t,".gitignore");if(!pn(e))return;let r=ss(e,"utf-8"),n=r.split(/\r?\n/).map(o=>{let i=o.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?o.replace(".devpipe",".codepipe"):o}).join(`
6
+ `);n!==r&&Jp(e,n)}function ve(t=process.cwd()){let e=Qp(t);if(!e)return null;let r=Zp(e),n=td(ss(tt(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function as(t,e,r){return Vp(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 dn(t,e=process.cwd()){try{let r=ve(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function td(t){let e=Xp(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),n=String(e.name??r),o=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of o){if(!s||typeof s!="object")continue;let a=s,c=String(a.repo??a.repoName??""),l=String(a.name??c);if(!l||!c)continue;let p=a.host,d=p==="bitbucket"?"bitbucket":p==="gitlab"?"gitlab":"github";i.push({name:l,host:d,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l)})}return{projectId:r,name:n,repos:i}}function cs(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 us=id(ps(sd(import.meta.url)),"..");function ds(t){let e=fn(us,".env");if(wo(e)&&process.loadEnvFile(e),t){let r=fn(us,"profiles",t,".env");wo(r)&&process.loadEnvFile(r)}}function Ot(t){let e=F("CONFIG");return e||(t?fn(ls(),".codepipe","profiles",t,"config.json"):fn(ls(),".codepipe","config.json"))}function Ce(t){let e=Ot(t);if(!wo(e))return null;let r=nd(e,"utf-8");return JSON.parse(r)}function qe(t,e){let r=Ot(e);rd(ps(r),{recursive:!0}),od(r,JSON.stringify(t,null,2)+`
7
+ `,{mode:384})}function mn(t){if(t)return{cfg:xe(t),profile:t};let e;try{e=ve()?.spec.projectId||void 0}catch{}if(e){let r=Ce(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:xe(void 0),profile:void 0}}function xe(t){let e=Ce(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 ${Ot(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}import{homedir as fs}from"node:os";import{join as ms}from"node:path";function gs(){xt(ms(fs(),".devpipe"),ms(fs(),".codepipe"))}import{homedir as hs}from"node:os";import{existsSync as ys,mkdirSync as ks,readFileSync as ws,writeFileSync as bs}from"node:fs";import{dirname as $s,join as vs}from"node:path";function xs(t,e,r){let n=L(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},z(n)}function Ss(t,e){let r=L(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],z(r),!0)}function Rs(t){return Object.keys(L(t)?.secrets??{}).sort()}function gn(t,e,r){let n=L(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,z(n),"pinned")}function Ts(t,e){let r=L(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],z(r),!0):!1}function De(t){return vs(hs(),".codepipe","secrets",`${t}.json`)}function L(t){let e=De(t);return ys(e)?JSON.parse(ws(e,"utf-8")):null}function z(t){let e=De(t.projectId);ks($s(e),{recursive:!0}),bs(e,JSON.stringify(t,null,2)+`
8
+ `,{mode:384})}function hn(){return vs(hs(),".codepipe","shared.json")}function bo(){let t=hn();return ys(t)?JSON.parse(ws(t,"utf-8")):null}function Is(t){let e=hn();ks($s(e),{recursive:!0}),bs(e,JSON.stringify(t,null,2)+`
9
+ `,{mode:384})}function Dt(t){let e=L(t)?.claude?.oauthToken;return e||bo()?.claude?.oauthToken}function Sr(t){let e=(r,n)=>{n&&!process.env[r]&&(process.env[r]=n)};e("GH_TOKEN",t.github?.token),e("BITBUCKET_EMAIL",t.bitbucket?.email),e("BITBUCKET_API_TOKEN",t.bitbucket?.apiToken),e("GITLAB_TOKEN",t.gitlab?.token),e("YOUTRACK_URL",t.youtrack?.url),e("YOUTRACK_TOKEN",t.youtrack?.token)}function Ut(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}async function Cs(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=Ce(e);r&&!t.force&&(console.error(`already configured at ${Ot(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");qe({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...L(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};z(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${Ot(e)}`)}import{homedir as oi}from"node:os";import{join as Fr}from"node:path";import{appendFileSync as ad,existsSync as Es,mkdirSync as cd,renameSync as Ps,statSync as ld,unlinkSync as ud}from"node:fs";import{Writable as pd}from"node:stream";import{join as dd}from"node:path";var js={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},Lt=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&cd(e.dir,{recursive:!0}),this.currentPath=dd(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
10
10
  `)?e:e+`
11
- `;vp(this.currentPath,r,"utf-8")}asWritable(){return new Tp({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||!as(this.currentPath)||Sp(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;as(n)&&(r>=this.cfg.maxFiles?Rp(n):cs(n,`${this.currentPath}.${r+1}`))}cs(this.currentPath,`${this.currentPath}.1`)}}};function tn(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=Ip(process.env[`${t}_MAX_BYTES`]??String(ls.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):ls.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function Ip(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 rn(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(jp(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 jp(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:Ep(o)).join(" ");return`${r} ${t} ${n}`}function Ep(t){try{return JSON.stringify(t)}catch{return String(t)}}import{existsSync as kc,rmSync as lm}from"node:fs";import{join as Ir}from"node:path";import{simpleGit as um}from"simple-git";import"ws";import{createHash as Pp}from"node:crypto";import{existsSync as Ap,readFileSync as _p}from"node:fs";import{homedir as Np,hostname as oo}from"node:os";import{join as Op}from"node:path";function us(t){return Pp("sha256").update(t).digest("hex").slice(0,12)}function Up(){let t=F("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=Op(Np(),".claude","credentials.json");if(!Ap(e))return;let r=JSON.parse(_p(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 ps(t){let e=Up(),r=F("ACCOUNT_ID")?.trim(),n=F("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=Pt(t);return o?{accountId:`acct-${us(o)}`,label:n||oo(),...e?{email:e}:{}}:{accountId:`acct-${us(`host:${oo()}`)}`,label:n||oo(),...e?{email:e}:{}}}import{existsSync as Dp}from"node:fs";import{join as Lp}from"node:path";import{simpleGit as Bp}from"simple-git";async function ds(t,e){if(!Dp(Lp(t,".git")))return{status:"skipped"};let r=Bp(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${Mp(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 Mp(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as so,readFileSync as ys,readdirSync as Hp,watch as Kp}from"node:fs";import{join as ao}from"node:path";import{existsSync as fs,readFileSync as ms,readdirSync as Gp,statSync as Fp}from"node:fs";import{join as io}from"node:path";import{parse as gs}from"yaml";function nn(t){let e=io(t,"actions"),r=[],n=[];if(!fs(e))return{defs:r,errors:n};let o;try{o=Gp(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=io(e,s);try{if(!Fp(a).isFile())continue;let c=ji(s,gs(ms(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 hs(t){let e={},r=io(t,"project.yaml");if(!fs(r))return e;let n;try{n=gs(ms(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))!ye.test(i)||ze(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var on=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;watcher=null;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(){if(this.started=!1,this.timer&&clearInterval(this.timer),this.timer=null,this.debounce&&clearTimeout(this.debounce),this.debounce=null,this.watcher)try{this.watcher.close()}catch{}this.watcher=null}installWatcher(){if(so(this.contextDir))try{this.watcher=Kp(this.contextDir,{recursive:!0},()=>{this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>this.report(),500),this.debounce.unref?.()})}catch{this.watcher=null}}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=nn(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(!so(r))return null;try{return ys(r,"utf-8")}catch{return null}}readPrompts(){let e=ao(this.contextDir,"prompts"),r={};if(!so(e))return r;let n;try{n=Hp(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=ys(ao(e,o),"utf-8")}catch{}}return r}};import{existsSync as mo,readFileSync as Ss,readdirSync as td}from"node:fs";import{join as Rs}from"node:path";import{simpleGit as rd}from"simple-git";import{existsSync as Vp,mkdirSync as Jp,rmSync as zp,writeFileSync as ks}from"node:fs";import{dirname as Xp,isAbsolute as Qp,join as vs,normalize as fo}from"node:path";import{simpleGit as xs}from"simple-git";import{existsSync as Qe,mkdirSync as ws,readFileSync as co,writeFileSync as Nt}from"node:fs";import{homedir as Wp}from"node:os";import{join as Ne}from"node:path";import{simpleGit as qp}from"simple-git";var Ot=["project.yaml","regimen.yaml"];function yr(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=Ne(t,o);Qe(s)||(Nt(s,i),r.push(o))}return r}function kt(t,e,r){let n=Ne(Wp(),".codepipe","profiles",t,"context-config");return ws(n,{recursive:!0}),Nt(Ne(n,"project.yaml"),e.projectYaml),Nt(Ne(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function sn(t,e,r){if(Qe(e))for(let n of Ot){let o=Ne(e,n),i=Ne(t,n);if(!(!Qe(o)||Qe(i)))try{Nt(i,co(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)}`)}}}var Yp=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"];function Ut(t){let e=Ne(t,".gitignore"),r=Qe(e)?co(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(Ot.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
11
+ `;ad(this.currentPath,r,"utf-8")}asWritable(){return new pd({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||!Es(this.currentPath)||ld(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;Es(n)&&(r>=this.cfg.maxFiles?ud(n):Ps(n,`${this.currentPath}.${r+1}`))}Ps(this.currentPath,`${this.currentPath}.1`)}}};function yn(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=fd(process.env[`${t}_MAX_BYTES`]??String(js.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):js.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function fd(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 kn(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(md(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 md(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:gd(o)).join(" ");return`${r} ${t} ${n}`}function gd(t){try{return JSON.stringify(t)}catch{return String(t)}}import{existsSync as il,rmSync as lg}from"node:fs";import{join as Gr}from"node:path";import{simpleGit as ug}from"simple-git";import"ws";import{createHash as hd}from"node:crypto";import{existsSync as yd,readFileSync as kd}from"node:fs";import{homedir as wd,hostname as $o}from"node:os";import{join as bd}from"node:path";function As(t){return hd("sha256").update(t).digest("hex").slice(0,12)}function $d(){let t=F("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=bd(wd(),".claude","credentials.json");if(!yd(e))return;let r=JSON.parse(kd(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 _s(t){let e=$d(),r=F("ACCOUNT_ID")?.trim(),n=F("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=Dt(t);return o?{accountId:`acct-${As(o)}`,label:n||$o(),...e?{email:e}:{}}:{accountId:`acct-${As(`host:${$o()}`)}`,label:n||$o(),...e?{email:e}:{}}}import{existsSync as vd}from"node:fs";import{join as xd}from"node:path";import{simpleGit as Sd}from"simple-git";async function Ns(t,e){if(!vd(xd(t,".git")))return{status:"skipped"};let r=Sd(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${Rd(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 Rd(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as xo,readFileSync as Bs,readdirSync as Cd,watch as Ed}from"node:fs";import{join as So}from"node:path";import{existsSync as Os,readFileSync as Ds,readdirSync as Td,statSync as Id}from"node:fs";import{join as vo}from"node:path";import{parse as Us}from"yaml";function wn(t){let e=vo(t,"actions"),r=[],n=[];if(!Os(e))return{defs:r,errors:n};let o;try{o=Td(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=vo(e,s);try{if(!Id(a).isFile())continue;let c=zi(s,Us(Ds(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 Ls(t){let e={},r=vo(t,"project.yaml");if(!Os(r))return e;let n;try{n=Us(Ds(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))!$e.test(i)||et(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var bn=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;watcher=null;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(){if(this.started=!1,this.timer&&clearInterval(this.timer),this.timer=null,this.debounce&&clearTimeout(this.debounce),this.debounce=null,this.watcher)try{this.watcher.close()}catch{}this.watcher=null}installWatcher(){if(xo(this.contextDir))try{this.watcher=Ed(this.contextDir,{recursive:!0},()=>{this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>this.report(),500),this.debounce.unref?.()})}catch{this.watcher=null}}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=wn(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=So(this.contextDir,e);if(!xo(r))return null;try{return Bs(r,"utf-8")}catch{return null}}readPrompts(){let e=So(this.contextDir,"prompts"),r={};if(!xo(e))return r;let n;try{n=Cd(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=Bs(So(e,o),"utf-8")}catch{}}return r}};import{existsSync as Ao,readFileSync as Ys,readdirSync as Gd}from"node:fs";import{join as qs}from"node:path";import{simpleGit as Fd}from"simple-git";import{existsSync as _d,mkdirSync as Nd,rmSync as Od,writeFileSync as Eo}from"node:fs";import{dirname as Dd,isAbsolute as Ud,join as Ks,normalize as xn}from"node:path";import{simpleGit as Ws}from"simple-git";import{existsSync as rt,mkdirSync as Ms,readFileSync as Ro,writeFileSync as Bt}from"node:fs";import{homedir as Pd}from"node:os";import{join as Ue}from"node:path";import{simpleGit as jd}from"simple-git";var Mt=["project.yaml","regimen.yaml"];function Rr(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=Ue(t,o);rt(s)||(Bt(s,i),r.push(o))}return r}function St(t,e,r){let n=Ue(Pd(),".codepipe","profiles",t,"context-config");return Ms(n,{recursive:!0}),Bt(Ue(n,"project.yaml"),e.projectYaml),Bt(Ue(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function $n(t,e,r){if(rt(e))for(let n of Mt){let o=Ue(e,n),i=Ue(t,n);if(!(!rt(o)||rt(i)))try{Bt(i,Ro(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)}`)}}}var Ad=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"];function Gt(t){let e=Ue(t,".gitignore"),r=rt(e)?Ro(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(Mt.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
12
12
  `)?"":`
13
- `;return Nt(e,r+i+Yp.join(`
13
+ `;return Bt(e,r+i+Ad.join(`
14
14
  `)+`
15
- `),!0}async function bs(t,e){try{if(!Qe(Ne(t,".git")))return;let r=qp(t),n=(await r.raw(["ls-files","--",...Ot])).split(`
16
- `).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;Ut(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 po(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 lo(t){let e=new Map;for(let r of Ot){let n=Ne(t,r);Qe(n)&&e.set(r,co(n))}return e}function uo(t,e){ws(t,{recursive:!0});for(let[r,n]of e){let o=Ne(t,r);Qe(o)||Nt(o,n)}}var $s=3,Zp=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]);async function Dt(t,e,r){if(!Vp(vs(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let i of e){let s=Ke(t,i.path);if(i.deleted){zp(s,{force:!0});continue}Jp(Xp(s),{recursive:!0}),i.encoding==="base64"?ks(s,Buffer.from(i.content,"base64")):ks(s,i.content)}let n=xs(t);await n.add(["-A","--","."]),await n.raw(["reset","-q","--",...Ot]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await po(t))}async function po(t){let e=xs(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=$s;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 ed(e);if(i.length>0&&i.every(s=>Zp.has(s)))await e.raw(["checkout","--theirs","--",...i]),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 ${$s} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function ed(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
17
- `).map(r=>r.trim()).filter(Boolean)}function Ke(t,e){if(Qp(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=fo(vs(t,e)),n=fo(t+"/");if(r!==fo(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var nd=/^(\d{4})-(.+)\.md$/,od="0000-template.md";function id(t){let e=t.split(`
18
- `),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 sd(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
19
- `),a=s.findIndex(k=>k.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),p=[],d="",u=null,m=a>=0?a+1:0;for(let k=m;k<s.length;k++){let h=(s[k]??"").trim();if(h===""){m=k+1;continue}let $=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(h);if(!$)break;let S=($[1]??"").trim().toLowerCase(),B=($[2]??"").trim(),j=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(h);j&&(u=parseInt(j[1]??"",10)),S==="tasks"&&(d=B),l.has(S)||p.push(h),m=k+1}let f=d?d.includes(n)?d:`${d}, ${n}`:n,y=s.slice(m).join(`
20
- `).replace(/^\n+/,""),w=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${f}`,...p,"",y].join(`
21
- `);return{content:w.endsWith(`
22
- `)?w:w+`
23
- `,supersedes:u}}function ad(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
24
-
25
- - **Status:** superseded by ADR-${r}`):n}function cd(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(`
15
+ `),!0}async function Gs(t,e){try{if(!rt(Ue(t,".git")))return;let r=jd(t),n=(await r.raw(["ls-files","--",...Mt])).split(`
16
+ `).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;Gt(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 Co(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 To(t){let e=new Map;for(let r of Mt){let n=Ue(t,r);rt(n)&&e.set(r,Ro(n))}return e}function Io(t,e){Ms(t,{recursive:!0});for(let[r,n]of e){let o=Ue(t,r);rt(o)||Bt(o,n)}}var Fs=3,Ld=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),Hs=/^tasks\/[^/]+\/comments\.jsonl$/,vn=new Map;async function Po(t,e){let r=xn(t),o=(vn.get(r)??Promise.resolve()).catch(()=>{}).then(e);vn.set(r,o);try{return await o}finally{vn.get(r)===o&&vn.delete(r)}}async function Ve(t,e,r){return Po(t,()=>jo(t,e,r))}async function jo(t,e,r){if(!_d(Ks(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let i of e){let s=ie(t,i.path);if(i.deleted){Od(s,{force:!0});continue}Nd(Dd(s),{recursive:!0}),i.encoding==="base64"?Eo(s,Buffer.from(i.content,"base64")):Eo(s,i.content)}let n=Ws(t);await n.add(["-A","--","."]),await n.raw(["reset","-q","--",...Mt]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await Co(t))}async function Co(t){let e=Ws(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=Fs;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 Md(e);if(i.length>0&&i.every(a=>Ld.has(a)||Hs.test(a))){for(let a of i)Hs.test(a)?await Bd(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 ${Fs} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function Bd(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(`
17
+ `)){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);Eo(ie(e,r),i.join(`
18
+ `)+(i.length>0?`
19
+ `:""))}async function Md(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
20
+ `).map(r=>r.trim()).filter(Boolean)}function ie(t,e){if(Ud(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=xn(Ks(t,e)),n=xn(t+"/");if(r!==xn(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var Hd=/^(\d{4})-(.+)\.md$/,Kd="0000-template.md";function Wd(t){let e=t.split(`
21
+ `),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 Yd(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
22
+ `),a=s.findIndex($=>$.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),p=[],d="",u=null,m=a>=0?a+1:0;for(let $=m;$<s.length;$++){let h=(s[$]??"").trim();if(h===""){m=$+1;continue}let w=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(h);if(!w)break;let I=(w[1]??"").trim().toLowerCase(),B=(w[2]??"").trim(),R=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(h);R&&(u=parseInt(R[1]??"",10)),I==="tasks"&&(d=B),l.has(I)||p.push(h),m=$+1}let f=d?d.includes(n)?d:`${d}, ${n}`:n,y=s.slice(m).join(`
23
+ `).replace(/^\n+/,""),k=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${f}`,...p,"",y].join(`
24
+ `);return{content:k.endsWith(`
25
+ `)?k:k+`
26
+ `,supersedes:u}}function qd(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
27
+
28
+ - **Status:** superseded by ADR-${r}`):n}function Vd(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(`
26
29
  `)+`
27
- `}async function Ts(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await rd(t).pull(void 0,void 0,["--rebase"])}catch{}let i=w=>o==="staging"?`adr/DRAFT-${w}.md`:`tasks/${e}/adr/DRAFT-${w}.md`,s=[],a=[];for(let w of r){let k=Ke(t,i(w));if(!mo(k)){a.push(w);continue}s.push({slug:w,content:Ss(k,"utf-8")})}let c=Rs(t,"adr"),l=new Map;if(mo(c))for(let w of td(c)){let k=nd.exec(w);!k||w===od||l.set(w,{num:parseInt(k[1]??"",10),slug:k[2]??"",content:Ss(Rs(c,w),"utf-8")})}let p=Math.max(0,...[...l.values()].map(w=>w.num))+1,d=new Map,u=[],m=[];for(let w of s){if([...l.entries()].find(([,j])=>j.slug===w.slug&&j.content.includes(e))){m.push(w.slug);continue}let h=p++,$=`${String(h).padStart(4,"0")}-${w.slug}.md`,{content:S,supersedes:B}=sd(w.content,h,w.slug,e,n);if(d.set($,S),l.set($,{num:h,slug:w.slug,content:S}),u.push(`adr/${$}`),B!==null){let j=[...l.keys()].find(A=>A.startsWith(`${String(B).padStart(4,"0")}-`));if(j&&j!==$){let A=ad(d.get(j)??l.get(j).content,h);d.set(j,A),l.set(j,{...l.get(j),content:A})}}}let f=[];if(o==="staging")for(let w of s)mo(Ke(t,`adr/DRAFT-${w.slug}.md`))&&f.push({path:`adr/DRAFT-${w.slug}.md`,content:"",deleted:!0});if(u.length===0&&f.length===0)return{promoted:u,skipped:m,missing:a};if(u.length>0){let w=[...l.entries()].map(([k,h])=>({num:h.num,file:k,header:id(h.content)}));d.set("INDEX.md",cd(w))}for(let[w,k]of d.entries())f.push({path:`adr/${w}`,content:k});let y=u.length>0?`adr(${e}): promote ${s.map(w=>w.slug).join(", ")}`:`adr(${e}): drop stale staged ${m.join(", ")}`;return await Dt(t,f,y),{promoted:u,skipped:m,missing:a}}import{existsSync as Cs,readFileSync as ud}from"node:fs";import{join as Is}from"node:path";function pd(t){for(let e of[Pe,mr]){let r=Is(t,e);if(Cs(r))try{return ki(ud(r,"utf-8"))}catch{return 0}}return 0}function dd(t,e,r,n=3){let o=e<n,i=o?$i(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function an(t,e){return dd(e,pd(t),r=>Cs(Is(t,r)))}import{existsSync as As,mkdirSync as Id,mkdtempSync as jd,rmSync as _s,writeFileSync as Ns}from"node:fs";import{tmpdir as Ed}from"node:os";import{dirname as Pd,join as ln}from"node:path";import{simpleGit as bo}from"simple-git";var $t=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};function js(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
28
- `+t.slice(t.length-e)}async function Ze(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n;try{n=await fetch("https://api.github.com/user",{headers:r})}catch(a){throw new Error(`cannot reach api.github.com (${a instanceof Error?a.message:String(a)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(!n.ok)throw new Error(`GitHub \u2192 ${n.status} ${n.statusText}`);let i=(await n.json()).login??"ok",s=n.headers.get("x-oauth-scopes");if(s!==null&&e&&!s.split(",").map(c=>c.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${s||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let a;try{let c=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r});c.ok&&(a=(await c.json()).type)}catch{}if(a==="Organization"){let c=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r});if(c.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(c.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(!c.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${c.status} ${c.statusText}`)}}return i}async function cn(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o;try{o=await fetch(n,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"}})}catch(s){throw new Error(`cannot reach api.github.com (${s instanceof Error?s.message:String(s)})`)}if(o.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(o.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(!o.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${o.status} ${o.statusText}`);if((await o.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}async function et(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;try{o=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch(s){throw new Error(`cannot reach api.bitbucket.org (${s instanceof Error?s.message:String(s)})`)}if(o.ok)return t;if(o.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;let i=await fd(o);throw o.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${i})`):o.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${i})`):o.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${i})`):new Error(`Bitbucket \u2192 ${o.status} ${o.statusText}${i}`)}async function fd(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function tt(t){let e;try{e=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}})}catch(n){throw new Error(`cannot reach gitlab.com (${n instanceof Error?n.message:String(n)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(!e.ok)throw new Error(`GitLab \u2192 ${e.status} ${e.statusText}`);return(await e.json()).username??"ok"}async function Ps(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}}var go=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 $t(`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 closePR(e,r,n){if(n&&n.length>0){let i=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(!i.ok)throw new Error(`bitbucket comment PR #${r}: ${i.status} ${await i.text()}`)}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()}`)}},ho=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 $t(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),a=!1,c=!1,l=!1;if(i.ok){let p=await i.json();for(let d of p.check_runs??[])l=!0,d.status!=="completed"?a=!0:d.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(d.conclusion)&&(c=!0)}if(s.ok){let p=await s.json();(p.total_count??0)>0&&(l=!0,p.state==="pending"?a=!0:(p.state==="failure"||p.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${o}/pulls/${r}`,{headers:n});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${o}/actions/runs?head_sha=${a}&per_page=20`,{headers:n});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],p=[];for(let d of l.filter(u=>u.conclusion&&i.includes(u.conclusion))){let u=await fetch(`${o}/actions/runs/${d.id}/jobs?per_page=50`,{headers:n});if(!u.ok)continue;let m=(await u.json()).jobs??[];for(let f of m.filter(y=>y.conclusion==="failure")){let y=await fetch(`${o}/actions/jobs/${f.id}/logs`,{headers:n});if(!y.ok)continue;let w=await y.text();p.push(`### CI job: ${f.name}
30
+ `}async function Vs(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await Fd(t).pull(void 0,void 0,["--rebase"])}catch{}let i=k=>o==="staging"?`adr/DRAFT-${k}.md`:`tasks/${e}/adr/DRAFT-${k}.md`,s=[],a=[];for(let k of r){let $=ie(t,i(k));if(!Ao($)){a.push(k);continue}s.push({slug:k,content:Ys($,"utf-8")})}let c=qs(t,"adr"),l=new Map;if(Ao(c))for(let k of Gd(c)){let $=Hd.exec(k);!$||k===Kd||l.set(k,{num:parseInt($[1]??"",10),slug:$[2]??"",content:Ys(qs(c,k),"utf-8")})}let p=Math.max(0,...[...l.values()].map(k=>k.num))+1,d=new Map,u=[],m=[];for(let k of s){if([...l.entries()].find(([,R])=>R.slug===k.slug&&R.content.includes(e))){m.push(k.slug);continue}let h=p++,w=`${String(h).padStart(4,"0")}-${k.slug}.md`,{content:I,supersedes:B}=Yd(k.content,h,k.slug,e,n);if(d.set(w,I),l.set(w,{num:h,slug:k.slug,content:I}),u.push(`adr/${w}`),B!==null){let R=[...l.keys()].find(j=>j.startsWith(`${String(B).padStart(4,"0")}-`));if(R&&R!==w){let j=qd(d.get(R)??l.get(R).content,h);d.set(R,j),l.set(R,{...l.get(R),content:j})}}}let f=[];if(o==="staging")for(let k of s)Ao(ie(t,`adr/DRAFT-${k.slug}.md`))&&f.push({path:`adr/DRAFT-${k.slug}.md`,content:"",deleted:!0});if(u.length===0&&f.length===0)return{promoted:u,skipped:m,missing:a};if(u.length>0){let k=[...l.entries()].map(([$,h])=>({num:h.num,file:$,header:Wd(h.content)}));d.set("INDEX.md",Vd(k))}for(let[k,$]of d.entries())f.push({path:`adr/${k}`,content:$});let y=u.length>0?`adr(${e}): promote ${s.map(k=>k.slug).join(", ")}`:`adr(${e}): drop stale staged ${m.join(", ")}`;return await Ve(t,f,y),{promoted:u,skipped:m,missing:a}}import{existsSync as Js,readFileSync as zd}from"node:fs";import{join as zs}from"node:path";function Xd(t){for(let e of[Ne,wr]){let r=zs(t,e);if(Js(r))try{return Gi(zd(r,"utf-8"))}catch{return 0}}return 0}function Qd(t,e,r,n=3){let o=e<n,i=o?Fi(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function Sn(t,e){return Qd(e,Xd(t),r=>Js(zs(t,r)))}import{existsSync as la,mkdirSync as Tf,mkdtempSync as If,rmSync as ua,writeFileSync as pa}from"node:fs";import{tmpdir as Cf}from"node:os";import{dirname as Ef,join as Tn}from"node:path";import{simpleGit as Mo}from"simple-git";var Rt=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};function Xs(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
31
+ `+t.slice(t.length-e)}async function nt(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n;try{n=await fetch("https://api.github.com/user",{headers:r})}catch(a){throw new Error(`cannot reach api.github.com (${a instanceof Error?a.message:String(a)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(!n.ok)throw new Error(`GitHub \u2192 ${n.status} ${n.statusText}`);let i=(await n.json()).login??"ok",s=n.headers.get("x-oauth-scopes");if(s!==null&&e&&!s.split(",").map(c=>c.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${s||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let a;try{let c=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r});c.ok&&(a=(await c.json()).type)}catch{}if(a==="Organization"){let c=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r});if(c.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(c.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(!c.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${c.status} ${c.statusText}`)}}return i}async function Rn(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o;try{o=await fetch(n,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"}})}catch(s){throw new Error(`cannot reach api.github.com (${s instanceof Error?s.message:String(s)})`)}if(o.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(o.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(!o.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${o.status} ${o.statusText}`);if((await o.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}async function ot(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;try{o=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch(s){throw new Error(`cannot reach api.bitbucket.org (${s instanceof Error?s.message:String(s)})`)}if(o.ok)return t;if(o.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;let i=await Zd(o);throw o.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${i})`):o.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${i})`):o.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${i})`):new Error(`Bitbucket \u2192 ${o.status} ${o.statusText}${i}`)}async function Zd(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function it(t){let e;try{e=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}})}catch(n){throw new Error(`cannot reach gitlab.com (${n instanceof Error?n.message:String(n)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(!e.ok)throw new Error(`GitLab \u2192 ${e.status} ${e.statusText}`);return(await e.json()).username??"ok"}async function Zs(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}}var _o=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 Rt(`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 closePR(e,r,n){if(n&&n.length>0){let i=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(!i.ok)throw new Error(`bitbucket comment PR #${r}: ${i.status} ${await i.text()}`)}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()}`)}},No=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 Rt(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),a=!1,c=!1,l=!1;if(i.ok){let p=await i.json();for(let d of p.check_runs??[])l=!0,d.status!=="completed"?a=!0:d.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(d.conclusion)&&(c=!0)}if(s.ok){let p=await s.json();(p.total_count??0)>0&&(l=!0,p.state==="pending"?a=!0:(p.state==="failure"||p.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${o}/pulls/${r}`,{headers:n});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${o}/actions/runs?head_sha=${a}&per_page=20`,{headers:n});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],p=[];for(let d of l.filter(u=>u.conclusion&&i.includes(u.conclusion))){let u=await fetch(`${o}/actions/runs/${d.id}/jobs?per_page=50`,{headers:n});if(!u.ok)continue;let m=(await u.json()).jobs??[];for(let f of m.filter(y=>y.conclusion==="failure")){let y=await fetch(`${o}/actions/jobs/${f.id}/logs`,{headers:n});if(!y.ok)continue;let k=await y.text();p.push(`### CI job: ${f.name}
29
32
 
30
- ${js(w,8e3)}`)}}return p.length===0?void 0:js(p.join(`
33
+ ${Xs(k,8e3)}`)}}return p.length===0?void 0:Xs(p.join(`
31
34
 
32
- `),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 closePR(e,r,n){if(n&&n.length>0){let i=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(!i.ok)throw new Error(`github comment PR #${r}: ${i.status} ${await i.text()}`)}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()}`)}},yo=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 $t(`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=md(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 p=await a.json().catch(()=>null);s=p?.sha??p?.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 closePR(e,r,n){if(n&&n.length>0){let i=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(!i.ok)throw new Error(`gitlab comment MR !${r}: ${i.status} ${await i.text()}`)}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()}`)}};function md(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"}}var wo=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(Es(e,r,"merge"))}async closePR(e,r,n){throw new Error(Es(e,r,"close"))}};function Es(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 We(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new ho(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new go(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new yo(e)}return new wo}function Lt(t,e,r,n){return[{path:"README.md",content:Rd(t,e)},{path:".gitignore",content:bd()},{path:"CLAUDE.md",content:$d(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:kd()},{path:"knowledge/README.md",content:vd()},{path:"knowledge/build.yaml",content:Sd()},{path:"actions/README.md",content:xd()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:wd()},{path:"adr/README.md",content:gd()},{path:"adr/0000-template.md",content:hd()},{path:"adr/INDEX.md",content:yd()},{path:Pe,content:Kr()}]}function gd(){return`# ADR \u2014 architecture decision records
35
+ `),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 closePR(e,r,n){if(n&&n.length>0){let i=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(!i.ok)throw new Error(`github comment PR #${r}: ${i.status} ${await i.text()}`)}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()}`)}},Oo=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 Rt(`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=ef(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 p=await a.json().catch(()=>null);s=p?.sha??p?.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 closePR(e,r,n){if(n&&n.length>0){let i=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(!i.ok)throw new Error(`gitlab comment MR !${r}: ${i.status} ${await i.text()}`)}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()}`)}};function ef(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"}}var Do=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(Qs(e,r,"merge"))}async closePR(e,r,n){throw new Error(Qs(e,r,"close"))}};function Qs(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 Je(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new No(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new _o(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new Oo(e)}return new Do}import{existsSync as st,readFileSync as Ft,readdirSync as ta}from"node:fs";import{join as Uo}from"node:path";import{simpleGit as ra}from"simple-git";import{parse as na}from"yaml";function oa(t){try{let e=ie(t,ln);if(!st(e))return null;let r=na(Ft(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!cn.test(n)?null:{prefix:n}}catch{return null}}function ia(t){return`# Built-in tracker configuration \u2014 shared by every team member.
36
+ # The issue-key prefix (<PREFIX>-<N>). Fixed at project init: changing it
37
+ # later would orphan existing tasks/<KEY>/ directories.
38
+ prefix: ${t}
39
+
40
+ # Statuses are the built-in default set for now:
41
+ # Backlog | To Do | In Progress | Review | Done | Rejected
42
+ # A configurable status set / pipeline mapping is a planned extension.
43
+ `}function Lo(t=0){return`${t}
44
+ `}function tf(t){return t==="depends_on"||t==="subtask"}function rf(t){let e;try{e=na(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=ns.includes(r.type)?r.type:an,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;tf(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 Bo(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(`
45
+ `)+`
46
+ `}function Ir(t,e){let r=ie(t,vr(e));return st(r)?rf(Ft(r,"utf-8")):null}function sa(t){let e=Uo(t,"tasks");if(!st(e))return[];let r=[];for(let n of ta(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=Ir(t,n.name);o&&r.push(o)}return r}function nf(t,e){let r=ie(t,`tasks/${e}/task.md`);if(!st(r))return;let n=Ft(r,"utf-8").split(`
47
+ `),o=n.indexOf("---");if(o<0)return;let i=n.slice(o+1),s=i.lastIndexOf("## Attachments");s>=0&&i.slice(s+1).every(p=>p.trim()===""||/^- \[[^\]]*\]\(attachments\/[^)]*\)$/.test(p.trim()))&&(i=i.slice(0,s));let a=i.join(`
48
+ `).trim();if(!(!a||a==="_(no description)_"))return a}function Cr(t,e,r={}){let n=r.withDescription?nf(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:of(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function of(t){return t.charAt(0).toUpperCase()+t.slice(1)}function sf(t){let e=ie(t,$r);if(!st(e))return 0;let r=Number.parseInt(Ft(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function af(t,e){let r=Uo(t,"tasks");if(!st(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of ta(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 cf(t,e){return Math.max(sf(t),af(t,e))+1}var ea=5;async function aa(t,e,r,n){return Po(t,()=>lf(t,e,r,n))}async function lf(t,e,r,n){if(!st(Uo(t,".git")))throw new Error(`context repo clone not found at ${t}`);await Tr(t);let o=null;for(let i=0;i<ea;i++){let s=cf(t,e),a=`${e}-${s}`,c=[...r(a),{path:$r,content:Lo(s)}];try{return await jo(t,c,n(a)),a}catch(l){if(o=l,await pf(t,n(a)),await Tr(t),uf(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${ea} attempts: ${o instanceof Error?o.message:String(o)}`)}function uf(t,e){for(let r of e){let n=ie(t,r.path);if(!st(n)||(r.encoding==="base64"?Ft(n).toString("base64"):Ft(n,"utf-8"))!==r.content)return!1}return!0}async function Tr(t){let e=ra(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 pf(t,e){let r=ra(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
49
+ `)[0]||!(await r.raw(["log","@{u}..HEAD","--pretty=%s"]).catch(()=>"")).trim().split(`
50
+ `).some(i=>i.trim()===e.split(`
51
+ `)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}function Ht(t,e,r,n){return[{path:"README.md",content:vf(t,e)},{path:".gitignore",content:hf()},{path:"CLAUDE.md",content:kf(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:yf()},{path:"knowledge/README.md",content:wf()},{path:"knowledge/build.yaml",content:$f()},{path:"actions/README.md",content:bf()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:gf()},{path:"adr/README.md",content:df()},{path:"adr/0000-template.md",content:ff()},{path:"adr/INDEX.md",content:mf()},{path:Ne,content:nn()},...t.trackerProvider==="internal"?[{path:ln,content:ia(t.youtrackProjectKey??br)},{path:$r,content:Lo()}]:[]]}function df(){return`# ADR \u2014 architecture decision records
33
52
 
34
53
  Accepted architectural decisions of this project \u2014 its **framework**. The
35
54
  agent reads this section (start with \`INDEX.md\`) at the beginning of every
@@ -57,7 +76,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
57
76
  canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
58
77
  is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
59
78
  open a PR to this repository.
60
- `}function hd(){return`# ADR-NNNN: <title>
79
+ `}function ff(){return`# ADR-NNNN: <title>
61
80
 
62
81
  - **Status:** accepted | superseded by ADR-NNNN
63
82
  - **Date:** YYYY-MM-DD
@@ -79,12 +98,12 @@ What becomes easier, what becomes harder, what future tasks must keep doing.
79
98
  ## Alternatives considered
80
99
 
81
100
  - **<alternative>** \u2014 why it was rejected.
82
- `}function yd(){return`# ADR index
101
+ `}function mf(){return`# ADR index
83
102
 
84
103
  <!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->
85
104
 
86
105
  (no accepted ADRs yet)
87
- `}function wd(){return`# Audit
106
+ `}function gf(){return`# Audit
88
107
 
89
108
  Pipeline event logs. Naming is per-writer: each codepipe
90
109
  project appends only to its own file \u2014
@@ -93,14 +112,14 @@ project appends only to its own file \u2014
93
112
 
94
113
  \u2014 so several team members' CLIs never contend on one file. Do not create a
95
114
  shared aggregate here.
96
- `}function Oe(t,e,r,n){return{projectYaml:Td(t,r,n),regimenYaml:Cd(t.automationLevel,e)}}function bd(){return`# codepipe project config is local to each member's workspace
115
+ `}function Le(t,e,r,n){let o=t.trackerProvider==="internal";return{projectYaml:o?xf(t):Sf(t,r,n),regimenYaml:Rf(t.automationLevel,o?!0:e,o)}}function hf(){return`# codepipe project config is local to each member's workspace
97
116
  project.yaml
98
117
  regimen.yaml
99
118
 
100
119
  # codepipe runtime
101
120
  session.log
102
121
  apply-queue.json
103
- `}function kd(){return`# Index prompt
122
+ `}function yf(){return`# Index prompt
104
123
 
105
124
  You are the **Indexer** agent on the CodePipe pipeline. Your one job is to build a
106
125
  navigation map of this project's repositories and save it to the Context Repo, so
@@ -157,7 +176,7 @@ current working directory; write nothing else under the Context Repo.
157
176
  Keep both durable and skimmable \u2014 they are read at the start of every future
158
177
  task. Prefer structure (headings, bullet lists) over prose. If a repository is
159
178
  empty or unavailable, say so briefly rather than inventing content.
160
- `}function $d(t){return`# Project context for the CodePipe agent
179
+ `}function kf(t){return`# Project context for the CodePipe agent
161
180
 
162
181
  Instructions for AI agents working on **${t.name}** tasks. Claude Code
163
182
  auto-loads this file when the Context Repo is mounted. Keep it short and
@@ -185,7 +204,7 @@ project's architectural invariants: read them at the start of a task and treat
185
204
  them as binding. New or changed decisions do **not** go here directly \u2014 during
186
205
  analysis you draft them as task artifacts, and they are promoted into \`adr/\`
187
206
  only after the analysis is approved.
188
- `}function vd(){return`# Knowledge
207
+ `}function wf(){return`# Knowledge
189
208
 
190
209
  Durable, reusable notes about this project \u2014 the CodePipe agent's long-lived
191
210
  **memory** across tasks. Architectural decisions, domain rules,
@@ -202,7 +221,7 @@ Keep each note in its own file \u2014 never grow one shared aggregate \u2014 so
202
221
  concurrent commits touch different files and rebase cleanly. \`INDEX.md\` is
203
222
  REGENERATED from the entries by the index job: don't hand-edit it, and treat
204
223
  any merge conflict in it as noise (either side converges on the next run).
205
- `}function xd(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
224
+ `}function bf(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
206
225
 
207
226
  One \`<id>.yml\` per action. Every file here appears as a button on the
208
227
  project's **RUN** tab; an action with \`params\` opens a small wizard first.
@@ -241,7 +260,7 @@ steps:
241
260
  Parameter values are passed to the commands **only as env vars** \u2014 reference
242
261
  them as \`$INPUT_<NAME>\` in \`run\`; they are never substituted into the
243
262
  command text itself.
244
- `}function Sd(){return`# BUILD phase config. Discovered & maintained by the agent.
263
+ `}function $f(){return`# BUILD phase config. Discovered & maintained by the agent.
245
264
  # Steps run in a rootless Podman container in the SANDBOX, before the PR.
246
265
  # Success = every step exits 0. Credentials are NOT available inside the container.
247
266
  #
@@ -257,7 +276,7 @@ command text itself.
257
276
  # - name: test
258
277
  # run: npm test
259
278
  # timeout_sec: 600 # per-step timeout (optional, default 600)
260
- `}function Rd(t,e){return`# ${e.name}
279
+ `}function vf(t,e){return`# ${e.name}
261
280
 
262
281
  Context Repo for the **${t.name}** project (CodePipe).
263
282
 
@@ -283,7 +302,38 @@ PRs to this repository (and the agent also writes to \`knowledge/\` and
283
302
  pipeline \u2014 don't edit them by hand.
284
303
 
285
304
  Automation level: **${t.automationLevel}**.
286
- `}function Td(t,e,r){let n=e?`
305
+ `}function xf(t){return`# Project description for CodePipe.
306
+ id: ${t.projectId}
307
+ name: ${t.name}
308
+
309
+ adapters:
310
+ # Built-in tracker: task state lives in this project's Context Repo
311
+ # (tasks/<KEY>/issue.yaml; the shared settings \u2014 tracker/config.yaml).
312
+ tracker: internal
313
+
314
+ # How approved changes reach the project repos:
315
+ # auto \u2014 HUB dispatches the apply plan; CLI pushes a branch and opens a PR.
316
+ # local \u2014 HUB waits; you apply the patch into your local checkout via the
317
+ # CLI REPL (/apply or /unstash) and commit/push yourself.
318
+ apply:
319
+ mode: auto
320
+
321
+ # Task-branch name template. <TASK_ID> \u2192 lower-cased task key (e.g.
322
+ # codepipe/task-1). Also editable from the dashboard: project card \u2192 Settings \u2192
323
+ # Branch (must keep the <TASK_ID> placeholder).
324
+ branch:
325
+ pattern: codepipe/<TASK_ID>
326
+
327
+ repos:
328
+ ${ca(t)}
329
+ `}function ca(t){return t.repos.length===0?` [] # add repos here
330
+ `:t.repos.map(e=>` - name: ${e.name}
331
+ host: ${e.host}
332
+ owner: ${e.owner}
333
+ repo: ${e.repoName}
334
+ mount_as: ${e.mountAs??e.name}`+(e.defaultBranch?`
335
+ default_branch: ${e.defaultBranch}`:"")).join(`
336
+ `)}function Sf(t,e,r){let n=e?`
287
337
  tracker_url: ${e}`:`
288
338
  # tracker_url: https://your.youtrack.cloud`,o=r?`require_assignee: true
289
339
  assignee: ${r}`:`require_assignee: false
@@ -325,14 +375,7 @@ Automation level: **${t.automationLevel}**.
325
375
  # non-empty assignee. assignee only takes effect when require_assignee=true.
326
376
  ${o}`:` # project_key: \u2026
327
377
  # tracker_url: https://your.youtrack.cloud
328
- poll_interval_sec: 60`,s=t.repos.length===0?` [] # add repos here
329
- `:t.repos.map(a=>` - name: ${a.name}
330
- host: ${a.host}
331
- owner: ${a.owner}
332
- repo: ${a.repoName}
333
- mount_as: ${a.mountAs??a.name}`+(a.defaultBranch?`
334
- default_branch: ${a.defaultBranch}`:"")).join(`
335
- `);return`# Project description for CodePipe.
378
+ poll_interval_sec: 60`,s=ca(t);return`# Project description for CodePipe.
336
379
  id: ${t.projectId}
337
380
  name: ${t.name}
338
381
 
@@ -363,21 +406,23 @@ branch:
363
406
 
364
407
  repos:
365
408
  ${s}
366
- `}function Cd(t,e){let r=t==="full",n=e?"true":"false";return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
409
+ `}function Rf(t,e,r=!1){let n=t==="full",o=e?"true":"false";return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
367
410
  automation:
368
411
  level: ${t}
369
412
 
370
413
  youtrack:
371
- # Master switch. With enabled=false CodePipe never writes to YouTrack,
414
+ ${r?` # The built-in tracker is CodePipe's own \u2014 these switches stay on (there
415
+ # is no external system to protect with a read-only mode). The block keeps
416
+ # the same keys as a YouTrack project so the settings machinery is shared.`:` # Master switch. With enabled=false CodePipe never writes to YouTrack,
372
417
  # regardless of the per-action flags below.
373
418
  # These flags are set from a dedicated 'codepipe init' question and do
374
- # NOT depend on automation.level \u2014 the two are orthogonal axes (writes vs gates).
419
+ # NOT depend on automation.level \u2014 the two are orthogonal axes (writes vs gates).`}
375
420
  writes:
376
- enabled: ${n}
377
- status_changes: ${n}
378
- pr_comment: ${n}
421
+ enabled: ${o}
422
+ status_changes: ${o}
423
+ pr_comment: ${o}
379
424
  # Mirror dashboard comments back into YouTrack. Off without enabled.
380
- dashboard_mirror: ${n}
425
+ dashboard_mirror: ${o}
381
426
  # YT column (Stage) for new drafts published from PLAN.
382
427
  # Backlog by default \u2192 the task shows up in the TODO section, not straight in WORK.
383
428
  draft_target_status: Backlog
@@ -392,10 +437,10 @@ gates:
392
437
  # 'assisted' requires a manual Run/Approve at each. Names and modes mirror
393
438
  # docs/PIPELINE.md so a future per-gate parser stays config-compatible.
394
439
  # Modes: always | auto_below_hours | never.
395
- G1_estimate: { mode: ${r?"never":"always"} }
396
- G2_solution: { mode: ${r?"never":"always"} }
397
- G3_implementation: { mode: ${r?"never":"always"} }
398
- G4_apply: { mode: ${r?"never":"always"} }
440
+ G1_estimate: { mode: ${n?"never":"always"} }
441
+ G2_solution: { mode: ${n?"never":"always"} }
442
+ G3_implementation: { mode: ${n?"never":"always"} }
443
+ G4_apply: { mode: ${n?"never":"always"} }
399
444
  # The first ACTUALLY consumed key of the gates block. When true, a task from
400
445
  # Develop parks in the AWAITING_APPROVAL phase (WORK section, "awaiting
401
446
  # approval") and doesn't start implementation until a manual Approve /
@@ -476,35 +521,38 @@ llm:
476
521
  # # the previous task's branch (auto-merge without reworking the
477
522
  # # tail of the chain).
478
523
  # mode: parallel
479
- `}function Ad(t){return`codepipe/context-migration-v${t}`}function _d(t){let e=vi(t.templateVersion),r=[`CodePipe context format migration: **v${t.templateVersion} \u2192 v${t.currentVersion}**.`,"","Additive only \u2014 this PR creates files your context is missing and updates",`the \`${Pe}\` stamp (renamed from \`${mr}\``,"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(`
480
- `)}async function Os(t,e,r,n){let o=bo(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=an(t,e);if(!i.outdated)return i;let s=Ad(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 Nd(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=We(c),p=await l.findOpenPrByBranch?.(c,s)??null;if(p)return n.info(`[ctx] migration PR already open: ${p.url}`),{...i,migrationPrUrl:p.url};let d=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:_d(i)});return n.info(`[ctx] migration PR opened: ${d.url}`),{...i,migrationPrUrl:d.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 Nd(t,e,r,n,o,i,s){let a=bo(t),c=jd(ln(Ed(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",o,c,`origin/${i}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},p={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},d=new Map(Lt(l,p).map(y=>[y.path,y.content])),u=0;for(let y of n.missingPaths){if(y===Pe)continue;let w=d.get(y);if(w==null){s.warn(`[ctx] migration: no template for ${y} \u2014 skipped`);continue}let k=ln(c,y);As(k)||(Id(Pd(k),{recursive:!0}),Ns(k,w),u++)}Ns(ln(c,Pe),Kr(n.currentVersion)),u++;let m=ln(c,mr);As(m)&&(_s(m,{force:!0}),u++);let f=bo(c);await f.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await f.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await f.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${u} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),_s(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{existsSync as Od,readFileSync as Ud,writeFileSync as Dd}from"node:fs";import{homedir as Ld}from"node:os";import{join as Us}from"node:path";import{parseDocument as Bd}from"yaml";function Md(t){let e={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(e.default_branch=t.defaultBranch),e}function Gd(t,e){let r=Bd(t);return r.set("repos",e.map(Md)),r.toString()}function Fd(t,e){let r=[Us(Ld(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(Us(e,"project.yaml")),r}function wr(t,e,r){let n=[],o=[];for(let i of Fd(t,r))if(Od(i))try{let s=Ud(i,"utf-8"),a=Gd(s,e);a!==s&&(Dd(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}import{homedir as Hd}from"node:os";import{existsSync as Kd,mkdirSync as Wd}from"node:fs";import{join as ko}from"node:path";import{simpleGit as Bs}from"simple-git";var Ds=t=>console.log(t);function Ls(t){Ds=t}function br(t,e="info"){Ds(t,e)}function ke(t,e,r){let n=r??ko(Hd(),".codepipe","repos");return ko(n,t,e)}async function $r(t,e,r={}){let n=ke(t,e.name,r.baseDir),o=r.cloneUrlOverride??$o(e);if(!Kd(ko(n,".git"))){Wd(n,{recursive:!0});let a=Bs();br(`[git] clone ${o} \u2192 ${n}`);try{await a.clone(o,n)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${o}
481
- ${l.trim()}`)}}let i=Bs(n);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
482
- ${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function kr(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var Ms=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function un(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&&br(`[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 kr(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await kr(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([...Ms,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function Gs(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await kr(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await kr(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 Fs(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:p,force:d}=r,u=await Gs(t,i,()=>un(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));d&&await t.raw(["branch","-D",a]).catch(()=>{});let m=`origin/${c}`;if(await kr(t,m)||(m=`origin/${p??c}`),(await t.revparse([m])).trim()===s)await t.raw(["branch","-f",a,u]),await t.checkout(a);else{await t.checkout(["-B",a,m]);try{await t.raw([...Ms,"cherry-pick",u])}catch(k){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let h=k instanceof Error?k.message:String(k);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
483
- ${h.trim()}`)}}let y=(await t.revparse(["HEAD"])).trim(),w=d?["--force-with-lease","-u","origin",a]:["-u","origin",a];return await t.push(w),await t.push([n,"--delete",o]).catch(()=>{}),{commit:y}}async function Hs(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,p=await Gs(t,i,()=>un(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:c}));return await t.raw(["branch","-f",a,p]),l&&await t.push(["--force-with-lease","-u","origin",a]),{commit:p,pushed:l}}async function Ks(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 $o(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`}import{createCipheriv as qd,createDecipheriv as Yd,createHash as Vd,createPrivateKey as Jd,createPublicKey as vo,diffieHellman as Ws,generateKeyPairSync as qs,hkdfSync as Ys,randomBytes as zd}from"node:crypto";var Vs=Buffer.from("devpipe-sealedbox-v1","utf-8");function pn(){let{publicKey:t,privateKey:e}=qs("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function ue(t){let e=Buffer.from(t,"base64");return(Vd("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function qe(t,e){let r=vo({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=qs("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=Ws({privateKey:o,publicKey:r}),c=Buffer.from(Ys("sha256",a,Buffer.concat([i,s]),Vs,32)),l=zd(12),p=qd("aes-256-gcm",c,l),d=typeof e=="string"?Buffer.from(e,"utf-8"):e,u=Buffer.concat([p.update(d),p.final()]),m=p.getAuthTag(),f={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:m.toString("base64"),ct:u.toString("base64")};return Buffer.from(JSON.stringify(f),"utf-8").toString("base64")}function Bt(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=Jd({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=vo({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=vo(n).export({type:"spki",format:"der"}),a=Ws({privateKey:n,publicKey:o}),c=Buffer.from(Ys("sha256",a,Buffer.concat([i,s]),Vs,32)),l=Yd("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()])}function Xd(t,e){let r={};t.github?.token&&(r.github={token:t.github.token}),t.bitbucket?.apiToken&&(r.bitbucket={apiToken:t.bitbucket.apiToken}),t.gitlab?.token&&(r.gitlab={token:t.gitlab.token});let n=e??t.claude?.oauthToken;return n&&(r.claudeOauthToken=n),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),r}function Js(t,e,r,n){let o=Xd(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=Zr(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=qe(a.publicKey,i)}catch(p){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${p instanceof Error?p.message:String(p)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}import{X509Certificate as Qs}from"node:crypto";import{readFileSync as Qd}from"node:fs";import rt from"node:tls";var Zs=typeof rt.getCACertificates=="function"&&typeof rt.setDefaultCACertificates=="function",zs=!1,Xs=new Map,ea=t=>console.warn(t);function Zd(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function ta(t=ea){if(zs)return;zs=!0;let e=F("EXTRA_CA_FILE");if(!(!e||!Zs))try{let r=Zd(Qd(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}rt.setDefaultCACertificates([...rt.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 ra(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 ef(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
484
- `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function tf(t,e,r){return new Promise((n,o)=>{let i=rt.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 Qs(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function xo(t,e,r){return new Promise(n=>{let o=rt.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 rf(t){try{let e=await fetch(t);return e.ok?new Qs(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function na(t,e=443,r=ea){let n=`${t}:${e}`,o=Xs.get(n);if(o)return o;let i=nf(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Xs.set(n,i),i}async function nf(t,e,r){if(!Zs)return!1;let n=8e3;if(await xo(t,e,n))return!0;let o=await tf(t,e,n),i=rt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=ef(o);if(!c)break;let l=await rf(c);if(!l)break;if(s.push(l.toString()),rt.setDefaultCACertificates([...i,...s]),await xo(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 xo(t,e,n)}function Ue(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function $e(t,e,r){ta();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(ra(s)&&await na(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}var oa=t=>new Promise(e=>setTimeout(e,t));function of(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function sf(){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 So(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=sf(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await $e(t,r,n)}catch(p){a=new Error(`${e}: ${p instanceof Error?p.message:String(p)}`)}if(l){if(l.ok)return l;let p=await l.text();if(c<o&&of(l.status,p)){await oa(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${p}`)}if(c<o){await oa(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function nt(t){let e;try{e=await $e(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 aa(t){try{let e=await $e(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}var vr="Stage",ia=new Map;async function af(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=ia.get(o);if(i)return i;let s=await $e(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(p=>p.name===n);if(!c)throw new Error(`yt: issue ${e} has no ${n} custom field`);let l=c.projectCustomField.bundle.values.find(p=>p.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${n} bundle for ${e}`);return ia.set(o,l.id),l.id}async function ca(t,e,r,n=vr){let o=await af(t,e,r,n);await So(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 la(t,e,r){return await(await So(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function ua(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await So(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}var sa=new Map;async function pa(t,e){let r=sa.get(e);if(r)return r;let n=await $e(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 sa.set(e,i.id),i.id}async function da(t,e,r,n,o,i=vr){let s=await pa(t,e),a=await $e(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 fa(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await $e(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()}`)}var ma="attachments(id,name,url,size,mimeType)",cf="links(direction,linkType(name),issues(idReadable))",ga=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${ma},${cf}`,lf=`id,text,created,author(login),${ma}`;function ha(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 ya(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 dn(t,e){let r=e.stageField??vr,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=${ga}&$top=200`,s=await $e(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>ba(c,r))}async function fn(t,e,r=vr){let n=`/api/issues/${encodeURIComponent(e)}?fields=${ga}`,o=await $e(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return ba(await o.json(),r)}async function wa(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${lf}&$top=500`,o=await $e(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=ha(s.attachments);return c&&(a.attachments=c),a})}function uf(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 ba(t,e=vr){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=ha(t.attachments);a&&(s.attachments=a);let c=uf(t.links);return c&&(s.links=c),s}async function ka(t,e){let r=await pf(t,e);return r.length>0?r:df(t,e)}async function pf(t,e){let r=await pa(t,e),n=await $e(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:$a(s.bundle)});return i}async function df(t,e){let r=`project: ${e}`,n=await $e(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:$a(s.projectCustomField?.bundle)});return i}function $a(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}function Te(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function va(t,e){let r=D(t),n=[],o=[],i=()=>Date.now();if(r?.youtrack?.url&&r.youtrack.token)try{let c=await nt({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:Te(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:Te(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 Ze(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"github",ok:!1,detail:Te(c)}),o.push({kind:"github",present:!0,ok:!1,detail:Te(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 et(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){n.push({name:"bitbucket",ok:!1,detail:Te(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:Te(c),checkedAt:i()})}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await tt(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"gitlab",ok:!1,detail:Te(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:Te(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 p of e?.repos??[])if(p.host==="github")try{await cn(c,p.owner,p.repoName),n.push({name:`repo:${p.name}`,ok:!0})}catch(d){n.push({name:`repo:${p.name}`,ok:!1,detail:Te(d)})}let l=e?.contextRepo;if(l?.host==="github")try{await cn(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(p){n.push({name:"context-repo",ok:!1,detail:Te(p)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await cn(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){o.push({kind:"contextWrite",present:!0,ok:!1,detail:Te(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=Pt(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 Ro(a);if(c==="invalid"){let l="Claude token rejected (401) \u2014 refresh via `claude setup-token`";n.push({name:"claude",ok:!1,detail:l}),o.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function Ro(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});return n.status===200?"valid":n.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}function xr(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 Sr(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 Rr(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 To(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 xa(t,e=process.env){return To(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>xr(t,e),e)}function Sa(t,e=process.env){return To(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>Sr(t,e),e)}function Ra(t,e=process.env){return To(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${wt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>Rr(t,e),e)}function Ta(t){let e=D(t);if(!e)return null;if(!e.sealKey){let r=pn();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},J(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:ue(e.sealKey.publicKey)}}async function Ca(t,e,r,n){let o;try{o=JSON.parse(Bt(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=D(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 Ze(o.token);return i.github={token:o.token},Mt(i,()=>{process.env.GH_TOKEN=o.token,xa(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await tt(o.token);return i.gitlab={token:o.token},Mt(i,()=>{process.env.GITLAB_TOKEN=o.token,Sa(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 et(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},Mt(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,Ra(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 nt({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},Mt(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 Ro(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},Mt(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},Mt(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 Mt(t,e){J(t),e()}import{spawn as ff}from"node:child_process";var mf=124,Ia=16*1024,ja=4e3;function gf(t,e,r,n,o,i){let s={...t},a=(c,l)=>{ze(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 Ea(t){let{def:e,onEvent:r}=t,n=gf(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
485
- `,o.length>Ia&&(o=o.slice(o.length-Ia))},s=(a,c)=>{let l=c.length>ja?c.slice(0,ja)+"\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 p=await hf(c.run,c.timeout_sec,t.cwd,n,s);if(p!==0)return i(`[${l}] exited with code ${p}`),r({ts:Date.now(),kind:"result",status:"failed",exitCode:p,failedStep:l}),{status:"failed",exitCode:p,failedStep:l,logTail:o}}return r({ts:Date.now(),kind:"result",status:"succeeded",exitCode:0}),{status:"succeeded",exitCode:0,logTail:o}}function hf(t,e,r,n,o){return new Promise(i=>{let s=ff("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??Ii)*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 p=m=>{let f="";return{data:y=>{f+=y.toString("utf-8");let w;for(;(w=f.indexOf(`
486
- `))!==-1;)o(m,f.slice(0,w).replace(/\r$/,"")),f=f.slice(w+1)},flush:()=>{f.length>0&&o(m,f.replace(/\r$/,"")),f=""}}},d=p("stdout"),u=p("stderr");s.stdout?.on("data",d.data),s.stderr?.on("data",u.data),s.on("error",m=>{clearTimeout(l),o("stderr",`spawn failed: ${m.message}`),i(127)}),s.on("close",(m,f)=>{clearTimeout(l),d.flush(),u.flush(),i(a?mf:m??(f?1:0))})})}import{existsSync as yf,readFileSync as wf,statSync as Pa}from"node:fs";var Aa=2*1024*1024;function bf(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function _a(t,e){let r=Ke(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!yf(r)||!Pa(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=Pa(r);if(n>Aa)throw new Error(`file too large: ${e} is ${n} bytes (limit ${Aa})`);let o=wf(r);return bf(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}import{existsSync as kf,readFileSync as $f,writeFileSync as vf}from"node:fs";import{join as xf}from"node:path";import{parseDocument as Sf}from"yaml";async function Na(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=Ni(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=xf(t,o);if(!kf(s))throw new Error(`${o} not found in context repo (${t})`);let a=Sf($f(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);vf(s,a.toString()),n.push(o)}return{files:n}}import{existsSync as Rf,readFileSync as Tf,writeFileSync as Cf}from"node:fs";import{join as If}from"node:path";import{isMap as Oa,parseDocument as jf}from"yaml";async function Ua(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||!Oi(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=If(t,"project.yaml");if(!Rf(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=jf(Tf(o,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>Oa(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!Oa(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),Cf(o,i.toString()),{repoName:r,defaultBranch:n}}import{existsSync as Co,readFileSync as Io,writeFileSync as Ef}from"node:fs";import{join as mn}from"node:path";import{parseDocument as jo}from"yaml";async function Da(t,e){let r=[];if(e.stageField!==void 0||e.sourceColumns!==void 0||e.rejectColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0||e.backlogScope!==void 0){let i=mn(t,"project.yaml");if(!Co(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=jo(Io(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.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=mn(t,"regimen.yaml");if(!Co(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=jo(Io(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)Ef(mn(t,i.path),i.content);return{files:r.map(i=>i.path)}}function gn(t){if(!t)return"Stage";try{let e=mn(t,"project.yaml");if(!Co(e))return"Stage";let n=jo(Io(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}import{existsSync as La,readFileSync as Pf,readdirSync as Af}from"node:fs";function _f(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=Df(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:Nf(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:Uf(Of(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 hn(t,e,r){if(r.length===0)return;let n=_f(t,e,r),o=r.map(i=>i.issue.key);await Dt(t,n,`sync(${o.join(", ")}): task data`)}function Nf(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(`
487
- `)}function Of(t,e,r){let n=new Map,o=Ke(t,`tasks/${e}/comments.jsonl`);if(La(o))for(let i of Pf(o,"utf-8").split(`
488
- `)){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){let s={id:i.id,author:i.author,origin:"youtrack",body:i.body,createdAt:new Date(i.createdAt).toISOString()},a=Yr(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function Uf(t){return t.map(e=>JSON.stringify(e)).join(`
524
+ `}function Pf(t){return`codepipe/context-migration-v${t}`}function jf(t){let e=Hi(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 \`${Ne}\` stamp (renamed from \`${wr}\``,"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(`
525
+ `)}async function da(t,e,r,n){let o=Mo(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Sn(t,e);if(!i.outdated)return i;let s=Pf(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 Af(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=Je(c),p=await l.findOpenPrByBranch?.(c,s)??null;if(p)return n.info(`[ctx] migration PR already open: ${p.url}`),{...i,migrationPrUrl:p.url};let d=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:jf(i)});return n.info(`[ctx] migration PR opened: ${d.url}`),{...i,migrationPrUrl:d.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 Af(t,e,r,n,o,i,s){let a=Mo(t),c=If(Tn(Cf(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",o,c,`origin/${i}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},p={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},d=new Map(Ht(l,p).map(y=>[y.path,y.content])),u=0;for(let y of n.missingPaths){if(y===Ne)continue;let k=d.get(y);if(k==null){s.warn(`[ctx] migration: no template for ${y} \u2014 skipped`);continue}let $=Tn(c,y);la($)||(Tf(Ef($),{recursive:!0}),pa($,k),u++)}pa(Tn(c,Ne),nn(n.currentVersion)),u++;let m=Tn(c,wr);la(m)&&(ua(m,{force:!0}),u++);let f=Mo(c);await f.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await f.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await f.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${u} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),ua(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{existsSync as _f,readFileSync as Nf,writeFileSync as Of}from"node:fs";import{homedir as Df}from"node:os";import{join as fa}from"node:path";import{parseDocument as Uf}from"yaml";function Lf(t){let e={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(e.default_branch=t.defaultBranch),e}function Bf(t,e){let r=Uf(t);return r.set("repos",e.map(Lf)),r.toString()}function Mf(t,e){let r=[fa(Df(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(fa(e,"project.yaml")),r}function Er(t,e,r){let n=[],o=[];for(let i of Mf(t,r))if(_f(i))try{let s=Nf(i,"utf-8"),a=Bf(s,e);a!==s&&(Of(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}import{homedir as Gf}from"node:os";import{existsSync as Ff,mkdirSync as Hf}from"node:fs";import{join as Go}from"node:path";import{simpleGit as ha}from"simple-git";var ma=t=>console.log(t);function ga(t){ma=t}function Pr(t,e="info"){ma(t,e)}function Se(t,e,r){let n=r??Go(Gf(),".codepipe","repos");return Go(n,t,e)}async function Ar(t,e,r={}){let n=Se(t,e.name,r.baseDir),o=r.cloneUrlOverride??Fo(e);if(!Ff(Go(n,".git"))){Hf(n,{recursive:!0});let a=ha();Pr(`[git] clone ${o} \u2192 ${n}`);try{await a.clone(o,n)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${o}
526
+ ${l.trim()}`)}}let i=ha(n);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
527
+ ${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function jr(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var ya=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function In(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&&Pr(`[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 jr(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await jr(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([...ya,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function ka(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await jr(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await jr(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 wa(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:p,force:d}=r,u=await ka(t,i,()=>In(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));d&&await t.raw(["branch","-D",a]).catch(()=>{});let m=`origin/${c}`;if(await jr(t,m)||(m=`origin/${p??c}`),(await t.revparse([m])).trim()===s)await t.raw(["branch","-f",a,u]),await t.checkout(a);else{await t.checkout(["-B",a,m]);try{await t.raw([...ya,"cherry-pick",u])}catch($){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let h=$ instanceof Error?$.message:String($);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
528
+ ${h.trim()}`)}}let y=(await t.revparse(["HEAD"])).trim(),k=d?["--force-with-lease","-u","origin",a]:["-u","origin",a];return await t.push(k),await t.push([n,"--delete",o]).catch(()=>{}),{commit:y}}async function ba(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,p=await ka(t,i,()=>In(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:c}));return await t.raw(["branch","-f",a,p]),l&&await t.push(["--force-with-lease","-u","origin",a]),{commit:p,pushed:l}}async function $a(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 Fo(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}import{createCipheriv as Kf,createDecipheriv as Wf,createHash as Yf,createPrivateKey as qf,createPublicKey as Ho,diffieHellman as va,generateKeyPairSync as xa,hkdfSync as Sa,randomBytes as Vf}from"node:crypto";var Ra=Buffer.from("devpipe-sealedbox-v1","utf-8");function Cn(){let{publicKey:t,privateKey:e}=xa("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function de(t){let e=Buffer.from(t,"base64");return(Yf("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function ze(t,e){let r=Ho({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=xa("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=va({privateKey:o,publicKey:r}),c=Buffer.from(Sa("sha256",a,Buffer.concat([i,s]),Ra,32)),l=Vf(12),p=Kf("aes-256-gcm",c,l),d=typeof e=="string"?Buffer.from(e,"utf-8"):e,u=Buffer.concat([p.update(d),p.final()]),m=p.getAuthTag(),f={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:m.toString("base64"),ct:u.toString("base64")};return Buffer.from(JSON.stringify(f),"utf-8").toString("base64")}function Kt(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=qf({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=Ho({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=Ho(n).export({type:"spki",format:"der"}),a=va({privateKey:n,publicKey:o}),c=Buffer.from(Sa("sha256",a,Buffer.concat([i,s]),Ra,32)),l=Wf("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()])}function Jf(t,e){let r={};t.github?.token&&(r.github={token:t.github.token}),t.bitbucket?.apiToken&&(r.bitbucket={apiToken:t.bitbucket.apiToken}),t.gitlab?.token&&(r.gitlab={token:t.gitlab.token});let n=e??t.claude?.oauthToken;return n&&(r.claudeOauthToken=n),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),r}function Ta(t,e,r,n){let o=Jf(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=gn(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=ze(a.publicKey,i)}catch(p){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${p instanceof Error?p.message:String(p)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}import{X509Certificate as Ea}from"node:crypto";import{readFileSync as zf}from"node:fs";import at from"node:tls";var Pa=typeof at.getCACertificates=="function"&&typeof at.setDefaultCACertificates=="function",Ia=!1,Ca=new Map,ja=t=>console.warn(t);function Xf(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function Aa(t=ja){if(Ia)return;Ia=!0;let e=F("EXTRA_CA_FILE");if(!(!e||!Pa))try{let r=Xf(zf(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}at.setDefaultCACertificates([...at.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 _a(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 Qf(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
529
+ `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function Zf(t,e,r){return new Promise((n,o)=>{let i=at.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 Ea(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function Ko(t,e,r){return new Promise(n=>{let o=at.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 em(t){try{let e=await fetch(t);return e.ok?new Ea(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Na(t,e=443,r=ja){let n=`${t}:${e}`,o=Ca.get(n);if(o)return o;let i=tm(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Ca.set(n,i),i}async function tm(t,e,r){if(!Pa)return!1;let n=8e3;if(await Ko(t,e,n))return!0;let o=await Zf(t,e,n),i=at.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=Qf(o);if(!c)break;let l=await em(c);if(!l)break;if(s.push(l.toString()),at.setDefaultCACertificates([...i,...s]),await Ko(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 Ko(t,e,n)}function La(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function Re(t,e,r){Aa();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(_a(s)&&await Na(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}var Oa=t=>new Promise(e=>setTimeout(e,t));function rm(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function nm(){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 Wo(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=nm(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await Re(t,r,n)}catch(p){a=new Error(`${e}: ${p instanceof Error?p.message:String(p)}`)}if(l){if(l.ok)return l;let p=await l.text();if(c<o&&rm(l.status,p)){await Oa(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${p}`)}if(c<o){await Oa(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function ct(t){let e;try{e=await Re(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 Ba(t){try{let e=await Re(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}var _r="Stage",Da=new Map;async function om(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=Da.get(o);if(i)return i;let s=await Re(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(p=>p.name===n);if(!c)throw new Error(`yt: issue ${e} has no ${n} custom field`);let l=c.projectCustomField.bundle.values.find(p=>p.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${n} bundle for ${e}`);return Da.set(o,l.id),l.id}async function Ma(t,e,r,n=_r){let o=await om(t,e,r,n);await Wo(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 Ga(t,e,r){return await(await Wo(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function Fa(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await Wo(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}var Ua=new Map;async function Ha(t,e){let r=Ua.get(e);if(r)return r;let n=await Re(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 Ua.set(e,i.id),i.id}async function Ka(t,e,r,n,o,i=_r){let s=await Ha(t,e),a=await Re(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 Wa(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await Re(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()}`)}var Ya="attachments(id,name,url,size,mimeType)",im="links(direction,linkType(name),issues(idReadable))",qa=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Ya},${im}`,sm=`id,text,created,author(login),${Ya}`;function Va(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 Ja(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 za(t,e){let r=e.stageField??_r,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=${qa}&$top=200`,s=await Re(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>Za(c,r))}async function Xa(t,e,r=_r){let n=`/api/issues/${encodeURIComponent(e)}?fields=${qa}`,o=await Re(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Za(await o.json(),r)}async function Qa(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${sm}&$top=500`,o=await Re(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=Va(s.attachments);return c&&(a.attachments=c),a})}function am(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 Za(t,e=_r){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=Va(t.attachments);a&&(s.attachments=a);let c=am(t.links);return c&&(s.links=c),s}async function ec(t,e){let r=await cm(t,e);return r.length>0?r:lm(t,e)}async function cm(t,e){let r=await Ha(t,e),n=await Re(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:tc(s.bundle)});return i}async function lm(t,e){let r=`project: ${e}`,n=await Re(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:tc(s.projectCustomField?.bundle)});return i}function tc(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}function Ee(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function rc(t,e){let r=L(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 ct({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:Ee(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:Ee(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 nt(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"github",ok:!1,detail:Ee(c)}),o.push({kind:"github",present:!0,ok:!1,detail:Ee(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 ot(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){n.push({name:"bitbucket",ok:!1,detail:Ee(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:Ee(c),checkedAt:i()})}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await it(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"gitlab",ok:!1,detail:Ee(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:Ee(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 p of e?.repos??[])if(p.host==="github")try{await Rn(c,p.owner,p.repoName),n.push({name:`repo:${p.name}`,ok:!0})}catch(d){n.push({name:`repo:${p.name}`,ok:!1,detail:Ee(d)})}let l=e?.contextRepo;if(l?.host==="github")try{await Rn(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(p){n.push({name:"context-repo",ok:!1,detail:Ee(p)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Rn(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){o.push({kind:"contextWrite",present:!0,ok:!1,detail:Ee(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=Dt(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 Yo(a);if(c==="invalid"){let l="Claude token rejected (401) \u2014 refresh via `claude setup-token`";n.push({name:"claude",ok:!1,detail:l}),o.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function Yo(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});return n.status===200?"valid":n.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}function Nr(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 Or(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 Dr(t,e=process.env){if(!t)return!1;let r=`https://${vt}:${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 qo(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 nc(t,e=process.env){return qo(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>Nr(t,e),e)}function oc(t,e=process.env){return qo(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>Or(t,e),e)}function ic(t,e=process.env){return qo(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${vt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>Dr(t,e),e)}function sc(t){let e=L(t);if(!e)return null;if(!e.sealKey){let r=Cn();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},z(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:de(e.sealKey.publicKey)}}async function ac(t,e,r,n){let o;try{o=JSON.parse(Kt(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=L(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 nt(o.token);return i.github={token:o.token},Wt(i,()=>{process.env.GH_TOKEN=o.token,nc(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await it(o.token);return i.gitlab={token:o.token},Wt(i,()=>{process.env.GITLAB_TOKEN=o.token,oc(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 ot(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},Wt(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,ic(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 ct({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},Wt(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 Yo(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},Wt(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},Wt(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 Wt(t,e){z(t),e()}import{spawn as um}from"node:child_process";var pm=124,cc=16*1024,lc=4e3;function dm(t,e,r,n,o,i){let s={...t},a=(c,l)=>{et(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 uc(t){let{def:e,onEvent:r}=t,n=dm(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
530
+ `,o.length>cc&&(o=o.slice(o.length-cc))},s=(a,c)=>{let l=c.length>lc?c.slice(0,lc)+"\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 p=await fm(c.run,c.timeout_sec,t.cwd,n,s);if(p!==0)return i(`[${l}] exited with code ${p}`),r({ts:Date.now(),kind:"result",status:"failed",exitCode:p,failedStep:l}),{status:"failed",exitCode:p,failedStep:l,logTail:o}}return r({ts:Date.now(),kind:"result",status:"succeeded",exitCode:0}),{status:"succeeded",exitCode:0,logTail:o}}function fm(t,e,r,n,o){return new Promise(i=>{let s=um("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??Ji)*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 p=m=>{let f="";return{data:y=>{f+=y.toString("utf-8");let k;for(;(k=f.indexOf(`
531
+ `))!==-1;)o(m,f.slice(0,k).replace(/\r$/,"")),f=f.slice(k+1)},flush:()=>{f.length>0&&o(m,f.replace(/\r$/,"")),f=""}}},d=p("stdout"),u=p("stderr");s.stdout?.on("data",d.data),s.stderr?.on("data",u.data),s.on("error",m=>{clearTimeout(l),o("stderr",`spawn failed: ${m.message}`),i(127)}),s.on("close",(m,f)=>{clearTimeout(l),d.flush(),u.flush(),i(a?pm:m??(f?1:0))})})}import{existsSync as mm,readFileSync as gm,statSync as pc}from"node:fs";var dc=2*1024*1024;function hm(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function fc(t,e){let r=ie(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!mm(r)||!pc(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=pc(r);if(n>dc)throw new Error(`file too large: ${e} is ${n} bytes (limit ${dc})`);let o=gm(r);return hm(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}import{existsSync as ym,readFileSync as km,writeFileSync as wm}from"node:fs";import{join as bm}from"node:path";import{parseDocument as $m}from"yaml";async function mc(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=ts(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=bm(t,o);if(!ym(s))throw new Error(`${o} not found in context repo (${t})`);let a=$m(km(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);wm(s,a.toString()),n.push(o)}return{files:n}}import{existsSync as vm,readFileSync as xm,writeFileSync as Sm}from"node:fs";import{join as Rm}from"node:path";import{isMap as gc,parseDocument as Tm}from"yaml";async function hc(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||!rs(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=Rm(t,"project.yaml");if(!vm(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=Tm(xm(o,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>gc(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!gc(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),Sm(o,i.toString()),{repoName:r,defaultBranch:n}}import{existsSync as Vo,readFileSync as Jo,writeFileSync as Im}from"node:fs";import{join as En}from"node:path";import{parseDocument as zo}from"yaml";async function yc(t,e){let r=[];if(e.stageField!==void 0||e.sourceColumns!==void 0||e.rejectColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0||e.backlogScope!==void 0){let i=En(t,"project.yaml");if(!Vo(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=zo(Jo(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.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=En(t,"regimen.yaml");if(!Vo(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=zo(Jo(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)Im(En(t,i.path),i.content);return{files:r.map(i=>i.path)}}function Pn(t){if(!t)return"Stage";try{let e=En(t,"project.yaml");if(!Vo(e))return"Stage";let n=zo(Jo(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}import{existsSync as bc,readFileSync as $c}from"node:fs";import{join as vc}from"node:path";import{parseDocument as xc}from"yaml";var Ur=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return za(this.cfg,e)}getIssue(e,r){return Xa(this.cfg,e,r??Pn(this.contextDir))}listComments(e,r){return Qa(this.cfg,e,r)}downloadAttachment(e){return Ja(this.cfg,e)}updateStatus(e,r){return Ma(this.cfg,e,r,Pn(this.contextDir))}addComment(e,r,n){return Ga(this.cfg,e,r)}createIssue(e){return Ka(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,Pn(this.contextDir))}editIssue(e,r){return Fa(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return Wa(this.cfg,e,r,n)}fetchStateFields(e){return ec(this.cfg,e)}};import{existsSync as Nm,readFileSync as Om}from"node:fs";import{randomBytes as Dm}from"node:crypto";import{existsSync as kc,readFileSync as Cm,readdirSync as Em}from"node:fs";function jn(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=_m(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:Pm(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:Am(jm(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 An(t,e,r){if(r.length===0)return;let n=jn(t,e,r),o=r.map(i=>i.issue.key);await Ve(t,n,`sync(${o.join(", ")}): task data`)}function Pm(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(`
532
+ `)}function jm(t,e,r){let n=new Map,o=ie(t,`tasks/${e}/comments.jsonl`);if(kc(o))for(let i of Cm(o,"utf-8").split(`
533
+ `)){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=_t(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function Am(t){return t.map(e=>JSON.stringify(e)).join(`
489
534
  `)+(t.length>0?`
490
- `:"")}function Df(t,e,r){let n=[],o=Ke(t,`tasks/${e}/attachments`);if(La(o))for(let i of Af(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}var yn=new Map;async function wn(t,e){let n=(yn.get(t)??Promise.resolve()).catch(()=>{}).then(e);yn.set(t,n);try{return await n}finally{yn.get(t)===n&&yn.delete(t)}}async function Ba(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;br(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return H("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return wn(`${i}/${r.name}`,async()=>{let s=await $r(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ke(i,r.name,t.baseDir),{commit:c}=await Fs(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});return ee({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"early_branch":{if(!r)return H("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return wn(`${i}/${r.name}`,async()=>{let s=await $r(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ke(i,r.name,t.baseDir),{commit:c,pushed:l}=await Hs(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return ee({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return H("no repo spec");let i=We(r),s=await i.createPullRequest(r,e);return ee({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return H("no repo spec");let i=We(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ee({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return H("no repo spec");let i=We(r);return await i.closePR(r,e.prNumber,e.comment),ee({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return H("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return wn(`${i}/${r.name}`,async()=>{let s=await $r(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ke(i,r.name,t.baseDir),{mergedSha:c}=await Ks(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ee({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"add_pr_comment":return ee({stub:!0});case"tracker_status":{let i=Ue();return i?t.trackerIssueId?(await ca(i,t.trackerIssueId,e.newStatus,gn(t.contextDir)),ee({issueId:t.trackerIssueId,newStatus:e.newStatus})):H("no tracker_issue_id provided"):H("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env")}case"tracker_comment":{let i=Ue();if(!i)return H("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.trackerIssueId)return H("no tracker_issue_id provided");let s=await la(i,t.trackerIssueId,e.body);return ee({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Ue();if(!i)return H("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!e.projectKey)return H("no projectKey in create_tracker_issue action");let{id:s,key:a}=await da(i,e.projectKey,e.title,e.body,e.targetStatus,gn(t.contextDir));return ee({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Ue();if(!i)return H("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");let s=0;for(let a of e.links)try{await fa(i,a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return H(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return ee({applied:s})}case"set_project_setting":{if(!t.contextDir)return H("no context repo clone on this CLI");let i=await Na(t.contextDir,e.edits);return ee({files:i.files})}case"tracker_edit":{let i=Ue();if(!i)return H("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.contextDir)return H("no context repo clone on this CLI");let s=gn(t.contextDir);await ua(i,e.issueKey,{...e.title!==void 0?{summary:e.title}:{},...e.body!==void 0?{description:e.body}:{}});let a=await fn(i,e.issueKey,s);return a&&await hn(t.contextDir,e.projectId,[{issue:a,comments:[],attachments:[]}]),ee({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return H("no context repo clone on this CLI");let i=await Da(t.contextDir,e);return ee({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return H("no context repo clone on this CLI");let i=await Ua(t.contextDir,e);return ee({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ee({reported:!0})):H("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return H("no context repo clone on this CLI");let i=await t.refreshContextStatus();return ee({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return H("no project workspace on this CLI");if(!r)return H("no repo spec");if(!t.onRunActivity)return H("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=nn(t.contextDir),c=s.find(m=>m.id===e.actionId);if(!c){let m=a.find(f=>f.file===`actions/${e.actionId}.yml`);return H(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=Ei(c,e.input);if(!l.ok)return H(l.error);let p=hs(t.contextDir),d=D(e.projectId),u={};return d?.github?.token&&(u.GH_TOKEN=d.github.token),d?.gitlab?.token&&(u.GITLAB_TOKEN=d.gitlab.token),d?.bitbucket&&(u.BITBUCKET_EMAIL=d.bitbucket.email,u.BITBUCKET_API_TOKEN=d.bitbucket.apiToken),d?.youtrack&&(u.YOUTRACK_URL=d.youtrack.url,u.YOUTRACK_TOKEN=d.youtrack.token),wn(`${e.projectId}/${r.name}`,async()=>{await $r(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=ke(e.projectId,r.name,t.baseDir),f=await Ea({cwd:m,def:c,input:l.values,variables:p,secrets:d?.secrets??{},credEnv:u,onEvent:y=>i(e.runId,y)});return ee({runId:e.runId,status:f.status,exitCode:f.exitCode,...f.failedStep?{failedStep:f.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return H("no context repo clone on this CLI");let i=_a(t.contextDir,e.path);return ee({path:e.path,...i})}default:return H(`unsupported action type: ${e.type}`)}}catch(i){return H(i instanceof Error?i.message:String(i))}}function ee(t){return{status:"done",result:t}}function H(t){return{status:"failed",error:t}}import{existsSync as rc,readFileSync as nc}from"node:fs";import{join as oc}from"node:path";import{homedir as Lf}from"node:os";import{existsSync as Bf,mkdirSync as Mf,readFileSync as Gf,writeFileSync as Ff}from"node:fs";import{dirname as Hf,join as Kf}from"node:path";function Eo(){return F("FARM_PINS")??Kf(Lf(),".codepipe","farm-pins.json")}function Ma(){let t=Eo();if(!Bf(t))return{};try{return JSON.parse(Gf(t,"utf-8"))}catch{return{}}}function Wf(t){let e=Eo();Mf(Hf(e),{recursive:!0}),Ff(e,JSON.stringify(t,null,2)+`
491
- `,{mode:384})}function qf(t){return Ma()[t]}function bn(t,e){let r=Ma();r[t]=e,Wf(r)}function kn(t,e){let r=ue(e),n=qf(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 ${Eo()}.`);return r}import Yf from"ws";function $n(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new Yf(r)}var N=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};async function ot(t,e,r){return Ce(t,e,"/projects",r)}async function Ga(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new N(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function vn(t,e,r,n){return Ce(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function Fa(t,e,r,n){return Ce(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function Ha(t,e,r,n){return Ce(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function Ka(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 N(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function xn(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new N(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function Wa(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new N(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}var Tr=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function qa(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 Tr(e)}if(!r.ok)throw new N(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function Ya(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new N(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function Va(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new N(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function Ja(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 N(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function za(t,e,r,n){return Ce(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function Xa(t,e,r,n,o){return Ce(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function Qa(t,e,r,n,o){return Ce(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function Za(t,e,r,n,o){return Ce(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function Cr(t,e,r,n){return Ce(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function Po(t,e,r,n){await Ce(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function ec(t,e,r,n){return Ce(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function tc(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 N(o.status,s,a)}return s}async function Y(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new N(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function Ce(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 N(o.status,s,a)}return s}async function ic(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=ue(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");kn(e.farmId,e.farmPublicKey);let s=D(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await Y(t.hubUrl,t.cliToken,t.projectId),c;if(r){let u=oc(r,"project.yaml"),m=oc(r,"regimen.yaml");rc(u)&&rc(m)?c={projectYaml:nc(u,"utf-8"),regimenYaml:nc(m,"utf-8")}:n.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},p=qe(e.farmPublicKey,JSON.stringify(l));bn(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let d=await vn(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:p});return d.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...d.daemonStatus?{daemonStatus:d.daemonStatus}:{}}:o(d.error??"farm provisioning failed")}catch(i){return o(i instanceof Error?i.message:String(i))}}import{homedir as Vf}from"node:os";import{existsSync as Jf,mkdirSync as zf,readFileSync as Xf,writeFileSync as Qf}from"node:fs";import{dirname as Zf,join as em}from"node:path";function Ao(){return F("RUNNER_PINS")??em(Vf(),".codepipe","runner-pins.json")}function sc(){let t=Ao();if(!Jf(t))return{};try{return JSON.parse(Xf(t,"utf-8"))}catch{return{}}}function tm(t){let e=Ao();zf(Zf(e),{recursive:!0}),Qf(e,JSON.stringify(t,null,2)+`
492
- `,{mode:384})}function rm(t){return sc()[t]}function _o(t,e){let r=sc();r[t]=e,tm(r)}function ac(t,e){let r=ue(e),n=rm(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 ${Ao()}.`);return r}var lc=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function cc(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:lc(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 nm={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:lc(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)=>cc(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>cc(t,e,r,"remove-token")},uc={api:nm,fetchProject:Y,provisionOnRunner:Fa,teardownOnRunner:Ha};async function pc(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(ue(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");ac(e.runnerId,e.runnerPublicKey);let i=D(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??[]).filter(c=>c.host==="github");if(a.length===0)throw new Error("the project has no GitHub repositories \u2014 nothing to connect a runner to");return{githubToken:i,repos:a}}async function dc(t,e,r,n=uc){let o=i=>({type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repos:s}=await pc(t,e,n),a=[];for(let u of s)await n.api.repoHasAdmin(i,u.owner,u.repoName)||a.push(`${u.owner}/${u.repoName}`);if(a.length>0)return o(`the GitHub token lacks admin access on ${a.join(", ")} \u2014 replace it (project page \u2192 Tokens \u2192 Replace) with a token that has admin rights on every repository`);let c=[];for(let u of s)c.push({owner:u.owner,repo:u.repoName,regToken:await n.api.mintRegistrationToken(i,u.owner,u.repoName)});let l={projectId:t.projectId,runners:c},p=qe(e.runnerPublicKey,JSON.stringify(l));_o(e.runnerId,e.fingerprint),r.info(`[ghr] ${c.length} registration token(s) sealed for runner host ${e.runnerName} \u2014 handing off`);let d=await n.provisionOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:p});return{type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:d.ok,...d.runners?{runners:d.runners}:{},...d.error?{error:d.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}async function fc(t,e,r,n=uc){let o=i=>({type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repos:s}=await pc(t,e,n),a=[];for(let d of s)try{a.push({owner:d.owner,repo:d.repoName,removeToken:await n.api.mintRemoveToken(i,d.owner,d.repoName)})}catch(u){r.warn(`[ghr] remove-token for ${d.owner}/${d.repoName} failed (${u instanceof Error?u.message:u}) \u2014 the runner host will force-remove`),a.push({owner:d.owner,repo:d.repoName})}let c={projectId:t.projectId,runners:a},l=qe(e.runnerPublicKey,JSON.stringify(c));_o(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle sealed for runner host ${e.runnerName} \u2014 handing off`);let p=await n.teardownOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:l});return{type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:p.ok,...p.error?{error:p.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}var mc=16*1024;function om(t){return ye.test(t)?ze(t)?`secret name "${t}" is reserved`:null:`secret name must match ${ye}`}function gc(t,e,r,n){let o=om(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(Bt(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>mc)return{ok:!1,detail:`secret value too large (max ${mc} chars)`};try{return ts(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function hc(t,e){try{return rs(t,e)?{ok:!0}:{ok:!0,detail:"no such secret (already absent)"}}catch(r){return{ok:!1,detail:r instanceof Error?r.message:String(r)}}}var Sn=class{constructor(e,r,n){this.intervalMs=e;this.send=r;this.log=n}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let n=[];for(let s of r.prs){let a=We(s.repoSpec);try{let c=await a.getPullRequest(s.repoSpec,s.number);n.push({number:s.number,url:s.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof $t){this.log.warn(`[track] task=${e} pr=${s.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${s.url} fetch failed: ${c instanceof Error?c.message:String(c)}`);return}}let o=n.map(s=>`${s.number}:${s.state}:${s.merged?1:0}:${s.ci}:${s.mergeable}`).join("|");if(this.lastSig.get(e)===o)return;for(let s=0;s<n.length;s++){let a=n[s];if(a.ci!=="failed")continue;let c=We(r.prs[s].repoSpec);if(c.getCiFailureLog)try{let l=await c.getCiFailureLog(r.prs[s].repoSpec,a.number);l&&(a.ciFailureLog=l)}catch(l){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${l instanceof Error?l.message:String(l)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:n}),this.lastSig.set(e,o);let i=im(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}};function im(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var Rn=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 e=Ue();if(!e){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn("[yt-sync] YOUTRACK_URL/YOUTRACK_TOKEN missing \u2014 poller idle. set them in cli/.env to enable YT read-sync."));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,e)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let $=e.stageField?{stageField:e.stageField}:{},S=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{};if((e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn){let A=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[]])],[L,P]=await Promise.all([A.length>0?dn(r,{projectKey:e.projectKey,columns:A,...$,...S}):Promise.resolve([]),dn(r,{projectKey:e.projectKey,columns:[e.backlogColumn],...$})]),g=new Map;for(let _ of[...L,...P])g.set(_.id,_);o=[...g.values()]}else{let A=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await dn(r,{projectKey:e.projectKey,columns:A,...$,...S})}}catch($){this.log.warn(`[yt-sync] listIssues failed: ${$ instanceof Error?$.message:String($)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let $ of o){if(s.add($.id),a.has($.status))continue;let S=await wc(r,$.id,e.sinceMs,this.log);S&&i.set($.id,S)}let c=[];for(let $ of e.offBoardIssueIds){if(s.has($))continue;let S=await wc(r,$,e.sinceMs,this.log);if(S&&S.length>0&&i.set($,S),e.requireAssignee||S&&S.length>0){let B=await cm(r,$,e.stageField,this.log);if(B)c.push(B);else if(S&&S.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter($=>!a.has($.status)),{attachmentsByIssue:p,attachmentKeys:d}=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 u=[...l,...c].map($=>({issue:$,comments:i.get($.id)??[],attachments:p.get($.id)??[]}));try{await hn(this.options.contextDir,e.projectId,u),this.abandonedTicks=0;for(let $ of d)this.shippedAttachments.add($)}catch($){let S=$ instanceof Error?$.message:String($);this.abandonTick(`context task sync failed: ${S}`);return}let m=this.options.isSelfComment??(()=>!1),f=[],y=[];for(let[$,S]of i){let B=S.filter(A=>!m(A.id));if(B.length===0)continue;f.push({issueId:$,comments:B.map(sm)});let j=B.flatMap(A=>{let L=Yr(A.body);return L?[{commentId:A.id,author:A.author,name:L.name,args:L.args,createdAt:A.createdAt}]:[]});j.length>0&&y.push({issueId:$,commands:j})}let w={type:"youtrack_observation",projectId:e.projectId,issues:o.map(yc),commentsBatch:f,...y.length>0?{commandsBatch:y}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(yc)}:{},observedAtMs:n};this.send(w);let k=f.reduce(($,S)=>$+S.comments.length,0),h=y.reduce(($,S)=>$+S.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${k} commands=${h} (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 p of r.get(s.id)??[])a.push(...p.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let p of a){let d=`${s.id}:${p.id}`;if(this.shippedAttachments.has(d))continue;let u;try{u=await ya(n,p.url)}catch(f){this.log.warn(`[yt-sync] attachment ${p.name} (${s.id}) download failed: ${f instanceof Error?f.message:String(f)}`);continue}let m=am(p.name);l.has(m)&&(m=`${p.id}-${m}`),l.add(m),c.push({name:m,contentBase64:u.toString("base64")}),i.push(d)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}};function yc(t){let{description:e,...r}=t;return r}function sm(t){let{body:e,...r}=t;return r}function am(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 cm(t,e,r,n){try{return await fn(t,e,r)}catch(o){return n.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function wc(t,e,r,n){try{return await wa(t,e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}var No="npm i -g @code-partner/codepipe@latest";function Tn(t,e={}){let r=e.log??{info:f=>console.log(f),warn:f=>console.warn(f)};r.info(`codepipe-cli v${he} (protocol ${Ee})`);let n=f=>e.onEvent?.(f),o=e.workspace;o?.contextDir&&bs(o.contextDir,r);let i=bc("CLI_TRACKING_POLL_INTERVAL_SEC"),s=bc("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let f=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(f)&&f>0?f*1e3:6e5})(),c=!1,l=!1,p=new Set,d=new Set,u=m();function m(){let f=$n(t.hubUrl,t.cliToken),y=null,w=new Sn(i,b=>{f.readyState===f.OPEN&&f.send(JSON.stringify(b))},r),k=new Rn(s,b=>{f.readyState===f.OPEN&&f.send(JSON.stringify(b))},r,{contextDir:o?.contextDir??null,isSelfComment:b=>d.has(b)}),h=null,$=async()=>{try{let b;try{let E=await Y(t.hubUrl,t.cliToken,t.projectId);b={repos:E.repos,contextRepo:E.contextRepo}}catch(E){r.warn(`[readiness] could not fetch project summary for push checks: ${E instanceof Error?E.message:String(E)}`)}let C=await va(t.projectId,b);if(f.readyState!==f.OPEN)return;let x={type:"cli_readiness",projectId:t.projectId,ready:C.ready,checks:C.checks,creds:C.creds,secretNames:ns(t.projectId),checkedAt:C.checkedAt};if(f.send(JSON.stringify(x)),C.ready)r.info("[readiness] ready");else{let E=C.checks.filter(M=>!M.ok).map(M=>`${M.name}(${M.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${E.join(", ")}`)}}catch(b){r.warn(`[readiness] check failed: ${b instanceof Error?b.message:String(b)}`)}},S=()=>{$(),h=setInterval(()=>void $(),a),typeof h.unref=="function"&&h.unref()},B=()=>{h&&(clearInterval(h),h=null)},j=150,A=new Map,L=b=>{let C=A.get(b);if(!C||(C.timer&&clearTimeout(C.timer),A.delete(b),C.events.length===0||f.readyState!==f.OPEN))return;let x={type:"run_activity",projectId:t.projectId,runId:b,events:C.events};f.send(JSON.stringify(x))},P=(b,C)=>{let x=A.get(b);if(x||(x={events:[],timer:null},A.set(b,x)),x.events.push(C),C.kind==="result"){L(b);return}x.timer||(x.timer=setTimeout(()=>L(b),j),x.timer.unref?.())},g=o?.contextDir?new on(o.contextDir,t.projectId,b=>{f.readyState===f.OPEN&&f.send(JSON.stringify(b))},r):null,_=async()=>{let b=o?.contextDir;if(!b)throw new Error("no context repo clone on this CLI");let C;try{C=(await Y(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let x=await Os(b,t.projectId,C,r);return f.readyState===f.OPEN&&f.send(JSON.stringify(x)),x};return f.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let b=ps(t.projectId),C=F("ORIGIN")==="farm"?"farm":"local",x=F("FARM_ID"),E=t.accountEmail??b.email,M;try{let R=Ta(t.projectId);R&&(M=R.publicKey,r.info(`[cred-channel] key fingerprint: ${R.fingerprint}`))}catch(R){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${R instanceof Error?R.message:String(R)}`)}let v={type:"register",projectId:t.projectId,platformVersion:he,protocolVersion:Ee,accountId:b.accountId,accountLabel:b.label,origin:C,inFlightActionIds:[...p],...E?{accountEmail:E}:{},...C==="farm"&&x?{farmId:x}:{},...M?{sealPublicKey:M}:{}};f.send(JSON.stringify(v))}),f.on("message",async b=>{let C=b.toString("utf-8");if(C==="pong"||C==="ping")return;let x;try{x=JSON.parse(C)}catch{return}if(!x||typeof x!="object")return;let E=x.type;if(E==="registered"){let v=x;if(v.ok){if(r.info(`[ws] registered for project ${v.projectId}`),n({kind:"registered",projectId:v.projectId??t.projectId}),w.start(),g?.start(),S(),Oo(t,o,r),o?.contextDir)try{let R=an(o.contextDir,t.projectId);f.readyState===f.OPEN&&f.send(JSON.stringify(R)),R.outdated&&(r.warn(`[ctx] context format outdated: v${R.templateVersion} \u2192 v${R.currentVersion}`+(R.missingPaths.length>0?` (missing: ${R.missingPaths.join(", ")})`:"")),l||(l=!0,_().catch(()=>{})))}catch(R){r.warn(`[ctx] context-format detect failed (non-fatal): ${R instanceof Error?R.message:String(R)}`)}}else r.warn(`[ws] register rejected: ${v.reason??"unknown"}`),n({kind:"register_rejected",reason:v.reason??"unknown"}),c=!0,f.close();return}if(E==="hello"){let v=x;y=Hr(v.protocolVersion);let R=y?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${v.platformVersion} (protocol ${v.protocolVersion}) \u2014 ${R}`),y||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${he}, protocol ${Ee}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${No}`),n({kind:"incompatible",hubVersion:typeof v.platformVersion=="string"?v.platformVersion:null,hubProtocol:typeof v.protocolVersion=="number"?v.protocolVersion:null,updateCommand:No}));return}if(E==="tracking_targets"){w.setTargets(x.targets);return}if(E==="youtrack_sync_request"){k.setRequest(x);return}if(E==="youtrack_force_sync"){k.forceSync();return}if(E==="sync_local"){await fm(x,o,f,r);return}if(E==="provision_repo"){let v=x;r.info(`[repo] provision_repo: ${v.repo.name} (${v.repo.host}:${v.repo.owner}/${v.repo.repoName})`),await pm(t,o,v.repo,r),await Oo(t,o,r);return}if(E==="remove_repo"){let v=x;r.info(`[repo] remove_repo: ${v.repoName}${v.purge?" (purge)":""}`),await Oo(t,o,r),v.purge&&dm(t,o,v.repoName,r);return}if(E==="context_write"){await mm(x,o,f,r);return}if(E==="adr_promote"){await gm(x,o,f,r);return}if(E==="cred_update"){let v=x,R=D(t.projectId),T=R?.sealKey?await Ca(t.projectId,v.kind,v.sealed,R.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},G={type:"cred_update_result",updateId:v.updateId,projectId:t.projectId,ok:T.ok,...T.detail?{detail:T.detail}:{}};f.readyState===f.OPEN&&f.send(JSON.stringify(G)),T.ok?(r.info(`[cred] ${v.kind} replaced${T.detail?` \u2014 ${T.detail}`:""}`),$()):r.warn(`[cred] ${v.kind} replacement rejected: ${T.detail??"unknown"}`);return}if(E==="move_to_farm"){let v=x;r.info(`[farm-move] request to move ${t.projectId} onto farm ${v.farmName} (${v.farmId})`);let R=await ic(t,v,o?.contextDir,r);f.readyState===f.OPEN&&f.send(JSON.stringify(R)),R.ok?r.info(`[farm-move] done \u2014 farm daemon ${R.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${R.error??"unknown error"}`);return}if(E==="gh_runner_setup"){let v=x;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${v.runnerName} (${v.runnerId})`);let R=await dc(t,v,r);f.readyState===f.OPEN&&f.send(JSON.stringify(R)),R.ok?r.info(`[ghr] runners connected on ${v.runnerName}`):r.warn(`[ghr] setup failed: ${R.error??"see per-repo statuses"}`);return}if(E==="gh_runner_teardown"){let v=x;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${v.runnerName} (${v.runnerId})`);let R=await fc(t,v,r);f.readyState===f.OPEN&&f.send(JSON.stringify(R)),R.ok?r.info(`[ghr] runners disconnected from ${v.runnerName}`):r.warn(`[ghr] teardown failed: ${R.error??"unknown error"}`);return}if(E==="tracker_fields_request"){let v=x,R={type:"tracker_fields_result",requestId:v.requestId,projectId:t.projectId,ok:!1},T=Ue();if(!T)R.error="YOUTRACK_URL/YOUTRACK_TOKEN not set on this CLI";else try{R.fields=await ka(T,v.projectKey),R.ok=!0}catch(G){R.error=G instanceof Error?G.message:String(G)}f.readyState===f.OPEN&&f.send(JSON.stringify(R)),R.ok||r.warn(`[yt-fields] listing failed: ${R.error??"unknown"}`);return}if(E==="project_secret_update"||E==="project_secret_delete"){let v=x,R;if(v.type==="project_secret_update"){let G=D(t.projectId);R=G?.sealKey?gc(t.projectId,v.name,v.sealed,G.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else R=hc(t.projectId,v.name);let T={type:"project_secret_update_result",updateId:v.updateId,projectId:t.projectId,ok:R.ok,...R.detail?{detail:R.detail}:{}};f.readyState===f.OPEN&&f.send(JSON.stringify(T)),R.ok?(r.info(`[secret] ${v.name} ${v.type==="project_secret_update"?"saved":"deleted"}`+(R.detail?` \u2014 ${R.detail}`:"")),$()):r.warn(`[secret] ${v.name} rejected: ${R.detail??"unknown"}`);return}if(E==="sandbox_keys"){let v=D(t.projectId);if(!v){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let R=Pt(t.projectId),T=Js(x,v,R,r);for(let G of T)f.readyState===f.OPEN&&f.send(JSON.stringify(G));return}if(E!=="dispatch_action")return;let M=x;if(y===!1){let v=`refused: HUB protocol incompatible with CLI v${he} (protocol ${Ee})`;f.send(JSON.stringify({type:"action_result",actionId:M.actionId,status:"failed",error:v})),r.warn(`[exec] ${M.actionId} (${M.action.type}) \u2192 REFUSED: ${v}`),r.warn(`[exec] update the CLI to clear this: ${No}`),n({kind:"action",actionId:M.actionId,actionType:M.action.type,ok:!1,error:v});return}p.add(M.actionId);try{let v=await Ba({action:M.action,repo:M.repo,trackerIssueId:M.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:g?()=>g.reportNow():void 0,refreshContextStatus:o?.contextDir?_:void 0,onRunActivity:P}).catch(G=>({status:"failed",error:G instanceof Error?G.message:String(G)}));M.action.type==="tracker_comment"&&v.status==="done"&&"result"in v&&typeof v.result?.commentId=="string"&&d.add(v.result.commentId),f.send(JSON.stringify({type:"action_result",actionId:M.actionId,...v}));let R=v.status!=="failed",T=!R&&"error"in v?v.error:void 0;R?r.info(`[exec] ${M.actionId} (${M.action.type}) \u2192 done`):r.warn(`[exec] ${M.actionId} (${M.action.type}) \u2192 FAILED: ${T??"?"}`),n({kind:"action",actionId:M.actionId,actionType:M.action.type,ok:R,...T?{error:T}:{}})}finally{p.delete(M.actionId)}}),f.on("close",(b,C)=>{let x=C?.toString("utf-8")??"";if(r.info(`[ws] closed code=${b}${x?` reason=${x}`:""}`),w.stop(),k.stop(),g?.stop(),B(),x==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:b}),!c&&setTimeout(()=>{u=m()},2e3)}),f.on("error",b=>r.warn(`[ws] error: ${b.message}`)),f}return{stop(){c=!0,u.close()}}}async function Oo(t,e,r){try{let n=await Y(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=wr(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 pm(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?Ir(e.root,o):ke(t.projectId,r.name);if(kc(Ir(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await um().clone($o(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 dm(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?Ir(e.root,o):ke(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!kc(Ir(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{lm(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 fm(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=Ir(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await ds(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 mm(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 Dt(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 gm(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 Ts(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 bc(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as Cc,mkdirSync as Ic}from"node:fs";import{dirname as jc}from"node:path";import{simpleGit as Gt}from"simple-git";import{execFileSync as hm}from"node:child_process";import{mkdtempSync as ym,mkdirSync as wm,readFileSync as $c,rmSync as bm,writeFileSync as km}from"node:fs";import{tmpdir as $m}from"node:os";import{dirname as vm,join as vc}from"node:path";function xc(t="codepipe-context"){let e=ym(vc($m(),"codepipe-ssh-")),r=vc(e,"id_ed25519");try{return hm("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:$c(r,"utf-8"),publicKey:$c(`${r}.pub`,"utf-8").trim()}}finally{bm(e,{recursive:!0,force:!0})}}async function Sc(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 Rc(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 Tc(t,e){wm(vm(t),{recursive:!0});let r=e.endsWith(`
535
+ `:"")}function _m(t,e,r){let n=[],o=ie(t,`tasks/${e}/attachments`);if(kc(o))for(let i of Em(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}var Lr=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await Tr(this.contextDir);let r=e.columns??[];return sa(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>Cr(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=Ir(this.contextDir,e);return r?Cr(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return wc(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 Tr(this.contextDir),!Ir(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${Dm(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=_t(r);s&&(i.parsedCommand=s);let c=[...wc(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
536
+ `)+`
537
+ `;return await Ve(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 aa(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:yo.statusColumns}]}async mutateRecord(e,r,n){let o=Ir(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=Cr(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:vr(e),content:Bo(i)},...jn(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await Ve(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:an,status:r.targetStatus,links:[],created:n,updated:n},i=Cr(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:vr(e),content:Bo(o)},...jn(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}};function wc(t,e){let r=ie(t,`tasks/${e}/comments.jsonl`);if(!Nm(r))return[];let n=[];for(let o of Om(r,"utf-8").split(`
538
+ `)){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}function Xo(t){if(!t)return"youtrack";try{let e=vc(t,"project.yaml");return bc(e)&&xc($c(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function Be(t){let e=Xo(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=oa(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=Um(n);return i?{ok:!0,kind:e,provider:new Lr(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=La();return r?{ok:!0,kind:e,provider:new Ur(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function Um(t){try{let e=vc(t,"project.yaml");if(!bc(e))return null;let r=xc($c(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var _n=new Map;async function Nn(t,e){let n=(_n.get(t)??Promise.resolve()).catch(()=>{}).then(e);_n.set(t,n);try{return await n}finally{_n.get(t)===n&&_n.delete(t)}}async function Sc(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;Pr(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return H("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Nn(`${i}/${r.name}`,async()=>{let s=await Ar(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Se(i,r.name,t.baseDir),{commit:c}=await wa(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});return te({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"early_branch":{if(!r)return H("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Nn(`${i}/${r.name}`,async()=>{let s=await Ar(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Se(i,r.name,t.baseDir),{commit:c,pushed:l}=await ba(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return te({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return H("no repo spec");let i=Je(r),s=await i.createPullRequest(r,e);return te({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return H("no repo spec");let i=Je(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return te({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return H("no repo spec");let i=Je(r);return await i.closePR(r,e.prNumber,e.comment),te({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return H("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Nn(`${i}/${r.name}`,async()=>{let s=await Ar(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Se(i,r.name,t.baseDir),{mergedSha:c}=await $a(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return te({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"add_pr_comment":return te({stub:!0});case"tracker_status":{let i=Be({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),te({issueId:t.trackerIssueId,newStatus:e.newStatus})):H("no tracker_issue_id provided"):H(i.error)}case"tracker_comment":{let i=Be({contextDir:t.contextDir});if(!i.ok)return H(i.error);if(!t.trackerIssueId)return H("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return te({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Be({contextDir:t.contextDir});if(!i.ok)return H(i.error);if(!e.projectKey)return H("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 te({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Be({contextDir:t.contextDir});if(!i.ok)return H(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 H(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return te({applied:s})}case"set_project_setting":{if(!t.contextDir)return H("no context repo clone on this CLI");let i=await mc(t.contextDir,e.edits);return te({files:i.files})}case"tracker_edit":{let i=Be({contextDir:t.contextDir});if(!i.ok)return H(i.error);if(!t.contextDir)return H("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 An(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),te({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return H("no context repo clone on this CLI");let i=await yc(t.contextDir,e);return te({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return H("no context repo clone on this CLI");let i=await hc(t.contextDir,e);return te({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),te({reported:!0})):H("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return H("no context repo clone on this CLI");let i=await t.refreshContextStatus();return te({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return H("no project workspace on this CLI");if(!r)return H("no repo spec");if(!t.onRunActivity)return H("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=wn(t.contextDir),c=s.find(m=>m.id===e.actionId);if(!c){let m=a.find(f=>f.file===`actions/${e.actionId}.yml`);return H(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=Xi(c,e.input);if(!l.ok)return H(l.error);let p=Ls(t.contextDir),d=L(e.projectId),u={};return d?.github?.token&&(u.GH_TOKEN=d.github.token),d?.gitlab?.token&&(u.GITLAB_TOKEN=d.gitlab.token),d?.bitbucket&&(u.BITBUCKET_EMAIL=d.bitbucket.email,u.BITBUCKET_API_TOKEN=d.bitbucket.apiToken),d?.youtrack&&(u.YOUTRACK_URL=d.youtrack.url,u.YOUTRACK_TOKEN=d.youtrack.token),Nn(`${e.projectId}/${r.name}`,async()=>{await Ar(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=Se(e.projectId,r.name,t.baseDir),f=await uc({cwd:m,def:c,input:l.values,variables:p,secrets:d?.secrets??{},credEnv:u,onEvent:y=>i(e.runId,y)});return te({runId:e.runId,status:f.status,exitCode:f.exitCode,...f.failedStep?{failedStep:f.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return H("no context repo clone on this CLI");let i=fc(t.contextDir,e.path);return te({path:e.path,...i})}default:return H(`unsupported action type: ${e.type}`)}}catch(i){return H(i instanceof Error?i.message:String(i))}}function te(t){return{status:"done",result:t}}function H(t){return{status:"failed",error:t}}import{existsSync as Gc,readFileSync as Fc}from"node:fs";import{join as Hc}from"node:path";import{homedir as Lm}from"node:os";import{existsSync as Bm,mkdirSync as Mm,readFileSync as Gm,writeFileSync as Fm}from"node:fs";import{dirname as Hm,join as Km}from"node:path";function Qo(){return F("FARM_PINS")??Km(Lm(),".codepipe","farm-pins.json")}function Rc(){let t=Qo();if(!Bm(t))return{};try{return JSON.parse(Gm(t,"utf-8"))}catch{return{}}}function Wm(t){let e=Qo();Mm(Hm(e),{recursive:!0}),Fm(e,JSON.stringify(t,null,2)+`
539
+ `,{mode:384})}function Ym(t){return Rc()[t]}function On(t,e){let r=Rc();r[t]=e,Wm(r)}function Dn(t,e){let r=de(e),n=Ym(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 ${Qo()}.`);return r}import qm from"ws";function Un(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new qm(r)}var N=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};async function lt(t,e,r){return Pe(t,e,"/projects",r)}async function Tc(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new N(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function Ln(t,e,r,n){return Pe(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function Ic(t,e,r,n){return Pe(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function Cc(t,e,r,n){return Pe(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function Ec(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 N(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function Bn(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new N(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function Pc(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new N(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}var Br=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function jc(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 Br(e)}if(!r.ok)throw new N(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function Ac(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new N(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function _c(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new N(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function Nc(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 N(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function Oc(t,e,r,n){return Pe(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function Dc(t,e,r,n,o){return Pe(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function Uc(t,e,r,n,o){return Pe(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function Lc(t,e,r,n,o){return Pe(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function Mr(t,e,r,n){return Pe(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function Zo(t,e,r,n){await Pe(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function Bc(t,e,r,n){return Pe(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function Mc(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 N(o.status,s,a)}return s}async function q(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new N(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function Pe(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 N(o.status,s,a)}return s}async function Kc(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=de(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Dn(e.farmId,e.farmPublicKey);let s=L(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await q(t.hubUrl,t.cliToken,t.projectId),c;if(r){let u=Hc(r,"project.yaml"),m=Hc(r,"regimen.yaml");Gc(u)&&Gc(m)?c={projectYaml:Fc(u,"utf-8"),regimenYaml:Fc(m,"utf-8")}:n.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},p=ze(e.farmPublicKey,JSON.stringify(l));On(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let d=await Ln(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:p});return d.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...d.daemonStatus?{daemonStatus:d.daemonStatus}:{}}:o(d.error??"farm provisioning failed")}catch(i){return o(i instanceof Error?i.message:String(i))}}import{homedir as Vm}from"node:os";import{existsSync as Jm,mkdirSync as zm,readFileSync as Xm,writeFileSync as Qm}from"node:fs";import{dirname as Zm,join as eg}from"node:path";function ei(){return F("RUNNER_PINS")??eg(Vm(),".codepipe","runner-pins.json")}function Wc(){let t=ei();if(!Jm(t))return{};try{return JSON.parse(Xm(t,"utf-8"))}catch{return{}}}function tg(t){let e=ei();zm(Zm(e),{recursive:!0}),Qm(e,JSON.stringify(t,null,2)+`
540
+ `,{mode:384})}function rg(t){return Wc()[t]}function ti(t,e){let r=Wc();r[t]=e,tg(r)}function Yc(t,e){let r=de(e),n=rg(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 ${ei()}.`);return r}var Vc=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function qc(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:Vc(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 ng={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Vc(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)=>qc(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>qc(t,e,r,"remove-token")},Jc={api:ng,fetchProject:q,provisionOnRunner:Ic,teardownOnRunner:Cc};async function zc(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(de(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Yc(e.runnerId,e.runnerPublicKey);let i=L(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??[]).filter(c=>c.host==="github");if(a.length===0)throw new Error("the project has no GitHub repositories \u2014 nothing to connect a runner to");return{githubToken:i,repos:a}}async function Xc(t,e,r,n=Jc){let o=i=>({type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repos:s}=await zc(t,e,n),a=[];for(let u of s)await n.api.repoHasAdmin(i,u.owner,u.repoName)||a.push(`${u.owner}/${u.repoName}`);if(a.length>0)return o(`the GitHub token lacks admin access on ${a.join(", ")} \u2014 replace it (project page \u2192 Tokens \u2192 Replace) with a token that has admin rights on every repository`);let c=[];for(let u of s)c.push({owner:u.owner,repo:u.repoName,regToken:await n.api.mintRegistrationToken(i,u.owner,u.repoName)});let l={projectId:t.projectId,runners:c},p=ze(e.runnerPublicKey,JSON.stringify(l));ti(e.runnerId,e.fingerprint),r.info(`[ghr] ${c.length} registration token(s) sealed for runner host ${e.runnerName} \u2014 handing off`);let d=await n.provisionOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:p});return{type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:d.ok,...d.runners?{runners:d.runners}:{},...d.error?{error:d.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}async function Qc(t,e,r,n=Jc){let o=i=>({type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repos:s}=await zc(t,e,n),a=[];for(let d of s)try{a.push({owner:d.owner,repo:d.repoName,removeToken:await n.api.mintRemoveToken(i,d.owner,d.repoName)})}catch(u){r.warn(`[ghr] remove-token for ${d.owner}/${d.repoName} failed (${u instanceof Error?u.message:u}) \u2014 the runner host will force-remove`),a.push({owner:d.owner,repo:d.repoName})}let c={projectId:t.projectId,runners:a},l=ze(e.runnerPublicKey,JSON.stringify(c));ti(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle sealed for runner host ${e.runnerName} \u2014 handing off`);let p=await n.teardownOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:l});return{type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:p.ok,...p.error?{error:p.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}var Zc=16*1024;function og(t){return $e.test(t)?et(t)?`secret name "${t}" is reserved`:null:`secret name must match ${$e}`}function el(t,e,r,n){let o=og(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(Kt(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>Zc)return{ok:!1,detail:`secret value too large (max ${Zc} chars)`};try{return xs(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function tl(t,e){try{return Ss(t,e)?{ok:!0}:{ok:!0,detail:"no such secret (already absent)"}}catch(r){return{ok:!1,detail:r instanceof Error?r.message:String(r)}}}var Mn=class{constructor(e,r,n){this.intervalMs=e;this.send=r;this.log=n}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let n=[];for(let s of r.prs){let a=Je(s.repoSpec);try{let c=await a.getPullRequest(s.repoSpec,s.number);n.push({number:s.number,url:s.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof Rt){this.log.warn(`[track] task=${e} pr=${s.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${s.url} fetch failed: ${c instanceof Error?c.message:String(c)}`);return}}let o=n.map(s=>`${s.number}:${s.state}:${s.merged?1:0}:${s.ci}:${s.mergeable}`).join("|");if(this.lastSig.get(e)===o)return;for(let s=0;s<n.length;s++){let a=n[s];if(a.ci!=="failed")continue;let c=Je(r.prs[s].repoSpec);if(c.getCiFailureLog)try{let l=await c.getCiFailureLog(r.prs[s].repoSpec,a.number);l&&(a.ciFailureLog=l)}catch(l){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${l instanceof Error?l.message:String(l)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:n}),this.lastSig.set(e,o);let i=ig(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}};function ig(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var Gn=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??(()=>Be({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 w=e.stageField?{stageField:e.stageField}:{},I=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},R=(e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(R){let j=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[]])],[M,E]=await Promise.all([j.length>0?r.listIssues({projectKey:e.projectKey,columns:j,...w,...I}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...w})]),g=new Map;for(let _ of[...M,...E])g.set(_.id,_);o=[...g.values()]}else{let j=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:j,...w,...I})}}catch(w){this.log.warn(`[yt-sync] listIssues failed: ${w instanceof Error?w.message:String(w)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let w of o){if(s.add(w.id),a.has(w.status))continue;let I=await nl(r,w.id,e.sinceMs,this.log);I&&i.set(w.id,I)}let c=[];for(let w of e.offBoardIssueIds){if(s.has(w))continue;let I=await nl(r,w,e.sinceMs,this.log);if(I&&I.length>0&&i.set(w,I),e.requireAssignee||I&&I.length>0){let B=await cg(r,w,e.stageField,this.log);if(B)c.push(B);else if(I&&I.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(w=>!a.has(w.status)),{attachmentsByIssue:p,attachmentKeys:d}=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 u=[...l,...c].map(w=>({issue:w,comments:i.get(w.id)??[],attachments:p.get(w.id)??[]}));try{await An(this.options.contextDir,e.projectId,u),this.abandonedTicks=0;for(let w of d)this.shippedAttachments.add(w)}catch(w){let I=w instanceof Error?w.message:String(w);this.abandonTick(`context task sync failed: ${I}`);return}let m=this.options.isSelfComment??(()=>!1),f=[],y=[];for(let[w,I]of i){let B=I.filter(j=>!m(j.id));if(B.length===0)continue;f.push({issueId:w,comments:B.map(sg)});let R=B.flatMap(j=>{let M=_t(j.body);return M?[{commentId:j.id,author:j.author,name:M.name,args:M.args,createdAt:j.createdAt}]:[]});R.length>0&&y.push({issueId:w,commands:R})}let k={type:"youtrack_observation",projectId:e.projectId,issues:o.map(rl),commentsBatch:f,...y.length>0?{commandsBatch:y}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(rl)}:{},observedAtMs:n};this.send(k);let $=f.reduce((w,I)=>w+I.comments.length,0),h=y.reduce((w,I)=>w+I.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${$} commands=${h} (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 p of r.get(s.id)??[])a.push(...p.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let p of a){let d=`${s.id}:${p.id}`;if(this.shippedAttachments.has(d))continue;let u;try{u=await n.downloadAttachment(p.url)}catch(f){this.log.warn(`[yt-sync] attachment ${p.name} (${s.id}) download failed: ${f instanceof Error?f.message:String(f)}`);continue}let m=ag(p.name);l.has(m)&&(m=`${p.id}-${m}`),l.add(m),c.push({name:m,contentBase64:u.toString("base64")}),i.push(d)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}};function rl(t){let{description:e,...r}=t;return r}function sg(t){let{body:e,...r}=t;return r}function ag(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 cg(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 nl(t,e,r,n){try{return await t.listComments(e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}var ri="npm i -g @code-partner/codepipe@latest";function Fn(t,e={}){let r=e.log??{info:f=>console.log(f),warn:f=>console.warn(f)};r.info(`codepipe-cli v${be} (protocol ${_e})`);let n=f=>e.onEvent?.(f),o=e.workspace;o?.contextDir&&Gs(o.contextDir,r);let i=ol("CLI_TRACKING_POLL_INTERVAL_SEC"),s=ol("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let f=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(f)&&f>0?f*1e3:6e5})(),c=!1,l=!1,p=new Set,d=new Set,u=m();function m(){let f=Un(t.hubUrl,t.cliToken),y=null,k=new Mn(i,b=>{f.readyState===f.OPEN&&f.send(JSON.stringify(b))},r),$=new Gn(s,b=>{f.readyState===f.OPEN&&f.send(JSON.stringify(b))},r,{contextDir:o?.contextDir??null,isSelfComment:b=>d.has(b)}),h=null,w=async()=>{try{let b={trackerProvider:Xo(o?.contextDir??null)};try{let P=await q(t.hubUrl,t.cliToken,t.projectId);b={...b,repos:P.repos,contextRepo:P.contextRepo}}catch(P){r.warn(`[readiness] could not fetch project summary for push checks: ${P instanceof Error?P.message:String(P)}`)}let C=await rc(t.projectId,b);if(f.readyState!==f.OPEN)return;let x={type:"cli_readiness",projectId:t.projectId,ready:C.ready,checks:C.checks,creds:C.creds,secretNames:Rs(t.projectId),checkedAt:C.checkedAt};if(f.send(JSON.stringify(x)),C.ready)r.info("[readiness] ready");else{let P=C.checks.filter(D=>!D.ok).map(D=>`${D.name}(${D.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${P.join(", ")}`)}}catch(b){r.warn(`[readiness] check failed: ${b instanceof Error?b.message:String(b)}`)}},I=()=>{w(),h=setInterval(()=>void w(),a),typeof h.unref=="function"&&h.unref()},B=()=>{h&&(clearInterval(h),h=null)},R=150,j=new Map,M=b=>{let C=j.get(b);if(!C||(C.timer&&clearTimeout(C.timer),j.delete(b),C.events.length===0||f.readyState!==f.OPEN))return;let x={type:"run_activity",projectId:t.projectId,runId:b,events:C.events};f.send(JSON.stringify(x))},E=(b,C)=>{let x=j.get(b);if(x||(x={events:[],timer:null},j.set(b,x)),x.events.push(C),C.kind==="result"){M(b);return}x.timer||(x.timer=setTimeout(()=>M(b),R),x.timer.unref?.())},g=o?.contextDir?new bn(o.contextDir,t.projectId,b=>{f.readyState===f.OPEN&&f.send(JSON.stringify(b))},r):null,_=async()=>{let b=o?.contextDir;if(!b)throw new Error("no context repo clone on this CLI");let C;try{C=(await q(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let x=await da(b,t.projectId,C,r);return f.readyState===f.OPEN&&f.send(JSON.stringify(x)),x};return f.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let b=_s(t.projectId),C=F("ORIGIN")==="farm"?"farm":"local",x=F("FARM_ID"),P=t.accountEmail??b.email,D;try{let S=sc(t.projectId);S&&(D=S.publicKey,r.info(`[cred-channel] key fingerprint: ${S.fingerprint}`))}catch(S){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${S instanceof Error?S.message:String(S)}`)}let v={type:"register",projectId:t.projectId,platformVersion:be,protocolVersion:_e,accountId:b.accountId,accountLabel:b.label,origin:C,inFlightActionIds:[...p],...P?{accountEmail:P}:{},...C==="farm"&&x?{farmId:x}:{},...D?{sealPublicKey:D}:{}};f.send(JSON.stringify(v))}),f.on("message",async b=>{let C=b.toString("utf-8");if(C==="pong"||C==="ping")return;let x;try{x=JSON.parse(C)}catch{return}if(!x||typeof x!="object")return;let P=x.type;if(P==="registered"){let v=x;if(v.ok){if(r.info(`[ws] registered for project ${v.projectId}`),n({kind:"registered",projectId:v.projectId??t.projectId}),k.start(),g?.start(),I(),ni(t,o,r),o?.contextDir)try{let S=Sn(o.contextDir,t.projectId);f.readyState===f.OPEN&&f.send(JSON.stringify(S)),S.outdated&&(r.warn(`[ctx] context format outdated: v${S.templateVersion} \u2192 v${S.currentVersion}`+(S.missingPaths.length>0?` (missing: ${S.missingPaths.join(", ")})`:"")),l||(l=!0,_().catch(()=>{})))}catch(S){r.warn(`[ctx] context-format detect failed (non-fatal): ${S instanceof Error?S.message:String(S)}`)}}else r.warn(`[ws] register rejected: ${v.reason??"unknown"}`),n({kind:"register_rejected",reason:v.reason??"unknown"}),c=!0,f.close();return}if(P==="hello"){let v=x;y=rn(v.protocolVersion);let S=y?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${v.platformVersion} (protocol ${v.protocolVersion}) \u2014 ${S}`),y||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${be}, protocol ${_e}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${ri}`),n({kind:"incompatible",hubVersion:typeof v.platformVersion=="string"?v.platformVersion:null,hubProtocol:typeof v.protocolVersion=="number"?v.protocolVersion:null,updateCommand:ri}));return}if(P==="tracking_targets"){k.setTargets(x.targets);return}if(P==="youtrack_sync_request"){$.setRequest(x);return}if(P==="youtrack_force_sync"){$.forceSync();return}if(P==="sync_local"){await fg(x,o,f,r);return}if(P==="provision_repo"){let v=x;r.info(`[repo] provision_repo: ${v.repo.name} (${v.repo.host}:${v.repo.owner}/${v.repo.repoName})`),await pg(t,o,v.repo,r),await ni(t,o,r);return}if(P==="remove_repo"){let v=x;r.info(`[repo] remove_repo: ${v.repoName}${v.purge?" (purge)":""}`),await ni(t,o,r),v.purge&&dg(t,o,v.repoName,r);return}if(P==="context_write"){await mg(x,o,f,r);return}if(P==="adr_promote"){await gg(x,o,f,r);return}if(P==="cred_update"){let v=x,S=L(t.projectId),G=S?.sealKey?await ac(t.projectId,v.kind,v.sealed,S.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},Q={type:"cred_update_result",updateId:v.updateId,projectId:t.projectId,ok:G.ok,...G.detail?{detail:G.detail}:{}};f.readyState===f.OPEN&&f.send(JSON.stringify(Q)),G.ok?(r.info(`[cred] ${v.kind} replaced${G.detail?` \u2014 ${G.detail}`:""}`),w()):r.warn(`[cred] ${v.kind} replacement rejected: ${G.detail??"unknown"}`);return}if(P==="move_to_farm"){let v=x;r.info(`[farm-move] request to move ${t.projectId} onto farm ${v.farmName} (${v.farmId})`);let S=await Kc(t,v,o?.contextDir,r);f.readyState===f.OPEN&&f.send(JSON.stringify(S)),S.ok?r.info(`[farm-move] done \u2014 farm daemon ${S.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${S.error??"unknown error"}`);return}if(P==="gh_runner_setup"){let v=x;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${v.runnerName} (${v.runnerId})`);let S=await Xc(t,v,r);f.readyState===f.OPEN&&f.send(JSON.stringify(S)),S.ok?r.info(`[ghr] runners connected on ${v.runnerName}`):r.warn(`[ghr] setup failed: ${S.error??"see per-repo statuses"}`);return}if(P==="gh_runner_teardown"){let v=x;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${v.runnerName} (${v.runnerId})`);let S=await Qc(t,v,r);f.readyState===f.OPEN&&f.send(JSON.stringify(S)),S.ok?r.info(`[ghr] runners disconnected from ${v.runnerName}`):r.warn(`[ghr] teardown failed: ${S.error??"unknown error"}`);return}if(P==="tracker_fields_request"){let v=x,S={type:"tracker_fields_result",requestId:v.requestId,projectId:t.projectId,ok:!1},G=Be({contextDir:o?.contextDir??null});if(!G.ok)S.error=G.error;else try{S.fields=await G.provider.fetchStateFields(v.projectKey),S.ok=!0}catch(Q){S.error=Q instanceof Error?Q.message:String(Q)}f.readyState===f.OPEN&&f.send(JSON.stringify(S)),S.ok||r.warn(`[yt-fields] listing failed: ${S.error??"unknown"}`);return}if(P==="project_secret_update"||P==="project_secret_delete"){let v=x,S;if(v.type==="project_secret_update"){let Q=L(t.projectId);S=Q?.sealKey?el(t.projectId,v.name,v.sealed,Q.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else S=tl(t.projectId,v.name);let G={type:"project_secret_update_result",updateId:v.updateId,projectId:t.projectId,ok:S.ok,...S.detail?{detail:S.detail}:{}};f.readyState===f.OPEN&&f.send(JSON.stringify(G)),S.ok?(r.info(`[secret] ${v.name} ${v.type==="project_secret_update"?"saved":"deleted"}`+(S.detail?` \u2014 ${S.detail}`:"")),w()):r.warn(`[secret] ${v.name} rejected: ${S.detail??"unknown"}`);return}if(P==="sandbox_keys"){let v=L(t.projectId);if(!v){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let S=Dt(t.projectId),G=Ta(x,v,S,r);for(let Q of G)f.readyState===f.OPEN&&f.send(JSON.stringify(Q));return}if(P!=="dispatch_action")return;let D=x;if(y===!1){let v=`refused: HUB protocol incompatible with CLI v${be} (protocol ${_e})`;f.send(JSON.stringify({type:"action_result",actionId:D.actionId,status:"failed",error:v})),r.warn(`[exec] ${D.actionId} (${D.action.type}) \u2192 REFUSED: ${v}`),r.warn(`[exec] update the CLI to clear this: ${ri}`),n({kind:"action",actionId:D.actionId,actionType:D.action.type,ok:!1,error:v});return}p.add(D.actionId);try{let v=await Sc({action:D.action,repo:D.repo,trackerIssueId:D.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:g?()=>g.reportNow():void 0,refreshContextStatus:o?.contextDir?_:void 0,onRunActivity:E}).catch(Q=>({status:"failed",error:Q instanceof Error?Q.message:String(Q)}));D.action.type==="tracker_comment"&&v.status==="done"&&"result"in v&&typeof v.result?.commentId=="string"&&d.add(v.result.commentId),f.send(JSON.stringify({type:"action_result",actionId:D.actionId,...v}));let S=v.status!=="failed",G=!S&&"error"in v?v.error:void 0;S?r.info(`[exec] ${D.actionId} (${D.action.type}) \u2192 done`):r.warn(`[exec] ${D.actionId} (${D.action.type}) \u2192 FAILED: ${G??"?"}`),n({kind:"action",actionId:D.actionId,actionType:D.action.type,ok:S,...G?{error:G}:{}})}finally{p.delete(D.actionId)}}),f.on("close",(b,C)=>{let x=C?.toString("utf-8")??"";if(r.info(`[ws] closed code=${b}${x?` reason=${x}`:""}`),k.stop(),$.stop(),g?.stop(),B(),x==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:b}),!c&&setTimeout(()=>{u=m()},2e3)}),f.on("error",b=>r.warn(`[ws] error: ${b.message}`)),f}return{stop(){c=!0,u.close()}}}async function ni(t,e,r){try{let n=await q(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=Er(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 pg(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?Gr(e.root,o):Se(t.projectId,r.name);if(il(Gr(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await ug().clone(Fo(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 dg(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?Gr(e.root,o):Se(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!il(Gr(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{lg(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 fg(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=Gr(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Ns(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 mg(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 Ve(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 gg(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 Vs(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 ol(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as dl,mkdirSync as fl}from"node:fs";import{dirname as ml}from"node:path";import{simpleGit as Yt}from"simple-git";import{execFileSync as hg}from"node:child_process";import{mkdtempSync as yg,mkdirSync as kg,readFileSync as sl,rmSync as wg,writeFileSync as bg}from"node:fs";import{tmpdir as $g}from"node:os";import{dirname as vg,join as al}from"node:path";function cl(t="codepipe-context"){let e=yg(al($g(),"codepipe-ssh-")),r=al(e,"id_ed25519");try{return hg("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:sl(r,"utf-8"),publicKey:sl(`${r}.pub`,"utf-8").trim()}}finally{wg(e,{recursive:!0,force:!0})}}async function ll(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 ul(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 pl(t,e){kg(vg(t),{recursive:!0});let r=e.endsWith(`
493
541
  `)?e:e+`
494
- `;return km(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}function xm(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 Sm(t,e){return e?.contextWrite?.token?{user:Vr(t),secret:e.contextWrite.token}:t===gr.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===gr.bitbucket?e?.bitbucket?.apiToken?{user:wt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}var Cn=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}};async function Ec(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 Cn))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 In(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await Y(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new Cn(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=Sm(jt(s.cloneUrl),r);if(a){let c=await Rm({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 Tm({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 Rm(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=xm(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(Cc(`${r}/.git`)){let l=Gt(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let p=lo(r);await l.reset(["--hard",`origin/${s}`]),uo(r,p),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Ic(jc(r),{recursive:!0}),await Gt().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await Pc(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 Tm(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=Tc(i,n),a=Rc(e.cloneUrl),c=e.branch;try{if(Cc(`${r}/.git`)){let l=Gt(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 p=lo(r);await l.reset(["--hard",`origin/${c}`]),uo(r,p),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Ic(jc(r),{recursive:!0}),await Gt().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await Gt(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await Pc(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 Pc(t){let e=Gt(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"))}async function Ac(t={profile:void 0}){let{cfg:e,profile:r}=Qr(t.profile),n=D(e.projectId);n&&hr(n),xr(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Sr(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),Rr(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=jr(Uo(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=tn("CLI_LOG",i,o);if(s.enabled){let u=new _t(s);rn(u),console.log(`[log] file logging \u2192 ${u.path} (rotate at ${s.maxBytes}B, keep ${s.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let a=null,c=zr(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 u=jr(Uo(),".codepipe",r?jr("profiles",r,"context"):"context");if(await Po(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await Ec(()=>In({cfg:e,secrets:n,contextDir:u,log:{info:m=>console.log(m),warn:m=>console.warn(m)}}),{log:{warn:m=>console.warn(m)}}),a||await Po(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let m=jr(Uo(),".codepipe",r?jr("profiles",r,"context-config"):"context-config");sn(a.contextDir,m,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=Tn(e,{...a?{workspace:a}:{},onEvent:u=>{u.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))}}),p=!1;function d(u){p||(p=!0,console.log(`
495
- [${u}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>d("SIGINT")),process.on("SIGTERM",()=>d("SIGTERM")),await new Promise(()=>{})}import{hostname as Nm}from"node:os";import{spawnSync as Cm}from"node:child_process";function Im(){try{return Cm("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function _c(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:Im(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}import{homedir as Ft}from"node:os";import{mkdirSync as jm,readFileSync as Nc,writeFileSync as Em,existsSync as Do}from"node:fs";import{dirname as Pm,join as it}from"node:path";Do(".env")&&process.loadEnvFile(".env");function Am(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function Ie(t){let e=F("SANDBOX_CONFIG");if(e)return e;let r=it(Ft(),".codepipe","worker");return t?it(r,"profiles",t,"config.json"):it(r,"config.json")}function Oc(){return it(Ft(),".devpipe-sandbox","config.json")}function jn(){bt(it(Ft(),".devpipe"),it(Ft(),".codepipe")),F("SANDBOX_CONFIG")||bt(it(Ft(),".devpipe-sandbox"),it(Ft(),".codepipe-sandbox"))}function ce(t){let e=Ie(t),r=null;return Do(e)?r=JSON.parse(Nc(e,"utf-8")):!t&&!F("SANDBOX_CONFIG")&&Do(Oc())&&(r=JSON.parse(Nc(Oc(),"utf-8"))),r?(r.planningLane=Am(),r):null}function Uc(t,e){let r=Ie(e);jm(Pm(r),{recursive:!0}),Em(r,JSON.stringify(t,null,2)+`
496
- `,{mode:384})}import _m from"ws";var Ht=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 _m(e)}};async function vt(t){jn();let e=ce(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Ie(t.profile)}.`),process.exit(1));let r=t.name??Nm(),n=_c({projects:t.projects??[],llm:t.llm??null}),o=new Ht(t.hub.replace(/\/$/,"")),i=pn(),s=ue(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});Uc({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 ${Ie(t.profile)}`),console.log(""),console.log(" cred-channel key fingerprint (confirm this on the CLI \u2014 pin-on-register):"),console.log(` ${s}`),console.log("")}import{mkdirSync as Tg,readFileSync as Wo,readdirSync as Cg,writeFileSync as Ig}from"node:fs";import{homedir as jg}from"node:os";import{dirname as Eg,join as zt}from"node:path";import{spawn as Mm}from"node:child_process";import{existsSync as Gm}from"node:fs";import{spawn as Om}from"node:child_process";var Dc=16e3,Lc=5e3,Bc=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),Um="\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C \u0437\u0430\u0432\u0435\u0440\u0448\u0438\u043B \u0434\u0438\u0430\u043B\u043E\u0433. \u0422\u0435\u043F\u0435\u0440\u044C, \u043E\u043F\u0438\u0440\u0430\u044F\u0441\u044C \u043D\u0430 \u0432\u0441\u0451, \u0447\u0442\u043E \u043C\u044B \u043E\u0431\u0441\u0443\u0434\u0438\u043B\u0438, \u043D\u0430\u043F\u0438\u0448\u0438 \u0444\u0430\u0439\u043B DRAFT.md \u0432 \u0442\u0435\u043A\u0443\u0449\u0435\u0439 \u0440\u0430\u0431\u043E\u0447\u0435\u0439 \u0434\u0438\u0440\u0435\u043A\u0442\u043E\u0440\u0438\u0438 \u043F\u043E \u043E\u043F\u0438\u0441\u0430\u043D\u043D\u043E\u043C\u0443 \u043A\u043E\u043D\u0442\u0440\u0430\u043A\u0442\u0443 (\u0441\u0442\u0440\u043E\u043A\u0430 1 \u2014 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A \u226480 \u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432 \u043D\u0430 \u0440\u0443\u0441\u0441\u043A\u043E\u043C, \u0441\u0442\u0440\u043E\u043A\u0430 2 \u043F\u0443\u0441\u0442\u0430\u044F, \u0434\u0430\u043B\u044C\u0448\u0435 \u0442\u0435\u043B\u043E \u043D\u0430 \u0440\u0443\u0441\u0441\u043A\u043E\u043C \u0432 Markdown) \u0438 \u0437\u0430\u0432\u0435\u0440\u0448\u0438 \u0440\u0430\u0431\u043E\u0442\u0443. \u0411\u043E\u043B\u044C\u0448\u0435 \u043D\u0438\u0447\u0435\u0433\u043E \u043D\u0435 \u043F\u0438\u0448\u0438.";function Lo(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function Dm(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 Lm(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function xt(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Bo(t){return JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:t}]}})+`
497
- `}async function Mc(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Ye;let r=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let c of e.addDirs??[])r.push("--add-dir",c);let n=e.onActivity,o=c=>{if(n)try{n(c)}catch{}},i=[],s=null,a=c=>{let l=Date.now(),p=c.type;if(p==="assistant"){let d=c.message;for(let u of d?.content??[]){let m=u.type;if(m==="text"){let f=String(u.text??"").trim();f&&o({ts:l,kind:"text",author:"agent",text:Lo(f,Dc)})}else if(m==="tool_use"){let f=String(u.name??""),y=u.input?.file_path??u.input?.path,w=Dm(y,e.workspaceDir);o({ts:l,kind:"tool",author:"agent",tool:f,...w?{file:w}:{}})}}return}if(p==="user"){let d=c.message;for(let u of d?.content??[])if(u.type==="tool_result"){let m=u.is_error===!0,f=m?Lo(Lm(u.content),200):"";o({ts:l,kind:"tool_result",author:"agent",isError:m,...f?{text:f}:{}})}return}if(p==="result"){s=c;let d=String(c.subtype??"").trim();o({ts:l,kind:"result",author:"agent",...d?{text:d}:{}});return}if(p==="system"){let d=String(c.subtype??"").trim();d&&o({ts:l,kind:"system",author:"agent",text:d})}};return o({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((c,l)=>{let p=Om(t,r,{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,u=!1,m=null,f=()=>{d=!0,p.kill("SIGTERM"),m=setTimeout(()=>p.kill("SIGKILL"),Lc)};e.signal?.addEventListener("abort",f,{once:!0});let y=null,w=()=>{y&&clearTimeout(y),y=setTimeout(()=>{u=!0,console.warn(`[claude:chat] idle for ${Bc}ms \u2014 ending session`),p.kill("SIGTERM"),m=setTimeout(()=>p.kill("SIGKILL"),Lc)},Bc)},k=()=>{m&&clearTimeout(m),y&&clearTimeout(y),e.signal?.removeEventListener("abort",f)},h=!0,$=j=>{if(!(!h||p.stdin.destroyed))try{p.stdin.write(j)}catch{}};$(Bo(e.prompt)),w(),(async()=>{try{for await(let j of e.interactive.inbox){if(d||!h)break;if(w(),j.kind==="user")o({ts:Date.now(),kind:"text",author:"user",text:Lo(j.text,Dc)}),$(Bo(j.text));else{$(Bo(Um)),h=!1;try{p.stdin.end()}catch{}break}}}catch{}})();let S="",B=j=>{let A;try{A=JSON.parse(j)}catch{return}a(A)};p.stdout.on("data",j=>{i.push(j),w(),S+=j;let A;for(;(A=S.indexOf(`
498
- `))!==-1;){let L=S.slice(0,A).trim();S=S.slice(A+1),L&&B(L)}}),p.stderr.on("data",j=>{i.push(j);for(let A of j.split(`
499
- `)){let L=A.trim();L&&console.warn(`[claude:chat:stderr] ${L}`)}}),p.on("error",j=>{k(),l(j)}),p.on("close",j=>{if(k(),d){l(new Ye);return}if(u){l(new Error("chat session ended: idle for too long without a reply"));return}S.trim()&&B(S.trim()),console.log(`[claude:chat] exit code=${j}`),c({artifactPaths:[],log:i.join(""),usage:Bm(s)})})})}function Bm(t){let e=gt();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=xt(r.input_tokens),e.outputTokens=xt(r.output_tokens),e.cacheReadInputTokens=xt(r.cache_read_input_tokens),e.cacheCreationInputTokens=xt(r.cache_creation_input_tokens)),e.totalCostUsd=xt(t.total_cost_usd),e.numTurns=xt(t.num_turns),e.durationMs=xt(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var Kt=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Ye=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},Fm=5e3,Er=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return Mc(this.binary,e);if(e.signal?.aborted)throw new Ye;let r=["-p",e.prompt,"--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let f of e.addDirs??[])r.push("--add-dir",f);let n=[],o=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,p=f=>{if(f){if(f.type==="result"){i=f;return}if(f.type==="rate_limit_event"){let y=qm(f.rate_limit_info);y&&(!l||y.utilization>l.utilization)&&(l=y);return}if(f.type==="assistant"){let y=f.message;typeof y?.model=="string"&&(c=y.model);let w=y?.usage;w&&(a+=1,s.input+=pe(w.input_tokens),s.output+=pe(w.output_tokens),s.cacheRead+=pe(w.cache_read_input_tokens),s.cacheCreate+=pe(w.cache_creation_input_tokens))}}},d=e.role,u=e.onActivity,m=f=>{if(u)for(let y of Vm(f,e.workspaceDir))try{u(y)}catch{}};return u?.({ts:Date.now(),kind:"start",text:`${d} job started`}),console.log(`[claude] spawn ${this.binary} role=${d}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((f,y)=>{let w=Mm(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 k=!1,h=null,$=()=>{k=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${d}`),w.kill("SIGTERM"),h=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),w.kill("SIGKILL")},Fm)};e.signal?.addEventListener("abort",$,{once:!0});let S=()=>{h&&clearTimeout(h),e.signal?.removeEventListener("abort",$)},B="";w.stdout.on("data",j=>{n.push(j),B+=j;let A;for(;(A=B.indexOf(`
500
- `))!==-1;){let L=B.slice(0,A).trim();if(B=B.slice(A+1),L){let P=Gc(L);p(P),P&&m(P)}}}),w.stderr.on("data",j=>{n.push(j),o.push(j);for(let A of j.split(`
501
- `)){let L=A.trim();L&&console.warn(`[claude:stderr] ${L}`)}}),w.on("error",j=>{S(),y(j)}),w.on("close",j=>{if(S(),k){y(new Ye);return}if(B.trim()){let L=Gc(B.trim());p(L),L&&m(L)}let A=i?.is_error===!0;if(j!==0||A){let L=typeof i?.api_error_status=="number"?i.api_error_status:void 0,P=typeof i?.subtype=="string"?i.subtype:void 0,g=typeof i?.result=="string"?i.result:void 0;y(new Kt(Hm(j,i,o.join("")),{code:j,apiErrorStatus:L,subtype:P,resultText:g,retryAfterMs:Km(i)}));return}console.log("[claude] exit code=0"),f({artifactPaths:[],log:n.join(""),usage:Ym(i,s,a,c),...l?{rateLimit:l}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(n=>n.includes("/")&&Gm(n))}};function Gc(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: ${st(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=Wm(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=Hc(o.content);console.log(`[claude] tool_result (error)${i?`: ${st(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)} ${st(JSON.stringify(e),200)}`),e}function Hm(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(st(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(st(r.trim().split(`
542
+ `;return bg(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}function xg(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 Sg(t,e){return e?.contextWrite?.token?{user:un(t),secret:e.contextWrite.token}:t===xr.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===xr.bitbucket?e?.bitbucket?.apiToken?{user:vt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}var Hn=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}};async function gl(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 Hn))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 Kn(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await q(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new Hn(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=Sg(Nt(s.cloneUrl),r);if(a){let c=await Rg({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 Tg({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 Rg(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=xg(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(dl(`${r}/.git`)){let l=Yt(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let p=To(r);await l.reset(["--hard",`origin/${s}`]),Io(r,p),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else fl(ml(r),{recursive:!0}),await Yt().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await hl(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 Tg(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=pl(i,n),a=ul(e.cloneUrl),c=e.branch;try{if(dl(`${r}/.git`)){let l=Yt(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 p=To(r);await l.reset(["--hard",`origin/${c}`]),Io(r,p),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else fl(ml(r),{recursive:!0}),await Yt().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await Yt(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await hl(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 hl(t){let e=Yt(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"))}async function yl(t={profile:void 0}){let{cfg:e,profile:r}=mn(t.profile),n=L(e.projectId);n&&Sr(n),Nr(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Or(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),Dr(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=Fr(oi(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=yn("CLI_LOG",i,o);if(s.enabled){let u=new Lt(s);kn(u),console.log(`[log] file logging \u2192 ${u.path} (rotate at ${s.maxBytes}B, keep ${s.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let a=null,c=dn(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 u=Fr(oi(),".codepipe",r?Fr("profiles",r,"context"):"context");if(await Zo(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await gl(()=>Kn({cfg:e,secrets:n,contextDir:u,log:{info:m=>console.log(m),warn:m=>console.warn(m)}}),{log:{warn:m=>console.warn(m)}}),a||await Zo(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let m=Fr(oi(),".codepipe",r?Fr("profiles",r,"context-config"):"context-config");$n(a.contextDir,m,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=Fn(e,{...a?{workspace:a}:{},onEvent:u=>{u.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))}}),p=!1;function d(u){p||(p=!0,console.log(`
543
+ [${u}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>d("SIGINT")),process.on("SIGTERM",()=>d("SIGTERM")),await new Promise(()=>{})}import{hostname as Ng}from"node:os";import{spawnSync as Ig}from"node:child_process";function Cg(){try{return Ig("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function kl(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:Cg(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}import{homedir as qt}from"node:os";import{mkdirSync as Eg,readFileSync as wl,writeFileSync as Pg,existsSync as ii}from"node:fs";import{dirname as jg,join as ut}from"node:path";ii(".env")&&process.loadEnvFile(".env");function Ag(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function je(t){let e=F("SANDBOX_CONFIG");if(e)return e;let r=ut(qt(),".codepipe","worker");return t?ut(r,"profiles",t,"config.json"):ut(r,"config.json")}function bl(){return ut(qt(),".devpipe-sandbox","config.json")}function Wn(){xt(ut(qt(),".devpipe"),ut(qt(),".codepipe")),F("SANDBOX_CONFIG")||xt(ut(qt(),".devpipe-sandbox"),ut(qt(),".codepipe-sandbox"))}function ue(t){let e=je(t),r=null;return ii(e)?r=JSON.parse(wl(e,"utf-8")):!t&&!F("SANDBOX_CONFIG")&&ii(bl())&&(r=JSON.parse(wl(bl(),"utf-8"))),r?(r.planningLane=Ag(),r):null}function $l(t,e){let r=je(e);Eg(jg(r),{recursive:!0}),Pg(r,JSON.stringify(t,null,2)+`
544
+ `,{mode:384})}import _g from"ws";var Vt=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 _g(e)}};async function Tt(t){Wn();let e=ue(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${je(t.profile)}.`),process.exit(1));let r=t.name??Ng(),n=kl({projects:t.projects??[],llm:t.llm??null}),o=new Vt(t.hub.replace(/\/$/,"")),i=Cn(),s=de(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});$l({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 ${je(t.profile)}`),console.log(""),console.log(" cred-channel key fingerprint (confirm this on the CLI \u2014 pin-on-register):"),console.log(` ${s}`),console.log("")}import{mkdirSync as Th,readFileSync as fi,readdirSync as Ih,writeFileSync as Ch}from"node:fs";import{homedir as Eh}from"node:os";import{dirname as Ph,join as tr}from"node:path";import{spawn as Mg}from"node:child_process";import{existsSync as Gg}from"node:fs";import{spawn as Og}from"node:child_process";var vl=16e3,xl=5e3,Sl=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),Dg="\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C \u0437\u0430\u0432\u0435\u0440\u0448\u0438\u043B \u0434\u0438\u0430\u043B\u043E\u0433. \u0422\u0435\u043F\u0435\u0440\u044C, \u043E\u043F\u0438\u0440\u0430\u044F\u0441\u044C \u043D\u0430 \u0432\u0441\u0451, \u0447\u0442\u043E \u043C\u044B \u043E\u0431\u0441\u0443\u0434\u0438\u043B\u0438, \u043D\u0430\u043F\u0438\u0448\u0438 \u0444\u0430\u0439\u043B DRAFT.md \u0432 \u0442\u0435\u043A\u0443\u0449\u0435\u0439 \u0440\u0430\u0431\u043E\u0447\u0435\u0439 \u0434\u0438\u0440\u0435\u043A\u0442\u043E\u0440\u0438\u0438 \u043F\u043E \u043E\u043F\u0438\u0441\u0430\u043D\u043D\u043E\u043C\u0443 \u043A\u043E\u043D\u0442\u0440\u0430\u043A\u0442\u0443 (\u0441\u0442\u0440\u043E\u043A\u0430 1 \u2014 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A \u226480 \u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432 \u043D\u0430 \u0440\u0443\u0441\u0441\u043A\u043E\u043C, \u0441\u0442\u0440\u043E\u043A\u0430 2 \u043F\u0443\u0441\u0442\u0430\u044F, \u0434\u0430\u043B\u044C\u0448\u0435 \u0442\u0435\u043B\u043E \u043D\u0430 \u0440\u0443\u0441\u0441\u043A\u043E\u043C \u0432 Markdown) \u0438 \u0437\u0430\u0432\u0435\u0440\u0448\u0438 \u0440\u0430\u0431\u043E\u0442\u0443. \u0411\u043E\u043B\u044C\u0448\u0435 \u043D\u0438\u0447\u0435\u0433\u043E \u043D\u0435 \u043F\u0438\u0448\u0438.";function si(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function Ug(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 Lg(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function It(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function ai(t){return JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:t}]}})+`
545
+ `}async function Rl(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Xe;let r=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let c of e.addDirs??[])r.push("--add-dir",c);let n=e.onActivity,o=c=>{if(n)try{n(c)}catch{}},i=[],s=null,a=c=>{let l=Date.now(),p=c.type;if(p==="assistant"){let d=c.message;for(let u of d?.content??[]){let m=u.type;if(m==="text"){let f=String(u.text??"").trim();f&&o({ts:l,kind:"text",author:"agent",text:si(f,vl)})}else if(m==="tool_use"){let f=String(u.name??""),y=u.input?.file_path??u.input?.path,k=Ug(y,e.workspaceDir);o({ts:l,kind:"tool",author:"agent",tool:f,...k?{file:k}:{}})}}return}if(p==="user"){let d=c.message;for(let u of d?.content??[])if(u.type==="tool_result"){let m=u.is_error===!0,f=m?si(Lg(u.content),200):"";o({ts:l,kind:"tool_result",author:"agent",isError:m,...f?{text:f}:{}})}return}if(p==="result"){s=c;let d=String(c.subtype??"").trim();o({ts:l,kind:"result",author:"agent",...d?{text:d}:{}});return}if(p==="system"){let d=String(c.subtype??"").trim();d&&o({ts:l,kind:"system",author:"agent",text:d})}};return o({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((c,l)=>{let p=Og(t,r,{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,u=!1,m=null,f=()=>{d=!0,p.kill("SIGTERM"),m=setTimeout(()=>p.kill("SIGKILL"),xl)};e.signal?.addEventListener("abort",f,{once:!0});let y=null,k=()=>{y&&clearTimeout(y),y=setTimeout(()=>{u=!0,console.warn(`[claude:chat] idle for ${Sl}ms \u2014 ending session`),p.kill("SIGTERM"),m=setTimeout(()=>p.kill("SIGKILL"),xl)},Sl)},$=()=>{m&&clearTimeout(m),y&&clearTimeout(y),e.signal?.removeEventListener("abort",f)},h=!0,w=R=>{if(!(!h||p.stdin.destroyed))try{p.stdin.write(R)}catch{}};w(ai(e.prompt)),k(),(async()=>{try{for await(let R of e.interactive.inbox){if(d||!h)break;if(k(),R.kind==="user")o({ts:Date.now(),kind:"text",author:"user",text:si(R.text,vl)}),w(ai(R.text));else{w(ai(Dg)),h=!1;try{p.stdin.end()}catch{}break}}}catch{}})();let I="",B=R=>{let j;try{j=JSON.parse(R)}catch{return}a(j)};p.stdout.on("data",R=>{i.push(R),k(),I+=R;let j;for(;(j=I.indexOf(`
546
+ `))!==-1;){let M=I.slice(0,j).trim();I=I.slice(j+1),M&&B(M)}}),p.stderr.on("data",R=>{i.push(R);for(let j of R.split(`
547
+ `)){let M=j.trim();M&&console.warn(`[claude:chat:stderr] ${M}`)}}),p.on("error",R=>{$(),l(R)}),p.on("close",R=>{if($(),d){l(new Xe);return}if(u){l(new Error("chat session ended: idle for too long without a reply"));return}I.trim()&&B(I.trim()),console.log(`[claude:chat] exit code=${R}`),c({artifactPaths:[],log:i.join(""),usage:Bg(s)})})})}function Bg(t){let e=wt();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=It(r.input_tokens),e.outputTokens=It(r.output_tokens),e.cacheReadInputTokens=It(r.cache_read_input_tokens),e.cacheCreationInputTokens=It(r.cache_creation_input_tokens)),e.totalCostUsd=It(t.total_cost_usd),e.numTurns=It(t.num_turns),e.durationMs=It(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var Jt=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Xe=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},Fg=5e3,Hr=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return Rl(this.binary,e);if(e.signal?.aborted)throw new Xe;let r=["-p",e.prompt,"--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let f of e.addDirs??[])r.push("--add-dir",f);let n=[],o=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,p=f=>{if(f){if(f.type==="result"){i=f;return}if(f.type==="rate_limit_event"){let y=Yg(f.rate_limit_info);y&&(!l||y.utilization>l.utilization)&&(l=y);return}if(f.type==="assistant"){let y=f.message;typeof y?.model=="string"&&(c=y.model);let k=y?.usage;k&&(a+=1,s.input+=fe(k.input_tokens),s.output+=fe(k.output_tokens),s.cacheRead+=fe(k.cache_read_input_tokens),s.cacheCreate+=fe(k.cache_creation_input_tokens))}}},d=e.role,u=e.onActivity,m=f=>{if(u)for(let y of Vg(f,e.workspaceDir))try{u(y)}catch{}};return u?.({ts:Date.now(),kind:"start",text:`${d} job started`}),console.log(`[claude] spawn ${this.binary} role=${d}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((f,y)=>{let k=Mg(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"}});k.stdout.setEncoding("utf-8"),k.stderr.setEncoding("utf-8");let $=!1,h=null,w=()=>{$=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${d}`),k.kill("SIGTERM"),h=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),k.kill("SIGKILL")},Fg)};e.signal?.addEventListener("abort",w,{once:!0});let I=()=>{h&&clearTimeout(h),e.signal?.removeEventListener("abort",w)},B="";k.stdout.on("data",R=>{n.push(R),B+=R;let j;for(;(j=B.indexOf(`
548
+ `))!==-1;){let M=B.slice(0,j).trim();if(B=B.slice(j+1),M){let E=Tl(M);p(E),E&&m(E)}}}),k.stderr.on("data",R=>{n.push(R),o.push(R);for(let j of R.split(`
549
+ `)){let M=j.trim();M&&console.warn(`[claude:stderr] ${M}`)}}),k.on("error",R=>{I(),y(R)}),k.on("close",R=>{if(I(),$){y(new Xe);return}if(B.trim()){let M=Tl(B.trim());p(M),M&&m(M)}let j=i?.is_error===!0;if(R!==0||j){let M=typeof i?.api_error_status=="number"?i.api_error_status:void 0,E=typeof i?.subtype=="string"?i.subtype:void 0,g=typeof i?.result=="string"?i.result:void 0;y(new Jt(Hg(R,i,o.join("")),{code:R,apiErrorStatus:M,subtype:E,resultText:g,retryAfterMs:Kg(i)}));return}console.log("[claude] exit code=0"),f({artifactPaths:[],log:n.join(""),usage:qg(i,s,a,c),...l?{rateLimit:l}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(n=>n.includes("/")&&Gg(n))}};function Tl(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: ${pt(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=Wg(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=Cl(o.content);console.log(`[claude] tool_result (error)${i?`: ${pt(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)} ${pt(JSON.stringify(e),200)}`),e}function Hg(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(pt(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(pt(r.trim().split(`
502
550
  `).slice(-5).join(`
503
- `),500)),n.join(" \u2014 ")}function Km(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 Hc(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Wm(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=${st(r,80)}`}return""}function st(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function pe(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function qm(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=pe(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:pe(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 Ym(t,e,r,n){let o=gt(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=pe(i.input_tokens),o.outputTokens=pe(i.output_tokens),o.cacheReadInputTokens=pe(i.cache_read_input_tokens),o.cacheCreationInputTokens=pe(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=pe(t?.total_cost_usd),o.numTurns=t&&pe(t.num_turns)>0?pe(t.num_turns):r,o.durationMs=pe(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}var Fc=200;function Vm(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:st(c,Fc)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,p=l?.file_path??l?.path??l?.notebook_path,d=Jm(p,e);i.push({ts:r,kind:"tool",tool:c,...d?{file:d}:{}})}}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?st(Hc(s.content),Fc):"";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 Jm(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}import{mkdirSync as zm,writeFileSync as Wt}from"node:fs";import{dirname as Xm,join as qt}from"node:path";function Kc(t,e,r){let n=qt(t,e);zm(Xm(n),{recursive:!0}),Wt(n,r)}var Pr=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=Qm(n,o,i);Wt(qt(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Wt(qt(e.workspaceDir,"SOLUTION.md"),Zm(n,o,i,a)),s.push("SOLUTION.md"),Wt(qt(e.workspaceDir,"QUESTIONS.md"),eg(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Kc(e.workspaceDir,"changes/sample.patch",tg(n,o,a)),s.push("changes/sample.patch"),Kc(e.workspaceDir,"diff-summary.md",rg(n,o,a)),s.push("diff-summary.md")}else e.role==="rework"&&(Wt(qt(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
504
- `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:gt()}}async runInteractive(e){let r=e.onActivity,n=i=>{r?.({ts:Date.now(),kind:"text",author:"agent",text:i}),r?.({ts:Date.now(),kind:"result",author:"agent",text:"success"})};r?.({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),n("\u041F\u0440\u0438\u0432\u0435\u0442! \u041E\u043F\u0438\u0448\u0438\u0442\u0435 \u0437\u0430\u0434\u0430\u0447\u0443, \u043A\u043E\u0442\u043E\u0440\u0443\u044E \u0445\u043E\u0442\u0438\u0442\u0435 \u0441\u0444\u043E\u0440\u043C\u0443\u043B\u0438\u0440\u043E\u0432\u0430\u0442\u044C.");let o="\u0427\u0435\u0440\u043D\u043E\u0432\u0438\u043A \u0438\u0437 \u0447\u0430\u0442\u0430";for await(let i of e.interactive.inbox){if(e.signal?.aborted)throw new Ye;if(i.kind==="user")r?.({ts:Date.now(),kind:"text",author:"user",text:i.text}),i.text.trim()&&(o=i.text.trim().slice(0,80)),n(`\u041F\u043E\u043D\u044F\u043B: **${i.text.trim()}**. \u0427\u0442\u043E-\u043D\u0438\u0431\u0443\u0434\u044C \u0435\u0449\u0451 \u0443\u0442\u043E\u0447\u043D\u0438\u0442\u044C?`);else break}return Wt(qt(e.workspaceDir,"DRAFT.md"),`${o}
551
+ `),500)),n.join(" \u2014 ")}function Kg(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 Cl(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Wg(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=${pt(r,80)}`}return""}function pt(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function fe(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Yg(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=fe(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:fe(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 qg(t,e,r,n){let o=wt(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=fe(i.input_tokens),o.outputTokens=fe(i.output_tokens),o.cacheReadInputTokens=fe(i.cache_read_input_tokens),o.cacheCreationInputTokens=fe(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=fe(t?.total_cost_usd),o.numTurns=t&&fe(t.num_turns)>0?fe(t.num_turns):r,o.durationMs=fe(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}var Il=200;function Vg(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:pt(c,Il)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,p=l?.file_path??l?.path??l?.notebook_path,d=Jg(p,e);i.push({ts:r,kind:"tool",tool:c,...d?{file:d}:{}})}}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?pt(Cl(s.content),Il):"";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 Jg(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}import{mkdirSync as zg,writeFileSync as zt}from"node:fs";import{dirname as Xg,join as Xt}from"node:path";function El(t,e,r){let n=Xt(t,e);zg(Xg(n),{recursive:!0}),zt(n,r)}var Kr=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=Qg(n,o,i);zt(Xt(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;zt(Xt(e.workspaceDir,"SOLUTION.md"),Zg(n,o,i,a)),s.push("SOLUTION.md"),zt(Xt(e.workspaceDir,"QUESTIONS.md"),eh(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;El(e.workspaceDir,"changes/sample.patch",th(n,o,a)),s.push("changes/sample.patch"),El(e.workspaceDir,"diff-summary.md",rh(n,o,a)),s.push("diff-summary.md")}else e.role==="rework"&&(zt(Xt(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
552
+ `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:wt()}}async runInteractive(e){let r=e.onActivity,n=i=>{r?.({ts:Date.now(),kind:"text",author:"agent",text:i}),r?.({ts:Date.now(),kind:"result",author:"agent",text:"success"})};r?.({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),n("\u041F\u0440\u0438\u0432\u0435\u0442! \u041E\u043F\u0438\u0448\u0438\u0442\u0435 \u0437\u0430\u0434\u0430\u0447\u0443, \u043A\u043E\u0442\u043E\u0440\u0443\u044E \u0445\u043E\u0442\u0438\u0442\u0435 \u0441\u0444\u043E\u0440\u043C\u0443\u043B\u0438\u0440\u043E\u0432\u0430\u0442\u044C.");let o="\u0427\u0435\u0440\u043D\u043E\u0432\u0438\u043A \u0438\u0437 \u0447\u0430\u0442\u0430";for await(let i of e.interactive.inbox){if(e.signal?.aborted)throw new Xe;if(i.kind==="user")r?.({ts:Date.now(),kind:"text",author:"user",text:i.text}),i.text.trim()&&(o=i.text.trim().slice(0,80)),n(`\u041F\u043E\u043D\u044F\u043B: **${i.text.trim()}**. \u0427\u0442\u043E-\u043D\u0438\u0431\u0443\u0434\u044C \u0435\u0449\u0451 \u0443\u0442\u043E\u0447\u043D\u0438\u0442\u044C?`);else break}return zt(Xt(e.workspaceDir,"DRAFT.md"),`${o}
505
553
 
506
554
  \u0421\u0444\u043E\u0440\u043C\u0438\u0440\u043E\u0432\u0430\u043D\u043E \u0432 \u0438\u043D\u0442\u0435\u0440\u0430\u043A\u0442\u0438\u0432\u043D\u043E\u043C \u0447\u0430\u0442\u0435 (mock runner).
507
- `),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:gt()}}};function Qm(t,e,r){return`# ${t} \u2014 Estimate
555
+ `),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:wt()}}};function Qg(t,e,r){return`# ${t} \u2014 Estimate
508
556
 
509
557
  **Title:** ${e}
510
558
 
@@ -525,7 +573,7 @@ production-grade estimates.)
525
573
  ${r.split(`
526
574
  `).slice(0,8).join(`
527
575
  `).trim()||"(empty)"}
528
- `}function Zm(t,e,r,n){let o=n?`
576
+ `}function Zg(t,e,r,n){let o=n?`
529
577
  ## Reviewer rework instruction
530
578
 
531
579
  > ${n.split(`
@@ -554,10 +602,10 @@ TBD (mock runner does not yet inspect project code).
554
602
  ${r.split(`
555
603
  `).slice(0,8).join(`
556
604
  `).trim()||"(empty)"}
557
- `}function eg(t){return`# ${t} \u2014 Open questions
605
+ `}function eh(t){return`# ${t} \u2014 Open questions
558
606
 
559
607
  (none \u2014 mock runner did not surface ambiguities.)
560
- `}function tg(t,e,r){let n=r?` (rework: ${r.split(`
608
+ `}function th(t,e,r){let n=r?` (rework: ${r.split(`
561
609
  `)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
562
610
  index 0000000..1111111 100644
563
611
  --- a/CHANGELOG.md
@@ -568,7 +616,7 @@ index 0000000..1111111 100644
568
616
  +- mock-runner placeholder change for slice 5 testing.
569
617
  +
570
618
  # Changelog
571
- `}function rg(t,e,r){return`# ${t} \u2014 Diff summary
619
+ `}function rh(t,e,r){return`# ${t} \u2014 Diff summary
572
620
 
573
621
  **Title:** ${e}
574
622
  ${r?`
@@ -579,98 +627,98 @@ ${r?`
579
627
  - \`CHANGELOG.md\` \u2014 added entry for ${t}.
580
628
 
581
629
  (Mock-runner output. Replace with claude-headless for production patches.)
582
- `}function Wc(t){switch(t){case"mock":return new Pr;case"claude-headless":return new Er;default:return null}}function Vc(t=process.env){return{maxAttempts:En(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:En(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:En(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:En(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}var ng=new Set([429,500,502,503,529]),qc=/(ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|EPIPE|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,og=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,ig=new Set(["error_max_turns"]);function sg(t){if(t instanceof Kt){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return og.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&ig.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:ng.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:qc.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 qc.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}var Yc=/(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;function Jc(t){if(t instanceof Kt){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&Yc.test(n)}let e=t instanceof Error?t.message:String(t);return Yc.test(e)}function ag(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 zc(t,e,r){let n=r.sleep??(s=>new Promise(a=>setTimeout(a,s))),o=Date.now()+r.policy.totalBudgetMs,i="";for(let s=1;;s++)try{return await t.run(e)}catch(a){i=a instanceof Error?a.message:String(a);let c=sg(a),l=s>=r.policy.maxAttempts;if(!c.retryable||l||r.aborted())throw s>1?new Error(`agent failed after ${s} attempts: ${i}`):a;let p=ag(s,r.policy,c.retryAfterMs);if(Date.now()+p>o)throw new Error(`agent failed after ${s} attempts (retry budget exhausted): ${i}`);console.warn(`[job] ${r.jobId} agent attempt ${s}/${r.policy.maxAttempts} failed (retryable: ${c.reason}) \u2014 cleaning workspace, backoff ${p}ms`),await r.onBeforeRetry(),await n(p)}}function En(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}import{mkdtempSync as cg,rmSync as lg,writeFileSync as Xc}from"node:fs";import{tmpdir as ug}from"node:os";import{join as Mo}from"node:path";function Pn(t){return`[url "https://${t}/"]
630
+ `}function Pl(t){switch(t){case"mock":return new Kr;case"claude-headless":return new Hr;default:return null}}function _l(t=process.env){return{maxAttempts:Yn(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:Yn(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:Yn(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:Yn(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}var nh=new Set([429,500,502,503,529]),jl=/(ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|EPIPE|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,oh=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,ih=new Set(["error_max_turns"]);function sh(t){if(t instanceof Jt){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return oh.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&ih.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:nh.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:jl.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 jl.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}var Al=/(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;function Nl(t){if(t instanceof Jt){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&Al.test(n)}let e=t instanceof Error?t.message:String(t);return Al.test(e)}function ah(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 Ol(t,e,r){let n=r.sleep??(s=>new Promise(a=>setTimeout(a,s))),o=Date.now()+r.policy.totalBudgetMs,i="";for(let s=1;;s++)try{return await t.run(e)}catch(a){i=a instanceof Error?a.message:String(a);let c=sh(a),l=s>=r.policy.maxAttempts;if(!c.retryable||l||r.aborted())throw s>1?new Error(`agent failed after ${s} attempts: ${i}`):a;let p=ah(s,r.policy,c.retryAfterMs);if(Date.now()+p>o)throw new Error(`agent failed after ${s} attempts (retry budget exhausted): ${i}`);console.warn(`[job] ${r.jobId} agent attempt ${s}/${r.policy.maxAttempts} failed (retryable: ${c.reason}) \u2014 cleaning workspace, backoff ${p}ms`),await r.onBeforeRetry(),await n(p)}}function Yn(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}import{mkdtempSync as ch,rmSync as lh,writeFileSync as Dl}from"node:fs";import{tmpdir as uh}from"node:os";import{join as ci}from"node:path";function qn(t){return`[url "https://${t}/"]
583
631
  insteadOf = git@${t}:
584
632
  insteadOf = ssh://git@${t}/
585
- `}var pg=Pn("github.com"),dg=Pn("bitbucket.org"),fg=Pn("gitlab.com");function Qc(t,e){if(t.length===0)return null;let r=cg(Mo(ug(),"devpipe-gitcreds-")),n=Mo(r,"credentials"),o=Mo(r,"gitconfig");return Xc(n,t.join(`
633
+ `}var ph=qn("github.com"),dh=qn("bitbucket.org"),fh=qn("gitlab.com");function Ul(t,e){if(t.length===0)return null;let r=ch(ci(uh(),"devpipe-gitcreds-")),n=ci(r,"credentials"),o=ci(r,"gitconfig");return Dl(n,t.join(`
586
634
  `)+`
587
- `,{mode:384}),Xc(o,`[credential]
635
+ `,{mode:384}),Dl(o,`[credential]
588
636
  helper = store --file=${n}
589
- `+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{lg(r,{recursive:!0,force:!0})}catch{}}}}function Go(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(pg)),t.bitbucket?.apiToken&&(e.push(`https://${wt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(dg)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(fg)),Qc(e,r)}function Zc(t,e){if(t.contextWrite?.token){let r=jt(e)??"github.com",n=Vr(r);return Qc([`https://${n}:${t.contextWrite.token}@${r}`],[Pn(r)])}return Go(t)}import{spawn as tl}from"node:child_process";import{existsSync as An,mkdirSync as _n,readFileSync as mg,rmSync as Fo,symlinkSync as gg}from"node:fs";import{homedir as hg}from"node:os";import{dirname as Nn,join as St}from"node:path";function rl(){return St(hg(),".codepipe-sandbox","repos")}var Yt=new Map;function nl(t,e){let n=(Yt.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{Yt.get(t)===o&&Yt.delete(t)},()=>{Yt.get(t)===o&&Yt.delete(t)});return Yt.set(t,o),n}function el(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 yg(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 ol(t,e,r,n,o){let i=async c=>{await X(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await X(t,["reset","--hard",`origin/${c}`],o),await X(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!el(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{An(t)&&Fo(t,{recursive:!0,force:!0}),_n(Nn(t),{recursive:!0});try{return await X(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!el(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),An(t)&&Fo(t,{recursive:!0,force:!0}),_n(Nn(t),{recursive:!0}),await X(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(An(St(t,".git")))try{return await s()}catch(c){if(!yg(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 il(t){await X(t.workspacePath,["reset","--hard",t.baseSha]),await X(t.workspacePath,["clean","-fdx"])}var Vt="CodePipe Agent",Jt="codepipe@codepartner.ee";async function sl(t,e){let r=t.workspacePath;await X(r,["add","-A"]);let n=(await se(r,["write-tree"])).trim(),o=(await se(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:Vt,GIT_AUTHOR_EMAIL:Jt,GIT_COMMITTER_NAME:Vt,GIT_COMMITTER_EMAIL:Jt};return(await se(r,["commit-tree",n,"-m",e],i)).trim()}async function al(t,e,r,n,o){try{await X(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw jt(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 cl(t,e){return se(t.workspacePath,["diff","--binary",t.baseSha,e])}async function ll(t,e,r,n,o){await X(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await X(t.workspacePath,["checkout","--force",r])}async function ul(t,e,r,n,o,i){let s=t.workspacePath;await X(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await se(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=f=>se(s,["rev-parse","-q","--verify",`${f}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await se(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await X(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(y=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(y)}`)}),await c(n)||await X(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:Vt,GIT_AUTHOR_EMAIL:Jt,GIT_COMMITTER_NAME:Vt,GIT_COMMITTER_EMAIL:Jt},p=(await se(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),d=(await se(s,["commit-tree",p,"-p",n,"-m","delivery"],l)).trim();await X(s,["cherry-pick","--quit"],l).catch(()=>{});let u=null;try{await X(s,["cherry-pick","--no-commit",d],l)}catch(f){u=f instanceof Error?f.message:String(f)}let m=(await se(s,["diff","--name-only","--diff-filter=U"])).split(`
590
- `).map(f=>f.trim()).filter(f=>f.length>0);if(u&&m.length===0)throw await X(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${u}`);return m}async function Ho(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:Vt,GIT_AUTHOR_EMAIL:Jt,GIT_COMMITTER_NAME:Vt,GIT_COMMITTER_EMAIL:Jt};(await se(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await X(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 X(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await X(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await se(n,["diff","--name-only","--diff-filter=U"])).split(`
591
- `).map(l=>l.trim()).filter(l=>l.length>0),c=await se(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}function X(t,e,r){return new Promise((n,o)=>{let i=tl("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}):
592
- ${s.join("").trim()||"(no stderr)"}`))})})}function se(t,e,r){return new Promise((n,o)=>{let i=tl("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}):
593
- ${a.join("").trim()||"(no stderr)"}`))})})}function pl(t,e){An(t)&&Fo(t,{recursive:!0,force:!0}),_n(Nn(t),{recursive:!0}),gg(e,t,"dir")}async function dl(t,e,r){await X(t,["worktree","prune"]).catch(()=>{}),_n(Nn(r),{recursive:!0}),await X(t,["worktree","add","--detach",r,`origin/${e}`])}async function fl(t,e,r,n="worktree",o){return r.length===0?[]:nl(e,async()=>{let i=[];for(let s of r){let a=St(rl(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await ol(a,s.cloneUrl,s.ref,s.defaultBranch,o)}catch(d){throw new Error(`failed to materialize project repo "${s.name}" (${s.cloneUrl}): `+(d instanceof Error?d.message:String(d)))}let l=(await se(a,["rev-parse","HEAD"])).trim(),p=St(t,"code",s.name);n==="direct"?(pl(p,a),console.log(`[git] code: linked ${p} \u2192 ${a} @ ${l.slice(0,10)}`)):(await dl(a,c,p),console.log(`[git] code: worktree ${p} \u2190 ${a} @ ${l.slice(0,10)}`)),i.push({name:s.name,workspacePath:p,cachePath:a,ref:c,baseSha:l})}return i})}async function ml(t,e,r,n="worktree",o){if(!r||!r.cloneUrl)return null;let i=r;return nl(e,async()=>{let s=St(rl(),e,"_context");console.log(`[git] context: ensure ${i.cloneUrl} @ ${i.ref} \u2192 ${s}`);try{await ol(s,i.cloneUrl,i.ref,void 0,o)}catch(l){throw new Error(`failed to materialize context repo (${i.cloneUrl}): `+(l instanceof Error?l.message:String(l)))}let a=St(t,"context");n==="direct"?(pl(a,s),console.log(`[git] context: linked ${a} \u2192 ${s}`)):(await dl(s,i.ref,a),console.log(`[git] context: worktree ${a} \u2190 ${s}`));let c=(await se(s,["rev-parse","HEAD"])).trim();return{workspacePath:a,cachePath:s,baseSha:c}})}async function gl(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await X(r,["add","-A",...n]).catch(()=>{});let o;try{o=await se(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
594
- `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=mg(St(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as wg}from"node:fs";import{join as bg}from"node:path";var Ko=8*1024,at=class extends Error{},Ar="meta/build-result.json";function hl(t){let e=bg(t,Ar),r;try{r=wg(e,"utf-8")}catch{throw new at(`BUILD produced no ${Ar} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(p){throw new at(`${Ar} is not valid JSON: ${p instanceof Error?p.message:String(p)}`)}if(!n||typeof n!="object")throw new at(`${Ar} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new at(`${Ar}: "ok" must be a boolean`);let i=o.ok,a=(Array.isArray(o.steps)?o.steps:[]).flatMap(p=>{if(!p||typeof p!="object")return[];let d=p,u=typeof d.name=="string"?d.name:null,m=typeof d.exitCode=="number"?d.exitCode:null;if(u===null||m===null)return[];let f={name:u,exitCode:m};return typeof d.durationMs=="number"&&(f.durationMs=d.durationMs),[f]}),c=typeof o.logTail=="string"?kg(o.logTail):"",l={ok:i,steps:a,logTail:c};if(typeof o.failedStep=="string"&&o.failedStep)l.failedStep=o.failedStep;else if(!i){let p=a.find(d=>d.exitCode!==0);p&&(l.failedStep=p.name)}return l}function kg(t){let e=Buffer.from(t,"utf-8");return e.length<=Ko?t:`\u2026 [${e.length-Ko} bytes elided] \u2026
595
- `+e.subarray(e.length-Ko).toString("utf-8")}import{lstatSync as $g,mkdtempSync as vg,readFileSync as xg,readdirSync as wl,rmSync as yl}from"node:fs";import{tmpdir as Sg}from"node:os";import{join as On,relative as Rg}from"node:path";var bl=new Set(["code","context"]);function kl(t){let e=vg(On(Sg(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>yl(e,{recursive:!0,force:!0}),listFiles:()=>$l(e,e),readFile:r=>xg(On(e,r),"utf-8"),clean:()=>{for(let r of wl(e))bl.has(r)||yl(On(e,r),{recursive:!0,force:!0})}}}function $l(t,e){let r=[];for(let n of wl(e)){let o=On(e,n),i=$g(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&bl.has(n))continue;r.push(...$l(t,o))}else r.push(Rg(t,o))}return r}var Un=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Pg=new Set(["implement","resolve-conflict"]);function Ag(t){let e=Buffer.from(t,"utf-8");if(e.length<=Un)return t;let r=Math.floor(Un/4),n=Un-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}
637
+ `+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{lh(r,{recursive:!0,force:!0})}catch{}}}}function li(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(ph)),t.bitbucket?.apiToken&&(e.push(`https://${vt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(dh)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(fh)),Ul(e,r)}function Ll(t,e){if(t.contextWrite?.token){let r=Nt(e)??"github.com",n=un(r);return Ul([`https://${n}:${t.contextWrite.token}@${r}`],[qn(r)])}return li(t)}import{spawn as Ml}from"node:child_process";import{existsSync as Vn,mkdirSync as Jn,readFileSync as mh,rmSync as ui,symlinkSync as gh}from"node:fs";import{homedir as hh}from"node:os";import{dirname as zn,join as Ct}from"node:path";function Gl(){return Ct(hh(),".codepipe-sandbox","repos")}var Qt=new Map;function Fl(t,e){let n=(Qt.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{Qt.get(t)===o&&Qt.delete(t)},()=>{Qt.get(t)===o&&Qt.delete(t)});return Qt.set(t,o),n}function Bl(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 yh(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 Hl(t,e,r,n,o){let i=async c=>{await X(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await X(t,["reset","--hard",`origin/${c}`],o),await X(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!Bl(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{Vn(t)&&ui(t,{recursive:!0,force:!0}),Jn(zn(t),{recursive:!0});try{return await X(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!Bl(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),Vn(t)&&ui(t,{recursive:!0,force:!0}),Jn(zn(t),{recursive:!0}),await X(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(Vn(Ct(t,".git")))try{return await s()}catch(c){if(!yh(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 Kl(t){await X(t.workspacePath,["reset","--hard",t.baseSha]),await X(t.workspacePath,["clean","-fdx"])}var Zt="CodePipe Agent",er="codepipe@codepartner.ee";async function Wl(t,e){let r=t.workspacePath;await X(r,["add","-A"]);let n=(await le(r,["write-tree"])).trim(),o=(await le(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:Zt,GIT_AUTHOR_EMAIL:er,GIT_COMMITTER_NAME:Zt,GIT_COMMITTER_EMAIL:er};return(await le(r,["commit-tree",n,"-m",e],i)).trim()}async function Yl(t,e,r,n,o){try{await X(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw Nt(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 ql(t,e){return le(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Vl(t,e,r,n,o){await X(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await X(t.workspacePath,["checkout","--force",r])}async function Jl(t,e,r,n,o,i){let s=t.workspacePath;await X(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await le(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=f=>le(s,["rev-parse","-q","--verify",`${f}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await le(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await X(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(y=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(y)}`)}),await c(n)||await X(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:Zt,GIT_AUTHOR_EMAIL:er,GIT_COMMITTER_NAME:Zt,GIT_COMMITTER_EMAIL:er},p=(await le(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),d=(await le(s,["commit-tree",p,"-p",n,"-m","delivery"],l)).trim();await X(s,["cherry-pick","--quit"],l).catch(()=>{});let u=null;try{await X(s,["cherry-pick","--no-commit",d],l)}catch(f){u=f instanceof Error?f.message:String(f)}let m=(await le(s,["diff","--name-only","--diff-filter=U"])).split(`
638
+ `).map(f=>f.trim()).filter(f=>f.length>0);if(u&&m.length===0)throw await X(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${u}`);return m}async function pi(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:Zt,GIT_AUTHOR_EMAIL:er,GIT_COMMITTER_NAME:Zt,GIT_COMMITTER_EMAIL:er};(await le(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await X(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 X(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await X(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await le(n,["diff","--name-only","--diff-filter=U"])).split(`
639
+ `).map(l=>l.trim()).filter(l=>l.length>0),c=await le(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}function X(t,e,r){return new Promise((n,o)=>{let i=Ml("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}):
640
+ ${s.join("").trim()||"(no stderr)"}`))})})}function le(t,e,r){return new Promise((n,o)=>{let i=Ml("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}):
641
+ ${a.join("").trim()||"(no stderr)"}`))})})}function zl(t,e){Vn(t)&&ui(t,{recursive:!0,force:!0}),Jn(zn(t),{recursive:!0}),gh(e,t,"dir")}async function Xl(t,e,r){await X(t,["worktree","prune"]).catch(()=>{}),Jn(zn(r),{recursive:!0}),await X(t,["worktree","add","--detach",r,`origin/${e}`])}async function Ql(t,e,r,n="worktree",o){return r.length===0?[]:Fl(e,async()=>{let i=[];for(let s of r){let a=Ct(Gl(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await Hl(a,s.cloneUrl,s.ref,s.defaultBranch,o)}catch(d){throw new Error(`failed to materialize project repo "${s.name}" (${s.cloneUrl}): `+(d instanceof Error?d.message:String(d)))}let l=(await le(a,["rev-parse","HEAD"])).trim(),p=Ct(t,"code",s.name);n==="direct"?(zl(p,a),console.log(`[git] code: linked ${p} \u2192 ${a} @ ${l.slice(0,10)}`)):(await Xl(a,c,p),console.log(`[git] code: worktree ${p} \u2190 ${a} @ ${l.slice(0,10)}`)),i.push({name:s.name,workspacePath:p,cachePath:a,ref:c,baseSha:l})}return i})}async function Zl(t,e,r,n="worktree",o){if(!r||!r.cloneUrl)return null;let i=r;return Fl(e,async()=>{let s=Ct(Gl(),e,"_context");console.log(`[git] context: ensure ${i.cloneUrl} @ ${i.ref} \u2192 ${s}`);try{await Hl(s,i.cloneUrl,i.ref,void 0,o)}catch(l){throw new Error(`failed to materialize context repo (${i.cloneUrl}): `+(l instanceof Error?l.message:String(l)))}let a=Ct(t,"context");n==="direct"?(zl(a,s),console.log(`[git] context: linked ${a} \u2192 ${s}`)):(await Xl(s,i.ref,a),console.log(`[git] context: worktree ${a} \u2190 ${s}`));let c=(await le(s,["rev-parse","HEAD"])).trim();return{workspacePath:a,cachePath:s,baseSha:c}})}async function eu(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await X(r,["add","-A",...n]).catch(()=>{});let o;try{o=await le(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
642
+ `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=mh(Ct(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as kh}from"node:fs";import{join as wh}from"node:path";var di=8*1024,dt=class extends Error{},Wr="meta/build-result.json";function tu(t){let e=wh(t,Wr),r;try{r=kh(e,"utf-8")}catch{throw new dt(`BUILD produced no ${Wr} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(p){throw new dt(`${Wr} is not valid JSON: ${p instanceof Error?p.message:String(p)}`)}if(!n||typeof n!="object")throw new dt(`${Wr} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new dt(`${Wr}: "ok" must be a boolean`);let i=o.ok,a=(Array.isArray(o.steps)?o.steps:[]).flatMap(p=>{if(!p||typeof p!="object")return[];let d=p,u=typeof d.name=="string"?d.name:null,m=typeof d.exitCode=="number"?d.exitCode:null;if(u===null||m===null)return[];let f={name:u,exitCode:m};return typeof d.durationMs=="number"&&(f.durationMs=d.durationMs),[f]}),c=typeof o.logTail=="string"?bh(o.logTail):"",l={ok:i,steps:a,logTail:c};if(typeof o.failedStep=="string"&&o.failedStep)l.failedStep=o.failedStep;else if(!i){let p=a.find(d=>d.exitCode!==0);p&&(l.failedStep=p.name)}return l}function bh(t){let e=Buffer.from(t,"utf-8");return e.length<=di?t:`\u2026 [${e.length-di} bytes elided] \u2026
643
+ `+e.subarray(e.length-di).toString("utf-8")}import{lstatSync as $h,mkdtempSync as vh,readFileSync as xh,readdirSync as nu,rmSync as ru}from"node:fs";import{tmpdir as Sh}from"node:os";import{join as Xn,relative as Rh}from"node:path";var ou=new Set(["code","context"]);function iu(t){let e=vh(Xn(Sh(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>ru(e,{recursive:!0,force:!0}),listFiles:()=>su(e,e),readFile:r=>xh(Xn(e,r),"utf-8"),clean:()=>{for(let r of nu(e))ou.has(r)||ru(Xn(e,r),{recursive:!0,force:!0})}}}function su(t,e){let r=[];for(let n of nu(e)){let o=Xn(e,n),i=$h(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&ou.has(n))continue;r.push(...su(t,o))}else r.push(Rh(t,o))}return r}var Qn=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),jh=new Set(["implement","resolve-conflict"]);function Ah(t){let e=Buffer.from(t,"utf-8");if(e.length<=Qn)return t;let r=Math.floor(Qn/4),n=Qn-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}
596
644
 
597
- \u2026 [${s} bytes elided \u2014 log capped at ${Un} bytes for upload] \u2026
645
+ \u2026 [${s} bytes elided \u2014 log capped at ${Qn} bytes for upload] \u2026
598
646
 
599
- ${i}`}function _g(){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 _r(t={}){jn();let e=ce(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,n=t.profile?`sandbox-${t.profile}`:"sandbox",o=zt(jg(),".codepipe","logs"),i=tn("SANDBOX_LOG",n,o);if(i.enabled){let P=new _t(i);rn(P),console.log(`[log] file logging \u2192 ${P.path} (rotate at ${i.maxBytes}B, keep ${i.maxFiles})`)}console.log(`codepipe-sandbox v${he} (protocol ${Ee})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let s=Wc(e.llm);console.log(`llm backend: ${s?s.name():"(none \u2014 will not claim agent jobs)"}`);let a=Vc();console.log(`llm retry: maxAttempts=${a.maxAttempts} backoff=${a.baseDelayMs}\u2013${a.maxDelayMs}ms budget=${a.totalBudgetMs}ms`);let c=new Ht(e.hubUrl,e.token),l=!1,p=new AbortController,d=new Map,u=null,m=null,f=!1,y=()=>{let P=c.openControlSocket();return u=P,P.on("open",()=>{console.log("[ws] connected");let g={type:"sandbox_hello",platformVersion:he,protocolVersion:Ee};P.send(JSON.stringify(g))}),P.on("message",g=>{let _=g.toString("utf-8"),b=null;try{let C=JSON.parse(_);C&&typeof C=="object"&&(b=C)}catch{}if(b&&b.type==="hello"){let C=b;m=Hr(C.protocolVersion);let x=m?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${C.platformVersion} (protocol ${C.protocolVersion}) \u2014 ${x}`),m&&(f=!1);return}if(b&&b.type==="pause_job"){let C=typeof b.jobId=="string"?b.jobId:"",x=C?d.get(C):void 0;x?(console.warn(`[ws] pause_job ${C} \u2014 aborting agent`),x.paused=!0,x.abort.abort()):console.log(`[ws] pause_job ${C} \u2014 not a running job, ignoring`),C&&P.send(JSON.stringify({type:"job_paused",jobId:C}));return}if(b&&(b.type==="chat_user_message"||b.type==="chat_finalize")){let C=typeof b.jobId=="string"?b.jobId:"",x=C?d.get(C):void 0;if(x?.chatInbox)if(b.type==="chat_user_message"){let E=typeof b.text=="string"?b.text:"";E.trim()&&x.chatInbox.push({kind:"user",text:E})}else x.chatInbox.finalize();else console.log(`[ws] ${String(b.type)} ${C} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${_}`)}),P.on("close",(g,_)=>{console.log(`[ws] closed code=${g} reason=${_?.toString()||""}`),u===P&&(u=null),!l&&setTimeout(y,2e3)}),P.on("error",g=>console.warn(`[ws] error: ${g.message}`)),P},w=y(),k=async P=>{for(;!l;){if(m===!1){f||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${he}, protocol ${Ee}) \u2014 not claiming jobs until versions align.`),f=!0),await new Promise(g=>setTimeout(g,5e3));continue}try{let g=await c.claim(p.signal,P);if(g.status===204)continue;if(g.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,l=!0;break}if(!g.ok){console.warn(`[claim:${P}] ${g.status} \u2014 backoff 5s`),await new Promise(b=>setTimeout(b,5e3));continue}let _=await g.json();await h(c,_)}catch(g){if(p.signal.aborted)break;let _=g instanceof Error?g.message:String(g);console.warn(`[claim:${P}] error: ${_} \u2014 backoff 5s`),await new Promise(b=>setTimeout(b,5e3))}}};async function h(P,g){let _={abort:new AbortController,paused:!1};g.role==="chat"&&(_.chatInbox=_g()),d.set(g.jobId,_);let b=!1,C=null,x=null,E=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),M=async()=>{try{await P.heartbeat(g.jobId)==="claim_lost"&&(b=!0,console.warn(`[job] ${g.jobId} claim lost \u2014 HUB sweeper took it`))}catch(V){let Se=V instanceof Error?V.message:String(V);console.warn(`[job] ${g.jobId} heartbeat error: ${Se}`)}};M();let v=setInterval(()=>{M()},E),R=new Date().toISOString();console.log(`[job] ${g.jobId} claimed \u2014 role=${g.role} task=${g.taskId} phase=${g.phase}`),console.log(`[job] ${g.jobId} prompt (${g.prompt.length} chars):`),console.log(S(g.prompt," \u2502 "));let T=[],G=null,Ve=400,ft=25,Wn=500,Je=()=>{if(G&&(clearTimeout(G),G=null),T.length===0)return;let V=T.splice(0,T.length),Se=u;if(!Se||Se.readyState!==Se.OPEN)return;let Le={type:"agent_activity",jobId:g.jobId,taskId:g.taskId,projectId:g.projectId,role:g.role,phase:g.phase,events:V};try{Se.send(JSON.stringify(Le))}catch{}},ae=V=>{T.push(V),T.length>Wn&&T.shift(),T.length>=ft?Je():G||(G=setTimeout(Je,Ve))},di=g.role==="analysis"&&g.taskId.startsWith("draft::")?g.taskId.slice(7):null,qn=new Set,Yn=null;try{if(!s){b||await P.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:R,finishedAt:new Date().toISOString()});return}let V=kl(g.jobId);console.log(`[job] ${g.jobId} workspace=${V.dir}`);let Se=$(g,r);C=Se.gitCreds,x=Se.contextGitCreds;let Le=C?.env,fi=Se.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:Se.claudeOauthToken}:void 0,Be=[],ur=null,Vn=null;try{let O="worktree";Be=await fl(V.dir,g.projectId,g.projectRepos,O,Le);let U=await ml(V.dir,g.projectId,g.contextRepo,O,Le);Vn=U,ur=U?.workspacePath??null}catch(O){let U=O instanceof Error?O.message:String(O);console.warn(`[job] ${g.jobId} materialize failed: ${U}`),b||await P.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${U}`},startedAt:R,finishedAt:new Date().toISOString()}),V.dispose();return}let mi=async()=>{if(!g.deliveries||g.deliveries.length===0)return[];let O=g.contextRepo?.cloneUrl;if(!O||!Le)throw new Error(O?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let U=[];for(let W of g.deliveries){let K=Be.find(ge=>ge.name===W.name);if(K){if(g.role==="implement"&&W.baseSha&&W.baseSha!==K.baseSha){let ge=await ul(K,W.deliveryRef,W.deliverySha,W.baseSha,O,Le);console.log(`[job] ${g.jobId} ${K.name}: base moved ${W.baseSha.slice(0,10)} \u2192 ${K.baseSha.slice(0,10)} \u2014 re-applied delivery ${W.deliverySha.slice(0,10)} (${ge.length} conflicted file(s))`),ge.length>0&&U.push(`- **${K.name}**:`,...ge.map(pr=>` - \`${pr}\``));continue}await ll(K,W.deliveryRef,W.deliverySha,O,Le),console.log(`[job] ${g.jobId} ${K.name}: checked out delivery ${W.deliverySha.slice(0,10)} for ${g.role}`)}}return U},Jn=[];if(g.role==="build"||g.role==="implement")try{Jn=await mi()}catch(O){let U=O instanceof Error?O.message:String(O);console.warn(`[job] ${g.jobId} delivery checkout failed: ${U}`),b||await P.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${U}`},startedAt:R,finishedAt:new Date().toISOString()}),V.dispose();return}let zn=g.role==="resolve-conflict"?g.metadata?.taskBranchByRepo??{}:{},gi="";if(g.role==="resolve-conflict"){if(!Be.some(O=>zn[O.name])){let O="resolve-conflict job carries no task branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${g.jobId} ${O}`),b||await P.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:O},startedAt:R,finishedAt:new Date().toISOString()}),V.dispose();return}try{let O=[];for(let U of Be){let W=zn[U.name];if(!W)continue;let K=await Ho(U,W,Le);console.log(`[job] ${g.jobId} ${U.name}: merged ${W} into ${U.ref} \u2014 ${K.length} conflicted file(s)`),K.length>0?O.push(`- **${U.name}**:`,...K.map(ge=>` - \`${ge}\``)):O.push(`- **${U.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}gi=`
647
+ ${i}`}function _h(){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 Yr(t={}){Wn();let e=ue(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,n=t.profile?`sandbox-${t.profile}`:"sandbox",o=tr(Eh(),".codepipe","logs"),i=yn("SANDBOX_LOG",n,o);if(i.enabled){let E=new Lt(i);kn(E),console.log(`[log] file logging \u2192 ${E.path} (rotate at ${i.maxBytes}B, keep ${i.maxFiles})`)}console.log(`codepipe-sandbox v${be} (protocol ${_e})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let s=Pl(e.llm);console.log(`llm backend: ${s?s.name():"(none \u2014 will not claim agent jobs)"}`);let a=_l();console.log(`llm retry: maxAttempts=${a.maxAttempts} backoff=${a.baseDelayMs}\u2013${a.maxDelayMs}ms budget=${a.totalBudgetMs}ms`);let c=new Vt(e.hubUrl,e.token),l=!1,p=new AbortController,d=new Map,u=null,m=null,f=!1,y=()=>{let E=c.openControlSocket();return u=E,E.on("open",()=>{console.log("[ws] connected");let g={type:"sandbox_hello",platformVersion:be,protocolVersion:_e};E.send(JSON.stringify(g))}),E.on("message",g=>{let _=g.toString("utf-8"),b=null;try{let C=JSON.parse(_);C&&typeof C=="object"&&(b=C)}catch{}if(b&&b.type==="hello"){let C=b;m=rn(C.protocolVersion);let x=m?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${C.platformVersion} (protocol ${C.protocolVersion}) \u2014 ${x}`),m&&(f=!1);return}if(b&&b.type==="pause_job"){let C=typeof b.jobId=="string"?b.jobId:"",x=C?d.get(C):void 0;x?(console.warn(`[ws] pause_job ${C} \u2014 aborting agent`),x.paused=!0,x.abort.abort()):console.log(`[ws] pause_job ${C} \u2014 not a running job, ignoring`),C&&E.send(JSON.stringify({type:"job_paused",jobId:C}));return}if(b&&(b.type==="chat_user_message"||b.type==="chat_finalize")){let C=typeof b.jobId=="string"?b.jobId:"",x=C?d.get(C):void 0;if(x?.chatInbox)if(b.type==="chat_user_message"){let P=typeof b.text=="string"?b.text:"";P.trim()&&x.chatInbox.push({kind:"user",text:P})}else x.chatInbox.finalize();else console.log(`[ws] ${String(b.type)} ${C} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${_}`)}),E.on("close",(g,_)=>{console.log(`[ws] closed code=${g} reason=${_?.toString()||""}`),u===E&&(u=null),!l&&setTimeout(y,2e3)}),E.on("error",g=>console.warn(`[ws] error: ${g.message}`)),E},k=y(),$=async E=>{for(;!l;){if(m===!1){f||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${be}, protocol ${_e}) \u2014 not claiming jobs until versions align.`),f=!0),await new Promise(g=>setTimeout(g,5e3));continue}try{let g=await c.claim(p.signal,E);if(g.status===204)continue;if(g.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,l=!0;break}if(!g.ok){console.warn(`[claim:${E}] ${g.status} \u2014 backoff 5s`),await new Promise(b=>setTimeout(b,5e3));continue}let _=await g.json();await h(c,_)}catch(g){if(p.signal.aborted)break;let _=g instanceof Error?g.message:String(g);console.warn(`[claim:${E}] error: ${_} \u2014 backoff 5s`),await new Promise(b=>setTimeout(b,5e3))}}};async function h(E,g){let _={abort:new AbortController,paused:!1};g.role==="chat"&&(_.chatInbox=_h()),d.set(g.jobId,_);let b=!1,C=null,x=null,P=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),D=async()=>{try{await E.heartbeat(g.jobId)==="claim_lost"&&(b=!0,console.warn(`[job] ${g.jobId} claim lost \u2014 HUB sweeper took it`))}catch(V){let Ie=V instanceof Error?V.message:String(V);console.warn(`[job] ${g.jobId} heartbeat error: ${Ie}`)}};D();let v=setInterval(()=>{D()},P),S=new Date().toISOString();console.log(`[job] ${g.jobId} claimed \u2014 role=${g.role} task=${g.taskId} phase=${g.phase}`),console.log(`[job] ${g.jobId} prompt (${g.prompt.length} chars):`),console.log(I(g.prompt," \u2502 "));let G=[],Q=null,A=400,ke=25,Ze=500,Ge=()=>{if(Q&&(clearTimeout(Q),Q=null),G.length===0)return;let V=G.splice(0,G.length),Ie=u;if(!Ie||Ie.readyState!==Ie.OPEN)return;let Fe={type:"agent_activity",jobId:g.jobId,taskId:g.taskId,projectId:g.projectId,role:g.role,phase:g.phase,events:V};try{Ie.send(JSON.stringify(Fe))}catch{}},ao=V=>{G.push(V),G.length>Ze&&G.shift(),G.length>=ke?Ge():Q||(Q=setTimeout(Ge,A))},yt=g.role==="analysis"&&g.taskId.startsWith("draft::")?g.taskId.slice(7):null,ae=new Set,co=null;try{if(!s){b||await E.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:S,finishedAt:new Date().toISOString()});return}let V=iu(g.jobId);console.log(`[job] ${g.jobId} workspace=${V.dir}`);let Ie=w(g,r);C=Ie.gitCreds,x=Ie.contextGitCreds;let Fe=C?.env,Ni=Ie.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:Ie.claudeOauthToken}:void 0,He=[],gr=null,lo=null;try{let O="worktree";He=await Ql(V.dir,g.projectId,g.projectRepos,O,Fe);let U=await Zl(V.dir,g.projectId,g.contextRepo,O,Fe);lo=U,gr=U?.workspacePath??null}catch(O){let U=O instanceof Error?O.message:String(O);console.warn(`[job] ${g.jobId} materialize failed: ${U}`),b||await E.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${U}`},startedAt:S,finishedAt:new Date().toISOString()}),V.dispose();return}let Oi=async()=>{if(!g.deliveries||g.deliveries.length===0)return[];let O=g.contextRepo?.cloneUrl;if(!O||!Fe)throw new Error(O?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let U=[];for(let W of g.deliveries){let K=He.find(we=>we.name===W.name);if(K){if(g.role==="implement"&&W.baseSha&&W.baseSha!==K.baseSha){let we=await Jl(K,W.deliveryRef,W.deliverySha,W.baseSha,O,Fe);console.log(`[job] ${g.jobId} ${K.name}: base moved ${W.baseSha.slice(0,10)} \u2192 ${K.baseSha.slice(0,10)} \u2014 re-applied delivery ${W.deliverySha.slice(0,10)} (${we.length} conflicted file(s))`),we.length>0&&U.push(`- **${K.name}**:`,...we.map(hr=>` - \`${hr}\``));continue}await Vl(K,W.deliveryRef,W.deliverySha,O,Fe),console.log(`[job] ${g.jobId} ${K.name}: checked out delivery ${W.deliverySha.slice(0,10)} for ${g.role}`)}}return U},uo=[];if(g.role==="build"||g.role==="implement")try{uo=await Oi()}catch(O){let U=O instanceof Error?O.message:String(O);console.warn(`[job] ${g.jobId} delivery checkout failed: ${U}`),b||await E.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${U}`},startedAt:S,finishedAt:new Date().toISOString()}),V.dispose();return}let po=g.role==="resolve-conflict"?g.metadata?.taskBranchByRepo??{}:{},Di="";if(g.role==="resolve-conflict"){if(!He.some(O=>po[O.name])){let O="resolve-conflict job carries no task branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${g.jobId} ${O}`),b||await E.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:O},startedAt:S,finishedAt:new Date().toISOString()}),V.dispose();return}try{let O=[];for(let U of He){let W=po[U.name];if(!W)continue;let K=await pi(U,W,Fe);console.log(`[job] ${g.jobId} ${U.name}: merged ${W} into ${U.ref} \u2014 ${K.length} conflicted file(s)`),K.length>0?O.push(`- **${U.name}**:`,...K.map(we=>` - \`${we}\``)):O.push(`- **${U.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}Di=`
600
648
 
601
649
  ## Conflicts to resolve
602
650
 
603
651
  `+(O.length>0?O.join(`
604
652
  `):"(no task branches to merge)")+`
605
- `}catch(O){let U=O instanceof Error?O.message:String(O);console.warn(`[job] ${g.jobId} conflict merge failed: ${U}`),b||await P.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${U}`},startedAt:R,finishedAt:new Date().toISOString()}),V.dispose();return}}let Vu=Jn.length>0?`
653
+ `}catch(O){let U=O instanceof Error?O.message:String(O);console.warn(`[job] ${g.jobId} conflict merge failed: ${U}`),b||await E.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${U}`},startedAt:S,finishedAt:new Date().toISOString()}),V.dispose();return}}let _p=uo.length>0?`
606
654
 
607
655
  ## Base branch moved \u2014 conflicts to resolve
608
656
 
609
657
  The base branch advanced since the previous iteration; its delivery was re-applied on top of the fresh base. These files now contain git conflict markers (\`<<<<<<<\`) \u2014 resolve them (keep both the base branch's changes and this task's changes) as part of this job:
610
658
 
611
- `+Jn.join(`
659
+ `+uo.join(`
612
660
  `)+`
613
- `:"",Ju=j(B(g.prompt,Be,ur),ur,g.taskId)+gi+Vu,Xn=[...Be.map(O=>O.workspacePath),...ur?[ur]:[]];Xn.length>0&&console.log(`[job] ${g.jobId} --add-dir: ${Xn.join(", ")}`),di&&(Yn=setInterval(()=>{let U=u;if(!U||U.readyState!==U.OPEN)return;let W;try{W=Cg(zt(V.dir,"drafts")).filter(K=>K.endsWith(".json")).sort()}catch{return}for(let K of W){if(qn.has(K))continue;if(qn.size>=Ui)break;let ge;try{let de=JSON.parse(Wo(zt(V.dir,"drafts",K),"utf-8")),mt=typeof de.localRef=="string"?de.localRef:"",q=typeof de.title=="string"?de.title:"",Z=typeof de.body=="string"?de.body:"";if(!mt||!q)continue;ge={localRef:mt,title:q,body:Z,...de.isEpic===!0?{isEpic:!0}:{},...Array.isArray(de.links)?{links:de.links}:{}}}catch{continue}qn.add(K);let pr={type:"child_draft",jobId:g.jobId,projectId:g.projectId,draftId:di,child:ge};try{U.send(JSON.stringify(pr))}catch{}}},1500));try{let O={workspaceDir:V.dir,role:g.role,prompt:Ju,addDirs:Xn,metadata:g.metadata??{},...g.model?{model:g.model}:{},...fi?{env:fi}:{},signal:_.abort.signal,onActivity:ae},U=_.chatInbox?await s.run({...O,interactive:{inbox:_.chatInbox.iterable}}):await zc(s,O,{jobId:g.jobId,policy:a,onBeforeRetry:async()=>{V.clean();for(let q of Be)try{await il(q);let Z=zn[q.name];g.role==="resolve-conflict"&&Z&&await Ho(q,Z,Le)}catch(Z){let dr=Z instanceof Error?Z.message:String(Z);console.warn(`[job] ${g.jobId} worktree reset failed (${q.name}): ${dr}`)}try{await mi()}catch(q){let Z=q instanceof Error?q.message:String(q);console.warn(`[job] ${g.jobId} delivery re-checkout failed: ${Z}`)}},aborted:()=>b||_.paused}),W=[];if(Pg.has(g.role)&&Be.length>0){let q=g.metadata??{},Z=typeof q.commitMessage=="string"?q.commitMessage:`${g.taskId}: changes`,dr=g.contextRepo?.cloneUrl,hi=x?.env;if(!dr||!hi)throw new Error("delivery requested but "+(dr?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let zu=g.taskId.includes(":")?g.taskId.slice(g.taskId.indexOf(":")+1):g.taskId;for(let Me of Be){let fr=await sl(Me,Z);if(!fr){console.log(`[job] ${g.jobId} ${Me.name}: no changes \u2014 no delivery`);continue}let Qn=`codepipe/deliveries/${zu}/${g.jobId}/${Me.name}`;await al(Me,fr,Qn,dr,hi),W.push({name:Me.name,deliveryRef:Qn,deliverySha:fr,baseSha:Me.baseSha}),console.log(`[job] ${g.jobId} ${Me.name}: delivered ${fr.slice(0,10)} \u2192 ${Qn}`);let yi=await cl(Me,fr);if(yi.trim().length>0){let Xu=zt("display",`${Me.name}.diff`),wi=zt(V.dir,Xu);Tg(Eg(wi),{recursive:!0}),Ig(wi,yi)}}}if(g.role==="resolve-conflict"&&W.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's diff-summary.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let K;g.role==="build"&&(K=hl(V.dir),console.log(`[job] ${g.jobId} build verdict: ok=${K.ok}`+(K.failedStep?` failedStep=${K.failedStep}`:"")));let ge=U.artifactPaths.length>0?U.artifactPaths:V.listFiles(),pr=Array.from(new Set(ge)),de;if(Vn)try{let q=g.role==="index"?["adr/SOURCES.md"]:g.role==="backfill"?["adr"]:[],Z=await gl(Vn,q);Z.length>0&&(de=Z,console.log(`[job] ${g.jobId} captured ${Z.length} knowledge file(s) for Context Repo`))}catch(q){let Z=q instanceof Error?q.message:String(q);console.warn(`[job] ${g.jobId} knowledge capture failed (non-fatal): ${Z}`)}let mt={jobId:g.jobId,status:"succeeded",artifacts:pr.map(q=>({path:q,contentBase64:Wo(`${V.dir}/${q}`).toString("base64")})),...de?{contextWrites:de}:{},...W.length>0?{deliveries:W}:{},log:Ag(U.log),startedAt:R,finishedAt:new Date().toISOString(),usage:U.usage,...U.rateLimit?{rateLimit:U.rateLimit}:{},...K?{build:K}:{}};if(b||_.paused)console.warn(`[job] ${g.jobId} skipping result upload \u2014 ${_.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await P.submitResult(mt),console.log(`[job] ${g.jobId} done \u2014 uploaded ${mt.artifacts.length} artifact(s):`);for(let q of mt.artifacts){let Z=Buffer.from(q.contentBase64,"base64").length;console.log(` \xB7 ${q.path} (${Z} bytes)`)}mt.artifacts.length===0&&console.warn(`[job] ${g.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(O){let U=O instanceof Error?O.message:String(O);if(_.paused)console.log(`[job] ${g.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(b)console.warn(`[job] ${g.jobId} failed after claim lost (${U}) \u2014 skipping result upload`);else{let W=Jc(O),K=O instanceof at;console.warn(W?`[job] ${g.jobId} failed: ${U} (Claude auth \u2014 token invalid/expired)`:K?`[job] ${g.jobId} failed: ${U} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${g.jobId} failed: ${U}`),await P.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:U},startedAt:R,finishedAt:new Date().toISOString(),...W?{authError:!0}:{},...K?{buildInconclusive:!0}:{}})}}finally{V.dispose()}}finally{clearInterval(v),Yn&&clearInterval(Yn),Je(),_.chatInbox?.close(),d.delete(g.jobId),C?.cleanup(),x?.cleanup()}}function $(P,g){if(!P.credBundle)return{gitCreds:null,contextGitCreds:null};if(!g)return console.warn(`[job] ${P.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let _;try{_=JSON.parse(Bt(g,P.credBundle).toString("utf-8"))}catch(E){return console.warn(`[job] ${P.jobId} failed to open credBundle: ${E instanceof Error?E.message:String(E)}`),{gitCreds:null,contextGitCreds:null}}let b=Go(_);b&&console.log(`[job] ${P.jobId} cred bundle opened \u2014 git creds configured`);let C=Zc(_,P.contextRepo.cloneUrl),x={gitCreds:b,contextGitCreds:C};return _.claudeOauthToken&&(x.claudeOauthToken=_.claudeOauthToken),x}function S(P,g){return P.split(`
661
+ `:"",Np=R(B(g.prompt,He,gr),gr,g.taskId)+Di+_p,fo=[...He.map(O=>O.workspacePath),...gr?[gr]:[]];fo.length>0&&console.log(`[job] ${g.jobId} --add-dir: ${fo.join(", ")}`),yt&&(co=setInterval(()=>{let U=u;if(!U||U.readyState!==U.OPEN)return;let W;try{W=Ih(tr(V.dir,"drafts")).filter(K=>K.endsWith(".json")).sort()}catch{return}for(let K of W){if(ae.has(K))continue;if(ae.size>=os)break;let we;try{let me=JSON.parse(fi(tr(V.dir,"drafts",K),"utf-8")),kt=typeof me.localRef=="string"?me.localRef:"",Y=typeof me.title=="string"?me.title:"",ee=typeof me.body=="string"?me.body:"";if(!kt||!Y)continue;we={localRef:kt,title:Y,body:ee,...me.isEpic===!0?{isEpic:!0}:{},...Array.isArray(me.links)?{links:me.links}:{}}}catch{continue}ae.add(K);let hr={type:"child_draft",jobId:g.jobId,projectId:g.projectId,draftId:yt,child:we};try{U.send(JSON.stringify(hr))}catch{}}},1500));try{let O={workspaceDir:V.dir,role:g.role,prompt:Np,addDirs:fo,metadata:g.metadata??{},...g.model?{model:g.model}:{},...Ni?{env:Ni}:{},signal:_.abort.signal,onActivity:ao},U=_.chatInbox?await s.run({...O,interactive:{inbox:_.chatInbox.iterable}}):await Ol(s,O,{jobId:g.jobId,policy:a,onBeforeRetry:async()=>{V.clean();for(let Y of He)try{await Kl(Y);let ee=po[Y.name];g.role==="resolve-conflict"&&ee&&await pi(Y,ee,Fe)}catch(ee){let yr=ee instanceof Error?ee.message:String(ee);console.warn(`[job] ${g.jobId} worktree reset failed (${Y.name}): ${yr}`)}try{await Oi()}catch(Y){let ee=Y instanceof Error?Y.message:String(Y);console.warn(`[job] ${g.jobId} delivery re-checkout failed: ${ee}`)}},aborted:()=>b||_.paused}),W=[];if(jh.has(g.role)&&He.length>0){let Y=g.metadata??{},ee=typeof Y.commitMessage=="string"?Y.commitMessage:`${g.taskId}: changes`,yr=g.contextRepo?.cloneUrl,Ui=x?.env;if(!yr||!Ui)throw new Error("delivery requested but "+(yr?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let Op=g.taskId.includes(":")?g.taskId.slice(g.taskId.indexOf(":")+1):g.taskId;for(let Ke of He){let kr=await Wl(Ke,ee);if(!kr){console.log(`[job] ${g.jobId} ${Ke.name}: no changes \u2014 no delivery`);continue}let mo=`codepipe/deliveries/${Op}/${g.jobId}/${Ke.name}`;await Yl(Ke,kr,mo,yr,Ui),W.push({name:Ke.name,deliveryRef:mo,deliverySha:kr,baseSha:Ke.baseSha}),console.log(`[job] ${g.jobId} ${Ke.name}: delivered ${kr.slice(0,10)} \u2192 ${mo}`);let Li=await ql(Ke,kr);if(Li.trim().length>0){let Dp=tr("display",`${Ke.name}.diff`),Bi=tr(V.dir,Dp);Th(Ph(Bi),{recursive:!0}),Ch(Bi,Li)}}}if(g.role==="resolve-conflict"&&W.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's diff-summary.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let K;g.role==="build"&&(K=tu(V.dir),console.log(`[job] ${g.jobId} build verdict: ok=${K.ok}`+(K.failedStep?` failedStep=${K.failedStep}`:"")));let we=U.artifactPaths.length>0?U.artifactPaths:V.listFiles(),hr=Array.from(new Set(we)),me;if(lo)try{let Y=g.role==="index"?["adr/SOURCES.md"]:g.role==="backfill"?["adr"]:[],ee=await eu(lo,Y);ee.length>0&&(me=ee,console.log(`[job] ${g.jobId} captured ${ee.length} knowledge file(s) for Context Repo`))}catch(Y){let ee=Y instanceof Error?Y.message:String(Y);console.warn(`[job] ${g.jobId} knowledge capture failed (non-fatal): ${ee}`)}let kt={jobId:g.jobId,status:"succeeded",artifacts:hr.map(Y=>({path:Y,contentBase64:fi(`${V.dir}/${Y}`).toString("base64")})),...me?{contextWrites:me}:{},...W.length>0?{deliveries:W}:{},log:Ah(U.log),startedAt:S,finishedAt:new Date().toISOString(),usage:U.usage,...U.rateLimit?{rateLimit:U.rateLimit}:{},...K?{build:K}:{}};if(b||_.paused)console.warn(`[job] ${g.jobId} skipping result upload \u2014 ${_.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await E.submitResult(kt),console.log(`[job] ${g.jobId} done \u2014 uploaded ${kt.artifacts.length} artifact(s):`);for(let Y of kt.artifacts){let ee=Buffer.from(Y.contentBase64,"base64").length;console.log(` \xB7 ${Y.path} (${ee} bytes)`)}kt.artifacts.length===0&&console.warn(`[job] ${g.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(O){let U=O instanceof Error?O.message:String(O);if(_.paused)console.log(`[job] ${g.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(b)console.warn(`[job] ${g.jobId} failed after claim lost (${U}) \u2014 skipping result upload`);else{let W=Nl(O),K=O instanceof dt;console.warn(W?`[job] ${g.jobId} failed: ${U} (Claude auth \u2014 token invalid/expired)`:K?`[job] ${g.jobId} failed: ${U} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${g.jobId} failed: ${U}`),await E.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:U},startedAt:S,finishedAt:new Date().toISOString(),...W?{authError:!0}:{},...K?{buildInconclusive:!0}:{}})}}finally{V.dispose()}}finally{clearInterval(v),co&&clearInterval(co),Ge(),_.chatInbox?.close(),d.delete(g.jobId),C?.cleanup(),x?.cleanup()}}function w(E,g){if(!E.credBundle)return{gitCreds:null,contextGitCreds:null};if(!g)return console.warn(`[job] ${E.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let _;try{_=JSON.parse(Kt(g,E.credBundle).toString("utf-8"))}catch(P){return console.warn(`[job] ${E.jobId} failed to open credBundle: ${P instanceof Error?P.message:String(P)}`),{gitCreds:null,contextGitCreds:null}}let b=li(_);b&&console.log(`[job] ${E.jobId} cred bundle opened \u2014 git creds configured`);let C=Ll(_,E.contextRepo.cloneUrl),x={gitCreds:b,contextGitCreds:C};return _.claudeOauthToken&&(x.claudeOauthToken=_.claudeOauthToken),x}function I(E,g){return E.split(`
614
662
  `).map(_=>g+_).join(`
615
- `)}function B(P,g,_){let b=g[0]?.workspacePath??"";return P.replace(/\{\{codeDir\}\}/g,b).replace(/\{\{codeRoot\}\}/g,b?b.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,_??"")}function j(P,g,_){let b=P,C=_.includes("::")?"":_.split(":",2)[1]??"",x=E=>{if(!g||!C)return"";try{return Wo(zt(g,"tasks",C,E),"utf-8").trim()}catch{return""}};if(b.includes("{{solutionMd}}")){let E=x("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";b=b.replace(/\{\{solutionMd\}\}/g,()=>E)}if(b.includes("{{taskDescription}}")){let E=x("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";b=b.replace(/\{\{taskDescription\}\}/g,()=>E)}return b}let A=P=>{if(l)return;l=!0,console.log(`
616
- [${P}] shutting down`),p.abort();let g=[...d.keys()];for(let C of d.values())C.abort.abort();let _=new AbortController,b=setTimeout(()=>_.abort(),3e3);(async()=>(await Promise.all(g.map(async C=>{try{await c.releaseJob(C,`sandbox ${P}`,_.signal),console.log(`[${P}] released job ${C}`)}catch(x){let E=x instanceof Error?x.message:String(x);console.warn(`[${P}] release failed: ${E} (sweeper will reclaim)`)}})),clearTimeout(b),w.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>A("SIGINT")),process.on("SIGTERM",()=>A("SIGTERM"));let L=[k("implementation")];e.planningLane!==!1?L.push(k("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(L)}async function vl(t={profile:void 0}){let e=be(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=$n(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 p=l.toString("utf-8");if(s.push(`msg:${p}`),p!=="pong")try{let d=JSON.parse(p);d.type==="registered"?(a=!!d.ok,clearTimeout(c),r.send("ping")):d.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,p)=>{s.push(`close:${l}:${p?.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 Y(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=ce(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`)")}import{spawn as uh}from"node:child_process";import{existsSync as er,mkdirSync as Kl,readFileSync as Wl,readdirSync as ph,writeFileSync as ql}from"node:fs";import{join as Rt,resolve as Yl}from"node:path";import{setTimeout as Jo}from"node:timers/promises";import{cancel as dh,confirm as tr,intro as Vl,isCancel as Ln,log as I,outro as zo,password as rr,select as ut,spinner as Jl,text as ne}from"@clack/prompts";import{simpleGit as Mn}from"simple-git";async function Qt(t,e,r){return e.host==="github"?Og(t,e,r):e.host==="gitlab"?Fg(t,e,r):Kg(t,e,r)}async function xl(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 lt(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Sl(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 ct(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Rl(e.gitlabToken,t):o}}return e.bitbucket?(await Xt(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Tl(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 Sl(t,e){let r=!1;try{r=(await lt(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 Rl(t,e){let r=!1;try{r=(await ct(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 Tl(t,e){let r=!1;try{r=(await Xt(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`}var Ng="https://api.github.com";async function lt(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(Ng+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 Og(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 Ug(n,e,r),i=await Lg(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=Lt(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await Bg(n,o.owner,o.name,a.path,i)||await Mg(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 Ug(t,e,r){let n=await lt(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 Sl(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Dg(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 lt(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 Dg(t,e){let{status:r,data:n}=await lt(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function Lg(t,e,r){let{data:n}=await lt(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function Bg(t,e,r,n,o){let{status:i,data:s}=await lt(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function Mg(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 lt(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}var Gg="https://gitlab.com/api/v4";async function ct(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(Gg+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 Fg(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 ct(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 Rl(n,e)} (attach joins an existing Context Repo and never creates one)`);let d=await ct(n,"GET","/user"),u={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(d.data?.username!==e.owner){let f=await ct(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(f.status===404||!f.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);u.namespace_id=f.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let m=await ct(n,"POST","/projects",u);if(!m.data)throw new Error("GitLab create project: empty response");i=m.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Lt(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let d=1;;d++){let m=(await ct(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${d}&ref=${encodeURIComponent(a)}`)).data??[];for(let f of m)l.add(f.path);if(m.length<100)break}let p=c.filter(d=>!l.has(d.path)).map(d=>({action:"create",file_path:d.path,content:d.content}));return p.length>0?await ct(n,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:p}):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}}var Hg="https://api.bitbucket.org/2.0";async function Xt(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(Hg+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 Kg(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 Xt(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 Tl(n,e)} (attach joins an existing Context Repo and never creates one)`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let d=await Xt(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(d.status===404||!d.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=d.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Lt(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let d of c)(await Xt(n,"GET",`${o}/src/${encodeURIComponent(a)}/${d.path}?format=meta`)).status===404&&l.push(d);if(l.length>0){let d=new URLSearchParams;d.set("message","chore(codepipe): scaffold context repo files"),d.set("branch",a);for(let m of l)d.set(m.path,m.content);if((await Xt(n,"POST",`${o}/src`,{form:d})).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 p=i.links?.clone?.find(d=>d.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:p??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var Wg={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function ve(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=Wg[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}import{createHash as qg}from"node:crypto";import{existsSync as Cl,mkdirSync as Yg,readFileSync as Il,readdirSync as Vg,rmSync as Dn,writeFileSync as Jg}from"node:fs";import{homedir as zg}from"node:os";import{dirname as Xg,join as qo}from"node:path";var Qg=24*60*60*1e3;function jl(){return qo(zg(),".codepipe","init-drafts")}function Yo(t){let e=qg("sha256").update(t).digest("hex").slice(0,16);return qo(jl(),`${e}.json`)}function El(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=Qg)}function Pl(t){let e=Yo(t);if(!Cl(e))return null;try{let r=JSON.parse(Il(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:El(r.savedAt)?(Dn(e,{force:!0}),null):r}catch{return null}}function Vo(t){Dn(Yo(t),{force:!0})}function Al(){let t=jl();if(Cl(t))for(let e of Vg(t)){let r=qo(t,e);try{let n=JSON.parse(Il(r,"utf-8"));El(n.savedAt)&&Dn(r,{force:!0})}catch{Dn(r,{force:!0})}}}var Zt=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(){Vo(this.cwd)}persist(){let e=Yo(this.cwd);Yg(Xg(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};Jg(e,JSON.stringify(r,null,2)+`
617
- `,{mode:384})}};function _l(t){return t?{message:"An index already exists. Re-index the project?",proceedValue:"yes",reindex:!0,options:[{value:"no",label:"No, keep the existing one"},{value:"yes",label:"Yes, re-index"}],initialValue:"no"}:{message:"Index the project repositories? (recommended on first run)",proceedValue:"yes",reindex:!1,options:[{value:"yes",label:"Yes"},{value:"skip",label:"Skip"}],initialValue:"yes"}}function Nl(){return{message:"Reconstruct architecture decisions from the existing code first? (deep one-off analysis \u2014 proposes decision drafts you review before they become canonical)",proceedValue:"yes",reindex:!1,options:[{value:"yes",label:"Yes \u2014 analyse and propose decision drafts"},{value:"skip",label:"Skip"}],initialValue:"yes"}}async function Ol(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}}import{existsSync as Zg}from"node:fs";import{join as eh}from"node:path";import{simpleGit as th}from"simple-git";var rh=3,nh=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,oh=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"]);function ih(t){let e=t.split("/");return e[e.length-1]??t}function Ul(t){if(t.filter(r=>!nh.test(ih(r))).length>rh)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(oh.has(n))return!0}return!1}async function sh(t){try{let r=(await th(t).raw(["ls-files"])).split(`
618
- `).map(n=>n.trim()).filter(Boolean);return Ul(r)}catch{return!1}}async function ah(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)?Ul(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function Dl(t,e){for(let r of t)try{let n=e.localRoot!=null?eh(e.localRoot,r.mountAs??r.name):null;if(n&&Zg(n)?await sh(n):await ah(r,e.tokens))return!0}catch{}return!1}import{existsSync as Ll}from"node:fs";import{join as Bl}from"node:path";import{simpleGit as Ml}from"simple-git";var ch={info:t=>console.log(t),warn:t=>console.warn(t)};async function Nr(t,e,r={}){let n=r.log??ch,o=[];for(let i of e){let s=Bl(t,i.mountAs),a=Mi(i);if(!Ll(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 Ml().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(p){let d=p instanceof Error?p.message:String(p);n.warn(`clone failed for ${i.mountAs}: ${d}`),o.push({mountAs:i.mountAs,status:"error",detail:d})}continue}if(!Ll(Bl(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=Ml(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!lh(l,a)){n.warn(`${i.mountAs}/ origin (${l||"none"}) != expected (${a}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail: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(p){let d=p instanceof Error?p.message:String(p);n.warn(`fetch failed for ${i.mountAs}: ${d}`),o.push({mountAs:i.mountAs,status:"error",detail:d})}}return o}function lh(t,e){return Gl(t)===Gl(e)}function Gl(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function Fl(t={}){let e=we();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 Nr(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 Hl=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function Q(t){dh(t),process.exit(1)}function xe(t){return Ln(t)&&Q("aborted"),t}function z(t){return Ln(t)&&Q("aborted"),typeof t=="string"?t:""}async function zl(t={}){Vl("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Al();let r=Pl(e),n,o=!1;r&&Object.keys(r.answers).length>0?xe(await tr({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(I.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new Zt(e,r),o=!0):(Vo(e),n=new Zt(e)):n=new Zt(e);let i=t.force===!0?null:await Qo(e),s=await n.ask("target",async()=>xe(await ut({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i,a?I.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||Ql(e,t.force===!0));let c=await n.ask("hubUrl",async()=>z(await ne({message:"HUB URL",placeholder:je,initialValue:F("HUB_URL")??je,validate:T=>T.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>nr()),{cliToken:p,accountEmail:d}=await n.ask("bootstrap",()=>or(c,l)),u=null;s==="farm"&&(u=await fh(c,p));let m=a?gh(a.parsed.repoName):"",f=await n.ask("projectId",async()=>z(await ne({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:T=>yt.test(T.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),y=await n.ask("projectName",async()=>z(await ne({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()),w=await n.ask("automationLevel",async()=>xe(await ut({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"}))),k=await n.ask("youtrack",()=>iu()),h=await n.ask("youtrackProjectKey",async()=>z(await ne({message:"YouTrack project key",placeholder:"DEV",validate:T=>T.trim().length>0?void 0:"required"})).trim()),$=await n.ask("youtrackWrites",async()=>xe(await tr({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),S=n.get("tokens")??{},B=()=>n.set("tokens",S),j=await n.ask("repos",()=>bh(S,l,a,{onCred:B,initial:n.get("reposPartial")??[],onProgress:T=>n.set("reposPartial",T)}));n.delete("reposPartial");let A=await kh(await n.ask("contextRepo",()=>ru(f,j,S,l)),f,j,S,l,B,T=>n.set("contextRepo",T)),{spec:L,mode:P}=A;I.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml).");let g=await n.ask("assigneeLogin",async()=>z(await ne({message:"your YouTrack login (the assignee value)",...k.login?{initialValue:k.login}:{},validate:T=>T.trim().length>0?void 0:"required"})).trim()),_=await n.ask("claudeToken",()=>Ch(s==="farm")),b={projectId:f,name:y,automationLevel:w,repos:j,youtrackProjectKey:h};I.step(`${P==="attach"?"attaching to":"provisioning"} Context Repo ${L.owner}/${L.name} (${L.host})\u2026`);let C;try{C=await Qt(b,L,{...nu(S),youtrackWrites:$,trackerUrl:k.url,mode:P,log:{info:T=>I.message(T),warn:T=>I.warn(T)}})}catch(T){Q(`Context Repo provisioning failed: ${T instanceof Error?T.message:String(T)}`)}b.contextRepo=C,I.success(`Context Repo ready: ${C.owner}/${C.name}@${C.branch}`),I.step(`registering project on ${c}\u2026`);let x;try{x=await ot(c,p,b)}catch(T){if(T instanceof N&&T.status===409){I.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{x=await Y(c,p,f)}catch(G){throw G instanceof N&&Q(`HUB \u2192 ${G.status} ${G.message}`),G}}else if(T instanceof N&&T.status===401)n.delete("cliToken"),Q("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(T instanceof N)Q(`HUB \u2192 ${T.status} ${T.message}`);else throw T}let E=x.contextRepo??C;I.success(`project ${x.projectId} ready (${x.provisioningStatus})`);let M=await Rh(E),v={url:k.url,token:k.token};if(s==="farm"){let T=u,G={...S,...M?{contextWrite:M}:{},..._?{claude:{oauthToken:_}}:{},youtrack:v},Ve=S.github?.token;if(E.host==="github"&&Ve)try{let ae=xc(`devpipe-${f}`);await Sc(E,Ve,ae.publicKey,`devpipe-${f}`),G.contextSsh={privateKey:ae.privateKey},I.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(ae){I.warn(`could not set up Context Repo SSH deploy key (${ae instanceof Error?ae.message:String(ae)}); the farm will fall back to the token path.`)}let ft={projectId:f,config:{hubUrl:c,cliToken:p,projectId:f},secrets:G,contextRepo:E,projectConfig:Oe(b,$,k.url,g||void 0)},Wn=qe(T.farm.publicKey,JSON.stringify(ft));I.step(`handing project ${f} to farm ${T.farm.name}\u2026`);let Je;try{Je=await vn(c,p,T.farm.farmId,{projectId:f,sealedBundle:Wn})}catch(ae){throw ae instanceof N&&Q(ae.status===409?`farm ${T.farm.name} is offline \u2014 start it and re-run.`:ae.status===504?`farm ${T.farm.name} did not respond in time.`:`HUB \u2192 ${ae.status} ${ae.message}`),ae}Je.ok||Q(`farm rejected provisioning: ${Je.error??"unknown error"}`),await Xo(c,p,f,E,Ve,x.repos,null,S),n.clear(),zo(`done. project ${f} is now hosted on farm ${T.farm.name} (daemon ${Je.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}ou(S),await Zl(e,E.cloneUrl,E.branch),tu(e),a&&await yh(e);{let T=Rt(e,Ae);Ut(T);let G=Oe(b,$,k.url,g||void 0),Ve=yr(T,G);Ve.length>0&&I.success(`local project config \u2192 .codepipe/{${Ve.join(", ")}}`),kt(f,G,{info:ft=>I.message(ft),warn:ft=>I.warn(ft)})}await eu(e,x.repos);let R={hubUrl:c,cliToken:p,projectId:f,...S,...M?{contextWrite:M}:{},..._?{claude:{oauthToken:_}}:{},youtrack:v};J(R),He({hubUrl:c,cliToken:p,projectId:f,accountEmail:d},f),I.success(`secrets \u2192 ${_e(f)}`),await Xo(c,p,f,E,S.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,x.repos,e,S),n.clear(),zo("done. next: `codepipe up` from this folder \u2014 starts the daemon and an agent worker. (`codepipe` opens the interactive REPL.)")}async function Xo(t,e,r,n,o,i=[],s=null,a={}){let c=await Ol(n,o);if(!c){let d=!1;try{d=await Dl(i,{localRoot:s,tokens:a})}catch{d=!1}if(d){let u=Nl(),m=await ut({message:u.message,options:u.options,initialValue:u.initialValue});if(!Ln(m)&&m===u.proceedValue)try{let{jobId:f}=await Cr(t,e,r,{reindex:!1,backfill:!0});I.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){I.warn(`could not start the retrospective analysis: ${f instanceof Error?f.message:String(f)}. Registration is not affected.`)}}}let l=_l(c),p=await ut({message:l.message,options:l.options,initialValue:l.initialValue});if(!(Ln(p)||p!==l.proceedValue))try{let{jobId:d}=await Cr(t,e,r,{reindex:l.reindex});I.success(`indexing queued (job ${d}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(d){I.warn(`could not start indexing: ${d instanceof Error?d.message:String(d)}. You can retry later \u2014 registration is not affected.`)}}async function fh(t,e){let r;try{r=await Ga(t,e)}catch(c){throw c instanceof N&&Q(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&Q("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=xe(await ut({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=kn(i.farmId,i.publicKey)}catch(c){Q(c instanceof Error?c.message:String(c))}return xe(await tr({message:`confirm farm ${i.name} cred-channel fingerprint:
663
+ `)}function B(E,g,_){let b=g[0]?.workspacePath??"";return E.replace(/\{\{codeDir\}\}/g,b).replace(/\{\{codeRoot\}\}/g,b?b.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,_??"")}function R(E,g,_){let b=E,C=_.includes("::")?"":_.split(":",2)[1]??"",x=P=>{if(!g||!C)return"";try{return fi(tr(g,"tasks",C,P),"utf-8").trim()}catch{return""}};if(b.includes("{{solutionMd}}")){let P=x("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";b=b.replace(/\{\{solutionMd\}\}/g,()=>P)}if(b.includes("{{taskDescription}}")){let P=x("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";b=b.replace(/\{\{taskDescription\}\}/g,()=>P)}return b}let j=E=>{if(l)return;l=!0,console.log(`
664
+ [${E}] shutting down`),p.abort();let g=[...d.keys()];for(let C of d.values())C.abort.abort();let _=new AbortController,b=setTimeout(()=>_.abort(),3e3);(async()=>(await Promise.all(g.map(async C=>{try{await c.releaseJob(C,`sandbox ${E}`,_.signal),console.log(`[${E}] released job ${C}`)}catch(x){let P=x instanceof Error?x.message:String(x);console.warn(`[${E}] release failed: ${P} (sweeper will reclaim)`)}})),clearTimeout(b),k.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>j("SIGINT")),process.on("SIGTERM",()=>j("SIGTERM"));let M=[$("implementation")];e.planningLane!==!1?M.push($("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(M)}async function au(t={profile:void 0}){let e=xe(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Un(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 p=l.toString("utf-8");if(s.push(`msg:${p}`),p!=="pong")try{let d=JSON.parse(p);d.type==="registered"?(a=!!d.ok,clearTimeout(c),r.send("ping")):d.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,p)=>{s.push(`close:${l}:${p?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of n.events)console.log(` ${i}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await q(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=ue(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`)")}import{spawn as uy}from"node:child_process";import{existsSync as ir,mkdirSync as Eu,readFileSync as Pu,readdirSync as py,writeFileSync as ju}from"node:fs";import{join as Et,resolve as Au}from"node:path";import{setTimeout as yi}from"node:timers/promises";import{cancel as dy,confirm as sr,intro as _u,isCancel as eo,log as T,outro as ki,password as ar,select as Qe,spinner as Nu,text as re}from"@clack/prompts";import{simpleGit as ro}from"simple-git";async function nr(t,e,r){return e.host==="github"?Oh(t,e,r):e.host==="gitlab"?Fh(t,e,r):Kh(t,e,r)}async function cu(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 mt(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await lu(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 ft(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await uu(e.gitlabToken,t):o}}return e.bitbucket?(await rr(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await pu(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 lu(t,e){let r=!1;try{r=(await mt(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 uu(t,e){let r=!1;try{r=(await ft(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 pu(t,e){let r=!1;try{r=(await rr(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`}var Nh="https://api.github.com";async function mt(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(Nh+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 Oh(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 Dh(n,e,r),i=await Lh(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=Ht(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await Bh(n,o.owner,o.name,a.path,i)||await Mh(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 Dh(t,e,r){let n=await mt(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 lu(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Uh(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 mt(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 Uh(t,e){let{status:r,data:n}=await mt(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function Lh(t,e,r){let{data:n}=await mt(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function Bh(t,e,r,n,o){let{status:i,data:s}=await mt(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function Mh(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 mt(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}var Gh="https://gitlab.com/api/v4";async function ft(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(Gh+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 Fh(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 ft(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 uu(n,e)} (attach joins an existing Context Repo and never creates one)`);let d=await ft(n,"GET","/user"),u={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(d.data?.username!==e.owner){let f=await ft(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(f.status===404||!f.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);u.namespace_id=f.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let m=await ft(n,"POST","/projects",u);if(!m.data)throw new Error("GitLab create project: empty response");i=m.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Ht(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let d=1;;d++){let m=(await ft(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${d}&ref=${encodeURIComponent(a)}`)).data??[];for(let f of m)l.add(f.path);if(m.length<100)break}let p=c.filter(d=>!l.has(d.path)).map(d=>({action:"create",file_path:d.path,content:d.content}));return p.length>0?await ft(n,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:p}):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}}var Hh="https://api.bitbucket.org/2.0";async function rr(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(Hh+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 Kh(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 rr(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 pu(n,e)} (attach joins an existing Context Repo and never creates one)`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let d=await rr(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(d.status===404||!d.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=d.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Ht(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let d of c)(await rr(n,"GET",`${o}/src/${encodeURIComponent(a)}/${d.path}?format=meta`)).status===404&&l.push(d);if(l.length>0){let d=new URLSearchParams;d.set("message","chore(codepipe): scaffold context repo files"),d.set("branch",a);for(let m of l)d.set(m.path,m.content);if((await rr(n,"POST",`${o}/src`,{form:d})).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 p=i.links?.clone?.find(d=>d.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:p??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var Wh={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function Te(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=Wh[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}import{createHash as Yh}from"node:crypto";import{existsSync as du,mkdirSync as qh,readFileSync as fu,readdirSync as Vh,rmSync as Zn,writeFileSync as Jh}from"node:fs";import{homedir as zh}from"node:os";import{dirname as Xh,join as mi}from"node:path";var Qh=24*60*60*1e3;function mu(){return mi(zh(),".codepipe","init-drafts")}function gi(t){let e=Yh("sha256").update(t).digest("hex").slice(0,16);return mi(mu(),`${e}.json`)}function gu(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=Qh)}function hu(t){let e=gi(t);if(!du(e))return null;try{let r=JSON.parse(fu(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:gu(r.savedAt)?(Zn(e,{force:!0}),null):r}catch{return null}}function hi(t){Zn(gi(t),{force:!0})}function yu(){let t=mu();if(du(t))for(let e of Vh(t)){let r=mi(t,e);try{let n=JSON.parse(fu(r,"utf-8"));gu(n.savedAt)&&Zn(r,{force:!0})}catch{Zn(r,{force:!0})}}}var or=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(){hi(this.cwd)}persist(){let e=gi(this.cwd);qh(Xh(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};Jh(e,JSON.stringify(r,null,2)+`
665
+ `,{mode:384})}};function ku(t){return t?{message:"An index already exists. Re-index the project?",proceedValue:"yes",reindex:!0,options:[{value:"no",label:"No, keep the existing one"},{value:"yes",label:"Yes, re-index"}],initialValue:"no"}:{message:"Index the project repositories? (recommended on first run)",proceedValue:"yes",reindex:!1,options:[{value:"yes",label:"Yes"},{value:"skip",label:"Skip"}],initialValue:"yes"}}function wu(){return{message:"Reconstruct architecture decisions from the existing code first? (deep one-off analysis \u2014 proposes decision drafts you review before they become canonical)",proceedValue:"yes",reindex:!1,options:[{value:"yes",label:"Yes \u2014 analyse and propose decision drafts"},{value:"skip",label:"Skip"}],initialValue:"yes"}}async function bu(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}}import{existsSync as Zh}from"node:fs";import{join as ey}from"node:path";import{simpleGit as ty}from"simple-git";var ry=3,ny=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,oy=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"]);function iy(t){let e=t.split("/");return e[e.length-1]??t}function $u(t){if(t.filter(r=>!ny.test(iy(r))).length>ry)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(oy.has(n))return!0}return!1}async function sy(t){try{let r=(await ty(t).raw(["ls-files"])).split(`
666
+ `).map(n=>n.trim()).filter(Boolean);return $u(r)}catch{return!1}}async function ay(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)?$u(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function vu(t,e){for(let r of t)try{let n=e.localRoot!=null?ey(e.localRoot,r.mountAs??r.name):null;if(n&&Zh(n)?await sy(n):await ay(r,e.tokens))return!0}catch{}return!1}import{existsSync as xu}from"node:fs";import{join as Su}from"node:path";import{simpleGit as Ru}from"simple-git";var cy={info:t=>console.log(t),warn:t=>console.warn(t)};async function qr(t,e,r={}){let n=r.log??cy,o=[];for(let i of e){let s=Su(t,i.mountAs),a=cs(i);if(!xu(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 Ru().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(p){let d=p instanceof Error?p.message:String(p);n.warn(`clone failed for ${i.mountAs}: ${d}`),o.push({mountAs:i.mountAs,status:"error",detail:d})}continue}if(!xu(Su(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=Ru(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!ly(l,a)){n.warn(`${i.mountAs}/ origin (${l||"none"}) != expected (${a}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail: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(p){let d=p instanceof Error?p.message:String(p);n.warn(`fetch failed for ${i.mountAs}: ${d}`),o.push({mountAs:i.mountAs,status:"error",detail:d})}}return o}function ly(t,e){return Tu(t)===Tu(e)}function Tu(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function Iu(t={}){let e=ve();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 qr(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 Cu=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function Z(t){dy(t),process.exit(1)}function ge(t){return eo(t)&&Z("aborted"),t}function J(t){return eo(t)&&Z("aborted"),typeof t=="string"?t:""}async function Ou(t={}){_u("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();yu();let r=hu(e),n,o=!1;r&&Object.keys(r.answers).length>0?ge(await sr({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(T.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new or(e,r),o=!0):(hi(e),n=new or(e)):n=new or(e);let i=t.force===!0?null:await bi(e),s=await n.ask("target",async()=>ge(await Qe({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i,a?T.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||Uu(e,t.force===!0));let c=await n.ask("hubUrl",async()=>J(await re({message:"HUB URL",placeholder:Ae,initialValue:F("HUB_URL")??Ae,validate:A=>A.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>cr()),{cliToken:p,accountEmail:d}=await n.ask("bootstrap",()=>lr(c,l)),u=null;s==="farm"&&(u=await fy(c,p));let m=a?gy(a.parsed.repoName):"",f=await n.ask("projectId",async()=>J(await re({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:A=>$t.test(A.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),y=await n.ask("projectName",async()=>J(await re({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:A=>A.trim().length>0?void 0:"required"})).trim()),k=await n.ask("automationLevel",async()=>ge(await Qe({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"}))),$=await n.ask("trackerProvider",async()=>ge(await Qe({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"}))),h=$==="internal",w=null,I,B=!0;h?I=await n.ask("trackerPrefix",async()=>J(await re({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:br,initialValue:br,validate:A=>cn.test(A.trim())?void 0:"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)"})).trim()):(w=await n.ask("youtrack",()=>Ku()),I=await n.ask("youtrackProjectKey",async()=>J(await re({message:"YouTrack project key",placeholder:"DEV",validate:A=>A.trim().length>0?void 0:"required"})).trim()),B=await n.ask("youtrackWrites",async()=>ge(await sr({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))));let R=n.get("tokens")??{},j=()=>n.set("tokens",R),M=await n.ask("repos",()=>wy(R,l,a,{onCred:j,initial:n.get("reposPartial")??[],onProgress:A=>n.set("reposPartial",A)}));n.delete("reposPartial");let E=await by(await n.ask("contextRepo",()=>Gu(f,M,R,l)),f,M,R,l,j,A=>n.set("contextRepo",A)),{spec:g,mode:_}=E,b;h||(T.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),b=await n.ask("assigneeLogin",async()=>J(await re({message:"your YouTrack login (the assignee value)",...w?.login?{initialValue:w.login}:{},validate:A=>A.trim().length>0?void 0:"required"})).trim()));let C=await n.ask("claudeToken",()=>Iy(s==="farm")),x={projectId:f,name:y,automationLevel:k,repos:M,trackerProvider:$,youtrackProjectKey:I};T.step(`${_==="attach"?"attaching to":"provisioning"} Context Repo ${g.owner}/${g.name} (${g.host})\u2026`);let P;try{P=await nr(x,g,{...Fu(R),youtrackWrites:B,...w?{trackerUrl:w.url}:{},mode:_,log:{info:A=>T.message(A),warn:A=>T.warn(A)}})}catch(A){Z(`Context Repo provisioning failed: ${A instanceof Error?A.message:String(A)}`)}x.contextRepo=P,T.success(`Context Repo ready: ${P.owner}/${P.name}@${P.branch}`),T.step(`registering project on ${c}\u2026`);let D;try{D=await lt(c,p,x)}catch(A){if(A instanceof N&&A.status===409){T.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{D=await q(c,p,f)}catch(ke){throw ke instanceof N&&Z(`HUB \u2192 ${ke.status} ${ke.message}`),ke}}else if(A instanceof N&&A.status===401)n.delete("cliToken"),Z("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(A instanceof N)Z(`HUB \u2192 ${A.status} ${A.message}`);else throw A}let v=D.contextRepo??P;T.success(`project ${D.projectId} ready (${D.provisioningStatus})`);let S=await Ry(v),G=w?{url:w.url,token:w.token}:void 0;if(s==="farm"){let A=u,ke={...R,...S?{contextWrite:S}:{},...C?{claude:{oauthToken:C}}:{},...G?{youtrack:G}:{}},Ze=R.github?.token;if(v.host==="github"&&Ze)try{let ae=cl(`devpipe-${f}`);await ll(v,Ze,ae.publicKey,`devpipe-${f}`),ke.contextSsh={privateKey:ae.privateKey},T.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(ae){T.warn(`could not set up Context Repo SSH deploy key (${ae instanceof Error?ae.message:String(ae)}); the farm will fall back to the token path.`)}let Ge={projectId:f,config:{hubUrl:c,cliToken:p,projectId:f},secrets:ke,contextRepo:v,projectConfig:Le(x,B,w?.url,b||void 0)},ao=ze(A.farm.publicKey,JSON.stringify(Ge));T.step(`handing project ${f} to farm ${A.farm.name}\u2026`);let yt;try{yt=await Ln(c,p,A.farm.farmId,{projectId:f,sealedBundle:ao})}catch(ae){throw ae instanceof N&&Z(ae.status===409?`farm ${A.farm.name} is offline \u2014 start it and re-run.`:ae.status===504?`farm ${A.farm.name} did not respond in time.`:`HUB \u2192 ${ae.status} ${ae.message}`),ae}yt.ok||Z(`farm rejected provisioning: ${yt.error??"unknown error"}`),await wi(c,p,f,v,Ze,D.repos,null,R),n.clear(),ki(`done. project ${f} is now hosted on farm ${A.farm.name} (daemon ${yt.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}Hu(R),await Lu(e,v.cloneUrl,v.branch),Mu(e),a&&await yy(e);{let A=Et(e,Oe);Gt(A);let ke=Le(x,B,w?.url,b||void 0),Ze=Rr(A,ke);Ze.length>0&&T.success(`local project config \u2192 .codepipe/{${Ze.join(", ")}}`),St(f,ke,{info:Ge=>T.message(Ge),warn:Ge=>T.warn(Ge)})}await Bu(e,D.repos);let Q={hubUrl:c,cliToken:p,projectId:f,...R,...S?{contextWrite:S}:{},...C?{claude:{oauthToken:C}}:{},...G?{youtrack:G}:{}};z(Q),qe({hubUrl:c,cliToken:p,projectId:f,accountEmail:d},f),T.success(`secrets \u2192 ${De(f)}`),await wi(c,p,f,v,R.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,D.repos,e,R),n.clear(),ki("done. next: `codepipe up` from this folder \u2014 starts the daemon and an agent worker. (`codepipe` opens the interactive REPL.)")}async function wi(t,e,r,n,o,i=[],s=null,a={}){let c=await bu(n,o);if(!c){let d=!1;try{d=await vu(i,{localRoot:s,tokens:a})}catch{d=!1}if(d){let u=wu(),m=await Qe({message:u.message,options:u.options,initialValue:u.initialValue});if(!eo(m)&&m===u.proceedValue)try{let{jobId:f}=await Mr(t,e,r,{reindex:!1,backfill:!0});T.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){T.warn(`could not start the retrospective analysis: ${f instanceof Error?f.message:String(f)}. Registration is not affected.`)}}}let l=ku(c),p=await Qe({message:l.message,options:l.options,initialValue:l.initialValue});if(!(eo(p)||p!==l.proceedValue))try{let{jobId:d}=await Mr(t,e,r,{reindex:l.reindex});T.success(`indexing queued (job ${d}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(d){T.warn(`could not start indexing: ${d instanceof Error?d.message:String(d)}. You can retry later \u2014 registration is not affected.`)}}async function fy(t,e){let r;try{r=await Tc(t,e)}catch(c){throw c instanceof N&&Z(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&Z("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=ge(await Qe({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=Dn(i.farmId,i.publicKey)}catch(c){Z(c instanceof Error?c.message:String(c))}return ge(await sr({message:`confirm farm ${i.name} cred-channel fingerprint:
619
667
  ${s}
620
- (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||Q("farm fingerprint not confirmed \u2014 aborting."),bn(i.farmId,s),{farm:i,fingerprint:s}}async function Xl(t){Vl(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();Ql(e,t.force===!0);let r=z(await ne({message:"HUB URL",initialValue:F("HUB_URL")??je,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await nr(),{cliToken:o,accountEmail:i}=await or(r,n);I.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await Y(r,o,t.projectId)}catch(d){throw d instanceof N&&Q(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||Q(`project ${t.projectId} has no Context Repo on HUB`);let a=await iu(),c={},l=new Set(s.repos.map(d=>d.host));l.add(s.contextRepo.host);for(let d of l)await Bn(d,c,d===s.contextRepo.host?s.contextRepo.owner:s.repos.find(u=>u.host===d)?.owner,n);ou(c),await Zl(e,s.contextRepo.cloneUrl,s.contextRepo.branch),tu(e);{let d=Rt(e,Ae);Ut(d);let u={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{}},m=Oe(u,!0,a.url),f=yr(d,m);f.length>0&&I.success(`local project config \u2192 .codepipe/{${f.join(", ")}} (defaults \u2014 review and adjust)`),kt(t.projectId,m,{info:y=>I.message(y),warn:y=>I.warn(y)})}await eu(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...c,youtrack:{url:a.url,token:a.token}};J(p),He({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),I.success(`secrets \u2192 ${_e(t.projectId)}`),await Xo(r,o,t.projectId,s.contextRepo,c.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,c),zo("done.")}function Ql(t,e){if(!er(t)){Kl(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=ph(t).filter(o=>!r.has(o));n.length!==0&&(e||Q(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function Qo(t){if(!er(Rt(t,".git")))return null;try{let r=(await Mn(t).remote(["get-url","origin"])||"").toString().trim(),n=r?ve(r):null;return n?{parsed:n,defaultBranch:await mh(t)}:null}catch{return null}}async function mh(t){let e=Mn(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 gh(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return yt.test(e)?e:""}function hh(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function yh(t){let e=Rt(t,".gitignore"),r=er(e)?Wl(e,"utf-8"):"";if(hh(r))return;if(!xe(await tr({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){I.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
668
+ (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||Z("farm fingerprint not confirmed \u2014 aborting."),On(i.farmId,s),{farm:i,fingerprint:s}}async function Du(t){_u(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();Uu(e,t.force===!0);let r=J(await re({message:"HUB URL",initialValue:F("HUB_URL")??Ae,validate:u=>u.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await cr(),{cliToken:o,accountEmail:i}=await lr(r,n);T.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await q(r,o,t.projectId)}catch(u){throw u instanceof N&&Z(`HUB \u2192 ${u.status} ${u.message}`),u}s.contextRepo||Z(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await Ku(),l={},p=new Set(s.repos.map(u=>u.host));p.add(s.contextRepo.host);for(let u of p)await to(u,l,u===s.contextRepo.host?s.contextRepo.owner:s.repos.find(m=>m.host===u)?.owner,n);Hu(l),await Lu(e,s.contextRepo.cloneUrl,s.contextRepo.branch),Mu(e);{let u=Et(e,Oe);Gt(u);let m={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.trackerProvider?{trackerProvider:s.trackerProvider}:{},...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{}},f=Le(m,!0,c?.url),y=Rr(u,f);y.length>0&&T.success(`local project config \u2192 .codepipe/{${y.join(", ")}} (defaults \u2014 review and adjust)`),St(t.projectId,f,{info:k=>T.message(k),warn:k=>T.warn(k)})}await Bu(e,s.repos);let d={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};z(d),qe({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),T.success(`secrets \u2192 ${De(t.projectId)}`),await wi(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),ki("done.")}function Uu(t,e){if(!ir(t)){Eu(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=py(t).filter(o=>!r.has(o));n.length!==0&&(e||Z(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function bi(t){if(!ir(Et(t,".git")))return null;try{let r=(await ro(t).remote(["get-url","origin"])||"").toString().trim(),n=r?Te(r):null;return n?{parsed:n,defaultBranch:await my(t)}:null}catch{return null}}async function my(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 gy(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return $t.test(e)?e:""}function hy(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function yy(t){let e=Et(t,".gitignore"),r=ir(e)?Pu(e,"utf-8"):"";if(hy(r))return;if(!ge(await sr({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){T.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
621
669
  `)?"":`
622
- `;ql(e,r+o+`
670
+ `;ju(e,r+o+`
623
671
  # codepipe workspace (added by \`codepipe init\`)
624
672
  .codepipe/
625
- `),I.success(`.codepipe/ added to ${Yl(e)}`)}function wh(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=uh(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}async function nr(){let t="";try{t=(await Mn().raw(["config","--global","user.email"])||"").trim()}catch{}return z(await ne({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function or(t,e){I.step(`connecting account ${e}`);let r;try{r=await qa(t,e)}catch(s){throw s instanceof Tr&&Q(`${e} is not authorized on this HUB yet.
673
+ `),T.success(`.codepipe/ added to ${Au(e)}`)}function ky(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=uy(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}async function cr(){let t="";try{t=(await ro().raw(["config","--global","user.email"])||"").trim()}catch{}return J(await re({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function lr(t,e){T.step(`connecting account ${e}`);let r;try{r=await jc(t,e)}catch(s){throw s instanceof Br&&Z(`${e} is not authorized on this HUB yet.
626
674
  Sign up at ${t} (registration form on the login screen),
627
675
  wait for the operator to approve it by email, then re-run
628
- \`codepipe init\` with the same email.`),s}r.accountCreated&&I.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&I.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(wh(r.authorizeUrl),I.message(`a browser tab was opened to confirm this CLI:
676
+ \`codepipe init\` with the same email.`),s}r.accountCreated&&T.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&T.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(ky(r.authorizeUrl),T.message(`a browser tab was opened to confirm this CLI:
629
677
  ${r.authorizeUrl}
630
678
  `+(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
631
- otherwise use the emailed link the page offers.`))),r.approvalRequired&&I.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),I.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 Ya(t,r.requestId)}catch(a){I.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await Jo(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&I.message(`connected as ${a} (the account confirmed in the browser).`),I.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&Q("the HUB rejected this account"),s.status==="expired"&&Q("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,I.message(`email confirmed. waiting for the operator to approve your account\u2026
632
- (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await Jo(5e3);continue}await Jo(2e3)}Q("bootstrap timed out")}async function Zl(t,e,r){let n=Rt(t,Ae);if(er(Rt(n,".git"))){I.message(`${n} already cloned \u2014 skipping`);return}er(n)&&Q(`${n} exists but is not a git repo \u2014 remove it and re-run`),Kl(n,{recursive:!0}),I.step(`cloning Context Repo \u2192 ${n}`);try{await Mn().clone(e,n,["--branch",r]),I.success(`cloned ${e}`)}catch(o){Q(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function eu(t,e){if(e.length===0)return;I.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 Nr(t,r,{log:{info:o=>I.message(o),warn:o=>I.warn(o)}});for(let o of n)I.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function tu(t){let e=Rt(t,Ae,".gitignore"),r="";if(er(e)&&(r=Wl(e,"utf-8")),Hl.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
679
+ otherwise use the emailed link the page offers.`))),r.approvalRequired&&T.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),T.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 Ac(t,r.requestId)}catch(a){T.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await yi(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&T.message(`connected as ${a} (the account confirmed in the browser).`),T.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&Z("the HUB rejected this account"),s.status==="expired"&&Z("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,T.message(`email confirmed. waiting for the operator to approve your account\u2026
680
+ (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await yi(5e3);continue}await yi(2e3)}Z("bootstrap timed out")}async function Lu(t,e,r){let n=Et(t,Oe);if(ir(Et(n,".git"))){T.message(`${n} already cloned \u2014 skipping`);return}ir(n)&&Z(`${n} exists but is not a git repo \u2014 remove it and re-run`),Eu(n,{recursive:!0}),T.step(`cloning Context Repo \u2192 ${n}`);try{await ro().clone(e,n,["--branch",r]),T.success(`cloned ${e}`)}catch(o){Z(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function Bu(t,e){if(e.length===0)return;T.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 qr(t,r,{log:{info:o=>T.message(o),warn:o=>T.warn(o)}});for(let o of n)T.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function Mu(t){let e=Et(t,Oe,".gitignore"),r="";if(ir(e)&&(r=Pu(e,"utf-8")),Cu.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
633
681
  `)||r.length===0?"":`
634
- `,i=Hl.join(`
682
+ `,i=Cu.join(`
635
683
  `)+`
636
- `;ql(e,r+o+(r?`
637
- `:"")+i),I.message(`appended runtime entries to ${Yl(e)}`)}async function bh(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;I.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await Bn(s.host,t,s.owner,e),i?.();let c=z(await ne({message:"repo logical name (used inside Context Repo paths)",placeholder:s.repoName,initialValue:s.repoName,validate:p=>p.trim().length>0?void 0:"required"})).trim(),l=z(await ne({message:"default branch",placeholder:a,initialValue:a,validate:p=>p.trim().length>0?void 0:"required"})).trim();o.push({name:c,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:l,mountAs:"."}),n.onProgress?.(o)}for(;xe(await tr({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=z(await ne({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:m=>!m||!m.trim()||ve(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=ve(a);I.message(`${c.host}: ${c.owner}/${c.repoName}`),await Bn(c.host,t,c.owner,e),i?.();let l=z(await ne({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(),p=z(await ne({message:"default branch (optional)",placeholder:"main"})).trim(),d=z(await ne({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),u={name:l,host:c.host,owner:c.owner,repoName:c.repoName};p&&(u.defaultBranch=p),d&&d!==l&&(u.mountAs=d),o.push(u),n.onProgress?.(o)}return o}async function ru(t,e,r,n){I.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let o=xe(await ut({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));o==="attach"&&I.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let i=e[0]?.host,s=e[0]?.owner,a;if(i&&s){let c=z(await ne({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:Fe(t),validate:p=>{let d=(p??"").trim();if(!d)return"required";if(!ve(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(),l=ve(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await $h(),l=z(await ne({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:d=>d.trim().length>0?void 0:"required"})).trim(),p=z(await ne({message:"Context Repo name",placeholder:Fe(t),initialValue:Fe(t),validate:d=>d.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:p}}return{spec:a,mode:o}}function nu(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??At()}}async function kh(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await Bn(c.host,n,c.owner,o),i?.();let p=Jl();p.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let d=await xl(c,nu(n),{explain:l==="attach"});if(d.found===!0)return p.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(d.found==="unknown")return p.stop(`could not check ${c.owner}/${c.name} (${d.detail}) \u2014 continuing`,1),a;if(l==="create")return p.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;p.stop(d.detail,1);let u=xe(await ut({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(u==="abort"&&Q("aborted"),u==="create")return a={spec:c,mode:"create"},s(a),a;a=await ru(e,r,n,o),s(a)}}async function $h(){return xe(await ut({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Or(t,e){let r=Jl();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 ou(t){xr(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Sr(t.gitlab?.token??process.env.GITLAB_TOKEN),Rr(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Bn(t,e,r,n){if(!e[t])if(t==="github"){let o=await vh(r);o?e.github=o:I.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let o=await xh(r,n);o?e.bitbucket=o:I.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 o=await Sh();o?e.gitlab=o:I.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function vh(t){for(;;){let e=z(await rr({message:`GitHub PAT \u2014 blank to skip
684
+ `;ju(e,r+o+(r?`
685
+ `:"")+i),T.message(`appended runtime entries to ${Au(e)}`)}async function wy(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;T.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await to(s.host,t,s.owner,e),i?.();let c=J(await re({message:"repo logical name (used inside Context Repo paths)",placeholder:s.repoName,initialValue:s.repoName,validate:p=>p.trim().length>0?void 0:"required"})).trim(),l=J(await re({message:"default branch",placeholder:a,initialValue:a,validate:p=>p.trim().length>0?void 0:"required"})).trim();o.push({name:c,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:l,mountAs:"."}),n.onProgress?.(o)}for(;ge(await sr({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=J(await re({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:m=>!m||!m.trim()||Te(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=Te(a);T.message(`${c.host}: ${c.owner}/${c.repoName}`),await to(c.host,t,c.owner,e),i?.();let l=J(await re({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(),p=J(await re({message:"default branch (optional)",placeholder:"main"})).trim(),d=J(await re({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),u={name:l,host:c.host,owner:c.owner,repoName:c.repoName};p&&(u.defaultBranch=p),d&&d!==l&&(u.mountAs=d),o.push(u),n.onProgress?.(o)}return o}async function Gu(t,e,r,n){T.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let o=ge(await Qe({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));o==="attach"&&T.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let i=e[0]?.host,s=e[0]?.owner,a;if(i&&s){let c=J(await re({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:Ye(t),validate:p=>{let d=(p??"").trim();if(!d)return"required";if(!Te(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(),l=Te(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await $y(),l=J(await re({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:d=>d.trim().length>0?void 0:"required"})).trim(),p=J(await re({message:"Context Repo name",placeholder:Ye(t),initialValue:Ye(t),validate:d=>d.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:p}}return{spec:a,mode:o}}function Fu(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??Ut()}}async function by(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await to(c.host,n,c.owner,o),i?.();let p=Nu();p.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let d=await cu(c,Fu(n),{explain:l==="attach"});if(d.found===!0)return p.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(d.found==="unknown")return p.stop(`could not check ${c.owner}/${c.name} (${d.detail}) \u2014 continuing`,1),a;if(l==="create")return p.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;p.stop(d.detail,1);let u=ge(await Qe({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(u==="abort"&&Z("aborted"),u==="create")return a={spec:c,mode:"create"},s(a),a;a=await Gu(e,r,n,o),s(a)}}async function $y(){return ge(await Qe({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Vr(t,e){let r=Nu();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 Hu(t){Nr(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Or(t.gitlab?.token??process.env.GITLAB_TOKEN),Dr(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function to(t,e,r,n){if(!e[t])if(t==="github"){let o=await vy(r);o?e.github=o:T.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let o=await xy(r,n);o?e.bitbucket=o:T.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 o=await Sy();o?e.gitlab=o:T.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function vy(t){for(;;){let e=J(await ar({message:`GitHub PAT \u2014 blank to skip
638
686
  classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
639
687
  fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
640
688
  if org: approve token in org Settings \u2192 Personal access tokens.
641
689
  (Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo;
642
- set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await Or("GitHub",()=>Ze(e,t?{owner:t}:void 0)))return{token:e};I.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function xh(t,e){for(I.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
690
+ set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await Vr("GitHub",()=>nt(e,t?{owner:t}:void 0)))return{token:e};T.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function xy(t,e){for(T.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
643
691
  How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
644
692
  'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes: read:account,
645
693
  read:repository:bitbucket + write:repository:bitbucket, write:pullrequest:bitbucket
646
694
  (+ admin:repository:bitbucket if this token will provision the Context Repo).
647
- The token is shown ONCE \u2014 copy it right away.`);;){let r=z(await ne({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:o=>!o||!o.trim()||o.includes("@")?void 0:"must be an email"})).trim();if(!r)return;let n=z(await rr({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!n){I.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await Or("Bitbucket",()=>et(r,n,t)))return{email:r,apiToken:n};I.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function Sh(){for(;;){let t=z(await rr({message:`GitLab PAT \u2014 blank to skip
648
- scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Or("GitLab",()=>tt(t))){let e=await Ps(t);return e&&I.warn(e),{token:t}}I.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function Rh(t){if(xe(await tr({message:`Issue a separate context-write token (scoped to the Context Repo only)?
695
+ The token is shown ONCE \u2014 copy it right away.`);;){let r=J(await re({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:o=>!o||!o.trim()||o.includes("@")?void 0:"must be an email"})).trim();if(!r)return;let n=J(await ar({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!n){T.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await Vr("Bitbucket",()=>ot(r,n,t)))return{email:r,apiToken:n};T.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function Sy(){for(;;){let t=J(await ar({message:`GitLab PAT \u2014 blank to skip
696
+ scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Vr("GitLab",()=>it(t))){let e=await Zs(t);return e&&T.warn(e),{token:t}}T.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function Ry(t){if(ge(await sr({message:`Issue a separate context-write token (scoped to the Context Repo only)?
649
697
  Without it the SANDBOX pushes delivery commits with the project ${t.host}
650
698
  credential. A scoped token hardens setups where the SANDBOX runs outside
651
- your trusted network.`,initialValue:!1})))for(t.host==="github"?I.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
699
+ your trusted network.`,initialValue:!1})))for(t.host==="github"?T.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
652
700
  permissions Contents: Read and write + Workflows: Read and write (Workflows is
653
- required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):I.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
654
- (${t.host==="gitlab"?"project access token, 'write_repository' scope":"Bitbucket repository access token, Repositories: Read & write \u2014 the only Bitbucket credential scopeable to a single repo; an account-wide API token would defeat the scoping"}).`);;){let r=z(await rr({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await Or("contextWrite",()=>Th(r,t)))return{token:r};I.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function Th(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n;try{n=await fetch(`https://api.github.com/repos/${e.owner}/${e.name}`,{headers:r})}catch(i){throw new Error(`cannot reach api.github.com (${i instanceof Error?i.message:String(i)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the PAT)");if(n.status===404)throw new Error(`token cannot see ${e.owner}/${e.name} (404) \u2014 scope the fine-grained PAT to that repo and approve it in the org, or use a classic PAT with 'repo'`);if(!n.ok)throw new Error(`GitHub \u2192 ${n.status} ${n.statusText}`);let o=await n.json();if(o.permissions&&o.permissions.push===!1)throw new Error(`token has no write access to ${e.owner}/${e.name} \u2014 needs Contents: write`);return o.full_name??`${e.owner}/${e.name}`}async function Ch(t){if(no()?.claude?.oauthToken&&!t)return I.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`)."),"";I.message("Claude login \u2014 pipeline agents run on your Claude subscription.\n Get a token: install Claude Code (https://claude.com/claude-code), run\n `claude setup-token` in a terminal and paste the result here."+(t?`
655
- Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=z(await rr({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||I.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`."),r):(I.warn(t?"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`."),"")}async function iu(){for(;;){let t=z(await ne({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=z(await rr({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Or("YouTrack",()=>nt({baseUrl:t,token:e}))){let r=await aa({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}I.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as Ih}from"node:fs";function oe(t){throw new Error(t)}function ie(t,e){return(typeof t!="string"||t.trim().length===0)&&oe(`config: '${e}' must be a non-empty string`),t.trim()}function Ur(t,e){if(t==null)return;typeof t!="string"&&oe(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function jh(t){(!t||typeof t!="object")&&oe("config: expected a JSON object");let e=t,r=ie(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||oe("config: 'hubUrl' must start with http(s)://");let n=ie(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&oe("config: 'project' is required");let i=o,s=ie(i.id,"project.id");yt.test(s)||oe("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=ie(i.name,"project.name"),c=ie(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&oe("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||oe("config: 'project.repos' must be an array");let p=l.map((h,$)=>{(!h||typeof h!="object")&&oe(`config: project.repos[${$}] must be an object`);let S=h,B=ie(S.host,`project.repos[${$}].host`);B!=="github"&&B!=="bitbucket"&&B!=="gitlab"&&oe(`config: project.repos[${$}].host must be 'github', 'bitbucket' or 'gitlab'`);let j={name:ie(S.name,`project.repos[${$}].name`),host:B,owner:ie(S.owner,`project.repos[${$}].owner`),repoName:ie(S.repoName,`project.repos[${$}].repoName`)},A=Ur(S.defaultBranch,`project.repos[${$}].defaultBranch`);A&&(j.defaultBranch=A);let L=Ur(S.mountAs,`project.repos[${$}].mountAs`);return L&&(j.mountAs=L),j}),d=i.contextRepo;(!d||typeof d!="object")&&oe("config: 'project.contextRepo' is required");let u=d,m=Ur(u.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&oe("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:m,owner:ie(u.owner,"project.contextRepo.owner"),name:Ur(u.name,"project.contextRepo.name")??Fe(s)},y={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:p,contextRepo:f}},w=Ur(i.youtrackProjectKey,"project.youtrackProjectKey");w&&(y.project.youtrackProjectKey=w),i.index!==void 0&&(typeof i.index!="boolean"&&oe("config: 'project.index' must be a boolean"),y.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&oe("config: 'project.youtrackWrites' must be a boolean"),y.project.youtrackWrites=i.youtrackWrites);let k=e.secrets;if(k!==void 0){(typeof k!="object"||k===null)&&oe("config: 'secrets' must be an object");let h=k,$={};if(h.github){let S=h.github;$.github={token:ie(S.token,"secrets.github.token")}}if(h.bitbucket){let S=h.bitbucket;$.bitbucket={email:ie(S.email,"secrets.bitbucket.email"),apiToken:ie(S.apiToken,"secrets.bitbucket.apiToken")}}if(h.gitlab){let S=h.gitlab;$.gitlab={token:ie(S.token,"secrets.gitlab.token")}}if(h.youtrack){let S=h.youtrack;$.youtrack={url:ie(S.url,"secrets.youtrack.url").replace(/\/$/,""),token:ie(S.token,"secrets.youtrack.token")}}if(h.contextWrite){let S=h.contextWrite;$.contextWrite={token:ie(S.token,"secrets.contextWrite.token")}}y.secrets=$}return y}async function Eh(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Ph(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await Ze(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${n}`)}if(e.bitbucket){let r=t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:t.project.repos.find(o=>o.host==="bitbucket")?.owner,n=await et(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${n}`)}if(e.gitlab){let r=await tt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await nt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function su(t){let e=!t.configPath||t.configPath==="-"?await Eh():Ih(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(u){oe(`config: invalid JSON \u2014 ${u instanceof Error?u.message:String(u)}`)}let n=jh(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 Ph(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 Qt(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??At(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:u=>console.log(` ${u}`),warn:u=>console.warn(` ${u}`)}})}catch(u){oe(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let p;try{p=await ot(o,i,a)}catch(u){if(u instanceof N&&u.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),p=await Y(o,i,s.id);else if(u instanceof N)oe(`HUB \u2192 ${u.status} ${u.message}`);else throw u}console.log(`project ${p.projectId} ready (${p.provisioningStatus})`);let d={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(J(d),He({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${_e(s.id)}`),kt(s.id,Oe(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url),{info:u=>console.log(u),warn:u=>console.warn(u)}),s.index)try{let{jobId:u}=await Cr(o,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${u}); runs once a SANDBOX claims it.`)}catch(u){console.warn(`could not enqueue index job: ${u instanceof Error?u.message:String(u)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}import{cancel as au,intro as cu,isCancel as lu,log as Zo,outro as Ah,password as uu}from"@clack/prompts";async function _h(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function pu(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await _h(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){cu("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Zo.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await uu({message:"Claude OAuth token"});lu(i)&&(au("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),is({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${en()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=be(t.profile);if(!e){cu(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Zo.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await uu({message:"Claude OAuth token"});lu(i)&&(au("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=D(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},J(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Zo.success("Claude OAuth token saved."),Ah("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as Nh,confirm as Oh,intro as Uh,isCancel as du,log as le,outro as Dh,select as fu,text as pt}from"@clack/prompts";function mu(t){Nh(t),process.exit(1)}function ir(t){return du(t)&&mu("aborted"),t}function Dr(t){return du(t)&&mu("aborted"),typeof t=="string"?t:""}async function Lh(t,e){let r=ir(await fu({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=Dr(await pt({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=Dr(await pt({message:"Context Repo name",placeholder:Fe(t),initialValue:Fe(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function gu(t={profile:void 0}){let e=be(t.profile);Uh(`codepipe project add \u2192 ${e.hubUrl}`);let r=ir(await pt({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:u=>yt.test(u.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=ir(await pt({message:"project name (human-readable)",placeholder:"CodePartner",validate:u=>u.trim().length>0?void 0:"required"})).trim(),o=ir(await fu({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=ir(await pt({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=ir(await Oh({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let u=Dr(await pt({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:k=>!k||!k.trim()||ve(k)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!u)break;let m=ve(u);le.message(`${m.host}: ${m.owner}/${m.repoName}`);let f=Dr(await pt({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:k=>k.trim().length>0?void 0:"required"})).trim(),y=Dr(await pt({message:"default branch (optional)",placeholder:"main"})).trim(),w={name:f,host:m.host,owner:m.owner,repoName:m.repoName};y&&(w.defaultBranch=y),a.push(w)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await Lh(r,a),p=D(e.projectId);le.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let d;try{d=await Qt(c,l,{githubToken:p?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:p?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:p?.bitbucket??At(),youtrackWrites:s,trackerUrl:p?.youtrack?.url,log:{info:u=>le.message(u),warn:u=>le.warn(u)}})}catch(u){le.error(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}c.contextRepo=d,le.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let u=await ot(e.hubUrl,e.cliToken,c);le.success(`project "${u.projectId}" \u2014 ${u.provisioningStatus}`),kt(r,Oe(c,s,p?.youtrack?.url),{info:m=>le.message(m),warn:m=>le.warn(m)}),u.contextRepo&&(le.message(` context repo: ${u.contextRepo.owner}/${u.contextRepo.name} (${u.contextRepo.cloneUrl})`),le.message(` branch: ${u.contextRepo.branch}`)),u.provisioningError&&le.error(` error: ${u.provisioningError}`),Dh("done")}catch(u){u instanceof N?(le.error(`HUB \u2192 ${u.status} ${u.message}`),u.payload&&typeof u.payload=="object"&&le.message(JSON.stringify(u.payload,null,2))):le.error(u instanceof Error?u.message:String(u)),process.exit(1)}}import{existsSync as Bh,rmSync as Mh}from"node:fs";import{confirm as Gh,intro as Fh,isCancel as Hh,log as dt,outro as Kh,spinner as Wh}from"@clack/prompts";function De(t){dt.error(t),process.exit(1)}var hu=t=>t.trim().replace(/\/+$/,"");async function yu(t){Fh("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??we()?.spec.projectId??void 0;e||De("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=Re(e);r||De(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=hu(r.hubUrl),o=r.projectId,i=hu(t.hub);i.startsWith("http")||De("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&De(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let k=Wh();k.start(`reading project ${o} from ${n}\u2026`);try{l=await Y(n,r.cliToken,o),k.stop(`read project ${o} (${l.name})`)}catch(h){throw k.stop("could not read the source project",1),h instanceof N&&De(`source HUB ${n} \u2192 ${h.status} ${h.message}. The source HUB must be reachable with a valid token to move a project.`),h}}l.contextRepo||De(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let p=D(o),d=(t.account??r.accountEmail??await nr()).trim().toLowerCase();if(dt.message(`move project '${o}'
701
+ required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):T.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
702
+ (${t.host==="gitlab"?"project access token, 'write_repository' scope":"Bitbucket repository access token, Repositories: Read & write \u2014 the only Bitbucket credential scopeable to a single repo; an account-wide API token would defeat the scoping"}).`);;){let r=J(await ar({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await Vr("contextWrite",()=>Ty(r,t)))return{token:r};T.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function Ty(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n;try{n=await fetch(`https://api.github.com/repos/${e.owner}/${e.name}`,{headers:r})}catch(i){throw new Error(`cannot reach api.github.com (${i instanceof Error?i.message:String(i)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the PAT)");if(n.status===404)throw new Error(`token cannot see ${e.owner}/${e.name} (404) \u2014 scope the fine-grained PAT to that repo and approve it in the org, or use a classic PAT with 'repo'`);if(!n.ok)throw new Error(`GitHub \u2192 ${n.status} ${n.statusText}`);let o=await n.json();if(o.permissions&&o.permissions.push===!1)throw new Error(`token has no write access to ${e.owner}/${e.name} \u2014 needs Contents: write`);return o.full_name??`${e.owner}/${e.name}`}async function Iy(t){if(bo()?.claude?.oauthToken&&!t)return T.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`)."),"";T.message("Claude login \u2014 pipeline agents run on your Claude subscription.\n Get a token: install Claude Code (https://claude.com/claude-code), run\n `claude setup-token` in a terminal and paste the result here."+(t?`
703
+ Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=J(await ar({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||T.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`."),r):(T.warn(t?"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`."),"")}async function Ku(){for(;;){let t=J(await re({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=J(await ar({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Vr("YouTrack",()=>ct({baseUrl:t,token:e}))){let r=await Ba({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}T.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as Cy}from"node:fs";function se(t){throw new Error(t)}function ce(t,e){return(typeof t!="string"||t.trim().length===0)&&se(`config: '${e}' must be a non-empty string`),t.trim()}function Jr(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 Ey(t){(!t||typeof t!="object")&&se("config: expected a JSON object");let e=t,r=ce(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||se("config: 'hubUrl' must start with http(s)://");let n=ce(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&se("config: 'project' is required");let i=o,s=ce(i.id,"project.id");$t.test(s)||se("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=ce(i.name,"project.name"),c=ce(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 p=l.map((h,w)=>{(!h||typeof h!="object")&&se(`config: project.repos[${w}] must be an object`);let I=h,B=ce(I.host,`project.repos[${w}].host`);B!=="github"&&B!=="bitbucket"&&B!=="gitlab"&&se(`config: project.repos[${w}].host must be 'github', 'bitbucket' or 'gitlab'`);let R={name:ce(I.name,`project.repos[${w}].name`),host:B,owner:ce(I.owner,`project.repos[${w}].owner`),repoName:ce(I.repoName,`project.repos[${w}].repoName`)},j=Jr(I.defaultBranch,`project.repos[${w}].defaultBranch`);j&&(R.defaultBranch=j);let M=Jr(I.mountAs,`project.repos[${w}].mountAs`);return M&&(R.mountAs=M),R}),d=i.contextRepo;(!d||typeof d!="object")&&se("config: 'project.contextRepo' is required");let u=d,m=Jr(u.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&se("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:m,owner:ce(u.owner,"project.contextRepo.owner"),name:Jr(u.name,"project.contextRepo.name")??Ye(s)},y={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:p,contextRepo:f}},k=Jr(i.youtrackProjectKey,"project.youtrackProjectKey");k&&(y.project.youtrackProjectKey=k),i.index!==void 0&&(typeof i.index!="boolean"&&se("config: 'project.index' must be a boolean"),y.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&se("config: 'project.youtrackWrites' must be a boolean"),y.project.youtrackWrites=i.youtrackWrites);let $=e.secrets;if($!==void 0){(typeof $!="object"||$===null)&&se("config: 'secrets' must be an object");let h=$,w={};if(h.github){let I=h.github;w.github={token:ce(I.token,"secrets.github.token")}}if(h.bitbucket){let I=h.bitbucket;w.bitbucket={email:ce(I.email,"secrets.bitbucket.email"),apiToken:ce(I.apiToken,"secrets.bitbucket.apiToken")}}if(h.gitlab){let I=h.gitlab;w.gitlab={token:ce(I.token,"secrets.gitlab.token")}}if(h.youtrack){let I=h.youtrack;w.youtrack={url:ce(I.url,"secrets.youtrack.url").replace(/\/$/,""),token:ce(I.token,"secrets.youtrack.token")}}if(h.contextWrite){let I=h.contextWrite;w.contextWrite={token:ce(I.token,"secrets.contextWrite.token")}}y.secrets=w}return y}async function Py(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function jy(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await nt(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${n}`)}if(e.bitbucket){let r=t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:t.project.repos.find(o=>o.host==="bitbucket")?.owner,n=await ot(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${n}`)}if(e.gitlab){let r=await it(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await ct({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Wu(t){let e=!t.configPath||t.configPath==="-"?await Py():Cy(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(u){se(`config: invalid JSON \u2014 ${u instanceof Error?u.message:String(u)}`)}let n=Ey(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 jy(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 nr(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??Ut(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:u=>console.log(` ${u}`),warn:u=>console.warn(` ${u}`)}})}catch(u){se(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let p;try{p=await lt(o,i,a)}catch(u){if(u instanceof N&&u.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),p=await q(o,i,s.id);else if(u instanceof N)se(`HUB \u2192 ${u.status} ${u.message}`);else throw u}console.log(`project ${p.projectId} ready (${p.provisioningStatus})`);let d={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(z(d),qe({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${De(s.id)}`),St(s.id,Le(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url),{info:u=>console.log(u),warn:u=>console.warn(u)}),s.index)try{let{jobId:u}=await Mr(o,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${u}); runs once a SANDBOX claims it.`)}catch(u){console.warn(`could not enqueue index job: ${u instanceof Error?u.message:String(u)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}import{cancel as Yu,intro as qu,isCancel as Vu,log as $i,outro as Ay,password as Ju}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 zu(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){qu("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),$i.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Ju({message:"Claude OAuth token"});Vu(i)&&(Yu("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Is({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${hn()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=xe(t.profile);if(!e){qu(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),$i.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Ju({message:"Claude OAuth token"});Vu(i)&&(Yu("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=L(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},z(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):($i.success("Claude OAuth token saved."),Ay("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as Ny,confirm as Oy,intro as Dy,isCancel as Xu,log as pe,outro as Uy,select as Qu,text as gt}from"@clack/prompts";function Zu(t){Ny(t),process.exit(1)}function ur(t){return Xu(t)&&Zu("aborted"),t}function zr(t){return Xu(t)&&Zu("aborted"),typeof t=="string"?t:""}async function Ly(t,e){let r=ur(await Qu({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=zr(await gt({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=zr(await gt({message:"Context Repo name",placeholder:Ye(t),initialValue:Ye(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function ep(t={profile:void 0}){let e=xe(t.profile);Dy(`codepipe project add \u2192 ${e.hubUrl}`);let r=ur(await gt({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:u=>$t.test(u.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=ur(await gt({message:"project name (human-readable)",placeholder:"CodePartner",validate:u=>u.trim().length>0?void 0:"required"})).trim(),o=ur(await Qu({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=ur(await gt({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=ur(await Oy({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let u=zr(await gt({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:$=>!$||!$.trim()||Te($)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!u)break;let m=Te(u);pe.message(`${m.host}: ${m.owner}/${m.repoName}`);let f=zr(await gt({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:$=>$.trim().length>0?void 0:"required"})).trim(),y=zr(await gt({message:"default branch (optional)",placeholder:"main"})).trim(),k={name:f,host:m.host,owner:m.owner,repoName:m.repoName};y&&(k.defaultBranch=y),a.push(k)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await Ly(r,a),p=L(e.projectId);pe.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let d;try{d=await nr(c,l,{githubToken:p?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:p?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:p?.bitbucket??Ut(),youtrackWrites:s,trackerUrl:p?.youtrack?.url,log:{info:u=>pe.message(u),warn:u=>pe.warn(u)}})}catch(u){pe.error(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}c.contextRepo=d,pe.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let u=await lt(e.hubUrl,e.cliToken,c);pe.success(`project "${u.projectId}" \u2014 ${u.provisioningStatus}`),St(r,Le(c,s,p?.youtrack?.url),{info:m=>pe.message(m),warn:m=>pe.warn(m)}),u.contextRepo&&(pe.message(` context repo: ${u.contextRepo.owner}/${u.contextRepo.name} (${u.contextRepo.cloneUrl})`),pe.message(` branch: ${u.contextRepo.branch}`)),u.provisioningError&&pe.error(` error: ${u.provisioningError}`),Uy("done")}catch(u){u instanceof N?(pe.error(`HUB \u2192 ${u.status} ${u.message}`),u.payload&&typeof u.payload=="object"&&pe.message(JSON.stringify(u.payload,null,2))):pe.error(u instanceof Error?u.message:String(u)),process.exit(1)}}import{existsSync as By,rmSync as My}from"node:fs";import{confirm as Gy,intro as Fy,isCancel as Hy,log as ht,outro as Ky,spinner as Wy}from"@clack/prompts";function Me(t){ht.error(t),process.exit(1)}var tp=t=>t.trim().replace(/\/+$/,"");async function rp(t){Fy("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??ve()?.spec.projectId??void 0;e||Me("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=Ce(e);r||Me(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=tp(r.hubUrl),o=r.projectId,i=tp(t.hub);i.startsWith("http")||Me("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&Me(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let $=Wy();$.start(`reading project ${o} from ${n}\u2026`);try{l=await q(n,r.cliToken,o),$.stop(`read project ${o} (${l.name})`)}catch(h){throw $.stop("could not read the source project",1),h instanceof N&&Me(`source HUB ${n} \u2192 ${h.status} ${h.message}. The source HUB must be reachable with a valid token to move a project.`),h}}l.contextRepo||Me(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let p=L(o),d=(t.account??r.accountEmail??await cr()).trim().toLowerCase();if(ht.message(`move project '${o}'
656
704
  from : ${n} (profile ${e})
657
705
  to : ${i} (profile ${s}, project ${a}, account ${d})
658
706
  \u2022 the source registration on the old HUB is left intact (non-destructive)
659
707
  \u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
660
- `+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let k=await Gh({message:"Continue?",initialValue:!0});(Hh(k)||!k)&&De("aborted")}!c&&a===o&&dt.warn(`source and destination share the same project id, so they share one secrets file (${_e(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:u,accountEmail:m}=await or(i,d),f={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:m,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};dt.step(`registering project on ${i}\u2026`);let y;try{y=await ot(i,u,f)}catch(k){if(k instanceof N&&k.status===409){dt.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{y=await Y(i,u,a)}catch(h){throw h instanceof N&&De(`target HUB \u2192 ${h.status} ${h.message}`),h}}else if(k instanceof N&&k.status===403)De(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(k instanceof N)De(`target HUB \u2192 ${k.status} ${k.message}`);else throw k}dt.success(`project ${y.projectId} ready on ${i} (${y.provisioningStatus})`),He({hubUrl:i,cliToken:u,projectId:a,accountEmail:m},s);let w={...p??{},hubUrl:i,cliToken:u,projectId:a};if(delete w.sandboxPins,J(w),dt.success(`profile '${s}' \u2192 ${_e(a)}`),c){let k=Ie(s);Bh(k)&&(Mh(k),dt.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}Kh(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}import{existsSync as ei,rmSync as qh,statSync as Yh}from"node:fs";import{join as Gn,relative as Vh,resolve as Jh}from"node:path";import{cancel as zh,intro as bu,isCancel as Xh,log as te,outro as ku,text as Tt}from"@clack/prompts";import{simpleGit as $u}from"simple-git";function fe(t){zh(t),process.exit(1)}function Ct(t){return Xh(t)&&fe("aborted"),typeof t=="string"?t:""}async function wu(t){try{let e=await $u(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function Qh(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function Zh(t,e){let r=D(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(Qh(r,e)){te.message(`reusing existing ${e} credentials`);return}if(te.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=Ct(await Tt({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=Ct(await Tt({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=Ct(await Tt({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}}J(r),te.success(`saved ${e} credentials`)}async function vu(t){let e=be(t.profile);bu(`codepipe repo add \u2192 project ${e.projectId}`);let r=we()??void 0,n;try{n=(await Y(e.hubUrl,e.cliToken,e.projectId)).repos}catch(h){fe(`could not read project from HUB: ${h instanceof Error?h.message:String(h)}`)}let o=t.target?.trim();if(!o){let h=await wu(process.cwd());h?(o=process.cwd(),te.message(`using the current directory (${h})`)):o=Ct(await Tt({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:$=>$.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(ei(o)&&Yh(o).isDirectory()){i=Jh(o);let h=await wu(i);h||fe(`${i} is not a git repository (no origin remote)`);let $=ve(h);$||fe(`origin ${h} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=$,s=h,te.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let h=ve(o);h||fe(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=h,s=o,te.message(`${a}: ${c}/${l}`)}let p=Ct(await Tt({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:h=>h.trim()?void 0:"required"})).trim();n.some(h=>h.name===p)&&fe(`a repo named "${p}" is already registered`);let d=Ct(await Tt({message:"default branch (optional)",placeholder:"main"})).trim(),u=p;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let h=Vh(r.root,i);u=h===""?".":h}let m=Ct(await Tt({message:"mount_as (directory relative to the workspace root)",placeholder:u,initialValue:u})).trim()||u;n.some(h=>(h.mountAs??h.name)===m)&&fe(`mount_as "${m}" is already used by another repo`),await Zh(e,a);let f={name:p,host:a,owner:c,repoName:l,mountAs:m,...d?{defaultBranch:d}:{}};if(!i){let h=r?Gn(r.root,m):ke(e.projectId,p);if(ei(Gn(h,".git")))te.message(`already cloned at ${h}`);else{te.info(`cloning ${s} \u2192 ${h} \u2026`);try{await $u().clone(s,h),te.success(`cloned into ${h}`)}catch($){fe(`clone failed: ${$ instanceof Error?$.message.trim():String($)}
661
- check that your ${a} credentials grant read access to ${c}/${l}`)}}}let y;try{y=await ec(e.hubUrl,e.cliToken,e.projectId,f)}catch(h){h instanceof N&&fe(`HUB \u2192 ${h.status} ${h.message}`),fe(h instanceof Error?h.message:String(h))}let{updated:w,errors:k}=wr(e.projectId,y.repos,r?.contextDir);for(let h of w)te.message(`updated ${h}`);for(let h of k)te.warn(`could not update ${h.path}: ${h.error}`);te.success(`added "${p}" \u2014 project now has ${y.repos.length} repo(s)`),ku("done")}async function xu(t){let e=be(t.profile);bu(`codepipe repo remove \u2192 project ${e.projectId}`);let r=we()??void 0,n;try{let c=(await Y(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 tc(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof N&&(a.status===404&&fe(`no repo named "${t.name}" in this project`),fe(`HUB \u2192 ${a.status} ${a.message}`)),fe(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=wr(e.projectId,o.repos,r?.contextDir);for(let a of i)te.message(`updated ${a}`);for(let a of s)te.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")te.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?Gn(r.root,n):ke(e.projectId,t.name);if(ei(Gn(a,".git")))try{qh(a,{recursive:!0,force:!0}),te.message(`deleted local clone ${a}`)}catch(c){te.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else te.message(`no local clone found to purge (${a})`)}te.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),ku("done")}async function Su(t){let e=be(t.profile),r;try{r=(await Y(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}`)}}import{spawn as ey}from"node:child_process";import{existsSync as Ru}from"node:fs";import{homedir as ty,hostname as ry}from"node:os";import{join as Fn}from"node:path";async function ny(t,e,r){let n=ce(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${Ie(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 Ka(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 ${Ie(e)} still holds its token.
662
- 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`),os(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function oy(t,e,r){let n=ce(e)!==null;if(!await ny(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 xn(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof N&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof N&&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 N?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 vt({hub:t.hubUrl,token:o,name:r.name??`${ry()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function iy(t,e){let r=ce(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=ue(r.sealPublicKey);if(!D(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=Zr(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 sy(t,e){let r=process.cwd(),n=Fn(r,Ae);if(zr(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(Ru(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 Y(t.hubUrl,t.cliToken,t.projectId)}catch(p){console.warn(`[up] could not fetch the project summary (${p instanceof Error?p.message:String(p)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await Qo(r);if(!Bi(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=D(t.projectId),a={info:p=>console.log(p),warn:p=>console.warn(p)},c=await In({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=Fn(ty(),".codepipe",e?Fn("profiles",e,"context-config"):"context-config");if(sn(c.contextDir,l,a),!Ru(Fn(c.contextDir,"project.yaml"))){Ut(c.contextDir);let p={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};yr(c.contextDir,Oe(p,!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 Tu(t){let{cfg:e,profile:r}=Qr(t.profile);await sy(e,r),await oy(e,r,t),iy(e.projectId,r);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(m,f)=>{let y=w=>k=>{for(let h of k.toString("utf-8").split(`
663
- `))h.length>0&&w.write(`${f} ${h}
664
- `)};m.stdout?.on("data",y(process.stdout)),m.stderr?.on("data",y(process.stderr))},i=(m,f)=>{let y=ey(process.execPath,[n,...f],{stdio:["ignore","pipe","pipe"],env:process.env});return o(y,m),y};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=i("[worker]",[...r?["--profile",r]:[],"worker","start"]),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,p=m=>{if(!l){l=!0,console.log(`
665
- [up] ${m} \u2014 stopping both roles`);for(let{child:f}of c)f.exitCode===null&&f.kill(m);setTimeout(()=>{for(let{name:f,child:y}of c)y.exitCode===null&&(console.warn(`[up] ${f} did not stop \u2014 SIGKILL`),y.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM"));let d=c.map(({name:m,child:f})=>new Promise(y=>{f.on("exit",(w,k)=>y({name:m,code:w??(k?1:0)}))})),u=await Promise.race(d);l||(console.log(`[up] ${u.name} exited (code ${u.code}) \u2014 stopping the other role`),p("SIGTERM")),await Promise.all(d),process.exit(u.code)}import{existsSync as Lu,mkdirSync as py,readFileSync as dy,writeFileSync as fy}from"node:fs";import{homedir as my}from"node:os";import{dirname as gy,join as Bu}from"node:path";import*as ar from"node:readline";import{existsSync as ni,readFileSync as ay,writeFileSync as cy}from"node:fs";import{join as Br}from"node:path";import{simpleGit as ri}from"simple-git";var Cu=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],ly="apply-queue.json";function Iu(t){return Br(t,ly)}function sr(t){let e=Iu(t);if(!ni(e))return{};try{return JSON.parse(ay(e,"utf-8"))}catch{return{}}}function ju(t,e){cy(Iu(t),JSON.stringify(e,null,2)+`
666
- `)}async function Eu(t,e,r,n,o){let i;try{i=await za(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(u){return{ok:!1,message:`claim failed: ${u instanceof Error?u.message:String(u)}`}}let s=[];for(let u of i.repos){let m=t.spec.repos.find(k=>k.name===u.repoName);if(!m)return{ok:!1,message:`repo "${u.repoName}" not in project.yaml \u2014 run /sync`};let f=Br(t.root,m.mountAs);if(!ni(Br(f,".git")))return{ok:!1,message:`${m.mountAs}/ not cloned \u2014 run /sync first`};if(!(await ri(f).status()).isClean())return{ok:!1,message:`${m.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:u,spec:m,dir:f})}let a=[];for(let u of s){let m=ri(u.dir),f=await uy(m),y=u.claimRepo;try{await m.fetch()}catch(h){return await ti(a,o),{ok:!1,message:`fetch failed in ${u.spec.mountAs}: ${Lr(h)}`}}let w=`origin/${y.baseRef}`,k;try{k=await un(m,{contextRepoCloneUrl:y.contextRepoCloneUrl,deliveryRef:y.deliveryRef,deliverySha:y.deliverySha,baseSha:y.baseSha,commitMessage:y.commitMessage})}catch(h){return await ti(a,o),{ok:!1,message:`fetch delivery failed in ${u.spec.mountAs}: ${Lr(h)}`}}a.push({git:m,dir:u.dir,mountAs:u.spec.mountAs,originalRef:f,branch:y.branchName,baseSha:w,deliveryCommit:k,startPoint:w})}let c=[];for(let u of a)try{if(n==="apply"){await u.git.checkout(["-B",u.branch,u.startPoint]),await u.git.raw([...Cu,"cherry-pick",u.deliveryCommit]);let m=(await u.git.revparse(["HEAD"])).trim();c.push({mountAs:u.mountAs,branch:u.branch,baseSha:u.baseSha,appliedSha:m})}else await u.git.checkout(["--detach",u.startPoint]),await u.git.raw([...Cu,"cherry-pick","--no-commit",u.deliveryCommit]),await u.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:u.mountAs,branch:u.branch,baseSha:u.baseSha})}catch(m){return await u.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await ti(a,o),{ok:!1,message:`apply failed in ${u.mountAs}: ${Lr(m)} (rolled back all repos)`}}let l=sr(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},ju(t.contextDir,l);let p=c.map(u=>u.mountAs).join(", "),d=n==="apply"?`review, push branch '${i.repos[0]?.branchName}', then: /applied ${r} --pr <url>`:`review with 'git diff', commit & push yourself, then: /applied ${r} --pr <url>`;return{ok:!0,message:`${n==="apply"?"applied":"unstashed"} ${r} in ${p}
708
+ `+(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 $=await Gy({message:"Continue?",initialValue:!0});(Hy($)||!$)&&Me("aborted")}!c&&a===o&&ht.warn(`source and destination share the same project id, so they share one secrets file (${De(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:u,accountEmail:m}=await lr(i,d),f={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:m,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};ht.step(`registering project on ${i}\u2026`);let y;try{y=await lt(i,u,f)}catch($){if($ instanceof N&&$.status===409){ht.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{y=await q(i,u,a)}catch(h){throw h instanceof N&&Me(`target HUB \u2192 ${h.status} ${h.message}`),h}}else if($ instanceof N&&$.status===403)Me(`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($ instanceof N)Me(`target HUB \u2192 ${$.status} ${$.message}`);else throw $}ht.success(`project ${y.projectId} ready on ${i} (${y.provisioningStatus})`),qe({hubUrl:i,cliToken:u,projectId:a,accountEmail:m},s);let k={...p??{},hubUrl:i,cliToken:u,projectId:a};if(delete k.sandboxPins,z(k),ht.success(`profile '${s}' \u2192 ${De(a)}`),c){let $=je(s);By($)&&(My($),ht.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}Ky(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}import{existsSync as vi,rmSync as Yy,statSync as qy}from"node:fs";import{join as no,relative as Vy,resolve as Jy}from"node:path";import{cancel as zy,intro as op,isCancel as Xy,log as ne,outro as ip,text as Pt}from"@clack/prompts";import{simpleGit as sp}from"simple-git";function he(t){zy(t),process.exit(1)}function jt(t){return Xy(t)&&he("aborted"),typeof t=="string"?t:""}async function np(t){try{let e=await sp(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function Qy(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function Zy(t,e){let r=L(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(Qy(r,e)){ne.message(`reusing existing ${e} credentials`);return}if(ne.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=jt(await Pt({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=jt(await Pt({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=jt(await Pt({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}}z(r),ne.success(`saved ${e} credentials`)}async function ap(t){let e=xe(t.profile);op(`codepipe repo add \u2192 project ${e.projectId}`);let r=ve()??void 0,n;try{n=(await q(e.hubUrl,e.cliToken,e.projectId)).repos}catch(h){he(`could not read project from HUB: ${h instanceof Error?h.message:String(h)}`)}let o=t.target?.trim();if(!o){let h=await np(process.cwd());h?(o=process.cwd(),ne.message(`using the current directory (${h})`)):o=jt(await Pt({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:w=>w.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(vi(o)&&qy(o).isDirectory()){i=Jy(o);let h=await np(i);h||he(`${i} is not a git repository (no origin remote)`);let w=Te(h);w||he(`origin ${h} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=w,s=h,ne.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let h=Te(o);h||he(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=h,s=o,ne.message(`${a}: ${c}/${l}`)}let p=jt(await Pt({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:h=>h.trim()?void 0:"required"})).trim();n.some(h=>h.name===p)&&he(`a repo named "${p}" is already registered`);let d=jt(await Pt({message:"default branch (optional)",placeholder:"main"})).trim(),u=p;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let h=Vy(r.root,i);u=h===""?".":h}let m=jt(await Pt({message:"mount_as (directory relative to the workspace root)",placeholder:u,initialValue:u})).trim()||u;n.some(h=>(h.mountAs??h.name)===m)&&he(`mount_as "${m}" is already used by another repo`),await Zy(e,a);let f={name:p,host:a,owner:c,repoName:l,mountAs:m,...d?{defaultBranch:d}:{}};if(!i){let h=r?no(r.root,m):Se(e.projectId,p);if(vi(no(h,".git")))ne.message(`already cloned at ${h}`);else{ne.info(`cloning ${s} \u2192 ${h} \u2026`);try{await sp().clone(s,h),ne.success(`cloned into ${h}`)}catch(w){he(`clone failed: ${w instanceof Error?w.message.trim():String(w)}
709
+ check that your ${a} credentials grant read access to ${c}/${l}`)}}}let y;try{y=await Bc(e.hubUrl,e.cliToken,e.projectId,f)}catch(h){h instanceof N&&he(`HUB \u2192 ${h.status} ${h.message}`),he(h instanceof Error?h.message:String(h))}let{updated:k,errors:$}=Er(e.projectId,y.repos,r?.contextDir);for(let h of k)ne.message(`updated ${h}`);for(let h of $)ne.warn(`could not update ${h.path}: ${h.error}`);ne.success(`added "${p}" \u2014 project now has ${y.repos.length} repo(s)`),ip("done")}async function cp(t){let e=xe(t.profile);op(`codepipe repo remove \u2192 project ${e.projectId}`);let r=ve()??void 0,n;try{let c=(await q(e.hubUrl,e.cliToken,e.projectId)).repos.find(l=>l.name===t.name);n=c?c.mountAs??c.name:void 0}catch{}let o;try{o=await Mc(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof N&&(a.status===404&&he(`no repo named "${t.name}" in this project`),he(`HUB \u2192 ${a.status} ${a.message}`)),he(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=Er(e.projectId,o.repos,r?.contextDir);for(let a of i)ne.message(`updated ${a}`);for(let a of s)ne.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")ne.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?no(r.root,n):Se(e.projectId,t.name);if(vi(no(a,".git")))try{Yy(a,{recursive:!0,force:!0}),ne.message(`deleted local clone ${a}`)}catch(c){ne.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else ne.message(`no local clone found to purge (${a})`)}ne.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),ip("done")}async function lp(t){let e=xe(t.profile),r;try{r=(await q(e.hubUrl,e.cliToken,e.projectId)).repos}catch(n){console.error(`could not read project from HUB: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(r.length===0){console.log(`project ${e.projectId} has no repos yet \u2014 add one with \`codepipe repo add\``);return}console.log(`project ${e.projectId} \u2014 ${r.length} repo(s):`);for(let n of r){let o=n.mountAs??n.name,i=n.defaultBranch?` @${n.defaultBranch}`:"";console.log(` ${n.name} ${n.host}:${n.owner}/${n.repoName}${i} \u2192 ${o}`)}}import{spawn as ek}from"node:child_process";import{existsSync as up}from"node:fs";import{homedir as tk,hostname as rk}from"node:os";import{join as oo}from"node:path";async function nk(t,e,r){let n=ue(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${je(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 Ec(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 ${je(e)} still holds its token.
710
+ 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`),Ts(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function ok(t,e,r){let n=ue(e)!==null;if(!await nk(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 Bn(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof N&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof N&&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 N?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 Tt({hub:t.hubUrl,token:o,name:r.name??`${rk()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function ik(t,e){let r=ue(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=de(r.sealPublicKey);if(!L(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=gn(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 sk(t,e){let r=process.cwd(),n=oo(r,Oe);if(dn(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(up(n)){console.warn(`[up] ${n} exists but is not this project's workspace \u2014 the context stays under ~/.codepipe/profiles`);return}let o;try{o=await q(t.hubUrl,t.cliToken,t.projectId)}catch(p){console.warn(`[up] could not fetch the project summary (${p instanceof Error?p.message:String(p)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await bi(r);if(!as(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=L(t.projectId),a={info:p=>console.log(p),warn:p=>console.warn(p)},c=await Kn({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=oo(tk(),".codepipe",e?oo("profiles",e,"context-config"):"context-config");if($n(c.contextDir,l,a),!up(oo(c.contextDir,"project.yaml"))){Gt(c.contextDir);let p={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};Rr(c.contextDir,Le(p,!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 pp(t){let{cfg:e,profile:r}=mn(t.profile);await sk(e,r),await ok(e,r,t),ik(e.projectId,r);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(m,f)=>{let y=k=>$=>{for(let h of $.toString("utf-8").split(`
711
+ `))h.length>0&&k.write(`${f} ${h}
712
+ `)};m.stdout?.on("data",y(process.stdout)),m.stderr?.on("data",y(process.stderr))},i=(m,f)=>{let y=ek(process.execPath,[n,...f],{stdio:["ignore","pipe","pipe"],env:process.env});return o(y,m),y};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=i("[worker]",[...r?["--profile",r]:[],"worker","start"]),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,p=m=>{if(!l){l=!0,console.log(`
713
+ [up] ${m} \u2014 stopping both roles`);for(let{child:f}of c)f.exitCode===null&&f.kill(m);setTimeout(()=>{for(let{name:f,child:y}of c)y.exitCode===null&&(console.warn(`[up] ${f} did not stop \u2014 SIGKILL`),y.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM"));let d=c.map(({name:m,child:f})=>new Promise(y=>{f.on("exit",(k,$)=>y({name:m,code:k??($?1:0)}))})),u=await Promise.race(d);l||(console.log(`[up] ${u.name} exited (code ${u.code}) \u2014 stopping the other role`),p("SIGTERM")),await Promise.all(d),process.exit(u.code)}import{existsSync as xp,mkdirSync as pk,readFileSync as dk,writeFileSync as fk}from"node:fs";import{homedir as mk}from"node:os";import{dirname as gk,join as Sp}from"node:path";import*as dr from"node:readline";import{existsSync as Ri,readFileSync as ak,writeFileSync as ck}from"node:fs";import{join as Qr}from"node:path";import{simpleGit as Si}from"simple-git";var dp=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],lk="apply-queue.json";function fp(t){return Qr(t,lk)}function pr(t){let e=fp(t);if(!Ri(e))return{};try{return JSON.parse(ak(e,"utf-8"))}catch{return{}}}function mp(t,e){ck(fp(t),JSON.stringify(e,null,2)+`
714
+ `)}async function gp(t,e,r,n,o){let i;try{i=await Oc(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(u){return{ok:!1,message:`claim failed: ${u instanceof Error?u.message:String(u)}`}}let s=[];for(let u of i.repos){let m=t.spec.repos.find($=>$.name===u.repoName);if(!m)return{ok:!1,message:`repo "${u.repoName}" not in project.yaml \u2014 run /sync`};let f=Qr(t.root,m.mountAs);if(!Ri(Qr(f,".git")))return{ok:!1,message:`${m.mountAs}/ not cloned \u2014 run /sync first`};if(!(await Si(f).status()).isClean())return{ok:!1,message:`${m.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:u,spec:m,dir:f})}let a=[];for(let u of s){let m=Si(u.dir),f=await uk(m),y=u.claimRepo;try{await m.fetch()}catch(h){return await xi(a,o),{ok:!1,message:`fetch failed in ${u.spec.mountAs}: ${Xr(h)}`}}let k=`origin/${y.baseRef}`,$;try{$=await In(m,{contextRepoCloneUrl:y.contextRepoCloneUrl,deliveryRef:y.deliveryRef,deliverySha:y.deliverySha,baseSha:y.baseSha,commitMessage:y.commitMessage})}catch(h){return await xi(a,o),{ok:!1,message:`fetch delivery failed in ${u.spec.mountAs}: ${Xr(h)}`}}a.push({git:m,dir:u.dir,mountAs:u.spec.mountAs,originalRef:f,branch:y.branchName,baseSha:k,deliveryCommit:$,startPoint:k})}let c=[];for(let u of a)try{if(n==="apply"){await u.git.checkout(["-B",u.branch,u.startPoint]),await u.git.raw([...dp,"cherry-pick",u.deliveryCommit]);let m=(await u.git.revparse(["HEAD"])).trim();c.push({mountAs:u.mountAs,branch:u.branch,baseSha:u.baseSha,appliedSha:m})}else await u.git.checkout(["--detach",u.startPoint]),await u.git.raw([...dp,"cherry-pick","--no-commit",u.deliveryCommit]),await u.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:u.mountAs,branch:u.branch,baseSha:u.baseSha})}catch(m){return await u.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await xi(a,o),{ok:!1,message:`apply failed in ${u.mountAs}: ${Xr(m)} (rolled back all repos)`}}let l=pr(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},mp(t.contextDir,l);let p=c.map(u=>u.mountAs).join(", "),d=n==="apply"?`review, push branch '${i.repos[0]?.branchName}', then: /applied ${r} --pr <url>`:`review with 'git diff', commit & push yourself, then: /applied ${r} --pr <url>`;return{ok:!0,message:`${n==="apply"?"applied":"unstashed"} ${r} in ${p}
667
715
  ${d}
668
- or: /abort ${r} --reason "..."`}}function oi(t,e){let r=sr(t);r[e]&&(delete r[e],ju(t,r))}async function ti(t,e){for(let r of t)try{await r.git.raw(["cherry-pick","--quit"]).catch(()=>{}),await r.git.checkout(["-f",r.originalRef]),await r.git.reset(["--hard",r.originalRef]),await r.git.raw(["branch","-D",r.branch]).catch(()=>{})}catch(n){e.warn(`rollback failed in ${r.mountAs}: ${Lr(n)} \u2014 check manually`)}}async function Pu(t,e,r){let o=sr(t.contextDir)[e];if(o){for(let i of o.repos){let s=Br(t.root,i.mountAs);if(!ni(Br(s,".git")))continue;let a=ri(s),c=t.spec.repos.find(p=>p.mountAs===i.mountAs),l=c?`origin/${c.defaultBranch}`:i.baseSha;try{await a.checkout(["-f",l]),await a.reset(["--hard",l]),await a.raw(["branch","-D",i.branch]).catch(()=>{})}catch(p){r.warn(`rollback failed in ${i.mountAs}: ${Lr(p)} \u2014 check manually`)}}oi(t.contextDir,e)}}async function uy(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function Lr(t){return t instanceof Error?t.message.trim():String(t)}var Hn=Bu(my(),".codepipe","history"),Au=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Mu=500,_u=40;async function Gu(){let t=we();t||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let e=D(t.spec.projectId);e||(console.error(`no secrets for project ${t.spec.projectId} at ~/.codepipe/secrets/${t.spec.projectId}.json. run \`codepipe init\` or \`codepipe clone\` to set them up.`),process.exit(1)),hr(e),console.log(`connected to ${e.hubUrl} as project ${t.spec.projectId}`),console.log("type /help to list commands. Ctrl+D or /quit to exit.");let r=sr(t.contextDir),n=Object.keys(r);n.length>0&&console.log(`
716
+ or: /abort ${r} --reason "..."`}}function Ti(t,e){let r=pr(t);r[e]&&(delete r[e],mp(t,r))}async function xi(t,e){for(let r of t)try{await r.git.raw(["cherry-pick","--quit"]).catch(()=>{}),await r.git.checkout(["-f",r.originalRef]),await r.git.reset(["--hard",r.originalRef]),await r.git.raw(["branch","-D",r.branch]).catch(()=>{})}catch(n){e.warn(`rollback failed in ${r.mountAs}: ${Xr(n)} \u2014 check manually`)}}async function hp(t,e,r){let o=pr(t.contextDir)[e];if(o){for(let i of o.repos){let s=Qr(t.root,i.mountAs);if(!Ri(Qr(s,".git")))continue;let a=Si(s),c=t.spec.repos.find(p=>p.mountAs===i.mountAs),l=c?`origin/${c.defaultBranch}`:i.baseSha;try{await a.checkout(["-f",l]),await a.reset(["--hard",l]),await a.raw(["branch","-D",i.branch]).catch(()=>{})}catch(p){r.warn(`rollback failed in ${i.mountAs}: ${Xr(p)} \u2014 check manually`)}}Ti(t.contextDir,e)}}async function uk(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function Xr(t){return t instanceof Error?t.message.trim():String(t)}var io=Sp(mk(),".codepipe","history"),yp=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Rp=500,kp=40;async function Tp(){let t=ve();t||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let e=L(t.spec.projectId);e||(console.error(`no secrets for project ${t.spec.projectId} at ~/.codepipe/secrets/${t.spec.projectId}.json. run \`codepipe init\` or \`codepipe clone\` to set them up.`),process.exit(1)),Sr(e),console.log(`connected to ${e.hubUrl} as project ${t.spec.projectId}`),console.log("type /help to list commands. Ctrl+D or /quit to exit.");let r=pr(t.contextDir),n=Object.keys(r);n.length>0&&console.log(`
669
717
  \u26A0 unfinished local apply: ${n.map(s=>`${s} (${r[s].repos.map(a=>a.mountAs).join(", ")})`).join("; ")}
670
- finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let o=ar.createInterface({input:process.stdin,output:process.stdout,completer:hy,history:Uy(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:o,unread:0,daemon:void 0,follow:!1,logBuffer:[]};Ls(s=>It(i,s)),i.daemon=Tn({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>It(i,s),warn:s=>It(i,s)},onEvent:s=>Ey(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),si(i),o.prompt(),o.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await yy(i,a)){Du(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,si(i),o.prompt()}),o.on("close",()=>{Du(i)})}function hy(t){let e=Au.filter(r=>r.startsWith(t));return[e.length?e:Au,t]}async function yy(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return wy(),!1;case"/status":return await by(t),!1;case"/tasks":return await ky(t,n),!1;case"/task":return await $y(t,n),!1;case"/sync":return await vy(t),!1;case"/logs":return Py(t,n),!1;case"/monitor":return Ay(t),!1;case"/apply":return await Nu(t,n,"apply"),!1;case"/unstash":return await Nu(t,n,"unstash"),!1;case"/applied":return await xy(t,n),!1;case"/abort":return await Sy(t,n),!1;case"/approve":return await Ou(t,n,"approve"),!1;case"/merge":return await Ou(t,n,"merge"),!1;case"/login":return Ty(t,n),!1;case"/secret":return Cy(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function wy(){console.log(["/help show this list","/status connection, project, Context Repo branch, 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 logs / toggle live / clear buffer","/monitor toggle live daemon log streaming (alias /logs follow)","/apply <key> apply task patch on a new branch + commit (local mode)","/unstash <key> apply task patch uncommitted on base commit","/applied <key> --pr U mark applied; --pr repo=URL for multi-repo","/abort <key> --reason roll back local apply, send task back to agent","/approve <key> merge the task's PR(s) (TRACKING, PR mode)","/merge <key> direct-merge the branch to main (TRACKING, no-PR mode)","/login <token> set the Claude OAuth token (not stored in history)","/secret set <k> <v> set a secret (not stored in history)","/secret list list secret keys (no values)","/secret unset <k> remove a secret","/quit stop the daemon and exit"].join(`
671
- `))}async function by(t){let e=t.connection==="registered"?"registered":t.connection==="rejected"?"rejected":t.connection==="offline"?"offline (reconnecting)":"connecting";console.log(` hub: ${t.secrets.hubUrl} (${e})`),console.log(` project: ${t.ws.spec.projectId}`),console.log(` workspace: ${t.ws.root}`);for(let r of t.ws.spec.repos){let n=Lu(Bu(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${n?"present":"missing (run /sync)"}`)}}async function ky(t,e){let r=_y(e,"--phase");try{let n=await Va(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){Gr(n)}}async function $y(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await Ja(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){Gr(n)}}async function vy(t){let e=await Nr(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 Nu(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await Eu(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function xy(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=sr(t.ws.contextDir)[r],i=Ny(e,"--pr");if(i.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let s=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of i){let l=c.indexOf("="),p,d;if(l>0?(p=c.slice(0,l),d=c.slice(l+1)):(d=c,p=o?.repos.length===1?Ry(t,o.repos[0].mountAs):s.length===1?s[0]:""),!p){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${d}`);return}let u=d.match(/(?:pull|pull-requests)\/(\d+)/);if(!u){console.log(` cannot parse PR number from ${d}`);return}a.push({repoName:p,url:d,number:Number(u[1])})}try{let c=await Xa(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);oi(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){Gr(c)}}async function Ou(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await Za(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){Gr(o)}}async function Sy(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=Oy(e,"--reason")||"local apply aborted";await Pu(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await Qa(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){Gr(o)}}function Ry(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function Ty(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},J(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 Cy(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(`
672
- `)}`:" (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}Iy(t.secrets,n,i),J(t.secrets),hr(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}jy(t.secrets,n),J(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function Iy(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 jy(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 Ey(t,e){switch(e.kind){case"connected":t.connection="connecting",It(t,"[hub] connected");break;case"registered":t.connection="registered",It(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Mr(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",It(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Mr(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Mr(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?It(t,`[hub] action ${e.actionType} done`):Mr(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function It(t,e){t.logBuffer.push(e),t.logBuffer.length>Mu&&t.logBuffer.shift(),t.follow&&Mr(t,e)}function Py(t,e){let r=e[0];if(r==="follow"||r==="on"){ii(t,!0);return}if(r==="off"){ii(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(Mu,Number(r)||_u)):_u,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 Ay(t){ii(t,!t.follow)}function ii(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Mr(t,e){ar.cursorTo(process.stdout,0),ar.clearLine(process.stdout,0),process.stdout.write(e+`
673
- `),t.unread+=1,si(t),t.rl.prompt(!0)}function si(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var Uu=!1;function Du(t){Uu||(Uu=!0,Dy(t.rl),t.daemon.stop(),console.log(`
674
- bye.`),setTimeout(()=>process.exit(0),150))}function _y(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function Ny(t,e){let r=[];for(let n=0;n<t.length;n++)t[n]===e&&t[n+1]&&r.push(t[n+1]);return r}function Oy(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function Gr(t){t instanceof N?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function Uy(){if(!Lu(Hn))return[];try{return dy(Hn,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function Dy(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{py(gy(Hn),{recursive:!0}),fy(Hn,r.slice().reverse().join(`
718
+ finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let o=dr.createInterface({input:process.stdin,output:process.stdout,completer:hk,history:Dk(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:o,unread:0,daemon:void 0,follow:!1,logBuffer:[]};ga(s=>At(i,s)),i.daemon=Fn({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>At(i,s),warn:s=>At(i,s)},onEvent:s=>Pk(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),Ci(i),o.prompt(),o.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await yk(i,a)){vp(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,Ci(i),o.prompt()}),o.on("close",()=>{vp(i)})}function hk(t){let e=yp.filter(r=>r.startsWith(t));return[e.length?e:yp,t]}async function yk(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return kk(),!1;case"/status":return await wk(t),!1;case"/tasks":return await bk(t,n),!1;case"/task":return await $k(t,n),!1;case"/sync":return await vk(t),!1;case"/logs":return jk(t,n),!1;case"/monitor":return Ak(t),!1;case"/apply":return await wp(t,n,"apply"),!1;case"/unstash":return await wp(t,n,"unstash"),!1;case"/applied":return await xk(t,n),!1;case"/abort":return await Sk(t,n),!1;case"/approve":return await bp(t,n,"approve"),!1;case"/merge":return await bp(t,n,"merge"),!1;case"/login":return Tk(t,n),!1;case"/secret":return Ik(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function kk(){console.log(["/help show this list","/status connection, project, Context Repo branch, 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 logs / toggle live / clear buffer","/monitor toggle live daemon log streaming (alias /logs follow)","/apply <key> apply task patch on a new branch + commit (local mode)","/unstash <key> apply task patch uncommitted on base commit","/applied <key> --pr U mark applied; --pr repo=URL for multi-repo","/abort <key> --reason roll back local apply, send task back to agent","/approve <key> merge the task's PR(s) (TRACKING, PR mode)","/merge <key> direct-merge the branch to main (TRACKING, no-PR mode)","/login <token> set the Claude OAuth token (not stored in history)","/secret set <k> <v> set a secret (not stored in history)","/secret list list secret keys (no values)","/secret unset <k> remove a secret","/quit stop the daemon and exit"].join(`
719
+ `))}async function wk(t){let e=t.connection==="registered"?"registered":t.connection==="rejected"?"rejected":t.connection==="offline"?"offline (reconnecting)":"connecting";console.log(` hub: ${t.secrets.hubUrl} (${e})`),console.log(` project: ${t.ws.spec.projectId}`),console.log(` workspace: ${t.ws.root}`);for(let r of t.ws.spec.repos){let n=xp(Sp(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${n?"present":"missing (run /sync)"}`)}}async function bk(t,e){let r=_k(e,"--phase");try{let n=await _c(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){en(n)}}async function $k(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await Nc(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){en(n)}}async function vk(t){let e=await qr(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 wp(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await gp(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function xk(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=pr(t.ws.contextDir)[r],i=Nk(e,"--pr");if(i.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let s=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of i){let l=c.indexOf("="),p,d;if(l>0?(p=c.slice(0,l),d=c.slice(l+1)):(d=c,p=o?.repos.length===1?Rk(t,o.repos[0].mountAs):s.length===1?s[0]:""),!p){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${d}`);return}let u=d.match(/(?:pull|pull-requests)\/(\d+)/);if(!u){console.log(` cannot parse PR number from ${d}`);return}a.push({repoName:p,url:d,number:Number(u[1])})}try{let c=await Dc(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);Ti(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){en(c)}}async function bp(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await Lc(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){en(o)}}async function Sk(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=Ok(e,"--reason")||"local apply aborted";await hp(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await Uc(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){en(o)}}function Rk(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function Tk(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},z(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 Ik(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(`
720
+ `)}`:" (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}Ck(t.secrets,n,i),z(t.secrets),Sr(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}Ek(t.secrets,n),z(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function Ck(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 Ek(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 Pk(t,e){switch(e.kind){case"connected":t.connection="connecting",At(t,"[hub] connected");break;case"registered":t.connection="registered",At(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Zr(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",At(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Zr(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Zr(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?At(t,`[hub] action ${e.actionType} done`):Zr(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function At(t,e){t.logBuffer.push(e),t.logBuffer.length>Rp&&t.logBuffer.shift(),t.follow&&Zr(t,e)}function jk(t,e){let r=e[0];if(r==="follow"||r==="on"){Ii(t,!0);return}if(r==="off"){Ii(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(Rp,Number(r)||kp)):kp,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 Ak(t){Ii(t,!t.follow)}function Ii(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Zr(t,e){dr.cursorTo(process.stdout,0),dr.clearLine(process.stdout,0),process.stdout.write(e+`
721
+ `),t.unread+=1,Ci(t),t.rl.prompt(!0)}function Ci(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var $p=!1;function vp(t){$p||($p=!0,Uk(t.rl),t.daemon.stop(),console.log(`
722
+ bye.`),setTimeout(()=>process.exit(0),150))}function _k(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function Nk(t,e){let r=[];for(let n=0;n<t.length;n++)t[n]===e&&t[n+1]&&r.push(t[n+1]);return r}function Ok(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function en(t){t instanceof N?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function Dk(){if(!xp(io))return[];try{return dk(io,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function Uk(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{pk(gk(io),{recursive:!0}),fk(io,r.slice().reverse().join(`
675
723
  `)+`
676
- `)}catch{}}import{hostname as Ly}from"node:os";import{cancel as By,confirm as Fu,intro as My,isCancel as Wu,log as cr,multiselect as Gy,outro as Hu,password as Fy,select as ai,text as ci}from"@clack/prompts";function Fr(t){By(t),process.exit(1)}function lr(t){return Wu(t)&&Fr("aborted"),t}function Kn(t){return Wu(t)&&Fr("aborted"),typeof t=="string"?t:""}function li(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Ku(t,e){try{let{secret:r}=await xn(t,e);return r}catch(r){throw r instanceof N&&r.status===404&&Fr("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 Hy(t,e){if(lr(await ai({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 Wa(t,e);if(o.length>0)return lr(await Gy({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}));cr.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){cr.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return Kn(await ci({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 ui(t){My("codepipe worker \u2014 set up this machine as a runner");let e=ce(t.profile);e&&(cr.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),lr(await Fu({message:"re-register this worker?",initialValue:!1}))||Fr("keeping the existing registration"));let r=Re(t.profile)??Re(),n=Kn(await ci({message:"HUB URL",placeholder:je,initialValue:F("HUB_URL")??r?.hubUrl??je,validate:u=>u.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=lr(await ai({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 Ku(n,a),cr.success("account-issued registration token minted");else if(i==="login"){let u=await nr();a=(await or(n,u)).cliToken,s=await Ku(n,a),cr.success("account-issued registration token minted")}else s=Kn(await Fy({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||Fr("a registration token is required");let c=await Hy(n,a),l=Kn(await ci({message:"worker name",initialValue:Ly(),validate:u=>u.trim().length>0?void 0:"required"})).trim(),p=lr(await ai({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 vt({hub:n,token:s,name:l,projects:c,...p?{llm:p}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),cr.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!lr(await Fu({message:"start the claim-loop now?",initialValue:!0}))){Hu("registered. start later with `codepipe worker`.");return}Hu("starting the claim-loop\u2026"),await _r(t.profile?{profile:t.profile}:{})}function Wy(){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 F("PROFILE")}var re=Wy();Ki(re);Yi();var me=new Ky;me.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(he).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{await Gu()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});me.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 su({configPath:t.config,skipVerify:t.skipVerify===!0}):await zl({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});me.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 ss({...t,profile:re})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});me.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 Xl({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});me.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await Ac({profile:re})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});me.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 Fl({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});me.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 pu({profile:re,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});me.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await vl({profile:re})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});me.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).action(async t=>{try{await Tu({profile:re,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var qu=me.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");qu.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??F("HUB_URL")??Re(re)?.hubUrl??je,r=t.token??F("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&li()){await ui({profile:re});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=F("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??F("WORKER_NAME"),i=t.llm??F("WORKER_LLM");await vt({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...re?{profile:re}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});qu.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ce(re)&&li()){await ui({profile:re});return}await _r(re?{profile:re}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Yu=me.command("project").description("Manage CodePipe projects");Yu.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await gu({profile:re})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Yu.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 yu({...t,cliProfile:re})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var pi=me.command("repo").description("Manage the project's git repositories");pi.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 vu({profile:re,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});pi.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 xu({profile:re,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});pi.command("list").description("List the project's repos").action(async()=>{try{await Su({profile:re})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});me.parseAsync();
724
+ `)}catch{}}import{hostname as Lk}from"node:os";import{cancel as Bk,confirm as Ip,intro as Mk,isCancel as Pp,log as fr,multiselect as Gk,outro as Cp,password as Fk,select as Ei,text as Pi}from"@clack/prompts";function tn(t){Bk(t),process.exit(1)}function mr(t){return Pp(t)&&tn("aborted"),t}function so(t){return Pp(t)&&tn("aborted"),typeof t=="string"?t:""}function ji(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Ep(t,e){try{let{secret:r}=await Bn(t,e);return r}catch(r){throw r instanceof N&&r.status===404&&tn("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 Hk(t,e){if(mr(await Ei({message:"which projects should this worker serve?",options:[{value:"all",label:"all my projects (recommended \u2014 new projects included automatically)"},{value:"selected",label:"only selected projects"}],initialValue:"all"}))==="all")return[];if(e)try{let o=await Pc(t,e);if(o.length>0)return mr(await Gk({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}));fr.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){fr.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return so(await Pi({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 Ai(t){Mk("codepipe worker \u2014 set up this machine as a runner");let e=ue(t.profile);e&&(fr.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),mr(await Ip({message:"re-register this worker?",initialValue:!1}))||tn("keeping the existing registration"));let r=Ce(t.profile)??Ce(),n=so(await Pi({message:"HUB URL",placeholder:Ae,initialValue:F("HUB_URL")??r?.hubUrl??Ae,validate:u=>u.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=mr(await Ei({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 Ep(n,a),fr.success("account-issued registration token minted");else if(i==="login"){let u=await cr();a=(await lr(n,u)).cliToken,s=await Ep(n,a),fr.success("account-issued registration token minted")}else s=so(await Fk({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||tn("a registration token is required");let c=await Hk(n,a),l=so(await Pi({message:"worker name",initialValue:Lk(),validate:u=>u.trim().length>0?void 0:"required"})).trim(),p=mr(await Ei({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 Tt({hub:n,token:s,name:l,projects:c,...p?{llm:p}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),fr.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!mr(await Ip({message:"start the claim-loop now?",initialValue:!0}))){Cp("registered. start later with `codepipe worker`.");return}Cp("starting the claim-loop\u2026"),await Yr(t.profile?{profile:t.profile}:{})}function Wk(){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 F("PROFILE")}var oe=Wk();ds(oe);gs();var ye=new Kk;ye.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(be).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{await Tp()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ye.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 Wu({configPath:t.config,skipVerify:t.skipVerify===!0}):await Ou({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ye.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 Cs({...t,profile:oe})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ye.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 Du({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});ye.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await yl({profile:oe})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ye.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 Iu({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ye.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 zu({profile:oe,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ye.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await au({profile:oe})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ye.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).action(async t=>{try{await pp({profile:oe,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var jp=ye.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");jp.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??F("HUB_URL")??Ce(oe)?.hubUrl??Ae,r=t.token??F("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&ji()){await Ai({profile:oe});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=F("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??F("WORKER_NAME"),i=t.llm??F("WORKER_LLM");await Tt({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...oe?{profile:oe}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});jp.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ue(oe)&&ji()){await Ai({profile:oe});return}await Yr(oe?{profile:oe}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Ap=ye.command("project").description("Manage CodePipe projects");Ap.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await ep({profile:oe})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ap.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 rp({...t,cliProfile:oe})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var _i=ye.command("repo").description("Manage the project's git repositories");_i.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 ap({profile:oe,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});_i.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 cp({profile:oe,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});_i.command("list").description("List the project's repos").action(async()=>{try{await lp({profile:oe})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ye.parseAsync();