@code-partner/codepipe 0.8.2-dev.186.g20b8fce → 0.8.2-dev.187.g9eed0ac
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 +140 -137
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,53 +1,55 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Qg=Object.defineProperty;var k=(t,e)=>()=>(t&&(e=t(t=0)),e);var Zg=(t,e)=>{for(var r in e)Qg(t,r,{get:e[r],enumerable:!0})};var Ee,Je,Ei=k(()=>{"use strict";Ee="0.8.2-dev.187.g9eed0ac",Je="https://hub.dev.codepipe.dev"});function Jn(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=eh&&t<=Xe}var Xe,eh,Ua=k(()=>{"use strict";Ei();Xe=4,eh=4});var Ma=k(()=>{"use strict";Ei()});function Xn(t=4){return`# CodePipe Context Repo format version.
|
|
3
3
|
# Bumped by the scaffold / the format-migration PR \u2014 do not edit by hand.
|
|
4
4
|
template_version: ${t}
|
|
5
|
-
`}function Ra(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 Ia(t,e=Ta){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 Ca(t,e=Ta){return e.filter(r=>r.version>t)}var ze,Zr,Ta,Ea=k(()=>{"use strict";ze=".codepipe-context.yaml",Zr=".devpipe-context.yaml",Ta=[{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",ze]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[ze]},{version:3,summary:"Custom project actions (the RUN tab): actions/ scaffold with the format README",addedPaths:["actions/README.md"]},{version:4,summary:"Project map: model/ scaffold with the format README (facts/ vs derived/ layout)",addedPaths:["model/README.md"]}]});var Pa=k(()=>{"use strict"});var Aa=k(()=>{"use strict"});var og,mx,ja=k(()=>{"use strict";og=[{id:"intake",label:"Intake",phases:["INTAKE"]},{id:"analysis",label:"Analysis",phases:["ANALYZING","ESTIMATING"]},{id:"ready",label:"Ready",phases:["READY"]},{id:"implementation",label:"Implementation",phases:["IMPLEMENTING","BUILD"]},{id:"delivery",label:"Delivery",phases:["READY_TO_APPLY","APPLYING","AWAITING_CLUSTER"]}],mx=og.flatMap(t=>t.phases)});function Ut(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var _a,ki=k(()=>{"use strict";_a=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"]});function Na(t,e){return e.toLowerCase().includes(t.toLowerCase())}function Da(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||sg.every(o=>e.some(i=>Na(o,i.id))))return null;let n=[...e].sort((o,i)=>{let s=o.createdAt??"",a=i.createdAt??"";return s!==a?s<a?1:-1:o.id<i.id?1:-1});for(let o of ig){let i=n.find(s=>Na(o,s.id));if(i)return i.id}return n[0].id}var Je,Oa,Ue,en,La,bi,$i,ig,sg,vi=k(()=>{"use strict";Je="claude",Oa=[Je],Ue="opus",en="sonnet",La="haiku",bi=[Ue,en,La],$i={analyze:Ue,implement:Ue,"resolve-conflict":Ue,rework:Ue,estimate:en,build:en,"code-review":Ue,draft:en,index:Ue,backfill:Ue,analysis:Ue,chat:Ue},ig=[Ue,en,La],sg=Array.from(new Set(Object.values($i)))});function gt(t){return ag.has(t)?!0:cg.some(e=>t.startsWith(e))}function Yn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Bt(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function xi(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function Fa(t,e){let r=Yn(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=Bt(r.id,"id")??n;if(!Ua.test(o))throw new Error(`id must match ${Ua} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=Bt(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=Yn(r.env,"env");s={};for(let[d,m]of Object.entries(p)){if(!Ce.test(d))throw new Error(`env name "${d}" must match ${Ce}`);if(typeof m!="string"&&typeof m!="number"&&typeof m!="boolean")throw new Error(`env.${d} must be a scalar`);s[d]=String(m)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>Ba)throw new Error(`too many params (max ${Ba})`);let p=new Set;a=c.map((d,m)=>lg(d,m,p))}let l=r.steps;if(!Array.isArray(l)||l.length===0)throw new Error("steps must be a non-empty list");if(l.length>Ma)throw new Error(`too many steps (max ${Ma})`);let u=l.map((p,d)=>{let m=Yn(p,`steps[${d}]`),f=Bt(m.run,`steps[${d}].run`);if(!f||f.trim().length===0)throw new Error(`steps[${d}].run is required`);let g=Bt(m.name,`steps[${d}].name`),y=xi(m.timeout_sec,`steps[${d}].timeout_sec`);if(y!==void 0&&(!Number.isInteger(y)||y<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:f,...g?{name:g}:{},...y!==void 0?{timeout_sec:y}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function lg(t,e,r){let n=Yn(t,`params[${e}]`),o=Bt(n.name,`params[${e}].name`);if(!o||!Ce.test(o))throw new Error(`params[${e}].name must match ${Ce}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let m=n.enum;if(!Array.isArray(m)||m.length===0||!m.every(f=>typeof f=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=m}let a=Bt(n.label,`params[${e}].label`),c=Bt(n.help,`params[${e}].help`),l=n.required===!0,u=xi(n.min,`params[${e}].min`),p=xi(n.max,`params[${e}].max`),d=n.default;if(d!=null&&typeof d!="string"&&typeof d!="number"&&typeof d!="boolean")throw new Error(`params[${e}].default must be a scalar`);return{name:o,type:i,...a?{label:a}:{},...c?{help:c}:{},...l?{required:!0}:{},...s?{enum:s}:{},...u!==void 0?{min:u}:{},...p!==void 0?{max:p}:{},...d!=null?{default:d}:{}}}function Ka(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 Ce,ag,cg,Ga,Ua,Ba,Ma,Si=k(()=>{"use strict";Ce=/^[A-Z][A-Z0-9_]*$/,ag=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),cg=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];Ga=600,Ua=/^[a-z0-9-]+$/,Ba=32,Ma=64});function qa(t=ug){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...qa(r.groups));return e}function dg(t,e){let r=JSON.stringify(e);return qa().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function Va(t){let e=dg(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.type==="string"&&e.mustContain&&!i.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:e.maxLength!==void 0&&i.length>e.maxLength?{ok:!1,error:`${e.id} must be \u2264 ${e.maxLength} chars`}:{ok:!0,field:e,value:i}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}case"string_map":{if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,error:`${e.id} must be a name\u2192value map`};let i=Object.entries(r);if(i.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(i.length>Ha)return{ok:!1,error:`${e.id} must have \u2264 ${Ha} entries`};let s={};for(let[a,c]of i){if(!Ce.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Ce}`};if(gt(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>Wa)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${Wa} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var Ha,Wa,Ya,ug,za=k(()=>{"use strict";Si();ki();vi();Ha=64,Wa=2e3,Ya=2e3,ug=[{id:"branch",label:"Branch",help:"Task-branch naming.",fields:[{id:"branch.pattern",file:"project.yaml",path:["branch","pattern"],type:"string",label:"Task-branch pattern",nullable:!0,mustContain:"<TASK_ID>",help:"Template for the per-task branch name. Must contain the <TASK_ID> placeholder. Empty \u21D2 default codepipe/<TASK_ID>."}]},{id:"llm",label:"LLM",fields:[{id:"llm.provider",file:"regimen.yaml",path:["llm","provider"],type:"enum",label:"Provider",nullable:!1,suggestions:[...Oa],help:"LLM backend for this project. Currently only claude is available."}],groups:[{id:"llm.models",label:"Models by role",help:"Model per pipeline stage. Empty \u21D2 the role's recommended default applies.",fields:[{id:"llm.models.default",file:"regimen.yaml",path:["llm","models","default"],type:"model",label:"default (catch-all)",nullable:!0,suggestions:[...bi],help:"Overrides the recommended defaults for every role not listed below."},..._a.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...bi],help:`recommended: ${$i[t]}`}))]}]},{id:"apply.style",label:"Commits & PRs",help:"Instructions for the AI agent on how to write commit messages and PR descriptions. Empty \u21D2 built-in templates.",fields:[{id:"apply.commit_style",file:"project.yaml",path:["apply","commit_style"],type:"string",label:"Commit message style",nullable:!0,multiline:!0,maxLength:Ya,help:'e.g. "English, imperative mood, first line \u2264 72 chars, start with the issue key". Empty \u21D2 "<KEY>: <task title>".'},{id:"apply.pr_style",file:"project.yaml",path:["apply","pr_style"],type:"string",label:"PR description style",nullable:!0,multiline:!0,maxLength:Ya,help:'e.g. "Russian, implementation details, bullet list of what was done". Empty \u21D2 the default PR body.'}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (on by default; orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on (default), a task taken from Develop waits in the QUEUE for a single Confirm before the pipeline starts \u2014 the Confirm pulls in dependency closure and topologically orders the queue. Off \u21D2 conveyor: the task starts the pipeline immediately."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]},{id:"implementation",label:"Implementation",help:"How a dependency cluster is serialized into branches and PRs.",fields:[{id:"implementation.mode",file:"regimen.yaml",path:["implementation","mode"],type:"enum",label:"Implementation mode",nullable:!0,suggestions:["cluster-pr","sequential","parallel"],help:"cluster-pr (default for new projects) \u2014 one shared branch and a single PR per dependency cluster; a lone task is a cluster of one. sequential / parallel are an explicit opt-out of that. Clearing removes the key from regimen.yaml but keeps the mode already stored for the project (it is not reset to the default)."}]}]});var Ja=k(()=>{"use strict"});var Xa=k(()=>{"use strict"});var Qa=k(()=>{"use strict"});function Za(t){return`codepipe-host-${t}`}var ec=k(()=>{"use strict"});function tc(t){return!(!t||t.length>250||!/^[A-Za-z0-9._/-]+$/.test(t)||/^[-/.]/.test(t)||/[/.]$/.test(t)||t.endsWith(".lock")||t.includes("..")||t.includes("//")||t.includes("/."))}function st(t){return`${t}${pg}`}var Mt,pg,rc=k(()=>{"use strict";Mt=/^[a-z][a-z0-9-]{1,30}$/,pg="-codepipe-ctx"});var nc=k(()=>{"use strict"});var oc=k(()=>{"use strict"});function sr(t){for(let e of fg){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var fg,ic=k(()=>{"use strict";fg=[{name:"rework",pattern:/^@(?:codepipe|devpipe)\s+rework:\s*(.+)$/im,description:"Send the task back to ANALYZING with a new instruction.",hasArg:!0},{name:"approve",pattern:/^@(?:codepipe|devpipe)\s+approve\s*$/im,description:"Merge every PR for this task (TRACKING only)."},{name:"reject",pattern:/^@(?:codepipe|devpipe)\s+reject(?::\s*(.+))?\s*$/im,description:"Abandon this task: close any open PR(s) and move it to DONE (reason rejected_and_closed). Valid from any non-terminal phase; from early phases it just skips the task.",hasArg:!0},{name:"merge",pattern:/^@(?:codepipe|devpipe)\s+merge\s*$/im,description:"Merge the task branch into the default branch without a PR (direct apply path, apply.pull_request=false; TRACKING only)."},{name:"rebase",pattern:/^@(?:codepipe|devpipe)\s+rebase\s*$/im,description:"Re-apply the patch on top of the latest base branch and force-push. Use after a PR merge conflict or APPLYING failure."},{name:"update",pattern:/^@(?:codepipe|devpipe)\s+update(?::\s*(.+))?\s*$/im,description:"Update a conflicting PR: resolve conflicts against the current base branch (TRACKING only). Optional `: <instruction>` is forwarded to the agent.",hasArg:!0},{name:"apply",pattern:/^@(?:codepipe|devpipe)\s+apply:\s*(local|auto)\s*$/im,description:"Override apply mode for this task: local (you apply by hand) or auto.",hasArg:!0}]});var sc=k(()=>{"use strict"});var ac=k(()=>{"use strict"});var cc=k(()=>{"use strict"});function lc(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function dc(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=lc(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(ar.test(r))return r;let n=lc(t);return ar.test(n)?n:Ti}function pc(t,e){let r=new Set([...e].map(n=>n.toUpperCase()));if(!r.has(t.toUpperCase()))return t;for(let n=1;n<1e4;n++){let o=String(n),i=t.slice(0,10-o.length)+o;if(!r.has(i.toUpperCase()))return i}return t}function rn(t){return`tasks/${t}/issue.yaml`}var uc,qn,Ti,ar,Ri,Ex,Vn,tn,fc=k(()=>{"use strict";uc=["bug","feature","epic"],qn="feature",Ti="TASK",ar=/^[A-Z][A-Z0-9]{1,9}$/;Ri={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},Ex=Ri.backlog,Vn="tracker/config.yaml",tn="tracker/counter"});var mc=k(()=>{"use strict"});function cr(t){let e=t.match(/^git@([^:/]+):/);if(e)return e[1]??null;let r=t.match(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)/);if(r)return r[1]??null;let n=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return n?n[1]??null:null}function zn(t){switch(t){case nn.gitlab:return"oauth2";case nn.bitbucket:return"x-token-auth";default:return"x-access-token"}}var nn,Gt,gc=k(()=>{"use strict";nn={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Gt="x-bitbucket-api-token-auth"});var hc=k(()=>{"use strict"});var yc=k(()=>{"use strict";mc();gc();hc()});var wc,W=k(()=>{"use strict";xa();Sa();Ea();Pa();Aa();ja();ki();vi();za();Si();Ja();Xa();Qa();ec();rc();nc();oc();ic();sc();ac();cc();fc();yc();wc=20});function M(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var ke=k(()=>{"use strict"});import{existsSync as kc,renameSync as mg}from"node:fs";function Ft(t,e,r=n=>console.error(n)){if(kc(e)||!kc(t))return!1;try{return mg(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 Jn=k(()=>{"use strict"});import{existsSync as Xn,readFileSync as bc,readdirSync as gg,writeFileSync as hg}from"node:fs";import{dirname as yg,join as ht}from"node:path";import{parse as wg}from"yaml";function kg(t=process.cwd()){let e=t;for(;;){if(Xn(ht(e,Xe,"project.yaml")))return e;if(Xn(ht(e,Ii,"project.yaml")))return Ft(ht(e,Ii),ht(e,Xe))&&$g(e),e;let r=yg(e);if(r===e)return null;e=r}}function bg(t){let e=ht(t,Xe);return Xn(e)?e:ht(t,Ii)}function $g(t){let e=ht(t,".gitignore");if(!Xn(e))return;let r=bc(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
|
-
`)
|
|
7
|
-
`,{mode:384})}function eo(t){if(t)return{cfg:Pe(t),profile:t};let e;try{e=Ee()?.spec.projectId||void 0}catch{}if(e){let r=Be(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:Pe(void 0),profile:void 0}}function Pe(t){let e=Be(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 ${lr(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var Sc,xe=k(()=>{"use strict";ke();at();Sc=Rg(Tc(Ig(import.meta.url)),"..")});import{homedir as Pc}from"node:os";import{existsSync as Ac,mkdirSync as jc,readFileSync as _c,writeFileSync as Nc}from"node:fs";import{dirname as Oc,join as Lc}from"node:path";function Dc(t,e,r){let n=B(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},z(n)}function Uc(t,e){let r=B(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],z(r),!0)}function Bc(t){return Object.keys(B(t)?.secrets??{}).sort()}function to(t,e,r){let n=B(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 Mc(t,e){let r=B(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],z(r),!0):!1}function Qe(t){return Lc(Pc(),".codepipe","secrets",`${t}.json`)}function B(t){let e=Qe(t);return Ac(e)?JSON.parse(_c(e,"utf-8")):null}function z(t){let e=Qe(t.projectId);jc(Oc(e),{recursive:!0}),Nc(e,JSON.stringify(t,null,2)+`
|
|
8
|
-
|
|
9
|
-
`,{mode:384})}function
|
|
5
|
+
`}function Fa(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 Ga(t,e=Ba){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 Ka(t,e=Ba){return e.filter(r=>r.version>t)}var Qe,nn,Ba,Ha=k(()=>{"use strict";Qe=".codepipe-context.yaml",nn=".devpipe-context.yaml",Ba=[{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",Qe]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[Qe]},{version:3,summary:"Custom project actions (the RUN tab): actions/ scaffold with the format README",addedPaths:["actions/README.md"]},{version:4,summary:"Project map: model/ scaffold with the format README (facts/ vs derived/ layout)",addedPaths:["model/README.md"]}]});function Zn(t){return`model/facts/identity/${t}.yaml`}function th(t){return t===""?"root":t.replace(/\//g,"-")}function Wa(t,e){return`model/derived/structure/${t}/${th(e)}.yaml`}function Ya(t){return typeof t=="string"&&oh.test(t)}function Pe(t){if(typeof t!="string")return null;let e=t.indexOf(":");if(e<=0)return null;let r=t.indexOf(":",e+1);if(r<0)return null;let n=t.slice(0,e);if(!rh.includes(n))return null;let o=t.slice(e+1,r),i=t.slice(r+1);return o===""&&n!=="system"||i===""?null:{level:n,repo:o,path:i}}function Me(t,e,r){return`${t}:${e}:${r}`}function lr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function qa(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function ut(t){return typeof t=="string"&&t.length>0}function Va(t){let e=[];if(!lr(t))return{ok:!1,errors:["shard: not an object"]};qa(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),ut(t.repo)||e.push("repo: missing or empty"),ut(t.builtFromCommit)||e.push("builtFromCommit: missing or empty");let r=typeof t.repo=="string"?t.repo:"",n=new Set;return Array.isArray(t.nodes)?t.nodes.forEach((o,i)=>{if(!lr(o)){e.push(`nodes[${i}]: not an object`);return}let s=Pe(o.key);if(!s){e.push(`nodes[${i}].key: malformed nodeKey (${JSON.stringify(o.key??null)})`);return}o.level!==s.level&&e.push(`nodes[${i}]: level "${String(o.level)}" does not match key prefix "${s.level}"`),r&&s.repo!==r&&e.push(`nodes[${i}].key: repo "${s.repo}" mixed into shard of repo "${r}"`);let a=o.key;n.has(a)&&e.push(`nodes[${i}].key: duplicate "${a}"`),n.add(a),o.entityId!==void 0&&!Ya(o.entityId)&&e.push(`nodes[${i}].entityId: malformed (${JSON.stringify(o.entityId)})`)}):e.push("nodes: not an array"),Array.isArray(t.edges)?t.edges.forEach((o,i)=>{if(!lr(o)){e.push(`edges[${i}]: not an object`);return}nh.includes(o.kind)||e.push(`edges[${i}].kind: unknown "${String(o.kind)}"`),(!ut(o.to)||!Pe(o.to))&&e.push(`edges[${i}].to: malformed nodeKey`),(!ut(o.from)||!n.has(o.from))&&e.push(`edges[${i}].from: "${String(o.from)}" is not a node of this shard`),o.weight!==void 0&&!(typeof o.weight=="number"&&Number.isFinite(o.weight))&&e.push(`edges[${i}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}}function za(t){let e=[];if(!lr(t))return{ok:!1,errors:["identity: not an object"]};if(qa(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),ut(t.repo)||e.push("repo: missing or empty"),t.builtFromCommit!==void 0&&!ut(t.builtFromCommit)&&e.push("builtFromCommit: not a non-empty string"),!Array.isArray(t.entities))e.push("entities: not an array");else{let r=new Set;t.entities.forEach((n,o)=>{if(!lr(n)){e.push(`entities[${o}]: not an object`);return}Ya(n.entityId)?r.has(n.entityId)?e.push(`entities[${o}].entityId: duplicate "${n.entityId}"`):r.add(n.entityId):e.push(`entities[${o}].entityId: malformed (${JSON.stringify(n.entityId??null)})`),Pe(n.currentKey)||e.push(`entities[${o}].currentKey: malformed nodeKey`),n.status!=="active"&&n.status!=="orphaned"&&e.push(`entities[${o}].status: expected active|orphaned`),ut(n.firstSeen)||e.push(`entities[${o}].firstSeen: missing`),ut(n.lastSeen)||e.push(`entities[${o}].lastSeen: missing`),n.aliases!==void 0&&(Array.isArray(n.aliases)?n.aliases.forEach((i,s)=>{(!lr(i)||!Pe(i.key)||!ut(i.until))&&e.push(`entities[${o}].aliases[${s}]: malformed`)}):e.push(`entities[${o}].aliases: not an array`))})}return e.length?{ok:!1,errors:e}:{ok:!0,value:t}}function Qn(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function ih(t){return{...t,nodes:Qn(t.nodes,e=>e.key),edges:Qn(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function sh(t){return{...t,entities:Qn(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:Qn(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function on(t){return ah.test(t)?t:JSON.stringify(t)}function Ja(t){if(t===null)return"null";if(typeof t=="boolean")return t?"true":"false";if(typeof t=="number"){if(!Number.isFinite(t))throw new Error(`model yaml: non-finite number ${t}`);return JSON.stringify(t)}if(typeof t=="string")return JSON.stringify(t);throw new Error(`model yaml: unsupported scalar ${typeof t}`)}function Xa(t){return t===null||["boolean","number","string"].includes(typeof t)}function Pi(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function Qa(t,e,r){if(Array.isArray(t)){for(let n of t)if(Xa(n))r.push(`${e}- ${Ja(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=Pi(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([i,s],a)=>{let c=a===0?`${e}- `:`${e} `;Ai(i,s,c,`${e} `,r)})}}return}for(let[n,o]of Pi(t))Ai(n,o,e,e,r)}function Ai(t,e,r,n,o){if(Xa(e))o.push(`${r}${on(t)}: ${Ja(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${on(t)}: []`):(o.push(`${r}${on(t)}:`),Qa(e,`${n} `,o));else{let i=Pi(e);if(i.length===0)o.push(`${r}${on(t)}: {}`);else{o.push(`${r}${on(t)}:`);for(let[s,a]of i)Ai(s,a,`${n} `,`${n} `,o)}}}function eo(t){let e=[];return Qa(t,"",e),e.join(`
|
|
6
|
+
`)+`
|
|
7
|
+
`}function Za(t){return eo(ih(t))}function ec(t){return eo(sh(t))}var ji,rh,nh,oh,ah,tc=k(()=>{"use strict";ji="model/derived/INDEX.yaml";rh=["system","container","component","code","task","adr"],nh=["contains","touched_by","correlates","relates","references","depends_on"],oh=/^e_[0-9a-f]{8}$/;ah=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});var rc=k(()=>{"use strict"});var ch,US,nc=k(()=>{"use strict";ch=[{id:"intake",label:"Intake",phases:["INTAKE"]},{id:"analysis",label:"Analysis",phases:["ANALYZING","ESTIMATING"]},{id:"ready",label:"Ready",phases:["READY"]},{id:"implementation",label:"Implementation",phases:["IMPLEMENTING","BUILD"]},{id:"delivery",label:"Delivery",phases:["READY_TO_APPLY","APPLYING","AWAITING_CLUSTER"]}],US=ch.flatMap(t=>t.phases)});function Ft(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var oc,_i=k(()=>{"use strict";oc=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"]});function ic(t,e){return e.toLowerCase().includes(t.toLowerCase())}function cc(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||uh.every(o=>e.some(i=>ic(o,i.id))))return null;let n=[...e].sort((o,i)=>{let s=o.createdAt??"",a=i.createdAt??"";return s!==a?s<a?1:-1:o.id<i.id?1:-1});for(let o of lh){let i=n.find(s=>ic(o,s.id));if(i)return i.id}return n[0].id}var Ze,sc,Be,sn,ac,Ni,Oi,lh,uh,Di=k(()=>{"use strict";Ze="claude",sc=[Ze],Be="opus",sn="sonnet",ac="haiku",Ni=[Be,sn,ac],Oi={analyze:Be,implement:Be,"resolve-conflict":Be,rework:Be,estimate:sn,build:sn,"code-review":Be,draft:sn,index:Be,backfill:Be,analysis:Be,chat:Be},lh=[Be,sn,ac],uh=Array.from(new Set(Object.values(Oi)))});function bt(t){return dh.has(t)?!0:ph.some(e=>t.startsWith(e))}function to(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Gt(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function Li(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function fc(t,e){let r=to(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=Gt(r.id,"id")??n;if(!lc.test(o))throw new Error(`id must match ${lc} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=Gt(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=to(r.env,"env");s={};for(let[d,m]of Object.entries(p)){if(!Ae.test(d))throw new Error(`env name "${d}" must match ${Ae}`);if(typeof m!="string"&&typeof m!="number"&&typeof m!="boolean")throw new Error(`env.${d} must be a scalar`);s[d]=String(m)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>uc)throw new Error(`too many params (max ${uc})`);let p=new Set;a=c.map((d,m)=>fh(d,m,p))}let l=r.steps;if(!Array.isArray(l)||l.length===0)throw new Error("steps must be a non-empty list");if(l.length>dc)throw new Error(`too many steps (max ${dc})`);let u=l.map((p,d)=>{let m=to(p,`steps[${d}]`),f=Gt(m.run,`steps[${d}].run`);if(!f||f.trim().length===0)throw new Error(`steps[${d}].run is required`);let g=Gt(m.name,`steps[${d}].name`),y=Li(m.timeout_sec,`steps[${d}].timeout_sec`);if(y!==void 0&&(!Number.isInteger(y)||y<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:f,...g?{name:g}:{},...y!==void 0?{timeout_sec:y}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function fh(t,e,r){let n=to(t,`params[${e}]`),o=Gt(n.name,`params[${e}].name`);if(!o||!Ae.test(o))throw new Error(`params[${e}].name must match ${Ae}`);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=Gt(n.label,`params[${e}].label`),c=Gt(n.help,`params[${e}].help`),l=n.required===!0,u=Li(n.min,`params[${e}].min`),p=Li(n.max,`params[${e}].max`),d=n.default;if(d!=null&&typeof d!="string"&&typeof d!="number"&&typeof d!="boolean")throw new Error(`params[${e}].default must be a scalar`);return{name:o,type:i,...a?{label:a}:{},...c?{help:c}:{},...l?{required:!0}:{},...s?{enum:s}:{},...u!==void 0?{min:u}:{},...p!==void 0?{max:p}:{},...d!=null?{default:d}:{}}}function mc(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 Ae,dh,ph,pc,lc,uc,dc,Ui=k(()=>{"use strict";Ae=/^[A-Z][A-Z0-9_]*$/,dh=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),ph=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];pc=600,lc=/^[a-z0-9-]+$/,uc=32,dc=64});function wc(t=mh){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...wc(r.groups));return e}function gh(t,e){let r=JSON.stringify(e);return wc().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function bc(t){let e=gh(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.type==="string"&&e.mustContain&&!i.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:e.maxLength!==void 0&&i.length>e.maxLength?{ok:!1,error:`${e.id} must be \u2264 ${e.maxLength} chars`}:{ok:!0,field:e,value:i}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}case"string_map":{if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,error:`${e.id} must be a name\u2192value map`};let i=Object.entries(r);if(i.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(i.length>gc)return{ok:!1,error:`${e.id} must have \u2264 ${gc} entries`};let s={};for(let[a,c]of i){if(!Ae.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Ae}`};if(bt(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>hc)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${hc} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var gc,hc,yc,mh,kc=k(()=>{"use strict";Ui();_i();Di();gc=64,hc=2e3,yc=2e3,mh=[{id:"branch",label:"Branch",help:"Task-branch naming.",fields:[{id:"branch.pattern",file:"project.yaml",path:["branch","pattern"],type:"string",label:"Task-branch pattern",nullable:!0,mustContain:"<TASK_ID>",help:"Template for the per-task branch name. Must contain the <TASK_ID> placeholder. Empty \u21D2 default codepipe/<TASK_ID>."}]},{id:"llm",label:"LLM",fields:[{id:"llm.provider",file:"regimen.yaml",path:["llm","provider"],type:"enum",label:"Provider",nullable:!1,suggestions:[...sc],help:"LLM backend for this project. Currently only claude is available."}],groups:[{id:"llm.models",label:"Models by role",help:"Model per pipeline stage. Empty \u21D2 the role's recommended default applies.",fields:[{id:"llm.models.default",file:"regimen.yaml",path:["llm","models","default"],type:"model",label:"default (catch-all)",nullable:!0,suggestions:[...Ni],help:"Overrides the recommended defaults for every role not listed below."},...oc.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Ni],help:`recommended: ${Oi[t]}`}))]}]},{id:"apply.style",label:"Commits & PRs",help:"Instructions for the AI agent on how to write commit messages and PR descriptions. Empty \u21D2 built-in templates.",fields:[{id:"apply.commit_style",file:"project.yaml",path:["apply","commit_style"],type:"string",label:"Commit message style",nullable:!0,multiline:!0,maxLength:yc,help:'e.g. "English, imperative mood, first line \u2264 72 chars, start with the issue key". Empty \u21D2 "<KEY>: <task title>".'},{id:"apply.pr_style",file:"project.yaml",path:["apply","pr_style"],type:"string",label:"PR description style",nullable:!0,multiline:!0,maxLength:yc,help:'e.g. "Russian, implementation details, bullet list of what was done". Empty \u21D2 the default PR body.'}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (on by default; orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on (default), a task taken from Develop waits in the QUEUE for a single Confirm before the pipeline starts \u2014 the Confirm pulls in dependency closure and topologically orders the queue. Off \u21D2 conveyor: the task starts the pipeline immediately."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]},{id:"implementation",label:"Implementation",help:"How a dependency cluster is serialized into branches and PRs.",fields:[{id:"implementation.mode",file:"regimen.yaml",path:["implementation","mode"],type:"enum",label:"Implementation mode",nullable:!0,suggestions:["cluster-pr","sequential","parallel"],help:"cluster-pr (default for new projects) \u2014 one shared branch and a single PR per dependency cluster; a lone task is a cluster of one. sequential / parallel are an explicit opt-out of that. Clearing removes the key from regimen.yaml but keeps the mode already stored for the project (it is not reset to the default)."}]}]});var $c=k(()=>{"use strict"});var vc=k(()=>{"use strict"});var xc=k(()=>{"use strict"});function Sc(t){return`codepipe-host-${t}`}var Rc=k(()=>{"use strict"});function Tc(t){return!(!t||t.length>250||!/^[A-Za-z0-9._/-]+$/.test(t)||/^[-/.]/.test(t)||/[/.]$/.test(t)||t.endsWith(".lock")||t.includes("..")||t.includes("//")||t.includes("/."))}function dt(t){return`${t}${hh}`}var Kt,hh,Ic=k(()=>{"use strict";Kt=/^[a-z][a-z0-9-]{1,30}$/,hh="-codepipe-ctx"});var Cc=k(()=>{"use strict"});var Ec=k(()=>{"use strict"});function ur(t){for(let e of yh){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var yh,Pc=k(()=>{"use strict";yh=[{name:"rework",pattern:/^@(?:codepipe|devpipe)\s+rework:\s*(.+)$/im,description:"Send the task back to ANALYZING with a new instruction.",hasArg:!0},{name:"approve",pattern:/^@(?:codepipe|devpipe)\s+approve\s*$/im,description:"Merge every PR for this task (TRACKING only)."},{name:"reject",pattern:/^@(?:codepipe|devpipe)\s+reject(?::\s*(.+))?\s*$/im,description:"Abandon this task: close any open PR(s) and move it to DONE (reason rejected_and_closed). Valid from any non-terminal phase; from early phases it just skips the task.",hasArg:!0},{name:"merge",pattern:/^@(?:codepipe|devpipe)\s+merge\s*$/im,description:"Merge the task branch into the default branch without a PR (direct apply path, apply.pull_request=false; TRACKING only)."},{name:"rebase",pattern:/^@(?:codepipe|devpipe)\s+rebase\s*$/im,description:"Re-apply the patch on top of the latest base branch and force-push. Use after a PR merge conflict or APPLYING failure."},{name:"update",pattern:/^@(?:codepipe|devpipe)\s+update(?::\s*(.+))?\s*$/im,description:"Update a conflicting PR: resolve conflicts against the current base branch (TRACKING only). Optional `: <instruction>` is forwarded to the agent.",hasArg:!0},{name:"apply",pattern:/^@(?:codepipe|devpipe)\s+apply:\s*(local|auto)\s*$/im,description:"Override apply mode for this task: local (you apply by hand) or auto.",hasArg:!0}]});var Ac=k(()=>{"use strict"});var jc=k(()=>{"use strict"});var _c=k(()=>{"use strict"});function Nc(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function Dc(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=Nc(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(dr.test(r))return r;let n=Nc(t);return dr.test(n)?n:Mi}function Lc(t,e){let r=new Set([...e].map(n=>n.toUpperCase()));if(!r.has(t.toUpperCase()))return t;for(let n=1;n<1e4;n++){let o=String(n),i=t.slice(0,10-o.length)+o;if(!r.has(i.toUpperCase()))return i}return t}function cn(t){return`tasks/${t}/issue.yaml`}var Oc,ro,Mi,dr,Bi,ZS,no,an,Uc=k(()=>{"use strict";Oc=["bug","feature","epic"],ro="feature",Mi="TASK",dr=/^[A-Z][A-Z0-9]{1,9}$/;Bi={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},ZS=Bi.backlog,no="tracker/config.yaml",an="tracker/counter"});var Mc=k(()=>{"use strict"});function pr(t){let e=t.match(/^git@([^:/]+):/);if(e)return e[1]??null;let r=t.match(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)/);if(r)return r[1]??null;let n=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return n?n[1]??null:null}function oo(t){switch(t){case ln.gitlab:return"oauth2";case ln.bitbucket:return"x-token-auth";default:return"x-access-token"}}var ln,Ht,Bc=k(()=>{"use strict";ln={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Ht="x-bitbucket-api-token-auth"});var Fc=k(()=>{"use strict"});var Gc=k(()=>{"use strict";Mc();Bc();Fc()});var Kc,W=k(()=>{"use strict";Ua();Ma();Ha();tc();rc();nc();_i();Di();kc();Ui();$c();vc();xc();Rc();Ic();Cc();Ec();Pc();Ac();jc();_c();Uc();Gc();Kc=20});function K(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var ke=k(()=>{"use strict"});import{existsSync as Hc,renameSync as wh}from"node:fs";function Wt(t,e,r=n=>console.error(n)){if(Hc(e)||!Hc(t))return!1;try{return wh(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 io=k(()=>{"use strict"});import{existsSync as so,readFileSync as Wc,readdirSync as bh,writeFileSync as kh}from"node:fs";import{dirname as $h,join as kt}from"node:path";import{parse as vh}from"yaml";function xh(t=process.cwd()){let e=t;for(;;){if(so(kt(e,et,"project.yaml")))return e;if(so(kt(e,Fi,"project.yaml")))return Wt(kt(e,Fi),kt(e,et))&&Rh(e),e;let r=$h(e);if(r===e)return null;e=r}}function Sh(t){let e=kt(t,et);return so(e)?e:kt(t,Fi)}function Rh(t){let e=kt(t,".gitignore");if(!so(e))return;let r=Wc(e,"utf-8"),n=r.split(/\r?\n/).map(o=>{let i=o.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?o.replace(".devpipe",".codepipe"):o}).join(`
|
|
8
|
+
`);n!==r&&kh(e,n)}function $e(t=process.cwd()){let e=xh(t);if(!e)return null;let r=Sh(e),n=Th(Wc(kt(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function Yc(t,e,r){return bh(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 ao(t,e=process.cwd()){try{let r=$e(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function Th(t){let e=vh(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),n=String(e.name??r),o=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of o){if(!s||typeof s!="object")continue;let a=s,c=String(a.repo??a.repoName??""),l=String(a.name??c);if(!l||!c)continue;let u=a.host,p=u==="bitbucket"?"bitbucket":u==="gitlab"?"gitlab":"github";i.push({name:l,host:p,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l)})}return{projectId:r,name:n,repos:i}}function qc(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 et,Fi,tt=k(()=>{"use strict";io();et=".codepipe",Fi=".devpipe"});import{homedir as Vc}from"node:os";import{mkdirSync as Ih,readFileSync as Ch,writeFileSync as Eh,existsSync as Gi}from"node:fs";import{dirname as Jc,join as co,resolve as Ph}from"node:path";import{fileURLToPath as Ah}from"node:url";function Xc(t){let e=co(zc,".env");if(Gi(e)&&process.loadEnvFile(e),t){let r=co(zc,"profiles",t,".env");Gi(r)&&process.loadEnvFile(r)}}function fr(t){let e=K("CONFIG");return e||(t?co(Vc(),".codepipe","profiles",t,"config.json"):co(Vc(),".codepipe","config.json"))}function Fe(t){let e=fr(t);if(!Gi(e))return null;let r=Ch(e,"utf-8");return JSON.parse(r)}function pt(t,e){let r=fr(e);Ih(Jc(r),{recursive:!0}),Eh(r,JSON.stringify(t,null,2)+`
|
|
9
|
+
`,{mode:384})}function lo(t){if(t)return{cfg:je(t),profile:t};let e;try{e=$e()?.spec.projectId||void 0}catch{}if(e){let r=Fe(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:je(void 0),profile:void 0}}function je(t){let e=Fe(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 ${fr(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var zc,Te=k(()=>{"use strict";ke();tt();zc=Ph(Jc(Ah(import.meta.url)),"..")});import{homedir as tl}from"node:os";import{existsSync as rl,mkdirSync as nl,readFileSync as ol,writeFileSync as il}from"node:fs";import{dirname as sl,join as al}from"node:path";function cl(t,e,r){let n=F(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},X(n)}function ll(t,e){let r=F(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],X(r),!0)}function ul(t){return Object.keys(F(t)?.secrets??{}).sort()}function uo(t,e,r){let n=F(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,X(n),"pinned")}function dl(t,e){let r=F(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],X(r),!0):!1}function rt(t){return al(tl(),".codepipe","secrets",`${t}.json`)}function F(t){let e=rt(t);return rl(e)?JSON.parse(ol(e,"utf-8")):null}function X(t){let e=rt(t.projectId);nl(sl(e),{recursive:!0}),il(e,JSON.stringify(t,null,2)+`
|
|
10
|
+
`,{mode:384})}function po(){return al(tl(),".codepipe","shared.json")}function Ki(){let t=po();return rl(t)?JSON.parse(ol(t,"utf-8")):null}function pl(t){let e=po();nl(sl(e),{recursive:!0}),il(e,JSON.stringify(t,null,2)+`
|
|
11
|
+
`,{mode:384})}function mr(t){let e=F(t)?.claude?.oauthToken;return e||Ki()?.claude?.oauthToken}function un(t){let e={GH_TOKEN:t.github?.token,BITBUCKET_EMAIL:t.bitbucket?.email,BITBUCKET_API_TOKEN:t.bitbucket?.apiToken,GITLAB_TOKEN:t.gitlab?.token,YOUTRACK_URL:t.youtrack?.url,YOUTRACK_TOKEN:t.youtrack?.token};for(let r of Hi){let n=e[r];n&&!process.env[r]&&(process.env[r]=n)}}function gr(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var Hi,oe=k(()=>{"use strict";Hi=["GH_TOKEN","BITBUCKET_EMAIL","BITBUCKET_API_TOKEN","GITLAB_TOKEN","YOUTRACK_URL","YOUTRACK_TOKEN"]});import{appendFileSync as jh,existsSync as ml,mkdirSync as _h,renameSync as gl,statSync as Nh,unlinkSync as Oh}from"node:fs";import{Writable as Dh}from"node:stream";import{join as Lh}from"node:path";function fo(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=Uh(process.env[`${t}_MAX_BYTES`]??String(hl.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):hl.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function Uh(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 mo(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(Mh(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 Mh(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:Bh(o)).join(" ");return`${r} ${t} ${n}`}function Bh(t){try{return JSON.stringify(t)}catch{return String(t)}}var hl,hr,Wi=k(()=>{"use strict";hl={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},hr=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&_h(e.dir,{recursive:!0}),this.currentPath=Lh(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
|
|
10
12
|
`)?e:e+`
|
|
11
|
-
`;
|
|
12
|
-
`+t.slice(t.length-e)}async function yt(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),io);try{let i;try{i=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new Ae(`cannot reach api.github.com (${l instanceof Error?l.message:String(l)})`)}if(i.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(so(i.status))throw new Ae(`api.github.com \u2192 ${i.status} ${i.statusText}`);if(!i.ok)throw new Error(`GitHub \u2192 ${i.status} ${i.statusText}`);let a=(await i.json()).login??"ok",c=i.headers.get("x-oauth-scopes");if(c!==null&&e&&!c.split(",").map(u=>u.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${c||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let l;try{let u=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});u.ok&&(l=(await u.json()).type)}catch{}if(l==="Organization"){let u=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});if(u.status===403)throw new Error(`token cannot access org "${e.owner}" (403) \u2014 for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens; for classic PATs: verify 'repo' or 'admin:org' scope`);if(u.status===404)throw new Error(`org "${e.owner}" not found or not visible to this token \u2014 check the org name; for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens`);if(!u.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${u.status} ${u.statusText}`)}}return a}finally{clearTimeout(o)}}async function ao(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),io);try{let s;try{s=await fetch(n,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},signal:o.signal})}catch(c){throw new Ae(`cannot reach api.github.com (${c instanceof Error?c.message:String(c)})`)}if(s.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(s.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(so(s.status))throw new Ae(`api.github.com \u2192 ${s.status} ${s.statusText}`);if(!s.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${s.status} ${s.statusText}`);if((await s.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}finally{clearTimeout(i)}}async function wt(t,e,r){let n=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",o=new AbortController,i=setTimeout(()=>o.abort(),io);try{let s;try{s=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new Ae(`cannot reach api.bitbucket.org (${c instanceof Error?c.message:String(c)})`)}if(s.ok)return t;if(s.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;if(so(s.status))throw new Ae(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await Kg(s);throw s.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${a})`):s.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${a})`):s.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${a})`):new Error(`Bitbucket \u2192 ${s.status} ${s.statusText}${a}`)}finally{clearTimeout(i)}}async function Kg(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function co(t,e,r,n){let o;try{o=await fetch(`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}/${encodeURIComponent(n)}/pullrequests?pagelen=1`,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch{return}if(o.status!==403)return;let i={};try{i=await o.json()}catch{}let s=i.error?.detail?.granted;if(Array.isArray(s)){let c=Jc.filter(l=>!s.includes(l));return c.length===0?void 0:`token lacks scope(s) ${c.join(", ")} \u2014 the pipeline would fail at PR time; re-create the API token with all of: ${Jc.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function kt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),io);try{let n;try{n=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"},signal:e.signal})}catch(i){throw new Ae(`cannot reach gitlab.com (${i instanceof Error?i.message:String(i)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(so(n.status))throw new Ae(`gitlab.com \u2192 ${n.status} ${n.statusText}`);if(!n.ok)throw new Error(`GitLab \u2192 ${n.status} ${n.statusText}`);return(await n.json()).username??"ok"}finally{clearTimeout(r)}}async function Xc(t){try{let e=await fetch("https://gitlab.com/api/v4/personal_access_tokens/self",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}});if(!e.ok)return;let n=(await e.json()).scopes??[];return n.length>0&&!n.includes("api")?`GitLab token scopes [${n.join(", ")}] lack 'api' \u2014 CodePipe can read and push, but cannot create a Context Repo or scaffold its files`:void 0}catch{return}}function Hg(t){switch(t){case"running":case"pending":case"created":case"waiting_for_resource":case"preparing":case"scheduled":return"running";case"success":return"success";case"failed":case"canceled":case"cancelled":return"failed";default:return"none"}}function _i(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 Me(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new Oi(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new Ni(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new Li(e)}return new Di}var Kt,Ae,io,Jc,Ni,Oi,Li,Di,bt=k(()=>{"use strict";Kt=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},Ae=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},io=5e3;Jc=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];Ni=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 Kt(`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()}`)}},Oi=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 Kt(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),a=!1,c=!1,l=!1;if(i.ok){let u=await i.json();for(let p of u.check_runs??[])l=!0,p.status!=="completed"?a=!0:p.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(p.conclusion)&&(c=!0)}if(s.ok){let u=await s.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${o}/pulls/${r}`,{headers:n});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${o}/actions/runs?head_sha=${a}&per_page=20`,{headers:n});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],u=[];for(let p of l.filter(d=>d.conclusion&&i.includes(d.conclusion))){let d=await fetch(`${o}/actions/runs/${p.id}/jobs?per_page=50`,{headers:n});if(!d.ok)continue;let m=(await d.json()).jobs??[];for(let f of m.filter(g=>g.conclusion==="failure")){let g=await fetch(`${o}/actions/jobs/${f.id}/logs`,{headers:n});if(!g.ok)continue;let y=await g.text();u.push(`### CI job: ${f.name}
|
|
13
|
-
|
|
14
|
-
${
|
|
15
|
-
|
|
16
|
-
`),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()}`)}},
|
|
17
|
-
`)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function Vg(t,e,r){return new Promise((n,o)=>{let i=$t.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 el(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function Ui(t,e,r){return new Promise(n=>{let o=$t.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 zg(t){try{let e=await fetch(t);return e.ok?new el(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function il(t,e=443,r=rl){let n=`${t}:${e}`,o=Zc.get(n);if(o)return o;let i=Jg(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Zc.set(n,i),i}async function Jg(t,e,r){if(!tl)return!1;let n=8e3;if(await Ui(t,e,n))return!0;let o=await Vg(t,e,n),i=$t.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=qg(o);if(!c)break;let l=await zg(c);if(!l)break;if(s.push(l.toString()),$t.setDefaultCACertificates([...i,...s]),await Ui(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 Ui(t,e,n)}var tl,Qc,Zc,rl,sl=k(()=>{"use strict";ke();tl=typeof $t.getCACertificates=="function"&&typeof $t.setDefaultCACertificates=="function",Qc=!1,Zc=new Map,rl=t=>console.warn(t)});function ul(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function je(t,e,r){nl();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(ol(s)&&await il(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function Xg(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Qg(){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 Bi(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=Qg(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await je(t,r,n)}catch(u){a=new Error(`${e}: ${u instanceof Error?u.message:String(u)}`)}if(l){if(l.ok)return l;let u=await l.text();if(c<o&&Xg(l.status,u)){await al(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await al(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function vt(t){let e;try{e=await je(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 dl(t){try{let e=await je(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function Zg(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=cl.get(o);if(i)return i;let s=await je(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!s.ok)throw new Error(`yt resolveStateId ${e}: ${s.status} ${await s.text()}`);let c=(await s.json()).customFields.find(u=>u.name===n);if(!c)throw new Error(`yt: issue ${e} has no ${n} custom field`);let l=c.projectCustomField.bundle.values.find(u=>u.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${n} bundle for ${e}`);return cl.set(o,l.id),l.id}async function pl(t,e,r,n=sn){let o=await Zg(t,e,r,n);await Bi(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 fl(t,e,r){return await(await Bi(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function ml(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await Bi(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function gl(t,e){let r=ll.get(e);if(r)return r;let n=await je(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 ll.set(e,i.id),i.id}async function hl(t,e,r,n,o,i=sn){let s=await gl(t,e),a=await je(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 yl(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await je(t,"/api/commands",{method:"POST",body:JSON.stringify({query:o,issues:[{idReadable:e}]})});if(!i.ok)throw new Error(`yt applyIssueLink (${o} on ${e}): ${i.status} ${await i.text()}`)}function bl(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 $l(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 vl(t,e){let r=e.stageField??sn,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=${kl}&$top=200`,s=await je(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>Tl(c,r))}async function xl(t,e,r=sn){let n=`/api/issues/${encodeURIComponent(e)}?fields=${kl}`,o=await je(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Tl(await o.json(),r)}async function Sl(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${th}&$top=500`,o=await je(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=bl(s.attachments);return c&&(a.attachments=c),a})}function rh(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 Tl(t,e=sn){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=bl(t.attachments);a&&(s.attachments=a);let c=rh(t.links);return c&&(s.links=c),s}async function Rl(t,e){let r=await nh(t,e);return r.length>0?r:oh(t,e)}async function nh(t,e){let r=await gl(t,e),n=await je(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:Il(s.bundle)});return i}async function oh(t,e){let r=`project: ${e}`,n=await je(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:Il(s.projectCustomField?.bundle)});return i}function Il(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var al,sn,cl,ll,wl,eh,kl,th,Ht=k(()=>{"use strict";sl();al=t=>new Promise(e=>setTimeout(e,t));sn="Stage",cl=new Map;ll=new Map;wl="attachments(id,name,url,size,mimeType)",eh="links(direction,linkType(name),issues(idReadable))",kl=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${wl},${eh}`,th=`id,text,created,author(login),${wl}`});function Ge(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function fr(t){return t instanceof Ae}async function Cl(t,e){let r=B(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 vt({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:Ge(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:Ge(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 yt(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){fr(c)?(n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"github",ok:!1,detail:Ge(c)}),o.push({kind:"github",present:!0,ok:!1,detail:Ge(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 wt(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){fr(c)?(n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"bitbucket",ok:!1,detail:Ge(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:Ge(c),checkedAt:i()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await kt(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){fr(c)?(n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"gitlab",ok:!1,detail:Ge(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:Ge(c),checkedAt:i()}))}}else o.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||n.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let u of e?.repos??[])if(u.host==="github")try{await ao(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){fr(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:Ge(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await ao(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){fr(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:Ge(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await ao(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){fr(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:i()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:Ge(l),checkedAt:i()})}else o.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:i()})}else o.push({kind:"contextWrite",present:!1,checkedAt:i()});let a=ur(t);if(!a)n.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),o.push({kind:"claude",present:!1,checkedAt:i()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:i()});else{let c=await xt(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 xt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});return n.status===200?"valid":n.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}async function El(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1000",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});if(n.status!==200)return null;let i=(await n.json())?.data;if(!Array.isArray(i))return null;let s=[];for(let a of i){let c=a?.id;if(typeof c!="string"||c.trim().length===0)continue;let l=a?.created_at;s.push({id:c,...typeof l=="string"?{createdAt:l}:{}})}return s}catch{return null}finally{clearTimeout(r)}}var mr=k(()=>{"use strict";re();bt();Ht()});import ih from"node:http";import Mi from"node:crypto";function lo(){let t=Gi(Mi.randomBytes(32)),e=Gi(Mi.createHash("sha256").update(t).digest()),r=Gi(Mi.randomBytes(32));return{verifier:t,challenge:e,state:r}}function Ki(t){let e=new URL(sh);return e.search=new URLSearchParams({response_type:"code",client_id:Pl,redirect_uri:t.redirectUri,scope:ch,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function uh(t,e){let r=t.get("error");if(r)throw new Error(`oauth-error: ${r}`);if(t.get("state")!==e)throw new Error("state-mismatch");let n=t.get("code");if(!n)throw new Error("no-code");return n}function Al(t,e){let[r,n]=t.trim().split("#");if(!r)throw new Error("no-code");if(n!==void 0&&n!==e)throw new Error("state-mismatch");return r}function dh(t){let e=t,r=e?.access_token;if(!r||typeof r!="string")throw new Error(`no access_token in response: ${JSON.stringify(t)}`);return{oauthToken:r,...typeof e.refresh_token=="string"?{refreshToken:e.refresh_token}:{},...typeof e.expires_in=="number"?{expiresIn:e.expires_in}:{}}}async function Hi(t){let e=await fetch(ah,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:t.code,state:t.state,redirect_uri:t.redirectUri,client_id:Pl,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return dh(await e.json())}async function Wi(t){let e=t.timeoutMs??lh,r=ih.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=Ki({redirectUri:o,challenge:t.challenge,state:t.state}),s,a=new Promise((l,u)=>{s=setTimeout(()=>u(new Error("no-callback")),e),r.on("request",(p,d)=>{let m=new URL(p.url??"/",o);if(m.pathname!=="/callback"){d.statusCode=404,d.end();return}clearTimeout(s),d.setHeader("content-type","text/html"),d.end("<h3>Authorized \u2014 you can close this tab.</h3>");try{l(uh(m.searchParams,t.state))}catch(f){u(f)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>Hi({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function jl(t){let e=await Wi(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
|
|
18
|
-
${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var
|
|
19
|
-
${l.trim()}`)}}let i=
|
|
20
|
-
${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function
|
|
21
|
-
${w.trim()}`)}}let g=(await t.revparse(["HEAD"])).trim(),y=r.push!==!1;if(y){let
|
|
22
|
-
${
|
|
13
|
+
`;jh(this.currentPath,r,"utf-8")}asWritable(){return new Dh({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||!ml(this.currentPath)||Nh(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;ml(n)&&(r>=this.cfg.maxFiles?Oh(n):gl(n,`${this.currentPath}.${r+1}`))}gl(this.currentPath,`${this.currentPath}.1`)}}}});import{createHash as Fh}from"node:crypto";import{existsSync as Gh,readFileSync as Kh}from"node:fs";import{homedir as Hh,hostname as Yi}from"node:os";import{join as Wh}from"node:path";function yl(t){return Fh("sha256").update(t).digest("hex").slice(0,12)}function Yh(){let t=K("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=Wh(Hh(),".claude","credentials.json");if(!Gh(e))return;let r=JSON.parse(Kh(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 wl(t){let e=Yh(),r=K("ACCOUNT_ID")?.trim(),n=K("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=mr(t);return o?{accountId:`acct-${yl(o)}`,label:n||Yi(),...e?{email:e}:{}}:{accountId:`acct-${yl(`host:${Yi()}`)}`,label:n||Yi(),...e?{email:e}:{}}}var bl=k(()=>{"use strict";ke();oe()});function ho(t){return t===429||t>=500}function kl(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
|
|
14
|
+
`+t.slice(t.length-e)}async function $t(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),go);try{let i;try{i=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new _e(`cannot reach api.github.com (${l instanceof Error?l.message:String(l)})`)}if(i.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(ho(i.status))throw new _e(`api.github.com \u2192 ${i.status} ${i.statusText}`);if(!i.ok)throw new Error(`GitHub \u2192 ${i.status} ${i.statusText}`);let a=(await i.json()).login??"ok",c=i.headers.get("x-oauth-scopes");if(c!==null&&e&&!c.split(",").map(u=>u.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${c||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let l;try{let u=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});u.ok&&(l=(await u.json()).type)}catch{}if(l==="Organization"){let u=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});if(u.status===403)throw new Error(`token cannot access org "${e.owner}" (403) \u2014 for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens; for classic PATs: verify 'repo' or 'admin:org' scope`);if(u.status===404)throw new Error(`org "${e.owner}" not found or not visible to this token \u2014 check the org name; for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens`);if(!u.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${u.status} ${u.statusText}`)}}return a}finally{clearTimeout(o)}}async function yo(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),go);try{let s;try{s=await fetch(n,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},signal:o.signal})}catch(c){throw new _e(`cannot reach api.github.com (${c instanceof Error?c.message:String(c)})`)}if(s.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(s.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(ho(s.status))throw new _e(`api.github.com \u2192 ${s.status} ${s.statusText}`);if(!s.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${s.status} ${s.statusText}`);if((await s.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}finally{clearTimeout(i)}}async function vt(t,e,r){let n=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",o=new AbortController,i=setTimeout(()=>o.abort(),go);try{let s;try{s=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new _e(`cannot reach api.bitbucket.org (${c instanceof Error?c.message:String(c)})`)}if(s.ok)return t;if(s.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;if(ho(s.status))throw new _e(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await qh(s);throw s.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${a})`):s.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${a})`):s.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${a})`):new Error(`Bitbucket \u2192 ${s.status} ${s.statusText}${a}`)}finally{clearTimeout(i)}}async function qh(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function wo(t,e,r,n){let o;try{o=await fetch(`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}/${encodeURIComponent(n)}/pullrequests?pagelen=1`,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch{return}if(o.status!==403)return;let i={};try{i=await o.json()}catch{}let s=i.error?.detail?.granted;if(Array.isArray(s)){let c=$l.filter(l=>!s.includes(l));return c.length===0?void 0:`token lacks scope(s) ${c.join(", ")} \u2014 the pipeline would fail at PR time; re-create the API token with all of: ${$l.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function xt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),go);try{let n;try{n=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"},signal:e.signal})}catch(i){throw new _e(`cannot reach gitlab.com (${i instanceof Error?i.message:String(i)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(ho(n.status))throw new _e(`gitlab.com \u2192 ${n.status} ${n.statusText}`);if(!n.ok)throw new Error(`GitLab \u2192 ${n.status} ${n.statusText}`);return(await n.json()).username??"ok"}finally{clearTimeout(r)}}async function vl(t){try{let e=await fetch("https://gitlab.com/api/v4/personal_access_tokens/self",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}});if(!e.ok)return;let n=(await e.json()).scopes??[];return n.length>0&&!n.includes("api")?`GitLab token scopes [${n.join(", ")}] lack 'api' \u2014 CodePipe can read and push, but cannot create a Context Repo or scaffold its files`:void 0}catch{return}}function Vh(t){switch(t){case"running":case"pending":case"created":case"waiting_for_resource":case"preparing":case"scheduled":return"running";case"success":return"success";case"failed":case"canceled":case"cancelled":return"failed";default:return"none"}}function qi(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 Ge(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new zi(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new Vi(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new Ji(e)}return new Xi}var Yt,_e,go,$l,Vi,zi,Ji,Xi,St=k(()=>{"use strict";Yt=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},_e=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},go=5e3;$l=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];Vi=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 Yt(`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()}`)}},zi=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 Yt(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),a=!1,c=!1,l=!1;if(i.ok){let u=await i.json();for(let p of u.check_runs??[])l=!0,p.status!=="completed"?a=!0:p.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(p.conclusion)&&(c=!0)}if(s.ok){let u=await s.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${o}/pulls/${r}`,{headers:n});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${o}/actions/runs?head_sha=${a}&per_page=20`,{headers:n});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],u=[];for(let p of l.filter(d=>d.conclusion&&i.includes(d.conclusion))){let d=await fetch(`${o}/actions/runs/${p.id}/jobs?per_page=50`,{headers:n});if(!d.ok)continue;let m=(await d.json()).jobs??[];for(let f of m.filter(g=>g.conclusion==="failure")){let g=await fetch(`${o}/actions/jobs/${f.id}/logs`,{headers:n});if(!g.ok)continue;let y=await g.text();u.push(`### CI job: ${f.name}
|
|
15
|
+
|
|
16
|
+
${kl(y,8e3)}`)}}return u.length===0?void 0:kl(u.join(`
|
|
17
|
+
|
|
18
|
+
`),16e3)}catch{return}}async mergePR(e,r,n,o){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},Ji=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 Yt(`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=Vh(i.head_pipeline?.status??i.pipeline?.status),a=i.merge_status==="cannot_be_merged"||i.has_conflicts===!0?"conflict":i.merge_status==="can_be_merged"&&i.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:s,mergeable:a}}async mergePR(e,r,n,o){let i=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,s,a=await fetch(i,{headers:this.headers()});if(a.ok){let u=await a.json().catch(()=>null);s=u?.sha??u?.diff_refs?.head_sha}let c=await fetch(`${i}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:n==="squash",should_remove_source_branch:o,...s?{sha:s}:{}})});if(!c.ok)throw new Error(`gitlab merge MR !${r}: ${c.status} ${await c.text()}`);let l=await c.json().catch(()=>null);return l?.merge_commit_sha?{mergedSha:l.merge_commit_sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`gitlab comment MR !${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!o.ok)throw new Error(`gitlab close MR !${r}: ${o.status} ${await o.text()}`)}};Xi=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(qi(e,r,"merge"))}async closePR(e,r,n){throw new Error(qi(e,r,"close"))}async addPRComment(e,r,n){throw new Error(qi(e,r,"comment"))}}});import{X509Certificate as Rl}from"node:crypto";import{readFileSync as zh}from"node:fs";import Rt from"node:tls";function Jh(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function Cl(t=Il){if(xl)return;xl=!0;let e=K("EXTRA_CA_FILE");if(!(!e||!Tl))try{let r=Jh(zh(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Rt.setDefaultCACertificates([...Rt.getCACertificates(),...r]),t(`[tls] trusting ${r.length} extra CA cert(s) from ${e}`)}catch(r){t(`[tls] failed to load CODEPIPE_EXTRA_CA_FILE ${e}: ${r instanceof Error?r.message:String(r)}`)}}function El(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 Xh(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
|
|
19
|
+
`)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function Qh(t,e,r){return new Promise((n,o)=>{let i=Rt.connect({host:t,port:e,servername:t,rejectUnauthorized:!1},()=>{let s=i.getPeerCertificate(!0),a=new Set;for(;s?.issuerCertificate&&s.issuerCertificate!==s&&s.fingerprint256&&!a.has(s.fingerprint256);)a.add(s.fingerprint256),s=s.issuerCertificate;let c=s?.raw?new Rl(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function Qi(t,e,r){return new Promise(n=>{let o=Rt.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{o.end(),n(!0)});o.on("error",()=>n(!1)),o.setTimeout(r,()=>{o.destroy(),n(!1)})})}async function Zh(t){try{let e=await fetch(t);return e.ok?new Rl(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Pl(t,e=443,r=Il){let n=`${t}:${e}`,o=Sl.get(n);if(o)return o;let i=ey(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Sl.set(n,i),i}async function ey(t,e,r){if(!Tl)return!1;let n=8e3;if(await Qi(t,e,n))return!0;let o=await Qh(t,e,n),i=Rt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=Xh(o);if(!c)break;let l=await Zh(c);if(!l)break;if(s.push(l.toString()),Rt.setDefaultCACertificates([...i,...s]),await Qi(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 Qi(t,e,n)}var Tl,xl,Sl,Il,Al=k(()=>{"use strict";ke();Tl=typeof Rt.getCACertificates=="function"&&typeof Rt.setDefaultCACertificates=="function",xl=!1,Sl=new Map,Il=t=>console.warn(t)});function Ol(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function Ne(t,e,r){Cl();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(El(s)&&await Pl(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function ty(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function ry(){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 Zi(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=ry(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await Ne(t,r,n)}catch(u){a=new Error(`${e}: ${u instanceof Error?u.message:String(u)}`)}if(l){if(l.ok)return l;let u=await l.text();if(c<o&&ty(l.status,u)){await jl(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await jl(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Tt(t){let e;try{e=await Ne(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 Dl(t){try{let e=await Ne(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function ny(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=_l.get(o);if(i)return i;let s=await Ne(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!s.ok)throw new Error(`yt resolveStateId ${e}: ${s.status} ${await s.text()}`);let c=(await s.json()).customFields.find(u=>u.name===n);if(!c)throw new Error(`yt: issue ${e} has no ${n} custom field`);let l=c.projectCustomField.bundle.values.find(u=>u.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${n} bundle for ${e}`);return _l.set(o,l.id),l.id}async function Ll(t,e,r,n=dn){let o=await ny(t,e,r,n);await Zi(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 Ul(t,e,r){return await(await Zi(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function Ml(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await Zi(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function Bl(t,e){let r=Nl.get(e);if(r)return r;let n=await Ne(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 Nl.set(e,i.id),i.id}async function Fl(t,e,r,n,o,i=dn){let s=await Bl(t,e),a=await Ne(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 Gl(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await Ne(t,"/api/commands",{method:"POST",body:JSON.stringify({query:o,issues:[{idReadable:e}]})});if(!i.ok)throw new Error(`yt applyIssueLink (${o} on ${e}): ${i.status} ${await i.text()}`)}function Wl(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 Yl(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 ql(t,e){let r=e.stageField??dn,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=${Hl}&$top=200`,s=await Ne(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>Jl(c,r))}async function Vl(t,e,r=dn){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Hl}`,o=await Ne(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Jl(await o.json(),r)}async function zl(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${iy}&$top=500`,o=await Ne(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=Wl(s.attachments);return c&&(a.attachments=c),a})}function sy(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 Jl(t,e=dn){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=Wl(t.attachments);a&&(s.attachments=a);let c=sy(t.links);return c&&(s.links=c),s}async function Xl(t,e){let r=await ay(t,e);return r.length>0?r:cy(t,e)}async function ay(t,e){let r=await Bl(t,e),n=await Ne(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:Ql(s.bundle)});return i}async function cy(t,e){let r=`project: ${e}`,n=await Ne(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:Ql(s.projectCustomField?.bundle)});return i}function Ql(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var jl,dn,_l,Nl,Kl,oy,Hl,iy,qt=k(()=>{"use strict";Al();jl=t=>new Promise(e=>setTimeout(e,t));dn="Stage",_l=new Map;Nl=new Map;Kl="attachments(id,name,url,size,mimeType)",oy="links(direction,linkType(name),issues(idReadable))",Hl=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Kl},${oy}`,iy=`id,text,created,author(login),${Kl}`});function Ke(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function yr(t){return t instanceof _e}async function Zl(t,e){let r=F(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 Tt({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:Ke(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:Ke(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 $t(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){yr(c)?(n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"github",ok:!1,detail:Ke(c)}),o.push({kind:"github",present:!0,ok:!1,detail:Ke(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 vt(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){yr(c)?(n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"bitbucket",ok:!1,detail:Ke(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:Ke(c),checkedAt:i()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await xt(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){yr(c)?(n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"gitlab",ok:!1,detail:Ke(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:Ke(c),checkedAt:i()}))}}else o.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||n.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let u of e?.repos??[])if(u.host==="github")try{await yo(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){yr(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:Ke(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await yo(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){yr(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:Ke(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await yo(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){yr(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:i()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:Ke(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=mr(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 It(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 It(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});return n.status===200?"valid":n.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}async function eu(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1000",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});if(n.status!==200)return null;let i=(await n.json())?.data;if(!Array.isArray(i))return null;let s=[];for(let a of i){let c=a?.id;if(typeof c!="string"||c.trim().length===0)continue;let l=a?.created_at;s.push({id:c,...typeof l=="string"?{createdAt:l}:{}})}return s}catch{return null}finally{clearTimeout(r)}}var wr=k(()=>{"use strict";oe();St();qt()});import ly from"node:http";import es from"node:crypto";function bo(){let t=ts(es.randomBytes(32)),e=ts(es.createHash("sha256").update(t).digest()),r=ts(es.randomBytes(32));return{verifier:t,challenge:e,state:r}}function ns(t){let e=new URL(uy);return e.search=new URLSearchParams({response_type:"code",client_id:tu,redirect_uri:t.redirectUri,scope:py,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function my(t,e){let r=t.get("error");if(r)throw new Error(`oauth-error: ${r}`);if(t.get("state")!==e)throw new Error("state-mismatch");let n=t.get("code");if(!n)throw new Error("no-code");return n}function ru(t,e){let[r,n]=t.trim().split("#");if(!r)throw new Error("no-code");if(n!==void 0&&n!==e)throw new Error("state-mismatch");return r}function gy(t){let e=t,r=e?.access_token;if(!r||typeof r!="string")throw new Error(`no access_token in response: ${JSON.stringify(t)}`);return{oauthToken:r,...typeof e.refresh_token=="string"?{refreshToken:e.refresh_token}:{},...typeof e.expires_in=="number"?{expiresIn:e.expires_in}:{}}}async function os(t){let e=await fetch(dy,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:t.code,state:t.state,redirect_uri:t.redirectUri,client_id:tu,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return gy(await e.json())}async function is(t){let e=t.timeoutMs??fy,r=ly.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=ns({redirectUri:o,challenge:t.challenge,state:t.state}),s,a=new Promise((l,u)=>{s=setTimeout(()=>u(new Error("no-callback")),e),r.on("request",(p,d)=>{let m=new URL(p.url??"/",o);if(m.pathname!=="/callback"){d.statusCode=404,d.end();return}clearTimeout(s),d.setHeader("content-type","text/html"),d.end("<h3>Authorized \u2014 you can close this tab.</h3>");try{l(my(m.searchParams,t.state))}catch(f){u(f)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>os({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function nu(t){let e=await is(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
|
|
20
|
+
${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var tu,uy,dy,rs,py,fy,ts,ss=k(()=>{"use strict";tu="9d1c250a-e61b-44d9-88ed-5944d1962f5e",uy="https://platform.claude.com/oauth/authorize",dy="https://platform.claude.com/v1/oauth/token",rs="https://platform.claude.com/oauth/code/callback",py="org:create_api_key user:profile user:inference",fy=12e4,ts=t=>Buffer.from(t).toString("base64url")});async function ou(t,e,r,n,o){let i=c=>{e.readyState===e.OPEN&&e.send(JSON.stringify(c))},s=c=>i({type:"agent_login_url",requestId:r.requestId,projectId:t.projectId,error:c});if(K("ORIGIN")==="farm"||K("CLAUDE_AUTOLOGIN")==="0"){s("autologin_disabled");return}let a;try{a=await is(bo())}catch(c){s(`listener failed: ${c instanceof Error?c.message:String(c)}`);return}i({type:"agent_login_url",requestId:r.requestId,projectId:t.projectId,authUrl:a.authUrl}),n.info(`[agent-auth] authorize Claude in a browser on THIS machine: ${a.authUrl}`),n.info(`[agent-auth] waiting for the redirect on ${a.redirectUri} \u2026`);try{let c=await a.waitForToken(),l=await It(c.oauthToken);if(l==="invalid"){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"token rejected (401) \u2014 previous token kept"}),n.warn("[agent-auth] new Claude token rejected (401) \u2014 previous token kept");return}let u=F(t.projectId);if(!u){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"no secrets file for this project on the CLI"}),n.warn("[agent-auth] no secrets file for this project \u2014 token not saved");return}u.claude={oauthToken:c.oauthToken},X(u),n.info(`[agent-auth] Claude token replaced (${c.oauthToken.slice(0,12)}\u2026, ${c.oauthToken.length} chars)`),i({type:"agent_login_result",projectId:t.projectId,ok:!0,...l==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}}),o()}catch(c){let l=c instanceof Error?c.message:String(c);i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:l}),n.warn(`[agent-auth] browser authorization failed: ${l}`)}finally{a.close()}}var iu=k(()=>{"use strict";ke();wr();oe();ss()});function su(t,e){let r=t.find(n=>n.kind==="claude");return r?.present===!0&&r.ok===!1?K("ORIGIN")==="farm"||K("CLAUDE_AUTOLOGIN")==="0"||e?"none":"open":r?.ok===!0?"rearm":"none"}function au(t,e){return`${t.replace(/\/$/,"")}/?project=${encodeURIComponent(e)}`}var cu=k(()=>{"use strict";ke()});import{spawn as hy}from"node:child_process";function Vt(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=hy(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var ko=k(()=>{"use strict"});import{setTimeout as yy}from"node:timers/promises";import wy from"ws";function $o(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new wy(r)}async function Ct(t,e,r){return He(t,e,"/projects",r)}async function lu(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new U(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function vo(t,e,r,n){return He(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function uu(t,e,r,n){return He(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function du(t,e,r,n){return He(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function pu(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 U(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function xo(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new U(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function as(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new U(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function fu(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await as(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 yy(r.delayMs??1500)}throw o}async function mu(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 pn(e)}if(!r.ok)throw new U(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function gu(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new U(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function hu(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new U(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function yu(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 U(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function cs(t,e,r,n){return He(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function wu(t,e,r,n,o){return He(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function bu(t,e,r,n,o){return He(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function ku(t,e,r,n,o){return He(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function fn(t,e,r,n){return He(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function ls(t,e,r,n){await He(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function $u(t,e,r,n){return He(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function vu(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 U(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 U(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function He(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 U(o.status,s,a)}return s}var U,pn,ge=k(()=>{"use strict";U=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};pn=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});function Su(t){xu=t}function mn(t,e="info"){xu(t,e)}var xu,So=k(()=>{"use strict";xu=t=>console.log(t)});import{homedir as by,tmpdir as ky}from"node:os";import{existsSync as $y,mkdirSync as vy,mkdtempSync as xy,rmSync as Sy}from"node:fs";import{join as gn}from"node:path";import{simpleGit as Ro}from"simple-git";function ve(t,e,r){let n=r??gn(by(),".codepipe","repos");return gn(n,t,e)}async function Jt(t,e,r={}){let n=ve(t,e.name,r.baseDir),o=r.cloneUrlOverride??yn(e);if(!$y(gn(n,".git"))){vy(n,{recursive:!0});let a=Ro();mn(`[git] clone ${o} \u2192 ${n}`);try{await a.clone(o,n)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${o}
|
|
21
|
+
${l.trim()}`)}}let i=Ro(n);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
|
|
22
|
+
${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function zt(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function Xt(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&&mn(`[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 zt(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await zt(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([...To,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function hn(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await zt(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await zt(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 Ru(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:u,force:p}=r,d=await hn(t,i,()=>Xt(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));p&&await t.raw(["branch","-D",a]).catch(()=>{});let m=`origin/${c}`;if(await zt(t,m)||(m=`origin/${u??c}`),(await t.revparse([m])).trim()===s)await t.raw(["branch","-f",a,d]),await t.checkout(a);else{await t.checkout(["-B",a,m]);try{await t.raw([...To,"cherry-pick",d])}catch(b){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let w=b instanceof Error?b.message:String(b);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
|
|
23
|
+
${w.trim()}`)}}let g=(await t.revparse(["HEAD"])).trim(),y=r.push!==!1;if(y){let b=p?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push(b)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:g,pushed:y}}async function Tu(t,e,r){let n=r.force?["--force-with-lease","-u","origin",r.branchName]:["-u","origin",r.branchName];return await t.push(n),{pushed:!0}}async function Iu(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,u=await hn(t,i,()=>Xt(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:c}));return await t.raw(["branch","-f",a,u]),l&&await t.push(["--force-with-lease","-u","origin",a]),{commit:u,pushed:l}}async function Cu(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,baseRef:a,branchName:c,commitMessage:l,defaultBranch:u}=r,p=await hn(t,i,()=>Xt(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));await t.fetch().catch(()=>{});let d=`origin/${a}`;if(await zt(t,d)||(d=`origin/${u??a}`),(await t.revparse([d])).trim()===s)return await t.raw(["branch","-f",c,p]),{commit:p,branch:c};let f=xy(gn(ky(),"codepipe-apply-")),g=gn(f,"wt");try{await t.raw(["worktree","add","--detach",g,d]);let y=Ro(g);try{await y.raw([...To,"cherry-pick",p])}catch(w){await y.raw(["cherry-pick","--abort"]).catch(()=>{});let x=w instanceof Error?w.message:String(w);throw new Error(`cherry-pick of ${i.slice(0,10)} onto ${a} hit conflicts
|
|
24
|
+
${x.trim()}`)}let b=(await y.revparse(["HEAD"])).trim();return await t.raw(["branch","-f",c,b]),{commit:b,branch:c}}finally{await t.raw(["worktree","remove","--force",g]).catch(()=>{}),Sy(f,{recursive:!0,force:!0}),await t.raw(["worktree","prune"]).catch(()=>{})}}async function Eu(t,e,r){let{branchName:n,dropTaskKeys:o}=r,i=`origin/${n}`;if(!await zt(t,i))throw new Error(`rewrite_cluster_branch: ${i} not found upstream`);let s=`origin/${r.defaultBranch??"main"}`,a=(await t.raw(["merge-base",i,s])).trim(),c=(await t.raw(["rev-list","--reverse",`${a}..${i}`])).split(`
|
|
23
25
|
`).map(m=>m.trim()).filter(m=>m.length>0),l=new Set(o.map(m=>m.toUpperCase())),u=[],p=0;for(let m of c)(await t.raw(["show","-s","--format=%(trailers:key=CodePipe-Task,valueonly)",m])).split(`
|
|
24
|
-
`).map(y=>y.trim().toUpperCase()).filter(y=>y.length>0).some(y=>l.has(y))?p++:u.push(m);if(p===0)return{commit:(await t.revparse([i])).trim(),dropped:0};await t.checkout(["-B",n,a]);for(let m of u)try{await t.raw([...
|
|
25
|
-
${g.trim()}`)}let d=(await t.revparse(["HEAD"])).trim();return await t.push(["--force-with-lease","-u","origin",n]),{commit:d,dropped:p}}async function
|
|
26
|
-
`).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
|
|
27
|
-
`)}async function
|
|
26
|
+
`).map(y=>y.trim().toUpperCase()).filter(y=>y.length>0).some(y=>l.has(y))?p++:u.push(m);if(p===0)return{commit:(await t.revparse([i])).trim(),dropped:0};await t.checkout(["-B",n,a]);for(let m of u)try{await t.raw([...To,"cherry-pick","--allow-empty","--keep-redundant-commits",m])}catch(f){await t.raw(["cherry-pick","--abort"]).catch(()=>{}),await t.checkout(["-B",n,i]).catch(()=>{});let g=f instanceof Error?f.message:String(f);throw new Error(`rewrite_cluster_branch: replaying ${m.slice(0,10)} after dropping ${o.join(", ")} hit conflicts
|
|
27
|
+
${g.trim()}`)}let d=(await t.revparse(["HEAD"])).trim();return await t.push(["--force-with-lease","-u","origin",n]),{commit:d,dropped:p}}async function Pu(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 yn(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 Au(t){return(await Ro().listRemote(["--heads",t])).split(`
|
|
28
|
+
`).map(r=>r.trim()).filter(r=>r.length>0).map(r=>r.split(/\s+/)[1]??"").filter(r=>r.startsWith("refs/heads/")).map(r=>r.slice(11))}function ju(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}var To,br=k(()=>{"use strict";So();To=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{existsSync as Co,readFileSync as Ry,writeFileSync as Ty}from"node:fs";import{join as Zt}from"node:path";import{simpleGit as Io}from"simple-git";function Nu(t){return Zt(t,Iy)}function er(t){let e=Nu(t);if(!Co(e))return{};try{return JSON.parse(Ry(e,"utf-8"))}catch{return{}}}function ds(t,e){Ty(Nu(t),JSON.stringify(e,null,2)+`
|
|
29
|
+
`)}async function Ou(t,e,r,n,o){let i;try{i=await cs(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(d){return{ok:!1,message:`claim failed: ${d instanceof Error?d.message:String(d)}`}}let s=[];for(let d of i.repos){let m=t.spec.repos.find(b=>b.name===d.repoName);if(!m)return{ok:!1,message:`repo "${d.repoName}" not in project.yaml \u2014 run /sync`};let f=Zt(t.root,m.mountAs);if(!Co(Zt(f,".git")))return{ok:!1,message:`${m.mountAs}/ not cloned \u2014 run /sync first`};if(!(await Io(f).status()).isClean())return{ok:!1,message:`${m.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:d,spec:m,dir:f})}let a=[];for(let d of s){let m=Io(d.dir),f=await Cy(m),g=d.claimRepo;try{await m.fetch()}catch(w){return await us(a,o),{ok:!1,message:`fetch failed in ${d.spec.mountAs}: ${Qt(w)}`}}let y=`origin/${g.baseRef}`,b;try{b=await Xt(m,{contextRepoCloneUrl:g.contextRepoCloneUrl,deliveryRef:g.deliveryRef,deliverySha:g.deliverySha,baseSha:g.baseSha,commitMessage:g.commitMessage})}catch(w){return await us(a,o),{ok:!1,message:`fetch delivery failed in ${d.spec.mountAs}: ${Qt(w)}`}}a.push({git:m,dir:d.dir,mountAs:d.spec.mountAs,originalRef:f,branch:g.branchName,baseSha:y,deliveryCommit:b,startPoint:y})}let c=[];for(let d of a)try{if(n==="apply"){await d.git.checkout(["-B",d.branch,d.startPoint]),await d.git.raw([..._u,"cherry-pick",d.deliveryCommit]);let m=(await d.git.revparse(["HEAD"])).trim();c.push({mountAs:d.mountAs,branch:d.branch,baseSha:d.baseSha,appliedSha:m})}else await d.git.checkout(["--detach",d.startPoint]),await d.git.raw([..._u,"cherry-pick","--no-commit",d.deliveryCommit]),await d.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:d.mountAs,branch:d.branch,baseSha:d.baseSha})}catch(m){return await d.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await us(a,o),{ok:!1,message:`apply failed in ${d.mountAs}: ${Qt(m)} (rolled back all repos)`}}let l=er(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},ds(t.contextDir,l);let u=c.map(d=>d.mountAs).join(", "),p=n==="apply"?`review, push branch '${i.repos[0]?.branchName}', then: /applied ${r} --pr <url>`:`review with 'git diff', commit & push yourself, then: /applied ${r} --pr <url>`;return{ok:!0,message:`${n==="apply"?"applied":"unstashed"} ${r} in ${u}
|
|
28
30
|
${p}
|
|
29
|
-
or: /abort ${r} --reason "..."`}}async function
|
|
31
|
+
or: /abort ${r} --reason "..."`}}async function Du(t,e,r){let n=[];for(let c of e.repos){let l=t.repos.find(p=>p.name===c.repoName);if(!l)return{ok:!1,message:`repo "${c.repoName}" not in project.yaml \u2014 run /sync`};let u=Zt(t.root,l.mountAs);if(!Co(Zt(u,".git")))return{ok:!1,message:`${l.mountAs}/ not cloned \u2014 run /sync first`};n.push({git:Io(u),dir:u,spec:l,cr:c})}let o=[],i=[];for(let c of n)try{let{commit:l}=await Cu(c.git,c.dir,{contextRepoCloneUrl:c.cr.contextRepoCloneUrl,deliveryRef:c.cr.deliveryRef,deliverySha:c.cr.deliverySha,baseSha:c.cr.baseSha,baseRef:c.cr.baseRef,branchName:c.cr.branchName,commitMessage:c.cr.commitMessage,defaultBranch:c.spec.defaultBranch});r.info(`[apply] ${e.taskKey}: ${c.cr.branchName} \u2192 ${c.spec.mountAs} (${l.slice(0,10)})`),o.push({git:c.git,branch:c.cr.branchName}),i.push({mountAs:c.spec.mountAs,branch:c.cr.branchName,baseSha:`origin/${c.cr.baseRef}`,appliedSha:l})}catch(l){for(let u of o)await u.git.raw(["branch","-D",u.branch]).catch(()=>{});return{ok:!1,message:`auto-apply failed in ${c.spec.mountAs}: ${Qt(l)}`}}try{await cs(t.hubUrl,t.cliToken,t.projectId,e.taskKey)}catch(c){return{ok:!1,message:`branch created but claim failed: ${Qt(c)} \u2014 retried on the next reconnect`,branches:o.map(l=>l.branch)}}let s=er(t.contextDir);s[e.taskKey]={mode:"apply",claimedAt:new Date().toISOString(),repos:i},ds(t.contextDir,s);let a=i.map(c=>`${c.branch} (${c.mountAs})`).join(", ");return{ok:!0,branches:i.map(c=>c.branch),message:`branch created locally without touching your checkout: ${a}
|
|
30
32
|
review, push, then: /applied ${e.taskKey} --pr <url>
|
|
31
|
-
or: /abort ${e.taskKey} --reason "..."`}}function
|
|
33
|
+
or: /abort ${e.taskKey} --reason "..."`}}function ps(t,e){let r=er(t);r[e]&&(delete r[e],ds(t,r))}async function us(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}: ${Qt(n)} \u2014 check manually`)}}async function Lu(t,e,r){let o=er(t.contextDir)[e];if(o){for(let i of o.repos){let s=Zt(t.root,i.mountAs);if(!Co(Zt(s,".git")))continue;let a=Io(s),c=t.spec.repos.find(u=>u.mountAs===i.mountAs),l=c?`origin/${c.defaultBranch}`:i.baseSha;try{await a.checkout(["-f",l]),await a.reset(["--hard",l]),await a.raw(["branch","-D",i.branch]).catch(()=>{})}catch(u){r.warn(`rollback failed in ${i.mountAs}: ${Qt(u)} \u2014 check manually`)}}ps(t.contextDir,e)}}async function Cy(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function Qt(t){return t instanceof Error?t.message.trim():String(t)}var _u,Iy,fs=k(()=>{"use strict";ge();br();_u=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],Iy="apply-queue.json"});import{existsSync as Ey}from"node:fs";import{join as Py}from"node:path";import{simpleGit as Ay}from"simple-git";async function Uu(t,e){if(!Ey(Py(t,".git")))return{status:"skipped"};let r=Ay(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${jy(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 jy(t){return t instanceof Error?t.message.trim():String(t)}var Mu=k(()=>{"use strict"});import{existsSync as Bu,readFileSync as Fu,readdirSync as _y,statSync as Ny}from"node:fs";import{join as ms}from"node:path";import{parse as Gu}from"yaml";function Eo(t){let e=ms(t,"actions"),r=[],n=[];if(!Bu(e))return{defs:r,errors:n};let o;try{o=_y(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=ms(e,s);try{if(!Ny(a).isFile())continue;let c=fc(s,Gu(Fu(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 Ku(t){let e={},r=ms(t,"project.yaml");if(!Bu(r))return e;let n;try{n=Gu(Fu(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))!Ae.test(i)||bt(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var gs=k(()=>{"use strict";W()});import{existsSync as hs,readFileSync as Hu,readdirSync as Oy,watch as Dy}from"node:fs";import{join as wn}from"node:path";var Po,Wu=k(()=>{"use strict";gs();Po=class{constructor(e,r,n,o,i=6e4){this.contextDir=e;this.projectId=r;this.send=n;this.log=o;this.intervalMs=i}timer=null;watchers=[];debounce=null;started=!1;start(){this.started||(this.started=!0,this.report(),this.timer=setInterval(()=>this.report(),this.intervalMs),this.timer.unref?.(),this.installWatcher())}stop(){this.started=!1,this.timer&&clearInterval(this.timer),this.timer=null,this.debounce&&clearTimeout(this.debounce),this.debounce=null;for(let e of this.watchers)try{e.close()}catch{}this.watchers=[]}installWatcher(){let e=()=>{this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>this.report(),500),this.debounce.unref?.()},r=[this.contextDir,wn(this.contextDir,"prompts"),wn(this.contextDir,"actions")];for(let n of r)if(hs(n))try{let o=Dy(n,e);o.on("error",i=>{this.log.warn(`[config] fs.watch failed on ${n} \u2014 falling back to periodic reporting: ${i instanceof Error?i.message:String(i)}`);try{o.close()}catch{}}),this.watchers.push(o)}catch{}}reportNow(){this.report()}report(){try{this.send(this.read())}catch(e){this.log.warn(`[config] report failed: ${e instanceof Error?e.message:String(e)}`)}}read(){let e=Eo(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=wn(this.contextDir,e);if(!hs(r))return null;try{return Hu(r,"utf-8")}catch{return null}}readPrompts(){let e=wn(this.contextDir,"prompts"),r={};if(!hs(e))return r;let n;try{n=Oy(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=Hu(wn(e,o),"utf-8")}catch{}}return r}}});import{existsSync as Et,mkdirSync as Yu,readFileSync as ys,writeFileSync as kr}from"node:fs";import{homedir as Ly}from"node:os";import{join as nt}from"node:path";import{simpleGit as Uy}from"simple-git";function bn(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=nt(t,o);Et(s)||(kr(s,i),r.push(o))}return r}function tr(t,e,r){let n=nt(Ly(),".codepipe","profiles",t,"context-config");return Yu(n,{recursive:!0}),kr(nt(n,"project.yaml"),e.projectYaml),kr(nt(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function Ao(t,e,r){if(Et(e))for(let n of $r){let o=nt(e,n),i=nt(t,n);if(!(!Et(o)||Et(i)))try{kr(i,ys(o)),r.info(`[config] seeded local ${n} from the provisioning bundle`)}catch(s){r.warn(`[config] could not seed ${n}: ${s instanceof Error?s.message:String(s)}`)}}}function vr(t){let e=nt(t,".gitignore"),r=Et(e)?ys(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if($r.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
|
|
32
34
|
`)?"":`
|
|
33
|
-
`;return
|
|
35
|
+
`;return kr(e,r+i+My.join(`
|
|
34
36
|
`)+`
|
|
35
|
-
`),!0}async function
|
|
36
|
-
`).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;
|
|
37
|
-
`)){let c=a.trim();if(c)try{let l=JSON.parse(c);if(typeof l.id!="string")continue;o.has(l.id)||o.set(l.id,{raw:c,createdAt:typeof l.createdAt=="string"?l.createdAt:""})}catch{}}let i=[...o.values()].sort((s,a)=>s.createdAt.localeCompare(a.createdAt)).map(s=>s.raw)
|
|
37
|
+
`),!0}async function qu(t,e){try{if(!Et(nt(t,".git")))return;let r=Uy(t),n=(await r.raw(["ls-files","--",...$r])).split(`
|
|
38
|
+
`).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;vr(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 ks(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 ws(t){let e=new Map;for(let r of $r){let n=nt(t,r);Et(n)&&e.set(r,ys(n))}return e}function bs(t,e){Yu(t,{recursive:!0});for(let[r,n]of e){let o=nt(t,r);Et(o)||kr(o,n)}}var $r,My,ft=k(()=>{"use strict";mt();$r=["project.yaml","regimen.yaml"];My=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as By,mkdirSync as Fy,rmSync as Gy,writeFileSync as $s}from"node:fs";import{dirname as Ky,isAbsolute as Hy,join as Ju,normalize as No}from"node:path";import{simpleGit as Xu}from"simple-git";async function vs(t,e){let r=No(t),o=(_o.get(r)??Promise.resolve()).catch(()=>{}).then(e);_o.set(r,o);try{return await o}finally{_o.get(r)===o&&_o.delete(r)}}async function We(t,e,r){return vs(t,()=>xs(t,e,r))}async function xs(t,e,r){if(!By(Ju(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=fe(t,a.path);if(a.deleted){Gy(c,{force:!0});continue}Fy(Ky(c),{recursive:!0}),a.encoding==="base64"?$s(c,Buffer.from(a.content,"base64")):$s(c,a.content)}let n=Xu(t),o=e.filter(a=>!a.deleted).map(a=>a.path),i=e.filter(a=>a.deleted).map(a=>a.path);for(let a=0;a<o.length;a+=jo)await n.raw(["add","-A","-f","--",...o.slice(a,a+jo)]);for(let a=0;a<i.length;a+=jo)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...i.slice(a,a+jo)]);await n.raw(["reset","-q","--",...$r]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await ks(t))}async function ks(t){let e=Xu(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=Vu;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 Vy(e);if(i.length>0&&i.every(a=>Wy.has(a)||zu.test(a)||Yy.test(a))){for(let a of i)zu.test(a)?await qy(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 ${Vu} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function qy(t,e,r){let n=async s=>await t.raw(["show",`:${s}:${r}`]).catch(()=>""),o=new Map;for(let s of[await n(2),await n(3)])for(let a of s.split(`
|
|
39
|
+
`)){let c=a.trim();if(c)try{let l=JSON.parse(c);if(typeof l.id!="string")continue;o.has(l.id)||o.set(l.id,{raw:c,createdAt:typeof l.createdAt=="string"?l.createdAt:""})}catch{}}let i=[...o.values()].sort((s,a)=>s.createdAt.localeCompare(a.createdAt)).map(s=>s.raw);$s(fe(e,r),i.join(`
|
|
38
40
|
`)+(i.length>0?`
|
|
39
|
-
`:""))}async function
|
|
40
|
-
`).map(r=>r.trim()).filter(Boolean)}function
|
|
41
|
-
`),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
|
|
42
|
-
`),a=s.findIndex(
|
|
41
|
+
`:""))}async function Vy(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
|
|
42
|
+
`).map(r=>r.trim()).filter(Boolean)}function fe(t,e){if(Hy(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=No(Ju(t,e)),n=No(t+"/");if(r!==No(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var Vu,Wy,Yy,zu,jo,_o,mt=k(()=>{"use strict";ft();Vu=3,Wy=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),Yy=/^model\/derived\//,zu=/^tasks\/[^/]+\/comments\.jsonl$/,jo=500,_o=new Map});import{existsSync as Ss,readFileSync as Qu,readdirSync as zy}from"node:fs";import{join as Zu}from"node:path";import{simpleGit as Jy}from"simple-git";function Zy(t){let e=t.split(`
|
|
43
|
+
`),r=e.find(i=>i.startsWith("# ")),n=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",o=i=>{let s=new RegExp(`^-\\s*\\*\\*${i}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=s.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:n,status:o("Status"),date:o("Date")}}function ew(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
|
|
44
|
+
`),a=s.findIndex(b=>b.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),u=[],p="",d=null,m=a>=0?a+1:0;for(let b=m;b<s.length;b++){let w=(s[b]??"").trim();if(w===""){m=b+1;continue}let x=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(w);if(!x)break;let I=(x[1]??"").trim().toLowerCase(),H=(x[2]??"").trim(),j=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(w);j&&(d=parseInt(j[1]??"",10)),I==="tasks"&&(p=H),l.has(I)||u.push(w),m=b+1}let f=p?p.includes(n)?p:`${p}, ${n}`:n,g=s.slice(m).join(`
|
|
43
45
|
`).replace(/^\n+/,""),y=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${f}`,...u,"",g].join(`
|
|
44
46
|
`);return{content:y.endsWith(`
|
|
45
47
|
`)?y:y+`
|
|
46
|
-
`,supersedes:d}}function
|
|
48
|
+
`,supersedes:d}}function tw(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
|
|
47
49
|
|
|
48
|
-
- **Status:** superseded by ADR-${r}`):n}function
|
|
50
|
+
- **Status:** superseded by ADR-${r}`):n}function rw(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(`
|
|
49
51
|
`)+`
|
|
50
|
-
`}async function
|
|
52
|
+
`}async function ed(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await Jy(t).pull(void 0,void 0,["--rebase"])}catch{}let i=y=>o==="staging"?`adr/DRAFT-${y}.md`:`tasks/${e}/adr/DRAFT-${y}.md`,s=[],a=[];for(let y of r){let b=fe(t,i(y));if(!Ss(b)){a.push(y);continue}s.push({slug:y,content:Qu(b,"utf-8")})}let c=Zu(t,"adr"),l=new Map;if(Ss(c))for(let y of zy(c)){let b=Xy.exec(y);!b||y===Qy||l.set(y,{num:parseInt(b[1]??"",10),slug:b[2]??"",content:Qu(Zu(c,y),"utf-8")})}let u=Math.max(0,...[...l.values()].map(y=>y.num))+1,p=new Map,d=[],m=[];for(let y of s){if([...l.entries()].find(([,j])=>j.slug===y.slug&&j.content.includes(e))){m.push(y.slug);continue}let w=u++,x=`${String(w).padStart(4,"0")}-${y.slug}.md`,{content:I,supersedes:H}=ew(y.content,w,y.slug,e,n);if(p.set(x,I),l.set(x,{num:w,slug:y.slug,content:I}),d.push(`adr/${x}`),H!==null){let j=[...l.keys()].find(v=>v.startsWith(`${String(H).padStart(4,"0")}-`));if(j&&j!==x){let v=tw(p.get(j)??l.get(j).content,w);p.set(j,v),l.set(j,{...l.get(j),content:v})}}}let f=[];if(o==="staging")for(let y of s)Ss(fe(t,`adr/DRAFT-${y.slug}.md`))&&f.push({path:`adr/DRAFT-${y.slug}.md`,content:"",deleted:!0});if(d.length===0&&f.length===0)return{promoted:d,skipped:m,missing:a};if(d.length>0){let y=[...l.entries()].map(([b,w])=>({num:w.num,file:b,header:Zy(w.content)}));p.set("INDEX.md",rw(y))}for(let[y,b]of p.entries())f.push({path:`adr/${y}`,content:b});let g=d.length>0?`adr(${e}): promote ${s.map(y=>y.slug).join(", ")}`:`adr(${e}): drop stale staged ${m.join(", ")}`;return await We(t,f,g),{promoted:d,skipped:m,missing:a}}var Xy,Qy,td=k(()=>{"use strict";mt();Xy=/^(\d{4})-(.+)\.md$/,Qy="0000-template.md"});import{existsSync as rd,readFileSync as ow}from"node:fs";import{join as nd}from"node:path";function iw(t){for(let e of[Qe,nn]){let r=nd(t,e);if(rd(r))try{return Fa(ow(r,"utf-8"))}catch{return 0}}return 0}function sw(t,e,r,n=4){let o=e<n,i=o?Ga(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function Oo(t,e){return sw(e,iw(t),r=>rd(nd(t,r)))}var Rs=k(()=>{"use strict";W()});import{existsSync as Pt,readFileSync as xr,readdirSync as id}from"node:fs";import{join as Ts}from"node:path";import{simpleGit as sd}from"simple-git";import{parse as ad}from"yaml";function cd(t){try{let e=fe(t,no);if(!Pt(e))return null;let r=ad(xr(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!dr.test(n)?null:{prefix:n}}catch{return null}}function ld(t){return`# Built-in tracker configuration \u2014 shared by every team member.
|
|
51
53
|
# The issue-key prefix (<PREFIX>-<N>). Fixed at project init: changing it
|
|
52
54
|
# later would orphan existing tasks/<KEY>/ directories.
|
|
53
55
|
prefix: ${t}
|
|
@@ -55,15 +57,15 @@ prefix: ${t}
|
|
|
55
57
|
# Statuses are the built-in default set for now:
|
|
56
58
|
# Backlog | To Do | In Progress | Review | Done | Rejected
|
|
57
59
|
# A configurable status set / pipeline mapping is a planned extension.
|
|
58
|
-
`}function
|
|
59
|
-
`}function
|
|
60
|
+
`}function Is(t=0){return`${t}
|
|
61
|
+
`}function aw(t){return t==="depends_on"||t==="subtask"}function cw(t){let e;try{e=ad(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=Oc.includes(r.type)?r.type:ro,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;aw(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 Cs(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(`
|
|
60
62
|
`)+`
|
|
61
|
-
`}function
|
|
63
|
+
`}function $n(t,e){let r=fe(t,cn(e));return Pt(r)?cw(xr(r,"utf-8")):null}function ud(t){let e=Ts(t,"tasks");if(!Pt(e))return[];let r=[];for(let n of id(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=$n(t,n.name);o&&r.push(o)}return r}function lw(t,e){let r=fe(t,`tasks/${e}/task.md`);if(!Pt(r))return;let n=xr(r,"utf-8").split(`
|
|
62
64
|
`),o=n.indexOf("---");if(o<0)return;let i=n.slice(o+1),s=i.lastIndexOf("## Attachments");s>=0&&i.slice(s+1).every(u=>u.trim()===""||/^- \[[^\]]*\]\(attachments\/[^)]*\)$/.test(u.trim()))&&(i=i.slice(0,s));let a=i.join(`
|
|
63
|
-
`).trim();if(!(!a||a==="_(no description)_"))return a}function
|
|
65
|
+
`).trim();if(!(!a||a==="_(no description)_"))return a}function vn(t,e,r={}){let n=r.withDescription?lw(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:uw(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function uw(t){return t.charAt(0).toUpperCase()+t.slice(1)}function dw(t){let e=fe(t,an);if(!Pt(e))return 0;let r=Number.parseInt(xr(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function pw(t,e){let r=Ts(t,"tasks");if(!Pt(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of id(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 fw(t,e){return Math.max(dw(t),pw(t,e))+1}async function dd(t,e,r,n){return vs(t,()=>mw(t,e,r,n))}async function mw(t,e,r,n){if(!Pt(Ts(t,".git")))throw new Error(`context repo clone not found at ${t}`);await kn(t);let o=null;for(let i=0;i<od;i++){let s=fw(t,e),a=`${e}-${s}`,c=[...r(a),{path:an,content:Is(s)}];try{return await xs(t,c,n(a)),a}catch(l){if(o=l,await hw(t,n(a)),await kn(t),gw(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${od} attempts: ${o instanceof Error?o.message:String(o)}`)}function gw(t,e){for(let r of e){let n=fe(t,r.path);if(!Pt(n)||(r.encoding==="base64"?xr(n).toString("base64"):xr(n,"utf-8"))!==r.content)return!1}return!0}async function kn(t){let e=sd(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 hw(t,e){let r=sd(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
|
|
64
66
|
`)[0]||!(await r.raw(["log","@{u}..HEAD","--pretty=%s"]).catch(()=>"")).trim().split(`
|
|
65
67
|
`).some(i=>i.trim()===e.split(`
|
|
66
|
-
`)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var
|
|
68
|
+
`)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var od,Do=k(()=>{"use strict";W();mt();od=5});function Sr(t,e,r,n){return[{path:"README.md",content:Cw(t,e)},{path:".gitignore",content:vw()},{path:"CLAUDE.md",content:Sw(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:xw()},{path:"knowledge/README.md",content:Rw()},{path:"knowledge/build.yaml",content:Iw()},{path:"actions/README.md",content:Tw()},{path:"model/README.md",content:yw()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:$w()},{path:"adr/README.md",content:ww()},{path:"adr/0000-template.md",content:bw()},{path:"adr/INDEX.md",content:kw()},{path:Qe,content:Xn()},...t.trackerProvider==="internal"?[{path:no,content:ld(t.youtrackProjectKey??Mi)},{path:an,content:Is()}]:[]]}function yw(){return`# model/ \u2014 the project map
|
|
67
69
|
|
|
68
70
|
A graph of the project built from **git history and task artifacts**: files
|
|
69
71
|
and directories connected by the fact of changing together and the fact of
|
|
@@ -90,7 +92,7 @@ asset \u2014 treat it like \`knowledge/\`.
|
|
|
90
92
|
|
|
91
93
|
Every YAML file carries \`modelFormatVersion\`; a reader that meets a
|
|
92
94
|
different version treats it as "rebuild needed", not as an error.
|
|
93
|
-
`}function
|
|
95
|
+
`}function ww(){return`# ADR \u2014 architecture decision records
|
|
94
96
|
|
|
95
97
|
Accepted architectural decisions of this project \u2014 its **framework**. The
|
|
96
98
|
agent reads this section (start with \`INDEX.md\`) at the beginning of every
|
|
@@ -118,7 +120,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
|
|
|
118
120
|
canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
|
|
119
121
|
is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
|
|
120
122
|
open a PR to this repository.
|
|
121
|
-
`}function
|
|
123
|
+
`}function bw(){return`# ADR-NNNN: <title>
|
|
122
124
|
|
|
123
125
|
- **Status:** accepted | superseded by ADR-NNNN
|
|
124
126
|
- **Date:** YYYY-MM-DD
|
|
@@ -140,12 +142,12 @@ What becomes easier, what becomes harder, what future tasks must keep doing.
|
|
|
140
142
|
## Alternatives considered
|
|
141
143
|
|
|
142
144
|
- **<alternative>** \u2014 why it was rejected.
|
|
143
|
-
`}function
|
|
145
|
+
`}function kw(){return`# ADR index
|
|
144
146
|
|
|
145
147
|
<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->
|
|
146
148
|
|
|
147
149
|
(no accepted ADRs yet)
|
|
148
|
-
`}function
|
|
150
|
+
`}function $w(){return`# Audit
|
|
149
151
|
|
|
150
152
|
Pipeline event logs. Naming is per-writer: each codepipe
|
|
151
153
|
project appends only to its own file \u2014
|
|
@@ -154,14 +156,14 @@ project appends only to its own file \u2014
|
|
|
154
156
|
|
|
155
157
|
\u2014 so several team members' CLIs never contend on one file. Do not create a
|
|
156
158
|
shared aggregate here.
|
|
157
|
-
`}function
|
|
159
|
+
`}function ot(t,e,r,n,o="auto",i=Ze,s){let a=t.trackerProvider==="internal";return{projectYaml:a?Ew(t,o):Pw(t,r,n,o),regimenYaml:Aw(t.automationLevel,a?!0:e,a,i,s)}}function vw(){return`# codepipe project config is local to each member's workspace
|
|
158
160
|
project.yaml
|
|
159
161
|
regimen.yaml
|
|
160
162
|
|
|
161
163
|
# codepipe runtime
|
|
162
164
|
session.log
|
|
163
165
|
apply-queue.json
|
|
164
|
-
`}function
|
|
166
|
+
`}function xw(){return`# Index prompt
|
|
165
167
|
|
|
166
168
|
You are the **Indexer** agent on the CodePipe pipeline. Your one job is to build a
|
|
167
169
|
navigation map of this project's repositories and save it to the Context Repo, so
|
|
@@ -218,7 +220,7 @@ current working directory; write nothing else under the Context Repo.
|
|
|
218
220
|
Keep both durable and skimmable \u2014 they are read at the start of every future
|
|
219
221
|
task. Prefer structure (headings, bullet lists) over prose. If a repository is
|
|
220
222
|
empty or unavailable, say so briefly rather than inventing content.
|
|
221
|
-
`}function
|
|
223
|
+
`}function Sw(t){return`# Project context for the CodePipe agent
|
|
222
224
|
|
|
223
225
|
Instructions for AI agents working on **${t.name}** tasks. Claude Code
|
|
224
226
|
auto-loads this file when the Context Repo is mounted. Keep it short and
|
|
@@ -246,7 +248,7 @@ project's architectural invariants: read them at the start of a task and treat
|
|
|
246
248
|
them as binding. New or changed decisions do **not** go here directly \u2014 during
|
|
247
249
|
analysis you draft them as task artifacts, and they are promoted into \`adr/\`
|
|
248
250
|
only after the analysis is approved.
|
|
249
|
-
`}function
|
|
251
|
+
`}function Rw(){return`# Knowledge
|
|
250
252
|
|
|
251
253
|
Durable, reusable notes about this project \u2014 the CodePipe agent's long-lived
|
|
252
254
|
**memory** across tasks. Architectural decisions, domain rules,
|
|
@@ -263,7 +265,7 @@ Keep each note in its own file \u2014 never grow one shared aggregate \u2014 so
|
|
|
263
265
|
concurrent commits touch different files and rebase cleanly. \`INDEX.md\` is
|
|
264
266
|
REGENERATED from the entries by the index job: don't hand-edit it, and treat
|
|
265
267
|
any merge conflict in it as noise (either side converges on the next run).
|
|
266
|
-
`}function
|
|
268
|
+
`}function Tw(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
|
|
267
269
|
|
|
268
270
|
One \`<id>.yml\` per action. Every file here appears as a button on the
|
|
269
271
|
project's **RUN** tab; an action with \`params\` opens a small wizard first.
|
|
@@ -302,7 +304,7 @@ steps:
|
|
|
302
304
|
Parameter values are passed to the commands **only as env vars** \u2014 reference
|
|
303
305
|
them as \`$INPUT_<NAME>\` in \`run\`; they are never substituted into the
|
|
304
306
|
command text itself.
|
|
305
|
-
`}function
|
|
307
|
+
`}function Iw(){return`# BUILD phase config. Discovered & maintained by the agent.
|
|
306
308
|
# Steps run in a rootless Podman container in the SANDBOX, before the PR.
|
|
307
309
|
# Success = every step exits 0. Credentials are NOT available inside the container.
|
|
308
310
|
#
|
|
@@ -318,7 +320,7 @@ command text itself.
|
|
|
318
320
|
# - name: test
|
|
319
321
|
# run: npm test
|
|
320
322
|
# timeout_sec: 600 # per-step timeout (optional, default 600)
|
|
321
|
-
`}function
|
|
323
|
+
`}function Cw(t,e){return`# ${e.name}
|
|
322
324
|
|
|
323
325
|
Context Repo for the **${t.name}** project (CodePipe).
|
|
324
326
|
|
|
@@ -344,7 +346,7 @@ PRs to this repository (and the agent also writes to \`knowledge/\` and
|
|
|
344
346
|
pipeline \u2014 don't edit them by hand.
|
|
345
347
|
|
|
346
348
|
Automation level: **${t.automationLevel}**.
|
|
347
|
-
`}function
|
|
349
|
+
`}function Ew(t,e="auto"){return`# Project description for CodePipe.
|
|
348
350
|
id: ${t.projectId}
|
|
349
351
|
name: ${t.name}
|
|
350
352
|
|
|
@@ -367,15 +369,15 @@ branch:
|
|
|
367
369
|
pattern: codepipe/<TASK_ID>
|
|
368
370
|
|
|
369
371
|
repos:
|
|
370
|
-
${
|
|
371
|
-
`}function
|
|
372
|
+
${pd(t)}
|
|
373
|
+
`}function pd(t){return t.repos.length===0?` [] # add repos here
|
|
372
374
|
`:t.repos.map(e=>` - name: ${e.name}
|
|
373
375
|
host: ${e.host}
|
|
374
376
|
owner: ${e.owner}
|
|
375
377
|
repo: ${e.repoName}
|
|
376
378
|
mount_as: ${e.mountAs??e.name}`+(e.defaultBranch?`
|
|
377
379
|
default_branch: ${e.defaultBranch}`:"")).join(`
|
|
378
|
-
`)}function
|
|
380
|
+
`)}function Pw(t,e,r,n="auto"){let o=e?`
|
|
379
381
|
tracker_url: ${e}`:`
|
|
380
382
|
# tracker_url: https://your.youtrack.cloud`,i=r?`require_assignee: true
|
|
381
383
|
assignee: ${r}`:`require_assignee: false
|
|
@@ -423,7 +425,7 @@ ${Gu(t)}
|
|
|
423
425
|
# non-empty assignee. assignee only takes effect when require_assignee=true.
|
|
424
426
|
${i}`:` # project_key: \u2026
|
|
425
427
|
# tracker_url: https://your.youtrack.cloud
|
|
426
|
-
poll_interval_sec: 60`,a=
|
|
428
|
+
poll_interval_sec: 60`,a=pd(t);return`# Project description for CodePipe.
|
|
427
429
|
id: ${t.projectId}
|
|
428
430
|
name: ${t.name}
|
|
429
431
|
|
|
@@ -454,7 +456,7 @@ branch:
|
|
|
454
456
|
|
|
455
457
|
repos:
|
|
456
458
|
${a}
|
|
457
|
-
`}function
|
|
459
|
+
`}function Aw(t,e,r=!1,n=Ze,o){let i=t==="full",s=e?"true":"false",a=o?` # Model selection. This project's Claude subscription did not include every
|
|
458
460
|
# model in the recommended per-role split, so CodePipe set a single default
|
|
459
461
|
# your subscription can serve for all roles. Tune per role later from the
|
|
460
462
|
# dashboard (Project Settings \u2192 llm.models) or by editing this file.
|
|
@@ -605,29 +607,29 @@ ${a}
|
|
|
605
607
|
# # While this key stays commented out, the project keeps its current mode \u2014
|
|
606
608
|
# # only new projects start on cluster-pr. Uncomment and set a value to switch.
|
|
607
609
|
# mode: cluster-pr
|
|
608
|
-
`}var
|
|
609
|
-
`)}async function Wu(t,e,r,n){let o=gs(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Ro(t,e);if(!i.outdated)return i;let s=Ay(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 _y(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=Me(c),u=await l.findOpenPrByBranch?.(c,s)??null;if(u)return n.info(`[ctx] migration PR already open: ${u.url}`),{...i,migrationPrUrl:u.url};let p=await l.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:s,baseBranch:a,title:`CodePipe: context format v${i.templateVersion} \u2192 v${i.currentVersion}`,body:jy(i)});return n.info(`[ctx] migration PR opened: ${p.url}`),{...i,migrationPrUrl:p.url}}catch(l){return n.warn(`[ctx] migration PR create/find failed (branch pushed, badge without link): ${l instanceof Error?l.message:String(l)}`),i}}async function _y(t,e,r,n,o,i,s){let a=gs(t),c=Cy(Co(Ey(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",o,c,`origin/${i}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},u={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},p=new Map(br(l,u).map(g=>[g.path,g.content])),d=0;for(let g of n.missingPaths){if(g===ze)continue;let y=p.get(g);if(y==null){s.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let $=Co(c,g);Fu($)||(Iy(Py($),{recursive:!0}),Hu($,y),d++)}Hu(Co(c,ze),Wn(n.currentVersion)),d++;let m=Co(c,Zr);Fu(m)&&(Ku(m,{force:!0}),d++);let f=gs(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 (${d} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),Ku(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}var Yu=k(()=>{"use strict";W();bt();ds();Zt()});import{existsSync as Ny,readFileSync as Oy,writeFileSync as Ly}from"node:fs";import{homedir as Dy}from"node:os";import{join as qu}from"node:path";import{parseDocument as Uy}from"yaml";function By(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 My(t,e){let r=Uy(t);return r.set("repos",e.map(By)),r.toString()}function Gy(t,e){let r=[qu(Dy(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(qu(e,"project.yaml")),r}function wn(t,e,r){let n=[],o=[];for(let i of Gy(t,r))if(Ny(i))try{let s=Oy(i,"utf-8"),a=My(s,e);a!==s&&(Ly(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}var hs=k(()=>{"use strict"});import{createCipheriv as Fy,createDecipheriv as Ky,createHash as Hy,createPrivateKey as Wy,createPublicKey as ys,diffieHellman as Vu,generateKeyPairSync as zu,hkdfSync as Ju,randomBytes as Yy}from"node:crypto";function Eo(){let{publicKey:t,privateKey:e}=zu("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function $e(t){let e=Buffer.from(t,"base64");return(Hy("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function dt(t,e){let r=ys({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=zu("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=Vu({privateKey:o,publicKey:r}),c=Buffer.from(Ju("sha256",a,Buffer.concat([i,s]),Xu,32)),l=Yy(12),u=Fy("aes-256-gcm",c,l),p=typeof e=="string"?Buffer.from(e,"utf-8"):e,d=Buffer.concat([u.update(p),u.final()]),m=u.getAuthTag(),f={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:m.toString("base64"),ct:d.toString("base64")};return Buffer.from(JSON.stringify(f),"utf-8").toString("base64")}function $r(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=Wy({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=ys({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=ys(n).export({type:"spki",format:"der"}),a=Vu({privateKey:n,publicKey:o}),c=Buffer.from(Ju("sha256",a,Buffer.concat([i,s]),Xu,32)),l=Ky("aes-256-gcm",c,Buffer.from(r.iv,"base64"));return l.setAuthTag(Buffer.from(r.tag,"base64")),Buffer.concat([l.update(Buffer.from(r.ct,"base64")),l.final()])}var Xu,_e=k(()=>{"use strict";Xu=Buffer.from("devpipe-sealedbox-v1","utf-8")});function qy(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 Qu(t,e,r,n){let o=qy(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=to(t.projectId,a.sandboxId,a.fingerprint);if(c==="mismatch"){n.warn(`[cred] SANDBOX ${a.name} (${a.sandboxId}) key fingerprint CHANGED \u2014 refusing to seal creds. Expected the pinned key; got ${a.fingerprint}. If this is intentional, clear the pin in the secrets file and re-run.`);continue}c==="pinned"&&n.info(`[cred] pinned SANDBOX ${a.name} (${a.sandboxId}) fingerprint ${a.fingerprint}`);let l;try{l=dt(a.publicKey,i)}catch(u){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}var Zu=k(()=>{"use strict";_e();re()});function kn(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 bn(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 $n(t,e=process.env){if(!t)return!1;let r=`https://${Gt}:${encodeURIComponent(t)}@bitbucket.org/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(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 ws(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 ed(t,e=process.env){return ws(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>kn(t,e),e)}function td(t,e=process.env){return ws(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>bn(t,e),e)}function rd(t,e=process.env){return ws(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Gt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>$n(t,e),e)}var Po=k(()=>{"use strict";W()});function nd(t){let e=B(t);if(!e)return null;if(!e.sealKey){let r=Eo();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},z(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:$e(e.sealKey.publicKey)}}async function od(t,e,r,n){let o;try{o=JSON.parse($r(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=B(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 yt(o.token);return i.github={token:o.token},vr(i,()=>{process.env.GH_TOKEN=o.token,ed(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await kt(o.token);return i.gitlab={token:o.token},vr(i,()=>{process.env.GITLAB_TOKEN=o.token,td(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 wt(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},vr(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,rd(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 vt({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},vr(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 xt(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},vr(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},vr(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 vr(t,e){z(t),e()}var id=k(()=>{"use strict";_e();re();bt();Ht();mr();Po()});import{spawn as Vy}from"node:child_process";function Jy(t,e,r,n,o,i){let s={...t},a=(c,l)=>{gt(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 cd(t){let{def:e,onEvent:r}=t,n=Jy(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
|
|
610
|
-
`,o.length>
|
|
611
|
-
`))!==-1;)o(m,f.slice(0,y).replace(/\r$/,"")),f=f.slice(y+1)},flush:()=>{f.length>0&&o(m,f.replace(/\r$/,"")),f=""}}},p=u("stdout"),d=u("stderr");s.stdout?.on("data",p.data),s.stderr?.on("data",d.data),s.on("error",m=>{clearTimeout(l),o("stderr",`spawn failed: ${m.message}`),i(127)}),s.on("close",(m,f)=>{clearTimeout(l),p.flush(),d.flush(),i(a?
|
|
612
|
-
`)}function
|
|
613
|
-
`)){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=
|
|
610
|
+
`}var rr=k(()=>{"use strict";W();Do()});import{existsSync as fd,mkdirSync as jw,mkdtempSync as _w,rmSync as md,writeFileSync as gd}from"node:fs";import{tmpdir as Nw}from"node:os";import{dirname as Ow,join as Lo}from"node:path";import{simpleGit as Es}from"simple-git";function Dw(t){return`codepipe/context-migration-v${t}`}function Lw(t){let e=Ka(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 \`${Qe}\` stamp (renamed from \`${nn}\``,"when the legacy file is present). Hand-edited files are never touched.","","## Format changes",""];for(let n of e){r.push(`- **v${n.version}** \u2014 ${n.summary}`);for(let o of n.addedPaths)r.push(` - \`${o}\``)}return r.push("","Merge to apply. CodePipe re-checks the stamp on the next daemon start and","clears the \u201Ccontext outdated\u201D badge.","","_Opened automatically by the CodePipe CLI._"),r.join(`
|
|
611
|
+
`)}async function hd(t,e,r,n){let o=Es(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Oo(t,e);if(!i.outdated)return i;let s=Dw(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 Uw(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=Ge(c),u=await l.findOpenPrByBranch?.(c,s)??null;if(u)return n.info(`[ctx] migration PR already open: ${u.url}`),{...i,migrationPrUrl:u.url};let p=await l.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:s,baseBranch:a,title:`CodePipe: context format v${i.templateVersion} \u2192 v${i.currentVersion}`,body:Lw(i)});return n.info(`[ctx] migration PR opened: ${p.url}`),{...i,migrationPrUrl:p.url}}catch(l){return n.warn(`[ctx] migration PR create/find failed (branch pushed, badge without link): ${l instanceof Error?l.message:String(l)}`),i}}async function Uw(t,e,r,n,o,i,s){let a=Es(t),c=_w(Lo(Nw(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",o,c,`origin/${i}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},u={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},p=new Map(Sr(l,u).map(g=>[g.path,g.content])),d=0;for(let g of n.missingPaths){if(g===Qe)continue;let y=p.get(g);if(y==null){s.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let b=Lo(c,g);fd(b)||(jw(Ow(b),{recursive:!0}),gd(b,y),d++)}gd(Lo(c,Qe),Xn(n.currentVersion)),d++;let m=Lo(c,nn);fd(m)&&(md(m,{force:!0}),d++);let f=Es(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 (${d} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),md(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}var yd=k(()=>{"use strict";W();St();Rs();rr()});import{existsSync as Mw,readFileSync as Bw,writeFileSync as Fw}from"node:fs";import{homedir as Gw}from"node:os";import{join as wd}from"node:path";import{parseDocument as Kw}from"yaml";function Hw(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 Ww(t,e){let r=Kw(t);return r.set("repos",e.map(Hw)),r.toString()}function Yw(t,e){let r=[wd(Gw(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(wd(e,"project.yaml")),r}function xn(t,e,r){let n=[],o=[];for(let i of Yw(t,r))if(Mw(i))try{let s=Bw(i,"utf-8"),a=Ww(s,e);a!==s&&(Fw(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}var Ps=k(()=>{"use strict"});import{createCipheriv as qw,createDecipheriv as Vw,createHash as zw,createPrivateKey as Jw,createPublicKey as As,diffieHellman as bd,generateKeyPairSync as kd,hkdfSync as $d,randomBytes as Xw}from"node:crypto";function Uo(){let{publicKey:t,privateKey:e}=kd("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function xe(t){let e=Buffer.from(t,"base64");return(zw("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function gt(t,e){let r=As({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=kd("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=bd({privateKey:o,publicKey:r}),c=Buffer.from($d("sha256",a,Buffer.concat([i,s]),vd,32)),l=Xw(12),u=qw("aes-256-gcm",c,l),p=typeof e=="string"?Buffer.from(e,"utf-8"):e,d=Buffer.concat([u.update(p),u.final()]),m=u.getAuthTag(),f={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:m.toString("base64"),ct:d.toString("base64")};return Buffer.from(JSON.stringify(f),"utf-8").toString("base64")}function Rr(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=Jw({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=As({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=As(n).export({type:"spki",format:"der"}),a=bd({privateKey:n,publicKey:o}),c=Buffer.from($d("sha256",a,Buffer.concat([i,s]),vd,32)),l=Vw("aes-256-gcm",c,Buffer.from(r.iv,"base64"));return l.setAuthTag(Buffer.from(r.tag,"base64")),Buffer.concat([l.update(Buffer.from(r.ct,"base64")),l.final()])}var vd,Oe=k(()=>{"use strict";vd=Buffer.from("devpipe-sealedbox-v1","utf-8")});function Qw(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 xd(t,e,r,n){let o=Qw(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=uo(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=gt(a.publicKey,i)}catch(u){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}var Sd=k(()=>{"use strict";Oe();oe()});function Sn(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 Rn(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 Tn(t,e=process.env){if(!t)return!1;let r=`https://${Ht}:${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 js(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 Rd(t,e=process.env){return js(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>Sn(t,e),e)}function Td(t,e=process.env){return js(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>Rn(t,e),e)}function Id(t,e=process.env){return js(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Ht}:${encodeURIComponent(t)}@bitbucket.org/`,()=>Tn(t,e),e)}var Mo=k(()=>{"use strict";W()});function Cd(t){let e=F(t);if(!e)return null;if(!e.sealKey){let r=Uo();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},X(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:xe(e.sealKey.publicKey)}}async function Ed(t,e,r,n){let o;try{o=JSON.parse(Rr(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=F(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 $t(o.token);return i.github={token:o.token},Tr(i,()=>{process.env.GH_TOKEN=o.token,Rd(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await xt(o.token);return i.gitlab={token:o.token},Tr(i,()=>{process.env.GITLAB_TOKEN=o.token,Td(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 vt(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},Tr(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,Id(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 Tt({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},Tr(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 It(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},Tr(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},Tr(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 Tr(t,e){X(t),e()}var Pd=k(()=>{"use strict";Oe();oe();St();qt();wr();Mo()});import{spawn as Zw}from"node:child_process";function tb(t,e,r,n,o,i){let s={...t},a=(c,l)=>{bt(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 _d(t){let{def:e,onEvent:r}=t,n=tb(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
|
|
612
|
+
`,o.length>Ad&&(o=o.slice(o.length-Ad))},s=(a,c)=>{let l=c.length>jd?c.slice(0,jd)+"\u2026":c;i(l),r({ts:Date.now(),kind:"log",stream:a,text:l})};r({ts:Date.now(),kind:"start",status:"running"});for(let[a,c]of e.steps.entries()){let l=c.name??`step ${a+1}`;r({ts:Date.now(),kind:"step",stepName:l});let u=await rb(c.run,c.timeout_sec,t.cwd,n,s);if(u!==0)return i(`[${l}] exited with code ${u}`),r({ts:Date.now(),kind:"result",status:"failed",exitCode:u,failedStep:l}),{status:"failed",exitCode:u,failedStep:l,logTail:o}}return r({ts:Date.now(),kind:"result",status:"succeeded",exitCode:0}),{status:"succeeded",exitCode:0,logTail:o}}function rb(t,e,r,n,o){return new Promise(i=>{let s=Zw("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??pc)*1e3,l=setTimeout(()=>{a=!0,o("stderr",`step timed out after ${c/1e3}s \u2014 killing`),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},c);l.unref?.();let u=m=>{let f="";return{data:g=>{f+=g.toString("utf-8");let y;for(;(y=f.indexOf(`
|
|
613
|
+
`))!==-1;)o(m,f.slice(0,y).replace(/\r$/,"")),f=f.slice(y+1)},flush:()=>{f.length>0&&o(m,f.replace(/\r$/,"")),f=""}}},p=u("stdout"),d=u("stderr");s.stdout?.on("data",p.data),s.stderr?.on("data",d.data),s.on("error",m=>{clearTimeout(l),o("stderr",`spawn failed: ${m.message}`),i(127)}),s.on("close",(m,f)=>{clearTimeout(l),p.flush(),d.flush(),i(a?eb:m??(f?1:0))})})}var eb,Ad,jd,Nd=k(()=>{"use strict";W();eb=124,Ad=16*1024,jd=4e3});import{existsSync as nb,readFileSync as ob,statSync as Od}from"node:fs";function ib(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function Ld(t,e){let r=fe(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!nb(r)||!Od(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=Od(r);if(n>Dd)throw new Error(`file too large: ${e} is ${n} bytes (limit ${Dd})`);let o=ob(r);return ib(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}var Dd,Ud=k(()=>{"use strict";mt();Dd=2*1024*1024});import{existsSync as sb,readFileSync as ab,writeFileSync as cb}from"node:fs";import{join as lb}from"node:path";import{parseDocument as ub}from"yaml";async function Md(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=bc(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=lb(t,o);if(!sb(s))throw new Error(`${o} not found in context repo (${t})`);let a=ub(ab(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);cb(s,a.toString()),n.push(o)}return{files:n}}var Bd=k(()=>{"use strict";W()});import{existsSync as db,readFileSync as pb,writeFileSync as fb}from"node:fs";import{join as mb}from"node:path";import{isMap as Fd,parseDocument as gb}from"yaml";async function Gd(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||!Tc(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=mb(t,"project.yaml");if(!db(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=gb(pb(o,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>Fd(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!Fd(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),fb(o,i.toString()),{repoName:r,defaultBranch:n}}var Kd=k(()=>{"use strict";W()});import{existsSync as _s,readFileSync as Ns,writeFileSync as hb}from"node:fs";import{join as Bo}from"node:path";import{parseDocument as Os}from"yaml";async function Hd(t,e){let r=[];if(e.stageField!==void 0||e.sourceColumns!==void 0||e.rejectColumns!==void 0||e.doneColumns!==void 0||e.reviewColumns!==void 0||e.statusColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0||e.backlogScope!==void 0){let i=Bo(t,"project.yaml");if(!_s(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=Os(Ns(i,"utf-8"));if(e.stageField!==void 0){let a=typeof e.stageField=="string"?e.stageField.trim():"";a&&a!=="Stage"?s.setIn(["youtrack","stage_field"],a):s.deleteIn(["youtrack","stage_field"])}if(e.rejectColumns!==void 0){let a=e.rejectColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","reject_columns"],a):s.deleteIn(["youtrack","reject_columns"])}if(e.doneColumns!==void 0){let a=e.doneColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","done_columns"],a):s.deleteIn(["youtrack","done_columns"])}if(e.reviewColumns!==void 0){let a=e.reviewColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","review_columns"],a):s.deleteIn(["youtrack","review_columns"])}if(e.statusColumns!==void 0){let a=e.statusColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","status_columns"],a):s.deleteIn(["youtrack","status_columns"])}if(e.sourceColumns!==void 0){let a=e.sourceColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);if(a.length===0)throw new Error("source_columns must be a non-empty list of non-empty strings");s.setIn(["youtrack","source_columns"],a)}if(e.backlogColumn!==void 0){let a=typeof e.backlogColumn=="string"?e.backlogColumn.trim():"";a?s.setIn(["youtrack","backlog_column"],a):s.deleteIn(["youtrack","backlog_column"])}if(e.assignee!==void 0){let a=typeof e.assignee=="string"?e.assignee.trim():"";a?s.setIn(["youtrack","assignee"],a):s.deleteIn(["youtrack","assignee"])}e.requireAssignee!==void 0&&s.setIn(["youtrack","require_assignee"],e.requireAssignee===!0),e.backlogScope!==void 0&&(e.backlogScope==="personal"?s.setIn(["youtrack","backlog_scope"],"personal"):e.backlogScope==="shared"?s.setIn(["youtrack","backlog_scope"],"shared"):s.deleteIn(["youtrack","backlog_scope"])),r.push({path:"project.yaml",content:s.toString()})}if(e.reviewStatus!==void 0||e.writes!==void 0){let i=Bo(t,"regimen.yaml");if(!_s(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=Os(Ns(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)hb(Bo(t,i.path),i.content);return{files:r.map(i=>i.path)}}function Fo(t){if(!t)return"Stage";try{let e=Bo(t,"project.yaml");if(!_s(e))return"Stage";let n=Os(Ns(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}var Ds=k(()=>{"use strict"});var In,Ls=k(()=>{"use strict";Ds();qt();In=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return ql(this.cfg,e)}getIssue(e,r){return Vl(this.cfg,e,r??Fo(this.contextDir))}listComments(e,r){return zl(this.cfg,e,r)}downloadAttachment(e){return Yl(this.cfg,e)}updateStatus(e,r){return Ll(this.cfg,e,r,Fo(this.contextDir))}addComment(e,r,n){return Ul(this.cfg,e,r)}createIssue(e){return Fl(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,Fo(this.contextDir))}editIssue(e,r){return Ml(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return Gl(this.cfg,e,r,n)}fetchStateFields(e){return Xl(this.cfg,e)}}});import{existsSync as Wd,readFileSync as yb,readdirSync as wb}from"node:fs";function Go(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=vb(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:bb(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:$b(kb(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 Ko(t,e,r){if(r.length===0)return;let n=Go(t,e,r),o=r.map(i=>i.issue.key);await We(t,n,`sync(${o.join(", ")}): task data`)}function bb(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(`
|
|
614
|
+
`)}function kb(t,e,r){let n=new Map,o=fe(t,`tasks/${e}/comments.jsonl`);if(Wd(o))for(let i of yb(o,"utf-8").split(`
|
|
615
|
+
`)){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=ur(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function $b(t){return t.map(e=>JSON.stringify(e)).join(`
|
|
614
616
|
`)+(t.length>0?`
|
|
615
|
-
`:"")}function
|
|
616
|
-
`)){let i=o.trim();if(i)try{let s=JSON.parse(i);s&&typeof s.id=="string"&&typeof s.body=="string"&&n.push(s)}catch{}}return n}var
|
|
617
|
+
`:"")}function vb(t,e,r){let n=[],o=fe(t,`tasks/${e}/attachments`);if(Wd(o))for(let i of wb(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}var Ho=k(()=>{"use strict";W();mt()});import{existsSync as xb,readFileSync as Sb}from"node:fs";import{randomBytes as Rb}from"node:crypto";function Yd(t,e){let r=fe(t,`tasks/${e}/comments.jsonl`);if(!xb(r))return[];let n=[];for(let o of Sb(r,"utf-8").split(`
|
|
618
|
+
`)){let i=o.trim();if(i)try{let s=JSON.parse(i);s&&typeof s.id=="string"&&typeof s.body=="string"&&n.push(s)}catch{}}return n}var Cn,Us=k(()=>{"use strict";W();mt();Ho();Do();Cn=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await kn(this.contextDir);let r=e.columns??[];return ud(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>vn(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=$n(this.contextDir,e);return r?vn(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return Yd(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 kn(this.contextDir),!$n(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${Rb(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=ur(r);s&&(i.parsedCommand=s);let c=[...Yd(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
|
|
617
619
|
`)+`
|
|
618
|
-
`;return await ut(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 Mu(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:Ri.statusColumns}]}async mutateRecord(e,r,n){let o=hn(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=yn(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:rn(e),content:ms(i)},..._o(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await ut(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:qn,status:r.targetStatus,links:[],created:n,updated:n},i=yn(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:rn(e),content:ms(o)},..._o(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}}});import{existsSync as vd,readFileSync as xd}from"node:fs";import{join as Sd}from"node:path";import{parseDocument as Td}from"yaml";function Ts(t){if(!t)return"youtrack";try{let e=Sd(t,"project.yaml");return vd(e)&&Td(xd(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function tt(t){let e=Ts(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=Du(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=$w(n);return i?{ok:!0,kind:e,provider:new xn(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=ul();return r?{ok:!0,kind:e,provider:new vn(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function $w(t){try{let e=Sd(t,"project.yaml");if(!vd(e))return null;let r=Td(xd(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var Lo=k(()=>{"use strict";Ht();xs();Ss();Io();xs();Ss()});async function xr(t,e){let n=(Do.get(t)??Promise.resolve()).catch(()=>{}).then(e);Do.set(t,n);try{return await n}finally{Do.get(t)===n&&Do.delete(t)}}async function Rd(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;ln(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return K("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return xr(`${i}/${r.name}`,async()=>{let s=await qt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=be(i,r.name,t.baseDir),{commit:c,pushed:l}=await eu(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force,push:e.push});return ne({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,pushed:l,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"push_branch":{if(!r)return K("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return xr(`${i}/${r.name}`,async()=>{let s=await qt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=be(i,r.name,t.baseDir);return await tu(s,a,{branchName:e.branchName,force:e.force}),ne({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"early_branch":{if(!r)return K("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return xr(`${i}/${r.name}`,async()=>{let s=await qt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=be(i,r.name,t.baseDir),{commit:c,pushed:l}=await ru(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return ne({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return K("no repo spec");let i=Me(r),s=await i.createPullRequest(r,e);return ne({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return K("no repo spec");let i=Me(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ne({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return K("no repo spec");let i=Me(r);return await i.closePR(r,e.prNumber,e.comment),ne({prNumber:e.prNumber,host:i.name})}case"rewrite_cluster_branch":{if(!r)return K("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return xr(`${i}/${r.name}`,async()=>{let s=await qt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=be(i,r.name,t.baseDir),{commit:c,dropped:l}=await ou(s,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:r.defaultBranch});return ne({branch:e.branchName,commit:c,dropped:l,pushed:l>0})})}case"merge_branch":{if(!r)return K("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return xr(`${i}/${r.name}`,async()=>{let s=await qt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=be(i,r.name,t.baseDir),{mergedSha:c}=await iu(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ne({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return K("no repo spec");let i=t.cloneUrlOverride??pn(r),a=(await su(i)).filter(u=>au(u,e.issueKey)),c=Me(r),l=null;if(c.findOpenPrByBranch)for(let u of a){let p=await c.findOpenPrByBranch(r,u).catch(()=>null);if(p){l={number:p.number,url:p.url};break}}return ne({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return K("no repo spec");let i=Me(r);return await i.addPRComment(r,e.prNumber,e.body),ne({prNumber:e.prNumber,host:i.name})}case"tracker_status":{let i=tt({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),ne({issueId:t.trackerIssueId,newStatus:e.newStatus})):K("no tracker_issue_id provided"):K(i.error)}case"tracker_comment":{let i=tt({contextDir:t.contextDir});if(!i.ok)return K(i.error);if(!t.trackerIssueId)return K("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return ne({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=tt({contextDir:t.contextDir});if(!i.ok)return K(i.error);if(!e.projectKey)return K("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 ne({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=tt({contextDir:t.contextDir});if(!i.ok)return K(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 K(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return ne({applied:s})}case"set_project_setting":{if(!t.contextDir)return K("no context repo clone on this CLI");let i=await md(t.contextDir,e.edits);return ne({files:i.files})}case"tracker_edit":{let i=tt({contextDir:t.contextDir});if(!i.ok)return K(i.error);if(!t.contextDir)return K("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 No(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),ne({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return K("no context repo clone on this CLI");let i=await kd(t.contextDir,e);return ne({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return K("no context repo clone on this CLI");let i=await yd(t.contextDir,e);return ne({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ne({reported:!0})):K("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return K("no context repo clone on this CLI");let i=await t.refreshContextStatus();return ne({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return K("no project workspace on this CLI");if(!r)return K("no repo spec");if(!t.onRunActivity)return K("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=bo(t.contextDir),c=s.find(m=>m.id===e.actionId);if(!c){let m=a.find(f=>f.file===`actions/${e.actionId}.yml`);return K(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=Ka(c,e.input);if(!l.ok)return K(l.error);let u=wu(t.contextDir),p=B(e.projectId),d={};return p?.github?.token&&(d.GH_TOKEN=p.github.token),p?.gitlab?.token&&(d.GITLAB_TOKEN=p.gitlab.token),p?.bitbucket&&(d.BITBUCKET_EMAIL=p.bitbucket.email,d.BITBUCKET_API_TOKEN=p.bitbucket.apiToken),p?.youtrack&&(d.YOUTRACK_URL=p.youtrack.url,d.YOUTRACK_TOKEN=p.youtrack.token),xr(`${e.projectId}/${r.name}`,async()=>{await qt(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=be(e.projectId,r.name,t.baseDir),f=await cd({cwd:m,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:g=>i(e.runId,g)});return ne({runId:e.runId,status:f.status,exitCode:f.exitCode,...f.failedStep?{failedStep:f.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return K("no context repo clone on this CLI");let i=pd(t.contextDir,e.path);return ne({path:e.path,...i})}case"local_apply":return K("local_apply requires a local workspace (handled by the daemon)");default:return K(`unsupported action type: ${e.type}`)}}catch(i){return K(i instanceof Error?i.message:String(i))}}function ne(t){return{status:"done",result:t}}function K(t){return{status:"failed",error:t}}var Do,Id=k(()=>{"use strict";W();ts();ld();fd();re();gd();wd();vs();bt();go();gr();Lo();Oo();Do=new Map});import{existsSync as vw,mkdtempSync as xw,rmSync as Sw}from"node:fs";import{tmpdir as Tw}from"node:os";import{join as Rs}from"node:path";import{simpleGit as Cd}from"simple-git";async function Ed(t,e,r){let n=[];for(let a of e){let c=t.repos.find(u=>u.name===a.repoName);if(!c)return{ok:!1,error:`repo "${a.repoName}" not in project.yaml \u2014 run /sync`};let l=Rs(t.root,c.mountAs);if(!vw(Rs(l,".git")))return{ok:!1,error:`${c.mountAs}/ not cloned \u2014 run /sync first`};n.push({payload:a,dir:l,mountAs:c.mountAs,defaultBranch:c.defaultBranch})}let o=[];for(let a of n){let c=Cd(a.dir),l=a.payload;try{await c.fetch()}catch(m){return{ok:!1,error:`fetch failed in ${a.mountAs}: ${Sn(m)}`}}let u=`origin/${l.baseRef}`;await Ew(c,u)||(u=`origin/${a.defaultBranch}`);let p;try{p=(await c.revparse([u])).trim()}catch(m){return{ok:!1,error:`base ${u} unavailable in ${a.mountAs}: ${Sn(m)}`}}let d;try{d=await dn(c,l.deliverySha,()=>Vt(c,{contextRepoCloneUrl:l.contextRepoCloneUrl,deliveryRef:l.deliveryRef,deliverySha:l.deliverySha,baseSha:l.baseSha,commitMessage:l.commitMessage}))}catch(m){return{ok:!1,error:`fetch delivery failed in ${a.mountAs}: ${Sn(m)}`}}o.push({repoName:l.repoName,mountAs:a.mountAs,git:c,branch:l.branchName,startPoint:p,deliveryCommit:d})}let i=[],s=[];for(let a of o){let c=await Pw(a.git,`refs/heads/${a.branch}`);try{let u=(await a.git.revparse([`${a.deliveryCommit}^`])).trim()===a.startPoint?a.deliveryCommit:await Iw(a);await a.git.raw(["branch","-f",a.branch,u]),i.push({git:a.git,mountAs:a.mountAs,branch:a.branch,priorSha:c}),s.push({repoName:a.repoName,branch:a.branch,commit:u}),r.info(`[local-apply] ${a.mountAs}: branch ${a.branch} \u2192 ${u.slice(0,10)} (no checkout)`)}catch(l){return await Cw(i,r),{ok:!1,error:`apply failed in ${a.mountAs}: ${Sn(l)} (rolled back all repos)`}}}return{ok:!0,repos:s}}async function Iw(t){let e=xw(Rs(Tw(),"codepipe-local-apply-"));try{await t.git.raw(["worktree","add","--detach",e,t.startPoint]);let r=Cd(e);try{await r.raw([...Rw,"cherry-pick",t.deliveryCommit])}catch(n){throw await r.raw(["cherry-pick","--abort"]).catch(()=>{}),n}return(await r.revparse(["HEAD"])).trim()}finally{await t.git.raw(["worktree","remove","--force",e]).catch(()=>{}),Sw(e,{recursive:!0,force:!0}),await t.git.raw(["worktree","prune"]).catch(()=>{})}}async function Cw(t,e){for(let r of t)try{r.priorSha?await r.git.raw(["branch","-f",r.branch,r.priorSha]):await r.git.raw(["branch","-D",r.branch])}catch(n){e.warn(`[local-apply] rollback of ${r.mountAs}#${r.branch} failed: ${Sn(n)} \u2014 check manually`)}}async function Ew(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function Pw(t,e){try{return(await t.raw(["rev-parse","--verify","--quiet",e])).trim()||null}catch{return null}}function Sn(t){return t instanceof Error?t.message.trim():String(t)}var Rw,Pd=k(()=>{"use strict";gr();Rw=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{homedir as Aw}from"node:os";import{existsSync as jw,mkdirSync as _w,readFileSync as Nw,writeFileSync as Ow}from"node:fs";import{dirname as Lw,join as Dw}from"node:path";function Is(){return M("FARM_PINS")??Dw(Aw(),".codepipe","farm-pins.json")}function Ad(){let t=Is();if(!jw(t))return{};try{return JSON.parse(Nw(t,"utf-8"))}catch{return{}}}function Uw(t){let e=Is();_w(Lw(e),{recursive:!0}),Ow(e,JSON.stringify(t,null,2)+`
|
|
619
|
-
`,{mode:384})}function
|
|
620
|
-
`,{mode:384})}function Vw(t){return Dd()[t]}function Ps(t,e){let r=Dd();r[t]=e,qw(r)}function Ud(t,e){let r=$e(e),n=Vw(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 ${Es()}.`);return r}var Bd=k(()=>{"use strict";ke();_e()});async function Md(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:Gd(t)});if(!o.ok)throw new Error(`github ${n} for ${e}/${r}: HTTP ${o.status}`);let i=await o.json();if(!i.token)throw new Error(`github ${n} for ${e}/${r}: no token in response`);return i.token}async function Kd(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if($e(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Ud(e.runnerId,e.runnerPublicKey);let i=B(t.projectId)?.github?.token;if(!i)throw new Error("no GitHub token stored for this project on this CLI");let a=((await r.fetchProject(t.hubUrl,t.cliToken,t.projectId)).repos??[]).find(c=>c.host==="github"&&c.owner===e.owner&&c.repoName===e.repo);if(!a)throw new Error(`${e.owner}/${e.repo} is not a GitHub repository of this project`);return{githubToken:i,repo:a}}async function Hd(t,e,r,n=Fd){let o=i=>({type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repo:s}=await Kd(t,e,n);if(!await n.api.repoHasAdmin(i,s.owner,s.repoName))return o(`the GitHub token lacks admin access on ${s.owner}/${s.repoName} \u2014 replace it (project page \u2192 Tokens \u2192 Replace) with a token that has admin rights on this repository`);let a={projectId:t.projectId,runners:[{owner:s.owner,repo:s.repoName,regToken:await n.api.mintRegistrationToken(i,s.owner,s.repoName)}],labels:[Za(e.runnerId)]},c=dt(e.runnerPublicKey,JSON.stringify(a));Ps(e.runnerId,e.fingerprint),r.info(`[ghr] registration token for ${s.owner}/${s.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let l=await n.provisionOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:c});return{type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:l.ok,...l.runners?{runners:l.runners}:{},...l.error?{error:l.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}async function Wd(t,e,r,n=Fd){let o=i=>({type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repo:s}=await Kd(t,e,n),a={owner:s.owner,repo:s.repoName};try{a.removeToken=await n.api.mintRemoveToken(i,s.owner,s.repoName)}catch(p){r.warn(`[ghr] remove-token for ${s.owner}/${s.repoName} failed (${p instanceof Error?p.message:p}) \u2014 the runner host will force-remove`)}let c={projectId:t.projectId,runners:[a]},l=dt(e.runnerPublicKey,JSON.stringify(c));Ps(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle for ${s.owner}/${s.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let u=await n.teardownOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:l,owner:s.owner,repo:s.repoName});return{type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:u.ok,...u.error?{error:u.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}var Gd,zw,Fd,Yd=k(()=>{"use strict";W();_e();Bd();me();re();Gd=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});zw={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Gd(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)=>Md(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Md(t,e,r,"remove-token")},Fd={api:zw,fetchProject:J,provisionOnRunner:Bl,teardownOnRunner:Ml}});function Jw(t){return Ce.test(t)?gt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Ce}`}function Vd(t,e,r,n){let o=Jw(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse($r(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>qd)return{ok:!1,detail:`secret value too large (max ${qd} chars)`};try{return Dc(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function zd(t,e){try{return Uc(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 qd,Jd=k(()=>{"use strict";W();_e();re();qd=16*1024});function Xw(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var Mo,Xd=k(()=>{"use strict";bt();Mo=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=Me(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 Kt){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=Me(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=Xw(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}}});function Qd(t){let{description:e,...r}=t;return r}function Qw(t){let{body:e,...r}=t;return r}function Zw(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 ek(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 Zd(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 Go,ep=k(()=>{"use strict";W();Oo();Lo();Go=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??(()=>tt({contextDir:this.options.contextDir})))();if(!r.ok){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn(`[yt-sync] tracker provider unavailable (${r.error}) \u2014 poller idle.`));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,r.provider)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let v=e.stageField?{stageField:e.stageField}:{},I=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},P=(e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(P){let N=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[F,fe]=await Promise.all([N.length>0?r.listIssues({projectKey:e.projectKey,columns:N,...v,...I}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...v})]),Oe=new Map;for(let A of[...F,...fe])Oe.set(A.id,A);o=[...Oe.values()]}else{let N=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:N,...v,...I})}}catch(v){this.log.warn(`[yt-sync] listIssues failed: ${v instanceof Error?v.message:String(v)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let v of o){if(s.add(v.id),a.has(v.status))continue;let I=await Zd(r,v.id,e.sinceMs,this.log);I&&i.set(v.id,I)}let c=[];for(let v of e.offBoardIssueIds){if(s.has(v))continue;let I=await Zd(r,v,e.sinceMs,this.log);if(I&&I.length>0&&i.set(v,I),e.requireAssignee||I&&I.length>0){let G=await ek(r,v,e.stageField,this.log);if(G)c.push(G);else if(I&&I.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(v=>!a.has(v.status)),{attachmentsByIssue:u,attachmentKeys:p}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let d=[...l,...c].map(v=>({issue:v,comments:i.get(v.id)??[],attachments:u.get(v.id)??[]}));try{await No(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let v of p)this.shippedAttachments.add(v)}catch(v){let I=v instanceof Error?v.message:String(v);this.abandonTick(`context task sync failed: ${I}`);return}let m=this.options.isSelfComment??(()=>!1),f=[],g=[];for(let[v,I]of i){let G=I.filter(N=>!m(N.id));if(G.length===0)continue;f.push({issueId:v,comments:G.map(Qw)});let P=G.flatMap(N=>{let F=sr(N.body);return F?[{commentId:N.id,author:N.author,name:F.name,args:F.args,createdAt:N.createdAt}]:[]});P.length>0&&g.push({issueId:v,commands:P})}let y={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Qd),commentsBatch:f,...g.length>0?{commandsBatch:g}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(Qd)}:{},observedAtMs:n};this.send(y);let $=f.reduce((v,I)=>v+I.comments.length,0),w=g.reduce((v,I)=>v+I.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${$} commands=${w} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let p=`${s.id}:${u.id}`;if(this.shippedAttachments.has(p))continue;let d;try{d=await n.downloadAttachment(u.url)}catch(f){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${f instanceof Error?f.message:String(f)}`);continue}let m=Zw(u.name);l.has(m)&&(m=`${u.id}-${m}`),l.add(m),c.push({name:m,contentBase64:d.toString("base64")}),i.push(p)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}}});import{existsSync as rp,rmSync as tk}from"node:fs";import{join as Tn}from"node:path";import{simpleGit as rk}from"simple-git";import"ws";function Fo(t,e={}){let r=e.log??{info:g=>console.log(g),warn:g=>console.warn(g)};r.info(`codepipe-cli v${Ie} (protocol ${Ve})`);let n=g=>e.onEvent?.(g),o=e.workspace;o?.contextDir&&vu(o.contextDir,r);let i=tp("CLI_TRACKING_POLL_INTERVAL_SEC"),s=tp("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let g=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(g)&&g>0?g*1e3:6e5})(),c=!1,l=!1,u=!1,p=new Set,d=new Set,m=f();function f(){let g=po(t.hubUrl,t.cliToken),y=null,$=new Mo(i,R=>{g.readyState===g.OPEN&&g.send(JSON.stringify(R))},r),w=new Go(s,R=>{g.readyState===g.OPEN&&g.send(JSON.stringify(R))},r,{contextDir:o?.contextDir??null,isSelfComment:R=>d.has(R)}),v=null,I=async()=>{try{let R={trackerProvider:Ts(o?.contextDir??null)};try{let C=await J(t.hubUrl,t.cliToken,t.projectId);R={...R,repos:C.repos,contextRepo:C.contextRepo}}catch(C){r.warn(`[readiness] could not fetch project summary for push checks: ${C instanceof Error?C.message:String(C)}`)}let S=await Cl(t.projectId,R);if(g.readyState!==g.OPEN)return;let x={type:"cli_readiness",projectId:t.projectId,ready:S.ready,checks:S.checks,creds:S.creds,secretNames:Bc(t.projectId),checkedAt:S.checkedAt};if(g.send(JSON.stringify(x)),S.ready)r.info("[readiness] ready");else{let C=S.checks.filter(b=>!b.ok).map(b=>`${b.name}(${b.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${C.join(", ")}`)}let j=Ol(S.creds,u);if(j==="open"){u=!0;let C=Ll(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${C}`),Wt(C)}else j==="rearm"&&(u=!1)}catch(R){r.warn(`[readiness] check failed: ${R instanceof Error?R.message:String(R)}`)}},G=()=>{I(),v=setInterval(()=>void I(),a),typeof v.unref=="function"&&v.unref()},P=()=>{v&&(clearInterval(v),v=null)},N=150,F=new Map,fe=R=>{let S=F.get(R);if(!S||(S.timer&&clearTimeout(S.timer),F.delete(R),S.events.length===0||g.readyState!==g.OPEN))return;let x={type:"run_activity",projectId:t.projectId,runId:R,events:S.events};g.send(JSON.stringify(x))},Oe=(R,S)=>{let x=F.get(R);if(x||(x={events:[],timer:null},F.set(R,x)),x.events.push(S),S.kind==="result"){fe(R);return}x.timer||(x.timer=setTimeout(()=>fe(R),N),x.timer.unref?.())},A=o?.contextDir?new $o(o.contextDir,t.projectId,R=>{g.readyState===g.OPEN&&g.send(JSON.stringify(R))},r):null,h=async()=>{let R=o?.contextDir;if(!R)throw new Error("no context repo clone on this CLI");let S;try{S=(await J(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let x=await Wu(R,t.projectId,S,r);return g.readyState===g.OPEN&&g.send(JSON.stringify(x)),x};return g.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let R=qc(t.projectId),S=M("ORIGIN")==="farm"?"farm":"local",x=M("FARM_ID"),j=t.accountEmail??R.email,C;try{let T=nd(t.projectId);T&&(C=T.publicKey,r.info(`[cred-channel] key fingerprint: ${T.fingerprint}`))}catch(T){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${T instanceof Error?T.message:String(T)}`)}let b={type:"register",projectId:t.projectId,platformVersion:Ie,protocolVersion:Ve,accountId:R.accountId,accountLabel:R.label,origin:S,inFlightActionIds:[...p],...j?{accountEmail:j}:{},...S==="farm"&&x?{farmId:x}:{},...C?{sealPublicKey:C}:{}};g.send(JSON.stringify(b))}),g.on("message",async R=>{let S=R.toString("utf-8");if(S==="pong"||S==="ping")return;let x;try{x=JSON.parse(S)}catch{return}if(!x||typeof x!="object")return;let j=x.type;if(j==="registered"){let b=x;if(b.ok){if(r.info(`[ws] registered for project ${b.projectId}`),n({kind:"registered",projectId:b.projectId??t.projectId}),$.start(),A?.start(),G(),js(t,o,r),o?.contextDir)try{let T=Ro(o.contextDir,t.projectId);g.readyState===g.OPEN&&g.send(JSON.stringify(T)),T.outdated&&(r.warn(`[ctx] context format outdated: v${T.templateVersion} \u2192 v${T.currentVersion}`+(T.missingPaths.length>0?` (missing: ${T.missingPaths.join(", ")})`:"")),l||(l=!0,h().catch(()=>{})))}catch(T){r.warn(`[ctx] context-format detect failed (non-fatal): ${T instanceof Error?T.message:String(T)}`)}}else r.warn(`[ws] register rejected: ${b.reason??"unknown"}`),n({kind:"register_rejected",reason:b.reason??"unknown"}),c=!0,g.close();return}if(j==="hello"){let b=x;y=Hn(b.protocolVersion);let T=y?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${b.platformVersion} (protocol ${b.protocolVersion}) \u2014 ${T}`),y||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Ie}, protocol ${Ve}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${As}`),n({kind:"incompatible",hubVersion:typeof b.platformVersion=="string"?b.platformVersion:null,hubProtocol:typeof b.protocolVersion=="number"?b.protocolVersion:null,updateCommand:As}));return}if(j==="tracking_targets"){$.setTargets(x.targets);return}if(j==="youtrack_sync_request"){w.setRequest(x);return}if(j==="youtrack_force_sync"){w.forceSync();return}if(j==="sync_local"){await ik(x,o,g,r);return}if(j==="provision_repo"){let b=x;r.info(`[repo] provision_repo: ${b.repo.name} (${b.repo.host}:${b.repo.owner}/${b.repo.repoName})`),await nk(t,o,b.repo,r),await js(t,o,r);return}if(j==="remove_repo"){let b=x;r.info(`[repo] remove_repo: ${b.repoName}${b.purge?" (purge)":""}`),await js(t,o,r),b.purge&&ok(t,o,b.repoName,r);return}if(j==="context_write"){await sk(x,o,g,r);return}if(j==="adr_promote"){await ak(x,o,g,r);return}if(j==="cred_update"){let b=x,T=B(t.projectId),O=T?.sealKey?await od(t.projectId,b.kind,b.sealed,T.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},q={type:"cred_update_result",updateId:b.updateId,projectId:t.projectId,ok:O.ok,...O.detail?{detail:O.detail}:{}};g.readyState===g.OPEN&&g.send(JSON.stringify(q)),O.ok?(r.info(`[cred] ${b.kind} replaced${O.detail?` \u2014 ${O.detail}`:""}`),I()):r.warn(`[cred] ${b.kind} replacement rejected: ${O.detail??"unknown"}`);return}if(j==="readiness_check"){r.info("[readiness] on-demand check requested"),I();return}if(j==="agent_login_start"){_l(t,g,x,r,I);return}if(j==="move_to_farm"){let b=x;r.info(`[farm-move] request to move ${t.projectId} onto farm ${b.farmName} (${b.farmId})`);let T=await Od(t,b,o?.contextDir,r);g.readyState===g.OPEN&&g.send(JSON.stringify(T)),T.ok?r.info(`[farm-move] done \u2014 farm daemon ${T.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${T.error??"unknown error"}`);return}if(j==="gh_runner_setup"){let b=x;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${b.runnerName} (${b.runnerId})`);let T=await Hd(t,b,r);g.readyState===g.OPEN&&g.send(JSON.stringify(T)),T.ok?r.info(`[ghr] runners connected on ${b.runnerName}`):r.warn(`[ghr] setup failed: ${T.error??"see per-repo statuses"}`);return}if(j==="gh_runner_teardown"){let b=x;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${b.runnerName} (${b.runnerId})`);let T=await Wd(t,b,r);g.readyState===g.OPEN&&g.send(JSON.stringify(T)),T.ok?r.info(`[ghr] runners disconnected from ${b.runnerName}`):r.warn(`[ghr] teardown failed: ${T.error??"unknown error"}`);return}if(j==="tracker_fields_request"){let b=x,T={type:"tracker_fields_result",requestId:b.requestId,projectId:t.projectId,ok:!1},O=tt({contextDir:o?.contextDir??null});if(!O.ok)T.error=O.error;else try{T.fields=await O.provider.fetchStateFields(b.projectKey),T.ok=!0}catch(q){T.error=q instanceof Error?q.message:String(q)}g.readyState===g.OPEN&&g.send(JSON.stringify(T)),T.ok||r.warn(`[yt-fields] listing failed: ${T.error??"unknown"}`);return}if(j==="project_secret_update"||j==="project_secret_delete"){let b=x,T;if(b.type==="project_secret_update"){let q=B(t.projectId);T=q?.sealKey?Vd(t.projectId,b.name,b.sealed,q.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else T=zd(t.projectId,b.name);let O={type:"project_secret_update_result",updateId:b.updateId,projectId:t.projectId,ok:T.ok,...T.detail?{detail:T.detail}:{}};g.readyState===g.OPEN&&g.send(JSON.stringify(O)),T.ok?(r.info(`[secret] ${b.name} ${b.type==="project_secret_update"?"saved":"deleted"}`+(T.detail?` \u2014 ${T.detail}`:"")),I()):r.warn(`[secret] ${b.name} rejected: ${T.detail??"unknown"}`);return}if(j==="auto_apply_local"){let b=x;if(!o?.contextDir){r.warn(`[apply] auto_apply_local for ${b.claim.taskKey} \u2014 no workspace (headless), skipped; task stays in READY_TO_APPLY`);return}let T=await du({hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId,root:o.root,contextDir:o.contextDir,repos:o.repos},b.claim,r).catch(O=>({ok:!1,message:O instanceof Error?O.message:String(O)}));T.ok?r.info(`[apply] ${b.claim.taskKey}: ${T.message}`):r.warn(`[apply] ${b.claim.taskKey}: ${T.message} \u2014 task stays in READY_TO_APPLY`),n({kind:"local_applied",taskKey:b.claim.taskKey,ok:T.ok,...T.ok?{branches:T.branches??[]}:{error:T.message}});return}if(j==="sandbox_keys"){let b=B(t.projectId);if(!b){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let T=ur(t.projectId),O=Qu(x,b,T,r);for(let q of O)g.readyState===g.OPEN&&g.send(JSON.stringify(q));return}if(j!=="dispatch_action")return;let C=x;if(y===!1){let b=`refused: HUB protocol incompatible with CLI v${Ie} (protocol ${Ve})`;g.send(JSON.stringify({type:"action_result",actionId:C.actionId,status:"failed",error:b})),r.warn(`[exec] ${C.actionId} (${C.action.type}) \u2192 REFUSED: ${b}`),r.warn(`[exec] update the CLI to clear this: ${As}`),n({kind:"action",actionId:C.actionId,actionType:C.action.type,ok:!1,error:b});return}if(C.action.type==="local_apply"){p.add(C.actionId);try{let b;if(!o)b={status:"failed",error:"no local workspace on this CLI"};else{let O=await Ed(o,C.action.repos,r);b=O.ok?{status:"done",result:{repos:O.repos}}:{status:"failed",error:O.error}}g.send(JSON.stringify({type:"action_result",actionId:C.actionId,...b}));let T=b.status!=="failed";T?r.info(`[exec] ${C.actionId} (local_apply) \u2192 done`):r.warn(`[exec] ${C.actionId} (local_apply) \u2192 FAILED: ${b.status==="failed"?b.error:"?"}`),n({kind:"action",actionId:C.actionId,actionType:"local_apply",ok:T,...b.status==="failed"?{error:b.error}:{}})}finally{p.delete(C.actionId)}return}p.add(C.actionId);try{let b=await Rd({action:C.action,repo:C.repo,trackerIssueId:C.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:A?()=>A.reportNow():void 0,refreshContextStatus:o?.contextDir?h:void 0,onRunActivity:Oe}).catch(q=>({status:"failed",error:q instanceof Error?q.message:String(q)}));C.action.type==="tracker_comment"&&b.status==="done"&&"result"in b&&typeof b.result?.commentId=="string"&&d.add(b.result.commentId),g.send(JSON.stringify({type:"action_result",actionId:C.actionId,...b}));let T=b.status!=="failed",O=!T&&"error"in b?b.error:void 0;T?r.info(`[exec] ${C.actionId} (${C.action.type}) \u2192 done`):r.warn(`[exec] ${C.actionId} (${C.action.type}) \u2192 FAILED: ${O??"?"}`),n({kind:"action",actionId:C.actionId,actionType:C.action.type,ok:T,...O?{error:O}:{}})}finally{p.delete(C.actionId)}}),g.on("close",(R,S)=>{let x=S?.toString("utf-8")??"";if(r.info(`[ws] closed code=${R}${x?` reason=${x}`:""}`),$.stop(),w.stop(),A?.stop(),P(),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:R}),!c&&setTimeout(()=>{m=f()},2e3)}),g.on("error",R=>r.warn(`[ws] error: ${R.message}`)),g}return{stop(){c=!0,m.close()}}}async function js(t,e,r){try{let n=await J(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=wn(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 nk(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?Tn(e.root,o):be(t.projectId,r.name);if(rp(Tn(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await rk().clone(pn(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 ok(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?Tn(e.root,o):be(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!rp(Tn(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{tk(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 ik(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=Tn(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await fu(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 sk(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 ut(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 ak(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 Eu(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 tp(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}var As,_s=k(()=>{"use strict";ke();W();Vc();Nl();Dl();uo();Zi();mu();bu();Pu();Rt();lt();ds();Yu();hs();gr();Zu();id();Id();Pd();Ld();Yd();me();Jd();mr();re();Xd();ep();Lo();As="npm i -g @code-partner/codepipe@latest"});import{execFileSync as ck}from"node:child_process";import{mkdtempSync as lk,mkdirSync as uk,readFileSync as np,rmSync as dk,writeFileSync as pk}from"node:fs";import{tmpdir as fk}from"node:os";import{dirname as mk,join as op}from"node:path";function ip(t="codepipe-context"){let e=lk(op(fk(),"codepipe-ssh-")),r=op(e,"id_ed25519");try{return ck("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:np(r,"utf-8"),publicKey:np(`${r}.pub`,"utf-8").trim()}}finally{dk(e,{recursive:!0,force:!0})}}async function sp(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 ap(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 cp(t,e){uk(mk(t),{recursive:!0});let r=e.endsWith(`
|
|
620
|
+
`;return await We(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 dd(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:Bi.statusColumns}]}async mutateRecord(e,r,n){let o=$n(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=vn(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:cn(e),content:Cs(i)},...Go(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await We(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:ro,status:r.targetStatus,links:[],created:n,updated:n},i=vn(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:cn(e),content:Cs(o)},...Go(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}}});import{existsSync as qd,readFileSync as Vd}from"node:fs";import{join as zd}from"node:path";import{parseDocument as Jd}from"yaml";function Ms(t){if(!t)return"youtrack";try{let e=zd(t,"project.yaml");return qd(e)&&Jd(Vd(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function it(t){let e=Ms(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=cd(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=Tb(n);return i?{ok:!0,kind:e,provider:new Cn(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=Ol();return r?{ok:!0,kind:e,provider:new In(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function Tb(t){try{let e=zd(t,"project.yaml");if(!qd(e))return null;let r=Jd(Vd(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var Wo=k(()=>{"use strict";qt();Ls();Us();Do();Ls();Us()});async function Ir(t,e){let n=(Yo.get(t)??Promise.resolve()).catch(()=>{}).then(e);Yo.set(t,n);try{return await n}finally{Yo.get(t)===n&&Yo.delete(t)}}async function Xd(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;mn(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return Y("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Ir(`${i}/${r.name}`,async()=>{let s=await Jt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{commit:c,pushed:l}=await Ru(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force,push:e.push});return ie({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,pushed:l,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"push_branch":{if(!r)return Y("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Ir(`${i}/${r.name}`,async()=>{let s=await Jt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir);return await Tu(s,a,{branchName:e.branchName,force:e.force}),ie({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"early_branch":{if(!r)return Y("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Ir(`${i}/${r.name}`,async()=>{let s=await Jt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{commit:c,pushed:l}=await Iu(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return ie({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return Y("no repo spec");let i=Ge(r),s=await i.createPullRequest(r,e);return ie({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return Y("no repo spec");let i=Ge(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ie({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return Y("no repo spec");let i=Ge(r);return await i.closePR(r,e.prNumber,e.comment),ie({prNumber:e.prNumber,host:i.name})}case"rewrite_cluster_branch":{if(!r)return Y("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Ir(`${i}/${r.name}`,async()=>{let s=await Jt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{commit:c,dropped:l}=await Eu(s,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:r.defaultBranch});return ie({branch:e.branchName,commit:c,dropped:l,pushed:l>0})})}case"merge_branch":{if(!r)return Y("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Ir(`${i}/${r.name}`,async()=>{let s=await Jt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{mergedSha:c}=await Pu(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ie({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return Y("no repo spec");let i=t.cloneUrlOverride??yn(r),a=(await Au(i)).filter(u=>ju(u,e.issueKey)),c=Ge(r),l=null;if(c.findOpenPrByBranch)for(let u of a){let p=await c.findOpenPrByBranch(r,u).catch(()=>null);if(p){l={number:p.number,url:p.url};break}}return ie({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return Y("no repo spec");let i=Ge(r);return await i.addPRComment(r,e.prNumber,e.body),ie({prNumber:e.prNumber,host:i.name})}case"tracker_status":{let i=it({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),ie({issueId:t.trackerIssueId,newStatus:e.newStatus})):Y("no tracker_issue_id provided"):Y(i.error)}case"tracker_comment":{let i=it({contextDir:t.contextDir});if(!i.ok)return Y(i.error);if(!t.trackerIssueId)return Y("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return ie({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=it({contextDir:t.contextDir});if(!i.ok)return Y(i.error);if(!e.projectKey)return Y("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 ie({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=it({contextDir:t.contextDir});if(!i.ok)return Y(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 Y(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return ie({applied:s})}case"set_project_setting":{if(!t.contextDir)return Y("no context repo clone on this CLI");let i=await Md(t.contextDir,e.edits);return ie({files:i.files})}case"tracker_edit":{let i=it({contextDir:t.contextDir});if(!i.ok)return Y(i.error);if(!t.contextDir)return Y("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 Ko(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),ie({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return Y("no context repo clone on this CLI");let i=await Hd(t.contextDir,e);return ie({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return Y("no context repo clone on this CLI");let i=await Gd(t.contextDir,e);return ie({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ie({reported:!0})):Y("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return Y("no context repo clone on this CLI");let i=await t.refreshContextStatus();return ie({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return Y("no project workspace on this CLI");if(!r)return Y("no repo spec");if(!t.onRunActivity)return Y("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=Eo(t.contextDir),c=s.find(m=>m.id===e.actionId);if(!c){let m=a.find(f=>f.file===`actions/${e.actionId}.yml`);return Y(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=mc(c,e.input);if(!l.ok)return Y(l.error);let u=Ku(t.contextDir),p=F(e.projectId),d={};return p?.github?.token&&(d.GH_TOKEN=p.github.token),p?.gitlab?.token&&(d.GITLAB_TOKEN=p.gitlab.token),p?.bitbucket&&(d.BITBUCKET_EMAIL=p.bitbucket.email,d.BITBUCKET_API_TOKEN=p.bitbucket.apiToken),p?.youtrack&&(d.YOUTRACK_URL=p.youtrack.url,d.YOUTRACK_TOKEN=p.youtrack.token),Ir(`${e.projectId}/${r.name}`,async()=>{await Jt(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=ve(e.projectId,r.name,t.baseDir),f=await _d({cwd:m,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:g=>i(e.runId,g)});return ie({runId:e.runId,status:f.status,exitCode:f.exitCode,...f.failedStep?{failedStep:f.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return Y("no context repo clone on this CLI");let i=Ld(t.contextDir,e.path);return ie({path:e.path,...i})}case"local_apply":return Y("local_apply requires a local workspace (handled by the daemon)");default:return Y(`unsupported action type: ${e.type}`)}}catch(i){return Y(i instanceof Error?i.message:String(i))}}function ie(t){return{status:"done",result:t}}function Y(t){return{status:"failed",error:t}}var Yo,Qd=k(()=>{"use strict";W();gs();Nd();Ud();oe();Bd();Kd();Ds();St();So();br();Wo();Ho();Yo=new Map});import{existsSync as Ib,mkdtempSync as Cb,rmSync as Eb}from"node:fs";import{tmpdir as Pb}from"node:os";import{join as Bs}from"node:path";import{simpleGit as Zd}from"simple-git";async function ep(t,e,r){let n=[];for(let a of e){let c=t.repos.find(u=>u.name===a.repoName);if(!c)return{ok:!1,error:`repo "${a.repoName}" not in project.yaml \u2014 run /sync`};let l=Bs(t.root,c.mountAs);if(!Ib(Bs(l,".git")))return{ok:!1,error:`${c.mountAs}/ not cloned \u2014 run /sync first`};n.push({payload:a,dir:l,mountAs:c.mountAs,defaultBranch:c.defaultBranch})}let o=[];for(let a of n){let c=Zd(a.dir),l=a.payload;try{await c.fetch()}catch(m){return{ok:!1,error:`fetch failed in ${a.mountAs}: ${En(m)}`}}let u=`origin/${l.baseRef}`;await Nb(c,u)||(u=`origin/${a.defaultBranch}`);let p;try{p=(await c.revparse([u])).trim()}catch(m){return{ok:!1,error:`base ${u} unavailable in ${a.mountAs}: ${En(m)}`}}let d;try{d=await hn(c,l.deliverySha,()=>Xt(c,{contextRepoCloneUrl:l.contextRepoCloneUrl,deliveryRef:l.deliveryRef,deliverySha:l.deliverySha,baseSha:l.baseSha,commitMessage:l.commitMessage}))}catch(m){return{ok:!1,error:`fetch delivery failed in ${a.mountAs}: ${En(m)}`}}o.push({repoName:l.repoName,mountAs:a.mountAs,git:c,branch:l.branchName,startPoint:p,deliveryCommit:d})}let i=[],s=[];for(let a of o){let c=await Ob(a.git,`refs/heads/${a.branch}`);try{let u=(await a.git.revparse([`${a.deliveryCommit}^`])).trim()===a.startPoint?a.deliveryCommit:await jb(a);await a.git.raw(["branch","-f",a.branch,u]),i.push({git:a.git,mountAs:a.mountAs,branch:a.branch,priorSha:c}),s.push({repoName:a.repoName,branch:a.branch,commit:u}),r.info(`[local-apply] ${a.mountAs}: branch ${a.branch} \u2192 ${u.slice(0,10)} (no checkout)`)}catch(l){return await _b(i,r),{ok:!1,error:`apply failed in ${a.mountAs}: ${En(l)} (rolled back all repos)`}}}return{ok:!0,repos:s}}async function jb(t){let e=Cb(Bs(Pb(),"codepipe-local-apply-"));try{await t.git.raw(["worktree","add","--detach",e,t.startPoint]);let r=Zd(e);try{await r.raw([...Ab,"cherry-pick",t.deliveryCommit])}catch(n){throw await r.raw(["cherry-pick","--abort"]).catch(()=>{}),n}return(await r.revparse(["HEAD"])).trim()}finally{await t.git.raw(["worktree","remove","--force",e]).catch(()=>{}),Eb(e,{recursive:!0,force:!0}),await t.git.raw(["worktree","prune"]).catch(()=>{})}}async function _b(t,e){for(let r of t)try{r.priorSha?await r.git.raw(["branch","-f",r.branch,r.priorSha]):await r.git.raw(["branch","-D",r.branch])}catch(n){e.warn(`[local-apply] rollback of ${r.mountAs}#${r.branch} failed: ${En(n)} \u2014 check manually`)}}async function Nb(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function Ob(t,e){try{return(await t.raw(["rev-parse","--verify","--quiet",e])).trim()||null}catch{return null}}function En(t){return t instanceof Error?t.message.trim():String(t)}var Ab,tp=k(()=>{"use strict";br();Ab=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{homedir as Db}from"node:os";import{existsSync as Lb,mkdirSync as Ub,readFileSync as Mb,writeFileSync as Bb}from"node:fs";import{dirname as Fb,join as Gb}from"node:path";function Fs(){return K("FARM_PINS")??Gb(Db(),".codepipe","farm-pins.json")}function rp(){let t=Fs();if(!Lb(t))return{};try{return JSON.parse(Mb(t,"utf-8"))}catch{return{}}}function Kb(t){let e=Fs();Ub(Fb(e),{recursive:!0}),Bb(e,JSON.stringify(t,null,2)+`
|
|
621
|
+
`,{mode:384})}function Hb(t){return rp()[t]}function qo(t,e){let r=rp();r[t]=e,Kb(r)}function Vo(t,e){let r=xe(e),n=Hb(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 ${Fs()}.`);return r}var Gs=k(()=>{"use strict";ke();Oe()});import{existsSync as np,readFileSync as op}from"node:fs";import{join as ip}from"node:path";async function sp(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=xe(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Vo(e.farmId,e.farmPublicKey);let s=F(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 d=ip(r,"project.yaml"),m=ip(r,"regimen.yaml");np(d)&&np(m)?c={projectYaml:op(d,"utf-8"),regimenYaml:op(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}:{}},u=gt(e.farmPublicKey,JSON.stringify(l));qo(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let p=await vo(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:u});return p.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...p.daemonStatus?{daemonStatus:p.daemonStatus}:{}}:o(p.error??"farm provisioning failed")}catch(i){return o(i instanceof Error?i.message:String(i))}}var ap=k(()=>{"use strict";Oe();Gs();ge();oe()});import{homedir as Wb}from"node:os";import{existsSync as Yb,mkdirSync as qb,readFileSync as Vb,writeFileSync as zb}from"node:fs";import{dirname as Jb,join as Xb}from"node:path";function Ks(){return K("RUNNER_PINS")??Xb(Wb(),".codepipe","runner-pins.json")}function cp(){let t=Ks();if(!Yb(t))return{};try{return JSON.parse(Vb(t,"utf-8"))}catch{return{}}}function Qb(t){let e=Ks();qb(Jb(e),{recursive:!0}),zb(e,JSON.stringify(t,null,2)+`
|
|
622
|
+
`,{mode:384})}function Zb(t){return cp()[t]}function Hs(t,e){let r=cp();r[t]=e,Qb(r)}function lp(t,e){let r=xe(e),n=Zb(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 ${Ks()}.`);return r}var up=k(()=>{"use strict";ke();Oe()});async function dp(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:pp(t)});if(!o.ok)throw new Error(`github ${n} for ${e}/${r}: HTTP ${o.status}`);let i=await o.json();if(!i.token)throw new Error(`github ${n} for ${e}/${r}: no token in response`);return i.token}async function mp(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(xe(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");lp(e.runnerId,e.runnerPublicKey);let i=F(t.projectId)?.github?.token;if(!i)throw new Error("no GitHub token stored for this project on this CLI");let a=((await r.fetchProject(t.hubUrl,t.cliToken,t.projectId)).repos??[]).find(c=>c.host==="github"&&c.owner===e.owner&&c.repoName===e.repo);if(!a)throw new Error(`${e.owner}/${e.repo} is not a GitHub repository of this project`);return{githubToken:i,repo:a}}async function gp(t,e,r,n=fp){let o=i=>({type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repo:s}=await mp(t,e,n);if(!await n.api.repoHasAdmin(i,s.owner,s.repoName))return o(`the GitHub token lacks admin access on ${s.owner}/${s.repoName} \u2014 replace it (project page \u2192 Tokens \u2192 Replace) with a token that has admin rights on this repository`);let a={projectId:t.projectId,runners:[{owner:s.owner,repo:s.repoName,regToken:await n.api.mintRegistrationToken(i,s.owner,s.repoName)}],labels:[Sc(e.runnerId)]},c=gt(e.runnerPublicKey,JSON.stringify(a));Hs(e.runnerId,e.fingerprint),r.info(`[ghr] registration token for ${s.owner}/${s.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let l=await n.provisionOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:c});return{type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:l.ok,...l.runners?{runners:l.runners}:{},...l.error?{error:l.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}async function hp(t,e,r,n=fp){let o=i=>({type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repo:s}=await mp(t,e,n),a={owner:s.owner,repo:s.repoName};try{a.removeToken=await n.api.mintRemoveToken(i,s.owner,s.repoName)}catch(p){r.warn(`[ghr] remove-token for ${s.owner}/${s.repoName} failed (${p instanceof Error?p.message:p}) \u2014 the runner host will force-remove`)}let c={projectId:t.projectId,runners:[a]},l=gt(e.runnerPublicKey,JSON.stringify(c));Hs(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle for ${s.owner}/${s.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let u=await n.teardownOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:l,owner:s.owner,repo:s.repoName});return{type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:u.ok,...u.error?{error:u.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}var pp,ek,fp,yp=k(()=>{"use strict";W();Oe();up();ge();oe();pp=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});ek={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:pp(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)=>dp(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>dp(t,e,r,"remove-token")},fp={api:ek,fetchProject:Q,provisionOnRunner:uu,teardownOnRunner:du}});function tk(t){return Ae.test(t)?bt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Ae}`}function bp(t,e,r,n){let o=tk(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(Rr(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>wp)return{ok:!1,detail:`secret value too large (max ${wp} chars)`};try{return cl(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function kp(t,e){try{return ll(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 wp,$p=k(()=>{"use strict";W();Oe();oe();wp=16*1024});function rk(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var zo,vp=k(()=>{"use strict";St();zo=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=Ge(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 Yt){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=Ge(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=rk(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}}});function xp(t){let{description:e,...r}=t;return r}function nk(t){let{body:e,...r}=t;return r}function ok(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 ik(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 Sp(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 Jo,Rp=k(()=>{"use strict";W();Ho();Wo();Jo=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??(()=>it({contextDir:this.options.contextDir})))();if(!r.ok){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn(`[yt-sync] tracker provider unavailable (${r.error}) \u2014 poller idle.`));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,r.provider)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let x=e.stageField?{stageField:e.stageField}:{},I=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},j=(e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(j){let v=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[A,L]=await Promise.all([v.length>0?r.listIssues({projectKey:e.projectKey,columns:v,...x,...I}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...x})]),G=new Map;for(let E of[...A,...L])G.set(E.id,E);o=[...G.values()]}else{let v=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:v,...x,...I})}}catch(x){this.log.warn(`[yt-sync] listIssues failed: ${x instanceof Error?x.message:String(x)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let x of o){if(s.add(x.id),a.has(x.status))continue;let I=await Sp(r,x.id,e.sinceMs,this.log);I&&i.set(x.id,I)}let c=[];for(let x of e.offBoardIssueIds){if(s.has(x))continue;let I=await Sp(r,x,e.sinceMs,this.log);if(I&&I.length>0&&i.set(x,I),e.requireAssignee||I&&I.length>0){let H=await ik(r,x,e.stageField,this.log);if(H)c.push(H);else if(I&&I.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(x=>!a.has(x.status)),{attachmentsByIssue:u,attachmentKeys:p}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let d=[...l,...c].map(x=>({issue:x,comments:i.get(x.id)??[],attachments:u.get(x.id)??[]}));try{await Ko(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let x of p)this.shippedAttachments.add(x)}catch(x){let I=x instanceof Error?x.message:String(x);this.abandonTick(`context task sync failed: ${I}`);return}let m=this.options.isSelfComment??(()=>!1),f=[],g=[];for(let[x,I]of i){let H=I.filter(v=>!m(v.id));if(H.length===0)continue;f.push({issueId:x,comments:H.map(nk)});let j=H.flatMap(v=>{let A=ur(v.body);return A?[{commentId:v.id,author:v.author,name:A.name,args:A.args,createdAt:v.createdAt}]:[]});j.length>0&&g.push({issueId:x,commands:j})}let y={type:"youtrack_observation",projectId:e.projectId,issues:o.map(xp),commentsBatch:f,...g.length>0?{commandsBatch:g}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(xp)}:{},observedAtMs:n};this.send(y);let b=f.reduce((x,I)=>x+I.comments.length,0),w=g.reduce((x,I)=>x+I.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${b} commands=${w} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let p=`${s.id}:${u.id}`;if(this.shippedAttachments.has(p))continue;let d;try{d=await n.downloadAttachment(u.url)}catch(f){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${f instanceof Error?f.message:String(f)}`);continue}let m=ok(u.name);l.has(m)&&(m=`${u.id}-${m}`),l.add(m),c.push({name:m,contentBase64:d.toString("base64")}),i.push(p)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}}});import{existsSync as Ip,rmSync as sk}from"node:fs";import{join as Pn}from"node:path";import{simpleGit as ak}from"simple-git";import"ws";function Xo(t,e={}){let r=e.log??{info:g=>console.log(g),warn:g=>console.warn(g)};r.info(`codepipe-cli v${Ee} (protocol ${Xe})`);let n=g=>e.onEvent?.(g),o=e.workspace;o?.contextDir&&qu(o.contextDir,r);let i=Tp("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Tp("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let g=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(g)&&g>0?g*1e3:6e5})(),c=!1,l=!1,u=!1,p=new Set,d=new Set,m=f();function f(){let g=$o(t.hubUrl,t.cliToken),y=null,b=new zo(i,C=>{g.readyState===g.OPEN&&g.send(JSON.stringify(C))},r),w=new Jo(s,C=>{g.readyState===g.OPEN&&g.send(JSON.stringify(C))},r,{contextDir:o?.contextDir??null,isSelfComment:C=>d.has(C)}),x=null,I=async()=>{try{let C={trackerProvider:Ms(o?.contextDir??null)};try{let P=await Q(t.hubUrl,t.cliToken,t.projectId);C={...C,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 R=await Zl(t.projectId,C);if(g.readyState!==g.OPEN)return;let S={type:"cli_readiness",projectId:t.projectId,ready:R.ready,checks:R.checks,creds:R.creds,secretNames:ul(t.projectId),checkedAt:R.checkedAt};if(g.send(JSON.stringify(S)),R.ready)r.info("[readiness] ready");else{let P=R.checks.filter($=>!$.ok).map($=>`${$.name}(${$.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${P.join(", ")}`)}let N=su(R.creds,u);if(N==="open"){u=!0;let P=au(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${P}`),Vt(P)}else N==="rearm"&&(u=!1)}catch(C){r.warn(`[readiness] check failed: ${C instanceof Error?C.message:String(C)}`)}},H=()=>{I(),x=setInterval(()=>void I(),a),typeof x.unref=="function"&&x.unref()},j=()=>{x&&(clearInterval(x),x=null)},v=150,A=new Map,L=C=>{let R=A.get(C);if(!R||(R.timer&&clearTimeout(R.timer),A.delete(C),R.events.length===0||g.readyState!==g.OPEN))return;let S={type:"run_activity",projectId:t.projectId,runId:C,events:R.events};g.send(JSON.stringify(S))},G=(C,R)=>{let S=A.get(C);if(S||(S={events:[],timer:null},A.set(C,S)),S.events.push(R),R.kind==="result"){L(C);return}S.timer||(S.timer=setTimeout(()=>L(C),v),S.timer.unref?.())},E=o?.contextDir?new Po(o.contextDir,t.projectId,C=>{g.readyState===g.OPEN&&g.send(JSON.stringify(C))},r):null,h=async()=>{let C=o?.contextDir;if(!C)throw new Error("no context repo clone on this CLI");let R;try{R=(await Q(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let S=await hd(C,t.projectId,R,r);return g.readyState===g.OPEN&&g.send(JSON.stringify(S)),S};return g.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let C=wl(t.projectId),R=K("ORIGIN")==="farm"?"farm":"local",S=K("FARM_ID"),N=t.accountEmail??C.email,P;try{let T=Cd(t.projectId);T&&(P=T.publicKey,r.info(`[cred-channel] key fingerprint: ${T.fingerprint}`))}catch(T){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${T instanceof Error?T.message:String(T)}`)}let $={type:"register",projectId:t.projectId,platformVersion:Ee,protocolVersion:Xe,accountId:C.accountId,accountLabel:C.label,origin:R,inFlightActionIds:[...p],...N?{accountEmail:N}:{},...R==="farm"&&S?{farmId:S}:{},...P?{sealPublicKey:P}:{}};g.send(JSON.stringify($))}),g.on("message",async C=>{let R=C.toString("utf-8");if(R==="pong"||R==="ping")return;let S;try{S=JSON.parse(R)}catch{return}if(!S||typeof S!="object")return;let N=S.type;if(N==="registered"){let $=S;if($.ok){if(r.info(`[ws] registered for project ${$.projectId}`),n({kind:"registered",projectId:$.projectId??t.projectId}),b.start(),E?.start(),H(),Ys(t,o,r),o?.contextDir)try{let T=Oo(o.contextDir,t.projectId);g.readyState===g.OPEN&&g.send(JSON.stringify(T)),T.outdated&&(r.warn(`[ctx] context format outdated: v${T.templateVersion} \u2192 v${T.currentVersion}`+(T.missingPaths.length>0?` (missing: ${T.missingPaths.join(", ")})`:"")),l||(l=!0,h().catch(()=>{})))}catch(T){r.warn(`[ctx] context-format detect failed (non-fatal): ${T instanceof Error?T.message:String(T)}`)}}else r.warn(`[ws] register rejected: ${$.reason??"unknown"}`),n({kind:"register_rejected",reason:$.reason??"unknown"}),c=!0,g.close();return}if(N==="hello"){let $=S;y=Jn($.protocolVersion);let T=y?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${$.platformVersion} (protocol ${$.protocolVersion}) \u2014 ${T}`),y||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Ee}, protocol ${Xe}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Ws}`),n({kind:"incompatible",hubVersion:typeof $.platformVersion=="string"?$.platformVersion:null,hubProtocol:typeof $.protocolVersion=="number"?$.protocolVersion:null,updateCommand:Ws}));return}if(N==="tracking_targets"){b.setTargets(S.targets);return}if(N==="youtrack_sync_request"){w.setRequest(S);return}if(N==="youtrack_force_sync"){w.forceSync();return}if(N==="sync_local"){await uk(S,o,g,r);return}if(N==="provision_repo"){let $=S;r.info(`[repo] provision_repo: ${$.repo.name} (${$.repo.host}:${$.repo.owner}/${$.repo.repoName})`),await ck(t,o,$.repo,r),await Ys(t,o,r);return}if(N==="remove_repo"){let $=S;r.info(`[repo] remove_repo: ${$.repoName}${$.purge?" (purge)":""}`),await Ys(t,o,r),$.purge&&lk(t,o,$.repoName,r);return}if(N==="context_write"){await dk(S,o,g,r);return}if(N==="adr_promote"){await pk(S,o,g,r);return}if(N==="cred_update"){let $=S,T=F(t.projectId),D=T?.sealKey?await Ed(t.projectId,$.kind,$.sealed,T.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},z={type:"cred_update_result",updateId:$.updateId,projectId:t.projectId,ok:D.ok,...D.detail?{detail:D.detail}:{}};g.readyState===g.OPEN&&g.send(JSON.stringify(z)),D.ok?(r.info(`[cred] ${$.kind} replaced${D.detail?` \u2014 ${D.detail}`:""}`),I()):r.warn(`[cred] ${$.kind} replacement rejected: ${D.detail??"unknown"}`);return}if(N==="readiness_check"){r.info("[readiness] on-demand check requested"),I();return}if(N==="agent_login_start"){ou(t,g,S,r,I);return}if(N==="move_to_farm"){let $=S;r.info(`[farm-move] request to move ${t.projectId} onto farm ${$.farmName} (${$.farmId})`);let T=await sp(t,$,o?.contextDir,r);g.readyState===g.OPEN&&g.send(JSON.stringify(T)),T.ok?r.info(`[farm-move] done \u2014 farm daemon ${T.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${T.error??"unknown error"}`);return}if(N==="gh_runner_setup"){let $=S;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${$.runnerName} (${$.runnerId})`);let T=await gp(t,$,r);g.readyState===g.OPEN&&g.send(JSON.stringify(T)),T.ok?r.info(`[ghr] runners connected on ${$.runnerName}`):r.warn(`[ghr] setup failed: ${T.error??"see per-repo statuses"}`);return}if(N==="gh_runner_teardown"){let $=S;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${$.runnerName} (${$.runnerId})`);let T=await hp(t,$,r);g.readyState===g.OPEN&&g.send(JSON.stringify(T)),T.ok?r.info(`[ghr] runners disconnected from ${$.runnerName}`):r.warn(`[ghr] teardown failed: ${T.error??"unknown error"}`);return}if(N==="tracker_fields_request"){let $=S,T={type:"tracker_fields_result",requestId:$.requestId,projectId:t.projectId,ok:!1},D=it({contextDir:o?.contextDir??null});if(!D.ok)T.error=D.error;else try{T.fields=await D.provider.fetchStateFields($.projectKey),T.ok=!0}catch(z){T.error=z instanceof Error?z.message:String(z)}g.readyState===g.OPEN&&g.send(JSON.stringify(T)),T.ok||r.warn(`[yt-fields] listing failed: ${T.error??"unknown"}`);return}if(N==="project_secret_update"||N==="project_secret_delete"){let $=S,T;if($.type==="project_secret_update"){let z=F(t.projectId);T=z?.sealKey?bp(t.projectId,$.name,$.sealed,z.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else T=kp(t.projectId,$.name);let D={type:"project_secret_update_result",updateId:$.updateId,projectId:t.projectId,ok:T.ok,...T.detail?{detail:T.detail}:{}};g.readyState===g.OPEN&&g.send(JSON.stringify(D)),T.ok?(r.info(`[secret] ${$.name} ${$.type==="project_secret_update"?"saved":"deleted"}`+(T.detail?` \u2014 ${T.detail}`:"")),I()):r.warn(`[secret] ${$.name} rejected: ${T.detail??"unknown"}`);return}if(N==="auto_apply_local"){let $=S;if(!o?.contextDir){r.warn(`[apply] auto_apply_local for ${$.claim.taskKey} \u2014 no workspace (headless), skipped; task stays in READY_TO_APPLY`);return}let T=await Du({hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId,root:o.root,contextDir:o.contextDir,repos:o.repos},$.claim,r).catch(D=>({ok:!1,message:D instanceof Error?D.message:String(D)}));T.ok?r.info(`[apply] ${$.claim.taskKey}: ${T.message}`):r.warn(`[apply] ${$.claim.taskKey}: ${T.message} \u2014 task stays in READY_TO_APPLY`),n({kind:"local_applied",taskKey:$.claim.taskKey,ok:T.ok,...T.ok?{branches:T.branches??[]}:{error:T.message}});return}if(N==="sandbox_keys"){let $=F(t.projectId);if(!$){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let T=mr(t.projectId),D=xd(S,$,T,r);for(let z of D)g.readyState===g.OPEN&&g.send(JSON.stringify(z));return}if(N!=="dispatch_action")return;let P=S;if(y===!1){let $=`refused: HUB protocol incompatible with CLI v${Ee} (protocol ${Xe})`;g.send(JSON.stringify({type:"action_result",actionId:P.actionId,status:"failed",error:$})),r.warn(`[exec] ${P.actionId} (${P.action.type}) \u2192 REFUSED: ${$}`),r.warn(`[exec] update the CLI to clear this: ${Ws}`),n({kind:"action",actionId:P.actionId,actionType:P.action.type,ok:!1,error:$});return}if(P.action.type==="local_apply"){p.add(P.actionId);try{let $;if(!o)$={status:"failed",error:"no local workspace on this CLI"};else{let D=await ep(o,P.action.repos,r);$=D.ok?{status:"done",result:{repos:D.repos}}:{status:"failed",error:D.error}}g.send(JSON.stringify({type:"action_result",actionId:P.actionId,...$}));let T=$.status!=="failed";T?r.info(`[exec] ${P.actionId} (local_apply) \u2192 done`):r.warn(`[exec] ${P.actionId} (local_apply) \u2192 FAILED: ${$.status==="failed"?$.error:"?"}`),n({kind:"action",actionId:P.actionId,actionType:"local_apply",ok:T,...$.status==="failed"?{error:$.error}:{}})}finally{p.delete(P.actionId)}return}p.add(P.actionId);try{let $=await Xd({action:P.action,repo:P.repo,trackerIssueId:P.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:E?()=>E.reportNow():void 0,refreshContextStatus:o?.contextDir?h:void 0,onRunActivity:G}).catch(z=>({status:"failed",error:z instanceof Error?z.message:String(z)}));P.action.type==="tracker_comment"&&$.status==="done"&&"result"in $&&typeof $.result?.commentId=="string"&&d.add($.result.commentId),g.send(JSON.stringify({type:"action_result",actionId:P.actionId,...$}));let T=$.status!=="failed",D=!T&&"error"in $?$.error:void 0;T?r.info(`[exec] ${P.actionId} (${P.action.type}) \u2192 done`):r.warn(`[exec] ${P.actionId} (${P.action.type}) \u2192 FAILED: ${D??"?"}`),n({kind:"action",actionId:P.actionId,actionType:P.action.type,ok:T,...D?{error:D}:{}})}finally{p.delete(P.actionId)}}),g.on("close",(C,R)=>{let S=R?.toString("utf-8")??"";if(r.info(`[ws] closed code=${C}${S?` reason=${S}`:""}`),b.stop(),w.stop(),E?.stop(),j(),S==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:C}),!c&&setTimeout(()=>{m=f()},2e3)}),g.on("error",C=>r.warn(`[ws] error: ${C.message}`)),g}return{stop(){c=!0,m.close()}}}async function Ys(t,e,r){try{let n=await Q(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=xn(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 ck(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?Pn(e.root,o):ve(t.projectId,r.name);if(Ip(Pn(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await ak().clone(yn(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 lk(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?Pn(e.root,o):ve(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Ip(Pn(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{sk(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 uk(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=Pn(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Uu(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 dk(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 We(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 pk(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 ed(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 Tp(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}var Ws,qs=k(()=>{"use strict";ke();W();bl();iu();cu();ko();fs();Mu();Wu();td();mt();ft();Rs();yd();Ps();br();Sd();Pd();Qd();tp();ap();yp();ge();$p();wr();oe();vp();Rp();Wo();Ws="npm i -g @code-partner/codepipe@latest"});import{execFileSync as fk}from"node:child_process";import{mkdtempSync as mk,mkdirSync as gk,readFileSync as Cp,rmSync as hk,writeFileSync as yk}from"node:fs";import{tmpdir as wk}from"node:os";import{dirname as bk,join as Ep}from"node:path";function Pp(t="codepipe-context"){let e=mk(Ep(wk(),"codepipe-ssh-")),r=Ep(e,"id_ed25519");try{return fk("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Cp(r,"utf-8"),publicKey:Cp(`${r}.pub`,"utf-8").trim()}}finally{hk(e,{recursive:!0,force:!0})}}async function Ap(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 jp(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 _p(t,e){gk(bk(t),{recursive:!0});let r=e.endsWith(`
|
|
621
623
|
`)?e:e+`
|
|
622
|
-
`;return
|
|
623
|
-
`,{mode:384})}var
|
|
624
|
-
`}async function
|
|
625
|
-
`))!==-1;){let
|
|
626
|
-
`)){let
|
|
624
|
+
`;return yk(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var Vs=k(()=>{"use strict"});import{existsSync as Np,mkdirSync as Op}from"node:fs";import{dirname as Dp}from"node:path";import{simpleGit as Cr}from"simple-git";function kk(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 $k(t,e){return e?.contextWrite?.token?{user:oo(t),secret:e.contextWrite.token}:t===ln.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===ln.bitbucket?e?.bitbucket?.apiToken?{user:Ht,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function Lp(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 Qo))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 Zo(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 Qo(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=$k(pr(s.cloneUrl),r);if(a){let c=await vk({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 xk({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 vk(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=kk(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(Np(`${r}/.git`)){let l=Cr(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=ws(r);await l.reset(["--hard",`origin/${s}`]),bs(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Op(Dp(r),{recursive:!0}),await Cr().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await Up(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 xk(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=_p(i,n),a=jp(e.cloneUrl),c=e.branch;try{if(Np(`${r}/.git`)){let l=Cr(r);await l.addConfig("core.sshCommand",s,!1,"local"),await l.remote(["set-url","origin",a]),await l.fetch("origin",c),await l.checkout(c);let u=ws(r);await l.reset(["--hard",`origin/${c}`]),bs(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Op(Dp(r),{recursive:!0}),await Cr().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await Cr(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await Up(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 Up(t){let e=Cr(t);await e.raw(["config","user.email"]).then(n=>n.trim()).catch(()=>"")||(await e.addConfig("user.email","farm@codepipe.local",!1,"local"),await e.addConfig("user.name","CodePipe Farm CLI",!1,"local"))}var Qo,zs=k(()=>{"use strict";W();ge();ft();Vs();Qo=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as Sk}from"node:child_process";function Rk(){try{return Sk("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function Bp(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:Rk(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var Fp=k(()=>{"use strict"});import{homedir as Er}from"node:os";import{mkdirSync as Tk,readFileSync as Gp,writeFileSync as Ik,existsSync as Xs}from"node:fs";import{dirname as Ck,join as At}from"node:path";function Ek(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function Ye(t){let e=K("SANDBOX_CONFIG");if(e)return e;let r=At(Er(),".codepipe","worker");return t?At(r,"profiles",t,"config.json"):At(r,"config.json")}function Kp(){return At(Er(),".devpipe-sandbox","config.json")}function ei(){Wt(At(Er(),".devpipe"),At(Er(),".codepipe")),K("SANDBOX_CONFIG")||Wt(At(Er(),".devpipe-sandbox"),At(Er(),".codepipe-sandbox"))}function Hp(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function ye(t){let e=Ye(t),r=null;return Xs(e)?r=JSON.parse(Gp(e,"utf-8")):!t&&!K("SANDBOX_CONFIG")&&Xs(Kp())&&(r=JSON.parse(Gp(Kp(),"utf-8"))),r?(r.planningLane=Ek(),r):null}function Wp(t,e){let r=Ye(e);Tk(Ck(r),{recursive:!0}),Ik(r,JSON.stringify(t,null,2)+`
|
|
625
|
+
`,{mode:384})}var ti=k(()=>{"use strict";ke();io();Xs(".env")&&process.loadEnvFile(".env")});import Pk from"ws";var Pr,Qs=k(()=>{"use strict";Pr=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 Pk(e)}}});import{hostname as Ak}from"node:os";async function nr(t){ei();let e=ye(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Ye(t.profile)}.`),process.exit(1));let r=t.name??Ak(),n=Bp({projects:t.projects??[],llm:t.llm??null}),o=new Pr(t.hub.replace(/\/$/,"")),i=Uo(),s=xe(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});Wp({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 ${Ye(t.profile)}`),console.log(""),console.log(" cred-channel key fingerprint (confirm this on the CLI \u2014 pin-on-register):"),console.log(` ${s}`),console.log("")}var Yp=k(()=>{"use strict";Oe();Fp();ti();Qs()});import{spawn as jk}from"node:child_process";function Zs(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function Nk(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 Ok(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function or(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function ea(t){return JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:t}]}})+`
|
|
626
|
+
`}async function Jp(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new ht;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(),u=c.type;if(u==="assistant"){let p=c.message;for(let d of p?.content??[]){let m=d.type;if(m==="text"){let f=String(d.text??"").trim();f&&o({ts:l,kind:"text",author:"agent",text:Zs(f,qp)})}else if(m==="tool_use"){let f=String(d.name??""),g=d.input?.file_path??d.input?.path,y=Nk(g,e.workspaceDir);o({ts:l,kind:"tool",author:"agent",tool:f,...y?{file:y}:{}})}}return}if(u==="user"){let p=c.message;for(let d of p?.content??[])if(d.type==="tool_result"){let m=d.is_error===!0,f=m?Zs(Ok(d.content),200):"";o({ts:l,kind:"tool_result",author:"agent",isError:m,...f?{text:f}:{}})}return}if(u==="result"){s=c;let p=String(c.subtype??"").trim();o({ts:l,kind:"result",author:"agent",...p?{text:p}:{}});return}if(u==="system"){let p=String(c.subtype??"").trim();p&&o({ts:l,kind:"system",author:"agent",text:p})}};return o({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((c,l)=>{let u=jk(t,r,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});u.stdout.setEncoding("utf-8"),u.stderr.setEncoding("utf-8");let p=!1,d=!1,m=null,f=()=>{p=!0,u.kill("SIGTERM"),m=setTimeout(()=>u.kill("SIGKILL"),Vp)};e.signal?.addEventListener("abort",f,{once:!0});let g=null,y=()=>{g&&clearTimeout(g),g=setTimeout(()=>{d=!0,console.warn(`[claude:chat] idle for ${zp}ms \u2014 ending session`),u.kill("SIGTERM"),m=setTimeout(()=>u.kill("SIGKILL"),Vp)},zp)},b=()=>{m&&clearTimeout(m),g&&clearTimeout(g),e.signal?.removeEventListener("abort",f)},w=!0,x=j=>{if(!(!w||u.stdin.destroyed))try{u.stdin.write(j)}catch{}};x(ea(e.prompt)),y(),(async()=>{try{for await(let j of e.interactive.inbox){if(p||!w)break;if(y(),j.kind==="user")o({ts:Date.now(),kind:"text",author:"user",text:Zs(j.text,qp)}),x(ea(j.text));else{x(ea(_k)),w=!1;try{u.stdin.end()}catch{}break}}}catch{}})();let I="",H=j=>{let v;try{v=JSON.parse(j)}catch{return}a(v)};u.stdout.on("data",j=>{i.push(j),y(),I+=j;let v;for(;(v=I.indexOf(`
|
|
627
|
+
`))!==-1;){let A=I.slice(0,v).trim();I=I.slice(v+1),A&&H(A)}}),u.stderr.on("data",j=>{i.push(j);for(let v of j.split(`
|
|
628
|
+
`)){let A=v.trim();A&&console.warn(`[claude:chat:stderr] ${A}`)}}),u.on("error",j=>{b(),l(j)}),u.on("close",j=>{if(b(),p){l(new ht);return}if(d){l(new Error("chat session ended: idle for too long without a reply"));return}I.trim()&&H(I.trim()),console.log(`[claude:chat] exit code=${j}`),c({artifactPaths:[],log:i.join(""),usage:Dk(s)})})})}function Dk(t){let e=Ft();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=or(r.input_tokens),e.outputTokens=or(r.output_tokens),e.cacheReadInputTokens=or(r.cache_read_input_tokens),e.cacheCreationInputTokens=or(r.cache_creation_input_tokens)),e.totalCostUsd=or(t.total_cost_usd),e.numTurns=or(t.num_turns),e.durationMs=or(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var qp,Vp,zp,_k,Xp=k(()=>{"use strict";W();Ar();qp=16e3,Vp=5e3,zp=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),_k="\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."});import{spawn as Lk}from"node:child_process";import{existsSync as Uk}from"node:fs";function Bk(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function Qp(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: ${jt(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=Kk(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=ef(o.content);console.log(`[claude] tool_result (error)${i?`: ${jt(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)} ${jt(JSON.stringify(e),200)}`),e}function Fk(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(jt(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(jt(r.trim().split(`
|
|
627
629
|
`).slice(-5).join(`
|
|
628
|
-
`),500)),n.join(" \u2014 ")}function
|
|
629
|
-
`))!==-1;){let
|
|
630
|
-
`)){let
|
|
630
|
+
`),500)),n.join(" \u2014 ")}function Gk(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 ef(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Kk(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=${jt(r,80)}`}return""}function jt(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function Se(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Hk(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=Se(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:Se(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 Wk(t,e,r,n){let o=Ft(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=Se(i.input_tokens),o.outputTokens=Se(i.output_tokens),o.cacheReadInputTokens=Se(i.cache_read_input_tokens),o.cacheCreationInputTokens=Se(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=Se(t?.total_cost_usd),o.numTurns=t&&Se(t.num_turns)>0?Se(t.num_turns):r,o.durationMs=Se(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}function Yk(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:jt(c,Zp)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,p=qk(u,e);i.push({ts:r,kind:"tool",tool:c,...p?{file:p}:{}})}}return i}if(n==="user"){let o=t.message,i=[];for(let s of o?.content??[])if(s.type==="tool_result"){let a=s.is_error===!0,c=a?jt(ef(s.content),Zp):"";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 qk(t,e){if(!(typeof t!="string"||!t))return t.startsWith(e)?t.slice(e.length).replace(/^\/+/,"")||t.split("/").pop()||void 0:t.startsWith("/")?t.split("/").pop()||void 0:t}var jr,ht,Mk,jn,Zp,Ar=k(()=>{"use strict";W();Xp();jr=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},ht=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},Mk=5e3;jn=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return Jp(this.binary,e);if(e.signal?.aborted)throw new ht;let r=["-p",Bk(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,u=f=>{if(f){if(f.type==="result"){i=f;return}if(f.type==="rate_limit_event"){let g=Hk(f.rate_limit_info);g&&(!l||g.utilization>l.utilization)&&(l=g);return}if(f.type==="assistant"){let g=f.message;typeof g?.model=="string"&&(c=g.model);let y=g?.usage;y&&(a+=1,s.input+=Se(y.input_tokens),s.output+=Se(y.output_tokens),s.cacheRead+=Se(y.cache_read_input_tokens),s.cacheCreate+=Se(y.cache_creation_input_tokens))}}},p=e.role,d=e.onActivity,m=f=>{if(d)for(let g of Yk(f,e.workspaceDir))try{d(g)}catch{}};return d?.({ts:Date.now(),kind:"start",text:`${p} job started`}),console.log(`[claude] spawn ${this.binary} role=${p}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((f,g)=>{let y=Lk(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"}});y.stdout.setEncoding("utf-8"),y.stderr.setEncoding("utf-8");let b=!1,w=null,x=()=>{b=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${p}`),y.kill("SIGTERM"),w=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),y.kill("SIGKILL")},Mk)};e.signal?.addEventListener("abort",x,{once:!0});let I=()=>{w&&clearTimeout(w),e.signal?.removeEventListener("abort",x)},H="";y.stdout.on("data",j=>{n.push(j),H+=j;let v;for(;(v=H.indexOf(`
|
|
631
|
+
`))!==-1;){let A=H.slice(0,v).trim();if(H=H.slice(v+1),A){let L=Qp(A);u(L),L&&m(L)}}}),y.stderr.on("data",j=>{n.push(j),o.push(j);for(let v of j.split(`
|
|
632
|
+
`)){let A=v.trim();A&&console.warn(`[claude:stderr] ${A}`)}}),y.on("error",j=>{I(),g(j)}),y.on("close",j=>{if(I(),b){g(new ht);return}if(H.trim()){let A=Qp(H.trim());u(A),A&&m(A)}let v=i?.is_error===!0;if(j!==0||v){let A=typeof i?.api_error_status=="number"?i.api_error_status:void 0,L=typeof i?.subtype=="string"?i.subtype:void 0,G=typeof i?.result=="string"?i.result:void 0;g(new jr(Fk(j,i,o.join("")),{code:j,apiErrorStatus:A,subtype:L,resultText:G,retryAfterMs:Gk(i)}));return}console.log("[claude] exit code=0"),f({artifactPaths:[],log:n.join(""),usage:Wk(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("/")&&Uk(n))}};Zp=200});import{mkdirSync as Vk,writeFileSync as _r}from"node:fs";import{dirname as zk,join as Nr}from"node:path";function tf(t,e,r){let n=Nr(t,e);Vk(zk(n),{recursive:!0}),_r(n,r)}function Jk(t,e,r){return`# ${t} \u2014 Estimate
|
|
631
633
|
|
|
632
634
|
**Title:** ${e}
|
|
633
635
|
|
|
@@ -648,7 +650,7 @@ production-grade estimates.)
|
|
|
648
650
|
${r.split(`
|
|
649
651
|
`).slice(0,8).join(`
|
|
650
652
|
`).trim()||"(empty)"}
|
|
651
|
-
`}function
|
|
653
|
+
`}function Xk(t,e,r,n){let o=n?`
|
|
652
654
|
## Reviewer rework instruction
|
|
653
655
|
|
|
654
656
|
> ${n.split(`
|
|
@@ -677,10 +679,10 @@ TBD (mock runner does not yet inspect project code).
|
|
|
677
679
|
${r.split(`
|
|
678
680
|
`).slice(0,8).join(`
|
|
679
681
|
`).trim()||"(empty)"}
|
|
680
|
-
`}function
|
|
682
|
+
`}function Qk(t){return`# ${t} \u2014 Open questions
|
|
681
683
|
|
|
682
684
|
(none \u2014 mock runner did not surface ambiguities.)
|
|
683
|
-
`}function
|
|
685
|
+
`}function Zk(t,e,r){let n=r?` (rework: ${r.split(`
|
|
684
686
|
`)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
|
|
685
687
|
index 0000000..1111111 100644
|
|
686
688
|
--- a/CHANGELOG.md
|
|
@@ -691,7 +693,7 @@ index 0000000..1111111 100644
|
|
|
691
693
|
+- mock-runner placeholder change for slice 5 testing.
|
|
692
694
|
+
|
|
693
695
|
# Changelog
|
|
694
|
-
`}function
|
|
696
|
+
`}function e$(t,e,r){return`# ${t} \u2014 Diff summary
|
|
695
697
|
|
|
696
698
|
**Title:** ${e}
|
|
697
699
|
${r?`
|
|
@@ -702,116 +704,117 @@ ${r?`
|
|
|
702
704
|
- \`CHANGELOG.md\` \u2014 added entry for ${t}.
|
|
703
705
|
|
|
704
706
|
(Mock-runner output. Replace with claude-headless for production patches.)
|
|
705
|
-
`}var
|
|
706
|
-
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:
|
|
707
|
+
`}var _n,ta=k(()=>{"use strict";W();Ar();_n=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=Jk(n,o,i);_r(Nr(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;_r(Nr(e.workspaceDir,"SOLUTION.md"),Xk(n,o,i,a)),s.push("SOLUTION.md"),_r(Nr(e.workspaceDir,"QUESTIONS.md"),Qk(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;tf(e.workspaceDir,"changes/sample.patch",Zk(n,o,a)),s.push("changes/sample.patch"),tf(e.workspaceDir,"diff-summary.md",e$(n,o,a)),s.push("diff-summary.md")}else e.role==="rework"&&(_r(Nr(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
|
|
708
|
+
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:Ft()}}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 ht;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 _r(Nr(e.workspaceDir,"DRAFT.md"),`${o}
|
|
707
709
|
|
|
708
710
|
\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).
|
|
709
|
-
`),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:
|
|
711
|
+
`),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:Ft()}}}});function rf(t){switch(t){case"mock":return new _n;case"claude-headless":return new jn;default:return null}}function nf(t,e){let r=e&&e.trim().length>0?e.trim():Ze;return t==="mock"?!0:t==="claude-headless"?r==="claude":!1}var of=k(()=>{"use strict";W();Ar();ta();Ar();ta()});function cf(t=process.env){return{maxAttempts:ri(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:ri(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:ri(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:ri(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function o$(t){if(t instanceof jr){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return r$.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&n$.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:t$.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:sf.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 sf.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function lf(t){if(t instanceof jr){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&af.test(n)}let e=t instanceof Error?t.message:String(t);return af.test(e)}function i$(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 uf(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=o$(a),l=s>=r.policy.maxAttempts;if(!c.retryable||l||r.aborted())throw s>1?new Error(`agent failed after ${s} attempts: ${i}`):a;let u=i$(s,r.policy,c.retryAfterMs);if(Date.now()+u>o)throw new Error(`agent failed after ${s} attempts (retry budget exhausted): ${i}`);console.warn(`[job] ${r.jobId} agent attempt ${s}/${r.policy.maxAttempts} failed (retryable: ${c.reason}) \u2014 cleaning workspace, backoff ${u}ms`),await r.onBeforeRetry(),await n(u)}}function ri(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}var t$,sf,r$,n$,af,df=k(()=>{"use strict";Ar();t$=new Set([429,500,502,503,529]),sf=/(\bETIMEDOUT\b|\bECONNRESET\b|\bECONNREFUSED\b|\bEAI_AGAIN\b|\bEPIPE\b|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,r$=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,n$=new Set(["error_max_turns"]);af=/(not logged in|invalid api key|invalid x-api-key|authentication[ _]error|unauthorized|oauth token (?:expired|revoked|invalid)|token (?:expired|revoked)|please run .{0,20}login|run `?claude\b.{0,20}(?:login|setup-token))/i});import{mkdtempSync as s$,rmSync as a$,writeFileSync as pf}from"node:fs";import{tmpdir as c$}from"node:os";import{join as ra}from"node:path";function ni(t){return`[url "https://${t}/"]
|
|
710
712
|
insteadOf = git@${t}:
|
|
711
713
|
insteadOf = ssh://git@${t}/
|
|
712
|
-
`}function
|
|
714
|
+
`}function ff(t,e){if(t.length===0)return null;let r=s$(ra(c$(),"devpipe-gitcreds-")),n=ra(r,"credentials"),o=ra(r,"gitconfig");return pf(n,t.join(`
|
|
713
715
|
`)+`
|
|
714
|
-
`,{mode:384}),
|
|
716
|
+
`,{mode:384}),pf(o,`[credential]
|
|
715
717
|
helper = store --file=${n}
|
|
716
|
-
`+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{
|
|
717
|
-
`).map(f=>f.trim()).filter(f=>f.length>0);if(d&&m.length===0)throw await
|
|
718
|
-
`).map(l=>l.trim()).filter(l=>l.length>0),c=await
|
|
719
|
-
${s.join("").trim()||"(no stderr)"}`))})})}function
|
|
720
|
-
${a.join("").trim()||"(no stderr)"}`))})})}function
|
|
721
|
-
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=
|
|
722
|
-
`+e.subarray(e.length-
|
|
723
|
-
\u2026 [${r.length-e} bytes elided]`}var
|
|
718
|
+
`+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{a$(r,{recursive:!0,force:!0})}catch{}}}}function na(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(l$)),t.bitbucket?.apiToken&&(e.push(`https://${Ht}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(u$)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(d$)),ff(e,r)}function mf(t,e){if(t.contextWrite?.token){let r=pr(e)??"github.com",n=oo(r);return ff([`https://${n}:${t.contextWrite.token}@${r}`],[ni(r)])}return na(t)}var l$,u$,d$,gf=k(()=>{"use strict";W();l$=ni("github.com"),u$=ni("bitbucket.org"),d$=ni("gitlab.com")});import{spawn as yf}from"node:child_process";import{existsSync as oi,mkdirSync as Nn,readFileSync as p$,rmSync as oa,symlinkSync as f$}from"node:fs";import{homedir as m$}from"node:os";import{dirname as Dr,join as _t}from"node:path";function wf(t){let e=_t(m$(),".codepipe-sandbox","repos");return t?_t(e,t):e}function bf(t,e){let n=(Or.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{Or.get(t)===o&&Or.delete(t)},()=>{Or.get(t)===o&&Or.delete(t)});return Or.set(t,o),n}function hf(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 g$(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 kf(t,e,r,n,o){let i=async c=>{await ee(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await ee(t,["reset","--hard",`origin/${c}`],o),await ee(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!hf(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{oi(t)&&oa(t,{recursive:!0,force:!0}),Nn(Dr(t),{recursive:!0});try{return await ee(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!hf(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),oi(t)&&oa(t,{recursive:!0,force:!0}),Nn(Dr(t),{recursive:!0}),await ee(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(oi(_t(t,".git")))try{return await s()}catch(c){if(!g$(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 $f(t){await ee(t.workspacePath,["reset","--hard",t.baseSha]),await ee(t.workspacePath,["clean","-fdx"])}async function vf(t,e){let r=t.workspacePath;await ee(r,["add","-A"]);let n=(await he(r,["write-tree"])).trim(),o=(await he(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:Lr,GIT_AUTHOR_EMAIL:Ur,GIT_COMMITTER_NAME:Lr,GIT_COMMITTER_EMAIL:Ur};return(await he(r,["commit-tree",n,"-m",e],i)).trim()}async function xf(t,e,r,n,o){try{await ee(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw pr(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 Sf(t,e){return he(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Rf(t,e,r,n,o){await ee(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await ee(t.workspacePath,["checkout","--force",r])}async function Tf(t,e,r,n,o,i){let s=t.workspacePath;await ee(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await he(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=>he(s,["rev-parse","-q","--verify",`${f}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await he(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ee(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(g=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(g)}`)}),await c(n)||await ee(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:Lr,GIT_AUTHOR_EMAIL:Ur,GIT_COMMITTER_NAME:Lr,GIT_COMMITTER_EMAIL:Ur},u=(await he(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),p=(await he(s,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await ee(s,["cherry-pick","--quit"],l).catch(()=>{});let d=null;try{await ee(s,["cherry-pick","--no-commit",p],l)}catch(f){d=f instanceof Error?f.message:String(f)}let m=(await he(s,["diff","--name-only","--diff-filter=U"])).split(`
|
|
719
|
+
`).map(f=>f.trim()).filter(f=>f.length>0);if(d&&m.length===0)throw await ee(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${d}`);return m}async function ia(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:Lr,GIT_AUTHOR_EMAIL:Ur,GIT_COMMITTER_NAME:Lr,GIT_COMMITTER_EMAIL:Ur};(await he(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ee(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 ee(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await ee(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await he(n,["diff","--name-only","--diff-filter=U"])).split(`
|
|
720
|
+
`).map(l=>l.trim()).filter(l=>l.length>0),c=await he(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 ee(t,e,r){return new Promise((n,o)=>{let i=yf("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}):
|
|
721
|
+
${s.join("").trim()||"(no stderr)"}`))})})}function he(t,e,r){return new Promise((n,o)=>{let i=yf("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}):
|
|
722
|
+
${a.join("").trim()||"(no stderr)"}`))})})}function If(t,e){oi(t)&&oa(t,{recursive:!0,force:!0}),Nn(Dr(t),{recursive:!0}),f$(e,t,"dir")}async function Cf(t,e,r){await ee(t,["worktree","prune"]).catch(()=>{}),Nn(Dr(r),{recursive:!0}),await ee(t,["worktree","add","--detach",r,`origin/${e}`])}async function h$(t,e,r){Nn(Dr(r),{recursive:!0}),await ee(Dr(r),["clone","--quiet","--no-checkout",t,r]),await ee(r,["checkout","--force","--detach",e])}async function Ef(t,e,r,n="worktree",o,i){return r.length===0?[]:bf(e,async()=>{let s=[];for(let a of r){let c=_t(wf(i),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await kf(c,a.cloneUrl,a.ref,a.defaultBranch,o)}catch(d){throw new Error(`failed to materialize project repo "${a.name}" (${a.cloneUrl}): `+(d instanceof Error?d.message:String(d)))}let u=(await he(c,["rev-parse","HEAD"])).trim(),p=_t(t,"code",a.name);n==="direct"?(If(p,c),console.log(`[git] code: linked ${p} \u2192 ${c} @ ${u.slice(0,10)}`)):n==="clone"?(await h$(c,u,p),console.log(`[git] code: clone ${p} \u2190 ${c} @ ${u.slice(0,10)}`)):(await Cf(c,l,p),console.log(`[git] code: worktree ${p} \u2190 ${c} @ ${u.slice(0,10)}`)),s.push({name:a.name,workspacePath:p,cachePath:c,ref:l,baseSha:u})}return s})}async function Pf(t,e,r,n="worktree",o,i){if(!r||!r.cloneUrl)return null;let s=r;return bf(e,async()=>{let a=_t(wf(i),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);try{await kf(a,s.cloneUrl,s.ref,void 0,o)}catch(u){throw new Error(`failed to materialize context repo (${s.cloneUrl}): `+(u instanceof Error?u.message:String(u)))}let c=_t(t,"context");n==="direct"?(If(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await Cf(a,s.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await he(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function Af(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await ee(r,["add","-A",...n]).catch(()=>{});let o;try{o=await he(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
|
|
723
|
+
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=p$(_t(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var Or,Lr,Ur,jf=k(()=>{"use strict";W();Or=new Map;Lr="CodePipe Agent",Ur="codepipe@codepartner.ee"});import{readFileSync as y$}from"node:fs";import{join as w$}from"node:path";function _f(t){let e=w$(t,On),r;try{r=y$(e,"utf-8")}catch{throw new Nt(`BUILD produced no ${On} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new Nt(`${On} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new Nt(`${On} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new Nt(`${On}: "ok" must be a boolean`);let i=o.ok,a=(Array.isArray(o.steps)?o.steps:[]).flatMap(u=>{if(!u||typeof u!="object")return[];let p=u,d=typeof p.name=="string"?p.name:null,m=typeof p.exitCode=="number"?p.exitCode:null;if(d===null||m===null)return[];let f={name:d,exitCode:m};return typeof p.durationMs=="number"&&(f.durationMs=p.durationMs),[f]}),c=typeof o.logTail=="string"?b$(o.logTail):"",l={ok:i,steps:a,logTail:c};if(typeof o.failedStep=="string"&&o.failedStep)l.failedStep=o.failedStep;else if(!i){let u=a.find(p=>p.exitCode!==0);u&&(l.failedStep=u.name)}return l}function b$(t){let e=Buffer.from(t,"utf-8");return e.length<=sa?t:`\u2026 [${e.length-sa} bytes elided] \u2026
|
|
724
|
+
`+e.subarray(e.length-sa).toString("utf-8")}var sa,Nt,On,Nf=k(()=>{"use strict";sa=8*1024,Nt=class extends Error{},On="meta/build-result.json"});import{readFileSync as k$}from"node:fs";import{join as $$}from"node:path";function Df(t){let e=$$(t,Mr),r;try{r=k$(e,"utf-8")}catch{throw new yt(`code review produced no ${Mr} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(c){throw new yt(`${Mr} is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(!n||typeof n!="object")throw new yt(`${Mr} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new yt(`${Mr}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?Of(o.remarks,v$):"";if(!i&&s.trim().length===0)throw new yt(`${Mr}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?Of(o.summary,x$):"";return{approved:i,remarks:s,summary:a}}function Of(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
|
|
725
|
+
\u2026 [${r.length-e} bytes elided]`}var v$,x$,yt,Mr,Lf=k(()=>{"use strict";v$=16*1024,x$=4*1024,yt=class extends Error{},Mr="meta/review-result.json"});import{readFileSync as S$,statSync as R$}from"node:fs";import{join as Uf}from"node:path";function j$(t){return t.startsWith("meta/")||A$.has(t)}function _$(t,e,r,n){return`[codepipe] artifact omitted from upload: ${t} was ${e} bytes, exceeds the SANDBOX upload budget (per-artifact ${r} / total ${n}). The delivered code (git) and the build/review verdict are unaffected \u2014 only this display/durability copy was dropped.`}function N$(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function Mf(t,e,r){let n=r?.maxBytes??T$,o=r?.totalBytes??I$,i=r?.maxCount??C$,s=e.map((f,g)=>{let y=null;try{y=R$(Uf(t,f)).size}catch{}return{path:f,index:g,size:y}}),a=[...s].sort((f,g)=>{let y=b=>j$(b.path)?0:1;return y(f)!==y(g)?y(f)-y(g):(f.size??0)-(g.size??0)}),c=a.slice(0,i),l=a.slice(i).sort((f,g)=>f.index-g.index).map(f=>f.path),u=new Array(s.length),p=[],d=0;for(let f of c){let g=null;if(f.size!==null&&f.size<=n&&d+f.size<=o)try{g=S$(Uf(t,f.path))}catch{}if(g!==null){d+=g.length,u[f.index]={path:f.path,contentBase64:g.toString("base64")};continue}let y=f.size===null?N$(f.path):_$(f.path,f.size,n,o),b=Buffer.from(y,"utf-8");d+=b.length,u[f.index]={path:f.path,contentBase64:b.toString("base64")},p.push({path:f.path,bytes:f.size??0})}let m=u.filter(f=>f!==void 0);if(l.length>0){let f=l.slice(0,P$),g=`# Artifacts omitted from upload
|
|
724
726
|
|
|
725
727
|
${l.length} file(s) exceeded the SANDBOX artifact count budget (${i}) and were dropped from the listing. The delivered code (git) and the build/review verdicts are unaffected. Usually this means a job left a stray tree in the workspace \u2014 throwaway copies belong in the workspace's \`scratch/\` directory, which is never uploaded.
|
|
726
728
|
|
|
727
729
|
`+f.map(y=>`- ${y}
|
|
728
730
|
`).join("")+(l.length>f.length?`
|
|
729
731
|
\u2026and ${l.length-f.length} more.
|
|
730
|
-
`:"");m.push({path:
|
|
732
|
+
`:"");m.push({path:E$,contentBase64:Buffer.from(g,"utf-8").toString("base64")})}return{artifacts:m,omitted:p,dropped:l}}var T$,I$,C$,E$,P$,A$,Bf=k(()=>{"use strict";T$=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),I$=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),C$=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),E$="artifacts-omitted.md",P$=500,A$=new Set(["QUESTIONS.md","SOLUTION.md","DRAFT.md","ESTIMATE.md","diff-summary.md","review-result.md","commit-message.txt","pr-description.md"])});import{lstatSync as O$,mkdtempSync as D$,readFileSync as L$,readdirSync as Gf,rmSync as Ff}from"node:fs";import{tmpdir as U$}from"node:os";import{join as ii,relative as M$}from"node:path";function Kf(t){let e=D$(ii(U$(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Ff(e,{recursive:!0,force:!0}),listFiles:()=>Hf(e,e),readFile:r=>L$(ii(e,r),"utf-8"),clean:()=>{for(let r of Gf(e))F$.has(r)||Ff(ii(e,r),{recursive:!0,force:!0})}}}function Hf(t,e){let r=[];for(let n of Gf(e)){let o=ii(e,n),i=O$(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&B$.has(n))continue;r.push(...Hf(t,o))}else r.push(M$(t,o))}return r}var B$,F$,Wf=k(()=>{"use strict";B$=new Set(["code","context","scratch"]),F$=new Set(["code","context"])});import{mkdirSync as G$,readFileSync as Yf,readdirSync as K$,writeFileSync as H$}from"node:fs";import{homedir as W$}from"node:os";import{dirname as Y$,join as Br}from"node:path";function V$(t){let e=Buffer.from(t,"utf-8");if(e.length<=si)return t;let r=Math.floor(si/4),n=si-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}
|
|
731
733
|
|
|
732
|
-
\u2026 [${s} bytes elided \u2014 log capped at ${
|
|
734
|
+
\u2026 [${s} bytes elided \u2014 log capped at ${si} bytes for upload] \u2026
|
|
733
735
|
|
|
734
|
-
${i}`}function
|
|
736
|
+
${i}`}function z$(){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 Dn(t={}){ei();let e=ye(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,n=e.sandboxId,o=e.llm,i=Hp(t.profile,e.sandboxId,!!K("SANDBOX_CONFIG")),s=Br(W$(),".codepipe","logs"),a=fo("SANDBOX_LOG",i,s);if(a.enabled){let E=new hr(a);mo(E),console.log(`[log] file logging \u2192 ${E.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${Ee} (protocol ${Xe})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=rf(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=cf();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let u=new Pr(e.hubUrl,e.token),p=!1,d=new AbortController,m=new Map,f=null,g=null,y=!1,b=()=>{let E=u.openControlSocket();return f=E,E.on("open",()=>{console.log("[ws] connected");let h={type:"sandbox_hello",platformVersion:Ee,protocolVersion:Xe};E.send(JSON.stringify(h))}),E.on("message",h=>{let C=h.toString("utf-8"),R=null;try{let S=JSON.parse(C);S&&typeof S=="object"&&(R=S)}catch{}if(R&&R.type==="hello"){let S=R;g=Jn(S.protocolVersion);let N=g?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${S.platformVersion} (protocol ${S.protocolVersion}) \u2014 ${N}`),g&&(y=!1);return}if(R&&R.type==="pause_job"){let S=typeof R.jobId=="string"?R.jobId:"",N=S?m.get(S):void 0;N?(console.warn(`[ws] pause_job ${S} \u2014 aborting agent`),N.paused=!0,N.abort.abort()):console.log(`[ws] pause_job ${S} \u2014 not a running job, ignoring`),S&&E.send(JSON.stringify({type:"job_paused",jobId:S}));return}if(R&&(R.type==="chat_user_message"||R.type==="chat_finalize")){let S=typeof R.jobId=="string"?R.jobId:"",N=S?m.get(S):void 0;if(N?.chatInbox)if(R.type==="chat_user_message"){let P=typeof R.text=="string"?R.text:"";P.trim()&&N.chatInbox.push({kind:"user",text:P})}else N.chatInbox.finalize();else console.log(`[ws] ${String(R.type)} ${S} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${C}`)}),E.on("close",(h,C)=>{console.log(`[ws] closed code=${h} reason=${C?.toString()||""}`),f===E&&(f=null),!p&&setTimeout(b,2e3)}),E.on("error",h=>console.warn(`[ws] error: ${h.message}`)),E},w=b(),x=async E=>{for(;!p;){if(g===!1){y||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${Ee}, protocol ${Xe}) \u2014 not claiming jobs until versions align.`),y=!0),await new Promise(h=>setTimeout(h,5e3));continue}try{let h=await u.claim(d.signal,E);if(h.status===204)continue;if(h.status===401){console.error("[claim] 401 unauthorized \u2014 the HUB does not know this worker registration. It was removed; re-register with `codepipe up --reregister` (or `codepipe worker register --force`). exiting."),process.exitCode=1,p=!0;break}if(!h.ok){console.warn(`[claim:${E}] ${h.status} \u2014 backoff 5s`),await new Promise(R=>setTimeout(R,5e3));continue}let C=await h.json();await I(u,C)}catch(h){if(d.signal.aborted)break;let C=h instanceof Error?h.message:String(h);console.warn(`[claim:${E}] error: ${C} \u2014 backoff 5s`),await new Promise(R=>setTimeout(R,5e3))}}};async function I(E,h){let C={abort:new AbortController,paused:!1};h.role==="chat"&&(C.chatInbox=z$()),m.set(h.jobId,C);let R=!1,S=null,N=null,P=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),$=async()=>{try{await E.heartbeat(h.jobId)==="claim_lost"&&(R=!0,console.warn(`[job] ${h.jobId} claim lost \u2014 HUB sweeper took it`))}catch(q){let Z=q instanceof Error?q.message:String(q);console.warn(`[job] ${h.jobId} heartbeat error: ${Z}`)}};$();let T=setInterval(()=>{$()},P),D=new Date().toISOString();console.log(`[job] ${h.jobId} claimed \u2014 role=${h.role} task=${h.taskId} phase=${h.phase}`),console.log(`[job] ${h.jobId} prompt (${h.prompt.length} chars):`),console.log(j(h.prompt," \u2502 "));let z=[],ze=null,$i=400,qn=25,vi=500,O=()=>{if(ze&&(clearTimeout(ze),ze=null),z.length===0)return;let q=z.splice(0,z.length),Z=f;if(!Z||Z.readyState!==Z.OPEN)return;let at={type:"agent_activity",jobId:h.jobId,taskId:h.taskId,projectId:h.projectId,role:h.role,phase:h.phase,events:q};try{Z.send(JSON.stringify(at))}catch{}},ae=q=>{z.push(q),z.length>vi&&z.shift(),z.length>=qn?O():ze||(ze=setTimeout(O,$i))},Ce=h.role==="analysis"&&h.taskId.startsWith("draft::")?h.taskId.slice(7):null,Le=new Set,wt=null;try{if(!c){R||await E.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:D,finishedAt:new Date().toISOString()});return}if(!nf(o,h.provider??null)){R||await E.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${h.provider??"claude"}"`},startedAt:D,finishedAt:new Date().toISOString()});return}let q=Kf(h.jobId);console.log(`[job] ${h.jobId} workspace=${q.dir}`);let Z=H(h,r);S=Z.gitCreds,N=Z.contextGitCreds;let at=S?.env,Aa=Z.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:Z.claudeOauthToken}:void 0,ct=[],Zr=null,xi=null;try{let M=h.role==="build"?"clone":"worktree";ct=await Ef(q.dir,h.projectId,h.projectRepos,M,at,n);let B=await Pf(q.dir,h.projectId,h.contextRepo,"worktree",at,n);xi=B,Zr=B?.workspacePath??null}catch(M){let B=M instanceof Error?M.message:String(M);console.warn(`[job] ${h.jobId} materialize failed: ${B}`),R||await E.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${B}`},startedAt:D,finishedAt:new Date().toISOString()}),q.dispose();return}let ja=async()=>{if(!h.deliveries||h.deliveries.length===0)return[];let M=h.contextRepo?.cloneUrl;if(!M||!at)throw new Error(M?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let B=[];for(let J of h.deliveries){let V=ct.find(de=>de.name===J.name);if(V){if(h.role==="implement"&&J.baseSha&&J.baseSha!==V.baseSha){let de=await Tf(V,J.deliveryRef,J.deliverySha,J.baseSha,M,at);console.log(`[job] ${h.jobId} ${V.name}: base moved ${J.baseSha.slice(0,10)} \u2192 ${V.baseSha.slice(0,10)} \u2014 re-applied delivery ${J.deliverySha.slice(0,10)} (${de.length} conflicted file(s))`),de.length>0&&B.push(`- **${V.name}**:`,...de.map(en=>` - \`${en}\``));continue}await Rf(V,J.deliveryRef,J.deliverySha,M,at),console.log(`[job] ${h.jobId} ${V.name}: checked out delivery ${J.deliverySha.slice(0,10)} for ${h.role}`)}}return B},Si=[];if(h.role==="build"||h.role==="implement"||h.role==="code-review")try{Si=await ja()}catch(M){let B=M instanceof Error?M.message:String(M);console.warn(`[job] ${h.jobId} delivery checkout failed: ${B}`),R||await E.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${B}`},startedAt:D,finishedAt:new Date().toISOString()}),q.dispose();return}let Ri=h.role==="resolve-conflict"?h.metadata?.taskBranchByRepo??{}:{},_a="";if(h.role==="resolve-conflict"){if(!ct.some(M=>Ri[M.name])){let M="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] ${h.jobId} ${M}`),R||await E.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:M},startedAt:D,finishedAt:new Date().toISOString()}),q.dispose();return}try{let M=[];for(let B of ct){let J=Ri[B.name];if(!J)continue;let V=await ia(B,J,at);console.log(`[job] ${h.jobId} ${B.name}: merged ${J} into ${B.ref} \u2014 ${V.length} conflicted file(s)`),V.length>0?M.push(`- **${B.name}**:`,...V.map(de=>` - \`${de}\``)):M.push(`- **${B.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}_a=`
|
|
735
737
|
|
|
736
738
|
## Conflicts to resolve
|
|
737
739
|
|
|
738
|
-
`+(
|
|
740
|
+
`+(M.length>0?M.join(`
|
|
739
741
|
`):"(no task branches to merge)")+`
|
|
740
|
-
`}catch(
|
|
742
|
+
`}catch(M){let B=M instanceof Error?M.message:String(M);console.warn(`[job] ${h.jobId} conflict merge failed: ${B}`),R||await E.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${B}`},startedAt:D,finishedAt:new Date().toISOString()}),q.dispose();return}}let Vg=Si.length>0?`
|
|
741
743
|
|
|
742
744
|
## Base branch moved \u2014 conflicts to resolve
|
|
743
745
|
|
|
744
746
|
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:
|
|
745
747
|
|
|
746
|
-
`+
|
|
748
|
+
`+Si.join(`
|
|
747
749
|
`)+`
|
|
748
|
-
`:"",
|
|
749
|
-
`).map(
|
|
750
|
-
`)}function
|
|
751
|
-
[${
|
|
752
|
-
${e}`);let r=await
|
|
753
|
-
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=Vb(await Yb({message:"Claude OAuth token \u2014 blank to skip"})).trim();return e?(e.startsWith("sk-ant-")||He.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`."),e):(He.warn(t.farm?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"")}var Tf,Rf=k(()=>{"use strict";uo();mr();re();Yi();Tf={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:Xb,promptManual:Qb,validate:xt}});function If(t){return Tf}async function Cf(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var Ef=k(()=>{"use strict";Rf()});async function Br(t,e,r){return e.host==="github"?e$(t,e,r):e.host==="gitlab"?a$(t,e,r):l$(t,e,r)}async function Pf(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 _t(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Af(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 jt(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await jf(e.gitlabToken,t):o}}return e.bitbucket?(await Ur(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await _f(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 Af(t,e){let r=!1;try{r=(await _t(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 jf(t,e){let r=!1;try{r=(await jt(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 _f(t,e){let r=!1;try{r=(await Ur(t,"GET",`/workspaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`Bitbucket repo ${e.owner}/${e.name} does not exist in workspace "${e.owner}" (which the credential can see) \u2014 check the repo name, or the API token lacks access to it`:`Bitbucket workspace "${e.owner}" is not visible to this credential \u2014 check the workspace name and the token's read:repository:bitbucket scope`}async function _t(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(Zb+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 e$(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 t$(n,e,r),i=await n$(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=br(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await o$(n,o.owner,o.name,a.path,i)||await i$(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 t$(t,e,r){let n=await _t(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 Af(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await r$(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 _t(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 r$(t,e){let{status:r,data:n}=await _t(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function n$(t,e,r){let{data:n}=await _t(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function o$(t,e,r,n,o){let{status:i,data:s}=await _t(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function i$(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 _t(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function jt(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(s$+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 a$(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 jt(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 jf(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await jt(n,"GET","/user"),d={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(p.data?.username!==e.owner){let f=await jt(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(f.status===404||!f.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);d.namespace_id=f.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let m=await jt(n,"POST","/projects",d);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=br(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let m=(await jt(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let f of m)l.add(f.path);if(m.length<100)break}let u=c.filter(p=>!l.has(p.path)).map(p=>({action:"create",file_path:p.path,content:p.content}));return u.length>0?await jt(n,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:u}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}async function Ur(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(c$+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 l$(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 Ur(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 _f(n,e)} (attach joins an existing Context Repo and never creates one)`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let p=await Ur(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(p.status===404||!p.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);i=p.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=br(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await Ur(n,"GET",`${o}/src/${encodeURIComponent(a)}/${p.path}?format=meta`)).status===404&&l.push(p);if(l.length>0){let p=new URLSearchParams;p.set("message","chore(codepipe): scaffold context repo files"),p.set("branch",a);for(let m of l)p.set(m.path,m.content);if((await Ur(n,"POST",`${o}/src`,{form:p})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let u=i.links?.clone?.find(p=>p.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:u??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var Zb,s$,c$,Qo=k(()=>{"use strict";Zt();Zb="https://api.github.com";s$="https://gitlab.com/api/v4";c$="https://api.bitbucket.org/2.0"});function Ne(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=u$[r];if(!o)return null;let i=n.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(i.length<2)return null;let s=i[i.length-1].replace(/\.git$/,"");return s?{host:o,owner:i.slice(0,-1).join("/"),repoName:s}:null}var u$,Zo=k(()=>{"use strict";u$={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as d$}from"node:crypto";import{existsSync as Nf,mkdirSync as p$,readFileSync as Of,readdirSync as f$,rmSync as ei,writeFileSync as m$}from"node:fs";import{homedir as g$}from"node:os";import{dirname as h$,join as qs}from"node:path";function Lf(){return qs(g$(),".codepipe","init-drafts")}function Vs(t){let e=d$("sha256").update(t).digest("hex").slice(0,16);return qs(Lf(),`${e}.json`)}function Df(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=y$)}function Uf(t){let e=Vs(t);if(!Nf(e))return null;try{let r=JSON.parse(Of(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Df(r.savedAt)?(ei(e,{force:!0}),null):r}catch{return null}}function zs(t){ei(Vs(t),{force:!0})}function Bf(){let t=Lf();if(Nf(t))for(let e of f$(t)){let r=qs(t,e);try{let n=JSON.parse(Of(r,"utf-8"));Df(n.savedAt)&&ei(r,{force:!0})}catch{ei(r,{force:!0})}}}var y$,Mr,Mf=k(()=>{"use strict";y$=24*60*60*1e3;Mr=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(){zs(this.cwd)}persist(){let e=Vs(this.cwd);p$(h$(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};m$(e,JSON.stringify(r,null,2)+`
|
|
754
|
-
`,{mode:384})}}});function
|
|
755
|
-
`).map(n=>n.trim()).filter(Boolean);return
|
|
756
|
-
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`),
|
|
757
|
-
`))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function
|
|
750
|
+
`:"",zg=A(v(h.prompt,ct,Zr),Zr,h.taskId)+_a+Vg,Ti=[...ct.map(M=>M.workspacePath),...Zr?[Zr]:[]];Ti.length>0&&console.log(`[job] ${h.jobId} --add-dir: ${Ti.join(", ")}`),Ce&&(wt=setInterval(()=>{let B=f;if(!B||B.readyState!==B.OPEN)return;let J;try{J=K$(Br(q.dir,"drafts")).filter(V=>V.endsWith(".json")).sort()}catch{return}for(let V of J){if(Le.has(V))continue;if(Le.size>=Kc)break;let de;try{let Ue=JSON.parse(Yf(Br(q.dir,"drafts",V),"utf-8")),cr=typeof Ue.localRef=="string"?Ue.localRef:"",Vn=typeof Ue.title=="string"?Ue.title:"",Ii=typeof Ue.body=="string"?Ue.body:"";if(!cr||!Vn)continue;de={localRef:cr,title:Vn,body:Ii,...Ue.isEpic===!0?{isEpic:!0}:{},...Array.isArray(Ue.links)?{links:Ue.links}:{}}}catch{continue}Le.add(V);let en={type:"child_draft",jobId:h.jobId,projectId:h.projectId,draftId:Ce,child:de};try{B.send(JSON.stringify(en))}catch{}}},1500));try{let M={workspaceDir:q.dir,role:h.role,prompt:zg,addDirs:Ti,metadata:h.metadata??{},...h.model?{model:h.model}:{},...Aa?{env:Aa}:{},signal:C.abort.signal,onActivity:ae},B=C.chatInbox?await c.run({...M,interactive:{inbox:C.chatInbox.iterable}}):await uf(c,M,{jobId:h.jobId,policy:l,onBeforeRetry:async()=>{q.clean();for(let re of ct)try{await $f(re);let pe=Ri[re.name];h.role==="resolve-conflict"&&pe&&await ia(re,pe,at)}catch(pe){let tn=pe instanceof Error?pe.message:String(pe);console.warn(`[job] ${h.jobId} worktree reset failed (${re.name}): ${tn}`)}try{await ja()}catch(re){let pe=re instanceof Error?re.message:String(re);console.warn(`[job] ${h.jobId} delivery re-checkout failed: ${pe}`)}},aborted:()=>R||C.paused}),J=[];if(q$.has(h.role)&&ct.length>0){let re=h.metadata??{},pe=typeof re.commitMessage=="string"?re.commitMessage:`${h.taskId}: changes`,tn=h.contextRepo?.cloneUrl,Oa=N?.env;if(!tn||!Oa)throw new Error("delivery requested but "+(tn?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let Jg=h.taskId.includes(":")?h.taskId.slice(h.taskId.indexOf(":")+1):h.taskId;for(let lt of ct){let rn=await vf(lt,pe);if(!rn){console.log(`[job] ${h.jobId} ${lt.name}: no changes \u2014 no delivery`);continue}let Ci=`codepipe/deliveries/${Jg}/${h.jobId}/${lt.name}`;await xf(lt,rn,Ci,tn,Oa),J.push({name:lt.name,deliveryRef:Ci,deliverySha:rn,baseSha:lt.baseSha}),console.log(`[job] ${h.jobId} ${lt.name}: delivered ${rn.slice(0,10)} \u2192 ${Ci}`);let Da=await Sf(lt,rn);if(Da.trim().length>0){let Xg=Br("display",`${lt.name}.diff`),La=Br(q.dir,Xg);G$(Y$(La),{recursive:!0}),H$(La,Da)}}}if(h.role==="resolve-conflict"&&J.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 V;h.role==="build"&&(V=_f(q.dir),console.log(`[job] ${h.jobId} build verdict: ok=${V.ok}`+(V.failedStep?` failedStep=${V.failedStep}`:"")));let de;h.role==="code-review"&&(de=Df(q.dir),console.log(`[job] ${h.jobId} review verdict: approved=${de.approved}`));let en=B.artifactPaths.length>0?B.artifactPaths:q.listFiles(),Ue=Array.from(new Set(en)),cr;if(xi)try{let re=h.role==="index"?["adr/SOURCES.md"]:h.role==="backfill"?["adr"]:[],pe=await Af(xi,re);pe.length>0&&(cr=pe,console.log(`[job] ${h.jobId} captured ${pe.length} knowledge file(s) for Context Repo`))}catch(re){let pe=re instanceof Error?re.message:String(re);console.warn(`[job] ${h.jobId} knowledge capture failed (non-fatal): ${pe}`)}let{artifacts:Vn,omitted:Ii,dropped:Na}=Mf(q.dir,Ue);for(let re of Ii)console.warn(`[job] ${h.jobId} artifact ${re.path} (${re.bytes} bytes) exceeded upload budget \u2014 content omitted`);Na.length>0&&console.warn(`[job] ${h.jobId} artifact listing truncated: ${Na.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let zn={jobId:h.jobId,status:"succeeded",artifacts:Vn,...cr?{contextWrites:cr}:{},...J.length>0?{deliveries:J}:{},log:V$(B.log),startedAt:D,finishedAt:new Date().toISOString(),usage:B.usage,...B.rateLimit?{rateLimit:B.rateLimit}:{},...V?{build:V}:{},...de?{review:de}:{}};if(R||C.paused)console.warn(`[job] ${h.jobId} skipping result upload \u2014 ${C.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await E.submitResult(zn),console.log(`[job] ${h.jobId} done \u2014 uploaded ${zn.artifacts.length} artifact(s):`);for(let re of zn.artifacts){let pe=Buffer.from(re.contentBase64,"base64").length;console.log(` \xB7 ${re.path} (${pe} bytes)`)}zn.artifacts.length===0&&console.warn(`[job] ${h.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(M){let B=M instanceof Error?M.message:String(M);if(C.paused)console.log(`[job] ${h.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(R)console.warn(`[job] ${h.jobId} failed after claim lost (${B}) \u2014 skipping result upload`);else{let J=lf(M),V=M instanceof Nt,de=M instanceof yt;console.warn(J?`[job] ${h.jobId} failed: ${B} (Claude auth \u2014 token invalid/expired)`:V?`[job] ${h.jobId} failed: ${B} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:de?`[job] ${h.jobId} failed: ${B} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${h.jobId} failed: ${B}`),await E.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:B},startedAt:D,finishedAt:new Date().toISOString(),...J?{authError:!0}:{},...V?{buildInconclusive:!0}:{},...de?{reviewInconclusive:!0}:{}})}}finally{q.dispose()}}finally{clearInterval(T),wt&&clearInterval(wt),O(),C.chatInbox?.close(),m.delete(h.jobId),S?.cleanup(),N?.cleanup()}}function H(E,h){if(!E.credBundle)return{gitCreds:null,contextGitCreds:null};if(!h)return console.warn(`[job] ${E.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let C;try{C=JSON.parse(Rr(h,E.credBundle).toString("utf-8"))}catch(P){return console.warn(`[job] ${E.jobId} failed to open credBundle: ${P instanceof Error?P.message:String(P)}`),{gitCreds:null,contextGitCreds:null}}let R=na(C);R&&console.log(`[job] ${E.jobId} cred bundle opened \u2014 git creds configured`);let S=mf(C,E.contextRepo.cloneUrl),N={gitCreds:R,contextGitCreds:S};return C.claudeOauthToken&&(N.claudeOauthToken=C.claudeOauthToken),N}function j(E,h){return E.split(`
|
|
751
|
+
`).map(C=>h+C).join(`
|
|
752
|
+
`)}function v(E,h,C){let R=h[0]?.workspacePath??"";return E.replace(/\{\{codeDir\}\}/g,R).replace(/\{\{codeRoot\}\}/g,R?R.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,C??"")}function A(E,h,C){let R=E,S=C.includes("::")?"":C.split(":",2)[1]??"",N=P=>{if(!h||!S)return"";try{return Yf(Br(h,"tasks",S,P),"utf-8").trim()}catch{return""}};if(R.includes("{{solutionMd}}")){let P=N("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";R=R.replace(/\{\{solutionMd\}\}/g,()=>P)}if(R.includes("{{taskDescription}}")){let P=N("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";R=R.replace(/\{\{taskDescription\}\}/g,()=>P)}return R}let L=E=>{if(p)return;p=!0,console.log(`
|
|
753
|
+
[${E}] shutting down`),d.abort();let h=[...m.keys()];for(let S of m.values())S.abort.abort();let C=new AbortController,R=setTimeout(()=>C.abort(),3e3);(async()=>(await Promise.all(h.map(async S=>{try{await u.releaseJob(S,`sandbox ${E}`,C.signal),console.log(`[${E}] released job ${S}`)}catch(N){let P=N instanceof Error?N.message:String(N);console.warn(`[${E}] release failed: ${P} (sweeper will reclaim)`)}})),clearTimeout(R),w.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>L("SIGINT")),process.on("SIGTERM",()=>L("SIGTERM"));let G=[x("implementation")];e.planningLane!==!1?G.push(x("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(G)}var si,q$,qf=k(()=>{"use strict";W();Oe();Wi();of();df();ke();ti();gf();Qs();jf();Nf();Lf();Bf();Wf();si=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),q$=new Set(["implement","resolve-conflict"])});var Fr=k(()=>{"use strict";Yp();qf();ti()});import{cancel as J$,isCancel as zf,log as qe,password as X$,text as Q$}from"@clack/prompts";function Z$(t){return zf(t)&&(J$("aborted"),process.exit(1)),typeof t=="string"?t:""}function ev(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function tv(t){let e=ns({redirectUri:rs,challenge:t.challenge,state:t.state});qe.message(`Open this URL, approve the access, and paste the code shown:
|
|
754
|
+
${e}`);let r=await Q$({message:"Authorization code \u2014 blank to skip"});if(zf(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=ru(r,t.state);return await os({code:n,verifier:t.verifier,state:t.state,redirectUri:rs})}catch(n){return qe.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function rv(t){if(Ki()?.claude?.oauthToken&&!t.farm)return qe.message("Claude: this machine already has a shared OAuth token \u2014 the project will use it (set a project-specific one later with `codepipe login`)."),"";if(process.env.CODEPIPE_CLAUDE_AUTOLOGIN==="0"||!process.stdout.isTTY)return null;qe.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=bo(),n;try{n=await nu({...r,openUrl:Vt,log:i=>qe.message(i)})}catch(i){qe.warn(`Browser sign-in didn't complete (${i instanceof Error?i.message:String(i)}) \u2014 trying the code-paste fallback.`);let s=await tv(r);if(s===null)return null;n=s}let o=await It(n.oauthToken);return o==="invalid"?(qe.warn("Claude rejected the obtained token (401) \u2014 falling back to manual entry."),null):(qe.success(`Claude: logged in \u2014 ${ev(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function nv(t){qe.message("Claude login \u2014 pipeline agents run on your Claude subscription.\n Get a token: install Claude Code (https://claude.com/claude-code), run\n `claude setup-token` in a terminal and paste the result here."+(t.farm?`
|
|
755
|
+
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=Z$(await X$({message:"Claude OAuth token \u2014 blank to skip"})).trim();return e?(e.startsWith("sk-ant-")||qe.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`."),e):(qe.warn(t.farm?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"")}var Jf,Xf=k(()=>{"use strict";ko();wr();oe();ss();Jf={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:rv,promptManual:nv,validate:It}});function Qf(t){return Jf}async function Zf(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var em=k(()=>{"use strict";Xf()});async function Kr(t,e,r){return e.host==="github"?iv(t,e,r):e.host==="gitlab"?pv(t,e,r):mv(t,e,r)}async function tm(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 Dt(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await rm(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 Ot(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await nm(e.gitlabToken,t):o}}return e.bitbucket?(await Gr(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await om(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 rm(t,e){let r=!1;try{r=(await Dt(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 nm(t,e){let r=!1;try{r=(await Ot(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 om(t,e){let r=!1;try{r=(await Gr(t,"GET",`/workspaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`Bitbucket repo ${e.owner}/${e.name} does not exist in workspace "${e.owner}" (which the credential can see) \u2014 check the repo name, or the API token lacks access to it`:`Bitbucket workspace "${e.owner}" is not visible to this credential \u2014 check the workspace name and the token's read:repository:bitbucket scope`}async function Dt(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(ov+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 iv(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 sv(n,e,r),i=await cv(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=Sr(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await lv(n,o.owner,o.name,a.path,i)||await uv(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 sv(t,e,r){let n=await Dt(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 rm(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await av(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 Dt(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 av(t,e){let{status:r,data:n}=await Dt(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function cv(t,e,r){let{data:n}=await Dt(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function lv(t,e,r,n,o){let{status:i,data:s}=await Dt(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function uv(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 Dt(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Ot(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(dv+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 pv(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 Ot(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 nm(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await Ot(n,"GET","/user"),d={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(p.data?.username!==e.owner){let f=await Ot(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(f.status===404||!f.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);d.namespace_id=f.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let m=await Ot(n,"POST","/projects",d);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=Sr(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let m=(await Ot(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let f of m)l.add(f.path);if(m.length<100)break}let u=c.filter(p=>!l.has(p.path)).map(p=>({action:"create",file_path:p.path,content:p.content}));return u.length>0?await Ot(n,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:u}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}async function Gr(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(fv+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 mv(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 Gr(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 om(n,e)} (attach joins an existing Context Repo and never creates one)`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let p=await Gr(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(p.status===404||!p.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);i=p.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Sr(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await Gr(n,"GET",`${o}/src/${encodeURIComponent(a)}/${p.path}?format=meta`)).status===404&&l.push(p);if(l.length>0){let p=new URLSearchParams;p.set("message","chore(codepipe): scaffold context repo files"),p.set("branch",a);for(let m of l)p.set(m.path,m.content);if((await Gr(n,"POST",`${o}/src`,{form:p})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let u=i.links?.clone?.find(p=>p.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:u??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var ov,dv,fv,ai=k(()=>{"use strict";rr();ov="https://api.github.com";dv="https://gitlab.com/api/v4";fv="https://api.bitbucket.org/2.0"});function De(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=gv[r];if(!o)return null;let i=n.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(i.length<2)return null;let s=i[i.length-1].replace(/\.git$/,"");return s?{host:o,owner:i.slice(0,-1).join("/"),repoName:s}:null}var gv,ci=k(()=>{"use strict";gv={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as hv}from"node:crypto";import{existsSync as im,mkdirSync as yv,readFileSync as sm,readdirSync as wv,rmSync as li,writeFileSync as bv}from"node:fs";import{homedir as kv}from"node:os";import{dirname as $v,join as aa}from"node:path";function am(){return aa(kv(),".codepipe","init-drafts")}function ca(t){let e=hv("sha256").update(t).digest("hex").slice(0,16);return aa(am(),`${e}.json`)}function cm(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=vv)}function lm(t){let e=ca(t);if(!im(e))return null;try{let r=JSON.parse(sm(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:cm(r.savedAt)?(li(e,{force:!0}),null):r}catch{return null}}function la(t){li(ca(t),{force:!0})}function um(){let t=am();if(im(t))for(let e of wv(t)){let r=aa(t,e);try{let n=JSON.parse(sm(r,"utf-8"));cm(n.savedAt)&&li(r,{force:!0})}catch{li(r,{force:!0})}}}var vv,Hr,dm=k(()=>{"use strict";vv=24*60*60*1e3;Hr=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(){la(this.cwd)}persist(){let e=ca(this.cwd);yv($v(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};bv(e,JSON.stringify(r,null,2)+`
|
|
756
|
+
`,{mode:384})}}});function pm(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 fm(){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 mm(t,e){if(t.host!=="github"||!e)return!1;try{return(await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/contents/knowledge/INDEX.md?ref=${encodeURIComponent(t.branch)}`,{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}})).status===200}catch{return!1}}var gm=k(()=>{"use strict"});import{existsSync as xv}from"node:fs";import{join as Sv}from"node:path";import{simpleGit as Rv}from"simple-git";function Ev(t){let e=t.split("/");return e[e.length-1]??t}function hm(t){if(t.filter(r=>!Iv.test(Ev(r))).length>Tv)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(Cv.has(n))return!0}return!1}async function Pv(t){try{let r=(await Rv(t).raw(["ls-files"])).split(`
|
|
757
|
+
`).map(n=>n.trim()).filter(Boolean);return hm(r)}catch{return!1}}async function Av(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)?hm(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function ym(t,e){for(let r of t)try{let n=e.localRoot!=null?Sv(e.localRoot,r.mountAs??r.name):null;if(n&&xv(n)?await Pv(n):await Av(r,e.tokens))return!0}catch{}return!1}var Tv,Iv,Cv,wm=k(()=>{"use strict";Tv=3,Iv=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,Cv=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as bm}from"node:fs";import{join as km}from"node:path";import{simpleGit as $m}from"simple-git";async function Un(t,e,r={}){let n=r.log??jv,o=[];for(let i of e){let s=km(t,i.mountAs),a=qc(i);if(!bm(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 $m().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let p=Ln(u instanceof Error?u.message:String(u));n.warn(`clone failed for ${i.mountAs}: ${p}`),o.push({mountAs:i.mountAs,status:"error",detail:p})}continue}if(!bm(km(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=$m(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!_v(l,a)){n.warn(`${i.mountAs}/ origin (${Ln(l)||"none"}) != expected (${Ln(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:Ln(l)});continue}if(r.dryRun){n.info(`would fetch ${i.mountAs}/`),o.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),o.push({mountAs:i.mountAs,status:"fetched"})}catch(u){let p=Ln(u instanceof Error?u.message:String(u));n.warn(`fetch failed for ${i.mountAs}: ${p}`),o.push({mountAs:i.mountAs,status:"error",detail:p})}}return o}function _v(t,e){return vm(t)===vm(e)}function vm(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function Ln(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function xm(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 Un(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 jv,ui=k(()=>{"use strict";tt();jv={info:t=>console.log(t),warn:t=>console.warn(t)}});import{spawn as Rm}from"node:child_process";import{existsSync as Sm}from"node:fs";import{homedir as Nv,hostname as Ov}from"node:os";import{join as di}from"node:path";async function Dv(t,e,r){let n=ye(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${Ye(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 pu(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 ${Ye(e)} still holds its token.
|
|
758
|
+
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`),dl(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function Lv(t,e,r){let n=ye(e)!==null;if(!await Dv(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 xo(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof U&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof U&&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 U?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 nr({hub:t.hubUrl,token:o,name:r.name??`${Ov()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function Uv(t,e){let r=ye(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=xe(r.sealPublicKey);if(!F(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=uo(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 ua(t,e,r){await Lv(t,e,r),Uv(t.projectId,e)}function Mv(t){return[...t?["--profile",t]:[],"worker","start"]}function Bv(t){let e={...t};for(let r of Hi)delete e[r];return e}function da(t){let e=Rm(process.execPath,[t.entry,...Mv(t.profile)],{stdio:["ignore","pipe","pipe"],env:Bv(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
|
|
759
|
+
`))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function Fv(t,e){let r=process.cwd(),n=di(r,et);if(ao(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(Sm(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(u){console.warn(`[up] could not fetch the project summary (${u instanceof Error?u.message:String(u)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await ma(r);if(!Yc(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=F(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await Zo({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=di(Nv(),".codepipe",e?di("profiles",e,"context-config"):"context-config");if(Ao(c.contextDir,l,a),!Sm(di(c.contextDir,"project.yaml"))){vr(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};bn(c.contextDir,ot(u,!0,s?.youtrack?.url)),console.log("[up] local project config seeded with defaults \u2014 review .codepipe/project.yaml")}console.log(`[up] project context materialized \u2192 ${n}`)}async function pa(t){let{cfg:e,profile:r}=lo(t.profile);await Fv(e,r),await ua(e,r,t);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(m,f)=>{let g=y=>b=>{for(let w of b.toString("utf-8").split(`
|
|
758
760
|
`))w.length>0&&y.write(`${f} ${w}
|
|
759
|
-
`)};m.stdout?.on("data",g(process.stdout)),m.stderr?.on("data",g(process.stderr))},i=(m,f)=>{let g=
|
|
761
|
+
`)};m.stdout?.on("data",g(process.stdout)),m.stderr?.on("data",g(process.stderr))},i=(m,f)=>{let g=Rm(process.execPath,[n,...f],{stdio:["ignore","pipe","pipe"],env:process.env});return o(g,m),g};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=da({entry:n,profile:r,onLine:m=>process.stdout.write(`[worker] ${m}
|
|
760
762
|
`)}),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,u=m=>{if(!l){l=!0,console.log(`
|
|
761
|
-
[up] ${m} \u2014 stopping both roles`);for(let{child:f}of c)f.exitCode===null&&f.kill(m);setTimeout(()=>{for(let{name:f,child:g}of c)g.exitCode===null&&(console.warn(`[up] ${f} did not stop \u2014 SIGKILL`),g.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:m,child:f})=>new Promise(g=>{f.on("exit",(y
|
|
763
|
+
[up] ${m} \u2014 stopping both roles`);for(let{child:f}of c)f.exitCode===null&&f.kill(m);setTimeout(()=>{for(let{name:f,child:g}of c)g.exitCode===null&&(console.warn(`[up] ${f} did not stop \u2014 SIGKILL`),g.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:m,child:f})=>new Promise(g=>{f.on("exit",(y,b)=>g({name:m,code:y??(b?1:0)}))})),d=await Promise.race(p);l||(console.log(`[up] ${d.name} exited (code ${d.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(p),process.exit(d.code)}var fa=k(()=>{"use strict";Oe();Fr();Te();ft();zs();rr();ge();oe();tt();Mn()});var Nm={};Zg(Nm,{replCommand:()=>wa});import{existsSync as Am,mkdirSync as Gv,readFileSync as Kv,writeFileSync as Hv}from"node:fs";import{homedir as Wv}from"node:os";import{dirname as Yv,join as jm}from"node:path";import*as Wr from"node:readline";async function wa(t={}){let e=$e();e||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let r=F(e.spec.projectId);r||(console.error(`no secrets for project ${e.spec.projectId} at ~/.codepipe/secrets/${e.spec.projectId}.json. run \`codepipe init\` or \`codepipe clone\` to set them up.`),process.exit(1)),un(r),console.log(`connected to ${r.hubUrl} as project ${e.spec.projectId}`),console.log("the CLI daemon and an embedded agent worker run in this session; /logs and /monitor show their output."),console.log("type /help to list commands. Ctrl+D or /quit to exit.");let n=er(e.contextDir),o=Object.keys(n);o.length>0&&console.log(`
|
|
762
764
|
\u26A0 unfinished local apply: ${o.map(a=>`${a} (${n[a].repos.map(c=>c.mountAs).join(", ")})`).join("; ")}
|
|
763
|
-
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let i=
|
|
764
|
-
`))}async function
|
|
765
|
-
`)}`:" (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}
|
|
766
|
-
`),t.unread+=1,
|
|
765
|
+
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let i=Wr.createInterface({input:process.stdin,output:process.stdout,completer:qv,history:fx(),removeHistoryDuplicates:!0}),s={ws:e,secrets:r,connection:"connecting",rl:i,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};Su(a=>Ut(s,a)),s.daemon=Xo({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:a=>Ut(s,a),warn:a=>Ut(s,a)},onEvent:a=>ax(s,a),workspace:{root:e.root,contextDir:e.contextDir,repos:e.spec.repos.map(a=>({name:a.name,mountAs:a.mountAs,defaultBranch:a.defaultBranch}))}});try{let a={hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId};await ua(a,t.profile,{profile:t.profile});let c=process.argv[1];if(!c)throw new Error("cannot resolve the codepipe entry script for the worker process");let l=da({entry:c,profile:t.profile,onLine:u=>Ut(s,`[worker] ${u}`)});l.on("exit",(u,p)=>{s.workerExited=!0,!ya&&Lt(s,`[worker] exited (code ${u??(p?1:0)}) \u2014 agent jobs will NOT run; /quit and restart codepipe to bring it back`)}),s.workerChild=l,console.log("embedded agent worker started \u2014 agent jobs run on this machine.")}catch(a){console.warn(`[worker] could not start the embedded worker (${a instanceof Error?a.message:String(a)}). REPL commands still work; run \`codepipe up --reregister\` if the registration was removed.`)}ha(s),i.prompt(),i.on("line",async a=>{let c=a.trim();if(c.length>0)try{if(await Vv(s,c)){Pm(s);return}}catch(l){console.error(l instanceof Error?l.message:String(l))}s.unread=0,ha(s),i.prompt()}),i.on("close",()=>{Pm(s)})}function qv(t){let e=Tm.filter(r=>r.startsWith(t));return[e.length?e:Tm,t]}async function Vv(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return zv(),!1;case"/status":return await Jv(t),!1;case"/tasks":return await Xv(t,n),!1;case"/task":return await Qv(t,n),!1;case"/sync":return await Zv(t),!1;case"/logs":return cx(t,n),!1;case"/monitor":return lx(t),!1;case"/apply":return await Cm(t,n,"apply"),!1;case"/unstash":return await Cm(t,n,"unstash"),!1;case"/applied":return await ex(t,n),!1;case"/abort":return await tx(t,n),!1;case"/approve":return await Em(t,n,"approve"),!1;case"/merge":return await Em(t,n,"merge"),!1;case"/login":return nx(t,n),!1;case"/secret":return ox(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function zv(){console.log(["/help show this list","/status connection, project, embedded worker, siblings","/tasks [--phase P] list tasks (optionally filtered by phase)","/task <key> task detail (phase + artifacts)","/sync clone/fetch project repos per project.yaml","/logs [n|follow|clear] tail last n daemon/worker logs / toggle live / clear buffer","/monitor toggle live daemon/worker log streaming (alias /logs follow)","/apply <key> apply task patch on a new branch + commit (local mode)","/unstash <key> apply task patch uncommitted on base commit","/applied <key> --pr U mark applied; --pr repo=URL for multi-repo","/abort <key> --reason roll back local apply, send task back to agent","/approve <key> merge the task's PR(s) (TRACKING, PR mode)","/merge <key> direct-merge the branch to main (TRACKING, no-PR mode)","/login <token> set the Claude OAuth token (not stored in history)","/secret set <k> <v> set a secret (not stored in history)","/secret list list secret keys (no values)","/secret unset <k> remove a secret","/quit stop the daemon and the worker, exit"].join(`
|
|
766
|
+
`))}async function Jv(t){let e=t.connection==="registered"?"registered":t.connection==="rejected"?"rejected":t.connection==="offline"?"offline (reconnecting)":"connecting";console.log(` hub: ${t.secrets.hubUrl} (${e})`);let r=t.workerChild?t.workerExited?"exited \u2014 agent jobs will not run (restart codepipe)":`running (pid ${t.workerChild.pid})`:"not started \u2014 agent jobs will not run";console.log(` worker: ${r}`),console.log(` project: ${t.ws.spec.projectId}`),console.log(` workspace: ${t.ws.root}`);for(let n of t.ws.spec.repos){let o=Am(jm(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function Xv(t,e){let r=ux(e,"--phase");try{let n=await hu(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){Bn(n)}}async function Qv(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await yu(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){Bn(n)}}async function Zv(t){let e=await Un(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 Cm(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await Ou(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function ex(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=er(t.ws.contextDir)[r],i=dx(e,"--pr");if(i.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let s=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of i){let l=c.indexOf("="),u,p;if(l>0?(u=c.slice(0,l),p=c.slice(l+1)):(p=c,u=o?.repos.length===1?rx(t,o.repos[0].mountAs):s.length===1?s[0]:""),!u){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${p}`);return}let d=p.match(/(?:pull|pull-requests)\/(\d+)/);if(!d){console.log(` cannot parse PR number from ${p}`);return}a.push({repoName:u,url:p,number:Number(d[1])})}try{let c=await wu(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);ps(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){Bn(c)}}async function Em(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await ku(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){Bn(o)}}async function tx(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=px(e,"--reason")||"local apply aborted";await Lu(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await bu(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){Bn(o)}}function rx(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function nx(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},X(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 ox(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(`
|
|
767
|
+
`)}`:" (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}ix(t.secrets,n,i),X(t.secrets),un(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}sx(t.secrets,n),X(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function ix(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 sx(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 ax(t,e){switch(e.kind){case"connected":t.connection="connecting",Ut(t,"[hub] connected");break;case"registered":t.connection="registered",Ut(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Lt(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",Ut(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Lt(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Lt(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?Ut(t,`[hub] action ${e.actionType} done`):Lt(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break;case"local_applied":e.ok?Lt(t,`[apply] ${e.taskKey}: branch ${(e.branches??[]).join(", ")} created locally (your checkout is untouched) \u2014 review, push, then: /applied ${e.taskKey} --pr <url>`):Lt(t,`[apply] ${e.taskKey}: auto-apply failed \u2014 task stays in READY_TO_APPLY: ${e.error??"?"}`);break}}function Ut(t,e){t.logBuffer.push(e),t.logBuffer.length>_m&&t.logBuffer.shift(),t.follow&&Lt(t,e)}function cx(t,e){let r=e[0];if(r==="follow"||r==="on"){ga(t,!0);return}if(r==="off"){ga(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(_m,Number(r)||Im)):Im,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 lx(t){ga(t,!t.follow)}function ga(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Lt(t,e){Wr.cursorTo(process.stdout,0),Wr.clearLine(process.stdout,0),process.stdout.write(e+`
|
|
768
|
+
`),t.unread+=1,ha(t),t.rl.prompt(!0)}function ha(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}function Pm(t){if(ya)return;ya=!0,mx(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
|
|
767
769
|
bye.`),setTimeout(()=>process.exit(0),150);return}console.log(`
|
|
768
|
-
stopping the embedded worker\u2026`),e.kill("SIGTERM"),e.on("exit",()=>{console.log("bye."),setTimeout(()=>process.exit(0),150)}),setTimeout(()=>{t.workerExited||e.kill("SIGKILL")},8e3).unref(),setTimeout(()=>process.exit(0),1e4).unref()}function
|
|
770
|
+
stopping the embedded worker\u2026`),e.kill("SIGTERM"),e.on("exit",()=>{console.log("bye."),setTimeout(()=>process.exit(0),150)}),setTimeout(()=>{t.workerExited||e.kill("SIGKILL")},8e3).unref(),setTimeout(()=>process.exit(0),1e4).unref()}function ux(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function dx(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 px(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function Bn(t){t instanceof U?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function fx(){if(!Am(pi))return[];try{return Kv(pi,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function mx(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{Gv(Yv(pi),{recursive:!0}),Hv(pi,r.slice().reverse().join(`
|
|
769
771
|
`)+`
|
|
770
|
-
`)}catch{}}var
|
|
771
|
-
${
|
|
772
|
-
starting codepipe \u2014 the CLI daemon, an agent worker, and a command line. type /help for commands; Ctrl+D or /quit to exit (restart anytime with \`codepipe\` from this folder).`);let{replCommand:
|
|
772
|
+
`)}catch{}}var pi,Tm,_m,Im,ya,ba=k(()=>{"use strict";qs();ge();So();oe();tt();ui();fa();fs();pi=jm(Wv(),".codepipe","history"),Tm=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],_m=500,Im=40;ya=!1});import{existsSync as Yr,mkdirSync as Dm,readFileSync as Lm,readdirSync as gx,writeFileSync as Um}from"node:fs";import{join as ir,resolve as Mm}from"node:path";import{setTimeout as ka}from"node:timers/promises";import{cancel as hx,confirm as qr,intro as Bm,isCancel as fi,log as _,outro as $a,password as Fn,select as Ve,spinner as xa,text as le}from"@clack/prompts";import{simpleGit as gi}from"simple-git";function ne(t){hx(t),process.exit(1)}function we(t){return fi(t)&&ne("aborted"),t}function te(t){return fi(t)&&ne("aborted"),typeof t=="string"?t:""}async function Fm(t={}){Bm("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();um();let r=lm(e),n,o=!1;r&&Object.keys(r.answers).length>0?we(await qr({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(_.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new Hr(e,r),o=!0):(la(e),n=new Hr(e)):n=new Hr(e);let i=t.force===!0?null:await ma(e),s=await n.ask("target",async()=>we(await Ve({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?_.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||Km(e,t.force===!0));let c=await n.ask("hubUrl",async()=>te(await le({message:"HUB URL",placeholder:Je,initialValue:K("HUB_URL")??Je,validate:O=>O.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>Vr()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>zr(c,l)),d=null;s==="farm"&&(d=await yx(c,u));let m=a?bx(a.parsed.repoName):"",f=await n.ask("projectId",async()=>te(await le({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:O=>Kt.test(O.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await n.ask("projectName",async()=>te(await le({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:O=>O.trim().length>0?void 0:"required"})).trim()),y=await n.ask("automationLevel",async()=>we(await Ve({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"}))),b=s==="farm"?"auto":await n.ask("applyMode",async()=>we(await Ve({message:"how do approved changes reach your repo?",options:[{value:"auto",label:"auto \u2014 CodePipe pushes the branch and opens a PR"},{value:"local",label:"local \u2014 changes wait; you pull them into your checkout via the CLI REPL (/apply or /unstash), no push/PR"}],initialValue:"auto"}))),w=await n.ask("trackerProvider",async()=>we(await Ve({message:"task tracker",options:[{value:"internal",label:"built-in \u2014 CodePipe tracks tasks itself (no external tracker needed)"},{value:"youtrack",label:"YouTrack \u2014 connect an existing YouTrack project"}],initialValue:"internal"}))),x=w==="internal",I=null,H,j=!0;if(x){let O,ae=xa();ae.start("checking task-key prefixes on your account\u2026");try{O=await fu(c,u,{excludeProjectId:f}),ae.stop("prefixes checked")}catch{ae.stop("could not reach the HUB",1),ne("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 Ce=Lc(Dc(g),O);H=await n.ask("trackerPrefix",async()=>te(await le({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:Ce,initialValue:Ce,validate:Le=>{let wt=Le.trim();if(!dr.test(wt))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(O.has(wt.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else I=await n.ask("youtrack",()=>Jm()),H=await n.ask("youtrackProjectKey",async()=>te(await le({message:"YouTrack project key",placeholder:"DEV",validate:O=>O.trim().length>0?void 0:"required"})).trim()),j=await n.ask("youtrackWrites",async()=>we(await qr({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let v=n.get("tokens")??{},A=()=>n.set("tokens",v),L=await n.ask("repos",()=>vx(v,l,a,{onCred:A,initial:n.get("reposPartial")??[],onProgress:O=>n.set("reposPartial",O)}));n.delete("reposPartial");let G=await xx(await n.ask("contextRepo",()=>qm(f,L,v,l)),f,L,v,l,A,O=>n.set("contextRepo",O)),{spec:E,mode:h}=G,C;x||(_.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),C=await n.ask("assigneeLogin",async()=>te(await le({message:"your YouTrack login (the assignee value)",...I?.login?{initialValue:I.login}:{},validate:O=>O.trim().length>0?void 0:"required"})).trim()));let R=await n.ask("llmProvider",async()=>{for(;;){if(we(await Ve({message:"LLM provider",options:[{value:"claude",label:"Claude",hint:"recommended"},{value:"codex",label:"Codex",hint:"coming soon"}],initialValue:"claude"}))==="claude")return"claude";_.warn("Codex support is coming soon \u2014 pick Claude for now.")}}),S=R==="claude"?await n.ask("claudeToken",()=>Zf(Qf("claude"),{farm:s==="farm"})):"",N;if(S){let O=await eu(S);if(O){let ae=cc(O);ae&&(N=ae,_.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${ae} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let P={projectId:f,name:g,automationLevel:y,repos:L,trackerProvider:w,youtrackProjectKey:H};_.step(`${h==="attach"?"attaching to":"provisioning"} Context Repo ${E.owner}/${E.name} (${E.host})\u2026`);let $;try{$=await Kr(P,E,{...Vm(v),youtrackWrites:j,...I?{trackerUrl:I.url}:{},mode:h,log:{info:O=>_.message(O),warn:O=>_.warn(O)}})}catch(O){ne(`Context Repo provisioning failed: ${O instanceof Error?O.message:String(O)}`)}P.contextRepo=$,_.success(`Context Repo ready: ${$.owner}/${$.name}@${$.branch}`),_.step(`registering project on ${c}\u2026`);let T;try{T=await Ct(c,u,P)}catch(O){if(O instanceof U&&O.status===409){_.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{T=await Q(c,u,f)}catch(ae){throw ae instanceof U&&ne(`HUB \u2192 ${ae.status} ${ae.message}`),ae}}else if(O instanceof U&&O.status===401)n.delete("cliToken"),ne("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(O instanceof U)ne(`HUB \u2192 ${O.status} ${O.message}`);else throw O}let D=T.contextRepo??$;_.success(`project ${T.projectId} ready (${T.provisioningStatus})`);let z=await Cx(D),ze=I?{url:I.url,token:I.token}:void 0;if(s==="farm"){let O=d,ae={...v,...z?{contextWrite:z}:{},...S?{claude:{oauthToken:S}}:{},...ze?{youtrack:ze}:{}},Ce=v.github?.token;if(D.host==="github"&&Ce)try{let Z=Pp(`devpipe-${f}`);await Ap(D,Ce,Z.publicKey,`devpipe-${f}`),ae.contextSsh={privateKey:Z.privateKey},_.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(Z){_.warn(`could not set up Context Repo SSH deploy key (${Z instanceof Error?Z.message:String(Z)}); the farm will fall back to the token path.`)}let Le={projectId:f,config:{hubUrl:c,cliToken:u,projectId:f},secrets:ae,contextRepo:D,projectConfig:ot(P,j,I?.url,C||void 0,"auto",R,N)},wt=gt(O.farm.publicKey,JSON.stringify(Le));_.step(`handing project ${f} to farm ${O.farm.name}\u2026`);let q;try{q=await vo(c,u,O.farm.farmId,{projectId:f,sealedBundle:wt})}catch(Z){throw Z instanceof U&&ne(Z.status===409?`farm ${O.farm.name} is offline \u2014 start it and re-run.`:Z.status===504?`farm ${O.farm.name} did not respond in time.`:`HUB \u2192 ${Z.status} ${Z.message}`),Z}q.ok||ne(`farm rejected provisioning: ${q.error??"unknown error"}`),await va(c,u,f,D,Ce,T.repos,null,v),n.clear(),$a(`done. project ${f} is now hosted on farm ${O.farm.name} (daemon ${q.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}zm(v),await Hm(e,D.cloneUrl,D.branch),Ym(e),a&&await $x(e);{let O=ir(e,et);vr(O);let ae=ot(P,j,I?.url,C||void 0,b,R,N),Ce=bn(O,ae);Ce.length>0&&_.success(`local project config \u2192 .codepipe/{${Ce.join(", ")}}`),tr(f,ae,{info:Le=>_.message(Le),warn:Le=>_.warn(Le)})}await Wm(e,T.repos);let $i={hubUrl:c,cliToken:u,projectId:f,...v,...z?{contextWrite:z}:{},...S?{claude:{oauthToken:S}}:{},...ze?{youtrack:ze}:{}};X($i),pt({hubUrl:c,cliToken:u,projectId:f,accountEmail:p},f),_.success(`secrets \u2192 ${rt(f)}`),await va(c,u,f,D,v.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,T.repos,e,v),n.clear();let qn=`${c}/?project=${encodeURIComponent(f)}`;Vt(qn),$a(`done. your project on the dashboard (sign in there to work with it):
|
|
773
|
+
${qn}
|
|
774
|
+
starting codepipe \u2014 the CLI daemon, an agent worker, and a command line. type /help for commands; Ctrl+D or /quit to exit (restart anytime with \`codepipe\` from this folder).`);let{replCommand:vi}=await Promise.resolve().then(()=>(ba(),Nm));await vi({})}async function va(t,e,r,n,o,i=[],s=null,a={}){let c=await mm(n,o);if(!c){let p=!1;try{p=await ym(i,{localRoot:s,tokens:a})}catch{p=!1}if(p){let d=fm(),m=await Ve({message:d.message,options:d.options,initialValue:d.initialValue});if(!fi(m)&&m===d.proceedValue)try{let{jobId:f}=await fn(t,e,r,{reindex:!1,backfill:!0});_.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){_.warn(`could not start the retrospective analysis: ${f instanceof Error?f.message:String(f)}. Registration is not affected.`)}}}let l=pm(c),u=await Ve({message:l.message,options:l.options,initialValue:l.initialValue});if(!(fi(u)||u!==l.proceedValue))try{let{jobId:p}=await fn(t,e,r,{reindex:l.reindex});_.success(`indexing queued (job ${p}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(p){_.warn(`could not start indexing: ${p instanceof Error?p.message:String(p)}. You can retry later \u2014 registration is not affected.`)}}async function yx(t,e){let r;try{r=await lu(t,e)}catch(c){throw c instanceof U&&ne(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&ne("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=we(await Ve({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=Vo(i.farmId,i.publicKey)}catch(c){ne(c instanceof Error?c.message:String(c))}return we(await qr({message:`confirm farm ${i.name} cred-channel fingerprint:
|
|
773
775
|
${s}
|
|
774
|
-
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||
|
|
776
|
+
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||ne("farm fingerprint not confirmed \u2014 aborting."),qo(i.farmId,s),{farm:i,fingerprint:s}}async function Gm(t){Bm(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();Km(e,t.force===!0);let r=te(await le({message:"HUB URL",initialValue:K("HUB_URL")??Je,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await Vr(),{cliToken:o,accountEmail:i}=await zr(r,n);_.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await Q(r,o,t.projectId)}catch(d){throw d instanceof U&&ne(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||ne(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await Jm(),l={},u=new Set(s.repos.map(d=>d.host));u.add(s.contextRepo.host);for(let d of u){let m=s.repos.find(f=>f.host===d);await mi(d,l,m?.owner??s.contextRepo.owner,n,m?.repoName)}zm(l),await Hm(e,s.contextRepo.cloneUrl,s.contextRepo.branch),Ym(e);{let d=ir(e,et);vr(d);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=ot(m,!0,c?.url,void 0,"auto",s.llmProvider??Ze),g=bn(d,f);g.length>0&&_.success(`local project config \u2192 .codepipe/{${g.join(", ")}} (defaults \u2014 review and adjust)`),tr(t.projectId,f,{info:y=>_.message(y),warn:y=>_.warn(y)})}await Wm(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};X(p),pt({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),_.success(`secrets \u2192 ${rt(t.projectId)}`),await va(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),$a("done.")}function Km(t,e){if(!Yr(t)){Dm(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=gx(t).filter(o=>!r.has(o));n.length!==0&&(e||ne(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function ma(t){if(!Yr(ir(t,".git")))return null;try{let r=(await gi(t).remote(["get-url","origin"])||"").toString().trim(),n=r?De(r):null;return n?{parsed:n,defaultBranch:await wx(t)}:null}catch{return null}}async function wx(t){let e=gi(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 bx(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Kt.test(e)?e:""}function kx(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function $x(t){let e=ir(t,".gitignore"),r=Yr(e)?Lm(e,"utf-8"):"";if(kx(r))return;if(!we(await qr({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){_.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
|
|
775
777
|
`)?"":`
|
|
776
|
-
`;
|
|
778
|
+
`;Um(e,r+o+`
|
|
777
779
|
# codepipe workspace (added by \`codepipe init\`)
|
|
778
780
|
.codepipe/
|
|
779
|
-
`),
|
|
781
|
+
`),_.success(`.codepipe/ added to ${Mm(e)}`)}async function Vr(){let t="";try{t=(await gi().raw(["config","--global","user.email"])||"").trim()}catch{}return te(await le({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function zr(t,e){_.step(`connecting account ${e}`);let r;try{r=await mu(t,e)}catch(s){throw s instanceof pn&&ne(`${e} is not authorized on this HUB yet.
|
|
780
782
|
Sign up at ${t} (registration form on the login screen),
|
|
781
783
|
wait for the operator to approve it by email, then re-run
|
|
782
|
-
\`codepipe init\` with the same email.`),s}r.accountCreated&&
|
|
784
|
+
\`codepipe init\` with the same email.`),s}r.accountCreated&&_.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&_.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(Vt(r.authorizeUrl),_.message(`a browser tab was opened to confirm this CLI:
|
|
783
785
|
${r.authorizeUrl}
|
|
784
786
|
`+(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
|
|
785
|
-
otherwise use the emailed link the page offers.`))),r.approvalRequired&&
|
|
786
|
-
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await
|
|
787
|
+
otherwise use the emailed link the page offers.`))),r.approvalRequired&&_.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),_.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 gu(t,r.requestId)}catch(a){_.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await ka(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&_.message(`connected as ${a} (the account confirmed in the browser).`),_.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&ne("the HUB rejected this account"),s.status==="expired"&&ne("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,_.message(`email confirmed. waiting for the operator to approve your account\u2026
|
|
788
|
+
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await ka(5e3);continue}await ka(2e3)}ne("bootstrap timed out")}async function Hm(t,e,r){let n=ir(t,et);if(Yr(ir(n,".git"))){_.message(`${n} already cloned \u2014 skipping`);return}Yr(n)&&ne(`${n} exists but is not a git repo \u2014 remove it and re-run`),Dm(n,{recursive:!0}),_.step(`cloning Context Repo \u2192 ${n}`);try{await gi().clone(e,n,["--branch",r]),_.success(`cloned ${e}`)}catch(o){ne(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function Wm(t,e){if(e.length===0)return;_.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 Un(t,r,{log:{info:o=>_.message(o),warn:o=>_.warn(o)}});for(let o of n)_.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function Ym(t){let e=ir(t,et,".gitignore"),r="";if(Yr(e)&&(r=Lm(e,"utf-8")),Om.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
|
|
787
789
|
`)||r.length===0?"":`
|
|
788
|
-
`,i=
|
|
790
|
+
`,i=Om.join(`
|
|
789
791
|
`)+`
|
|
790
|
-
`;
|
|
791
|
-
`:"")+i),
|
|
792
|
+
`;Um(e,r+o+(r?`
|
|
793
|
+
`:"")+i),_.message(`appended runtime entries to ${Mm(e)}`)}async function vx(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;_.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await mi(s.host,t,s.owner,e,s.repoName),i?.();let c=te(await le({message:"repo logical name (used inside Context Repo paths)",placeholder:s.repoName,initialValue:s.repoName,validate:u=>u.trim().length>0?void 0:"required"})).trim(),l=te(await le({message:"default branch",placeholder:a,initialValue:a,validate:u=>u.trim().length>0?void 0:"required"})).trim();o.push({name:c,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:l,mountAs:"."}),n.onProgress?.(o)}for(;we(await qr({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=te(await le({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:m=>!m||!m.trim()||De(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=De(a);_.message(`${c.host}: ${c.owner}/${c.repoName}`),await mi(c.host,t,c.owner,e,c.repoName),i?.();let l=te(await le({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:m=>m.trim().length>0?void 0:"required"})).trim(),u=te(await le({message:"default branch (optional)",placeholder:"main"})).trim(),p=te(await le({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),d={name:l,host:c.host,owner:c.owner,repoName:c.repoName};u&&(d.defaultBranch=u),p&&p!==l&&(d.mountAs=p),o.push(d),n.onProgress?.(o)}return o}async function qm(t,e,r,n){_.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=we(await Ve({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"&&_.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=te(await le({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:dt(t),validate:u=>{let p=(u??"").trim();if(!p)return"required";if(!De(p)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(p))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),l=De(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await Sx(),l=te(await le({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=te(await le({message:"Context Repo name",placeholder:dt(t),initialValue:dt(t),validate:p=>p.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:o}}function Vm(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??gr()}}async function xx(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await mi(c.host,n,c.owner,o),i?.();let u=xa();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let p=await tm(c,Vm(n),{explain:l==="attach"});if(p.found===!0)return u.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(p.found==="unknown")return u.stop(`could not check ${c.owner}/${c.name} (${p.detail}) \u2014 continuing`,1),a;if(l==="create")return u.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;u.stop(p.detail,1);let d=we(await Ve({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(d==="abort"&&ne("aborted"),d==="create")return a={spec:c,mode:"create"},s(a),a;a=await qm(e,r,n,o),s(a)}}async function Sx(){return we(await Ve({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Gn(t,e){let r=xa();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 zm(t){Sn(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Rn(t.gitlab?.token??process.env.GITLAB_TOKEN),Tn(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function mi(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await Rx(r);i?e.github=i:_.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let i=await Tx(r,n,o);i?e.bitbucket=i:_.warn("no Bitbucket API token \u2014 git falls back to this machine's SSH keys / BITBUCKET_* env; private repos won't clone over HTTPS and PRs won't open.")}else{let i=await Ix();i?e.gitlab=i:_.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function Rx(t){for(;;){let e=te(await Fn({message:`GitHub PAT \u2014 blank to skip
|
|
792
794
|
classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
|
|
793
795
|
fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
|
|
794
796
|
if org: approve token in org Settings \u2192 Personal access tokens.
|
|
795
797
|
(Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo;
|
|
796
|
-
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await
|
|
798
|
+
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await Gn("GitHub",()=>$t(e,t?{owner:t}:void 0)))return{token:e};_.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function Tx(t,e,r){for(_.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
|
|
797
799
|
How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
|
|
798
800
|
'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes:
|
|
799
801
|
read:repository:bitbucket + write:repository:bitbucket +
|
|
800
802
|
read:pullrequest:bitbucket + write:pullrequest:bitbucket
|
|
801
803
|
\u2014 write scopes do NOT include read: pick BOTH scopes of each pair
|
|
802
804
|
(+ admin:repository:bitbucket if this token will provision the Context Repo).
|
|
803
|
-
The token is shown ONCE \u2014 copy it right away.`);;){let n=
|
|
804
|
-
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await
|
|
805
|
+
The token is shown ONCE \u2014 copy it right away.`);;){let n=te(await le({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:i=>!i||!i.trim()||i.includes("@")?void 0:"must be an email"})).trim();if(!n)return;let o=te(await Fn({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){_.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await Gn("Bitbucket",async()=>{let i=await vt(n,o,t);if(t&&r){let s=await wo(n,o,t,r);if(s)throw new Error(s)}return i}))return{email:n,apiToken:o};_.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function Ix(){for(;;){let t=te(await Fn({message:`GitLab PAT \u2014 blank to skip
|
|
806
|
+
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Gn("GitLab",()=>xt(t))){let e=await vl(t);return e&&_.warn(e),{token:t}}_.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function Cx(t){if(we(await qr({message:`Issue a separate context-write token (scoped to the Context Repo only)?
|
|
805
807
|
Without it the SANDBOX pushes delivery commits with the project ${t.host}
|
|
806
808
|
credential. A scoped token hardens setups where the SANDBOX runs outside
|
|
807
|
-
your trusted network.`,initialValue:!1})))for(t.host==="github"?
|
|
809
|
+
your trusted network.`,initialValue:!1})))for(t.host==="github"?_.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
|
|
808
810
|
permissions Contents: Read and write + Workflows: Read and write (Workflows is
|
|
809
|
-
required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):
|
|
810
|
-
(${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=
|
|
811
|
-
[${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}Dr();xe();me();async function xf(t={profile:void 0}){let e=Pe(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=po(e.hubUrl,e.cliToken),n=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let u=l.toString("utf-8");if(s.push(`msg:${u}`),u!=="pong")try{let p=JSON.parse(u);p.type==="registered"?(a=!!p.ok,clearTimeout(c),r.send("ping")):p.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,u)=>{s.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of n.events)console.log(` ${i}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await J(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=he(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`)")}Nn();import{readFileSync as Tv}from"node:fs";W();xe();lt();Qo();Zt();bt();Ht();me();re();function se(t){throw new Error(t)}function pe(t,e){return(typeof t!="string"||t.trim().length===0)&&se(`config: '${e}' must be a non-empty string`),t.trim()}function Un(t,e){if(t==null)return;typeof t!="string"&&se(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function Rv(t){(!t||typeof t!="object")&&se("config: expected a JSON object");let e=t,r=pe(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||se("config: 'hubUrl' must start with http(s)://");let n=pe(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&se("config: 'project' is required");let i=o,s=pe(i.id,"project.id");Mt.test(s)||se("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=pe(i.name,"project.name"),c=pe(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&se("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||se("config: 'project.repos' must be an array");let u=l.map((w,v)=>{(!w||typeof w!="object")&&se(`config: project.repos[${v}] must be an object`);let I=w,G=pe(I.host,`project.repos[${v}].host`);G!=="github"&&G!=="bitbucket"&&G!=="gitlab"&&se(`config: project.repos[${v}].host must be 'github', 'bitbucket' or 'gitlab'`);let P={name:pe(I.name,`project.repos[${v}].name`),host:G,owner:pe(I.owner,`project.repos[${v}].owner`),repoName:pe(I.repoName,`project.repos[${v}].repoName`)},N=Un(I.defaultBranch,`project.repos[${v}].defaultBranch`);N&&(P.defaultBranch=N);let F=Un(I.mountAs,`project.repos[${v}].mountAs`);return F&&(P.mountAs=F),P}),p=i.contextRepo;(!p||typeof p!="object")&&se("config: 'project.contextRepo' is required");let d=p,m=Un(d.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&se("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:m,owner:pe(d.owner,"project.contextRepo.owner"),name:Un(d.name,"project.contextRepo.name")??st(s)},g={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:f}},y=Un(i.youtrackProjectKey,"project.youtrackProjectKey");if(y&&(g.project.youtrackProjectKey=y),i.index!==void 0&&(typeof i.index!="boolean"&&se("config: 'project.index' must be a boolean"),g.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&se("config: 'project.youtrackWrites' must be a boolean"),g.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let w=pe(i.llmProvider,"project.llmProvider");w==="codex"&&se(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),w!=="claude"&&se("config: 'project.llmProvider' must be 'claude'"),g.project.llmProvider=w}let $=e.secrets;if($!==void 0){(typeof $!="object"||$===null)&&se("config: 'secrets' must be an object");let w=$,v={};if(w.github){let I=w.github;v.github={token:pe(I.token,"secrets.github.token")}}if(w.bitbucket){let I=w.bitbucket;v.bitbucket={email:pe(I.email,"secrets.bitbucket.email"),apiToken:pe(I.apiToken,"secrets.bitbucket.apiToken")}}if(w.gitlab){let I=w.gitlab;v.gitlab={token:pe(I.token,"secrets.gitlab.token")}}if(w.youtrack){let I=w.youtrack;v.youtrack={url:pe(I.url,"secrets.youtrack.url").replace(/\/$/,""),token:pe(I.token,"secrets.youtrack.token")}}if(w.contextWrite){let I=w.contextWrite;v.contextWrite={token:pe(I.token,"secrets.contextWrite.token")}}g.secrets=v}return g}async function Iv(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Cv(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await yt(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${n}`)}if(e.bitbucket){let r=t.project.repos.find(i=>i.host==="bitbucket"),n=r?.owner??(t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:void 0),o=await wt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await co(e.bitbucket.email,e.bitbucket.apiToken,r.owner,r.repoName);if(i)throw new Error(`Bitbucket: ${i}`)}console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await kt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await vt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Rm(t){let e=!t.configPath||t.configPath==="-"?await Iv():Tv(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){se(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=Rv(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 Cv(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 Br(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??dr(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){se(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let u;try{u=await St(o,i,a)}catch(d){if(d instanceof L&&d.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await J(o,i,s.id);else if(d instanceof L)se(`HUB \u2192 ${d.status} ${d.message}`);else throw d}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let p={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(z(p),ct({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Qe(s.id)}`),Qt(s.id,et(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,"auto",s.llmProvider??Je),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await cn(o,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${d}); runs once a SANDBOX claims it.`)}catch(d){console.warn(`could not enqueue index job: ${d instanceof Error?d.message:String(d)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}xe();re();import{cancel as Im,intro as Cm,isCancel as Em,log as ua,outro as Ev,password as Pm}from"@clack/prompts";async function Pv(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Am(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Pv(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Cm("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),ua.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Pm({message:"Claude OAuth token"});Em(i)&&(Im("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Gc({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${ro()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Pe(t.profile);if(!e){Cm(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),ua.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Pm({message:"Claude OAuth token"});Em(i)&&(Im("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=B(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}.`):(ua.success("Claude OAuth token saved."),Ev("It will be sealed into job bundles when a SANDBOX (re)connects."))}W();xe();lt();Qo();Zt();Zo();me();re();import{cancel as Av,confirm as jv,intro as _v,isCancel as jm,log as we,outro as Nv,select as _m,text as Lt}from"@clack/prompts";function Nm(t){Av(t),process.exit(1)}function Yr(t){return jm(t)&&Nm("aborted"),t}function Bn(t){return jm(t)&&Nm("aborted"),typeof t=="string"?t:""}async function Ov(t,e){let r=Yr(await _m({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=Bn(await Lt({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=Bn(await Lt({message:"Context Repo name",placeholder:st(t),initialValue:st(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function Om(t={profile:void 0}){let e=Pe(t.profile);_v(`codepipe project add \u2192 ${e.hubUrl}`);let r=Yr(await Lt({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>Mt.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=Yr(await Lt({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=Yr(await _m({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=Yr(await Lt({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Yr(await jv({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=Bn(await Lt({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()||Ne($)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!d)break;let m=Ne(d);we.message(`${m.host}: ${m.owner}/${m.repoName}`);let f=Bn(await Lt({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:$=>$.trim().length>0?void 0:"required"})).trim(),g=Bn(await Lt({message:"default branch (optional)",placeholder:"main"})).trim(),y={name:f,host:m.host,owner:m.owner,repoName:m.repoName};g&&(y.defaultBranch=g),a.push(y)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await Ov(r,a),u=B(e.projectId);we.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await Br(c,l,{githubToken:u?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:u?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:u?.bitbucket??dr(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:d=>we.message(d),warn:d=>we.warn(d)}})}catch(d){we.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,we.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await St(e.hubUrl,e.cliToken,c);we.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),Qt(r,et(c,s,u?.youtrack?.url),{info:m=>we.message(m),warn:m=>we.warn(m)}),d.contextRepo&&(we.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),we.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&we.error(` error: ${d.provisioningError}`),Nv("done")}catch(d){d instanceof L?(we.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&we.message(JSON.stringify(d.payload,null,2))):we.error(d instanceof Error?d.message:String(d)),process.exit(1)}}Dr();xe();me();re();at();Nn();import{existsSync as Lv,rmSync as Dv}from"node:fs";import{confirm as Uv,intro as Bv,isCancel as Mv,log as Dt,outro as Gv,spinner as Fv}from"@clack/prompts";function rt(t){Dt.error(t),process.exit(1)}var Lm=t=>t.trim().replace(/\/+$/,"");async function Dm(t){Bv("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Ee()?.spec.projectId??void 0;e||rt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=Be(e);r||rt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Lm(r.hubUrl),o=r.projectId,i=Lm(t.hub);i.startsWith("http")||rt("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&rt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let $=Fv();$.start(`reading project ${o} from ${n}\u2026`);try{l=await J(n,r.cliToken,o),$.stop(`read project ${o} (${l.name})`)}catch(w){throw $.stop("could not read the source project",1),w instanceof L&&rt(`source HUB ${n} \u2192 ${w.status} ${w.message}. The source HUB must be reachable with a valid token to move a project.`),w}}l.contextRepo||rt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=B(o),p=(t.account??r.accountEmail??await Hr()).trim().toLowerCase();if(Dt.message(`move project '${o}'
|
|
811
|
+
required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):_.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
|
|
812
|
+
(${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=te(await Fn({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await Gn("contextWrite",()=>Ex(r,t)))return{token:r};_.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function Ex(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 Jm(){for(;;){let t=te(await le({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=te(await Fn({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Gn("YouTrack",()=>Tt({baseUrl:t,token:e}))){let r=await Dl({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}_.warn("re-enter the YouTrack URL / token.")}}var Om,Mn=k(()=>{"use strict";ke();W();Oe();em();ko();Te();ft();rr();wr();ai();Vs();ci();St();qt();dm();ge();gm();wm();Gs();Mo();oe();ui();tt();Om=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});W();ke();Te();import{Command as TS}from"commander";io();import{homedir as Qc}from"node:os";import{join as Zc}from"node:path";function el(){Wt(Zc(Qc(),".devpipe"),Zc(Qc(),".codepipe"))}Te();oe();async function fl(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=Fe(e);r&&!t.force&&(console.error(`already configured at ${fr(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");pt({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...F(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};X(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${fr(e)}`)}Wi();Te();qs();ge();oe();ft();zs();tt();Mo();import{homedir as Js}from"node:os";import{join as An}from"node:path";async function Mp(t={profile:void 0}){let{cfg:e,profile:r}=lo(t.profile),n=F(e.projectId);n&&un(n),Sn(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Rn(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),Tn(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=An(Js(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=fo("CLI_LOG",i,o);if(s.enabled){let d=new hr(s);mo(d),console.log(`[log] file logging \u2192 ${d.path} (rotate at ${s.maxBytes}B, keep ${s.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let a=null,c=ao(e.projectId);if(c&&(a={root:c.root,contextDir:c.contextDir,repos:c.spec.repos},console.log(`[ctx] workspace found at ${c.root} \u2014 using its Context Repo clone`)),!a){let d=An(Js(),".codepipe",r?An("profiles",r,"context"):"context");if(await ls(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await Lp(()=>Zo({cfg:e,secrets:n,contextDir:d,log:{info:m=>console.log(m),warn:m=>console.warn(m)}}),{log:{warn:m=>console.warn(m)}}),a||await ls(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=An(Js(),".codepipe",r?An("profiles",r,"context-config"):"context-config");Ao(a.contextDir,m,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=Xo(e,{...a?{workspace:a}:{},onEvent:d=>{d.kind==="replaced"&&(console.error(`[daemon] project ${e.projectId} is now served by another CLI \u2014 exiting. Run exactly one CLI per project.`),process.exit(0))}}),u=!1;function p(d){u||(u=!0,console.log(`
|
|
813
|
+
[${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}Fr();Te();ge();async function Vf(t={profile:void 0}){let e=je(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=$o(e.hubUrl,e.cliToken),n=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let u=l.toString("utf-8");if(s.push(`msg:${u}`),u!=="pong")try{let p=JSON.parse(u);p.type==="registered"?(a=!!p.ok,clearTimeout(c),r.send("ping")):p.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,u)=>{s.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of n.events)console.log(` ${i}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await 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=ye(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`)")}Mn();import{readFileSync as Px}from"node:fs";W();Te();ft();ai();rr();St();qt();ge();oe();function ce(t){throw new Error(t)}function me(t,e){return(typeof t!="string"||t.trim().length===0)&&ce(`config: '${e}' must be a non-empty string`),t.trim()}function Kn(t,e){if(t==null)return;typeof t!="string"&&ce(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function Ax(t){(!t||typeof t!="object")&&ce("config: expected a JSON object");let e=t,r=me(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||ce("config: 'hubUrl' must start with http(s)://");let n=me(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&ce("config: 'project' is required");let i=o,s=me(i.id,"project.id");Kt.test(s)||ce("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=me(i.name,"project.name"),c=me(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&ce("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||ce("config: 'project.repos' must be an array");let u=l.map((w,x)=>{(!w||typeof w!="object")&&ce(`config: project.repos[${x}] must be an object`);let I=w,H=me(I.host,`project.repos[${x}].host`);H!=="github"&&H!=="bitbucket"&&H!=="gitlab"&&ce(`config: project.repos[${x}].host must be 'github', 'bitbucket' or 'gitlab'`);let j={name:me(I.name,`project.repos[${x}].name`),host:H,owner:me(I.owner,`project.repos[${x}].owner`),repoName:me(I.repoName,`project.repos[${x}].repoName`)},v=Kn(I.defaultBranch,`project.repos[${x}].defaultBranch`);v&&(j.defaultBranch=v);let A=Kn(I.mountAs,`project.repos[${x}].mountAs`);return A&&(j.mountAs=A),j}),p=i.contextRepo;(!p||typeof p!="object")&&ce("config: 'project.contextRepo' is required");let d=p,m=Kn(d.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&ce("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:m,owner:me(d.owner,"project.contextRepo.owner"),name:Kn(d.name,"project.contextRepo.name")??dt(s)},g={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:f}},y=Kn(i.youtrackProjectKey,"project.youtrackProjectKey");if(y&&(g.project.youtrackProjectKey=y),i.index!==void 0&&(typeof i.index!="boolean"&&ce("config: 'project.index' must be a boolean"),g.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&ce("config: 'project.youtrackWrites' must be a boolean"),g.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let w=me(i.llmProvider,"project.llmProvider");w==="codex"&&ce(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),w!=="claude"&&ce("config: 'project.llmProvider' must be 'claude'"),g.project.llmProvider=w}let b=e.secrets;if(b!==void 0){(typeof b!="object"||b===null)&&ce("config: 'secrets' must be an object");let w=b,x={};if(w.github){let I=w.github;x.github={token:me(I.token,"secrets.github.token")}}if(w.bitbucket){let I=w.bitbucket;x.bitbucket={email:me(I.email,"secrets.bitbucket.email"),apiToken:me(I.apiToken,"secrets.bitbucket.apiToken")}}if(w.gitlab){let I=w.gitlab;x.gitlab={token:me(I.token,"secrets.gitlab.token")}}if(w.youtrack){let I=w.youtrack;x.youtrack={url:me(I.url,"secrets.youtrack.url").replace(/\/$/,""),token:me(I.token,"secrets.youtrack.token")}}if(w.contextWrite){let I=w.contextWrite;x.contextWrite={token:me(I.token,"secrets.contextWrite.token")}}g.secrets=x}return g}async function jx(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function _x(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await $t(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${n}`)}if(e.bitbucket){let r=t.project.repos.find(i=>i.host==="bitbucket"),n=r?.owner??(t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:void 0),o=await vt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await wo(e.bitbucket.email,e.bitbucket.apiToken,r.owner,r.repoName);if(i)throw new Error(`Bitbucket: ${i}`)}console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await xt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Tt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Xm(t){let e=!t.configPath||t.configPath==="-"?await jx():Px(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){ce(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=Ax(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 _x(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 Kr(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??gr(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){ce(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let u;try{u=await Ct(o,i,a)}catch(d){if(d instanceof U&&d.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await Q(o,i,s.id);else if(d instanceof U)ce(`HUB \u2192 ${d.status} ${d.message}`);else throw d}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let p={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(X(p),pt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${rt(s.id)}`),tr(s.id,ot(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,"auto",s.llmProvider??Ze),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await fn(o,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${d}); runs once a SANDBOX claims it.`)}catch(d){console.warn(`could not enqueue index job: ${d instanceof Error?d.message:String(d)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}Te();oe();import{cancel as Qm,intro as Zm,isCancel as eg,log as Sa,outro as Nx,password as tg}from"@clack/prompts";async function Ox(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function rg(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Ox(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Zm("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Sa.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await tg({message:"Claude OAuth token"});eg(i)&&(Qm("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),pl({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${po()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=je(t.profile);if(!e){Zm(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Sa.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await tg({message:"Claude OAuth token"});eg(i)&&(Qm("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=F(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},X(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Sa.success("Claude OAuth token saved."),Nx("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{existsSync as Xx}from"node:fs";import{join as Rg}from"node:path";import{cancel as Qx,intro as Zx,log as Tg,outro as Ig}from"@clack/prompts";W();mt();import{existsSync as ng,readFileSync as Dx,readdirSync as Lx}from"node:fs";import{join as og}from"node:path";import{simpleGit as Ux}from"simple-git";import{parse as Mx}from"yaml";function Bx(t){let e=new Map,r=og(t,ji);if(!ng(r))return e;let n;try{n=Mx(Dx(r,"utf-8"))}catch{return e}let o=n?.repos;if(!o||typeof o!="object")return e;for(let[i,s]of Object.entries(o)){if(!s||typeof s!="object")continue;let a=s,c=a.counts??{};typeof a.builtFromCommit=="string"&&e.set(i,{builtFromCommit:a.builtFromCommit,counts:{component:typeof c.component=="number"?c.component:0,code:typeof c.code=="number"?c.code:0}})}return e}function Fx(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return eo({modelFormatVersion:2,repos:e})}function ig(t,e){let r=og(t,e);if(!ng(r))return[];let n=[];for(let o of Lx(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...ig(t,i)):n.push(i)}return n}async function sg(t,e){let r=[],n=0;for(let l of e){r.push(...l.files);let u=`model/derived/structure/${l.repo}`;for(let p of ig(t,u))l.emittedShardPaths.has(p)||(r.push({path:p,content:"",deleted:!0}),n++)}let o=Bx(t);for(let l of e)o.set(l.repo,{builtFromCommit:l.headCommit,counts:l.counts});r.push({path:ji,content:Fx(o)});let i=Ux(t),s=(await i.revparse(["HEAD"]).catch(()=>"")).trim(),a=`model: build ${e.map(l=>`${l.repo}@${l.headCommit.slice(0,10)}`).join(", ")}`;return await We(t,r,a),{committed:(await i.revparse(["HEAD"]).catch(()=>"")).trim()!==s,filesWritten:r.filter(l=>!l.deleted).length,filesDeleted:n}}W();import{existsSync as bg,readFileSync as kg}from"node:fs";import{join as $g}from"node:path";import{simpleGit as Vx}from"simple-git";import{parse as vg}from"yaml";W();import{createHash as Gx}from"node:crypto";var Kx=5;function Hx(t,e,r,n){for(let o=0;;o++){let s=`e_${Gx("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(s))return s}}function ag(t){let{repo:e,headCommit:r,headDate:n,prev:o,renameChains:i,prevBlobByPath:s,headBlobByPath:a}=t,c=[...t.currentKeys].sort(),l=new Set(c),u=o?.entities??[],p=new Set(u.map(v=>v.entityId)),d=new Set,m=[],f=new Map,g=(v,A)=>{d.add(A),f.set(A,v.entityId),m.push(v)},y=[];for(let v of u)l.has(v.currentKey)&&!d.has(v.currentKey)?g({...v,status:"active",lastSeen:r},v.currentKey):y.push(v);let b=[],w=[];for(let v of y){let A=Pe(v.currentKey),L=A?i.get(A.path):void 0;if(A&&L){let G=Me(A.level,e,L.finalPath);if(l.has(G)&&!d.has(G)){b.push({entity:v,newKey:G,untilCommit:L.commit}),d.add(G);continue}}w.push(v)}let x=[];if(s){let v=new Map;for(let L of c){if(d.has(L))continue;let G=Pe(L);if(G?.level!=="code")continue;let E=a.get(G.path);E&&v.set(E,v.has(E)?null:L)}let A=new Map;for(let L of w){let G=Pe(L.currentKey);if(G?.level!=="code")continue;let E=s.get(G.path);E&&A.set(E,A.has(E)?null:L)}for(let L of w){let G=Pe(L.currentKey),E=G?.level==="code"?s.get(G.path):void 0,h=E?v.get(E):void 0;E&&h&&A.get(E)===L&&!d.has(h)?(b.push({entity:L,newKey:h,untilCommit:r}),d.add(h)):x.push(L)}}else x.push(...w);let I=new Map;for(let v of b){let A=Pe(v.entity.currentKey),L=Pe(v.newKey);if(A?.level!=="code"||!L)continue;let G=A.path,E=L.path;for(let h=G.lastIndexOf("/");h>0;h=G.lastIndexOf("/",h-1)){let C=G.slice(0,h),R=G.slice(h+1);if(!E.endsWith(`/${R}`))continue;let S=E.slice(0,E.length-R.length-1);if(S===C)continue;let N=`${C}\0${S}`,P=I.get(N);I.set(N,{count:(P?.count??0)+1,commit:P&&P.commit>v.untilCommit?P.commit:v.untilCommit})}}let H=[...I.entries()].filter(([,v])=>v.count>=Kx).map(([v,A])=>{let[L,G]=v.split("\0");return{from:L,to:G,commit:A.commit}}).sort((v,A)=>A.from.length-v.from.length||(v.from<A.from?-1:1)),j=[];for(let v of x){let A=Pe(v.currentKey),L=!1;if(A?.level==="component")for(let G of H){let E=null;if(A.path===G.from?E=G.to:A.path.startsWith(`${G.from}/`)&&(E=G.to+A.path.slice(G.from.length)),E===null)continue;let h=Me("component",e,E);l.has(h)&&!d.has(h)&&(b.push({entity:v,newKey:h,untilCommit:G.commit}),d.add(h),L=!0);break}L||j.push(v)}for(let v of b.sort((A,L)=>A.newKey<L.newKey?-1:1))g({...v.entity,currentKey:v.newKey,aliases:[...v.entity.aliases??[],{key:v.entity.currentKey,until:v.untilCommit}],status:"active",lastSeen:r},v.newKey);for(let v of j)m.push({...v,status:"orphaned"});for(let v of c){if(d.has(v))continue;let A=Hx(e,v,r,p);p.add(A),g({entityId:A,currentKey:v,firstSeen:n,lastSeen:r,status:"active"},v)}return{table:{modelFormatVersion:2,repo:e,builtFromCommit:r,entities:m},byKey:f}}import{simpleGit as Wx}from"simple-git";async function cg(t,e,r){let n=Wx(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
|
|
814
|
+
`).map(s=>s.trim()).filter(Boolean),i=[];for(let s of o){let c=(await n.raw(["diff","-M","-C","-z","--name-status","--diff-filter=R",`${s}^`,s]).catch(()=>"")).split("\0");for(let l=0;l+2<c.length;){if(!(c[l]??"").startsWith("R")){l+=1;continue}let p=c[l+1]??"",d=c[l+2]??"";p&&d&&i.push({fromPath:p,toPath:d,commit:s}),l+=3}}return i}function lg(t){let e=new Map,r=new Map;for(let n of t){let o=r.get(n.fromPath)??n.fromPath;r.delete(n.fromPath),r.set(n.toPath,o),e.set(o,{finalPath:n.toPath,commit:n.commit})}for(let[n,o]of e)o.finalPath===n&&e.delete(n);return e}W();var Yx=".";function hi(t){return Me("container",t,Yx)}function ug(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}var qx=12;function dg(t,e,r,n){let o=[],i=u=>{let p=Me("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:ug(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,qx)}},s=(u,p)=>{let d=Me("component",t,u),m=n.get(d);return{key:d,level:"component",label:ug(u),...m?{entityId:m}:{},...p?{aggregate:!0}:{}}},a=(u,p,d)=>{let m=r.filesByDir.get(d)??[],f=r.childDirs.get(d)??[],g=[p,...m.map(i)],y=[...m.map(b=>({kind:"contains",from:p.key,to:Me("code",t,b.path)})),...f.map(b=>({kind:"contains",from:p.key,to:Me("component",t,b)}))];c(u,g,y)},c=(u,p,d)=>{let m={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},f=Va(m);if(!f.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${f.errors.join("; ")}`);o.push({path:Wa(t,u),content:Za(m)})},l={key:hi(t),level:"container",label:t,...n.get(hi(t))?{entityId:n.get(hi(t))}:{}};a("",l,"");for(let u of r.components)r.collapsed.has(u)?c(u,[s(u,!0)],[]):a(u,s(u,!1),u);return o.sort((u,p)=>u.path<p.path?-1:u.path>p.path?1:0),{files:o,counts:r.counts}}function pg(t,e){let r=[hi(t)];for(let n of e.components)r.push(Me("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(Me("code",t,o.path));return r.sort()}import{simpleGit as mg}from"simple-git";var gg=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"];function hg(t){let e=new Set,r=[],n=new Set;for(let o of t){let i=o.trim();if(i)if(i.endsWith("/"))e.add(i.slice(0,-1));else if(i.includes("*")){let s=i.replace(/[.*+?^${}()|[\]\\]/g,a=>a==="*"?"\0":`\\${a}`).replace(/\0/g,".*");r.push(new RegExp(`^${s}$`))}else n.add(i)}return o=>{let i=o.split("/"),s=i[i.length-1]??o;if(n.has(o))return!0;for(let a of i)if(e.has(a)||n.has(a))return!0;return r.some(a=>a.test(s))}}async function yg(t,e="HEAD"){let r=mg(t),n=(await r.revparse([e])).trim(),o=(await r.raw(["show","-s","--format=%cs",n])).trim();return{commit:n,commitDate:o,files:await Ra(t,n)}}async function Ra(t,e){let n=await mg(t).raw(["ls-tree","-r","-z",e]),o=[];for(let i of n.split("\0")){if(!i)continue;let s=i.indexOf(" ");if(s<0)continue;let[,a,c]=i.slice(0,s).split(/\s+/);a!=="blob"||!c||o.push({path:i.slice(s+1),blobHash:c})}return o.sort((i,s)=>i.path<s.path?-1:i.path>s.path?1:0),o}function fg(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function wg(t,e){let r=[...t].sort((f,g)=>f.path<g.path?-1:f.path>g.path?1:0),n=new Map,o=new Map;for(let f of r){let g=fg(f.path);n.has(g)||n.set(g,[]),n.get(g).push(f);let y=g;for(;y!=="";){let b=fg(y);o.has(b)||o.set(b,new Set),o.get(b).add(y),y=b}}let i=f=>[...o.get(f)??[]].sort(),s=Math.max(e,1)-1,a=new Set,c=new Set,l=[""];for(;l.length>0;){let f=l.shift(),g=(n.get(f)??[]).length+i(f).length;if(g<=s)s-=g,c.add(f),l.push(...i(f));else{if(f==="")return{components:[],collapsed:new Set,filesByDir:new Map,childDirs:new Map,counts:{component:0,code:0}};a.add(f)}}let u=[],p=new Map,d=new Map,m=0;for(let f of[...c].sort()){let g=n.get(f)??[];p.set(f,g),d.set(f,i(f)),m+=g.length,f!==""&&u.push(f)}for(let f of a)u.push(f);return u.sort(),{components:u,collapsed:a,filesByDir:p,childDirs:d,counts:{component:u.length,code:m}}}var zx=1500;function xg(t){let e={ignore:gg,containerNodeCap:zx},r=$g(t,"regimen.yaml");if(!bg(r))return e;let n;try{n=vg(kg(r,"utf-8"))}catch{return e}let o=n?.context,i=o&&typeof o=="object"?o.model:void 0;if(!i||typeof i!="object")return e;let s=i,a=Array.isArray(s.ignore)?s.ignore.filter(u=>typeof u=="string"&&u.trim().length>0):e.ignore,c=s.container_node_cap,l=typeof c=="number"&&Number.isInteger(c)&&c>0?c:e.containerNodeCap;return{ignore:a,containerNodeCap:l}}function Jx(t,e){let r=$g(t,Zn(e));if(!bg(r))return null;let n=vg(kg(r,"utf-8")),o=za(n);if(!o.ok)throw new Error(`model: ${Zn(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function Sg(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await yg(r),s=hg(o.ignore),a=i.files.filter(y=>!s(y.path)),c=wg(a,o.containerNodeCap),l=Jx(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await Vx(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=lg(await cg(r,l.builtFromCommit,i.commit)),p=new Map((await Ra(r,l.builtFromCommit)).map(w=>[w.path,w.blobHash]))):l?.builtFromCommit===i.commit&&(p=new Map(a.map(y=>[y.path,y.blobHash])));let d=new Map(a.map(y=>[y.path,y.blobHash])),m=ag({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:pg(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),f=dg(e,i.commit,c,m.byKey),g=[{path:Zn(e),content:ec(m.table)},...f.files.map(y=>({path:y.path,content:y.content}))];return{repo:e,headCommit:i.commit,files:g,emittedShardPaths:new Set(f.files.map(y=>y.path)),counts:f.counts}}tt();function yi(t){Qx(t),process.exit(1)}async function Cg(t){Zx("codepipe model build");let e=$e();e||yi("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");let r=e.spec.repos.filter(s=>!t.repo||s.name===t.repo);r.length===0&&yi(t.repo?`repo "${t.repo}" is not part of this project (see project.yaml)`:"the project has no repos configured");let n=xg(e.contextDir),o=[];for(let s of r){let a=s.mountAs==="."?e.root:Rg(e.root,s.mountAs);if(!Xx(Rg(a,".git"))){Tg.warn(`${s.name}: no local clone at ${a} \u2014 skipped (run \`codepipe clone\` first)`);continue}try{let c=await Sg({repo:s.name,repoDir:a,contextDir:e.contextDir,settings:n});o.push(c),Tg.info(`${s.name}: ${c.counts.code} files, ${c.counts.component} components @ ${c.headCommit.slice(0,10)}`)}catch(c){yi(`${s.name}: ${c instanceof Error?c.message:String(c)}`)}}o.length===0&&yi("nothing to build \u2014 no repo clones found");let i=await sg(e.contextDir,o);i.committed?Ig(`model updated: ${i.filesWritten} files written, ${i.filesDeleted} stale removed`):Ig("model already up to date (no changes)")}W();Te();ft();ai();rr();ci();ge();oe();import{cancel as eS,confirm as tS,intro as rS,isCancel as Eg,log as be,outro as nS,select as Pg,text as Mt}from"@clack/prompts";function Ag(t){eS(t),process.exit(1)}function Jr(t){return Eg(t)&&Ag("aborted"),t}function Wn(t){return Eg(t)&&Ag("aborted"),typeof t=="string"?t:""}async function oS(t,e){let r=Jr(await Pg({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=Wn(await Mt({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=Wn(await Mt({message:"Context Repo name",placeholder:dt(t),initialValue:dt(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function jg(t={profile:void 0}){let e=je(t.profile);rS(`codepipe project add \u2192 ${e.hubUrl}`);let r=Jr(await Mt({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>Kt.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=Jr(await Mt({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=Jr(await Pg({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=Jr(await Mt({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Jr(await tS({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=Wn(await Mt({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:b=>!b||!b.trim()||De(b)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!d)break;let m=De(d);be.message(`${m.host}: ${m.owner}/${m.repoName}`);let f=Wn(await Mt({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:b=>b.trim().length>0?void 0:"required"})).trim(),g=Wn(await Mt({message:"default branch (optional)",placeholder:"main"})).trim(),y={name:f,host:m.host,owner:m.owner,repoName:m.repoName};g&&(y.defaultBranch=g),a.push(y)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await oS(r,a),u=F(e.projectId);be.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await Kr(c,l,{githubToken:u?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:u?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:u?.bitbucket??gr(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:d=>be.message(d),warn:d=>be.warn(d)}})}catch(d){be.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,be.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await Ct(e.hubUrl,e.cliToken,c);be.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),tr(r,ot(c,s,u?.youtrack?.url),{info:m=>be.message(m),warn:m=>be.warn(m)}),d.contextRepo&&(be.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),be.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&be.error(` error: ${d.provisioningError}`),nS("done")}catch(d){d instanceof U?(be.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&be.message(JSON.stringify(d.payload,null,2))):be.error(d instanceof Error?d.message:String(d)),process.exit(1)}}Fr();Te();ge();oe();tt();Mn();import{existsSync as iS,rmSync as sS}from"node:fs";import{confirm as aS,intro as cS,isCancel as lS,log as Bt,outro as uS,spinner as dS}from"@clack/prompts";function st(t){Bt.error(t),process.exit(1)}var _g=t=>t.trim().replace(/\/+$/,"");async function Ng(t){cS("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??$e()?.spec.projectId??void 0;e||st("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=Fe(e);r||st(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=_g(r.hubUrl),o=r.projectId,i=_g(t.hub);i.startsWith("http")||st("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&st(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let b=dS();b.start(`reading project ${o} from ${n}\u2026`);try{l=await Q(n,r.cliToken,o),b.stop(`read project ${o} (${l.name})`)}catch(w){throw b.stop("could not read the source project",1),w instanceof U&&st(`source HUB ${n} \u2192 ${w.status} ${w.message}. The source HUB must be reachable with a valid token to move a project.`),w}}l.contextRepo||st(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=F(o),p=(t.account??r.accountEmail??await Vr()).trim().toLowerCase();if(Bt.message(`move project '${o}'
|
|
812
815
|
from : ${n} (profile ${e})
|
|
813
816
|
to : ${i} (profile ${s}, project ${a}, account ${p})
|
|
814
817
|
\u2022 the source registration on the old HUB is left intact (non-destructive)
|
|
815
818
|
\u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
|
|
816
|
-
`+(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
|
|
817
|
-
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let g;try{g=await Jl(e.hubUrl,e.cliToken,e.projectId,f)}catch(w){w instanceof L&&Se(`HUB \u2192 ${w.status} ${w.message}`),Se(w instanceof Error?w.message:String(w))}let{updated:y,errors:$}=wn(e.projectId,g.repos,r?.contextDir);for(let w of y)ce.message(`updated ${w}`);for(let w of $)ce.warn(`could not update ${w.path}: ${w.error}`);ce.success(`added "${u}" \u2014 project now has ${g.repos.length} repo(s)`),Mm("done")}async function Km(t){let e=Pe(t.profile);Bm(`codepipe repo remove \u2192 project ${e.projectId}`);let r=Ee()??void 0,n;try{let c=(await J(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 Xl(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof L&&(a.status===404&&Se(`no repo named "${t.name}" in this project`),Se(`HUB \u2192 ${a.status} ${a.message}`)),Se(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=wn(e.projectId,o.repos,r?.contextDir);for(let a of i)ce.message(`updated ${a}`);for(let a of s)ce.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")ce.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?ai(r.root,n):be(e.projectId,t.name);if(da(ai(a,".git")))try{Kv(a,{recursive:!0,force:!0}),ce.message(`deleted local clone ${a}`)}catch(c){ce.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else ce.message(`no local clone found to purge (${a})`)}ce.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),Mm("done")}async function Hm(t){let e=Pe(t.profile),r;try{r=(await J(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}`)}}ti();Zs();ia();Dr();W();ke();Dr();xe();me();Nn();import{hostname as Xv}from"node:os";import{cancel as Qv,confirm as Wm,intro as Zv,isCancel as Vm,log as qr,multiselect as ex,outro as Ym,password as tx,select as pa,text as fa}from"@clack/prompts";function Mn(t){Qv(t),process.exit(1)}function Vr(t){return Vm(t)&&Mn("aborted"),t}function ci(t){return Vm(t)&&Mn("aborted"),typeof t=="string"?t:""}function li(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function qm(t,e){try{let{secret:r}=await mo(t,e);return r}catch(r){throw r instanceof L&&r.status===404&&Mn("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 rx(t,e){if(Vr(await pa({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 qi(t,e);if(o.length>0)return Vr(await ex({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}));qr.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){qr.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return ci(await fa({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 ma(t){Zv("codepipe worker \u2014 set up this machine as a runner");let e=he(t.profile);e&&(qr.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Vr(await Wm({message:"re-register this worker?",initialValue:!1}))||Mn("keeping the existing registration"));let r=Be(t.profile)??Be(),n=ci(await fa({message:"HUB URL",placeholder:qe,initialValue:M("HUB_URL")??r?.hubUrl??qe,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=Vr(await pa({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 qm(n,a),qr.success("account-issued registration token minted");else if(i==="login"){let d=await Hr();a=(await Wr(n,d)).cliToken,s=await qm(n,a),qr.success("account-issued registration token minted")}else s=ci(await tx({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||Mn("a registration token is required");let c=await rx(n,a),l=ci(await fa({message:"worker name",initialValue:Xv(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=Vr(await pa({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 er({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),qr.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Vr(await Wm({message:"start the claim-loop now?",initialValue:!0}))){Ym("registered. start later with `codepipe worker`.");return}Ym("starting the claim-loop\u2026"),await An(t.profile?{profile:t.profile}:{})}function ox(){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 M("PROFILE")}var oe=ox();Rc(oe);Ec();var Te=new nx;Te.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Ie).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{li()?await oa({profile:oe}):await Qs({profile:oe})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Te.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 Rm({configPath:t.config,skipVerify:t.skipVerify===!0}):await hm({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Te.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 Fc({...t,profile:oe})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Te.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 ym({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Te.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await mp({profile:oe})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Te.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 Qf({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Te.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 Am({profile:oe,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Te.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await xf({profile:oe})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Te.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 Qs({profile:oe,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var zm=Te.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");zm.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??M("HUB_URL")??Be(oe)?.hubUrl??qe,r=t.token??M("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&li()){await ma({profile:oe});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let n=M("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??M("WORKER_NAME"),i=t.llm??M("WORKER_LLM");await er({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...oe?{profile:oe}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});zm.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!he(oe)&&li()){await ma({profile:oe});return}await An(oe?{profile:oe}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Jm=Te.command("project").description("Manage CodePipe projects");Jm.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Om({profile:oe})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Jm.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 Dm({...t,cliProfile:oe})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var ga=Te.command("repo").description("Manage the project's git repositories");ga.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 Fm({profile:oe,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ga.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 Km({profile:oe,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});ga.command("list").description("List the project's repos").action(async()=>{try{await Hm({profile:oe})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Te.parseAsync();
|
|
819
|
+
`+(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 b=await aS({message:"Continue?",initialValue:!0});(lS(b)||!b)&&st("aborted")}!c&&a===o&&Bt.warn(`source and destination share the same project id, so they share one secrets file (${rt(a)}). Running both profiles at the same time will conflict \u2014 pass --project <newId> for a parallel setup, or keep only one active.`);let{cliToken:d,accountEmail:m}=await zr(i,p),f={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:m,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};Bt.step(`registering project on ${i}\u2026`);let g;try{g=await Ct(i,d,f)}catch(b){if(b instanceof U&&b.status===409){Bt.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{g=await Q(i,d,a)}catch(w){throw w instanceof U&&st(`target HUB \u2192 ${w.status} ${w.message}`),w}}else if(b instanceof U&&b.status===403)st(`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(b instanceof U)st(`target HUB \u2192 ${b.status} ${b.message}`);else throw b}Bt.success(`project ${g.projectId} ready on ${i} (${g.provisioningStatus})`),pt({hubUrl:i,cliToken:d,projectId:a,accountEmail:m},s);let y={...u??{},hubUrl:i,cliToken:d,projectId:a};if(delete y.sandboxPins,X(y),Bt.success(`profile '${s}' \u2192 ${rt(a)}`),c){let b=Ye(s);iS(b)&&(sS(b),Bt.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}uS(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}Te();Ps();ci();ge();br();oe();tt();import{existsSync as Ta,rmSync as pS,statSync as fS}from"node:fs";import{join as wi,relative as mS,resolve as gS}from"node:path";import{cancel as hS,intro as Dg,isCancel as yS,log as ue,outro as Lg,text as sr}from"@clack/prompts";import{simpleGit as Ug}from"simple-git";function Ie(t){hS(t),process.exit(1)}function ar(t){return yS(t)&&Ie("aborted"),typeof t=="string"?t:""}async function Og(t){try{let e=await Ug(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function wS(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function bS(t,e){let r=F(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(wS(r,e)){ue.message(`reusing existing ${e} credentials`);return}if(ue.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=ar(await sr({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=ar(await sr({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=ar(await sr({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}}X(r),ue.success(`saved ${e} credentials`)}async function Mg(t){let e=je(t.profile);Dg(`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(w){Ie(`could not read project from HUB: ${w instanceof Error?w.message:String(w)}`)}let o=t.target?.trim();if(!o){let w=await Og(process.cwd());w?(o=process.cwd(),ue.message(`using the current directory (${w})`)):o=ar(await sr({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:x=>x.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(Ta(o)&&fS(o).isDirectory()){i=gS(o);let w=await Og(i);w||Ie(`${i} is not a git repository (no origin remote)`);let x=De(w);x||Ie(`origin ${w} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=x,s=w,ue.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let w=De(o);w||Ie(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=w,s=o,ue.message(`${a}: ${c}/${l}`)}let u=ar(await sr({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:w=>w.trim()?void 0:"required"})).trim();n.some(w=>w.name===u)&&Ie(`a repo named "${u}" is already registered`);let p=ar(await sr({message:"default branch (optional)",placeholder:"main"})).trim(),d=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let w=mS(r.root,i);d=w===""?".":w}let m=ar(await sr({message:"mount_as (directory relative to the workspace root)",placeholder:d,initialValue:d})).trim()||d;n.some(w=>(w.mountAs??w.name)===m)&&Ie(`mount_as "${m}" is already used by another repo`),await bS(e,a);let f={name:u,host:a,owner:c,repoName:l,mountAs:m,...p?{defaultBranch:p}:{}};if(!i){let w=r?wi(r.root,m):ve(e.projectId,u);if(Ta(wi(w,".git")))ue.message(`already cloned at ${w}`);else{ue.info(`cloning ${s} \u2192 ${w} \u2026`);try{await Ug().clone(s,w),ue.success(`cloned into ${w}`)}catch(x){Ie(`clone failed: ${x instanceof Error?x.message.trim():String(x)}
|
|
820
|
+
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let g;try{g=await $u(e.hubUrl,e.cliToken,e.projectId,f)}catch(w){w instanceof U&&Ie(`HUB \u2192 ${w.status} ${w.message}`),Ie(w instanceof Error?w.message:String(w))}let{updated:y,errors:b}=xn(e.projectId,g.repos,r?.contextDir);for(let w of y)ue.message(`updated ${w}`);for(let w of b)ue.warn(`could not update ${w.path}: ${w.error}`);ue.success(`added "${u}" \u2014 project now has ${g.repos.length} repo(s)`),Lg("done")}async function Bg(t){let e=je(t.profile);Dg(`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 vu(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof U&&(a.status===404&&Ie(`no repo named "${t.name}" in this project`),Ie(`HUB \u2192 ${a.status} ${a.message}`)),Ie(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=xn(e.projectId,o.repos,r?.contextDir);for(let a of i)ue.message(`updated ${a}`);for(let a of s)ue.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")ue.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?wi(r.root,n):ve(e.projectId,t.name);if(Ta(wi(a,".git")))try{pS(a,{recursive:!0,force:!0}),ue.message(`deleted local clone ${a}`)}catch(c){ue.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else ue.message(`no local clone found to purge (${a})`)}ue.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),Lg("done")}async function Fg(t){let e=je(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}`)}}ui();fa();ba();Fr();W();ke();Fr();Te();ge();Mn();import{hostname as kS}from"node:os";import{cancel as $S,confirm as Gg,intro as vS,isCancel as Wg,log as Xr,multiselect as xS,outro as Kg,password as SS,select as Ia,text as Ca}from"@clack/prompts";function Yn(t){$S(t),process.exit(1)}function Qr(t){return Wg(t)&&Yn("aborted"),t}function bi(t){return Wg(t)&&Yn("aborted"),typeof t=="string"?t:""}function ki(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Hg(t,e){try{let{secret:r}=await xo(t,e);return r}catch(r){throw r instanceof U&&r.status===404&&Yn("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 RS(t,e){if(Qr(await Ia({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 as(t,e);if(o.length>0)return Qr(await xS({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}));Xr.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Xr.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return bi(await Ca({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 Ea(t){vS("codepipe worker \u2014 set up this machine as a runner");let e=ye(t.profile);e&&(Xr.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Qr(await Gg({message:"re-register this worker?",initialValue:!1}))||Yn("keeping the existing registration"));let r=Fe(t.profile)??Fe(),n=bi(await Ca({message:"HUB URL",placeholder:Je,initialValue:K("HUB_URL")??r?.hubUrl??Je,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=Qr(await Ia({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 Hg(n,a),Xr.success("account-issued registration token minted");else if(i==="login"){let d=await Vr();a=(await zr(n,d)).cliToken,s=await Hg(n,a),Xr.success("account-issued registration token minted")}else s=bi(await SS({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||Yn("a registration token is required");let c=await RS(n,a),l=bi(await Ca({message:"worker name",initialValue:kS(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=Qr(await Ia({message:"agent backend",options:[{value:"claude-headless",label:"claude-headless \u2014 Claude Code on PATH (the real thing)"},{value:"mock",label:"mock \u2014 deterministic stub (development)"},{value:"",label:"none \u2014 this worker will not claim agent jobs"}],initialValue:"claude-headless"}));if(await nr({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Xr.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Qr(await Gg({message:"start the claim-loop now?",initialValue:!0}))){Kg("registered. start later with `codepipe worker`.");return}Kg("starting the claim-loop\u2026"),await Dn(t.profile?{profile:t.profile}:{})}function IS(){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 K("PROFILE")}var se=IS();Xc(se);el();var Re=new TS;Re.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Ee).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{ki()?await wa({profile:se}):await pa({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Re.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 Xm({configPath:t.config,skipVerify:t.skipVerify===!0}):await Fm({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Re.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 fl({...t,profile:se})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Re.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 Gm({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Re.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await Mp({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Re.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 xm({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Re.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 rg({profile:se,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Re.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Vf({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Re.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 pa({profile:se,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Yg=Re.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Yg.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??K("HUB_URL")??Fe(se)?.hubUrl??Je,r=t.token??K("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&ki()){await Ea({profile:se});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=K("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??K("WORKER_NAME"),i=t.llm??K("WORKER_LLM");await nr({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...se?{profile:se}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Yg.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ye(se)&&ki()){await Ea({profile:se});return}await Dn(se?{profile:se}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var qg=Re.command("project").description("Manage CodePipe projects");qg.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await jg({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});qg.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 Ng({...t,cliProfile:se})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Pa=Re.command("repo").description("Manage the project's git repositories");Pa.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 Mg({profile:se,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Pa.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 Bg({profile:se,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Pa.command("list").description("List the project's repos").action(async()=>{try{await Fg({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var CS=Re.command("model").description("Project map (model/ in the Context Repo)");CS.command("build").description("Build the project map from the local repo clones' git history").option("--repo <name>","Build only this repo (logical name)").action(async t=>{try{await Cg({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Re.parseAsync();
|