@code-partner/codepipe 0.3.9-dev.121.g4711664 → 0.3.9-dev.122.gea2a7e9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +115 -115
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,38 +1,38 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var ke="0.3.9-dev.
|
|
2
|
+
var ke="0.3.9-dev.122.gea2a7e9",Oe="https://hub.dev.codepipe.dev";var De=4,Vp=4;function cn(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Vp&&t<=De}var Ue=".codepipe-context.yaml",Sr=".devpipe-context.yaml",qi=[{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",Ue]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[Ue]},{version:3,summary:"Custom project actions (the RUN tab): actions/ scaffold with the format README",addedPaths:["actions/README.md"]}];function ln(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 Yi(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 qi(t,e=Wi){let r=[];for(let n of e)if(!(n.version<=t))for(let o of n.addedPaths)r.includes(o)||r.push(o);return r}function Vi(t,e=Wi){return e.filter(r=>r.version>t)}var Wp=[{id:"intake",label:"Intake",phases:["INTAKE"]},{id:"analysis",label:"Analysis",phases:["ANALYZING","ESTIMATING"]},{id:"ready",label:"Ready",phases:["READY"]},{id:"implementation",label:"Implementation",phases:["IMPLEMENTING","BUILD"]},{id:"delivery",label:"Delivery",phases:["READY_TO_APPLY","APPLYING"]}],uk=Wp.flatMap(t=>t.phases);var Ji=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"];function bt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var De="opus",ln="sonnet",Yp="haiku",ko=[De,ln,Yp],zi={analyze:De,implement:De,"resolve-conflict":De,rework:De,estimate:ln,build:ln,"code-review":De,draft:ln,index:De,backfill:De,analysis:De,chat:De};var be=/^[A-Z][A-Z0-9_]*$/,qp=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),Vp=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];function tt(t){return qp.has(t)?!0:Vp.some(e=>t.startsWith(e))}var es=600,Xi=/^[a-z0-9-]+$/,Qi=32,Zi=64;function un(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function $t(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function bo(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function ts(t,e){let r=un(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=$t(r.id,"id")??n;if(!Xi.test(o))throw new Error(`id must match ${Xi} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=$t(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let d=un(r.env,"env");s={};for(let[u,m]of Object.entries(d)){if(!be.test(u))throw new Error(`env name "${u}" must match ${be}`);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)=>Jp(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>Zi)throw new Error(`too many steps (max ${Zi})`);let p=l.map((d,u)=>{let m=un(d,`steps[${u}]`),f=$t(m.run,`steps[${u}].run`);if(!f||f.trim().length===0)throw new Error(`steps[${u}].run is required`);let y=$t(m.name,`steps[${u}].name`),w=bo(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 Jp(t,e,r){let n=un(t,`params[${e}]`),o=$t(n.name,`params[${e}].name`);if(!o||!be.test(o))throw new Error(`params[${e}].name must match ${be}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let 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=$t(n.label,`params[${e}].label`),c=$t(n.help,`params[${e}].help`),l=n.required===!0,p=bo(n.min,`params[${e}].min`),d=bo(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 rs(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 ns=64,os=2e3,zp=[{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:[...ko],help:"Overrides the recommended defaults for every role not listed below."},...Ji.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...ko],help:`recommended: ${zi[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 is(t=zp){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...is(r.groups));return e}function Xp(t,e){let r=JSON.stringify(e);return is().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function ss(t){let e=Xp(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>ns)return{ok:!1,error:`${e.id} must have \u2264 ${ns} entries`};let s={};for(let[a,c]of i){if(!be.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${be}`};if(tt(a))return{ok:!1,error:`${e.id}: name "${a}" is reserved`};if(typeof c!="string")return{ok:!1,error:`${e.id}: value of "${a}" must be a string`};if(c.length>os)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${os} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}function as(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 vt=/^[a-z][a-z0-9-]{1,30}$/,Qp="-codepipe-ctx";function qe(t){return`${t}${Qp}`}var Zp=[{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 Ot(t){for(let e of Zp){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var cs=["bug","feature","epic"],pn="feature",xr="TASK",dn=/^[A-Z][A-Z0-9]{1,9}$/,$o={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},Sk=$o.backlog,fn="tracker/config.yaml",Sr="tracker/counter";function Rr(t){return`tasks/${t}/issue.yaml`}var Tr={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function Dt(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 xt="x-bitbucket-api-token-auth";function mn(t){switch(t){case Tr.gitlab:return"oauth2";case Tr.bitbucket:return"x-token-auth";default:return"x-access-token"}}var ls=20;function F(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as tk}from"commander";import{homedir as ms}from"node:os";import{mkdirSync as ld,readFileSync as ud,writeFileSync as pd,existsSync as xo}from"node:fs";import{dirname as hs,join as yn,resolve as dd}from"node:path";import{fileURLToPath as fd}from"node:url";import{existsSync as gn,readFileSync as ps,readdirSync as td,writeFileSync as rd}from"node:fs";import{dirname as nd,join as rt}from"node:path";import{parse as od}from"yaml";import{existsSync as us,renameSync as ed}from"node:fs";function St(t,e,r=n=>console.error(n)){if(us(e)||!us(t))return!1;try{return ed(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 Ue=".codepipe",vo=".devpipe";function id(t=process.cwd()){let e=t;for(;;){if(gn(rt(e,Ue,"project.yaml")))return e;if(gn(rt(e,vo,"project.yaml")))return St(rt(e,vo),rt(e,Ue))&&ad(e),e;let r=nd(e);if(r===e)return null;e=r}}function sd(t){let e=rt(t,Ue);return gn(e)?e:rt(t,vo)}function ad(t){let e=rt(t,".gitignore");if(!gn(e))return;let r=ps(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&&
|
|
7
|
-
`,{mode:384})}function wn(t){if(t)return{cfg:ve(t),profile:t};let e;try{e=$e()?.spec.projectId||void 0}catch{}if(e){let r=
|
|
8
|
-
`,{mode:384})}function bn(){return
|
|
9
|
-
`,{mode:384})}function
|
|
5
|
+
`}function Vi(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 Ji(t,e=qi){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 zi(t,e=qi){return e.filter(r=>r.version>t)}var Jp=[{id:"intake",label:"Intake",phases:["INTAKE"]},{id:"analysis",label:"Analysis",phases:["ANALYZING","ESTIMATING"]},{id:"ready",label:"Ready",phases:["READY"]},{id:"implementation",label:"Implementation",phases:["IMPLEMENTING","BUILD"]},{id:"delivery",label:"Delivery",phases:["READY_TO_APPLY","APPLYING"]}],gk=Jp.flatMap(t=>t.phases);var Xi=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"];function bt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Le="opus",un="sonnet",zp="haiku",wo=[Le,un,zp],Qi={analyze:Le,implement:Le,"resolve-conflict":Le,rework:Le,estimate:un,build:un,"code-review":Le,draft:un,index:Le,backfill:Le,analysis:Le,chat:Le};var be=/^[A-Z][A-Z0-9_]*$/,Xp=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),Qp=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];function tt(t){return Xp.has(t)?!0:Qp.some(e=>t.startsWith(e))}var rs=600,Zi=/^[a-z0-9-]+$/,es=32,ts=64;function pn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function $t(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function ko(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function ns(t,e){let r=pn(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=$t(r.id,"id")??n;if(!Zi.test(o))throw new Error(`id must match ${Zi} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=$t(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let d=pn(r.env,"env");s={};for(let[u,m]of Object.entries(d)){if(!be.test(u))throw new Error(`env name "${u}" must match ${be}`);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>es)throw new Error(`too many params (max ${es})`);let d=new Set;a=c.map((u,m)=>Zp(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>ts)throw new Error(`too many steps (max ${ts})`);let p=l.map((d,u)=>{let m=pn(d,`steps[${u}]`),f=$t(m.run,`steps[${u}].run`);if(!f||f.trim().length===0)throw new Error(`steps[${u}].run is required`);let y=$t(m.name,`steps[${u}].name`),w=ko(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 Zp(t,e,r){let n=pn(t,`params[${e}]`),o=$t(n.name,`params[${e}].name`);if(!o||!be.test(o))throw new Error(`params[${e}].name must match ${be}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let 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=$t(n.label,`params[${e}].label`),c=$t(n.help,`params[${e}].help`),l=n.required===!0,p=ko(n.min,`params[${e}].min`),d=ko(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 os(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 is=64,ss=2e3,ed=[{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:[...wo],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:[...wo],help:`recommended: ${Qi[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 as(t=ed){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...as(r.groups));return e}function td(t,e){let r=JSON.stringify(e);return as().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function cs(t){let e=td(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>is)return{ok:!1,error:`${e.id} must have \u2264 ${is} entries`};let s={};for(let[a,c]of i){if(!be.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${be}`};if(tt(a))return{ok:!1,error:`${e.id}: name "${a}" is reserved`};if(typeof c!="string")return{ok:!1,error:`${e.id}: value of "${a}" must be a string`};if(c.length>ss)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${ss} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}function ls(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 vt=/^[a-z][a-z0-9-]{1,30}$/,rd="-codepipe-ctx";function Ve(t){return`${t}${rd}`}var nd=[{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 Dt(t){for(let e of nd){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var ps=["bug","feature","epic"],dn="feature",bo="TASK",Ut=/^[A-Z][A-Z0-9]{1,9}$/;function us(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function ds(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=us(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Ut.test(r))return r;let n=us(t);return Ut.test(n)?n:bo}function fs(t,e){let r=new Set([...e].map(n=>n.toUpperCase()));if(!r.has(t.toUpperCase()))return t;for(let n=1;n<1e4;n++){let o=String(n),i=t.slice(0,10-o.length)+o;if(!r.has(i.toUpperCase()))return i}return t}var $o={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},Pk=$o.backlog,fn="tracker/config.yaml",Rr="tracker/counter";function Tr(t){return`tasks/${t}/issue.yaml`}var Ir={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function Lt(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 xt="x-bitbucket-api-token-auth";function mn(t){switch(t){case Ir.gitlab:return"oauth2";case Ir.bitbucket:return"x-token-auth";default:return"x-access-token"}}var ms=20;function F(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as sk}from"commander";import{homedir as ks}from"node:os";import{mkdirSync as fd,readFileSync as md,writeFileSync as gd,existsSync as xo}from"node:fs";import{dirname as $s,join as yn,resolve as hd}from"node:path";import{fileURLToPath as yd}from"node:url";import{existsSync as gn,readFileSync as hs,readdirSync as id,writeFileSync as sd}from"node:fs";import{dirname as ad,join as rt}from"node:path";import{parse as cd}from"yaml";import{existsSync as gs,renameSync as od}from"node:fs";function St(t,e,r=n=>console.error(n)){if(gs(e)||!gs(t))return!1;try{return od(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 Be=".codepipe",vo=".devpipe";function ld(t=process.cwd()){let e=t;for(;;){if(gn(rt(e,Be,"project.yaml")))return e;if(gn(rt(e,vo,"project.yaml")))return St(rt(e,vo),rt(e,Be))&&pd(e),e;let r=ad(e);if(r===e)return null;e=r}}function ud(t){let e=rt(t,Be);return gn(e)?e:rt(t,vo)}function pd(t){let e=rt(t,".gitignore");if(!gn(e))return;let r=hs(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&&sd(e,n)}function $e(t=process.cwd()){let e=ld(t);if(!e)return null;let r=ud(e),n=dd(hs(rt(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function ys(t,e,r){return id(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 hn(t,e=process.cwd()){try{let r=$e(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function dd(t){let e=cd(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 ws(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 bs=hd($s(yd(import.meta.url)),"..");function vs(t){let e=yn(bs,".env");if(xo(e)&&process.loadEnvFile(e),t){let r=yn(bs,"profiles",t,".env");xo(r)&&process.loadEnvFile(r)}}function Bt(t){let e=F("CONFIG");return e||(t?yn(ks(),".codepipe","profiles",t,"config.json"):yn(ks(),".codepipe","config.json"))}function Ee(t){let e=Bt(t);if(!xo(e))return null;let r=md(e,"utf-8");return JSON.parse(r)}function Je(t,e){let r=Bt(e);fd($s(r),{recursive:!0}),gd(r,JSON.stringify(t,null,2)+`
|
|
7
|
+
`,{mode:384})}function wn(t){if(t)return{cfg:ve(t),profile:t};let e;try{e=$e()?.spec.projectId||void 0}catch{}if(e){let r=Ee(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:ve(void 0),profile:void 0}}function ve(t){let e=Ee(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 ${Bt(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}import{homedir as xs}from"node:os";import{join as Ss}from"node:path";function Rs(){St(Ss(xs(),".devpipe"),Ss(xs(),".codepipe"))}import{homedir as Ts}from"node:os";import{existsSync as Is,mkdirSync as Cs,readFileSync as Ps,writeFileSync as Es}from"node:fs";import{dirname as js,join as As}from"node:path";function _s(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 Ns(t,e){let r=L(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],z(r),!0)}function Os(t){return Object.keys(L(t)?.secrets??{}).sort()}function kn(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 Ds(t,e){let r=L(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],z(r),!0):!1}function Me(t){return As(Ts(),".codepipe","secrets",`${t}.json`)}function L(t){let e=Me(t);return Is(e)?JSON.parse(Ps(e,"utf-8")):null}function z(t){let e=Me(t.projectId);Cs(js(e),{recursive:!0}),Es(e,JSON.stringify(t,null,2)+`
|
|
8
|
+
`,{mode:384})}function bn(){return As(Ts(),".codepipe","shared.json")}function So(){let t=bn();return Is(t)?JSON.parse(Ps(t,"utf-8")):null}function Us(t){let e=bn();Cs(js(e),{recursive:!0}),Es(e,JSON.stringify(t,null,2)+`
|
|
9
|
+
`,{mode:384})}function Mt(t){let e=L(t)?.claude?.oauthToken;return e||So()?.claude?.oauthToken}function Cr(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 Gt(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}async function Ls(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=Ee(e);r&&!t.force&&(console.error(`already configured at ${Bt(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");Je({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=${Bt(e)}`)}import{homedir as ui}from"node:os";import{join as qr}from"node:path";import{appendFileSync as wd,existsSync as Bs,mkdirSync as kd,renameSync as Ms,statSync as bd,unlinkSync as $d}from"node:fs";import{Writable as vd}from"node:stream";import{join as xd}from"node:path";var Gs={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},Ft=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&kd(e.dir,{recursive:!0}),this.currentPath=xd(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
|
-
`;
|
|
11
|
+
`;wd(this.currentPath,r,"utf-8")}asWritable(){return new vd({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||!Bs(this.currentPath)||bd(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;Bs(n)&&(r>=this.cfg.maxFiles?$d(n):Ms(n,`${this.currentPath}.${r+1}`))}Ms(this.currentPath,`${this.currentPath}.1`)}}};function $n(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=Sd(process.env[`${t}_MAX_BYTES`]??String(Gs.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):Gs.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function Sd(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 vn(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(Rd(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 Rd(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:Td(o)).join(" ");return`${r} ${t} ${n}`}function Td(t){try{return JSON.stringify(t)}catch{return String(t)}}import{existsSync as gl,rmSync as $g}from"node:fs";import{join as Yr}from"node:path";import{simpleGit as vg}from"simple-git";import"ws";import{createHash as Id}from"node:crypto";import{existsSync as Cd,readFileSync as Pd}from"node:fs";import{homedir as Ed,hostname as Ro}from"node:os";import{join as jd}from"node:path";function Fs(t){return Id("sha256").update(t).digest("hex").slice(0,12)}function Ad(){let t=F("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=jd(Ed(),".claude","credentials.json");if(!Cd(e))return;let r=JSON.parse(Pd(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 Hs(t){let e=Ad(),r=F("ACCOUNT_ID")?.trim(),n=F("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=Mt(t);return o?{accountId:`acct-${Fs(o)}`,label:n||Ro(),...e?{email:e}:{}}:{accountId:`acct-${Fs(`host:${Ro()}`)}`,label:n||Ro(),...e?{email:e}:{}}}import{existsSync as _d}from"node:fs";import{join as Nd}from"node:path";import{simpleGit as Od}from"simple-git";async function Ks(t,e){if(!_d(Nd(t,".git")))return{status:"skipped"};let r=Od(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${Dd(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 Dd(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as Io,readFileSync as Js,readdirSync as Bd,watch as Md}from"node:fs";import{join as Co}from"node:path";import{existsSync as Ws,readFileSync as Ys,readdirSync as Ud,statSync as Ld}from"node:fs";import{join as To}from"node:path";import{parse as qs}from"yaml";function xn(t){let e=To(t,"actions"),r=[],n=[];if(!Ws(e))return{defs:r,errors:n};let o;try{o=Ud(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=To(e,s);try{if(!Ld(a).isFile())continue;let c=ns(s,qs(Ys(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 Vs(t){let e={},r=To(t,"project.yaml");if(!Ws(r))return e;let n;try{n=qs(Ys(r,"utf-8"))}catch{return e}if(!n||typeof n!="object")return e;let o=n.variables;if(!o||typeof o!="object"||Array.isArray(o))return e;for(let[i,s]of Object.entries(o))!be.test(i)||tt(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var Sn=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(Io(this.contextDir))try{this.watcher=Md(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=xn(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=Co(this.contextDir,e);if(!Io(r))return null;try{return Js(r,"utf-8")}catch{return null}}readPrompts(){let e=Co(this.contextDir,"prompts"),r={};if(!Io(e))return r;let n;try{n=Bd(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=Js(Co(e,o),"utf-8")}catch{}}return r}};import{existsSync as Do,readFileSync as ra,readdirSync as Qd}from"node:fs";import{join as na}from"node:path";import{simpleGit as Zd}from"simple-git";import{existsSync as Kd,mkdirSync as Wd,rmSync as Yd,writeFileSync as _o}from"node:fs";import{dirname as qd,isAbsolute as Vd,join as ea,normalize as In}from"node:path";import{simpleGit as ta}from"simple-git";import{existsSync as nt,mkdirSync as zs,readFileSync as Po,writeFileSync as Ht}from"node:fs";import{homedir as Gd}from"node:os";import{join as Ge}from"node:path";import{simpleGit as Fd}from"simple-git";var Kt=["project.yaml","regimen.yaml"];function Pr(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=Ge(t,o);nt(s)||(Ht(s,i),r.push(o))}return r}function Rt(t,e,r){let n=Ge(Gd(),".codepipe","profiles",t,"context-config");return zs(n,{recursive:!0}),Ht(Ge(n,"project.yaml"),e.projectYaml),Ht(Ge(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function Rn(t,e,r){if(nt(e))for(let n of Kt){let o=Ge(e,n),i=Ge(t,n);if(!(!nt(o)||nt(i)))try{Ht(i,Po(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 Hd=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"];function Wt(t){let e=Ge(t,".gitignore"),r=nt(e)?Po(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(Kt.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
|
|
12
12
|
`)?"":`
|
|
13
|
-
`;return
|
|
13
|
+
`;return Ht(e,r+i+Hd.join(`
|
|
14
14
|
`)+`
|
|
15
|
-
`),!0}async function
|
|
16
|
-
`).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;
|
|
15
|
+
`),!0}async function Xs(t,e){try{if(!nt(Ge(t,".git")))return;let r=Fd(t),n=(await r.raw(["ls-files","--",...Kt])).split(`
|
|
16
|
+
`).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;Wt(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 Ao(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 Eo(t){let e=new Map;for(let r of Kt){let n=Ge(t,r);nt(n)&&e.set(r,Po(n))}return e}function jo(t,e){zs(t,{recursive:!0});for(let[r,n]of e){let o=Ge(t,r);nt(o)||Ht(o,n)}}var Qs=3,Jd=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),Zs=/^tasks\/[^/]+\/comments\.jsonl$/,Tn=new Map;async function No(t,e){let r=In(t),o=(Tn.get(r)??Promise.resolve()).catch(()=>{}).then(e);Tn.set(r,o);try{return await o}finally{Tn.get(r)===o&&Tn.delete(r)}}async function ze(t,e,r){return No(t,()=>Oo(t,e,r))}async function Oo(t,e,r){if(!Kd(ea(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let i of e){let s=se(t,i.path);if(i.deleted){Yd(s,{force:!0});continue}Wd(qd(s),{recursive:!0}),i.encoding==="base64"?_o(s,Buffer.from(i.content,"base64")):_o(s,i.content)}let n=ta(t);await n.add(["-A","--","."]),await n.raw(["reset","-q","--",...Kt]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await Ao(t))}async function Ao(t){let e=ta(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=Qs;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 Xd(e);if(i.length>0&&i.every(a=>Jd.has(a)||Zs.test(a))){for(let a of i)Zs.test(a)?await zd(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 ${Qs} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function zd(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
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);_o(se(e,r),i.join(`
|
|
18
18
|
`)+(i.length>0?`
|
|
19
|
-
`:""))}async function
|
|
20
|
-
`).map(r=>r.trim()).filter(Boolean)}function se(t,e){if(
|
|
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
|
|
19
|
+
`:""))}async function Xd(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
|
|
20
|
+
`).map(r=>r.trim()).filter(Boolean)}function se(t,e){if(Vd(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=In(ea(t,e)),n=In(t+"/");if(r!==In(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var ef=/^(\d{4})-(.+)\.md$/,tf="0000-template.md";function rf(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 nf(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
|
|
22
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 k=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(h);if(!k)break;let I=(k[1]??"").trim().toLowerCase(),B=(k[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
23
|
`).replace(/^\n+/,""),w=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${f}`,...p,"",y].join(`
|
|
24
24
|
`);return{content:w.endsWith(`
|
|
25
25
|
`)?w:w+`
|
|
26
|
-
`,supersedes:u}}function
|
|
26
|
+
`,supersedes:u}}function of(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
27
|
|
|
28
|
-
- **Status:** superseded by ADR-${r}`):n}function
|
|
28
|
+
- **Status:** superseded by ADR-${r}`):n}function sf(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(`
|
|
29
29
|
`)+`
|
|
30
|
-
`}async function
|
|
31
|
-
`+t.slice(t.length-e)}async function ot(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 En(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 it(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 af(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 af(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function st(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 na(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 Lo=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 Tt(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){let i=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:o})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:n}})});if(!o.ok)throw new Error(`bitbucket comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},Bo=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 Tt(`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 oa(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await Zd(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 $=se(t,i(w));if(!Do($)){a.push(w);continue}s.push({slug:w,content:ra($,"utf-8")})}let c=na(t,"adr"),l=new Map;if(Do(c))for(let w of Qd(c)){let $=ef.exec(w);!$||w===tf||l.set(w,{num:parseInt($[1]??"",10),slug:$[2]??"",content:ra(na(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(([,R])=>R.slug===w.slug&&R.content.includes(e))){m.push(w.slug);continue}let h=p++,k=`${String(h).padStart(4,"0")}-${w.slug}.md`,{content:I,supersedes:B}=nf(w.content,h,w.slug,e,n);if(d.set(k,I),l.set(k,{num:h,slug:w.slug,content:I}),u.push(`adr/${k}`),B!==null){let R=[...l.keys()].find(A=>A.startsWith(`${String(B).padStart(4,"0")}-`));if(R&&R!==k){let A=of(d.get(R)??l.get(R).content,h);d.set(R,A),l.set(R,{...l.get(R),content:A})}}}let f=[];if(o==="staging")for(let w of s)Do(se(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(([$,h])=>({num:h.num,file:$,header:rf(h.content)}));d.set("INDEX.md",sf(w))}for(let[w,$]of d.entries())f.push({path:`adr/${w}`,content:$});let y=u.length>0?`adr(${e}): promote ${s.map(w=>w.slug).join(", ")}`:`adr(${e}): drop stale staged ${m.join(", ")}`;return await ze(t,f,y),{promoted:u,skipped:m,missing:a}}import{existsSync as ia,readFileSync as cf}from"node:fs";import{join as sa}from"node:path";function lf(t){for(let e of[Ue,Sr]){let r=sa(t,e);if(ia(r))try{return Vi(cf(r,"utf-8"))}catch{return 0}}return 0}function uf(t,e,r,n=3){let o=e<n,i=o?Ji(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function Cn(t,e){return uf(e,lf(t),r=>ia(sa(t,r)))}import{existsSync as wa,mkdirSync as Uf,mkdtempSync as Lf,rmSync as ka,writeFileSync as ba}from"node:fs";import{tmpdir as Bf}from"node:os";import{dirname as Mf,join as En}from"node:path";import{simpleGit as Wo}from"simple-git";var Tt=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};function aa(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
|
|
31
|
+
`+t.slice(t.length-e)}async function ot(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 Pn(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 it(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 pf(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 pf(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function st(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 ca(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 Lo=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 Tt(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){let i=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:o})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:n}})});if(!o.ok)throw new Error(`bitbucket comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},Bo=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 Tt(`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}
|
|
32
32
|
|
|
33
|
-
${
|
|
33
|
+
${aa(w,8e3)}`)}}return p.length===0?void 0:aa(p.join(`
|
|
34
34
|
|
|
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 addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},Mo=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 Tt(`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=
|
|
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 addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},Mo=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 Tt(`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=df(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 addPRComment(e,r,n){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`gitlab comment MR !${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!o.ok)throw new Error(`gitlab close MR !${r}: ${o.status} ${await o.text()}`)}};function df(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 Go=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(Uo(e,r,"merge"))}async closePR(e,r,n){throw new Error(Uo(e,r,"close"))}async addPRComment(e,r,n){throw new Error(Uo(e,r,"comment"))}};function Uo(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 Bo(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new Lo(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new Mo(e)}return new Go}import{existsSync as at,readFileSync as Yt,readdirSync as ua}from"node:fs";import{join as Fo}from"node:path";import{simpleGit as pa}from"simple-git";import{parse as da}from"yaml";function fa(t){try{let e=se(t,fn);if(!at(e))return null;let r=da(Yt(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!Ut.test(n)?null:{prefix:n}}catch{return null}}function ma(t){return`# Built-in tracker configuration \u2014 shared by every team member.
|
|
36
36
|
# The issue-key prefix (<PREFIX>-<N>). Fixed at project init: changing it
|
|
37
37
|
# later would orphan existing tasks/<KEY>/ directories.
|
|
38
38
|
prefix: ${t}
|
|
@@ -41,14 +41,14 @@ prefix: ${t}
|
|
|
41
41
|
# Backlog | To Do | In Progress | Review | Done | Rejected
|
|
42
42
|
# A configurable status set / pipeline mapping is a planned extension.
|
|
43
43
|
`}function Ho(t=0){return`${t}
|
|
44
|
-
`}function
|
|
44
|
+
`}function ff(t){return t==="depends_on"||t==="subtask"}function mf(t){let e;try{e=da(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=ps.includes(r.type)?r.type:dn,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;ff(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 Ko(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
45
|
`)+`
|
|
46
|
-
`}function
|
|
46
|
+
`}function jr(t,e){let r=se(t,Tr(e));return at(r)?mf(Yt(r,"utf-8")):null}function ga(t){let e=Fo(t,"tasks");if(!at(e))return[];let r=[];for(let n of ua(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=jr(t,n.name);o&&r.push(o)}return r}function gf(t,e){let r=se(t,`tasks/${e}/task.md`);if(!at(r))return;let n=Yt(r,"utf-8").split(`
|
|
47
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
|
|
48
|
+
`).trim();if(!(!a||a==="_(no description)_"))return a}function Ar(t,e,r={}){let n=r.withDescription?gf(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:hf(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function hf(t){return t.charAt(0).toUpperCase()+t.slice(1)}function yf(t){let e=se(t,Rr);if(!at(e))return 0;let r=Number.parseInt(Yt(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function wf(t,e){let r=Fo(t,"tasks");if(!at(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of ua(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 kf(t,e){return Math.max(yf(t),wf(t,e))+1}var la=5;async function ha(t,e,r,n){return No(t,()=>bf(t,e,r,n))}async function bf(t,e,r,n){if(!at(Fo(t,".git")))throw new Error(`context repo clone not found at ${t}`);await Er(t);let o=null;for(let i=0;i<la;i++){let s=kf(t,e),a=`${e}-${s}`,c=[...r(a),{path:Rr,content:Ho(s)}];try{return await Oo(t,c,n(a)),a}catch(l){if(o=l,await vf(t,n(a)),await Er(t),$f(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${la} attempts: ${o instanceof Error?o.message:String(o)}`)}function $f(t,e){for(let r of e){let n=se(t,r.path);if(!at(n)||(r.encoding==="base64"?Yt(n).toString("base64"):Yt(n,"utf-8"))!==r.content)return!1}return!0}async function Er(t){let e=pa(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 vf(t,e){let r=pa(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
|
|
49
49
|
`)[0]||!(await r.raw(["log","@{u}..HEAD","--pretty=%s"]).catch(()=>"")).trim().split(`
|
|
50
50
|
`).some(i=>i.trim()===e.split(`
|
|
51
|
-
`)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}function
|
|
51
|
+
`)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}function qt(t,e,r,n){return[{path:"README.md",content:_f(t,e)},{path:".gitignore",content:If()},{path:"CLAUDE.md",content:Pf(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:Cf()},{path:"knowledge/README.md",content:Ef()},{path:"knowledge/build.yaml",content:Af()},{path:"actions/README.md",content:jf()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:Tf()},{path:"adr/README.md",content:xf()},{path:"adr/0000-template.md",content:Sf()},{path:"adr/INDEX.md",content:Rf()},{path:Ue,content:ln()},...t.trackerProvider==="internal"?[{path:fn,content:ma(t.youtrackProjectKey??bo)},{path:Rr,content:Ho()}]:[]]}function xf(){return`# ADR \u2014 architecture decision records
|
|
52
52
|
|
|
53
53
|
Accepted architectural decisions of this project \u2014 its **framework**. The
|
|
54
54
|
agent reads this section (start with \`INDEX.md\`) at the beginning of every
|
|
@@ -76,7 +76,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
|
|
|
76
76
|
canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
|
|
77
77
|
is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
|
|
78
78
|
open a PR to this repository.
|
|
79
|
-
`}function
|
|
79
|
+
`}function Sf(){return`# ADR-NNNN: <title>
|
|
80
80
|
|
|
81
81
|
- **Status:** accepted | superseded by ADR-NNNN
|
|
82
82
|
- **Date:** YYYY-MM-DD
|
|
@@ -98,12 +98,12 @@ What becomes easier, what becomes harder, what future tasks must keep doing.
|
|
|
98
98
|
## Alternatives considered
|
|
99
99
|
|
|
100
100
|
- **<alternative>** \u2014 why it was rejected.
|
|
101
|
-
`}function
|
|
101
|
+
`}function Rf(){return`# ADR index
|
|
102
102
|
|
|
103
103
|
<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->
|
|
104
104
|
|
|
105
105
|
(no accepted ADRs yet)
|
|
106
|
-
`}function
|
|
106
|
+
`}function Tf(){return`# Audit
|
|
107
107
|
|
|
108
108
|
Pipeline event logs. Naming is per-writer: each codepipe
|
|
109
109
|
project appends only to its own file \u2014
|
|
@@ -112,14 +112,14 @@ project appends only to its own file \u2014
|
|
|
112
112
|
|
|
113
113
|
\u2014 so several team members' CLIs never contend on one file. Do not create a
|
|
114
114
|
shared aggregate here.
|
|
115
|
-
`}function
|
|
115
|
+
`}function Fe(t,e,r,n){let o=t.trackerProvider==="internal";return{projectYaml:o?Nf(t):Of(t,r,n),regimenYaml:Df(t.automationLevel,o?!0:e,o)}}function If(){return`# codepipe project config is local to each member's workspace
|
|
116
116
|
project.yaml
|
|
117
117
|
regimen.yaml
|
|
118
118
|
|
|
119
119
|
# codepipe runtime
|
|
120
120
|
session.log
|
|
121
121
|
apply-queue.json
|
|
122
|
-
`}function
|
|
122
|
+
`}function Cf(){return`# Index prompt
|
|
123
123
|
|
|
124
124
|
You are the **Indexer** agent on the CodePipe pipeline. Your one job is to build a
|
|
125
125
|
navigation map of this project's repositories and save it to the Context Repo, so
|
|
@@ -176,7 +176,7 @@ current working directory; write nothing else under the Context Repo.
|
|
|
176
176
|
Keep both durable and skimmable \u2014 they are read at the start of every future
|
|
177
177
|
task. Prefer structure (headings, bullet lists) over prose. If a repository is
|
|
178
178
|
empty or unavailable, say so briefly rather than inventing content.
|
|
179
|
-
`}function
|
|
179
|
+
`}function Pf(t){return`# Project context for the CodePipe agent
|
|
180
180
|
|
|
181
181
|
Instructions for AI agents working on **${t.name}** tasks. Claude Code
|
|
182
182
|
auto-loads this file when the Context Repo is mounted. Keep it short and
|
|
@@ -204,7 +204,7 @@ project's architectural invariants: read them at the start of a task and treat
|
|
|
204
204
|
them as binding. New or changed decisions do **not** go here directly \u2014 during
|
|
205
205
|
analysis you draft them as task artifacts, and they are promoted into \`adr/\`
|
|
206
206
|
only after the analysis is approved.
|
|
207
|
-
`}function
|
|
207
|
+
`}function Ef(){return`# Knowledge
|
|
208
208
|
|
|
209
209
|
Durable, reusable notes about this project \u2014 the CodePipe agent's long-lived
|
|
210
210
|
**memory** across tasks. Architectural decisions, domain rules,
|
|
@@ -221,7 +221,7 @@ Keep each note in its own file \u2014 never grow one shared aggregate \u2014 so
|
|
|
221
221
|
concurrent commits touch different files and rebase cleanly. \`INDEX.md\` is
|
|
222
222
|
REGENERATED from the entries by the index job: don't hand-edit it, and treat
|
|
223
223
|
any merge conflict in it as noise (either side converges on the next run).
|
|
224
|
-
`}function
|
|
224
|
+
`}function jf(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
|
|
225
225
|
|
|
226
226
|
One \`<id>.yml\` per action. Every file here appears as a button on the
|
|
227
227
|
project's **RUN** tab; an action with \`params\` opens a small wizard first.
|
|
@@ -260,7 +260,7 @@ steps:
|
|
|
260
260
|
Parameter values are passed to the commands **only as env vars** \u2014 reference
|
|
261
261
|
them as \`$INPUT_<NAME>\` in \`run\`; they are never substituted into the
|
|
262
262
|
command text itself.
|
|
263
|
-
`}function
|
|
263
|
+
`}function Af(){return`# BUILD phase config. Discovered & maintained by the agent.
|
|
264
264
|
# Steps run in a rootless Podman container in the SANDBOX, before the PR.
|
|
265
265
|
# Success = every step exits 0. Credentials are NOT available inside the container.
|
|
266
266
|
#
|
|
@@ -276,7 +276,7 @@ command text itself.
|
|
|
276
276
|
# - name: test
|
|
277
277
|
# run: npm test
|
|
278
278
|
# timeout_sec: 600 # per-step timeout (optional, default 600)
|
|
279
|
-
`}function
|
|
279
|
+
`}function _f(t,e){return`# ${e.name}
|
|
280
280
|
|
|
281
281
|
Context Repo for the **${t.name}** project (CodePipe).
|
|
282
282
|
|
|
@@ -302,7 +302,7 @@ PRs to this repository (and the agent also writes to \`knowledge/\` and
|
|
|
302
302
|
pipeline \u2014 don't edit them by hand.
|
|
303
303
|
|
|
304
304
|
Automation level: **${t.automationLevel}**.
|
|
305
|
-
`}function
|
|
305
|
+
`}function Nf(t){return`# Project description for CodePipe.
|
|
306
306
|
id: ${t.projectId}
|
|
307
307
|
name: ${t.name}
|
|
308
308
|
|
|
@@ -325,15 +325,15 @@ branch:
|
|
|
325
325
|
pattern: codepipe/<TASK_ID>
|
|
326
326
|
|
|
327
327
|
repos:
|
|
328
|
-
${
|
|
329
|
-
`}function
|
|
328
|
+
${ya(t)}
|
|
329
|
+
`}function ya(t){return t.repos.length===0?` [] # add repos here
|
|
330
330
|
`:t.repos.map(e=>` - name: ${e.name}
|
|
331
331
|
host: ${e.host}
|
|
332
332
|
owner: ${e.owner}
|
|
333
333
|
repo: ${e.repoName}
|
|
334
334
|
mount_as: ${e.mountAs??e.name}`+(e.defaultBranch?`
|
|
335
335
|
default_branch: ${e.defaultBranch}`:"")).join(`
|
|
336
|
-
`)}function
|
|
336
|
+
`)}function Of(t,e,r){let n=e?`
|
|
337
337
|
tracker_url: ${e}`:`
|
|
338
338
|
# tracker_url: https://your.youtrack.cloud`,o=r?`require_assignee: true
|
|
339
339
|
assignee: ${r}`:`require_assignee: false
|
|
@@ -381,7 +381,7 @@ ${da(t)}
|
|
|
381
381
|
# non-empty assignee. assignee only takes effect when require_assignee=true.
|
|
382
382
|
${o}`:` # project_key: \u2026
|
|
383
383
|
# tracker_url: https://your.youtrack.cloud
|
|
384
|
-
poll_interval_sec: 60`,s=
|
|
384
|
+
poll_interval_sec: 60`,s=ya(t);return`# Project description for CodePipe.
|
|
385
385
|
id: ${t.projectId}
|
|
386
386
|
name: ${t.name}
|
|
387
387
|
|
|
@@ -412,7 +412,7 @@ branch:
|
|
|
412
412
|
|
|
413
413
|
repos:
|
|
414
414
|
${s}
|
|
415
|
-
`}function
|
|
415
|
+
`}function Df(t,e,r=!1){let n=t==="full",o=e?"true":"false";return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
|
|
416
416
|
automation:
|
|
417
417
|
level: ${t}
|
|
418
418
|
|
|
@@ -547,39 +547,39 @@ llm:
|
|
|
547
547
|
# # the previous task's branch (auto-merge without reworking the
|
|
548
548
|
# # tail of the chain).
|
|
549
549
|
# mode: parallel
|
|
550
|
-
`}function
|
|
551
|
-
`)}async function
|
|
550
|
+
`}function Gf(t){return`codepipe/context-migration-v${t}`}function Ff(t){let e=zi(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 \`${Ue}\` stamp (renamed from \`${Sr}\``,"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(`
|
|
551
|
+
`)}async function $a(t,e,r,n){let o=Wo(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Cn(t,e);if(!i.outdated)return i;let s=Gf(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 Hf(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:Ff(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 Hf(t,e,r,n,o,i,s){let a=Wo(t),c=Lf(En(Bf(),"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(qt(l,p).map(y=>[y.path,y.content])),u=0;for(let y of n.missingPaths){if(y===Ue)continue;let w=d.get(y);if(w==null){s.warn(`[ctx] migration: no template for ${y} \u2014 skipped`);continue}let $=En(c,y);wa($)||(Uf(Mf($),{recursive:!0}),ba($,w),u++)}ba(En(c,Ue),ln(n.currentVersion)),u++;let m=En(c,Sr);wa(m)&&(ka(m,{force:!0}),u++);let f=Wo(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(()=>{}),ka(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{existsSync as Kf,readFileSync as Wf,writeFileSync as Yf}from"node:fs";import{homedir as qf}from"node:os";import{join as va}from"node:path";import{parseDocument as Vf}from"yaml";function Jf(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 zf(t,e){let r=Vf(t);return r.set("repos",e.map(Jf)),r.toString()}function Xf(t,e){let r=[va(qf(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(va(e,"project.yaml")),r}function _r(t,e,r){let n=[],o=[];for(let i of Xf(t,r))if(Kf(i))try{let s=Wf(i,"utf-8"),a=zf(s,e);a!==s&&(Yf(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 Qf}from"node:os";import{existsSync as Zf,mkdirSync as em}from"node:fs";import{join as Yo}from"node:path";import{simpleGit as qo}from"simple-git";var xa=t=>console.log(t);function Sa(t){xa=t}function Nr(t,e="info"){xa(t,e)}function xe(t,e,r){let n=r??Yo(Qf(),".codepipe","repos");return Yo(n,t,e)}async function Dr(t,e,r={}){let n=xe(t,e.name,r.baseDir),o=r.cloneUrlOverride??Ur(e);if(!Zf(Yo(n,".git"))){em(n,{recursive:!0});let a=qo();Nr(`[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}
|
|
552
552
|
${l.trim()}`)}}let i=qo(n);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
|
|
553
|
-
${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function
|
|
554
|
-
${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
|
|
555
|
-
`).map(r=>r.trim()).filter(r=>r.length>0).map(r=>r.split(/\s+/)[1]??"").filter(r=>r.startsWith("refs/heads/")).map(r=>r.slice(11))}function
|
|
556
|
-
`)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function sm(t,e,r){return new Promise((n,o)=>{let i=ct.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 Na(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function Jo(t,e,r){return new Promise(n=>{let o=ct.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 am(t){try{let e=await fetch(t);return e.ok?new Na(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Ba(t,e=443,r=Da){let n=`${t}:${e}`,o=_a.get(n);if(o)return o;let i=cm(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return _a.set(n,i),i}async function cm(t,e,r){if(!Oa)return!1;let n=8e3;if(await Jo(t,e,n))return!0;let o=await sm(t,e,n),i=ct.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=im(o);if(!c)break;let l=await am(c);if(!l)break;if(s.push(l.toString()),ct.setDefaultCACertificates([...i,...s]),await Jo(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 Jo(t,e,n)}function Ha(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function Se(t,e,r){Ua();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(La(s)&&await Ba(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}var Ma=t=>new Promise(e=>setTimeout(e,t));function lm(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function um(){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 zo(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=um(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await Se(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&&lm(l.status,p)){await Ma(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${p}`)}if(c<o){await Ma(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function lt(t){let e;try{e=await Se(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 Ka(t){try{let e=await Se(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}var Ur="Stage",Ga=new Map;async function pm(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=Ga.get(o);if(i)return i;let s=await Se(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 Ga.set(o,l.id),l.id}async function Wa(t,e,r,n=Ur){let o=await pm(t,e,r,n);await zo(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 Ya(t,e,r){return await(await zo(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function qa(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await zo(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}var Fa=new Map;async function Va(t,e){let r=Fa.get(e);if(r)return r;let n=await Se(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 Fa.set(e,i.id),i.id}async function Ja(t,e,r,n,o,i=Ur){let s=await Va(t,e),a=await Se(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 za(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await Se(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 Xa="attachments(id,name,url,size,mimeType)",dm="links(direction,linkType(name),issues(idReadable))",Qa=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Xa},${dm}`,fm=`id,text,created,author(login),${Xa}`;function Za(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 ec(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 tc(t,e){let r=e.stageField??Ur,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 Se(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>oc(c,r))}async function rc(t,e,r=Ur){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Qa}`,o=await Se(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return oc(await o.json(),r)}async function nc(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${fm}&$top=500`,o=await Se(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=Za(s.attachments);return c&&(a.attachments=c),a})}function mm(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 oc(t,e=Ur){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=Za(t.attachments);a&&(s.attachments=a);let c=mm(t.links);return c&&(s.links=c),s}async function ic(t,e){let r=await gm(t,e);return r.length>0?r:hm(t,e)}async function gm(t,e){let r=await Va(t,e),n=await Se(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:sc(s.bundle)});return i}async function hm(t,e){let r=`project: ${e}`,n=await Se(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:sc(s.projectCustomField?.bundle)});return i}function sc(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}function Pe(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function ac(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 lt({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:Pe(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:Pe(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 ot(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:Pe(c)}),o.push({kind:"github",present:!0,ok:!1,detail:Pe(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 it(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:Pe(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:Pe(c),checkedAt:i()})}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await st(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:Pe(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:Pe(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 En(c,p.owner,p.repoName),n.push({name:`repo:${p.name}`,ok:!0})}catch(d){n.push({name:`repo:${p.name}`,ok:!1,detail:Pe(d)})}let l=e?.contextRepo;if(l?.host==="github")try{await En(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(p){n.push({name:"context-repo",ok:!1,detail:Pe(p)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await En(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:Pe(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=Lt(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 Xo(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 Xo(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 Lr(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 Br(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 Mr(t,e=process.env){if(!t)return!1;let r=`https://${xt}:${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 cc(t,e=process.env){return Qo(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>Lr(t,e),e)}function lc(t,e=process.env){return Qo(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>Br(t,e),e)}function uc(t,e=process.env){return Qo(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${xt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>Mr(t,e),e)}function pc(t){let e=L(t);if(!e)return null;if(!e.sealKey){let r=An();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},z(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:fe(e.sealKey.publicKey)}}async function dc(t,e,r,n){let o;try{o=JSON.parse(Yt(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 ot(o.token);return i.github={token:o.token},qt(i,()=>{process.env.GH_TOKEN=o.token,cc(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await st(o.token);return i.gitlab={token:o.token},qt(i,()=>{process.env.GITLAB_TOKEN=o.token,lc(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 it(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},qt(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,uc(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 lt({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},qt(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 Xo(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},qt(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},qt(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 qt(t,e){z(t),e()}import{spawn as ym}from"node:child_process";var wm=124,fc=16*1024,mc=4e3;function km(t,e,r,n,o,i){let s={...t},a=(c,l)=>{tt(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 gc(t){let{def:e,onEvent:r}=t,n=km(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
|
|
557
|
-
`,o.length>
|
|
558
|
-
`))!==-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?
|
|
559
|
-
`)}function
|
|
560
|
-
`)){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=
|
|
553
|
+
${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function Or(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var Ra=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function jn(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&&Nr(`[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 Or(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await Or(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([...Ra,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function Ta(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await Or(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await Or(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 Ia(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 Ta(t,i,()=>jn(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 Or(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([...Ra,"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
|
|
554
|
+
${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 Ca(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,p=await Ta(t,i,()=>jn(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 Pa(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 Ur(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}async function Ea(t){return(await qo().listRemote(["--heads",t])).split(`
|
|
555
|
+
`).map(r=>r.trim()).filter(r=>r.length>0).map(r=>r.split(/\s+/)[1]??"").filter(r=>r.startsWith("refs/heads/")).map(r=>r.slice(11))}function ja(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}import{createCipheriv as tm,createDecipheriv as rm,createHash as nm,createPrivateKey as om,createPublicKey as Vo,diffieHellman as Aa,generateKeyPairSync as _a,hkdfSync as Na,randomBytes as im}from"node:crypto";var Oa=Buffer.from("devpipe-sealedbox-v1","utf-8");function An(){let{publicKey:t,privateKey:e}=_a("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function me(t){let e=Buffer.from(t,"base64");return(nm("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function Xe(t,e){let r=Vo({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=_a("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=Aa({privateKey:o,publicKey:r}),c=Buffer.from(Na("sha256",a,Buffer.concat([i,s]),Oa,32)),l=im(12),p=tm("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 Vt(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=om({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=Aa({privateKey:n,publicKey:o}),c=Buffer.from(Na("sha256",a,Buffer.concat([i,s]),Oa,32)),l=rm("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 sm(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 Da(t,e,r,n){let o=sm(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=kn(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=Xe(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 Ba}from"node:crypto";import{readFileSync as am}from"node:fs";import ct from"node:tls";var Ma=typeof ct.getCACertificates=="function"&&typeof ct.setDefaultCACertificates=="function",Ua=!1,La=new Map,Ga=t=>console.warn(t);function cm(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function Fa(t=Ga){if(Ua)return;Ua=!0;let e=F("EXTRA_CA_FILE");if(!(!e||!Ma))try{let r=cm(am(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}ct.setDefaultCACertificates([...ct.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 Ha(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 lm(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
|
|
556
|
+
`)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function um(t,e,r){return new Promise((n,o)=>{let i=ct.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 Ba(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function Jo(t,e,r){return new Promise(n=>{let o=ct.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 pm(t){try{let e=await fetch(t);return e.ok?new Ba(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Ka(t,e=443,r=Ga){let n=`${t}:${e}`,o=La.get(n);if(o)return o;let i=dm(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return La.set(n,i),i}async function dm(t,e,r){if(!Ma)return!1;let n=8e3;if(await Jo(t,e,n))return!0;let o=await um(t,e,n),i=ct.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=lm(o);if(!c)break;let l=await pm(c);if(!l)break;if(s.push(l.toString()),ct.setDefaultCACertificates([...i,...s]),await Jo(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 Jo(t,e,n)}function Va(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function Se(t,e,r){Fa();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(Ha(s)&&await Ka(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}var Wa=t=>new Promise(e=>setTimeout(e,t));function fm(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function mm(){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 zo(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=mm(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await Se(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&&fm(l.status,p)){await Wa(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${p}`)}if(c<o){await Wa(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function lt(t){let e;try{e=await Se(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 Ja(t){try{let e=await Se(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}var Lr="Stage",Ya=new Map;async function gm(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=Ya.get(o);if(i)return i;let s=await Se(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 Ya.set(o,l.id),l.id}async function za(t,e,r,n=Lr){let o=await gm(t,e,r,n);await zo(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 Xa(t,e,r){return await(await zo(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function Qa(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await zo(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}var qa=new Map;async function Za(t,e){let r=qa.get(e);if(r)return r;let n=await Se(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 qa.set(e,i.id),i.id}async function ec(t,e,r,n,o,i=Lr){let s=await Za(t,e),a=await Se(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 tc(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await Se(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 rc="attachments(id,name,url,size,mimeType)",hm="links(direction,linkType(name),issues(idReadable))",nc=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${rc},${hm}`,ym=`id,text,created,author(login),${rc}`;function oc(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 ic(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 sc(t,e){let r=e.stageField??Lr,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=${nc}&$top=200`,s=await Se(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>lc(c,r))}async function ac(t,e,r=Lr){let n=`/api/issues/${encodeURIComponent(e)}?fields=${nc}`,o=await Se(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return lc(await o.json(),r)}async function cc(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${ym}&$top=500`,o=await Se(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=oc(s.attachments);return c&&(a.attachments=c),a})}function wm(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 lc(t,e=Lr){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=oc(t.attachments);a&&(s.attachments=a);let c=wm(t.links);return c&&(s.links=c),s}async function uc(t,e){let r=await km(t,e);return r.length>0?r:bm(t,e)}async function km(t,e){let r=await Za(t,e),n=await Se(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:pc(s.bundle)});return i}async function bm(t,e){let r=`project: ${e}`,n=await Se(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:pc(s.projectCustomField?.bundle)});return i}function pc(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}function Ae(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function dc(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 lt({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:Ae(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:Ae(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 ot(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:Ae(c)}),o.push({kind:"github",present:!0,ok:!1,detail:Ae(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 it(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:Ae(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:Ae(c),checkedAt:i()})}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await st(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:Ae(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:Ae(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 Pn(c,p.owner,p.repoName),n.push({name:`repo:${p.name}`,ok:!0})}catch(d){n.push({name:`repo:${p.name}`,ok:!1,detail:Ae(d)})}let l=e?.contextRepo;if(l?.host==="github")try{await Pn(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(p){n.push({name:"context-repo",ok:!1,detail:Ae(p)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Pn(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:Ae(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=Mt(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 Xo(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 Xo(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 Br(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 Mr(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 Gr(t,e=process.env){if(!t)return!1;let r=`https://${xt}:${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 fc(t,e=process.env){return Qo(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>Br(t,e),e)}function mc(t,e=process.env){return Qo(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>Mr(t,e),e)}function gc(t,e=process.env){return Qo(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${xt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>Gr(t,e),e)}function hc(t){let e=L(t);if(!e)return null;if(!e.sealKey){let r=An();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},z(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:me(e.sealKey.publicKey)}}async function yc(t,e,r,n){let o;try{o=JSON.parse(Vt(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 ot(o.token);return i.github={token:o.token},Jt(i,()=>{process.env.GH_TOKEN=o.token,fc(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await st(o.token);return i.gitlab={token:o.token},Jt(i,()=>{process.env.GITLAB_TOKEN=o.token,mc(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 it(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},Jt(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,gc(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 lt({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},Jt(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 Xo(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},Jt(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},Jt(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 Jt(t,e){z(t),e()}import{spawn as $m}from"node:child_process";var vm=124,wc=16*1024,kc=4e3;function xm(t,e,r,n,o,i){let s={...t},a=(c,l)=>{tt(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 bc(t){let{def:e,onEvent:r}=t,n=xm(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
|
|
557
|
+
`,o.length>wc&&(o=o.slice(o.length-wc))},s=(a,c)=>{let l=c.length>kc?c.slice(0,kc)+"\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 Sm(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 Sm(t,e,r,n,o){return new Promise(i=>{let s=$m("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??rs)*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(`
|
|
558
|
+
`))!==-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?vm:m??(f?1:0))})})}import{existsSync as Rm,readFileSync as Tm,statSync as $c}from"node:fs";var vc=2*1024*1024;function Im(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function xc(t,e){let r=se(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!Rm(r)||!$c(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=$c(r);if(n>vc)throw new Error(`file too large: ${e} is ${n} bytes (limit ${vc})`);let o=Tm(r);return Im(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}import{existsSync as Cm,readFileSync as Pm,writeFileSync as Em}from"node:fs";import{join as jm}from"node:path";import{parseDocument as Am}from"yaml";async function Sc(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=cs(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=jm(t,o);if(!Cm(s))throw new Error(`${o} not found in context repo (${t})`);let a=Am(Pm(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);Em(s,a.toString()),n.push(o)}return{files:n}}import{existsSync as _m,readFileSync as Nm,writeFileSync as Om}from"node:fs";import{join as Dm}from"node:path";import{isMap as Rc,parseDocument as Um}from"yaml";async function Tc(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||!ls(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=Dm(t,"project.yaml");if(!_m(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=Um(Nm(o,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>Rc(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!Rc(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),Om(o,i.toString()),{repoName:r,defaultBranch:n}}import{existsSync as Zo,readFileSync as ei,writeFileSync as Lm}from"node:fs";import{join as _n}from"node:path";import{parseDocument as ti}from"yaml";async function Ic(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=_n(t,"project.yaml");if(!Zo(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=ti(ei(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=_n(t,"regimen.yaml");if(!Zo(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=ti(ei(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)Lm(_n(t,i.path),i.content);return{files:r.map(i=>i.path)}}function Nn(t){if(!t)return"Stage";try{let e=_n(t,"project.yaml");if(!Zo(e))return"Stage";let n=ti(ei(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}import{existsSync as Ec,readFileSync as jc}from"node:fs";import{join as Ac}from"node:path";import{parseDocument as _c}from"yaml";var Fr=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return sc(this.cfg,e)}getIssue(e,r){return ac(this.cfg,e,r??Nn(this.contextDir))}listComments(e,r){return cc(this.cfg,e,r)}downloadAttachment(e){return ic(this.cfg,e)}updateStatus(e,r){return za(this.cfg,e,r,Nn(this.contextDir))}addComment(e,r,n){return Xa(this.cfg,e,r)}createIssue(e){return ec(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,Nn(this.contextDir))}editIssue(e,r){return Qa(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return tc(this.cfg,e,r,n)}fetchStateFields(e){return uc(this.cfg,e)}};import{existsSync as Wm,readFileSync as Ym}from"node:fs";import{randomBytes as qm}from"node:crypto";import{existsSync as Cc,readFileSync as Bm,readdirSync as Mm}from"node:fs";function On(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=Km(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:Gm(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:Hm(Fm(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 Dn(t,e,r){if(r.length===0)return;let n=On(t,e,r),o=r.map(i=>i.issue.key);await ze(t,n,`sync(${o.join(", ")}): task data`)}function Gm(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(`
|
|
559
|
+
`)}function Fm(t,e,r){let n=new Map,o=se(t,`tasks/${e}/comments.jsonl`);if(Cc(o))for(let i of Bm(o,"utf-8").split(`
|
|
560
|
+
`)){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=Dt(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function Hm(t){return t.map(e=>JSON.stringify(e)).join(`
|
|
561
561
|
`)+(t.length>0?`
|
|
562
|
-
`:"")}function
|
|
562
|
+
`:"")}function Km(t,e,r){let n=[],o=se(t,`tasks/${e}/attachments`);if(Cc(o))for(let i of Mm(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}var Hr=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await Er(this.contextDir);let r=e.columns??[];return ga(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>Ar(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=jr(this.contextDir,e);return r?Ar(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return Pc(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 Er(this.contextDir),!jr(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${qm(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=Dt(r);s&&(i.parsedCommand=s);let c=[...Pc(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
|
|
563
563
|
`)+`
|
|
564
|
-
`;return await
|
|
565
|
-
`)){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 ri(t){if(!t)return"youtrack";try{let e=
|
|
566
|
-
`,{mode:384})}function
|
|
567
|
-
`,{mode:384})}function lg(t){return zc()[t]}function si(t,e){let r=zc();r[t]=e,cg(r)}function Xc(t,e){let r=fe(e),n=lg(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 ${ii()}.`);return r}var Zc=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:Zc(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 ug={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Zc(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")},el={api:ug,fetchProject:q,provisionOnRunner:Ac,teardownOnRunner:_c};async function tl(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(fe(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Xc(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 rl(t,e,r,n=el){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 tl(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));si(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 nl(t,e,r,n=el){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 tl(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));si(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 ol=16*1024;function pg(t){return be.test(t)?tt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${be}`}function il(t,e,r,n){let o=pg(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(Yt(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>ol)return{ok:!1,detail:`secret value too large (max ${ol} chars)`};try{return Cs(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function sl(t,e){try{return Es(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 Kn=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=Ee(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 Tt){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=Ee(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=dg(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}};function dg(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var Wn=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??(()=>Ge({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 k=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??[],...e.reviewColumns??[]])],[M,E]=await Promise.all([j.length>0?r.listIssues({projectKey:e.projectKey,columns:j,...k,...I}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...k})]),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.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:j,...k,...I})}}catch(k){this.log.warn(`[yt-sync] listIssues failed: ${k instanceof Error?k.message:String(k)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let k of o){if(s.add(k.id),a.has(k.status))continue;let I=await cl(r,k.id,e.sinceMs,this.log);I&&i.set(k.id,I)}let c=[];for(let k of e.offBoardIssueIds){if(s.has(k))continue;let I=await cl(r,k,e.sinceMs,this.log);if(I&&I.length>0&&i.set(k,I),e.requireAssignee||I&&I.length>0){let B=await gg(r,k,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(k=>!a.has(k.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(k=>({issue:k,comments:i.get(k.id)??[],attachments:p.get(k.id)??[]}));try{await Dn(this.options.contextDir,e.projectId,u),this.abandonedTicks=0;for(let k of d)this.shippedAttachments.add(k)}catch(k){let I=k instanceof Error?k.message:String(k);this.abandonTick(`context task sync failed: ${I}`);return}let m=this.options.isSelfComment??(()=>!1),f=[],y=[];for(let[k,I]of i){let B=I.filter(j=>!m(j.id));if(B.length===0)continue;f.push({issueId:k,comments:B.map(fg)});let R=B.flatMap(j=>{let M=Ot(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:k,commands:R})}let w={type:"youtrack_observation",projectId:e.projectId,issues:o.map(al),commentsBatch:f,...y.length>0?{commandsBatch:y}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(al)}:{},observedAtMs:n};this.send(w);let $=f.reduce((k,I)=>k+I.comments.length,0),h=y.reduce((k,I)=>k+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=mg(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 al(t){let{description:e,...r}=t;return r}function fg(t){let{body:e,...r}=t;return r}function mg(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 gg(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 cl(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 ai="npm i -g @code-partner/codepipe@latest";function Yn(t,e={}){let r=e.log??{info:f=>console.log(f),warn:f=>console.warn(f)};r.info(`codepipe-cli v${ke} (protocol ${Ne})`);let n=f=>e.onEvent?.(f),o=e.workspace;o?.contextDir&&Ys(o.contextDir,r);let i=ll("CLI_TRACKING_POLL_INTERVAL_SEC"),s=ll("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=Gn(t.hubUrl,t.cliToken),y=null,w=new Kn(i,b=>{f.readyState===f.OPEN&&f.send(JSON.stringify(b))},r),$=new Wn(s,b=>{f.readyState===f.OPEN&&f.send(JSON.stringify(b))},r,{contextDir:o?.contextDir??null,isSelfComment:b=>d.has(b)}),h=null,k=async()=>{try{let b={trackerProvider:ri(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 ac(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:Ps(t.projectId),checkedAt:C.checkedAt};if(f.send(JSON.stringify(x)),C.ready)r.info("[readiness] ready");else{let P=C.checks.filter(U=>!U.ok).map(U=>`${U.name}(${U.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${P.join(", ")}`)}}catch(b){r.warn(`[readiness] check failed: ${b instanceof Error?b.message:String(b)}`)}},I=()=>{k(),h=setInterval(()=>void k(),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 Sn(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 ha(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=Ls(t.projectId),C=F("ORIGIN")==="farm"?"farm":"local",x=F("FARM_ID"),P=t.accountEmail??b.email,U;try{let S=pc(t.projectId);S&&(U=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:ke,protocolVersion:Ne,accountId:b.accountId,accountLabel:b.label,origin:C,inFlightActionIds:[...p],...P?{accountEmail:P}:{},...C==="farm"&&x?{farmId:x}:{},...U?{sealPublicKey:U}:{}};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}),w.start(),g?.start(),I(),ci(t,o,r),o?.contextDir)try{let S=Cn(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=an(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${ke}, protocol ${Ne}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${ai}`),n({kind:"incompatible",hubVersion:typeof v.platformVersion=="string"?v.platformVersion:null,hubProtocol:typeof v.protocolVersion=="number"?v.protocolVersion:null,updateCommand:ai}));return}if(P==="tracking_targets"){w.setTargets(x.targets);return}if(P==="youtrack_sync_request"){$.setRequest(x);return}if(P==="youtrack_force_sync"){$.forceSync();return}if(P==="sync_local"){await bg(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 wg(t,o,v.repo,r),await ci(t,o,r);return}if(P==="remove_repo"){let v=x;r.info(`[repo] remove_repo: ${v.repoName}${v.purge?" (purge)":""}`),await ci(t,o,r),v.purge&&kg(t,o,v.repoName,r);return}if(P==="context_write"){await $g(x,o,f,r);return}if(P==="adr_promote"){await vg(x,o,f,r);return}if(P==="cred_update"){let v=x,S=L(t.projectId),G=S?.sealKey?await dc(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}`:""}`),k()):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 Jc(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 rl(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 nl(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=Ge({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?il(t.projectId,v.name,v.sealed,Q.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else S=sl(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}`:"")),k()):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=Lt(t.projectId),G=ja(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 U=x;if(y===!1){let v=`refused: HUB protocol incompatible with CLI v${ke} (protocol ${Ne})`;f.send(JSON.stringify({type:"action_result",actionId:U.actionId,status:"failed",error:v})),r.warn(`[exec] ${U.actionId} (${U.action.type}) \u2192 REFUSED: ${v}`),r.warn(`[exec] update the CLI to clear this: ${ai}`),n({kind:"action",actionId:U.actionId,actionType:U.action.type,ok:!1,error:v});return}p.add(U.actionId);try{let v=await Ec({action:U.action,repo:U.repo,trackerIssueId:U.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)}));U.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:U.actionId,...v}));let S=v.status!=="failed",G=!S&&"error"in v?v.error:void 0;S?r.info(`[exec] ${U.actionId} (${U.action.type}) \u2192 done`):r.warn(`[exec] ${U.actionId} (${U.action.type}) \u2192 FAILED: ${G??"?"}`),n({kind:"action",actionId:U.actionId,actionType:U.action.type,ok:S,...G?{error:G}:{}})}finally{p.delete(U.actionId)}}),f.on("close",(b,C)=>{let x=C?.toString("utf-8")??"";if(r.info(`[ws] closed code=${b}${x?` reason=${x}`:""}`),w.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 ci(t,e,r){try{let n=await q(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=Ar(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 wg(t,e,r,n){let o=r.mountAs??r.name;if(o==="."){n.info(`[repo] ${r.name} mounts in place (mount_as: .) \u2014 nothing to clone`);return}let i=e?Wr(e.root,o):xe(t.projectId,r.name);if(ul(Wr(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await yg().clone(Dr(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 kg(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?Wr(e.root,o):xe(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!ul(Wr(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{hg(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 bg(t,e,r,n){if(!e){n.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let o of t.repos){let i=e.repos.find(l=>l.name===o.repoName),s=Wr(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Bs(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 $g(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 Je(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 vg(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 Zs(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 ll(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as yl,mkdirSync as wl}from"node:fs";import{dirname as kl}from"node:path";import{simpleGit as Vt}from"simple-git";import{execFileSync as xg}from"node:child_process";import{mkdtempSync as Sg,mkdirSync as Rg,readFileSync as pl,rmSync as Tg,writeFileSync as Ig}from"node:fs";import{tmpdir as Cg}from"node:os";import{dirname as Eg,join as dl}from"node:path";function fl(t="codepipe-context"){let e=Sg(dl(Cg(),"codepipe-ssh-")),r=dl(e,"id_ed25519");try{return xg("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:pl(r,"utf-8"),publicKey:pl(`${r}.pub`,"utf-8").trim()}}finally{Tg(e,{recursive:!0,force:!0})}}async function ml(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 gl(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 hl(t,e){Rg(Eg(t),{recursive:!0});let r=e.endsWith(`
|
|
564
|
+
`;return await ze(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 ha(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:$o.statusColumns}]}async mutateRecord(e,r,n){let o=jr(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=Ar(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:Tr(e),content:Ko(i)},...On(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await ze(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:dn,status:r.targetStatus,links:[],created:n,updated:n},i=Ar(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:Tr(e),content:Ko(o)},...On(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}};function Pc(t,e){let r=se(t,`tasks/${e}/comments.jsonl`);if(!Wm(r))return[];let n=[];for(let o of Ym(r,"utf-8").split(`
|
|
565
|
+
`)){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 ri(t){if(!t)return"youtrack";try{let e=Ac(t,"project.yaml");return Ec(e)&&_c(jc(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function He(t){let e=ri(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=fa(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=Vm(n);return i?{ok:!0,kind:e,provider:new Hr(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=Va();return r?{ok:!0,kind:e,provider:new Fr(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function Vm(t){try{let e=Ac(t,"project.yaml");if(!Ec(e))return null;let r=_c(jc(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var Un=new Map;async function Ln(t,e){let n=(Un.get(t)??Promise.resolve()).catch(()=>{}).then(e);Un.set(t,n);try{return await n}finally{Un.get(t)===n&&Un.delete(t)}}async function Nc(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;Nr(`[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 Ln(`${i}/${r.name}`,async()=>{let s=await Dr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=xe(i,r.name,t.baseDir),{commit:c}=await Ia(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 Ln(`${i}/${r.name}`,async()=>{let s=await Dr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=xe(i,r.name,t.baseDir),{commit:c,pushed:l}=await Ca(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=je(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=je(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=je(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 Ln(`${i}/${r.name}`,async()=>{let s=await Dr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=xe(i,r.name,t.baseDir),{mergedSha:c}=await Pa(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"resolve_review_branch":{if(!r)return H("no repo spec");let i=t.cloneUrlOverride??Ur(r),a=(await Ea(i)).filter(p=>ja(p,e.issueKey)),c=je(r),l=null;if(c.findOpenPrByBranch)for(let p of a){let d=await c.findOpenPrByBranch(r,p).catch(()=>null);if(d){l={number:d.number,url:d.url};break}}return ee({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return H("no repo spec");let i=je(r);return await i.addPRComment(r,e.prNumber,e.body),ee({prNumber:e.prNumber,host:i.name})}case"tracker_status":{let i=He({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),ee({issueId:t.trackerIssueId,newStatus:e.newStatus})):H("no tracker_issue_id provided"):H(i.error)}case"tracker_comment":{let i=He({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 ee({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=He({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 ee({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=He({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 ee({applied:s})}case"set_project_setting":{if(!t.contextDir)return H("no context repo clone on this CLI");let i=await Sc(t.contextDir,e.edits);return ee({files:i.files})}case"tracker_edit":{let i=He({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 Dn(t.contextDir,e.projectId,[{issue:s,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 Ic(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 Tc(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}=xn(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=os(c,e.input);if(!l.ok)return H(l.error);let p=Vs(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),Ln(`${e.projectId}/${r.name}`,async()=>{await Dr(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=xe(e.projectId,r.name,t.baseDir),f=await bc({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=xc(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 Xc,readFileSync as Qc}from"node:fs";import{join as Zc}from"node:path";import{homedir as Jm}from"node:os";import{existsSync as zm,mkdirSync as Xm,readFileSync as Qm,writeFileSync as Zm}from"node:fs";import{dirname as eg,join as tg}from"node:path";function ni(){return F("FARM_PINS")??tg(Jm(),".codepipe","farm-pins.json")}function Oc(){let t=ni();if(!zm(t))return{};try{return JSON.parse(Qm(t,"utf-8"))}catch{return{}}}function rg(t){let e=ni();Xm(eg(e),{recursive:!0}),Zm(e,JSON.stringify(t,null,2)+`
|
|
566
|
+
`,{mode:384})}function ng(t){return Oc()[t]}function Bn(t,e){let r=Oc();r[t]=e,rg(r)}function Mn(t,e){let r=me(e),n=ng(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 ${ni()}.`);return r}import{setTimeout as og}from"node:timers/promises";import ig from"ws";function Gn(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new ig(r)}var N=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};async function ut(t,e,r){return _e(t,e,"/projects",r)}async function Dc(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 Fn(t,e,r,n){return _e(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function Uc(t,e,r,n){return _e(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function Lc(t,e,r,n){return _e(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function Bc(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 Hn(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 oi(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}async function Mc(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await oi(t,e),a=new Set;for(let c of s)c.id!==r.excludeProjectId&&c.trackerProvider==="internal"&&c.youtrackProjectKey&&a.add(c.youtrackProjectKey.toUpperCase());return a}catch(s){o=s,i<n-1&&await og(r.delayMs??1500)}throw o}var Kr=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function Gc(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 Kr(e)}if(!r.ok)throw new N(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function Fc(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 Hc(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 Kc(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 Wc(t,e,r,n){return _e(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function Yc(t,e,r,n,o){return _e(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function qc(t,e,r,n,o){return _e(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function Vc(t,e,r,n,o){return _e(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function Wr(t,e,r,n){return _e(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function ii(t,e,r,n){await _e(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function Jc(t,e,r,n){return _e(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function zc(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 _e(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 el(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=me(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Mn(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=Zc(r,"project.yaml"),m=Zc(r,"regimen.yaml");Xc(u)&&Xc(m)?c={projectYaml:Qc(u,"utf-8"),regimenYaml:Qc(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=Xe(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 Fn(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 sg}from"node:os";import{existsSync as ag,mkdirSync as cg,readFileSync as lg,writeFileSync as ug}from"node:fs";import{dirname as pg,join as dg}from"node:path";function si(){return F("RUNNER_PINS")??dg(sg(),".codepipe","runner-pins.json")}function tl(){let t=si();if(!ag(t))return{};try{return JSON.parse(lg(t,"utf-8"))}catch{return{}}}function fg(t){let e=si();cg(pg(e),{recursive:!0}),ug(e,JSON.stringify(t,null,2)+`
|
|
567
|
+
`,{mode:384})}function mg(t){return tl()[t]}function ai(t,e){let r=tl();r[t]=e,fg(r)}function rl(t,e){let r=me(e),n=mg(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 ${si()}.`);return r}var ol=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function nl(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:ol(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 gg={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:ol(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)=>nl(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>nl(t,e,r,"remove-token")},il={api:gg,fetchProject:q,provisionOnRunner:Uc,teardownOnRunner:Lc};async function sl(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(me(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");rl(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 al(t,e,r,n=il){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 sl(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=Xe(e.runnerPublicKey,JSON.stringify(l));ai(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 cl(t,e,r,n=il){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 sl(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=Xe(e.runnerPublicKey,JSON.stringify(c));ai(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 ll=16*1024;function hg(t){return be.test(t)?tt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${be}`}function ul(t,e,r,n){let o=hg(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(Vt(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>ll)return{ok:!1,detail:`secret value too large (max ${ll} chars)`};try{return _s(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function pl(t,e){try{return Ns(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 Kn=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 Tt){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=yg(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}};function yg(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var Wn=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??(()=>He({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 k=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 A=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[M,P]=await Promise.all([A.length>0?r.listIssues({projectKey:e.projectKey,columns:A,...k,...I}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...k})]),g=new Map;for(let _ of[...M,...P])g.set(_.id,_);o=[...g.values()]}else{let A=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:A,...k,...I})}}catch(k){this.log.warn(`[yt-sync] listIssues failed: ${k instanceof Error?k.message:String(k)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let k of o){if(s.add(k.id),a.has(k.status))continue;let I=await fl(r,k.id,e.sinceMs,this.log);I&&i.set(k.id,I)}let c=[];for(let k of e.offBoardIssueIds){if(s.has(k))continue;let I=await fl(r,k,e.sinceMs,this.log);if(I&&I.length>0&&i.set(k,I),e.requireAssignee||I&&I.length>0){let B=await bg(r,k,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(k=>!a.has(k.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(k=>({issue:k,comments:i.get(k.id)??[],attachments:p.get(k.id)??[]}));try{await Dn(this.options.contextDir,e.projectId,u),this.abandonedTicks=0;for(let k of d)this.shippedAttachments.add(k)}catch(k){let I=k instanceof Error?k.message:String(k);this.abandonTick(`context task sync failed: ${I}`);return}let m=this.options.isSelfComment??(()=>!1),f=[],y=[];for(let[k,I]of i){let B=I.filter(A=>!m(A.id));if(B.length===0)continue;f.push({issueId:k,comments:B.map(wg)});let R=B.flatMap(A=>{let M=Dt(A.body);return M?[{commentId:A.id,author:A.author,name:M.name,args:M.args,createdAt:A.createdAt}]:[]});R.length>0&&y.push({issueId:k,commands:R})}let w={type:"youtrack_observation",projectId:e.projectId,issues:o.map(dl),commentsBatch:f,...y.length>0?{commandsBatch:y}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(dl)}:{},observedAtMs:n};this.send(w);let $=f.reduce((k,I)=>k+I.comments.length,0),h=y.reduce((k,I)=>k+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=kg(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 dl(t){let{description:e,...r}=t;return r}function wg(t){let{body:e,...r}=t;return r}function kg(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 bg(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 fl(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 ci="npm i -g @code-partner/codepipe@latest";function Yn(t,e={}){let r=e.log??{info:f=>console.log(f),warn:f=>console.warn(f)};r.info(`codepipe-cli v${ke} (protocol ${De})`);let n=f=>e.onEvent?.(f),o=e.workspace;o?.contextDir&&Xs(o.contextDir,r);let i=ml("CLI_TRACKING_POLL_INTERVAL_SEC"),s=ml("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=Gn(t.hubUrl,t.cliToken),y=null,w=new Kn(i,b=>{f.readyState===f.OPEN&&f.send(JSON.stringify(b))},r),$=new Wn(s,b=>{f.readyState===f.OPEN&&f.send(JSON.stringify(b))},r,{contextDir:o?.contextDir??null,isSelfComment:b=>d.has(b)}),h=null,k=async()=>{try{let b={trackerProvider:ri(o?.contextDir??null)};try{let E=await q(t.hubUrl,t.cliToken,t.projectId);b={...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 dc(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:Os(t.projectId),checkedAt:C.checkedAt};if(f.send(JSON.stringify(x)),C.ready)r.info("[readiness] ready");else{let E=C.checks.filter(U=>!U.ok).map(U=>`${U.name}(${U.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${E.join(", ")}`)}}catch(b){r.warn(`[readiness] check failed: ${b instanceof Error?b.message:String(b)}`)}},I=()=>{k(),h=setInterval(()=>void k(),a),typeof h.unref=="function"&&h.unref()},B=()=>{h&&(clearInterval(h),h=null)},R=150,A=new Map,M=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"){M(b);return}x.timer||(x.timer=setTimeout(()=>M(b),R),x.timer.unref?.())},g=o?.contextDir?new Sn(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 $a(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=Hs(t.projectId),C=F("ORIGIN")==="farm"?"farm":"local",x=F("FARM_ID"),E=t.accountEmail??b.email,U;try{let S=hc(t.projectId);S&&(U=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:ke,protocolVersion:De,accountId:b.accountId,accountLabel:b.label,origin:C,inFlightActionIds:[...p],...E?{accountEmail:E}:{},...C==="farm"&&x?{farmId:x}:{},...U?{sealPublicKey:U}:{}};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(),I(),li(t,o,r),o?.contextDir)try{let S=Cn(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(E==="hello"){let v=x;y=cn(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${ke}, protocol ${De}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${ci}`),n({kind:"incompatible",hubVersion:typeof v.platformVersion=="string"?v.platformVersion:null,hubProtocol:typeof v.protocolVersion=="number"?v.protocolVersion:null,updateCommand:ci}));return}if(E==="tracking_targets"){w.setTargets(x.targets);return}if(E==="youtrack_sync_request"){$.setRequest(x);return}if(E==="youtrack_force_sync"){$.forceSync();return}if(E==="sync_local"){await Rg(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 xg(t,o,v.repo,r),await li(t,o,r);return}if(E==="remove_repo"){let v=x;r.info(`[repo] remove_repo: ${v.repoName}${v.purge?" (purge)":""}`),await li(t,o,r),v.purge&&Sg(t,o,v.repoName,r);return}if(E==="context_write"){await Tg(x,o,f,r);return}if(E==="adr_promote"){await Ig(x,o,f,r);return}if(E==="cred_update"){let v=x,S=L(t.projectId),G=S?.sealKey?await yc(t.projectId,v.kind,v.sealed,S.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},Z={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(Z)),G.ok?(r.info(`[cred] ${v.kind} replaced${G.detail?` \u2014 ${G.detail}`:""}`),k()):r.warn(`[cred] ${v.kind} replacement rejected: ${G.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 S=await el(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(E==="gh_runner_setup"){let v=x;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${v.runnerName} (${v.runnerId})`);let S=await al(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(E==="gh_runner_teardown"){let v=x;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${v.runnerName} (${v.runnerId})`);let S=await cl(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(E==="tracker_fields_request"){let v=x,S={type:"tracker_fields_result",requestId:v.requestId,projectId:t.projectId,ok:!1},G=He({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(Z){S.error=Z instanceof Error?Z.message:String(Z)}f.readyState===f.OPEN&&f.send(JSON.stringify(S)),S.ok||r.warn(`[yt-fields] listing failed: ${S.error??"unknown"}`);return}if(E==="project_secret_update"||E==="project_secret_delete"){let v=x,S;if(v.type==="project_secret_update"){let Z=L(t.projectId);S=Z?.sealKey?ul(t.projectId,v.name,v.sealed,Z.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else S=pl(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}`:"")),k()):r.warn(`[secret] ${v.name} rejected: ${S.detail??"unknown"}`);return}if(E==="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=Mt(t.projectId),G=Da(x,v,S,r);for(let Z of G)f.readyState===f.OPEN&&f.send(JSON.stringify(Z));return}if(E!=="dispatch_action")return;let U=x;if(y===!1){let v=`refused: HUB protocol incompatible with CLI v${ke} (protocol ${De})`;f.send(JSON.stringify({type:"action_result",actionId:U.actionId,status:"failed",error:v})),r.warn(`[exec] ${U.actionId} (${U.action.type}) \u2192 REFUSED: ${v}`),r.warn(`[exec] update the CLI to clear this: ${ci}`),n({kind:"action",actionId:U.actionId,actionType:U.action.type,ok:!1,error:v});return}p.add(U.actionId);try{let v=await Nc({action:U.action,repo:U.repo,trackerIssueId:U.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:g?()=>g.reportNow():void 0,refreshContextStatus:o?.contextDir?_:void 0,onRunActivity:P}).catch(Z=>({status:"failed",error:Z instanceof Error?Z.message:String(Z)}));U.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:U.actionId,...v}));let S=v.status!=="failed",G=!S&&"error"in v?v.error:void 0;S?r.info(`[exec] ${U.actionId} (${U.action.type}) \u2192 done`):r.warn(`[exec] ${U.actionId} (${U.action.type}) \u2192 FAILED: ${G??"?"}`),n({kind:"action",actionId:U.actionId,actionType:U.action.type,ok:S,...G?{error:G}:{}})}finally{p.delete(U.actionId)}}),f.on("close",(b,C)=>{let x=C?.toString("utf-8")??"";if(r.info(`[ws] closed code=${b}${x?` reason=${x}`:""}`),w.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 li(t,e,r){try{let n=await q(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=_r(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 xg(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?Yr(e.root,o):xe(t.projectId,r.name);if(gl(Yr(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await vg().clone(Ur(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 Sg(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?Yr(e.root,o):xe(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!gl(Yr(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{$g(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 Rg(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=Yr(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Ks(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 Tg(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 ze(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 Ig(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 oa(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 ml(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as vl,mkdirSync as xl}from"node:fs";import{dirname as Sl}from"node:path";import{simpleGit as zt}from"simple-git";import{execFileSync as Cg}from"node:child_process";import{mkdtempSync as Pg,mkdirSync as Eg,readFileSync as hl,rmSync as jg,writeFileSync as Ag}from"node:fs";import{tmpdir as _g}from"node:os";import{dirname as Ng,join as yl}from"node:path";function wl(t="codepipe-context"){let e=Pg(yl(_g(),"codepipe-ssh-")),r=yl(e,"id_ed25519");try{return Cg("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:hl(r,"utf-8"),publicKey:hl(`${r}.pub`,"utf-8").trim()}}finally{jg(e,{recursive:!0,force:!0})}}async function kl(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 bl(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 $l(t,e){Eg(Ng(t),{recursive:!0});let r=e.endsWith(`
|
|
568
568
|
`)?e:e+`
|
|
569
|
-
`;return
|
|
570
|
-
[${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
|
|
571
|
-
`,{mode:384})}import
|
|
572
|
-
`}async function
|
|
573
|
-
`))!==-1;){let M=I.slice(0,
|
|
574
|
-
`)){let M=
|
|
575
|
-
`))!==-1;){let M=B.slice(0,
|
|
576
|
-
`)){let M=
|
|
569
|
+
`;return Ag(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}function Og(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 Dg(t,e){return e?.contextWrite?.token?{user:mn(t),secret:e.contextWrite.token}:t===Ir.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Ir.bitbucket?e?.bitbucket?.apiToken?{user:xt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}var qn=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}};async function Rl(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 qn))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 Vn(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 qn(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=Dg(Lt(s.cloneUrl),r);if(a){let c=await Ug({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 Lg({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 Ug(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=Og(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(vl(`${r}/.git`)){let l=zt(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let p=Eo(r);await l.reset(["--hard",`origin/${s}`]),jo(r,p),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else xl(Sl(r),{recursive:!0}),await zt().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await Tl(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 Lg(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=$l(i,n),a=bl(e.cloneUrl),c=e.branch;try{if(vl(`${r}/.git`)){let l=zt(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=Eo(r);await l.reset(["--hard",`origin/${c}`]),jo(r,p),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else xl(Sl(r),{recursive:!0}),await zt().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await zt(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await Tl(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 Tl(t){let e=zt(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 Il(t={profile:void 0}){let{cfg:e,profile:r}=wn(t.profile),n=L(e.projectId);n&&Cr(n),Br(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Mr(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),Gr(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=qr(ui(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=$n("CLI_LOG",i,o);if(s.enabled){let u=new Ft(s);vn(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=hn(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=qr(ui(),".codepipe",r?qr("profiles",r,"context"):"context");if(await ii(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await Rl(()=>Vn({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 ii(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=qr(ui(),".codepipe",r?qr("profiles",r,"context-config"):"context-config");Rn(a.contextDir,m,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=Yn(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(`
|
|
570
|
+
[${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 Yg}from"node:os";import{spawnSync as Bg}from"node:child_process";function Mg(){try{return Bg("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function Cl(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:Mg(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}import{homedir as Xt}from"node:os";import{mkdirSync as Gg,readFileSync as Pl,writeFileSync as Fg,existsSync as pi}from"node:fs";import{dirname as Hg,join as pt}from"node:path";pi(".env")&&process.loadEnvFile(".env");function Kg(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function Ne(t){let e=F("SANDBOX_CONFIG");if(e)return e;let r=pt(Xt(),".codepipe","worker");return t?pt(r,"profiles",t,"config.json"):pt(r,"config.json")}function El(){return pt(Xt(),".devpipe-sandbox","config.json")}function Jn(){St(pt(Xt(),".devpipe"),pt(Xt(),".codepipe")),F("SANDBOX_CONFIG")||St(pt(Xt(),".devpipe-sandbox"),pt(Xt(),".codepipe-sandbox"))}function de(t){let e=Ne(t),r=null;return pi(e)?r=JSON.parse(Pl(e,"utf-8")):!t&&!F("SANDBOX_CONFIG")&&pi(El())&&(r=JSON.parse(Pl(El(),"utf-8"))),r?(r.planningLane=Kg(),r):null}function jl(t,e){let r=Ne(e);Gg(Hg(r),{recursive:!0}),Fg(r,JSON.stringify(t,null,2)+`
|
|
571
|
+
`,{mode:384})}import Wg from"ws";var Qt=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 Wg(e)}};async function It(t){Jn();let e=de(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Ne(t.profile)}.`),process.exit(1));let r=t.name??Yg(),n=Cl({projects:t.projects??[],llm:t.llm??null}),o=new Qt(t.hub.replace(/\/$/,"")),i=An(),s=me(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});jl({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 ${Ne(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 Fh,readFileSync as ki,readdirSync as Hh,writeFileSync as Kh}from"node:fs";import{homedir as Wh}from"node:os";import{dirname as Yh,join as sr}from"node:path";import{spawn as Qg}from"node:child_process";import{existsSync as Zg}from"node:fs";import{spawn as qg}from"node:child_process";var Al=16e3,_l=5e3,Nl=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),Vg="\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 di(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}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}function zg(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Ct(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function fi(t){return JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:t}]}})+`
|
|
572
|
+
`}async function Ol(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Qe;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:di(f,Al)})}else if(m==="tool_use"){let f=String(u.name??""),y=u.input?.file_path??u.input?.path,w=Jg(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?di(zg(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=qg(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"),_l)};e.signal?.addEventListener("abort",f,{once:!0});let y=null,w=()=>{y&&clearTimeout(y),y=setTimeout(()=>{u=!0,console.warn(`[claude:chat] idle for ${Nl}ms \u2014 ending session`),p.kill("SIGTERM"),m=setTimeout(()=>p.kill("SIGKILL"),_l)},Nl)},$=()=>{m&&clearTimeout(m),y&&clearTimeout(y),e.signal?.removeEventListener("abort",f)},h=!0,k=R=>{if(!(!h||p.stdin.destroyed))try{p.stdin.write(R)}catch{}};k(fi(e.prompt)),w(),(async()=>{try{for await(let R of e.interactive.inbox){if(d||!h)break;if(w(),R.kind==="user")o({ts:Date.now(),kind:"text",author:"user",text:di(R.text,Al)}),k(fi(R.text));else{k(fi(Vg)),h=!1;try{p.stdin.end()}catch{}break}}}catch{}})();let I="",B=R=>{let A;try{A=JSON.parse(R)}catch{return}a(A)};p.stdout.on("data",R=>{i.push(R),w(),I+=R;let A;for(;(A=I.indexOf(`
|
|
573
|
+
`))!==-1;){let M=I.slice(0,A).trim();I=I.slice(A+1),M&&B(M)}}),p.stderr.on("data",R=>{i.push(R);for(let A of R.split(`
|
|
574
|
+
`)){let M=A.trim();M&&console.warn(`[claude:chat:stderr] ${M}`)}}),p.on("error",R=>{$(),l(R)}),p.on("close",R=>{if($(),d){l(new Qe);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:Xg(s)})})})}function Xg(t){let e=bt();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=Ct(r.input_tokens),e.outputTokens=Ct(r.output_tokens),e.cacheReadInputTokens=Ct(r.cache_read_input_tokens),e.cacheCreationInputTokens=Ct(r.cache_creation_input_tokens)),e.totalCostUsd=Ct(t.total_cost_usd),e.numTurns=Ct(t.num_turns),e.durationMs=Ct(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var Zt=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Qe=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},eh=5e3,Vr=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return Ol(this.binary,e);if(e.signal?.aborted)throw new Qe;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=oh(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+=ge(w.input_tokens),s.output+=ge(w.output_tokens),s.cacheRead+=ge(w.cache_read_input_tokens),s.cacheCreate+=ge(w.cache_creation_input_tokens))}}},d=e.role,u=e.onActivity,m=f=>{if(u)for(let y of sh(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=Qg(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 $=!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")},eh)};e.signal?.addEventListener("abort",k,{once:!0});let I=()=>{h&&clearTimeout(h),e.signal?.removeEventListener("abort",k)},B="";w.stdout.on("data",R=>{n.push(R),B+=R;let A;for(;(A=B.indexOf(`
|
|
575
|
+
`))!==-1;){let M=B.slice(0,A).trim();if(B=B.slice(A+1),M){let P=Dl(M);p(P),P&&m(P)}}}),w.stderr.on("data",R=>{n.push(R),o.push(R);for(let A of R.split(`
|
|
576
|
+
`)){let M=A.trim();M&&console.warn(`[claude:stderr] ${M}`)}}),w.on("error",R=>{I(),y(R)}),w.on("close",R=>{if(I(),$){y(new Qe);return}if(B.trim()){let M=Dl(B.trim());p(M),M&&m(M)}let A=i?.is_error===!0;if(R!==0||A){let M=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 Zt(th(R,i,o.join("")),{code:R,apiErrorStatus:M,subtype:P,resultText:g,retryAfterMs:rh(i)}));return}console.log("[claude] exit code=0"),f({artifactPaths:[],log:n.join(""),usage:ih(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("/")&&Zg(n))}};function Dl(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: ${dt(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=nh(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=Ll(o.content);console.log(`[claude] tool_result (error)${i?`: ${dt(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)} ${dt(JSON.stringify(e),200)}`),e}function th(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(dt(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(dt(r.trim().split(`
|
|
577
577
|
`).slice(-5).join(`
|
|
578
|
-
`),500)),n.join(" \u2014 ")}function
|
|
579
|
-
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:bt()}}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
|
|
578
|
+
`),500)),n.join(" \u2014 ")}function rh(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 Ll(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function nh(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=${dt(r,80)}`}return""}function dt(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function ge(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function oh(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=ge(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:ge(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 ih(t,e,r,n){let o=bt(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=ge(i.input_tokens),o.outputTokens=ge(i.output_tokens),o.cacheReadInputTokens=ge(i.cache_read_input_tokens),o.cacheCreationInputTokens=ge(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=ge(t?.total_cost_usd),o.numTurns=t&&ge(t.num_turns)>0?ge(t.num_turns):r,o.durationMs=ge(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}var Ul=200;function sh(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:dt(c,Ul)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,p=l?.file_path??l?.path??l?.notebook_path,d=ah(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?dt(Ll(s.content),Ul):"";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 ah(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 ch,writeFileSync as er}from"node:fs";import{dirname as lh,join as tr}from"node:path";function Bl(t,e,r){let n=tr(t,e);ch(lh(n),{recursive:!0}),er(n,r)}var Jr=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=uh(n,o,i);er(tr(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;er(tr(e.workspaceDir,"SOLUTION.md"),ph(n,o,i,a)),s.push("SOLUTION.md"),er(tr(e.workspaceDir,"QUESTIONS.md"),dh(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Bl(e.workspaceDir,"changes/sample.patch",fh(n,o,a)),s.push("changes/sample.patch"),Bl(e.workspaceDir,"diff-summary.md",mh(n,o,a)),s.push("diff-summary.md")}else e.role==="rework"&&(er(tr(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
|
|
579
|
+
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:bt()}}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 Qe;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 er(tr(e.workspaceDir,"DRAFT.md"),`${o}
|
|
580
580
|
|
|
581
581
|
\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).
|
|
582
|
-
`),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:bt()}}};function
|
|
582
|
+
`),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:bt()}}};function uh(t,e,r){return`# ${t} \u2014 Estimate
|
|
583
583
|
|
|
584
584
|
**Title:** ${e}
|
|
585
585
|
|
|
@@ -600,7 +600,7 @@ production-grade estimates.)
|
|
|
600
600
|
${r.split(`
|
|
601
601
|
`).slice(0,8).join(`
|
|
602
602
|
`).trim()||"(empty)"}
|
|
603
|
-
`}function
|
|
603
|
+
`}function ph(t,e,r,n){let o=n?`
|
|
604
604
|
## Reviewer rework instruction
|
|
605
605
|
|
|
606
606
|
> ${n.split(`
|
|
@@ -629,10 +629,10 @@ TBD (mock runner does not yet inspect project code).
|
|
|
629
629
|
${r.split(`
|
|
630
630
|
`).slice(0,8).join(`
|
|
631
631
|
`).trim()||"(empty)"}
|
|
632
|
-
`}function
|
|
632
|
+
`}function dh(t){return`# ${t} \u2014 Open questions
|
|
633
633
|
|
|
634
634
|
(none \u2014 mock runner did not surface ambiguities.)
|
|
635
|
-
`}function
|
|
635
|
+
`}function fh(t,e,r){let n=r?` (rework: ${r.split(`
|
|
636
636
|
`)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
|
|
637
637
|
index 0000000..1111111 100644
|
|
638
638
|
--- a/CHANGELOG.md
|
|
@@ -643,7 +643,7 @@ index 0000000..1111111 100644
|
|
|
643
643
|
+- mock-runner placeholder change for slice 5 testing.
|
|
644
644
|
+
|
|
645
645
|
# Changelog
|
|
646
|
-
`}function
|
|
646
|
+
`}function mh(t,e,r){return`# ${t} \u2014 Diff summary
|
|
647
647
|
|
|
648
648
|
**Title:** ${e}
|
|
649
649
|
${r?`
|
|
@@ -654,99 +654,99 @@ ${r?`
|
|
|
654
654
|
- \`CHANGELOG.md\` \u2014 added entry for ${t}.
|
|
655
655
|
|
|
656
656
|
(Mock-runner output. Replace with claude-headless for production patches.)
|
|
657
|
-
`}function
|
|
657
|
+
`}function Ml(t){switch(t){case"mock":return new Jr;case"claude-headless":return new Vr;default:return null}}function Hl(t=process.env){return{maxAttempts:zn(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:zn(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:zn(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:zn(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}var gh=new Set([429,500,502,503,529]),Gl=/(ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|EPIPE|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,hh=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,yh=new Set(["error_max_turns"]);function wh(t){if(t instanceof Zt){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return hh.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&yh.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:gh.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:Gl.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 Gl.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}var Fl=/(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 Kl(t){if(t instanceof Zt){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&Fl.test(n)}let e=t instanceof Error?t.message:String(t);return Fl.test(e)}function kh(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 Wl(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=wh(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=kh(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 zn(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}import{mkdtempSync as bh,rmSync as $h,writeFileSync as Yl}from"node:fs";import{tmpdir as vh}from"node:os";import{join as mi}from"node:path";function Xn(t){return`[url "https://${t}/"]
|
|
658
658
|
insteadOf = git@${t}:
|
|
659
659
|
insteadOf = ssh://git@${t}/
|
|
660
|
-
`}var
|
|
660
|
+
`}var xh=Xn("github.com"),Sh=Xn("bitbucket.org"),Rh=Xn("gitlab.com");function ql(t,e){if(t.length===0)return null;let r=bh(mi(vh(),"devpipe-gitcreds-")),n=mi(r,"credentials"),o=mi(r,"gitconfig");return Yl(n,t.join(`
|
|
661
661
|
`)+`
|
|
662
|
-
`,{mode:384}),
|
|
662
|
+
`,{mode:384}),Yl(o,`[credential]
|
|
663
663
|
helper = store --file=${n}
|
|
664
|
-
`+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{
|
|
665
|
-
`).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
|
|
666
|
-
`).map(l=>l.trim()).filter(l=>l.length>0),c=await
|
|
667
|
-
${s.join("").trim()||"(no stderr)"}`))})})}function
|
|
668
|
-
${a.join("").trim()||"(no stderr)"}`))})})}function
|
|
669
|
-
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c
|
|
670
|
-
`+e.subarray(e.length-
|
|
671
|
-
\u2026 [${r.length-e} bytes elided]`}import{lstatSync as
|
|
664
|
+
`+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{$h(r,{recursive:!0,force:!0})}catch{}}}}function gi(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(xh)),t.bitbucket?.apiToken&&(e.push(`https://${xt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(Sh)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(Rh)),ql(e,r)}function Vl(t,e){if(t.contextWrite?.token){let r=Lt(e)??"github.com",n=mn(r);return ql([`https://${n}:${t.contextWrite.token}@${r}`],[Xn(r)])}return gi(t)}import{spawn as zl}from"node:child_process";import{existsSync as Qn,mkdirSync as Zn,readFileSync as Th,rmSync as hi,symlinkSync as Ih}from"node:fs";import{homedir as Ch}from"node:os";import{dirname as eo,join as Pt}from"node:path";function Xl(){return Pt(Ch(),".codepipe-sandbox","repos")}var rr=new Map;function Ql(t,e){let n=(rr.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{rr.get(t)===o&&rr.delete(t)},()=>{rr.get(t)===o&&rr.delete(t)});return rr.set(t,o),n}function Jl(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 Ph(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 Zl(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||!Jl(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{Qn(t)&&hi(t,{recursive:!0,force:!0}),Zn(eo(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||!Jl(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),Qn(t)&&hi(t,{recursive:!0,force:!0}),Zn(eo(t),{recursive:!0}),await X(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(Qn(Pt(t,".git")))try{return await s()}catch(c){if(!Ph(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 eu(t){await X(t.workspacePath,["reset","--hard",t.baseSha]),await X(t.workspacePath,["clean","-fdx"])}var nr="CodePipe Agent",or="codepipe@codepartner.ee";async function tu(t,e){let r=t.workspacePath;await X(r,["add","-A"]);let n=(await pe(r,["write-tree"])).trim(),o=(await pe(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:nr,GIT_AUTHOR_EMAIL:or,GIT_COMMITTER_NAME:nr,GIT_COMMITTER_EMAIL:or};return(await pe(r,["commit-tree",n,"-m",e],i)).trim()}async function ru(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 Lt(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 nu(t,e){return pe(t.workspacePath,["diff","--binary",t.baseSha,e])}async function ou(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 iu(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 pe(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=>pe(s,["rev-parse","-q","--verify",`${f}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await pe(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:nr,GIT_AUTHOR_EMAIL:or,GIT_COMMITTER_NAME:nr,GIT_COMMITTER_EMAIL:or},p=(await pe(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),d=(await pe(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 pe(s,["diff","--name-only","--diff-filter=U"])).split(`
|
|
665
|
+
`).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 yi(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:nr,GIT_AUTHOR_EMAIL:or,GIT_COMMITTER_NAME:nr,GIT_COMMITTER_EMAIL:or};(await pe(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 pe(n,["diff","--name-only","--diff-filter=U"])).split(`
|
|
666
|
+
`).map(l=>l.trim()).filter(l=>l.length>0),c=await pe(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=zl("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}):
|
|
667
|
+
${s.join("").trim()||"(no stderr)"}`))})})}function pe(t,e,r){return new Promise((n,o)=>{let i=zl("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}):
|
|
668
|
+
${a.join("").trim()||"(no stderr)"}`))})})}function su(t,e){Qn(t)&&hi(t,{recursive:!0,force:!0}),Zn(eo(t),{recursive:!0}),Ih(e,t,"dir")}async function au(t,e,r){await X(t,["worktree","prune"]).catch(()=>{}),Zn(eo(r),{recursive:!0}),await X(t,["worktree","add","--detach",r,`origin/${e}`])}async function cu(t,e,r,n="worktree",o){return r.length===0?[]:Ql(e,async()=>{let i=[];for(let s of r){let a=Pt(Xl(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await Zl(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 pe(a,["rev-parse","HEAD"])).trim(),p=Pt(t,"code",s.name);n==="direct"?(su(p,a),console.log(`[git] code: linked ${p} \u2192 ${a} @ ${l.slice(0,10)}`)):(await au(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 lu(t,e,r,n="worktree",o){if(!r||!r.cloneUrl)return null;let i=r;return Ql(e,async()=>{let s=Pt(Xl(),e,"_context");console.log(`[git] context: ensure ${i.cloneUrl} @ ${i.ref} \u2192 ${s}`);try{await Zl(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=Pt(t,"context");n==="direct"?(su(a,s),console.log(`[git] context: linked ${a} \u2192 ${s}`)):(await au(s,i.ref,a),console.log(`[git] context: worktree ${a} \u2190 ${s}`));let c=(await pe(s,["rev-parse","HEAD"])).trim();return{workspacePath:a,cachePath:s,baseSha:c}})}async function uu(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await X(r,["add","-A",...n]).catch(()=>{});let o;try{o=await pe(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
|
|
669
|
+
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=Th(Pt(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as Eh}from"node:fs";import{join as jh}from"node:path";var wi=8*1024,ft=class extends Error{},zr="meta/build-result.json";function pu(t){let e=jh(t,zr),r;try{r=Eh(e,"utf-8")}catch{throw new ft(`BUILD produced no ${zr} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(p){throw new ft(`${zr} is not valid JSON: ${p instanceof Error?p.message:String(p)}`)}if(!n||typeof n!="object")throw new ft(`${zr} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new ft(`${zr}: "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"?Ah(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 Ah(t){let e=Buffer.from(t,"utf-8");return e.length<=wi?t:`\u2026 [${e.length-wi} bytes elided] \u2026
|
|
670
|
+
`+e.subarray(e.length-wi).toString("utf-8")}import{readFileSync as _h}from"node:fs";import{join as Nh}from"node:path";var Oh=16*1024,Dh=4*1024,Ze=class extends Error{},ir="meta/review-result.json";function fu(t){let e=Nh(t,ir),r;try{r=_h(e,"utf-8")}catch{throw new Ze(`code review produced no ${ir} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(c){throw new Ze(`${ir} is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(!n||typeof n!="object")throw new Ze(`${ir} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new Ze(`${ir}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?du(o.remarks,Oh):"";if(!i&&s.trim().length===0)throw new Ze(`${ir}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?du(o.summary,Dh):"";return{approved:i,remarks:s,summary:a}}function du(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
|
|
671
|
+
\u2026 [${r.length-e} bytes elided]`}import{lstatSync as Uh,mkdtempSync as Lh,readFileSync as Bh,readdirSync as gu,rmSync as mu}from"node:fs";import{tmpdir as Mh}from"node:os";import{join as to,relative as Gh}from"node:path";var hu=new Set(["code","context"]);function yu(t){let e=Lh(to(Mh(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>mu(e,{recursive:!0,force:!0}),listFiles:()=>wu(e,e),readFile:r=>Bh(to(e,r),"utf-8"),clean:()=>{for(let r of gu(e))hu.has(r)||mu(to(e,r),{recursive:!0,force:!0})}}}function wu(t,e){let r=[];for(let n of gu(e)){let o=to(e,n),i=Uh(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&hu.has(n))continue;r.push(...wu(t,o))}else r.push(Gh(t,o))}return r}var ro=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),qh=new Set(["implement","resolve-conflict"]);function Vh(t){let e=Buffer.from(t,"utf-8");if(e.length<=ro)return t;let r=Math.floor(ro/4),n=ro-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}
|
|
672
672
|
|
|
673
673
|
\u2026 [${s} bytes elided \u2014 log capped at ${ro} bytes for upload] \u2026
|
|
674
674
|
|
|
675
|
-
${i}`}function
|
|
675
|
+
${i}`}function Jh(){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 Xr(t={}){Jn();let e=de(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=sr(Wh(),".codepipe","logs"),i=$n("SANDBOX_LOG",n,o);if(i.enabled){let P=new Ft(i);vn(P),console.log(`[log] file logging \u2192 ${P.path} (rotate at ${i.maxBytes}B, keep ${i.maxFiles})`)}console.log(`codepipe-sandbox v${ke} (protocol ${De})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let s=Ml(e.llm);console.log(`llm backend: ${s?s.name():"(none \u2014 will not claim agent jobs)"}`);let a=Hl();console.log(`llm retry: maxAttempts=${a.maxAttempts} backoff=${a.baseDelayMs}\u2013${a.maxDelayMs}ms budget=${a.totalBudgetMs}ms`);let c=new Qt(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:ke,protocolVersion:De};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=cn(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(),$=async P=>{for(;!l;){if(m===!1){f||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${ke}, protocol ${De}) \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=Jh()),d.set(g.jobId,_);let b=!1,C=null,x=null,E=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),U=async()=>{try{await P.heartbeat(g.jobId)==="claim_lost"&&(b=!0,console.warn(`[job] ${g.jobId} claim lost \u2014 HUB sweeper took it`))}catch(W){let Ce=W instanceof Error?W.message:String(W);console.warn(`[job] ${g.jobId} heartbeat error: ${Ce}`)}};U();let v=setInterval(()=>{U()},E),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=[],Z=null,j=400,ue=25,Te=500,Ie=()=>{if(Z&&(clearTimeout(Z),Z=null),G.length===0)return;let W=G.splice(0,G.length),Ce=u;if(!Ce||Ce.readyState!==Ce.OPEN)return;let We={type:"agent_activity",jobId:g.jobId,taskId:g.taskId,projectId:g.projectId,role:g.role,phase:g.phase,events:W};try{Ce.send(JSON.stringify(We))}catch{}},Nt=W=>{G.push(W),G.length>Te&&G.shift(),G.length>=ue?Ie():Z||(Z=setTimeout(Ie,j))},wt=g.role==="analysis"&&g.taskId.startsWith("draft::")?g.taskId.slice(7):null,ce=new Set,po=null;try{if(!s){b||await P.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:S,finishedAt:new Date().toISOString()});return}let W=yu(g.jobId);console.log(`[job] ${g.jobId} workspace=${W.dir}`);let Ce=k(g,r);C=Ce.gitCreds,x=Ce.contextGitCreds;let We=C?.env,Gi=Ce.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:Ce.claudeOauthToken}:void 0,Ye=[],br=null,fo=null;try{let O="worktree";Ye=await cu(W.dir,g.projectId,g.projectRepos,O,We);let D=await lu(W.dir,g.projectId,g.contextRepo,O,We);fo=D,br=D?.workspacePath??null}catch(O){let D=O instanceof Error?O.message:String(O);console.warn(`[job] ${g.jobId} materialize failed: ${D}`),b||await P.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${D}`},startedAt:S,finishedAt:new Date().toISOString()}),W.dispose();return}let Fi=async()=>{if(!g.deliveries||g.deliveries.length===0)return[];let O=g.contextRepo?.cloneUrl;if(!O||!We)throw new Error(O?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let D=[];for(let Y of g.deliveries){let K=Ye.find(oe=>oe.name===Y.name);if(K){if(g.role==="implement"&&Y.baseSha&&Y.baseSha!==K.baseSha){let oe=await iu(K,Y.deliveryRef,Y.deliverySha,Y.baseSha,O,We);console.log(`[job] ${g.jobId} ${K.name}: base moved ${Y.baseSha.slice(0,10)} \u2192 ${K.baseSha.slice(0,10)} \u2014 re-applied delivery ${Y.deliverySha.slice(0,10)} (${oe.length} conflicted file(s))`),oe.length>0&&D.push(`- **${K.name}**:`,...oe.map($r=>` - \`${$r}\``));continue}await ou(K,Y.deliveryRef,Y.deliverySha,O,We),console.log(`[job] ${g.jobId} ${K.name}: checked out delivery ${Y.deliverySha.slice(0,10)} for ${g.role}`)}}return D},mo=[];if(g.role==="build"||g.role==="implement"||g.role==="code-review")try{mo=await Fi()}catch(O){let D=O instanceof Error?O.message:String(O);console.warn(`[job] ${g.jobId} delivery checkout failed: ${D}`),b||await P.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${D}`},startedAt:S,finishedAt:new Date().toISOString()}),W.dispose();return}let go=g.role==="resolve-conflict"?g.metadata?.taskBranchByRepo??{}:{},Hi="";if(g.role==="resolve-conflict"){if(!Ye.some(O=>go[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:S,finishedAt:new Date().toISOString()}),W.dispose();return}try{let O=[];for(let D of Ye){let Y=go[D.name];if(!Y)continue;let K=await yi(D,Y,We);console.log(`[job] ${g.jobId} ${D.name}: merged ${Y} into ${D.ref} \u2014 ${K.length} conflicted file(s)`),K.length>0?O.push(`- **${D.name}**:`,...K.map(oe=>` - \`${oe}\``)):O.push(`- **${D.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}Hi=`
|
|
676
676
|
|
|
677
677
|
## Conflicts to resolve
|
|
678
678
|
|
|
679
679
|
`+(O.length>0?O.join(`
|
|
680
680
|
`):"(no task branches to merge)")+`
|
|
681
|
-
`}catch(O){let D=O instanceof Error?O.message:String(O);console.warn(`[job] ${g.jobId} conflict merge failed: ${D}`),b||await
|
|
681
|
+
`}catch(O){let D=O instanceof Error?O.message:String(O);console.warn(`[job] ${g.jobId} conflict merge failed: ${D}`),b||await P.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${D}`},startedAt:S,finishedAt:new Date().toISOString()}),W.dispose();return}}let Kp=mo.length>0?`
|
|
682
682
|
|
|
683
683
|
## Base branch moved \u2014 conflicts to resolve
|
|
684
684
|
|
|
685
685
|
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:
|
|
686
686
|
|
|
687
|
-
`+
|
|
687
|
+
`+mo.join(`
|
|
688
688
|
`)+`
|
|
689
|
-
`:"",
|
|
689
|
+
`:"",Wp=R(B(g.prompt,Ye,br),br,g.taskId)+Hi+Kp,ho=[...Ye.map(O=>O.workspacePath),...br?[br]:[]];ho.length>0&&console.log(`[job] ${g.jobId} --add-dir: ${ho.join(", ")}`),wt&&(po=setInterval(()=>{let D=u;if(!D||D.readyState!==D.OPEN)return;let Y;try{Y=Hh(sr(W.dir,"drafts")).filter(K=>K.endsWith(".json")).sort()}catch{return}for(let K of Y){if(ce.has(K))continue;if(ce.size>=ms)break;let oe;try{let Pe=JSON.parse(ki(sr(W.dir,"drafts",K),"utf-8")),Ot=typeof Pe.localRef=="string"?Pe.localRef:"",kt=typeof Pe.title=="string"?Pe.title:"",V=typeof Pe.body=="string"?Pe.body:"";if(!Ot||!kt)continue;oe={localRef:Ot,title:kt,body:V,...Pe.isEpic===!0?{isEpic:!0}:{},...Array.isArray(Pe.links)?{links:Pe.links}:{}}}catch{continue}ce.add(K);let $r={type:"child_draft",jobId:g.jobId,projectId:g.projectId,draftId:wt,child:oe};try{D.send(JSON.stringify($r))}catch{}}},1500));try{let O={workspaceDir:W.dir,role:g.role,prompt:Wp,addDirs:ho,metadata:g.metadata??{},...g.model?{model:g.model}:{},...Gi?{env:Gi}:{},signal:_.abort.signal,onActivity:Nt},D=_.chatInbox?await s.run({...O,interactive:{inbox:_.chatInbox.iterable}}):await Wl(s,O,{jobId:g.jobId,policy:a,onBeforeRetry:async()=>{W.clean();for(let V of Ye)try{await eu(V);let ie=go[V.name];g.role==="resolve-conflict"&&ie&&await yi(V,ie,We)}catch(ie){let vr=ie instanceof Error?ie.message:String(ie);console.warn(`[job] ${g.jobId} worktree reset failed (${V.name}): ${vr}`)}try{await Fi()}catch(V){let ie=V instanceof Error?V.message:String(V);console.warn(`[job] ${g.jobId} delivery re-checkout failed: ${ie}`)}},aborted:()=>b||_.paused}),Y=[];if(qh.has(g.role)&&Ye.length>0){let V=g.metadata??{},ie=typeof V.commitMessage=="string"?V.commitMessage:`${g.taskId}: changes`,vr=g.contextRepo?.cloneUrl,Ki=x?.env;if(!vr||!Ki)throw new Error("delivery requested but "+(vr?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let Yp=g.taskId.includes(":")?g.taskId.slice(g.taskId.indexOf(":")+1):g.taskId;for(let qe of Ye){let xr=await tu(qe,ie);if(!xr){console.log(`[job] ${g.jobId} ${qe.name}: no changes \u2014 no delivery`);continue}let yo=`codepipe/deliveries/${Yp}/${g.jobId}/${qe.name}`;await ru(qe,xr,yo,vr,Ki),Y.push({name:qe.name,deliveryRef:yo,deliverySha:xr,baseSha:qe.baseSha}),console.log(`[job] ${g.jobId} ${qe.name}: delivered ${xr.slice(0,10)} \u2192 ${yo}`);let Wi=await nu(qe,xr);if(Wi.trim().length>0){let qp=sr("display",`${qe.name}.diff`),Yi=sr(W.dir,qp);Fh(Yh(Yi),{recursive:!0}),Kh(Yi,Wi)}}}if(g.role==="resolve-conflict"&&Y.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=pu(W.dir),console.log(`[job] ${g.jobId} build verdict: ok=${K.ok}`+(K.failedStep?` failedStep=${K.failedStep}`:"")));let oe;g.role==="code-review"&&(oe=fu(W.dir),console.log(`[job] ${g.jobId} review verdict: approved=${oe.approved}`));let $r=D.artifactPaths.length>0?D.artifactPaths:W.listFiles(),Pe=Array.from(new Set($r)),Ot;if(fo)try{let V=g.role==="index"?["adr/SOURCES.md"]:g.role==="backfill"?["adr"]:[],ie=await uu(fo,V);ie.length>0&&(Ot=ie,console.log(`[job] ${g.jobId} captured ${ie.length} knowledge file(s) for Context Repo`))}catch(V){let ie=V instanceof Error?V.message:String(V);console.warn(`[job] ${g.jobId} knowledge capture failed (non-fatal): ${ie}`)}let kt={jobId:g.jobId,status:"succeeded",artifacts:Pe.map(V=>({path:V,contentBase64:ki(`${W.dir}/${V}`).toString("base64")})),...Ot?{contextWrites:Ot}:{},...Y.length>0?{deliveries:Y}:{},log:Vh(D.log),startedAt:S,finishedAt:new Date().toISOString(),usage:D.usage,...D.rateLimit?{rateLimit:D.rateLimit}:{},...K?{build:K}:{},...oe?{review:oe}:{}};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(kt),console.log(`[job] ${g.jobId} done \u2014 uploaded ${kt.artifacts.length} artifact(s):`);for(let V of kt.artifacts){let ie=Buffer.from(V.contentBase64,"base64").length;console.log(` \xB7 ${V.path} (${ie} 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 D=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 (${D}) \u2014 skipping result upload`);else{let Y=Kl(O),K=O instanceof ft,oe=O instanceof Ze;console.warn(Y?`[job] ${g.jobId} failed: ${D} (Claude auth \u2014 token invalid/expired)`:K?`[job] ${g.jobId} failed: ${D} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:oe?`[job] ${g.jobId} failed: ${D} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${g.jobId} failed: ${D}`),await P.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:D},startedAt:S,finishedAt:new Date().toISOString(),...Y?{authError:!0}:{},...K?{buildInconclusive:!0}:{},...oe?{reviewInconclusive:!0}:{}})}}finally{W.dispose()}}finally{clearInterval(v),po&&clearInterval(po),Ie(),_.chatInbox?.close(),d.delete(g.jobId),C?.cleanup(),x?.cleanup()}}function k(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(Vt(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=gi(_);b&&console.log(`[job] ${P.jobId} cred bundle opened \u2014 git creds configured`);let C=Vl(_,P.contextRepo.cloneUrl),x={gitCreds:b,contextGitCreds:C};return _.claudeOauthToken&&(x.claudeOauthToken=_.claudeOauthToken),x}function I(P,g){return P.split(`
|
|
690
690
|
`).map(_=>g+_).join(`
|
|
691
|
-
`)}function B(
|
|
692
|
-
[${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),w.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 mu(t={profile:void 0}){let e=ve(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Gn(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=pe(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 $y}from"node:child_process";import{existsSync as cr,mkdirSync as Du,readFileSync as Uu,readdirSync as vy,writeFileSync as Lu}from"node:fs";import{join as Pt,resolve as Bu}from"node:path";import{setTimeout as vi}from"node:timers/promises";import{cancel as xy,confirm as lr,intro as Mu,isCancel as oo,log as T,outro as xi,password as ur,select as Ze,spinner as Gu,text as te}from"@clack/prompts";import{simpleGit as so}from"simple-git";async function sr(t,e,r){return e.host==="github"?Yh(t,e,r):e.host==="gitlab"?Zh(t,e,r):ty(t,e,r)}async function gu(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 gt(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await hu(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 mt(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await yu(e.gitlabToken,t):o}}return e.bitbucket?(await ir(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await wu(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 hu(t,e){let r=!1;try{r=(await gt(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 yu(t,e){let r=!1;try{r=(await mt(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 wu(t,e){let r=!1;try{r=(await ir(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 Wh="https://api.github.com";async function gt(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(Wh+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 Yh(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 qh(n,e,r),i=await Jh(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=Wt(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await zh(n,o.owner,o.name,a.path,i)||await Xh(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 qh(t,e,r){let n=await gt(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 hu(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Vh(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 gt(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 Vh(t,e){let{status:r,data:n}=await gt(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function Jh(t,e,r){let{data:n}=await gt(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function zh(t,e,r,n,o){let{status:i,data:s}=await gt(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function Xh(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 gt(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}var Qh="https://gitlab.com/api/v4";async function mt(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(Qh+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 Zh(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 mt(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 yu(n,e)} (attach joins an existing Context Repo and never creates one)`);let d=await mt(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 mt(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 mt(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=Wt(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let d=1;;d++){let m=(await mt(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 mt(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 ey="https://api.bitbucket.org/2.0";async function ir(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(ey+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 ty(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 ir(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 wu(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 ir(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=Wt(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let d of c)(await ir(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 ir(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 ry={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function Re(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=ry[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 ny}from"node:crypto";import{existsSync as ku,mkdirSync as oy,readFileSync as bu,readdirSync as iy,rmSync as no,writeFileSync as sy}from"node:fs";import{homedir as ay}from"node:os";import{dirname as cy,join as ki}from"node:path";var ly=24*60*60*1e3;function $u(){return ki(ay(),".codepipe","init-drafts")}function bi(t){let e=ny("sha256").update(t).digest("hex").slice(0,16);return ki($u(),`${e}.json`)}function vu(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=ly)}function xu(t){let e=bi(t);if(!ku(e))return null;try{let r=JSON.parse(bu(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:vu(r.savedAt)?(no(e,{force:!0}),null):r}catch{return null}}function $i(t){no(bi(t),{force:!0})}function Su(){let t=$u();if(ku(t))for(let e of iy(t)){let r=ki(t,e);try{let n=JSON.parse(bu(r,"utf-8"));vu(n.savedAt)&&no(r,{force:!0})}catch{no(r,{force:!0})}}}var ar=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(){$i(this.cwd)}persist(){let e=bi(this.cwd);oy(cy(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};sy(e,JSON.stringify(r,null,2)+`
|
|
693
|
-
`,{mode:384})}};function
|
|
694
|
-
`).map(n=>n.trim()).filter(Boolean);return Cu(r)}catch{return!1}}async function wy(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)?Cu(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function Eu(t,e){for(let r of t)try{let n=e.localRoot!=null?py(e.localRoot,r.mountAs??r.name):null;if(n&&uy(n)?await yy(n):await wy(r,e.tokens))return!0}catch{}return!1}import{existsSync as Pu}from"node:fs";import{join as ju}from"node:path";import{simpleGit as Au}from"simple-git";var ky={info:t=>console.log(t),warn:t=>console.warn(t)};async function Xr(t,e,r={}){let n=r.log??ky,o=[];for(let i of e){let s=ju(t,i.mountAs),a=fs(i);if(!Pu(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 Au().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(!Pu(ju(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=Au(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!by(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 by(t,e){return _u(t)===_u(e)}function _u(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function Nu(t={}){let e=$e();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 Xr(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 Ou=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function Z(t){xy(t),process.exit(1)}function ge(t){return oo(t)&&Z("aborted"),t}function J(t){return oo(t)&&Z("aborted"),typeof t=="string"?t:""}async function Fu(t={}){Mu("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Su();let r=xu(e),n,o=!1;r&&Object.keys(r.answers).length>0?ge(await lr({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 ar(e,r),o=!0):($i(e),n=new ar(e)):n=new ar(e);let i=t.force===!0?null:await Ri(e),s=await n.ask("target",async()=>ge(await Ze({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||Ku(e,t.force===!0));let c=await n.ask("hubUrl",async()=>J(await te({message:"HUB URL",placeholder:_e,initialValue:F("HUB_URL")??_e,validate:A=>A.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>pr()),{cliToken:p,accountEmail:d}=await n.ask("bootstrap",()=>dr(c,l)),u=null;s==="farm"&&(u=await Sy(c,p));let m=a?Ty(a.parsed.repoName):"",f=await n.ask("projectId",async()=>J(await te({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:A=>vt.test(A.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),y=await n.ask("projectName",async()=>J(await te({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()),w=await n.ask("automationLevel",async()=>ge(await Ze({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 Ze({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",k=null,I,B=!0;h?I=await n.ask("trackerPrefix",async()=>J(await te({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:xr,initialValue:xr,validate:A=>dn.test(A.trim())?void 0:"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)"})).trim()):(k=await n.ask("youtrack",()=>Xu()),I=await n.ask("youtrackProjectKey",async()=>J(await te({message:"YouTrack project key",placeholder:"DEV",validate:A=>A.trim().length>0?void 0:"required"})).trim()),B=await n.ask("youtrackWrites",async()=>ge(await lr({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",()=>Py(R,l,a,{onCred:j,initial:n.get("reposPartial")??[],onProgress:A=>n.set("reposPartial",A)}));n.delete("reposPartial");let E=await jy(await n.ask("contextRepo",()=>Vu(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 te({message:"your YouTrack login (the assignee value)",...k?.login?{initialValue:k.login}:{},validate:A=>A.trim().length>0?void 0:"required"})).trim()));let C=await n.ask("claudeToken",()=>Ly(s==="farm")),x={projectId:f,name:y,automationLevel:w,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 sr(x,g,{...Ju(R),youtrackWrites:B,...k?{trackerUrl:k.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 U;try{U=await ut(c,p,x)}catch(A){if(A instanceof N&&A.status===409){T.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{U=await q(c,p,f)}catch(we){throw we instanceof N&&Z(`HUB \u2192 ${we.status} ${we.message}`),we}}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=U.contextRepo??P;T.success(`project ${U.projectId} ready (${U.provisioningStatus})`);let S=await Dy(v),G=k?{url:k.url,token:k.token}:void 0;if(s==="farm"){let A=u,we={...R,...S?{contextWrite:S}:{},...C?{claude:{oauthToken:C}}:{},...G?{youtrack:G}:{}},et=R.github?.token;if(v.host==="github"&&et)try{let ce=fl(`devpipe-${f}`);await ml(v,et,ce.publicKey,`devpipe-${f}`),we.contextSsh={privateKey:ce.privateKey},T.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(ce){T.warn(`could not set up Context Repo SSH deploy key (${ce instanceof Error?ce.message:String(ce)}); the farm will fall back to the token path.`)}let He={projectId:f,config:{hubUrl:c,cliToken:p,projectId:f},secrets:we,contextRepo:v,projectConfig:Me(x,B,k?.url,b||void 0)},po=ze(A.farm.publicKey,JSON.stringify(He));T.step(`handing project ${f} to farm ${A.farm.name}\u2026`);let wt;try{wt=await Fn(c,p,A.farm.farmId,{projectId:f,sealedBundle:po})}catch(ce){throw ce instanceof N&&Z(ce.status===409?`farm ${A.farm.name} is offline \u2014 start it and re-run.`:ce.status===504?`farm ${A.farm.name} did not respond in time.`:`HUB \u2192 ${ce.status} ${ce.message}`),ce}wt.ok||Z(`farm rejected provisioning: ${wt.error??"unknown error"}`),await Si(c,p,f,v,et,U.repos,null,R),n.clear(),xi(`done. project ${f} is now hosted on farm ${A.farm.name} (daemon ${wt.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}zu(R),await Wu(e,v.cloneUrl,v.branch),qu(e),a&&await Cy(e);{let A=Pt(e,Ue);Ht(A);let we=Me(x,B,k?.url,b||void 0),et=Cr(A,we);et.length>0&&T.success(`local project config \u2192 .codepipe/{${et.join(", ")}}`),Rt(f,we,{info:He=>T.message(He),warn:He=>T.warn(He)})}await Yu(e,U.repos);let Q={hubUrl:c,cliToken:p,projectId:f,...R,...S?{contextWrite:S}:{},...C?{claude:{oauthToken:C}}:{},...G?{youtrack:G}:{}};z(Q),Ve({hubUrl:c,cliToken:p,projectId:f,accountEmail:d},f),T.success(`secrets \u2192 ${Le(f)}`),await Si(c,p,f,v,R.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,U.repos,e,R),n.clear(),xi("done. next: `codepipe up` from this folder \u2014 starts the daemon and an agent worker. (`codepipe` opens the interactive REPL.)")}async function Si(t,e,r,n,o,i=[],s=null,a={}){let c=await Iu(n,o);if(!c){let d=!1;try{d=await Eu(i,{localRoot:s,tokens:a})}catch{d=!1}if(d){let u=Tu(),m=await Ze({message:u.message,options:u.options,initialValue:u.initialValue});if(!oo(m)&&m===u.proceedValue)try{let{jobId:f}=await Kr(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=Ru(c),p=await Ze({message:l.message,options:l.options,initialValue:l.initialValue});if(!(oo(p)||p!==l.proceedValue))try{let{jobId:d}=await Kr(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 Sy(t,e){let r;try{r=await jc(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 Ze({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=Mn(i.farmId,i.publicKey)}catch(c){Z(c instanceof Error?c.message:String(c))}return ge(await lr({message:`confirm farm ${i.name} cred-channel fingerprint:
|
|
691
|
+
`)}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 R(P,g,_){let b=P,C=_.includes("::")?"":_.split(":",2)[1]??"",x=E=>{if(!g||!C)return"";try{return ki(sr(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(`
|
|
692
|
+
[${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 M=[$("implementation")];e.planningLane!==!1?M.push($("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(M)}async function ku(t={profile:void 0}){let e=ve(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Gn(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=de(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 Ty}from"node:child_process";import{existsSync as ur,mkdirSync as Gu,readFileSync as Fu,readdirSync as Iy,writeFileSync as Hu}from"node:fs";import{join as Et,resolve as Ku}from"node:path";import{setTimeout as xi}from"node:timers/promises";import{cancel as Cy,confirm as pr,intro as Wu,isCancel as oo,log as T,outro as Si,password as dr,select as et,spinner as Ti,text as te}from"@clack/prompts";import{simpleGit as so}from"simple-git";async function cr(t,e,r){return e.host==="github"?Xh(t,e,r):e.host==="gitlab"?oy(t,e,r):sy(t,e,r)}async function bu(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 gt(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await $u(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 mt(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await vu(e.gitlabToken,t):o}}return e.bitbucket?(await ar(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await xu(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 $u(t,e){let r=!1;try{r=(await gt(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 vu(t,e){let r=!1;try{r=(await mt(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 xu(t,e){let r=!1;try{r=(await ar(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 zh="https://api.github.com";async function gt(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(zh+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 Xh(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 Qh(n,e,r),i=await ey(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=qt(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await ty(n,o.owner,o.name,a.path,i)||await ry(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 Qh(t,e,r){let n=await gt(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 $u(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Zh(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 gt(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 Zh(t,e){let{status:r,data:n}=await gt(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function ey(t,e,r){let{data:n}=await gt(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function ty(t,e,r,n,o){let{status:i,data:s}=await gt(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function ry(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 gt(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}var ny="https://gitlab.com/api/v4";async function mt(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(ny+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 oy(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 mt(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 vu(n,e)} (attach joins an existing Context Repo and never creates one)`);let d=await mt(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 mt(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 mt(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=qt(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let d=1;;d++){let m=(await mt(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 mt(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 iy="https://api.bitbucket.org/2.0";async function ar(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(iy+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 sy(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 ar(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 xu(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 ar(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=qt(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let d of c)(await ar(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 ar(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 ay={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function Re(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=ay[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 cy}from"node:crypto";import{existsSync as Su,mkdirSync as ly,readFileSync as Ru,readdirSync as uy,rmSync as no,writeFileSync as py}from"node:fs";import{homedir as dy}from"node:os";import{dirname as fy,join as bi}from"node:path";var my=24*60*60*1e3;function Tu(){return bi(dy(),".codepipe","init-drafts")}function $i(t){let e=cy("sha256").update(t).digest("hex").slice(0,16);return bi(Tu(),`${e}.json`)}function Iu(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=my)}function Cu(t){let e=$i(t);if(!Su(e))return null;try{let r=JSON.parse(Ru(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Iu(r.savedAt)?(no(e,{force:!0}),null):r}catch{return null}}function vi(t){no($i(t),{force:!0})}function Pu(){let t=Tu();if(Su(t))for(let e of uy(t)){let r=bi(t,e);try{let n=JSON.parse(Ru(r,"utf-8"));Iu(n.savedAt)&&no(r,{force:!0})}catch{no(r,{force:!0})}}}var lr=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(){vi(this.cwd)}persist(){let e=$i(this.cwd);ly(fy(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};py(e,JSON.stringify(r,null,2)+`
|
|
693
|
+
`,{mode:384})}};function Eu(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 ju(){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 Au(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 gy}from"node:fs";import{join as hy}from"node:path";import{simpleGit as yy}from"simple-git";var wy=3,ky=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,by=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"]);function $y(t){let e=t.split("/");return e[e.length-1]??t}function _u(t){if(t.filter(r=>!ky.test($y(r))).length>wy)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(by.has(n))return!0}return!1}async function vy(t){try{let r=(await yy(t).raw(["ls-files"])).split(`
|
|
694
|
+
`).map(n=>n.trim()).filter(Boolean);return _u(r)}catch{return!1}}async function xy(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 Nu(t,e){for(let r of t)try{let n=e.localRoot!=null?hy(e.localRoot,r.mountAs??r.name):null;if(n&&gy(n)?await vy(n):await xy(r,e.tokens))return!0}catch{}return!1}import{existsSync as Ou}from"node:fs";import{join as Du}from"node:path";import{simpleGit as Uu}from"simple-git";var Sy={info:t=>console.log(t),warn:t=>console.warn(t)};async function Qr(t,e,r={}){let n=r.log??Sy,o=[];for(let i of e){let s=Du(t,i.mountAs),a=ws(i);if(!Ou(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 Uu().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(!Ou(Du(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=Uu(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!Ry(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 Ry(t,e){return Lu(t)===Lu(e)}function Lu(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function Bu(t={}){let e=$e();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 Mu=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function Q(t){Cy(t),process.exit(1)}function he(t){return oo(t)&&Q("aborted"),t}function J(t){return oo(t)&&Q("aborted"),typeof t=="string"?t:""}async function Yu(t={}){Wu("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Pu();let r=Cu(e),n,o=!1;r&&Object.keys(r.answers).length>0?he(await pr({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 lr(e,r),o=!0):(vi(e),n=new lr(e)):n=new lr(e);let i=t.force===!0?null:await Ii(e),s=await n.ask("target",async()=>he(await et({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||Vu(e,t.force===!0));let c=await n.ask("hubUrl",async()=>J(await te({message:"HUB URL",placeholder:Oe,initialValue:F("HUB_URL")??Oe,validate:j=>j.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>fr()),{cliToken:p,accountEmail:d}=await n.ask("bootstrap",()=>mr(c,l)),u=null;s==="farm"&&(u=await Py(c,p));let m=a?jy(a.parsed.repoName):"",f=await n.ask("projectId",async()=>J(await te({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:j=>vt.test(j.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),y=await n.ask("projectName",async()=>J(await te({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:j=>j.trim().length>0?void 0:"required"})).trim()),w=await n.ask("automationLevel",async()=>he(await et({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()=>he(await et({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",k=null,I,B=!0;if(h){let j,ue=Ti();ue.start("checking task-key prefixes on your account\u2026");try{j=await Mc(c,p,{excludeProjectId:f}),ue.stop("prefixes checked")}catch{ue.stop("could not reach the HUB",1),Q("Could not verify the task-key prefix against your account \u2014 the HUB is unreachable right now. Prefix uniqueness is required, so init can't continue. Check your connection and re-run `codepipe init` later.")}let Te=fs(ds(y),j);I=await n.ask("trackerPrefix",async()=>J(await te({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:Te,initialValue:Te,validate:Ie=>{let Nt=Ie.trim();if(!Ut.test(Nt))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(j.has(Nt.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else k=await n.ask("youtrack",()=>tp()),I=await n.ask("youtrackProjectKey",async()=>J(await te({message:"YouTrack project key",placeholder:"DEV",validate:j=>j.trim().length>0?void 0:"required"})).trim()),B=await n.ask("youtrackWrites",async()=>he(await pr({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let R=n.get("tokens")??{},A=()=>n.set("tokens",R),M=await n.ask("repos",()=>Oy(R,l,a,{onCred:A,initial:n.get("reposPartial")??[],onProgress:j=>n.set("reposPartial",j)}));n.delete("reposPartial");let P=await Dy(await n.ask("contextRepo",()=>Qu(f,M,R,l)),f,M,R,l,A,j=>n.set("contextRepo",j)),{spec:g,mode:_}=P,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 te({message:"your YouTrack login (the assignee value)",...k?.login?{initialValue:k.login}:{},validate:j=>j.trim().length>0?void 0:"required"})).trim()));let C=await n.ask("claudeToken",()=>Hy(s==="farm")),x={projectId:f,name:y,automationLevel:w,repos:M,trackerProvider:$,youtrackProjectKey:I};T.step(`${_==="attach"?"attaching to":"provisioning"} Context Repo ${g.owner}/${g.name} (${g.host})\u2026`);let E;try{E=await cr(x,g,{...Zu(R),youtrackWrites:B,...k?{trackerUrl:k.url}:{},mode:_,log:{info:j=>T.message(j),warn:j=>T.warn(j)}})}catch(j){Q(`Context Repo provisioning failed: ${j instanceof Error?j.message:String(j)}`)}x.contextRepo=E,T.success(`Context Repo ready: ${E.owner}/${E.name}@${E.branch}`),T.step(`registering project on ${c}\u2026`);let U;try{U=await ut(c,p,x)}catch(j){if(j instanceof N&&j.status===409){T.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{U=await q(c,p,f)}catch(ue){throw ue instanceof N&&Q(`HUB \u2192 ${ue.status} ${ue.message}`),ue}}else if(j instanceof N&&j.status===401)n.delete("cliToken"),Q("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(j instanceof N)Q(`HUB \u2192 ${j.status} ${j.message}`);else throw j}let v=U.contextRepo??E;T.success(`project ${U.projectId} ready (${U.provisioningStatus})`);let S=await Gy(v),G=k?{url:k.url,token:k.token}:void 0;if(s==="farm"){let j=u,ue={...R,...S?{contextWrite:S}:{},...C?{claude:{oauthToken:C}}:{},...G?{youtrack:G}:{}},Te=R.github?.token;if(v.host==="github"&&Te)try{let ce=wl(`devpipe-${f}`);await kl(v,Te,ce.publicKey,`devpipe-${f}`),ue.contextSsh={privateKey:ce.privateKey},T.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(ce){T.warn(`could not set up Context Repo SSH deploy key (${ce instanceof Error?ce.message:String(ce)}); the farm will fall back to the token path.`)}let Ie={projectId:f,config:{hubUrl:c,cliToken:p,projectId:f},secrets:ue,contextRepo:v,projectConfig:Fe(x,B,k?.url,b||void 0)},Nt=Xe(j.farm.publicKey,JSON.stringify(Ie));T.step(`handing project ${f} to farm ${j.farm.name}\u2026`);let wt;try{wt=await Fn(c,p,j.farm.farmId,{projectId:f,sealedBundle:Nt})}catch(ce){throw ce instanceof N&&Q(ce.status===409?`farm ${j.farm.name} is offline \u2014 start it and re-run.`:ce.status===504?`farm ${j.farm.name} did not respond in time.`:`HUB \u2192 ${ce.status} ${ce.message}`),ce}wt.ok||Q(`farm rejected provisioning: ${wt.error??"unknown error"}`),await Ri(c,p,f,v,Te,U.repos,null,R),n.clear(),Si(`done. project ${f} is now hosted on farm ${j.farm.name} (daemon ${wt.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}ep(R),await Ju(e,v.cloneUrl,v.branch),Xu(e),a&&await _y(e);{let j=Et(e,Be);Wt(j);let ue=Fe(x,B,k?.url,b||void 0),Te=Pr(j,ue);Te.length>0&&T.success(`local project config \u2192 .codepipe/{${Te.join(", ")}}`),Rt(f,ue,{info:Ie=>T.message(Ie),warn:Ie=>T.warn(Ie)})}await zu(e,U.repos);let Z={hubUrl:c,cliToken:p,projectId:f,...R,...S?{contextWrite:S}:{},...C?{claude:{oauthToken:C}}:{},...G?{youtrack:G}:{}};z(Z),Je({hubUrl:c,cliToken:p,projectId:f,accountEmail:d},f),T.success(`secrets \u2192 ${Me(f)}`),await Ri(c,p,f,v,R.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,U.repos,e,R),n.clear(),Si("done. next: `codepipe up` from this folder \u2014 starts the daemon and an agent worker. (`codepipe` opens the interactive REPL.)")}async function Ri(t,e,r,n,o,i=[],s=null,a={}){let c=await Au(n,o);if(!c){let d=!1;try{d=await Nu(i,{localRoot:s,tokens:a})}catch{d=!1}if(d){let u=ju(),m=await et({message:u.message,options:u.options,initialValue:u.initialValue});if(!oo(m)&&m===u.proceedValue)try{let{jobId:f}=await Wr(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=Eu(c),p=await et({message:l.message,options:l.options,initialValue:l.initialValue});if(!(oo(p)||p!==l.proceedValue))try{let{jobId:d}=await Wr(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 Py(t,e){let r;try{r=await Dc(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=he(await et({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=Mn(i.farmId,i.publicKey)}catch(c){Q(c instanceof Error?c.message:String(c))}return he(await pr({message:`confirm farm ${i.name} cred-channel fingerprint:
|
|
695
695
|
${s}
|
|
696
|
-
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||
|
|
696
|
+
(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 qu(t){Wu(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();Vu(e,t.force===!0);let r=J(await te({message:"HUB URL",initialValue:F("HUB_URL")??Oe,validate:u=>u.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await fr(),{cliToken:o,accountEmail:i}=await mr(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&&Q(`HUB \u2192 ${u.status} ${u.message}`),u}s.contextRepo||Q(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await tp(),l={},p=new Set(s.repos.map(u=>u.host));p.add(s.contextRepo.host);for(let u of p)await io(u,l,u===s.contextRepo.host?s.contextRepo.owner:s.repos.find(m=>m.host===u)?.owner,n);ep(l),await Ju(e,s.contextRepo.cloneUrl,s.contextRepo.branch),Xu(e);{let u=Et(e,Be);Wt(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=Fe(m,!0,c?.url),y=Pr(u,f);y.length>0&&T.success(`local project config \u2192 .codepipe/{${y.join(", ")}} (defaults \u2014 review and adjust)`),Rt(t.projectId,f,{info:w=>T.message(w),warn:w=>T.warn(w)})}await zu(e,s.repos);let d={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};z(d),Je({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),T.success(`secrets \u2192 ${Me(t.projectId)}`),await Ri(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),Si("done.")}function Vu(t,e){if(!ur(t)){Gu(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=Iy(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 Ii(t){if(!ur(Et(t,".git")))return null;try{let r=(await so(t).remote(["get-url","origin"])||"").toString().trim(),n=r?Re(r):null;return n?{parsed:n,defaultBranch:await Ey(t)}:null}catch{return null}}async function Ey(t){let e=so(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 jy(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return vt.test(e)?e:""}function Ay(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function _y(t){let e=Et(t,".gitignore"),r=ur(e)?Fu(e,"utf-8"):"";if(Ay(r))return;if(!he(await pr({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(`
|
|
697
697
|
`)?"":`
|
|
698
|
-
`;
|
|
698
|
+
`;Hu(e,r+o+`
|
|
699
699
|
# codepipe workspace (added by \`codepipe init\`)
|
|
700
700
|
.codepipe/
|
|
701
|
-
`),T.success(`.codepipe/ added to ${
|
|
701
|
+
`),T.success(`.codepipe/ added to ${Ku(e)}`)}function Ny(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=Ty(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}async function fr(){let t="";try{t=(await so().raw(["config","--global","user.email"])||"").trim()}catch{}return J(await te({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function mr(t,e){T.step(`connecting account ${e}`);let r;try{r=await Gc(t,e)}catch(s){throw s instanceof Kr&&Q(`${e} is not authorized on this HUB yet.
|
|
702
702
|
Sign up at ${t} (registration form on the login screen),
|
|
703
703
|
wait for the operator to approve it by email, then re-run
|
|
704
|
-
\`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&&(
|
|
704
|
+
\`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&&(Ny(r.authorizeUrl),T.message(`a browser tab was opened to confirm this CLI:
|
|
705
705
|
${r.authorizeUrl}
|
|
706
706
|
`+(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
|
|
707
|
-
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
|
|
708
|
-
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await
|
|
707
|
+
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 Fc(t,r.requestId)}catch(a){T.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await xi(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"&&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,T.message(`email confirmed. waiting for the operator to approve your account\u2026
|
|
708
|
+
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await xi(5e3);continue}await xi(2e3)}Q("bootstrap timed out")}async function Ju(t,e,r){let n=Et(t,Be);if(ur(Et(n,".git"))){T.message(`${n} already cloned \u2014 skipping`);return}ur(n)&&Q(`${n} exists but is not a git repo \u2014 remove it and re-run`),Gu(n,{recursive:!0}),T.step(`cloning Context Repo \u2192 ${n}`);try{await so().clone(e,n,["--branch",r]),T.success(`cloned ${e}`)}catch(o){Q(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function zu(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 Xu(t){let e=Et(t,Be,".gitignore"),r="";if(ur(e)&&(r=Fu(e,"utf-8")),Mu.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
|
|
709
709
|
`)||r.length===0?"":`
|
|
710
|
-
`,i=
|
|
710
|
+
`,i=Mu.join(`
|
|
711
711
|
`)+`
|
|
712
|
-
`;
|
|
713
|
-
`:"")+i),T.message(`appended runtime entries to ${
|
|
712
|
+
`;Hu(e,r+o+(r?`
|
|
713
|
+
`:"")+i),T.message(`appended runtime entries to ${Ku(e)}`)}async function Oy(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 io(s.host,t,s.owner,e),i?.();let c=J(await te({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 te({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(;he(await pr({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=J(await te({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:m=>!m||!m.trim()||Re(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=Re(a);T.message(`${c.host}: ${c.owner}/${c.repoName}`),await io(c.host,t,c.owner,e),i?.();let l=J(await te({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 te({message:"default branch (optional)",placeholder:"main"})).trim(),d=J(await te({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 Qu(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=he(await et({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 te({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:Ve(t),validate:p=>{let d=(p??"").trim();if(!d)return"required";if(!Re(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=Re(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await Uy(),l=J(await te({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:d=>d.trim().length>0?void 0:"required"})).trim(),p=J(await te({message:"Context Repo name",placeholder:Ve(t),initialValue:Ve(t),validate:d=>d.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:p}}return{spec:a,mode:o}}function Zu(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??Gt()}}async function Dy(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await io(c.host,n,c.owner,o),i?.();let p=Ti();p.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let d=await bu(c,Zu(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=he(await et({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 Qu(e,r,n,o),s(a)}}async function Uy(){return he(await et({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Zr(t,e){let r=Ti();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 ep(t){Br(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Mr(t.gitlab?.token??process.env.GITLAB_TOKEN),Gr(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function io(t,e,r,n){if(!e[t])if(t==="github"){let o=await Ly(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 By(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 My();o?e.gitlab=o:T.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function Ly(t){for(;;){let e=J(await dr({message:`GitHub PAT \u2014 blank to skip
|
|
714
714
|
classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
|
|
715
715
|
fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
|
|
716
716
|
if org: approve token in org Settings \u2192 Personal access tokens.
|
|
717
717
|
(Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo;
|
|
718
|
-
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await
|
|
718
|
+
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await Zr("GitHub",()=>ot(e,t?{owner:t}:void 0)))return{token:e};T.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function By(t,e){for(T.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
|
|
719
719
|
How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
|
|
720
720
|
'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes: read:account,
|
|
721
721
|
read:repository:bitbucket + write:repository:bitbucket, write:pullrequest:bitbucket
|
|
722
722
|
(+ admin:repository:bitbucket if this token will provision the Context Repo).
|
|
723
|
-
The token is shown ONCE \u2014 copy it right away.`);;){let r=J(await te({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
|
|
724
|
-
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await
|
|
723
|
+
The token is shown ONCE \u2014 copy it right away.`);;){let r=J(await te({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 dr({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 Zr("Bitbucket",()=>it(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 My(){for(;;){let t=J(await dr({message:`GitLab PAT \u2014 blank to skip
|
|
724
|
+
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Zr("GitLab",()=>st(t))){let e=await ca(t);return e&&T.warn(e),{token:t}}T.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function Gy(t){if(he(await pr({message:`Issue a separate context-write token (scoped to the Context Repo only)?
|
|
725
725
|
Without it the SANDBOX pushes delivery commits with the project ${t.host}
|
|
726
726
|
credential. A scoped token hardens setups where the SANDBOX runs outside
|
|
727
727
|
your trusted network.`,initialValue:!1})))for(t.host==="github"?T.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
|
|
728
728
|
permissions Contents: Read and write + Workflows: Read and write (Workflows is
|
|
729
729
|
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
|
|
730
|
-
(${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
|
|
731
|
-
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=J(await ur({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 Xu(){for(;;){let t=J(await te({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 ur({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Qr("YouTrack",()=>lt({baseUrl:t,token:e}))){let r=await Ka({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}T.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as By}from"node:fs";function ae(t){throw new Error(t)}function le(t,e){return(typeof t!="string"||t.trim().length===0)&&ae(`config: '${e}' must be a non-empty string`),t.trim()}function Zr(t,e){if(t==null)return;typeof t!="string"&&ae(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function My(t){(!t||typeof t!="object")&&ae("config: expected a JSON object");let e=t,r=le(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||ae("config: 'hubUrl' must start with http(s)://");let n=le(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&ae("config: 'project' is required");let i=o,s=le(i.id,"project.id");vt.test(s)||ae("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=le(i.name,"project.name"),c=le(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&ae("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||ae("config: 'project.repos' must be an array");let p=l.map((h,k)=>{(!h||typeof h!="object")&&ae(`config: project.repos[${k}] must be an object`);let I=h,B=le(I.host,`project.repos[${k}].host`);B!=="github"&&B!=="bitbucket"&&B!=="gitlab"&&ae(`config: project.repos[${k}].host must be 'github', 'bitbucket' or 'gitlab'`);let R={name:le(I.name,`project.repos[${k}].name`),host:B,owner:le(I.owner,`project.repos[${k}].owner`),repoName:le(I.repoName,`project.repos[${k}].repoName`)},j=Zr(I.defaultBranch,`project.repos[${k}].defaultBranch`);j&&(R.defaultBranch=j);let M=Zr(I.mountAs,`project.repos[${k}].mountAs`);return M&&(R.mountAs=M),R}),d=i.contextRepo;(!d||typeof d!="object")&&ae("config: 'project.contextRepo' is required");let u=d,m=Zr(u.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&ae("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:m,owner:le(u.owner,"project.contextRepo.owner"),name:Zr(u.name,"project.contextRepo.name")??qe(s)},y={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:p,contextRepo:f}},w=Zr(i.youtrackProjectKey,"project.youtrackProjectKey");w&&(y.project.youtrackProjectKey=w),i.index!==void 0&&(typeof i.index!="boolean"&&ae("config: 'project.index' must be a boolean"),y.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&ae("config: 'project.youtrackWrites' must be a boolean"),y.project.youtrackWrites=i.youtrackWrites);let $=e.secrets;if($!==void 0){(typeof $!="object"||$===null)&&ae("config: 'secrets' must be an object");let h=$,k={};if(h.github){let I=h.github;k.github={token:le(I.token,"secrets.github.token")}}if(h.bitbucket){let I=h.bitbucket;k.bitbucket={email:le(I.email,"secrets.bitbucket.email"),apiToken:le(I.apiToken,"secrets.bitbucket.apiToken")}}if(h.gitlab){let I=h.gitlab;k.gitlab={token:le(I.token,"secrets.gitlab.token")}}if(h.youtrack){let I=h.youtrack;k.youtrack={url:le(I.url,"secrets.youtrack.url").replace(/\/$/,""),token:le(I.token,"secrets.youtrack.token")}}if(h.contextWrite){let I=h.contextWrite;k.contextWrite={token:le(I.token,"secrets.contextWrite.token")}}y.secrets=k}return y}async function Gy(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Fy(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await ot(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 it(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${n}`)}if(e.gitlab){let r=await st(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await lt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Qu(t){let e=!t.configPath||t.configPath==="-"?await Gy():By(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(u){ae(`config: invalid JSON \u2014 ${u instanceof Error?u.message:String(u)}`)}let n=My(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 Fy(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 sr(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??Bt(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:u=>console.log(` ${u}`),warn:u=>console.warn(` ${u}`)}})}catch(u){ae(`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 ut(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)ae(`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),Ve({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Le(s.id)}`),Rt(s.id,Me(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 Kr(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 Zu,intro as ep,isCancel as tp,log as Ti,outro as Hy,password as rp}from"@clack/prompts";async function Ky(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function np(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Ky(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){ep("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Ti.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await rp({message:"Claude OAuth token"});tp(i)&&(Zu("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),As({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${bn()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=ve(t.profile);if(!e){ep(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Ti.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await rp({message:"Claude OAuth token"});tp(i)&&(Zu("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}.`):(Ti.success("Claude OAuth token saved."),Hy("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as Wy,confirm as Yy,intro as qy,isCancel as op,log as de,outro as Vy,select as ip,text as ht}from"@clack/prompts";function sp(t){Wy(t),process.exit(1)}function fr(t){return op(t)&&sp("aborted"),t}function en(t){return op(t)&&sp("aborted"),typeof t=="string"?t:""}async function Jy(t,e){let r=fr(await ip({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=en(await ht({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=en(await ht({message:"Context Repo name",placeholder:qe(t),initialValue:qe(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function ap(t={profile:void 0}){let e=ve(t.profile);qy(`codepipe project add \u2192 ${e.hubUrl}`);let r=fr(await ht({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:u=>vt.test(u.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=fr(await ht({message:"project name (human-readable)",placeholder:"CodePartner",validate:u=>u.trim().length>0?void 0:"required"})).trim(),o=fr(await ip({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=fr(await ht({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=fr(await Yy({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let u=en(await ht({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()||Re($)?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=Re(u);de.message(`${m.host}: ${m.owner}/${m.repoName}`);let f=en(await ht({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:$=>$.trim().length>0?void 0:"required"})).trim(),y=en(await ht({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 Jy(r,a),p=L(e.projectId);de.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let d;try{d=await sr(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??Bt(),youtrackWrites:s,trackerUrl:p?.youtrack?.url,log:{info:u=>de.message(u),warn:u=>de.warn(u)}})}catch(u){de.error(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}c.contextRepo=d,de.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let u=await ut(e.hubUrl,e.cliToken,c);de.success(`project "${u.projectId}" \u2014 ${u.provisioningStatus}`),Rt(r,Me(c,s,p?.youtrack?.url),{info:m=>de.message(m),warn:m=>de.warn(m)}),u.contextRepo&&(de.message(` context repo: ${u.contextRepo.owner}/${u.contextRepo.name} (${u.contextRepo.cloneUrl})`),de.message(` branch: ${u.contextRepo.branch}`)),u.provisioningError&&de.error(` error: ${u.provisioningError}`),Vy("done")}catch(u){u instanceof N?(de.error(`HUB \u2192 ${u.status} ${u.message}`),u.payload&&typeof u.payload=="object"&&de.message(JSON.stringify(u.payload,null,2))):de.error(u instanceof Error?u.message:String(u)),process.exit(1)}}import{existsSync as zy,rmSync as Xy}from"node:fs";import{confirm as Qy,intro as Zy,isCancel as ew,log as yt,outro as tw,spinner as rw}from"@clack/prompts";function Fe(t){yt.error(t),process.exit(1)}var cp=t=>t.trim().replace(/\/+$/,"");async function lp(t){Zy("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??$e()?.spec.projectId??void 0;e||Fe("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=Ce(e);r||Fe(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=cp(r.hubUrl),o=r.projectId,i=cp(t.hub);i.startsWith("http")||Fe("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&Fe(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let $=rw();$.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&&Fe(`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||Fe(`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 pr()).trim().toLowerCase();if(yt.message(`move project '${o}'
|
|
730
|
+
(${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 dr({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await Zr("contextWrite",()=>Fy(r,t)))return{token:r};T.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function Fy(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 Hy(t){if(So()?.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?`
|
|
731
|
+
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=J(await dr({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 tp(){for(;;){let t=J(await te({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 dr({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Zr("YouTrack",()=>lt({baseUrl:t,token:e}))){let r=await Ja({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}T.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as Ky}from"node:fs";function ae(t){throw new Error(t)}function le(t,e){return(typeof t!="string"||t.trim().length===0)&&ae(`config: '${e}' must be a non-empty string`),t.trim()}function en(t,e){if(t==null)return;typeof t!="string"&&ae(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function Wy(t){(!t||typeof t!="object")&&ae("config: expected a JSON object");let e=t,r=le(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||ae("config: 'hubUrl' must start with http(s)://");let n=le(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&ae("config: 'project' is required");let i=o,s=le(i.id,"project.id");vt.test(s)||ae("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=le(i.name,"project.name"),c=le(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&ae("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||ae("config: 'project.repos' must be an array");let p=l.map((h,k)=>{(!h||typeof h!="object")&&ae(`config: project.repos[${k}] must be an object`);let I=h,B=le(I.host,`project.repos[${k}].host`);B!=="github"&&B!=="bitbucket"&&B!=="gitlab"&&ae(`config: project.repos[${k}].host must be 'github', 'bitbucket' or 'gitlab'`);let R={name:le(I.name,`project.repos[${k}].name`),host:B,owner:le(I.owner,`project.repos[${k}].owner`),repoName:le(I.repoName,`project.repos[${k}].repoName`)},A=en(I.defaultBranch,`project.repos[${k}].defaultBranch`);A&&(R.defaultBranch=A);let M=en(I.mountAs,`project.repos[${k}].mountAs`);return M&&(R.mountAs=M),R}),d=i.contextRepo;(!d||typeof d!="object")&&ae("config: 'project.contextRepo' is required");let u=d,m=en(u.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&ae("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:m,owner:le(u.owner,"project.contextRepo.owner"),name:en(u.name,"project.contextRepo.name")??Ve(s)},y={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:p,contextRepo:f}},w=en(i.youtrackProjectKey,"project.youtrackProjectKey");w&&(y.project.youtrackProjectKey=w),i.index!==void 0&&(typeof i.index!="boolean"&&ae("config: 'project.index' must be a boolean"),y.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&ae("config: 'project.youtrackWrites' must be a boolean"),y.project.youtrackWrites=i.youtrackWrites);let $=e.secrets;if($!==void 0){(typeof $!="object"||$===null)&&ae("config: 'secrets' must be an object");let h=$,k={};if(h.github){let I=h.github;k.github={token:le(I.token,"secrets.github.token")}}if(h.bitbucket){let I=h.bitbucket;k.bitbucket={email:le(I.email,"secrets.bitbucket.email"),apiToken:le(I.apiToken,"secrets.bitbucket.apiToken")}}if(h.gitlab){let I=h.gitlab;k.gitlab={token:le(I.token,"secrets.gitlab.token")}}if(h.youtrack){let I=h.youtrack;k.youtrack={url:le(I.url,"secrets.youtrack.url").replace(/\/$/,""),token:le(I.token,"secrets.youtrack.token")}}if(h.contextWrite){let I=h.contextWrite;k.contextWrite={token:le(I.token,"secrets.contextWrite.token")}}y.secrets=k}return y}async function Yy(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function qy(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await ot(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 it(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${n}`)}if(e.gitlab){let r=await st(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await lt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function rp(t){let e=!t.configPath||t.configPath==="-"?await Yy():Ky(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(u){ae(`config: invalid JSON \u2014 ${u instanceof Error?u.message:String(u)}`)}let n=Wy(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 qy(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 cr(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??Gt(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:u=>console.log(` ${u}`),warn:u=>console.warn(` ${u}`)}})}catch(u){ae(`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 ut(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)ae(`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),Je({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Me(s.id)}`),Rt(s.id,Fe(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 Wr(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 np,intro as op,isCancel as ip,log as Ci,outro as Vy,password as sp}from"@clack/prompts";async function Jy(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function ap(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Jy(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){op("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Ci.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await sp({message:"Claude OAuth token"});ip(i)&&(np("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Us({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${bn()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=ve(t.profile);if(!e){op(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Ci.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await sp({message:"Claude OAuth token"});ip(i)&&(np("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}.`):(Ci.success("Claude OAuth token saved."),Vy("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as zy,confirm as Xy,intro as Qy,isCancel as cp,log as fe,outro as Zy,select as lp,text as ht}from"@clack/prompts";function up(t){zy(t),process.exit(1)}function gr(t){return cp(t)&&up("aborted"),t}function tn(t){return cp(t)&&up("aborted"),typeof t=="string"?t:""}async function ew(t,e){let r=gr(await lp({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=tn(await ht({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=tn(await ht({message:"Context Repo name",placeholder:Ve(t),initialValue:Ve(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function pp(t={profile:void 0}){let e=ve(t.profile);Qy(`codepipe project add \u2192 ${e.hubUrl}`);let r=gr(await ht({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:u=>vt.test(u.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=gr(await ht({message:"project name (human-readable)",placeholder:"CodePartner",validate:u=>u.trim().length>0?void 0:"required"})).trim(),o=gr(await lp({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=gr(await ht({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=gr(await Xy({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let u=tn(await ht({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()||Re($)?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=Re(u);fe.message(`${m.host}: ${m.owner}/${m.repoName}`);let f=tn(await ht({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:$=>$.trim().length>0?void 0:"required"})).trim(),y=tn(await ht({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 ew(r,a),p=L(e.projectId);fe.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let d;try{d=await cr(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??Gt(),youtrackWrites:s,trackerUrl:p?.youtrack?.url,log:{info:u=>fe.message(u),warn:u=>fe.warn(u)}})}catch(u){fe.error(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}c.contextRepo=d,fe.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let u=await ut(e.hubUrl,e.cliToken,c);fe.success(`project "${u.projectId}" \u2014 ${u.provisioningStatus}`),Rt(r,Fe(c,s,p?.youtrack?.url),{info:m=>fe.message(m),warn:m=>fe.warn(m)}),u.contextRepo&&(fe.message(` context repo: ${u.contextRepo.owner}/${u.contextRepo.name} (${u.contextRepo.cloneUrl})`),fe.message(` branch: ${u.contextRepo.branch}`)),u.provisioningError&&fe.error(` error: ${u.provisioningError}`),Zy("done")}catch(u){u instanceof N?(fe.error(`HUB \u2192 ${u.status} ${u.message}`),u.payload&&typeof u.payload=="object"&&fe.message(JSON.stringify(u.payload,null,2))):fe.error(u instanceof Error?u.message:String(u)),process.exit(1)}}import{existsSync as tw,rmSync as rw}from"node:fs";import{confirm as nw,intro as ow,isCancel as iw,log as yt,outro as sw,spinner as aw}from"@clack/prompts";function Ke(t){yt.error(t),process.exit(1)}var dp=t=>t.trim().replace(/\/+$/,"");async function fp(t){ow("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??$e()?.spec.projectId??void 0;e||Ke("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=Ee(e);r||Ke(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=dp(r.hubUrl),o=r.projectId,i=dp(t.hub);i.startsWith("http")||Ke("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&Ke(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let $=aw();$.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&&Ke(`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||Ke(`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 fr()).trim().toLowerCase();if(yt.message(`move project '${o}'
|
|
732
732
|
from : ${n} (profile ${e})
|
|
733
733
|
to : ${i} (profile ${s}, project ${a}, account ${d})
|
|
734
734
|
\u2022 the source registration on the old HUB is left intact (non-destructive)
|
|
735
735
|
\u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
|
|
736
|
-
`+(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
|
|
737
|
-
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let y;try{y=await
|
|
738
|
-
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`),
|
|
736
|
+
`+(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 nw({message:"Continue?",initialValue:!0});(iw($)||!$)&&Ke("aborted")}!c&&a===o&&yt.warn(`source and destination share the same project id, so they share one secrets file (${Me(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 mr(i,d),f={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:m,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};yt.step(`registering project on ${i}\u2026`);let y;try{y=await ut(i,u,f)}catch($){if($ instanceof N&&$.status===409){yt.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{y=await q(i,u,a)}catch(h){throw h instanceof N&&Ke(`target HUB \u2192 ${h.status} ${h.message}`),h}}else if($ instanceof N&&$.status===403)Ke(`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)Ke(`target HUB \u2192 ${$.status} ${$.message}`);else throw $}yt.success(`project ${y.projectId} ready on ${i} (${y.provisioningStatus})`),Je({hubUrl:i,cliToken:u,projectId:a,accountEmail:m},s);let w={...p??{},hubUrl:i,cliToken:u,projectId:a};if(delete w.sandboxPins,z(w),yt.success(`profile '${s}' \u2192 ${Me(a)}`),c){let $=Ne(s);tw($)&&(rw($),yt.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}sw(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}import{existsSync as Pi,rmSync as cw,statSync as lw}from"node:fs";import{join as ao,relative as uw,resolve as pw}from"node:path";import{cancel as dw,intro as gp,isCancel as fw,log as re,outro as hp,text as jt}from"@clack/prompts";import{simpleGit as yp}from"simple-git";function ye(t){dw(t),process.exit(1)}function At(t){return fw(t)&&ye("aborted"),typeof t=="string"?t:""}async function mp(t){try{let e=await yp(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function mw(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function gw(t,e){let r=L(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(mw(r,e)){re.message(`reusing existing ${e} credentials`);return}if(re.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=At(await jt({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=At(await jt({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=At(await jt({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),re.success(`saved ${e} credentials`)}async function wp(t){let e=ve(t.profile);gp(`codepipe repo add \u2192 project ${e.projectId}`);let r=$e()??void 0,n;try{n=(await q(e.hubUrl,e.cliToken,e.projectId)).repos}catch(h){ye(`could not read project from HUB: ${h instanceof Error?h.message:String(h)}`)}let o=t.target?.trim();if(!o){let h=await mp(process.cwd());h?(o=process.cwd(),re.message(`using the current directory (${h})`)):o=At(await jt({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:k=>k.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(Pi(o)&&lw(o).isDirectory()){i=pw(o);let h=await mp(i);h||ye(`${i} is not a git repository (no origin remote)`);let k=Re(h);k||ye(`origin ${h} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=k,s=h,re.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let h=Re(o);h||ye(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=h,s=o,re.message(`${a}: ${c}/${l}`)}let p=At(await jt({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)&&ye(`a repo named "${p}" is already registered`);let d=At(await jt({message:"default branch (optional)",placeholder:"main"})).trim(),u=p;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let h=uw(r.root,i);u=h===""?".":h}let m=At(await jt({message:"mount_as (directory relative to the workspace root)",placeholder:u,initialValue:u})).trim()||u;n.some(h=>(h.mountAs??h.name)===m)&&ye(`mount_as "${m}" is already used by another repo`),await gw(e,a);let f={name:p,host:a,owner:c,repoName:l,mountAs:m,...d?{defaultBranch:d}:{}};if(!i){let h=r?ao(r.root,m):xe(e.projectId,p);if(Pi(ao(h,".git")))re.message(`already cloned at ${h}`);else{re.info(`cloning ${s} \u2192 ${h} \u2026`);try{await yp().clone(s,h),re.success(`cloned into ${h}`)}catch(k){ye(`clone failed: ${k instanceof Error?k.message.trim():String(k)}
|
|
737
|
+
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let y;try{y=await Jc(e.hubUrl,e.cliToken,e.projectId,f)}catch(h){h instanceof N&&ye(`HUB \u2192 ${h.status} ${h.message}`),ye(h instanceof Error?h.message:String(h))}let{updated:w,errors:$}=_r(e.projectId,y.repos,r?.contextDir);for(let h of w)re.message(`updated ${h}`);for(let h of $)re.warn(`could not update ${h.path}: ${h.error}`);re.success(`added "${p}" \u2014 project now has ${y.repos.length} repo(s)`),hp("done")}async function kp(t){let e=ve(t.profile);gp(`codepipe repo remove \u2192 project ${e.projectId}`);let r=$e()??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 zc(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof N&&(a.status===404&&ye(`no repo named "${t.name}" in this project`),ye(`HUB \u2192 ${a.status} ${a.message}`)),ye(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=_r(e.projectId,o.repos,r?.contextDir);for(let a of i)re.message(`updated ${a}`);for(let a of s)re.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")re.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?ao(r.root,n):xe(e.projectId,t.name);if(Pi(ao(a,".git")))try{cw(a,{recursive:!0,force:!0}),re.message(`deleted local clone ${a}`)}catch(c){re.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else re.message(`no local clone found to purge (${a})`)}re.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),hp("done")}async function bp(t){let e=ve(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 hw}from"node:child_process";import{existsSync as $p}from"node:fs";import{homedir as yw,hostname as ww}from"node:os";import{join as co}from"node:path";async function kw(t,e,r){let n=de(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${Ne(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 Bc(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 ${Ne(e)} still holds its token.
|
|
738
|
+
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`),Ds(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function bw(t,e,r){let n=de(e)!==null;if(!await kw(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 Hn(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 It({hub:t.hubUrl,token:o,name:r.name??`${ww()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function $w(t,e){let r=de(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=me(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=kn(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 vw(t,e){let r=process.cwd(),n=co(r,Be);if(hn(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if($p(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 Ii(r);if(!ys(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 Vn({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=co(yw(),".codepipe",e?co("profiles",e,"context-config"):"context-config");if(Rn(c.contextDir,l,a),!$p(co(c.contextDir,"project.yaml"))){Wt(c.contextDir);let p={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};Pr(c.contextDir,Fe(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 vp(t){let{cfg:e,profile:r}=wn(t.profile);await vw(e,r),await bw(e,r,t),$w(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=>$=>{for(let h of $.toString("utf-8").split(`
|
|
739
739
|
`))h.length>0&&w.write(`${f} ${h}
|
|
740
|
-
`)};m.stdout?.on("data",y(process.stdout)),m.stderr?.on("data",y(process.stderr))},i=(m,f)=>{let y=
|
|
741
|
-
[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,$)=>y({name:m,code:w??($?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
|
|
742
|
-
`)}async function
|
|
740
|
+
`)};m.stdout?.on("data",y(process.stdout)),m.stderr?.on("data",y(process.stderr))},i=(m,f)=>{let y=hw(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(`
|
|
741
|
+
[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,$)=>y({name:m,code:w??($?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 Np,mkdirSync as Iw,readFileSync as Cw,writeFileSync as Pw}from"node:fs";import{homedir as Ew}from"node:os";import{dirname as jw,join as Op}from"node:path";import*as yr from"node:readline";import{existsSync as Ai,readFileSync as xw,writeFileSync as Sw}from"node:fs";import{join as nn}from"node:path";import{simpleGit as ji}from"simple-git";var xp=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],Rw="apply-queue.json";function Sp(t){return nn(t,Rw)}function hr(t){let e=Sp(t);if(!Ai(e))return{};try{return JSON.parse(xw(e,"utf-8"))}catch{return{}}}function Rp(t,e){Sw(Sp(t),JSON.stringify(e,null,2)+`
|
|
742
|
+
`)}async function Tp(t,e,r,n,o){let i;try{i=await Wc(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=nn(t.root,m.mountAs);if(!Ai(nn(f,".git")))return{ok:!1,message:`${m.mountAs}/ not cloned \u2014 run /sync first`};if(!(await ji(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=ji(u.dir),f=await Tw(m),y=u.claimRepo;try{await m.fetch()}catch(h){return await Ei(a,o),{ok:!1,message:`fetch failed in ${u.spec.mountAs}: ${rn(h)}`}}let w=`origin/${y.baseRef}`,$;try{$=await jn(m,{contextRepoCloneUrl:y.contextRepoCloneUrl,deliveryRef:y.deliveryRef,deliverySha:y.deliverySha,baseSha:y.baseSha,commitMessage:y.commitMessage})}catch(h){return await Ei(a,o),{ok:!1,message:`fetch delivery failed in ${u.spec.mountAs}: ${rn(h)}`}}a.push({git:m,dir:u.dir,mountAs:u.spec.mountAs,originalRef:f,branch:y.branchName,baseSha:w,deliveryCommit:$,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([...xp,"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([...xp,"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 Ei(a,o),{ok:!1,message:`apply failed in ${u.mountAs}: ${rn(m)} (rolled back all repos)`}}let l=hr(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},Rp(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}
|
|
743
743
|
${d}
|
|
744
|
-
or: /abort ${r} --reason "..."`}}function
|
|
744
|
+
or: /abort ${r} --reason "..."`}}function _i(t,e){let r=hr(t);r[e]&&(delete r[e],Rp(t,r))}async function Ei(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}: ${rn(n)} \u2014 check manually`)}}async function Ip(t,e,r){let o=hr(t.contextDir)[e];if(o){for(let i of o.repos){let s=nn(t.root,i.mountAs);if(!Ai(nn(s,".git")))continue;let a=ji(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}: ${rn(p)} \u2014 check manually`)}}_i(t.contextDir,e)}}async function Tw(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function rn(t){return t instanceof Error?t.message.trim():String(t)}var lo=Op(Ew(),".codepipe","history"),Cp=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Dp=500,Pp=40;async function Up(){let t=$e();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)),Cr(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=hr(t.contextDir),n=Object.keys(r);n.length>0&&console.log(`
|
|
745
745
|
\u26A0 unfinished local apply: ${n.map(s=>`${s} (${r[s].repos.map(a=>a.mountAs).join(", ")})`).join("; ")}
|
|
746
|
-
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let o=
|
|
747
|
-
`))}async function
|
|
748
|
-
`)}`:" (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}
|
|
749
|
-
`),t.unread+=1,
|
|
750
|
-
bye.`),setTimeout(()=>process.exit(0),150))}function
|
|
746
|
+
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let o=yr.createInterface({input:process.stdin,output:process.stdout,completer:Aw,history:Qw(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:o,unread:0,daemon:void 0,follow:!1,logBuffer:[]};Sa(s=>_t(i,s)),i.daemon=Yn({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>_t(i,s),warn:s=>_t(i,s)},onEvent:s=>Yw(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),Oi(i),o.prompt(),o.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await _w(i,a)){_p(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,Oi(i),o.prompt()}),o.on("close",()=>{_p(i)})}function Aw(t){let e=Cp.filter(r=>r.startsWith(t));return[e.length?e:Cp,t]}async function _w(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return Nw(),!1;case"/status":return await Ow(t),!1;case"/tasks":return await Dw(t,n),!1;case"/task":return await Uw(t,n),!1;case"/sync":return await Lw(t),!1;case"/logs":return qw(t,n),!1;case"/monitor":return Vw(t),!1;case"/apply":return await Ep(t,n,"apply"),!1;case"/unstash":return await Ep(t,n,"unstash"),!1;case"/applied":return await Bw(t,n),!1;case"/abort":return await Mw(t,n),!1;case"/approve":return await jp(t,n,"approve"),!1;case"/merge":return await jp(t,n,"merge"),!1;case"/login":return Fw(t,n),!1;case"/secret":return Hw(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function Nw(){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(`
|
|
747
|
+
`))}async function Ow(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=Np(Op(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${n?"present":"missing (run /sync)"}`)}}async function Dw(t,e){let r=Jw(e,"--phase");try{let n=await Hc(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){sn(n)}}async function Uw(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await Kc(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){sn(n)}}async function Lw(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 Ep(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await Tp(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function Bw(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=hr(t.ws.contextDir)[r],i=zw(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?Gw(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 Yc(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);_i(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){sn(c)}}async function jp(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await Vc(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){sn(o)}}async function Mw(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=Xw(e,"--reason")||"local apply aborted";await Ip(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await qc(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){sn(o)}}function Gw(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function Fw(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 Hw(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(`
|
|
748
|
+
`)}`:" (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}Kw(t.secrets,n,i),z(t.secrets),Cr(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}Ww(t.secrets,n),z(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function Kw(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 Ww(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 Yw(t,e){switch(e.kind){case"connected":t.connection="connecting",_t(t,"[hub] connected");break;case"registered":t.connection="registered",_t(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",on(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",_t(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",on(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":on(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?_t(t,`[hub] action ${e.actionType} done`):on(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function _t(t,e){t.logBuffer.push(e),t.logBuffer.length>Dp&&t.logBuffer.shift(),t.follow&&on(t,e)}function qw(t,e){let r=e[0];if(r==="follow"||r==="on"){Ni(t,!0);return}if(r==="off"){Ni(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(Dp,Number(r)||Pp)):Pp,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 Vw(t){Ni(t,!t.follow)}function Ni(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function on(t,e){yr.cursorTo(process.stdout,0),yr.clearLine(process.stdout,0),process.stdout.write(e+`
|
|
749
|
+
`),t.unread+=1,Oi(t),t.rl.prompt(!0)}function Oi(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var Ap=!1;function _p(t){Ap||(Ap=!0,Zw(t.rl),t.daemon.stop(),console.log(`
|
|
750
|
+
bye.`),setTimeout(()=>process.exit(0),150))}function Jw(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function zw(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 Xw(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function sn(t){t instanceof N?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function Qw(){if(!Np(lo))return[];try{return Cw(lo,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function Zw(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{Iw(jw(lo),{recursive:!0}),Pw(lo,r.slice().reverse().join(`
|
|
751
751
|
`)+`
|
|
752
|
-
`)}catch{}}import{hostname as Jw}from"node:os";import{cancel as zw,confirm as Np,intro as Xw,isCancel as Up,log as hr,multiselect as Qw,outro as Op,password as Zw,select as Ni,text as Oi}from"@clack/prompts";function sn(t){zw(t),process.exit(1)}function yr(t){return Up(t)&&sn("aborted"),t}function uo(t){return Up(t)&&sn("aborted"),typeof t=="string"?t:""}function Di(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Dp(t,e){try{let{secret:r}=await Hn(t,e);return r}catch(r){throw r instanceof N&&r.status===404&&sn("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 ek(t,e){if(yr(await Ni({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 Oc(t,e);if(o.length>0)return yr(await Qw({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}));hr.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){hr.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return uo(await Oi({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){Xw("codepipe worker \u2014 set up this machine as a runner");let e=pe(t.profile);e&&(hr.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),yr(await Np({message:"re-register this worker?",initialValue:!1}))||sn("keeping the existing registration"));let r=Ce(t.profile)??Ce(),n=uo(await Oi({message:"HUB URL",placeholder:_e,initialValue:F("HUB_URL")??r?.hubUrl??_e,validate:u=>u.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=yr(await Ni({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 Dp(n,a),hr.success("account-issued registration token minted");else if(i==="login"){let u=await pr();a=(await dr(n,u)).cliToken,s=await Dp(n,a),hr.success("account-issued registration token minted")}else s=uo(await Zw({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||sn("a registration token is required");let c=await ek(n,a),l=uo(await Oi({message:"worker name",initialValue:Jw(),validate:u=>u.trim().length>0?void 0:"required"})).trim(),p=yr(await Ni({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 It({hub:n,token:s,name:l,projects:c,...p?{llm:p}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),hr.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!yr(await Np({message:"start the claim-loop now?",initialValue:!0}))){Op("registered. start later with `codepipe worker`.");return}Op("starting the claim-loop\u2026"),await zr(t.profile?{profile:t.profile}:{})}function rk(){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 ne=rk();ys(ne);bs();var ye=new tk;ye.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(ke).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{await _p()}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 Qu({configPath:t.config,skipVerify:t.skipVerify===!0}):await Fu({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 _s({...t,profile:ne})}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 Hu({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 vl({profile:ne})}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 Nu({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 np({profile:ne,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 mu({profile:ne})}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 wp({profile:ne,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Lp=ye.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Lp.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(ne)?.hubUrl??_e,r=t.token??F("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Di()){await Ui({profile:ne});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 It({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...ne?{profile:ne}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Lp.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!pe(ne)&&Di()){await Ui({profile:ne});return}await zr(ne?{profile:ne}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Bp=ye.command("project").description("Manage CodePipe projects");Bp.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await ap({profile:ne})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Bp.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 lp({...t,cliProfile:ne})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Li=ye.command("repo").description("Manage the project's git repositories");Li.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 mp({profile:ne,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Li.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 gp({profile:ne,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Li.command("list").description("List the project's repos").action(async()=>{try{await hp({profile:ne})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ye.parseAsync();
|
|
752
|
+
`)}catch{}}import{hostname as ek}from"node:os";import{cancel as tk,confirm as Lp,intro as rk,isCancel as Gp,log as wr,multiselect as nk,outro as Bp,password as ok,select as Di,text as Ui}from"@clack/prompts";function an(t){tk(t),process.exit(1)}function kr(t){return Gp(t)&&an("aborted"),t}function uo(t){return Gp(t)&&an("aborted"),typeof t=="string"?t:""}function Li(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Mp(t,e){try{let{secret:r}=await Hn(t,e);return r}catch(r){throw r instanceof N&&r.status===404&&an("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 ik(t,e){if(kr(await Di({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 oi(t,e);if(o.length>0)return kr(await nk({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}));wr.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){wr.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return uo(await Ui({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 Bi(t){rk("codepipe worker \u2014 set up this machine as a runner");let e=de(t.profile);e&&(wr.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),kr(await Lp({message:"re-register this worker?",initialValue:!1}))||an("keeping the existing registration"));let r=Ee(t.profile)??Ee(),n=uo(await Ui({message:"HUB URL",placeholder:Oe,initialValue:F("HUB_URL")??r?.hubUrl??Oe,validate:u=>u.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=kr(await Di({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 Mp(n,a),wr.success("account-issued registration token minted");else if(i==="login"){let u=await fr();a=(await mr(n,u)).cliToken,s=await Mp(n,a),wr.success("account-issued registration token minted")}else s=uo(await ok({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||an("a registration token is required");let c=await ik(n,a),l=uo(await Ui({message:"worker name",initialValue:ek(),validate:u=>u.trim().length>0?void 0:"required"})).trim(),p=kr(await Di({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 It({hub:n,token:s,name:l,projects:c,...p?{llm:p}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),wr.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!kr(await Lp({message:"start the claim-loop now?",initialValue:!0}))){Bp("registered. start later with `codepipe worker`.");return}Bp("starting the claim-loop\u2026"),await Xr(t.profile?{profile:t.profile}:{})}function ak(){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 ne=ak();vs(ne);Rs();var we=new sk;we.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(ke).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{await Up()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});we.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 rp({configPath:t.config,skipVerify:t.skipVerify===!0}):await Yu({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});we.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 Ls({...t,profile:ne})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});we.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 qu({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});we.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await Il({profile:ne})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});we.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 Bu({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});we.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 ap({profile:ne,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});we.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await ku({profile:ne})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});we.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 vp({profile:ne,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Fp=we.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Fp.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")??Ee(ne)?.hubUrl??Oe,r=t.token??F("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Li()){await Bi({profile:ne});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 It({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...ne?{profile:ne}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Fp.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!de(ne)&&Li()){await Bi({profile:ne});return}await Xr(ne?{profile:ne}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Hp=we.command("project").description("Manage CodePipe projects");Hp.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await pp({profile:ne})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Hp.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 fp({...t,cliProfile:ne})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Mi=we.command("repo").description("Manage the project's git repositories");Mi.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 wp({profile:ne,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Mi.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 kp({profile:ne,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Mi.command("list").description("List the project's repos").action(async()=>{try{await bp({profile:ne})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});we.parseAsync();
|