@bensandee/tooling 0.107.0 → 0.109.0
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/bin.mjs +213 -208
- package/package.json +6 -6
- package/tooling.schema.json +18 -75
package/dist/bin.mjs
CHANGED
|
@@ -1,31 +1,31 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import e,{accessSync as t,appendFileSync as n,closeSync as r,constants as i,copyFileSync as a,existsSync as o,fstatSync as s,globSync as c,lstatSync as l,mkdirSync as u,mkdtempSync as d,openSync as f,readFileSync as p,readSync as m,readdirSync as h,readlinkSync as g,realpathSync as _,renameSync as v,rmSync as y,statSync as b,symlinkSync as x,unlinkSync as S,writeFileSync as C,writeSync as ee}from"node:fs";import w,*as te from"node:path";import{parseArgs as ne,parseEnv as re}from"node:util";import{FatalError as T,TransientError as E,UnexpectedError as D,describeError as
|
|
3
|
-
`)}catch{}process.exitCode=1}function installJsonExitNet(e,t,n,r){process.on(`exit`,()=>{runJsonExitNet({write:e=>ee(1,e),wroteDocument:r,command:t,version:n,binName:e})})}function classifyThrown(e,t){let n=e instanceof Error&&e.name===`CLIError`?`usage`:`runtime`,r=ae(ie(e));if(!t)return{kind:n,message:r};let i=e instanceof Error&&typeof e.stack==`string`?ae(e.stack):void 0;return i===void 0?{kind:n,message:r}:{kind:n,message:r,detail:i}}const Fe=`BST_ENV_FILE`;function loadEnvFileFromEnv(){let e=process.env[Fe]?.trim();if(e===void 0||e===``)return;let t=te.resolve(e),n;try{n=p(t,`utf8`)}catch(e){let n=e instanceof Error?e.message:String(e);throw new T(`${Fe} names ${t}, which could not be read (${n}). Unset ${Fe} or point it at a readable env file.`)}let r=[],i=[];for(let[e,t]of Object.entries(re(n)))process.env[e]===void 0?(process.env[e]=t,r.push(e)):i.push(e);return{path:t,added:r,kept:i}}function describeEnvFileLoad(e){if(e===void 0)return`No env file loaded -- ${Fe} is unset or empty.`;let t=[`Loaded ${String(e.added.length)} variable(s) from ${e.path} (${Fe}): `+(e.added.length===0?`none`:e.added.join(`, `))];return e.kept.length>0&&t.push(`${String(e.kept.length)} already set in the environment kept their value: `+e.kept.join(`, `)),t.join(`; `)}const Ie={out:e=>{process.stdout.write(`${e}\n`)},err:e=>{process.stderr.write(`${e}\n`)},exit:e=>process.exit(e)};function loadEnvFileForBin(e,t,n=Ie){try{return loadEnvFileFromEnv()}catch(r){let i=r instanceof Error?r.message:String(r);if(resolveJsonMode(e)){let r=buildErrorDocument({command:resolveCommandName(e),version:t.version,kind:`usage`,message:i});n.out(JSON.stringify(r))}else n.err(`${t.name}: ${i}`);return n.exit(1)}}const Le=loadEnvFileForBin(process.argv.slice(2),{name:`bst`,version:`0.107.0`}),Re={error:0,warn:1,info:2,debug:3,trace:4};let ze=`info`;function setLogLevel(e){ze=e}function resolveLogLevel(e){return e.trace===!0||process.env.TOOLING_TRACE===`true`?`trace`:e.verbose===!0||process.env.TOOLING_DEBUG===`true`?`debug`:`info`}const Be=!!process.env.CI,out$1=e=>console.log(e),err=e=>console.error(e),Ve={info:out$1,warn:e=>out$1(`[warn] ${e}`),error:e=>out$1(`[error] ${e}`),success:e=>out$1(`[ok] ${e}`)};let He;function setDefaultUserSink(e){He=e}let Ue=Be,We=!1;function setJsonMode(e){We=e}function isJsonMode(){return We}let Ge;function setJsonNoticeSink(e){Ge=e}function formatContext(e){let t=[];if(e.repo!==void 0){let n=e.repo.split(`/`).findLast(e=>e.length>0);n!==void 0&&t.push(n)}return e.issue!==void 0&&t.push(`#${String(e.issue)}`),e.pr!==void 0&&t.push(`PR#${String(e.pr)}`),e.phase!==void 0&&t.push(e.phase),t.length>0?`[${t.join(` `)}]`:``}function build(e){let t=formatContext(e.context),enabled=t=>Re[t]<=Re[e.level??ze],stamp=()=>`[${e.now().toISOString()}]`,userFacing=(n,r)=>i=>{if(!enabled(r))return;if(We){(n===`warn`||n===`error`)&&Ge&&Ge(k(i));return}let a=[];(e.timestamps??!1)&&a.push(stamp()),t&&a.push(t),a.push(k(i)),(e.userSink??(Ue?Ve:He??Ve))[n](a.join(` `))},diagnostic=n=>r=>{if(!enabled(n))return;let i=[stamp()];t&&i.push(t),i.push(`[${n}]`,k(r)),e.diagnosticSink(i.join(` `))};return{info:userFacing(`info`,`info`),warn:userFacing(`warn`,`warn`),error:userFacing(`error`,`error`),success:userFacing(`success`,`info`),debug:diagnostic(`debug`),trace:diagnostic(`trace`),child:t=>build({...e,context:{...e.context,...t}})}}function createLogger(e={}){return build({level:e.level,timestamps:e.timestamps,context:e.context??{},userSink:e.userSink,diagnosticSink:e.diagnosticSink??err,now:e.now??(()=>/* @__PURE__ */ new Date)})}const Ke=createLogger();setDefaultUserSink(j.log);const qe=!!process.env.CI,out=e=>console.log(e),F=Ke;function note(e,t){isJsonMode()||(qe?(t&&out(`--- ${t} ---`),out(e)):j.note(e,t))}const stdout=e=>console.log(e);function initialState(){return{payload:void 0,hasPayload:!1,error:void 0,hasError:!1,notices:[],wrote:!1}}let I=initialState();function isJsonRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function isStringArray(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function createCliOutput(e){let t=e||isJsonMode();return{json:e=>{t&&(I.hasPayload&&Ke.debug(`output: a second json() call overwrote the first -- last call wins.`),I.payload=e,I.hasPayload=!0)},text:e=>{t||stdout(e)},notice:e=>{t?I.notices.push(k(e)):stdout(e)}}}function recordJsonError(e){I.error=e,I.hasError=!0}function buildFlushDocument(){let e;if(I.hasError?e=I.error:I.hasPayload&&(e=I.payload),e!==void 0){if(I.notices.length===0)return e;if(isJsonRecord(e)){let{notices:t}=e;return{...e,notices:isStringArray(t)?[...t,...I.notices]:I.notices}}return{payload:e,notices:I.notices}}}function flushJsonOutput(){let e=buildFlushDocument();return e!==void 0&&(stdout(JSON.stringify(e)),I.wrote=!0,!0)}function jsonDocumentWritten(){return I.wrote}function defaultGitRunner(e,t,n){try{let r=M(`git`,e,{cwd:t,stdio:[`ignore`,`pipe`,`ignore`],timeout:n?.timeoutMs}).toString(`utf-8`).trim();return r===``?void 0:r}catch{return}}function resolveCurrentBranch(e){let t=e.env??process.env,n=t.GITHUB_REF;if(n!==void 0&&n!==``){if(!n.startsWith(`refs/heads/`))return;let e=t.GITHUB_REF_NAME;return e!==void 0&&e!==``?e:n.slice(11)}let r=(e.git??defaultGitRunner)([`rev-parse`,`--abbrev-ref`,`HEAD`],e.cwd);if(r!==void 0&&r!==`HEAD`)return r}function readOriginUrl(e,t=defaultGitRunner){return t([`remote`,`get-url`,`origin`],e,{timeoutMs:5e3})??null}const Je=N.union([N.string(),N.object({url:N.string()})]);function readPackageRepositoryUrl(e){let t=w.join(e,`package.json`),n;try{n=p(t,`utf-8`)}catch{return null}let r;try{r=JSON.parse(n)}catch(e){throw new T(`${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}let i=N.object({repository:Je.optional()}).safeParse(r);if(!i.success)return null;let a=i.data.repository;return a?typeof a==`string`?a:a.url:null}function parseGitUrl(e){try{let t=new URL(e),n=t.pathname.replace(/\.git$/,``).replace(/^\//,``);return n.includes(`/`)?{protocol:t.protocol,hostname:t.hostname,repository:n}:null}catch{return null}}function forgeTokenFromEnv(e){return e.RELEASE_TOKEN||e.FORGEJO_TOKEN}function resolveRepoUrlFrom(e,t){let n=normalizeGitUrl(e()??``);if(n!==null&&parseGitUrl(n)!==null)return n;let r=t();return r===null||parseGitUrl(r)===null?null:normalizeGitUrl(r)}function resolveForgejoCoordinates(e,t){let n=e.FORGEJO_SERVER_URL,r=e.FORGEJO_REPOSITORY;if(n&&r)return{serverUrl:n,repository:r};let i=t(),a=i===null?null:parseGitUrl(i);return a===null||a.hostname===`github.com`?null:{serverUrl:n??`${a.protocol}//${a.hostname}`,repository:r??a.repository}}function resolveForgejoConnection(e,t){let n=e.FORGEJO_SERVER_URL,r=e.FORGEJO_REPOSITORY,i=forgeTokenFromEnv(e);if(n&&r&&i)return{serverUrl:n,repository:r,token:i};let a=t(),o=a===null?null:parseGitUrl(a);if(o===null){if(n){if(!r)throw new T(`FORGEJO_REPOSITORY environment variable is required`);if(!i)throw new T(`RELEASE_TOKEN environment variable is required`)}return null}if(o.hostname===`github.com`)return null;if(!i)throw new T(`RELEASE_TOKEN environment variable is required (server URL and repository were resolved from package.json)`);return{serverUrl:n??`${o.protocol}//${o.hostname}`,repository:r??o.repository,token:i}}const Ye=/^\/([^/]+\/[^/]+)\/(?:issues|pulls?)\/(\d+)\/?$/;function parseIssueRef(e){if(e===void 0||e.trim()===``)return{};let t=e.trim();if(/^\d+$/.test(t))return{number:Number.parseInt(t,10)};let n;try{n=new URL(t)}catch{n=void 0}if(n!==void 0&&n.protocol!==`http:`&&n.protocol!==`https:`)throw new T(`Not an issue number or issue URL: "${t}" (expected e.g. 273 or https://host/owner/repo/issues/273)`);if(n!==void 0){let e=Ye.exec(n.pathname);if(e){let[,t,r]=e;if(t!==void 0&&r!==void 0)return{number:Number.parseInt(r,10),target:{serverUrl:n.origin,repository:t,hostname:n.hostname}}}}throw new T(`Not an issue number or issue URL: "${t}" (expected e.g. 273 or https://host/owner/repo/issues/273)`)}var RepoTargetEmptyError=class extends T{constructor(){super(`No repository URL was given.`)}},RepoTargetMismatchError=class extends T{given;fromReference;constructor(e,t){super(`The repository (${e}) and the issue URL (${t}) disagree.`),this.given=e,this.fromReference=t}};function parseRepoTarget(e){if(e===void 0)return;if(e.trim()===``)throw new RepoTargetEmptyError;let t=/^(https?:\/\/[^/]+)\/([^/]+\/[^/]+?)(?:\.git)?\/?$/.exec(e.trim());if(!t)throw new T(`Not a repository URL: "${e}"`);let[,n,r]=t;if(n===void 0||r===void 0)throw new T(`Not a repository URL: "${e}"`);return{serverUrl:n,repository:r,hostname:new URL(n).hostname}}function resolveIssueTarget(e,t){let n=parseRepoTarget(t);if(e===void 0)return n;if(n===void 0||e.serverUrl===n.serverUrl&&e.repository===n.repository)return e;throw new RepoTargetMismatchError(`${n.serverUrl}/${n.repository}`,`${e.serverUrl}/${e.repository}`)}function normalizeGitUrl(e){let t=e.startsWith(`git+`)?e.slice(4):e,n=t.match(/^git@([^:]+):(.+?)(?:\.git)?$/);if(n)return`https://${n[1]}/${n[2]}`;try{let e=new URL(t);return e.pathname=e.pathname.replace(/\.git$/,``),e.username=``,e.password=``,e.toString().replace(/\/$/,``)}catch{return null}}const Xe=[`eslint`,`prettier`,`jest`,`webpack`,`rollup`],Ze=N.record(N.string(),N.string()),Qe=N.looseObject({name:N.string(),version:N.string().optional(),onFail:N.string().optional()}),$e=N.looseObject({name:N.string().optional(),version:N.string().optional(),private:N.boolean().optional(),type:N.string().optional(),scripts:Ze.optional(),dependencies:Ze.optional(),devDependencies:Ze.optional(),peerDependencies:Ze.optional(),bin:N.union([N.string(),Ze]).optional(),exports:N.unknown().optional(),main:N.string().optional(),types:N.string().optional(),typings:N.string().optional(),engines:Ze.optional(),devEngines:N.looseObject({runtime:N.union([Qe,N.array(Qe)]).optional()}).optional(),repository:N.union([N.string(),N.looseObject({url:N.string()})]).optional(),packageManager:N.string().optional(),publishConfig:N.unknown().optional()}),et=N.looseObject({extends:N.union([N.string(),N.array(N.string())]).optional(),include:N.array(N.string()).optional(),exclude:N.array(N.string()).optional(),files:N.array(N.string()).optional(),references:N.array(N.looseObject({path:N.string()})).optional(),compilerOptions:N.record(N.string(),N.unknown()).optional()}),tt=N.looseObject({$schema:N.string().optional(),extends:N.array(N.string()).optional()});function parseTsconfig(e){let t=et.safeParse(_e(e));return t.success?t.data:{}}function parseRenovateJson(e){try{let t=tt.safeParse(me.parse(e));return t.success?t.data:{}}catch{return{}}}const nt=N.looseObject({commit:N.union([N.boolean(),N.string()]).optional()});function parseChangesetConfig(e){try{let t=nt.safeParse(JSON.parse(e));return t.success?t.data:void 0}catch{return}}function parsePackageJson(e){try{let t=$e.safeParse(JSON.parse(e));return t.success?t.data:void 0}catch{return}}function describePackageJsonFailure(e){let t;try{t=JSON.parse(e)}catch(e){return`not valid JSON: ${e instanceof Error?e.message:String(e)}`}let n=$e.safeParse(t);if(n.success)return;let r=n.error.issues[0];return`${r&&r.path.length>0?r.path.join(`.`):`a managed field`} has the wrong type${r?` (${r.message})`:``}`}const L=[`crowdedDirectories`,`circularDependencies`,`fanInOutliers`,`fanOutOutliers`],rt=[`fanInOutliers`,`fanOutOutliers`,`crowdedDirectories`],R=[`fanInOutliers`,`fanOutOutliers`,`crowdedDirectories`],it=[`linesOfCode`],at=N.object({linesOfCode:N.number().int().nonnegative().optional()}),ot=N.object({crowdedDirectories:N.number().int().nonnegative(),circularDependencies:N.number().int().nonnegative().optional(),fanInOutliers:N.number().int().nonnegative().optional(),fanOutOutliers:N.number().int().nonnegative().optional()}),st=ot.extend(at.shape).extend({sha:N.string(),timestamp:N.string()}),ct=new Set(R),lt=N.preprocess(e=>typeof e==`object`&&e?Object.fromEntries(Object.entries(e).filter(([e])=>ct.has(e))):e,N.partialRecord(N.enum(R),N.record(N.string(),N.number().int().nonnegative()))),ut=ot.extend({moduleCeilings:lt.optional(),sizeBudgets:N.record(N.string(),N.number().int().nonnegative()).optional()});function parseHealthBaseline(e){let t;try{t=JSON.parse(e)}catch(e){throw new T(`health-baseline.json is not valid JSON: ${O(e)}`)}let n=ut.safeParse(t);if(!n.success)throw new T(`health-baseline.json has unexpected shape: ${n.error.message}`);return n.data}function parseHealthHistoryLine(e){let t;try{t=JSON.parse(e)}catch{return}let n=st.safeParse(t);return n.success?n.data:void 0}function parseToolingConfigSlice(e,t,n){if(e===void 0||e.trim()===``)return;let r=n.path??`.tooling.json`,i;try{i=JSON.parse(e)}catch(e){throw new T(`Could not parse ${r} as JSON: ${O(e)}`)}let a=t.safeParse(i,{reportInput:!0});if(!a.success){let e=a.error.issues.flatMap(e=>formatIssue$1(e).split(`
|
|
2
|
+
import e,{accessSync as t,appendFileSync as n,closeSync as r,constants as i,copyFileSync as a,existsSync as o,fstatSync as s,globSync as c,lstatSync as l,mkdirSync as u,mkdtempSync as d,openSync as f,readFileSync as p,readSync as m,readdirSync as h,readlinkSync as g,realpathSync as _,renameSync as v,rmSync as y,statSync as b,symlinkSync as x,unlinkSync as S,writeFileSync as C,writeSync as ee}from"node:fs";import w,*as te from"node:path";import{parseArgs as ne,parseEnv as re,stripVTControlCharacters as ie}from"node:util";import{FatalError as T,TransientError as E,UnexpectedError as D,describeError as O,describeError as k,redact as ae,redact as A}from"@bensandee/common";import{defineCommand as j,renderUsage as oe,runCommand as se,runMain as ce}from"citty";import*as M from"@clack/prompts";import{isCancel as le,select as ue}from"@clack/prompts";import{execFileSync as N,execSync as de,spawn as fe,spawnSync as pe}from"node:child_process";import{z as P}from"zod";import me from"json5";import{applyEdits as he,modify as ge,parse as _e}from"jsonc-parser";import ve from"cross-spawn";import ye,{tmpdir as be}from"node:os";import{createHmac as xe,randomUUID as Se}from"node:crypto";import{isMap as Ce,isScalar as we,isSeq as Te,parse as Ee,parseAllDocuments as De,parseDocument as Oe,stringify as ke,visit as Ae}from"yaml";import{StringDecoder as je}from"node:string_decoder";import{parse as Me}from"smol-toml";import F from"picomatch";import Ne from"node:net";import{fileURLToPath as Pe}from"node:url";function resolveJsonMode(e){return!(!e.some(requestsJson)||e.includes(`--help`)||e.includes(`-h`)||e.length===1&&(e[0]===`--version`||e[0]===`-v`))}function requestsJson(e){return e===`--json`?!0:e.startsWith(`--json=`)?e!==`--json=false`:!1}function resolveCommandName(e){for(let t of e){if(t===`--`)return;if(!t.startsWith(`-`))return t}}function verboseRequested(e){return process.env.TOOLING_TRACE===`true`||process.env.TOOLING_DEBUG===`true`||e.includes(`--verbose`)||e.includes(`-v`)||e.includes(`--trace`)}function asCommandDef(e){if(e!==void 0&&typeof e!=`function`&&!(e instanceof Promise))return e}function commandDeclaresJson(e){if(e===void 0)return!1;let t=e.args;return t===void 0||typeof t==`function`||t instanceof Promise?!1:`json`in t}function buildErrorDocument(e){let t=e.detail===void 0?{kind:e.kind,message:e.message}:{kind:e.kind,message:e.message,detail:e.detail};return{ok:!1,command:e.command,version:e.version,error:t}}function runJsonExitNet(e){if(e.wroteDocument())return;let t=e.command??e.binName,n=buildErrorDocument({command:e.command,version:e.version,kind:`runtime`,message:`${t} --json exited before the command produced a result: the process ended with the command still outstanding, so no document was recorded.`});try{e.write(JSON.stringify(n)+`
|
|
3
|
+
`)}catch{}process.exitCode=1}function installJsonExitNet(e,t,n,r){process.on(`exit`,()=>{runJsonExitNet({write:e=>ee(1,e),wroteDocument:r,command:t,version:n,binName:e})})}function classifyThrown(e,t){let n=e instanceof Error&&e.name===`CLIError`?`usage`:`runtime`,r=ae(O(e));if(!t)return{kind:n,message:r};let i=e instanceof Error&&typeof e.stack==`string`?ae(e.stack):void 0;return i===void 0?{kind:n,message:r}:{kind:n,message:r,detail:i}}const Fe=`BST_ENV_FILE`;function loadEnvFileFromEnv(){let e=process.env[Fe]?.trim();if(e===void 0||e===``)return;let t=te.resolve(e),n;try{n=p(t,`utf8`)}catch(e){let n=e instanceof Error?e.message:String(e);throw new T(`${Fe} names ${t}, which could not be read (${n}). Unset ${Fe} or point it at a readable env file.`)}let r=[],i=[];for(let[e,t]of Object.entries(re(n)))process.env[e]===void 0?(process.env[e]=t,r.push(e)):i.push(e);return{path:t,added:r,kept:i}}function describeEnvFileLoad(e){if(e===void 0)return`No env file loaded -- ${Fe} is unset or empty.`;let t=[`Loaded ${String(e.added.length)} variable(s) from ${e.path} (${Fe}): `+(e.added.length===0?`none`:e.added.join(`, `))];return e.kept.length>0&&t.push(`${String(e.kept.length)} already set in the environment kept their value: `+e.kept.join(`, `)),t.join(`; `)}const Ie={out:e=>{process.stdout.write(`${e}\n`)},err:e=>{process.stderr.write(`${e}\n`)},exit:e=>process.exit(e)};function loadEnvFileForBin(e,t,n=Ie){try{return loadEnvFileFromEnv()}catch(r){let i=r instanceof Error?r.message:String(r);if(resolveJsonMode(e)){let r=buildErrorDocument({command:resolveCommandName(e),version:t.version,kind:`usage`,message:i});n.out(JSON.stringify(r))}else n.err(`${t.name}: ${i}`);return n.exit(1)}}const Le=loadEnvFileForBin(process.argv.slice(2),{name:`bst`,version:`0.109.0`}),Re={error:0,warn:1,info:2,debug:3,trace:4};let ze=`info`;function setLogLevel(e){ze=e}function resolveLogLevel(e){return e.trace===!0||process.env.TOOLING_TRACE===`true`?`trace`:e.verbose===!0||process.env.TOOLING_DEBUG===`true`?`debug`:`info`}const Be=!!process.env.CI,out$1=e=>console.log(e),err=e=>console.error(e),Ve={info:out$1,warn:e=>out$1(`[warn] ${e}`),error:e=>out$1(`[error] ${e}`),success:e=>out$1(`[ok] ${e}`)};let He;function setDefaultUserSink(e){He=e}let Ue=Be,We=!1;function setJsonMode(e){We=e}function isJsonMode(){return We}let Ge;function setJsonNoticeSink(e){Ge=e}function formatContext(e){let t=[];if(e.repo!==void 0){let n=e.repo.split(`/`).findLast(e=>e.length>0);n!==void 0&&t.push(n)}return e.issue!==void 0&&t.push(`#${String(e.issue)}`),e.pr!==void 0&&t.push(`PR#${String(e.pr)}`),e.phase!==void 0&&t.push(e.phase),t.length>0?`[${t.join(` `)}]`:``}function build(e){let t=formatContext(e.context),enabled=t=>Re[t]<=Re[e.level??ze],stamp=()=>`[${e.now().toISOString()}]`,userFacing=(n,r)=>i=>{if(!enabled(r))return;if(We){(n===`warn`||n===`error`)&&Ge&&Ge(A(i));return}let a=[];(e.timestamps??!1)&&a.push(stamp()),t&&a.push(t),a.push(A(i)),(e.userSink??(Ue?Ve:He??Ve))[n](a.join(` `))},diagnostic=n=>r=>{if(!enabled(n))return;let i=[stamp()];t&&i.push(t),i.push(`[${n}]`,A(r)),e.diagnosticSink(i.join(` `))};return{info:userFacing(`info`,`info`),warn:userFacing(`warn`,`warn`),error:userFacing(`error`,`error`),success:userFacing(`success`,`info`),debug:diagnostic(`debug`),trace:diagnostic(`trace`),child:t=>build({...e,context:{...e.context,...t}})}}function createLogger(e={}){return build({level:e.level,timestamps:e.timestamps,context:e.context??{},userSink:e.userSink,diagnosticSink:e.diagnosticSink??err,now:e.now??(()=>/* @__PURE__ */ new Date)})}const Ke=createLogger();setDefaultUserSink(M.log);const qe=!!process.env.CI,out=e=>console.log(e),I=Ke;function note(e,t){isJsonMode()||(qe?(t&&out(`--- ${t} ---`),out(e)):M.note(e,t))}const stdout=e=>console.log(e);function initialState(){return{payload:void 0,hasPayload:!1,error:void 0,hasError:!1,notices:[],wrote:!1}}let L=initialState();function isJsonRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function isStringArray(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function createCliOutput(e){let t=e||isJsonMode();return{json:e=>{t&&(L.hasPayload&&Ke.debug(`output: a second json() call overwrote the first -- last call wins.`),L.payload=e,L.hasPayload=!0)},text:e=>{t||stdout(e)},notice:e=>{t?L.notices.push(A(e)):stdout(e)}}}function recordJsonError(e){L.error=e,L.hasError=!0}function buildFlushDocument(){let e;if(L.hasError?e=L.error:L.hasPayload&&(e=L.payload),e!==void 0){if(L.notices.length===0)return e;if(isJsonRecord(e)){let{notices:t}=e;return{...e,notices:isStringArray(t)?[...t,...L.notices]:L.notices}}return{payload:e,notices:L.notices}}}function flushJsonOutput(){let e=buildFlushDocument();return e!==void 0&&(stdout(JSON.stringify(e)),L.wrote=!0,!0)}function jsonDocumentWritten(){return L.wrote}function defaultGitRunner(e,t,n){try{let r=N(`git`,e,{cwd:t,stdio:[`ignore`,`pipe`,`ignore`],timeout:n?.timeoutMs}).toString(`utf-8`).trim();return r===``?void 0:r}catch{return}}function resolveCurrentBranch(e){let t=e.env??process.env,n=t.GITHUB_REF;if(n!==void 0&&n!==``){if(!n.startsWith(`refs/heads/`))return;let e=t.GITHUB_REF_NAME;return e!==void 0&&e!==``?e:n.slice(11)}let r=(e.git??defaultGitRunner)([`rev-parse`,`--abbrev-ref`,`HEAD`],e.cwd);if(r!==void 0&&r!==`HEAD`)return r}function readOriginUrl(e,t=defaultGitRunner){return t([`remote`,`get-url`,`origin`],e,{timeoutMs:5e3})??null}const Je=P.union([P.string(),P.object({url:P.string()})]);function readPackageRepositoryUrl(e){let t=w.join(e,`package.json`),n;try{n=p(t,`utf-8`)}catch{return null}let r;try{r=JSON.parse(n)}catch(e){throw new T(`${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}let i=P.object({repository:Je.optional()}).safeParse(r);if(!i.success)return null;let a=i.data.repository;return a?typeof a==`string`?a:a.url:null}function parseGitUrl(e){try{let t=new URL(e),n=t.pathname.replace(/\.git$/,``).replace(/^\//,``);return n.includes(`/`)?{protocol:t.protocol,hostname:t.hostname,repository:n}:null}catch{return null}}function forgeTokenFromEnv(e){return e.RELEASE_TOKEN||e.FORGEJO_TOKEN}function resolveRepoUrlFrom(e,t){let n=normalizeGitUrl(e()??``);if(n!==null&&parseGitUrl(n)!==null)return n;let r=t();return r===null||parseGitUrl(r)===null?null:normalizeGitUrl(r)}function resolveForgejoCoordinates(e,t){let n=e.FORGEJO_SERVER_URL,r=e.FORGEJO_REPOSITORY;if(n&&r)return{serverUrl:n,repository:r};let i=t(),a=i===null?null:parseGitUrl(i);return a===null||a.hostname===`github.com`?null:{serverUrl:n??`${a.protocol}//${a.hostname}`,repository:r??a.repository}}function resolveForgejoConnection(e,t){let n=e.FORGEJO_SERVER_URL,r=e.FORGEJO_REPOSITORY,i=forgeTokenFromEnv(e);if(n&&r&&i)return{serverUrl:n,repository:r,token:i};let a=t(),o=a===null?null:parseGitUrl(a);if(o===null){if(n){if(!r)throw new T(`FORGEJO_REPOSITORY environment variable is required`);if(!i)throw new T(`RELEASE_TOKEN environment variable is required`)}return null}if(o.hostname===`github.com`)return null;if(!i)throw new T(`RELEASE_TOKEN environment variable is required (server URL and repository were resolved from package.json)`);return{serverUrl:n??`${o.protocol}//${o.hostname}`,repository:r??o.repository,token:i}}const Ye=/^\/([^/]+\/[^/]+)\/(?:issues|pulls?)\/(\d+)\/?$/;function parseIssueRef(e){if(e===void 0||e.trim()===``)return{};let t=e.trim();if(/^\d+$/.test(t))return{number:Number.parseInt(t,10)};let n;try{n=new URL(t)}catch{n=void 0}if(n!==void 0&&n.protocol!==`http:`&&n.protocol!==`https:`)throw new T(`Not an issue number or issue URL: "${t}" (expected e.g. 273 or https://host/owner/repo/issues/273)`);if(n!==void 0){let e=Ye.exec(n.pathname);if(e){let[,t,r]=e;if(t!==void 0&&r!==void 0)return{number:Number.parseInt(r,10),target:{serverUrl:n.origin,repository:t,hostname:n.hostname}}}}throw new T(`Not an issue number or issue URL: "${t}" (expected e.g. 273 or https://host/owner/repo/issues/273)`)}var RepoTargetEmptyError=class extends T{constructor(){super(`No repository URL was given.`)}},RepoTargetMismatchError=class extends T{given;fromReference;constructor(e,t){super(`The repository (${e}) and the issue URL (${t}) disagree.`),this.given=e,this.fromReference=t}};function parseRepoTarget(e){if(e===void 0)return;if(e.trim()===``)throw new RepoTargetEmptyError;let t=/^(https?:\/\/[^/]+)\/([^/]+\/[^/]+?)(?:\.git)?\/?$/.exec(e.trim());if(!t)throw new T(`Not a repository URL: "${e}"`);let[,n,r]=t;if(n===void 0||r===void 0)throw new T(`Not a repository URL: "${e}"`);return{serverUrl:n,repository:r,hostname:new URL(n).hostname}}function resolveIssueTarget(e,t){let n=parseRepoTarget(t);if(e===void 0)return n;if(n===void 0||e.serverUrl===n.serverUrl&&e.repository===n.repository)return e;throw new RepoTargetMismatchError(`${n.serverUrl}/${n.repository}`,`${e.serverUrl}/${e.repository}`)}function normalizeGitUrl(e){let t=e.startsWith(`git+`)?e.slice(4):e,n=t.match(/^git@([^:]+):(.+?)(?:\.git)?$/);if(n)return`https://${n[1]}/${n[2]}`;try{let e=new URL(t);return e.pathname=e.pathname.replace(/\.git$/,``),e.username=``,e.password=``,e.toString().replace(/\/$/,``)}catch{return null}}const Xe=[`eslint`,`prettier`,`jest`,`webpack`,`rollup`],Ze=P.record(P.string(),P.string()),Qe=P.looseObject({name:P.string(),version:P.string().optional(),onFail:P.string().optional()}),$e=P.looseObject({name:P.string().optional(),version:P.string().optional(),private:P.boolean().optional(),type:P.string().optional(),scripts:Ze.optional(),dependencies:Ze.optional(),devDependencies:Ze.optional(),peerDependencies:Ze.optional(),bin:P.union([P.string(),Ze]).optional(),exports:P.unknown().optional(),main:P.string().optional(),types:P.string().optional(),typings:P.string().optional(),engines:Ze.optional(),devEngines:P.looseObject({runtime:P.union([Qe,P.array(Qe)]).optional()}).optional(),repository:P.union([P.string(),P.looseObject({url:P.string()})]).optional(),packageManager:P.string().optional(),publishConfig:P.unknown().optional()}),et=P.looseObject({extends:P.union([P.string(),P.array(P.string())]).optional(),include:P.array(P.string()).optional(),exclude:P.array(P.string()).optional(),files:P.array(P.string()).optional(),references:P.array(P.looseObject({path:P.string()})).optional(),compilerOptions:P.record(P.string(),P.unknown()).optional()}),tt=P.looseObject({$schema:P.string().optional(),extends:P.array(P.string()).optional()});function parseTsconfig(e){let t=et.safeParse(_e(e));return t.success?t.data:{}}function parseRenovateJson(e){try{let t=tt.safeParse(me.parse(e));return t.success?t.data:{}}catch{return{}}}const nt=P.looseObject({commit:P.union([P.boolean(),P.string()]).optional()});function parseChangesetConfig(e){try{let t=nt.safeParse(JSON.parse(e));return t.success?t.data:void 0}catch{return}}function parsePackageJson(e){try{let t=$e.safeParse(JSON.parse(e));return t.success?t.data:void 0}catch{return}}function describePackageJsonFailure(e){let t;try{t=JSON.parse(e)}catch(e){return`not valid JSON: ${e instanceof Error?e.message:String(e)}`}let n=$e.safeParse(t);if(n.success)return;let r=n.error.issues[0];return`${r&&r.path.length>0?r.path.join(`.`):`a managed field`} has the wrong type${r?` (${r.message})`:``}`}const R=[`crowdedDirectories`,`circularDependencies`,`fanInOutliers`,`fanOutOutliers`],rt=[`fanInOutliers`,`fanOutOutliers`,`crowdedDirectories`],z=[`fanInOutliers`,`fanOutOutliers`,`crowdedDirectories`],it=[`linesOfCode`],at=P.object({linesOfCode:P.number().int().nonnegative().optional()}),ot=P.object({crowdedDirectories:P.number().int().nonnegative(),circularDependencies:P.number().int().nonnegative().optional(),fanInOutliers:P.number().int().nonnegative().optional(),fanOutOutliers:P.number().int().nonnegative().optional()}),st=ot.extend(at.shape).extend({sha:P.string(),timestamp:P.string()}),ct=new Set(z),lt=P.preprocess(e=>typeof e==`object`&&e?Object.fromEntries(Object.entries(e).filter(([e])=>ct.has(e))):e,P.partialRecord(P.enum(z),P.record(P.string(),P.number().int().nonnegative()))),ut=ot.extend({moduleCeilings:lt.optional(),sizeBudgets:P.record(P.string(),P.number().int().nonnegative()).optional()});function parseHealthBaseline(e){let t;try{t=JSON.parse(e)}catch(e){throw new T(`health-baseline.json is not valid JSON: ${k(e)}`)}let n=ut.safeParse(t);if(!n.success)throw new T(`health-baseline.json has unexpected shape: ${n.error.message}`);return n.data}function parseHealthHistoryLine(e){let t;try{t=JSON.parse(e)}catch{return}let n=st.safeParse(t);return n.success?n.data:void 0}function parseToolingConfigSlice(e,t,n){if(e===void 0||e.trim()===``)return;let r=n.path??`.tooling.json`,i;try{i=JSON.parse(e)}catch(e){throw new T(`Could not parse ${r} as JSON: ${k(e)}`)}let a=t.safeParse(i,{reportInput:!0});if(!a.success){let e=a.error.issues.flatMap(e=>formatIssue$1(e).split(`
|
|
4
4
|
`)),t=e.length,i=t===1?`1 problem`:`${t} problems`;throw new T(`Invalid ${r} (${n.block}) -- ${i}:\n${e.join(`
|
|
5
|
-
`)}`)}return a.data}function tolerantBlock(e){return
|
|
6
|
-
`)}return` ${t}: ${e.message}`}const dt=/^[a-z0-9][a-z0-9-]*$/,ft=N.union([N.object({file:N.string().min(1).meta({description:`Repo-relative path of the one file whose byte size is measured.`})}).meta({description:`A size budget measuring the bytes of a single file.`}),N.object({glob:N.string().min(1).meta({description:`Glob matched against repo-relative paths under the target.`}),aggregate:N.enum([`total`,`largest`]).meta({description:`How the matched files become one number: the sum of their bytes, or the biggest single file.`})}).meta({description:`A size budget measuring the bytes of every file a glob matches.`}),N.object({script:N.string().min(1).meta({description:"Package script run as `pnpm run --silent <script>`; it reports one number through the reserved measure marker."}),files:N.array(N.string().min(1)).meta({description:`Globs naming the code that computes the number: a match in the branch's diff marks the measurement as changed by this branch.`})}).meta({description:`A size budget measured by running a package script that prints one number.`})]),pt=N.strictObject({enabled:N.boolean().optional().meta({description:"Opts into the gate (default false; absent and false alike mean off). `health:check` and `health:summary` print a disabled notice and exit 0 rather than failing while off. Read at generation time as well as at check time, so enabling the gate takes a `repo:sync` as well as a config edit. Dominates `history`."}),src:N.array(N.string()).optional().meta({description:'Repo-relative directory roots the measurement is scoped to (default `["packages/*/src"]` when a `packages/` directory exists at the repo root, else `["src"]`). Scopes both the file-tree walk and the dependency-cruiser globs, but not the same way: for the file-tree walk, an entry is expanded against existing directories (one `*` segment only, nothing else). An entry the expander cannot represent at all (`src/**/*.ts`, any other `**`) and one that is well-formed but names no existing directory (a typo, a directory renamed after the config was written) are both reported by name, classified separately, and a run whose file-tree scope resolves to zero source files fails `health:check` before its baseline is read, created, updated, or reset -- `--no-fail-on-empty-src` downgrades that to a notice. For the dependency-cruiser globs the entry is spliced in verbatim, so a `**` entry like `packages/**/src` still cruises and leaves the graph metrics live even though `crowdedDirectories` and the linesOfCode observation see an empty tree. Use `packages/*/src`. The file-tree walk also drops test files, `.d.ts` declarations and `exclude` matches; the dependency-cruiser half drops only `exclude` matches, so a colocated test file or a `.d.ts` under a `src` root still carries graph edges.'}),exclude:N.array(N.string()).optional().meta({description:`Picomatch globs, matched against a repo-relative path and each of its ancestor directories (so a bare directory pattern like "packages/legacy" works). A matching path leaves the measured codebase entirely, for every gated metric and the linesOfCode observation alike: an excluded file is not counted, and its module and edges leave the dependency graph before any count is derived. Unlike exempt, an excluded module's contribution to other modules' fan-in/fan-out is also gone, not just its own listing. The list is additive -- each entry only ever excludes more -- and negation is not supported: a leading "!" is not an exception carved out of an earlier entry, and matches every path the negated pattern does not name.`}),extensions:N.array(N.string()).optional().meta({description:'Leading-dot file extensions that count as source (default `[".ts", ".tsx"]` for a `typescript` stack, `[".js", ".jsx", ".mjs", ".cjs"]` for `javascript`, `[]` for `none`). Feeds the walk and the cruiser globs. `[]` means match-all for the walk and switches the linesOfCode observation off; the line counter strips C-family comments, so a non-C-family extension degrades that observation to non-blank lines. `[]` means something different for the cruiser half: the cruiser glob then has no extension group to match, leaving the dependency-cruiser half matching nothing, so on a ts/js stack an explicit `"extensions": []` leaves every graph metric reading 0 while the gate passes.'}),directoryFileLimit:N.number().int().nonnegative().optional().meta({description:`A directory is a crowdedDirectories offender at strictly more than this many measured files sitting directly in it (default 20). The metric counts over-limit directories rather than files, so splitting one crowded directory into two crowded directories makes it worse. 0 makes every directory holding a measured file an offender.`}),fanInLimit:N.number().int().nonnegative().optional().meta({description:"A module is a fan-in outlier above this many importers, and only when it also exceeds `moduleSizeLimit` source lines (defaults 10 and 200) -- popularity alone is not coupling. Only value edges are counted: a type-only import is erased before the graph is built and never moves this count, and a third-party import resolves outside the graph entirely. A cross-package import counts unless `crossPackage` is off (default on) -- see that setting. Never duplicate a type or fork a helper to stay under the limit -- prefer a justified `exempt` entry, which names the hub, over raising the limit, which hides it."}),fanOutLimit:N.number().int().nonnegative().optional().meta({description:"A module is a fan-out outlier above this many first-party dependencies (default 10). Counted on the same value-edge basis as fanInLimit, `crossPackage` included, with the same consequence: an import you were about to inline or copy to protect this budget most likely costs nothing."}),moduleSizeLimit:N.number().int().nonnegative().optional().meta({description:`Raw source lines a module must exceed before its importer count can make it a fan-in outlier (default 200) -- comments and blanks included, since the question is how big the module is to read, not how much code it holds. A module with many importers and little surface is a leaf, not a junction: it has one job and no reason to change for any of its callers, so counting its importers reports popularity rather than coupling. Applies to fan-in only -- a small module with many dependencies is a barrel, which is a finding.`}),crossPackage:N.boolean().optional().meta({description:"Count dependency edges that cross a workspace package boundary (default true). On by default because the alternative measures the wrong thing: with it off, moving a module into its own package removes its importers from every metric, so extracting a package hides a hub rather than fixing it. A monorepo adopting the default sees fan-in and fan-out rise once, and adopts that rise with `bst health:raise` in the pull request that adopts the setting, which a person merges; a single-package repo has no workspace siblings to resolve, so no new edge enters its graph. Set it to false only where the package boundary is a curated API surface an edge across genuinely costs less, or to hold a baseline on the old measurement basis."}),history:N.enum([`orphan-branch`,`none`]).optional().meta({description:'How history is persisted. "orphan-branch" (default) has `health:record` append one JSON line per commit to `historyBranch` and has `repo:sync` emit the CI record and status steps; "none" turns both off. Does not disable the gate, since the baseline is a committed file. Ignored when `enabled` is false.'}),historyBranch:N.string().optional().meta({description:'The orphan branch `health:record` appends to and `health:status` reads (default "bst/health-metrics"). Never merges into the default branch and holds no source; separate from `coverage.historyBranch` and must not share a branch with it. `branch:prune`\'s built-in never-touch list matches the default name exactly, so a custom name should be named in `branchPrune.exclude` as well.'}),tolerance:N.number().int().nonnegative().optional().meta({description:"Slack in offender counts before an increase is a regression: a metric fails when the current count exceeds baseline + tolerance (default 0, so any increase fails). The same allowance applies to every per-module ceiling in health-baseline.json's moduleCeilings, not only the headline metrics. A count, not a percentage -- coverage's percentage-point slack is `coverage.tolerancePp`. Raising it un-tracks every module beneath the new line at once, which is why a justified `exempt` entry is the better answer to one stubborn hub."}),sizeBudgets:N.record(N.string().regex(dt),ft).optional().meta({description:"Artifact size budgets: id -> what to measure. Each id records one ceiling in health-baseline.json's sizeBudgets, and `health:check` fails when the measured number exceeds it. Absent means no size metric at all. A budget with no recorded value fails as unrecorded until `--update-baseline` records it; a file or glob that measures nothing fails rather than reading as zero. Measured at the working tree only, never at the merge base, so a crossing always names this branch. Raising a recorded value is a raise: write it with `bst health:raise`, in the pull request whose change crossed the budget."}),exempt:N.partialRecord(N.enum(rt),N.record(N.string(),N.string().min(1).refine(e=>e.trim()!==``,{message:`must not be blank`}))).optional().meta({description:"Per-metric, per-module exemption, keyed first by metric name (fanInOutliers, fanOutOutliers or crowdedDirectories) then by the repo-relative path exactly as `health:summary --explain` prints it: a module path for the two fan metrics, a directory path for crowdedDirectories. A key may instead be a picomatch glob (e.g. `packages/contract/src/core/**`), matched against the path itself and never its ancestors; an exact key wins over a glob that also matches, and otherwise the first matching glob's reason applies. A glob also covers modules added later, which still show in the summary with their counts. Each path maps to a required, non-empty justification string. An exempt module or directory is listed in the summary with its count and reason, carries no ceiling in health-baseline.json, and is counted in no metric -- it is out of the gate, not suppressed inside it. Adding one is a raise: write it with `bst health:raise --exempt`, in the pull request whose code made the module a hub. An exempt module stays fully in the graph -- its edges still count toward every other module's fan-in/fan-out."})}),z=N.strictObject({enabled:N.boolean().optional().meta({description:`Run the chars:check gate (default true). Set false to opt out -- the only off-switch: the gate scans tracked text files for LLM-tell punctuation and invisible or deceptive characters, and passes letters in any language.`}),exclude:N.array(N.string()).optional().meta({description:`Additional path globs the chars:check scan skips. Added to the built-in defaults (docs/**/retired/**, **/CHANGELOG.md, and the two generated .claude/hooks/bst-hook files), not a replacement for them.`}),deny:N.array(N.string()).optional().meta({description:`Named offender categories to add to the default deny-list (e.g. "math")`}),allow:N.array(N.string()).optional().meta({description:`Codepoints (as U+XXXX) to drop from the effective deny-list`}),treatAsProse:N.array(N.string()).optional().meta({description:`Path globs (matched the same way as exclude) whose files --fix classifies as prose wholesale regardless of extension, flattening rather than flagging. The opt-back-in for an extension with no dedicated lexical-context classifier where blind flattening is known safe. No built-in defaults.`})});function isCharsGateOn(e){return e?.enabled!==!1}const mt=N.strictObject({strictTypeAware:N.boolean().optional().meta({description:"Make a missing oxlint-tsgolint binary a hard failure for `bst lint:types` (the type-aware oxlint gate) rather than a notice (default false): arming it is what turns a platform gap into a build break, deliberately, because the repo that armed it is the one that asked for it. Findings block in every repo regardless of this setting."})}),ht=N.strictObject({add:N.array(N.string()).optional().meta({description:`Extra package.json scripts to run as first-class check steps, appended to the built-in list (e.g. ['lint:php']). An added step with no matching script is a hard failure.`}),skip:N.array(N.string()).optional().meta({description:`Check steps to skip, unioned with the built-in CI defaults (never replacing them). Supports glob patterns.`}),runOnVersionPr:N.boolean().optional().meta({description:`Run the CI check job on the changesets version PR (changeset-release/<defaultBranch>). Default false: the generated check job is skipped there, because that branch is regenerated on every push to the default branch and that branch's own run gates the release. Has no effect unless releaseStrategy is changesets.`})}),gt=N.strictObject({history:N.enum([`orphan-branch`,`none`]).optional().meta({description:`How coverage history is persisted. 'orphan-branch' (default) appends to a dedicated branch; 'none' disables CI history but keeps the local ratchet.`}),historyBranch:N.string().optional().meta({description:`Orphan branch name for coverage history (default: 'bst/coverage-metrics')`}),tolerancePp:N.number().nonnegative().optional().meta({description:`Tolerance in percentage points for baseline comparison (default: 0.1)`}),floorPp:N.number().nonnegative().max(100).optional().meta({description:`Absolute floor in percent: a total at or above it passes the check regardless of baseline delta, and --update-baseline tracks its current value freely (up or down). Below the floor, the baseline ratchet applies unchanged. Unset means pure ratchet semantics.`}),gateOnPullRequests:N.boolean().optional().meta({description:`When true, checks:run's automatic coverage mode collects coverage on every branch instead of only the default branch, so pull-request and feature-branch runs also produce coverage/coverage-summary.json. An explicit --no-coverage still wins. Coverage recording and history stay default-branch-only. (default: false)`}),include:N.array(N.string()).optional().meta({description:`Glob patterns replacing the default coverage source scope (['src/**']) in the generated vitest.config.ts.`}),exclude:N.array(N.string()).optional().meta({description:`Glob patterns appended to the universal coverage.exclude defaults in the generated vitest.config.ts, for project-specific untestable files (entrypoints, dev-only shims, icon barrels).`})}),_t=N.strictObject({history:N.enum([`orphan-branch`,`none`]).optional().meta({description:'How egress-audit history is persisted. "orphan-branch" (default) has `bst-agent egress:record` append one JSON line per record to `historyBranch`; "none" turns off `egress:record` (it prints a disabled notice and exits 0). Unlike `health.history`, there is no `enabled` key gating `egress:summary` / `egress:check` themselves -- those read the current transcripts root unconditionally, so `history: "none"` is the only off-switch this block has.'}),historyBranch:N.string().optional().meta({description:'Orphan branch name for egress-audit history (default "bst/egress-metrics"). Separate from `coverage.historyBranch` and `health.historyBranch` and must not share a branch with either.'})}),vt=N.enum([`typescript`,`javascript`,`none`]),yt=N.array(N.string()),bt=N.strictObject({name:N.string().meta({description:`Service name`}),url:N.string().meta({description:`Health check URL`}),status:N.number().int().optional().meta({description:`Expected HTTP status code`})}),xt=N.strictObject({composeFiles:N.array(N.string()).optional().meta({description:`Compose files to use`}),envFile:N.string().optional().meta({description:`Environment file for compose`}),services:N.array(N.string()).optional().meta({description:`Services to check (default: all)`}),healthChecks:N.array(bt).optional().meta({description:`Health check definitions`}),buildCommand:N.array(N.string()).optional().meta({description:`Command to build images before checking (e.g. ["pnpm", "image:build"])`}),buildCwd:N.string().optional().meta({description:`Working directory for build command`}),smoketest:N.array(N.string()).optional().meta({description:`Command to run as a smoketest after health checks pass (e.g. ["pnpm", "test:smoke"])`}),smoketestCwd:N.string().optional().meta({description:`Working directory for smoketest command`}),timeoutMs:N.number().int().positive().optional().meta({description:`Overall timeout in milliseconds`}),pollIntervalMs:N.number().int().positive().optional().meta({description:`Poll interval in milliseconds`})}),St=N.strictObject({dockerfile:N.string().optional().meta({description:`Path to Dockerfile relative to package (falls back to convention when omitted)`}),context:N.string().optional().meta({description:`Docker build context relative to package (falls back to convention, default '.')`}),buildArgs:N.record(N.string(),N.string()).optional().meta({description:"Build args passed to `docker build` for this package. Values support ${VAR} and ${VAR:-default} expansion against process.env."}),imageName:N.string().min(1).optional().meta({description:`Image name used for docker:build tags, docker:publish refs, and docker:check cross-referencing. Falls back to the derived name: the package.json name for the root package (npm scope stripped), or {root-name}-{package-name} for a monorepo package. A value that already carries a registry host (e.g. 'ghcr.io/me/app') is used as written by docker:publish, with no registryNamespace prefix added, and must name the registry this run logs in to -- one naming any other host refuses before login.`}),version:N.string().optional().meta({description:`Version used for docker:publish tags; overrides the version resolved from the enclosing package.`}),publish:N.boolean().optional().meta({description:`The publish decision either way: true keeps an image published -- including one whose compose service is declared only in the check overlay, which is not published by default -- and false excludes it while publishDocker stays true. Unset means the discovery default, which publishes everything except a check-only image.`})}),Ct=N.record(N.string(),St),wt=N.record(N.string(),tolerantBlock(St)),Tt=N.object({...xt.shape,healthChecks:N.array(tolerantBlock(bt)).optional()}),Et=/^(?!refs\/)(?!.*\/\/)(?!.*\.\.)(?!.*\/$)(?!.*\.lock$)[A-Za-z0-9][A-Za-z0-9._/-]*$/,Dt=N.string().regex(Et,`must be a plain branch name: ASCII letters, digits, '.', '_', '-' and '/', starting with a letter or digit, with no leading 'refs/', no '//', '..', trailing '/', or '.lock' suffix`),Ot=N.looseObject({agent:N.looseObject({enabled:N.boolean().optional()}).optional()});function agentEnabledIn(e){try{return parseToolingConfigSlice(e,Ot,{block:`agent`})?.agent?.enabled===!0}catch{return!1}}const kt=/* @__PURE__ */ new Set([`node_modules`,`vendor`,`dist`,`public`,`build`,`coverage`,`venv`,`__pycache__`,`target`,`out`,`tmp`]),At=/* @__PURE__ */ new Set([`.ts`,`.tsx`,`.mts`,`.cts`]),jt=/* @__PURE__ */ new Set([`.js`,`.jsx`,`.mjs`,`.cjs`]);function sourceGlob(e,t=`src`){return`${t}/**/*.{${[...e===`typescript`?At:jt].map(e=>e.slice(1)).join(`,`)}}`}function isRootConfigFile(e){return e.includes(w.sep)?!1:/\.config\.[cm]?[jt]sx?$/.test(e)||e.startsWith(`.`)}function scanSource(e,t,n){if(n.ts)return;let r;try{r=h(e,{withFileTypes:!0})}catch{return}for(let i of r){if(n.ts)return;let r=t?w.join(t,i.name):i.name;if(i.isDirectory()){if(i.name.startsWith(`.`)||kt.has(i.name))continue;scanSource(w.join(e,i.name),r,n);continue}if(isRootConfigFile(r))continue;let a=w.extname(i.name);if(At.has(a)){n.ts=!0;return}jt.has(a)&&(n.js=!0)}}function detectStack(e){if(o(w.join(e,`tsconfig.json`)))return`typescript`;let t={ts:!1,js:!1};return scanSource(e,``,t),t.ts?`typescript`:t.js?`javascript`:`none`}function readStackOverride(e){let t=w.join(e,`.tooling.json`);if(!o(t))return;let n;try{n=p(t,`utf-8`)}catch{return}let r=w.relative(process.cwd(),t)||t;return parseToolingConfigSlice(n,N.object({stack:vt.optional()}),{block:`stack`,path:r})?.stack}function resolveStack(e){return readStackOverride(e)??detectStack(e)}function builderFromConfigFiles(e){let has=t=>o(w.join(e,t));return has(`vite.config.ts`)||has(`vite.config.js`)||has(`vite.config.mjs`)?`vite`:has(`tsdown.config.ts`)||has(`tsdown.config.mts`)?`tsdown`:`none`}function shellTokens(e){return e.split(/[\s;&|]+/).filter(e=>e!==``)}function scriptInvokes(e,t){return shellTokens(e).some(e=>e===t||w.basename(e)===t)}function detectBuilder(e,t){let n=t?.scripts;if(n){let e=Object.values(n).filter(e=>typeof e==`string`&&e.trim()!==``);if(e.some(e=>scriptInvokes(e,`tsdown`)))return`tsdown`;if(e.some(e=>scriptInvokes(e,`vite`)))return`vite`;let t=n.build;if(typeof t==`string`&&t.trim()!==``)return`custom`}return builderFromConfigFiles(e)}const Mt={eslint:[/^\.eslintrc/,/^eslint\.config\./],prettier:[/^\.prettierrc/,/^prettier\.config\./],jest:[/^jest\.config\./,/^jest\.setup\./],webpack:[/^webpack\.config\./],rollup:[/^rollup\.config\./]};function detectProject(e){let exists=t=>o(w.join(e,t)),t=readPackageJson(e);return{hasPackageJson:exists(`package.json`),hasTsconfig:exists(`tsconfig.json`),hasOxlintConfig:exists(`oxlint.config.ts`),oxlintExtendsRecommended:fileContains(w.join(e,`oxlint.config.ts`),`@bensandee/config/oxlint/recommended`),hasLegacyOxlintJson:exists(`.oxlintrc.json`),hasGitignore:exists(`.gitignore`),hasVitestConfig:exists(`vitest.config.ts`)||exists(`vitest.config.mts`),hasTsdownConfig:exists(`tsdown.config.ts`)||exists(`tsdown.config.mts`),hasPnpmWorkspace:exists(`pnpm-workspace.yaml`),hasKnipConfig:exists(`knip.json`)||exists(`knip.jsonc`)||exists(`knip.ts`)||exists(`knip.mts`)||exists(`knip.config.ts`)||exists(`knip.config.mts`),hasRenovateConfig:exists(`renovate.json`)||exists(`renovate.json5`)||exists(`.renovaterc`)||exists(`.renovaterc.json`)||exists(`.github/renovate.json`)||exists(`.github/renovate.json5`),hasReleaseItConfig:exists(`.release-it.json`)||exists(`.release-it.yaml`)||exists(`.release-it.toml`),hasSimpleReleaseConfig:exists(`.versionrc`)||exists(`.versionrc.json`)||exists(`.versionrc.js`),hasChangesetsConfig:exists(`.changeset/config.json`),hasRepositoryField:!!t?.repository,hasCommitAndTagVersion:!!t?.devDependencies?.[`commit-and-tag-version`],gitRemoteUrl:detectGitRemoteUrl(e),legacyConfigs:detectLegacyConfigs(e)}}function detectGitRemoteUrl(e){return normalizeGitUrl(readOriginUrl(e)??``)}function detectLegacyConfigs(e){let t;try{t=h(e)}catch{return[]}let n=[];for(let e of Xe){let r=Mt[e],i=t.filter(e=>r.some(t=>t.test(e)));i.length>0&&n.push({tool:e,files:i})}return n}function fileContains(e,t){if(!o(e))return!1;try{return p(e,`utf-8`).includes(t)}catch{return!1}}function readPackageJson(e){let t=w.join(e,`package.json`);if(o(t))try{return parsePackageJson(p(t,`utf-8`))}catch{return}}function detectProjectType(e){let t=readPackageJson(e);if(!t)return`default`;let n={...t.dependencies,...t.devDependencies};if(`react`in n||`react-dom`in n)return`react`;let r=t.scripts??{};return t.bin||Object.values(r).some(e=>typeof e==`string`&&/\b(node|tsx|ts-node)\b/.test(e))?`node`:t.exports||t.main||t.types||t.typings?`library`:`default`}function resolveProjectType(e,t,n){return t===`monorepo`?`default`:e===`react`?`react`:n===`none`?`node`:e}const Nt=/* @__PURE__ */ new Set([`react`,`react-dom`,`vue`,`svelte`,`solid-js`,`next`,`nuxt`,`@angular/core`,`preact`]);function packageHasWebUIDeps(e){let t={...e.dependencies,...e.devDependencies};for(let e of Nt)if(e in t)return!0;return!1}function hasWebUIDeps(e){let t=readPackageJson(e);return t?packageHasWebUIDeps(t):!1}function repoHasWebUI(e){return e.config.structure===`monorepo`?getMonorepoPackages(e.targetDir).some(e=>hasWebUIDeps(e.dir)):e.packageJson?packageHasWebUIDeps(e.packageJson):!1}function detectCiPlatform(e){return o(w.join(e,`.forgejo`,`workflows`))?`forgejo`:o(w.join(e,`.github`,`workflows`))?`github`:`none`}function computeDefaults(e){let t=detectProject(e),n=t.hasPnpmWorkspace,r=t.legacyConfigs.some(e=>e.tool===`prettier`),i=n?`monorepo`:`single`,a=detectBuilder(e,readPackageJson(e));return{structure:i,useEslintPlugin:!0,formatter:r?`prettier`:`oxfmt`,stack:detectStack(e),builder:a,setupVitest:!n&&!t.hasVitestConfig,ci:detectCiPlatform(e),setupRenovate:!0,releaseStrategy:`none`,publishNpm:!1,publishDocker:!1,projectType:resolveProjectType(detectProjectType(e),i,a),detectPackageTypes:!0}}function getPublishablePackages(e,t,n){if(t===`monorepo`){let t=getMonorepoPackages(e),n=[];for(let e of t){let t=readPackageJson(e.dir);t&&!t.private&&t.name&&n.push({name:t.name,dir:e.dir})}return n}let r=n??readPackageJson(e);return!r||r.private||!r.name?[]:[{name:r.name,dir:e}]}function getMonorepoPackages(e){let t=w.join(e,`packages`);if(!o(t))return[];let n=[];try{for(let e of h(t,{withFileTypes:!0})){if(!e.isDirectory())continue;let r=w.join(t,e.name),i=readPackageJson(r);i&&n.push({dir:r,name:i.name??e.name})}}catch{}return n}function isCancelled$1(e){return j.isCancel(e)}function detectProjectInfo(e){let t=readPackageJson(e);return{detected:detectProject(e),defaults:computeDefaults(e),name:t?.name??w.basename(e)}}async function runInitPrompts(e,t,n){j.intro(`@bensandee/tooling repo:sync`);let{detected:r,defaults:i,name:a}=detectProjectInfo(e),s=!t,c=t?.structure??i.structure,l=t?.stack??i.stack,u=t?.builder??i.builder,d=t?.useEslintPlugin??i.useEslintPlugin,f=t?.formatter??i.formatter,p=t?.setupVitest??i.setupVitest,m=t?.ci??i.ci,h=t?.setupRenovate??i.setupRenovate,g=t?.releaseStrategy??i.releaseStrategy,_=t?.projectType??i.projectType,v=t?.detectPackageTypes??i.detectPackageTypes,y=(n?.skipStackPrompt??!1)||!!process.env.CI;if(s&&i.stack===`none`&&!y){let e=await j.select({message:`What is this project's source language?`,initialValue:`typescript`,options:[{value:`typescript`,label:`TypeScript`},{value:`javascript`,label:`JavaScript`},{value:`none`,label:`Neither -- another language (PHP, Python, Go, ...)`}]});if(isCancelled$1(e)&&(j.cancel(`Cancelled.`),process.exit(0)),l=e,l!==`none`){let e=await j.select({message:`What builds this project?`,initialValue:`tsdown`,options:[{value:`tsdown`,label:`tsdown`},{value:`vite`,label:`Vite`},{value:`custom`,label:`Custom build script`},{value:`none`,label:`None`}]});isCancelled$1(e)&&(j.cancel(`Cancelled.`),process.exit(0)),u=e}}if(t?.projectType===void 0&&(_=resolveProjectType(detectProjectType(e),c,u)),r.legacyConfigs.some(e=>e.tool===`prettier`)&&s){let e=await j.select({message:`Existing Prettier config found. Keep Prettier or migrate to oxfmt?`,initialValue:`prettier`,options:[{value:`prettier`,label:`Keep Prettier`},{value:`oxfmt`,label:`Migrate to oxfmt`,hint:`fast, Rust-based`}]});isCancelled$1(e)&&(j.cancel(`Cancelled.`),process.exit(0)),f=e}let b=detectCiPlatform(e);if(s&&b===`none`&&!y){let e=await j.select({message:`CI workflow`,initialValue:`forgejo`,options:[{value:`forgejo`,label:`Forgejo Actions`},{value:`github`,label:`GitHub Actions`},{value:`none`,label:`None`}]});isCancelled$1(e)&&(j.cancel(`Cancelled.`),process.exit(0)),m=e}let x=r.hasReleaseItConfig||r.hasSimpleReleaseConfig||r.hasChangesetsConfig;if(s&&!x&&!y){let e=await j.select({message:`Release management`,initialValue:i.releaseStrategy,options:[{value:`none`,label:`None`},{value:`release-it`,label:`release-it`,hint:`interactive, conventional commits`},{value:`changesets`,label:`Changesets`,hint:`PR-based versioning`},{value:`simple`,label:`Simple`,hint:`uses commit-and-tag-version internally`}]});isCancelled$1(e)&&(j.cancel(`Cancelled.`),process.exit(0)),g=e}let S=t?.publishNpm??!1;if(s&&g!==`none`&&getPublishablePackages(e,c).length>0){let e=await j.confirm({message:`Publish packages to npm?`,initialValue:!1});isCancelled$1(e)&&(j.cancel(`Cancelled.`),process.exit(0)),S=e}let C=t?.publishDocker??!1;if(s&&(o(w.join(e,`Dockerfile`))||o(w.join(e,`docker/Dockerfile`)))){let e=await j.confirm({message:`Publish Docker images to a registry?`,initialValue:!1});isCancelled$1(e)&&(j.cancel(`Cancelled.`),process.exit(0)),C=e}return j.outro(`Configuration complete!`),{name:a,structure:c,stack:l,builder:u,useEslintPlugin:d,formatter:f,setupVitest:p,ci:m,setupRenovate:h,releaseStrategy:g,publishNpm:S,publishDocker:C,projectType:_,detectPackageTypes:v,targetDir:e}}function buildDefaultConfig(e,t){let{defaults:n,name:r}=detectProjectInfo(e);return{name:r,...n,...t.eslintPlugin!==void 0&&{useEslintPlugin:t.eslintPlugin},...t.noCi&&{ci:`none`},targetDir:e}}const Pt=/* @__PURE__ */ new Set([`ENOENT`,`EINVAL`,`ENOEXEC`]);function shouldRetryViaShim(e,t=process.platform){if(t!==`win32`||!(e instanceof Error)||!(`code`in e))return!1;let{code:n}=e;return typeof n==`string`&&Pt.has(n)}const Ft=ve.sync,It=ve;function runFormatter(e,t,n,r){let i=w.join(e,`node_modules`,`.bin`,t);if(!o(i))return;let a=[`--stdin-filepath`,n],s={cwd:e,input:r,encoding:`utf-8`},c=pe(i,a,s);if(shouldRetryViaShim(c.error)&&(c=Ft(i,a,s)),c.error||c.status!==0)return;let l=c.stdout;if(l)return l}function createContentFormatter(e){let t=/* @__PURE__ */ new Map;return(n,r)=>{let i=`${w.extname(n)}\0${r}`,a=t.get(i);if(a!==void 0)return a;let o=runFormatter(e.targetDir,e.formatter,n,r)??r;return t.set(i,o),o}}function formattedTemplate(e,t,n){return e.read(t)===n?n:e.format(t,n)}function isGeneratedTemplate(e,t,n){let r=e.read(t);return r===void 0?!1:r===n||r===e.format(t,n)}function isContained(e,t){let n=w.resolve(e,t);return n.startsWith(e+w.sep)||n===e}function assertContained(e,t){if(!isContained(e,t))throw new T(`Path traversal detected: ${t} resolves outside target directory`)}function normalizeEol(e){return e.replaceAll(`\r
|
|
5
|
+
`)}`)}return a.data}function tolerantBlock(e){return P.object(e.shape)}function isInformativeBranch(e){return e.some(e=>e.path.length>0||e.code===`unrecognized_keys`)}function describeInputType(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function formatIssue$1(e){let t=e.path.length>0?e.path.map(String).join(`.`):`(root)`;if(e.code===`invalid_type`)return e.input===void 0?` ${t}: missing (expected ${e.expected})`:` ${t}: expected ${e.expected}, got ${describeInputType(e.input)}`;if(e.code===`unrecognized_keys`)return` ${t}: ${e.keys.length>1?`unknown fields`:`unknown field`} ${e.keys.map(e=>`"${e}"`).join(`, `)}`;if(e.code===`invalid_union`){let t=e.errors.filter(isInformativeBranch);if(t.length===1)return t[0].map(t=>formatIssue$1({...t,path:[...e.path,...t.path]})).join(`
|
|
6
|
+
`)}return` ${t}: ${e.message}`}const dt=/^[a-z0-9][a-z0-9-]*$/,ft=P.union([P.object({file:P.string().min(1).meta({description:`Repo-relative path of the one file whose byte size is measured.`})}).meta({description:`A size budget measuring the bytes of a single file.`}),P.object({glob:P.string().min(1).meta({description:`Glob matched against repo-relative paths under the target.`}),aggregate:P.enum([`total`,`largest`]).meta({description:`How the matched files become one number: the sum of their bytes, or the biggest single file.`})}).meta({description:`A size budget measuring the bytes of every file a glob matches.`}),P.object({script:P.string().min(1).meta({description:"Package script run as `pnpm run --silent <script>`; it reports one number through the reserved measure marker."}),files:P.array(P.string().min(1)).meta({description:`Globs naming the code that computes the number: a match in the branch's diff marks the measurement as changed by this branch.`})}).meta({description:`A size budget measured by running a package script that prints one number.`})]),pt=P.strictObject({enabled:P.boolean().optional().meta({description:"Opts into the gate (default false; absent and false alike mean off). `health:check` and `health:summary` print a disabled notice and exit 0 rather than failing while off. Read at generation time as well as at check time, so enabling the gate takes a `repo:sync` as well as a config edit. Dominates `history`."}),src:P.array(P.string()).optional().meta({description:'Repo-relative directory roots the measurement is scoped to (default `["packages/*/src"]` when a `packages/` directory exists at the repo root, else `["src"]`). Scopes both the file-tree walk and the dependency-cruiser globs, but not the same way: for the file-tree walk, an entry is expanded against existing directories (one `*` segment only, nothing else). An entry the expander cannot represent at all (`src/**/*.ts`, any other `**`) and one that is well-formed but names no existing directory (a typo, a directory renamed after the config was written) are both reported by name, classified separately, and a run whose file-tree scope resolves to zero source files fails `health:check` before its baseline is read, created, updated, or reset -- `--no-fail-on-empty-src` downgrades that to a notice. For the dependency-cruiser globs the entry is spliced in verbatim, so a `**` entry like `packages/**/src` still cruises and leaves the graph metrics live even though `crowdedDirectories` and the linesOfCode observation see an empty tree. Use `packages/*/src`. The file-tree walk also drops test files, `.d.ts` declarations and `exclude` matches; the dependency-cruiser half drops only `exclude` matches, so a colocated test file or a `.d.ts` under a `src` root still carries graph edges.'}),exclude:P.array(P.string()).optional().meta({description:`Picomatch globs, matched against a repo-relative path and each of its ancestor directories (so a bare directory pattern like "packages/legacy" works). A matching path leaves the measured codebase entirely, for every gated metric and the linesOfCode observation alike: an excluded file is not counted, and its module and edges leave the dependency graph before any count is derived. Unlike exempt, an excluded module's contribution to other modules' fan-in/fan-out is also gone, not just its own listing. The list is additive -- each entry only ever excludes more -- and negation is not supported: a leading "!" is not an exception carved out of an earlier entry, and matches every path the negated pattern does not name.`}),extensions:P.array(P.string()).optional().meta({description:'Leading-dot file extensions that count as source (default `[".ts", ".tsx"]` for a `typescript` stack, `[".js", ".jsx", ".mjs", ".cjs"]` for `javascript`, `[]` for `none`). Feeds the walk and the cruiser globs. `[]` means match-all for the walk and switches the linesOfCode observation off; the line counter strips C-family comments, so a non-C-family extension degrades that observation to non-blank lines. `[]` means something different for the cruiser half: the cruiser glob then has no extension group to match, leaving the dependency-cruiser half matching nothing, so on a ts/js stack an explicit `"extensions": []` leaves every graph metric reading 0 while the gate passes.'}),directoryFileLimit:P.number().int().nonnegative().optional().meta({description:`A directory is a crowdedDirectories offender at strictly more than this many measured files sitting directly in it (default 20). The metric counts over-limit directories rather than files, so splitting one crowded directory into two crowded directories makes it worse. 0 makes every directory holding a measured file an offender.`}),fanInLimit:P.number().int().nonnegative().optional().meta({description:"A module is a fan-in outlier above this many importers, and only when it also exceeds `moduleSizeLimit` source lines (defaults 10 and 200) -- popularity alone is not coupling. Only value edges are counted: a type-only import is erased before the graph is built and never moves this count, and a third-party import resolves outside the graph entirely. A cross-package import counts unless `crossPackage` is off (default on) -- see that setting. Never duplicate a type or fork a helper to stay under the limit -- prefer a justified `exempt` entry, which names the hub, over raising the limit, which hides it."}),fanOutLimit:P.number().int().nonnegative().optional().meta({description:"A module is a fan-out outlier above this many first-party dependencies (default 10). Counted on the same value-edge basis as fanInLimit, `crossPackage` included, with the same consequence: an import you were about to inline or copy to protect this budget most likely costs nothing."}),moduleSizeLimit:P.number().int().nonnegative().optional().meta({description:`Raw source lines a module must exceed before its importer count can make it a fan-in outlier (default 200) -- comments and blanks included, since the question is how big the module is to read, not how much code it holds. A module with many importers and little surface is a leaf, not a junction: it has one job and no reason to change for any of its callers, so counting its importers reports popularity rather than coupling. Applies to fan-in only -- a small module with many dependencies is a barrel, which is a finding.`}),crossPackage:P.boolean().optional().meta({description:"Count dependency edges that cross a workspace package boundary (default true). On by default because the alternative measures the wrong thing: with it off, moving a module into its own package removes its importers from every metric, so extracting a package hides a hub rather than fixing it. A monorepo adopting the default sees fan-in and fan-out rise once, and adopts that rise with `bst health:raise` in the pull request that adopts the setting, which a person merges; a single-package repo has no workspace siblings to resolve, so no new edge enters its graph. Set it to false only where the package boundary is a curated API surface an edge across genuinely costs less, or to hold a baseline on the old measurement basis."}),history:P.enum([`orphan-branch`,`none`]).optional().meta({description:'How history is persisted. "orphan-branch" (default) has `health:record` append one JSON line per commit to `historyBranch` and has `repo:sync` emit the CI record and status steps; "none" turns both off. Does not disable the gate, since the baseline is a committed file. Ignored when `enabled` is false.'}),historyBranch:P.string().optional().meta({description:'The orphan branch `health:record` appends to and `health:status` reads (default "bst/health-metrics"). Never merges into the default branch and holds no source; separate from `coverage.historyBranch` and must not share a branch with it. `branch:prune`\'s built-in never-touch list matches the default name exactly, so a custom name should be named in `branchPrune.exclude` as well.'}),tolerance:P.number().int().nonnegative().optional().meta({description:"Slack in offender counts before an increase is a regression: a metric fails when the current count exceeds baseline + tolerance (default 0, so any increase fails). The same allowance applies to every per-module ceiling in health-baseline.json's moduleCeilings, not only the headline metrics. A count, not a percentage -- coverage's percentage-point slack is `coverage.tolerancePp`. Raising it un-tracks every module beneath the new line at once, which is why a justified `exempt` entry is the better answer to one stubborn hub."}),sizeBudgets:P.record(P.string().regex(dt),ft).optional().meta({description:"Artifact size budgets: id -> what to measure. Each id records one ceiling in health-baseline.json's sizeBudgets, and `health:check` fails when the measured number exceeds it. Absent means no size metric at all. A budget with no recorded value fails as unrecorded until `--update-baseline` records it; a file or glob that measures nothing fails rather than reading as zero. Measured at the working tree only, never at the merge base, so a crossing always names this branch. Raising a recorded value is a raise: write it with `bst health:raise`, in the pull request whose change crossed the budget."}),exempt:P.partialRecord(P.enum(rt),P.record(P.string(),P.string().min(1).refine(e=>e.trim()!==``,{message:`must not be blank`}))).optional().meta({description:"Per-metric, per-module exemption, keyed first by metric name (fanInOutliers, fanOutOutliers or crowdedDirectories) then by the repo-relative path exactly as `health:summary --explain` prints it: a module path for the two fan metrics, a directory path for crowdedDirectories. A key may instead be a picomatch glob (e.g. `packages/contract/src/core/**`), matched against the path itself and never its ancestors; an exact key wins over a glob that also matches, and otherwise the first matching glob's reason applies. A glob also covers modules added later, which still show in the summary with their counts. Each path maps to a required, non-empty justification string. An exempt module or directory is listed in the summary with its count and reason, carries no ceiling in health-baseline.json, and is counted in no metric -- it is out of the gate, not suppressed inside it. Adding one is a raise: write it with `bst health:raise --exempt`, in the pull request whose code made the module a hub. An exempt module stays fully in the graph -- its edges still count toward every other module's fan-in/fan-out."})}),B=P.strictObject({enabled:P.boolean().optional().meta({description:`Run the chars:check gate (default true). Set false to opt out -- the only off-switch: the gate scans tracked text files for LLM-tell punctuation and invisible or deceptive characters, and passes letters in any language.`}),exclude:P.array(P.string()).optional().meta({description:`Additional path globs the chars:check scan skips. Added to the built-in defaults (docs/**/retired/**, **/CHANGELOG.md, and the two generated .claude/hooks/bst-hook files), not a replacement for them.`}),deny:P.array(P.string()).optional().meta({description:`Named offender categories to add to the default deny-list (e.g. "math")`}),allow:P.array(P.string()).optional().meta({description:`Codepoints (as U+XXXX) to drop from the effective deny-list`}),treatAsProse:P.array(P.string()).optional().meta({description:`Path globs (matched the same way as exclude) whose files --fix classifies as prose wholesale regardless of extension, flattening rather than flagging. The opt-back-in for an extension with no dedicated lexical-context classifier where blind flattening is known safe. No built-in defaults.`})});function isCharsGateOn(e){return e?.enabled!==!1}const mt=P.strictObject({strictTypeAware:P.boolean().optional().meta({description:"Make a missing oxlint-tsgolint binary a hard failure for `bst lint:types` (the type-aware oxlint gate) rather than a notice (default false): arming it is what turns a platform gap into a build break, deliberately, because the repo that armed it is the one that asked for it. Findings block in every repo regardless of this setting."})}),ht=P.strictObject({add:P.array(P.string()).optional().meta({description:`Extra package.json scripts to run as first-class check steps, appended to the built-in list (e.g. ['lint:php']). An added step with no matching script is a hard failure.`}),skip:P.array(P.string()).optional().meta({description:`Check steps to skip, unioned with the built-in CI defaults (never replacing them). Supports glob patterns.`}),runOnVersionPr:P.boolean().optional().meta({description:`Run the CI check job on the changesets version PR (changeset-release/<defaultBranch>). Default false: the generated check job is skipped there, because that branch is regenerated on every push to the default branch and that branch's own run gates the release. Has no effect unless releaseStrategy is changesets.`})}),gt=P.strictObject({history:P.enum([`orphan-branch`,`none`]).optional().meta({description:`How coverage history is persisted. 'orphan-branch' (default) appends to a dedicated branch; 'none' disables CI history but keeps the local ratchet.`}),historyBranch:P.string().optional().meta({description:`Orphan branch name for coverage history (default: 'bst/coverage-metrics')`}),tolerancePp:P.number().nonnegative().optional().meta({description:`Tolerance in percentage points for baseline comparison (default: 0.1)`}),floorPp:P.number().nonnegative().max(100).optional().meta({description:`Absolute floor in percent: a total at or above it passes the check regardless of baseline delta, and --update-baseline tracks its current value freely (up or down). Below the floor, the baseline ratchet applies unchanged. Unset means pure ratchet semantics.`}),gateOnPullRequests:P.boolean().optional().meta({description:`When true, checks:run's automatic coverage mode collects coverage on every branch instead of only the default branch, so pull-request and feature-branch runs also produce coverage/coverage-summary.json. An explicit --no-coverage still wins. Coverage recording and history stay default-branch-only. (default: false)`}),include:P.array(P.string()).optional().meta({description:`Glob patterns replacing the default coverage source scope (['src/**']) in the generated vitest.config.ts.`}),exclude:P.array(P.string()).optional().meta({description:`Glob patterns appended to the universal coverage.exclude defaults in the generated vitest.config.ts, for project-specific untestable files (entrypoints, dev-only shims, icon barrels).`})}),_t=P.strictObject({history:P.enum([`orphan-branch`,`none`]).optional().meta({description:'How egress-audit history is persisted. "orphan-branch" (default) has `bst-agent egress:record` append one JSON line per record to `historyBranch`; "none" turns off `egress:record` (it prints a disabled notice and exits 0). Unlike `health.history`, there is no `enabled` key gating `egress:summary` / `egress:check` themselves -- those read the current transcripts root unconditionally, so `history: "none"` is the only off-switch this block has.'}),historyBranch:P.string().optional().meta({description:'Orphan branch name for egress-audit history (default "bst/egress-metrics"). Separate from `coverage.historyBranch` and `health.historyBranch` and must not share a branch with either.'})}),vt=P.enum([`typescript`,`javascript`,`none`]),yt=P.array(P.string()),bt=P.strictObject({name:P.string().meta({description:`Service name`}),url:P.string().meta({description:`Health check URL`}),status:P.number().int().optional().meta({description:`Expected HTTP status code`})}),xt=P.strictObject({composeFiles:P.array(P.string()).optional().meta({description:`Compose files to use`}),envFile:P.string().optional().meta({description:`Environment file for compose`}),services:P.array(P.string()).optional().meta({description:`Services to check (default: all)`}),healthChecks:P.array(bt).optional().meta({description:`Health check definitions`}),buildCommand:P.array(P.string()).optional().meta({description:`Command to build images before checking (e.g. ["pnpm", "image:build"])`}),buildCwd:P.string().optional().meta({description:`Working directory for build command`}),smoketest:P.array(P.string()).optional().meta({description:`Command to run as a smoketest after health checks pass (e.g. ["pnpm", "test:smoke"])`}),smoketestCwd:P.string().optional().meta({description:`Working directory for smoketest command`}),timeoutMs:P.number().int().positive().optional().meta({description:`Overall timeout in milliseconds`}),pollIntervalMs:P.number().int().positive().optional().meta({description:`Poll interval in milliseconds`})}),St=P.strictObject({dockerfile:P.string().optional().meta({description:`Path to Dockerfile relative to package (falls back to convention when omitted)`}),context:P.string().optional().meta({description:`Docker build context relative to package (falls back to convention, default '.')`}),buildArgs:P.record(P.string(),P.string()).optional().meta({description:"Build args passed to `docker build` for this package. Values support ${VAR} and ${VAR:-default} expansion against process.env."}),imageName:P.string().min(1).optional().meta({description:`Image name used for docker:build tags, docker:publish refs, and docker:check cross-referencing. Falls back to the derived name: the package.json name for the root package (npm scope stripped), or {root-name}-{package-name} for a monorepo package. A value that already carries a registry host (e.g. 'ghcr.io/me/app') is used as written by docker:publish, with no registryNamespace prefix added, and must name the registry this run logs in to -- one naming any other host refuses before login.`}),version:P.string().optional().meta({description:`Version used for docker:publish tags; overrides the version resolved from the enclosing package.`}),publish:P.boolean().optional().meta({description:`The publish decision either way: true keeps an image published -- including one whose compose service is declared only in the check overlay, which is not published by default -- and false excludes it while publishDocker stays true. Unset means the discovery default, which publishes everything except a check-only image.`})}),Ct=P.record(P.string(),St),wt=P.record(P.string(),tolerantBlock(St)),Tt=P.object({...xt.shape,healthChecks:P.array(tolerantBlock(bt)).optional()}),Et=/^(?!refs\/)(?!.*\/\/)(?!.*\.\.)(?!.*\/$)(?!.*\.lock$)[A-Za-z0-9][A-Za-z0-9._/-]*$/,Dt=P.string().regex(Et,`must be a plain branch name: ASCII letters, digits, '.', '_', '-' and '/', starting with a letter or digit, with no leading 'refs/', no '//', '..', trailing '/', or '.lock' suffix`),Ot=P.looseObject({agent:P.looseObject({enabled:P.boolean().optional()}).optional()});function agentEnabledIn(e){try{return parseToolingConfigSlice(e,Ot,{block:`agent`})?.agent?.enabled===!0}catch{return!1}}const kt=/* @__PURE__ */ new Set([`node_modules`,`vendor`,`dist`,`public`,`build`,`coverage`,`venv`,`__pycache__`,`target`,`out`,`tmp`]),At=/* @__PURE__ */ new Set([`.ts`,`.tsx`,`.mts`,`.cts`]),jt=/* @__PURE__ */ new Set([`.js`,`.jsx`,`.mjs`,`.cjs`]);function sourceGlob(e,t=`src`){return`${t}/**/*.{${[...e===`typescript`?At:jt].map(e=>e.slice(1)).join(`,`)}}`}function isRootConfigFile(e){return e.includes(w.sep)?!1:/\.config\.[cm]?[jt]sx?$/.test(e)||e.startsWith(`.`)}function scanSource(e,t,n){if(n.ts)return;let r;try{r=h(e,{withFileTypes:!0})}catch{return}for(let i of r){if(n.ts)return;let r=t?w.join(t,i.name):i.name;if(i.isDirectory()){if(i.name.startsWith(`.`)||kt.has(i.name))continue;scanSource(w.join(e,i.name),r,n);continue}if(isRootConfigFile(r))continue;let a=w.extname(i.name);if(At.has(a)){n.ts=!0;return}jt.has(a)&&(n.js=!0)}}function detectStack(e){if(o(w.join(e,`tsconfig.json`)))return`typescript`;let t={ts:!1,js:!1};return scanSource(e,``,t),t.ts?`typescript`:t.js?`javascript`:`none`}function readStackOverride(e){let t=w.join(e,`.tooling.json`);if(!o(t))return;let n;try{n=p(t,`utf-8`)}catch{return}let r=w.relative(process.cwd(),t)||t;return parseToolingConfigSlice(n,P.object({stack:vt.optional()}),{block:`stack`,path:r})?.stack}function resolveStack(e){return readStackOverride(e)??detectStack(e)}function builderFromConfigFiles(e){let has=t=>o(w.join(e,t));return has(`vite.config.ts`)||has(`vite.config.js`)||has(`vite.config.mjs`)?`vite`:has(`tsdown.config.ts`)||has(`tsdown.config.mts`)?`tsdown`:`none`}function shellTokens(e){return e.split(/[\s;&|]+/).filter(e=>e!==``)}function scriptInvokes(e,t){return shellTokens(e).some(e=>e===t||w.basename(e)===t)}function detectBuilder(e,t){let n=t?.scripts;if(n){let e=Object.values(n).filter(e=>typeof e==`string`&&e.trim()!==``);if(e.some(e=>scriptInvokes(e,`tsdown`)))return`tsdown`;if(e.some(e=>scriptInvokes(e,`vite`)))return`vite`;let t=n.build;if(typeof t==`string`&&t.trim()!==``)return`custom`}return builderFromConfigFiles(e)}const Mt={eslint:[/^\.eslintrc/,/^eslint\.config\./],prettier:[/^\.prettierrc/,/^prettier\.config\./],jest:[/^jest\.config\./,/^jest\.setup\./],webpack:[/^webpack\.config\./],rollup:[/^rollup\.config\./]};function detectProject(e){let exists=t=>o(w.join(e,t)),t=readPackageJson(e);return{hasPackageJson:exists(`package.json`),hasTsconfig:exists(`tsconfig.json`),hasOxlintConfig:exists(`oxlint.config.ts`),oxlintExtendsRecommended:fileContains(w.join(e,`oxlint.config.ts`),`@bensandee/config/oxlint/recommended`),hasLegacyOxlintJson:exists(`.oxlintrc.json`),hasGitignore:exists(`.gitignore`),hasVitestConfig:exists(`vitest.config.ts`)||exists(`vitest.config.mts`),hasTsdownConfig:exists(`tsdown.config.ts`)||exists(`tsdown.config.mts`),hasPnpmWorkspace:exists(`pnpm-workspace.yaml`),hasKnipConfig:exists(`knip.json`)||exists(`knip.jsonc`)||exists(`knip.ts`)||exists(`knip.mts`)||exists(`knip.config.ts`)||exists(`knip.config.mts`),hasRenovateConfig:exists(`renovate.json`)||exists(`renovate.json5`)||exists(`.renovaterc`)||exists(`.renovaterc.json`)||exists(`.github/renovate.json`)||exists(`.github/renovate.json5`),hasReleaseItConfig:exists(`.release-it.json`)||exists(`.release-it.yaml`)||exists(`.release-it.toml`),hasSimpleReleaseConfig:exists(`.versionrc`)||exists(`.versionrc.json`)||exists(`.versionrc.js`),hasChangesetsConfig:exists(`.changeset/config.json`),hasRepositoryField:!!t?.repository,hasCommitAndTagVersion:!!t?.devDependencies?.[`commit-and-tag-version`],gitRemoteUrl:detectGitRemoteUrl(e),legacyConfigs:detectLegacyConfigs(e)}}function detectGitRemoteUrl(e){return normalizeGitUrl(readOriginUrl(e)??``)}function detectLegacyConfigs(e){let t;try{t=h(e)}catch{return[]}let n=[];for(let e of Xe){let r=Mt[e],i=t.filter(e=>r.some(t=>t.test(e)));i.length>0&&n.push({tool:e,files:i})}return n}function fileContains(e,t){if(!o(e))return!1;try{return p(e,`utf-8`).includes(t)}catch{return!1}}function readPackageJson(e){let t=w.join(e,`package.json`);if(o(t))try{return parsePackageJson(p(t,`utf-8`))}catch{return}}function detectProjectType(e){let t=readPackageJson(e);if(!t)return`default`;let n={...t.dependencies,...t.devDependencies};if(`react`in n||`react-dom`in n)return`react`;let r=t.scripts??{};return t.bin||Object.values(r).some(e=>typeof e==`string`&&/\b(node|tsx|ts-node)\b/.test(e))?`node`:t.exports||t.main||t.types||t.typings?`library`:`default`}function resolveProjectType(e,t,n){return t===`monorepo`?`default`:e===`react`?`react`:n===`none`?`node`:e}const Nt=/* @__PURE__ */ new Set([`react`,`react-dom`,`vue`,`svelte`,`solid-js`,`next`,`nuxt`,`@angular/core`,`preact`]);function packageHasWebUIDeps(e){let t={...e.dependencies,...e.devDependencies};for(let e of Nt)if(e in t)return!0;return!1}function hasWebUIDeps(e){let t=readPackageJson(e);return t?packageHasWebUIDeps(t):!1}function repoHasWebUI(e){return e.config.structure===`monorepo`?getMonorepoPackages(e.targetDir).some(e=>hasWebUIDeps(e.dir)):e.packageJson?packageHasWebUIDeps(e.packageJson):!1}function detectCiPlatform(e){return o(w.join(e,`.forgejo`,`workflows`))?`forgejo`:o(w.join(e,`.github`,`workflows`))?`github`:`none`}function computeDefaults(e){let t=detectProject(e),n=t.hasPnpmWorkspace,r=t.legacyConfigs.some(e=>e.tool===`prettier`),i=n?`monorepo`:`single`,a=detectBuilder(e,readPackageJson(e));return{structure:i,useEslintPlugin:!0,formatter:r?`prettier`:`oxfmt`,stack:detectStack(e),builder:a,setupVitest:!n&&!t.hasVitestConfig,ci:detectCiPlatform(e),setupRenovate:!0,releaseStrategy:`none`,publishNpm:!1,publishDocker:!1,projectType:resolveProjectType(detectProjectType(e),i,a),detectPackageTypes:!0}}function getPublishablePackages(e,t,n){if(t===`monorepo`){let t=getMonorepoPackages(e),n=[];for(let e of t){let t=readPackageJson(e.dir);t&&!t.private&&t.name&&n.push({name:t.name,dir:e.dir})}return n}let r=n??readPackageJson(e);return!r||r.private||!r.name?[]:[{name:r.name,dir:e}]}function getMonorepoPackages(e){let t=w.join(e,`packages`);if(!o(t))return[];let n=[];try{for(let e of h(t,{withFileTypes:!0})){if(!e.isDirectory())continue;let r=w.join(t,e.name),i=readPackageJson(r);i&&n.push({dir:r,name:i.name??e.name})}}catch{}return n}function isCancelled$1(e){return M.isCancel(e)}function detectProjectInfo(e){let t=readPackageJson(e);return{detected:detectProject(e),defaults:computeDefaults(e),name:t?.name??w.basename(e)}}async function runInitPrompts(e,t,n){M.intro(`@bensandee/tooling repo:sync`);let{detected:r,defaults:i,name:a}=detectProjectInfo(e),s=!t,c=t?.structure??i.structure,l=t?.stack??i.stack,u=t?.builder??i.builder,d=t?.useEslintPlugin??i.useEslintPlugin,f=t?.formatter??i.formatter,p=t?.setupVitest??i.setupVitest,m=t?.ci??i.ci,h=t?.setupRenovate??i.setupRenovate,g=t?.releaseStrategy??i.releaseStrategy,_=t?.projectType??i.projectType,v=t?.detectPackageTypes??i.detectPackageTypes,y=(n?.skipStackPrompt??!1)||!!process.env.CI;if(s&&i.stack===`none`&&!y){let e=await M.select({message:`What is this project's source language?`,initialValue:`typescript`,options:[{value:`typescript`,label:`TypeScript`},{value:`javascript`,label:`JavaScript`},{value:`none`,label:`Neither -- another language (PHP, Python, Go, ...)`}]});if(isCancelled$1(e)&&(M.cancel(`Cancelled.`),process.exit(0)),l=e,l!==`none`){let e=await M.select({message:`What builds this project?`,initialValue:`tsdown`,options:[{value:`tsdown`,label:`tsdown`},{value:`vite`,label:`Vite`},{value:`custom`,label:`Custom build script`},{value:`none`,label:`None`}]});isCancelled$1(e)&&(M.cancel(`Cancelled.`),process.exit(0)),u=e}}if(t?.projectType===void 0&&(_=resolveProjectType(detectProjectType(e),c,u)),r.legacyConfigs.some(e=>e.tool===`prettier`)&&s){let e=await M.select({message:`Existing Prettier config found. Keep Prettier or migrate to oxfmt?`,initialValue:`prettier`,options:[{value:`prettier`,label:`Keep Prettier`},{value:`oxfmt`,label:`Migrate to oxfmt`,hint:`fast, Rust-based`}]});isCancelled$1(e)&&(M.cancel(`Cancelled.`),process.exit(0)),f=e}let b=detectCiPlatform(e);if(s&&b===`none`&&!y){let e=await M.select({message:`CI workflow`,initialValue:`forgejo`,options:[{value:`forgejo`,label:`Forgejo Actions`},{value:`github`,label:`GitHub Actions`},{value:`none`,label:`None`}]});isCancelled$1(e)&&(M.cancel(`Cancelled.`),process.exit(0)),m=e}let x=r.hasReleaseItConfig||r.hasSimpleReleaseConfig||r.hasChangesetsConfig;if(s&&!x&&!y){let e=await M.select({message:`Release management`,initialValue:i.releaseStrategy,options:[{value:`none`,label:`None`},{value:`release-it`,label:`release-it`,hint:`interactive, conventional commits`},{value:`changesets`,label:`Changesets`,hint:`PR-based versioning`},{value:`simple`,label:`Simple`,hint:`uses commit-and-tag-version internally`}]});isCancelled$1(e)&&(M.cancel(`Cancelled.`),process.exit(0)),g=e}let S=t?.publishNpm??!1;if(s&&g!==`none`&&getPublishablePackages(e,c).length>0){let e=await M.confirm({message:`Publish packages to npm?`,initialValue:!1});isCancelled$1(e)&&(M.cancel(`Cancelled.`),process.exit(0)),S=e}let C=t?.publishDocker??!1;if(s&&(o(w.join(e,`Dockerfile`))||o(w.join(e,`docker/Dockerfile`)))){let e=await M.confirm({message:`Publish Docker images to a registry?`,initialValue:!1});isCancelled$1(e)&&(M.cancel(`Cancelled.`),process.exit(0)),C=e}return M.outro(`Configuration complete!`),{name:a,structure:c,stack:l,builder:u,useEslintPlugin:d,formatter:f,setupVitest:p,ci:m,setupRenovate:h,releaseStrategy:g,publishNpm:S,publishDocker:C,projectType:_,detectPackageTypes:v,targetDir:e}}function buildDefaultConfig(e,t){let{defaults:n,name:r}=detectProjectInfo(e);return{name:r,...n,...t.eslintPlugin!==void 0&&{useEslintPlugin:t.eslintPlugin},...t.noCi&&{ci:`none`},targetDir:e}}const Pt=/* @__PURE__ */ new Set([`ENOENT`,`EINVAL`,`ENOEXEC`]);function shouldRetryViaShim(e,t=process.platform){if(t!==`win32`||!(e instanceof Error)||!(`code`in e))return!1;let{code:n}=e;return typeof n==`string`&&Pt.has(n)}const Ft=ve.sync,It=ve;function runFormatter(e,t,n,r){let i=w.join(e,`node_modules`,`.bin`,t);if(!o(i))return;let a=[`--stdin-filepath`,n],s={cwd:e,input:r,encoding:`utf-8`},c=pe(i,a,s);if(shouldRetryViaShim(c.error)&&(c=Ft(i,a,s)),c.error||c.status!==0)return;let l=c.stdout;if(l)return l}function createContentFormatter(e){let t=/* @__PURE__ */ new Map;return(n,r)=>{let i=`${w.extname(n)}\0${r}`,a=t.get(i);if(a!==void 0)return a;let o=runFormatter(e.targetDir,e.formatter,n,r)??r;return t.set(i,o),o}}function formattedTemplate(e,t,n){return e.read(t)===n?n:e.format(t,n)}function isGeneratedTemplate(e,t,n){let r=e.read(t);return r===void 0?!1:r===n||r===e.format(t,n)}function isContained(e,t){let n=w.resolve(e,t);return n.startsWith(e+w.sep)||n===e}function assertContained(e,t){if(!isContained(e,t))throw new T(`Path traversal detected: ${t} resolves outside target directory`)}function normalizeEol(e){return e.replaceAll(`\r
|
|
7
7
|
`,`
|
|
8
8
|
`)}function contentEqual(e,t,n){if(e.endsWith(`.json`))try{return JSON.stringify(JSON.parse(t))===JSON.stringify(JSON.parse(n))}catch{return t===n}return normalizeEol(t)===normalizeEol(n)}function fileExists(e,t){return o(w.join(e,t))}function listFiles(e,t){if(!isContained(e,t))return[];try{return h(w.join(e,t),{withFileTypes:!0}).filter(e=>e.isFile()).map(e=>e.name).toSorted()}catch{return[]}}function readLinkTarget(e,t){if(!isContained(e,t))return;let n=w.join(e,t);try{return l(n).isSymbolicLink()?g(n):void 0}catch{return}}function readFile(e,t){let n=w.join(e,t);if(o(n))return p(n,`utf-8`)}function readFileNormalized(e,t,n){let r=readFile(e,t);if(r!==void 0)return r.includes(`\r
|
|
9
|
-
`)&&n(),normalizeEol(r)}function writeFile(e,t,n){let r=w.join(e,t);u(w.dirname(r),{recursive:!0}),C(r,n)}function isArchivable(e){return!e.split(`/`).includes(`.tooling-archived`)}function archiveFile(e,t,n){if(!isArchivable(t))return;let r=p(w.join(e,t));writeFile(e,`.tooling-archived/${t}`,r),n.push(t)}function archiveBeforeRemove(e,t,n){if(!isArchivable(t))return;let r=w.join(e,t);if(o(r)){if(!b(r).isDirectory())archiveFile(e,t,n);else for(let i of h(r,{recursive:!0,encoding:`utf-8`})){let a=w.join(r,i);b(a).isDirectory()||archiveFile(e,w.join(t,i),n)}}}function createContext(e,t,n){let r=[],i=!1,markCrlf=()=>{i=!0},a=readFile(e.targetDir,`package.json`),s=createContentFormatter(e),c={config:e,targetDir:e.targetDir,format:s,packageJson:a?parsePackageJson(a):void 0,exists:t=>isContained(e.targetDir,t)?fileExists(e.targetDir,t):!1,read:t=>{if(isContained(e.targetDir,t))return readFileNormalized(e.targetDir,t,markCrlf)},write:(t,n)=>{assertContained(e.targetDir,t);let i=readFile(e.targetDir,t);i!==void 0&&!contentEqual(t,i,n)&&archiveFile(e.targetDir,t,r),writeFile(e.targetDir,t,n),t===`package.json`&&(c.packageJson=parsePackageJson(n))},remove:t=>{assertContained(e.targetDir,t);let n=w.join(e.targetDir,t);o(n)&&(archiveBeforeRemove(e.targetDir,t,r),y(n,{recursive:!0}))},list:t=>listFiles(e.targetDir,t),readLink:t=>readLinkTarget(e.targetDir,t),symlink:(t,n)=>{assertContained(e.targetDir,n),x(t,w.join(e.targetDir,n))},confirmOverwrite:t,...n===void 0?{}:{dockerDiscovery:n}};return{ctx:c,archivedFiles:r,sawCrlf:()=>i}}function createDryRunContext(e,t){let n=readFile(e.targetDir,`package.json`),r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,a=!1,markCrlf=()=>{a=!0},o=createContentFormatter(e),s={config:e,targetDir:e.targetDir,format:o,packageJson:n?parsePackageJson(n):void 0,exists:t=>i.has(t)||fileExists(e.targetDir,t),read:t=>i.get(t)??readFileNormalized(e.targetDir,t,markCrlf),write:(e,t)=>{r.set(e,t),i.set(e,t),e===`package.json`&&(s.packageJson=parsePackageJson(t))},remove:()=>{},list:t=>{let n=`${t}/`,r=[...i.keys()].filter(e=>e.startsWith(n)&&!e.slice(n.length).includes(`/`)).map(e=>e.slice(n.length));return[.../* @__PURE__ */ new Set([...listFiles(e.targetDir,t),...r])].toSorted()},readLink:t=>readLinkTarget(e.targetDir,t),symlink:()=>{},confirmOverwrite:async()=>`overwrite`,...t===void 0?{}:{dockerDiscovery:t}};return{ctx:s,pendingWrites:r,sawCrlf:()=>a}}const Lt=/^(?!\.\.?\/)[\w.-]+\/(?!\.\.?$)[\w.-]+$/u,Rt=N.strictObject({enforced:N.union([N.boolean(),N.array(N.string())]).optional().meta({description:`Which discovered pairs fail the build. true = all; an array names active dirs (e.g. ["docs/plans"]); default false = every violation is advisory.`}),dirs:N.array(N.string()).optional().meta({description:`Extra active doc dirs beyond convention (e.g. ["docs/rfcs"]). Each retires into its own retired/ subdir.`}),staleDays:N.number().int().nonnegative().optional().meta({description:`Days before an unchanged active doc is flagged (default 30; 0 disables the rule).`}),staleEnforced:N.boolean().optional().meta({description:`Make the staleness rule fatal inside an enforced pair (default false: staleness is always advisory).`})}),zt={enabled:!0,enforced:!1,extraDirs:[],staleDays:30,staleEnforced:!1},Bt=N.object({docs:N.union([N.literal(!1),tolerantBlock(Rt)]).optional()});function resolveDocsConfigFromReader(e){let t=e.read(`.tooling.json`);if(t===void 0)return zt;let n;try{n=JSON.parse(t)}catch{return zt}let r=Bt.safeParse(n);if(!r.success)return zt;let i=r.data.docs;return i===!1?{...zt,enabled:!1}:i===void 0?zt:{enabled:!0,enforced:i.enforced??!1,extraDirs:i.dirs??[],staleDays:i.staleDays??30,staleEnforced:i.staleEnforced??!1}}function resolveDocsConfig(e){return resolveDocsConfigFromReader({read:t=>{let n=w.join(e,t);if(o(n))try{return p(n,`utf-8`)}catch{return}}})}const B=`.tooling.json`,Vt=N.strictObject({command:N.array(N.string()).nonempty().optional().meta({description:`argv passed directly to the child process (no shell interpolation), e.g. ["pnpm","build"]`}),file:N.string().optional().meta({description:`Path to the single asset file to upload, relative to the project root. Exactly one of file and files`}),files:N.array(N.string()).nonempty().optional().meta({description:`Glob patterns; every match is uploaded under its basename, after the entry's build runs. Exactly one of file and files`}),name:N.string().optional().meta({description:`Asset name in the release (defaults to the file's basename; file only)`}),package:N.string().optional().meta({description:"Workspace package this asset belongs to: the build, its version stamp and its uploads run once per release of that package. When `snapshot` is set in a monorepo, repo:sync requires every releaseAssets entry to name one"})}),Ht=N.strictObject({file:N.string().meta({description:`Path to the file whose version line release:assets stamps, relative to the project root`}),prefix:N.string().min(1).meta({description:`Literal string (never a pattern) the target line must start with. Not a regex -- read the output line straight off prefix + version + suffix`}),suffix:N.string().optional().meta({description:`Literal string (never a pattern) the target line must end with (default: none)`}),package:N.string().optional().meta({description:`Workspace package whose release version this stamp carries; the stamp runs with each release of that package. Omitted: the root package's version, as before`})}),Ut=N.strictObject({preid:N.string().regex(/^[a-z][a-z0-9]*$/).meta({description:"Prerelease identifier the snapshot versions carry, e.g. `alpha` in `1.2.6-alpha.42`"}),keep:N.number().int().min(1).optional().meta({description:`How many snapshot releases to keep per package before the oldest are pruned (default: 3)`}),packages:N.array(N.string()).nonempty().optional().meta({description:`Workspace package names to snapshot. Required in a monorepo; in a single-package repo the root package is the default`})}),Wt=N.strictObject({dispatchRepo:N.string().meta({description:`Target repository (owner/repo) whose workflow the release dispatches to trigger a deploy`}),stack:N.string().optional().meta({description:"Deploy stack name passed as the `stack` input (default: package name, '-' -> '_')"}),workflow:N.string().optional().meta({description:`Workflow filename or ID to dispatch in the target repo (default: 'deploy.yml')`}),ref:N.string().optional().meta({description:`Git ref to dispatch the workflow on (default: 'main')`})}),Gt={class:N.array(N.enum([`human-decision`,`pre-existing`,`nit`])).nonempty().optional().meta({description:`Match when the finding's class is any of these. Only human-decision findings become issues today, so this matcher exists for a class a later change files as one; it is declared now so a rule using it does not need the schema to change under it.`}),phase:N.array(N.string().min(1)).nonempty().optional().meta({description:`Match when the phase of the run that filed the finding is any of these (review, spec, plan, implement, ...). Distinguishes, for example, a finding filed by spec work against a docs-only pull request from one a review raised on the code.`}),mentions:N.array(N.string().min(1)).nonempty().optional().meta({description:`Match when the finding's title or body prose contains any of these. A plain string is a case-insensitive substring; a pattern written /.../flags is a regular expression. A string written literal:<text> is the substring <text>, which is how to name a path such as /src/utils that would otherwise read as a regular expression. This is how a rule looks at which files a finding concerns: a finding about health-baseline.json says so in its text.`}),prLabels:N.array(N.string().min(1)).nonempty().optional().meta({description:`Match when the pull request carries any of these labels (from the claim snapshot).`})},Kt=/^\/(.+)\/([a-z]*)$/su,qt=`literal:`;function compileMentionPattern(e){if(e.startsWith(qt))return e.length===8?{ok:!1,error:`it has no text after the literal: prefix`}:{ok:!0,regex:null};let t=Kt.exec(e);if(!t)return{ok:!0,regex:null};try{return{ok:!0,regex:new RegExp(t[1],t[2])}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function checkMentionPatterns(e,t){for(let[n,r]of(e.mentions??[]).entries()){let e=compileMentionPattern(r);e.ok||t.addIssue({code:`custom`,path:[`mentions`,n],message:r.startsWith(qt)?`"${r}" is not a valid mention: ${e.error}`:`"${r}" is not a valid /.../flags regular expression: ${e.error}`})}}const Jt=N.strictObject(Gt).superRefine(checkMentionPatterns),Yt=N.strictObject({when:Jt.optional().meta({description:`The clause this rule matches on -- a conjunction of optional matchers, all of which must match. An absent clause matches every finding; a matcher that is present may not be empty.`}),hold:N.boolean().meta({description:`What this rule decides: true withholds the pull request from unattended merging, false lets it through.`})}),Xt=N.strictObject({rules:N.array(Yt).default([]).meta({description:"Ordered rules; the first whose `when` matches decides, and no match falls through to `default`."}),default:N.boolean().default(!0).meta({description:`What to do with a finding no rule matched (default true -- hold). Failing closed is the deliberate shipped default: an unwanted hold costs one tap to answer the finding, while an unwanted pass is the problem the gate exists to prevent.`})}),Zt=N.strictObject({enabled:N.boolean().optional().meta({description:`Whether the agent's lint-warning sweep may open pull requests in this repo (default: on). false disarms it; the repo is then never cloned or measured by it.`}),minWarnings:N.number().int().nonnegative().optional().meta({description:`How many oxlint warnings the default branch must carry before the sweep opens a pull request (default 5). Below the floor the warn marker on checks:run is the whole response.`}),cooldownDays:N.number().int().nonnegative().optional().meta({description:`Days after a lint-sweep pull request merged or closed before the sweep may open another (default 7): a merged sweep whose declined warnings survive must not re-file them the next morning.`}),compatIssues:N.boolean().optional().meta({description:`Whether the sweep splits expired @compat warnings out of its plan and files one issue per expired id (default: on). false keeps them in the bulk plan with the other warnings.`})}),Qt=N.strictObject({browseHosts:N.array(N.string().min(1)).optional().meta({description:"Host patterns or path patterns this repo's agent containers ask to fetch from, on top of the hosts every run needs: an exact host (`fastdl.mongodb.org`), a wildcard over its leftmost label (`*.example.com`), or a path under one exact host (`raw.githubusercontent.com/owner/repo/`). No ports. This list is a request the deployment grants, not an opening: its grant mode decides whether a default branch's requests take effect on their own, an admin can refuse a host for this repo, and a host the product or the deployment known-denies is never opened whatever the declaration or the verdict says. A host the deployment has narrowed to its path patterns never takes a host-wide request automatically: that one waits for an admin, while a path pattern under it is granted as any other request. What is granted joins the browse lane, which serves GET and HEAD only."})}),$t=N.strictObject({enabled:N.boolean().optional().meta({description:"The repo's explicit consent to the agent (default false). Only `true`, read from the repo's **default branch**, lets the agent work the repo: claim units, run sweeps, recover orphans, merge, act on a chat proposal or start a new spec. A missing key, `false`, a missing `.tooling.json` or a read that fails all mean not enabled, and the answer is re-read within about a minute. Every other `agent.*` key below has no effect without this one; `repo:sync` warns when the block sets one of them and this key is not `true`. Where this is `true`, `repo:sync` also installs `@bensandee/agent-cli`. `pnpm exec bst setup:agent` sets it to true and runs the sync. Provisioning the agent's labels is not consent, and is never gated by this key."}),autonomy:N.boolean().optional().meta({description:"Retired and ignored -- it armed neither the advance rung nor the sweeps it once did. Advance is now the unit's own `agent-flags/advance` or `agent-flags/autopilot` label, and the trunk-red detector and world-changed retrigger sweep read `agent.trunkRed`. The key is still accepted so an existing config keeps syncing; the agent warns once per launch for a repo that still sets it."}),trunkRed:N.boolean().optional().meta({description:`Whether this repo's trunk-red detector and world-changed retrigger sweep run (default: on). The detector files a tracking issue when the default branch's combined status settles red and labels it agent/spec, and closes that issue with a comment if the branch recovers on its own before a human acts on it. The retrigger sweep re-queues a pull request labelled agent-flags/autopilot parked at a -stuck or -failed terminal when the fact its park recorded stops being true (the default branch went green, or moved past a conflicted base). A missing key means on; false disarms both.`}),preRunRebase:N.boolean().optional().meta({description:`Merge the current default branch into the work branch before the container starts (default true) -- for an implement (execute) run, and for a spec or plan rerun on an existing branch. A clean merge or an already-up-to-date branch runs the container as is; a conflicting merge is aborted, recorded on the run's status comment, and the run proceeds on the un-synced branch -- a conflict, timeout or failed merge never fails the run, for any phase. Only the execute phase keeps the two-strike rule: two consecutive conflicting attempts hand the unit to agent/repair before any container runs, while a docs run just tries again on its next slice. Set false to skip the attempt entirely for this repo, in every phase: no fetch, no merge, no abort, and the branch is worked exactly as cloned.`}),backlog:N.boolean().optional().meta({description:`Whether the agent may self-trigger backlog runs consuming this repo's .agent/findings/ ledger (default: on wherever the ledger exists, which only happens in a repo whose own review loop wrote it). A backlog run opens a pull request that fixes or refutes the pending findings; false disarms it, leaving the ledger to accumulate for a human. A run starts only once at least three findings are pending or one is older than seven days.`}),lintSweep:Zt.optional().meta({description:`The lint-warning sweep: a periodic agent job that measures this repo's oxlint warnings on its default branch in a container and, past minWarnings, opens a pull request carrying a generated plan for an agent/implement run to work off. Expired @compat warnings leave that plan and each get their own issue instead (see compatIssues).`}),openDocs:N.boolean().optional().meta({description:"Whether the agent reads this repo's open specs and plans on its default branch and classifies each one's next phase for the control panel's Inbox (default: on). On unless `false`: the sweep is advice only -- it writes nothing to this repo or the forge, and the only write a row can cause is an operator's click. `false` skips the repo in the sweep entirely, so it costs no classifier runs and contributes no rows."}),priority:N.record(N.string(),N.enum([`critical`,`high`,`normal`,`low`])).optional().meta({description:`Map this repo's own issue-label names onto the agent's four priority levels, e.g. {"P1": "critical", "P4": "low"}. The map UNIONS with the built-in priority/<level> names rather than replacing them, and the agent does not create aliased labels -- the repo owns names the agent did not choose. Priority affects claim order only: it never changes a run's model, effort, or any budget.`}),triageAnalysis:N.boolean().optional().meta({description:`Whether the agent may route its own agent-note/human-triage-needed issues through the agent/analyze stage (default: off). Unlike agent.backlog, which defaults on, this defaults off: a backlog run batches every pending finding into one container, while triage routing spends one container per issue -- arming it is the reversible direction, not disarming it.`}),egress:Qt.optional().meta({description:"Extra egress hosts this repo's agent containers ask to reach -- a request the deployment grants, not an opening of a host. `browseHosts` joins the agent's browse lane (GET and HEAD only) on top of the hosts every run needs; the passthrough lane stays agent-owned. Each entry is a host pattern -- an exact host or a *.host wildcard, never a port. Read from the repo's DEFAULT BRANCH, never off a pull request's own tree, so a run can never widen its own egress: under the default `auto` grant mode the request takes effect on the first container started after a human merges it, and under `approve` it waits for an admin's grant for this repo. A host the product or the deployment known-denies is never opened, whatever the declaration or the verdict says. An entry whose pattern the agent cannot parse refuses the run rather than being dropped. Changing this block holds the pull request from automerge."}),findingHolds:Xt.optional().meta({description:"Which of a pull request's linked open findings withhold its unattended merge. `rules` is ordered and the first `when` that matches decides; no match falls through to `default`; an absent block is { rules: [], default: true }, so every open linked finding holds by default. Read off the repo's DEFAULT BRANCH, never off the pull request's own tree -- a pull request cannot edit the rule deciding whether it is held. In a `mentions` entry a /.../flags pattern is a regular expression, a literal:<text> pattern is the substring <text> (how to name a path such as /src/utils), and anything else is a case-insensitive substring."}),chatIssueRepos:N.array(N.string().regex(Lt)).optional().meta({description:"Repositories with a DIFFERENT owner that a control-panel chat from this repository may file an issue in, each one a full `owner/name`, never a wildcard. A repository with the same owner needs no entry, and an entry grants nothing on its own: the target must have enabled the agent too. Read from the repo's DEFAULT BRANCH at the moment a card is applied, so a pull request cannot widen the reach of its own chat. Like every other `agent.*` key, this has no effect unless `agent.enabled` is true."}),ciOnlySteps:N.array(N.string().regex(/^[\w:*?.\-[\]{}!,]+$/)).optional().meta({description:"Step names or globs in `checks:run --skip` syntax that agent runs leave to CI, for example [\"docker:check\"]. Separate from `checks.skip`, which drops a step in CI too: here CI still runs the step and its status still gates the merge. Read from the repo's DEFAULT BRANCH only, never off the pull request's own tree, so a pull request cannot widen its own skip list. The agent merges such a pull request only on green CI, because the gate no longer measures these steps. Like every other `agent.*` key, this has no effect unless `agent.enabled` is true."}),localVerify:N.boolean().optional().meta({description:"Keep an agent run's check gate in the agent's own sandboxed verify container instead of measuring it on this repo's forge CI. `true` is the local verify; leaving the key out is the other answer, so the agent waits for the CI run of the commit it pushed and reads its `checks:run` job log, falling back to the local verify whenever CI cannot stand in. Read from the repo's DEFAULT BRANCH only, never off the pull request's own tree, so a pull request cannot choose the gate that measures it. Like every other `agent.*` key, this has no effect unless `agent.enabled` is true."})}),en=N.object({...$t.shape,lintSweep:tolerantBlock(Zt).optional(),findingHolds:N.unknown().optional(),egress:N.unknown().optional(),chatIssueRepos:N.unknown().optional()}),tn=N.strictObject({mergedDays:N.number().int().nonnegative().optional().meta({description:`Days after a work branch's PR merged before bst branch:prune deletes it (default 7). Zero is valid on purpose (an explicit 'delete everything merged already'), matching the --merged-days CLI flag's contract.`}),backupDays:N.number().int().nonnegative().optional().meta({description:`Days before bst branch:prune deletes an agent/(repair|rebase|failover)-backup/* ref whose parent branch has no merged PR to key on (default 30). Deliberately longer than mergedDays: a backup ref may be the only surviving copy of the work it holds. Zero is valid on purpose, matching the --backup-days CLI flag's contract.`}),exclude:N.array(N.string()).optional().meta({description:`Branch-name globs added to bst branch:prune's built-in never-touch list (main, changeset-release/*, renovate/*, bst/coverage-metrics, bst/health-metrics, bst/egress-metrics, anything with an open PR or protected). Additive only -- there is no key that removes a built-in entry.`})}),nn=N.strictObject({assignees:N.array(N.string().min(1)).optional().meta({description:"The repo's default reviewer(s) for issues opened by `bst issue:create` -- assigned when the invocation names no --assignee and no --repo. An explicit --assignee replaces this default rather than adding to it; --no-assignee opens an issue deliberately unassigned."})}),rn=N.strictObject({$schema:N.string().optional().meta({description:`JSON Schema reference (ignored by tooling)`}),structure:N.enum([`single`,`monorepo`]).optional().meta({description:`Project structure`}),useEslintPlugin:N.boolean().optional().meta({description:`Include @bensandee/eslint-plugin oxlint plugin`}),formatter:N.enum([`oxfmt`,`prettier`]).optional().meta({description:`Formatter choice`}),setupVitest:N.boolean().optional().meta({description:`Generate vitest config and example test`}),ci:N.enum([`github`,`forgejo`,`none`]).optional().meta({description:`CI platform`}),setupRenovate:N.boolean().optional().meta({description:`Generate Renovate config`}),releaseStrategy:N.enum([`release-it`,`simple`,`changesets`,`none`]).optional().meta({description:`Release management strategy`}),publishNpm:N.boolean().optional().meta({description:`Publish packages to npm (opt-in)`}),publishDocker:N.boolean().optional().meta({description:`Publish Docker images to a registry (opt-in)`}),projectType:N.enum([`default`,`node`,`react`,`library`]).optional().meta({description:`Project type (determines tsconfig base)`}),detectPackageTypes:N.boolean().optional().meta({description:`Auto-detect project types for monorepo packages`}),docker:Ct.optional().meta({description:`Docker image overrides, keyed by a package directory or a discovered image name (any field may be omitted to fall back to convention or discovery)`}),dockerCheck:N.union([N.literal(!1),xt]).optional().meta({description:`Docker health check configuration or false to disable`}),registryHost:N.string().optional().meta({description:`Docker registry hostname (e.g. ghcr.io, code.example.com)`}),registryNamespace:N.string().optional().meta({description:`Docker registry namespace (e.g. ghcr.io/myorg, code.example.com/myorg)`}),releaseAssets:N.array(Vt).optional().meta({description:`Custom assets to build and upload to the release`}),versionStamp:N.array(Ht).optional().meta({description:`Files release:assets stamps with the release version before building assets, and verifies afterward. For a repo whose released artifact carries its version somewhere other than package.json (e.g. a WordPress theme's style.css Version: header). Fails loudly when a file's prefix/suffix does not match exactly one line.`}),snapshot:Ut.optional().meta({description:"Snapshot channel: a push to the default branch that cuts no real release gets a prerelease <version>-<preid>.<build> per listed package, built with the release-assets machinery and uploaded as a prerelease, pruning all but the newest `keep` per package."}),postReleaseHook:N.string().optional().meta({description:`Override the post-release hook command (default: POST to POST_RELEASE_HOOK_URL with HMAC-SHA256 auth)`}),postReleaseHookSecrets:N.array(N.string()).optional().meta({description:`Additional secret names to inject as env vars in the post-release hook step (e.g. ['WEBHOOK_SECRET'])`}),coverage:N.union([N.literal(!1),gt]).optional().meta({description:`Coverage tracking configuration. Set to false to disable; omit for default-on (when a vitest config is present).`}),health:pt.optional().meta({description:`Codebase-health gate configuration. Opt-in: set enabled true to gate structural metrics (crowded directories, circular deps, fan-in/out) against health-baseline.json.`}),egress:_t.optional().meta({description:`Egress-audit history configuration, consumed by the bst-agent egress:* commands. There is no enabled key: egress:summary and egress:check read the transcripts root unconditionally, so history: 'none' is the only off-switch, and it disables egress:record alone.`}),chars:z.optional().meta({description:`Character gate (bst chars:check) configuration. On by default: the gate scans tracked text files for LLM-tell punctuation and invisible or deceptive characters, and passes letters in any language. Set enabled false to opt out.`}),ascii:z.optional().meta({description:`Deprecated alias of chars, read until 2026-12-15`}),docs:N.union([N.literal(!1),Rt]).optional().meta({description:"Plan/spec lifecycle gate (`bst docs:check`). Overrides only -- dirs are discovered by convention. Set to false to disable. Violations are advisory until a pair is named in `enforced`."}),deploy:Wt.optional().meta({description:"Generate a deploy-dispatch step in the release workflow that triggers a workflow_dispatch event in another repo after a successful release. The resolved release token must have rights on `dispatchRepo`."}),pnpmWorkspace:N.literal(!1).optional().meta({description:`Set to false to opt out of pnpm-workspace.yaml management (skips both generation and the repo:sync --check validation).`}),defaultBranch:Dt.optional().meta({description:"Repository default branch name. Drives the generated CI `on.push` trigger and every default-branch gate in `ci.yml` and `release.yml`, the release path (`release:changesets`, the version PR, `release:trigger`) and `checks:run`'s coverage gate. Generated output uses 'main' when unset; `checks:run` still falls back to `origin/HEAD`. Must be a plain branch name: ASCII letters, digits, '.', '_', '-' and '/', with no leading 'refs/'."}),unmanagedDevDependencies:yt.optional().meta({description:`devDependency names repo:sync must never add or re-pin. Escape hatch for holding a tooling-managed dep (oxlint, vitest, knip, ...) at a deliberately off-canonical version; without it, repo:sync raises any managed devDep whose version has drifted below the canonical pin.`}),stack:vt.optional().meta({description:`Whether the repo has TS/JS source. Detected from source evidence; TypeScript is never inferred from absence. Setting this key pins its value, even one that equals detection, and repo:sync keeps it until the key is deleted.`}),builder:N.enum([`tsdown`,`vite`,`custom`,`none`]).optional().meta({description:`What compiles the project. Detected from the package.json build script, then config-file presence. Setting this key pins its value, even one that equals detection, and repo:sync keeps it until the key is deleted.`}),checks:ht.optional().meta({description:`Check-pipeline overrides: extra steps to add, and steps to skip (unioned with CI defaults).`}),lint:mt.optional().meta({description:`bst lint:types (the type-aware oxlint gate) overrides. See lint.strictTypeAware.`}),agent:$t.optional().meta({description:`agent:start behaviour overrides. Opt-in: agent.enabled is the consent gate -- every other key in the block does nothing without it.`}),branchPrune:tn.optional().meta({description:`bst branch:prune overrides: mergedDays/backupDays windows, and extra never-touch exclusions layered on top of the hard-coded list.`}),issues:nn.optional().meta({description:"Repo-level issue policy -- currently just the default reviewer(s) `bst issue:create` assigns. The natural home for any future issue-policy key."})}),an=N.object({...rn.shape,defaultBranch:N.string().optional(),docker:wt.optional(),dockerCheck:N.union([N.literal(!1),Tt]).optional(),coverage:N.union([N.literal(!1),tolerantBlock(gt)]).optional(),health:tolerantBlock(pt).optional(),chars:tolerantBlock(z).optional(),ascii:tolerantBlock(z).optional(),docs:N.union([N.literal(!1),tolerantBlock(Rt)]).optional(),deploy:tolerantBlock(Wt).optional(),checks:tolerantBlock(ht).optional(),lint:tolerantBlock(mt).optional(),agent:en.optional(),branchPrune:tolerantBlock(tn).optional(),releaseAssets:N.array(tolerantBlock(Vt)).optional(),versionStamp:N.array(tolerantBlock(Ht)).optional(),snapshot:tolerantBlock(Ut).optional(),issues:tolerantBlock(nn).optional(),egress:tolerantBlock(_t).optional()});function readConfigFile(e){let t=w.join(e,B);if(o(t))return{raw:p(t,`utf-8`),displayPath:w.relative(process.cwd(),t)||t}}function parseConfigFile(e,t){let n;try{n=JSON.parse(e.raw)}catch(t){throw new T(`Could not parse ${e.displayPath} as JSON: ${O(t)}`)}let r=t.safeParse(n,{reportInput:!0});if(!r.success){let t=r.error.issues.flatMap(e=>formatIssue$1(e).split(`
|
|
9
|
+
`)&&n(),normalizeEol(r)}function writeFile(e,t,n){let r=w.join(e,t);u(w.dirname(r),{recursive:!0}),C(r,n)}function isArchivable(e){return!e.split(`/`).includes(`.tooling-archived`)}function archiveFile(e,t,n){if(!isArchivable(t))return;let r=p(w.join(e,t));writeFile(e,`.tooling-archived/${t}`,r),n.push(t)}function archiveBeforeRemove(e,t,n){if(!isArchivable(t))return;let r=w.join(e,t);if(o(r)){if(!b(r).isDirectory())archiveFile(e,t,n);else for(let i of h(r,{recursive:!0,encoding:`utf-8`})){let a=w.join(r,i);b(a).isDirectory()||archiveFile(e,w.join(t,i),n)}}}function createContext(e,t,n){let r=[],i=!1,markCrlf=()=>{i=!0},a=readFile(e.targetDir,`package.json`),s=createContentFormatter(e),c={config:e,targetDir:e.targetDir,format:s,packageJson:a?parsePackageJson(a):void 0,exists:t=>isContained(e.targetDir,t)?fileExists(e.targetDir,t):!1,read:t=>{if(isContained(e.targetDir,t))return readFileNormalized(e.targetDir,t,markCrlf)},write:(t,n)=>{assertContained(e.targetDir,t);let i=readFile(e.targetDir,t);i!==void 0&&!contentEqual(t,i,n)&&archiveFile(e.targetDir,t,r),writeFile(e.targetDir,t,n),t===`package.json`&&(c.packageJson=parsePackageJson(n))},remove:t=>{assertContained(e.targetDir,t);let n=w.join(e.targetDir,t);o(n)&&(archiveBeforeRemove(e.targetDir,t,r),y(n,{recursive:!0}))},list:t=>listFiles(e.targetDir,t),readLink:t=>readLinkTarget(e.targetDir,t),symlink:(t,n)=>{assertContained(e.targetDir,n),x(t,w.join(e.targetDir,n))},confirmOverwrite:t,...n===void 0?{}:{dockerDiscovery:n}};return{ctx:c,archivedFiles:r,sawCrlf:()=>i}}function createDryRunContext(e,t){let n=readFile(e.targetDir,`package.json`),r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,a=!1,markCrlf=()=>{a=!0},o=createContentFormatter(e),s={config:e,targetDir:e.targetDir,format:o,packageJson:n?parsePackageJson(n):void 0,exists:t=>i.has(t)||fileExists(e.targetDir,t),read:t=>i.get(t)??readFileNormalized(e.targetDir,t,markCrlf),write:(e,t)=>{r.set(e,t),i.set(e,t),e===`package.json`&&(s.packageJson=parsePackageJson(t))},remove:()=>{},list:t=>{let n=`${t}/`,r=[...i.keys()].filter(e=>e.startsWith(n)&&!e.slice(n.length).includes(`/`)).map(e=>e.slice(n.length));return[.../* @__PURE__ */ new Set([...listFiles(e.targetDir,t),...r])].toSorted()},readLink:t=>readLinkTarget(e.targetDir,t),symlink:()=>{},confirmOverwrite:async()=>`overwrite`,...t===void 0?{}:{dockerDiscovery:t}};return{ctx:s,pendingWrites:r,sawCrlf:()=>a}}const Lt=P.strictObject({enforced:P.union([P.boolean(),P.array(P.string())]).optional().meta({description:`Which discovered pairs fail the build. true = all; an array names active dirs (e.g. ["docs/plans"]); default false = every violation is advisory.`}),dirs:P.array(P.string()).optional().meta({description:`Extra active doc dirs beyond convention (e.g. ["docs/rfcs"]). Each retires into its own retired/ subdir.`}),staleDays:P.number().int().nonnegative().optional().meta({description:`Days before an unchanged active doc is flagged (default 30; 0 disables the rule).`}),staleEnforced:P.boolean().optional().meta({description:`Make the staleness rule fatal inside an enforced pair (default false: staleness is always advisory).`})}),Rt={enabled:!0,enforced:!1,extraDirs:[],staleDays:30,staleEnforced:!1},zt=P.object({docs:P.union([P.literal(!1),tolerantBlock(Lt)]).optional()});function resolveDocsConfigFromReader(e){let t=e.read(`.tooling.json`);if(t===void 0)return Rt;let n;try{n=JSON.parse(t)}catch{return Rt}let r=zt.safeParse(n);if(!r.success)return Rt;let i=r.data.docs;return i===!1?{...Rt,enabled:!1}:i===void 0?Rt:{enabled:!0,enforced:i.enforced??!1,extraDirs:i.dirs??[],staleDays:i.staleDays??30,staleEnforced:i.staleEnforced??!1}}function resolveDocsConfig(e){return resolveDocsConfigFromReader({read:t=>{let n=w.join(e,t);if(o(n))try{return p(n,`utf-8`)}catch{return}}})}const V=`.tooling.json`,Bt=P.strictObject({command:P.array(P.string()).nonempty().optional().meta({description:`argv passed directly to the child process (no shell interpolation), e.g. ["pnpm","build"]`}),file:P.string().optional().meta({description:`Path to the single asset file to upload, relative to the project root. Exactly one of file and files`}),files:P.array(P.string()).nonempty().optional().meta({description:`Glob patterns; every match is uploaded under its basename, after the entry's build runs. Exactly one of file and files`}),name:P.string().optional().meta({description:`Asset name in the release (defaults to the file's basename; file only)`}),package:P.string().optional().meta({description:"Workspace package this asset belongs to: the build, its version stamp and its uploads run once per release of that package. When `snapshot` is set in a monorepo, repo:sync requires every releaseAssets entry to name one"})}),Vt=P.strictObject({file:P.string().meta({description:`Path to the file whose version line release:assets stamps, relative to the project root`}),prefix:P.string().min(1).meta({description:`Literal string (never a pattern) the target line must start with. Not a regex -- read the output line straight off prefix + version + suffix`}),suffix:P.string().optional().meta({description:`Literal string (never a pattern) the target line must end with (default: none)`}),package:P.string().optional().meta({description:`Workspace package whose release version this stamp carries; the stamp runs with each release of that package. Omitted: the root package's version, as before`})}),Ht=P.strictObject({preid:P.string().regex(/^[a-z][a-z0-9]*$/).meta({description:"Prerelease identifier the snapshot versions carry, e.g. `alpha` in `1.2.6-alpha.42`"}),keep:P.number().int().min(1).optional().meta({description:`How many snapshot releases to keep per package before the oldest are pruned (default: 3)`}),packages:P.array(P.string()).nonempty().optional().meta({description:`Workspace package names to snapshot. Required in a monorepo; in a single-package repo the root package is the default`})}),Ut=P.strictObject({dispatchRepo:P.string().meta({description:`Target repository (owner/repo) whose workflow the release dispatches to trigger a deploy`}),stack:P.string().optional().meta({description:"Deploy stack name passed as the `stack` input (default: package name, '-' -> '_')"}),workflow:P.string().optional().meta({description:`Workflow filename or ID to dispatch in the target repo (default: 'deploy.yml')`}),ref:P.string().optional().meta({description:`Git ref to dispatch the workflow on (default: 'main')`})}),Wt=P.strictObject({enabled:P.boolean().optional().meta({description:`Whether the agent's lint-warning sweep may open pull requests in this repo (default: on). false disarms it; the repo is then never cloned or measured by it.`}),minWarnings:P.number().int().nonnegative().optional().meta({description:`How many oxlint warnings the default branch must carry before the sweep opens a pull request (default 5). Below the floor the warn marker on checks:run is the whole response.`}),cooldownDays:P.number().int().nonnegative().optional().meta({description:`Days after a lint-sweep pull request merged or closed before the sweep may open another (default 7): a merged sweep whose declined warnings survive must not re-file them the next morning.`}),compatIssues:P.boolean().optional().meta({description:`Whether the sweep splits expired @compat warnings out of its plan and files one issue per expired id (default: on). false keeps them in the bulk plan with the other warnings.`})}),Gt=P.strictObject({browseHosts:P.array(P.string().min(1)).optional().meta({description:"Host patterns or path patterns this repo's agent containers ask to fetch from, on top of the hosts every run needs: an exact host (`fastdl.mongodb.org`), a wildcard over its leftmost label (`*.example.com`), or a path under one exact host (`raw.githubusercontent.com/owner/repo/`). No ports. This list is a request the deployment grants, not an opening: its grant mode decides whether a default branch's requests take effect on their own, an admin can refuse a host for this repo, and a host the product or the deployment known-denies is never opened whatever the declaration or the verdict says. A host the deployment has narrowed to its path patterns never takes a host-wide request automatically: that one waits for an admin, while a path pattern under it is granted as any other request. What is granted joins the browse lane, which serves GET and HEAD only."})}),Kt=P.strictObject({enabled:P.boolean().optional().meta({description:"The repo's explicit consent to the agent (default false). Only `true`, read from the repo's **default branch**, lets the agent work the repo: claim units, run sweeps, recover orphans, merge, act on a chat proposal or start a new spec. A missing key, `false`, a missing `.tooling.json` or a read that fails all mean not enabled, and the answer is re-read within about a minute. Every other `agent.*` key below has no effect without this one; `repo:sync` warns when the block sets one of them and this key is not `true`. Where this is `true`, `repo:sync` also installs `@bensandee/agent-cli`. `pnpm exec bst setup:agent` sets it to true and runs the sync. Provisioning the agent's labels is not consent, and is never gated by this key."}),autonomy:P.boolean().optional().meta({description:"Retired and ignored -- it armed neither the advance rung nor the sweeps it once did. Advance is now the unit's own `agent-flags/advance` or `agent-flags/autopilot` label, and the trunk-red detector and world-changed retrigger sweep read `agent.trunkRed`. The key is still accepted so an existing config keeps syncing; the agent warns once per launch for a repo that still sets it."}),trunkRed:P.boolean().optional().meta({description:`Whether this repo's trunk-red detector and world-changed retrigger sweep run (default: on). The detector files a tracking issue when the default branch's combined status settles red and labels it agent/spec, and closes that issue with a comment if the branch recovers on its own before a human acts on it. The retrigger sweep re-queues a pull request labelled agent-flags/autopilot parked at a -stuck or -failed terminal when the fact its park recorded stops being true (the default branch went green, or moved past a conflicted base). A missing key means on; false disarms both.`}),preRunRebase:P.boolean().optional().meta({description:`Merge the current default branch into the work branch before the container starts (default true) -- for an implement (execute) run, and for a spec or plan rerun on an existing branch. A clean merge or an already-up-to-date branch runs the container as is; a conflicting merge is aborted, recorded on the run's status comment, and the run proceeds on the un-synced branch -- a conflict, timeout or failed merge never fails the run, for any phase. Only the execute phase keeps the two-strike rule: two consecutive conflicting attempts hand the unit to agent/repair before any container runs, while a docs run just tries again on its next slice. Set false to skip the attempt entirely for this repo, in every phase: no fetch, no merge, no abort, and the branch is worked exactly as cloned.`}),backlog:P.boolean().optional().meta({description:`Whether the agent may self-trigger backlog runs consuming this repo's .agent/findings/ ledger (default: on wherever the ledger exists, which only happens in a repo whose own review loop wrote it). A backlog run opens a pull request that fixes or refutes the pending findings; false disarms it, leaving the ledger to accumulate for a human. A run starts only once at least three findings are pending or one is older than seven days.`}),lintSweep:Wt.optional().meta({description:`The lint-warning sweep: a periodic agent job that measures this repo's oxlint warnings on its default branch in a container and, past minWarnings, opens a pull request carrying a generated plan for an agent/implement run to work off. Expired @compat warnings leave that plan and each get their own issue instead (see compatIssues).`}),openDocs:P.boolean().optional().meta({description:"Whether the agent reads this repo's open specs and plans on its default branch and classifies each one's next phase for the control panel's Inbox (default: on). On unless `false`: the sweep is advice only -- it writes nothing to this repo or the forge, and the only write a row can cause is an operator's click. `false` skips the repo in the sweep entirely, so it costs no classifier runs and contributes no rows."}),priority:P.record(P.string(),P.enum([`critical`,`high`,`normal`,`low`])).optional().meta({description:`Map this repo's own issue-label names onto the agent's four priority levels, e.g. {"P1": "critical", "P4": "low"}. The map UNIONS with the built-in priority/<level> names rather than replacing them, and the agent does not create aliased labels -- the repo owns names the agent did not choose. Priority affects claim order only: it never changes a run's model, effort, or any budget.`}),closure:P.record(P.string(),P.enum([`duplicate`,`obsolete`,`wontfix`,`invalid`])).optional().meta({description:`Map this repo's own issue-label names onto the agent's four closure reasons, e.g. {"Reviewed/Duplicate": "duplicate"}. The map UNIONS with the built-in closed/<reason> names rather than replacing them, and the agent does not create aliased labels -- the repo owns names the agent did not choose. A closure reason records why a unit was closed: no claim, sweep, or goal reads it.`}),triageAnalysis:P.boolean().optional().meta({description:`Whether the agent may route its own agent-note/human-triage-needed issues through the agent/analyze stage (default: off). Unlike agent.backlog, which defaults on, this defaults off: a backlog run batches every pending finding into one container, while triage routing spends one container per issue -- arming it is the reversible direction, not disarming it.`}),egress:Gt.optional().meta({description:"Extra egress hosts this repo's agent containers ask to reach -- a request the deployment grants, not an opening of a host. `browseHosts` joins the agent's browse lane (GET and HEAD only) on top of the hosts every run needs; the passthrough lane stays agent-owned. Each entry is a host pattern -- an exact host or a *.host wildcard, never a port. Read from the repo's DEFAULT BRANCH, never off a pull request's own tree, so a run can never widen its own egress: under the default `auto` grant mode the request takes effect on the first container started after a human merges it, and under `approve` it waits for an admin's grant for this repo. A host the product or the deployment known-denies is never opened, whatever the declaration or the verdict says. An entry whose pattern the agent cannot parse refuses the run rather than being dropped. Changing this block holds the pull request from automerge."}),findingHolds:P.unknown().optional().meta({description:`Retired and ignored -- every open finding linked to a pull request now holds its unattended merge, and no rule narrows that. The key is still accepted so an existing config keeps syncing; the agent warns once per launch for a repo that still sets it.`}),chatIssueRepos:P.unknown().optional().meta({description:`Retired and ignored -- a control-panel chat files an issue only in a repository with the same owner as the chat's repository, and this list no longer adds one with a different owner. The key is still accepted so an existing config keeps syncing; the agent warns once per launch for a repo that still sets it.`}),ciOnlySteps:P.array(P.string().regex(/^[\w:*?.\-[\]{}!,]+$/)).optional().meta({description:"Step names or globs in `checks:run --skip` syntax that agent runs leave to CI, for example [\"docker:check\"]. Separate from `checks.skip`, which drops a step in CI too: here CI still runs the step and its status still gates the merge. Read from the repo's DEFAULT BRANCH only, never off the pull request's own tree, so a pull request cannot widen its own skip list. The agent merges such a pull request only on green CI, because the gate no longer measures these steps. Like every other `agent.*` key, this has no effect unless `agent.enabled` is true."}),localVerify:P.boolean().optional().meta({description:"Keep an agent run's check gate in the agent's own sandboxed verify container instead of measuring it on this repo's forge CI. `true` is the local verify; leaving the key out is the other answer, so the agent waits for the CI run of the commit it pushed and reads its `checks:run` job log, falling back to the local verify whenever CI cannot stand in. Read from the repo's DEFAULT BRANCH only, never off the pull request's own tree, so a pull request cannot choose the gate that measures it. Like every other `agent.*` key, this has no effect unless `agent.enabled` is true."})}),qt=P.object({...Kt.shape,lintSweep:tolerantBlock(Wt).optional(),egress:P.unknown().optional()}),Jt=P.strictObject({mergedDays:P.number().int().nonnegative().optional().meta({description:`Days after a work branch's PR merged before bst branch:prune deletes it (default 7). Zero is valid on purpose (an explicit 'delete everything merged already'), matching the --merged-days CLI flag's contract.`}),backupDays:P.number().int().nonnegative().optional().meta({description:`Days before bst branch:prune deletes an agent/(repair|rebase|failover)-backup/* ref whose parent branch has no merged PR to key on (default 30). Deliberately longer than mergedDays: a backup ref may be the only surviving copy of the work it holds. Zero is valid on purpose, matching the --backup-days CLI flag's contract.`}),exclude:P.array(P.string()).optional().meta({description:`Branch-name globs added to bst branch:prune's built-in never-touch list (main, changeset-release/*, renovate/*, bst/coverage-metrics, bst/health-metrics, bst/egress-metrics, anything with an open PR or protected). Additive only -- there is no key that removes a built-in entry.`})}),Yt=P.strictObject({assignees:P.array(P.string().min(1)).optional().meta({description:"The repo's default reviewer(s) for issues opened by `bst issue:create` -- assigned when the invocation names no --assignee and no --repo. An explicit --assignee replaces this default rather than adding to it; --no-assignee opens an issue deliberately unassigned."})}),Xt=P.strictObject({$schema:P.string().optional().meta({description:`JSON Schema reference (ignored by tooling)`}),structure:P.enum([`single`,`monorepo`]).optional().meta({description:`Project structure`}),useEslintPlugin:P.boolean().optional().meta({description:`Include @bensandee/eslint-plugin oxlint plugin`}),formatter:P.enum([`oxfmt`,`prettier`]).optional().meta({description:`Formatter choice`}),setupVitest:P.boolean().optional().meta({description:`Generate vitest config and example test`}),ci:P.enum([`github`,`forgejo`,`none`]).optional().meta({description:`CI platform`}),setupRenovate:P.boolean().optional().meta({description:`Generate Renovate config`}),releaseStrategy:P.enum([`release-it`,`simple`,`changesets`,`none`]).optional().meta({description:`Release management strategy`}),publishNpm:P.boolean().optional().meta({description:`Publish packages to npm (opt-in)`}),publishDocker:P.boolean().optional().meta({description:`Publish Docker images to a registry (opt-in)`}),projectType:P.enum([`default`,`node`,`react`,`library`]).optional().meta({description:`Project type (determines tsconfig base)`}),detectPackageTypes:P.boolean().optional().meta({description:`Auto-detect project types for monorepo packages`}),docker:Ct.optional().meta({description:`Docker image overrides, keyed by a package directory or a discovered image name (any field may be omitted to fall back to convention or discovery)`}),dockerCheck:P.union([P.literal(!1),xt]).optional().meta({description:`Docker health check configuration or false to disable`}),registryHost:P.string().optional().meta({description:`Docker registry hostname (e.g. ghcr.io, code.example.com)`}),registryNamespace:P.string().optional().meta({description:`Docker registry namespace (e.g. ghcr.io/myorg, code.example.com/myorg)`}),releaseAssets:P.array(Bt).optional().meta({description:`Custom assets to build and upload to the release`}),versionStamp:P.array(Vt).optional().meta({description:`Files release:assets stamps with the release version before building assets, and verifies afterward. For a repo whose released artifact carries its version somewhere other than package.json (e.g. a WordPress theme's style.css Version: header). Fails loudly when a file's prefix/suffix does not match exactly one line.`}),snapshot:Ht.optional().meta({description:"Snapshot channel: a push to the default branch that cuts no real release gets a prerelease <version>-<preid>.<build> per listed package, built with the release-assets machinery and uploaded as a prerelease, pruning all but the newest `keep` per package."}),postReleaseHook:P.string().optional().meta({description:`Override the post-release hook command (default: POST to POST_RELEASE_HOOK_URL with HMAC-SHA256 auth)`}),postReleaseHookSecrets:P.array(P.string()).optional().meta({description:`Additional secret names to inject as env vars in the post-release hook step (e.g. ['WEBHOOK_SECRET'])`}),coverage:P.union([P.literal(!1),gt]).optional().meta({description:`Coverage tracking configuration. Set to false to disable; omit for default-on (when a vitest config is present).`}),mergePrep:P.literal(!1).optional().meta({description:"Prepare-for-merge routine: the `.agent/guides/merge-prep.md` guide and the `.claude/skills/prepare-for-merge/SKILL.md` skill. On by default; set to false to stop shipping both, and `repo:sync` then removes them while it still owns them. A file that has opted out is left alone: the guide by an ignore directive on its first line, the skill by one on its second, since line 1 of a skill must stay `---`."}),health:pt.optional().meta({description:`Codebase-health gate configuration. Opt-in: set enabled true to gate structural metrics (crowded directories, circular deps, fan-in/out) against health-baseline.json.`}),egress:_t.optional().meta({description:`Egress-audit history configuration, consumed by the bst-agent egress:* commands. There is no enabled key: egress:summary and egress:check read the transcripts root unconditionally, so history: 'none' is the only off-switch, and it disables egress:record alone.`}),chars:B.optional().meta({description:`Character gate (bst chars:check) configuration. On by default: the gate scans tracked text files for LLM-tell punctuation and invisible or deceptive characters, and passes letters in any language. Set enabled false to opt out.`}),ascii:B.optional().meta({description:`Deprecated alias of chars, read until 2026-12-15`}),docs:P.union([P.literal(!1),Lt]).optional().meta({description:"Plan/spec lifecycle gate (`bst docs:check`). Overrides only -- dirs are discovered by convention. Set to false to disable. Violations are advisory until a pair is named in `enforced`."}),deploy:Ut.optional().meta({description:"Generate a deploy-dispatch step in the release workflow that triggers a workflow_dispatch event in another repo after a successful release. The resolved release token must have rights on `dispatchRepo`."}),pnpmWorkspace:P.literal(!1).optional().meta({description:`Set to false to opt out of pnpm-workspace.yaml management (skips both generation and the repo:sync --check validation).`}),defaultBranch:Dt.optional().meta({description:"Repository default branch name. Drives the generated CI `on.push` trigger and every default-branch gate in `ci.yml` and `release.yml`, the release path (`release:changesets`, the version PR, `release:trigger`) and `checks:run`'s coverage gate. Generated output uses 'main' when unset; `checks:run` still falls back to `origin/HEAD`. Must be a plain branch name: ASCII letters, digits, '.', '_', '-' and '/', with no leading 'refs/'."}),unmanagedDevDependencies:yt.optional().meta({description:`devDependency names repo:sync must never add or re-pin. Escape hatch for holding a tooling-managed dep (oxlint, vitest, knip, ...) at a deliberately off-canonical version; without it, repo:sync raises any managed devDep whose version has drifted below the canonical pin.`}),stack:vt.optional().meta({description:`Whether the repo has TS/JS source. Detected from source evidence; TypeScript is never inferred from absence. Setting this key pins its value, even one that equals detection, and repo:sync keeps it until the key is deleted.`}),builder:P.enum([`tsdown`,`vite`,`custom`,`none`]).optional().meta({description:`What compiles the project. Detected from the package.json build script, then config-file presence. Setting this key pins its value, even one that equals detection, and repo:sync keeps it until the key is deleted.`}),checks:ht.optional().meta({description:`Check-pipeline overrides: extra steps to add, and steps to skip (unioned with CI defaults).`}),lint:mt.optional().meta({description:`bst lint:types (the type-aware oxlint gate) overrides. See lint.strictTypeAware.`}),agent:Kt.optional().meta({description:`agent:start behaviour overrides. Opt-in: agent.enabled is the consent gate -- every other key in the block does nothing without it.`}),branchPrune:Jt.optional().meta({description:`bst branch:prune overrides: mergedDays/backupDays windows, and extra never-touch exclusions layered on top of the hard-coded list.`}),issues:Yt.optional().meta({description:"Repo-level issue policy -- currently just the default reviewer(s) `bst issue:create` assigns. The natural home for any future issue-policy key."})}),Zt=P.object({...Xt.shape,defaultBranch:P.string().optional(),docker:wt.optional(),dockerCheck:P.union([P.literal(!1),Tt]).optional(),coverage:P.union([P.literal(!1),tolerantBlock(gt)]).optional(),health:tolerantBlock(pt).optional(),chars:tolerantBlock(B).optional(),ascii:tolerantBlock(B).optional(),docs:P.union([P.literal(!1),tolerantBlock(Lt)]).optional(),deploy:tolerantBlock(Ut).optional(),checks:tolerantBlock(ht).optional(),lint:tolerantBlock(mt).optional(),agent:qt.optional(),branchPrune:tolerantBlock(Jt).optional(),releaseAssets:P.array(tolerantBlock(Bt)).optional(),versionStamp:P.array(tolerantBlock(Vt)).optional(),snapshot:tolerantBlock(Ht).optional(),issues:tolerantBlock(Yt).optional(),egress:tolerantBlock(_t).optional()});function readConfigFile(e){let t=w.join(e,V);if(o(t))return{raw:p(t,`utf-8`),displayPath:w.relative(process.cwd(),t)||t}}function parseConfigFile(e,t){let n;try{n=JSON.parse(e.raw)}catch(t){throw new T(`Could not parse ${e.displayPath} as JSON: ${k(t)}`)}let r=t.safeParse(n,{reportInput:!0});if(!r.success){let t=r.error.issues.flatMap(e=>formatIssue$1(e).split(`
|
|
10
10
|
`)),n=t.length,i=n===1?`1 problem`:`${n} problems`;throw new T(`Invalid .tooling.json (${e.displayPath}) -- ${i}:\n${t.join(`
|
|
11
|
-
`)}`)}return r.data}function loadToolingConfig(e){let t=readConfigFile(e);if(t)return parseConfigFile(t,
|
|
12
|
-
`;return i!==void 0&&contentEqual(
|
|
13
|
-
`))}function parseComposeYaml(e){return Ee(e,{logLevel:`silent`})}const yn=N.looseObject({published:N.union([N.string(),N.number()]).optional(),target:N.union([N.string(),N.number()]).optional()}),bn=N.union([N.string(),N.looseObject({context:N.string().optional(),dockerfile:N.string().optional()})]),xn=N.looseObject({image:N.string().optional(),build:bn.optional(),profiles:N.array(N.string()).optional(),ports:N.array(N.unknown()).optional(),healthcheck:N.unknown().optional()}),Sn=N.looseObject({services:N.record(N.string(),xn).optional()});function startsUnderCheckProfile(e){return e.profiles.length===0||e.profiles.includes(`bst-check`)}function resolveBuildDockerfile(e,t){if(t===void 0)return;if(typeof t==`string`)return w.resolve(e,t,`Dockerfile`);let n=t.context??`.`,r=t.dockerfile??`Dockerfile`;return w.resolve(e,n,r)}function resolveBuildContext(e,t){if(t===void 0)return;if(typeof t==`string`)return w.resolve(e,t);let n=t.context??`.`;return w.resolve(e,n)}const Cn=[`target`,`args`,`secrets`,`platforms`,`additional_contexts`,`dockerfile_inline`];function hasUnreproducibleBuildKeys(e){return e===void 0||typeof e==`string`?!1:Cn.some(t=>e[t]!==void 0)}const wn=/^\$\{([A-Za-z_][A-Za-z0-9_]*)(?::?-(\d+))?\}$/;function parseHostPortSegment(e){let t=e.trim(),n=wn.exec(t);if(n?.[1]){let e=n[2];return{kind:`variable`,name:n[1],default:e?Number.parseInt(e,10):void 0}}let r=Number.parseInt(t,10);return Number.isNaN(r)?void 0:{kind:`literal`,port:r}}function parseContainerPortSegment(e){let t=Number.parseInt(e.trim(),10);return Number.isNaN(t)?void 0:t}function splitPortSegments(e){let t=[],n=0,r=0;for(let i=0;i<e.length;i++)e.startsWith("${",i)?(n++,i++):e[i]===`}`&&n>0?n--:e[i]===`:`&&n===0&&(t.push(e.slice(r,i)),r=i+1);if(n===0)return t.push(e.slice(r)),t}function parsePortString(e){let t=e.split(`/`)[0];if(!t)return;let n=splitPortSegments(t);if(n){if(n.length===2)return{hostPort:n[0]?parseHostPortSegment(n[0]):void 0,containerPort:n[1]?parseContainerPortSegment(n[1]):void 0};if(n.length===3)return{hostPort:n[1]?parseHostPortSegment(n[1]):void 0,containerPort:n[2]?parseContainerPortSegment(n[2]):void 0}}}function findHostPort(e){for(let t of e??[]){let e=extractPortMapping(t);if(!e)continue;let{hostPort:n,containerPort:r}=e;return n===void 0?{containerPort:r}:n.kind===`literal`?{hostPort:n.port,containerPort:r}:{portEnvVar:n.name,hostPort:n.default,containerPort:r}}return{}}function parseLongSyntaxTarget(e){if(typeof e==`number`)return e;if(typeof e==`string`)return parseContainerPortSegment(e)}function parseLongSyntaxPort(e){let t=yn.safeParse(e);if(!t.success)return;let{published:n,target:r}=t.data,i;return typeof n==`number`?i={kind:`literal`,port:n}:typeof n==`string`&&(i=parseHostPortSegment(n)),{hostPort:i,containerPort:parseLongSyntaxTarget(r)}}function extractPortMapping(e){let t=typeof e==`string`?parsePortString(e):parseLongSyntaxPort(e);if(t&&(t.hostPort!==void 0||t.containerPort!==void 0))return t}function parseComposeServiceSources(e,t){let n=/* @__PURE__ */ new Map;for(let{file:r,content:i}of t){let t;try{t=parseComposeYaml(i)}catch{F.debug(`compose file "${r}" failed to parse as YAML; skipping`);continue}let a=Sn.safeParse(t);if(!a.success)F.debug(`compose file "${r}" failed schema validation; skipping`);else if(a.data.services)for(let[t,i]of Object.entries(a.data.services)){let a=n.get(t),o=a?.hostPort,s=a?.portEnvVar,c=a?.containerPort;if(o===void 0&&s===void 0&&c===void 0){let e=findHostPort(i.ports);o=e.hostPort,s=e.portEnvVar,c=e.containerPort}let l=resolveBuildDockerfile(e,i.build),u=resolveBuildContext(e,i.build),d=[...a?.declaredIn??[],r],f=[...a?.profiles??[]];for(let e of i.profiles??[])f.includes(e)||f.push(e);let p=(a?.buildHasUnreproducibleKeys??!1)||hasUnreproducibleBuildKeys(i.build)||void 0;n.set(t,{name:t,image:i.image??a?.image,buildDockerfile:l??a?.buildDockerfile,buildContext:u??a?.buildContext,buildHasUnreproducibleKeys:p,hostPort:o,portEnvVar:s,containerPort:c,hasHealthcheck:(a?.hasHealthcheck??!1)||i.healthcheck!==void 0,declaredIn:d,profiles:f})}}return[...n.values()]}function parseComposeServices(e,t){let n=[];for(let r of t)try{let t=p(w.join(e,r),`utf-8`);n.push({file:r,content:t})}catch{continue}return parseComposeServiceSources(e,n)}function stripComposeVariables(e){return e.replace(/\$\{[^}]*\}/g,``)}function bareImageName(e){let t=stripComposeVariables(e),n=t.lastIndexOf(`/`),r=t.lastIndexOf(`:`);return(r>n?t.slice(0,r):t)||void 0}function roundTripImageName(e){if(e.includes("${")||e.includes(`@`))return;let t=e.lastIndexOf(`/`),n=e.lastIndexOf(`:`);return n>t?e.slice(n+1)===`latest`?e.slice(0,n):void 0:e}function imageRegistryHost(e){let t=e.indexOf(`/`);if(t===-1)return;let n=e.slice(0,t);if(n.includes(`.`)||n.includes(`:`)||n===`localhost`)return n}function extractComposeImageNames(e){let t=/* @__PURE__ */ new Set;for(let n of e)if(n.image){let e=bareImageName(n.image);e&&t.add(e)}return[...t]}function extractComposeBuildDockerfiles(e){let t=/* @__PURE__ */ new Set;for(let n of e)n.buildDockerfile&&t.add(n.buildDockerfile);return[...t]}const Tn=[`docker-compose.yaml`,`docker-compose.yml`,`compose.yaml`,`compose.yml`],En=[`.`,`docker`];function deriveCheckOverlayName(e){return e.replace(/\.(yaml|yml)$/,`.check.$1`)}function probeConventional(e,t){let n=[],r=[];for(let i of Tn){let a=e(w.join(t,i));a!==null&&(n.push(i),r.push({file:i,content:a}))}return{files:n,sources:r}}function readConfigured(e,t,n){let r=[],i=[];for(let a of n){let n=e(w.join(t,a));n===null?F.debug(`compose file "${a}" configured in ${t} does not exist; skipping`):(r.push(a),i.push({file:a,content:n}))}return{files:r,sources:i}}function withOverlay(e,t,n,r,i){let a=deriveCheckOverlayName(i);if(n.includes(a))return{composeDir:t,files:n,checkOverlay:a,sources:r};let o=e(w.join(t,a));return o===null?{composeDir:t,files:n,checkOverlay:void 0,sources:r}:{composeDir:t,files:n,checkOverlay:a,sources:[...r,{file:a,content:o}]}}function resolveComposeFileSet(e,t,n){if(n!==void 0&&n.length===0)return{composeDir:t,files:[],checkOverlay:void 0,sources:[]};for(let r of En){let i=w.join(t,r),a=probeConventional(e,i),o=a.files[0];if(o===void 0)continue;let{files:s,sources:c}=n===void 0?a:readConfigured(e,i,n);return withOverlay(e,i,s,c,o)}if(n===void 0)return{composeDir:t,files:[],checkOverlay:void 0,sources:[]};let{files:r,sources:i}=readConfigured(e,t,n);return{composeDir:t,files:r,checkOverlay:void 0,sources:i}}const Dn=6e5;function morePagesFollow(e,t,n,r){if(t===0)return!1;let i=e.headers.get(`x-total-count`)?.trim()??``,a=i===``?NaN:Number(i);return!Number.isSafeInteger(a)||a<0?t>=r:n<a}const On={attempts:5,baseDelayMs:250,maxDelayMs:2e3};function isTransientTransportError(e){return e instanceof TypeError||e instanceof DOMException&&(e.name===`TimeoutError`||e.name===`AbortError`)}function withTimeoutSignal(e,t){if(t<=0)return e;let n=AbortSignal.timeout(t);return e?.signal==null?{...e,signal:n}:{...e,signal:AbortSignal.any([e.signal,n])}}async function retryBackoff(e,t,n){if(t<=0)return;let r=Math.min(t*2**(e-1),n);await new Promise(e=>setTimeout(e,r))}async function retryOnTransient(e,t=On,n=null){let r;for(let i=1;i<=t.attempts;i++)try{return await e()}catch(e){if(n?.aborted||!isTransientTransportError(e))throw e;r=e,i<t.attempts&&await retryBackoff(i,t.baseDelayMs,t.maxDelayMs)}throw r}function fetchWithRetry(e,t=On,n=12e4){return(r,i,a)=>{let o=(i?.method??`GET`).toUpperCase(),s=o===`GET`||o===`HEAD`||a?.idempotent===!0,c=a?.timeoutMs??n,l=i?.signal??null,attempt=()=>e(r,withTimeoutSignal(i,c));return s?retryOnTransient(attempt,a?.attempts===void 0?t:{...t,attempts:a.attempts},l):attempt()}}const kn=67108864;function execCapture$2(e,t,n){try{return{status:0,stdout:M(e,t,{cwd:n.cwd,env:n.env?{...process.env,...n.env}:void 0,input:n.input,encoding:`utf-8`,stdio:[n.stdin??`pipe`,`pipe`,`pipe`],maxBuffer:kn}),stderr:``}}catch(e){if(isExecSyncError(e))return{status:e.status,stdout:e.stdout,stderr:e.stderr};if(n.keepPartialStdoutOnKill&&isKilledExecError(e)){let t=O(e),n=e.stderr.trim()===``?t:`${e.stderr}\n${t}`;return{status:1,stdout:e.stdout,stderr:n}}return{status:1,stdout:``,stderr:O(e),error:e}}}function isExecSyncError(e){return e instanceof Error&&`stdout`in e&&typeof e.stdout==`string`&&`stderr`in e&&typeof e.stderr==`string`&&`status`in e&&typeof e.status==`number`}function isKilledExecError(e){return e instanceof Error&&`stdout`in e&&typeof e.stdout==`string`&&`stderr`in e&&typeof e.stderr==`string`&&`signal`in e&&typeof e.signal==`string`}function captureSpawnOptions(e){return{cwd:e?.cwd,env:{...process.env,...e?.env},input:e?.input,timeout:e?.timeoutMs,killSignal:`SIGKILL`,maxBuffer:268435456,encoding:`utf-8`,stdio:[`pipe`,`pipe`,`pipe`]}}function execCaptureViaShim(e,t,n){let r=Ft(e,t,captureSpawnOptions(n)),i=r.stdout??``,a=r.stderr??``;return r.signal!==null&&r.signal!==void 0?{stdout:i,stderr:a,exitCode:124}:r.error?{stdout:i,stderr:O(r.error),exitCode:1}:{stdout:i,stderr:a,exitCode:r.status??1}}function execCapture$1(e,t,n){try{return{stdout:M(e,t,captureSpawnOptions(n)),stderr:``,exitCode:0}}catch(r){return isExecSyncError(r)?{stdout:r.stdout,stderr:r.stderr,exitCode:r.status}:isKilledExecError(r)?{stdout:r.stdout,stderr:r.stderr,exitCode:124}:shouldRetryViaShim(r)?execCaptureViaShim(e,t,n):{stdout:``,stderr:``,exitCode:1}}}function spawnStreamChild(e,t,n,r){let i=e?It(t,n,{cwd:r.cwd,env:{...process.env,...r.env},stdio:[`pipe`,`pipe`,`pipe`],signal:r.signal??void 0,killSignal:`SIGKILL`}):fe(t,n,{cwd:r.cwd,env:{...process.env,...r.env},stdio:[`pipe`,`pipe`,`pipe`],signal:r.signal??void 0,killSignal:`SIGKILL`}),{stdout:a,stderr:o,stdin:s}=i;if(a===null||o===null||s===null)throw new D(`Spawned child for ${commandLine(t,n)} is missing a piped stream`);return{child:i,stdoutStream:a,stderrStream:o,stdinStream:s}}const An=Symbol(`child closed`);async function writeStreamedStdin(e,t,n){let r=t[Symbol.asyncIterator]();try{for(;;){let t=await Promise.race([r.next(),n]);if(t===An)return;if(t.done===!0)break;e.write(t.value)}}catch{}finally{e.end(),await r.return?.().catch(()=>{})}}function execStreamCapture(e,t,n,r,i={}){let{onLine:a,onStderrLine:o}=i,{child:s,stdoutStream:c,stderrStream:l,stdinStream:u}=spawnStreamChild(e,t,n,r),d=``,f=``,p=``,m=``,h=new je(`utf8`),g=new je(`utf8`),_=!1,v=!1,y,b=r.timeoutMs===void 0?void 0:setTimeout(()=>{_=!0,s.kill(`SIGKILL`)},r.timeoutMs),stopTimeout=()=>{b&&clearTimeout(b)};c.on(`data`,e=>{let t=h.write(e);if(d+=t,!a)return;p+=t;let n=p.split(`
|
|
11
|
+
`)}`)}return r.data}function loadToolingConfig(e){let t=readConfigFile(e);if(t)return parseConfigFile(t,Zt)}function parseToolingConfigStrict(e,t){return parseConfigFile({raw:e,displayPath:t},Xt)}function loadToolingConfigStrict(e){let t=readConfigFile(e);if(!t)return;let n=parseToolingConfigStrict(t.raw,t.displayPath);return refuseRenamedCharsKey(n,t.displayPath),n}function refuseRenamedCharsKey(e,t){if(e.chars!==void 0&&e.ascii!==void 0)throw new T(`${t} sets both chars and ascii; rename ascii to chars`)}const Qt=[`structure`,`useEslintPlugin`,`formatter`,`stack`,`builder`,`setupVitest`,`ci`,`setupRenovate`,`releaseStrategy`,`publishNpm`,`publishDocker`,`projectType`,`detectPackageTypes`],$t=/* @__PURE__ */ new Set([`setupVitest`,`projectType`]),en=P.record(P.string(),P.unknown());function parseExistingConfig(e){if(e===void 0)return{};try{let t=en.safeParse(JSON.parse(e));if(t.success)return t.data}catch{}return{}}function pruneCharsDefaults(e){let t=en.safeParse(e);if(!t.success||t.data.enabled!==!0)return e;let n={};for(let[e,r]of Object.entries(t.data))e!==`enabled`&&(n[e]=r);if(Object.keys(n).length!==0)return n}function saveToolingConfig(e,t){let n={...computeDefaults(t.targetDir),projectType:resolveProjectType(detectProjectType(t.targetDir),t.structure,t.builder)},r=t.structure===`monorepo`,i=e.exists(V)?e.read(V):void 0,a=parseExistingConfig(i),o=new Set(Qt),s={$schema:`node_modules/@bensandee/tooling/tooling.schema.json`};for(let e of Qt)r&&$t.has(e)||(Object.hasOwn(a,e)&&a[e]===t[e]||t[e]!==n[e])&&(s[e]=t[e]);for(let[e,t]of Object.entries(a))if(!(e===`$schema`||o.has(e))){if(e===`chars`||e===`ascii`){let e=pruneCharsDefaults(t);if(e===void 0)continue;s.chars=e}else s[e]=t}let c=JSON.stringify(s,null,2)+`
|
|
12
|
+
`;return i!==void 0&&contentEqual(V,i,c)?{filePath:V,action:`skipped`,description:`Already up to date`}:(e.write(V,e.format(V,c)),{filePath:V,action:i?`updated`:`created`,description:`Saved tooling configuration`})}function mergeWithSavedConfig(e,t){let n=t.structure??e.structure,r=t.builder??e.builder;return{name:e.name,targetDir:e.targetDir,structure:n,useEslintPlugin:t.useEslintPlugin??e.useEslintPlugin,formatter:t.formatter??e.formatter,stack:t.stack??e.stack,builder:r,setupVitest:t.setupVitest??e.setupVitest,ci:t.ci??e.ci,setupRenovate:t.setupRenovate??e.setupRenovate,releaseStrategy:t.releaseStrategy??e.releaseStrategy,publishNpm:t.publishNpm??e.publishNpm,publishDocker:t.publishDocker??e.publishDocker,projectType:t.projectType??resolveProjectType(detectProjectType(e.targetDir),n,r),detectPackageTypes:t.detectPackageTypes??e.detectPackageTypes}}function resolveForgeToken(e){let t=forgeTokenFromEnv(process.env);if(!t)throw new T(`${e} needs a forge token -- set RELEASE_TOKEN (preferred) or FORGEJO_TOKEN.`);return t}function resolveSimpleReleaseToken(){let e=process.env.RELEASE_TOKEN?.trim();if(!e)throw new T(`RELEASE_TOKEN environment variable is required for release:simple. Create a PAT with write:repository (Forgejo) or contents: write (GitHub) scope on the target forge, store it as the RELEASE_TOKEN secret on your repo (or org), and expose it as env to this step.`);return e}function resolveConnectionCoordinates(e){return resolveForgejoCoordinates(process.env,()=>resolveOperationalRepoUrl(e))}function resolveConnection(e){let t=resolveForgejoConnection(process.env,()=>resolveOperationalRepoUrl(e));return t===null?{type:`github`}:{type:`forgejo`,conn:t}}function resolveOperationalRepo(e){let t=resolveOperationalRepoUrl(e);return t===null?null:parseGitUrl(t)}function resolveOperationalRepoUrl(e){return resolveRepoUrlFrom(()=>readOriginUrl(e),()=>readPackageRepositoryUrl(e))}function repositoryFromRemoteUrl(e){let t=normalizeGitUrl(e.trim());return t===null?null:parseGitUrl(t)?.repository??null}function parseRepositoryUrl(e){let t=readPackageRepositoryUrl(e);return t===null?null:parseGitUrl(t)}var ForgeAccessError=class extends T{};function authHeaders(e){return{Authorization:`token ${e.token}`}}function jsonHeaders(e){return{...authHeaders(e),"Content-Type":`application/json`}}function repoNotFoundMessage(e){return`Repository ${e.repository} not found (or the token cannot see it)`}function repoBase(e){return`${e.serverUrl}/api/v1/repos/${e.repository}`}function issuesBase(e){return`${repoBase(e)}/issues`}function issueNotFoundMessage(e,t){return`Issue #${String(t)} not found in ${e.repository}`}const tn=P.object({id:P.number(),name:P.string(),size:P.number(),created_at:P.string(),browser_download_url:P.string()}),nn=P.array(tn);function normalizeAttachment(e){return{id:e.id,name:e.name,size:e.size,createdAt:e.created_at,downloadUrl:e.browser_download_url}}async function responseBodyText(e){try{let t=await e.text(),n=t.length>500?t.slice(0,500)+`...`:t;return ae(n)}catch{return`(could not read response body)`}}const rn=P.union([P.object({message:P.literal(``)}),P.object({message:P.string(),url:P.string().regex(/\/api\/swagger$/)})]);function isForgejoGenericServerErrorBody(e){if(e===``)return!0;try{let t=JSON.parse(e);return rn.safeParse(t).success}catch{return!1}}const an=/\bdispatch\b/i;function forgejoErrorHint(e,t,n){let r=an.test(n.verb),i=n.resource??`the resource`;if(e===401||e===403)return`Forgejo rejected the token. It needs the scope required for "${n.verb}" on ${i}.`;if(e===404){let e=`"${i}" was not found on the server. Verify the name${n.ref?`, that it exists on ${n.ref}`:``}, and that the token can see it.`;return r?`${e} For dispatch, also confirm the workflow has an "on: workflow_dispatch:" trigger.`:e}if(e===400||e===422){let e=`Forgejo rejected the request payload for "${n.verb}". Check for missing or invalid fields.`;return r?`${e} For dispatch, common causes are a missing "on: workflow_dispatch:" trigger or a required input not being provided.`:e}if(e>=500&&e<600){if(isForgejoGenericServerErrorBody(t)){let e=n.ref?` on ${n.ref}`:``;return`Forgejo returned a generic server error. Most often this means the requested route is unavailable${r?` (e.g. "${i}" doesn't exist${e}, or the workflow lacks an "on: workflow_dispatch:" trigger)`:``}. Less commonly: the token lacks scope, or it is a server-side bug.`}return`Forgejo server error -- usually transient. Retry; if it persists, check the server logs.`}return``}async function forgejoErrorMessage(e,t){let n=await responseBodyText(e),r=forgejoErrorHint(e.status,n,t);return`Failed to ${t.verb} on Forgejo: ${String(e.status)} ${e.statusText}`+(r?`\nHint: ${r}`:``)+(n?`\nResponse: ${n}`:``)}async function throwForgejoFailure(e,t,n){if(e.status===404)throw new ForgeAccessError(n??await forgejoErrorMessage(e,t));let r=await forgejoErrorMessage(e,t);throw e.status===401||e.status===403?new ForgeAccessError(r):e.status===422?new T(`${r}\nForgejo rejected this as invalid (422) -- retrying with the same input cannot succeed (e.g. a nonexistent label or an assignee the repository will not accept).`):e.status===410?new T(`${r}\nForgejo returned 410 Gone -- issues are likely disabled on this repository; retrying will not help.`):new E(r)}P.array(P.object({name:P.string()}));const on=P.object({sha1:P.string()}),sn=/^[A-Za-z_][A-Za-z0-9_]*$/,cn=/^(FORGEJO_|GITEA_|GITHUB_|[0-9])/i;function isValidSecretName(e){return sn.test(e)&&!cn.test(e)}var OtpRequiredError=class extends E{};async function failureError(e,t){let n=await forgejoErrorMessage(e,t);return n.includes(`OTP`)?new OtpRequiredError(n):new E(n)}async function createAccessToken(e,t){let{serverUrl:n,username:r,password:i,tokenName:a,scopes:o,otp:s}=t,c=`${n}/api/v1/users/${encodeURIComponent(r)}/tokens`,l={Authorization:`Basic ${btoa(`${r}:${i}`)}`,"Content-Type":`application/json`};s&&(l[`X-Forgejo-OTP`]=s);let u=await e.fetch(c,{method:`POST`,headers:l,body:JSON.stringify({name:a,scopes:o})});if(!u.ok)throw await failureError(u,{verb:`create access token`,resource:r});let d=on.safeParse(await u.json());if(!d.success)throw new D(`Unexpected token response: ${d.error.message}`);return d.data.sha1}async function setActionSecret(e,t,n,r){let[i,a]=t.repository.split(`/`),o=`${t.serverUrl}/api/v1/repos/${i}/${a}/actions/secrets/${encodeURIComponent(n)}`,s=await e.fetch(o,{method:`PUT`,headers:{Authorization:`token ${t.token}`,"Content-Type":`application/json`},body:JSON.stringify({data:r})});if(!s.ok)throw new E(await forgejoErrorMessage(s,{verb:`set secret`,resource:n}))}async function setUserActionSecret(e,t){let{serverUrl:n,authorization:r,secretName:i,secretValue:a,otp:o}=t,s=`${n}/api/v1/user/actions/secrets/${encodeURIComponent(i)}`,c={Authorization:r,"Content-Type":`application/json`};o&&(c[`X-Forgejo-OTP`]=o);let l=await e.fetch(s,{method:`PUT`,headers:c,body:JSON.stringify({data:a})});if(!l.ok)throw await failureError(l,{verb:`set user secret`,resource:i})}const ln={"code.orangebikelabs.com":`OBL_REGISTRY`,"docker.io":`DOCKERHUB`,"index.docker.io":`DOCKERHUB`,"quay.io":`QUAY`,"ghcr.io":`GHCR`},un=`REGISTRY`;function sanitizeSecretBaseName(e){if(e===``)return un;if(isValidSecretName(e))return e;let t=`${un}_${e}`;return isValidSecretName(t)?t:un}function dockerSecretBaseName(e){return sanitizeSecretBaseName(ln[e]??e.toUpperCase().replace(/[^A-Z0-9]/g,`_`))}function dockerSecretNames(e){if(e===null)return{username:`REGISTRY_USERNAME`,password:`REGISTRY_PASSWORD`};let t=dockerSecretBaseName(e);return{username:`${t}_USERNAME`,password:`${t}_PASSWORD`}}function registryHostFromHostname(e){return e===`github.com`?`ghcr.io`:e}function resolveDockerRegistryHost(e){let t=loadRegistryHostOverride(e);if(t!==void 0&&t.length>0)return t;let n=resolveOperationalRepo(e);return n===null?null:registryHostFromHostname(n.hostname)}function loadRegistryHostOverride(e){try{return loadToolingConfig(e)?.registryHost}catch{return}}function escapeBakeTemplate(e){return e.replace(/\$\{/gu,()=>"$${").replace(/%\{/gu,()=>`%%{`)}function escapeBakeTemplateValues(e){let t={};for(let[n,r]of Object.entries(e))t[n]=escapeBakeTemplate(r);return t}function uniqueTargetName(e,t){let n=t.replace(/[^A-Za-z0-9_-]/gu,`_`),candidate=e=>e===1?n:`${n}_${String(e)}`,r=1;for(;e.has(candidate(r));)r++;return candidate(r)}function buildBakeDefinition(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Set,r=[];for(let i of e){let e=uniqueTargetName(n,i.imageName);n.add(e),t.set(i.imageName,e),r.push({image:i,target:e})}let i={},a=[];for(let{image:e,target:n}of r){let r={context:escapeBakeTemplate(e.context),dockerfile:escapeBakeTemplate(e.dockerfile),tags:[escapeBakeTemplate(`${e.imageName}:latest`)],args:escapeBakeTemplateValues(e.args),labels:escapeBakeTemplateValues(e.labels)};if(e.bases.length>0){let n={};for(let r of e.bases){let i=t.get(r);if(i===void 0)throw new D(`Docker bake definition: image "${e.imageName}" FROMs "${r}", which is not in the set of images being built`);n[r]=`target:${i}`}r.contexts=n}i[n]=r,a.push(n)}return{group:{default:{targets:a}},target:i}}const dn=createLogger({level:`trace`});function isEnvVerbose(){return process.env.TOOLING_DEBUG===`true`}function debug(e,t){e.verbose&&dn.debug(t)}function debugExec(e,t,n){if(!e.verbose)return;let r=[`${A(t)} (exit code ${String(n.exitCode)})`];n.stdout.trim()&&r.push(` stdout: ${A(n.stdout.trim())}`),n.stderr.trim()&&r.push(` stderr: ${A(n.stderr.trim())}`),dn.debug(r.join(`
|
|
13
|
+
`))}function parseComposeYaml(e){return Ee(e,{logLevel:`silent`})}const fn=P.looseObject({published:P.union([P.string(),P.number()]).optional(),target:P.union([P.string(),P.number()]).optional()}),pn=P.union([P.string(),P.looseObject({context:P.string().optional(),dockerfile:P.string().optional()})]),mn=P.looseObject({image:P.string().optional(),build:pn.optional(),profiles:P.array(P.string()).optional(),ports:P.array(P.unknown()).optional(),healthcheck:P.unknown().optional()}),hn=P.looseObject({services:P.record(P.string(),mn).optional()});function startsUnderCheckProfile(e){return e.profiles.length===0||e.profiles.includes(`bst-check`)}function resolveBuildDockerfile(e,t){if(t===void 0)return;if(typeof t==`string`)return w.resolve(e,t,`Dockerfile`);let n=t.context??`.`,r=t.dockerfile??`Dockerfile`;return w.resolve(e,n,r)}function resolveBuildContext(e,t){if(t===void 0)return;if(typeof t==`string`)return w.resolve(e,t);let n=t.context??`.`;return w.resolve(e,n)}const gn=[`target`,`args`,`secrets`,`platforms`,`additional_contexts`,`dockerfile_inline`];function hasUnreproducibleBuildKeys(e){return e===void 0||typeof e==`string`?!1:gn.some(t=>e[t]!==void 0)}const _n=/^\$\{([A-Za-z_][A-Za-z0-9_]*)(?::?-(\d+))?\}$/;function parseHostPortSegment(e){let t=e.trim(),n=_n.exec(t);if(n?.[1]){let e=n[2];return{kind:`variable`,name:n[1],default:e?Number.parseInt(e,10):void 0}}let r=Number.parseInt(t,10);return Number.isNaN(r)?void 0:{kind:`literal`,port:r}}function parseContainerPortSegment(e){let t=Number.parseInt(e.trim(),10);return Number.isNaN(t)?void 0:t}function splitPortSegments(e){let t=[],n=0,r=0;for(let i=0;i<e.length;i++)e.startsWith("${",i)?(n++,i++):e[i]===`}`&&n>0?n--:e[i]===`:`&&n===0&&(t.push(e.slice(r,i)),r=i+1);if(n===0)return t.push(e.slice(r)),t}function parsePortString(e){let t=e.split(`/`)[0];if(!t)return;let n=splitPortSegments(t);if(n){if(n.length===2)return{hostPort:n[0]?parseHostPortSegment(n[0]):void 0,containerPort:n[1]?parseContainerPortSegment(n[1]):void 0};if(n.length===3)return{hostPort:n[1]?parseHostPortSegment(n[1]):void 0,containerPort:n[2]?parseContainerPortSegment(n[2]):void 0}}}function findHostPort(e){for(let t of e??[]){let e=extractPortMapping(t);if(!e)continue;let{hostPort:n,containerPort:r}=e;return n===void 0?{containerPort:r}:n.kind===`literal`?{hostPort:n.port,containerPort:r}:{portEnvVar:n.name,hostPort:n.default,containerPort:r}}return{}}function parseLongSyntaxTarget(e){if(typeof e==`number`)return e;if(typeof e==`string`)return parseContainerPortSegment(e)}function parseLongSyntaxPort(e){let t=fn.safeParse(e);if(!t.success)return;let{published:n,target:r}=t.data,i;return typeof n==`number`?i={kind:`literal`,port:n}:typeof n==`string`&&(i=parseHostPortSegment(n)),{hostPort:i,containerPort:parseLongSyntaxTarget(r)}}function extractPortMapping(e){let t=typeof e==`string`?parsePortString(e):parseLongSyntaxPort(e);if(t&&(t.hostPort!==void 0||t.containerPort!==void 0))return t}function parseComposeServiceSources(e,t){let n=/* @__PURE__ */ new Map;for(let{file:r,content:i}of t){let t;try{t=parseComposeYaml(i)}catch{I.debug(`compose file "${r}" failed to parse as YAML; skipping`);continue}let a=hn.safeParse(t);if(!a.success)I.debug(`compose file "${r}" failed schema validation; skipping`);else if(a.data.services)for(let[t,i]of Object.entries(a.data.services)){let a=n.get(t),o=a?.hostPort,s=a?.portEnvVar,c=a?.containerPort;if(o===void 0&&s===void 0&&c===void 0){let e=findHostPort(i.ports);o=e.hostPort,s=e.portEnvVar,c=e.containerPort}let l=resolveBuildDockerfile(e,i.build),u=resolveBuildContext(e,i.build),d=[...a?.declaredIn??[],r],f=[...a?.profiles??[]];for(let e of i.profiles??[])f.includes(e)||f.push(e);let p=(a?.buildHasUnreproducibleKeys??!1)||hasUnreproducibleBuildKeys(i.build)||void 0;n.set(t,{name:t,image:i.image??a?.image,buildDockerfile:l??a?.buildDockerfile,buildContext:u??a?.buildContext,buildHasUnreproducibleKeys:p,hostPort:o,portEnvVar:s,containerPort:c,hasHealthcheck:(a?.hasHealthcheck??!1)||i.healthcheck!==void 0,declaredIn:d,profiles:f})}}return[...n.values()]}function parseComposeServices(e,t){let n=[];for(let r of t)try{let t=p(w.join(e,r),`utf-8`);n.push({file:r,content:t})}catch{continue}return parseComposeServiceSources(e,n)}function stripComposeVariables(e){return e.replace(/\$\{[^}]*\}/g,``)}function bareImageName(e){let t=stripComposeVariables(e),n=t.lastIndexOf(`/`),r=t.lastIndexOf(`:`);return(r>n?t.slice(0,r):t)||void 0}function roundTripImageName(e){if(e.includes("${")||e.includes(`@`))return;let t=e.lastIndexOf(`/`),n=e.lastIndexOf(`:`);return n>t?e.slice(n+1)===`latest`?e.slice(0,n):void 0:e}function imageRegistryHost(e){let t=e.indexOf(`/`);if(t===-1)return;let n=e.slice(0,t);if(n.includes(`.`)||n.includes(`:`)||n===`localhost`)return n}function extractComposeImageNames(e){let t=/* @__PURE__ */ new Set;for(let n of e)if(n.image){let e=bareImageName(n.image);e&&t.add(e)}return[...t]}function extractComposeBuildDockerfiles(e){let t=/* @__PURE__ */ new Set;for(let n of e)n.buildDockerfile&&t.add(n.buildDockerfile);return[...t]}const vn=[`docker-compose.yaml`,`docker-compose.yml`,`compose.yaml`,`compose.yml`],yn=[`.`,`docker`];function deriveCheckOverlayName(e){return e.replace(/\.(yaml|yml)$/,`.check.$1`)}function probeConventional(e,t){let n=[],r=[];for(let i of vn){let a=e(w.join(t,i));a!==null&&(n.push(i),r.push({file:i,content:a}))}return{files:n,sources:r}}function readConfigured(e,t,n){let r=[],i=[];for(let a of n){let n=e(w.join(t,a));n===null?I.debug(`compose file "${a}" configured in ${t} does not exist; skipping`):(r.push(a),i.push({file:a,content:n}))}return{files:r,sources:i}}function withOverlay(e,t,n,r,i){let a=deriveCheckOverlayName(i);if(n.includes(a))return{composeDir:t,files:n,checkOverlay:a,sources:r};let o=e(w.join(t,a));return o===null?{composeDir:t,files:n,checkOverlay:void 0,sources:r}:{composeDir:t,files:n,checkOverlay:a,sources:[...r,{file:a,content:o}]}}function resolveComposeFileSet(e,t,n){if(n!==void 0&&n.length===0)return{composeDir:t,files:[],checkOverlay:void 0,sources:[]};for(let r of yn){let i=w.join(t,r),a=probeConventional(e,i),o=a.files[0];if(o===void 0)continue;let{files:s,sources:c}=n===void 0?a:readConfigured(e,i,n);return withOverlay(e,i,s,c,o)}if(n===void 0)return{composeDir:t,files:[],checkOverlay:void 0,sources:[]};let{files:r,sources:i}=readConfigured(e,t,n);return{composeDir:t,files:r,checkOverlay:void 0,sources:i}}const bn=6e5;function morePagesFollow(e,t,n,r){if(t===0)return!1;let i=e.headers.get(`x-total-count`)?.trim()??``,a=i===``?NaN:Number(i);return!Number.isSafeInteger(a)||a<0?t>=r:n<a}const xn={attempts:5,baseDelayMs:250,maxDelayMs:2e3};function isTransientTransportError(e){return e instanceof TypeError||e instanceof DOMException&&(e.name===`TimeoutError`||e.name===`AbortError`)}function withTimeoutSignal(e,t){if(t<=0)return e;let n=AbortSignal.timeout(t);return e?.signal==null?{...e,signal:n}:{...e,signal:AbortSignal.any([e.signal,n])}}async function retryBackoff(e,t,n){if(t<=0)return;let r=Math.min(t*2**(e-1),n);await new Promise(e=>setTimeout(e,r))}async function retryOnTransient(e,t=xn,n=null){let r;for(let i=1;i<=t.attempts;i++)try{return await e()}catch(e){if(n?.aborted||!isTransientTransportError(e))throw e;r=e,i<t.attempts&&await retryBackoff(i,t.baseDelayMs,t.maxDelayMs)}throw r}function fetchWithRetry(e,t=xn,n=12e4){return(r,i,a)=>{let o=(i?.method??`GET`).toUpperCase(),s=o===`GET`||o===`HEAD`||a?.idempotent===!0,c=a?.timeoutMs??n,l=i?.signal??null,attempt=()=>e(r,withTimeoutSignal(i,c));return s?retryOnTransient(attempt,a?.attempts===void 0?t:{...t,attempts:a.attempts},l):attempt()}}const Sn=67108864;function execCapture$2(e,t,n){try{return{status:0,stdout:N(e,t,{cwd:n.cwd,env:n.env?{...process.env,...n.env}:void 0,input:n.input,encoding:`utf-8`,stdio:[n.stdin??`pipe`,`pipe`,`pipe`],maxBuffer:Sn}),stderr:``}}catch(e){if(isExecSyncError(e))return{status:e.status,stdout:e.stdout,stderr:e.stderr};if(n.keepPartialStdoutOnKill&&isKilledExecError(e)){let t=k(e),n=e.stderr.trim()===``?t:`${e.stderr}\n${t}`;return{status:1,stdout:e.stdout,stderr:n}}return{status:1,stdout:``,stderr:k(e),error:e}}}function isExecSyncError(e){return e instanceof Error&&`stdout`in e&&typeof e.stdout==`string`&&`stderr`in e&&typeof e.stderr==`string`&&`status`in e&&typeof e.status==`number`}function isKilledExecError(e){return e instanceof Error&&`stdout`in e&&typeof e.stdout==`string`&&`stderr`in e&&typeof e.stderr==`string`&&`signal`in e&&typeof e.signal==`string`}function captureSpawnOptions(e){return{cwd:e?.cwd,env:{...process.env,...e?.env},input:e?.input,timeout:e?.timeoutMs,killSignal:`SIGKILL`,maxBuffer:268435456,encoding:`utf-8`,stdio:[`pipe`,`pipe`,`pipe`]}}function execCaptureViaShim(e,t,n){let r=Ft(e,t,captureSpawnOptions(n)),i=r.stdout??``,a=r.stderr??``;return r.signal!==null&&r.signal!==void 0?{stdout:i,stderr:a,exitCode:124}:r.error?{stdout:i,stderr:k(r.error),exitCode:1}:{stdout:i,stderr:a,exitCode:r.status??1}}function execCapture$1(e,t,n){try{return{stdout:N(e,t,captureSpawnOptions(n)),stderr:``,exitCode:0}}catch(r){return isExecSyncError(r)?{stdout:r.stdout,stderr:r.stderr,exitCode:r.status}:isKilledExecError(r)?{stdout:r.stdout,stderr:r.stderr,exitCode:124}:shouldRetryViaShim(r)?execCaptureViaShim(e,t,n):{stdout:``,stderr:``,exitCode:1}}}function spawnStreamChild(e,t,n,r){let i=e?It(t,n,{cwd:r.cwd,env:{...process.env,...r.env},stdio:[`pipe`,`pipe`,`pipe`],signal:r.signal??void 0,killSignal:`SIGKILL`}):fe(t,n,{cwd:r.cwd,env:{...process.env,...r.env},stdio:[`pipe`,`pipe`,`pipe`],signal:r.signal??void 0,killSignal:`SIGKILL`}),{stdout:a,stderr:o,stdin:s}=i;if(a===null||o===null||s===null)throw new D(`Spawned child for ${commandLine(t,n)} is missing a piped stream`);return{child:i,stdoutStream:a,stderrStream:o,stdinStream:s}}const Cn=Symbol(`child closed`);async function writeStreamedStdin(e,t,n){let r=t[Symbol.asyncIterator]();try{for(;;){let t=await Promise.race([r.next(),n]);if(t===Cn)return;if(t.done===!0)break;e.write(t.value)}}catch{}finally{e.end(),await r.return?.().catch(()=>{})}}function execStreamCapture(e,t,n,r,i={}){let{onLine:a,onStderrLine:o}=i,{child:s,stdoutStream:c,stderrStream:l,stdinStream:u}=spawnStreamChild(e,t,n,r),d=``,f=``,p=``,m=``,h=new je(`utf8`),g=new je(`utf8`),_=!1,v=!1,y,b=r.timeoutMs===void 0?void 0:setTimeout(()=>{_=!0,s.kill(`SIGKILL`)},r.timeoutMs),stopTimeout=()=>{b&&clearTimeout(b)};c.on(`data`,e=>{let t=h.write(e);if(d+=t,!a)return;p+=t;let n=p.split(`
|
|
14
14
|
`);p=n.pop()??``;for(let e of n)a(e)}),l.on(`data`,e=>{let t=g.write(e);if(f+=t,!o)return;m+=t;let n=m.split(`
|
|
15
|
-
`);m=n.pop()??``;for(let e of n)o(e)}),s.on(`error`,e=>{e.name!==`AbortError`&&(v=!0,y=e)}),u.on(`error`,()=>{});let x=Promise.withResolvers();return r.inputStream===void 0?(r.input!==void 0&&u.write(r.input),u.end()):writeStreamedStdin(u,r.inputStream,x.promise).catch(()=>{}),new Promise(e=>{s.on(`close`,(t,n)=>{x.resolve(
|
|
16
|
-
`)){let e=/refs\/tags\/(.+)/.exec(n);e?.[1]&&!e[1].endsWith(`^{}`)&&t.push(e[1])}return t}function reconcileTags(e,t){let n=new Set(t);return e.filter(e=>!n.has(e))}const
|
|
17
|
-
`)){let e=/^([0-9a-f]{7,40})\s+refs\/tags\/(.+)$/.exec(n.trim());if(e?.[1]&&e[2]){if(e[2].endsWith(`^{}`)){let n=e[2].slice(0,-3),r=t.get(n);t.set(n,{ref:r?.ref??e[1],commit:e[1]})}else t.set(e[2],{ref:e[1],commit:e[1]})}}return t}function parseReleaseVersion(e){let t=jn.exec(e.trim());if(t?.[1]&&t[2]&&t[3])return{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:t[4]===void 0?[]:t[4].split(`.`)}}function isPrerelease$1(e){return(parseReleaseVersion(e)?.prerelease.length??0)>0}const Mn=/(?:^|[^\d.])(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)(?:\+[0-9A-Za-z.-]+)?$/u;function tagIsPrerelease(e){let t=Mn.exec(e)?.[1];return t!==void 0&&isPrerelease$1(t)}function comparePrereleaseIdentifier(e,t){let n=/^\d+$/.test(e),r=/^\d+$/.test(t);if(n&&r){let n=Number(e)-Number(t);return n<0?-1:+(n>0)}return n?-1:r?1:e<t?-1:+(e>t)}function comparePrerelease(e,t){let n=Math.min(e.length,t.length);for(let r=0;r<n;r++){let n=comparePrereleaseIdentifier(e[r],t[r]);if(n!==0)return n<0?-1:1}return e.length===t.length?0:e.length<t.length?-1:1}function compareReleaseVersions(e,t){let n=parseReleaseVersion(e),r=parseReleaseVersion(t);if(!n||!r)return 0;let i=[n.major-r.major,n.minor-r.minor,n.patch-r.patch];for(let e of i)if(e!==0)return e<0?-1:1;return n.prerelease.length===0&&r.prerelease.length===0?0:n.prerelease.length===0?1:r.prerelease.length===0?-1:comparePrerelease(n.prerelease,r.prerelease)}function changesetsTagFamily(e){let t=`${e}@`;return{exact:e=>`${t}${e}`,floating:e=>computeSlidingTags(e).map(e=>`${t}${e}`),versionOfExact:e=>{if(!e.startsWith(t))return;let n=e.slice(t.length);if(!(n===`latest`||n.startsWith(`v`)))return parseReleaseVersion(n)?n:void 0}}}function simpleTagFamily(e=`v`){return{exact:t=>`${e}${t}`,floating:e=>computeSlidingTags(e),versionOfExact:t=>{if(!t.startsWith(e))return;let n=t.slice(e.length);return parseReleaseVersion(n)?n:void 0}}}function highestVersionAtSha(e,t,n){let r;for(let[i,a]of t){if(a.commit!==n)continue;let t=e.versionOfExact(i);t!==void 0&&(r===void 0||compareReleaseVersions(t,r)>0)&&(r=t)}return r}function planFloatingTagMoves(e,t,n){let r=n.get(e.exact(t))?.commit,i=[];if(isPrerelease$1(t)){for(let a of e.floating(t)){let e=n.get(a);i.push({tag:a,targetSha:r,observedSha:e?.commit,observedRef:e?.ref,decision:`keep`,reason:`${t} is a prerelease`})}return i}for(let a of e.floating(t)){let o=n.get(a),s=o?.commit,c={tag:a,targetSha:r,observedSha:s,observedRef:o?.ref};if(s===void 0){i.push({...c,decision:`move`,reason:`the tag does not exist yet`});continue}let l=highestVersionAtSha(e,n,s);if(l===void 0){i.push({...c,decision:`move`,reason:`target has no exact version tag`});continue}let u=compareReleaseVersions(t,l);u>0?i.push({...c,decision:`move`,reason:`newer than ${l}`}):u===0?i.push({...c,decision:`current`,reason:`already at ${l}`}):i.push({...c,decision:`keep`,reason:`${l} is newer`})}return i}function reportFloatingTagOutcome(e,t){let n=`moved ${String(e.moved.length)}, kept ${String(e.kept.length)}, failed ${String(e.failed.length)}`;if(e.moved.length===0){F.info(`Floating tags: ${n}`);return}let r=t?`would move`:`moved`;F.info(`Floating tags: ${n} (${r}: ${e.moved.join(`, `)})`)}function describeGitFailure(e){return e.stderr.trim()||e.stdout.trim()||`unknown git error`}function readRemoteTagTargets(e){let t=e.executor.exec(`git`,[...e.options.git.args,`ls-remote`,`--tags`,e.options.git.url],{cwd:e.options.cwd});if(debugExec({verbose:e.options.verbose},`floating tags: ls-remote`,t),t.exitCode!==0)F.warn(`Could not read remote tags for floating tags: ${describeGitFailure(t)}`);else return parseRemoteTagTargets(t.stdout)}function markUnsettledFailed(e,t){for(let n of t)for(let t of n.family.floating(n.version))e.decided.has(t)||e.outcome.failed.push(t)}function moveFloatingTags(e,t,n){let r={executor:e,options:t},i={outcome:{moved:[],kept:[],failed:[]},decided:/* @__PURE__ */ new Set,rejected:[],lastError:``};for(let e=1;e<=5;e++){i.rejected=[];let t=readRemoteTagTargets(r);if(t===void 0)return markUnsettledFailed(i,n),i.outcome;for(let e of n)for(let n of planFloatingTagMoves(e.family,e.version,t))i.decided.has(n.tag)||applyFloatingMove(r,e,n,i);if(i.rejected.length===0)return i.outcome;if(e===5){for(let e of i.rejected)i.outcome.failed.push(e);return F.warn(`Floating tags still rejected after 5 attempts: ${i.rejected.join(`, `)} (${i.lastError})`),i.outcome}}return i.outcome}function applyFloatingMove(e,t,n,r){if(n.decision===`keep`||n.decision===`current`){r.decided.add(n.tag),r.outcome.kept.push(n.tag),F.info(`Leaving ${n.tag} alone: ${n.reason}`);return}let i=t.version,a=n.targetSha??localTarget(e,t);a===void 0?(r.decided.add(n.tag),r.outcome.failed.push(n.tag),F.warn(`Could not resolve the commit for ${n.tag}: no ${t.family.exact(i)} to point it at`)):e.options.dryRun?(r.decided.add(n.tag),r.outcome.moved.push(n.tag),F.info(`[dry-run] Would move ${n.tag} to ${i}`)):pushFloatingMove(e,n,a,r)}function pushFloatingMove(e,t,n,r){let i=e.executor.exec(`git`,[`tag`,`-f`,t.tag,n],{cwd:e.options.cwd});if(debugExec({verbose:e.options.verbose},`floating tags: tag ${t.tag}`,i),i.exitCode!==0){r.decided.add(t.tag),r.outcome.failed.push(t.tag),F.warn(`Failed to create ${t.tag}: ${describeGitFailure(i)}`);return}let a=t.observedRef??``,o=`--force-with-lease=refs/tags/${t.tag}:${a}`,s=e.executor.exec(`git`,[...e.options.git.args,`push`,o,e.options.git.url,`refs/tags/${t.tag}`],{cwd:e.options.cwd});debugExec({verbose:e.options.verbose},`floating tags: push ${t.tag}`,s),s.exitCode===0?(r.decided.add(t.tag),r.outcome.moved.push(t.tag)):(r.lastError=describeGitFailure(s),r.rejected.push(t.tag))}function localTarget(e,t){return resolveTagCommit(e.executor,e.options.cwd,t.family.exact(t.version))}const Nn=`enforce`,Pn=N.looseObject({version:N.string().optional()});function hasHeadParent(e,t){let n=e.exec(`git`,[`rev-parse`,`--verify`,`--quiet`,`HEAD~1`],{cwd:t});return n.exitCode===0&&n.stdout.trim()!==``}function readAtRev(e,t,n,r){let i=e.exec(`git`,[`show`,`${n}:${r}`],{cwd:t});if(i.exitCode===0)return i.stdout}function versionOf(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}let n=Pn.safeParse(t);return n.success?n.data.version:void 0}function headChangedVersion(e,t,n){let r=versionOf(readAtRev(e,t,`HEAD~1`,n)),i=versionOf(readAtRev(e,t,`HEAD`,n));return r!==void 0&&i!==void 0&&r!==i}function skipLine(e,t){return`${e.imageName} v${e.version??`?`}: HEAD did not change the version in ${t}, so it is not pushed. Publish it by hand with --image ${e.imageName}.`}function selectImagesToPush(e,t,n){let r=t.images??[];return r.length>0?selectNamedImages(r,n):t.releaseStrategy===`changesets`?selectBoundedImages(e,t.cwd,n):{push:[...n],skipped:[]}}function selectNamedImages(e,t){let n=t.map(e=>e.imageName),r=new Set(n),i=e.filter(e=>!r.has(e));if(i.length>0)throw new T(`--image names ${i.join(`, `)}, which no publishable image carries. Publishable images: ${n.join(`, `)}.`);let a=new Set(e),o=[],s=[];for(let e of t)a.has(e.imageName)?o.push(e):(F.info(`${e.imageName}: not named by --image, so it is not pushed.`),s.push(e));return{push:o,skipped:s}}function bumpedByPath(e,t,n,r){let i=r.get(n);if(i!==void 0)return i;let a=headChangedVersion(e,t,n);return r.set(n,a),a}function selectBoundedImages(e,t,n){let r=/* @__PURE__ */ new Set,i=[];for(let e of n)e.versionSource.kind===`override`?r.add(e):i.push(e);let a=new Set(r);if(i.length===0)return{push:n.filter(e=>a.has(e)),skipped:[]};if(!hasHeadParent(e,t))return F.info(`HEAD has no parent commit to compare against, so no image that takes its version from a package.json is pushed. Publish one by hand with --image <name>.`),{push:n.filter(e=>a.has(e)),skipped:n.filter(e=>!a.has(e))};let o=/* @__PURE__ */ new Map;for(let n of i){let r=n.versionSource;if(r.kind===`manifest`){if(bumpedByPath(e,t,r.path,o)){a.add(n);continue}F.info(skipLine(n,r.path))}}return{push:n.filter(e=>a.has(e)),skipped:n.filter(e=>!a.has(e))}}function defaultPublish(e,t){return e===void 0||t!==`enforce`}const Fn=N.object({name:N.string().optional(),version:N.string().optional()}),In=N.object({docker:wt.optional(),dockerCheck:N.union([N.literal(!1),Tt]).optional()});function loadDockerConfigSlice(e,t){let n=w.join(t,`.tooling.json`),r=parseToolingConfigSlice(e.readFile(n)??void 0,In,{block:`docker/dockerCheck`,path:n}),i=r?.dockerCheck;return{overrides:r?.docker??{},composeFiles:i===!1||i===void 0?void 0:i.composeFiles}}function mergeDockerConfig(e,t){if(!t)return e;let n=t.dockerfile??e?.dockerfile;if(n)return{dockerfile:n,context:t.context??e?.context??`.`,buildArgs:t.buildArgs??e?.buildArgs,imageName:t.imageName??e?.imageName,version:t.version,publish:t.publish}}function readPackageInfo(e,t){let n=e.readFile(t);if(n)try{let e=Fn.safeParse(JSON.parse(n));return e.success?{name:e.data.name,version:e.data.version}:{name:void 0,version:void 0}}catch{return{name:void 0,version:void 0}}}function findEnclosingPackage(e,t,n){let r=w.normalize(w.dirname(n));for(;;){let n=r.split(`/`);if(n[0]!==`packages`||n.length<2)return;let i=`${n.join(`/`)}/package.json`,a=readPackageInfo(e,w.join(t,...n,`package.json`));if(a!==void 0)return{info:a,path:i};r=n.slice(0,-1).join(`/`)}}function resolveDockerVersion(e,t,n){if(n.version!==void 0)return{version:n.version,source:{kind:`override`}};let r=findEnclosingPackage(e,t,n.dockerfile);if(r!==void 0)return{version:r.info.version,source:{kind:`manifest`,path:r.path}};let i=readPackageInfo(e,w.join(t,`package.json`));return i===void 0?{version:void 0,source:{kind:`none`}}:{version:i.version,source:{kind:`manifest`,path:`package.json`}}}function stripScope(e){let t=e.indexOf(`/`);return e.startsWith(`@`)&&t!==-1?e.slice(t+1):e}const Ln=[`Dockerfile`,`docker/Dockerfile`];function findConventionDockerfile(e,t,n){for(let r of Ln){let i=`packages/${n}/${r}`;if(e.readFile(w.join(t,i))!==null)return{dockerfile:i,context:`.`}}}function findRootDockerfile(e,t){for(let n of Ln)if(e.readFile(w.join(t,n))!==null)return{dockerfile:n,context:`.`}}const Rn={checkOnlyIn:void 0,phase:Nn};function createDockerPackage(e,t,n,r){let{dir:i,docker:a,origin:o}=r,s=i===`.`,c=readPackageInfo(e,s?w.join(t,`package.json`):w.join(t,`packages`,i,`package.json`))?.name,l=a.imageName??(s?stripScope(c??n):`${n}-${stripScope(c??i)}`),{version:u,source:d}=resolveDockerVersion(e,t,a);return{dir:i,imageName:l,version:u,versionSource:d,publish:a.publish??defaultPublish(o.checkOnlyIn,o.phase),docker:a,checkOnlyIn:o.checkOnlyIn}}function readComposeSources(e,t,n){let r=resolveComposeFileSet(t=>e.readFile(t),t,n);if(r.sources.length!==0)return{composeDir:r.composeDir,sources:r.sources,checkOverlay:r.checkOverlay}}function discoverComposeImages(e,t,n){let r=readComposeSources(e,t,n);if(!r)return[];let i=parseComposeServiceSources(r.composeDir,r.sources),a=[];for(let e of i){if(e.buildDockerfile===void 0||e.buildContext===void 0||e.image===void 0)continue;if(e.buildHasUnreproducibleKeys){F.debug(`compose service "${e.name}": build sets an unreproducible key; skipping`);continue}let t=roundTripImageName(e.image);t===void 0?F.debug(`compose service "${e.name}": image "${e.image}" is not a name bst can round-trip (unresolved variable, digest pin, or non-latest tag); skipping Docker discovery`):a.push({serviceName:e.name,dockerfileAbs:e.buildDockerfile,contextAbs:e.buildContext,imageName:t,checkOnlyIn:r.checkOverlay!==void 0&&e.declaredIn.length===1&&e.declaredIn[0]===r.checkOverlay?r.checkOverlay:void 0})}return a}function addComposeDiscoveredPackages(e,t,n){let{executor:r,cwd:i,repoName:a,overrides:o,composeFiles:s}=e,c=new Set(t.map(e=>w.resolve(i,e.docker.dockerfile))),l=new Set(t.map(e=>e.imageName)),u=/* @__PURE__ */ new Set;for(let d of discoverComposeImages(r,i,s)){if(u.has(d.imageName)){F.debug(`compose service "${d.serviceName}": image "${d.imageName}" is already claimed by an earlier service; skipping Docker discovery`);continue}u.add(d.imageName);let s=o[d.imageName];if(s!==void 0&&n.add(d.imageName),c.has(d.dockerfileAbs)){if(s!==void 0){let e=t.findIndex(e=>w.resolve(i,e.docker.dockerfile)===d.dockerfileAbs),n=t[e];if(n){let o={dockerfile:n.docker.dockerfile,context:n.docker.context,buildArgs:n.docker.buildArgs??s.buildArgs,imageName:n.docker.imageName??s.imageName,version:n.docker.version??s.version,publish:n.docker.publish??s.publish};t[e]=createDockerPackage(r,i,a,{dir:n.dir,docker:o,origin:Rn})}}continue}if(l.has(d.imageName)){let e=t.find(e=>e.imageName===d.imageName);F.warn(`compose service "${d.serviceName}" names image "${d.imageName}", which package "${e?.dir}" (${e?.docker.dockerfile}) already claims by convention or override; the service builds a different Dockerfile (${w.relative(i,d.dockerfileAbs)}) and is being skipped to avoid two Dockerfiles building under one tag`);continue}let f=mergeDockerConfig({dockerfile:w.relative(i,d.dockerfileAbs),context:w.relative(i,d.contextAbs)||`.`,imageName:d.imageName},s);f&&t.push(createDockerPackage(r,i,a,{dir:d.serviceName,docker:f,origin:{checkOnlyIn:d.checkOnlyIn,phase:e.phase}}))}}function extractFromRefs(e){let t=[],n=/^\s*FROM\s+(\S+)/gim,r=n.exec(e);for(;r!==null;){let i=r[1];i!==void 0&&t.push(i.split(`:`)[0]??i),r=n.exec(e)}return t}function localBaseImages(e,t,n){let r=new Set(e.map(e=>e.imageName)),i=/* @__PURE__ */ new Map;for(let a of e){let e=t.readFile(w.join(n,a.docker.dockerfile)),o=[];if(e!==null)for(let t of extractFromRefs(e))t!==a.imageName&&r.has(t)&&!o.includes(t)&&o.push(t);i.set(a.imageName,o)}return i}function sortPackagesByDependency(e,t,n){let r=new Map(e.map((e,t)=>[e.imageName,t])),i=localBaseImages(e,t,n),a=[];for(let t of e){let e=[];for(let n of i.get(t.imageName)??[]){let t=r.get(n);t!==void 0&&e.push(t)}a.push(e)}let o=[],s=/* @__PURE__ */ new Set,c=/* @__PURE__ */ new Set;function visit(t){if(!s.has(t)){if(c.has(t))throw new T(`Docker image dependency cycle detected: "${e[t]?.imageName??String(t)}" is reached from its own FROM chain`);c.add(t);for(let e of a[t]??[])visit(e);c.delete(t),s.add(t),o.push(t)}}for(let t=0;t<e.length;t++)visit(t);let l=[];for(let t of o){let n=e[t];n!==void 0&&l.push(n)}return l}function refuseDuplicateImageNames(e){let t=/* @__PURE__ */ new Map;for(let n of e){let e=t.get(n.imageName);e===void 0?t.set(n.imageName,[n.dir]):e.push(n.dir)}for(let[e,n]of t)if(n.length>1)throw new T(`More than one Docker package builds the image name "${e}": ${n.map(e=>`"${e}"`).join(`, `)}. They would all build the same tag, so set a distinct "imageName" for one of them under .tooling.json#docker`)}function detectDockerPackages(e,t,n,r=Nn){let{overrides:i,composeFiles:a}=loadDockerConfigSlice(e,t),o=e.listPackageDirs(t),s=[],c=/* @__PURE__ */ new Set;if(o.length>0){let r=findRootDockerfile(e,t),a=i[`.`],l=mergeDockerConfig(r,a);l&&(s.push(createDockerPackage(e,t,n,{dir:`.`,docker:l,origin:Rn})),c.add(`.`));for(let r of o){let a=findConventionDockerfile(e,t,r),o=i[r],l=mergeDockerConfig(a,o);l&&(s.push(createDockerPackage(e,t,n,{dir:r,docker:l,origin:Rn})),c.add(r))}}else{let r=findRootDockerfile(e,t),a=i[`.`],o=mergeDockerConfig(r,a);o&&s.push(createDockerPackage(e,t,n,{dir:`.`,docker:o,origin:Rn}))}if(addComposeDiscoveredPackages({executor:e,cwd:t,repoName:n,overrides:i,composeFiles:a,phase:r},s,c),o.length>0)for(let[r,a]of Object.entries(i)){if(c.has(r))continue;let i=mergeDockerConfig(void 0,a);if(!i)throw new T(`Docker override for "${r}" has no dockerfile: it names no package directory, no convention Dockerfile was found for it, and no compose service was discovered under that image name (TOOLING_DEBUG=true reports which services were skipped and why)`);s.push(createDockerPackage(e,t,n,{dir:r,docker:i,origin:Rn}))}return refuseDuplicateImageNames(s),sortPackagesByDependency(s,e,t)}function readSinglePackageDocker(e,t,n,r){let i=w.basename(w.resolve(t,n)),a=findConventionDockerfile(e,t,i),{overrides:o}=loadDockerConfigSlice(e,t),s=o[i],c=mergeDockerConfig(a,s);if(!c)throw new T(`No Dockerfile found for package "${i}" (checked convention paths and .tooling.json)`);return createDockerPackage(e,t,r,{dir:i,docker:c,origin:Rn})}function parseSemver(e){let t=e.replace(/^v/,``),n=/^(\d+)\.(\d+)\.(\d+)/.exec(t);if(!n?.[1]||!n[2]||!n[3])throw new T(`Invalid semver version: ${e}`);return{major:Number(n[1]),minor:Number(n[2]),patch:Number(n[3])}}function generateTags(e){let{major:t,minor:n}=parseSemver(e);return[`latest`,exactImageTag(e),`v${t}.${n}`,`v${t}`]}function exactImageTag(e){return parseSemver(e),`v${e.replace(/^v/,``).split(`+`)[0]}`}function imageRef(e,t,n){return imageRegistryHost(t)?`${t}:${n}`:`${e}/${t}:${n}`}function readRepoName(e,t){let n=e.readFile(w.join(t,`package.json`));if(!n)throw new T(`No package.json found in project root`);let r=parsePackageJson(n)?.name;if(!r)throw new T(`Root package.json must have a name field`);return r}const zn=/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g;function interpolate(e,t,n){return e.replace(zn,(e,r,i)=>{let a=t[r];return a!==void 0&&a!==``?a:i===void 0?(n?.(r),``):i})}function resolveBuildArgs(e,t){let n=Object.entries(e.docker.buildArgs??{});if(n.length===0)return{};let r=/* @__PURE__ */ new Set,i={};for(let[a,o]of n)i[a]=interpolate(o,t,t=>{r.has(t)||(r.add(t),F.warn(`docker build arg "${a}" for ${e.dir}: env var ${t} is not set; using empty string`))});return i}const Bn=`org.opencontainers.image.version`;function resolveProvenanceLabels(e,t,n){let r=e.exec(`git`,[`rev-parse`,`HEAD`],{cwd:t}),i=r.stdout.trim();if(r.exitCode!==0||i===``)return{};let a=e.exec(`git`,[`rev-parse`,`--show-prefix`],{cwd:t});if(a.exitCode!==0)return{};let o=[a.stdout.trim().replace(/\/$/,``),w.relative(t,w.resolve(t,n)).split(w.sep).join(`/`)].filter(e=>e!==``).join(`/`),s=o===``?`HEAD^{tree}`:`HEAD:${o}`,c=e.exec(`git`,[`rev-parse`,s],{cwd:t}),l=c.stdout.trim();if(c.exitCode!==0||l===``)return{};let u=e.exec(`git`,[`status`,`--porcelain`,`--`,n],{cwd:t});return{"org.opencontainers.image.revision":i,"com.bensandee.tooling.context-tree":`${l}${u.exitCode===0&&u.stdout.trim()!==``?`-dirty`:``}`}}function resolveImageLabels(e,t,n){let r=resolveProvenanceLabels(e,n,t.docker.context);return t.version&&(r[Bn]=t.version),r}function buildImage(e,t,n,r){let i=w.resolve(n,t.docker.dockerfile),a=w.resolve(n,t.docker.context),o=Object.entries(resolveBuildArgs(t,process.env)).map(([e,t])=>`${e}=${t}`);F.info(` build args: ${o.length>0?o.join(` `):`(none)`}`),F.info(` extra args: ${r.length>0?r.join(` `):`(none)`}`);let s=o.flatMap(e=>[`--build-arg`,e]),c=Object.entries(resolveImageLabels(e,t,n)).flatMap(([e,t])=>[`--label`,`${e}=${t}`]);e.execInherit(`docker`,[`build`,`-f`,i,`-t`,`${t.imageName}:latest`,...s,...c,...r,a])}function bakeImages(e,t,n){let r=n.cwd,i=localBaseImages(t,e,r),a=[];for(let o of t){F.info(`Building image for ${o.dir} (${o.imageName}:latest)...`),debug(n,`Dockerfile: ${o.docker.dockerfile}, context: ${o.docker.context}`);let t=resolveBuildArgs(o,process.env),s=Object.entries(t).map(([e,t])=>`${e}=${t}`);F.info(` build args: ${s.length>0?s.join(` `):`(none)`}`),a.push({imageName:o.imageName,dockerfile:w.resolve(r,o.docker.dockerfile),context:w.resolve(r,o.docker.context),args:t,labels:resolveImageLabels(e,o,r),bases:i.get(o.imageName)??[]})}let o=w.join(ye.tmpdir(),`bst-docker-bake-${Se()}`),s=w.join(o,`docker-bake.json`);e.makeDir(o);try{e.writeFile(s,JSON.stringify(buildBakeDefinition(a))),e.execInherit(`docker`,[`buildx`,`bake`,`--file`,s,`--load`],{cwd:r})}finally{e.removeDir(o)}}function runDockerBuild(e,t){let n=readRepoName(e,t.cwd);if(t.packageDir){let r=readSinglePackageDocker(e,t.cwd,t.packageDir,n);return F.info(`Building image for ${r.dir} (${r.imageName}:latest)...`),debug(t,`Dockerfile: ${r.docker.dockerfile}, context: ${r.docker.context}`),buildImage(e,r,t.cwd,t.extraArgs),F.info(`Built ${r.imageName}:latest`),{packages:[r]}}let r=detectDockerPackages(e,t.cwd,n,t.checkOnlyPhase??`enforce`);if(r.length===0)return F.info(`No packages with docker config found`),{packages:[]};F.info(`Found ${String(r.length)} Docker package(s): ${r.map(e=>e.dir).join(`, `)}`);let i=!0;if(t.extraArgs.length>0?(F.info("Building one image at a time: the extra arguments go to `docker build`, and bake does not take them."),i=!1):e.exec(`docker`,[`buildx`,`version`]).exitCode!==0&&(F.info("Building one image at a time: `docker buildx` is not available on this host."),i=!1),i)bakeImages(e,r,t);else for(let n of r)F.info(`Building image for ${n.dir} (${n.imageName}:latest)...`),debug(t,`Dockerfile: ${n.docker.dockerfile}, context: ${n.docker.context}`),buildImage(e,n,t.cwd,t.extraArgs);return F.info(`Built ${String(r.length)} image(s)`),{packages:r}}function tagAndPushPackage(e,t,n,r){let i=n.version??``,a=isPrerelease$1(i),o=generateTags(i),s=exactImageTag(i),c=imageRef(t.registryNamespace,n.imageName,s);F.info(`${n.dir} v${n.version} -> tags: ${o.join(`, `)}`);for(let c of o){let o=imageRef(t.registryNamespace,n.imageName,c);if(a&&c!==s){F.info(`Leaving ${o} alone: ${i} is a prerelease`),r.skipped.push(o);continue}F.info(`Tagging ${n.imageName} -> ${o}`);let l=e.exec(`docker`,[`tag`,n.imageName,o]);if(debugExec(t,`docker tag ${n.imageName} ${o}`,l),l.exitCode!==0)throw new T(`docker tag failed: ${l.stderr}`);t.dryRun&&(r.tags.push(o),F.info(`[dry-run] Skipping push for ${o}`))}if(t.dryRun)return;let l=publishRecord(e,t,c,r);if(!a)for(let a of o)a!==s&&moveFloatingRef(e,t,{version:i,ref:imageRef(t.registryNamespace,n.imageName,a),exactRef:c,recordKept:l},r)}function publishRecord(e,t,n,r){return inspectImageManifest(e,t,n)===void 0?(pushRef(e,t,n),r.tags.push(n),!1):(F.info(`Keeping ${n}: the registry already has this record`),r.kept.push(n),!0)}function moveFloatingRef(e,t,n,r){let{version:i,ref:a,exactRef:o,recordKept:s}=n,c=readPublishedImageVersion(e,t,a);if(s){if(c!==void 0&&parseReleaseVersion(c)!==void 0){let e=compareReleaseVersions(i,c);if(e===0){F.info(`Leaving ${a} alone: already at ${i}`),r.skipped.push(a);return}if(e<0){F.info(`Leaving ${a} at ${c} (newer than ${i})`),r.skipped.push(a);return}}retagFromRecord(e,t,a,o),r.tags.push(a)}else c!==void 0&&compareReleaseVersions(i,c)<0?(F.info(`Leaving ${a} at ${c} (newer than ${i})`),r.skipped.push(a)):(pushRef(e,t,a),r.tags.push(a))}function pushRef(e,t,n){F.info(`Pushing ${n}...`);let r=e.exec(`docker`,[`push`,n]);if(debugExec(t,`docker push ${n}`,r),r.exitCode!==0)throw new T(`docker push failed: ${r.stderr}`)}function retagFromRecord(e,t,n,r){F.info(`Retagging ${n} from the record ${r}...`);let i=e.exec(`docker`,[`buildx`,`imagetools`,`create`,`--tag`,n,r]);if(debugExec(t,`docker buildx imagetools create --tag ${n} ${r}`,i),i.exitCode!==0)throw new T(`imagetools create failed: ${i.stderr}`)}const Vn=N.object({config:N.object({Labels:N.union([N.record(N.string(),N.string()),N.null()]).optional()})}),Hn=N.record(N.string(),Vn);function versionFromImageManifest(e){for(let t of Object.values(e)){let e=t.config.Labels?.[Bn];if(e!==void 0)return e}}function inspectImageManifest(e,t,n){let r=e.exec(`docker`,[`buildx`,`imagetools`,`inspect`,n,`--format`,`{{json .Image}}`]);if(debugExec(t,`docker buildx imagetools inspect ${n}`,r),r.exitCode===0)return r.stdout}function readPublishedImageVersion(e,t,n){let r=inspectImageManifest(e,t,n);if(r===void 0)return;let i;try{i=JSON.parse(r)}catch(e){debug(t,`Could not parse the manifest for ${n}: ${String(e)}`);return}let a=Vn.safeParse(i);if(a.success)return a.data.config.Labels?.[Bn];let o=Hn.safeParse(i);if(o.success)return versionFromImageManifest(o.data);debug(t,`Unexpected manifest shape for ${n}; no version label read`)}function reportCheckOnlyImages(e,t){for(let n of e)n.checkOnlyIn!==void 0&&n.docker.publish===void 0&&(t===`warn`?F.warn(`Image "${n.imageName}" is declared only in ${n.checkOnlyIn}, the check overlay, so a later tooling release stops publishing it by default. Keep it: set publish to true for "${n.imageName}" under .tooling.json#docker. Settle it: set publish to false there, or move the service into a base compose file.`):F.info(`Skipped "${n.imageName}": it is declared only in ${n.checkOnlyIn}, the check overlay, so it was not pushed. Set publish to true for "${n.imageName}" under .tooling.json#docker to publish it anyway.`))}function runDockerPublish(e,t){let n=t.checkOnlyPhase??`enforce`,{packages:r}=runDockerBuild(e,{cwd:t.cwd,packageDir:void 0,extraArgs:[],verbose:t.verbose,checkOnlyPhase:n});if(reportCheckOnlyImages(r,n),r.length===0)return{packages:[],tags:[],skipped:[],kept:[],skippedImages:[]};let i=r.filter(e=>e.publish);if(i.length===0)return{packages:r,tags:[],skipped:[],kept:[],skippedImages:[]};for(let e of i){if(!e.version)throw new T(`Docker image "${e.imageName}" (dockerfile ${e.docker.dockerfile}) has no version to publish. Checked: an explicit "version" override in .tooling.json#docker, the nearest enclosing packages/<name>/package.json walking up from the dockerfile, and the root package.json. Set an explicit version override for this image.`);let n=imageRegistryHost(e.imageName);if(n!==void 0&&n.toLowerCase()!==t.registryHost.toLowerCase())throw new T(`Docker image "${e.imageName}" names registry "${n}", but this run logs in to "${t.registryHost}". Fix one of the three: point the publish target at "${n}" (registryHost/registryNamespace in .tooling.json, or DOCKER_REGISTRY_HOST/DOCKER_REGISTRY_NAMESPACE); override the name via .tooling.json#docker keyed by the discovered image name (e.g. {"docker": {"${e.imageName}": {"imageName": "<unqualified-name>"}}}); or exclude it with {"docker": {"${e.imageName}": {"publish": false}}}.`)}let a=selectImagesToPush(e,t,i),o=a.push,s=a.skipped.map(e=>e.imageName);if(o.length===0)F.info(`No image to push, so this run neither logs in nor logs out.`);else if(t.dryRun)F.info(`[dry-run] Skipping docker login`);else{F.info(`Logging in to ${t.registryHost}...`);let n=e.exec(`docker`,[`login`,t.registryHost,`-u`,t.username,`--password-stdin`],{input:t.password});if(debugExec(t,`docker login`,n),n.exitCode!==0)throw new T(`Docker login failed: ${n.stderr}`)}let c={tags:[],skipped:[],kept:[]};try{for(let n of o)tagAndPushPackage(e,t,n,c)}finally{o.length>0&&!t.dryRun&&(F.info(`Logging out from ${t.registryHost}...`),e.exec(`docker`,[`logout`,t.registryHost]))}return logPublishSummary(c,s,t),{packages:r,...c,skippedImages:s}}function logPublishSummary(e,t,n){if(F.info(`Published ${String(e.tags.length)} image tag(s)`),e.skipped.length>0&&F.info(`Left ${String(e.skipped.length)} floating tag(s) alone: ${e.skipped.join(`, `)}`),e.kept.length>0&&F.info(`Kept ${String(e.kept.length)} record(s) already in the registry: ${e.kept.join(`, `)}`),t.length>0){let e=n.images!==void 0&&n.images.length>0?`not named by --image`:`whose version HEAD did not change`;F.info(`Skipped ${String(t.length)} image(s) ${e}: ${t.join(`, `)}`)}}function keysMatch(e,t,n,r){return e.cwd===t&&e.repoName===n&&e.phase===r}function answersMatch(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function replayMatches(e,t){for(let n of e)if(n.kind===`list`){if(!answersMatch(n.answer,t.listPackageDirs(n.cwd)))return!1}else if(t.readFile(n.path)!==n.answer)return!1;return!0}function recordingReader(e,t){return{listPackageDirs(n){let r=e.listPackageDirs(n);return t.push({kind:`list`,cwd:n,answer:[...r]}),r},readFile(n){let r=e.readFile(n);return t.push({kind:`read`,path:n,answer:r}),r}}}function recordDiscovery(e,t,n,r){let i=[],a=detectDockerPackages(recordingReader(e,i),t,n,r);return{key:{cwd:t,repoName:n,phase:r},reads:i,result:a}}function createDockerDiscoveryMemo(){let e;function detect(t,n,r,i=Nn){let a=e;if(a!==void 0&&keysMatch(a.key,n,r,i)&&replayMatches(a.reads,t))return[...a.result];let o=recordDiscovery(t,n,r,i);return e=o,[...o.result]}return{detect}}const Un=/* @__PURE__ */ new WeakMap;function memoFor(e){if(e.dockerDiscovery!==void 0)return e.dockerDiscovery;let t=Un.get(e);if(t!==void 0)return t;let n=createDockerDiscoveryMemo();return Un.set(e,n),n}function detectContextDockerPackages(e){return memoFor(e).detect(contextAsDockerReader(e),e.targetDir,e.config.name)}function contextAsDockerReader(e){return{listPackageDirs(e){let t=w.join(e,`packages`);try{return h(t,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}},readFile(t){let n=w.relative(e.targetDir,t);return e.read(n)??null}}}const Wn=`add "publishConfig": { "registry": "<your registry URL>" } to its package.json`;function isUsableRegistry(e){if(typeof e!=`string`||e.trim()===``)return!1;try{let t=new URL(e);return t.protocol===`https:`||t.protocol===`http:`}catch{return!1}}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function lintPublishConfig(e,t){let n=[];for(let r of getPublishablePackages(e,t)){let t=readPackageJson(r.dir);if(!t)continue;let i=w.relative(e,w.join(r.dir,`package.json`)),a=t.publishConfig,o=isRecord(a)?a.registry:void 0;o===void 0?n.push({kind:`missing`,package:r.name,file:i,message:`${r.name} is published from this repo but declares no publishConfig.registry, so its release destination is inherited -- a project .npmrc can repoint it silently. In ${i}, ${Wn}.`}):isUsableRegistry(o)||n.push({kind:`malformed`,package:r.name,file:i,message:`${r.name} declares publishConfig.registry as ${JSON.stringify(o)}, which is not an absolute http(s) URL and cannot be published to. In ${i}, ${Wn}.`})}return n}function declaredPublishRegistries(e,t,n){let r=[];for(let i of getPublishablePackages(e,t,n)){let e=t===`single`?n??readPackageJson(i.dir):readPackageJson(i.dir);if(!e)continue;let a=e.publishConfig,o=isRecord(a)?a.registry:void 0;typeof o==`string`&&isUsableRegistry(o)&&!r.includes(o)&&r.push(o)}return r}function managedFileHeader(e,t){return t.map(t=>t===``?e:`${e} ${t}`).join(`
|
|
15
|
+
`);m=n.pop()??``;for(let e of n)o(e)}),s.on(`error`,e=>{e.name!==`AbortError`&&(v=!0,y=e)}),u.on(`error`,()=>{});let x=Promise.withResolvers();return r.inputStream===void 0?(r.input!==void 0&&u.write(r.input),u.end()):writeStreamedStdin(u,r.inputStream,x.promise).catch(()=>{}),new Promise(e=>{s.on(`close`,(t,n)=>{x.resolve(Cn),stopTimeout();let i=h.end();d+=i,p+=i;let s=g.end();f+=s,m+=s,p.length>0&&a&&(a(p),p=``),m.length>0&&o&&(o(m),m=``),e({result:{stdout:d,stderr:f,...classifyStreamClose({spawnFailed:v,code:t,signal:n,timedOut:_,options:r})},spawnError:y})})})}function classifyStreamClose(e){let{spawnFailed:t,code:n,signal:r,timedOut:i,options:a}=e,o;o=t?1:n===null?i||r!==null?124:1:n;let s;return r!==null&&(i?s=`timeout`:a.signal?.aborted&&(s=`aborted`)),{exitCode:o,killedBy:s}}const sinceMs=e=>`${String(Math.round(performance.now()-e))}ms`,commandLine=(e,t)=>[e,...t].join(` `);function tracedRunners(e){let t=fetchWithRetry(globalThis.fetch);return{exec(t,n,r){e.trace(`exec -> ${commandLine(t,n)}`);let i=performance.now(),a=execCapture$1(t,n,r);return e.trace(`exec [ok] ${t} (exit ${String(a.exitCode)}, ${sinceMs(i)})`),a},async execStream(t,n,r,i,a){e.trace(`execStream -> ${commandLine(t,n)}`);let o=performance.now(),s={onLine:i,onStderrLine:a},c=await execStreamCapture(!1,t,n,r,s);return shouldRetryViaShim(c.spawnError)&&(c=await execStreamCapture(!0,t,n,r,s)),e.trace(`execStream [ok] ${t} (exit ${String(c.result.exitCode)}, ${sinceMs(o)})`),c.result},execInherit(t,n,r){e.trace(`execInherit -> ${commandLine(t,n)}`);let i=performance.now();try{let a={cwd:r?.cwd,env:r?.env?{...process.env,...r.env}:void 0,stdio:`inherit`};try{N(t,n,a)}catch(e){if(!shouldRetryViaShim(e))throw e;let r=Ft(t,n,a);if(r.error)throw r.error;if(r.signal!==null&&r.signal!==void 0)throw new D(`Command killed by signal ${r.signal}: ${commandLine(t,n)}`);if(r.status!==0)throw new D(`Command failed with exit code ${String(r.status)}: ${commandLine(t,n)}`)}e.trace(`execInherit [ok] ${t} (${sinceMs(i)})`)}catch(n){let r=n instanceof Error?n.message:String(n);throw e.trace(`execInherit [x] ${t} (${r}, ${sinceMs(i)})`),n}},async fetch(n,r,i){let a=(r?.method??`GET`).toUpperCase();e.trace(`fetch -> ${a} ${n}`);let o=performance.now();try{let s=await t(n,r,i);return e.trace(`fetch [ok] ${a} ${n} (${String(s.status)}, ${sinceMs(o)})`),s}catch(t){let r=t instanceof Error?t.message:String(t);throw e.trace(`fetch [x] ${a} ${n} (${r}, ${sinceMs(o)})`),t}}}}function fileErrorCode(e){if(e instanceof Error&&`code`in e&&typeof e.code==`string`)return e.code}function listWorkspacePackages(e){let t=w.join(e,`packages`),n=[];try{for(let e of h(t)){let r=w.join(t,e,`package.json`);try{let t=parsePackageJson(p(r,`utf-8`));t?.name&&t.version&&n.push({name:t.name,version:t.version,dir:e})}catch{}}}catch{}return n}function readRegularFile(e,t){let n;try{n=f(e,i.O_RDONLY|i.O_NOFOLLOW|i.O_NONBLOCK)}catch(e){let t=fileErrorCode(e);return t===`ENOENT`?{kind:`absent`}:t===`ELOOP`?{kind:`refused`,reason:`symlink`}:{kind:`refused`,reason:`unreadable`}}try{let e=s(n);if(!e.isFile())return{kind:`refused`,reason:`not-regular`};if(e.size>t)return{kind:`refused`,reason:`too-large`};let r=Buffer.alloc(t+1),i;try{i=m(n,r,0,r.length,0)}catch{return{kind:`refused`,reason:`unreadable`}}return i>t?{kind:`refused`,reason:`too-large`}:{kind:`ok`,content:r.toString(`utf8`,0,i)}}catch{return{kind:`refused`,reason:`unreadable`}}finally{r(n)}}function createRealExecutor$1(e=Ke){return{...tracedRunners(e),listChangesetFiles(e){let t=w.join(e,`.changeset`);try{return h(t).filter(e=>e.endsWith(`.md`)&&e!==`README.md`)}catch{return[]}},listWorkspacePackages,listPackageDirs(e){let t=w.join(e,`packages`);try{return h(t,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}},listFiles(e){try{return h(e,{withFileTypes:!0}).filter(e=>e.isFile()).map(e=>e.name)}catch{return[]}},globFiles(e,t){let n=/* @__PURE__ */ new Set;for(let r of t){let t;try{t=c(r,{cwd:e,withFileTypes:!0})}catch{continue}for(let e of t)e.isFile()&&n.add(w.join(e.parentPath,e.name))}return[...n]},readFile(e){try{return p(e,`utf-8`)}catch{return null}},readFileBuffer(e){try{return p(e)}catch{return null}},readRegularFile,writeFile(e,t){u(w.dirname(e),{recursive:!0}),C(e,t)},replaceFile(e,t){u(w.dirname(e),{recursive:!0}),y(e,{recursive:!0,force:!0}),C(e,t,{flag:`wx`})},writeFileBuffer(e,t){u(w.dirname(e),{recursive:!0}),C(e,t)},appendFile(e,t){u(w.dirname(e),{recursive:!0}),n(e,t)},listDirsWithMtime(e){try{return h(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(t=>({name:t.name,mtimeMs:b(w.join(e,t.name)).mtimeMs}))}catch{return[]}},makeDir(e){u(e,{recursive:!0})},removeDir(e){y(e,{recursive:!0,force:!0})}}}function computeSlidingTags(e){let t=(e.split(`-`)[0]??e).split(`.`);if(t.length<2||!t[0]||!t[1])throw new T(`Invalid version format "${e}". Expected semver (X.Y.Z)`);return[`v${t[0]}`,`v${t[0]}.${t[1]}`,`latest`]}function resolveTagCommit(e,t,n){let r=e.exec(`git`,[`rev-parse`,`${n}^{commit}`],{cwd:t}),i=r.stdout.trim();return r.exitCode===0&&i?i:void 0}function exactTag(e,t){return`${e}@${t}`}function computeExpectedTags(e){return e.map(e=>exactTag(e.name,e.version))}function parseRemoteTags(e){let t=[];for(let n of e.split(`
|
|
16
|
+
`)){let e=/refs\/tags\/(.+)/.exec(n);e?.[1]&&!e[1].endsWith(`^{}`)&&t.push(e[1])}return t}function reconcileTags(e,t){let n=new Set(t);return e.filter(e=>!n.has(e))}const wn=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function parseRemoteTagTargets(e){let t=/* @__PURE__ */ new Map;for(let n of e.split(`
|
|
17
|
+
`)){let e=/^([0-9a-f]{7,40})\s+refs\/tags\/(.+)$/.exec(n.trim());if(e?.[1]&&e[2]){if(e[2].endsWith(`^{}`)){let n=e[2].slice(0,-3),r=t.get(n);t.set(n,{ref:r?.ref??e[1],commit:e[1]})}else t.set(e[2],{ref:e[1],commit:e[1]})}}return t}function parseReleaseVersion(e){let t=wn.exec(e.trim());if(t?.[1]&&t[2]&&t[3])return{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:t[4]===void 0?[]:t[4].split(`.`)}}function isPrerelease$1(e){return(parseReleaseVersion(e)?.prerelease.length??0)>0}const Tn=/(?:^|[^\d.])(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)(?:\+[0-9A-Za-z.-]+)?$/u;function tagIsPrerelease(e){let t=Tn.exec(e)?.[1];return t!==void 0&&isPrerelease$1(t)}function comparePrereleaseIdentifier(e,t){let n=/^\d+$/.test(e),r=/^\d+$/.test(t);if(n&&r){let n=Number(e)-Number(t);return n<0?-1:+(n>0)}return n?-1:r?1:e<t?-1:+(e>t)}function comparePrerelease(e,t){let n=Math.min(e.length,t.length);for(let r=0;r<n;r++){let n=comparePrereleaseIdentifier(e[r],t[r]);if(n!==0)return n<0?-1:1}return e.length===t.length?0:e.length<t.length?-1:1}function compareReleaseVersions(e,t){let n=parseReleaseVersion(e),r=parseReleaseVersion(t);if(!n||!r)return 0;let i=[n.major-r.major,n.minor-r.minor,n.patch-r.patch];for(let e of i)if(e!==0)return e<0?-1:1;return n.prerelease.length===0&&r.prerelease.length===0?0:n.prerelease.length===0?1:r.prerelease.length===0?-1:comparePrerelease(n.prerelease,r.prerelease)}function changesetsTagFamily(e){let t=`${e}@`;return{exact:e=>`${t}${e}`,floating:e=>computeSlidingTags(e).map(e=>`${t}${e}`),versionOfExact:e=>{if(!e.startsWith(t))return;let n=e.slice(t.length);if(!(n===`latest`||n.startsWith(`v`)))return parseReleaseVersion(n)?n:void 0}}}function simpleTagFamily(e=`v`){return{exact:t=>`${e}${t}`,floating:e=>computeSlidingTags(e),versionOfExact:t=>{if(!t.startsWith(e))return;let n=t.slice(e.length);return parseReleaseVersion(n)?n:void 0}}}function highestVersionAtSha(e,t,n){let r;for(let[i,a]of t){if(a.commit!==n)continue;let t=e.versionOfExact(i);t!==void 0&&(r===void 0||compareReleaseVersions(t,r)>0)&&(r=t)}return r}function planFloatingTagMoves(e,t,n){let r=n.get(e.exact(t))?.commit,i=[];if(isPrerelease$1(t)){for(let a of e.floating(t)){let e=n.get(a);i.push({tag:a,targetSha:r,observedSha:e?.commit,observedRef:e?.ref,decision:`keep`,reason:`${t} is a prerelease`})}return i}for(let a of e.floating(t)){let o=n.get(a),s=o?.commit,c={tag:a,targetSha:r,observedSha:s,observedRef:o?.ref};if(s===void 0){i.push({...c,decision:`move`,reason:`the tag does not exist yet`});continue}let l=highestVersionAtSha(e,n,s);if(l===void 0){i.push({...c,decision:`move`,reason:`target has no exact version tag`});continue}let u=compareReleaseVersions(t,l);u>0?i.push({...c,decision:`move`,reason:`newer than ${l}`}):u===0?i.push({...c,decision:`current`,reason:`already at ${l}`}):i.push({...c,decision:`keep`,reason:`${l} is newer`})}return i}function reportFloatingTagOutcome(e,t){let n=`moved ${String(e.moved.length)}, kept ${String(e.kept.length)}, failed ${String(e.failed.length)}`;if(e.moved.length===0){I.info(`Floating tags: ${n}`);return}let r=t?`would move`:`moved`;I.info(`Floating tags: ${n} (${r}: ${e.moved.join(`, `)})`)}function describeGitFailure(e){return e.stderr.trim()||e.stdout.trim()||`unknown git error`}function readRemoteTagTargets(e){let t=e.executor.exec(`git`,[...e.options.git.args,`ls-remote`,`--tags`,e.options.git.url],{cwd:e.options.cwd});if(debugExec({verbose:e.options.verbose},`floating tags: ls-remote`,t),t.exitCode!==0)I.warn(`Could not read remote tags for floating tags: ${describeGitFailure(t)}`);else return parseRemoteTagTargets(t.stdout)}function markUnsettledFailed(e,t){for(let n of t)for(let t of n.family.floating(n.version))e.decided.has(t)||e.outcome.failed.push(t)}function moveFloatingTags(e,t,n){let r={executor:e,options:t},i={outcome:{moved:[],kept:[],failed:[]},decided:/* @__PURE__ */ new Set,rejected:[],lastError:``};for(let e=1;e<=5;e++){i.rejected=[];let t=readRemoteTagTargets(r);if(t===void 0)return markUnsettledFailed(i,n),i.outcome;for(let e of n)for(let n of planFloatingTagMoves(e.family,e.version,t))i.decided.has(n.tag)||applyFloatingMove(r,e,n,i);if(i.rejected.length===0)return i.outcome;if(e===5){for(let e of i.rejected)i.outcome.failed.push(e);return I.warn(`Floating tags still rejected after 5 attempts: ${i.rejected.join(`, `)} (${i.lastError})`),i.outcome}}return i.outcome}function applyFloatingMove(e,t,n,r){if(n.decision===`keep`||n.decision===`current`){r.decided.add(n.tag),r.outcome.kept.push(n.tag),I.info(`Leaving ${n.tag} alone: ${n.reason}`);return}let i=t.version,a=n.targetSha??localTarget(e,t);a===void 0?(r.decided.add(n.tag),r.outcome.failed.push(n.tag),I.warn(`Could not resolve the commit for ${n.tag}: no ${t.family.exact(i)} to point it at`)):e.options.dryRun?(r.decided.add(n.tag),r.outcome.moved.push(n.tag),I.info(`[dry-run] Would move ${n.tag} to ${i}`)):pushFloatingMove(e,n,a,r)}function pushFloatingMove(e,t,n,r){let i=e.executor.exec(`git`,[`tag`,`-f`,t.tag,n],{cwd:e.options.cwd});if(debugExec({verbose:e.options.verbose},`floating tags: tag ${t.tag}`,i),i.exitCode!==0){r.decided.add(t.tag),r.outcome.failed.push(t.tag),I.warn(`Failed to create ${t.tag}: ${describeGitFailure(i)}`);return}let a=t.observedRef??``,o=`--force-with-lease=refs/tags/${t.tag}:${a}`,s=e.executor.exec(`git`,[...e.options.git.args,`push`,o,e.options.git.url,`refs/tags/${t.tag}`],{cwd:e.options.cwd});debugExec({verbose:e.options.verbose},`floating tags: push ${t.tag}`,s),s.exitCode===0?(r.decided.add(t.tag),r.outcome.moved.push(t.tag)):(r.lastError=describeGitFailure(s),r.rejected.push(t.tag))}function localTarget(e,t){return resolveTagCommit(e.executor,e.options.cwd,t.family.exact(t.version))}const En=`enforce`,Dn=P.looseObject({version:P.string().optional()});function hasHeadParent(e,t){let n=e.exec(`git`,[`rev-parse`,`--verify`,`--quiet`,`HEAD~1`],{cwd:t});return n.exitCode===0&&n.stdout.trim()!==``}function readAtRev(e,t,n,r){let i=e.exec(`git`,[`show`,`${n}:${r}`],{cwd:t});if(i.exitCode===0)return i.stdout}function versionOf(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}let n=Dn.safeParse(t);return n.success?n.data.version:void 0}function headChangedVersion(e,t,n){let r=versionOf(readAtRev(e,t,`HEAD~1`,n)),i=versionOf(readAtRev(e,t,`HEAD`,n));return r!==void 0&&i!==void 0&&r!==i}function skipLine(e,t){return`${e.imageName} v${e.version??`?`}: HEAD did not change the version in ${t}, so it is not pushed. Publish it by hand with --image ${e.imageName}.`}function selectImagesToPush(e,t,n){let r=t.images??[];return r.length>0?selectNamedImages(r,n):t.releaseStrategy===`changesets`?selectBoundedImages(e,t.cwd,n):{push:[...n],skipped:[]}}function selectNamedImages(e,t){let n=t.map(e=>e.imageName),r=new Set(n),i=e.filter(e=>!r.has(e));if(i.length>0)throw new T(`--image names ${i.join(`, `)}, which no publishable image carries. Publishable images: ${n.join(`, `)}.`);let a=new Set(e),o=[],s=[];for(let e of t)a.has(e.imageName)?o.push(e):(I.info(`${e.imageName}: not named by --image, so it is not pushed.`),s.push(e));return{push:o,skipped:s}}function bumpedByPath(e,t,n,r){let i=r.get(n);if(i!==void 0)return i;let a=headChangedVersion(e,t,n);return r.set(n,a),a}function selectBoundedImages(e,t,n){let r=/* @__PURE__ */ new Set,i=[];for(let e of n)e.versionSource.kind===`override`?r.add(e):i.push(e);let a=new Set(r);if(i.length===0)return{push:n.filter(e=>a.has(e)),skipped:[]};if(!hasHeadParent(e,t))return I.info(`HEAD has no parent commit to compare against, so no image that takes its version from a package.json is pushed. Publish one by hand with --image <name>.`),{push:n.filter(e=>a.has(e)),skipped:n.filter(e=>!a.has(e))};let o=/* @__PURE__ */ new Map;for(let n of i){let r=n.versionSource;if(r.kind===`manifest`){if(bumpedByPath(e,t,r.path,o)){a.add(n);continue}I.info(skipLine(n,r.path))}}return{push:n.filter(e=>a.has(e)),skipped:n.filter(e=>!a.has(e))}}function defaultPublish(e,t){return e===void 0||t!==`enforce`}const On=P.object({name:P.string().optional(),version:P.string().optional()}),kn=P.object({docker:wt.optional(),dockerCheck:P.union([P.literal(!1),Tt]).optional()});function loadDockerConfigSlice(e,t){let n=w.join(t,`.tooling.json`),r=parseToolingConfigSlice(e.readFile(n)??void 0,kn,{block:`docker/dockerCheck`,path:n}),i=r?.dockerCheck;return{overrides:r?.docker??{},composeFiles:i===!1||i===void 0?void 0:i.composeFiles}}function mergeDockerConfig(e,t){if(!t)return e;let n=t.dockerfile??e?.dockerfile;if(n)return{dockerfile:n,context:t.context??e?.context??`.`,buildArgs:t.buildArgs??e?.buildArgs,imageName:t.imageName??e?.imageName,version:t.version,publish:t.publish}}function readPackageInfo(e,t){let n=e.readFile(t);if(n)try{let e=On.safeParse(JSON.parse(n));return e.success?{name:e.data.name,version:e.data.version}:{name:void 0,version:void 0}}catch{return{name:void 0,version:void 0}}}function findEnclosingPackage(e,t,n){let r=w.normalize(w.dirname(n));for(;;){let n=r.split(`/`);if(n[0]!==`packages`||n.length<2)return;let i=`${n.join(`/`)}/package.json`,a=readPackageInfo(e,w.join(t,...n,`package.json`));if(a!==void 0)return{info:a,path:i};r=n.slice(0,-1).join(`/`)}}function resolveDockerVersion(e,t,n){if(n.version!==void 0)return{version:n.version,source:{kind:`override`}};let r=findEnclosingPackage(e,t,n.dockerfile);if(r!==void 0)return{version:r.info.version,source:{kind:`manifest`,path:r.path}};let i=readPackageInfo(e,w.join(t,`package.json`));return i===void 0?{version:void 0,source:{kind:`none`}}:{version:i.version,source:{kind:`manifest`,path:`package.json`}}}function stripScope(e){let t=e.indexOf(`/`);return e.startsWith(`@`)&&t!==-1?e.slice(t+1):e}const An=[`Dockerfile`,`docker/Dockerfile`];function findConventionDockerfile(e,t,n){for(let r of An){let i=`packages/${n}/${r}`;if(e.readFile(w.join(t,i))!==null)return{dockerfile:i,context:`.`}}}function findRootDockerfile(e,t){for(let n of An)if(e.readFile(w.join(t,n))!==null)return{dockerfile:n,context:`.`}}const jn={checkOnlyIn:void 0,phase:En};function createDockerPackage(e,t,n,r){let{dir:i,docker:a,origin:o}=r,s=i===`.`,c=readPackageInfo(e,s?w.join(t,`package.json`):w.join(t,`packages`,i,`package.json`))?.name,l=a.imageName??(s?stripScope(c??n):`${n}-${stripScope(c??i)}`),{version:u,source:d}=resolveDockerVersion(e,t,a);return{dir:i,imageName:l,version:u,versionSource:d,publish:a.publish??defaultPublish(o.checkOnlyIn,o.phase),docker:a,checkOnlyIn:o.checkOnlyIn}}function readComposeSources(e,t,n){let r=resolveComposeFileSet(t=>e.readFile(t),t,n);if(r.sources.length!==0)return{composeDir:r.composeDir,sources:r.sources,checkOverlay:r.checkOverlay}}function discoverComposeImages(e,t,n){let r=readComposeSources(e,t,n);if(!r)return[];let i=parseComposeServiceSources(r.composeDir,r.sources),a=[];for(let e of i){if(e.buildDockerfile===void 0||e.buildContext===void 0||e.image===void 0)continue;if(e.buildHasUnreproducibleKeys){I.debug(`compose service "${e.name}": build sets an unreproducible key; skipping`);continue}let t=roundTripImageName(e.image);t===void 0?I.debug(`compose service "${e.name}": image "${e.image}" is not a name bst can round-trip (unresolved variable, digest pin, or non-latest tag); skipping Docker discovery`):a.push({serviceName:e.name,dockerfileAbs:e.buildDockerfile,contextAbs:e.buildContext,imageName:t,checkOnlyIn:r.checkOverlay!==void 0&&e.declaredIn.length===1&&e.declaredIn[0]===r.checkOverlay?r.checkOverlay:void 0})}return a}function addComposeDiscoveredPackages(e,t,n){let{executor:r,cwd:i,repoName:a,overrides:o,composeFiles:s}=e,c=new Set(t.map(e=>w.resolve(i,e.docker.dockerfile))),l=new Set(t.map(e=>e.imageName)),u=/* @__PURE__ */ new Set;for(let d of discoverComposeImages(r,i,s)){if(u.has(d.imageName)){I.debug(`compose service "${d.serviceName}": image "${d.imageName}" is already claimed by an earlier service; skipping Docker discovery`);continue}u.add(d.imageName);let s=o[d.imageName];if(s!==void 0&&n.add(d.imageName),c.has(d.dockerfileAbs)){if(s!==void 0){let e=t.findIndex(e=>w.resolve(i,e.docker.dockerfile)===d.dockerfileAbs),n=t[e];if(n){let o={dockerfile:n.docker.dockerfile,context:n.docker.context,buildArgs:n.docker.buildArgs??s.buildArgs,imageName:n.docker.imageName??s.imageName,version:n.docker.version??s.version,publish:n.docker.publish??s.publish};t[e]=createDockerPackage(r,i,a,{dir:n.dir,docker:o,origin:jn})}}continue}if(l.has(d.imageName)){let e=t.find(e=>e.imageName===d.imageName);I.warn(`compose service "${d.serviceName}" names image "${d.imageName}", which package "${e?.dir}" (${e?.docker.dockerfile}) already claims by convention or override; the service builds a different Dockerfile (${w.relative(i,d.dockerfileAbs)}) and is being skipped to avoid two Dockerfiles building under one tag`);continue}let f=mergeDockerConfig({dockerfile:w.relative(i,d.dockerfileAbs),context:w.relative(i,d.contextAbs)||`.`,imageName:d.imageName},s);f&&t.push(createDockerPackage(r,i,a,{dir:d.serviceName,docker:f,origin:{checkOnlyIn:d.checkOnlyIn,phase:e.phase}}))}}function extractFromRefs(e){let t=[],n=/^\s*FROM\s+(\S+)/gim,r=n.exec(e);for(;r!==null;){let i=r[1];i!==void 0&&t.push(i.split(`:`)[0]??i),r=n.exec(e)}return t}function localBaseImages(e,t,n){let r=new Set(e.map(e=>e.imageName)),i=/* @__PURE__ */ new Map;for(let a of e){let e=t.readFile(w.join(n,a.docker.dockerfile)),o=[];if(e!==null)for(let t of extractFromRefs(e))t!==a.imageName&&r.has(t)&&!o.includes(t)&&o.push(t);i.set(a.imageName,o)}return i}function sortPackagesByDependency(e,t,n){let r=new Map(e.map((e,t)=>[e.imageName,t])),i=localBaseImages(e,t,n),a=[];for(let t of e){let e=[];for(let n of i.get(t.imageName)??[]){let t=r.get(n);t!==void 0&&e.push(t)}a.push(e)}let o=[],s=/* @__PURE__ */ new Set,c=/* @__PURE__ */ new Set;function visit(t){if(!s.has(t)){if(c.has(t))throw new T(`Docker image dependency cycle detected: "${e[t]?.imageName??String(t)}" is reached from its own FROM chain`);c.add(t);for(let e of a[t]??[])visit(e);c.delete(t),s.add(t),o.push(t)}}for(let t=0;t<e.length;t++)visit(t);let l=[];for(let t of o){let n=e[t];n!==void 0&&l.push(n)}return l}function refuseDuplicateImageNames(e){let t=/* @__PURE__ */ new Map;for(let n of e){let e=t.get(n.imageName);e===void 0?t.set(n.imageName,[n.dir]):e.push(n.dir)}for(let[e,n]of t)if(n.length>1)throw new T(`More than one Docker package builds the image name "${e}": ${n.map(e=>`"${e}"`).join(`, `)}. They would all build the same tag, so set a distinct "imageName" for one of them under .tooling.json#docker`)}function detectDockerPackages(e,t,n,r=En){let{overrides:i,composeFiles:a}=loadDockerConfigSlice(e,t),o=e.listPackageDirs(t),s=[],c=/* @__PURE__ */ new Set;if(o.length>0){let r=findRootDockerfile(e,t),a=i[`.`],l=mergeDockerConfig(r,a);l&&(s.push(createDockerPackage(e,t,n,{dir:`.`,docker:l,origin:jn})),c.add(`.`));for(let r of o){let a=findConventionDockerfile(e,t,r),o=i[r],l=mergeDockerConfig(a,o);l&&(s.push(createDockerPackage(e,t,n,{dir:r,docker:l,origin:jn})),c.add(r))}}else{let r=findRootDockerfile(e,t),a=i[`.`],o=mergeDockerConfig(r,a);o&&s.push(createDockerPackage(e,t,n,{dir:`.`,docker:o,origin:jn}))}if(addComposeDiscoveredPackages({executor:e,cwd:t,repoName:n,overrides:i,composeFiles:a,phase:r},s,c),o.length>0)for(let[r,a]of Object.entries(i)){if(c.has(r))continue;let i=mergeDockerConfig(void 0,a);if(!i)throw new T(`Docker override for "${r}" has no dockerfile: it names no package directory, no convention Dockerfile was found for it, and no compose service was discovered under that image name (TOOLING_DEBUG=true reports which services were skipped and why)`);s.push(createDockerPackage(e,t,n,{dir:r,docker:i,origin:jn}))}return refuseDuplicateImageNames(s),sortPackagesByDependency(s,e,t)}function readSinglePackageDocker(e,t,n,r){let i=w.basename(w.resolve(t,n)),a=findConventionDockerfile(e,t,i),{overrides:o}=loadDockerConfigSlice(e,t),s=o[i],c=mergeDockerConfig(a,s);if(!c)throw new T(`No Dockerfile found for package "${i}" (checked convention paths and .tooling.json)`);return createDockerPackage(e,t,r,{dir:i,docker:c,origin:jn})}function parseSemver(e){let t=e.replace(/^v/,``),n=/^(\d+)\.(\d+)\.(\d+)/.exec(t);if(!n?.[1]||!n[2]||!n[3])throw new T(`Invalid semver version: ${e}`);return{major:Number(n[1]),minor:Number(n[2]),patch:Number(n[3])}}function generateTags(e){let{major:t,minor:n}=parseSemver(e);return[`latest`,exactImageTag(e),`v${t}.${n}`,`v${t}`]}function exactImageTag(e){return parseSemver(e),`v${e.replace(/^v/,``).split(`+`)[0]}`}function imageRef(e,t,n){return imageRegistryHost(t)?`${t}:${n}`:`${e}/${t}:${n}`}function readRepoName(e,t){let n=e.readFile(w.join(t,`package.json`));if(!n)throw new T(`No package.json found in project root`);let r=parsePackageJson(n)?.name;if(!r)throw new T(`Root package.json must have a name field`);return r}const Mn=/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g;function interpolate(e,t,n){return e.replace(Mn,(e,r,i)=>{let a=t[r];return a!==void 0&&a!==``?a:i===void 0?(n?.(r),``):i})}function resolveBuildArgs(e,t){let n=Object.entries(e.docker.buildArgs??{});if(n.length===0)return{};let r=/* @__PURE__ */ new Set,i={};for(let[a,o]of n)i[a]=interpolate(o,t,t=>{r.has(t)||(r.add(t),I.warn(`docker build arg "${a}" for ${e.dir}: env var ${t} is not set; using empty string`))});return i}const Nn=`org.opencontainers.image.version`;function resolveProvenanceLabels(e,t,n){let r=e.exec(`git`,[`rev-parse`,`HEAD`],{cwd:t}),i=r.stdout.trim();if(r.exitCode!==0||i===``)return{};let a=e.exec(`git`,[`rev-parse`,`--show-prefix`],{cwd:t});if(a.exitCode!==0)return{};let o=[a.stdout.trim().replace(/\/$/,``),w.relative(t,w.resolve(t,n)).split(w.sep).join(`/`)].filter(e=>e!==``).join(`/`),s=o===``?`HEAD^{tree}`:`HEAD:${o}`,c=e.exec(`git`,[`rev-parse`,s],{cwd:t}),l=c.stdout.trim();if(c.exitCode!==0||l===``)return{};let u=e.exec(`git`,[`status`,`--porcelain`,`--`,n],{cwd:t});return{"org.opencontainers.image.revision":i,"com.bensandee.tooling.context-tree":`${l}${u.exitCode===0&&u.stdout.trim()!==``?`-dirty`:``}`}}function resolveImageLabels(e,t,n){let r=resolveProvenanceLabels(e,n,t.docker.context);return t.version&&(r[Nn]=t.version),r}function buildImage(e,t,n,r){let i=w.resolve(n,t.docker.dockerfile),a=w.resolve(n,t.docker.context),o=Object.entries(resolveBuildArgs(t,process.env)).map(([e,t])=>`${e}=${t}`);I.info(` build args: ${o.length>0?o.join(` `):`(none)`}`),I.info(` extra args: ${r.length>0?r.join(` `):`(none)`}`);let s=o.flatMap(e=>[`--build-arg`,e]),c=Object.entries(resolveImageLabels(e,t,n)).flatMap(([e,t])=>[`--label`,`${e}=${t}`]);e.execInherit(`docker`,[`build`,`-f`,i,`-t`,`${t.imageName}:latest`,...s,...c,...r,a])}function bakeImages(e,t,n){let r=n.cwd,i=localBaseImages(t,e,r),a=[];for(let o of t){I.info(`Building image for ${o.dir} (${o.imageName}:latest)...`),debug(n,`Dockerfile: ${o.docker.dockerfile}, context: ${o.docker.context}`);let t=resolveBuildArgs(o,process.env),s=Object.entries(t).map(([e,t])=>`${e}=${t}`);I.info(` build args: ${s.length>0?s.join(` `):`(none)`}`),a.push({imageName:o.imageName,dockerfile:w.resolve(r,o.docker.dockerfile),context:w.resolve(r,o.docker.context),args:t,labels:resolveImageLabels(e,o,r),bases:i.get(o.imageName)??[]})}let o=w.join(ye.tmpdir(),`bst-docker-bake-${Se()}`),s=w.join(o,`docker-bake.json`);e.makeDir(o);try{e.writeFile(s,JSON.stringify(buildBakeDefinition(a))),e.execInherit(`docker`,[`buildx`,`bake`,`--file`,s,`--load`],{cwd:r})}finally{e.removeDir(o)}}function runDockerBuild(e,t){let n=readRepoName(e,t.cwd);if(t.packageDir){let r=readSinglePackageDocker(e,t.cwd,t.packageDir,n);return I.info(`Building image for ${r.dir} (${r.imageName}:latest)...`),debug(t,`Dockerfile: ${r.docker.dockerfile}, context: ${r.docker.context}`),buildImage(e,r,t.cwd,t.extraArgs),I.info(`Built ${r.imageName}:latest`),{packages:[r]}}let r=detectDockerPackages(e,t.cwd,n,t.checkOnlyPhase??`enforce`);if(r.length===0)return I.info(`No packages with docker config found`),{packages:[]};I.info(`Found ${String(r.length)} Docker package(s): ${r.map(e=>e.dir).join(`, `)}`);let i=!0;if(t.extraArgs.length>0?(I.info("Building one image at a time: the extra arguments go to `docker build`, and bake does not take them."),i=!1):e.exec(`docker`,[`buildx`,`version`]).exitCode!==0&&(I.info("Building one image at a time: `docker buildx` is not available on this host."),i=!1),i)bakeImages(e,r,t);else for(let n of r)I.info(`Building image for ${n.dir} (${n.imageName}:latest)...`),debug(t,`Dockerfile: ${n.docker.dockerfile}, context: ${n.docker.context}`),buildImage(e,n,t.cwd,t.extraArgs);return I.info(`Built ${String(r.length)} image(s)`),{packages:r}}function tagAndPushPackage(e,t,n,r){let i=n.version??``,a=isPrerelease$1(i),o=generateTags(i),s=exactImageTag(i),c=imageRef(t.registryNamespace,n.imageName,s);I.info(`${n.dir} v${n.version} -> tags: ${o.join(`, `)}`);for(let c of o){let o=imageRef(t.registryNamespace,n.imageName,c);if(a&&c!==s){I.info(`Leaving ${o} alone: ${i} is a prerelease`),r.skipped.push(o);continue}I.info(`Tagging ${n.imageName} -> ${o}`);let l=e.exec(`docker`,[`tag`,n.imageName,o]);if(debugExec(t,`docker tag ${n.imageName} ${o}`,l),l.exitCode!==0)throw new T(`docker tag failed: ${l.stderr}`);t.dryRun&&(r.tags.push(o),I.info(`[dry-run] Skipping push for ${o}`))}if(t.dryRun)return;let l=publishRecord(e,t,c,r);if(!a)for(let a of o)a!==s&&moveFloatingRef(e,t,{version:i,ref:imageRef(t.registryNamespace,n.imageName,a),exactRef:c,recordKept:l},r)}function publishRecord(e,t,n,r){return inspectImageManifest(e,t,n)===void 0?(pushRef(e,t,n),r.tags.push(n),!1):(I.info(`Keeping ${n}: the registry already has this record`),r.kept.push(n),!0)}function moveFloatingRef(e,t,n,r){let{version:i,ref:a,exactRef:o,recordKept:s}=n,c=readPublishedImageVersion(e,t,a);if(s){if(c!==void 0&&parseReleaseVersion(c)!==void 0){let e=compareReleaseVersions(i,c);if(e===0){I.info(`Leaving ${a} alone: already at ${i}`),r.skipped.push(a);return}if(e<0){I.info(`Leaving ${a} at ${c} (newer than ${i})`),r.skipped.push(a);return}}retagFromRecord(e,t,a,o),r.tags.push(a)}else c!==void 0&&compareReleaseVersions(i,c)<0?(I.info(`Leaving ${a} at ${c} (newer than ${i})`),r.skipped.push(a)):(pushRef(e,t,a),r.tags.push(a))}function pushRef(e,t,n){I.info(`Pushing ${n}...`);let r=e.exec(`docker`,[`push`,n]);if(debugExec(t,`docker push ${n}`,r),r.exitCode!==0)throw new T(`docker push failed: ${r.stderr}`)}function retagFromRecord(e,t,n,r){I.info(`Retagging ${n} from the record ${r}...`);let i=e.exec(`docker`,[`buildx`,`imagetools`,`create`,`--tag`,n,r]);if(debugExec(t,`docker buildx imagetools create --tag ${n} ${r}`,i),i.exitCode!==0)throw new T(`imagetools create failed: ${i.stderr}`)}const Pn=P.object({config:P.object({Labels:P.union([P.record(P.string(),P.string()),P.null()]).optional()})}),Fn=P.record(P.string(),Pn);function versionFromImageManifest(e){for(let t of Object.values(e)){let e=t.config.Labels?.[Nn];if(e!==void 0)return e}}function inspectImageManifest(e,t,n){let r=e.exec(`docker`,[`buildx`,`imagetools`,`inspect`,n,`--format`,`{{json .Image}}`]);if(debugExec(t,`docker buildx imagetools inspect ${n}`,r),r.exitCode===0)return r.stdout}function readPublishedImageVersion(e,t,n){let r=inspectImageManifest(e,t,n);if(r===void 0)return;let i;try{i=JSON.parse(r)}catch(e){debug(t,`Could not parse the manifest for ${n}: ${String(e)}`);return}let a=Pn.safeParse(i);if(a.success)return a.data.config.Labels?.[Nn];let o=Fn.safeParse(i);if(o.success)return versionFromImageManifest(o.data);debug(t,`Unexpected manifest shape for ${n}; no version label read`)}function reportCheckOnlyImages(e,t){for(let n of e)n.checkOnlyIn!==void 0&&n.docker.publish===void 0&&(t===`warn`?I.warn(`Image "${n.imageName}" is declared only in ${n.checkOnlyIn}, the check overlay, so a later tooling release stops publishing it by default. Keep it: set publish to true for "${n.imageName}" under .tooling.json#docker. Settle it: set publish to false there, or move the service into a base compose file.`):I.info(`Skipped "${n.imageName}": it is declared only in ${n.checkOnlyIn}, the check overlay, so it was not pushed. Set publish to true for "${n.imageName}" under .tooling.json#docker to publish it anyway.`))}function runDockerPublish(e,t){let n=t.checkOnlyPhase??`enforce`,{packages:r}=runDockerBuild(e,{cwd:t.cwd,packageDir:void 0,extraArgs:[],verbose:t.verbose,checkOnlyPhase:n});if(reportCheckOnlyImages(r,n),r.length===0)return{packages:[],tags:[],skipped:[],kept:[],skippedImages:[]};let i=r.filter(e=>e.publish);if(i.length===0)return{packages:r,tags:[],skipped:[],kept:[],skippedImages:[]};for(let e of i){if(!e.version)throw new T(`Docker image "${e.imageName}" (dockerfile ${e.docker.dockerfile}) has no version to publish. Checked: an explicit "version" override in .tooling.json#docker, the nearest enclosing packages/<name>/package.json walking up from the dockerfile, and the root package.json. Set an explicit version override for this image.`);let n=imageRegistryHost(e.imageName);if(n!==void 0&&n.toLowerCase()!==t.registryHost.toLowerCase())throw new T(`Docker image "${e.imageName}" names registry "${n}", but this run logs in to "${t.registryHost}". Fix one of the three: point the publish target at "${n}" (registryHost/registryNamespace in .tooling.json, or DOCKER_REGISTRY_HOST/DOCKER_REGISTRY_NAMESPACE); override the name via .tooling.json#docker keyed by the discovered image name (e.g. {"docker": {"${e.imageName}": {"imageName": "<unqualified-name>"}}}); or exclude it with {"docker": {"${e.imageName}": {"publish": false}}}.`)}let a=selectImagesToPush(e,t,i),o=a.push,s=a.skipped.map(e=>e.imageName);if(o.length===0)I.info(`No image to push, so this run neither logs in nor logs out.`);else if(t.dryRun)I.info(`[dry-run] Skipping docker login`);else{I.info(`Logging in to ${t.registryHost}...`);let n=e.exec(`docker`,[`login`,t.registryHost,`-u`,t.username,`--password-stdin`],{input:t.password});if(debugExec(t,`docker login`,n),n.exitCode!==0)throw new T(`Docker login failed: ${n.stderr}`)}let c={tags:[],skipped:[],kept:[]};try{for(let n of o)tagAndPushPackage(e,t,n,c)}finally{o.length>0&&!t.dryRun&&(I.info(`Logging out from ${t.registryHost}...`),e.exec(`docker`,[`logout`,t.registryHost]))}return logPublishSummary(c,s,t),{packages:r,...c,skippedImages:s}}function logPublishSummary(e,t,n){if(I.info(`Published ${String(e.tags.length)} image tag(s)`),e.skipped.length>0&&I.info(`Left ${String(e.skipped.length)} floating tag(s) alone: ${e.skipped.join(`, `)}`),e.kept.length>0&&I.info(`Kept ${String(e.kept.length)} record(s) already in the registry: ${e.kept.join(`, `)}`),t.length>0){let e=n.images!==void 0&&n.images.length>0?`not named by --image`:`whose version HEAD did not change`;I.info(`Skipped ${String(t.length)} image(s) ${e}: ${t.join(`, `)}`)}}function keysMatch(e,t,n,r){return e.cwd===t&&e.repoName===n&&e.phase===r}function answersMatch(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function replayMatches(e,t){for(let n of e)if(n.kind===`list`){if(!answersMatch(n.answer,t.listPackageDirs(n.cwd)))return!1}else if(t.readFile(n.path)!==n.answer)return!1;return!0}function recordingReader(e,t){return{listPackageDirs(n){let r=e.listPackageDirs(n);return t.push({kind:`list`,cwd:n,answer:[...r]}),r},readFile(n){let r=e.readFile(n);return t.push({kind:`read`,path:n,answer:r}),r}}}function recordDiscovery(e,t,n,r){let i=[],a=detectDockerPackages(recordingReader(e,i),t,n,r);return{key:{cwd:t,repoName:n,phase:r},reads:i,result:a}}function createDockerDiscoveryMemo(){let e;function detect(t,n,r,i=En){let a=e;if(a!==void 0&&keysMatch(a.key,n,r,i)&&replayMatches(a.reads,t))return[...a.result];let o=recordDiscovery(t,n,r,i);return e=o,[...o.result]}return{detect}}const In=/* @__PURE__ */ new WeakMap;function memoFor(e){if(e.dockerDiscovery!==void 0)return e.dockerDiscovery;let t=In.get(e);if(t!==void 0)return t;let n=createDockerDiscoveryMemo();return In.set(e,n),n}function detectContextDockerPackages(e){return memoFor(e).detect(contextAsDockerReader(e),e.targetDir,e.config.name)}function contextAsDockerReader(e){return{listPackageDirs(e){let t=w.join(e,`packages`);try{return h(t,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}},readFile(t){let n=w.relative(e.targetDir,t);return e.read(n)??null}}}const Ln=`add "publishConfig": { "registry": "<your registry URL>" } to its package.json`;function isUsableRegistry(e){if(typeof e!=`string`||e.trim()===``)return!1;try{let t=new URL(e);return t.protocol===`https:`||t.protocol===`http:`}catch{return!1}}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function lintPublishConfig(e,t){let n=[];for(let r of getPublishablePackages(e,t)){let t=readPackageJson(r.dir);if(!t)continue;let i=w.relative(e,w.join(r.dir,`package.json`)),a=t.publishConfig,o=isRecord(a)?a.registry:void 0;o===void 0?n.push({kind:`missing`,package:r.name,file:i,message:`${r.name} is published from this repo but declares no publishConfig.registry, so its release destination is inherited -- a project .npmrc can repoint it silently. In ${i}, ${Ln}.`}):isUsableRegistry(o)||n.push({kind:`malformed`,package:r.name,file:i,message:`${r.name} declares publishConfig.registry as ${JSON.stringify(o)}, which is not an absolute http(s) URL and cannot be published to. In ${i}, ${Ln}.`})}return n}function declaredPublishRegistries(e,t,n){let r=[];for(let i of getPublishablePackages(e,t,n)){let e=t===`single`?n??readPackageJson(i.dir):readPackageJson(i.dir);if(!e)continue;let a=e.publishConfig,o=isRecord(a)?a.registry:void 0;typeof o==`string`&&isUsableRegistry(o)&&!r.includes(o)&&r.push(o)}return r}const Rn=`Managed by @bensandee/tooling --`;function managedFileHeader(e,t){return t.map(t=>t===``?e:`${e} ${t}`).join(`
|
|
18
18
|
`)+`
|
|
19
|
-
`}const
|
|
20
|
-
`),n=[],r=0;for(;r<t.length;)if(t[r].trim()===
|
|
21
|
-
`),n=[],r=!1;for(let e of t)e.trim()===
|
|
19
|
+
`}const zn=managedFileHeader(`#`,["Managed by @bensandee/tooling -- `bst repo:sync` regenerates this workflow,",`so direct edits are overwritten on the next sync.`,"To preserve changes, wrap them between `# @tooling:custom` and","`# @tooling:endcustom` markers, or stop managing this file by making","`# @bensandee/tooling:ignore` the first line."]),Bn=managedFileHeader(`#`,["Managed by @bensandee/tooling -- `bst repo:sync` keeps the `lint` and","`format` pre-commit commands current. Other commands you add are preserved.","To stop managing this file, make `# @bensandee/tooling:ignore` the first line."]),Vn=`# ${Rn} \`bst repo:sync\` rewrites this skill and archives local edits. To keep your own version, make this line (line 2, inside the frontmatter) read \`# @bensandee/tooling:ignore\`, keeping line 1 as \`---\`.`,Hn=`# @tooling:custom`,Un=`# @tooling:endcustom`;function extractCustomBlocks(e){let t=e.split(`
|
|
20
|
+
`),n=[],r=0;for(;r<t.length;)if(t[r].trim()===Hn){let e=``;for(let n=r-1;n>=0;n--)if(t[n].trim()!==``){e=t[n].trim();break}let i=[t[r]];for(r++;r<t.length&&t[r].trim()!==Un;)i.push(t[r]),r++;r<t.length&&(i.push(t[r]),r++),n.push({anchor:e,lines:i})}else r++;return n}function stripCustomBlocks(e){let t=e.split(`
|
|
21
|
+
`),n=[],r=!1;for(let e of t)e.trim()===Hn?r=!0:r&&e.trim()===Un?r=!1:r||n.push(e);return n.join(`
|
|
22
22
|
`)}function insertCustomBlocks(e,t){if(t.length===0)return e;let n=e.split(`
|
|
23
23
|
`),r=[];for(let e of t){let t=-1;for(let r=0;r<n.length;r++)if(n[r].trim()===e.anchor){t=r;break}t<0&&(t=n.length-1),r.push({afterIndex:t,block:e})}r.sort((e,t)=>t.afterIndex-e.afterIndex);for(let{afterIndex:e,block:t}of r)n.splice(e+1,0,...t.lines);return n.join(`
|
|
24
24
|
`)}function ensureSchemaComment(e,t){return t!==`forgejo`||e.includes(`yaml-language-server`)?e:`# yaml-language-server: $schema=../../.vscode/forgejo-workflow.schema.json
|
|
25
25
|
`+e}function isToolingIgnored(e){return e.split(`
|
|
26
|
-
`,10).some(e=>e.trim().replace(/^#+\s*/,``).startsWith(`@bensandee/tooling:ignore`))}function mergeLefthookCommands(e,t){if(isToolingIgnored(e))return{content:e,changed:!1};try{let n=Oe(e),r=!1;if(!n.hasIn([`pre-commit`,`commands`]))return n.setIn([`pre-commit`,`commands`],t),{content:n.toString(),changed:!0};let i=n.getIn([`pre-commit`,`commands`]);if(!Ce(i))return{content:e,changed:!1};for(let[e,n]of Object.entries(t))i.has(e)||(i.set(e,n),r=!0);return{content:r?n.toString():e,changed:r}}catch{return{content:e,changed:!1}}}function removeLefthookCommand(e,t,n){if(isToolingIgnored(e))return{content:e,changed:!1};try{let r=Oe(e);return r.getIn([`pre-commit`,`commands`,t,`run`])===n?(r.deleteIn([`pre-commit`,`commands`,t]),{content:r.toString(),changed:!0}):{content:e,changed:!1}}catch{return{content:e,changed:!1}}}function normalizeWorkflow(e,t=[]){let n=stripCustomBlocks(e),r=Oe(n);return r.comment=null,r.commentBefore=null,Ae(r,{Node(e,t){`comment`in t&&(t.comment=null),`commentBefore`in t&&(t.commentBefore=null)},Pair(e,n){if(we(n.key)&&n.key.value===`uses`&&we(n.value)&&typeof n.value.value==`string`){let e=n.value.value.replace(/@.*$/,``);if(t.some(t=>t.name===e))return;n.value.value=e}}}),r.toString({lineWidth:0,nullStr:``})}const
|
|
27
|
-
`+r,e.ci)}const
|
|
28
|
-
`),tokenEnv:{NODE_AUTH_TOKEN:actionsExpr(`secrets.NPM_TOKEN`)}}}const
|
|
26
|
+
`,10).some(e=>e.trim().replace(/^#+\s*/,``).startsWith(`@bensandee/tooling:ignore`))}function mergeLefthookCommands(e,t){if(isToolingIgnored(e))return{content:e,changed:!1};try{let n=Oe(e),r=!1;if(!n.hasIn([`pre-commit`,`commands`]))return n.setIn([`pre-commit`,`commands`],t),{content:n.toString(),changed:!0};let i=n.getIn([`pre-commit`,`commands`]);if(!Ce(i))return{content:e,changed:!1};for(let[e,n]of Object.entries(t))i.has(e)||(i.set(e,n),r=!0);return{content:r?n.toString():e,changed:r}}catch{return{content:e,changed:!1}}}function removeLefthookCommand(e,t,n){if(isToolingIgnored(e))return{content:e,changed:!1};try{let r=Oe(e);return r.getIn([`pre-commit`,`commands`,t,`run`])===n?(r.deleteIn([`pre-commit`,`commands`,t]),{content:r.toString(),changed:!0}):{content:e,changed:!1}}catch{return{content:e,changed:!1}}}function normalizeWorkflow(e,t=[]){let n=stripCustomBlocks(e),r=Oe(n);return r.comment=null,r.commentBefore=null,Ae(r,{Node(e,t){`comment`in t&&(t.comment=null),`commentBefore`in t&&(t.commentBefore=null)},Pair(e,n){if(we(n.key)&&n.key.value===`uses`&&we(n.value)&&typeof n.value.value==`string`){let e=n.value.value.replace(/@.*$/,``);if(t.some(t=>t.name===e))return;n.value.value=e}}}),r.toString({lineWidth:0,nullStr:``})}const Wn=/pnpm install --frozen-lockfile(?! && pnpm --filter @bensandee\/tooling\.\.\. build)/g;function applyWorkspaceToolingBuild(e,t){let n=t?.dependencies?.[`@bensandee/tooling`]??t?.devDependencies?.[`@bensandee/tooling`];return n===void 0||!n.startsWith(`workspace:`)?e:e.replaceAll(Wn,`pnpm install --frozen-lockfile && pnpm --filter @bensandee/tooling... build`)}function escapeRegex(e){return e.replaceAll(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const Gn=/^(?<indent>\s*(?:-\s+)?uses:\s*)(?<name>[^\s@#]+)@(?<ref>\S+)(?<comment>[ \t]+#[^\n]*)?$/gm;function extractPinnedActions(e){let t=/* @__PURE__ */ new Map;for(let n of e.matchAll(Gn)){let{name:e,ref:r,comment:i}=n.groups??{};e&&r&&(e.startsWith(`./`)||e.startsWith(`docker://`)||t.has(e)||t.set(e,`${r}${i??``}`))}return t}function preservePinnedActions(e,t,n=[]){let r=e;for(let{name:e,comment:t}of n){let n=new RegExp(String.raw`^(\s*(?:-\s+)?uses:\s*)${escapeRegex(e)}@(\S+)(?:[ \t]+#[^\n]*)?$`,`gm`);r=r.replace(n,`$1${e}@$2 # ${t}`)}if(!t)return r;let i=extractPinnedActions(t);if(i.size===0)return r;for(let[e,t]of i){if(n.some(t=>t.name===e))continue;let i=new RegExp(String.raw`^(\s*(?:-\s+)?uses:\s*)${escapeRegex(e)}@\S+(?:[ \t]+#[^\n]*)?$`,`gm`);r=r.replace(i,`$1${e}@${t}`)}return r}const Kn=`vars.BST_TRUSTED_RUNNER || vars.BST_RUNNER || 'ubuntu-latest'`;function runnerExpr(e){return`\${{ ${e} }}`}function buildWorkflowYaml(e){let t={name:e.name};e.enableEmailNotifications&&(t[`enable-email-notifications`]=!0),t.on=e.on,e.permissions&&(t.permissions=e.permissions),e.concurrency&&(t.concurrency=e.concurrency);let n={[e.jobName]:{...e.jobIf&&{if:e.jobIf},"runs-on":e.runsOn??runnerExpr(`vars.BST_RUNNER || 'ubuntu-latest'`),...e.jobEnv&&{env:e.jobEnv},...e.jobOutputs&&{outputs:e.jobOutputs},steps:e.steps.map(e=>e.step)}};for(let[t,r]of Object.entries(e.extraJobs??{}))n[t]={...r.needs&&{needs:r.needs},...r.if&&{if:r.if},...r[`continue-on-error`]&&{"continue-on-error":!0},"runs-on":r.runsOn??runnerExpr(`vars.BST_RUNNER || 'ubuntu-latest'`),...r.env&&{env:r.env},...r.outputs&&{outputs:r.outputs},steps:r.steps.map(e=>e.step)};t.jobs=n;let r=ke(t,{lineWidth:0,nullStr:``}).replace(/^(?=\S)/gm,(e,t)=>t===0?e:`\n${e}`);return ensureSchemaComment(zn+`
|
|
27
|
+
`+r,e.ci)}const qn=`2026.11.5`,Jn=`7a5b051d6f17d335c502f8047a5175cf3103f347d91942771c60da4e302ebcb0`,Yn=`https://code.orangebikelabs.com/bensandee/common/actions/setup-mise`;function actionsExpr(e){return`\${{ ${e} }}`}function branchNameLiteral(e){return Et.test(e)?e:e.replace(/'/g,`''`)}function isDefaultBranch(e){return`github.ref == 'refs/heads/${branchNameLiteral(e)}'`}function isNotDefaultBranch(e){return`github.ref != 'refs/heads/${branchNameLiteral(e)}'`}function defaultBranchJobEnv(e){return{IS_MAIN:actionsExpr(isDefaultBranch(e))}}const Xn=`env.IS_MAIN == 'true'`;function onlyOnDefaultBranch(e,t){return`${isDefaultBranch(e)} && (${t})`}function npmrcAuthKey(e){return`${e.replace(/^https?:/i,``).replace(/\/+$/,``)}/`}function npmAuthWiring(e,t){let n=t?declaredPublishRegistries(e.targetDir,e.config.structure,e.packageJson):[];if(n.length===0)return{publishRun:e=>e,tokenEnv:{}};let r=[`if [ -n "$NODE_AUTH_TOKEN" ]; then`,` NPM_CONFIG_USERCONFIG="$(mktemp)"`,` export NPM_CONFIG_USERCONFIG`,` if [ -f ~/.npmrc ]; then cat ~/.npmrc > "$NPM_CONFIG_USERCONFIG"; fi`,...n.map(e=>` printf '\\n%s\\n' '${npmrcAuthKey(e)}:_authToken=\${NODE_AUTH_TOKEN}' >> "$NPM_CONFIG_USERCONFIG"`),`fi`];return{publishRun:e=>[...r,e].join(`
|
|
28
|
+
`),tokenEnv:{NODE_AUTH_TOKEN:actionsExpr(`secrets.NPM_TOKEN`)}}}const Zn=`https://github.com/jdx/mise/releases/download/v${qn}/mise-v${qn}-linux-x64`;function pnpmStoreCacheSteps(){return[{step:{id:`pnpm-store`,name:`Locate pnpm store`,run:`echo "dir=$(pnpm store path)" >> "$GITHUB_OUTPUT"`}},{step:{name:`Cache pnpm store`,uses:`actions/cache@v4`,with:{path:actionsExpr(`steps.pnpm-store.outputs.dir`),key:`pnpm-${actionsExpr(`runner.os`)}-${actionsExpr(`hashFiles('pnpm-lock.yaml')`)}`}}}]}const Qn=[{name:Yn,comment:`setup-mise@latest`}];function miseSetupSteps(e){return e===`forgejo`?[{step:{name:`Set up mise`,uses:`${Yn}@ebe622ef0d24c7efec4a5f6093ddb18500900e24`,with:{version:qn,sha256:Jn}}},...pnpmStoreCacheSteps()]:inlineMiseSteps()}function inlineMiseSteps(){let e=[`curl -fsSL -o "$RUNNER_TEMP/mise" `+Zn,`echo "${Jn} $RUNNER_TEMP/mise" | sha256sum -c`,`mkdir -p "$HOME/.local/bin" && install -m 0755 "$RUNNER_TEMP/mise" "$HOME/.local/bin/mise"`,`export MISE_TRUSTED_CONFIG_PATHS="$GITHUB_WORKSPACE"`,`export MISE_YES=1`,`"$HOME/.local/bin/mise" install`,`"$HOME/.local/bin/mise" env --json | "$HOME/.local/bin/mise" exec -- node -e 'const fs = require("fs");
|
|
29
29
|
const env = JSON.parse(fs.readFileSync(0, "utf8"));
|
|
30
30
|
let out = "";
|
|
31
31
|
for (const [key, value] of Object.entries(env)) {
|
|
@@ -37,19 +37,20 @@ fs.appendFileSync(
|
|
|
37
37
|
process.env.GITHUB_PATH,
|
|
38
38
|
process.env.HOME + "/.local/share/mise/shims\\n" + process.env.HOME + "/.local/bin\\n",
|
|
39
39
|
);'`].join(`
|
|
40
|
-
`);return[{step:{name:`Cache mise tools`,uses:`actions/cache@v4`,with:{path:`~/.local/share/mise`,key:`mise-${actionsExpr(`runner.os`)}-${actionsExpr(`hashFiles('mise.toml')`)}`}}},{step:{name:`Install mise`,env:{GITHUB_TOKEN:``},run:e}},...pnpmStoreCacheSteps()]}function dockerPublishEnv(e){let{username:t,password:n}=dockerSecretNames(e);return{...e===null?{DOCKER_REGISTRY_HOST:actionsExpr(`vars.DOCKER_REGISTRY_HOST`),DOCKER_REGISTRY_NAMESPACE:actionsExpr(`vars.DOCKER_REGISTRY_NAMESPACE`)}:{},DOCKER_USERNAME:actionsExpr(`secrets.${t}`),DOCKER_PASSWORD:actionsExpr(`secrets.${n}`),RELEASE_DEBUG:actionsExpr(`vars.RELEASE_DEBUG || 'false'`)}}function isToolingManagedWorkflow(e){return!isToolingIgnored(e)&&e.includes(`Managed by @bensandee/tooling --`)}function retireManagedWorkflow(e,t,n){let r=e.read(t);if(r===void 0)return;if(!isToolingManagedWorkflow(r))return{filePath:t,action:`skipped`,description:`${t} is not managed by tooling, so it was left in place`};e.remove(t);let i=`Moved to .tooling-archived/${t} (${n})`;return extractCustomBlocks(r).length>0&&(i+=`; its # @tooling:custom blocks are kept only in the archive`),{filePath:t,action:`removed`,description:i}}const ir=N.object({registryHost:N.string().optional()});function resolveGenTimeHost(e){let t=e.read(`.tooling.json`);if(t)try{let e=ir.safeParse(JSON.parse(t));if(e.success&&e.data.registryHost&&e.data.registryHost.length>0)return e.data.registryHost}catch(e){F.warn(`Failed to parse .tooling.json: ${e instanceof Error?e.message:e}`)}let n=detectGitRemoteUrl(e.targetDir);if(n!==null){let e=parseGitUrl(n);if(e)return registryHostFromHostname(e.hostname)}let r=e.read(`package.json`);if(!r)return null;let i=parsePackageJson(r)?.repository,a=null;if(typeof i==`string`?a=i:i&&typeof i==`object`&&(a=i.url),typeof a!=`string`)return null;let o=parseGitUrl(a);return o?registryHostFromHostname(o.hostname):null}const ar=N.object({postReleaseHook:N.string().optional(),postReleaseHookSecrets:N.array(N.string()).optional()}),or=N.object({releaseAssets:N.array(Vt).optional()}),sr=N.object({versionStamp:N.array(Ht).optional()}),cr=N.object({deploy:Wt.optional()});function getDeployConfig(e){let t=e.read(`.tooling.json`);if(t)try{let e=cr.safeParse(JSON.parse(t));return e.success?e.data.deploy:void 0}catch(e){F.warn(`Failed to parse .tooling.json: ${e instanceof Error?e.message:e}`);return}}function getPostReleaseHookCommand(e){let t=e.read(`.tooling.json`);if(t)try{let e=ar.safeParse(JSON.parse(t));return e.success?e.data.postReleaseHook:void 0}catch(e){F.warn(`Failed to parse .tooling.json: ${e instanceof Error?e.message:e}`);return}}function getPostReleaseHookSecrets(e){let t=e.read(`.tooling.json`);if(t)try{let e=ar.safeParse(JSON.parse(t));return e.success?e.data.postReleaseHookSecrets:void 0}catch(e){F.warn(`Failed to parse .tooling.json: ${e instanceof Error?e.message:e}`);return}}function getDockerPackageNames(e){return detectContextDockerPackages(e).map(e=>e.imageName)}function hasDockerPackages(e){return getDockerPackageNames(e).length>0}function detectReleaseAssetsConventionDirs(e){let t=[];if(e.config.structure===`monorepo`){let n=getMonorepoPackages(e.targetDir);for(let r of n){let n=w.basename(r.dir),i=e.read(`packages/${n}/package.json`);i&&parsePackageJson(i)?.scripts?.[`build:release-assets`]&&t.push(`packages/${n}`)}}else{let n=e.read(`package.json`);n&&parsePackageJson(n)?.scripts?.[`build:release-assets`]&&t.push(`.`)}return t}function hasReleaseAssets(e){if(detectReleaseAssetsConventionDirs(e).length>0)return!0;let t=e.read(`.tooling.json`);if(!t)return!1;try{let e=or.safeParse(JSON.parse(t));return e.success?!!e.data.releaseAssets&&e.data.releaseAssets.length>0:!1}catch(e){return F.warn(`Failed to parse .tooling.json: ${e instanceof Error?e.message:e}`),!1}}function hasVersionStamp(e){let t=e.read(`.tooling.json`);if(!t)return!1;try{let e=sr.safeParse(JSON.parse(t));return e.success?!!e.data.versionStamp&&e.data.versionStamp.length>0:!1}catch(e){return F.warn(`Failed to parse .tooling.json: ${e instanceof Error?e.message:e}`),!1}}async function generateDeployCi(e){let t=`deploy-ci`;return e.config.ci===`none`?{filePath:t,action:`skipped`,description:`Publish workflow not applicable`}:retireManagedWorkflow(e,e.config.ci===`github`?`.github/workflows/publish.yml`:`.forgejo/workflows/publish.yml`,"run `pnpm exec bst docker:publish` to publish by hand")??{filePath:t,action:`skipped`,description:`No publish workflow to retire`}}const lr=[`.ts`,`.tsx`],ur=[`.js`,`.jsx`,`.mjs`,`.cjs`];function defaultExtensions(e){return e===`typescript`?lr:e===`javascript`?ur:[]}const dr=N.object({health:tolerantBlock(pt).optional()});function defaultSrc(e){return e?[`packages/*/src`]:[`src`]}function resolveFromOverrides(e,t,n){let r=e??{},i=r.enabled===!0;return{enabled:i,src:r.src??defaultSrc(t),exclude:r.exclude??[],extensions:r.extensions??defaultExtensions(n),directoryFileLimit:r.directoryFileLimit??20,fanInLimit:r.fanInLimit??10,fanOutLimit:r.fanOutLimit??10,moduleSizeLimit:r.moduleSizeLimit??200,crossPackage:r.crossPackage??!0,historyEnabled:i&&r.history!==`none`,historyBranch:r.historyBranch??`bst/health-metrics`,tolerance:r.tolerance??0,graphMetricsEnabled:n!==`none`,exempt:r.exempt??{},sizeBudgets:r.sizeBudgets??{}}}function resolveHealthConfigFromContext(e,t){return resolveFromOverrides(parseToolingConfigSlice(e.read(`.tooling.json`),dr,{block:`health`})?.health,t.isMonorepo,e.config.stack)}function detectHealthContext(e){return{stack:resolveStack(e),isMonorepo:o(w.join(e,`packages`))}}function resolveHealthConfig(e){let{stack:t,isMonorepo:n}=detectHealthContext(e);return resolveHealthConfigFromContext({exists:t=>o(w.join(e,t)),read:t=>{let n=w.join(e,t);if(o(n))try{return p(n,`utf-8`)}catch{return}},config:{stack:t}},{isMonorepo:n})}function healthOverridesAt(e){let t=w.join(e,`.tooling.json`),n;if(o(t))try{n=p(t,`utf-8`)}catch{n=void 0}return parseToolingConfigSlice(n,dr,{block:`health`})?.health}function commandSegments(e){return e.split(/&&|\|\|?|;/).map(e=>e.trim())}function lastCommandSegment(e){return commandSegments(e).at(-1)??``}function isCheckScriptForwardingSafe(e){return/(?:^|[\s/])bst\s+checks:run(?=\s|$)/.test(lastCommandSegment(e))}function isCiCheckScriptForwardingSafe(e){return/(?:^|\s)pnpm\s+(?:run\s+)?check(?=\s|$)/.test(lastCommandSegment(e))}function diagnoseCheckScriptForwarding(e){if(!e)return;let t=[],n=e.check;n!==void 0&&!isCheckScriptForwardingSafe(n)&&t.push(`the \`check\` script does not end with \`bst checks:run\` (its last command is \`${lastCommandSegment(n)}\`)`);let r=e[`ci:check`];if(r!==void 0&&!isCiCheckScriptForwardingSafe(r)&&t.push(`the \`ci:check\` script does not end with \`pnpm check\` (its last command is \`${lastCommandSegment(r)}\`)`),t.length!==0)return`Likely cause: ${t.join(`, and `)}. pnpm appends forwarded args (e.g. \`--with-coverage\`, \`--skip 'docker:*'\`) to the end of the resolved script, so they never reach \`bst checks:run\`. Make \`bst checks:run\` the last command -- move extra checks into \`bst checks:run --add <name,...>\`.`}const fr=[`build`,`typecheck`,`lint`,`test`,`knip`,`format`];function recursionIsPinnedToRoot(e){return e.split(/&&|\|\|?|;/).some(e=>{let t=e.trim().split(/\s+/);if(t[0]!==`pnpm`)return!1;let n=!1,r=!1;for(let e of t.slice(1)){if(!e.startsWith(`-`))break;e===`--recursive`?n=!0:e===`--workspace-root`?r=!0:/^-[a-zA-Z]+$/.test(e)&&(e.includes(`r`)&&(n=!0),e.includes(`w`)&&(r=!0))}return n&&r})}function diagnoseToolchainScripts(e){if(!e)return;let t=fr.filter(t=>{let n=e[t];return n!==void 0&&recursionIsPinnedToRoot(n)});if(t.length!==0)return`${t.map(e=>`\`${e}\``).join(`, `)} ${t.length===1?`combines`:`combine`} pnpm's \`-r\` (recursive) with \`-w\` (workspace-root). \`-w\` wins, so the command runs once at the workspace root and never descends into \`packages/*\` -- in a monorepo whose root holds no source, that is a no-op that still exits 0. Drop the \`-w\`.`}function diagnoseCheckScriptForwardingAt(e){let t;try{t=parsePackageJson(p(w.join(e,`package.json`),`utf-8`))?.scripts}catch{return}return diagnoseCheckScriptForwarding(t)}const pr=`@bensandee/agent-cli`;function agentEnabled(e){return agentEnabledIn(e.read(`.tooling.json`))}function wantsAgentCli(e){return!agentEnabled(e)||isWorkspacePackage(e,`@bensandee/agent-cli`)?!1:!readUnmanagedDevDepNames(e).has(pr)}function isWorkspacePackage(e,t){if(e.config.structure!==`monorepo`)return!1;let n=w.join(e.targetDir,`packages`);if(!o(n))return!1;try{for(let e of h(n,{withFileTypes:!0})){if(!e.isDirectory())continue;let r=w.join(n,e.name,`package.json`);if(o(r))try{if(parsePackageJson(p(r,`utf-8`))?.name===t)return!0}catch{}}}catch{}return!1}const mr=N.object({unmanagedDevDependencies:yt.optional()});function readUnmanagedDevDepNames(e){let t=parseToolingConfigSlice(e.read(`.tooling.json`),mr,{block:`unmanagedDevDependencies`});return new Set(t?.unmanagedDevDependencies??[])}const hr=`commit-and-tag-version`;function wantsCommitAndTagVersion(e){return e.config.releaseStrategy===`simple`&&!readUnmanagedDevDepNames(e).has(hr)}const gr=`24.13.0`,_r=`>=${gr}`;function versionPart(e){return e&&e!==`x`&&e!==`*`?Number(e):0}function compareTuples(e,t){for(let n=0;n<3;n++)if(e[n]!==t[n])return e[n]-t[n];return 0}function conjunctionFloor(e){let t;for(let n of e.trim().split(/\s+/)){if(!n||n.startsWith(`<`))continue;let e=/(\d+)(?:\.(\d+|x|\*))?(?:\.(\d+|x|\*))?/.exec(n);if(!e)continue;let r=[Number(e[1]),versionPart(e[2]),versionPart(e[3])];(!t||compareTuples(r,t)>0)&&(t=r)}return t}function minVersionTuple(e){let t;for(let n of e.split(`||`)){let e=conjunctionFloor(n);if(!e)return;(!t||compareTuples(e,t)<0)&&(t=e)}return t}function removeDevEnginesRuntime(e){return e.devEngines?.runtime?(delete e.devEngines.runtime,Object.keys(e.devEngines).length===0&&delete e.devEngines,!0):!1}const vr={check:`bst checks:run`,"ci:check":`pnpm check --skip 'docker:*'`,"tooling:check":`bst repo:sync --check`,"docs:check":`bst docs:check`,"tooling:sync":`bst repo:sync`},yr={test:`vitest run`,"test:coverage":`vitest run --coverage`,lint:`oxlint`,"lint:report":`bst lint:report`,knip:`knip`},br={test:`pnpm -r test`,"test:coverage":`vitest run --coverage`,lint:`oxlint`,"lint:report":`bst lint:report`,knip:`knip`},xr={typecheck:`tsc --noEmit`,"lint:types":`bst lint:types`},Sr={typecheck:`pnpm -r --parallel run typecheck`,"lint:types":`bst lint:types`},Cr={build:`tsdown`,dev:`tsdown --watch`},wr={build:`pnpm -r build`};function standardScripts(e){let t=e.structure===`monorepo`,n={...vr};return e.stack!==`none`&&Object.assign(n,t?br:yr),e.stack===`typescript`&&Object.assign(n,t?Sr:xr),e.stack!==`none`&&e.builder===`tsdown`&&Object.assign(n,t?wr:Cr),n}const Tr={check:`bst checks:run`,"ci:check":`pnpm check`,"tooling:check":`bst repo:sync --check`,"docs:check":`bst docs:check`,"tooling:sync":`bst repo:sync`,"trigger-release":`bst release:trigger`,"docker:build":`bst docker:build`,"docker:check":`bst docker:check`,"health:check":`bst health:check`,"lint:types":`bst lint:types`};function matchesManagedScript(e,t){return e.includes(t)}function perPackageDevDeps(e){let t={};return e.stack===`none`||(Object.assign(t,vitestDevDeps()),e.stack===`typescript`&&(t.typescript={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.0.5`,"commit-and-tag-version":`13.3.0`,knip:`6.44.0`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.196`,oxfmt:`0.75.0`,oxlint:`1.90.0`,"oxlint-tsgolint":`7.0.2005`,prettier:`3.9.10`,"release-it":`21.1.1`,tsdown:`0.23.4`,typescript:`6.0.3`,vitest:`5.0.5`,pnpm:`11.28.9`}.typescript,t[`@types/node`]={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.0.5`,"commit-and-tag-version":`13.3.0`,knip:`6.44.0`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.196`,oxfmt:`0.75.0`,oxlint:`1.90.0`,"oxlint-tsgolint":`7.0.2005`,prettier:`3.9.10`,"release-it":`21.1.1`,tsdown:`0.23.4`,typescript:`6.0.3`,vitest:`5.0.5`,pnpm:`11.28.9`}[`@types/node`]),e.builder===`tsdown`&&(t.tsdown={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.0.5`,"commit-and-tag-version":`13.3.0`,knip:`6.44.0`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.196`,oxfmt:`0.75.0`,oxlint:`1.90.0`,"oxlint-tsgolint":`7.0.2005`,prettier:`3.9.10`,"release-it":`21.1.1`,tsdown:`0.23.4`,typescript:`6.0.3`,vitest:`5.0.5`,pnpm:`11.28.9`}.tsdown)),t}function vitestDevDeps(){return{vitest:{"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.0.5`,"commit-and-tag-version":`13.3.0`,knip:`6.44.0`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.196`,oxfmt:`0.75.0`,oxlint:`1.90.0`,"oxlint-tsgolint":`7.0.2005`,prettier:`3.9.10`,"release-it":`21.1.1`,tsdown:`0.23.4`,typescript:`6.0.3`,vitest:`5.0.5`,pnpm:`11.28.9`}.vitest,"@vitest/coverage-v8":{"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.0.5`,"commit-and-tag-version":`13.3.0`,knip:`6.44.0`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.196`,oxfmt:`0.75.0`,oxlint:`1.90.0`,"oxlint-tsgolint":`7.0.2005`,prettier:`3.9.10`,"release-it":`21.1.1`,tsdown:`0.23.4`,typescript:`6.0.3`,vitest:`5.0.5`,pnpm:`11.28.9`}[`@vitest/coverage-v8`]}}function rootDevDeps(e){let t={lefthook:{"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.0.5`,"commit-and-tag-version":`13.3.0`,knip:`6.44.0`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.196`,oxfmt:`0.75.0`,oxlint:`1.90.0`,"oxlint-tsgolint":`7.0.2005`,prettier:`3.9.10`,"release-it":`21.1.1`,tsdown:`0.23.4`,typescript:`6.0.3`,vitest:`5.0.5`,pnpm:`11.28.9`}.lefthook};return e.stack!==`none`&&(t.knip={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.0.5`,"commit-and-tag-version":`13.3.0`,knip:`6.44.0`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.196`,oxfmt:`0.75.0`,oxlint:`1.90.0`,"oxlint-tsgolint":`7.0.2005`,prettier:`3.9.10`,"release-it":`21.1.1`,tsdown:`0.23.4`,typescript:`6.0.3`,vitest:`5.0.5`,pnpm:`11.28.9`}.knip,t.oxlint={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.0.5`,"commit-and-tag-version":`13.3.0`,knip:`6.44.0`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.196`,oxfmt:`0.75.0`,oxlint:`1.90.0`,"oxlint-tsgolint":`7.0.2005`,prettier:`3.9.10`,"release-it":`21.1.1`,tsdown:`0.23.4`,typescript:`6.0.3`,vitest:`5.0.5`,pnpm:`11.28.9`}.oxlint,Object.assign(t,vitestDevDeps())),e.stack===`typescript`&&(t[`oxlint-tsgolint`]={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.0.5`,"commit-and-tag-version":`13.3.0`,knip:`6.44.0`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.196`,oxfmt:`0.75.0`,oxlint:`1.90.0`,"oxlint-tsgolint":`7.0.2005`,prettier:`3.9.10`,"release-it":`21.1.1`,tsdown:`0.23.4`,typescript:`6.0.3`,vitest:`5.0.5`,pnpm:`11.28.9`}[`oxlint-tsgolint`]),t}function addReleaseDeps(e,t){switch(t.config.releaseStrategy){case`release-it`:e[`release-it`]={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.0.5`,"commit-and-tag-version":`13.3.0`,knip:`6.44.0`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.196`,oxfmt:`0.75.0`,oxlint:`1.90.0`,"oxlint-tsgolint":`7.0.2005`,prettier:`3.9.10`,"release-it":`21.1.1`,tsdown:`0.23.4`,typescript:`6.0.3`,vitest:`5.0.5`,pnpm:`11.28.9`}[`release-it`],t.config.structure===`monorepo`&&(e[`@release-it/bumper`]={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.0.5`,"commit-and-tag-version":`13.3.0`,knip:`6.44.0`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.196`,oxfmt:`0.75.0`,oxlint:`1.90.0`,"oxlint-tsgolint":`7.0.2005`,prettier:`3.9.10`,"release-it":`21.1.1`,tsdown:`0.23.4`,typescript:`6.0.3`,vitest:`5.0.5`,pnpm:`11.28.9`}[`@release-it/bumper`]);break;case`simple`:wantsCommitAndTagVersion(t)&&(e[hr]={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.0.5`,"commit-and-tag-version":`13.3.0`,knip:`6.44.0`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.196`,oxfmt:`0.75.0`,oxlint:`1.90.0`,"oxlint-tsgolint":`7.0.2005`,prettier:`3.9.10`,"release-it":`21.1.1`,tsdown:`0.23.4`,typescript:`6.0.3`,vitest:`5.0.5`,pnpm:`11.28.9`}[`commit-and-tag-version`]);break;case`changesets`:e[`@changesets/cli`]={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.0.5`,"commit-and-tag-version":`13.3.0`,knip:`6.44.0`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.196`,oxfmt:`0.75.0`,oxlint:`1.90.0`,"oxlint-tsgolint":`7.0.2005`,prettier:`3.9.10`,"release-it":`21.1.1`,tsdown:`0.23.4`,typescript:`6.0.3`,vitest:`5.0.5`,pnpm:`11.28.9`}[`@changesets/cli`]}}function mergeManagedScripts(e,t,n){let r=e.scripts??{};for(let[e,i]of Object.entries(t))(e!==`lint:report`||r.lint===void 0||r.lint===t.lint)&&(e in r?e in Tr&&!matchesManagedScript(r[e]??``,Tr[e]??``)&&(r[e]=i,n.push(`updated script: ${e}`)):(r[e]=i,n.push(`added script: ${e}`)));e.scripts=r}function isProtocolSpec(e){return e.includes(`:`)}function isBelowPin(e,t){if(isProtocolSpec(e)||isProtocolSpec(t))return!1;let n=minVersionTuple(e),r=minVersionTuple(t);return!n||!r?!1:compareTuples(n,r)<0}function mergeManagedDevDeps(e,t,n,r){let i=e.devDependencies??{};for(let[e,a]of Object.entries(t)){if(n.has(e))continue;let t=i[e];t===void 0?(i[e]=a,r.push(`added devDependency: ${e}`)):e.startsWith(`@bensandee/`)?t!==a&&t!==`workspace:*`&&(i[e]=a,r.push(`updated devDependency: ${e} to ${a}`)):isBelowPin(t,a)&&(i[e]=a,r.push(`bumped devDependency: ${e} ${t} -> ${a}`))}e.devDependencies=i}const Er=/* @__PURE__ */ new Set([`tsdown`]);function tsdownConfigIsReclaimable(e){return e.read(`tsdown.config.ts`)===void 0}function reclaimManagedDevDeps(e,t,n,r,i){if(e.config.structure===`monorepo`)return;let a=t.devDependencies;if(a){for(let t of Er)r.has(t)||t in n||(t!==`tsdown`||tsdownConfigIsReclaimable(e))&&t in a&&(delete a[t],i.push(`removed devDependency: ${t} (no longer used)`));t.devDependencies=a}}function migrateAsciiCheckScript(e,t){let n=e.scripts;if(n===void 0)return;let r=n[`ascii:check`];r!==void 0&&(r===`bst ascii:check`?(delete n[`ascii:check`],t.push(`renamed script: ascii:check -> chars:check`)):F.warn(`package.json: the ascii:check script is not the generated one, so the rename to chars:check leaves it alone. Rename it by hand: "ascii:check": "${r}" becomes "chars:check": "bst chars:check".`))}function isCharsCheckEnabled(e){let t=parseToolingConfigSlice(e.read(`.tooling.json`),N.object({chars:z.optional(),ascii:z.optional()}),{block:`chars`});return isCharsGateOn(t?.chars??t?.ascii)}function applyMetadataDefaults(e,t,n){let r=e.dependencies??{},i=`@bensandee/common`,a=r[i];if(a!==void 0&&a!==`workspace:*`){let o=isWorkspacePackage(t,i),s=o?`workspace:*`:`0.2.0`;(o||isBelowPin(a,s))&&(r[i]=s,e.dependencies=r,n.push(`updated dependency: ${i} to ${s}`))}if(!e.repository){let r=detectGitRemoteUrl(t.targetDir);r&&(e.repository=r,n.push(`added repository from git remote`))}e.engines||(e.engines={node:_r},n.push(`set engines.node ${_r}`)),removeDevEnginesRuntime(e)&&n.push(`removed devEngines.runtime (mise.toml declares the runtime)`);let o={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.0.5`,"commit-and-tag-version":`13.3.0`,knip:`6.44.0`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.196`,oxfmt:`0.75.0`,oxlint:`1.90.0`,"oxlint-tsgolint":`7.0.2005`,prettier:`3.9.10`,"release-it":`21.1.1`,tsdown:`0.23.4`,typescript:`6.0.3`,vitest:`5.0.5`,pnpm:`11.28.9`}.pnpm,s=o?`pnpm@${o}`:void 0;if(s){let t=e.packageManager;if(!t)e.packageManager=s,n.push(`set packageManager: ${s}`);else{let r=/^pnpm@(\d+)\./.exec(t);r&&Number(r[1])<11&&(e.packageManager=s,n.push(`bumped packageManager: ${t} -> ${s}`))}}}function buildManagedScripts(e){let t=standardScripts(e.config),n=e.config.formatter===`oxfmt`?`oxfmt .`:`prettier --write .`,r={...t,format:n};return e.config.releaseStrategy===`changesets`&&(r.changeset=`changeset`),e.config.releaseStrategy!==`none`&&e.config.releaseStrategy!==`changesets`&&(r[`trigger-release`]=`bst release:trigger`),hasDockerPackages(e)&&(r[`docker:build`]=`bst docker:build`,r[`docker:check`]=`bst docker:check`),resolveHealthConfigFromContext(e,{isMonorepo:e.config.structure===`monorepo`}).enabled&&(r[`health:check`]=`bst health:check`),isCharsCheckEnabled(e)&&(r[`chars:check`]=`bst chars:check`),r}function buildManagedDevDeps(e){let t=e.config.structure===`monorepo`,n={...rootDevDeps(e.config)};return t||Object.assign(n,perPackageDevDeps(e.config)),e.config.stack!==`none`&&(n[`@bensandee/config`]=isWorkspacePackage(e,`@bensandee/config`)?`workspace:*`:`0.15.1`),isWorkspacePackage(e,`@bensandee/tooling`)||(n[`@bensandee/tooling`]=`0.107.0`),e.config.useEslintPlugin&&e.config.stack!==`none`&&(n[`@bensandee/eslint-plugin`]=isWorkspacePackage(e,`@bensandee/eslint-plugin`)?`workspace:*`:`0.18.0`),wantsAgentCli(e)&&(n[pr]=`0.3.3`),e.config.formatter===`oxfmt`&&(n.oxfmt={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.0.5`,"commit-and-tag-version":`13.3.0`,knip:`6.44.0`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.196`,oxfmt:`0.75.0`,oxlint:`1.90.0`,"oxlint-tsgolint":`7.0.2005`,prettier:`3.9.10`,"release-it":`21.1.1`,tsdown:`0.23.4`,typescript:`6.0.3`,vitest:`5.0.5`,pnpm:`11.28.9`}.oxfmt),e.config.formatter===`prettier`&&(n.prettier={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.0.5`,"commit-and-tag-version":`13.3.0`,knip:`6.44.0`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.196`,oxfmt:`0.75.0`,oxlint:`1.90.0`,"oxlint-tsgolint":`7.0.2005`,prettier:`3.9.10`,"release-it":`21.1.1`,tsdown:`0.23.4`,typescript:`6.0.3`,vitest:`5.0.5`,pnpm:`11.28.9`}.prettier),addReleaseDeps(n,e),n}async function generatePackageJson(e){let t=`package.json`,n=e.read(t),r=buildManagedScripts(e),i=readUnmanagedDevDepNames(e),a=buildManagedDevDeps(e);if(n!==void 0&&n.trim()!==``){let o=parsePackageJson(n);if(!o)return{filePath:t,action:`failed`,description:`Could not parse existing package.json -- ${describePackageJsonFailure(n)??`unknown error`}`};let s=[];o.type!==`module`&&(o.type=`module`,s.push(`set type: "module"`)),migrateAsciiCheckScript(o,s),mergeManagedScripts(o,r,s);let c=diagnoseCheckScriptForwarding(o.scripts??{});c&&F.warn(`package.json: pnpm-forwarded check flags may be dropped. ${c}`);let l=diagnoseToolchainScripts(o.scripts??{});return l&&F.warn(`package.json: a toolchain script may be a silent no-op. ${l}`),mergeManagedDevDeps(o,a,i,s),reclaimManagedDevDeps(e,o,a,i,s),applyMetadataDefaults(o,e,s),s.length===0?{filePath:t,action:`skipped`,description:`Already up to spec`}:(e.write(t,JSON.stringify(o,null,2)+`
|
|
41
|
-
`),{filePath:t,action:`updated`,description:s.join(`, `)})}let o=detectGitRemoteUrl(e.targetDir),s={name:e.config.name,version:`0.1.0`,private:!0,...o&&{repository:o},type:`module`,scripts:r,devDependencies:Object.fromEntries(Object.entries(a).filter(([e])=>!i.has(e))),engines:{node:
|
|
42
|
-
`),{filePath:t,action:`created`,description:`Generated package.json`}}async function generateWorkspaceEngines(e){if(e.config.structure!==`monorepo`)return[];let t=[];for(let n of getMonorepoPackages(e.targetDir)){let r=removeWorkspaceDevEnginesRuntime(e,w.join(w.relative(e.targetDir,n.dir),`package.json`));r&&t.push(r)}return t}function removeWorkspaceDevEnginesRuntime(e,t){let n=e.read(t);if(!n)return;let r=parsePackageJson(n);if(!r?.devEngines?.runtime)return;let i=Object.keys(r.devEngines).length===1?[`devEngines`]:[`devEngines`,`runtime`],a=he(n,ge(n,i,void 0,{}));return e.write(t,a),{filePath:t,action:`updated`,description:`removed devEngines.runtime (mise.toml declares the runtime)`}}function reportStaleConfig(e,t){return
|
|
43
|
-
`}function withMergedVerbatimKey(e){let t=parseTsconfig(e);return t.compilerOptions={...t.compilerOptions,[
|
|
44
|
-
`}async function generateTsconfig(e){let t=`tsconfig.json`,n=e.read(t);if(e.config.structure===`monorepo`)return[generateMonorepoRootTsconfig(e),...e.config.detectPackageTypes?generateMonorepoPackageTsconfigs(e):[]];let r=`@bensandee/config/tsconfig/${e.config.projectType}`;if(e.config.stack!==`typescript`){let i=extendsNodePreset(r),a=buildGeneratedTsconfig(e,r),o=buildGeneratedTsconfig(e,r,{include:
|
|
45
|
-
`),{filePath:t,action:`updated`,description:a.join(`, `)})}function generateMonorepoRootTsconfig(e){let t=`tsconfig.json`;return e.read(t)?{filePath:t,action:`skipped`,description:`Root tsconfig left as-is`}:{filePath:t,action:`skipped`,description:`No tsconfig.json found`}}function generateMonorepoPackageTsconfigs(e){let t=getMonorepoPackages(e.targetDir),n=[];for(let r of t){let t=w.relative(e.targetDir,r.dir),i=w.join(t,`tsconfig.json`),a=e.read(i),o=detectProjectType(r.dir),s=`@bensandee/config/tsconfig/${o}`;if(a){if(a.includes(`// @bensandee/tooling:ignore`)){n.push({filePath:i,action:`skipped`,description:`Ignored via tooling:ignore comment`});continue}let r=parseTsconfig(a);if(isSolutionStyle(r)){n.push({filePath:i,action:`skipped`,description:`Solution-style tsconfig -- traversing references`});for(let i of r.references??[]){let r=w.join(t,resolveReferencePath(i.path));n.push(mergeSingleTsconfig(e,r,s))}continue}warnIfNarrowInclude(e,i,r.include);let c=[];if(r.extends!==s){let e=r.extends;r.extends=s,c.push(e?`changed extends: ${String(e)} -> ${s}`:`added extends: ${s}`)}if(!r.include&&e.exists(w.join(t,`src`))&&(r.include=[...
|
|
46
|
-
`),n.push({filePath:i,action:`updated`,description:c.join(`, `)})}else e.write(i,buildGeneratedTsconfig(e,s,{dir:t})),n.push({filePath:i,action:`created`,description:`Generated tsconfig.json with @bensandee/config/tsconfig/${o} (detected ${o})`})}return n}const
|
|
40
|
+
`);return[{step:{name:`Cache mise tools`,uses:`actions/cache@v4`,with:{path:`~/.local/share/mise`,key:`mise-${actionsExpr(`runner.os`)}-${actionsExpr(`hashFiles('mise.toml')`)}`}}},{step:{name:`Install mise`,env:{GITHUB_TOKEN:``},run:e}},...pnpmStoreCacheSteps()]}function dockerPublishEnv(e){let{username:t,password:n}=dockerSecretNames(e);return{...e===null?{DOCKER_REGISTRY_HOST:actionsExpr(`vars.DOCKER_REGISTRY_HOST`),DOCKER_REGISTRY_NAMESPACE:actionsExpr(`vars.DOCKER_REGISTRY_NAMESPACE`)}:{},DOCKER_USERNAME:actionsExpr(`secrets.${t}`),DOCKER_PASSWORD:actionsExpr(`secrets.${n}`),RELEASE_DEBUG:actionsExpr(`vars.RELEASE_DEBUG || 'false'`)}}function isToolingManagedWorkflow(e){return!isToolingIgnored(e)&&e.includes(`Managed by @bensandee/tooling --`)}function retireManagedWorkflow(e,t,n){let r=e.read(t);if(r===void 0)return;if(!isToolingManagedWorkflow(r))return{filePath:t,action:`skipped`,description:`${t} is not managed by tooling, so it was left in place`};e.remove(t);let i=`Moved to .tooling-archived/${t} (${n})`;return extractCustomBlocks(r).length>0&&(i+=`; its # @tooling:custom blocks are kept only in the archive`),{filePath:t,action:`removed`,description:i}}const $n=P.object({registryHost:P.string().optional()});function resolveGenTimeHost(e){let t=e.read(`.tooling.json`);if(t)try{let e=$n.safeParse(JSON.parse(t));if(e.success&&e.data.registryHost&&e.data.registryHost.length>0)return e.data.registryHost}catch(e){I.warn(`Failed to parse .tooling.json: ${e instanceof Error?e.message:e}`)}let n=detectGitRemoteUrl(e.targetDir);if(n!==null){let e=parseGitUrl(n);if(e)return registryHostFromHostname(e.hostname)}let r=e.read(`package.json`);if(!r)return null;let i=parsePackageJson(r)?.repository,a=null;if(typeof i==`string`?a=i:i&&typeof i==`object`&&(a=i.url),typeof a!=`string`)return null;let o=parseGitUrl(a);return o?registryHostFromHostname(o.hostname):null}const er=P.object({postReleaseHook:P.string().optional(),postReleaseHookSecrets:P.array(P.string()).optional()}),tr=P.object({releaseAssets:P.array(Bt).optional()}),nr=P.object({versionStamp:P.array(Vt).optional()}),rr=P.object({deploy:Ut.optional()});function getDeployConfig(e){let t=e.read(`.tooling.json`);if(t)try{let e=rr.safeParse(JSON.parse(t));return e.success?e.data.deploy:void 0}catch(e){I.warn(`Failed to parse .tooling.json: ${e instanceof Error?e.message:e}`);return}}function getPostReleaseHookCommand(e){let t=e.read(`.tooling.json`);if(t)try{let e=er.safeParse(JSON.parse(t));return e.success?e.data.postReleaseHook:void 0}catch(e){I.warn(`Failed to parse .tooling.json: ${e instanceof Error?e.message:e}`);return}}function getPostReleaseHookSecrets(e){let t=e.read(`.tooling.json`);if(t)try{let e=er.safeParse(JSON.parse(t));return e.success?e.data.postReleaseHookSecrets:void 0}catch(e){I.warn(`Failed to parse .tooling.json: ${e instanceof Error?e.message:e}`);return}}function getDockerPackageNames(e){return detectContextDockerPackages(e).map(e=>e.imageName)}function hasDockerPackages(e){return getDockerPackageNames(e).length>0}function detectReleaseAssetsConventionDirs(e){let t=[];if(e.config.structure===`monorepo`){let n=getMonorepoPackages(e.targetDir);for(let r of n){let n=w.basename(r.dir),i=e.read(`packages/${n}/package.json`);i&&parsePackageJson(i)?.scripts?.[`build:release-assets`]&&t.push(`packages/${n}`)}}else{let n=e.read(`package.json`);n&&parsePackageJson(n)?.scripts?.[`build:release-assets`]&&t.push(`.`)}return t}function hasReleaseAssets(e){if(detectReleaseAssetsConventionDirs(e).length>0)return!0;let t=e.read(`.tooling.json`);if(!t)return!1;try{let e=tr.safeParse(JSON.parse(t));return e.success?!!e.data.releaseAssets&&e.data.releaseAssets.length>0:!1}catch(e){return I.warn(`Failed to parse .tooling.json: ${e instanceof Error?e.message:e}`),!1}}function hasVersionStamp(e){let t=e.read(`.tooling.json`);if(!t)return!1;try{let e=nr.safeParse(JSON.parse(t));return e.success?!!e.data.versionStamp&&e.data.versionStamp.length>0:!1}catch(e){return I.warn(`Failed to parse .tooling.json: ${e instanceof Error?e.message:e}`),!1}}async function generateDeployCi(e){let t=`deploy-ci`;return e.config.ci===`none`?{filePath:t,action:`skipped`,description:`Publish workflow not applicable`}:retireManagedWorkflow(e,e.config.ci===`github`?`.github/workflows/publish.yml`:`.forgejo/workflows/publish.yml`,"run `pnpm exec bst docker:publish` to publish by hand")??{filePath:t,action:`skipped`,description:`No publish workflow to retire`}}const ir=[`.ts`,`.tsx`],ar=[`.js`,`.jsx`,`.mjs`,`.cjs`];function defaultExtensions(e){return e===`typescript`?ir:e===`javascript`?ar:[]}const or=P.object({health:tolerantBlock(pt).optional()});function defaultSrc(e){return e?[`packages/*/src`]:[`src`]}function resolveFromOverrides(e,t,n){let r=e??{},i=r.enabled===!0;return{enabled:i,src:r.src??defaultSrc(t),exclude:r.exclude??[],extensions:r.extensions??defaultExtensions(n),directoryFileLimit:r.directoryFileLimit??20,fanInLimit:r.fanInLimit??10,fanOutLimit:r.fanOutLimit??10,moduleSizeLimit:r.moduleSizeLimit??200,crossPackage:r.crossPackage??!0,historyEnabled:i&&r.history!==`none`,historyBranch:r.historyBranch??`bst/health-metrics`,tolerance:r.tolerance??0,graphMetricsEnabled:n!==`none`,exempt:r.exempt??{},sizeBudgets:r.sizeBudgets??{}}}function resolveHealthConfigFromContext(e,t){return resolveFromOverrides(parseToolingConfigSlice(e.read(`.tooling.json`),or,{block:`health`})?.health,t.isMonorepo,e.config.stack)}function detectHealthContext(e){return{stack:resolveStack(e),isMonorepo:o(w.join(e,`packages`))}}function resolveHealthConfig(e){let{stack:t,isMonorepo:n}=detectHealthContext(e);return resolveHealthConfigFromContext({exists:t=>o(w.join(e,t)),read:t=>{let n=w.join(e,t);if(o(n))try{return p(n,`utf-8`)}catch{return}},config:{stack:t}},{isMonorepo:n})}function healthOverridesAt(e){let t=w.join(e,`.tooling.json`),n;if(o(t))try{n=p(t,`utf-8`)}catch{n=void 0}return parseToolingConfigSlice(n,or,{block:`health`})?.health}function commandSegments(e){return e.split(/&&|\|\|?|;/).map(e=>e.trim())}function lastCommandSegment(e){return commandSegments(e).at(-1)??``}function isCheckScriptForwardingSafe(e){return/(?:^|[\s/])bst\s+checks:run(?=\s|$)/.test(lastCommandSegment(e))}function isCiCheckScriptForwardingSafe(e){return/(?:^|\s)pnpm\s+(?:run\s+)?check(?=\s|$)/.test(lastCommandSegment(e))}function diagnoseCheckScriptForwarding(e){if(!e)return;let t=[],n=e.check;n!==void 0&&!isCheckScriptForwardingSafe(n)&&t.push(`the \`check\` script does not end with \`bst checks:run\` (its last command is \`${lastCommandSegment(n)}\`)`);let r=e[`ci:check`];if(r!==void 0&&!isCiCheckScriptForwardingSafe(r)&&t.push(`the \`ci:check\` script does not end with \`pnpm check\` (its last command is \`${lastCommandSegment(r)}\`)`),t.length!==0)return`Likely cause: ${t.join(`, and `)}. pnpm appends forwarded args (e.g. \`--with-coverage\`, \`--skip 'docker:*'\`) to the end of the resolved script, so they never reach \`bst checks:run\`. Make \`bst checks:run\` the last command -- move extra checks into \`bst checks:run --add <name,...>\`.`}const sr=[`build`,`typecheck`,`lint`,`test`,`knip`,`format`];function recursionIsPinnedToRoot(e){return e.split(/&&|\|\|?|;/).some(e=>{let t=e.trim().split(/\s+/);if(t[0]!==`pnpm`)return!1;let n=!1,r=!1;for(let e of t.slice(1)){if(!e.startsWith(`-`))break;e===`--recursive`?n=!0:e===`--workspace-root`?r=!0:/^-[a-zA-Z]+$/.test(e)&&(e.includes(`r`)&&(n=!0),e.includes(`w`)&&(r=!0))}return n&&r})}function diagnoseToolchainScripts(e){if(!e)return;let t=sr.filter(t=>{let n=e[t];return n!==void 0&&recursionIsPinnedToRoot(n)});if(t.length!==0)return`${t.map(e=>`\`${e}\``).join(`, `)} ${t.length===1?`combines`:`combine`} pnpm's \`-r\` (recursive) with \`-w\` (workspace-root). \`-w\` wins, so the command runs once at the workspace root and never descends into \`packages/*\` -- in a monorepo whose root holds no source, that is a no-op that still exits 0. Drop the \`-w\`.`}function diagnoseCheckScriptForwardingAt(e){let t;try{t=parsePackageJson(p(w.join(e,`package.json`),`utf-8`))?.scripts}catch{return}return diagnoseCheckScriptForwarding(t)}const cr=`@bensandee/agent-cli`;function agentEnabled(e){return agentEnabledIn(e.read(`.tooling.json`))}function wantsAgentCli(e){return!agentEnabled(e)||isWorkspacePackage(e,`@bensandee/agent-cli`)?!1:!readUnmanagedDevDepNames(e).has(cr)}function isWorkspacePackage(e,t){if(e.config.structure!==`monorepo`)return!1;let n=w.join(e.targetDir,`packages`);if(!o(n))return!1;try{for(let e of h(n,{withFileTypes:!0})){if(!e.isDirectory())continue;let r=w.join(n,e.name,`package.json`);if(o(r))try{if(parsePackageJson(p(r,`utf-8`))?.name===t)return!0}catch{}}}catch{}return!1}const lr=P.object({unmanagedDevDependencies:yt.optional()});function readUnmanagedDevDepNames(e){let t=parseToolingConfigSlice(e.read(`.tooling.json`),lr,{block:`unmanagedDevDependencies`});return new Set(t?.unmanagedDevDependencies??[])}const ur=`commit-and-tag-version`;function wantsCommitAndTagVersion(e){return e.config.releaseStrategy===`simple`&&!readUnmanagedDevDepNames(e).has(ur)}const dr=`24.13.0`,fr=`>=${dr}`;function versionPart(e){return e&&e!==`x`&&e!==`*`?Number(e):0}function compareTuples(e,t){for(let n=0;n<3;n++)if(e[n]!==t[n])return e[n]-t[n];return 0}function conjunctionFloor(e){let t;for(let n of e.trim().split(/\s+/)){if(!n||n.startsWith(`<`))continue;let e=/(\d+)(?:\.(\d+|x|\*))?(?:\.(\d+|x|\*))?/.exec(n);if(!e)continue;let r=[Number(e[1]),versionPart(e[2]),versionPart(e[3])];(!t||compareTuples(r,t)>0)&&(t=r)}return t}function minVersionTuple(e){let t;for(let n of e.split(`||`)){let e=conjunctionFloor(n);if(!e)return;(!t||compareTuples(e,t)<0)&&(t=e)}return t}function removeDevEnginesRuntime(e){return e.devEngines?.runtime?(delete e.devEngines.runtime,Object.keys(e.devEngines).length===0&&delete e.devEngines,!0):!1}const pr={check:`bst checks:run`,"ci:check":`pnpm check --skip 'docker:*'`,"tooling:check":`bst repo:sync --check`,"docs:check":`bst docs:check`,"tooling:sync":`bst repo:sync`},mr={test:`vitest run`,"test:coverage":`vitest run --coverage`,lint:`oxlint`,"lint:report":`bst lint:report`,knip:`knip`},hr={test:`pnpm -r test`,"test:coverage":`vitest run --coverage`,lint:`oxlint`,"lint:report":`bst lint:report`,knip:`knip`},gr={typecheck:`tsc --noEmit`,"lint:types":`bst lint:types`},_r={typecheck:`pnpm -r --parallel run typecheck`,"lint:types":`bst lint:types`},vr={build:`tsdown`,dev:`tsdown --watch`},yr={build:`pnpm -r build`};function standardScripts(e){let t=e.structure===`monorepo`,n={...pr};return e.stack!==`none`&&Object.assign(n,t?hr:mr),e.stack===`typescript`&&Object.assign(n,t?_r:gr),e.stack!==`none`&&e.builder===`tsdown`&&Object.assign(n,t?yr:vr),n}const br={check:`bst checks:run`,"ci:check":`pnpm check`,"tooling:check":`bst repo:sync --check`,"docs:check":`bst docs:check`,"tooling:sync":`bst repo:sync`,"trigger-release":`bst release:trigger`,"docker:build":`bst docker:build`,"docker:check":`bst docker:check`,"health:check":`bst health:check`,"lint:types":`bst lint:types`};function matchesManagedScript(e,t){return e.includes(t)}function perPackageDevDeps(e){let t={};return e.stack===`none`||(Object.assign(t,vitestDevDeps()),e.stack===`typescript`&&(t.typescript={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.1.0`,"commit-and-tag-version":`13.3.0`,knip:`6.44.1`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.197`,oxfmt:`0.76.0`,oxlint:`1.91.0`,"oxlint-tsgolint":`7.0.2006`,prettier:`3.9.10`,"release-it":`21.1.2`,tsdown:`0.23.7`,typescript:`6.0.3`,vitest:`5.1.0`,pnpm:`11.28.11`}.typescript,t[`@types/node`]={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.1.0`,"commit-and-tag-version":`13.3.0`,knip:`6.44.1`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.197`,oxfmt:`0.76.0`,oxlint:`1.91.0`,"oxlint-tsgolint":`7.0.2006`,prettier:`3.9.10`,"release-it":`21.1.2`,tsdown:`0.23.7`,typescript:`6.0.3`,vitest:`5.1.0`,pnpm:`11.28.11`}[`@types/node`]),e.builder===`tsdown`&&(t.tsdown={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.1.0`,"commit-and-tag-version":`13.3.0`,knip:`6.44.1`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.197`,oxfmt:`0.76.0`,oxlint:`1.91.0`,"oxlint-tsgolint":`7.0.2006`,prettier:`3.9.10`,"release-it":`21.1.2`,tsdown:`0.23.7`,typescript:`6.0.3`,vitest:`5.1.0`,pnpm:`11.28.11`}.tsdown)),t}function vitestDevDeps(){return{vitest:{"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.1.0`,"commit-and-tag-version":`13.3.0`,knip:`6.44.1`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.197`,oxfmt:`0.76.0`,oxlint:`1.91.0`,"oxlint-tsgolint":`7.0.2006`,prettier:`3.9.10`,"release-it":`21.1.2`,tsdown:`0.23.7`,typescript:`6.0.3`,vitest:`5.1.0`,pnpm:`11.28.11`}.vitest,"@vitest/coverage-v8":{"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.1.0`,"commit-and-tag-version":`13.3.0`,knip:`6.44.1`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.197`,oxfmt:`0.76.0`,oxlint:`1.91.0`,"oxlint-tsgolint":`7.0.2006`,prettier:`3.9.10`,"release-it":`21.1.2`,tsdown:`0.23.7`,typescript:`6.0.3`,vitest:`5.1.0`,pnpm:`11.28.11`}[`@vitest/coverage-v8`]}}function rootDevDeps(e){let t={lefthook:{"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.1.0`,"commit-and-tag-version":`13.3.0`,knip:`6.44.1`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.197`,oxfmt:`0.76.0`,oxlint:`1.91.0`,"oxlint-tsgolint":`7.0.2006`,prettier:`3.9.10`,"release-it":`21.1.2`,tsdown:`0.23.7`,typescript:`6.0.3`,vitest:`5.1.0`,pnpm:`11.28.11`}.lefthook};return e.stack!==`none`&&(t.knip={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.1.0`,"commit-and-tag-version":`13.3.0`,knip:`6.44.1`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.197`,oxfmt:`0.76.0`,oxlint:`1.91.0`,"oxlint-tsgolint":`7.0.2006`,prettier:`3.9.10`,"release-it":`21.1.2`,tsdown:`0.23.7`,typescript:`6.0.3`,vitest:`5.1.0`,pnpm:`11.28.11`}.knip,t.oxlint={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.1.0`,"commit-and-tag-version":`13.3.0`,knip:`6.44.1`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.197`,oxfmt:`0.76.0`,oxlint:`1.91.0`,"oxlint-tsgolint":`7.0.2006`,prettier:`3.9.10`,"release-it":`21.1.2`,tsdown:`0.23.7`,typescript:`6.0.3`,vitest:`5.1.0`,pnpm:`11.28.11`}.oxlint,Object.assign(t,vitestDevDeps())),e.stack===`typescript`&&(t[`oxlint-tsgolint`]={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.1.0`,"commit-and-tag-version":`13.3.0`,knip:`6.44.1`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.197`,oxfmt:`0.76.0`,oxlint:`1.91.0`,"oxlint-tsgolint":`7.0.2006`,prettier:`3.9.10`,"release-it":`21.1.2`,tsdown:`0.23.7`,typescript:`6.0.3`,vitest:`5.1.0`,pnpm:`11.28.11`}[`oxlint-tsgolint`]),t}function addReleaseDeps(e,t){switch(t.config.releaseStrategy){case`release-it`:e[`release-it`]={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.1.0`,"commit-and-tag-version":`13.3.0`,knip:`6.44.1`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.197`,oxfmt:`0.76.0`,oxlint:`1.91.0`,"oxlint-tsgolint":`7.0.2006`,prettier:`3.9.10`,"release-it":`21.1.2`,tsdown:`0.23.7`,typescript:`6.0.3`,vitest:`5.1.0`,pnpm:`11.28.11`}[`release-it`],t.config.structure===`monorepo`&&(e[`@release-it/bumper`]={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.1.0`,"commit-and-tag-version":`13.3.0`,knip:`6.44.1`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.197`,oxfmt:`0.76.0`,oxlint:`1.91.0`,"oxlint-tsgolint":`7.0.2006`,prettier:`3.9.10`,"release-it":`21.1.2`,tsdown:`0.23.7`,typescript:`6.0.3`,vitest:`5.1.0`,pnpm:`11.28.11`}[`@release-it/bumper`]);break;case`simple`:wantsCommitAndTagVersion(t)&&(e[ur]={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.1.0`,"commit-and-tag-version":`13.3.0`,knip:`6.44.1`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.197`,oxfmt:`0.76.0`,oxlint:`1.91.0`,"oxlint-tsgolint":`7.0.2006`,prettier:`3.9.10`,"release-it":`21.1.2`,tsdown:`0.23.7`,typescript:`6.0.3`,vitest:`5.1.0`,pnpm:`11.28.11`}[`commit-and-tag-version`]);break;case`changesets`:e[`@changesets/cli`]={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.1.0`,"commit-and-tag-version":`13.3.0`,knip:`6.44.1`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.197`,oxfmt:`0.76.0`,oxlint:`1.91.0`,"oxlint-tsgolint":`7.0.2006`,prettier:`3.9.10`,"release-it":`21.1.2`,tsdown:`0.23.7`,typescript:`6.0.3`,vitest:`5.1.0`,pnpm:`11.28.11`}[`@changesets/cli`]}}function mergeManagedScripts(e,t,n){let r=e.scripts??{};for(let[e,i]of Object.entries(t))(e!==`lint:report`||r.lint===void 0||r.lint===t.lint)&&(e in r?e in br&&!matchesManagedScript(r[e]??``,br[e]??``)&&(r[e]=i,n.push(`updated script: ${e}`)):(r[e]=i,n.push(`added script: ${e}`)));e.scripts=r}function isProtocolSpec(e){return e.includes(`:`)}function isBelowPin(e,t){if(isProtocolSpec(e)||isProtocolSpec(t))return!1;let n=minVersionTuple(e),r=minVersionTuple(t);return!n||!r?!1:compareTuples(n,r)<0}function mergeManagedDevDeps(e,t,n,r){let i=e.devDependencies??{};for(let[e,a]of Object.entries(t)){if(n.has(e))continue;let t=i[e];t===void 0?(i[e]=a,r.push(`added devDependency: ${e}`)):e.startsWith(`@bensandee/`)?t!==a&&t!==`workspace:*`&&(i[e]=a,r.push(`updated devDependency: ${e} to ${a}`)):isBelowPin(t,a)&&(i[e]=a,r.push(`bumped devDependency: ${e} ${t} -> ${a}`))}e.devDependencies=i}const xr=/* @__PURE__ */ new Set([`tsdown`]);function tsdownConfigIsReclaimable(e){return e.read(`tsdown.config.ts`)===void 0}function reclaimManagedDevDeps(e,t,n,r,i){if(e.config.structure===`monorepo`)return;let a=t.devDependencies;if(a){for(let t of xr)r.has(t)||t in n||(t!==`tsdown`||tsdownConfigIsReclaimable(e))&&t in a&&(delete a[t],i.push(`removed devDependency: ${t} (no longer used)`));t.devDependencies=a}}function migrateAsciiCheckScript(e,t){let n=e.scripts;if(n===void 0)return;let r=n[`ascii:check`];r!==void 0&&(r===`bst ascii:check`?(delete n[`ascii:check`],t.push(`renamed script: ascii:check -> chars:check`)):I.warn(`package.json: the ascii:check script is not the generated one, so the rename to chars:check leaves it alone. Rename it by hand: "ascii:check": "${r}" becomes "chars:check": "bst chars:check".`))}function isCharsCheckEnabled(e){let t=parseToolingConfigSlice(e.read(`.tooling.json`),P.object({chars:B.optional(),ascii:B.optional()}),{block:`chars`});return isCharsGateOn(t?.chars??t?.ascii)}function applyMetadataDefaults(e,t,n){let r=e.dependencies??{},i=`@bensandee/common`,a=r[i];if(a!==void 0&&a!==`workspace:*`){let o=isWorkspacePackage(t,i),s=o?`workspace:*`:`0.2.0`;(o||isBelowPin(a,s))&&(r[i]=s,e.dependencies=r,n.push(`updated dependency: ${i} to ${s}`))}if(!e.repository){let r=detectGitRemoteUrl(t.targetDir);r&&(e.repository=r,n.push(`added repository from git remote`))}e.engines||(e.engines={node:fr},n.push(`set engines.node ${fr}`)),removeDevEnginesRuntime(e)&&n.push(`removed devEngines.runtime (mise.toml declares the runtime)`);let o={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.1.0`,"commit-and-tag-version":`13.3.0`,knip:`6.44.1`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.197`,oxfmt:`0.76.0`,oxlint:`1.91.0`,"oxlint-tsgolint":`7.0.2006`,prettier:`3.9.10`,"release-it":`21.1.2`,tsdown:`0.23.7`,typescript:`6.0.3`,vitest:`5.1.0`,pnpm:`11.28.11`}.pnpm,s=o?`pnpm@${o}`:void 0;if(s){let t=e.packageManager;if(!t)e.packageManager=s,n.push(`set packageManager: ${s}`);else{let r=/^pnpm@(\d+)\./.exec(t);r&&Number(r[1])<11&&(e.packageManager=s,n.push(`bumped packageManager: ${t} -> ${s}`))}}}function buildManagedScripts(e){let t=standardScripts(e.config),n=e.config.formatter===`oxfmt`?`oxfmt .`:`prettier --write .`,r={...t,format:n};return e.config.releaseStrategy===`changesets`&&(r.changeset=`changeset`),e.config.releaseStrategy!==`none`&&e.config.releaseStrategy!==`changesets`&&(r[`trigger-release`]=`bst release:trigger`),hasDockerPackages(e)&&(r[`docker:build`]=`bst docker:build`,r[`docker:check`]=`bst docker:check`),resolveHealthConfigFromContext(e,{isMonorepo:e.config.structure===`monorepo`}).enabled&&(r[`health:check`]=`bst health:check`),isCharsCheckEnabled(e)&&(r[`chars:check`]=`bst chars:check`),r}function buildManagedDevDeps(e){let t=e.config.structure===`monorepo`,n={...rootDevDeps(e.config)};return t||Object.assign(n,perPackageDevDeps(e.config)),e.config.stack!==`none`&&(n[`@bensandee/config`]=isWorkspacePackage(e,`@bensandee/config`)?`workspace:*`:`0.15.1`),isWorkspacePackage(e,`@bensandee/tooling`)||(n[`@bensandee/tooling`]=`0.109.0`),e.config.useEslintPlugin&&e.config.stack!==`none`&&(n[`@bensandee/eslint-plugin`]=isWorkspacePackage(e,`@bensandee/eslint-plugin`)?`workspace:*`:`0.18.0`),wantsAgentCli(e)&&(n[cr]=`0.4.0`),e.config.formatter===`oxfmt`&&(n.oxfmt={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.1.0`,"commit-and-tag-version":`13.3.0`,knip:`6.44.1`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.197`,oxfmt:`0.76.0`,oxlint:`1.91.0`,"oxlint-tsgolint":`7.0.2006`,prettier:`3.9.10`,"release-it":`21.1.2`,tsdown:`0.23.7`,typescript:`6.0.3`,vitest:`5.1.0`,pnpm:`11.28.11`}.oxfmt),e.config.formatter===`prettier`&&(n.prettier={"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.1.0`,"commit-and-tag-version":`13.3.0`,knip:`6.44.1`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.197`,oxfmt:`0.76.0`,oxlint:`1.91.0`,"oxlint-tsgolint":`7.0.2006`,prettier:`3.9.10`,"release-it":`21.1.2`,tsdown:`0.23.7`,typescript:`6.0.3`,vitest:`5.1.0`,pnpm:`11.28.11`}.prettier),addReleaseDeps(n,e),n}async function generatePackageJson(e){let t=`package.json`,n=e.read(t),r=buildManagedScripts(e),i=readUnmanagedDevDepNames(e),a=buildManagedDevDeps(e);if(n!==void 0&&n.trim()!==``){let o=parsePackageJson(n);if(!o)return{filePath:t,action:`failed`,description:`Could not parse existing package.json -- ${describePackageJsonFailure(n)??`unknown error`}`};let s=[];o.type!==`module`&&(o.type=`module`,s.push(`set type: "module"`)),migrateAsciiCheckScript(o,s),mergeManagedScripts(o,r,s);let c=diagnoseCheckScriptForwarding(o.scripts??{});c&&I.warn(`package.json: pnpm-forwarded check flags may be dropped. ${c}`);let l=diagnoseToolchainScripts(o.scripts??{});return l&&I.warn(`package.json: a toolchain script may be a silent no-op. ${l}`),mergeManagedDevDeps(o,a,i,s),reclaimManagedDevDeps(e,o,a,i,s),applyMetadataDefaults(o,e,s),s.length===0?{filePath:t,action:`skipped`,description:`Already up to spec`}:(e.write(t,JSON.stringify(o,null,2)+`
|
|
41
|
+
`),{filePath:t,action:`updated`,description:s.join(`, `)})}let o=detectGitRemoteUrl(e.targetDir),s={name:e.config.name,version:`0.1.0`,private:!0,...o&&{repository:o},type:`module`,scripts:r,devDependencies:Object.fromEntries(Object.entries(a).filter(([e])=>!i.has(e))),engines:{node:fr},packageManager:`pnpm@${{"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.1.0`,"commit-and-tag-version":`13.3.0`,knip:`6.44.1`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.197`,oxfmt:`0.76.0`,oxlint:`1.91.0`,"oxlint-tsgolint":`7.0.2006`,prettier:`3.9.10`,"release-it":`21.1.2`,tsdown:`0.23.7`,typescript:`6.0.3`,vitest:`5.1.0`,pnpm:`11.28.11`}.pnpm}`};return e.write(t,JSON.stringify(s,null,2)+`
|
|
42
|
+
`),{filePath:t,action:`created`,description:`Generated package.json`}}async function generateWorkspaceEngines(e){if(e.config.structure!==`monorepo`)return[];let t=[];for(let n of getMonorepoPackages(e.targetDir)){let r=removeWorkspaceDevEnginesRuntime(e,w.join(w.relative(e.targetDir,n.dir),`package.json`));r&&t.push(r)}return t}function removeWorkspaceDevEnginesRuntime(e,t){let n=e.read(t);if(!n)return;let r=parsePackageJson(n);if(!r?.devEngines?.runtime)return;let i=Object.keys(r.devEngines).length===1?[`devEngines`]:[`devEngines`,`runtime`],a=he(n,ge(n,i,void 0,{}));return e.write(t,a),{filePath:t,action:`updated`,description:`removed devEngines.runtime (mise.toml declares the runtime)`}}function reportStaleConfig(e,t){return I.warn(`${e} is stale: ${t}, so nothing reads it. bst does not delete it -- remove it yourself, or correct the stack/builder in .tooling.json if this is wrong.`),{filePath:e,action:`skipped`,description:`Stale (${t}); left in place`}}const Sr=[`src`,`test`,`*.ts`],Cr=[`src`];function formatInclude(e){return`[${e.map(e=>JSON.stringify(e)).join(`, `)}]`}function describeInclude(e){return`added include: ${formatInclude(e)}`}function warnIfNarrowInclude(e,t,n){if(!Array.isArray(n)||n.length!==Cr.length||!n.every((e,t)=>e===Cr[t]))return;let r=w.join(w.dirname(t),`test`);e.exists(r)&&I.warn(`${t}: "include" is ${formatInclude(n)}, so a test/ directory beside it sits outside tsc --noEmit and its types go unchecked. Consider "include": ${formatInclude(Sr)}.`)}const wr=`@bensandee/config/tsconfig/node`;function extendsNodePreset(e){return e===void 0?!1:Array.isArray(e)?e.includes(wr):e===wr}const Tr=`verbatimModuleSyntax`;function buildGeneratedTsconfig(e,t,n={}){let r=n.dir??`.`,i=n.include??Sr,a={extends:t,...n.verbatimModuleSyntax?{compilerOptions:{[Tr]:!0}}:{},...e.exists(w.join(r,`src`))?{include:[...i]}:{}};return JSON.stringify(a,null,2)+`
|
|
43
|
+
`}function withMergedVerbatimKey(e){let t=parseTsconfig(e);return t.compilerOptions={...t.compilerOptions,[Tr]:!0},JSON.stringify(t,null,2)+`
|
|
44
|
+
`}async function generateTsconfig(e){let t=`tsconfig.json`,n=e.read(t);if(e.config.structure===`monorepo`)return[generateMonorepoRootTsconfig(e),...e.config.detectPackageTypes?generateMonorepoPackageTsconfigs(e):[]];let r=`@bensandee/config/tsconfig/${e.config.projectType}`;if(e.config.stack!==`typescript`){let i=extendsNodePreset(r),a=buildGeneratedTsconfig(e,r),o=buildGeneratedTsconfig(e,r,{include:Cr}),s=/* @__PURE__ */ new Set([buildGeneratedTsconfig(e,r,{verbatimModuleSyntax:i}),buildGeneratedTsconfig(e,r,{verbatimModuleSyntax:i,include:Cr}),a,o,...i?[withMergedVerbatimKey(a),withMergedVerbatimKey(o)]:[]]);return n!==void 0&&s.has(n)?[reportStaleConfig(t,`stack is ${e.config.stack}`)]:[{filePath:t,action:`skipped`,description:`Stack is ${e.config.stack}; tsconfig.json not managed`}]}if(!n)return e.write(t,buildGeneratedTsconfig(e,r,{verbatimModuleSyntax:extendsNodePreset(r)})),[{filePath:t,action:`created`,description:`Generated tsconfig.json with ${r}`}];if(n.includes(`// @bensandee/tooling:ignore`))return[{filePath:t,action:`skipped`,description:`Ignored via tooling:ignore comment`}];let i=parseTsconfig(n);if(isSolutionStyle(i)){let n=[{filePath:t,action:`skipped`,description:`Solution-style tsconfig -- traversing references`}];for(let t of i.references??[]){let i=resolveReferencePath(t.path);n.push(mergeSingleTsconfig(e,i,r))}return n}return[mergeSingleTsconfig(e,t,r)]}function isSolutionStyle(e){return Array.isArray(e.references)&&e.references.length>0&&Array.isArray(e.files)&&e.files.length===0}function resolveReferencePath(e){let t=e.endsWith(`.json`)?e:w.join(e,`tsconfig.json`);return w.normalize(t)}function mergeSingleTsconfig(e,t,n){let r=e.read(t);if(!r)return{filePath:t,action:`skipped`,description:`File not found`};if(r.includes(`// @bensandee/tooling:ignore`))return{filePath:t,action:`skipped`,description:`Ignored via tooling:ignore comment`};let i=parseTsconfig(r);warnIfNarrowInclude(e,t,i.include);let a=[];if(i.extends||(i.extends=n,a.push(`added extends: ${n}`)),extendsNodePreset(i.extends)&&i.compilerOptions?.[Tr]===void 0&&(i.compilerOptions={...i.compilerOptions,[Tr]:!0},a.push(`added compilerOptions.${Tr}: true`)),!i.include){let n=w.dirname(t),r=n===`.`?`src`:w.join(n,`src`);e.exists(r)&&(i.include=[...Sr],a.push(describeInclude(Sr)))}return a.length===0?{filePath:t,action:`skipped`,description:`Already up to spec`}:(e.write(t,JSON.stringify(i,null,2)+`
|
|
45
|
+
`),{filePath:t,action:`updated`,description:a.join(`, `)})}function generateMonorepoRootTsconfig(e){let t=`tsconfig.json`;return e.read(t)?{filePath:t,action:`skipped`,description:`Root tsconfig left as-is`}:{filePath:t,action:`skipped`,description:`No tsconfig.json found`}}function generateMonorepoPackageTsconfigs(e){let t=getMonorepoPackages(e.targetDir),n=[];for(let r of t){let t=w.relative(e.targetDir,r.dir),i=w.join(t,`tsconfig.json`),a=e.read(i),o=detectProjectType(r.dir),s=`@bensandee/config/tsconfig/${o}`;if(a){if(a.includes(`// @bensandee/tooling:ignore`)){n.push({filePath:i,action:`skipped`,description:`Ignored via tooling:ignore comment`});continue}let r=parseTsconfig(a);if(isSolutionStyle(r)){n.push({filePath:i,action:`skipped`,description:`Solution-style tsconfig -- traversing references`});for(let i of r.references??[]){let r=w.join(t,resolveReferencePath(i.path));n.push(mergeSingleTsconfig(e,r,s))}continue}warnIfNarrowInclude(e,i,r.include);let c=[];if(r.extends!==s){let e=r.extends;r.extends=s,c.push(e?`changed extends: ${String(e)} -> ${s}`:`added extends: ${s}`)}if(!r.include&&e.exists(w.join(t,`src`))&&(r.include=[...Sr],c.push(describeInclude(Sr))),c.length===0){n.push({filePath:i,action:`skipped`,description:`Already up to spec (${o})`});continue}e.write(i,JSON.stringify(r,null,2)+`
|
|
46
|
+
`),n.push({filePath:i,action:`updated`,description:c.join(`, `)})}else e.write(i,buildGeneratedTsconfig(e,s,{dir:t})),n.push({filePath:i,action:`created`,description:`Generated tsconfig.json with @bensandee/config/tsconfig/${o} (detected ${o})`})}return n}const Er=[`lines`,`statements`,`branches`,`functions`],Dr=.1;function round2$1(e){return Math.round(e*100)/100}function compareTotals(e,t,n=Dr,r){let i=Er.map(i=>{let a=e[i],o=t[i];return{key:i,baseline:a,current:o,delta:round2$1(o-a),pass:r!==void 0&&o>=r||o>=a||a-o<=n}}),a=i.every(e=>e.pass);return r===void 0?{pass:a,tolerancePp:n,totals:i}:{pass:a,tolerancePp:n,floorPp:r,totals:i}}function isFlatOrUp(e,t){return Er.every(n=>t[n]>=e[n])}function mergeTotalsWithFloor(e,t,n){let r={...e};for(let i of Er)(t[i]>=n||t[i]>=e[i])&&(r[i]=t[i]);return r}const Or=P.object({total:P.number(),covered:P.number(),skipped:P.number().optional(),pct:P.number()}),kr=P.object({lines:Or,statements:Or,branches:Or,functions:Or}),Ar=P.object({total:kr}).catchall(kr),jr=P.object({lines:P.number(),statements:P.number(),branches:P.number(),functions:P.number()}),Mr=P.object({lines:P.number(),branches:P.number()}),Nr=P.object({totals:jr,packages:P.record(P.string(),Mr),scope:P.literal(`include`)}),Pr=Nr.extend({scope:P.literal(`include`).optional(),sha:P.string(),timestamp:P.string()});function parseV8Summary(e){let t;try{t=JSON.parse(e)}catch(e){throw new T(`coverage-summary.json is not valid JSON: ${k(e)}`)}let n=Ar.safeParse(t);if(!n.success)throw new T(`coverage-summary.json shape doesn't match v8 / istanbul output: ${n.error.message}`);return n.data}function parseBaseline(e){let t;try{t=JSON.parse(e)}catch(e){throw new T(`coverage-baseline.json is not valid JSON: ${k(e)}`)}let n=Nr.safeParse(t);if(!n.success)throw new T(`coverage-baseline.json has unexpected shape: ${n.error.message}`);return n.data}function parseHistoryLine(e){let t;try{t=JSON.parse(e)}catch{return}let n=Pr.safeParse(t);return n.success?n.data:void 0}const Fr=`bst/coverage-metrics`,Ir=`coverage-history.jsonl`;function remoteRef(e){return`refs/remotes/${e.remote??`origin`}/${e.historyBranch}`}function fetchBranch(e,t){let n=t.remote??`origin`;if(e.exec(`git`,[`fetch`,n,`${t.historyBranch}:${remoteRef(t)}`],{cwd:t.cwd}).exitCode!==0)return{exists:!1};let r=e.exec(`git`,[`rev-parse`,`--quiet`,`--verify`,remoteRef(t)],{cwd:t.cwd});return r.exitCode===0?{exists:!0,parentSha:r.stdout.trim()}:{exists:!1}}function readRemoteHistory(e,t){let n=t.historyFile??Ir,r=`${remoteRef(t)}:${n}`;if(e.exec(`git`,[`cat-file`,`-e`,r],{cwd:t.cwd}).exitCode!==0)return``;let i=e.exec(`git`,[`show`,r],{cwd:t.cwd});if(i.exitCode!==0)throw new T(`git show ${r} failed: ${i.stderr.trim()||`unknown error`}`);return i.stdout}function makeBlob(e,t,n){let r=e.exec(`git`,[`hash-object`,`-w`,`--stdin`],{cwd:t,input:n});if(r.exitCode!==0)throw new T(`git hash-object failed: ${r.stderr.trim()||`unknown error`}`);return r.stdout.trim()}function makeTree(e,t,n){let r=`100644 blob ${n}\t${t.historyFile??Ir}\n`,i=e.exec(`git`,[`mktree`],{cwd:t.cwd,input:r});if(i.exitCode!==0)throw new T(`git mktree failed: ${i.stderr.trim()||`unknown error`}`);return i.stdout.trim()}function makeCommit(e,t,n,r,i){let a={};t.authorName&&(a.GIT_AUTHOR_NAME=t.authorName,a.GIT_COMMITTER_NAME=t.authorName),t.authorEmail&&(a.GIT_AUTHOR_EMAIL=t.authorEmail,a.GIT_COMMITTER_EMAIL=t.authorEmail);let o=r?[`commit-tree`,`-p`,r,`-m`,i,n]:[`commit-tree`,`-m`,i,n],s=e.exec(`git`,o,{cwd:t.cwd,env:a});if(s.exitCode!==0)throw new T(`git commit-tree failed: ${s.stderr.trim()||`unknown error`}`);return s.stdout.trim()}function pushCommit(e,t,n,r){let i=t.remote??`origin`,a=`${n}:refs/heads/${t.historyBranch}`;if(r===void 0)return e.exec(`git`,[`push`,i,a],{cwd:t.cwd});let o=`--force-with-lease=refs/heads/${t.historyBranch}:${r}`;return e.exec(`git`,[`push`,o,i,a],{cwd:t.cwd})}function shortSha(e){return e.slice(0,7)}function appendRecord(e,t,n){let r=JSON.stringify(n)+`
|
|
47
47
|
`,i=``;for(let a=1;a<=5;a++){let o=fetchBranch(e,t),s=(o.exists?readRemoteHistory(e,t):``)+r,c=makeTree(e,t,makeBlob(e,t.cwd,s)),l=`chore(${t.scope??`coverage`}): record ${shortSha(n.sha)} [skip ci]`,u=makeCommit(e,t,c,o.parentSha,l),d=pushCommit(e,t,u,o.parentSha);if(d.exitCode===0)return{commitSha:u,bootstrapped:!o.exists,attempts:a};i=d.stderr.trim()||d.stdout.trim()||`unknown push error`}throw new T(`Failed to push to ${t.historyBranch} after 5 attempts: ${i}`)}function readRecords(e,t){if(!fetchBranch(e,t).exists)return[];let n=readRemoteHistory(e,t),r=[];for(let e of n.split(`
|
|
48
48
|
`)){if(e.trim()===``)continue;let t=parseHistoryLine(e);t&&r.push(t)}return r}function readRecordsGeneric(e,t,n){if(!fetchBranch(e,t).exists)return[];let r=readRemoteHistory(e,t),i=[];for(let e of r.split(`
|
|
49
|
-
`)){if(e.trim()===``)continue;let t=n(e);t&&i.push(t)}return i}function resolveFromInputs(e){if(e.coverage===!1)return{enabled:!1,historyEnabled:!1,historyBranch:
|
|
49
|
+
`)){if(e.trim()===``)continue;let t=n(e);t&&i.push(t)}return i}function resolveFromInputs(e){if(e.coverage===!1)return{enabled:!1,historyEnabled:!1,historyBranch:Fr,tolerancePp:Dr,gateOnPullRequests:!1};if(e.stack===`none`)return{enabled:!1,historyEnabled:!1,historyBranch:Fr,tolerancePp:Dr,gateOnPullRequests:!1,disabledReason:`no JS/TS source`};let t=e.hasVitestConfig||e.setupVitest,n=e.coverage??{};return{enabled:t,historyEnabled:t&&n.history!==`none`,historyBranch:n.historyBranch??`bst/coverage-metrics`,tolerancePp:n.tolerancePp??.1,floorPp:n.floorPp,gateOnPullRequests:n.gateOnPullRequests??!1,includeGlobs:n.include,excludeGlobs:n.exclude}}function resolveCoverageConfig(e){let t=loadToolingConfig(e);return resolveFromInputs({hasVitestConfig:o(w.join(e,`vitest.config.ts`))||o(w.join(e,`vitest.config.mts`)),setupVitest:t?.setupVitest===!0,coverage:t?.coverage,stack:resolveStack(e)})}const Lr=P.union([P.literal(!1),gt]),Rr=P.object({setupVitest:P.boolean().optional(),coverage:Lr.optional()});function resolveCoverageConfigFromContext(e,t){let n=parseToolingConfigSlice(e.read(`.tooling.json`),Rr,{block:`coverage / setupVitest`}),r=typeof n?.setupVitest==`boolean`?n.setupVitest:t,i=n?.coverage;return resolveFromInputs({hasVitestConfig:e.exists(`vitest.config.ts`)||e.exists(`vitest.config.mts`),setupVitest:r,coverage:i,stack:e.config.stack})}const zr=[`src/**`];function renderStringArray(e){return`[${e.map(e=>JSON.stringify(e)).join(`, `)}]`}function vitestConfigTemplate(e={}){let t=e.includeGlobs??zr,n=e.excludeGlobs??[],r=n.length>0?`[...coverageConfigDefaults.exclude, ${n.map(e=>JSON.stringify(e)).join(`, `)}]`:`[...coverageConfigDefaults.exclude]`;return`import { coverageConfigDefaults, defineConfig } from "vitest/config";
|
|
50
50
|
|
|
51
51
|
export default defineConfig({
|
|
52
52
|
test: {
|
|
53
|
+
silent: "passed-only",
|
|
53
54
|
include: ["test/**/*.test.ts"],
|
|
54
55
|
coverage: {
|
|
55
56
|
provider: "v8",
|
|
@@ -59,14 +60,14 @@ export default defineConfig({
|
|
|
59
60
|
},
|
|
60
61
|
},
|
|
61
62
|
});
|
|
62
|
-
`}const
|
|
63
|
+
`}const Br=[`vitest.config.ts`,`vitest.config.mts`];function findJsonSummaryIssue(e){if(!/\bcoverage\s*:\s*\{/.test(e))return`missing-coverage`;let t=/\breporter\s*:\s*\[([\s\S]*?)\]/.exec(e);if(!t)return`missing-reporter`;if(!t[1]?.includes(`json-summary`))return`missing-json-summary`}function describeIssue(e){switch(e){case`missing-coverage`:return"no `coverage` block found";case`missing-reporter`:return"no `reporter` array inside `coverage` block";case`missing-json-summary`:return'`coverage.reporter` does not include "json-summary"'}}function warnIfMissingJsonSummary(e){if(resolveCoverageConfigFromContext(e,e.config.setupVitest).enabled)for(let t of Br){if(!e.exists(t))continue;let n=e.read(t);if(n===void 0)continue;let r=findJsonSummaryIssue(n);if(r===void 0)return;I.warn(`${t}: ${describeIssue(r)} -- coverage tracking (pnpm exec bst coverage:summary / coverage:check) requires the "json-summary" reporter to read coverage/coverage-summary.json.`);return}}function warnIfMissingSilent(e){for(let t of Br){if(!e.exists(t))continue;let n=e.read(t);if(n!==void 0){if(/\bsilent\s*:/.test(n))return;I.warn(`${t}: no silent setting -- vitest prints console output from passing tests, which buries the failure in a red CI run. Suggested: silent: "passed-only".`);return}}}function extractCoverageBlock(e){let t=/\bcoverage\s*:\s*\{/.exec(e);if(!t)return;let n=t.index+t[0].length,r=1,i=n;for(;i<e.length&&r>0;i++)e[i]===`{`?r++:e[i]===`}`&&r--;return e.slice(n,i-1)}function suggestedInclude(e){return e===`monorepo`?`["packages/*/src/**"]`:`["src/**"]`}function warnIfMissingInclude(e){if(resolveCoverageConfigFromContext(e,e.config.setupVitest).enabled)for(let t of Br){if(!e.exists(t))continue;let n=e.read(t);if(n===void 0)continue;let r=extractCoverageBlock(n);if(r===void 0||/\binclude\s*:/.test(r))return;I.warn(`${t}: coverage.include is not set -- Vitest 3+ instruments only files a test imports, so an untested source file is invisible to coverage-baseline.json / pnpm exec bst coverage:check, not just uncovered. Suggested: coverage.include: ${suggestedInclude(e.config.structure)}.`);return}}async function generateVitest(e){let t=[];if(e.config.stack===`none`)return[{filePath:`vitest.config.ts`,action:`skipped`,description:`No JS/TS source; not managed`}];if(!e.config.setupVitest)return warnIfMissingJsonSummary(e),warnIfMissingInclude(e),warnIfMissingSilent(e),[{filePath:`vitest.config.ts`,action:`skipped`,description:`Vitest setup not requested`}];if(e.config.structure===`monorepo`)return warnIfMissingJsonSummary(e),warnIfMissingInclude(e),warnIfMissingSilent(e),[{filePath:`vitest.config.ts`,action:`skipped`,description:`Monorepo: vitest config belongs in individual packages`}];let n=`vitest.config.ts`,r=resolveCoverageConfigFromContext(e,e.config.setupVitest),i=formattedTemplate(e,n,vitestConfigTemplate({includeGlobs:r.includeGlobs,excludeGlobs:r.excludeGlobs}));e.exists(n)?e.read(n)===i?t.push({filePath:n,action:`skipped`,description:`Config already up to date`}):await e.confirmOverwrite(n)===`skip`?t.push({filePath:n,action:`skipped`,description:`Existing config preserved`}):(e.write(n,i),t.push({filePath:n,action:`updated`,description:`Replaced vitest config`})):(e.write(n,i),t.push({filePath:n,action:`created`,description:`Generated vitest.config.ts`}));let a=`test/example.test.ts`;return e.exists(`test`)||(e.write(a,formattedTemplate(e,a,`import { describe, it, expect } from "vitest";
|
|
63
64
|
|
|
64
65
|
describe("example", () => {
|
|
65
66
|
it("should pass a basic assertion", () => {
|
|
66
67
|
expect(1 + 1).toBe(2);
|
|
67
68
|
});
|
|
68
69
|
});
|
|
69
|
-
`)),t.push({filePath:a,action:`created`,description:`Generated starter test file`})),warnIfMissingJsonSummary(e),warnIfMissingInclude(e),t}const
|
|
70
|
+
`)),t.push({filePath:a,action:`created`,description:`Generated starter test file`})),warnIfMissingJsonSummary(e),warnIfMissingInclude(e),warnIfMissingSilent(e),t}const Vr=`...(recommended.ignorePatterns ?? [])`,Hr=`import recommended from "@bensandee/config/oxlint/recommended";
|
|
70
71
|
import bensandee from "@bensandee/eslint-plugin/recommended";
|
|
71
72
|
import { defineConfig } from "oxlint";
|
|
72
73
|
|
|
@@ -74,9 +75,9 @@ export default defineConfig({
|
|
|
74
75
|
extends: [recommended],
|
|
75
76
|
jsPlugins: bensandee.jsPlugins ?? [],
|
|
76
77
|
rules: bensandee.rules ?? {},
|
|
77
|
-
ignorePatterns: [${
|
|
78
|
+
ignorePatterns: [${Vr}],
|
|
78
79
|
});
|
|
79
|
-
`,
|
|
80
|
+
`,Ur=`import recommended from "@bensandee/config/oxlint/recommended";
|
|
80
81
|
import bensandee from "@bensandee/eslint-plugin/recommended";
|
|
81
82
|
import { defineConfig } from "oxlint";
|
|
82
83
|
|
|
@@ -93,25 +94,25 @@ export default defineConfig({
|
|
|
93
94
|
extends: [recommended],
|
|
94
95
|
jsPlugins: bensandee.jsPlugins ?? [],
|
|
95
96
|
rules: reportOnly,
|
|
96
|
-
ignorePatterns: [${
|
|
97
|
+
ignorePatterns: [${Vr}],
|
|
97
98
|
});
|
|
98
|
-
`,
|
|
99
|
+
`,Wr=`import { presetRules, recommended } from "@bensandee/config/oxlint";
|
|
99
100
|
import { defineConfig } from "oxlint";
|
|
100
101
|
|
|
101
102
|
export default defineConfig({
|
|
102
103
|
rules: presetRules,
|
|
103
|
-
ignorePatterns: [${
|
|
104
|
+
ignorePatterns: [${Vr}],
|
|
104
105
|
});
|
|
105
|
-
`;function addIgnorePatterns(e){if(e.includes(`ignorePatterns`))return;let t=e.match(/defineConfig\(\{(\r?\n)/);if(!t)return;let n=(t.index??0)+t[0].length;return e.slice(0,n)+` ignorePatterns: [${
|
|
106
|
-
`,
|
|
107
|
-
`,
|
|
108
|
-
|
|
109
|
-
`,`${
|
|
110
|
-
`+t.slice(r),o=r+40}let c=a.slice(r),l=
|
|
111
|
-
`,
|
|
112
|
-
`),{filePath:t,action:`created`,description:`Generated .oxfmtrc.json`}}let i=
|
|
106
|
+
`;function addIgnorePatterns(e){if(e.includes(`ignorePatterns`))return;let t=e.match(/defineConfig\(\{(\r?\n)/);if(!t)return;let n=(t.index??0)+t[0].length;return e.slice(0,n)+` ignorePatterns: [${Vr}],\n`+e.slice(n)}const Gr=`import bensandee from "@bensandee/eslint-plugin/recommended";
|
|
107
|
+
`,Kr=` ...bensandee.rules,
|
|
108
|
+
`,qr=` ...Object.fromEntries(Object.keys(bensandee.rules ?? {}).map((name) => [name, "warn"])),
|
|
109
|
+
`,Jr=/\[name, (["'])warn\1\]/,Yr=/^ {2}"?rules"?: \{/m,Xr=/^ {2}"?rules"?\s*[,:]/m,Zr=/^ {2}"?jsPlugins"?: \[/m,Qr=/^ {2}"?jsPlugins"?\s*[,:]/m,H=Symbol(`unrecognized-oxlint-config-shape`);function addBensandeePlugin(e){if(e.includes(`@bensandee/eslint-plugin`))return;let t=e.replace(`import { defineConfig } from "oxlint";
|
|
110
|
+
`,`${Gr}import { defineConfig } from "oxlint";\n`);if(t===e)return H;let n=t.match(/defineConfig\(\{(\r?\n)/);if(!n)return H;let r=(n.index??0)+n[0].length,i=t.slice(0,r);if(Qr.test(i)||Xr.test(i))return H;let a,o,s=Zr.exec(t.slice(r));if(s){let e=r+s.index+s[0].length;a=t.slice(0,e)+`...(bensandee.jsPlugins ?? []), `+t.slice(e),o=r}else{if(Qr.test(t.slice(r)))return H;a=t.slice(0,r)+` jsPlugins: bensandee.jsPlugins ?? [],
|
|
111
|
+
`+t.slice(r),o=r+40}let c=a.slice(r),l=Yr.exec(c);if(l){let e=r+l.index+l[0].length;return a.slice(0,e)+`\n${Kr}`+a.slice(e)}return Xr.test(c)?H:a.slice(0,o)+` rules: {\n${Kr} },\n`+a.slice(o)}const $r=[` rules: {\n${Kr} },\n`,` rules: {\n${qr} },\n`],ei=[`\n${Kr}`,`\n${qr}`],ti=` jsPlugins: bensandee.jsPlugins ?? [],
|
|
112
|
+
`,ni=/\.\.\.\(bensandee\.jsPlugins \?\? \[\]\),\s+/;function removeBensandeePlugin(e){if(!e.includes(`@bensandee/eslint-plugin`))return;if(!e.includes(Gr))return H;let t=e.replace(Gr,``);if(t.includes(ti))t=t.replace(ti,``);else if(ni.test(t))t=t.replace(ni,``);else return H;let n=$r.find(e=>t.includes(e))??ei.find(e=>t.includes(e));return n===void 0?H:t.replace(n,``)}function migrateReportSpread(e){return e.replace(`\n${qr}`,`\n${Kr}`)}async function generateOxlint(e){let t=`oxlint.config.ts`;if(e.config.stack===`none`)return{filePath:t,action:`skipped`,description:`No JS/TS source; not managed`};let n=e.config.useEslintPlugin?Hr:Wr,r=formattedTemplate(e,t,n),i=e.read(t);if(i){if(isGeneratedTemplate(e,t,n))return{filePath:t,action:`skipped`,description:`Already configured`};if((e.config.useEslintPlugin?[Wr,Ur]:[Hr,Ur]).some(n=>isGeneratedTemplate(e,t,n)))return e.write(t,r),{filePath:t,action:`updated`,description:`Generated oxlint.config.ts`};if(i.includes(`@bensandee/config/oxlint`)){let n=addIgnorePatterns(i)??i,r,a;if(e.config.useEslintPlugin){let e=migrateReportSpread(n);if(r=addBensandeePlugin(e),a=typeof r==`string`?r:e,r===void 0&&Jr.test(e))return{filePath:t,action:`failed`,description:`Plugin severities not migrated: unrecognized config shape -- replace the all-"warn" rule map with "...bensandee.rules,"`}}else r=removeBensandeePlugin(n),a=typeof r==`string`?r:n;return a===i?r===H?{filePath:t,action:`skipped`,description:e.config.useEslintPlugin?`Plugin wiring not injected: unrecognized config shape`:`Plugin wiring not removed: unrecognized config shape`}:{filePath:t,action:`skipped`,description:`Already configured`}:(e.write(t,e.format(t,a)),{filePath:t,action:`updated`,description:`Updated managed config`})}if(await e.confirmOverwrite(t)===`skip`)return{filePath:t,action:`skipped`,description:`User chose to keep existing`}}return e.write(t,r),{filePath:t,action:i?`updated`:`created`,description:`Generated oxlint.config.ts`}}const ri=[`.claude`,`.agent/findings`,`docs/**/retired/`],ii=/* @__PURE__ */ new Set([`**/*.md`]),ai=[`**/CHANGELOG.md`],oi=[{marker:`composer.json`,ignore:[`composer.json`,`composer.lock`,`pint.json`]}];function foreignOwnedPatterns(e){let t=[];for(let{marker:n,ignore:r}of oi)e.exists(n)&&t.push(...r);return t}function requiredIgnorePatterns(e){let t=[...ri,...foreignOwnedPatterns(e)];return e.config.releaseStrategy===`none`?t:[...t,...ai]}async function generateFormatter(e){return e.config.formatter===`oxfmt`?generateOxfmt(e):generatePrettier(e)}async function generateOxfmt(e){let t=`.oxfmtrc.json`,n=requiredIgnorePatterns(e),r=e.read(t);if(!r){let r={ignorePatterns:n};return e.write(t,JSON.stringify(r,null,2)+`
|
|
113
|
+
`),{filePath:t,action:`created`,description:`Generated .oxfmtrc.json`}}let i=P.record(P.string(),P.unknown()),a;try{a=JSON.parse(r)}catch{let r={ignorePatterns:n};return e.write(t,JSON.stringify(r,null,2)+`
|
|
113
114
|
`),{filePath:t,action:`updated`,description:`Replaced malformed .oxfmtrc.json`}}let o=i.safeParse(a);if(!o.success){let r={ignorePatterns:n};return e.write(t,JSON.stringify(r,null,2)+`
|
|
114
|
-
`),{filePath:t,action:`updated`,description:`Replaced malformed .oxfmtrc.json`}}let s=o.data,c=Array.isArray(s.ignorePatterns)?s.ignorePatterns:[],l=c.filter(e=>typeof e==`string`),u=new Set(l),d=n.filter(e=>!u.has(e)),f=l.filter(e=>!
|
|
115
|
+
`),{filePath:t,action:`updated`,description:`Replaced malformed .oxfmtrc.json`}}let s=o.data,c=Array.isArray(s.ignorePatterns)?s.ignorePatterns:[],l=c.filter(e=>typeof e==`string`),u=new Set(l),d=n.filter(e=>!u.has(e)),f=l.filter(e=>!ii.has(e)),p=l.filter(e=>ii.has(e)),m=c.filter(e=>typeof e!=`string`);if(d.length===0&&p.length===0)return{filePath:t,action:`skipped`,description:`Existing oxfmt config already has required ignorePatterns`};s.ignorePatterns=[...f,...m,...d],e.write(t,JSON.stringify(s,null,2)+`
|
|
115
116
|
`);let h=[];return d.length>0&&h.push(`Added ignorePatterns: ${d.join(`, `)}`),p.length>0&&h.push(`removed: ${p.join(`, `)}`),{filePath:t,action:`updated`,description:h.join(`; `)}}async function generatePrettier(e){let t=`.prettierrc`;return e.exists(t)?{filePath:t,action:`skipped`,description:`Existing prettier config preserved`}:(e.write(t,`{
|
|
116
117
|
"semi": true,
|
|
117
118
|
"singleQuote": false,
|
|
@@ -129,34 +130,34 @@ export default defineConfig({
|
|
|
129
130
|
export default defineConfig({
|
|
130
131
|
entry: ["src/index.ts"],
|
|
131
132
|
});
|
|
132
|
-
`);if(n){if(n===r)return{filePath:t,action:`skipped`,description:`Already configured`};if(await e.confirmOverwrite(t)===`skip`)return{filePath:t,action:`skipped`,description:`Existing tsdown config preserved`}}return e.write(t,r),{filePath:t,action:n?`updated`:`created`,description:`Generated tsdown.config.ts`}}const
|
|
133
|
+
`);if(n){if(n===r)return{filePath:t,action:`skipped`,description:`Already configured`};if(await e.confirmOverwrite(t)===`skip`)return{filePath:t,action:`skipped`,description:`Existing tsdown config preserved`}}return e.write(t,r),{filePath:t,action:n?`updated`:`created`,description:`Generated tsdown.config.ts`}}const si=/^\[tools\]\s*$/m,ci=/^\[{1,2}[^[].*\]{1,2}\s*$/m,li=/^pnpm\s*=.*$/m,ui=P.record(P.string(),P.union([P.string(),P.record(P.string(),P.unknown())])),di=P.looseObject({tools:P.unknown().optional()});function toolsRange(e){let t=si.exec(e);if(!t)return;let n=t.index+t[0].length,r=e.slice(n),i=ci.exec(r);return{start:n,end:i?n+i.index:e.length}}function pnpmVersionFromPackageManager(e){return/^pnpm@(\S+)$/.exec(e??``)?.[1]}function devEnginesNodeVersion(e){let t=e?.runtime;if(t)return(Array.isArray(t)?t:[t]).find(e=>e.name===`node`)?.version}function nodePinFor(e,t){let n=minVersionTuple(dr);for(let r of[e,t]){let e=r?minVersionTuple(r):void 0;e&&(!n||compareTuples(e,n)>0)&&(n=e)}return n?n.join(`.`):dr}function ownedLines(e,t){let n=[`[tools]`,`node = "${t}"`];return e&&n.push(`pnpm = "${e}"`),n}function appendLine(e,t){return(e.endsWith(`
|
|
133
134
|
`)||e.length===0?e:e+`
|
|
134
135
|
`)+t+`
|
|
135
|
-
`}function tableFormFailure(e,t){return{filePath:e,action:`failed`,description:`mise.toml: tools.${t} is a table; repo:sync owns it as a plain string pin`}}function isBelowFloor(e,t){let n=minVersionTuple(t);if(n===void 0)return!1;let r=/^(\d+)\.(\d+)\.(\d+)$/.exec(e);if(r)return compareTuples([Number(r[1]),Number(r[2]),Number(r[3])],n)<0;let i=/^(\d+)$/.exec(e);return i?Number(i[1])<n[0]:!1}function readPackageJsonFacts(e){let t=e.read(`package.json`),n=t?parsePackageJson(t):void 0;return{enginesNode:n?.engines?.node,devEngines:n?.devEngines,pnpmVersion:pnpmVersionFromPackageManager(n?.packageManager)}}function editToolsBody(e,t,n,r,i){let a=e,o=[];return t===void 0&&(a=appendLine(a,`node = "${i}"`),o.push(`added tools.node = "${i}"`)),r&&n!==r&&(n===void 0?(a=appendLine(a,`pnpm = "${r}"`),o.push(`added tools.pnpm = "${r}"`)):(a=a.replace(
|
|
136
|
+
`}function tableFormFailure(e,t){return{filePath:e,action:`failed`,description:`mise.toml: tools.${t} is a table; repo:sync owns it as a plain string pin`}}function isBelowFloor(e,t){let n=minVersionTuple(t);if(n===void 0)return!1;let r=/^(\d+)\.(\d+)\.(\d+)$/.exec(e);if(r)return compareTuples([Number(r[1]),Number(r[2]),Number(r[3])],n)<0;let i=/^(\d+)$/.exec(e);return i?Number(i[1])<n[0]:!1}function readPackageJsonFacts(e){let t=e.read(`package.json`),n=t?parsePackageJson(t):void 0;return{enginesNode:n?.engines?.node,devEngines:n?.devEngines,pnpmVersion:pnpmVersionFromPackageManager(n?.packageManager)}}function editToolsBody(e,t,n,r,i){let a=e,o=[];return t===void 0&&(a=appendLine(a,`node = "${i}"`),o.push(`added tools.node = "${i}"`)),r&&n!==r&&(n===void 0?(a=appendLine(a,`pnpm = "${r}"`),o.push(`added tools.pnpm = "${r}"`)):(a=a.replace(li,e=>`pnpm = "${r}"${/(\s*#.*)$/.exec(e)?.[1]??``}`),o.push(`updated tools.pnpm ${n} -> ${r}`))),{body:a,changes:o}}async function generateMise(e,t){let n=`mise.toml`,{enginesNode:r,devEngines:i,pnpmVersion:a}=readPackageJsonFacts(e),o=nodePinFor(r,devEnginesNodeVersion(t??i)),s=e.read(n);if(!s)return e.write(n,ownedLines(a,o).join(`
|
|
136
137
|
`)+`
|
|
137
|
-
`),{filePath:n,action:`created`,description:`Generated mise.toml`};let c;try{c=Me(s)}catch(e){return{filePath:n,action:`failed`,description:`Could not parse existing mise.toml -- ${e instanceof Error?e.message:String(e)}`}}let l=
|
|
138
|
+
`),{filePath:n,action:`created`,description:`Generated mise.toml`};let c;try{c=Me(s)}catch(e){return{filePath:n,action:`failed`,description:`Could not parse existing mise.toml -- ${e instanceof Error?e.message:String(e)}`}}let l=di.safeParse(c),u=l.success?l.data.tools??{}:{},d=ui.safeParse(u),f=d.success?d.data:{};if(typeof f.node==`object`)return tableFormFailure(n,`node`);if(typeof f.pnpm==`object`)return tableFormFailure(n,`pnpm`);let p=f.node,m=f.pnpm;if(p!==void 0&&r!==void 0&&isBelowFloor(p,r))return{filePath:n,action:`failed`,description:`mise.toml: tools.node "${p}" is below engines.node "${r}"`};let h=toolsRange(s),g,_;if(h===void 0){if(Object.keys(f).length>0)return{filePath:n,action:`failed`,description:`mise.toml: tools.* is declared with dotted keys; repo:sync only manages a [tools] table`};g=ownedLines(a,o).join(`
|
|
138
139
|
`)+`
|
|
139
140
|
|
|
140
|
-
`+s,_=[`added [tools] table`]}else{let e=s.slice(h.start,h.end),t=editToolsBody(e,p,m,a,o);_=t.changes,g=t.body===e?s:s.slice(0,h.start)+t.body+s.slice(h.end)}return _.length===0?{filePath:n,action:`skipped`,description:`Already up to spec`}:(e.write(n,g),{filePath:n,action:`updated`,description:_.join(`, `)})}let
|
|
141
|
-
${e}`)}}const
|
|
142
|
-
`)){let e=t.trim(),i=/^\[+\s*([^\]]+?)\s*\]+/.exec(e);if(i)r=i[1];else if(r!==void 0&&n.has(r)&&
|
|
141
|
+
`+s,_=[`added [tools] table`]}else{let e=s.slice(h.start,h.end),t=editToolsBody(e,p,m,a,o);_=t.changes,g=t.body===e?s:s.slice(0,h.start)+t.body+s.slice(h.end)}return _.length===0?{filePath:n,action:`skipped`,description:`Already up to spec`}:(e.write(n,g),{filePath:n,action:`updated`,description:_.join(`, `)})}let fi={warn(e){process.stderr.write(`${e}\n`)},debug(){}};function setForgejoLogger(e){fi=e}const U={warn(e){fi.warn(e)},debug(e){fi.debug(e)}};async function findRelease(e,t,n){let r=encodeURIComponent(n),i=`${t.serverUrl}/api/v1/repos/${t.repository}/releases/tags/${r}`,a=await e.fetch(i,{headers:{Authorization:`token ${t.token}`}});if(a.status===200)return!0;if(a.status===404)return!1;throw new E(await forgejoErrorMessage(a,{verb:`check release`,resource:n}))}const pi=P.object({id:P.number(),tag_name:P.string().optional(),created_at:P.string().optional(),published_at:P.string().optional(),html_url:P.string().nullish(),prerelease:P.boolean().optional()});function isEpochReleaseDate(e){if(!e)return!0;let t=new Date(e).getTime();return Number.isNaN(t)||t<=0}async function getReleaseByTag(e,t,n){let r=encodeURIComponent(n),i=`${t.serverUrl}/api/v1/repos/${t.repository}/releases/tags/${r}`,a=await e.fetch(i,{headers:{Authorization:`token ${t.token}`}});if(a.status===404)return null;if(!a.ok)throw new E(await forgejoErrorMessage(a,{verb:`check release`,resource:n}));let o=pi.safeParse(await a.json());if(!o.success)throw new D(`Unexpected release response: ${o.error.message}`);return o.data}async function createRelease(e,t,n,r={}){let i=`${t.serverUrl}/api/v1/repos/${t.repository}/releases`,a={tag_name:n,name:r.name??n,body:r.body??`Published ${n}`,prerelease:r.prerelease??!1};r.target&&(a.target_commitish=r.target);let o=await e.fetch(i,{method:`POST`,headers:{Authorization:`token ${t.token}`,"Content-Type":`application/json`},body:JSON.stringify(a)});if(!o.ok)throw new E(await forgejoErrorMessage(o,{verb:`create release`,resource:n}))}async function deleteTag(e,t,n){let r=encodeURIComponent(n),i=`${t.serverUrl}/api/v1/repos/${t.repository}/tags/${r}`,a=await e.fetch(i,{method:`DELETE`,headers:{Authorization:`token ${t.token}`}});if(!a.ok&&a.status!==404)throw new E(await forgejoErrorMessage(a,{verb:`delete tag`,resource:n}))}const mi=P.looseObject({name:P.string(),id:P.string(),commit:P.object({sha:P.string().regex(/^[0-9a-f]{40}$/)})});async function getTagCommit(e,t,n){let r=encodeURIComponent(n),i=`${t.serverUrl}/api/v1/repos/${t.repository}/tags/${r}`,a=await e.fetch(i,{headers:{Authorization:`token ${t.token}`}});if(a.status===404)return null;if(!a.ok)throw new E(await forgejoErrorMessage(a,{verb:`read tag`,resource:n}));let o=mi.safeParse(await a.json());if(!o.success)throw new D(`Unexpected tag response: ${o.error.message}`);return o.data.commit.sha}async function deleteRelease(e,t,n){let r=`${t.serverUrl}/api/v1/repos/${t.repository}/releases/${String(n)}`,i=await e.fetch(r,{method:`DELETE`,headers:{Authorization:`token ${t.token}`}});if(!i.ok&&i.status!==404)throw new E(await forgejoErrorMessage(i,{verb:`delete release`,resource:String(n)}))}async function markReleasePrerelease(e,t,n,r){let i=`${t.serverUrl}/api/v1/repos/${t.repository}/releases/${String(n)}`,a=await e.fetch(i,{method:`PATCH`,headers:{Authorization:`token ${t.token}`,"Content-Type":`application/json`},body:JSON.stringify({prerelease:!0})},{idempotent:!0});if(!a.ok)throw new E(await forgejoErrorMessage(a,{verb:`edit release`,resource:r}))}async function ensureRelease(e,t,n,r={}){let i=r.attempts??4,a=r.baseDelayMs??2e3,o=r.queuePolls??5,s=await getReleaseByTag(e,t,n);if(s&&!isEpochReleaseDate(s.created_at))return r.prerelease===!0&&s.prerelease===!1&&await markReleasePrerelease(e,t,s.id,n),{status:`exists`,release:releaseRef(s)};let c=s,l=!1;for(let s=1;s<=i;s++){c&&isEpochReleaseDate(c.created_at)&&(await deleteRelease(e,t,c.id),c=null,l=!0,await settleBackoff(s,a));try{await createRelease(e,t,n,{target:r.target,prerelease:r.prerelease,name:r.name,body:r.body})}catch(r){let o=await getReleaseByTag(e,t,n);if(o&&!isEpochReleaseDate(o.created_at))return{status:`race`,release:releaseRef(o)};if(c=o,s>=i)break;U.warn(`Release creation attempt ${String(s)}/${String(i)} failed: ${O(r)}`),await settleBackoff(s,a);continue}if(c=await getReleaseByTag(e,t,n),c&&isEpochReleaseDate(c.created_at)&&o>0&&(c=await awaitQueueDate(e,t,n,o,a),o=0),c&&!isEpochReleaseDate(c.created_at))return{status:l?`repaired`:`created`,release:releaseRef(c)};s<i&&U.warn(`Release for ${n} came back epoch-dated (attempt ${String(s)}/${String(i)}) -- waiting for Forgejo to settle the tag's date before retrying`)}let u=r.target?await recreateTagViaApi(e,t,n,{target:r.target,prerelease:r.prerelease,name:r.name,body:r.body,current:c,attempts:i,baseDelayMs:a}):null;if(u)return{status:`repaired`,release:releaseRef(u)};throw new E(`Release for ${n} never got a real (non-epoch) created date after ${String(i)} attempts. Forgejo dates a release for a pushed tag from its push queue, which did not date this one, so it stayed at the Unix epoch (1969/1970). `+(r.target?`Recreating the tag via the API did not help -- investigate the server or upgrade Forgejo.`:`Pass the release tag's target commit so the tag can be recreated, or retry the release.`))}async function recreateTagViaApi(e,t,n,r){let{target:i,prerelease:a,name:o,body:s,current:c,attempts:l,baseDelayMs:u}=r;U.warn(`Release for ${n} stayed epoch-dated -- recreating the tag via the API so Forgejo stamps a real date (the tag becomes lightweight)`),c&&await deleteRelease(e,t,c.id),await deleteTag(e,t,n);for(let r=1;r<=l;r++){try{await createRelease(e,t,n,{target:i,prerelease:a,name:o,body:s})}catch(e){if(r>=l)throw new E(`Release for ${n} was deleted to repair its epoch date, but recreating it from ${i} failed: ${O(e)}. The tag no longer exists on the server -- re-push it (or re-run the release) to restore it.`);await settleBackoff(r,u);continue}let c=await getReleaseByTag(e,t,n);return c&&!isEpochReleaseDate(c.created_at)?c:null}return null}function releaseRef(e){return{id:e.id,url:e.html_url??null}}async function awaitQueueDate(e,t,n,r,i){let a=null;for(let o=1;o<=r;o++)if(await settleBackoff(o,i/4),a=await getReleaseByTag(e,t,n),!a||!isEpochReleaseDate(a.created_at))return a;return U.debug(`Release for ${n} is still epoch-dated after ${String(r)} re-reads`),a}async function settleBackoff(e,t){if(t<=0)return;let n=Math.min(t*2**(e-1),16e3);await new Promise(e=>setTimeout(e,n))}const hi=P.object({id:P.number(),name:P.string()}),gi=P.object({id:P.number(),assets:P.array(hi).nullish()});async function deleteReleaseAssetsNamed(e,t,n,r,i){for(let a of n.assets??[]){if(!i(a.name))continue;let o=`${t.serverUrl}/api/v1/repos/${t.repository}/releases/${String(n.id)}/assets/${String(a.id)}`,s=await e.fetch(o,{method:`DELETE`,headers:{Authorization:`token ${t.token}`}});if(!s.ok){let e=await forgejoErrorMessage(s,{verb:`delete asset`,resource:`${a.name} on ${r}`});throw new E(`Cannot replace asset ${a.name} on ${r}: the forge refused to delete the existing copy (asset ${String(a.id)}, HTTP ${String(s.status)}).\n${e}`)}}}async function uploadReleaseAsset(e,t,n,r){let i=encodeURIComponent(n),a=`${t.serverUrl}/api/v1/repos/${t.repository}/releases/tags/${i}`,o=await e.fetch(a,{headers:{Authorization:`token ${t.token}`}});if(!o.ok)throw new E(await forgejoErrorMessage(o,{verb:`get release`,resource:n}));let s=gi.safeParse(await o.json());if(!s.success)throw new D(`Unexpected release response: ${s.error.message}`);let c=s.data,l=c.id,u=r.replace===!0&&(c.assets??[]).some(e=>e.name===r.assetName),d={releaseId:l,tag:n};if(r.replace){let i=RegExp(`^${escapeRegExp$2(r.assetName)}\\.replacing-[0-9a-f]{8}$`);await deleteReleaseAssetsNamed(e,t,c,n,e=>i.test(e))}if(!u){await postReleaseAsset(e,t,d,r.assetName,r.fileBuffer);return}let f=`${r.assetName}.replacing-${Se().slice(0,8)}`,p=await postReleaseAsset(e,t,d,f,r.fileBuffer);if(p<0)throw new D(`Uploaded ${f} to ${n} but the response carried no asset id, so it was not renamed to ${r.assetName}; the old copy is kept and ${f} is left behind.`);try{await deleteReleaseAssetsNamed(e,t,c,n,e=>e===r.assetName)}catch(e){throw new E(`${O(e)}\nThe new copy was already uploaded as ${f} (asset ${String(p)}); the next replace run's sweep removes it.`)}await renameReleaseAsset(e,t,d,{assetId:p,name:r.assetName,tempName:f})}function escapeRegExp$2(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const _i=P.object({id:P.number()});async function postReleaseAsset(e,t,{releaseId:n,tag:r},i,a){let o=`${t.serverUrl}/api/v1/repos/${t.repository}/releases/${String(n)}/assets?name=${encodeURIComponent(i)}`,s=new FormData;s.append(`attachment`,new Blob([new Uint8Array(a)]),i);let c=await e.fetch(o,{method:`POST`,headers:{Authorization:`token ${t.token}`},body:s},{timeoutMs:bn});if(!c.ok)throw new E(await forgejoErrorMessage(c,{verb:`upload asset`,resource:`${i} to ${r}`}));let l=_i.safeParse(await c.json().catch(()=>null));return l.success?l.data.id:-1}async function renameReleaseAsset(e,t,{releaseId:n,tag:r},{assetId:i,name:a,tempName:o}){let s=`${t.serverUrl}/api/v1/repos/${t.repository}/releases/${String(n)}/assets/${String(i)}`,c=await e.fetch(s,{method:`PATCH`,headers:{Authorization:`token ${t.token}`,"Content-Type":`application/json`},body:JSON.stringify({name:a})});if(!c.ok){let e=await forgejoErrorMessage(c,{verb:`rename asset`,resource:`${o} on ${r}`});throw new E(`The old ${a} on ${r} is deleted but the new copy is still named ${o} (asset ${String(i)}, HTTP ${String(c.status)}); rename it by hand.
|
|
142
|
+
${e}`)}}const vi=P.looseObject({id:P.number(),tag_name:P.string(),name:P.string().nullish(),target_commitish:P.string().nullish(),created_at:P.string().nullish(),html_url:P.string().nullish(),draft:P.boolean().optional(),prerelease:P.boolean().optional(),assets:P.array(P.unknown()).nullish()});P.looseObject({name:P.string(),commit:P.looseObject({sha:P.string(),created:P.string().nullish()})});async function readListPages(e,t,n,r,i){let a=[],o=i?1/0:r.limit,s=Math.min(Math.max(r.limit,1),50);for(let r=1;r<=20&&a.length<o;r++){let i=new URLSearchParams({page:String(r),limit:String(s)}),o=`${t.serverUrl}/api/v1/repos/${t.repository}/${n}?${i.toString()}`,c=await e.fetch(o,{headers:{Authorization:`token ${t.token}`}});if(!c.ok)throw new E(await forgejoErrorMessage(c,{verb:`list ${n}`,resource:t.repository}));let l=await c.json();if(!Array.isArray(l))throw new D(`Unexpected ${n} list response: not an array`);if(l.length===0)break;a.push(...l)}return a}async function listReleases(e,t,n){let r=vi.array().safeParse(await readListPages(e,t,`releases`,n,!1));if(!r.success)throw new D(`Unexpected release list response: ${r.error.message}`);let i=r.data.slice(0,n.limit);return Promise.all(i.map(async n=>({tag:n.tag_name,name:n.name??n.tag_name,commitSha:await getTagCommit(e,t,n.tag_name),target:n.target_commitish??null,createdAt:n.created_at??null,url:n.html_url??null,draft:n.draft??!1,prerelease:n.prerelease??!1,assetCount:n.assets?.length??0})))}function releaseTag(e){return e.root?`v${e.version}`:`${e.name}@${e.version}`}const yi=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]*)?$/;function parseReleaseTag(e,t){if(e.startsWith(`v`)&&t!==null){let n=e.slice(1);if(yi.test(n))return{packageName:t,version:n}}let n=e.lastIndexOf(`@`);if(n>0){let t=e.slice(n+1);if(yi.test(t))return{packageName:e.slice(0,n),version:t}}return null}const bi=[{file:`Cargo.toml`,sections:[`package`]},{file:`pyproject.toml`,sections:[`project`,`tool.poetry`]}],xi=/^\s*version\s*=\s*"[^"]*"/;function sectionHasStaticVersion(e,t){let n=new Set(t),r;for(let t of e.split(`
|
|
143
|
+
`)){let e=t.trim(),i=/^\[+\s*([^\]]+?)\s*\]+/.exec(e);if(i)r=i[1];else if(r!==void 0&&n.has(r)&&xi.test(e))return!0}return!1}function detectForeignVersionOfRecord(e){for(let{file:t,sections:n}of bi){let r=w.join(e,t);if(!o(r))continue;let i;try{i=p(r,`utf-8`)}catch{continue}if(sectionHasStaticVersion(i,n))return t}}function releaseTargetConflict(e,t,n){if(e===`none`&&t===`simple`)return detectForeignVersionOfRecord(n)}function splitLines(e){let t=e.endsWith(`
|
|
143
144
|
`);return{lines:(t?e.slice(0,-1):e).split(`
|
|
144
145
|
`),trailingNewline:t}}function joinLines({lines:e,trailingNewline:t}){return e.join(`
|
|
145
146
|
`)+(t?`
|
|
146
|
-
`:``)}function stripCr(e){return e.endsWith(`\r`)?e.slice(0,-1):e}function expectedStampLine(e,t){return e.prefix+t+(e.suffix??``)}function matchingLineIndexes(e,t){let n=t.suffix??``,r=t.prefix.length+n.length,{lines:i}=splitLines(e),a=[];return i.forEach((e,i)=>{let o=stripCr(e);o.startsWith(t.prefix)&&o.endsWith(n)&&o.length>=r&&a.push(i)}),a}function describeStampProblem(e,t){let n=matchingLineIndexes(e,t);if(n.length===1)return;let r=t.suffix===void 0?``:` and suffix ${JSON.stringify(t.suffix)}`,i=`prefix ${JSON.stringify(t.prefix)}${r}`;return n.length===0?`${t.file}: no line matches ${i}. Fix the prefix/suffix to match the file's actual content.`:`${t.file}: ${n.length} lines match ${i}, which is ambiguous. Use a more specific prefix, or split this into a second versionStamp entry.`}function stampContent(e,t,n){let r=splitLines(e),[i]=matchingLineIndexes(e,t),a=r.lines[i].endsWith(`\r`),o=expectedStampLine(t,n);return r.lines[i]=a?`${o}\r`:o,joinLines(r)}function releaseContextEnv(e){return{RELEASE_VERSION:e.version,RELEASE_TAG:e.tag,RELEASE_PRERELEASE:String(e.prerelease),RELEASE_BUILD_NUMBER:e.buildNumber}}const
|
|
147
|
-
`).filter(e=>(e.endsWith(`\r`)?e.slice(0,-1):e)===r).length;if(t!==1)throw new T(`versionStamp verify failed for ${n}: expected exactly one line "${r}" after the build, found ${t}. The build likely overwrote the stamp -- check for a script that regenerates or copies over this file.`)}}function refuseForeignVersionOfRecord(e){let t=detectForeignVersionOfRecord(e);if(t)throw new T(`bst stamps package.json's version into versionStamp files, but this repo's version-of-record is ${t}. A stamp would carry a version the ${t} artifact never gets. Release this repo through its own toolchain, or remove the versionStamp block.`)}function stampOwnedVersionFiles(e,t,n,r,i){let a=i?null:rootPackageName(e,t),o=(n?.versionStamp??[]).filter(e=>stampOwner(e,a)===r.packageName);return o.length===0?[]:(refuseForeignVersionOfRecord(t),stampVersionFiles(e,t,o,r.version))}function stampWithRootVersion(e,t,n){return n.length===0?[]:stampVersionFiles(e,t,n,resolveStampVersion(e,t))}function runBuild(e,t,n,r){if(!t.command||t.command.length===0)return;let[i,...a]=t.command;if(!i)return;let o=t.commandCwd===r.cwd?`root`:w.relative(r.cwd,t.commandCwd);
|
|
148
|
-
`).filter(Boolean),a=process.env.GITHUB_RUN_NUMBER??``,o=[];for(let r of i){if(!t.dryRun&&!await releaseExists(e,t,r)){
|
|
149
|
-
`).map(normalizeEntry).filter(e=>e.length>0)),a=n.filter(e=>!i.has(normalizeEntry(e)));if(a.length===0)return{filePath:t,action:`skipped`,description:`Already has all standard entries`};let o=
|
|
147
|
+
`:``)}function stripCr(e){return e.endsWith(`\r`)?e.slice(0,-1):e}function expectedStampLine(e,t){return e.prefix+t+(e.suffix??``)}function matchingLineIndexes(e,t){let n=t.suffix??``,r=t.prefix.length+n.length,{lines:i}=splitLines(e),a=[];return i.forEach((e,i)=>{let o=stripCr(e);o.startsWith(t.prefix)&&o.endsWith(n)&&o.length>=r&&a.push(i)}),a}function describeStampProblem(e,t){let n=matchingLineIndexes(e,t);if(n.length===1)return;let r=t.suffix===void 0?``:` and suffix ${JSON.stringify(t.suffix)}`,i=`prefix ${JSON.stringify(t.prefix)}${r}`;return n.length===0?`${t.file}: no line matches ${i}. Fix the prefix/suffix to match the file's actual content.`:`${t.file}: ${n.length} lines match ${i}, which is ambiguous. Use a more specific prefix, or split this into a second versionStamp entry.`}function stampContent(e,t,n){let r=splitLines(e),[i]=matchingLineIndexes(e,t),a=r.lines[i].endsWith(`\r`),o=expectedStampLine(t,n);return r.lines[i]=a?`${o}\r`:o,joinLines(r)}function releaseContextEnv(e){return{RELEASE_VERSION:e.version,RELEASE_TAG:e.tag,RELEASE_PRERELEASE:String(e.prerelease),RELEASE_BUILD_NUMBER:e.buildNumber}}const Si=`build:release-assets`,Ci=`release-assets`;function configuredTargets(e,t,n){return(t?.releaseAssets??[]).map(t=>{let r=t.package??n;if(t.file===void 0==(t.files===void 0))throw new T(`releaseAssets entry must set exactly one of file and files: ${JSON.stringify(t)}`);if(t.file===void 0){let n=t.files??[];return{owner:r,commandCwd:e,command:t.command,files:[],globs:n,label:`files ${JSON.stringify(n)}`}}return{owner:r,commandCwd:e,command:t.command,files:[{path:w.resolve(e,t.file),...t.name&&{name:t.name}}],label:`file ${t.file}`}})}function conventionTargets(e,t,n){let r=[],checkDir=(i,a)=>{let o=w.resolve(t,i),s=e.readFile(w.join(o,`package.json`));if(!s)return;let c=parsePackageJson(s);c?.scripts?.[Si]&&r.push({owner:a||n!==null?n:c.name??null,commandCwd:o,command:[`pnpm`,`run`,Si],files:[],collectFromDir:w.join(o,Ci)})};checkDir(`.`,!0);for(let n of e.listPackageDirs(t))checkDir(w.join(`packages`,n),!1);return r}function allTargets(e,t,n,r){return[...configuredTargets(t,n,r),...conventionTargets(e,t,r)]}function isMonorepoRepo$1(e,t,n){return n?.structure===void 0?e.readFile(w.join(t,`pnpm-workspace.yaml`))!==null:n.structure===`monorepo`}function rootPackageName(e,t){let n=e.readFile(w.join(t,`package.json`));return(n===null?void 0:parsePackageJson(n))?.name??``}function ownedTargets(e,t,n,r,i){return allTargets(e,t,n,i?null:rootPackageName(e,t)).filter(e=>e.owner===r)}function resolveStampVersion(e,t){let n=w.join(t,`package.json`),r=e.readFile(n);if(r===null)throw new T(`release:assets could not read package.json at ${n} to resolve the version for versionStamp.`);let i=parsePackageJson(r);if(!i?.version)throw new T(`release:assets could not find a "version" field in package.json at ${n}. versionStamp needs a version to stamp.`);return i.version}function stampVersionFiles(e,t,n,r){let i=[];for(let a of n){let n=w.resolve(t,a.file),o=e.readFile(n);if(o===null)throw new T(`versionStamp file not found: ${a.file} (resolved to ${n})`);let s=describeStampProblem(o,a);if(s)throw new T(`versionStamp: ${s}`);let c=expectedStampLine(a,r);e.writeFile(n,stampContent(o,a,r)),I.info(`Stamped ${a.file}: ${c}`),i.push({path:n,expectedLine:c})}return i}function verifyStamp(e,t){for(let{path:n,expectedLine:r}of t){let t=(e.readFile(n)??``).split(`
|
|
148
|
+
`).filter(e=>(e.endsWith(`\r`)?e.slice(0,-1):e)===r).length;if(t!==1)throw new T(`versionStamp verify failed for ${n}: expected exactly one line "${r}" after the build, found ${t}. The build likely overwrote the stamp -- check for a script that regenerates or copies over this file.`)}}function refuseForeignVersionOfRecord(e){let t=detectForeignVersionOfRecord(e);if(t)throw new T(`bst stamps package.json's version into versionStamp files, but this repo's version-of-record is ${t}. A stamp would carry a version the ${t} artifact never gets. Release this repo through its own toolchain, or remove the versionStamp block.`)}function stampOwnedVersionFiles(e,t,n,r,i){let a=i?null:rootPackageName(e,t),o=(n?.versionStamp??[]).filter(e=>stampOwner(e,a)===r.packageName);return o.length===0?[]:(refuseForeignVersionOfRecord(t),stampVersionFiles(e,t,o,r.version))}function stampWithRootVersion(e,t,n){return n.length===0?[]:stampVersionFiles(e,t,n,resolveStampVersion(e,t))}function runBuild(e,t,n,r){if(!t.command||t.command.length===0)return;let[i,...a]=t.command;if(!i)return;let o=t.commandCwd===r.cwd?`root`:w.relative(r.cwd,t.commandCwd);I.info(`Building assets in ${o}: ${t.command.join(` `)}`);let s=n===null?{cwd:t.commandCwd}:{cwd:t.commandCwd,env:releaseContextEnv(n)};e.execInherit(i,a,s),debug(r,`Asset build completed for ${o}`)}function collectFromDir(e,t){if(!t.collectFromDir)return[];let n=e.listFiles(t.collectFromDir).map(e=>({path:w.join(t.collectFromDir??``,e)}));if(n.length===0)throw new T(`${Si} ran in ${t.commandCwd} but emitted no files to ${t.collectFromDir}. Update your script to write artifacts there, or declare assets explicitly via releaseAssets in .tooling.json.`);return n}function collectFromGlobs(e,t,n){if(!n.globs)return[];let r=e.globFiles(t,n.globs);if(r.length===0)throw new T(`releaseAssets entry with ${n.label??`globs`} matched no files under ${t} after its build ran. Check the glob and where the build writes its output.`);return r.map(e=>({path:e}))}function buildTargets(e,t,n,r){let i=[];for(let a of t)runBuild(e,a,n,r),i.push(...a.files,...collectFromDir(e,a),...collectFromGlobs(e,r.cwd,a));let a=uniqueByPath(i);return refuseDuplicateAssetNames(a),a}function uniqueByPath(e){let t=/* @__PURE__ */ new Set;return e.filter(e=>{let n=w.resolve(e.path);return!t.has(n)&&(t.add(n),!0)})}function refuseDuplicateAssetNames(e){let t=/* @__PURE__ */ new Map;for(let n of e){let e=n.name??w.basename(n.path),r=t.get(e);if(r!==void 0)throw new T(`Two release assets would upload as "${e}": ${r} and ${n.path}. Rename one with a releaseAssets \`name\`, or narrow the glob.`);t.set(e,n.path)}}function uploadToGitHub(e,t,n,r){let i=r.name??w.basename(r.path),a=e.exec(`gh`,[`release`,`upload`,n,r.path,`--clobber`],{cwd:t.cwd});if(debugExec(t,`gh release upload ${n} ${i}`,a),a.exitCode!==0)throw new T(`GitHub release upload failed for ${i}: ${a.stderr||a.stdout}`);I.info(`Uploaded ${i} to ${n} (GitHub)`)}async function uploadToForgejo(e,t,n,r){let i=r.name??w.basename(r.path),a=e.readFileBuffer(r.path);if(!a)throw new T(`Asset file not found: ${r.path}`);await uploadReleaseAsset(e,t,n,{assetName:i,fileBuffer:a}),I.info(`Uploaded ${i} to ${n} (Forgejo)`)}function isPrerelease(e){let[t=``]=e.split(`+`);return t.includes(`-`)}async function findReleasesAtHead(e,t,n){let r=e.exec(`git`,[`tag`,`--points-at`,`HEAD`],{cwd:t.cwd});if(debugExec(t,`git tag --points-at HEAD`,r),r.exitCode!==0){if(t.dryRun)return[];throw new T(`Could not determine current tags`)}let i=r.stdout.trim().split(`
|
|
149
|
+
`).filter(Boolean),a=process.env.GITHUB_RUN_NUMBER??``,o=[];for(let r of i){if(!t.dryRun&&!await releaseExists(e,t,r)){I.info(`No release found for ${r}, skipping (likely a sliding tag)`);continue}let i=parseReleaseTag(r,n),s=i===null?null:{...i,tag:r,prerelease:isPrerelease(i.version),buildNumber:a};o.push({tag:r,context:s})}return o}async function uploadFiles(e,t,n,r){if(t.dryRun)I.info(`[dry-run] Skipping upload to ${n}`);else{if(!t.platform)throw new T(`Platform connection is required for asset upload`);I.info(`Uploading assets to release ${n}`);for(let i of r)t.platform.type===`github`?uploadToGitHub(e,t,n,i):await uploadToForgejo(e,t.platform.conn,n,i)}}async function runReleaseAssets(e,t){debug(t,`Config: dryRun=${String(t.dryRun)} cwd=${t.cwd}`);let n=isMonorepoRepo$1(e,t.cwd,t.toolingConfig),r=n?null:rootPackageName(e,t.cwd),i=allTargets(e,t.cwd,t.toolingConfig,r),a=t.toolingConfig?.versionStamp??[];if(i.length===0&&a.length===0){I.info(`No release assets configured in .tooling.json or by convention (${Si} script)`);return}if(a.length>0&&refuseForeignVersionOfRecord(t.cwd),!t.dryRun&&!t.platform&&i.length>0)throw new T(`Platform connection is required for asset upload`);let o=await findReleasesAtHead(e,t,r),s={targets:i,stampEntries:a,isMonorepo:n,releases:o};if(o.every(e=>e.context===null)){await buildOnceForEveryRelease(e,t,s,null);return}await buildPerPackageRelease(e,t,s);let c={...s,targets:i.filter(e=>e.owner===null),stampEntries:a.filter(e=>stampOwner(e,r)===null)};(c.targets.length!==0||c.stampEntries.length!==0)&&await buildOnceForEveryRelease(e,t,c,(o.length===1?o[0]:void 0)?.context??null)}function stampOwner(e,t){return e.package??t}async function buildOnceForEveryRelease(e,t,n,r){let i=stampWithRootVersion(e,t.cwd,n.stampEntries),a=buildTargets(e,n.targets,r,t);verifyStamp(e,i),n.releases.length===0&&I.info(`No release found at HEAD, skipping upload`);for(let r of n.releases)await uploadFiles(e,t,r.tag,a)}async function buildPerPackageRelease(e,t,n){for(let r of n.releases){let i=r.context;if(i===null)continue;let a=n.targets.filter(e=>e.owner===i.packageName),o=stampOwnedVersionFiles(e,t.cwd,t.toolingConfig,i,n.isMonorepo);if(a.length===0&&o.length===0)continue;let s=buildTargets(e,a,i,t);verifyStamp(e,o),await uploadFiles(e,t,r.tag,s)}}async function releaseExists(e,t,n){if(!t.platform)return!1;if(t.platform.type===`forgejo`)return findRelease(e,t.platform.conn,n);let r=e.exec(`gh`,[`release`,`view`,n],{cwd:t.cwd});return debugExec(t,`gh release view ${n}`,r),r.exitCode===0}const wi=[`node_modules/`,`.pnpm-store/`,`dist/`,`*.tsbuildinfo`,`.env`,`.env.*`,`!.env.example`],Ti=[`.tooling-migrate.md`,`.tooling-archived/`,`.claude/hooks/bst-hook.audit.local.jsonl*`,`.superpowers/`,`coverage/`,`.bst/`];function conditionalEntries(e){let t=[];return hasReleaseAssets(e)&&t.push(`${Ci}/`),t}function normalizeEntry(e){let t=e.trim();return t.startsWith(`/`)&&(t=t.slice(1)),t.endsWith(`/`)&&(t=t.slice(0,-1)),t}async function generateGitignore(e){let t=`.gitignore`,n=[...wi,...Ti,...conditionalEntries(e)],r=e.read(t);if(r){let i=new Set(r.split(`
|
|
150
|
+
`).map(normalizeEntry).filter(e=>e.length>0)),a=n.filter(e=>!i.has(normalizeEntry(e)));if(a.length===0)return{filePath:t,action:`skipped`,description:`Already has all standard entries`};let o=wi.filter(e=>!i.has(normalizeEntry(e))),s=r.trimEnd()+`
|
|
150
151
|
|
|
151
152
|
# Added by @bensandee/tooling
|
|
152
153
|
`+a.join(`
|
|
153
154
|
`)+`
|
|
154
155
|
`;return e.write(t,s),o.length===0?{filePath:t,action:`skipped`,description:`Only optional entries missing`}:{filePath:t,action:`updated`,description:`Appended ${String(a.length)} missing entries`}}return e.write(t,n.join(`
|
|
155
156
|
`)+`
|
|
156
|
-
`),{filePath:t,action:`created`,description:`Generated .gitignore`}}const
|
|
157
|
-
# core.autocrlf/core.eol at checkout. Rules below this line win over it.`,
|
|
158
|
-
`).some(e=>{let t=e.trim();if(t.startsWith(`#`))return!1;let n=t.split(/\s+/).filter(Boolean);if(n[0]!==`*`)return!1;let r=new Set(n.slice(1));return r.has(`text=auto`)&&r.has(`eol=lf`)})}async function generateGitattributes(e){let t=`.gitattributes`,n=e.read(t);if(n===void 0||n.trim()===``)return e.write(t,`${
|
|
159
|
-
# placed below would override any binary/-text marks you already have.\n${Mi}\n\n${n}`;return e.write(t,r),{filePath:t,action:`updated`,description:`Prepended the LF rule`}}const Ni=`main`,Pi=N.object({defaultBranch:N.union([N.literal(``),Dt]).optional()});function configuredDefaultBranch(e){let t=parseToolingConfigSlice(e,Pi,{block:`defaultBranch`})?.defaultBranch;return t===void 0||t===``?Ni:t}function readConfiguredDefaultBranch(e){let t=w.join(e,`.tooling.json`);if(!o(t))return Ni;let n;try{n=p(t,`utf-8`)}catch(e){throw new T(`Cannot read ${t}: ${O(e)}`,{cause:e})}return configuredDefaultBranch(n)}function processCiEventSource(){return{env:process.env,readFile:e=>{try{return p(e,`utf-8`)}catch{return}}}}const Fi=N.object({repository:N.object({default_branch:N.string().min(1)})});function ciDefaultBranch(e){if(e===void 0||e.env.GITHUB_ACTIONS!==`true`)return;let t=e.env.GITHUB_EVENT_PATH;if(t===void 0||t===``)return;let n=e.readFile(t);if(n===void 0||n.trim()===``)return;let r;try{r=JSON.parse(n)}catch{return}let i=Fi.safeParse(r);return i.success?i.data.repository.default_branch:void 0}function refuseForgeDefaultMismatch(e,t,n){let r=ciDefaultBranch(t);if(r!==void 0&&r!==e)throw new T(`${n}: .tooling.json#defaultBranch is "${e}", but the forge reports "${r}" as this repository's default branch. Set .tooling.json#defaultBranch to "${r}" and run pnpm exec bst repo:sync.`)}const Ii=`pnpm exec bst webhook:send "$POST_RELEASE_HOOK_URL" --tag "$RELEASE_TAG"`;function secretsEnv(e){let t={};for(let n of e??[])t[n]=actionsExpr(`secrets.${n}`);return t}function hookSecretEnv(e){return{POST_RELEASE_HOOK_URL:actionsExpr(`vars.POST_RELEASE_HOOK_URL || secrets.POST_RELEASE_HOOK_URL`),WEBHOOK_SECRET:actionsExpr(`secrets.POST_RELEASE_HOOK_SECRET`),...secretsEnv(e)}}function postReleaseHookStep(e){let t=e?.condition??(e?.guardMain?isDefaultBranch(e.defaultBranch):void 0);return{step:{name:`Post-release hook`,...t&&{if:t},env:hookSecretEnv(e?.secrets),run:e?.command??Ii}}}function postReleaseHookJob(e){return{needs:e.needsJob,if:onlyOnDefaultBranch(e.defaultBranch,e.publishCondition),runsOn:e.runsOn,"continue-on-error":!0,steps:[...commonSteps(e.ci),{step:{name:`Post-release hook`,env:{...hookSecretEnv(e.secrets),RELEASE_TAG:e.releaseTagExpr},run:e.command??Ii}}]}}function deployDispatchStep(e){let t=e.deploy.stack??e.packageName.replace(/-/g,`_`),n=e.deploy.workflow??`deploy.yml`,r=e.deploy.ref??`main`,i=[`pnpm exec bst workflow:dispatch`,`--repo ${e.deploy.dispatchRepo}`,`--workflow ${n}`,`--ref ${r}`,`--input stack=${t}`,`--input release_tag=$RELEASE_TAG`].join(` `);return{step:{name:`Dispatch deploy`,...e.condition&&{if:e.condition},env:{...e.releaseEnv,...secretsEnv(e.secrets),RELEASE_TAG:e.releaseTagExpr},run:i}}}function commonSteps(e){return[{step:{uses:`actions/checkout@v6`,with:{"fetch-depth":0}}},...miseSetupSteps(e),{step:{run:`pnpm install --frozen-lockfile`}}]}function releaseItSteps(e,t){let n=e===`github`?{GITHUB_TOKEN:actionsExpr(`secrets.RELEASE_TOKEN`)}:{RELEASE_TOKEN:actionsExpr(`secrets.RELEASE_TOKEN`)};return[...commonSteps(e),{step:{run:t.publishRun(`pnpm release-it --ci`),env:{...n,...t.tokenEnv,RELEASE_DEBUG:actionsExpr(`vars.RELEASE_DEBUG || 'false'`)}}}]}function simpleWorkflowDispatchTrigger(){return{workflow_dispatch:{inputs:{bump:{description:`Version bump type (default: conventional-commits auto-detect)`,required:!1,type:`choice`,default:`auto`,options:[`auto`,`major`,`minor`,`patch`,`first-release`]},prerelease:{description:`Create a prerelease with the given tag (e.g., beta, alpha)`,required:!1,type:`string`}}}}}function connectionEnv(e){return e===`github`?{RELEASE_TOKEN:actionsExpr(`secrets.RELEASE_TOKEN`),GITHUB_TOKEN:actionsExpr(`secrets.RELEASE_TOKEN`)}:{FORGEJO_SERVER_URL:actionsExpr(`github.server_url`),FORGEJO_REPOSITORY:actionsExpr(`github.repository`),RELEASE_TOKEN:actionsExpr(`secrets.RELEASE_TOKEN`)}}function simpleReleaseEnv(){return{RELEASE_BUMP:actionsExpr(`inputs.bump`),RELEASE_PRERELEASE:actionsExpr(`inputs.prerelease`)}}function simpleReleaseSteps(e){let{ci:t,hasDocker:n,hasAssets:r,host:i}=e,a=connectionEnv(t),o=`steps.release.outputs.pushed == 'true'`,s={step:{id:`release`,name:`Release`,env:{...a,...simpleReleaseEnv(),RELEASE_DEBUG:actionsExpr(`vars.RELEASE_DEBUG || 'false'`)},run:`pnpm exec bst release:simple`}},c={step:{name:`Upload Release Assets`,if:o,env:a,run:`pnpm exec bst release:assets`}},l={step:{name:`Publish Docker images`,if:o,env:dockerPublishEnv(i),run:`pnpm exec bst docker:publish`}};return[...commonSteps(t),s,...r?[c]:[],...n?[l]:[]]}function buildSteps(e,t){switch(e){case`release-it`:return releaseItSteps(t.ci,t.npmAuth);case`simple`:return simpleReleaseSteps(t);default:return null}}function hasReleaseWorkflow(e){return e===`simple`||e===`release-it`}function releaseWorkflowPath(e){return e===`github`?`.github/workflows/release.yml`:`.forgejo/workflows/release.yml`}async function generateReleaseCi(e){let t=`release-ci`,n=e.config.ci===`github`,r=configuredDefaultBranch(e.read(`.tooling.json`)),i=actionsExpr(Zn);if(e.config.ci===`none`||e.config.releaseStrategy===`none`)return{filePath:t,action:`skipped`,description:`Release CI workflow not applicable`};if(!hasReleaseWorkflow(e.config.releaseStrategy))return{filePath:t,action:`skipped`,description:`Release step included in CI workflow`};let a=e.config.publishNpm===!0,o=releaseWorkflowPath(e.config.ci),s=hasDockerPackages(e)&&e.config.publishDocker,c=hasReleaseAssets(e)||hasVersionStamp(e),l=resolveGenTimeHost(e),u=npmAuthWiring(e,a&&e.config.releaseStrategy===`release-it`),d=getPostReleaseHookSecrets(e),f=buildSteps(e.config.releaseStrategy,{ci:e.config.ci,npmAuth:u,hasDocker:s,hasAssets:c,host:l});if(!f)return{filePath:t,action:`skipped`,description:`Release CI workflow not applicable`};let p=getDeployConfig(e);p&&(e.config.releaseStrategy===`release-it`?F.warn("`deploy` is set in .tooling.json but releaseStrategy=release-it does not support deploy dispatch -- no deploy step generated. Use the 'simple' or 'changesets' strategy."):e.config.releaseStrategy===`simple`&&f.push(deployDispatchStep({deploy:p,packageName:e.config.name,releaseEnv:connectionEnv(e.config.ci),releaseTagExpr:actionsExpr(`steps.release.outputs.tag`),condition:`steps.release.outputs.pushed == 'true'`,secrets:d})));let m,h;e.config.releaseStrategy===`release-it`?f.push(postReleaseHookStep({defaultBranch:r,command:getPostReleaseHookCommand(e),secrets:d})):e.config.releaseStrategy===`simple`&&(h={pushed:actionsExpr(`steps.release.outputs.pushed`),tag:actionsExpr(`steps.release.outputs.tag`)},m={"post-release-hook":postReleaseHookJob({defaultBranch:r,ci:e.config.ci,needsJob:`release`,runsOn:i,publishCondition:`needs.release.outputs.pushed == 'true'`,releaseTagExpr:actionsExpr(`needs.release.outputs.tag`),command:getPostReleaseHookCommand(e),secrets:d})});let g=e.config.releaseStrategy===`simple`?simpleWorkflowDispatchTrigger():{workflow_dispatch:null},_=buildWorkflowYaml({ci:e.config.ci,name:`Release`,on:g,...n&&{permissions:{contents:`write`}},jobName:`release`,jobIf:isDefaultBranch(r),runsOn:i,...h&&{jobOutputs:h},steps:f,...m&&{extraJobs:m}}),v=e.exists(o),y=v?e.read(o):void 0,b=applyWorkspaceToolingBuild(_,e.packageJson);if(y){if(isToolingIgnored(y))return{filePath:o,action:`skipped`,description:`Release workflow has ignore comment`};if(y.includes(`Managed by @bensandee/tooling --`)&&normalizeWorkflow(y,rr)===normalizeWorkflow(b,rr))return{filePath:o,action:`skipped`,description:`Release workflow already up to date`}}let x=preservePinnedActions(b,y,rr),S=y?insertCustomBlocks(x,extractCustomBlocks(y)):x;return e.write(o,S),{filePath:o,action:v?`updated`:`created`,description:`Generated ${n?`GitHub`:`Forgejo`} Actions release workflow`}}function versionPrBranch(e){return`changeset-release/${e}`}function coverageHistorySteps(){return[{step:{name:`Print coverage summary`,if:tr,run:`pnpm exec bst coverage:summary`}},{step:{name:`Append record to bst/coverage-metrics branch`,if:tr,run:`pnpm exec bst coverage:record`}},{step:{name:`Show recent coverage trend`,if:tr,run:`pnpm exec bst coverage:status --limit 10`}}]}function healthSteps(e){return e?[{step:{name:`Append health record to bst/health-metrics branch`,if:tr,run:`pnpm exec bst health:record`}},{step:{name:`Show recent codebase-health trend`,if:tr,run:`pnpm exec bst health:status --limit 10`}}]:[]}function changesetsReleaseStep(e,t,n,r){if(e===`github`){let e={GITHUB_TOKEN:actionsExpr(`secrets.RELEASE_TOKEN`),...t&&{NPM_TOKEN:actionsExpr(`secrets.NPM_TOKEN`)}};return{step:{id:`release`,uses:`changesets/action@v1`,if:isDefaultBranch(r),with:{publish:`pnpm changeset publish`,version:`pnpm changeset version`},env:e}}}let i={FORGEJO_SERVER_URL:actionsExpr(`github.server_url`),FORGEJO_REPOSITORY:actionsExpr(`github.repository`),RELEASE_TOKEN:actionsExpr(`secrets.RELEASE_TOKEN`),...n.tokenEnv,RELEASE_DEBUG:actionsExpr(`vars.RELEASE_DEBUG || 'false'`)};return{step:{id:`release`,name:`Release`,if:isDefaultBranch(r),env:i,run:n.publishRun(`pnpm exec bst release:changesets`)}}}function ciConcurrency(e,t){return e===`forgejo`?{group:`ci-${actionsExpr(`${isDefaultBranch(t)} && github.sha || github.ref`)}`,"cancel-in-progress":actionsExpr(isNotDefaultBranch(t))}:{group:`ci-${actionsExpr(`github.ref`)}`,"cancel-in-progress":actionsExpr(isNotDefaultBranch(t))}}function checkJobRunsOn(e){return actionsExpr(`${isDefaultBranch(e)} && (${Zn}) || (vars.BST_RUNNER || 'ubuntu-latest')`)}function checkSteps(e,t,n){let r=t?`pnpm ci:check`:`pnpm ci:check --no-coverage`;return[{step:{uses:`actions/checkout@v6`,with:{"fetch-depth":0}}},...miseSetupSteps(e),{step:{run:`pnpm install --frozen-lockfile`}},...n?[{step:{name:`Sweep leaked Docker resources`,run:`if command -v docker >/dev/null 2>&1; then pnpm exec bst docker:sweep; fi`}}]:[],{step:{name:`Run all checks`,run:r}}]}function ciWorkflowPath(e,t){return`${e===`github`?`.github/workflows`:`.forgejo/workflows`}/${t===`changesets`?`ci.yml`:`check.yml`}`}const Li=N.object({snapshot:Ut.optional()});function snapshotJob(e,t,n){return{needs:`check`,if:onlyOnDefaultBranch(e,`needs.check.outputs.published != 'true'`),runsOn:actionsExpr(Zn),outputs:{published:actionsExpr(`steps.snapshot.outputs.published`),version:actionsExpr(`steps.snapshot.outputs.version`),tag:actionsExpr(`steps.snapshot.outputs.tag`),packages:actionsExpr(`steps.snapshot.outputs.packages`)},steps:[...commonSteps(t),{step:{id:`snapshot`,name:`Snapshot release`,env:n,run:`pnpm exec bst release:snapshot`}}]}}async function generateCi(e){if(e.config.ci===`none`)return{filePath:`ci`,action:`skipped`,description:`CI workflow not requested`};let t=configuredDefaultBranch(e.read(`.tooling.json`)),n=checkJobRunsOn(t),r=e.config.ci===`github`,i=!r,a=e.config.releaseStrategy===`changesets`,o=e.config.publishNpm===!0,s=getPostReleaseHookCommand(e),c=getPostReleaseHookSecrets(e),l=getDeployConfig(e),u=resolveCoverageConfigFromContext(e,e.config.setupVitest),d=u.historyEnabled,f=resolveHealthConfigFromContext(e,{isMonorepo:e.config.structure===`monorepo`}).historyEnabled,p=a&&hasDockerPackages(e)&&e.config.publishDocker,m=a&&(hasReleaseAssets(e)||hasVersionStamp(e)),h=p?resolveGenTimeHost(e):null,g=`steps.release.outputs.published == 'true'`,_=onlyOnDefaultBranch(t,g),v=e.config.structure===`monorepo`?`.[0] | "\\(.name)@\\(.version)"`:`.[0] | "v\\(.version)"`,y={step:{name:`Derive release tag`,id:`derive-tag`,if:g,env:{PUBLISHED_PACKAGES:actionsExpr(`steps.release.outputs.publishedPackages`)},run:`echo "tag=$(echo "$PUBLISHED_PACKAGES" | jq -r '${v}')" >> "$GITHUB_OUTPUT"\necho "version=$(echo "$PUBLISHED_PACKAGES" | jq -r '.[0].version')" >> "$GITHUB_OUTPUT"`}},b=actionsExpr(r?`steps.derive-tag.outputs.tag`:`steps.release.outputs.tag`),x=actionsExpr(r?`steps.derive-tag.outputs.version`:`steps.release.outputs.version`),S={};r?S.GITHUB_TOKEN=actionsExpr(`secrets.RELEASE_TOKEN`):(S.FORGEJO_SERVER_URL=actionsExpr(`github.server_url`),S.FORGEJO_REPOSITORY=actionsExpr(`github.repository`),S.RELEASE_TOKEN=actionsExpr(`secrets.RELEASE_TOKEN`));let C=npmAuthWiring(e,a&&o&&!r),ee=[...checkSteps(e.config.ci,u.enabled,hasDockerPackages(e)),...d?coverageHistorySteps():[],...healthSteps(f),...a?[changesetsReleaseStep(e.config.ci,o,C,t)]:[],...a&&r?[y]:[],...m?[{step:{name:`Upload Release Assets`,if:_,env:S,run:`pnpm exec bst release:assets`}}]:[],...p?[{step:{name:`Publish Docker images`,if:_,env:dockerPublishEnv(h),run:`pnpm exec bst docker:publish`}}]:[],...a&&l?[deployDispatchStep({deploy:l,packageName:e.config.name,releaseEnv:S,releaseTagExpr:b,condition:_,secrets:c})]:[]],w,te;a&&(te={published:actionsExpr(`steps.release.outputs.published`),tag:b,version:x},w={"post-release-hook":postReleaseHookJob({defaultBranch:t,ci:e.config.ci,needsJob:`check`,runsOn:actionsExpr(Zn),publishCondition:`needs.check.outputs.published == 'true'`,releaseTagExpr:actionsExpr(`needs.check.outputs.tag`),command:s,secrets:c})},parseToolingConfigSlice(e.read(`.tooling.json`),Li,{block:`snapshot`})?.snapshot&&(w.snapshot=snapshotJob(t,e.config.ci,{...S})));let ne=d||f?defaultBranchJobEnv(t):{},re=parseToolingConfigSlice(e.read(`.tooling.json`),N.object({checks:ht.optional()}),{block:`checks`}),T=a&&re?.checks?.runOnVersionPr!==!0,E=buildWorkflowYaml({ci:e.config.ci,name:`CI`,on:{push:{branches:[t],"tags-ignore":[`**`]},pull_request:null},...r&&(d||f)&&{permissions:{contents:`write`}},enableEmailNotifications:i,...a&&{concurrency:ciConcurrency(e.config.ci,t)},jobName:`check`,runsOn:n,...T&&{jobIf:`github.head_ref != '${versionPrBranch(t)}'`},...Object.keys(ne).length>0&&{jobEnv:ne},...te&&{jobOutputs:te},steps:ee,...w&&{extraJobs:w}}),D=ciWorkflowPath(e.config.ci,e.config.releaseStrategy),ie=e.exists(D),O=ie?e.read(D):void 0,ae=applyWorkspaceToolingBuild(E,e.packageJson);if(O){if(isToolingIgnored(O))return{filePath:D,action:`skipped`,description:`CI workflow has ignore comment`};if(O.includes(`Managed by @bensandee/tooling --`)&&normalizeWorkflow(O,rr)===normalizeWorkflow(ae,rr))return{filePath:D,action:`skipped`,description:`CI workflow already up to date`}}let k=preservePinnedActions(ae,O,rr),A=O?insertCustomBlocks(k,extractCustomBlocks(O)):k;return e.write(D,A),{filePath:D,action:ie?`updated`:`created`,description:`Generated ${r?`GitHub`:`Forgejo`} Actions CI workflow`}}const Ri=[`composer`];function scriptsInvoke(e,t){let n=new RegExp(String.raw`(?<![\w.-])${t}(?![\w.-])`);return Object.values(e.packageJson?.scripts??{}).some(e=>n.test(e))}function foreignOwnedBinaries(e){return Ri.filter(t=>scriptsInvoke(e,t))}function ignoreBinariesField(e){return e.length>0?`\n ignoreBinaries: ${JSON.stringify(e)},`:``}function ignorableDependencies(e){let t=[];return wantsAgentCli(e)&&t.push(pr),wantsCommitAndTagVersion(e)&&t.push(hr),t}function ignoreDependenciesField(e){return e.length>0?`\n ignoreDependencies: ${JSON.stringify(e)},`:``}function buildKnipConfigSingle(e,t,n){return`import type { KnipConfig } from "knip";
|
|
157
|
+
`),{filePath:t,action:`created`,description:`Generated .gitignore`}}const Ei=`# Managed by @bensandee/tooling: LF working tree on every platform, overriding
|
|
158
|
+
# core.autocrlf/core.eol at checkout. Rules below this line win over it.`,Di=`* text=auto eol=lf`;function hasLfRule(e){return e.split(`
|
|
159
|
+
`).some(e=>{let t=e.trim();if(t.startsWith(`#`))return!1;let n=t.split(/\s+/).filter(Boolean);if(n[0]!==`*`)return!1;let r=new Set(n.slice(1));return r.has(`text=auto`)&&r.has(`eol=lf`)})}async function generateGitattributes(e){let t=`.gitattributes`,n=e.read(t);if(n===void 0||n.trim()===``)return e.write(t,`${Ei}\n${Di}\n`),{filePath:t,action:n===void 0?`created`:`updated`,description:`Generated .gitattributes`};if(hasLfRule(n))return{filePath:t,action:`skipped`,description:`Already has the LF rule`};let r=`${Ei}\n# Prepended above your existing rules: .gitattributes is last-match-wins, so a rule
|
|
160
|
+
# placed below would override any binary/-text marks you already have.\n${Di}\n\n${n}`;return e.write(t,r),{filePath:t,action:`updated`,description:`Prepended the LF rule`}}const Oi=`main`,ki=P.object({defaultBranch:P.union([P.literal(``),Dt]).optional()});function configuredDefaultBranch(e){let t=parseToolingConfigSlice(e,ki,{block:`defaultBranch`})?.defaultBranch;return t===void 0||t===``?Oi:t}function readConfiguredDefaultBranch(e){let t=w.join(e,`.tooling.json`);if(!o(t))return Oi;let n;try{n=p(t,`utf-8`)}catch(e){throw new T(`Cannot read ${t}: ${k(e)}`,{cause:e})}return configuredDefaultBranch(n)}function processCiEventSource(){return{env:process.env,readFile:e=>{try{return p(e,`utf-8`)}catch{return}}}}const Ai=P.object({repository:P.object({default_branch:P.string().min(1)})});function ciDefaultBranch(e){if(e===void 0||e.env.GITHUB_ACTIONS!==`true`)return;let t=e.env.GITHUB_EVENT_PATH;if(t===void 0||t===``)return;let n=e.readFile(t);if(n===void 0||n.trim()===``)return;let r;try{r=JSON.parse(n)}catch{return}let i=Ai.safeParse(r);return i.success?i.data.repository.default_branch:void 0}function refuseForgeDefaultMismatch(e,t,n){let r=ciDefaultBranch(t);if(r!==void 0&&r!==e)throw new T(`${n}: .tooling.json#defaultBranch is "${e}", but the forge reports "${r}" as this repository's default branch. Set .tooling.json#defaultBranch to "${r}" and run pnpm exec bst repo:sync.`)}const ji=`pnpm exec bst webhook:send "$POST_RELEASE_HOOK_URL" --tag "$RELEASE_TAG"`;function secretsEnv(e){let t={};for(let n of e??[])t[n]=actionsExpr(`secrets.${n}`);return t}function hookSecretEnv(e){return{POST_RELEASE_HOOK_URL:actionsExpr(`vars.POST_RELEASE_HOOK_URL`),WEBHOOK_SECRET:actionsExpr(`secrets.POST_RELEASE_HOOK_SECRET`),...secretsEnv(e)}}function postReleaseHookStep(e){let t=e?.condition??(e?.guardMain?isDefaultBranch(e.defaultBranch):void 0);return{step:{name:`Post-release hook`,...t&&{if:t},env:hookSecretEnv(e?.secrets),run:e?.command??ji}}}function postReleaseHookJob(e){return{needs:e.needsJob,if:onlyOnDefaultBranch(e.defaultBranch,e.publishCondition),runsOn:e.runsOn,"continue-on-error":!0,steps:[...commonSteps(e.ci),{step:{name:`Post-release hook`,env:{...hookSecretEnv(e.secrets),RELEASE_TAG:e.releaseTagExpr},run:e.command??ji}}]}}function deployDispatchStep(e){let t=e.deploy.stack??e.packageName.replace(/-/g,`_`),n=e.deploy.workflow??`deploy.yml`,r=e.deploy.ref??`main`,i=[`pnpm exec bst workflow:dispatch`,`--repo ${e.deploy.dispatchRepo}`,`--workflow ${n}`,`--ref ${r}`,`--input stack=${t}`,`--input release_tag=$RELEASE_TAG`].join(` `);return{step:{name:`Dispatch deploy`,...e.condition&&{if:e.condition},env:{...e.releaseEnv,...secretsEnv(e.secrets),RELEASE_TAG:e.releaseTagExpr},run:i}}}function commonSteps(e){return[{step:{uses:`actions/checkout@v6`,with:{"fetch-depth":0}}},...miseSetupSteps(e),{step:{run:`pnpm install --frozen-lockfile`}}]}function releaseItSteps(e,t){let n=e===`github`?{GITHUB_TOKEN:actionsExpr(`secrets.RELEASE_TOKEN`)}:{RELEASE_TOKEN:actionsExpr(`secrets.RELEASE_TOKEN`)};return[...commonSteps(e),{step:{run:t.publishRun(`pnpm release-it --ci`),env:{...n,...t.tokenEnv,RELEASE_DEBUG:actionsExpr(`vars.RELEASE_DEBUG || 'false'`)}}}]}function simpleWorkflowDispatchTrigger(){return{workflow_dispatch:{inputs:{bump:{description:`Version bump type (default: conventional-commits auto-detect)`,required:!1,type:`choice`,default:`auto`,options:[`auto`,`major`,`minor`,`patch`,`first-release`]},prerelease:{description:`Create a prerelease with the given tag (e.g., beta, alpha)`,required:!1,type:`string`}}}}}function connectionEnv(e){return e===`github`?{RELEASE_TOKEN:actionsExpr(`secrets.RELEASE_TOKEN`),GITHUB_TOKEN:actionsExpr(`secrets.RELEASE_TOKEN`)}:{FORGEJO_SERVER_URL:actionsExpr(`github.server_url`),FORGEJO_REPOSITORY:actionsExpr(`github.repository`),RELEASE_TOKEN:actionsExpr(`secrets.RELEASE_TOKEN`)}}function simpleReleaseEnv(){return{RELEASE_BUMP:actionsExpr(`inputs.bump`),RELEASE_PRERELEASE:actionsExpr(`inputs.prerelease`)}}function simpleReleaseSteps(e){let{ci:t,hasDocker:n,hasAssets:r,host:i}=e,a=connectionEnv(t),o=`steps.release.outputs.pushed == 'true'`,s={step:{id:`release`,name:`Release`,env:{...a,...simpleReleaseEnv(),RELEASE_DEBUG:actionsExpr(`vars.RELEASE_DEBUG || 'false'`)},run:`pnpm exec bst release:simple`}},c={step:{name:`Upload Release Assets`,if:o,env:a,run:`pnpm exec bst release:assets`}},l={step:{name:`Publish Docker images`,if:o,env:dockerPublishEnv(i),run:`pnpm exec bst docker:publish`}};return[...commonSteps(t),s,...r?[c]:[],...n?[l]:[]]}function buildSteps(e,t){switch(e){case`release-it`:return releaseItSteps(t.ci,t.npmAuth);case`simple`:return simpleReleaseSteps(t);default:return null}}function hasReleaseWorkflow(e){return e===`simple`||e===`release-it`}function releaseWorkflowPath(e){return e===`github`?`.github/workflows/release.yml`:`.forgejo/workflows/release.yml`}async function generateReleaseCi(e){let t=`release-ci`,n=e.config.ci===`github`,r=configuredDefaultBranch(e.read(`.tooling.json`)),i=actionsExpr(Kn);if(e.config.ci===`none`||e.config.releaseStrategy===`none`)return{filePath:t,action:`skipped`,description:`Release CI workflow not applicable`};if(!hasReleaseWorkflow(e.config.releaseStrategy))return{filePath:t,action:`skipped`,description:`Release step included in CI workflow`};let a=e.config.publishNpm===!0,o=releaseWorkflowPath(e.config.ci),s=hasDockerPackages(e)&&e.config.publishDocker,c=hasReleaseAssets(e)||hasVersionStamp(e),l=resolveGenTimeHost(e),u=npmAuthWiring(e,a&&e.config.releaseStrategy===`release-it`),d=getPostReleaseHookSecrets(e),f=buildSteps(e.config.releaseStrategy,{ci:e.config.ci,npmAuth:u,hasDocker:s,hasAssets:c,host:l});if(!f)return{filePath:t,action:`skipped`,description:`Release CI workflow not applicable`};let p=getDeployConfig(e);p&&(e.config.releaseStrategy===`release-it`?I.warn("`deploy` is set in .tooling.json but releaseStrategy=release-it does not support deploy dispatch -- no deploy step generated. Use the 'simple' or 'changesets' strategy."):e.config.releaseStrategy===`simple`&&f.push(deployDispatchStep({deploy:p,packageName:e.config.name,releaseEnv:connectionEnv(e.config.ci),releaseTagExpr:actionsExpr(`steps.release.outputs.tag`),condition:`steps.release.outputs.pushed == 'true'`,secrets:d})));let m,h;e.config.releaseStrategy===`release-it`?f.push(postReleaseHookStep({defaultBranch:r,command:getPostReleaseHookCommand(e),secrets:d})):e.config.releaseStrategy===`simple`&&(h={pushed:actionsExpr(`steps.release.outputs.pushed`),tag:actionsExpr(`steps.release.outputs.tag`)},m={"post-release-hook":postReleaseHookJob({defaultBranch:r,ci:e.config.ci,needsJob:`release`,runsOn:i,publishCondition:`needs.release.outputs.pushed == 'true'`,releaseTagExpr:actionsExpr(`needs.release.outputs.tag`),command:getPostReleaseHookCommand(e),secrets:d})});let g=e.config.releaseStrategy===`simple`?simpleWorkflowDispatchTrigger():{workflow_dispatch:null},_=buildWorkflowYaml({ci:e.config.ci,name:`Release`,on:g,...n&&{permissions:{contents:`write`}},jobName:`release`,jobIf:isDefaultBranch(r),runsOn:i,...h&&{jobOutputs:h},steps:f,...m&&{extraJobs:m}}),v=e.exists(o),y=v?e.read(o):void 0,b=applyWorkspaceToolingBuild(_,e.packageJson);if(y){if(isToolingIgnored(y))return{filePath:o,action:`skipped`,description:`Release workflow has ignore comment`};if(y.includes(`Managed by @bensandee/tooling --`)&&normalizeWorkflow(y,Qn)===normalizeWorkflow(b,Qn))return{filePath:o,action:`skipped`,description:`Release workflow already up to date`}}let x=preservePinnedActions(b,y,Qn),S=y?insertCustomBlocks(x,extractCustomBlocks(y)):x;return e.write(o,S),{filePath:o,action:v?`updated`:`created`,description:`Generated ${n?`GitHub`:`Forgejo`} Actions release workflow`}}function versionPrBranch(e){return`changeset-release/${e}`}function coverageHistorySteps(){return[{step:{name:`Print coverage summary`,if:Xn,run:`pnpm exec bst coverage:summary`}},{step:{name:`Append record to bst/coverage-metrics branch`,if:Xn,run:`pnpm exec bst coverage:record`}},{step:{name:`Show recent coverage trend`,if:Xn,run:`pnpm exec bst coverage:status --limit 10`}}]}function healthSteps(e){return e?[{step:{name:`Append health record to bst/health-metrics branch`,if:Xn,run:`pnpm exec bst health:record`}},{step:{name:`Show recent codebase-health trend`,if:Xn,run:`pnpm exec bst health:status --limit 10`}}]:[]}function changesetsReleaseStep(e,t,n,r){if(e===`github`){let e={GITHUB_TOKEN:actionsExpr(`secrets.RELEASE_TOKEN`),...t&&{NPM_TOKEN:actionsExpr(`secrets.NPM_TOKEN`)}};return{step:{id:`release`,uses:`changesets/action@v1`,if:isDefaultBranch(r),with:{publish:`pnpm changeset publish`,version:`pnpm changeset version`},env:e}}}let i={FORGEJO_SERVER_URL:actionsExpr(`github.server_url`),FORGEJO_REPOSITORY:actionsExpr(`github.repository`),RELEASE_TOKEN:actionsExpr(`secrets.RELEASE_TOKEN`),...n.tokenEnv,RELEASE_DEBUG:actionsExpr(`vars.RELEASE_DEBUG || 'false'`)};return{step:{id:`release`,name:`Release`,if:isDefaultBranch(r),env:i,run:n.publishRun(`pnpm exec bst release:changesets`)}}}function ciConcurrency(e,t){return e===`forgejo`?{group:`ci-${actionsExpr(`${isDefaultBranch(t)} && github.sha || github.ref`)}`,"cancel-in-progress":actionsExpr(isNotDefaultBranch(t))}:{group:`ci-${actionsExpr(`github.ref`)}`,"cancel-in-progress":actionsExpr(isNotDefaultBranch(t))}}function checkJobRunsOn(e){return actionsExpr(`${isDefaultBranch(e)} && (${Kn}) || (vars.BST_RUNNER || 'ubuntu-latest')`)}function checkSteps(e,t,n){let r=t?`pnpm ci:check`:`pnpm ci:check --no-coverage`;return[{step:{uses:`actions/checkout@v6`,with:{"fetch-depth":0}}},...miseSetupSteps(e),{step:{run:`pnpm install --frozen-lockfile`}},...n?[{step:{name:`Sweep leaked Docker resources`,run:`if command -v docker >/dev/null 2>&1; then pnpm exec bst docker:sweep; fi`}}]:[],{step:{name:`Run all checks`,run:r}},{step:{name:`Failure summary`,if:`failure()`,run:`pnpm exec bst checks:failures`}}]}function ciWorkflowPath(e,t){return`${e===`github`?`.github/workflows`:`.forgejo/workflows`}/${t===`changesets`?`ci.yml`:`check.yml`}`}const Mi=P.object({snapshot:Ht.optional()});function snapshotJob(e,t,n){return{needs:`check`,if:onlyOnDefaultBranch(e,`needs.check.outputs.published != 'true'`),runsOn:actionsExpr(Kn),outputs:{published:actionsExpr(`steps.snapshot.outputs.published`),version:actionsExpr(`steps.snapshot.outputs.version`),tag:actionsExpr(`steps.snapshot.outputs.tag`),packages:actionsExpr(`steps.snapshot.outputs.packages`)},steps:[...commonSteps(t),{step:{id:`snapshot`,name:`Snapshot release`,env:n,run:`pnpm exec bst release:snapshot`}}]}}async function generateCi(e){if(e.config.ci===`none`)return{filePath:`ci`,action:`skipped`,description:`CI workflow not requested`};let t=configuredDefaultBranch(e.read(`.tooling.json`)),n=checkJobRunsOn(t),r=e.config.ci===`github`,i=!r,a=e.config.releaseStrategy===`changesets`,o=e.config.publishNpm===!0,s=getPostReleaseHookCommand(e),c=getPostReleaseHookSecrets(e),l=getDeployConfig(e),u=resolveCoverageConfigFromContext(e,e.config.setupVitest),d=u.historyEnabled,f=resolveHealthConfigFromContext(e,{isMonorepo:e.config.structure===`monorepo`}).historyEnabled,p=a&&hasDockerPackages(e)&&e.config.publishDocker,m=a&&(hasReleaseAssets(e)||hasVersionStamp(e)),h=p?resolveGenTimeHost(e):null,g=`steps.release.outputs.published == 'true'`,_=onlyOnDefaultBranch(t,g),v=e.config.structure===`monorepo`?`.[0] | "\\(.name)@\\(.version)"`:`.[0] | "v\\(.version)"`,y={step:{name:`Derive release tag`,id:`derive-tag`,if:g,env:{PUBLISHED_PACKAGES:actionsExpr(`steps.release.outputs.publishedPackages`)},run:`echo "tag=$(echo "$PUBLISHED_PACKAGES" | jq -r '${v}')" >> "$GITHUB_OUTPUT"\necho "version=$(echo "$PUBLISHED_PACKAGES" | jq -r '.[0].version')" >> "$GITHUB_OUTPUT"`}},b=actionsExpr(r?`steps.derive-tag.outputs.tag`:`steps.release.outputs.tag`),x=actionsExpr(r?`steps.derive-tag.outputs.version`:`steps.release.outputs.version`),S={};r?S.GITHUB_TOKEN=actionsExpr(`secrets.RELEASE_TOKEN`):(S.FORGEJO_SERVER_URL=actionsExpr(`github.server_url`),S.FORGEJO_REPOSITORY=actionsExpr(`github.repository`),S.RELEASE_TOKEN=actionsExpr(`secrets.RELEASE_TOKEN`));let C=npmAuthWiring(e,a&&o&&!r),ee=[...checkSteps(e.config.ci,u.enabled,hasDockerPackages(e)),...d?coverageHistorySteps():[],...healthSteps(f),...a?[changesetsReleaseStep(e.config.ci,o,C,t)]:[],...a&&r?[y]:[],...m?[{step:{name:`Upload Release Assets`,if:_,env:S,run:`pnpm exec bst release:assets`}}]:[],...p?[{step:{name:`Publish Docker images`,if:_,env:dockerPublishEnv(h),run:`pnpm exec bst docker:publish`}}]:[],...a&&l?[deployDispatchStep({deploy:l,packageName:e.config.name,releaseEnv:S,releaseTagExpr:b,condition:_,secrets:c})]:[]],w,te;a&&(te={published:actionsExpr(`steps.release.outputs.published`),tag:b,version:x},w={"post-release-hook":postReleaseHookJob({defaultBranch:t,ci:e.config.ci,needsJob:`check`,runsOn:actionsExpr(Kn),publishCondition:`needs.check.outputs.published == 'true'`,releaseTagExpr:actionsExpr(`needs.check.outputs.tag`),command:s,secrets:c})},parseToolingConfigSlice(e.read(`.tooling.json`),Mi,{block:`snapshot`})?.snapshot&&(w.snapshot=snapshotJob(t,e.config.ci,{...S})));let ne=d||f?defaultBranchJobEnv(t):{},re=parseToolingConfigSlice(e.read(`.tooling.json`),P.object({checks:ht.optional()}),{block:`checks`}),ie=a&&re?.checks?.runOnVersionPr!==!0,T=buildWorkflowYaml({ci:e.config.ci,name:`CI`,on:{push:{branches:[t],"tags-ignore":[`**`]},pull_request:null},...r&&(d||f)&&{permissions:{contents:`write`}},enableEmailNotifications:i,...a&&{concurrency:ciConcurrency(e.config.ci,t)},jobName:`check`,runsOn:n,...ie&&{jobIf:`github.head_ref != '${versionPrBranch(t)}'`},...Object.keys(ne).length>0&&{jobEnv:ne},...te&&{jobOutputs:te},steps:ee,...w&&{extraJobs:w}}),E=ciWorkflowPath(e.config.ci,e.config.releaseStrategy),D=e.exists(E),O=D?e.read(E):void 0,k=applyWorkspaceToolingBuild(T,e.packageJson);if(O){if(isToolingIgnored(O))return{filePath:E,action:`skipped`,description:`CI workflow has ignore comment`};if(O.includes(`Managed by @bensandee/tooling --`)&&normalizeWorkflow(O,Qn)===normalizeWorkflow(k,Qn))return{filePath:E,action:`skipped`,description:`CI workflow already up to date`}}let ae=preservePinnedActions(k,O,Qn),A=O?insertCustomBlocks(ae,extractCustomBlocks(O)):ae;return e.write(E,A),{filePath:E,action:D?`updated`:`created`,description:`Generated ${r?`GitHub`:`Forgejo`} Actions CI workflow`}}const Ni=[`composer`];function scriptsInvoke(e,t){let n=new RegExp(String.raw`(?<![\w.-])${t}(?![\w.-])`);return Object.values(e.packageJson?.scripts??{}).some(e=>n.test(e))}function foreignOwnedBinaries(e){return Ni.filter(t=>scriptsInvoke(e,t))}function ignoreBinariesField(e){return e.length>0?`\n ignoreBinaries: ${JSON.stringify(e)},`:``}function ignorableDependencies(e){let t=[];return wantsAgentCli(e)&&t.push(cr),wantsCommitAndTagVersion(e)&&t.push(ur),t}function ignoreDependenciesField(e){return e.length>0?`\n ignoreDependencies: ${JSON.stringify(e)},`:``}function buildKnipConfigSingle(e,t,n){return`import type { KnipConfig } from "knip";
|
|
160
161
|
|
|
161
162
|
export default {
|
|
162
163
|
project: ["${e}"],${ignoreBinariesField(t)}${ignoreDependenciesField(n)}
|
|
@@ -174,24 +175,24 @@ export default {${ignoreBinariesField(t)}${ignoreDependenciesField(n)}
|
|
|
174
175
|
},
|
|
175
176
|
},
|
|
176
177
|
} satisfies KnipConfig;
|
|
177
|
-
`}const
|
|
178
|
-
`}function arrayHasEntry(e,t){return e.includes(`"${t}"`)||e.includes(`'${t}'`)}function missingIgnoreBinariesInTs(e,t){let n=/ignoreBinaries:\s*\[([^\]]*)\]/.exec(e);if(!n)return t;let r=n[1]??``;return t.filter(e=>!arrayHasEntry(r,e))}function missingIgnoreDependenciesInTs(e,t){let n=/ignoreDependencies:\s*\[([^\]]*)\]/.exec(e);if(!n)return t;let r=n[1]??``;return t.filter(e=>!arrayHasEntry(r,e))}function insertIntoTsArray(e,t,n){let r=n.map(e=>`"${e}"`).join(`, `),i=RegExp(`(`+t+`:\\s*\\[)`);if(i.test(e))return{content:e.replace(i,`$1${r}, `),changed:!0};let a=/(export default\s*\{)\n/;return a.test(e)?{content:e.replace(a,`$1\n ${t}: [${r}],\n`),changed:!0}:{content:e,changed:!1}}function ensureIgnoreInTs(e,t,n,r){let i=e,a=!1;if(r&&!i.includes(`.claude/hooks`)){let e=/(ignore:\s*\[)/;if(e.test(i))i=i.replace(e,`$1"${
|
|
179
|
-
`:formattedTemplate(e,s,o(a,r,i));return e.write(s,t),{filePath:s,action:`created`,description:createdDescription(s)}}let c=ensureIgnorePattern(n,s,r,i);return c?(e.write(s,e.format(s,c)),{filePath:s,action:`updated`,description:`Added ".claude/hooks/**", foreign-owned ignoreBinaries, and/or ignored dependencies`}):{filePath:s,action:`skipped`,description:s===t?`Already configured`:`Existing config found at ${s}`}}return e.write(t,formattedTemplate(e,t,o(a,r,i))),{filePath:t,action:`created`,description:createdDescription(t)}}const
|
|
180
|
-
`),{filePath:n,action:`updated`,description:`Added extends: ${
|
|
181
|
-
`),{filePath:t,action:`created`,description:`Generated renovate.json extending shared config`}}const
|
|
178
|
+
`}const Pi=`.claude/hooks/**`,Fi=[`knip.config.ts`,`knip.config.mts`,`knip.json`,`knip.jsonc`,`knip.ts`,`knip.mts`],Ii=/* @__PURE__ */ new Set([`.json`,`.jsonc`]);function isJsonConfig(e){let t=e.lastIndexOf(`.`);return t!==-1&&Ii.has(e.slice(t))}const Li=P.object({project:P.array(P.string()).optional(),workspaces:P.record(P.string(),P.object({project:P.array(P.string()).optional()}).passthrough()).optional()}).passthrough();function declaredProjectPatterns(e,t){return isJsonConfig(t)?jsonProjectPatterns(e):tsProjectPatterns(e)}function jsonProjectPatterns(e){let t;try{t=JSON.parse(e)}catch{return}let n=Li.safeParse(t);if(!n.success)return;let r=[];n.data.project&&r.push(n.data.project);for(let e of Object.values(n.data.workspaces??{}))e.project&&r.push(e.project);if(r.length!==0)return r.flat()}function tsProjectPatterns(e){let t=[...e.matchAll(/\bproject\s*:\s*\[([^\]]*)\]/g)];if(t.length!==0)return t.flatMap(e=>[...(e[1]??``).matchAll(/["'`]([^"'`]+)["'`]/g)].map(e=>e[1]??``))}function hookIsInProjectScope(e,t){let n=declaredProjectPatterns(e,t);return n===void 0||n.some(e=>F(e,{dot:!0})(`.claude/hooks/bst-hook.mjs`))}function ensureIgnorePattern(e,t,n,r){let i=hookIsInProjectScope(e,t);return isJsonConfig(t)?ensureIgnoreInJson(e,n,r,i):ensureIgnoreInTs(e,n,r,i)}const Ri=P.object({ignore:P.array(P.string()).optional(),ignoreBinaries:P.array(P.string()).optional(),ignoreDependencies:P.array(P.string()).optional()}).passthrough();function ensureIgnoreInJson(e,t,n,r){let i;try{i=JSON.parse(e)}catch{return}let a=Ri.safeParse(i);if(!a.success)return;let o=a.data,s=!1;r&&!(o.ignore??[]).includes(Pi)&&(o.ignore=[...o.ignore??[],Pi],s=!0);let c=new Set(o.ignoreBinaries??[]),l=t.filter(e=>!c.has(e));l.length>0&&(o.ignoreBinaries=[...o.ignoreBinaries??[],...l],s=!0);let u=new Set(o.ignoreDependencies??[]),d=n.filter(e=>!u.has(e));if(d.length>0&&(o.ignoreDependencies=[...o.ignoreDependencies??[],...d],s=!0),s)return JSON.stringify(o,null,2)+`
|
|
179
|
+
`}function arrayHasEntry(e,t){return e.includes(`"${t}"`)||e.includes(`'${t}'`)}function missingIgnoreBinariesInTs(e,t){let n=/ignoreBinaries:\s*\[([^\]]*)\]/.exec(e);if(!n)return t;let r=n[1]??``;return t.filter(e=>!arrayHasEntry(r,e))}function missingIgnoreDependenciesInTs(e,t){let n=/ignoreDependencies:\s*\[([^\]]*)\]/.exec(e);if(!n)return t;let r=n[1]??``;return t.filter(e=>!arrayHasEntry(r,e))}function insertIntoTsArray(e,t,n){let r=n.map(e=>`"${e}"`).join(`, `),i=RegExp(`(`+t+`:\\s*\\[)`);if(i.test(e))return{content:e.replace(i,`$1${r}, `),changed:!0};let a=/(export default\s*\{)\n/;return a.test(e)?{content:e.replace(a,`$1\n ${t}: [${r}],\n`),changed:!0}:{content:e,changed:!1}}function ensureIgnoreInTs(e,t,n,r){let i=e,a=!1;if(r&&!i.includes(`.claude/hooks`)){let e=/(ignore:\s*\[)/;if(e.test(i))i=i.replace(e,`$1"${Pi}", `),a=!0;else{let e=/(export default\s*\{)\n/;e.test(i)&&(i=i.replace(e,`$1\n ignore: ["${Pi}"],\n`),a=!0)}}let o=missingIgnoreBinariesInTs(i,t);if(o.length>0){let e=insertIntoTsArray(i,`ignoreBinaries`,o);i=e.content,a||=e.changed}let s=missingIgnoreDependenciesInTs(i,n);if(s.length>0){let e=insertIntoTsArray(i,`ignoreDependencies`,s);i=e.content,a||=e.changed}return a?i:void 0}function createdDescription(e){return`Generated ${e} for dead code analysis`}async function generateKnip(e){let t=`knip.config.ts`;if(e.config.stack===`none`)return{filePath:t,action:`skipped`,description:`No JS/TS source; not managed`};let n=e.config.structure===`monorepo`,r=foreignOwnedBinaries(e),i=ignorableDependencies(e),a=sourceGlob(e.config.stack),o=n?buildKnipConfigMonorepo:buildKnipConfigSingle,s=Fi.find(t=>e.exists(t));if(s){let n=e.read(s);if(n===void 0)return{filePath:s,action:`failed`,description:`Could not read existing knip config`};if(n.trim()===``){let t=isJsonConfig(s)?ensureIgnorePattern(`{}`,s,r,i)??`{}
|
|
180
|
+
`:formattedTemplate(e,s,o(a,r,i));return e.write(s,t),{filePath:s,action:`created`,description:createdDescription(s)}}let c=ensureIgnorePattern(n,s,r,i);return c?(e.write(s,e.format(s,c)),{filePath:s,action:`updated`,description:`Added ".claude/hooks/**", foreign-owned ignoreBinaries, and/or ignored dependencies`}):{filePath:s,action:`skipped`,description:s===t?`Already configured`:`Existing config found at ${s}`}}return e.write(t,formattedTemplate(e,t,o(a,r,i))),{filePath:t,action:`created`,description:createdDescription(t)}}const zi=`local>bensandee/tooling`,Bi=[`renovate.json`,`renovate.json5`,`.renovaterc`,`.renovaterc.json`,`.github/renovate.json`,`.github/renovate.json5`];async function generateRenovate(e){let t=`renovate.json`;if(!e.config.setupRenovate)return{filePath:t,action:`skipped`,description:`Renovate not requested`};let n=Bi.find(t=>e.exists(t));if(n){let t=e.read(n);if(t){let r=parseRenovateJson(t),i=r.extends??[];return i.includes(zi)?{filePath:n,action:`skipped`,description:`Already extends shared config`}:(i.unshift(zi),r.extends=i,e.write(n,JSON.stringify(r,null,2)+`
|
|
181
|
+
`),{filePath:n,action:`updated`,description:`Added extends: ${zi}`})}}let r={$schema:`https://docs.renovatebot.com/renovate-schema.json`,extends:[zi]};return e.write(t,JSON.stringify(r,null,2)+`
|
|
182
|
+
`),{filePath:t,action:`created`,description:`Generated renovate.json extending shared config`}}const W=`pnpm-workspace.yaml`,Vi=1440,Hi=`@bensandee/*`,Ui=`packages:
|
|
182
183
|
- "packages/*"
|
|
183
184
|
|
|
184
185
|
blockExoticSubdeps: true
|
|
185
186
|
|
|
186
|
-
minimumReleaseAge: ${
|
|
187
|
+
minimumReleaseAge: ${Vi}
|
|
187
188
|
minimumReleaseAgeExclude:
|
|
188
189
|
- "@bensandee/*"
|
|
189
|
-
`,
|
|
190
|
+
`,Wi=`blockExoticSubdeps: true
|
|
190
191
|
|
|
191
|
-
minimumReleaseAge: ${
|
|
192
|
+
minimumReleaseAge: ${Vi}
|
|
192
193
|
minimumReleaseAgeExclude:
|
|
193
194
|
- "@bensandee/*"
|
|
194
|
-
`,
|
|
195
|
+
`,Gi=P.object({pnpmWorkspace:P.literal(!1).optional()});function isPnpmWorkspaceDisabled(e){let t=e.read(`.tooling.json`);if(!t)return!1;try{let e=Gi.safeParse(JSON.parse(t));return e.success&&e.data.pnpmWorkspace===!1}catch{return!1}}function applyManagedKeys(e){let t=[];e.get(`blockExoticSubdeps`)!==!0&&(e.set(`blockExoticSubdeps`,!0),t.push(`set blockExoticSubdeps: true`));let n=e.get(`minimumReleaseAge`);(typeof n!=`number`||!Number.isFinite(n)||n<0)&&(e.set(`minimumReleaseAge`,Vi),t.push(`set minimumReleaseAge: ${Vi}`));let r=e.get(`minimumReleaseAgeExclude`);return Te(r)?r.items.some(e=>we(e)&&e.value===Hi)||(r.add(Hi),t.push(`added "${Hi}" to minimumReleaseAgeExclude`)):(e.set(`minimumReleaseAgeExclude`,[Hi]),t.push(`set minimumReleaseAgeExclude: ["${Hi}"]`)),t}async function generatePnpmWorkspace(e){if(isPnpmWorkspaceDisabled(e))return{filePath:W,action:`skipped`,description:`pnpmWorkspace: false in .tooling.json`};let t=e.config.structure===`monorepo`,n=e.read(W);if(n===void 0||n.trim()===``)return e.write(W,t?Ui:Wi),{filePath:W,action:`created`,description:`Generated pnpm-workspace.yaml`};let r=Oe(n);if(r.errors.length>0)return{filePath:W,action:`failed`,description:`Could not parse existing pnpm-workspace.yaml: ${r.errors[0]?.message??`unknown error`}`};let i=applyManagedKeys(r);return i.length===0?{filePath:W,action:`skipped`,description:`Already up to spec`}:(e.write(W,r.toString()),{filePath:W,action:`updated`,description:i.join(`, `)})}const Ki=`.claude/hooks/bst-hook.settings.json`,qi=P.object({allow:P.array(P.unknown()).optional()});function writeIfChanged(e,t,n,r){let i=e.read(t);return i===n?{filePath:t,action:`skipped`,description:`${r} is up to date`}:(e.write(t,n),{filePath:t,action:i?`updated`:`created`,description:i?`Updated ${r}`:`Generated ${r}`})}function checkLegacyAllowKey(e){let t=e.read(Ki);if(t===void 0)return;let n;try{n=JSON.parse(t)}catch{return}let r=qi.safeParse(n);if(r.success&&r.data.allow&&r.data.allow.length!==0)return I.warn(`${Ki}: the "allow" key is no longer read (there is no allow tier any more). It is safe to remove.`),{filePath:Ki,action:`skipped`,description:`Legacy allow key ignored; left in place`}}function writeEmbedded(e,t){return t.content===t.placeholder?{filePath:t.filePath,action:`failed`,description:t.notBuiltDescription}:writeIfChanged(e,t.filePath,t.content,t.label)}const Ji="run `pnpm build` from the repo root";async function generateClaudeHooks(e,t={hook:`/**
|
|
195
196
|
* bst-hook -- Claude Code PreToolUse hook
|
|
196
197
|
* @bensandee/claude-hooks
|
|
197
198
|
* https://github.com/bensandee/tooling
|
|
@@ -2199,7 +2200,10 @@ const GIT_FLAGS_WITH_ARG = /* @__PURE__ */ new Set([
|
|
|
2199
2200
|
"-C",
|
|
2200
2201
|
"-c",
|
|
2201
2202
|
"--git-dir",
|
|
2202
|
-
"--work-tree"
|
|
2203
|
+
"--work-tree",
|
|
2204
|
+
"--namespace",
|
|
2205
|
+
"--config-env",
|
|
2206
|
+
"--attr-source"
|
|
2203
2207
|
]);
|
|
2204
2208
|
function getGitSubcommandIndex(tokens) {
|
|
2205
2209
|
for (let i = 1; i < tokens.length; i++) {
|
|
@@ -2585,31 +2589,17 @@ const GIT_CHECKED_OUT_WRITES = /* @__PURE__ */ new Set([
|
|
|
2585
2589
|
"am",
|
|
2586
2590
|
"pull"
|
|
2587
2591
|
]);
|
|
2588
|
-
function subcommandArgs(tokens, sub
|
|
2592
|
+
function subcommandArgs(tokens, sub) {
|
|
2589
2593
|
const after = tokens.slice(tokens.indexOf(sub) + 1);
|
|
2590
2594
|
const flags = [];
|
|
2591
2595
|
const positionals = [];
|
|
2592
|
-
for (
|
|
2593
|
-
|
|
2594
|
-
if (!t.startsWith("-")) {
|
|
2595
|
-
positionals.push(t);
|
|
2596
|
-
continue;
|
|
2597
|
-
}
|
|
2598
|
-
flags.push(t);
|
|
2599
|
-
if (valueFlags.has(t)) i++;
|
|
2600
|
-
}
|
|
2596
|
+
for (const t of after) if (t.startsWith("-")) flags.push(t);
|
|
2597
|
+
else positionals.push(t);
|
|
2601
2598
|
return {
|
|
2602
2599
|
flags,
|
|
2603
2600
|
positionals
|
|
2604
2601
|
};
|
|
2605
2602
|
}
|
|
2606
|
-
const GIT_PUSH_VALUE_FLAGS = /* @__PURE__ */ new Set([
|
|
2607
|
-
"-o",
|
|
2608
|
-
"--push-option",
|
|
2609
|
-
"--repo",
|
|
2610
|
-
"--receive-pack",
|
|
2611
|
-
"--exec"
|
|
2612
|
-
]);
|
|
2613
2603
|
function isMergeFastForwardFromUpstream(tokens, upstream) {
|
|
2614
2604
|
const { flags, positionals } = subcommandArgs(tokens, "merge");
|
|
2615
2605
|
if (!flags.includes("--ff-only") || positionals.length !== 1) return false;
|
|
@@ -2639,9 +2629,8 @@ function isRefMovingReset(tokens, cwd, head) {
|
|
|
2639
2629
|
if (target === null) return false;
|
|
2640
2630
|
return target !== resolveCommit(cwd, head);
|
|
2641
2631
|
}
|
|
2642
|
-
function pushDestinations(
|
|
2643
|
-
const
|
|
2644
|
-
const refspecs = positionals.slice(1);
|
|
2632
|
+
function pushDestinations(push, current) {
|
|
2633
|
+
const refspecs = push.refspecs;
|
|
2645
2634
|
if (refspecs.length === 0) return null;
|
|
2646
2635
|
const names = [];
|
|
2647
2636
|
for (const spec of refspecs) {
|
|
@@ -2678,9 +2667,11 @@ function movesProtectedRef(tokens, ctx) {
|
|
|
2678
2667
|
const protectedSet = getProtectedBranches(cwd, ctx.repoProtectedBranches ?? []);
|
|
2679
2668
|
const onProtected = current !== null && protectedSet.has(current);
|
|
2680
2669
|
if (sub === "push") {
|
|
2681
|
-
const
|
|
2670
|
+
const push = readGitPush(tokens);
|
|
2671
|
+
if (push === null) return false;
|
|
2672
|
+
const { flags } = push;
|
|
2682
2673
|
if (flags.some((f) => GIT_PUSH_EVERY_BRANCH.has(f))) return true;
|
|
2683
|
-
const destinations = pushDestinations(
|
|
2674
|
+
const destinations = pushDestinations(push, current);
|
|
2684
2675
|
if (destinations === null) {
|
|
2685
2676
|
if (flags.includes("--tags")) return false;
|
|
2686
2677
|
return onProtected;
|
|
@@ -2892,17 +2883,19 @@ const PUSH_LONG_OPTIONS_WITH_VALUE = [
|
|
|
2892
2883
|
"--repo",
|
|
2893
2884
|
"--receive-pack",
|
|
2894
2885
|
"--exec",
|
|
2895
|
-
"--push-option"
|
|
2886
|
+
"--push-option",
|
|
2887
|
+
"--recurse-submodules"
|
|
2896
2888
|
];
|
|
2897
2889
|
function longPushOptionTakesNext(token) {
|
|
2898
2890
|
if (token.includes("=") || token.length <= 2) return false;
|
|
2899
2891
|
return PUSH_LONG_OPTIONS_WITH_VALUE.filter((o) => o.startsWith(token)).length === 1;
|
|
2900
2892
|
}
|
|
2901
|
-
function
|
|
2893
|
+
function readGitPush(tokens) {
|
|
2902
2894
|
const pushIdx = getGitSubcommandIndex(tokens);
|
|
2903
|
-
if (pushIdx === -1 || tokens[pushIdx] !== "push") return
|
|
2895
|
+
if (pushIdx === -1 || tokens[pushIdx] !== "push") return null;
|
|
2904
2896
|
const afterPush = tokens.slice(pushIdx + 1);
|
|
2905
|
-
|
|
2897
|
+
const flags = [];
|
|
2898
|
+
const operands = [];
|
|
2906
2899
|
let afterDashes = false;
|
|
2907
2900
|
for (let i = 0; i < afterPush.length; i++) {
|
|
2908
2901
|
const t = afterPush[i] ?? "";
|
|
@@ -2911,25 +2904,32 @@ function isGitForcePush(tokens) {
|
|
|
2911
2904
|
afterDashes = true;
|
|
2912
2905
|
continue;
|
|
2913
2906
|
}
|
|
2914
|
-
if (t === "--force") return true;
|
|
2915
2907
|
if (t.startsWith("--")) {
|
|
2908
|
+
flags.push(t);
|
|
2916
2909
|
if (longPushOptionTakesNext(t)) i++;
|
|
2917
2910
|
continue;
|
|
2918
2911
|
}
|
|
2919
2912
|
if (t.startsWith("-") && t.length > 1) {
|
|
2920
|
-
|
|
2921
|
-
if (
|
|
2922
|
-
if (takesNext) i++;
|
|
2913
|
+
flags.push(t);
|
|
2914
|
+
if (scanPushCluster(t).takesNext) i++;
|
|
2923
2915
|
continue;
|
|
2924
2916
|
}
|
|
2925
2917
|
}
|
|
2926
|
-
|
|
2927
|
-
repoPending = false;
|
|
2928
|
-
continue;
|
|
2929
|
-
}
|
|
2930
|
-
if (t.startsWith("+")) return true;
|
|
2918
|
+
operands.push(t);
|
|
2931
2919
|
}
|
|
2932
|
-
|
|
2920
|
+
const [repository = null, ...refspecs] = operands;
|
|
2921
|
+
return {
|
|
2922
|
+
repository,
|
|
2923
|
+
refspecs,
|
|
2924
|
+
flags
|
|
2925
|
+
};
|
|
2926
|
+
}
|
|
2927
|
+
function isGitForcePush(tokens) {
|
|
2928
|
+
const push = readGitPush(tokens);
|
|
2929
|
+
if (push === null) return false;
|
|
2930
|
+
if (push.flags.includes("--force")) return true;
|
|
2931
|
+
if (push.flags.some((f) => !f.startsWith("--") && scanPushCluster(f).force)) return true;
|
|
2932
|
+
return push.refspecs.some((r) => r.startsWith("+"));
|
|
2933
2933
|
}
|
|
2934
2934
|
const ENV_READ_FILE_COMMANDS = /* @__PURE__ */ new Set([
|
|
2935
2935
|
"cat",
|
|
@@ -3022,7 +3022,7 @@ const denyRules = [
|
|
|
3022
3022
|
match: /^git$/,
|
|
3023
3023
|
action: "deny",
|
|
3024
3024
|
when: (tokens) => isGitForcePush(tokens),
|
|
3025
|
-
reason: "Use \`git push --force-with-lease\` instead of \`--force
|
|
3025
|
+
reason: "Use \`git push --force-with-lease\` instead of \`--force\`, and drop the leading \`+\` from a refspec."
|
|
3026
3026
|
},
|
|
3027
3027
|
{
|
|
3028
3028
|
name: "git-protected-branch-write",
|
|
@@ -4071,14 +4071,14 @@ audit({
|
|
|
4071
4071
|
if (decision.action === "deny") writeDeny(decision.reason);
|
|
4072
4072
|
else if (decision.advice) writeAdvice(decision.advice);
|
|
4073
4073
|
|
|
4074
|
-
export { };`,guide:"# bst-hook Permission Guide\n\nThis project uses a PreToolUse hook (`bst-hook`) that checks each Bash command\nand file tool call before it runs. The hook only ever blocks a command; it does\nnot approve anything on its own. A command that matches a rule below is denied,\nwith a message that says what to do instead.\n\n## Denied commands\n\nThese are blocked. The hook tells you what to do instead.\n\n### Bash\n\n- **sudo**: Don't use sudo. If you need elevated permissions, ask me to do it manually.\n- **git-force-push**: Use `git push --force-with-lease` instead of `--force
|
|
4074
|
+
export { };`,guide:"# bst-hook Permission Guide\n\nThis project uses a PreToolUse hook (`bst-hook`) that checks each Bash command\nand file tool call before it runs. The hook only ever blocks a command; it does\nnot approve anything on its own. A command that matches a rule below is denied,\nwith a message that says what to do instead.\n\n## Denied commands\n\nThese are blocked. The hook tells you what to do instead.\n\n### Bash\n\n- **sudo**: Don't use sudo. If you need elevated permissions, ask me to do it manually.\n- **git-force-push**: Use `git push --force-with-lease` instead of `--force`, and drop the leading `+` from a refspec.\n- **git-protected-branch-write**: This would move a protected branch (main, master, the remote's default branch, or one listed in .claude/hooks/bst-hook.settings.json#protectedBranches). Work on a feature branch in a worktree: `git worktree add ../<repo>-<topic> -b feat/<topic>`, then commit and push there. To bring `main` up to date, use `git pull --ff-only`.\n- **chmod-777**: Don't use 777 permissions. Use more restrictive permissions.\n- **node-modules-write**: Don't write into node_modules/. Its files are hardlinks into pnpm's global store, so overwriting one in place (plain `cp`, `>` redirect, `sed -i`, ...) writes through the link and corrupts that package for every project on this machine -- silently, since the directory you wrote into ends up fine. To test a local build as an installed dependency, run it directly (`node packages/<pkg>/dist/bin.mjs <cmd>`), or install into a scratch tree with an isolated store (`pnpm add --store-dir <scratch> <pkg>`). If you must replace a file in place, `cp --remove-destination` is safe -- it unlinks the target first. Run `pnpm store status` to check whether the store is already damaged.\n- **env-file-read**: Don't read .env files. These contain secrets that should not appear in the conversation.\n- **env-file-write**: Don't write to .env files. These contain secrets.\n- **health-baseline-reset**: Run `pnpm exec bst health:raise` to raise only what this branch crossed. `--update-baseline --reset` records every outlier, including the ones already on the default branch.\n- **npx-redirect**: This project uses pnpm. Use `pnpm dlx <pkg>` or `pnpm exec <cmd>` instead of npx.\n- **mise-self-update**: Don't self-update mise. The version is Renovate-managed; ask a human to bump the pin.\n\n### File tools (Read, Write, Edit, Glob, Grep)\n\n- **env-file-read**: Don't read .env files. These contain secrets that should not appear in the conversation.\n- **env-file-write**: Don't write to .env files. These contain secrets.\n- **hooks-folder-write**: Don't write to .claude/hooks/. These files are managed by the project and should not be modified directly.\n- **git-dir-write**: Don't write into .git/ directly. Its internals (config, hooks, refs) are not plain project files -- a config edit can redirect remotes or push destinations that other rules trust, and a hooks/ script runs automatically on the next commit/push. Use git subcommands instead, or ask the user.\n- **node-modules-write**: Don't write into node_modules/. Its files are hardlinks into pnpm's global store -- editing one in place corrupts that package for every project on this machine. Edit the source package and rebuild, or install into a scratch tree with an isolated store (`pnpm add --store-dir <scratch> <pkg>`).\n- **claude-settings-write**: Don't write to .claude/settings.json. This file is managed by the project and should not be modified directly.\n\n## How commands are evaluated\n\n- **Pipelines and chains**: every segment is checked; a deny on any segment blocks the whole command.\n- **pnpm scripts**: `pnpm <script>` resolves against `package.json` (including pre/post hooks and `--filter` workspaces) and evaluates the resolved command recursively.\n- **cd propagation**: `cd dir && cmd` evaluates `cmd` relative to the new directory.\n- **Branch switch propagation**: `git switch <branch> && cmd` (or `git checkout <branch>`) evaluates a git write in `cmd` against the branch it switched to, not the one checked out before. This holds only across `&&` and only in the same directory.\n- **Audit log**: all decisions are logged to `.claude/hooks/bst-hook.audit.local.jsonl`.\n\n## Advisories\n\nThese never block a command. The hook adds one note to the session instead.\n\n- **Worktree advisory**: creating a branch with `git checkout -b/-B` or `git switch -c/-C` in the primary worktree; the note suggests an isolated worktree instead.\n- **Claim advisory**: creating a branch or a worktree (`git checkout -b/-B`, `git switch -c/-C`, `git worktree add -b/-B`) in a repository whose `.tooling.json` sets `agent.enabled: true`; the note reminds you to claim the issue with `pnpm exec bst work:start <n>` first.\n\n## Everything else\n\nA command that matches none of the rules above is judged by Claude Code's own\nauto mode, not by this hook.\n"}){let n=[{filePath:`.claude/hooks/bst-hook.mjs`,content:t.hook,placeholder:`/* bst-hook not built -- run pnpm build from packages/claude-hooks first */`,label:`bst-hook.mjs`,notBuiltDescription:`bst-hook not built: ${Ji}`},{filePath:`.claude/hooks/bst-hook-guide.md`,content:t.guide,placeholder:`<!-- bst-hook guide not built -->`,label:`bst-hook-guide.md`,notBuiltDescription:`bst-hook guide not built: ${Ji}`}].map(t=>writeEmbedded(e,t)),r=checkLegacyAllowKey(e);return r&&n.push(r),n}const Yi=P.object({type:P.string().optional(),command:P.string().optional()}).loose(),Xi=P.object({matcher:P.string().optional(),hooks:P.array(Yi).default([])}).loose(),Zi=P.object({permissions:P.object({allow:P.array(P.string()).default([]),deny:P.array(P.string()).default([])}).loose().default({allow:[],deny:[]}),hooks:P.record(P.string(),P.array(Xi)).default({}),instructions:P.array(P.string()).default([]),enabledPlugins:P.record(P.string(),P.boolean()).default({}),extraKnownMarketplaces:P.record(P.string(),P.record(P.string(),P.unknown())).default({})});function parseClaudeSettings(e){try{let t=JSON.parse(e),n=P.record(P.string(),P.unknown()).safeParse(t),r=Zi.safeParse(t);return!n.success||!r.success?void 0:{settings:r.data,rawJson:n.data}}catch{return}}function buildSettings(e){let t=[],n={"code-simplifier@claude-plugins-official":!0};return repoHasWebUI(e)&&(n[`frontend-design@claude-plugins-official`]=!0),{permissions:{allow:t,deny:[]},hooks:{PreToolUse:[{matcher:`Bash|Read|Write|Edit|Glob|Grep`,hooks:[{type:`command`,command:`node "$(git rev-parse --show-toplevel)/.claude/hooks/bst-hook.mjs"`}]}]},instructions:[],enabledPlugins:n,extraKnownMarketplaces:{}}}const Qi=`bst-hook.mjs`;function mergeGeneratedMatcher(e,t,n,r){let i=t.findIndex(e=>e.matcher===r.matcher&&e.hooks.some(e=>e.command?.includes(Qi)===!0));if(i!==-1){let a=t[i],o=r.hooks.find(e=>e.command?.includes(Qi)===!0)?.command,s=a.hooks.find(e=>e.command?.includes(Qi)===!0)?.command;if(o&&s&&o!==s){let t=(e[n]??[])[i];return t.hooks=t.hooks.map(e=>e.command?.includes(Qi)===!0?Object.assign(e,{command:o}):e),1}return 0}return e[n]=[...e[n]??[],r],1}function serializeSettings$1(e){let{enabledPlugins:t,extraKnownMarketplaces:n,hooks:r,instructions:i,...a}=e,o={...a};return Object.keys(r).length>0&&(o.hooks=r),i.length>0&&(o.instructions=i),Object.keys(t).length>0&&(o.enabledPlugins=t),Object.keys(n).length>0&&(o.extraKnownMarketplaces=n),JSON.stringify(o,null,2)+`
|
|
4075
4075
|
`}function writeOrMergeSettings(e,t,n){let r=e.read(t);if(r!==void 0&&r.trim()!==``){let i=parseClaudeSettings(r);if(!i)return{filePath:t,action:`failed`,description:`Could not parse existing settings`};let{settings:a,rawJson:o}=i,s=n.permissions.allow.filter(e=>!a.permissions.allow.includes(e)),c=n.permissions.deny.filter(e=>!a.permissions.deny.includes(e)),l=0,u={...a.hooks};for(let[e,t]of Object.entries(n.hooks)){let n=u[e]??[];for(let r of t)l+=mergeGeneratedMatcher(u,n,e,r)}let d=Object.entries(n.enabledPlugins).filter(([e])=>!(e in a.enabledPlugins)),f=Object.entries(n.extraKnownMarketplaces).filter(([e])=>!(e in a.extraKnownMarketplaces)),p=s.length+c.length+l+d.length+f.length;if(p===0)return{filePath:t,action:`skipped`,description:`Already has all rules and hooks`};o.permissions={...a.permissions,allow:[...a.permissions.allow,...s],deny:[...a.permissions.deny,...c]},Object.keys(u).length>0&&(o.hooks=u),a.instructions.length>0?o.instructions=a.instructions:delete o.instructions;let m={...a.enabledPlugins};for(let[e,t]of d)m[e]=t;let h={...a.extraKnownMarketplaces};for(let[e,t]of f)h[e]=t;return Object.keys(m).length>0?o.enabledPlugins=m:delete o.enabledPlugins,Object.keys(h).length>0?o.extraKnownMarketplaces=h:delete o.extraKnownMarketplaces,e.write(t,JSON.stringify(o,null,2)+`
|
|
4076
4076
|
`),{filePath:t,action:`updated`,description:`Updated ${String(p)} rules/hooks`}}return e.write(t,serializeSettings$1(n)),{filePath:t,action:`created`,description:`Generated ${t}`}}async function generateClaudeSettings(e){let t=[];if(t.push(writeOrMergeSettings(e,`.claude/settings.json`,buildSettings(e))),e.config.structure===`monorepo`)for(let n of getMonorepoPackages(e.targetDir)){let r=w.relative(e.targetDir,n.dir),i=w.join(r,`.claude`);e.exists(i)&&(e.remove(i),t.push({filePath:i,action:`removed`,description:`Removed subpackage ${i} (plugins consolidated at root)`}))}return t}function buildConfig$3(e,t){let n={$schema:`https://unpkg.com/release-it/schema/release-it.json`,git:{commitMessage:"chore: release v${version}",tagName:"v${version}"},npm:{publish:!0}};e===`github`&&(n.github={release:!0});let r={};return t&&(n.npm={publish:!0,allowSameVersion:!0},r[`@release-it/bumper`]={out:`packages/*/package.json`}),Object.keys(r).length>0&&(n.plugins=r),n}async function generateReleaseIt(e){let t=`.release-it.json`;if(e.config.releaseStrategy!==`release-it`)return{filePath:t,action:`skipped`,description:`release-it not requested`};let n=JSON.stringify(buildConfig$3(e.config.ci,e.config.structure===`monorepo`),null,2)+`
|
|
4077
4077
|
`,r=e.read(t);if(r){if(contentEqual(t,r,n))return{filePath:t,action:`skipped`,description:`Already configured`};if(await e.confirmOverwrite(t)===`skip`)return{filePath:t,action:`skipped`,description:`Existing release-it config preserved`}}return e.write(t,n),{filePath:t,action:r?`updated`:`created`,description:`Generated .release-it.json`}}function buildConfig$2(e,t){return{$schema:`https://unpkg.com/@changesets/config@3.1.1/schema.json`,changelog:`@changesets/cli/changelog`,commit:!1,fixed:[],linked:[],access:`public`,baseBranch:e,updateInternalDependencies:`patch`,ignore:[],...t?{privatePackages:{version:!0,tag:!0}}:{}}}async function generateChangesets(e){let t=`.changeset/config.json`;if(e.config.releaseStrategy!==`changesets`)return{filePath:t,action:`skipped`,description:`Changesets not requested`};let n=e.config.structure!==`monorepo`&&e.packageJson?.private===!0,r=JSON.stringify(buildConfig$2(configuredDefaultBranch(e.read(`.tooling.json`)),n),null,2)+`
|
|
4078
|
-
`;return e.read(t)?{filePath:t,action:`skipped`,description:`Existing changesets config preserved`}:(e.write(t,r),{filePath:t,action:`created`,description:`Generated .changeset/config.json`})}const
|
|
4079
|
-
`)}const
|
|
4080
|
-
`),t.push({filePath:`package.json`,action:`updated`,description:i.join(`, `)}))}async function generateLefthook(e){let t=`lefthook.yml`,n=buildConfig$1(e.config),r=[];archiveHuskyHooks(e,r),archiveLintStagedConfigs(e,r),cleanPackageJson(e,r);let i=
|
|
4081
|
-
`}const
|
|
4078
|
+
`;return e.read(t)?{filePath:t,action:`skipped`,description:`Existing changesets config preserved`}:(e.write(t,r),{filePath:t,action:`created`,description:`Generated .changeset/config.json`})}const $i=`pnpm exec oxlint --no-error-on-unmatched-pattern {staged_files}`;function formatCommandFor(e){return e===`prettier`?`pnpm exec prettier --ignore-unknown --no-error-on-unmatched-pattern --write {staged_files}`:`pnpm exec oxfmt --no-error-on-unmatched-pattern {staged_files}`}function wantsLint(e){return e.stack!==`none`}function requiredCommands(e){return{...wantsLint(e)&&{lint:{run:$i}},format:{run:formatCommandFor(e.formatter),stage_fixed:!0}}}function buildConfig$1(e){return[Bn.trimEnd(),``,`pre-commit:`,` commands:`,...wantsLint(e)?[` lint:`,` run: ${$i}`]:[],` format:`,` run: ${formatCommandFor(e.formatter)}`,` stage_fixed: true`,``].join(`
|
|
4079
|
+
`)}const ea=`.tooling-archived`,ta=[`pre-commit`,`commit-msg`,`pre-push`,`post-merge`,`post-checkout`,`prepare-commit-msg`],na=[`lint-staged.config.mjs`,`lint-staged.config.js`,`lint-staged.config.cjs`,`.lintstagedrc`,`.lintstagedrc.json`,`.lintstagedrc.yaml`,`.lintstagedrc.yml`,`.lintstagedrc.mjs`,`.lintstagedrc.cjs`],ra=[`lefthook.yml`,`.lefthook.yml`];function archiveHuskyHooks(e,t){let n=!1;for(let r of ta){let i=`.husky/${r}`;e.read(i)!==void 0&&(e.remove(i),t.push({filePath:i,action:`archived`,description:`Moved to ${ea}/${i}`}),n=!0)}return n}function archiveLintStagedConfigs(e,t){let n=!1;for(let r of na)e.read(r)!==void 0&&(e.remove(r),t.push({filePath:r,action:`archived`,description:`Moved to ${ea}/${r}`}),n=!0);return n}function cleanPackageJson(e,t){let n=e.read(`package.json`);if(!n)return;let r=parsePackageJson(n);if(!r)return;let i=[];r.devDependencies&&(`husky`in r.devDependencies&&(delete r.devDependencies.husky,i.push(`removed devDependency: husky`)),`lint-staged`in r.devDependencies&&(delete r.devDependencies[`lint-staged`],i.push(`removed devDependency: lint-staged`))),r.scripts?.prepare&&/\bhusky\b/.test(r.scripts.prepare)&&(delete r.scripts.prepare,i.push(`removed husky prepare script`)),i.length!==0&&(e.write(`package.json`,JSON.stringify(r,null,2)+`
|
|
4080
|
+
`),t.push({filePath:`package.json`,action:`updated`,description:i.join(`, `)}))}async function generateLefthook(e){let t=`lefthook.yml`,n=buildConfig$1(e.config),r=[];archiveHuskyHooks(e,r),archiveLintStagedConfigs(e,r),cleanPackageJson(e,r);let i=ra.find(t=>e.exists(t));if(i){let t=e.read(i);if(t===void 0)r.push({filePath:i,action:`failed`,description:`Could not read existing lefthook config`});else if(t.trim()===``)e.write(i,n),r.push({filePath:i,action:`created`,description:`Generated lefthook pre-commit config`});else{let n=[],a=t;if(!wantsLint(e.config)){let e=removeLefthookCommand(a,`lint`,$i);e.changed&&(a=e.content,n.push(`removed managed oxlint command (stack has no JS/TS source)`))}let o=mergeLefthookCommands(a,requiredCommands(e.config));o.changed&&(a=o.content,n.push(`Added missing pre-commit commands`)),n.length>0?(e.write(i,a),r.push({filePath:i,action:`updated`,description:n.join(`, `)})):r.push({filePath:i,action:`skipped`,description:`Lefthook config already up to date`})}return r}return e.write(t,n),r.push({filePath:t,action:`created`,description:`Generated lefthook pre-commit config`}),r}const G=`.vscode/forgejo-workflow.schema.json`,K=`.vscode/settings.json`,ia=`.forgejo/workflows/*.{yml,yaml}`,aa=P.looseObject({"yaml.schemas":P.record(P.string(),P.unknown()).default({})});function serializeSettings(e){return JSON.stringify(e,null,2)+`
|
|
4081
|
+
`}const oa=P.record(P.string(),P.unknown());function readSettings(e){let t=e.read(K);if(t===void 0)return{failure:`Could not read existing settings`};if(t.trim()===``)return{settings:{}};let n=aa.safeParse(_e(t));return n.success?{settings:n.data}:{failure:`Could not parse existing settings`}}function mergeYamlSchemas(e){let t=oa.safeParse(e[`yaml.schemas`]),n=t.success?{...t.data}:{};return G in n?{merged:e,changed:!1}:(n[G]=ia,{merged:{...e,"yaml.schemas":n},changed:!0})}function writeSchemaToSettings(e){if(e.exists(K)){let t=readSettings(e);if(`failure`in t)return{filePath:K,action:`failed`,description:t.failure};let{merged:n,changed:r}=mergeYamlSchemas(t.settings);return r?(e.write(K,serializeSettings(n)),{filePath:K,action:`updated`,description:`Added Forgejo workflow schema mapping`}):{filePath:K,action:`skipped`,description:`Already has Forgejo schema mapping`}}return e.write(K,serializeSettings({"yaml.schemas":{[G]:ia}})),{filePath:K,action:`created`,description:`Generated .vscode/settings.json with Forgejo workflow schema`}}async function generateVscodeSettings(e){let t=[];if(e.config.ci!==`forgejo`)return t.push({filePath:K,action:`skipped`,description:`Not a Forgejo project`}),t;let n=`{
|
|
4082
4082
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
|
4083
4083
|
"$comment": "GitHub Actions workflow schema extended with Forgejo-specific properties",
|
|
4084
4084
|
"additionalProperties": false,
|
|
@@ -5885,30 +5885,34 @@ export { };`,guide:"# bst-hook Permission Guide\n\nThis project uses a PreToolU
|
|
|
5885
5885
|
"required": ["on", "jobs"],
|
|
5886
5886
|
"type": "object"
|
|
5887
5887
|
}
|
|
5888
|
-
`,r=e.read(
|
|
5888
|
+
`,r=e.read(G);return r!==void 0&&contentEqual(G,r,n)?t.push({filePath:G,action:`skipped`,description:`Schema already up to date`}):(e.write(G,n),t.push({filePath:G,action:r?`updated`:`created`,description:`Wrote the Forgejo workflow schema`})),t.push(writeSchemaToSettings(e)),t}const q=`.claude/skills/prepare-for-merge/SKILL.md`;function skillContent(){return[`---`,Vn,`name: prepare-for-merge`,`description: "Prepare the current branch's pull request for merge. Use when asked to 'merge from main', 'merge main in', 'merge up', 'catch up with main', 'prepare for merge', 'get this ready to merge', or 'ready this PR'. The default branch may have another name than 'main'."`,`---`,``,`**Do not run this routine in a headless agent run** (a spec, plan, execute, review or fix container). Such a run commits on the branch it was started on, never pushes, never writes a forge label, and merges the default branch in only when its own prompt hands it a merge to finish. Say in your summary that the request arrived, and carry on with your own work.
|
|
5889
|
+
|
|
5890
|
+
Otherwise, read \`.agent/guides/merge-prep.md\` and follow it. That guide holds the steps, the stopping points, and the report; this skill only gets you to it.`,``].join(`
|
|
5891
|
+
`)}function secondLine(e){return e.split(`
|
|
5892
|
+
`)[1]?.trim()??``}function writeSkill(e){let t=e.read(q);if(t!==void 0&&secondLine(t)===`# @bensandee/tooling:ignore`)return{filePath:q,action:`skipped`,description:`Ignored via tooling:ignore`};let n=formattedTemplate(e,q,skillContent());return t===n?{filePath:q,action:`skipped`,description:`Skill already up to date`}:(e.write(q,n),t===void 0?{filePath:q,action:`created`,description:`Generated prepare-for-merge skill`}:{filePath:q,action:`updated`,description:`Updated prepare-for-merge skill`})}function removeSkill(e){let t=e.read(q);return t===void 0||!secondLine(t).includes(`Managed by @bensandee/tooling --`)?[]:(e.remove(q),[{filePath:q,action:`removed`,description:`Removed prepare-for-merge skill no longer shipped`}])}function syncMergePrepSkill(e,t){return t?[writeSkill(e)]:removeSkill(e)}const sa=/^[ \t]*(?:\*\*)?[A-Z][A-Za-z]*(?: [A-Za-z][A-Za-z]*)*(?:\*\*)?:(?:\*\*)?(?:\s|$)/,ca=/^#{1,6}(?:\s|$)/,la=/^(?:[-*+]|\d+[.)])\s/,ua=/^\|/,da=/^(?:`{3,}|~{3,})/,fa=/^(?:-{3,}|\*{3,}|_{3,})\s*$/;function opensNewMarkdownBlock(e){return ca.test(e)||la.test(e)||ua.test(e)||da.test(e)||fa.test(e)}function opensNewBlock(e){return sa.test(e)||opensNewMarkdownBlock(e)}const pa=/^>\s?/;function stripBlockquoteMarker(e){let t=pa.exec(e);return t===null?{stripped:e,quoted:!1}:{stripped:e.slice(t[0].length),quoted:!0}}function continuationLines(e,t,n){let r=[],i=t,a=t;for(;a<e.length&&e[a]===`
|
|
5889
5893
|
`;){let t=a+1,o=e.indexOf(`
|
|
5890
5894
|
`,t),s=o===-1?e.length:o,c=e.slice(t,s);if(c.trim()===``)break;let{stripped:l,quoted:u}=stripBlockquoteMarker(c);if(u!==n||opensNewBlock(l))break;r.push(c),i=s,a=s}return{lines:r,blockEnd:i}}function enclosingBlockEnd(e,t,n){let r=t,i=t;for(;i<e.length&&e[i]===`
|
|
5891
5895
|
`;){let t=i+1,a=e.indexOf(`
|
|
5892
|
-
`,t),o=a===-1?e.length:a,s=e.slice(t,o);if(s.trim()===``)break;if(n){let{quoted:e}=stripBlockquoteMarker(s);if(!e&&opensNewMarkdownBlock(s))break}else if(opensNewMarkdownBlock(s)||
|
|
5893
|
-
`:`\n\n${i}`}`}const
|
|
5894
|
-
`),n=[],r,i=0,a=0;for(let e of t)if(r===void 0){let t=
|
|
5896
|
+
`,t),o=a===-1?e.length:a,s=e.slice(t,o);if(s.trim()===``)break;if(n){let{quoted:e}=stripBlockquoteMarker(s);if(!e&&opensNewMarkdownBlock(s))break}else if(opensNewMarkdownBlock(s)||pa.test(s))break;r=o,i=o}return r}function insertBlockAtBoundary(e,t,n){let r=e.slice(0,t),i=e.slice(t).replace(/^\n+/,``);return`${r}\n\n${n}${i===``?`
|
|
5897
|
+
`:`\n\n${i}`}`}const ma=/\[[^\]]*\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g,ha=/^[a-z][a-z0-9+.-]*:/i,ga=/^ {0,3}((?:>[ \t]?)+ {0,3})?(`{3,}|~{3,})/;function quoteDepthOf(e){if(e===void 0)return 0;let t=e.match(/>/g);return t===null?0:t.length}function fenceCloseRe(e,t,n){let r=n===0?``:`(?:>[ \\t]?){${String(n)},} {0,3}`;return RegExp(`^ {0,3}${r}${e}{${t},}\\s*$`)}function isBlankLine(e){return e.trim()===``}function stripFencedCodeBlocks(e){let t=e.split(`
|
|
5898
|
+
`),n=[],r,i=0,a=0;for(let e of t)if(r===void 0){let t=ga.exec(e);if(t?.[2]!==void 0){r=t[2][0],i=t[2].length,a=quoteDepthOf(t[1]),n.push(` `.repeat(e.length));continue}n.push(e)}else fenceCloseRe(r,i,a).test(e)&&(r=void 0,i=0,a=0),n.push(` `.repeat(e.length));return n.join(`
|
|
5895
5899
|
`)}function stripInlineCodeSpansInParagraph(e){let t=``,n=0;for(;n<e.length;){if(e[n]!=="`"){t+=e[n],n++;continue}let r=n;for(;e[r]==="`";)r++;let i=r-n,a=r,o=-1,s=-1;for(;a<e.length;)if(e[a]==="`"){let t=a;for(;e[a]==="`";)a++;if(a-t===i){o=t,s=a;break}}else a++;o===-1?(t+=e.slice(n,r),n=r):(t+=` `.repeat(s-n),n=s)}return t}function stripInlineCodeSpans(e){let t=e.split(`
|
|
5896
5900
|
`),n=[],r=[],flush=()=>{if(r.length===0)return;let e=stripInlineCodeSpansInParagraph(r.join(`
|
|
5897
5901
|
`));n.push(...e.split(`
|
|
5898
5902
|
`)),r=[]};for(let e of t)isBlankLine(e)?(flush(),n.push(e)):r.push(e);return flush(),n.join(`
|
|
5899
|
-
`)}function stripCode(e){return stripInlineCodeSpans(stripFencedCodeBlocks(e))}function scanLinks(e,t){let n=[],r=stripCode(e),i=new RegExp(
|
|
5903
|
+
`)}function stripCode(e){return stripInlineCodeSpans(stripFencedCodeBlocks(e))}function scanLinks(e,t){let n=[],r=stripCode(e),i=new RegExp(ma.source,`gd`);for(let a of r.matchAll(i)){let r=a[1];if(r===void 0||ha.test(r)||r.startsWith(`#`))continue;let i=r.split(`#`)[0];if(i===void 0||i===``)continue;let o;try{o=decodeURIComponent(i)}catch{o=i}let s=o.startsWith(`/`)?w.posix.normalize(o.slice(1)):w.posix.normalize(w.posix.join(t,o)),c=a.indices?.[1];c!==void 0&&n.push({raw:r,target:s,index:c[0],length:i.length,linkStart:a.index,linkEnd:a.index+a[0].length,text:e.slice(a.index+1,c[0]-2)})}return n}function relativeLinks(e,t){return scanLinks(e,t).map(({raw:e,target:t})=>({raw:e,target:t}))}function relativeLinksWithOffsets(e,t){return scanLinks(e,t)}const _a=`docs`;function resolvesInsideDocs(e){return e===_a||e.startsWith(`${_a}/`)}const va=[`completed`,`shipped`,`superseded`,`abandoned`,`cancelled`,`canceled`,`rejected`],ya=[`draft`,`proposed`,`approved`,`planned`,`open`,`blocked`,`partial`,`partially`,`in progress`,`wip`],ba=[`partial`,`partially`,`in progress`,`wip`];function wordsPattern(e){return`\\b(${e.map(e=>e.replaceAll(` `,`[ -]`)).join(`|`)})\\b`}const xa=new RegExp(wordsPattern(va),`i`),Sa=RegExp(`${wordsPattern(va)}[^\\n]*?\\d{4}-\\d{2}-\\d{2}`,`i`),Ca=new RegExp(wordsPattern(ya),`i`),wa=new RegExp(wordsPattern(ba),`i`),Ta=[`completed`,`superseded`,`abandoned`,`rejected`];function isRetireVerb(e){return Ta.some(t=>t===e)}const Ea={completed:`Shipped`,superseded:`Superseded`,abandoned:`Abandoned`,rejected:`Rejected`},Da=Object.values(Ea).join(`|`),Oa=`\\b(?:${Da})\\b`,ka=`(?:[:\\u2014\\u2013]|--?\\s)`,Aa=RegExp(`^[ \\t]*(?:> ?)?(?:\\*\\*)?${Oa}\\s*${ka}`,`im`),ja=RegExp(`^\\s*(?:> ?)?(\\*\\*)?\\b(${Da})\\b(\\*\\*)?\\s*${ka}(\\*\\*)?\\s*`,`i`);function splitRetireLeadIn(e){let t=ja.exec(e),n=t?.[2];if(t===null||n===void 0)return{verb:void 0,body:e};let r=Ta.find(e=>Ea[e].toLowerCase()===n.toLowerCase()),i=e.slice(t[0].length),a=t[1]!==void 0,o=t[3]!==void 0||t[4]!==void 0;return a&&!o&&i.endsWith(`**`)&&(i=i.slice(0,-2).trimEnd()),{verb:r,body:i}}const Ma=/^(?:(>[ \t]*)|[ \t]*)(?:\*\*)?Status(?:\*\*:|:\*\*|:)[ \t]*(.+)$/im,Na=/^>\s*\*\*Historical\.\*\*/m;function hasHistoricalBanner(e){let t=stripCode(e),n=t.split(`
|
|
5900
5904
|
`).slice(0,bannerScanLines(t)).join(`
|
|
5901
|
-
`);return
|
|
5905
|
+
`);return Na.test(n)}function bannerScanLines(e){let t=matchStatusBlock(e);if(t===void 0)return 30;let n=enclosingBlockEnd(e,t.blockEnd,t.quoted),r=e.slice(0,n).split(`
|
|
5902
5906
|
`).length;return Math.max(30,r+3)}function formatHistoricalBanner(e){return[`> **Historical.** This document describes the tree as of ${e} and is not current`,`> state. Verify any claim against the source before acting on it.`].join(`
|
|
5903
|
-
`)}const
|
|
5907
|
+
`)}const Pa=/\d{4}-\d{2}-\d{2}/;function datedStatusValue(e){let t=e.split(`
|
|
5904
5908
|
`).slice(0,30).join(`
|
|
5905
|
-
`),n=
|
|
5906
|
-
`)+1,s=e.slice(o,a-r.length),c=t[1]!==void 0,{lines:l,blockEnd:u}=continuationLines(e,a,c);return{lineStart:o,lineEnd:a,blockEnd:u,rawValue:r,prefix:s,continuation:l,quoted:c}}const
|
|
5907
|
-
`),
|
|
5908
|
-
`),
|
|
5909
|
-
`);function webUiGuideBody(){let e=`pnpm dlx modern-web-guidance@${{"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.0
|
|
5910
|
-
`)}const
|
|
5911
|
-
`)}const
|
|
5909
|
+
`),n=Ma.exec(t)?.[2]?.trim().replace(Fa,``);if(n!==void 0&&Sa.test(n))return Pa.exec(n)?.[0]}const Fa=/^\*{1,2}\s*/;function formatDatedStatus(e,t){return`**${e} ${t}**`}function matchStatusBlock(e){let t=Ma.exec(e);if(t===null)return;let n=t[0],r=t[2]??``,i=n.slice(0,n.length-r.length),a=t.index+n.length,o=t.index+i.lastIndexOf(`
|
|
5910
|
+
`)+1,s=e.slice(o,a-r.length),c=t[1]!==void 0,{lines:l,blockEnd:u}=continuationLines(e,a,c);return{lineStart:o,lineEnd:a,blockEnd:u,rawValue:r,prefix:s,continuation:l,quoted:c}}const J=`CLAUDE.md`;function codeList(e){return e.map(e=>`\`${e}\``).join(`, `)}const Ia=[`### Agent rules`,``,"- Use pnpm, not npm/yarn/npx. Run binaries with `pnpm exec`.","- `mise install` provides the toolchain (`mise.toml`); a non-interactive session finds it only through mise's shims (`mise activate --shims` in the login profile)."],La=["- Fix lint violations; don't suppress them. For `no-empty-function`, use a `{ /* no-op */ }` body, not a disable comment.","- Write text in any language; letters, accents and other scripts are fine. Keep out what `chars:check` denies: LLM-tell punctuation (curly quotes, ellipsis, en and em dashes, arrows, box-drawing, status glyphs) and invisible or deceptive characters (bidi controls, zero-width and tag characters, odd spaces). Write `...`, `-`/`--`, straight quotes, `->` and `-`/`|`/`+` instead. Where a denied character must survive to output, escape it for its context: `\\uXXXX` in a JS/TS/Kotlin/Java string, char or regex; `&#xXXXX;` in JSX or XML; a spliced `${'\\uXXXX'}` in a Kotlin raw string. `pnpm exec bst chars:check --fix` applies the safe rewrites (`--fix-ambiguous` for em dashes and status glyphs) and flags the rest.",`- Write in plain language, per ISO 24495-1 -- every word you produce, code comments and commit bodies included.`],Ra="- Relative imports carry `.ts` with no build step or `nodenext` resolution; otherwise prefer extensionless.";function importRule(e){return e.structure===`monorepo`?Ra:e.builder===`none`||e.projectType===`node`?"- Relative imports always carry the `.ts` extension.":e.builder===`custom`?Ra:"- Prefer extensionless imports; if an extension is required, use `.ts` over `.js`."}const za="- Find a command with `pnpm exec bst --help`, its flags with `pnpm exec bst <command> --help`, before guessing.";function declaresAny(e,t){return e!==void 0&&[e.dependencies,e.devDependencies,e.peerDependencies].some(e=>e!==void 0&&t.some(t=>t in e))}function declaresForgejoCli(e){return declaresAny(e,[`@bensandee/forgejo-cli`])}function declaresAgentCli(e){return declaresAny(e,[`@bensandee/agent-cli`,`@bensandee/agent`])}function findCommandRule(e){return za+(declaresForgejoCli(e)?" For Forgejo API work, run `pnpm exec bst-fj --help`.":``)+(declaresAgentCli(e)?" For the agent's runs and transcripts, run `pnpm exec bst-agent --help`.":``)}function agentRulesTail(e){return["- The bst-hook blocks a short list of dangerous commands (`.claude/hooks/bst-hook-guide.md` lists them); Claude Code's auto mode judges everything else.","- Machine-reading a bst command? Run `pnpm exec bst <cmd> --json`, never `--json` before `<cmd>`; capture `2>&1` and parse it as one JSON document, failures included as `{ok: false, error}`. `--verbose` breaks this.",e?"- Before starting or resuming work, run `pnpm exec bst work:start <n>`; hand it back with `pnpm exec bst work:end <n>`.":"- Before starting or resuming work, run `pnpm exec bst work:status`.",za,``,`#### Git discipline`,``,`**The branch you are on is the mode switch.** The bst-hook refuses any command that would move a protected branch, so on one you leave changes unstaged; on a feature branch you commit, push, and open the PR yourself. Pick the mode, announce it, and only ask when it's genuinely ambiguous.`,``,`**Small change** -- a fix, a doc edit, a one-file tweak: work on the default branch and leave it unstaged. Don't commit; surface the commit message as text for the user to run.`,``,"**Large effort** -- anything that warranted a written plan or spec (spec, then plan, then code, each approved before the next): start it in a worktree (see the Git guide), commit as you go, finish with `pnpm exec bst pr:create`. Push later commits with `pnpm exec bst pr:update`, which rewrites nothing unless given `--title`/`--body`; `--closes <n>` on either links an issue. The one exception: a headless agent run (a spec, plan, execute, or review container) never starts a worktree -- it works and commits on the branch it was started on."]}const Ba={red:`Red:`,noTest:`No test:`},Va=[`# Tests`,``,`**A test earns its place by failing when behaviour changes.** Prove each new one red by undoing the change it covers: a test that cannot fail reads as coverage, which is worse than none.`,``,`- Write the test before the code it covers, and watch it fail for the reason you expect. A test that passes on its first run is testing something that already works.`,`- Carry the evidence in the commit body: \`${Ba.red} <test name> failed: <reason>\` when the test ran red first, or \`${Ba.noTest} <reason>\` when there was none to write; the reason is one clause (a missing export, a wrong value, a thrown error) so a reviewer can tell a run that followed the cycle from one that did not.`,`- A change with no test to write is allowed, but the \`${Ba.noTest}\` line always states the reason -- a plan's retire-the-plan task and a docs-only change are the named examples. "It is small" is not a reason -- a small change has a small test.`,`- Never assert that a constant equals its own literal (a default, threshold, model name, label). Test the logic that reads it.`,"- Never pin prose with `toContain`/`toBe`. Snapshot it, or assert a property: ordering, absence, output that changes with an input, a character set or length.",`- One case per branch. A new literal down a path already tested, or the same call through a one-line wrapper, is a duplicate.`,`- Never assert what the test set up: a mock's stub, a type the compiler guarantees, a call count no caller relies on.`,"- A test that exists only for a compatibility path carries the same `@compat` marker as the code.",`- Test a branch in the module that owns it. A wrapper gets one test that it is wired to that module, not a re-run of the module's own cases.`,`- A fixture used in three or more cases goes into a builder, in the test file or in a shared test helper, not written out again in each case.`].join(`
|
|
5911
|
+
`),Ha=[`# Plan lifecycle`,``,"A plan's **directory** is the source of truth for whether it shipped -- not its `Status:` line, not its checkboxes. Read the source it names.",``,"`.superpowers/` (no `docs/` prefix) is scratch state, not a plan's home -- a plan doc lives under `docs/plans/` (older ones under `docs/superpowers/plans/`), even one drafted while running a plan through subagents.",``,'Retiring the plan is the last task of the plan, done in the PR that delivers the work: "in the tree" means committed on this branch, not merged to a default branch. Run `pnpm exec bst docs:retire <plan.md> --status <verb> --shipped "<text>"` -- it moves the doc, relinks what the move breaks, de-links paths pointing outside `docs/`, and writes the dated terminal `Status:` line, the historical banner, and the "Shipped:" paragraph. You supply the judgement: the honest verb -- `completed` / `superseded` / `abandoned` / `rejected` -- and a truthful `--shipped`, which is the text after the `Shipped:` lead-in the command writes itself, naming the delivering PR; never fabricate it for uncommitted code or claim a merge that has not happened. A plan that lands one phase of a larger spec retires the plan and leaves the spec open.',``,"`docs:check` enforces the mechanical half (status <-> directory, dated retirements, links, staleness). It cannot tell whether the code shipped -- that's your job.",``,`An active doc's \`Status:\` may say anything that is not a retirement word; \`draft\`, \`approved\`, and \`planned\` are the usual ones before anything ships. \`docs:check\` reads a status as retired when it contains one of ${codeList(va)} and none of ${codeList(ya)}, so a status naming a shipped phase stays active while it also says an open word. A spec whose status says ${codeList(ba)} is read as partly delivered, and \`docs:check\` stops warning that every plan implementing it has retired.`,``,"**A retired doc is a historical record, not documentation you maintain.** Do not read one for staleness or check its claims against the tree -- that misreading has already caused real defects -- and keeping one up to date is not your job. One question decides whether an edit is allowed: would it have been right the day the doc retired? Yes means the doc misrecords its own moment and you may fix it where you already are -- an unchecked box for work that PR delivered, a `Shipped:` naming the wrong PR. No means the tree moved afterwards and the doc is merely old -- a renamed path, a superseded claim -- so leave it. The move, status line, banner, and delinking stay `docs:retire`/`docs:delink`'s; never hand-write those."].join(`
|
|
5912
|
+
`),Ua=[`# Specs and plans`,``,`**Spec, then plan, then code -- each approved before the next starts.** Approving a spec lets you write the plan, not the code. Approving an idea lets you write the spec, nothing more. With no one to approve (a headless run), the stage you were started on is the approval: finish it, and do not start the next.`,``,`## The spec`,``,"Say why and what, not how: the problem, who it is for, the constraints, what done looks like, and the alternatives you rejected, each with its reason -- an established tool you chose not to use among them, by name. Work with several independent parts gets one spec per part. Save it as `docs/specs/<YYYY-MM-DD>-<topic>-design.md`.",``,`## The plan`,``,"Write for an executor who has not seen this repo or the spec. They write idiomatic code once they know the exact interface and the exact test, and make a reasonable choice wherever the plan leaves one open; what they cannot know is what you decided. A plan records those decisions -- it is not a transcript of the code. Save it under `docs/plans/`, named by the rules below.",``,`### Which plan a branch works`,``,`A plan may be written by you, by another session, or by a headless agent, and the run that executes it may be any of these. That run never asks which plan is meant: it finds the plan from the branch alone, so the name and the git history must say it.`,``,"- A plan this branch **added** is found without a marker, counted at its new path when the branch moved it there with `git mv`. A plan the branch did not add is found by a marker in its path -- the marker of either half of the pair the run works, `issue-<n>` or `pr-<n>` -- or, when the branch added no plan at all, by being the one plan it modified that still has a task open. A plan with none of these is invisible to the run that should execute it, however clearly its text names the work.","- Name a new plan `docs/plans/<YYYY-MM-DD>-<topic>.md`, and when the work has an issue or pull request, put its marker in the name: `docs/plans/<YYYY-MM-DD>-issue-<n>-<topic>.md`. The marker is what keeps the plan findable when a second plan joins the branch.",`- To refine a plan this branch already added, edit it in place and keep its name, so the branch never carries two plans for one piece of work.`,"- To work a plan the branch inherited from the default branch -- a deferred plan, or one that landed in an earlier pull request -- rename it with `git mv` to a name that carries the marker, in the first commit that touches it, then work it under that name. Use the marker of the object the run works: when an agent executes the plan on a pull request, that is the pull request's `pr-<n>`.","- After committing the plan, check that it is findable: `pnpm exec bst docs:check` reports R9 for a plan on the branch that the lookup above could not find.",``,`### Writing the plan`,``,`- Check the plan's premises against the tree before building on them. "Today X is broken" is a claim: read the code that handles X, not just the line that throws.`,"- A plan or spec that must mention a character `chars:check` denies names it by its code point (`U+202E`) or by the escape its context uses, and never pastes the glyph: an active doc is inside the gate's scope and holds the branch red until it retires.","- Label each task `Task <n>:` at the start of its heading or checkbox, numbered from 1, so `plan:brief` can find it. To split a task after the plan is written, give the parts one lowercase letter (`Task 18a:`, `Task 18b:`) rather than renumbering, so later tasks and every cross-reference keep their numbers. A checkbox's first sentence is the task's name on the control panel: end it with a period inside one short line, and put the files, commands, and checks in the sentences after it.",`- Give each task what makes it unambiguous and nothing more: a test's name and its assertions with the spec's exact values and why that test fails before the change, a code change's exact signature and file, a command with the output that means it passed. Write out a body only for an algorithm the signature and tests do not determine. Work that uses another task's result names that task's interfaces, never repeats its code. A task with no test to write says \`${Ba.noTest} <reason>\` in the plan, so the executor inherits the call instead of making it cold.`,`- A plan or spec task that verifies its work names the checks that prove it: the test files it writes or changes, plus typecheck and lint for the files it touches. No task says "run the gate" or spells a gate command, because the gate belongs to the run, which takes it once when the work is ready to hand over (see the check-cadence guide), and its command depends on where the run happens. A gate command found in a retired plan or spec is not precedent.`,`- Keep tasks small. Each one runs its own test cycle and ends in a result that can be checked on its own: write the failing test, watch it fail, make it pass, commit. A run cut off partway then loses one task, not the plan. A large plan is fine; a large task is not.`,"- A plan that builds on earlier work opens with a task that checks the prerequisite exists, and records a `**Blocked:**` note if it does not, instead of rebuilding it. When that work has not merged yet, the check accepts what lands, under whatever names it lands with, and does not pin the names of one open proposal. It covers work a later change can supply and a run can retry once it lands; work only a person can do goes in a human phase, the next bullet.","- Split the plan into phases, each a heading above its tasks (a `##` phase heading over `###` task headings), and mark each phase in its heading as autonomous or as needing a person; for a human phase, name what it needs: hardware, data not in the repository, access, a decision. A phase label is a heading, never a checkbox, because a checkbox reads as a task and gets claimed as work. Task numbers run across the whole plan: a phase never restarts them. The bullet above is for work a later change can supply; this one is for work only a person can do.",`- Put autonomous phases first: a human phase goes after every autonomous phase and before the retire task, and no autonomous task depends on a human phase, so the executor commits everything it can do alone before it needs a person. Open each human phase with what the person does, where they commit the result, and how the executor checks that the result is there; the check reads only what is committed, because an executor may not have the device, the data, or the access the person has, and the phase's boxes get ticked once that check passes on the committed result. Data too large to commit gets a committed stand-in the plan names, such as a sample, a summary, or recorded results; when no stand-in can do the job, the phase is hand work from start to finish and the person ticks its boxes.`,`- State a judgement that recurs across many places once, as a rule in the plan, so every task decides it the same way.`,`- Where the property that matters is out of the executor's reach (a container, a live process, a real network), say so and name the test that stands in for watching it.`,"- A plan that holds back regenerating a generated workflow until something is confirmed puts `# @bensandee/tooling:ignore` on the file's first line, with a comment naming the issue that removes it. Without the marker, the next `repo:sync` or the agent's workflow sync regenerates the file after the merge, and nothing on that pull request says why it waited. Removing the marker is that issue's work.","- The last task retires the plan (see the plan-lifecycle guide). Its checkbox text starts with the literal `Retire this plan`, not `Task <n>:`, so tooling can recognize it, and that first sentence ends there: `Retire this plan and its spec.`, then the command. Put that box under its own heading after the last phase rather than straight under the last task's boxes, so it reads as its own unit and not as another step of that task.",`- Reread the finished plan against the spec. A plan several times longer than its spec has written the program instead of the decisions: replace bodies with signatures, test names, and assertions. A line that decides nothing ("TBD", "handle edge cases", a type no task defines) is the opposite failure. Fix both.`,``,`## Working through a plan`,``,`Do the tasks in order, commit after each, and tick a box only once its result is verified. Each task starts red -- write its test, watch it fail, make it pass -- and its commit body carries the testing guide's \`${Ba.red}\` or \`${Ba.noTest}\` line. A box you cannot finish, or cannot finish in full, keeps its text exactly as written and gets one of four notes underneath:`,``,"- `**Progress:**` -- partly done: what landed, what remains, where to pick up. The next pass resumes it.","- `**Blocked:**` -- tried and failing: the error. The next pass retries it.",'- `**Declined:**` -- must not be done, with the reason: a standing rule, a repo convention, or a check that found it moot. No pass touches it again. "Too hard" or "out of budget" is Progress, not Declined.','- `**Deferred:** Task <n> -- <reason>` -- part of the box waits on a later task. Split that box first, so the work that waits is a box of its own, and defer only that one; deferring the whole box drops the part that does not wait. The note says which task and what in it the box waits on, both on that one line. The same plan-only commit adds `- [ ] **Carried from Task <source>:** <the work>` to that task, which is the work going on there; the target cannot be the retire task. The deferral then resolves the box: it says "later", not "never". With no carried box in the target, nothing is deferred and the box stays outstanding, counted against every later pass.',``,`To run a plan through subagents, see the subagents guide.`].join(`
|
|
5913
|
+
`);function webUiGuideBody(){let e=`pnpm dlx modern-web-guidance@${{"@changesets/cli":`3.0.3`,"@release-it/bumper":`8.0.1`,"@types/node":`24.19.2`,"@vitest/coverage-v8":`5.1.0`,"commit-and-tag-version":`13.3.0`,knip:`6.44.1`,lefthook:`2.2.2`,"modern-web-guidance":`0.0.197`,oxfmt:`0.76.0`,oxlint:`1.91.0`,"oxlint-tsgolint":`7.0.2006`,prettier:`3.9.10`,"release-it":`21.1.2`,tsdown:`0.23.7`,typescript:`6.0.3`,vitest:`5.1.0`,pnpm:`11.28.11`}[`modern-web-guidance`]}`;return[`# Web UI`,``,`**Look up how the platform does it before you write UI code.** [Modern Web Guidance](https://github.com/GoogleChrome/modern-web-guidance) is a set of guides to current browser features, each with the pattern to use and a fallback for older browsers.`,``,`1. Search for what you are about to build, phrased as a goal: \`${e} search "<goal>"\`. It prints a JSON list of matching guides with their ids. If nothing matches well, \`${e} list\` prints every guide.`,`2. Retrieve the guides that match: \`${e} retrieve "<id>[,<id>]"\`. The output can be long; if the terminal cuts it off, write it to a file and read that.`,`3. Build, then check the change against the retrieved guide before you call it done: its pattern is used, and each fallback is either applied or dropped under the browser-support policy below.`,``,"- A browser-support policy in the repo's `CLAUDE.md` decides which fallbacks you need. Without one, a Baseline Widely Available feature needs no fallback, and a newer feature follows the guide's fallback.",`- Prefer the platform feature a guide recommends over adding a library.`,`- If the command cannot reach the registry, say so and carry on without it. Do not wait for it.`].join(`
|
|
5914
|
+
`)}function mergePrepEnabled(e){return parseToolingConfigSlice(e.read(`.tooling.json`),P.object({mergePrep:P.literal(!1).optional()}),{block:`mergePrep`})?.mergePrep!==!1}const Wa=[`# Check cadence`,``,`Match the check to the blast radius of what you just did -- the full pipeline is not a per-edit gate.`,``,"- **After an edit** -- the one test file that covers it: `pnpm exec vitest run <path>`."],Ga=[`- **Once, when the work is ready to hand over** (a pull request, or the end of a plan phase) --`," the gate; a headless agent run takes the command its run prompt names, otherwise `pnpm check`."," Where `docker info` fails, run `pnpm check --skip 'docker:*'` and report that the `docker:*`",` steps did not run.`,``,"- **Reading the gate's output** -- keep the whole run in a file, never `tail` or `grep` it, and",' never rerun it for output you did not keep: `pnpm check > /tmp/gate.log 2>&1; echo "exit=$?"`.'," After a red, rerun only the failed steps (`pnpm check --only <step>` where the `check` script's"," last command runs `checks:run`, else that step's own script) and the failing test files,",` then take one more full gate.`,``,"- **When `format --check` still fails after `pnpm format`** -- run `pnpm format` again until it changes nothing. A code span broken across a line inside a list item can take up to four passes to settle.",``,"- **When a fenced block must keep its bytes** (a markdown or JSON example, a repro) -- tag it `text`: the formatter also formats code inside fences.",``,`Batch the fixes, not the runs: re-running a checker after every single fix turns one report into eight.`];function checkCadenceBody(e){let t=[...Wa];return t.push(e.stack===`typescript`?"- **Before a commit** -- `pnpm typecheck`, then `pnpm exec oxlint <the files you touched>`. Repo-wide `pnpm lint` reports files you never opened; lefthook already formats the staged ones.":"- **Before a commit** -- `pnpm exec oxlint <the files you touched>`. Repo-wide `pnpm lint` reports files you never opened; lefthook already formats the staged ones."),t.push(...Ga),t.join(`
|
|
5915
|
+
`)}const Ka=[`# Codebase health`,``,"`health:check` gates four structural metrics against `health-baseline.json`: any increase fails, as does a module or directory past its recorded ceiling. `pnpm exec bst health:summary --explain` names the offenders.",``],qa=[``,`So never duplicate a type, or fork a helper, to protect a fan budget -- import it. Nor move a module out of its home directory to dodge crowding. The converse holds: turning a type-only import into a value import adds an edge, so a module that already imports another for its types gains a real edge the first time it imports a value from it.`,``,"**An exemption takes a module or directory out of the gate.** It is listed with its count and reason in `health:summary --explain`, carries no ceiling, and is counted in no metric. `crowdedDirectories` is exemptable by directory path. A key may be a glob. Adding one is a raise too.",``,'**A raise travels with the code that caused it.** A raise is a higher count or ceiling, a ceiling for a module that has none, a new exemption, or a higher limit. Write it with `pnpm exec bst health:raise` in the pull request whose code crossed the budget; say in the commit why, and a person merges it. Its `--exempt <leaf> --reason "<text>"` is for a hub by construction. Never raise a limit to pass. `--update-baseline --reset` rebuilds a baseline, never one branch. A lowering travels the same way: `pnpm exec bst health:tighten` writes it, from the measurement.',``,"Prefer an exemption to raising `fanInLimit` or `fanOutLimit`: an exemption names the hub in `health:summary --explain`, while a higher limit silently un-tracks every module beneath it. A per-module ceiling has no such shadow -- it ratchets one module at one count and fails again one edge later.",``,`**Never contort code to meet a budget.** Write the correct solution, then adjust the budget to match: a health ceiling as the raise rule above says, and a bundle or other size budget by a full 1%, rounded up, never to the byte.`];function healthRuleBody(e){let t=[...Ka];return t.push(e.structure===`monorepo`?"**The fan-in, fan-out, and cycle metrics count value edges only.** A type-only import is erased before the graph is built and never moves a metric. An import across a workspace package boundary counts at the `health.crossPackage` default and is invisible when it is off.":`**The fan-in, fan-out, and cycle metrics count value edges, and nothing else.** A type-only import is erased before the graph is built, and an import of an installed package resolves outside it -- neither moves any metric.`),t.push(...qa),t.join(`
|
|
5912
5916
|
`)}function buildBlockText(e){return`${e.startMarker}\n\n${e.body}\n\n${e.endMarker}\n`}function findBlock(e,t){let n=e.split(`
|
|
5913
5917
|
`),r=-1;for(let e=0;e<n.length;e++)if(n[e]?.trim()===t.startMarker){r=e;break}if(r!==-1){for(let e=r+1;e<n.length;e++)if(n[e]?.trim()===t.endMarker)return{startLine:r,endLine:e}}}function upsertBlock(e,t){let n=buildBlockText(t),r=findBlock(e,t);if(!r)return`${e.replace(/\n+$/,``)}\n\n${n}`;let i=e.split(`
|
|
5914
5918
|
`),a=i.slice(0,r.startLine),o=i.slice(r.endLine+1),s=a.join(`
|
|
@@ -5917,7 +5921,7 @@ export { };`,guide:"# bst-hook Permission Guide\n\nThis project uses a PreToolU
|
|
|
5917
5921
|
`;return`${s}\n\n${n.replace(/\n+$/,``)}${l}`}function removeBlock(e,t){let n=findBlock(e,t);if(!n)return e;let r=e.split(`
|
|
5918
5922
|
`),i=r.slice(0,n.startLine),a=r.slice(n.endLine+1),o=i.join(`
|
|
5919
5923
|
`).replace(/\n+$/,``),s=a.join(`
|
|
5920
|
-
`).replace(/^\n+/,``);return s.length===0?`${o}\n`:`${o}\n\n${s}`}function applyBlock(e,t){return t.enabled?upsertBlock(e,t):removeBlock(e,t)}const Ya=`.agent/guides`;function agentGuides(e,t,n,r){return[{name:`testing.md`,trigger:`change source, or write or change a test`,body:Ha,enabled:!0},{name:`comments.md`,trigger:`add or change a code comment`,body:"# Comments\n\n**Match the surrounding idiom and naming -- but not its comment density.** These rules govern the comment you are writing, and are no licence to sweep a file you are passing through.\n\n- Default to none. A comment earns its place by carrying what the code cannot -- a rejected alternative, the bug that forced this shape, an invariant enforced elsewhere -- and earns it one decision at a time, in a sentence or two each: what was rejected, and what it cost. Five decisions is five sentences, not five paragraphs. Recoverable from the code? Leave it unwritten.\n- Present tense, about what is. No `now`, `previously`, `changed to`: diff narration is stale on the next edit, and the commit message carries it. No running ledgers or changelogs: when adjusting a threshold, constant, or baseline, state the active invariant and prune past deltas.\n- Never cite a lifecycle-managed doc, PR, or issue from code: no PR or issue numbers (`PR #123`, `closes #456`), no path under `docs/specs/`, `docs/plans/`, `docs/superpowers/` or `docs/design/`, none carrying a `retired/` or `completed/` segment, no `docs/plan-*.md`, and no bare decision or task ID (`D3`, `T2`). They move, retire, and renumber, nothing checks the reference, and the reader has no way to tell a dead one from a live one. State the constraint itself, or cite a maintained reference doc instead. A `docs/` path that is a glob or an elided example rather than a reference (`docs/*.md`) is vocabulary, not a citation, and is fine.\n- Code that exists only to accept an older shape -- a file, field, flag, environment variable, label or comment format -- carries `// @compat <id> until <expiry>: <reason>` on the line above it. The expiry is a date (`YYYY-MM-DD`) when the old shape lives with consumers who upgrade on their own schedule; a version of the code's own package (`v1.4.0`) when its consumer upgrades with each release; or `forge-clean` for old data on the forge, which has neither. Remove the code and every test that carries the same id together.\n- **The code is the fact.** When a comment disagrees with it, fix it in one line or delete it -- never grow one to argue the code is right.",enabled:!0},{name:`git.md`,trigger:`create a branch, worktree, commit, merge, or pull request`,body:"# Git\n\n**Feature work -> a worktree, by default.** The primary checkout is shared mutable state: another session -- a second agent window, the user's own shell -- can switch branches between any two of your commands, and a commit lands on whatever branch HEAD names then. `git worktree add ../<repo>-<topic> -b feat/<topic>` -- a **sibling outside** the repo, never nested; install its dependencies first; `git worktree remove` it once its PR merges. A sibling directory is invisible in the editor's file tree and isn't writable from this session -- announce the worktree's path and open a session there (`code ../<repo>-<topic>`); without one, stay on a feature branch in the primary checkout and verify `git branch --show-current` before every commit and push. A headless agent run (a container driving the spec, plan, execute, or review phase) never takes this path: it commits only on the branch it was started on, because that is the one branch the host reads back once the container exits.\n\n## Claiming work by hand\n\nIf the bst agent drives this repo, claim an issue or pull request before you work it by hand, so the agent does not start a run beside you: run `pnpm exec bst work:start <n>`. It prints the same orientation `work:status` does and then puts `agent-flags/human-driven` on the object. It claims only where the repo's default branch sets `agent.enabled: true`, and does nothing anywhere else. **Exit 1 means do not start**: a run is live on the pair, or one is queued on it -- the output names which. An object the agent parked at a terminal such as `agent/implement-blocked` is claimed, since nothing runs there until a person acts. Exit 0 means the pair is yours, whether the command wrote the flag or found it there already.\n\nThe flag records who is working an object now, not who wrote it. Do not claim an issue or pull request you only file or open for later, even one a person or a coding session wrote by hand: leave it unclaimed so the agent can take it if asked. Claim it when you are about to work it.\n\nClaim **before** you create the branch or worktree, not when you open the pull request. Local notes, a branch name and a worktree are all invisible to the agent; only the flag on the forge holds the issue, and a run claims what it sees. When you split work into several issues, claim each one you work, not the parent. `pnpm exec bst pr:create` reports an issue the new pull request closes that no one has claimed, or that the agent holds; that report is a backstop, not the claim, and it arrives after the branch exists.\n\nA pull request you open yourself that closes no claimed issue needs its own `pnpm exec bst work:start <n>` once it exists -- the flag on either half of a pair holds both, but there is no pair until something closes something.\n\nHand the work back with the control panel's **Release to the agent**, or by removing `agent-flags/human-driven` from both halves. Removing it does not queue anything: the agent picks the object up on its next cycle only if a label or a comment asks it to.\n\n## Issue linking\n\n**A closing keyword in the PR body is the only link.** A branch name like `fix/273-...` links nothing. Link an issue with `pnpm exec bst pr:create --closes 273` or `pr:update --closes 273`; each adds the line only when the body does not already close the issue. Add it from the first push, on a spec or plan pull request too, because the agent uses the keyword to find an issue's open pull request. Without the CLI, put `Closes #273` (or `Fixes` / `Resolves`) on its own line in the body.\n\nIt fails silently: an issue still open after its PR merged means the merger lacked permission to close it. The merge succeeds either way, so nothing reports it.\n\n## Commit subjects\n\nFollow Conventional Commits: `<type>(<scope>): <summary>`. The type is one of `feat`, `fix`, `docs`, `refactor`, `test`, `chore`, `perf`, `build`, `ci`; the scope is optional and names the package or area touched; the summary is an imperative, plain-language sentence. This binds a commit message you suggest to the user too. Nothing checks it, so do not copy the style of recent `git log` if it has drifted.\n\n## Pull request titles\n\nStart a pull request's title with the stage it carries: `Spec:` for a spec, `Plan:` for a plan, and no stem once it carries the implementation. A draft keeps its `WIP:` marker in front (`WIP: Plan: Add retry to uploads`). When a pull request moves on to the next stage, move the stem with it. This is informational -- nothing checks it and nothing fails without it -- but it tells a reviewer at a glance what they are reading.\n\n**Drop `WIP:` and fix the stem when the work is done.** Once the pull request carries finished work you are handing over for review -- a spec or a plan ready to approve, or an implementation whose check passes -- remove the `WIP:` marker and make the stem match what it now carries: no stem for an implementation. Do it in the same step that reports the work done, without being asked. A marker left behind tells a reviewer the work is still moving.\n\n`pr:update` never changes a pull request's draft state or its base. `pnpm exec bst pr:ready [<n>]` marks a draft ready and drops its `WIP:` marker on either forge; `--title \"<title>\"` fixes the stem in the same step. `pnpm exec bst pr:retarget [<n>] --base <branch>` repoints a pull request, such as a stacked one whose parent has merged. In both, `<n>` defaults to the current branch's pull request, and is required when you name another repository with `--repo`. Both confirm the change by re-reading the forge.\n\n## Merging the default branch in\n\n**A merge with no conflicts is not yet a merge that works.** Read the incoming diff for what your branch builds on -- a field made required, a shared schema, a size budget -- and run the full check before you push the merge. Fix what it finds in the merge commit itself, so that commit passes on its own.\n\n**Never trust git's merge of a baseline file** (`health-baseline.json`, `coverage-baseline.json`): a merge that reports no conflict can still drop the default branch's own entries. Take the default branch's copy, then re-measure: `pnpm exec bst health:raise` for `health-baseline.json`, the coverage command for the other. Adopt only what your branch changed.",enabled:!0},{name:`planning.md`,trigger:`write a spec or plan, or work through a plan's tasks`,body:Wa,enabled:!0},{name:`subagents.md`,trigger:`hand work to a subagent, or run a plan through subagents`,body:`# Subagents
|
|
5924
|
+
`).replace(/^\n+/,``);return s.length===0?`${o}\n`:`${o}\n\n${s}`}function applyBlock(e,t){return t.enabled?upsertBlock(e,t):removeBlock(e,t)}const Ja=`.agent/guides`;function agentGuides(e,t,n,r,i){return[{name:`testing.md`,trigger:`change source, or write or change a test`,body:Va,enabled:!0},{name:`comments.md`,trigger:`add or change a code comment`,body:"# Comments\n\n**Match the surrounding idiom and naming -- but not its comment density.** These rules govern the comment you are writing, and are no licence to sweep a file you are passing through.\n\n- Default to none. A comment earns its place by carrying what the code cannot -- a rejected alternative, the bug that forced this shape, an invariant enforced elsewhere -- and earns it one decision at a time, in a sentence or two each: what was rejected, and what it cost. Five decisions is five sentences, not five paragraphs. Recoverable from the code? Leave it unwritten.\n- Present tense, about what is. No `now`, `previously`, `changed to`: diff narration is stale on the next edit, and the commit message carries it. No running ledgers or changelogs: when adjusting a threshold, constant, or baseline, state the active invariant and prune past deltas.\n- Never cite a lifecycle-managed doc, PR, or issue from code: no PR or issue numbers (`PR #123`, `closes #456`), no path under `docs/specs/`, `docs/plans/`, `docs/superpowers/` or `docs/design/`, none carrying a `retired/` or `completed/` segment, no `docs/plan-*.md`, and no bare decision or task ID (`D3`, `T2`). They move, retire, and renumber, nothing checks the reference, and the reader has no way to tell a dead one from a live one. State the constraint itself, or cite a maintained reference doc instead. A `docs/` path that is a glob or an elided example rather than a reference (`docs/*.md`) is vocabulary, not a citation, and is fine.\n- Code that exists only to accept an older shape -- a file, field, flag, environment variable, label or comment format -- carries `// @compat <id> until <expiry>: <reason>` on the line above it. The expiry is a date (`YYYY-MM-DD`) when the old shape lives with consumers who upgrade on their own schedule; a version of the code's own package (`v1.4.0`) when its consumer upgrades with each release; or `forge-clean` for old data on the forge, which has neither. Remove the code and every test that carries the same id together.\n- **The code is the fact.** When a comment disagrees with it, fix it in one line or delete it -- never grow one to argue the code is right.",enabled:!0},{name:`git.md`,trigger:`create a branch, worktree, commit, merge, or pull request`,body:"# Git\n\n**Feature work -> a worktree, by default.** The primary checkout is shared mutable state: another session -- a second agent window, the user's own shell -- can switch branches between any two of your commands, and a commit lands on whatever branch HEAD names then. `git worktree add ../<repo>-<topic> -b feat/<topic>` -- a **sibling outside** the repo, never nested; install its dependencies first; `git worktree remove` it once its PR merges. A sibling directory is invisible in the editor's file tree and isn't writable from this session -- announce the worktree's path and open a session there (`code ../<repo>-<topic>`); without one, stay on a feature branch in the primary checkout and verify `git branch --show-current` before every commit and push. A headless agent run (a container driving the spec, plan, execute, or review phase) never takes this path: it commits only on the branch it was started on, because that is the one branch the host reads back once the container exits.\n\n## Claiming work by hand\n\nIf the bst agent drives this repo, claim an issue or pull request before you work it by hand, so the agent does not start a run beside you: run `pnpm exec bst work:start <n>`. It prints the same orientation `work:status` does and then puts `agent-flags/human-driven` on the object. It claims only where the repo's default branch sets `agent.enabled: true`, and does nothing anywhere else. **Exit 1 means do not start**: a run is live on the pair, or one is queued on it -- the output names which. An object the agent parked at a terminal such as `agent/implement-blocked` is claimed, since nothing runs there until a person acts. Exit 0 means the pair is yours, whether the command wrote the flag or found it there already.\n\nThe flag records who is working an object now, not who wrote it. Do not claim an issue or pull request you only file or open for later, even one a person or a coding session wrote by hand: leave it unclaimed so the agent can take it if asked. Claim it when you are about to work it.\n\nClaim **before** you create the branch or worktree, not when you open the pull request. Local notes, a branch name and a worktree are all invisible to the agent; only the flag on the forge holds the issue, and a run claims what it sees. When you split work into several issues, claim each one you work, not the parent. `pnpm exec bst pr:create` reports an issue the new pull request closes that no one has claimed, or that the agent holds; that report is a backstop, not the claim, and it arrives after the branch exists.\n\nA pull request you open yourself that closes no claimed issue needs its own `pnpm exec bst work:start <n>` once it exists -- the flag on either half of a pair holds both, but there is no pair until something closes something.\n\nHand the work back with `pnpm exec bst work:end <n>`. It removes `agent-flags/human-driven` from every object that holds the unit, and queues nothing: the agent picks the object up on its next cycle only if a label or a comment asks it to. Add `--resume` to queue the agent's next step as well. Where that step is a panel click -- Merge, Fix selected, approving a CI-definition change or an egress list -- it refuses and writes nothing, so take that step on the panel yourself. Pass the answer to a blocked question with `--comment <text>`, which posts before any label changes. The control panel's **Release to the agent** does the same from a browser.\n\n## Issue linking\n\n**A closing keyword in the PR body is the only link.** A branch name like `fix/273-...` links nothing. Link an issue with `pnpm exec bst pr:create --closes 273` or `pr:update --closes 273`; each adds the line only when the body does not already close the issue. Add it from the first push, on a spec or plan pull request too, because the agent uses the keyword to find an issue's open pull request. Without the CLI, put `Closes #273` (or `Fixes` / `Resolves`) on its own line in the body.\n\nIt fails silently: an issue still open after its PR merged means the merger lacked permission to close it. The merge succeeds either way, so nothing reports it.\n\n## Commit subjects\n\nFollow Conventional Commits: `<type>(<scope>): <summary>`. The type is one of `feat`, `fix`, `docs`, `refactor`, `test`, `chore`, `perf`, `build`, `ci`; the scope is optional and names the package or area touched; the summary is an imperative, plain-language sentence. This binds a commit message you suggest to the user too. Nothing checks it, so do not copy the style of recent `git log` if it has drifted.\n\n## Pull request titles\n\nStart a pull request's title with the stage it carries: `Spec:` for a spec, `Plan:` for a plan, and no stem once it carries the implementation. A draft keeps its `WIP:` marker in front (`WIP: Plan: Add retry to uploads`). When a pull request moves on to the next stage, move the stem with it. This is informational -- nothing checks it and nothing fails without it -- but it tells a reviewer at a glance what they are reading.\n\n**Drop `WIP:` and fix the stem when the work is done.** Once the pull request carries finished work you are handing over for review -- a spec or a plan ready to approve, or an implementation whose check passes -- remove the `WIP:` marker and make the stem match what it now carries: no stem for an implementation. Do it in the same step that reports the work done, without being asked. A marker left behind tells a reviewer the work is still moving.\n\n`pr:update` never changes a pull request's draft state or its base. `pnpm exec bst pr:ready [<n>]` marks a draft ready and drops its `WIP:` marker on either forge; `--title \"<title>\"` fixes the stem in the same step. `pnpm exec bst pr:retarget [<n>] --base <branch>` repoints a pull request, such as a stacked one whose parent has merged. In both, `<n>` defaults to the current branch's pull request, and is required when you name another repository with `--repo`. Both confirm the change by re-reading the forge.\n\n## Merging the default branch in\n\n**A merge with no conflicts is not yet a merge that works.** Read the incoming diff for what your branch builds on -- a field made required, a shared schema, a size budget -- and run the full check before you push the merge. Fix what it finds in the merge commit itself, so that commit passes on its own.\n\n**Never trust git's merge of a baseline file** (`health-baseline.json`, `coverage-baseline.json`): a merge that reports no conflict can still drop the default branch's own entries. Take the default branch's copy, then re-measure: `pnpm exec bst health:raise` for `health-baseline.json`, the coverage command for the other. Adopt only what your branch changed.",enabled:!0},{name:`merge-prep.md`,trigger:`prepare a pull request for merge, or merge the default branch into one`,body:"# Preparing a pull request for merge\n\n**A headless agent run (a spec, plan, execute, review or fix container) does not run this routine.** Such a run commits only on the branch it was started on, never pushes, never writes a forge label, and merges the default branch in only when its own prompt hands it a merge to finish. Note the request in your summary and carry on with your own work.\n\nOtherwise the routine runs straight through, without stopping to ask. It stops only at a real merge conflict, a failed gate, a refused claim, a claim whose label read broke, or the default branch. It never force-pushes, rewrites pushed history, resets, deletes a branch, or merges the pull request -- landing a pull request stays a person's click, or the agent's automerge where the repo arms it.\n\n1. **Refuse on the default branch.** This works a feature branch's pull request. On the default branch, or with no pull request for the branch, stop and say so.\n2. **Claim the pull request.** Run `pnpm exec bst work:start <n>` for the pull request, and for the issue it closes when there is one. A `claimed`, `already-claimed` or `not-agent-repo` outcome means carry on. `refused` -- the agent holds the pair, or a run is live on it -- means stop and report: the routine must not take work out from under a run. A `failed` whose reason is a broken label read means stop and report too: nothing was claimed, so a run may be live unseen. A `failed` for any other reason -- a GitHub checkout, a forge with no claim label provisioned, a write that would not go through -- is not about who holds the work, so report it in the summary and carry on. Where a stop names something to fix, run the routine again once it is fixed.\n3. **Merge the default branch in.** Fetch, then merge `origin/<default>` into the branch with a merge commit -- never a rebase. Follow the git guide's \"Merging the default branch in\" section for the baseline rule, and add two things it cannot know this routine wants: rebuild before you re-measure, so the measurement is of the merged tree, and say in the merge commit why each raise is there. Any conflict outside a baseline file: stop, report the files, and leave the merge in progress for the person.\n4. **Retire finished docs.** Read `pnpm exec bst work:status` for the branch's plans. A plan whose only open box is its retire task gets that task done -- `pnpm exec bst docs:retire` per the plan-lifecycle guide, with a truthful `--shipped` naming this pull request -- and its spec too when the plan delivered all of it. A plan with other open boxes is not retired; name it in the summary.\n5. **Run the gate.** Run the repo's `check` script (the check-cadence guide names it, where the repo has that guide). A repo with no check script skips this step and the summary says so. A failure ends the routine here, before step 6, with the failing steps reported -- the pull request is never marked ready on a head that did not pass. This is where the routine leaves the git guide's rule: that guide has you fix what a merge breaks, in the merge commit, and step 3 above still does that; a gate failure here is a separate job the person asks for, not something this routine fixes on its way past.\n6. **Mark it ready and publish.** Only after the gate passed. Push with `pnpm exec bst pr:update`, adding `--body` only when the work the body describes changed. Then drop `WIP:` and set the stem to what the pull request now carries, per the git guide's \"Pull request titles\" section: `pnpm exec bst pr:ready --title \"<title>\"` on a draft, `pnpm exec bst pr:update --title \"<title>\"` otherwise.\n7. **Report.** One short summary: what was merged in, any raise and why, docs retired, the title and draft changes, the gate result, and anything skipped or refused.",enabled:i},{name:`planning.md`,trigger:`write a spec or plan, or work through a plan's tasks`,body:Ua,enabled:!0},{name:`subagents.md`,trigger:`hand work to a subagent, or run a plan through subagents`,body:`# Subagents
|
|
5921
5925
|
|
|
5922
5926
|
**A subagent knows only what you hand it.** Write the brief as its whole world: never your session's history, and never "see above".
|
|
5923
5927
|
|
|
@@ -5942,7 +5946,7 @@ Run subagents at the same time only for problems that share no files and no stat
|
|
|
5942
5946
|
- Findings go back to the same implementer, followed by a review of the fix diff only. Cap it at five rounds, switching to a stronger model from round four. At the cap, rule on each open finding and record why. Never fix in your own session: that skips review. A minor finding nobody fixes in this run goes to the findings ledger, not a scratch note.
|
|
5943
5947
|
- Do not stop between tasks to ask. Stop only for something irreversible or destructive, a security-sensitive action, a side effect outside the working tree (a push, a merge, a publish), or a plan so broken that every way forward is a guess. Anything else, decide, and record the ruling with what it costs if wrong.
|
|
5944
5948
|
- Keep every ruling where the human will read it: list them all, each with what it costs if wrong, in your final message and in the pull request body.
|
|
5945
|
-
- Finish with a review of the whole branch on the strongest model and one fixer for all its findings. Then delete the plan's scratch directory.`,enabled:!0},{name:`plan-lifecycle.md`,trigger:`read or retire a plan or spec`,body:
|
|
5949
|
+
- Finish with a review of the whole branch on the strongest model and one fixer for all its findings. Then delete the plan's scratch directory.`,enabled:!0},{name:`plan-lifecycle.md`,trigger:`read or retire a plan or spec`,body:Ha,enabled:!0},{name:`debugging.md`,trigger:`fix a bug, a failing test, or unexpected behaviour`,body:`# Debugging
|
|
5946
5950
|
|
|
5947
5951
|
**Find the root cause before you change anything.** A fix you cannot explain is a guess, and a guess that goes green hides the cause instead of removing it.
|
|
5948
5952
|
|
|
@@ -5987,19 +5991,19 @@ When you decide against an established tool, name it and the reason: in the spec
|
|
|
5987
5991
|
|
|
5988
5992
|
## Requesting a review
|
|
5989
5993
|
|
|
5990
|
-
Give the reviewer the requirement (the plan, issue, or spec) and the exact commit range, not your session's history -- it should judge the work, not your reasoning about it. Review before merge, and after any change large enough that you would not spot your own mistake in it.`,enabled:!0},{name:`findings.md`,trigger:`note a defect you are not fixing, or work a finding`,body:"# Findings ledger\n\nA defect you notice but are not fixing in the current change -- a nit, or something pre-existing -- goes in `.agent/findings/`, one file per finding, via `pnpm exec bst findings:add` (never hand-write the filename: a name the parser cannot read back is silently dropped from every listing). A finding names the PR or issue that surfaced it. The file IS the pending state: merging it enqueues it for the automated backlog run, fixing or refuting it means deleting the file in the same commit (`pnpm exec bst findings:resolve`), and deferring it appends a note (`pnpm exec bst findings:resolve --defer`). A finding only a human can decide leaves the ledger as an issue: the backlog run escalates it through the `human-decision` follow-up route and deletes the file; by hand, file the issue yourself and `pnpm exec bst findings:resolve` the entry. `pnpm exec bst findings:list` shows what is pending.",enabled:!0},{name:`check-cadence.md`,trigger:`run tests, typecheck, lint, or the check pipeline`,body:checkCadenceBody(e),enabled:e.stack!==`none`},{name:`coverage.md`,trigger:"commit a change under `src/`",body:"# Coverage baseline\n\nTouched `src/`? Run `pnpm test:coverage`, then `pnpm exec bst coverage:check`. If a total regressed beyond tolerance, add tests until parity -- or exclude the file via `coverage.exclude` in `.tooling.json` and say why in the commit. If no total dropped, run `pnpm exec bst coverage:check --update-baseline` and stage `coverage-baseline.json`. Skip for docs-, config-, dependency-, or test-only changes.\n\nIf the total dropped only because previously-untested code entered the denominator -- a first test, or `coverage.include` newly enabled -- that is expected, not a regression: do not exclude the file you just tested. Adopt the baseline instead: `pnpm exec bst coverage:check --update-baseline --reset` (a downward move needs `--reset`).\n\nTotals at or above `coverage.floorPp` pass and re-baseline freely; the ratchet applies only below the floor.",enabled:t},{name:`health.md`,trigger:"add a cross-module import, or when `health:check` or a size budget fails",body:healthRuleBody(e),enabled:n}]}function guideIndex(e){let t=[`#### Guides`,``,"Each guide below is a file `repo:sync` keeps current. Read it at the moment it names, before you act. Where an installed plugin or skill covers the same ground as a guide, the guide wins.",``];for(let n of e.filter(e=>e.enabled))t.push(`- Before you ${n.trigger}: \`${
|
|
5991
|
-
`)}function agentRulesBody(e,t,n,r){let i=[...
|
|
5994
|
+
Give the reviewer the requirement (the plan, issue, or spec) and the exact commit range, not your session's history -- it should judge the work, not your reasoning about it. Review before merge, and after any change large enough that you would not spot your own mistake in it.`,enabled:!0},{name:`findings.md`,trigger:`note a defect you are not fixing, or work a finding`,body:"# Findings ledger\n\nA defect you notice but are not fixing in the current change -- a nit, or something pre-existing -- goes in `.agent/findings/`, one file per finding, via `pnpm exec bst findings:add` (never hand-write the filename: a name the parser cannot read back is silently dropped from every listing). A finding names the PR or issue that surfaced it. The file IS the pending state: merging it enqueues it for the automated backlog run, fixing or refuting it means deleting the file in the same commit (`pnpm exec bst findings:resolve`), and deferring it appends a note (`pnpm exec bst findings:resolve --defer`). A finding only a human can decide leaves the ledger as an issue: the backlog run escalates it through the `human-decision` follow-up route and deletes the file; by hand, file the issue yourself and `pnpm exec bst findings:resolve` the entry. `pnpm exec bst findings:list` shows what is pending.",enabled:!0},{name:`check-cadence.md`,trigger:`run tests, typecheck, lint, or the check pipeline`,body:checkCadenceBody(e),enabled:e.stack!==`none`},{name:`coverage.md`,trigger:"commit a change under `src/`",body:"# Coverage baseline\n\nTouched `src/`? Run `pnpm test:coverage`, then `pnpm exec bst coverage:check`. If a total regressed beyond tolerance, add tests until parity -- or exclude the file via `coverage.exclude` in `.tooling.json` and say why in the commit. If no total dropped, run `pnpm exec bst coverage:check --update-baseline` and stage `coverage-baseline.json`. Skip for docs-, config-, dependency-, or test-only changes.\n\nIf the total dropped only because previously-untested code entered the denominator -- a first test, or `coverage.include` newly enabled -- that is expected, not a regression: do not exclude the file you just tested. Adopt the baseline instead: `pnpm exec bst coverage:check --update-baseline --reset` (a downward move needs `--reset`).\n\nTotals at or above `coverage.floorPp` pass and re-baseline freely; the ratchet applies only below the floor.",enabled:t},{name:`health.md`,trigger:"add a cross-module import, or when `health:check` or a size budget fails",body:healthRuleBody(e),enabled:n}]}function guideIndex(e){let t=[`#### Guides`,``,"Each guide below is a file `repo:sync` keeps current. Read it at the moment it names, before you act. Where an installed plugin or skill covers the same ground as a guide, the guide wins.",``];for(let n of e.filter(e=>e.enabled))t.push(`- Before you ${n.trigger}: \`${Ja}/${n.name}\`.`);return t.join(`
|
|
5995
|
+
`)}function agentRulesBody(e,t,n,r){let i=[...Ia];e.stack===`typescript`&&i.push("- Never overrule the type checker: no `as T` assertions and no `any`. Narrow instead, with a zod schema, a type guard, or a control-flow check. `as const` and `satisfies` are fine, because they make a type stricter, not looser."),i.push(...La),e.stack===`typescript`&&i.push(importRule(e)),e.releaseStrategy===`changesets`&&i.push("- A user-facing change owes a changeset in `.changeset/`, written with the change: `patch` for a fix, `minor` for a feature, naming every package it affects. One file per smallest unit of work.");let a=agentRulesTail(r).map(e=>e===za?findCommandRule(n):e);return i.push(...a,``,guideIndex(t)),i.join(`
|
|
5992
5996
|
`)}function isGuideIgnored(e){return e.split(`
|
|
5993
5997
|
`)[0]?.trim()===`<!-- @bensandee/tooling:ignore -->`}function isGuideOwned(e){return(e.split(`
|
|
5994
|
-
`)[0]??``).includes(
|
|
5995
|
-
\n${t.body}\n`);return r===i?{filePath:n,action:`skipped`,description:`Guide already up to date`}:(e.write(n,i),r===void 0?{filePath:n,action:`created`,description:`Generated agent guide`}:{filePath:n,action:`updated`,description:`Updated agent guide`})}function syncGuides(e,t){let n=t.filter(e=>e.enabled),r=n.map(t=>writeGuide(e,t)),i=new Set(n.map(e=>e.name));for(let t of e.list(
|
|
5998
|
+
`)[0]??``).includes(Rn)}function writeGuide(e,t){let n=`${Ja}/${t.name}`,r=e.read(n);if(r!==void 0&&isGuideIgnored(r))return{filePath:n,action:`skipped`,description:`Ignored via tooling:ignore comment`};let i=formattedTemplate(e,n,`<!-- Managed by @bensandee/tooling -- \`bst repo:sync\` rewrites this guide and archives local edits. To keep your own version, make the first line an HTML comment reading @bensandee/tooling:ignore. -->
|
|
5999
|
+
\n${t.body}\n`);return r===i?{filePath:n,action:`skipped`,description:`Guide already up to date`}:(e.write(n,i),r===void 0?{filePath:n,action:`created`,description:`Generated agent guide`}:{filePath:n,action:`updated`,description:`Updated agent guide`})}function syncGuides(e,t){let n=t.filter(e=>e.enabled),r=n.map(t=>writeGuide(e,t)),i=new Set(n.map(e=>e.name));for(let t of e.list(Ja)){if(i.has(t))continue;let n=`${Ja}/${t}`,a=e.read(n);a!==void 0&&isGuideOwned(a)&&(e.remove(n),r.push({filePath:n,action:`removed`,description:`Removed agent guide no longer shipped`}))}return r}const Ya=[`findings-ledger`,`check-cadence`,`coverage-rule`,`health-rule`];function syncClaudeMdFile(e,t){let n=[{name:`agent-rules`,startMarker:`<!-- @tooling:agent-rules -->`,endMarker:`<!-- @tooling:endagent-rules -->`,body:agentRulesBody(e.config,t,e.packageJson,agentEnabled(e)),enabled:!0},...Ya.map(e=>({name:e,startMarker:`<!-- @tooling:${e} -->`,endMarker:`<!-- @tooling:end${e} -->`,body:``,enabled:!1}))],r=e.read(J),i=r??`# CLAUDE.md
|
|
5996
6000
|
|
|
5997
6001
|
Project guidance for Claude Code.
|
|
5998
|
-
`;for(let e of n)i=applyBlock(i,e);return i=formattedTemplate(e,
|
|
6002
|
+
`;for(let e of n)i=applyBlock(i,e);return i=formattedTemplate(e,J,i),r?i===r?{filePath:J,action:`skipped`,description:`Managed agent rules already up to date`}:(e.write(J,i),{filePath:J,action:`updated`,description:`Updated managed agent rules`}):(e.write(J,i),{filePath:J,action:`created`,description:`Generated CLAUDE.md with the managed agent rules`})}const Y=`AGENTS.md`;function syncAgentsMdLink(e){let t=e.readLink(Y);if(t===J)return{filePath:Y,action:`skipped`,description:`Already links to CLAUDE.md`};if(t!==void 0)return{filePath:Y,action:`skipped`,description:`Left alone: a symlink to ${t}, not to CLAUDE.md`};if(e.exists(Y))return{filePath:Y,action:`skipped`,description:`Left alone: a regular file the repo owns; link it to CLAUDE.md to share the rules`};try{e.symlink(J,Y)}catch(e){let t=e instanceof Error?e.message:String(e);return{filePath:Y,action:`skipped`,description:`Could not link AGENTS.md to CLAUDE.md (${t}); create the link by hand`}}return{filePath:Y,action:`created`,description:`Linked AGENTS.md to CLAUDE.md`}}async function generateClaudeMd(e){let t=resolveCoverageConfigFromContext(e,e.config.setupVitest),n=resolveHealthConfigFromContext(e,{isMonorepo:e.config.structure===`monorepo`}),r=mergePrepEnabled(e),i=agentGuides(e.config,t.enabled,n.enabled&&n.graphMetricsEnabled,repoHasWebUI(e),r);return[syncClaudeMdFile(e,i),...syncGuides(e,i),syncAgentsMdLink(e),...syncMergePrepSkill(e,r)]}function buildConfig(){return{header:`# Changelog
|
|
5999
6003
|
|
|
6000
6004
|
All notable changes to this project will be documented in this file.
|
|
6001
6005
|
`,types:[{type:`feat`,section:`Features`},{type:`fix`,section:`Bug Fixes`},{type:`chore`,section:`Chores`},{type:`refactor`,section:`Refactoring`},{type:`perf`,section:`Performance`},{type:`docs`,hidden:!0},{type:`style`,hidden:!0},{type:`test`,hidden:!0},{type:`ci`,hidden:!0}],tagPrefix:`v`}}async function generateVersionrc(e){let t=`.versionrc.json`;if(e.config.releaseStrategy!==`simple`)return{filePath:t,action:`skipped`,description:`simple release not requested`};if(e.exists(t)||e.exists(`.versionrc`))return{filePath:t,action:`skipped`,description:`Existing versionrc config preserved`};let n=JSON.stringify(buildConfig(),null,2)+`
|
|
6002
|
-
`;return e.write(t,n),{filePath:t,action:`created`,description:`Generated .versionrc.json`}}async function generateStaleCiWorkflows(e){let t=e.config.ci;if(t===`none`)return[];let n=e.config.releaseStrategy,r=ciWorkflowPath(t,n),i=[ciWorkflowPath(t,`changesets`),ciWorkflowPath(t,`none`),releaseWorkflowPath(t)],a=/* @__PURE__ */ new Set([r]);hasReleaseWorkflow(n)&&a.add(releaseWorkflowPath(t));let o=[];for(let s of i){if(a.has(s))continue;let i=retireReason(n,s,r,t),c=e.read(s);if(c!==void 0&&isToolingManagedWorkflow(c)){let e=extractCustomBlocks(c);if(e.length>0){o.push({filePath:s,action:`skipped`,description:customBlockAdvice(s,i,e.length,r,t)});continue}}let l=retireManagedWorkflow(e,s,i);l!==void 0&&o.push(l)}return o}function baseName(e){return e.slice(e.lastIndexOf(`/`)+1)}function customBlockAdvice(e,t,n,r,i){let a=`${e} is stale (${t}) but carries ${String(n)} # @tooling:custom block${n===1?``:`s`}`;return e!==releaseWorkflowPath(i)||r===ciWorkflowPath(i,`changesets`)?`${a}: move them into ${baseName(r)}, then delete ${e} to retire it`:`${a}: delete ${e} to retire it`}function retireReason(e,t,n,r){let i=baseName(n),a=`releaseStrategy "${e}"`;return t===releaseWorkflowPath(r)?n===ciWorkflowPath(r,`changesets`)?`${a} releases from ${i}`:`${a} has no release workflow`:`${a} runs checks in ${i}`}async function runGenerators(e){let t=[],n=e.packageJson?.devEngines;return t.push(await generatePackageJson(e)),t.push(await generateMise(e,n)),t.push(...await generateWorkspaceEngines(e)),t.push(await generatePnpmWorkspace(e)),t.push(...await generateTsconfig(e)),t.push(await generateTsdown(e)),t.push(await generateOxlint(e)),t.push(await generateFormatter(e)),t.push(...await generateLefthook(e)),t.push(await generateGitignore(e)),t.push(await generateGitattributes(e)),t.push(await generateKnip(e)),t.push(await generateRenovate(e)),t.push(await generateCi(e)),t.push(...await generateClaudeHooks(e)),t.push(...await generateClaudeSettings(e)),t.push(await generateReleaseIt(e)),t.push(await generateVersionrc(e)),t.push(await generateChangesets(e)),t.push(await generateReleaseCi(e)),t.push(...await generateStaleCiWorkflows(e)),t.push(await generateDeployCi(e)),t.push(...await generateClaudeMd(e)),t.push(...await generateVitest(e)),t.push(...await generateVscodeSettings(e)),t.push(saveToolingConfig(e,e.config)),t}function failedResults(e){return e.filter(e=>e.action===`failed`)}function reportFailures(e,t){if(e.length!==0){
|
|
6006
|
+
`;return e.write(t,n),{filePath:t,action:`created`,description:`Generated .versionrc.json`}}async function generateStaleCiWorkflows(e){let t=e.config.ci;if(t===`none`)return[];let n=e.config.releaseStrategy,r=ciWorkflowPath(t,n),i=[ciWorkflowPath(t,`changesets`),ciWorkflowPath(t,`none`),releaseWorkflowPath(t)],a=/* @__PURE__ */ new Set([r]);hasReleaseWorkflow(n)&&a.add(releaseWorkflowPath(t));let o=[];for(let s of i){if(a.has(s))continue;let i=retireReason(n,s,r,t),c=e.read(s);if(c!==void 0&&isToolingManagedWorkflow(c)){let e=extractCustomBlocks(c);if(e.length>0){o.push({filePath:s,action:`skipped`,description:customBlockAdvice(s,i,e.length,r,t)});continue}}let l=retireManagedWorkflow(e,s,i);l!==void 0&&o.push(l)}return o}function baseName(e){return e.slice(e.lastIndexOf(`/`)+1)}function customBlockAdvice(e,t,n,r,i){let a=`${e} is stale (${t}) but carries ${String(n)} # @tooling:custom block${n===1?``:`s`}`;return e!==releaseWorkflowPath(i)||r===ciWorkflowPath(i,`changesets`)?`${a}: move them into ${baseName(r)}, then delete ${e} to retire it`:`${a}: delete ${e} to retire it`}function retireReason(e,t,n,r){let i=baseName(n),a=`releaseStrategy "${e}"`;return t===releaseWorkflowPath(r)?n===ciWorkflowPath(r,`changesets`)?`${a} releases from ${i}`:`${a} has no release workflow`:`${a} runs checks in ${i}`}async function runGenerators(e){let t=[],n=e.packageJson?.devEngines;return t.push(await generatePackageJson(e)),t.push(await generateMise(e,n)),t.push(...await generateWorkspaceEngines(e)),t.push(await generatePnpmWorkspace(e)),t.push(...await generateTsconfig(e)),t.push(await generateTsdown(e)),t.push(await generateOxlint(e)),t.push(await generateFormatter(e)),t.push(...await generateLefthook(e)),t.push(await generateGitignore(e)),t.push(await generateGitattributes(e)),t.push(await generateKnip(e)),t.push(await generateRenovate(e)),t.push(await generateCi(e)),t.push(...await generateClaudeHooks(e)),t.push(...await generateClaudeSettings(e)),t.push(await generateReleaseIt(e)),t.push(await generateVersionrc(e)),t.push(await generateChangesets(e)),t.push(await generateReleaseCi(e)),t.push(...await generateStaleCiWorkflows(e)),t.push(await generateDeployCi(e)),t.push(...await generateClaudeMd(e)),t.push(...await generateVitest(e)),t.push(...await generateVscodeSettings(e)),t.push(saveToolingConfig(e,e.config)),t}function failedResults(e){return e.filter(e=>e.action===`failed`)}function reportFailures(e,t){if(e.length!==0){I.error(`${String(e.length)} file(s) could not be synced by ${t} -- fix them by hand:`);for(let t of e)I.info(` ${t.filePath} -- ${t.description}`)}}function generateMigratePrompt(e,t,n){let r=[],i=(/* @__PURE__ */ new Date()).toISOString();r.push(`# Migration Prompt\n\n_Generated by \`@bensandee/tooling@0.109.0 repo:sync\` on ${i}_\n`);let a=e.filter(e=>e.action===`created`||e.action===`updated`||e.action===`archived`);if(a.length>0){let e=a.map(e=>{let t=e.action===`archived`?`archived`:e.action;return`- \`${e.filePath}\` (${t}) -- ${e.description}`}).join(`
|
|
6003
6007
|
`);r.push(`## Files changed\n\n${e}\n`)}let o=[];return addLegacyToolingTasks(o,t,n),addArchivedFileTasks(o,e),addOxlintTasks(o,e,n),addMonorepoTasks(o,t,n),addTestGenerationTasks(o,e),o.length>0&&(r.push(`## Migration tasks\n\n${o.join(`
|
|
6004
6008
|
`)}`),r.push(`## Ground rules
|
|
6005
6009
|
|
|
@@ -6018,7 +6022,7 @@ build -> typecheck -> lint -> test -> format -> knip
|
|
|
6018
6022
|
|
|
6019
6023
|
When everything passes, run \`/init\` to generate a \`CLAUDE.md\` for this repository.
|
|
6020
6024
|
`),r.join(`
|
|
6021
|
-
`)}const
|
|
6025
|
+
`)}const Xa={eslint:`oxlint`,prettier:`oxfmt`,jest:`vitest`,webpack:`tsdown`,rollup:`tsdown`};function addLegacyToolingTasks(e,t,n){let r=n.legacyConfigs.filter(e=>e.tool!==`prettier`||t.formatter!==`prettier`);if(r.length===0)return;let i=r.map(e=>{let t=Xa[e.tool],n=e.files.map(e=>`\`${e}\``).join(`, `),r=[`- Remove ${e.tool} config files (${n}). This project now uses **${t}**.`,` - Uninstall ${e.tool}-related packages from devDependencies`];return e.tool===`eslint`&&r.push(` - Migrate any custom ESLint rules that don't have oxlint equivalents`),e.tool===`jest`&&r.push(` - Migrate jest-specific test utilities (jest.mock, jest.fn) to vitest equivalents (vi.mock, vi.fn)`),r.join(`
|
|
6022
6026
|
`)});e.push(`### Remove legacy tooling\n\n${i.join(`
|
|
6023
6027
|
`)}\n`)}function addArchivedFileTasks(e,t){let n=t.filter(e=>e.action===`archived`);if(n.length===0)return;let r=n.map(e=>`- \`${e.filePath}\` -> \`.tooling-archived/${e.filePath}\``).join(`
|
|
6024
6028
|
`);e.push(`### Review archived files
|
|
@@ -6038,119 +6042,120 @@ import { defineConfig } from "oxlint";
|
|
|
6038
6042
|
|
|
6039
6043
|
export default defineConfig({ extends: [recommended] });
|
|
6040
6044
|
\`\`\`
|
|
6041
|
-
`)}function addMonorepoTasks(e,t,n){t.structure!==`monorepo`||n.hasPnpmWorkspace||e.push("### Migrate to monorepo structure\n\nThis project was converted to a monorepo. Complete the migration:\n\n1. Move existing source into `packages/<name>/`\n2. Split root `package.json` into workspace manifest + package-level `package.json`\n3. Move `tsconfig.json` into the package, add project references to root\n4. Create a package-level `tsdown.config.ts`\n5. Update import paths and build scripts\n")}function addTestGenerationTasks(e,t){t.some(e=>e.filePath===`test/example.test.ts`&&e.action===`created`)&&e.push("### Generate tests\n\nA starter test was created at `test/example.test.ts`. Review `src/` and create additional tests covering exported functions and edge cases.\n")}function logDetectionSummary(e){if(e.config.publishDocker){let t=detectContextDockerPackages(e).filter(e=>e.publish);t.length>0&&
|
|
6042
|
-
`),`Summary`);let h=o.find(e=>e.filePath===`.gitattributes`);a()&&h&&(h.action===`created`||h.action===`updated`)&&
|
|
6043
|
-
`),`Next steps`),{results:o,install:v}}async function runInit(e,t={}){return(await runInitReport(e,t)).results}const
|
|
6044
|
-
`).map(e=>e.trim()).filter(e=>e.length>0):[]}function listSweepCandidates(e){let t=[.../* @__PURE__ */ new Set([...containerIds(e,`label=${
|
|
6045
|
-
`)){if(e.trim().length===0)continue;let t;try{t=JSON.parse(e)}catch{continue}let n=
|
|
6045
|
+
`)}function addMonorepoTasks(e,t,n){t.structure!==`monorepo`||n.hasPnpmWorkspace||e.push("### Migrate to monorepo structure\n\nThis project was converted to a monorepo. Complete the migration:\n\n1. Move existing source into `packages/<name>/`\n2. Split root `package.json` into workspace manifest + package-level `package.json`\n3. Move `tsconfig.json` into the package, add project references to root\n4. Create a package-level `tsdown.config.ts`\n5. Update import paths and build scripts\n")}function addTestGenerationTasks(e,t){t.some(e=>e.filePath===`test/example.test.ts`&&e.action===`created`)&&e.push("### Generate tests\n\nA starter test was created at `test/example.test.ts`. Review `src/` and create additional tests covering exported functions and edge cases.\n")}function logDetectionSummary(e){if(e.config.publishDocker){let t=detectContextDockerPackages(e).filter(e=>e.publish);t.length>0&&I.info(`Docker images to build and publish: ${t.map(e=>e.imageName).join(`, `)}`)}if(e.config.publishNpm){let t=getPublishablePackages(e.targetDir,e.config.structure,e.packageJson);t.length>0&&I.info(`npm packages to publish: ${t.map(e=>e.name).join(`, `)}`)}let t=detectReleaseAssetsConventionDirs(e);if(t.length>0){let e=t.length===1&&t[0]===`.`?`root`:t.join(`, `);I.info(`Release assets convention detected in ${e} -- emit build artifacts to ${Ci}/ (gitignored).`)}}async function runInitReport(e,t={}){let n=detectProject(e.targetDir),{ctx:r,archivedFiles:i,sawCrlf:a}=createContext(e,t.confirmOverwrite??(async e=>{let t=await ue({message:`${e} already exists. What do you want to do?`,options:[{value:`overwrite`,label:`Overwrite`},{value:`skip`,label:`Skip`}]});return le(t)?`skip`:t}),t.dockerDiscovery);logDetectionSummary(r);let o=await runGenerators(r),s=new Set(o.filter(e=>e.action===`archived`).map(e=>e.filePath));for(let e of i)s.has(e)||o.push({filePath:e,action:`archived`,description:`Original saved to .tooling-archived/${e}`});let c=o.filter(e=>e.action===`created`),l=o.filter(e=>e.action===`updated`),u=o.filter(e=>e.action===`removed`),d=c.length>0||l.length>0||u.length>0||i.length>0,f=failedResults(o);reportFailures(f,`repo:sync`);let p=`.tooling-migrate.md`;if(!t.noPrompt){let t=generateMigratePrompt(o,e,n);r.write(p,t)}if(!d&&t.noPrompt)return f.length===0&&I.success(`Repository is up to date.`),{results:o,install:`not-run`};if(o.some(e=>e.action===`archived`&&e.filePath.startsWith(`.husky/`)))try{de(`git config --unset core.hooksPath`,{cwd:e.targetDir,stdio:`ignore`,timeout:5e3})}catch{}let m=[];c.length>0&&m.push(`Created: ${c.map(e=>e.filePath).join(`, `)}`),l.length>0&&m.push(`Updated: ${l.map(e=>e.filePath).join(`, `)}`),u.length>0&&m.push(`Removed: ${u.map(e=>e.filePath).join(`, `)}`),note(m.join(`
|
|
6046
|
+
`),`Summary`);let h=o.find(e=>e.filePath===`.gitattributes`);a()&&h&&(h.action===`created`||h.action===`updated`)&&I.warn("CRLF line endings found on disk. Commit .gitattributes, then refresh the checkout: `git add --renormalize .` for the index, plus a forced re-checkout of the working tree. That refresh rewrites the working tree, so run it on a clean tree -- commit or stash first."),t.noPrompt||I.info(`Migration prompt written to ${p}`);let g=o.some(e=>e.filePath===`package.json`&&(e.action===`created`||e.action===`updated`)),_=r.exists(`pnpm-lock.yaml`),v=`not-run`;if(g&&_){I.info(`package.json changed -- running pnpm install...`);try{de(`pnpm install`,{cwd:e.targetDir,stdio:t.installOutput===`capture`?`ignore`:`inherit`,timeout:12e4}),v=`ran`}catch{I.warn(`pnpm install failed -- run it manually`),v=`failed`}}if(d&&r.exists(`package.json`))try{de(`pnpm format`,{cwd:e.targetDir,stdio:`ignore`,timeout:3e4})}catch{}return note([...g&&!_?[`Run: pnpm install`]:[],`Run: pnpm check`,...t.noPrompt?[]:[`Run: claude "Execute the migration steps in .tooling-migrate.md"`]].map((e,t)=>`${t+1}. ${e}`).join(`
|
|
6047
|
+
`),`Next steps`),{results:o,install:v}}async function runInit(e,t={}){return(await runInitReport(e,t)).results}const Za=P.looseObject({name:P.unknown().optional()}),Qa=new Set(vn),$a=/^(?:docker-compose|compose).*\.(?:yml|yaml)$/;function lintComposeFiles(e,t){let n=[],r=/* @__PURE__ */ new Set,i=[],a=t?.dockerCheck,s=a!==void 0&&a!==!1;for(let t of yn){let i=w.resolve(e,t);o(i)&&visitDir(e,i,r,n)}if(s&&a.composeFiles)for(let t of a.composeFiles){let n=w.resolve(e,t);if(!o(n))continue;let a=w.dirname(n);if(r.has(a))continue;let s=w.basename(n);i.push({absPath:n,relPath:w.relative(e,n),basename:s})}let c=/* @__PURE__ */ new Map;for(let e of i){let t=w.dirname(e.absPath),n=c.get(t)??[];n.push(e),c.set(t,n)}for(let e of c.values())e.sort((e,t)=>e.relPath.localeCompare(t.relPath)),lintDirFiles(e,n);return n}function visitDir(e,t,n,r){if(n.has(t))return;n.add(t);let i;try{i=h(t)}catch{return}let a=i.filter(e=>$a.test(e)).toSorted().map(n=>{let r=w.join(t,n);return{absPath:r,relPath:w.relative(e,r),basename:n}});a.length!==0&&lintDirFiles(a,r)}function lintDirFiles(e,t){let n=/* @__PURE__ */ new Map;for(let r of e){let e=readTopLevelName(r.absPath);if(n.set(r.relPath,e),!Qa.has(r.basename)&&(e===void 0||e===``)){let e=suggestProjectName(r);t.push({kind:`missing-name`,files:[r.relPath],message:`${r.relPath}: override compose file is missing required top-level 'name:' directive.\n Add: name: ${e}\n Why: without an explicit name, this override inherits the base file's project namespace.\n A 'docker compose down -v' against this override would target the base project's volumes\n -- which has caused production volume loss in the past.`})}}let r=/* @__PURE__ */ new Map;for(let[e,t]of n){if(t===void 0||t===``)continue;let n=r.get(t)??[];n.push(e),r.set(t,n)}for(let[e,n]of r){if(n.length<2)continue;n.sort();let[r,i,...a]=n,o=a.length>0?`, ${a.join(`, `)}`:``;t.push({kind:`duplicate-name`,files:n,message:`${String(r)} and ${String(i)}${o} both declare 'name: ${e}'.\n Each compose file in the same directory must declare a unique 'name:'.\n Suggested fix: rename one (e.g. 'name: ${e}-test' in one of them).`})}}function suggestProjectName(e){let t=e.basename.replace(/\.(yml|yaml)$/,``).split(`.`),n=t[t.length-1];return t.length>1&&n?`<project>-${n}`:`<project>-check`}function readTopLevelName(e){let t;try{t=p(e,`utf-8`)}catch{return}let n;try{n=parseComposeYaml(t)}catch{return}let r=Za.safeParse(n);if(!r.success)return;let i=r.data.name;if(typeof i==`string`)return i}const eo=`com.bensandee.ci`,to=/(?:^|\/)tooling-check-[^/]+\/overlay\.ya?ml$/;function isHarnessContainer(e){return e.ciLabel===`1`||e.configFiles!==null&&e.configFiles.split(`,`).some(e=>to.test(e.trim()))}function selectSweepTargets(e,t){return e.filter(e=>!isHarnessContainer(e)||!Number.isFinite(e.createdMs)?!1:t.nowMs-e.createdMs>=t.maxAgeMs)}const no=P.object({id:P.string(),name:P.string(),created:P.string(),project:P.string().nullable(),configFiles:P.string().nullable(),ci:P.string().nullable()}),ro=[`{`,`"id":{{json .Id}},`,`"name":{{json .Name}},`,`"created":{{json .Created}},`,`"project":{{json (index .Config.Labels "com.docker.compose.project")}},`,`"configFiles":{{json (index .Config.Labels "com.docker.compose.project.config_files")}},`,`"ci":{{json (index .Config.Labels "${eo}")}}`,`}`].join(``);function containerIds(e,t){let n=e.exec(`docker`,[`ps`,`-aq`,`--filter`,t]);return n.exitCode===0?n.stdout.split(`
|
|
6048
|
+
`).map(e=>e.trim()).filter(e=>e.length>0):[]}function listSweepCandidates(e){let t=[.../* @__PURE__ */ new Set([...containerIds(e,`label=${eo}=1`),...containerIds(e,`label=com.docker.compose.project.config_files`)])];if(t.length===0)return[];let n=e.exec(`docker`,[`inspect`,`--format`,ro,...t]),r=[];for(let e of n.stdout.split(`
|
|
6049
|
+
`)){if(e.trim().length===0)continue;let t;try{t=JSON.parse(e)}catch{continue}let n=no.safeParse(t);n.success&&r.push({id:n.data.id,name:n.data.name.replace(/^\//,``),project:n.data.project,configFiles:n.data.configFiles,ciLabel:n.data.ci,createdMs:Date.parse(n.data.created)})}return r}const io=P.object({id:P.string(),name:P.string(),created:P.string()});function selectSweepNetworks(e,t){return e.filter(e=>Number.isFinite(e.createdMs)?t.nowMs-e.createdMs>=t.maxAgeMs:!1)}function listLabelledNetworks(e){let t=e.exec(`docker`,[`network`,`ls`,`-q`,`--filter`,`label=${eo}=1`]);if(t.exitCode!==0)return[];let n=t.stdout.split(`
|
|
6046
6050
|
`).map(e=>e.trim()).filter(e=>e.length>0);if(n.length===0)return[];let r=e.exec(`docker`,[`network`,`inspect`,`--format`,`{"id":{{json .Id}},"name":{{json .Name}},"created":{{json .Created}}}`,...n]),i=[];for(let e of r.stdout.split(`
|
|
6047
|
-
`)){if(e.trim().length===0)continue;let t;try{t=JSON.parse(e)}catch{continue}let n=
|
|
6048
|
-
`).map(e=>e.trim()).filter(e=>e.length>0):[]}function runSweep(e,t={}){let n=t.dryRun??!1,r={containers:[],networks:[],volumes:[],failed:[],dryRun:n},i=selectSweepTargets(listSweepCandidates(e),{nowMs:e.now(),maxAgeMs:t.maxAgeMs??144e5});for(let t of i){if(e.log(`${n?`Would reclaim`:`Reclaiming`} leaked container ${t.name}`),n){r.containers.push({id:t.id,name:t.name});continue}let i=e.exec(`docker`,[`rm`,`-f`,`-v`,t.id]);i.exitCode===0?r.containers.push({id:t.id,name:t.name}):recordFailure(e,r,`container`,t.name,i)}let a=[...new Set(i.map(e=>e.project).filter(e=>e!==null))];for(let t of a)for(let i of[`network`,`volume`]){let a=resourceIds(e,i,t);if(a.length===0)continue;e.log(`${n?`Would reclaim`:`Reclaiming`} ${i}(s): ${a.join(`, `)}`);let o=i===`network`?r.networks:r.volumes;for(let t of a){if(n){o.push(t);continue}let a=e.exec(`docker`,[i,`rm`,t]);a.exitCode===0?o.push(t):recordFailure(e,r,i,t,a)}}let o=selectSweepNetworks(listLabelledNetworks(e),{nowMs:e.now(),maxAgeMs:t.maxAgeMs??144e5});for(let t of o){if(r.networks.some(e=>t.id.startsWith(e)||e.startsWith(t.id)))continue;if(e.log(`${n?`Would reclaim`:`Reclaiming`} network: ${t.id}`),n){r.networks.push(t.id);continue}let i=e.exec(`docker`,[`network`,`rm`,t.id]);i.exitCode===0?r.networks.push(t.id):recordFailure(e,r,`network`,t.id,i)}return r}function recordFailure(e,t,n,r,i){let a=i.stderr.trim()||`docker exited ${String(i.exitCode)}`;t.failed.push({kind:n,ref:r,error:a}),e.log(`Could not reclaim ${n} ${r}: ${a}`)}function readFileOrNull(e){try{return p(e,`utf-8`)}catch{return null}}function detectComposeFiles(e){let t=resolveComposeFileSet(readFileOrNull,e);return{dir:t.composeDir,files:t.files}}function crossReferenceDockerImages(e,t){let n=extractComposeImageNames(t),r=new Set(extractComposeBuildDockerfiles(t)),i=[];for(let t of e){let e=n.some(e=>e===t.imageName||e.endsWith(`/${t.imageName}`)),a=r.has(t.dockerfileAbs);!e&&!a?i.push({kind:`unreferenced`,dir:t.dir,imageName:t.imageName}):a&&!e&&i.push({kind:`rebuild-no-image`,dir:t.dir,imageName:t.imageName})}return i}function findDockerRebuildRisks(e,t,n=createDockerDiscoveryMemo()){let r=t?.dockerCheck;if(r===!1)return[];let i=createFileReader(),a=i.readFile(w.join(e,`package.json`)),o=a?parsePackageJson(a):void 0;if(!o?.name)return[];let s=n.detect(i,e,o.name);if(s.length===0)return[];let c=computeCheckDefaults(e),l=r?.composeFiles??c.composeFiles??[];if(l.length===0)return[];let u=parseComposeServices(c.composeCwd??e,checkComposeFiles(l,c.checkOverlay));return crossReferenceDockerImages(s.map(t=>({dir:t.dir,imageName:t.imageName,dockerfileAbs:w.resolve(e,t.docker.dockerfile)})),u).filter(e=>e.kind===`rebuild-no-image`).map(e=>`Docker package "${e.dir}" is built by a compose service with no \`image: ${e.imageName}\`.\n docker:build tags ${e.imageName}:latest, but compose tags its own build separately,\n so the Dockerfile builds twice and docker:check cannot reuse the docker:build output.\n Fix: add \`image: ${e.imageName}\` to that service (skip if it builds a variant on purpose).`)}function findCheckOnlyPublishRisks(e,t=
|
|
6049
|
-
`)){let e=parseMeasureMarkerLine(n);e!==void 0&&(t=e)}return t}
|
|
6050
|
-
`);o=t.pop()??``;for(let e of t)scan(e)}),i.on(`error`,()=>{r({exitCode:1,lastMarkerLine:a})}),i.on(`close`,e=>{o!==``&&scan(o),r({exitCode:e??1,lastMarkerLine:a})})})}function matches(e,t){return t.size>0&&P.isMatch(e,[...t])}function groupSkippedSteps(e,t,n,r){let i={"--skip":[],"checks.skip":[]};for(let a of e)t.has(a)&&(matches(a,n)?i[`--skip`].push(a):matches(a,r)&&i[`checks.skip`].push(a));return[`--skip`,`checks.skip`].filter(e=>i[e].length>0).map(e=>({source:e,steps:i[e]}))}function createRealHealthExecutor(e){return{exec(t,n,r){let i=execCapture$2(t,n,{cwd:r?.cwd??e,env:r?.env,input:r?.input,keepPartialStdoutOnKill:!1});return{stdout:i.stdout,stderr:i.stderr,exitCode:i.status}},readFile(t){let n=w.join(e,t);if(o(n))try{return p(n,`utf-8`)}catch{return}},readDir(t){let n=w.join(e,t);try{return h(n)}catch{return}},readDirRecursive(t,n){let r=[],walk=t=>{let i;try{i=h(w.join(e,t))}catch{return}for(let a of i){if(a===`node_modules`||a===`.git`||a===`dist`)continue;let i=w.join(t,a),o=!1;try{o=b(w.join(e,i)).isDirectory()}catch{o=!1}o?walk(i):(n.length===0||n.some(e=>a.endsWith(e)))&&r.push(i.replace(/\\/g,`/`))}};return walk(t),r}}}const ho=`health-baseline.json`,go=`.tooling.json`;function repoPrefix(e,t){let n=e.exec(`git`,[`rev-parse`,`--show-prefix`],{cwd:t});return n.exitCode===0?n.stdout.trim():``}const _o=N.object({defaultBranch:N.string().optional()});function parseDefaultBranchOverride(e){if(e===void 0||e.trim()===``)return;let t;try{t=JSON.parse(e)}catch{return}let n=_o.safeParse(t);return n.success?n.data.defaultBranch:void 0}function resolveReferenceBranch(e,t,n,r){let i=gitRunner(e),a=ciDefaultBranch(r)??originHeadBranch(i,t),o=a??`main`,s=`refs/remotes/origin/${o}`;if(i([`rev-parse`,`--verify`,`--quiet`,s],t)!==void 0){let r=parseDefaultBranchOverride(showAt(e,t,s,`${n}${go}`))??o;if(a!==void 0)return{branch:r};let i=parseDefaultBranchOverride(e.readFile(go));return i===void 0||i===r?{branch:r}:{branch:r,warning:unconfirmedDefaultWarning(r,i)}}return a===void 0?{branch:parseDefaultBranchOverride(e.readFile(go))??`main`}:{branch:o}}function originHeadBranch(e,t){let n=e([`symbolic-ref`,`--short`,`refs/remotes/origin/HEAD`],t);if(n===void 0)return;let r=n.startsWith(`origin/`)?n.slice(7):n;return r===``?void 0:r}function unconfirmedDefaultWarning(e,t){return`health: could not confirm the default branch, so the reference was read against origin/${e}, while .tooling.json#defaultBranch names ${t}. If ${t} is the repository's default branch, record it in this clone with \`git remote set-head origin --auto\`, or run in GitHub or Forgejo Actions, where the event payload names it.`}function gitRunner(e){return(t,n)=>{let r=e.exec(`git`,t,{cwd:n});if(r.exitCode!==0)return;let i=r.stdout.trim();return i===``?void 0:i}}function showAt(e,t,n,r){let i=e.exec(`git`,[`show`,`${n}:${r}`],{cwd:t});if(i.exitCode===0)return i.stdout}function readReference(e,t){let n=repoPrefix(e,t.cwd),{branch:r,warning:i}=resolveReferenceBranch(e,t.cwd,n,t.ciEvent),a=e.exec(`git`,[`merge-base`,`HEAD`,`origin/${r}`],{cwd:t.cwd}),o=a.stdout.trim();if(a.exitCode!==0||o===``)return{kind:`unavailable`,reason:`health: cannot read the reference at the merge base with origin/${r}. Run \`git fetch origin ${r}\` so the default branch is present (a shallow clone or a missing remote-tracking ref makes it absent), or set .tooling.json#defaultBranch on the default branch if it has another name -- once that branch is fetched, its own copy of the setting decides, not this branch's. health:check fails closed without a reference.`};let s=showAt(e,t.cwd,o,`${n}${ho}`),c=showAt(e,t.cwd,o,`${n}${go}`),l=resolveHealthConfigFromContext({exists:e=>e===go&&c!==void 0,read:e=>e===go?c:void 0,config:{stack:t.stack}},{isMonorepo:t.isMonorepo}),u={mergeBase:o,prefix:n,baseline:s===void 0?void 0:parseHealthBaseline(s),health:l};return i===void 0?{kind:`read`,reference:u}:{kind:`read`,reference:u,warning:i}}function referenceEnablesHealth(e){try{let t=readReference(createRealHealthExecutor(e),{cwd:e,stack:`none`,isMonorepo:!1,ciEvent:processCiEventSource()});return t.kind===`read`&&t.reference.health.enabled&&t.reference.baseline!==void 0}catch{return!1}}const vo=[`fanInLimit`,`fanOutLimit`,`directoryFileLimit`,`moduleSizeLimit`,`tolerance`],yo=[`enabled`,`crossPackage`];function canonicalJson(e){return JSON.stringify(sortKeys(e))}const bo=N.record(N.string(),N.unknown());function sortKeys(e){if(Array.isArray(e))return e.map(sortKeys);let t=bo.safeParse(e);if(t.success){let e=Object.keys(t.data).toSorted(),n={};for(let r of e)n[r]=sortKeys(t.data[r]);return n}return e}function sizeRaises(e,t){let n=[];for(let[r,i]of Object.entries(e.baseline?.sizeBudgets??{})){if(t.baseline===void 0)continue;let e=t.baseline.sizeBudgets?.[r];e===void 0?t.health.sizeBudgets[r]!==void 0&&n.push({leaf:`sizeBudgets.${r}`,reference:String(i),current:`absent`}):e>i&&n.push({leaf:`sizeBudgets.${r}`,reference:String(i),current:String(e)})}for(let[r,i]of Object.entries(e.health.sizeBudgets)){let e=t.health.sizeBudgets[r];if(e===void 0){n.push({leaf:`health.sizeBudgets.${r}`,reference:`present`,current:`absent`});continue}let a=canonicalJson(i);a!==canonicalJson(e)&&n.push({leaf:`health.sizeBudgets.${r}`,reference:a,current:canonicalJson(e)})}return n}function findRaises(e,t){return[...baselineRaises(e,t),...sizeRaises(e,t),...configRaises(e.health,t.health)]}function baselineRaises(e,t){let n=[];for(let r of L){let i=e.baseline?.[r],a=t.baseline?.[r];i!==void 0&&a!==void 0&&a>i?n.push({leaf:r,reference:String(i),current:String(a)}):i!==void 0&&a===void 0&&t.baseline!==void 0&&(t.measured===void 0||t.measured.metrics[r]!==void 0)&&n.push({leaf:r,reference:String(i),current:`absent`})}for(let r of R){let i=t.measured?.ceilings[r]??{};for(let[a,o]of Object.entries(e.baseline?.moduleCeilings?.[r]??{}))t.baseline!==void 0&&t.baseline.moduleCeilings?.[r]?.[a]===void 0&&(t.measured===void 0||i[a]!==void 0)&&n.push({leaf:`moduleCeilings.${r}.${a}`,reference:String(o),current:`absent`})}for(let r of R){let i=t.baseline?.moduleCeilings?.[r];if(i!==void 0)for(let[t,a]of Object.entries(i)){let i=`moduleCeilings.${r}.${t}`,o=e.baseline?.moduleCeilings?.[r]?.[t];o===void 0?n.push({leaf:i,reference:`absent`,current:String(a)}):a>o&&n.push({leaf:i,reference:String(o),current:String(a)})}}return e.baseline!==void 0&&t.baseline===void 0&&n.push({leaf:ho,reference:`present`,current:`absent`}),n}function configRaises(e,t){let n=[];for(let r of rt){let i=t.exempt[r];if(i!==void 0)for(let t of Object.keys(i))e.exempt[r]?.[t]===void 0&&n.push({leaf:`health.exempt.${r}.${t}`,reference:`absent`,current:`present`})}for(let r of vo){let i=e[r],a=t[r];a>i&&n.push({leaf:`health.${r}`,reference:String(i),current:String(a)})}for(let r of t.exclude)e.exclude.includes(r)||n.push({leaf:`health.exclude.${r}`,reference:`absent`,current:`present`});for(let r of yo)e[r]&&!t[r]&&n.push({leaf:`health.${r}`,reference:`true`,current:`false`});return n}function branchDiffNames(e,t,n){let r=e.exec(`git`,[`diff`,`--name-only`,n],{cwd:t}),i=e.exec(`git`,[`ls-files`,`--others`,`--exclude-standard`,`--full-name`,`--`,`:/`],{cwd:t}),a=/* @__PURE__ */ new Set;for(let e of[r,i])for(let t of e.stdout.split(`
|
|
6051
|
-
`)){let e=t.trim();e!==``&&a.add(e)}return[...a].toSorted()}const
|
|
6052
|
-
`).map(e=>e.trim()).filter(e=>e!==``)}async function commitMessages(e,t,n,r=null){let i=await e.run([`log`,`-z`,`--format=%B`,`${n}..HEAD`],{cwd:t,timeoutMs:J,signal:r});if(i.exitCode!==0)throw new T(`Failed to read commit messages: ${i.stderr||i.stdout}`);return i.stdout.split(`\0`).map(e=>e.trim()).filter(e=>e!==``)}async function hasUncommittedChanges(e,t,n=null){return(await e.run([`status`,`--porcelain`],{cwd:t,timeoutMs:J,signal:n})).stdout.trim()!==``}async function pushBranch(e,t,n,r,i=!1){let a=i?[`push`,`--force-with-lease`,`-u`,`origin`,n]:[`push`,`-u`,`origin`,n],o=await e.run(a,r===void 0?{cwd:t,timeoutMs:xo,signal:null}:{cwd:t,env:r,timeoutMs:xo,signal:null});if(o.exitCode!==0)throw new T(`Failed to push ${n}: ${o.stderr||o.stdout}`)}function resolveDefaultBranch(e){let t=e.configOverride;return t!==void 0&&t!==``?pickDefaultBranch(t,void 0):pickDefaultBranch(void 0,(e.git??defaultGitRunner)([`symbolic-ref`,`--short`,`refs/remotes/origin/HEAD`],e.cwd))}const So=[`--help`,`-h`,`--version`,`-v`,`--verbose`,`--trace`],Co=new Set(So.map(flagName));function hasHelpFlag(e){return e.includes(`--help`)||e.includes(`-h`)}function isLoneVersionQuery(e){return e.length===1&&(e[0]===`--version`||e[0]===`-v`)}function splitAtCommand(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(r===`--`)return;if(r.startsWith(`-`))t!==void 0&&!r.includes(`=`)&&declaresValueFlag(r,t)&&n++;else return{index:n,before:e.slice(0,n)}}}function declaresValueFlag(e,t){let n=flagName(e),r=toCamelCase(n);for(let[e,i]of Object.entries(t)){if(i.type!==`string`&&i.type!==`enum`)continue;if(r===toCamelCase(e))return!0;let t=`alias`in i?i.alias:void 0;if(t!==void 0&&(Array.isArray(t)?t.includes(n):t===n))return!0}return!1}function flagBase(e){let t=e.indexOf(`=`);return t===-1?e:e.slice(0,t)}function flagName(e){return flagBase(e).replace(/^-{1,2}/,``)}function resolveStaticArgsDef(e){let t=e.args;if(t!==void 0&&typeof t!=`function`&&!(t instanceof Promise))return t}function toCamelCase(e){return e.replace(/-([a-z0-9])/g,(e,t)=>t.toUpperCase())}function toKebabCase(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase()}function buildParseTable(e){let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Map,r=new Set(Co),i=[];for(let[a,o]of Object.entries(e)){if(o.type===`positional`)continue;o.type===`boolean`&&t.add(a);let e=`alias`in o?o.alias:void 0,s;s=e===void 0?[]:Array.isArray(e)?e:[e];let c=[...s],l=toCamelCase(a),u=toKebabCase(a);l!==a&&!c.includes(l)&&c.push(l),u!==a&&!c.includes(u)&&c.push(u),n.set(a,c),r.add(a);for(let e of c)r.add(e);i.push(`--${a}`)}function typeFor(e){if(t.has(e))return`boolean`;for(let[r,i]of n)if((r===e||i.includes(e))&&t.has(r))return`boolean`;return`string`}let a={};for(let[e,t]of n){a[e]={type:typeFor(e)};for(let e of t)a[e]={type:typeFor(e)}}return{nodeOptions:a,knownNames:r,acceptedFlags:i}}function parsePostCommandArgs(e,t){let n=[],r=[];for(let t=0;t<e.length;t++){let i=e[t];if(i===`--`){r.push(...e.slice(t));break}i.startsWith(`--no-`)?n.push(i.slice(5)):r.push(i)}let i={},a=[];try{let e=ne({args:r,options:Object.keys(t).length>0?t:void 0,allowPositionals:!0,strict:!1});i=e.values,a=e.positionals}catch{i={}}return{values:i,positionals:a,negatedNames:n}}function findBadDirArg(e,t,n,r){let{positionals:i}=parsePostCommandArgs(e,n),a=Object.entries(t).filter(([,e])=>e.type===`positional`);for(let[e,[t,n]]of a.entries()){let a=i.at(e);if(a===void 0||n.valueHint!==`dir`)continue;let o=r(a);if(o!==`directory`)return{argName:t,value:a,missing:o===`missing`}}}function computeUnknownArgNames(e,t){let n=buildParseTable(t),{values:r,negatedNames:i}=parsePostCommandArgs(e,n.nodeOptions),a=/* @__PURE__ */ new Set;for(let e of Object.keys(r))n.knownNames.has(e)||a.add(e);for(let e of i)n.knownNames.has(e)||a.add(e);return[...a]}function buildDisplayTokenMap(e){let t=/* @__PURE__ */ new Map;for(let n of e){if(n===`--`)break;if(n.startsWith(`--no-`)){let e=n.slice(5);t.has(e)||t.set(e,flagBase(n));continue}if(!n.startsWith(`-`))continue;let e=flagName(n);t.has(e)||t.set(e,flagBase(n))}return t}function formatFlagToken(e){return e.length===1?`-${e}`:`--${e}`}function resolveStaticSubCommands(e){let t=e.subCommands;if(t!==void 0&&typeof t!=`function`&&!(t instanceof Promise))return t}function resolveLeafCommand(e,t,n){let r=resolveStaticArgsDef(e),i=resolveStaticSubCommands(e);if(i!==void 0){let e=splitAtCommand(n,r);if(e!==void 0){let r=n[e.index];if(!(r in i))return;let a=asCommandDef(i[r]);return a===void 0?void 0:resolveLeafCommand(a,[...t,r],n.slice(e.index+1))}}return r===void 0?void 0:{chain:t,argsDef:r,postCommandArgs:n}}function findUnknownFlags(e,t,n){if(hasHelpFlag(e)||isLoneVersionQuery(e))return{kind:`none`};let r=splitAtCommand(e);if(r===void 0)return{kind:`none`};let i=e[r.index];if(!(i in t))return{kind:`none`};let a=asCommandDef(t[i]);if(a===void 0)return{kind:`none`};for(let e of r.before)if(!Co.has(flagName(e)))return{kind:`before-command`,command:i,flag:flagBase(e)};let o=resolveLeafCommand(a,[i],e.slice(r.index+1));if(o===void 0)return{kind:`none`};let s=buildParseTable(o.argsDef),c=computeUnknownArgNames(o.postCommandArgs,o.argsDef);if(c.length===0){let e=n===void 0?void 0:findBadDirArg(o.postCommandArgs,o.argsDef,s.nodeOptions,n);return e===void 0?{kind:`none`}:{kind:`not-a-directory`,command:i,commandPath:o.chain.join(` `),...e}}let l=buildDisplayTokenMap(o.postCommandArgs);return{kind:`unknown`,command:i,commandPath:o.chain.join(` `),unknownFlags:c.map(e=>l.get(e)??formatFlagToken(e)),accepted:s.acceptedFlags}}function formatUnknownFlagsMessage(e){let t=`Unknown ${e.unknownFlags.length===1?`flag`:`flags`} ${e.unknownFlags.join(`, `)} for ${e.commandPath}. Nothing ran.`,n=So.filter(t=>t.startsWith(`--`)&&t!==`--version`&&!e.accepted.includes(t));return`${t}\nAccepted: ${n.length===0?e.accepted.join(`, `):`${e.accepted.join(`, `)} (plus ${n.join(`, `)})`}.`}function formatFlagBeforeCommandMessage(e){return`${e.flag} must come after the command name.`}function formatNotADirectoryMessage(e){return`${e.missing?`No such directory: ${e.value}.`:`${e.value} is not a directory.`} ${e.commandPath} takes a directory as [${e.argName}]. Nothing ran.`}function formatFlagCheckMessage(e){return e.kind===`before-command`?formatFlagBeforeCommandMessage(e):e.kind===`not-a-directory`?formatNotADirectoryMessage(e):formatUnknownFlagsMessage(e)}function collectFlagValues(e,t){let n=`${t}=`,r=[];for(let i=0;i<e.length;i+=1){let a=e[i];if(a!==void 0){if(a===`--`)break;if(a===t){let t=e[i+1];t!==void 0&&(r.push(t),i+=1)}else a.startsWith(n)&&r.push(a.slice(n.length))}}return r.map(e=>e.trim()).filter(e=>e!==``)}function hasNegationFlag(e,t){for(let n of e){if(n===`--`)break;if(n===t)return!0}return!1}function flagPresent(e,t){for(let n of e){if(n===`--`)break;if(n===t||n.startsWith(`${t}=`))return!0}return!1}function resolveRepeatableFlag(e,t,n,r){let i=collectFlagValues(e,t),a=hasNegationFlag(e,n);if(i.length>0&&a)throw new T(`${t} and ${n} are contradictory -- pass only one.`);if(i.length===0&&flagPresent(e,t)){let e=r.fallback===void 0?``:` Refusing rather than falling back to ${r.fallback}.`;throw new T(`${t} was given with no ${r.noun} (expected e.g. ${t} ${r.example}).${e}`)}return a?{kind:`negated`}:i.length>0?{kind:`values`,values:i}:{kind:`absent`}}function parseListFlag(e,t){let n=`--${t}`,r=[];for(let[t,i]of e.entries()){if(i===`--`)break;if(i.startsWith(`${n}=`)){r.push(i.slice(n.length+1));continue}if(i!==n)continue;let a=e[t+1];a!==void 0&&!a.startsWith(`--`)&&r.push(a)}return r.flatMap(e=>e.split(`,`)).map(e=>e.trim()).filter(e=>e.length>0)}const wo=[{name:`build`},{name:`typecheck`},{name:`lint`},{name:`lint:types`},{name:`test`},{name:`format`,args:`--check`},{name:`knip`},{name:`tooling:check`},{name:`docs:check`},{name:`docker:build`},{name:`docker:check`}],To={name:`health:check`};function withHealthCheck(e,t=To){let n=e.findIndex(e=>e.name===`tooling:check`),r=n===-1?e.length:n+1;return[...e.slice(0,r),t,...e.slice(r)]}const Eo={name:`chars:check`},Do=`ascii:check`;function legacyCharsAlias(e){return e===Do?Eo.name:void 0}function withLegacyCharsSkip(e){let t=new Set(e),n=[...t].map(legacyCharsAlias).filter(e=>e!==void 0);for(let e of n)t.add(e);return t}function withCharsCheck(e){let t=e.findIndex(e=>e.name===`lint`),n=t===-1?e.length:t+1;return[...e.slice(0,n),Eo,...e.slice(n)]}function charsBlock(e){return e?.chars??e?.ascii}function resolveBuiltinChecks(e){let t=wo;return isCharsGateOn(charsBlock(e))&&(t=withCharsCheck(t)),e?.health?.enabled===!0&&(t=withHealthCheck(t)),t}function resolveRunBuiltins(e,t,n=referenceEnablesHealth){let r=resolveBuiltinChecks(t);return n(e)?t?.health?.enabled===!0?r.map(e=>e.name===To.name?{...To,required:!0}:e):withHealthCheck(r,{...To,required:!0}):r}function staleChecksAddNames(e,t=e?.checks?.add??[]){if(t.length===0)return[];let n=new Set(resolveBuiltinChecks(e).map(e=>e.name));return t.filter(e=>n.has(e)||n.has(legacyCharsAlias(e)??``))}function shouldSkip(e,t){return t.size!==0&&P.isMatch(e,[...t])}function coveringStepBodies(e,t){if(e===`lint`){let e=t[`lint:report`]??t.lint;return e===void 0?[]:[e]}if(e===`test`)return[t.test,t[`test:coverage`]].filter(e=>e!==void 0);let n=t[e];return n===void 0?[]:[n]}function coveredChecksAddEntries(e,t){let n=e?.checks?.add??[];if(n.length===0)return[];let r=new Set(staleChecksAddNames(e,n)),i=new Set(e?.checks?.skip??[]),a=n.filter(e=>!r.has(e)&&!shouldSkip(e,i));if(a.length===0)return[];let o=resolveBuiltinChecks(e).map(e=>e.name),s=[];for(let e of a){let n=[.../* @__PURE__ */ new Set([...o,...a.filter(t=>t!==e)])].filter(e=>!shouldSkip(e,i)),r=new RegExp(String.raw`(?:^|[\s/])${escapeRegex(e)}(?=\s|$)`),c;for(let i of n){for(let n of coveringStepBodies(i,t)){let t=commandSegments(n).find(e=>r.test(e));if(t!==void 0){c={name:e,coveredBy:i,fragment:t};break}}if(c)break}c&&s.push(c)}return s}function coverageModeFromFlags(e,t){return e===!1?`off`:e===!0||t?`on`:`auto`}function decideCoverage(e,t,n){let r=t.coverage??`auto`;if(r===`on`)return{enabled:!0,source:`flag`};if(r===`off`)return{enabled:!1,source:`flag`};let i=n?.coverage;if(i!==!1&&i?.gateOnPullRequests===!0)return{enabled:!0,source:`config`};let a=Object.hasOwn(t,`currentBranch`)?t.currentBranch:resolveCurrentBranch({cwd:e}),o=t.defaultBranch??resolveDefaultBranch({cwd:e});return{enabled:a!==void 0&&a===o,source:`branch`}}function defaultGetScripts(e){try{let t=parsePackageJson(p(w.join(e,`package.json`),`utf-8`));return new Set(Object.keys(t?.scripts??{}))}catch{return/* @__PURE__ */ new Set}}const rawLog$2=e=>console.log(e);function failedRunSkippedLine(e){return e.length===0?null:`Skipped: ${e.join(`, `)}`}function passedSummary(e,t){let n=[...e.length>0?[`${String(e.length)} advisory: ${e.map(e=>e.name).join(`, `)}`]:[],...t.length>0?[`skipped: ${t.join(`, `)}`]:[]];return n.length===0?`All checks passed`:`All checks passed (${n.join(`; `)})`}function skippedLine(e){return`Skipped (${e.source}): ${e.steps.join(`, `)}`}const Oo={groupStart:e=>rawLog$2(`::group::${e}`),groupEnd:()=>rawLog$2(`::endgroup::`),passed:(e,t)=>rawLog$2(`[ok] ${e} (${t}s)`),warned:(e,t,n)=>{rawLog$2(`[warn] ${e} (${t}s): ${String(n)} advisory finding(s)`),rawLog$2(`::warning::${e}: ${String(n)} advisory finding(s)`)},failed:(e,t)=>{rawLog$2(`[x] ${e} (${t}s)`),rawLog$2(`::error::${e} failed`)},undefinedCheck:e=>rawLog$2(`::error::${e} not defined in package.json`),requiredByConfigSkip:e=>rawLog$2(`::error::${e} is required by the default branch's health gate; checks.skip cannot skip it (--skip still can)`),skipped:e=>{for(let t of e)rawLog$2(skippedLine(t))},skippedNotDefined:e=>rawLog$2(`Skipped (not defined): ${e.join(`, `)}`),allPassed:(e,t)=>rawLog$2(`[ok] ${passedSummary(e,t)}`),anyFailed:(e,t)=>{let n=failedRunSkippedLine(t);n!==null&&rawLog$2(n),rawLog$2(`::error::Failed checks: ${e.join(`, `)}`)}},ko={groupStart:e=>{},groupEnd:()=>{},passed:e=>F.success(e),warned:(e,t,n)=>F.warn(`${e}: ${String(n)} advisory finding(s)`),failed:e=>F.error(`${e} failed`),undefinedCheck:e=>F.error(`${e} not defined in package.json`),requiredByConfigSkip:e=>F.error(`${e} is required by the default branch's health gate; checks.skip cannot skip it (--skip still can)`),skipped:e=>{for(let t of e)F.info(skippedLine(t))},skippedNotDefined:e=>F.info(`Skipped (not defined): ${e.join(`, `)}`),allPassed:(e,t)=>F.success(passedSummary(e,t)),anyFailed:(e,t)=>{let n=failedRunSkippedLine(t);n!==null&&F.info(n),F.error(`Failed checks: ${e.join(`, `)}`)}};function reportSkipped(e,t,n,r,i){let a=groupSkippedSteps(t,n,r,i);return e.skipped(a),a.flatMap(e=>e.steps)}function reportSkippedUnlessRefused(e,t,n,r,i){return reportSkipped(e,t.filter(e=>!requiredSkipIsRefused(e,r,i)).map(e=>e.name),n,r,i)}function requiredSkipIsRefused(e,t,n){return e.required===!0&&shouldSkip(e.name,n)&&!shouldSkip(e.name,t)}function logCoverageChoice(e,t,n,r){t.enabled&&!n&&t.source===`flag`&&F.warn(`--with-coverage requested but test:coverage script is not defined; falling back to test`),t.enabled&&!n&&t.source===`config`&&F.warn(`coverage.gateOnPullRequests is set but test:coverage script is not defined; falling back to test`),debug(e,`Coverage: ${r??`auto`} (source: ${t.source}) -> ${n?`test:coverage`:`test`}`)}function withLegacyCharsScript(e){let t=new Set(e);return!t.has(Eo.name)&&e.has(Do)&&t.add(Eo.name),t}function withAddedChecks(e,t){let n=new Set(e.map(e=>e.name));function isBuiltInName(e){if(n.has(e))return!0;let t=legacyCharsAlias(e);return t!==void 0&&n.has(t)}return[...e,...t.filter(e=>!isBuiltInName(e)).map(e=>({name:e}))]}function scriptNameFor(e,t,n){return e===`test`&&n?`test:coverage`:e===`lint`&&t.has(`lint:report`)?`lint:report`:e===Eo.name&&!t.has(Eo.name)&&t.has(Do)?Do:e}async function runRunChecks(e,t={}){let n=t.execCommand??execStep,r=t.getScripts??defaultGetScripts,i=t.toolingConfig??loadToolingConfig(e),a=i?.checks,o=withLegacyCharsSkip(t.skip??[]),s=withLegacyCharsSkip(a?.skip??[]),c=/* @__PURE__ */ new Set([...o,...s]),l=[.../* @__PURE__ */ new Set([...t.add??[],...a?.add??[]])],u=!!process.env.CI,d=t.failFast??!u,f=u?Oo:ko,p={verbose:t.verbose??!1},m=r(e),h=withLegacyCharsScript(m),g=new Set(l),_=withAddedChecks(resolveRunBuiltins(e,i,t.referenceEnablesHealth),l),v=[],y=[],b=[],x=decideCoverage(e,t,i),S=x.enabled&&m.has(`test:coverage`);logCoverageChoice(p,x,S,t.coverage);let C=reportSkippedUnlessRefused(f,_,h,o,s);for(let t of _){if(shouldSkip(t.name,c)){if(requiredSkipIsRefused(t,o,s)&&(f.requiredByConfigSkip(t.name),v.push(t.name),d))return 1;continue}if(!h.has(t.name)){g.has(t.name)||t.required===!0?(f.undefinedCheck(t.name),v.push(t.name)):b.push(t.name);continue}let r=scriptNameFor(t.name,m,S),i=t.args?`pnpm run ${r} ${t.args}`:`pnpm run ${r}`;debug(p,`Running: ${i} (in ${e})`),f.groupStart(t.name);let a=Date.now(),l=await n(i,e),u=((Date.now()-a)/1e3).toFixed(1);if(f.groupEnd(),debug(p,`${t.name}: exit code ${String(l.exitCode)}, ${u}s`),l.exitCode===0){let e=l.lastMarkerLine===null?null:parseWarnMarkerLine(l.lastMarkerLine);e===null?f.passed(t.name,u):(f.warned(t.name,u,e),y.push({name:t.name,count:e}))}else if(f.failed(t.name,u),v.push(t.name),d)return 1}return b.length>0&&f.skippedNotDefined(b),v.length>0?(f.anyFailed(v,C),1):(f.allPassed(y,C),0)}const Ao=withCharsCheck(withHealthCheck(wo)).map(e=>e.name).join(`, `),jo=A({meta:{name:`checks:run`,description:`Run the repo's standard check pipeline. The steps are ${Ao} (chars:check runs unless .tooling.json#chars.enabled is false, and health:check only where .tooling.json enables it). A step that exits 0 and prints ::bst-checks:: warn <count> on stdout is reported as warned; no exit code changes.`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Target directory (default: current directory)`,required:!1},skip:{type:`string`,description:`Comma-separated globs of checks to skip (${Ao}). Repeatable; every occurrence UNIONS, with each other and with .tooling.json#checks.skip`,required:!1},add:{type:`string`,description:"Comma-separated extra check names to run via `pnpm run <name>`. Repeatable; every occurrence UNIONS, with each other and with .tooling.json#checks.add; an added check with no matching script is a hard failure",required:!1},"fail-fast":{type:`boolean`,description:`Stop on first failure (default: true in dev, false in CI)`,required:!1},verbose:{type:`boolean`,description:`Emit detailed debug logging`,required:!1},"with-coverage":{type:`boolean`,description:`Force the test step to run with coverage (pnpm run test:coverage); overrides branch detection`,required:!1},coverage:{type:`boolean`,description:`Force the test step to run with coverage; --no-coverage forces it to run without. With neither, coverage is branch-aware (on for the default branch only, or for every branch when .tooling.json#coverage.gateOnPullRequests is set)`,required:!1}},async run({args:e,rawArgs:t}){let n=w.resolve(e.dir??`.`),r=parseListFlag(t,`skip`),i=parseListFlag(t,`add`),a=r.length>0?new Set(r):void 0,o=i.length>0?i:void 0,s=e[`fail-fast`]?!0:void 0,c=e.verbose===!0||isEnvVerbose(),l=coverageModeFromFlags(typeof e.coverage==`boolean`?e.coverage:void 0,e[`with-coverage`]===!0),u=loadToolingConfig(n),d=u?.defaultBranch,f=await runRunChecks(n,{skip:a,add:o,failFast:s,verbose:c,coverage:l,defaultBranch:d,toolingConfig:u});process.exitCode=f}}),Mo=[`.forgejo/workflows/`,`.github/workflows/`];function isWorkflowDirPath(e){return Mo.some(t=>e.startsWith(t))}const No=/\bapt(?:-get)?(?:\s+-\S+)*\s+install\b/g,Po=/&&|\|\||;|\|/;function workflowFiles(e){let t=[];for(let n of Mo){let r;try{r=h(w.join(e,n))}catch{continue}for(let i of r){if(!/\.ya?ml$/.test(i))continue;let r=`${n}${i}`;isReadableFile$1(w.join(e,r))&&t.push(r)}}return t}function isReadableFile$1(e){try{return b(e).isFile()}catch{return!1}}function readText(e){try{return p(e,`utf8`)}catch{return null}}function logicalLines(e){let t=[],n=``;for(let r of e){if(r.trim().startsWith(`#`))continue;let e=r.trimEnd();e.endsWith(`\\`)?n+=`${e.slice(0,-1)} `:(t.push(n+r),n=``)}return n!==``&&t.push(n),t}function packagesIn(e){let t=[];for(let n of e.matchAll(No)){let r=e.slice(n.index+n[0].length).split(Po)[0]??``;for(let e of r.split(/\s+/))e===``||e.startsWith(`-`)||t.push(e)}return t}function installsWithApt(e){return e.search(No)!==-1}function findWorkflowAptSteps(e){let t=[];for(let n of workflowFiles(e)){let r=readText(w.join(e,n));if(r===null||isToolingIgnored(r))continue;let i=!1,a=/* @__PURE__ */ new Set;for(let e of extractCustomBlocks(r))for(let t of logicalLines(e.lines))if(installsWithApt(t)){i=!0;for(let e of packagesIn(t))a.add(e)}i&&t.push({file:n,packages:[...a]})}return t.toSorted((e,t)=>e.file.localeCompare(t.file))}function runReleaseTargetGate(e,t){let n=releaseTargetConflict(e.stack,e.releaseStrategy,t);return n?(F.error(`releaseStrategy "simple" bumps package.json, but this repo's version-of-record is ${n}. A release would tag a version the ${n} artifact never gets. Release this repo through its own toolchain, or set releaseStrategy away from "simple".`),!0):!1}function runComposeLintGate(e,t,n){let r=lintComposeFiles(e,t);for(let e of r)F.error(e.message);for(let r of findDockerRebuildRisks(e,t,n))F.warn(r);return r.length}function runCheckOnlyImageGate(e,t,n,r){if(!e.publishDocker)return[];let i=[];for(let e of findCheckOnlyPublishRisks(t,r,n))F.warn(`Image "${e.imageName}" is declared only in ${e.declaredIn}, the check overlay, so a later tooling release stops publishing it with docker:publish by default. Keep it: set publish to true for "${e.imageName}" under .tooling.json#docker. Settle it: set publish to false there, or move the service into a base compose file.`),i.push(e.imageName);return i}function runWorkflowAptGate(e){let t=findWorkflowAptSteps(e);for(let e of t){let t=e.packages.length>0?e.packages.join(`, `):`packages`;F.warn(`${e.file} installs ${t} with apt in a custom block. The agent's containers cannot run that step, so its runs lack what CI has. Declare each tool in mise.toml as conda:<name> (both CI and the agent install from it), then remove the apt step.`)}return t}function findInertAgentKeys(e){let t=e?.agent;return!t||t.enabled===!0?[]:Object.keys(t).filter(e=>e!==`enabled`).toSorted()}function runInertAgentSettingsGate(e){let t=findInertAgentKeys(e);return t.length===0?[]:(F.warn(`.tooling.json sets ${t.map(e=>`agent.${e}`).join(`, `)}, but agent.enabled is not true, so the agent ignores them. Run \`pnpm exec bst setup:agent\` to enable the agent, or remove those keys.`),t)}function runPublishConfigGate(e,t){if(!e.publishNpm)return 0;let n=lintPublishConfig(t,e.structure);for(let e of n)F.error(e.message);return n.length}const Fo=/* @__PURE__ */ new Set([`simple`,`changesets`]);function warnInertVersionStamp(e,t){e!==0&&(Fo.has(t)||F.warn(`.tooling.json#versionStamp is configured, but releaseStrategy "${t}" emits no release-assets step, so nothing ever stamps the file and the released artifact keeps its committed placeholder version. Release through "simple" or "changesets", or remove the block.`))}function runVersionStampGate(e,t,n){let r=e?.versionStamp??[];warnInertVersionStamp(r.length,n);let i=0;for(let e of r){let n=w.resolve(t,e.file);if(!o(n)){F.error(`versionStamp: ${e.file} does not exist (resolved to ${n}).`),i++;continue}let r;try{r=p(n,`utf-8`)}catch(t){let n=t instanceof Error?t.message:String(t);F.error(`versionStamp: ${e.file} could not be read: ${n}`),i++;continue}let a=describeStampProblem(r,e);a&&(F.error(`versionStamp: ${a}`),i++)}return i}function describeAssetEntry(e,t){let n=e.file??(e.files===void 0?``:e.files.join(`, `));return n===``?`releaseAssets[${String(t)}]`:`releaseAssets[${String(t)}] ("${n}")`}function readPreTag(e){try{return parsePreTag(p(w.join(e,lo),`utf-8`))}catch{return}}function runSnapshotConfigGate(e,t,n){let r=0,i=e?.releaseAssets??[];for(let[e,t]of i.entries())t.file===void 0==(t.files===void 0)&&(F.error(`.tooling.json ${describeAssetEntry(t,e)} sets ${t.file===void 0?`neither`:`both`} file and files. Exactly one names the asset: keep file for a single path, or files for the globs the build writes.`),r++);let a=e?.snapshot;if(!a)return r;let o=readPreTag(t);o!==void 0&&o===a.preid&&(F.error(`.tooling.json#snapshot.preid "${a.preid}" equals the tag in .changeset/pre.json, so a snapshot would look like a build of the pre release line. Pick a different preid.`),r++);let s=getMonorepoPackages(t).map(e=>e.name);if(n!==`monorepo`){let e=readPackageJson(t)?.name;e!==void 0&&s.push(e)}let c=a.packages;(c===void 0||c.length===0)&&n===`monorepo`&&(F.error(`.tooling.json#snapshot is set on a monorepo but names no packages, and bst will not choose them for you: most monorepos have packages nobody installs from a snapshot. List the ones to snapshot under snapshot.packages. This repo has: ${s.length===0?`none under packages/`:s.join(`, `)}.`),r++);for(let e of c??[])s.includes(e)||(F.error(`.tooling.json#snapshot.packages names "${e}", which has no package.json behind it. release:snapshot resolves every name to a package directory, and would fail mid-publish over this one. Fix the name or drop it. This repo has: ${s.join(`, `)}.`),r++);if(n!==`monorepo`)return r;for(let[e,t]of i.entries())t.package===void 0&&(F.error(`.tooling.json ${describeAssetEntry(t,e)} names no package, but snapshot is set on a monorepo and a snapshot is cut per package, so it must know which package this asset serves. Set package to the package it serves (this repo has: ${s.join(`, `)}).`),r++);for(let[t,n]of(e?.versionStamp??[]).entries())n.package===void 0&&(F.error(`.tooling.json versionStamp[${String(t)}] ("${n.file}") names no package, but snapshot is set on a monorepo and a stamp carries the version of the release it belongs to. Set package to the package whose release it stamps (this repo has: ${s.join(`, `)}).`),r++);return r}const Io=N.looseObject({privatePackages:N.union([N.boolean(),N.looseObject({version:N.boolean().optional(),tag:N.boolean().optional()})]).optional()});function changesetsTagsPrivatePackages(e){let t=w.join(e,`.changeset`,`config.json`);if(!o(t))return;let n;try{n=JSON.parse(p(t,`utf-8`))}catch{return}let r=Io.safeParse(n);if(!r.success)return;let i=r.data.privatePackages;return i===void 0?!1:typeof i==`boolean`?i:i.tag===!0}function runPrivateReleaseAdvisory(e,t,n){if(e.ci!==`github`||e.releaseStrategy!==`changesets`)return[];let r=[],i=`Set "privatePackages": { "version": true, "tag": true } in .changeset/config.json`;if(e.structure===`monorepo`){if(changesetsTagsPrivatePackages(n)===!0)return[];let e=getMonorepoPackages(n);for(let n of t?.snapshot?.packages??[]){let t=e.find(e=>e.name===n);if(t===void 0||readPackageJson(t.dir)?.private!==!0)continue;let a=`.tooling.json#snapshot.packages names "${n}", whose package.json is private. Its snapshots ship, because bst cuts them itself, but changesets skips a private package, so its stable releases never will. ${i}, or drop "${n}" from snapshot.packages.`;F.warn(a),r.push(a)}return r}if(readPackageJson(n)?.private!==!0||changesetsTagsPrivatePackages(n)!==!1)return[];let a=`The root package is private, and .changeset/config.json never turns privatePackages.tag on, so changesets skips it: this repo versions nothing, tags nothing and publishes nothing. ${i}, or drop "private": true from package.json.`;return F.warn(a),r.push(a),r}function warnStaleChecksAdd(e){let t=staleChecksAddNames(e);t.length!==0&&F.warn(`.tooling.json#checks.add names built-in step(s) checks:run already runs: ${t.join(`, `)}. The entries are deduplicated at run time and do nothing -- remove them.`)}function warnUnconfiguredDefaultBranch(e,t,n=defaultGitRunner){if(t?.defaultBranch!==void 0)return;let r=n([`symbolic-ref`,`--short`,`refs/remotes/origin/HEAD`],e);if(r===void 0)return;let i=r.startsWith(`origin/`)?r.slice(7):r;i!==``&&i!==`main`&&F.warn(`origin/HEAD names "${i}", but .tooling.json sets no defaultBranch, so the generated CI workflow triggers on "${Ni}" and gates its release steps there. Set .tooling.json#defaultBranch to "${i}" and run pnpm exec bst repo:sync.`)}function warnCoveredChecksAdd(e,t){let n=coveredChecksAddEntries(e,readPackageJson(t)?.scripts??{});for(let e of n)F.warn(`.tooling.json#checks.add entry "${e.name}" is already run by the "${e.coveredBy}" step's script ("${e.fragment}"), so every pipeline run executes it twice. Remove the add entry, or drop the inline invocation from the "${e.coveredBy}" script.`)}const Lo=N.record(N.string(),N.union([N.string(),N.unknown()]));function readDeclaredTools(e){let t;try{t=p(e,`utf-8`)}catch{return}let n;try{n=Me(t)}catch{return}let r=N.looseObject({tools:N.unknown().optional()}).safeParse(n);if(!r.success)return;let i=Lo.safeParse(r.data.tools??{});if(!i.success)return;let a={};for(let[e,t]of Object.entries(i.data))typeof t==`string`&&(a[e]=t);return a}const Ro=N.looseObject({version:N.string(),install_path:N.string(),installed:N.boolean()}),zo=N.record(N.string(),N.array(Ro));function miseIsAbsent(e){let t=ve.sync(`mise`,[`--version`],{cwd:e}).error;return t instanceof Error&&`code`in t&&t.code===`ENOENT`}function normalizeVersionOutput(e){return e.trim().replace(/^v/,``)}const Bo='(`eval "$(mise activate bash)"`, `mise activate bash --shims`, or `mise exec`)';function describeFailedProbe(e){if(e.error)return e.error.message;let t=(e.stderr?.toString()??``).trim().split(`
|
|
6053
|
-
`)[0]??``;return`exited ${String(e.status)}${t?`: ${t}`:``}`}function liveVersionMismatch(e,t,n,r){let i=ve.sync(t,[`--version`],{cwd:e}),a=i.status===0&&i.stdout?normalizeVersionOutput(i.stdout.toString()):void 0;if(a===r)return!1;let o=a===void 0?`failed (${describeFailedProbe(i)})`:`reports ${a}`;return
|
|
6054
|
-
`).length-1;
|
|
6051
|
+
`)){if(e.trim().length===0)continue;let t;try{t=JSON.parse(e)}catch{continue}let n=io.safeParse(t);n.success&&i.push({id:n.data.id,name:n.data.name,createdMs:Date.parse(n.data.created)})}return i}function resourceIds(e,t,n){let r=e.exec(`docker`,[t,`ls`,`-q`,`--filter`,`label=com.docker.compose.project=${n}`]);return r.exitCode===0?r.stdout.split(`
|
|
6052
|
+
`).map(e=>e.trim()).filter(e=>e.length>0):[]}function runSweep(e,t={}){let n=t.dryRun??!1,r={containers:[],networks:[],volumes:[],failed:[],dryRun:n},i=selectSweepTargets(listSweepCandidates(e),{nowMs:e.now(),maxAgeMs:t.maxAgeMs??144e5});for(let t of i){if(e.log(`${n?`Would reclaim`:`Reclaiming`} leaked container ${t.name}`),n){r.containers.push({id:t.id,name:t.name});continue}let i=e.exec(`docker`,[`rm`,`-f`,`-v`,t.id]);i.exitCode===0?r.containers.push({id:t.id,name:t.name}):recordFailure(e,r,`container`,t.name,i)}let a=[...new Set(i.map(e=>e.project).filter(e=>e!==null))];for(let t of a)for(let i of[`network`,`volume`]){let a=resourceIds(e,i,t);if(a.length===0)continue;e.log(`${n?`Would reclaim`:`Reclaiming`} ${i}(s): ${a.join(`, `)}`);let o=i===`network`?r.networks:r.volumes;for(let t of a){if(n){o.push(t);continue}let a=e.exec(`docker`,[i,`rm`,t]);a.exitCode===0?o.push(t):recordFailure(e,r,i,t,a)}}let o=selectSweepNetworks(listLabelledNetworks(e),{nowMs:e.now(),maxAgeMs:t.maxAgeMs??144e5});for(let t of o){if(r.networks.some(e=>t.id.startsWith(e)||e.startsWith(t.id)))continue;if(e.log(`${n?`Would reclaim`:`Reclaiming`} network: ${t.id}`),n){r.networks.push(t.id);continue}let i=e.exec(`docker`,[`network`,`rm`,t.id]);i.exitCode===0?r.networks.push(t.id):recordFailure(e,r,`network`,t.id,i)}return r}function recordFailure(e,t,n,r,i){let a=i.stderr.trim()||`docker exited ${String(i.exitCode)}`;t.failed.push({kind:n,ref:r,error:a}),e.log(`Could not reclaim ${n} ${r}: ${a}`)}function readFileOrNull(e){try{return p(e,`utf-8`)}catch{return null}}function detectComposeFiles(e){let t=resolveComposeFileSet(readFileOrNull,e);return{dir:t.composeDir,files:t.files}}function crossReferenceDockerImages(e,t){let n=extractComposeImageNames(t),r=new Set(extractComposeBuildDockerfiles(t)),i=[];for(let t of e){let e=n.some(e=>e===t.imageName||e.endsWith(`/${t.imageName}`)),a=r.has(t.dockerfileAbs);!e&&!a?i.push({kind:`unreferenced`,dir:t.dir,imageName:t.imageName}):a&&!e&&i.push({kind:`rebuild-no-image`,dir:t.dir,imageName:t.imageName})}return i}function findDockerRebuildRisks(e,t,n=createDockerDiscoveryMemo()){let r=t?.dockerCheck;if(r===!1)return[];let i=createFileReader(),a=i.readFile(w.join(e,`package.json`)),o=a?parsePackageJson(a):void 0;if(!o?.name)return[];let s=n.detect(i,e,o.name);if(s.length===0)return[];let c=computeCheckDefaults(e),l=r?.composeFiles??c.composeFiles??[];if(l.length===0)return[];let u=parseComposeServices(c.composeCwd??e,checkComposeFiles(l,c.checkOverlay));return crossReferenceDockerImages(s.map(t=>({dir:t.dir,imageName:t.imageName,dockerfileAbs:w.resolve(e,t.docker.dockerfile)})),u).filter(e=>e.kind===`rebuild-no-image`).map(e=>`Docker package "${e.dir}" is built by a compose service with no \`image: ${e.imageName}\`.\n docker:build tags ${e.imageName}:latest, but compose tags its own build separately,\n so the Dockerfile builds twice and docker:check cannot reuse the docker:build output.\n Fix: add \`image: ${e.imageName}\` to that service (skip if it builds a variant on purpose).`)}function findCheckOnlyPublishRisks(e,t=En,n=createDockerDiscoveryMemo()){if(t===`enforce`)return[];let r=createFileReader(),i=r.readFile(w.join(e,`package.json`)),a=i?parsePackageJson(i):void 0;if(!a?.name)return[];let o=[];for(let i of n.detect(r,e,a.name,t))i.checkOnlyIn!==void 0&&i.docker.publish===void 0&&o.push({imageName:i.imageName,declaredIn:i.checkOnlyIn});return o}function isLocallyBuiltService(e,t){if(!e.image)return!1;let n=bareImageName(e.image);if(!n)return!1;if(t.has(n))return!0;for(let e of t)if(n.endsWith(`/${e}`))return!0;return!1}function deriveHealthChecks(e){let t=[];for(let n of e)n.hasHealthcheck||n.containerPort!==void 0&&t.push({name:n.name,url:`http://localhost:${String(n.containerPort)}/`,viaNetworkService:n.name});return t}function detectCheckOverlay(e,t){let n=deriveCheckOverlayName(t);return o(w.join(e,n))?n:void 0}function checkComposeFiles(e,t){return t===void 0||e.includes(t)?e:[...e,t]}function parseCheckComposeServices(e,t,n){return parseComposeServices(e,checkComposeFiles(t,n))}function detectCheckEnvFile(e){if(o(w.join(e,`docker-compose.check.env`)))return`docker-compose.check.env`}function composeEnvFileValue(e,t,n){let r;try{r=p(w.join(e,t),`utf-8`)}catch{return}let i=RegExp(`^(?:export\\s+)?${n}\\s*=(.*)$`);for(let e of r.split(/\r?\n/)){let t=e.trim();if(t.startsWith(`#`))continue;let n=i.exec(t);if(n){let e=n[1]?.trim()??``;return/^(["']).*\1$/.test(e)?e.slice(1,-1):e}}}const ao={interval:`5s`,timeout:`5s`,retries:12,start_period:`10s`,start_interval:`5s`};function generateCheckOverlay(e,t=[]){let n=new Set(t),r={};for(let t of e){let e={restart:`no`};e.labels={[eo]:`1`},t.hasHealthcheck&&(e.healthcheck={...ao}),isLocallyBuiltService(t,n)&&(e.pull_policy=`never`),r[t.name]=e}return ke({services:r,networks:{default:{labels:{[eo]:`1`}}}})}const oo=[`interval`,`timeout`,`retries`,`start_period`,`start_interval`],so=P.looseObject({interval:P.unknown().optional(),timeout:P.unknown().optional(),retries:P.unknown().optional(),start_period:P.unknown().optional(),start_interval:P.unknown().optional()});function findOverlayHealthcheckTimingOverrides(e,t){if(t===void 0)return[];let n;try{let r=p(w.join(e,t),`utf-8`);n=hn.safeParse(parseComposeYaml(r))}catch{return[]}if(!n.success||!n.data.services)return[];let r=[];for(let[e,t]of Object.entries(n.data.services)){let n=so.safeParse(t.healthcheck);n.success&&oo.some(e=>n.data[e]!==void 0)&&r.push(e)}return r}function detectSmoketest(e){try{if(parsePackageJson(p(w.join(e,`package.json`),`utf-8`))?.scripts?.[`test:smoke`])return[`pnpm`,`test:smoke`]}catch{}}function computeCheckDefaults(e){let{dir:t,files:n}=detectComposeFiles(e);if(n.length===0)return{};let r=n[0],i=r?detectCheckOverlay(t,r):void 0,a=detectCheckEnvFile(t),o=parseComposeServices(t,checkComposeFiles(n,i)).filter(startsUnderCheckProfile),s=deriveHealthChecks(o),c=detectSmoketest(e);return{composeCwd:t===e?void 0:t,composeFiles:n,checkOverlay:i,envFile:a,services:o.map(e=>e.name),healthChecks:s.length>0?s:void 0,smoketest:c}}function createFileReader(){return{listPackageDirs(e){let t=w.join(e,`packages`);try{return h(t,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}},readFile(e){try{return p(e,`utf-8`)}catch{return null}}}}const co=`.changeset/pre.json`,lo=P.looseObject({tag:P.string()});function parsePreTag(e){try{let t=lo.safeParse(JSON.parse(e));return t.success?t.data.tag:void 0}catch{return}}const uo=`::bst-checks::`,fo=RegExp(`^${uo} warn (\\d+)\\s*$`);function formatWarnMarker(e){return`${uo} warn ${String(e)}`}function parseWarnMarkerLine(e){let t=fo.exec(e);if(t===null)return null;let n=Number.parseInt(t[1]??``,10);return Number.isNaN(n)?null:n}const po=/* @__PURE__ */ RegExp(`^::bst-health:: measure (\\d+)\\s*$`);function parseMeasureMarkerLine(e){let t=po.exec(e);if(t===null)return;let n=Number.parseInt(t[1]??``,10);return Number.isNaN(n)?void 0:n}function readMeasureMarker(e){let t;for(let n of e.split(`
|
|
6053
|
+
`)){let e=parseMeasureMarkerLine(n);e!==void 0&&(t=e)}return t}const mo=2e3,ho={lines:[],totalLines:0};function createStreamTail(e){let t=new je(`utf-8`),n=[],r=``,i=0;function record(t){let r=t.endsWith(`\r`)?t.slice(0,-1):t;i+=1,e?.(r),n.push(r.length>2e3?r.slice(0,mo):r),n.length>400&&n.shift()}return{write(e){let n=(r+t.write(e)).split(`
|
|
6054
|
+
`);r=n.pop()??``,r.length>2e3&&(r=r.slice(0,mo));for(let e of n)record(e)},flush(){r+=t.end(),r!==``&&record(r),r=``},tail(){return i===0?ho:{lines:n,totalLines:i}}}}function execStep(e,t,n=process.stdout,r=process.stderr){return new Promise(i=>{let a=fe(e,{cwd:t,shell:!0,stdio:[`inherit`,`pipe`,`pipe`],env:process.stdout.isTTY||process.stderr.isTTY?{...process.env,FORCE_COLOR:`1`}:process.env}),o=null,s=createStreamTail(e=>{e.startsWith(`::bst-checks::`)&&(o=e)}),c=createStreamTail();a.stdout?.on(`data`,e=>{n.write(e),s.write(e)}),a.stderr?.on(`data`,e=>{r.write(e),c.write(e)}),a.on(`error`,()=>{i({exitCode:1,lastMarkerLine:o,stdout:s.tail(),stderr:c.tail()})}),a.on(`close`,e=>{s.flush(),c.flush(),i({exitCode:e??1,lastMarkerLine:o,stdout:s.tail(),stderr:c.tail()})})})}const go=/^@bensandee\/[\w-]+ v\S+( \([^)]*\))?$/;function isStderrNoise(e){return e.startsWith(`$ `)||go.test(e)}function isStdoutNoise(e){return/^\[?ELIFECYCLE\]? /.test(e)||e.startsWith(`ERR_PNPM_`)}function cleanLines(e,t){let n=e.lines.map(e=>ie(e)).filter(e=>!t(e)),r=0,i=n.length;for(;r<i&&n[r].trim()===``;)r+=1;for(;i>r&&n[i-1].trim()===``;)--i;return n.slice(r,i)}function excerptOf(e,t,n,r,i){let a=n.length>r?n.slice(n.length-r):n;return{name:e,stream:t,excerpt:a,truncatedLines:Math.max(0,i-a.length)}}function buildStepFailure(e,t){let n=cleanLines(t.stderr,isStderrNoise);if(n.length>0)return excerptOf(e,`stderr`,n,150,t.stderr.totalLines);let r=cleanLines(t.stdout,isStdoutNoise);return r.length>0?excerptOf(e,`stdout`,r,60,t.stdout.totalLines):{name:e,stream:`none`,excerpt:[],truncatedLines:0}}function neutralizeLine(e){return` | ${e.replaceAll(`Failed checks: `,`Failed checks (quoted): `)}`}function renderDigest(e){let t=[`Failure digest:`];for(let n of e)if(n.stream===`none`)t.push(`--- ${n.name} failed: no output ---`),t.push(neutralizeLine(`(no output)`));else{t.push(`--- ${n.name} failed: last ${String(n.excerpt.length)} lines of ${n.stream} ---`),n.truncatedLines>0&&t.push(neutralizeLine(`(${String(n.truncatedLines)} earlier lines are in the ${n.name} group above)`));for(let e of n.excerpt)t.push(neutralizeLine(e))}return t}const _o=`.bst/check-failures.json`,vo=P.object({name:P.string(),stream:P.enum([`stderr`,`stdout`,`none`]),excerpt:P.array(P.string()),truncatedLines:P.number().int().min(0)}),yo=P.object({version:P.literal(1),failures:P.array(vo)});function recordFailures(e,t){let n=w.join(e,_o);if(t.length===0){y(n,{force:!0});return}let r=yo.safeParse({version:1,failures:t});if(!r.success)throw new D(`a failure digest could not be serialized: ${r.error.message}`);u(w.dirname(n),{recursive:!0}),C(n,`${JSON.stringify(r.data,null,2)}\n`,`utf-8`)}function readFailures(e){let t=w.join(e,_o);if(!o(t))return{kind:`missing`};try{let e=yo.safeParse(JSON.parse(p(t,`utf-8`)));return e.success?{kind:`recorded`,failures:e.data.failures}:{kind:`unreadable`,reason:e.error.message}}catch(e){return{kind:`unreadable`,reason:e instanceof Error?e.message:String(e)}}}function matches(e,t){return t.size>0&&F.isMatch(e,[...t])}function groupSkippedSteps(e,t,n,r){let i={"--skip":[],"checks.skip":[]};for(let a of e)t.has(a)&&(matches(a,n)?i[`--skip`].push(a):matches(a,r)&&i[`checks.skip`].push(a));return[`--skip`,`checks.skip`].filter(e=>i[e].length>0).map(e=>({source:e,steps:i[e]}))}function matchesAny(e,t){return t.size>0&&e.some(e=>F.isMatch(e.name,[...t]))}function selectOnly(e,t){return{selected:e.filter(e=>matchesAny([e],t)).map(e=>e.name),unmatched:[...t].filter(t=>!matchesAny(e,/* @__PURE__ */ new Set([t])))}}function createRealHealthExecutor(e){return{exec(t,n,r){let i=execCapture$2(t,n,{cwd:r?.cwd??e,env:r?.env,input:r?.input,keepPartialStdoutOnKill:!1});return{stdout:i.stdout,stderr:i.stderr,exitCode:i.status}},readFile(t){let n=w.join(e,t);if(o(n))try{return p(n,`utf-8`)}catch{return}},readDir(t){let n=w.join(e,t);try{return h(n)}catch{return}},readDirRecursive(t,n){let r=[],walk=t=>{let i;try{i=h(w.join(e,t))}catch{return}for(let a of i){if(a===`node_modules`||a===`.git`||a===`dist`)continue;let i=w.join(t,a),o=!1;try{o=b(w.join(e,i)).isDirectory()}catch{o=!1}o?walk(i):(n.length===0||n.some(e=>a.endsWith(e)))&&r.push(i.replace(/\\/g,`/`))}};return walk(t),r}}}const bo=`health-baseline.json`,xo=`.tooling.json`;function repoPrefix(e,t){let n=e.exec(`git`,[`rev-parse`,`--show-prefix`],{cwd:t});return n.exitCode===0?n.stdout.trim():``}const So=P.object({defaultBranch:P.string().optional()});function parseDefaultBranchOverride(e){if(e===void 0||e.trim()===``)return;let t;try{t=JSON.parse(e)}catch{return}let n=So.safeParse(t);return n.success?n.data.defaultBranch:void 0}function resolveReferenceBranch(e,t,n,r){let i=gitRunner(e),a=ciDefaultBranch(r)??originHeadBranch(i,t),o=a??`main`,s=`refs/remotes/origin/${o}`;if(i([`rev-parse`,`--verify`,`--quiet`,s],t)!==void 0){let r=parseDefaultBranchOverride(showAt(e,t,s,`${n}${xo}`))??o;if(a!==void 0)return{branch:r};let i=parseDefaultBranchOverride(e.readFile(xo));return i===void 0||i===r?{branch:r}:{branch:r,warning:unconfirmedDefaultWarning(r,i)}}return a===void 0?{branch:parseDefaultBranchOverride(e.readFile(xo))??`main`}:{branch:o}}function originHeadBranch(e,t){let n=e([`symbolic-ref`,`--short`,`refs/remotes/origin/HEAD`],t);if(n===void 0)return;let r=n.startsWith(`origin/`)?n.slice(7):n;return r===``?void 0:r}function unconfirmedDefaultWarning(e,t){return`health: could not confirm the default branch, so the reference was read against origin/${e}, while .tooling.json#defaultBranch names ${t}. If ${t} is the repository's default branch, record it in this clone with \`git remote set-head origin --auto\`, or run in GitHub or Forgejo Actions, where the event payload names it.`}function gitRunner(e){return(t,n)=>{let r=e.exec(`git`,t,{cwd:n});if(r.exitCode!==0)return;let i=r.stdout.trim();return i===``?void 0:i}}function showAt(e,t,n,r){let i=e.exec(`git`,[`show`,`${n}:${r}`],{cwd:t});if(i.exitCode===0)return i.stdout}function readReference(e,t){let n=repoPrefix(e,t.cwd),{branch:r,warning:i}=resolveReferenceBranch(e,t.cwd,n,t.ciEvent),a=e.exec(`git`,[`merge-base`,`HEAD`,`origin/${r}`],{cwd:t.cwd}),o=a.stdout.trim();if(a.exitCode!==0||o===``)return{kind:`unavailable`,reason:`health: cannot read the reference at the merge base with origin/${r}. Run \`git fetch origin ${r}\` so the default branch is present (a shallow clone or a missing remote-tracking ref makes it absent), or set .tooling.json#defaultBranch on the default branch if it has another name -- once that branch is fetched, its own copy of the setting decides, not this branch's. health:check fails closed without a reference.`};let s=showAt(e,t.cwd,o,`${n}${bo}`),c=showAt(e,t.cwd,o,`${n}${xo}`),l=resolveHealthConfigFromContext({exists:e=>e===xo&&c!==void 0,read:e=>e===xo?c:void 0,config:{stack:t.stack}},{isMonorepo:t.isMonorepo}),u={mergeBase:o,prefix:n,baseline:s===void 0?void 0:parseHealthBaseline(s),health:l};return i===void 0?{kind:`read`,reference:u}:{kind:`read`,reference:u,warning:i}}function referenceEnablesHealth(e){try{let t=readReference(createRealHealthExecutor(e),{cwd:e,stack:`none`,isMonorepo:!1,ciEvent:processCiEventSource()});return t.kind===`read`&&t.reference.health.enabled&&t.reference.baseline!==void 0}catch{return!1}}const Co=[`fanInLimit`,`fanOutLimit`,`directoryFileLimit`,`moduleSizeLimit`,`tolerance`],wo=[`enabled`,`crossPackage`];function canonicalJson(e){return JSON.stringify(sortKeys(e))}const To=P.record(P.string(),P.unknown());function sortKeys(e){if(Array.isArray(e))return e.map(sortKeys);let t=To.safeParse(e);if(t.success){let e=Object.keys(t.data).toSorted(),n={};for(let r of e)n[r]=sortKeys(t.data[r]);return n}return e}function sizeRaises(e,t){let n=[];for(let[r,i]of Object.entries(e.baseline?.sizeBudgets??{})){if(t.baseline===void 0)continue;let e=t.baseline.sizeBudgets?.[r];e===void 0?t.health.sizeBudgets[r]!==void 0&&n.push({leaf:`sizeBudgets.${r}`,reference:String(i),current:`absent`}):e>i&&n.push({leaf:`sizeBudgets.${r}`,reference:String(i),current:String(e)})}for(let[r,i]of Object.entries(e.health.sizeBudgets)){let e=t.health.sizeBudgets[r];if(e===void 0){n.push({leaf:`health.sizeBudgets.${r}`,reference:`present`,current:`absent`});continue}let a=canonicalJson(i);a!==canonicalJson(e)&&n.push({leaf:`health.sizeBudgets.${r}`,reference:a,current:canonicalJson(e)})}return n}function findRaises(e,t){return[...baselineRaises(e,t),...sizeRaises(e,t),...configRaises(e.health,t.health)]}function baselineRaises(e,t){let n=[];for(let r of R){let i=e.baseline?.[r],a=t.baseline?.[r];i!==void 0&&a!==void 0&&a>i?n.push({leaf:r,reference:String(i),current:String(a)}):i!==void 0&&a===void 0&&t.baseline!==void 0&&(t.measured===void 0||t.measured.metrics[r]!==void 0)&&n.push({leaf:r,reference:String(i),current:`absent`})}for(let r of z){let i=t.measured?.ceilings[r]??{};for(let[a,o]of Object.entries(e.baseline?.moduleCeilings?.[r]??{}))t.baseline!==void 0&&t.baseline.moduleCeilings?.[r]?.[a]===void 0&&(t.measured===void 0||i[a]!==void 0)&&n.push({leaf:`moduleCeilings.${r}.${a}`,reference:String(o),current:`absent`})}for(let r of z){let i=t.baseline?.moduleCeilings?.[r];if(i!==void 0)for(let[t,a]of Object.entries(i)){let i=`moduleCeilings.${r}.${t}`,o=e.baseline?.moduleCeilings?.[r]?.[t];o===void 0?n.push({leaf:i,reference:`absent`,current:String(a)}):a>o&&n.push({leaf:i,reference:String(o),current:String(a)})}}return e.baseline!==void 0&&t.baseline===void 0&&n.push({leaf:bo,reference:`present`,current:`absent`}),n}function configRaises(e,t){let n=[];for(let r of rt){let i=t.exempt[r];if(i!==void 0)for(let t of Object.keys(i))e.exempt[r]?.[t]===void 0&&n.push({leaf:`health.exempt.${r}.${t}`,reference:`absent`,current:`present`})}for(let r of Co){let i=e[r],a=t[r];a>i&&n.push({leaf:`health.${r}`,reference:String(i),current:String(a)})}for(let r of t.exclude)e.exclude.includes(r)||n.push({leaf:`health.exclude.${r}`,reference:`absent`,current:`present`});for(let r of wo)e[r]&&!t[r]&&n.push({leaf:`health.${r}`,reference:`true`,current:`false`});return n}function branchDiffNames(e,t,n){let r=e.exec(`git`,[`diff`,`--name-only`,n],{cwd:t}),i=e.exec(`git`,[`ls-files`,`--others`,`--exclude-standard`,`--full-name`,`--`,`:/`],{cwd:t}),a=/* @__PURE__ */ new Set;for(let e of[r,i])for(let t of e.stdout.split(`
|
|
6055
|
+
`)){let e=t.trim();e!==``&&a.add(e)}return[...a].toSorted()}const X=6e4,Eo=3e5;function pickDefaultBranch(e,t){if(e!==void 0&&e!==``)return e;if(t!==void 0){let e=t.startsWith(`origin/`)?t.slice(7):t;if(e!==``)return e}return`main`}async function resolveOriginHead(e,t,n=null){let r=await e.run([`symbolic-ref`,`--short`,`refs/remotes/origin/HEAD`],{cwd:t,timeoutMs:X,signal:n});if(r.exitCode!==0)return;let i=r.stdout.trim();return i===``?void 0:i}async function currentBranch(e,t,n=null){let r=await e.run([`rev-parse`,`--abbrev-ref`,`HEAD`],{cwd:t,timeoutMs:X,signal:n}),i=r.stdout.trim();if(r.exitCode!==0||i===``)throw new T(`Could not determine the current branch -- is this a git repository?`);if(i===`HEAD`)throw new T(`HEAD is detached. Check out a feature branch first.`);return i}async function baseRef(e,t,n,r=null){let i=`origin/${n}`,a=await e.run([`rev-parse`,`--verify`,`--quiet`,i],{cwd:t,timeoutMs:X,signal:r});return a.exitCode===0&&a.stdout.trim()!==``?i:n}async function commitSubjects(e,t,n,r=null){return(await e.run([`log`,`--format=%s`,`${n}..HEAD`],{cwd:t,timeoutMs:X,signal:r})).stdout.split(`
|
|
6056
|
+
`).map(e=>e.trim()).filter(e=>e!==``)}async function commitMessages(e,t,n,r=null){let i=await e.run([`log`,`-z`,`--format=%B`,`${n}..HEAD`],{cwd:t,timeoutMs:X,signal:r});if(i.exitCode!==0)throw new T(`Failed to read commit messages: ${i.stderr||i.stdout}`);return i.stdout.split(`\0`).map(e=>e.trim()).filter(e=>e!==``)}async function hasUncommittedChanges(e,t,n=null){return(await e.run([`status`,`--porcelain`],{cwd:t,timeoutMs:X,signal:n})).stdout.trim()!==``}async function pushBranch(e,t,n,r,i=!1){let a=i?[`push`,`--force-with-lease`,`-u`,`origin`,n]:[`push`,`-u`,`origin`,n],o=await e.run(a,r===void 0?{cwd:t,timeoutMs:Eo,signal:null}:{cwd:t,env:r,timeoutMs:Eo,signal:null});if(o.exitCode!==0)throw new T(`Failed to push ${n}: ${o.stderr||o.stdout}`)}function resolveDefaultBranch(e){let t=e.configOverride;return t!==void 0&&t!==``?pickDefaultBranch(t,void 0):pickDefaultBranch(void 0,(e.git??defaultGitRunner)([`symbolic-ref`,`--short`,`refs/remotes/origin/HEAD`],e.cwd))}const Do=[`--help`,`-h`,`--version`,`-v`,`--verbose`,`--trace`],Oo=new Set(Do.map(flagName));function hasHelpFlag(e){return e.includes(`--help`)||e.includes(`-h`)}function isLoneVersionQuery(e){return e.length===1&&(e[0]===`--version`||e[0]===`-v`)}function splitAtCommand(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(r===`--`)return;if(r.startsWith(`-`))t!==void 0&&!r.includes(`=`)&&declaresValueFlag(r,t)&&n++;else return{index:n,before:e.slice(0,n)}}}function declaresValueFlag(e,t){let n=flagName(e),r=toCamelCase(n);for(let[e,i]of Object.entries(t)){if(i.type!==`string`&&i.type!==`enum`)continue;if(r===toCamelCase(e))return!0;let t=`alias`in i?i.alias:void 0;if(t!==void 0&&(Array.isArray(t)?t.includes(n):t===n))return!0}return!1}function flagBase(e){let t=e.indexOf(`=`);return t===-1?e:e.slice(0,t)}function flagName(e){return flagBase(e).replace(/^-{1,2}/,``)}function resolveStaticArgsDef(e){let t=e.args;if(t!==void 0&&typeof t!=`function`&&!(t instanceof Promise))return t}function toCamelCase(e){return e.replace(/-([a-z0-9])/g,(e,t)=>t.toUpperCase())}function toKebabCase(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase()}function buildParseTable(e){let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Map,r=new Set(Oo),i=[];for(let[a,o]of Object.entries(e)){if(o.type===`positional`)continue;o.type===`boolean`&&t.add(a);let e=`alias`in o?o.alias:void 0,s;s=e===void 0?[]:Array.isArray(e)?e:[e];let c=[...s],l=toCamelCase(a),u=toKebabCase(a);l!==a&&!c.includes(l)&&c.push(l),u!==a&&!c.includes(u)&&c.push(u),n.set(a,c),r.add(a);for(let e of c)r.add(e);i.push(`--${a}`)}function typeFor(e){if(t.has(e))return`boolean`;for(let[r,i]of n)if((r===e||i.includes(e))&&t.has(r))return`boolean`;return`string`}let a={};for(let[e,t]of n){a[e]={type:typeFor(e)};for(let e of t)a[e]={type:typeFor(e)}}return{nodeOptions:a,knownNames:r,acceptedFlags:i}}function parsePostCommandArgs(e,t){let n=[],r=[];for(let t=0;t<e.length;t++){let i=e[t];if(i===`--`){r.push(...e.slice(t));break}i.startsWith(`--no-`)?n.push(i.slice(5)):r.push(i)}let i={},a=[];try{let e=ne({args:r,options:Object.keys(t).length>0?t:void 0,allowPositionals:!0,strict:!1});i=e.values,a=e.positionals}catch{i={}}return{values:i,positionals:a,negatedNames:n}}function findBadDirArg(e,t,n,r){let{positionals:i}=parsePostCommandArgs(e,n),a=Object.entries(t).filter(([,e])=>e.type===`positional`);for(let[e,[t,n]]of a.entries()){let a=i.at(e);if(a===void 0||n.valueHint!==`dir`)continue;let o=r(a);if(o!==`directory`)return{argName:t,value:a,missing:o===`missing`}}}function computeUnknownArgNames(e,t){let n=buildParseTable(t),{values:r,negatedNames:i}=parsePostCommandArgs(e,n.nodeOptions),a=/* @__PURE__ */ new Set;for(let e of Object.keys(r))n.knownNames.has(e)||a.add(e);for(let e of i)n.knownNames.has(e)||a.add(e);return[...a]}function buildDisplayTokenMap(e){let t=/* @__PURE__ */ new Map;for(let n of e){if(n===`--`)break;if(n.startsWith(`--no-`)){let e=n.slice(5);t.has(e)||t.set(e,flagBase(n));continue}if(!n.startsWith(`-`))continue;let e=flagName(n);t.has(e)||t.set(e,flagBase(n))}return t}function formatFlagToken(e){return e.length===1?`-${e}`:`--${e}`}function resolveStaticSubCommands(e){let t=e.subCommands;if(t!==void 0&&typeof t!=`function`&&!(t instanceof Promise))return t}function resolveLeafCommand(e,t,n){let r=resolveStaticArgsDef(e),i=resolveStaticSubCommands(e);if(i!==void 0){let e=splitAtCommand(n,r);if(e!==void 0){let r=n[e.index];if(!(r in i))return;let a=asCommandDef(i[r]);return a===void 0?void 0:resolveLeafCommand(a,[...t,r],n.slice(e.index+1))}}return r===void 0?void 0:{chain:t,argsDef:r,postCommandArgs:n}}function findUnknownFlags(e,t,n){if(hasHelpFlag(e)||isLoneVersionQuery(e))return{kind:`none`};let r=splitAtCommand(e);if(r===void 0)return{kind:`none`};let i=e[r.index];if(!(i in t))return{kind:`none`};let a=asCommandDef(t[i]);if(a===void 0)return{kind:`none`};for(let e of r.before)if(!Oo.has(flagName(e)))return{kind:`before-command`,command:i,flag:flagBase(e)};let o=resolveLeafCommand(a,[i],e.slice(r.index+1));if(o===void 0)return{kind:`none`};let s=buildParseTable(o.argsDef),c=computeUnknownArgNames(o.postCommandArgs,o.argsDef);if(c.length===0){let e=n===void 0?void 0:findBadDirArg(o.postCommandArgs,o.argsDef,s.nodeOptions,n);return e===void 0?{kind:`none`}:{kind:`not-a-directory`,command:i,commandPath:o.chain.join(` `),...e}}let l=buildDisplayTokenMap(o.postCommandArgs);return{kind:`unknown`,command:i,commandPath:o.chain.join(` `),unknownFlags:c.map(e=>l.get(e)??formatFlagToken(e)),accepted:s.acceptedFlags}}function formatUnknownFlagsMessage(e){let t=`Unknown ${e.unknownFlags.length===1?`flag`:`flags`} ${e.unknownFlags.join(`, `)} for ${e.commandPath}. Nothing ran.`,n=Do.filter(t=>t.startsWith(`--`)&&t!==`--version`&&!e.accepted.includes(t));return`${t}\nAccepted: ${n.length===0?e.accepted.join(`, `):`${e.accepted.join(`, `)} (plus ${n.join(`, `)})`}.`}function formatFlagBeforeCommandMessage(e){return`${e.flag} must come after the command name.`}function formatNotADirectoryMessage(e){return`${e.missing?`No such directory: ${e.value}.`:`${e.value} is not a directory.`} ${e.commandPath} takes a directory as [${e.argName}]. Nothing ran.`}function formatFlagCheckMessage(e){return e.kind===`before-command`?formatFlagBeforeCommandMessage(e):e.kind===`not-a-directory`?formatNotADirectoryMessage(e):formatUnknownFlagsMessage(e)}function collectFlagValues(e,t){let n=`${t}=`,r=[];for(let i=0;i<e.length;i+=1){let a=e[i];if(a!==void 0){if(a===`--`)break;if(a===t){let t=e[i+1];t!==void 0&&(r.push(t),i+=1)}else a.startsWith(n)&&r.push(a.slice(n.length))}}return r.map(e=>e.trim()).filter(e=>e!==``)}function hasNegationFlag(e,t){for(let n of e){if(n===`--`)break;if(n===t)return!0}return!1}function flagPresent(e,t){for(let n of e){if(n===`--`)break;if(n===t||n.startsWith(`${t}=`))return!0}return!1}function resolveRepeatableFlag(e,t,n,r){let i=collectFlagValues(e,t),a=hasNegationFlag(e,n);if(i.length>0&&a)throw new T(`${t} and ${n} are contradictory -- pass only one.`);if(i.length===0&&flagPresent(e,t)){let e=r.fallback===void 0?``:` Refusing rather than falling back to ${r.fallback}.`;throw new T(`${t} was given with no ${r.noun} (expected e.g. ${t} ${r.example}).${e}`)}return a?{kind:`negated`}:i.length>0?{kind:`values`,values:i}:{kind:`absent`}}function parseListFlag(e,t){let n=`--${t}`,r=[];for(let[t,i]of e.entries()){if(i===`--`)break;if(i.startsWith(`${n}=`)){r.push(i.slice(n.length+1));continue}if(i!==n)continue;let a=e[t+1];a!==void 0&&!a.startsWith(`--`)&&r.push(a)}return r.flatMap(e=>e.split(`,`)).map(e=>e.trim()).filter(e=>e.length>0)}const ko=[{name:`build`},{name:`typecheck`},{name:`lint`},{name:`lint:types`},{name:`test`},{name:`format`,args:`--check`},{name:`knip`},{name:`tooling:check`},{name:`docs:check`},{name:`docker:build`},{name:`docker:check`}],Ao={name:`health:check`};function withHealthCheck(e,t=Ao){let n=e.findIndex(e=>e.name===`tooling:check`),r=n===-1?e.length:n+1;return[...e.slice(0,r),t,...e.slice(r)]}const jo={name:`chars:check`},Mo=`ascii:check`;function legacyCharsAlias(e){return e===Mo?jo.name:void 0}function withLegacyCharsSkip(e){let t=new Set(e),n=[...t].map(legacyCharsAlias).filter(e=>e!==void 0);for(let e of n)t.add(e);return t}function withCharsCheck(e){let t=e.findIndex(e=>e.name===`lint`),n=t===-1?e.length:t+1;return[...e.slice(0,n),jo,...e.slice(n)]}function charsBlock(e){return e?.chars??e?.ascii}function resolveBuiltinChecks(e){let t=ko;return isCharsGateOn(charsBlock(e))&&(t=withCharsCheck(t)),e?.health?.enabled===!0&&(t=withHealthCheck(t)),t}function resolveRunBuiltins(e,t,n=referenceEnablesHealth){let r=resolveBuiltinChecks(t);return n(e)?t?.health?.enabled===!0?r.map(e=>e.name===Ao.name?{...Ao,required:!0}:e):withHealthCheck(r,{...Ao,required:!0}):r}function staleChecksAddNames(e,t=e?.checks?.add??[]){if(t.length===0)return[];let n=new Set(resolveBuiltinChecks(e).map(e=>e.name));return t.filter(e=>n.has(e)||n.has(legacyCharsAlias(e)??``))}function shouldSkip(e,t){return t.size!==0&&F.isMatch(e,[...t])}function coveringStepBodies(e,t){if(e===`lint`){let e=t[`lint:report`]??t.lint;return e===void 0?[]:[e]}if(e===`test`)return[t.test,t[`test:coverage`]].filter(e=>e!==void 0);let n=t[e];return n===void 0?[]:[n]}function coveredChecksAddEntries(e,t){let n=e?.checks?.add??[];if(n.length===0)return[];let r=new Set(staleChecksAddNames(e,n)),i=new Set(e?.checks?.skip??[]),a=n.filter(e=>!r.has(e)&&!shouldSkip(e,i));if(a.length===0)return[];let o=resolveBuiltinChecks(e).map(e=>e.name),s=[];for(let e of a){let n=[.../* @__PURE__ */ new Set([...o,...a.filter(t=>t!==e)])].filter(e=>!shouldSkip(e,i)),r=new RegExp(String.raw`(?:^|[\s/])${escapeRegex(e)}(?=\s|$)`),c;for(let i of n){for(let n of coveringStepBodies(i,t)){let t=commandSegments(n).find(e=>r.test(e));if(t!==void 0){c={name:e,coveredBy:i,fragment:t};break}}if(c)break}c&&s.push(c)}return s}function coverageModeFromFlags(e,t){return e===!1?`off`:e===!0||t?`on`:`auto`}function decideCoverage(e,t,n){let r=t.coverage??`auto`;if(r===`on`)return{enabled:!0,source:`flag`};if(r===`off`)return{enabled:!1,source:`flag`};let i=n?.coverage;if(i!==!1&&i?.gateOnPullRequests===!0)return{enabled:!0,source:`config`};let a=Object.hasOwn(t,`currentBranch`)?t.currentBranch:resolveCurrentBranch({cwd:e}),o=t.defaultBranch??resolveDefaultBranch({cwd:e});return{enabled:a!==void 0&&a===o,source:`branch`}}function defaultGetScripts(e){try{let t=parsePackageJson(p(w.join(e,`package.json`),`utf-8`));return new Set(Object.keys(t?.scripts??{}))}catch{return/* @__PURE__ */ new Set}}const rawLog$2=e=>console.log(e);function failedRunSkippedLine(e){return e.length===0?null:`Skipped: ${e.join(`, `)}`}function passedSummary(e,t){let n=[...e.length>0?[`${String(e.length)} advisory: ${e.map(e=>e.name).join(`, `)}`]:[],...t.length>0?[`skipped: ${t.join(`, `)}`]:[]];return n.length===0?`All checks passed`:`All checks passed (${n.join(`; `)})`}function skippedLine(e){return`Skipped (${e.source}): ${e.steps.join(`, `)}`}const No={groupStart:e=>rawLog$2(`::group::${e}`),groupEnd:()=>rawLog$2(`::endgroup::`),passed:(e,t)=>rawLog$2(`[ok] ${e} (${t}s)`),warned:(e,t,n)=>{rawLog$2(`[warn] ${e} (${t}s): ${String(n)} advisory finding(s)`),rawLog$2(`::warning::${e}: ${String(n)} advisory finding(s)`)},failed:(e,t)=>{rawLog$2(`[x] ${e} (${t}s)`),rawLog$2(`::error::${e} failed`)},undefinedCheck:e=>rawLog$2(`::error::${e} not defined in package.json`),requiredByConfigSkip:e=>rawLog$2(`::error::${e} is required by the default branch's health gate; checks.skip cannot skip it (--skip still can)`),skipped:e=>{for(let t of e)rawLog$2(skippedLine(t))},skippedNotDefined:e=>rawLog$2(`Skipped (not defined): ${e.join(`, `)}`),onlySelected:e=>rawLog$2(`Only: ${e.join(`, `)}`),unmatchedOnly:(e,t)=>rawLog$2(`::error::--only matched no step for: ${e.join(`, `)}; the steps are ${t.join(`, `)}`),allPassed:(e,t)=>rawLog$2(`[ok] ${passedSummary(e,t)}`),anyFailed:(e,t)=>{let n=failedRunSkippedLine(t);n!==null&&rawLog$2(n),rawLog$2(`::error::Failed checks: ${e.join(`, `)}`)},digest:e=>{for(let t of e)rawLog$2(t)}},Po={groupStart:e=>{},groupEnd:()=>{},passed:e=>I.success(e),warned:(e,t,n)=>I.warn(`${e}: ${String(n)} advisory finding(s)`),failed:e=>I.error(`${e} failed`),undefinedCheck:e=>I.error(`${e} not defined in package.json`),requiredByConfigSkip:e=>I.error(`${e} is required by the default branch's health gate; checks.skip cannot skip it (--skip still can)`),skipped:e=>{for(let t of e)I.info(skippedLine(t))},skippedNotDefined:e=>I.info(`Skipped (not defined): ${e.join(`, `)}`),onlySelected:e=>I.info(`Only: ${e.join(`, `)}`),unmatchedOnly:(e,t)=>I.error(`--only matched no step for: ${e.join(`, `)}; the steps are ${t.join(`, `)}`),allPassed:(e,t)=>I.success(passedSummary(e,t)),anyFailed:(e,t)=>{let n=failedRunSkippedLine(t);n!==null&&I.info(n),I.error(`Failed checks: ${e.join(`, `)}`)},digest:e=>{for(let t of e)rawLog$2(t)}};function reportSkipped(e,t,n,r,i){let a=groupSkippedSteps(t,n,r,i);return e.skipped(a),a.flatMap(e=>e.steps)}function reportSkippedUnlessRefused(e,t,n,r,i){return reportSkipped(e,t.filter(e=>!requiredSkipIsRefused(e,r,i)).map(e=>e.name),n,r,i)}function requiredSkipIsRefused(e,t,n){return e.required===!0&&shouldSkip(e.name,n)&&!shouldSkip(e.name,t)}function logCoverageChoice(e,t,n,r){t.enabled&&!n&&t.source===`flag`&&I.warn(`--with-coverage requested but test:coverage script is not defined; falling back to test`),t.enabled&&!n&&t.source===`config`&&I.warn(`coverage.gateOnPullRequests is set but test:coverage script is not defined; falling back to test`),debug(e,`Coverage: ${r??`auto`} (source: ${t.source}) -> ${n?`test:coverage`:`test`}`)}function withLegacyCharsScript(e){let t=new Set(e);return!t.has(jo.name)&&e.has(Mo)&&t.add(jo.name),t}function withAddedChecks(e,t){let n=new Set(e.map(e=>e.name));function isBuiltInName(e){if(n.has(e))return!0;let t=legacyCharsAlias(e);return t!==void 0&&n.has(t)}return[...e,...t.filter(e=>!isBuiltInName(e)).map(e=>({name:e}))]}function scriptNameFor(e,t,n){return e===`test`&&n?`test:coverage`:e===`lint`&&t.has(`lint:report`)?`lint:report`:e===jo.name&&!t.has(jo.name)&&t.has(Mo)?Mo:e}function narrowToOnly(e,t,n){if(n===void 0||n.size===0)return{run:t,selected:/* @__PURE__ */ new Set,unmatched:!1};let r=selectOnly(t,withLegacyCharsSkip(n)),i=r.unmatched.filter(e=>!r.selected.includes(legacyCharsAlias(e)??``));if(i.length>0)return e.unmatchedOnly(i,t.map(e=>e.name)),{run:[],selected:/* @__PURE__ */ new Set,unmatched:!0};e.onlySelected(r.selected);let a=new Set(r.selected);return{run:t.filter(e=>a.has(e.name)),selected:a,unmatched:!1}}async function runRunChecks(e,t={}){let n=t.execCommand??execStep,r=t.getScripts??defaultGetScripts,i=t.toolingConfig??loadToolingConfig(e),a=i?.checks,o=withLegacyCharsSkip(t.skip??[]),s=withLegacyCharsSkip(a?.skip??[]),c=/* @__PURE__ */ new Set([...o,...s]),l=[.../* @__PURE__ */ new Set([...t.add??[],...a?.add??[]])],u=!!process.env.CI,d=t.failFast??!u,f=u?No:Po,p={verbose:t.verbose??!1},m=r(e),h=withLegacyCharsScript(m),g=new Set(l),_=withAddedChecks(resolveRunBuiltins(e,i,t.referenceEnablesHealth),l),v=[],y=[],b=[],x=[],S=t.recordFailures??recordFailures,printDigest=()=>{x.length>0&&f.digest(renderDigest(x))},C=decideCoverage(e,t,i),ee=C.enabled&&m.has(`test:coverage`);logCoverageChoice(p,C,ee,t.coverage);let w=narrowToOnly(f,_,t.only);if(w.unmatched)return S(e,[]),1;let te=w.selected,ne=w.run,re=reportSkippedUnlessRefused(f,ne,h,o,s);for(let t of ne){if(shouldSkip(t.name,c)){if(requiredSkipIsRefused(t,o,s)&&(f.requiredByConfigSkip(t.name),v.push(t.name),d))return S(e,x),1;continue}if(!h.has(t.name)){g.has(t.name)||t.required===!0||te.has(t.name)?(f.undefinedCheck(t.name),v.push(t.name)):b.push(t.name);continue}let r=scriptNameFor(t.name,m,ee),i=t.args?`pnpm run ${r} ${t.args}`:`pnpm run ${r}`;debug(p,`Running: ${i} (in ${e})`),f.groupStart(t.name);let a=Date.now(),l=await n(i,e),u=((Date.now()-a)/1e3).toFixed(1);if(f.groupEnd(),debug(p,`${t.name}: exit code ${String(l.exitCode)}, ${u}s`),l.exitCode===0){let e=l.lastMarkerLine===null?null:parseWarnMarkerLine(l.lastMarkerLine);e===null?f.passed(t.name,u):(f.warned(t.name,u,e),y.push({name:t.name,count:e}))}else if(f.failed(t.name,u),v.push(t.name),x.push(buildStepFailure(t.name,l)),d)return printDigest(),S(e,x),1}return b.length>0&&f.skippedNotDefined(b),v.length>0?(printDigest(),S(e,x),f.anyFailed(v,re),1):(S(e,x),f.allPassed(y,re),0)}const Fo=withCharsCheck(withHealthCheck(ko)).map(e=>e.name).join(`, `),Io=j({meta:{name:`checks:run`,description:`Run the repo's standard check pipeline. The steps are ${Fo} (chars:check runs unless .tooling.json#chars.enabled is false, and health:check only where .tooling.json enables it). A step that exits 0 and prints ::bst-checks:: warn <count> on stdout is reported as warned; no exit code changes.`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Target directory (default: current directory)`,required:!1},skip:{type:`string`,description:`Comma-separated globs of checks to skip (${Fo}). Repeatable; every occurrence UNIONS, with each other and with .tooling.json#checks.skip`,required:!1},add:{type:`string`,description:"Comma-separated extra check names to run via `pnpm run <name>`. Repeatable; every occurrence UNIONS, with each other and with .tooling.json#checks.add; an added check with no matching script is a hard failure",required:!1},only:{type:`string`,description:`Comma-separated globs of the only checks to run (${Fo}), in pipeline order. Repeatable; occurrences union. --skip and .tooling.json#checks.skip still win; a glob that matches no step, or a matched step with no script, fails the run`,required:!1},"fail-fast":{type:`boolean`,description:`Stop on first failure (default: true in dev, false in CI)`,required:!1},verbose:{type:`boolean`,description:`Emit detailed debug logging`,required:!1},"with-coverage":{type:`boolean`,description:`Force the test step to run with coverage (pnpm run test:coverage); overrides branch detection`,required:!1},coverage:{type:`boolean`,description:`Force the test step to run with coverage; --no-coverage forces it to run without. With neither, coverage is branch-aware (on for the default branch only, or for every branch when .tooling.json#coverage.gateOnPullRequests is set)`,required:!1}},async run({args:e,rawArgs:t}){let n=w.resolve(e.dir??`.`),r=parseListFlag(t,`skip`),i=parseListFlag(t,`add`),a=parseListFlag(t,`only`),o=r.length>0?new Set(r):void 0,s=i.length>0?i:void 0,c=a.length>0?new Set(a):void 0,l=e[`fail-fast`]?!0:void 0,u=e.verbose===!0||isEnvVerbose(),d=coverageModeFromFlags(typeof e.coverage==`boolean`?e.coverage:void 0,e[`with-coverage`]===!0),f=loadToolingConfig(n),p=f?.defaultBranch,m=await runRunChecks(n,{skip:o,only:c,add:s,failFast:l,verbose:u,coverage:d,defaultBranch:p,toolingConfig:f});process.exitCode=m}}),Lo=[`dl.google.com`],Ro=/^sha256:[0-9a-f]{64}$/,zo=P.record(P.string(),P.union([P.string(),P.looseObject({})])),Bo=P.record(P.string(),P.unknown()),Vo=P.looseObject({tools:P.unknown().optional(),settings:P.unknown().optional()});function resolveArchiveHost(e,t){if(typeof t==`string`)return{reason:`mise.toml: ${e} is a plain string; it must be a table with url and checksum`};let n=t.url;if(typeof n!=`string`)return{reason:`mise.toml: ${e} is missing a string url`};let r=t.checksum;if(typeof r!=`string`||!Ro.test(r))return{reason:`mise.toml: ${e} is missing a valid sha256:<64 hex> checksum`};if(!URL.canParse(n))return{reason:`mise.toml: ${e}'s url "${n}" does not parse`};let i=new URL(n);return i.protocol===`https:`?Lo.includes(i.hostname)?{host:i.hostname}:{reason:`mise.toml: ${e} fetches from ${i.hostname}, which the agent's archive host set does not carry`}:{reason:`mise.toml: ${e} fetches over ${i.protocol}, not https:`}}function parseToolsTable(e){let t;try{t=Me(e)}catch(e){return{reason:`mise.toml: could not parse -- ${e instanceof Error?e.message:String(e)}`}}let n=Vo.safeParse(t);if(!n.success)return{reason:`mise.toml: not a valid document`};let r=zo.safeParse(n.data.tools??{});return r.success?{tools:r.data}:{reason:`mise.toml: [tools] is not a valid table`}}function scanTools(e){let t=[],n=[],r=!1,i=!1,a=!1;for(let[o,s]of Object.entries(e))if(o!==`node`&&o!==`pnpm`){if(o===`java`)r=!0;else if(o.startsWith(`conda:`))i=!0;else if(o!==`python`&&o!==`uv`){if(o.startsWith(`pipx:`))a=!0;else if(o.startsWith(`http:`)){let e=resolveArchiveHost(o,s);`reason`in e?t.push(e.reason):n.push(e.host)}else t.push(`mise.toml: tools.${o} is not a tool the agent's toolchain map knows`)}}if(a){let n=pipxCompanionRefusalOf(e);n!==null&&t.push(n)}return{refusals:t,java:r,conda:i,pypi:a,archiveHosts:n}}function pipxCompanionRefusalOf(e){let t=[];if(`python`in e||t.push(`python`),`uv`in e||t.push(`uv`),t.length===0)return null;let n=t.map(e=>`a ${e} key`).join(` and `),r=t.map(e=>`${e} = "<version>"`).join(` and `),i=[];return t.includes(`python`)&&i.push(`uv would otherwise run the tool on an interpreter the repo never pinned`),t.includes(`uv`)&&i.push(`mise's pipx backend otherwise falls back to a pipx binary the image lacks`),`mise.toml: a "pipx:" tool needs ${n}: ${i.join(`; `)}. Add ${r} under [tools].`}function readTable(e){if(typeof e!=`object`||!e||Array.isArray(e))return{};let t=Bo.safeParse(e);return t.success?t.data:{}}function readMiseDocument(e){let t;try{t=Me(e)}catch{return null}let n=Vo.safeParse(t);return n.success?{tools:readTable(n.data.tools),settings:readTable(n.data.settings)}:null}function miseToolchainRefusals(e){let t=parseToolsTable(e);return`reason`in t?[t.reason]:scanTools(t.tools).refusals}function pipxCompanionRefusal(e){let t;try{t=Me(e)}catch{return null}let n=Vo.safeParse(t);if(!n.success)return null;let r=Bo.safeParse(n.data.tools??{});return!r.success||!Object.keys(r.data).some(e=>e.startsWith(`pipx:`))?null:pipxCompanionRefusalOf(r.data)}const Ho=/^(?:[A-Za-z][A-Za-z0-9-]*-)?v?\d+(?:\.\d+)?$/,Uo=/* @__PURE__ */ new Set([`node`,`pnpm`]);function isLooseVersion(e){return e===`latest`||e===`lts`||e.startsWith(`prefix:`)||/^sub-\d+:/.test(e)?!0:Ho.test(e)}function isTable(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function versionsOf(e){return typeof e==`string`?[e]:Array.isArray(e)?e.filter(e=>typeof e==`string`):isTable(e)&&typeof e.version==`string`?[e.version]:[]}function loosePinAdvisories(e){let t=[];for(let[n,r]of Object.entries(e)){if(Uo.has(n)||n.startsWith(`http:`))continue;let e=versionsOf(r).filter(isLooseVersion);e.length!==0&&t.push(`mise.toml: tools.${n} is pinned to ${e.map(e=>`"${e}"`).join(`, `)}, which mise treats as a prefix and resolves to the newest matching release. Pin the full release instead, for example ${n} = "<x.y.z>", so CI and agent runs cannot resolve different releases, and Renovate can bump the pin.`)}return t}const Wo=`.tool-versions`,Go=`.python-version`;function readVersionFile(e,t){try{return p(w.join(e,t),`utf-8`)}catch{return null}}function pythonPinOf(e){let t=e.python;return typeof t==`string`?t:isTable(t)&&typeof t.version==`string`?t.version:null}function firstVersionLine(e){for(let t of e.split(/\r?\n/)){let e=t.trim();if(!(e===``||e.startsWith(`#`)))return e}return null}function versionFileAdvisories(e,t,n){let r=[];if(readVersionFile(e,Wo)!==null){let e=n?` The agent's toolchain check reads mise.toml only, so a tool declared only in .tool-versions is installed without that check.`:``;r.push(`${Wo} beside mise.toml declares tools too; mise merges the two files, so they can disagree and nothing says which one a reader should trust. Move its entries into mise.toml and delete the file.${e}`)}let i=firstVersionLine(readVersionFile(e,Go)??``),a=pythonPinOf(t);return i!==null&&a!==null&&i!==a&&r.push(`mise.toml pins python to "${a}" but ${Go} says "${i}". Make the two equal, or delete ${Go}, so the interpreter does not depend on which file wins.`),r}const Ko=`pypi.org`,qo=[Ko,`files.pythonhosted.org`],Jo=[{setting:`pipx.registry_url`,path:[`pipx`,`registry_url`],defaultHosts:[Ko],moves:`the Python package index`},{setting:`pypi.registry_url`,path:[`pypi`,`registry_url`],defaultHosts:[Ko],moves:`the Python package index`},{setting:`node.mirror_url`,path:[`node`,`mirror_url`],defaultHosts:[`nodejs.org`],moves:`Node.js downloads`}],Yo=[`--index-url`,`--extra-index-url`,`--index`,`--default-index`,`--find-links`];function settingString(e,t){let n=e.settings;for(let e of t){if(!isTable(n))return null;n=n[e]}return typeof n==`string`?n:null}function hostOf(e){if(!URL.canParse(e))return null;let t=new URL(e).hostname;return t===``?null:t}function hostIsRequested(e,t){let n=e.toLowerCase();return t.some(e=>{if(e.includes(`/`))return!1;let t=e.toLowerCase();if(t===n)return!0;if(!t.startsWith(`*.`))return!1;let r=t.slice(2),i=n.indexOf(`.`);return i<=0?!1:n.slice(i+1)===r})}function movedHostFixes(e){return`Add ${e} to agent.egress.browseHosts (a request the deployment still has to grant), or remove the setting.`}function settingHostAdvisory(e,t,n){return`mise.toml: [settings] ${e} moves ${n} to ${t}, which the agent's egress proxy does not open. ${movedHostFixes(t)}`}function uvxArgsAdvisories(e,t,n){let r=[],i=t.split(/\s+/).filter(e=>e!==``);for(let[t,a]of i.entries())for(let o of Yo){let s;if(a===o?s=i[t+1]:a.startsWith(`${o}=`)&&(s=a.slice(o.length+1)),s===void 0)continue;let c=hostOf(s)??hostOf(s.slice(s.indexOf(`=`)+1));c===null?r.push(`mise.toml: tools.${e} passes ${o} ${s} to uv, which moves the install away from the Python package index. Remove the flag, or point it at ${qo.join(` or `)}.`):qo.includes(c)||hostIsRequested(c,n)||r.push(`mise.toml: tools.${e} passes ${o} ${s} to uv, so the install fetches from ${c}. ${movedHostFixes(c)}`)}return r}function hostSettingAdvisories(e,t){let n=[],r=e.settings.python;isTable(r)&&r.compile===!0&&n.push(`mise.toml: [settings] python.compile = true builds CPython from source, so the install reaches hosts outside the agent's measured set. Remove the setting to fetch the prebuilt release instead.`);for(let r of Jo){let i=settingString(e,r.path);if(i===null)continue;let a=hostOf(i);a!==null&&(r.defaultHosts.includes(a)||hostIsRequested(a,t)||n.push(settingHostAdvisory(r.setting,a,r.moves)))}for(let[r,i]of Object.entries(e.tools)){if(!r.startsWith(`pipx:`)||!isTable(i))continue;let e=i.uvx_args;typeof e==`string`&&n.push(...uvxArgsAdvisories(r,e,t))}return n}const Xo=P.looseObject({tools:P.unknown().optional(),tasks:P.unknown().optional()}),Zo=[`mise.toml`,`.mise.toml`,`mise/config.toml`,`.mise/config.toml`,`.config/mise.toml`,`.config/mise/mise.toml`,`.config/mise/config.toml`],Qo=[`mise-tasks`,`.mise-tasks`,`.mise/tasks`,`.config/mise/tasks`,`mise/tasks`];function readMiseFile(e){for(let t of Zo){let n=readOneMiseFile(e,t);if(n!==null)return{name:t,raw:n}}return null}function readMiseFiles(e){let t=[];for(let n of Zo){let r=readOneMiseFile(e,n);r!==null&&t.push(r)}return t}function readOneMiseFile(e,t){try{return p(w.join(e,t),`utf-8`)}catch{return null}}function hasTaskTable(e,t){let n;try{n=Me(e)}catch{return!1}let r=Xo.safeParse(n);if(!r.success)return!1;let i=r.data.tasks;return typeof i!=`object`||!i||Array.isArray(i)?!1:Object.hasOwn(i,t)}function hasTaskFile(e,t){return Qo.some(n=>isExecutableFile(w.join(e,n,t)))}function isExecutableFile(e){try{return t(e,i.X_OK),!0}catch{return!1}}function declaresTask(e,t){return readMiseFiles(e).some(e=>hasTaskTable(e,t))||hasTaskFile(e,t)}function agentIgnoresConfigAdvisory(e){return`The repo's mise config is ${e}, and the agent reads mise.toml only, so agent runs install none of its tools and run no bst-setup task. Move the config to mise.toml if agent runs need it.`}function findMiseAdvisories(e,t){let n=readMiseFile(e);if(n===null)return[];let{raw:r}=n,i=t.agentEnabled&&n.name===`mise.toml`,a=[];if(i)a.push(...miseToolchainRefusals(r)),declaresTask(e,`setup`)&&!declaresTask(e,`bst-setup`)&&a.push(`mise.toml declares a setup task but no bst-setup task, which is the only task the agent's container runs. Add a [tasks.bst-setup] with depends = ["setup"] if agent runs need it.`);else{t.agentEnabled&&a.push(agentIgnoresConfigAdvisory(n.name));let e=pipxCompanionRefusal(r);e!==null&&a.push(e)}let o=readMiseDocument(r);return o!==null&&(a.push(...loosePinAdvisories(o.tools)),a.push(...versionFileAdvisories(e,o.tools,i)),i&&a.push(...hostSettingAdvisories(o,t.browseHosts))),a}const $o=[`.forgejo/workflows/`,`.github/workflows/`];function isWorkflowDirPath(e){return $o.some(t=>e.startsWith(t))}const es=/\bapt(?:-get)?(?:\s+-\S+)*\s+install\b/g,ts=/&&|\|\||;|\|/;function workflowFiles(e){let t=[];for(let n of $o){let r;try{r=h(w.join(e,n))}catch{continue}for(let i of r){if(!/\.ya?ml$/.test(i))continue;let r=`${n}${i}`;isReadableFile$1(w.join(e,r))&&t.push(r)}}return t}function isReadableFile$1(e){try{return b(e).isFile()}catch{return!1}}function readText(e){try{return p(e,`utf8`)}catch{return null}}function logicalLines(e){let t=[],n=``;for(let r of e){if(r.trim().startsWith(`#`))continue;let e=r.trimEnd();e.endsWith(`\\`)?n+=`${e.slice(0,-1)} `:(t.push(n+r),n=``)}return n!==``&&t.push(n),t}function packagesIn(e){let t=[];for(let n of e.matchAll(es)){let r=e.slice(n.index+n[0].length).split(ts)[0]??``;for(let e of r.split(/\s+/))e===``||e.startsWith(`-`)||t.push(e)}return t}function installsWithApt(e){return e.search(es)!==-1}function findWorkflowAptSteps(e){let t=[];for(let n of workflowFiles(e)){let r=readText(w.join(e,n));if(r===null||isToolingIgnored(r))continue;let i=!1,a=/* @__PURE__ */ new Set;for(let e of extractCustomBlocks(r))for(let t of logicalLines(e.lines))if(installsWithApt(t)){i=!0;for(let e of packagesIn(t))a.add(e)}i&&t.push({file:n,packages:[...a]})}return t.toSorted((e,t)=>e.file.localeCompare(t.file))}function runReleaseTargetGate(e,t){let n=releaseTargetConflict(e.stack,e.releaseStrategy,t);return n?(I.error(`releaseStrategy "simple" bumps package.json, but this repo's version-of-record is ${n}. A release would tag a version the ${n} artifact never gets. Release this repo through its own toolchain, or set releaseStrategy away from "simple".`),!0):!1}function runComposeLintGate(e,t,n){let r=lintComposeFiles(e,t);for(let e of r)I.error(e.message);for(let r of findDockerRebuildRisks(e,t,n))I.warn(r);return r.length}function runCheckOnlyImageGate(e,t,n,r){if(!e.publishDocker)return[];let i=[];for(let e of findCheckOnlyPublishRisks(t,r,n))I.warn(`Image "${e.imageName}" is declared only in ${e.declaredIn}, the check overlay, so a later tooling release stops publishing it with docker:publish by default. Keep it: set publish to true for "${e.imageName}" under .tooling.json#docker. Settle it: set publish to false there, or move the service into a base compose file.`),i.push(e.imageName);return i}function runWorkflowAptGate(e){let t=findWorkflowAptSteps(e);for(let e of t){let t=e.packages.length>0?e.packages.join(`, `):`packages`;I.warn(`${e.file} installs ${t} with apt in a custom block. The agent's containers cannot run that step, so its runs lack what CI has. Declare each tool in mise.toml as conda:<name> (both CI and the agent install from it), then remove the apt step.`)}return t}function runMiseAdvisoryGate(e,t){let n=findMiseAdvisories(e,{agentEnabled:t?.agent?.enabled===!0,browseHosts:t?.agent?.egress?.browseHosts??[]});for(let e of n)I.warn(e);return n}function findInertAgentKeys(e){let t=e?.agent;return!t||t.enabled===!0?[]:Object.keys(t).filter(e=>e!==`enabled`).toSorted()}function runInertAgentSettingsGate(e){let t=findInertAgentKeys(e);return t.length===0?[]:(I.warn(`.tooling.json sets ${t.map(e=>`agent.${e}`).join(`, `)}, but agent.enabled is not true, so the agent ignores them. Run \`pnpm exec bst setup:agent\` to enable the agent, or remove those keys.`),t)}function runPublishConfigGate(e,t){if(!e.publishNpm)return 0;let n=lintPublishConfig(t,e.structure);for(let e of n)I.error(e.message);return n.length}const ns=/* @__PURE__ */ new Set([`simple`,`changesets`]);function warnInertVersionStamp(e,t){e!==0&&(ns.has(t)||I.warn(`.tooling.json#versionStamp is configured, but releaseStrategy "${t}" emits no release-assets step, so nothing ever stamps the file and the released artifact keeps its committed placeholder version. Release through "simple" or "changesets", or remove the block.`))}function runVersionStampGate(e,t,n){let r=e?.versionStamp??[];warnInertVersionStamp(r.length,n);let i=0;for(let e of r){let n=w.resolve(t,e.file);if(!o(n)){I.error(`versionStamp: ${e.file} does not exist (resolved to ${n}).`),i++;continue}let r;try{r=p(n,`utf-8`)}catch(t){let n=t instanceof Error?t.message:String(t);I.error(`versionStamp: ${e.file} could not be read: ${n}`),i++;continue}let a=describeStampProblem(r,e);a&&(I.error(`versionStamp: ${a}`),i++)}return i}function describeAssetEntry(e,t){let n=e.file??(e.files===void 0?``:e.files.join(`, `));return n===``?`releaseAssets[${String(t)}]`:`releaseAssets[${String(t)}] ("${n}")`}function readPreTag(e){try{return parsePreTag(p(w.join(e,co),`utf-8`))}catch{return}}function runSnapshotConfigGate(e,t,n){let r=0,i=e?.releaseAssets??[];for(let[e,t]of i.entries())t.file===void 0==(t.files===void 0)&&(I.error(`.tooling.json ${describeAssetEntry(t,e)} sets ${t.file===void 0?`neither`:`both`} file and files. Exactly one names the asset: keep file for a single path, or files for the globs the build writes.`),r++);let a=e?.snapshot;if(!a)return r;let o=readPreTag(t);o!==void 0&&o===a.preid&&(I.error(`.tooling.json#snapshot.preid "${a.preid}" equals the tag in .changeset/pre.json, so a snapshot would look like a build of the pre release line. Pick a different preid.`),r++);let s=getMonorepoPackages(t).map(e=>e.name);if(n!==`monorepo`){let e=readPackageJson(t)?.name;e!==void 0&&s.push(e)}let c=a.packages;(c===void 0||c.length===0)&&n===`monorepo`&&(I.error(`.tooling.json#snapshot is set on a monorepo but names no packages, and bst will not choose them for you: most monorepos have packages nobody installs from a snapshot. List the ones to snapshot under snapshot.packages. This repo has: ${s.length===0?`none under packages/`:s.join(`, `)}.`),r++);for(let e of c??[])s.includes(e)||(I.error(`.tooling.json#snapshot.packages names "${e}", which has no package.json behind it. release:snapshot resolves every name to a package directory, and would fail mid-publish over this one. Fix the name or drop it. This repo has: ${s.join(`, `)}.`),r++);if(n!==`monorepo`)return r;for(let[e,t]of i.entries())t.package===void 0&&(I.error(`.tooling.json ${describeAssetEntry(t,e)} names no package, but snapshot is set on a monorepo and a snapshot is cut per package, so it must know which package this asset serves. Set package to the package it serves (this repo has: ${s.join(`, `)}).`),r++);for(let[t,n]of(e?.versionStamp??[]).entries())n.package===void 0&&(I.error(`.tooling.json versionStamp[${String(t)}] ("${n.file}") names no package, but snapshot is set on a monorepo and a stamp carries the version of the release it belongs to. Set package to the package whose release it stamps (this repo has: ${s.join(`, `)}).`),r++);return r}const rs=P.looseObject({privatePackages:P.union([P.boolean(),P.looseObject({version:P.boolean().optional(),tag:P.boolean().optional()})]).optional()});function changesetsTagsPrivatePackages(e){let t=w.join(e,`.changeset`,`config.json`);if(!o(t))return;let n;try{n=JSON.parse(p(t,`utf-8`))}catch{return}let r=rs.safeParse(n);if(!r.success)return;let i=r.data.privatePackages;return i===void 0?!1:typeof i==`boolean`?i:i.tag===!0}function runPrivateReleaseAdvisory(e,t,n){if(e.ci!==`github`||e.releaseStrategy!==`changesets`)return[];let r=[],i=`Set "privatePackages": { "version": true, "tag": true } in .changeset/config.json`;if(e.structure===`monorepo`){if(changesetsTagsPrivatePackages(n)===!0)return[];let e=getMonorepoPackages(n);for(let n of t?.snapshot?.packages??[]){let t=e.find(e=>e.name===n);if(t===void 0||readPackageJson(t.dir)?.private!==!0)continue;let a=`.tooling.json#snapshot.packages names "${n}", whose package.json is private. Its snapshots ship, because bst cuts them itself, but changesets skips a private package, so its stable releases never will. ${i}, or drop "${n}" from snapshot.packages.`;I.warn(a),r.push(a)}return r}if(readPackageJson(n)?.private!==!0||changesetsTagsPrivatePackages(n)!==!1)return[];let a=`The root package is private, and .changeset/config.json never turns privatePackages.tag on, so changesets skips it: this repo versions nothing, tags nothing and publishes nothing. ${i}, or drop "private": true from package.json.`;return I.warn(a),r.push(a),r}function warnStaleChecksAdd(e){let t=staleChecksAddNames(e);t.length!==0&&I.warn(`.tooling.json#checks.add names built-in step(s) checks:run already runs: ${t.join(`, `)}. The entries are deduplicated at run time and do nothing -- remove them.`)}function warnUnconfiguredDefaultBranch(e,t,n=defaultGitRunner){if(t?.defaultBranch!==void 0)return;let r=n([`symbolic-ref`,`--short`,`refs/remotes/origin/HEAD`],e);if(r===void 0)return;let i=r.startsWith(`origin/`)?r.slice(7):r;i!==``&&i!==`main`&&I.warn(`origin/HEAD names "${i}", but .tooling.json sets no defaultBranch, so the generated CI workflow triggers on "${Oi}" and gates its release steps there. Set .tooling.json#defaultBranch to "${i}" and run pnpm exec bst repo:sync.`)}function warnCoveredChecksAdd(e,t){let n=coveredChecksAddEntries(e,readPackageJson(t)?.scripts??{});for(let e of n)I.warn(`.tooling.json#checks.add entry "${e.name}" is already run by the "${e.coveredBy}" step's script ("${e.fragment}"), so every pipeline run executes it twice. Remove the add entry, or drop the inline invocation from the "${e.coveredBy}" script.`)}const is=P.record(P.string(),P.union([P.string(),P.unknown()]));function readDeclaredTools(e){let t;try{t=p(e,`utf-8`)}catch{return}let n;try{n=Me(t)}catch{return}let r=P.looseObject({tools:P.unknown().optional()}).safeParse(n);if(!r.success)return;let i=is.safeParse(r.data.tools??{});if(!i.success)return;let a={};for(let[e,t]of Object.entries(i.data))typeof t==`string`&&(a[e]=t);return a}const as=P.looseObject({version:P.string(),install_path:P.string(),installed:P.boolean()}),os=P.record(P.string(),P.array(as));function miseIsAbsent(e){let t=ve.sync(`mise`,[`--version`],{cwd:e}).error;return t instanceof Error&&`code`in t&&t.code===`ENOENT`}function normalizeVersionOutput(e){return e.trim().replace(/^v/,``)}const ss='(`eval "$(mise activate bash)"`, `mise activate bash --shims`, or `mise exec`)';function describeFailedProbe(e){if(e.error)return e.error.message;let t=(e.stderr?.toString()??``).trim().split(`
|
|
6057
|
+
`)[0]??``;return`exited ${String(e.status)}${t?`: ${t}`:``}`}function liveVersionMismatch(e,t,n,r){let i=ve.sync(t,[`--version`],{cwd:e}),a=i.status===0&&i.stdout?normalizeVersionOutput(i.stdout.toString()):void 0;if(a===r)return!1;let o=a===void 0?`failed (${describeFailedProbe(i)})`:`reports ${a}`;return I.error(`mise.toml pins ${t} ${n??r} (resolved to ${r}), but \`${t} --version\` on PATH ${o}. Activate mise ${ss} before running this check.`),!0}function isInside(e,t){let n=w.relative(t,e);return n===``||!n.startsWith(`..`)&&!w.isAbsolute(n)}function resolveOnPath(e){for(let n of(process.env.PATH??``).split(w.delimiter)){if(!n)continue;let r=w.join(n,e);try{if(b(r).isFile())return t(r,i.X_OK),r}catch{}}}function javaMismatch(e){let t=w.dirname(w.dirname(w.dirname(e.install_path))),n=process.env.JAVA_HOME;if(n)return!isInside(n,t)&&(I.error(`mise.toml declares java, but JAVA_HOME points outside mise's install (${n}). Unset it, or activate mise ${ss} before running this check.`),!0);let r=resolveOnPath(`java`);return r!==void 0&&isInside(r,t)?!1:(I.error(`mise.toml declares java, but \`java\` on PATH is ${r??`missing`}, not mise's. Activate mise ${ss} before running this check.`),!0)}function checkDeclaredToolsActive(e,t){let n=ve.sync(`mise`,[`ls`,`--current`,`--json`],{cwd:e});if(n.status!==0&&(n.stderr?.toString()??``).includes(`are not trusted`))return I.error("mise refuses this repo's mise.toml until it is trusted. Run `mise trust`, or add the directory your checkouts live in to `trusted_config_paths` in ~/.config/mise/config.toml so every new worktree is trusted."),1;let r={};try{let e=os.safeParse(JSON.parse(n.stdout?.toString()??``));e.success&&(r=e.data)}catch{}let i={},a=0;for(let e of Object.keys(t)){let t=(r[e]??[]).find(e=>e.installed);t?i[e]=t:(I.error(`mise.toml declares ${e}, but it is not installed. Run \`mise install\`.`),a++)}for(let n of[`node`,`pnpm`]){let r=i[n];r&&liveVersionMismatch(e,n,t[n],r.version)&&a++}let o=i.java;return o&&javaMismatch(o)&&a++,a}function runToolchainGate(e){let t=w.join(e,`mise.toml`);if(!o(t))return 0;if(miseIsAbsent(e))return I.error('mise.toml declares this repo\'s toolchain, but mise is not on PATH. Install it (https://mise.jdx.dev/getting-started.html), then add `eval "$(mise activate bash)"` to ~/.bashrc for interactive shells and `eval "$(mise activate bash --shims)"` to ~/.profile, so editors, git hooks, and AI sessions get the same tools. If this repo\'s mise.toml has an [env] block, also add the directory your checkouts live in to `trusted_config_paths` in ~/.config/mise/config.toml.'),1;let n=readDeclaredTools(t);return n?checkDeclaredToolsActive(e,n):0}const rawLog$1=e=>console.log(e),cs=j({meta:{name:`repo:sync`,description:`Detect, generate, and sync project tooling (idempotent). Before it generates anything it lints compose files: an override compose file needs its own top-level name:, and no two compose files in a directory may share one. It also refuses a publishable package that has no publishConfig.registry, and reports it without repairing it.`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Target directory (default: current directory)`,required:!1},check:{type:`boolean`,description:`Dry-run mode: report drift without writing files. Exits 1 on drift, on a generator failure, or on a failed gate. Drift found only under .forgejo/workflows/ or .github/workflows/ is advisory: it prints the ::bst-checks:: warn marker and exits 0.`},yes:{type:`boolean`,alias:`y`,description:`Accept all defaults (non-interactive)`},"eslint-plugin":{type:`boolean`,description:`Include @bensandee/eslint-plugin (default: true)`},ci:{type:`boolean`,default:!0,description:`Generate the CI workflow (default). --no-ci skips CI workflow generation.`},prompt:{type:`boolean`,default:!0,description:`Generate the migration prompt (default). --no-prompt skips it, and skips the first-run stack prompt.`},json:{type:`boolean`,description:`Emit one JSON document: status (up-to-date | drift | workflow-drift | failed), actionable, failed, checkOnlyImages, aptSteps, inertAgentKeys, privateRelease, miseAdvisories, warnCount, exitCode. --check only: the write mode prompts and inherits child streams.`}},async run({args:e}){let t=w.resolve(e.dir??`.`),n=createCliOutput(e.json===!0);if((e.json===!0||isJsonMode())&&e.check!==!0)throw new T(`--json is granted to repo:sync --check only: the write mode prompts on a first run and inherits pnpm install's streams.`);if(e.check){let e=await runCheckReport(t);n.json(e),process.exitCode=e.exitCode;return}let r={eslintPlugin:typeof e[`eslint-plugin`]==`boolean`?e[`eslint-plugin`]:void 0,noCi:e.ci===!1};if(loadToolingConfigStrict(t)){failedResults(await runUpdate(t,r)).length>0&&(process.exitCode=1);return}let i=createDockerDiscoveryMemo();if(runComposeLintGate(t,void 0,i)>0){process.exitCode=1;return}let a=e.yes?buildDefaultConfig(t,r):await runInitPrompts(t,void 0,{skipStackPrompt:e.prompt===!1});runReleaseTargetGate(a,t),(runPublishConfigGate(a,t)>0||failedResults(await runInit(a,{noPrompt:e.prompt===!1,dockerDiscovery:i})).length>0)&&(process.exitCode=1)}});async function runUpdateReport(e,t={},n={}){let r=createDockerDiscoveryMemo(),i=loadToolingConfigStrict(e);if(!i)return I.error("No .tooling.json found. Run `pnpm exec bst repo:sync` first to initialize the project."),process.exitCode=1,{status:`stopped`,results:[],install:`not-run`};if(warnStaleChecksAdd(i),warnUnconfiguredDefaultBranch(e,i),warnCoveredChecksAdd(i,e),runInertAgentSettingsGate(i),runComposeLintGate(e,i,r)>0)return process.exitCode=1,{status:`stopped`,results:[],install:`not-run`};let a=mergeWithSavedConfig(buildDefaultConfig(e,t),i);return runReleaseTargetGate(a,e),runVersionStampGate(i,e,a.releaseStrategy),runSnapshotConfigGate(i,e,a.structure)>0||(runPrivateReleaseAdvisory(a,i,e),runPublishConfigGate(a,e)>0)?(process.exitCode=1,{status:`stopped`,results:[],install:`not-run`}):{status:`ran`,...await runInitReport(a,{noPrompt:!0,confirmOverwrite:async()=>`overwrite`,dockerDiscovery:r,installOutput:n.installOutput})}}async function runUpdate(e,t={}){return(await runUpdateReport(e,t)).results}function gateFailure(){return{status:`failed`,actionable:[],failed:[],checkOnlyImages:[],aptSteps:[],inertAgentKeys:[],privateRelease:[],miseAdvisories:[],warnCount:0,exitCode:1}}function advisoryWarnCount(e){return e.checkOnlyImages.length+e.aptSteps.length+e.privateRelease.length+e.miseAdvisories.length+ +(e.inertAgentKeys.length>0)}function upToDateReport(e){let t=advisoryWarnCount(e);return t>0?isJsonMode()||rawLog$1(formatWarnMarker(t)):I.success(`Repository is up to date.`),{status:`up-to-date`,actionable:[],failed:[],checkOnlyImages:e.checkOnlyImages,aptSteps:e.aptSteps,inertAgentKeys:e.inertAgentKeys,privateRelease:e.privateRelease,miseAdvisories:e.miseAdvisories,warnCount:t,exitCode:0}}async function runCheckReport(e){let t=createDockerDiscoveryMemo(),n=loadToolingConfigStrict(e);if(warnUnconfiguredDefaultBranch(e,n),n&&(warnStaleChecksAdd(n),warnCoveredChecksAdd(n,e)),runComposeLintGate(e,n,t)>0)return gateFailure();let r=buildDefaultConfig(e,{}),i=n?mergeWithSavedConfig(r,n):r;if(runReleaseTargetGate(i,e)||runVersionStampGate(n,e,i.releaseStrategy)>0||runSnapshotConfigGate(n,e,i.structure)>0||runPublishConfigGate(i,e)>0||runToolchainGate(e)>0)return gateFailure();let a={checkOnlyImages:runCheckOnlyImageGate(i,e,t),aptSteps:runWorkflowAptGate(e),inertAgentKeys:runInertAgentSettingsGate(n),privateRelease:runPrivateReleaseAdvisory(i,n,e),miseAdvisories:runMiseAdvisoryGate(e,n)},{ctx:o,pendingWrites:s}=createDryRunContext(i,t);logDetectionSummary(o);let c=await runGenerators(o),l=failedResults(c);reportFailures(l,`repo:sync`);let u=actionableResults(c,s,e),d=advisoryWarnCount(a);if(u.length===0&&l.length===0)return upToDateReport(a);if(u.length===0)return{status:`failed`,actionable:[],failed:l,checkOnlyImages:[],aptSteps:[],inertAgentKeys:[],privateRelease:[],miseAdvisories:[],warnCount:0,exitCode:1};I.warn(`${u.length} file(s) would be changed by repo:sync`);for(let t of u)logActionableChange(t,e,s);if(l.length===0&&u.every(e=>isWorkflowDirPath(e.filePath))){let e=u.length+d;return isJsonMode()||rawLog$1(formatWarnMarker(e)),{status:`workflow-drift`,actionable:u,failed:[],checkOnlyImages:a.checkOnlyImages,aptSteps:a.aptSteps,inertAgentKeys:a.inertAgentKeys,privateRelease:a.privateRelease,miseAdvisories:a.miseAdvisories,warnCount:e,exitCode:0}}return{status:`drift`,actionable:u,failed:l,checkOnlyImages:[],aptSteps:[],inertAgentKeys:[],privateRelease:[],miseAdvisories:[],warnCount:0,exitCode:1}}function actionableResults(e,t,n){return e.filter(e=>{if(e.action===`removed`)return!0;if(e.action!==`created`&&e.action!==`updated`)return!1;let r=t.get(e.filePath);if(r!==void 0&&e.action===`updated`){let t=w.join(n,e.filePath),i=o(t)?p(t,`utf-8`):void 0;if(i&&contentEqual(e.filePath,i,r))return!1}return!0})}function isBundledFile(e){return e.endsWith(`bst-hook.mjs`)}function logActionableChange(e,t,n){I.info(` ${e.action}: ${e.filePath} -- ${e.description}`);let r=n.get(e.filePath);if(r===void 0)return;let i=w.join(t,e.filePath),a=o(i)?p(i,`utf-8`):void 0;if(isBundledFile(e.filePath))I.info(` bundled file changed (${formatBytes(a?.length??0)} -> ${formatBytes(r.length)})`);else if(a){let e=lineDiff(a,r);for(let t of e)I.info(` ${t}`)}else{let e=r.split(`
|
|
6058
|
+
`).length-1;I.info(` + ${e} new lines`)}}function formatBytes(e){return e<1024?`${String(e)} B`:`${(e/1024).toFixed(1)} kB`}const normalize$1=e=>e.trimEnd();function lineDiff(e,t){let n=e.split(`
|
|
6055
6059
|
`).map(normalize$1),r=t.split(`
|
|
6056
|
-
`).map(normalize$1),i=new Set(n),a=new Set(r),o=n.filter(e=>e.trim()!==``&&!a.has(e)),s=r.filter(e=>e.trim()!==``&&!i.has(e)),c=[];for(let e of o)c.push(`- ${e.trim()}`);for(let e of s)c.push(`+ ${e.trim()}`);return c}function buildGitAuth(e){let t=e.serverUrl.replace(/^https?:\/\//,``);return{args:[`-c`,`http.${e.serverUrl}/.extraheader=`],url:`https://x-access-token:${e.token}@${t}/${e.repository}`}}const
|
|
6060
|
+
`).map(normalize$1),i=new Set(n),a=new Set(r),o=n.filter(e=>e.trim()!==``&&!a.has(e)),s=r.filter(e=>e.trim()!==``&&!i.has(e)),c=[];for(let e of o)c.push(`- ${e.trim()}`);for(let e of s)c.push(`+ ${e.trim()}`);return c}function buildGitAuth(e){let t=e.serverUrl.replace(/^https?:\/\//,``);return{args:[`-c`,`http.${e.serverUrl}/.extraheader=`],url:`https://x-access-token:${e.token}@${t}/${e.repository}`}}const ls=[`WIP:`,`[WIP]`];function hasWipPrefix(e){return matchedWipPrefix(e)!==void 0}function matchedWipPrefix(e){let t=e.toLowerCase();return ls.find(e=>t.startsWith(e.toLowerCase()))}function stripWipPrefix(e){let t=matchedWipPrefix(e);return t===void 0?e:e.slice(t.length).trimStart()}const us=P.object({number:P.number(),html_url:P.string().optional()});function prWebUrl(e,t){return`${e.serverUrl}/${e.repository}/pulls/${String(t)}`}function headOfThisRepo(e,t){let n=e.repository.toLowerCase();return e=>e.headRef===t&&e.headRepo!==null&&e.headRepo.toLowerCase()===n}async function findOpenPrEntry(e,t,n,r=null){let i=headOfThisRepo(t,n),a=!1,o=(await listPulls(e,t,{state:`open`,stopWhen:i,onPageCap:()=>{a=!0},signal:r})).find(i);if(o!==void 0){if(o.baseRef===null)throw new D(`Open PR #${String(o.number)} on ${t.repository} carries no base branch`);return{number:o.number,base:o.baseRef}}if(a)throw new T(`Open PR lookup on ${t.repository} for head "${n}" hit the 20-page cap without finding it or reaching an empty page; a truncated read here reads as "no open PR" and makes a caller create a duplicate`);return null}async function findOpenPr(e,t,n,r=null){return(await findOpenPrEntry(e,t,n,r))?.number??null}async function listBranchPulls(e,t,n,r,i=null){let a=!1,o=await listPulls(e,t,{state:r,head:n,onPageCap:()=>{a=!0},signal:i}),s=headOfThisRepo(t,n),c=o.filter(s).map(e=>({number:e.number,base:e.baseRef,merged:e.merged}));if(a)throw new T(`Pull request listing on ${t.repository} for branch "${n}" hit the 20-page cap without reaching an empty page, so it cannot say how many pull requests that branch has; pass the pull request NUMBER instead of autodetecting it.`);return c}const ds=P.object({number:P.number(),title:P.string().nullish(),body:P.string().nullish(),head:P.object({ref:P.string(),repo:P.object({full_name:P.string()}).nullish()}),base:P.object({ref:P.string()}).nullish(),state:P.enum([`open`,`closed`]),merged:P.boolean().nullish(),merged_at:P.string().nullish(),html_url:P.string().nullish(),draft:P.boolean().nullish(),user:P.object({login:P.string().nullish()}).nullish(),updated_at:P.string().nullish(),labels:P.array(P.object({name:P.string()})).nullish()});function updatedBefore(e){return t=>t.updatedAt!==null&&Date.parse(t.updatedAt)<e}async function listPulls(e,t,n={}){let r=n.startPage??1;if(!Number.isInteger(r)||r<1)throw new T(`Cannot list PRs on ${t.repository}: startPage must be an integer of at least 1, got ${String(r)}`);let i=r+20-1,a={Authorization:`token ${t.token}`},o=[];for(let s=r;s<=i;s++){n.signal?.throwIfAborted();let r=new URLSearchParams({state:n.state??`all`,limit:`50`,page:String(s)}),c=n.updatedSince===void 0?n.sort:`recentupdate`;c!==void 0&&r.set(`sort`,c);for(let e of n.labelIds??[])r.append(`labels`,String(e));n.head!==void 0&&r.set(`head`,n.head);let l=`${t.serverUrl}/api/v1/repos/${t.repository}/pulls?${r.toString()}`,u=await e.fetch(l,{headers:a,signal:n.signal??null});u.ok||await throwForgejoFailure(u,{verb:`list PRs`,resource:t.repository});let d=ds.array().safeParse(await u.json());if(!d.success)throw new D(`Unexpected PR list response: ${d.error.message}`);let f=d.data.map(e=>({number:e.number,title:e.title??null,body:e.body??null,headRef:e.head.ref,headRepo:e.head.repo?.full_name??null,baseRef:e.base?.ref??null,state:e.state,merged:e.merged??e.merged_at!=null,mergedAt:e.merged_at??null,url:e.html_url??null,draft:e.draft??null,author:e.user?.login??null,updatedAt:e.updated_at??null,labels:(e.labels??[]).map(e=>e.name)}));if(o.push(...f),f.length===0||n.stopWhen!==void 0&&f.some(n.stopWhen)||n.updatedSince!==void 0&&f.some(updatedBefore(n.updatedSince))||n.limit!==void 0&&o.length>=n.limit)break;s===i&&(U.warn(`PR listing on ${t.repository} hit the 20-page cap without an empty page; results may be truncated`),n.onPageCap?.(i))}return o}async function createPr(e,t,n){let r=`${t.serverUrl}/api/v1/repos/${t.repository}/pulls`,i={title:n.title,head:n.head,base:n.base};n.body&&(i.body=n.body);let a=await e.fetch(r,{method:`POST`,headers:{Authorization:`token ${t.token}`,"Content-Type":`application/json`},body:JSON.stringify(i)});a.ok||await throwForgejoFailure(a,{verb:`create PR`,resource:`${n.head}->${n.base}`});let o=us.safeParse(await a.json());if(!o.success)throw new D(`Unexpected create-PR response: ${o.error.message}`);return{number:o.data.number,htmlUrl:o.data.html_url??prWebUrl(t,o.data.number)}}P.object({body:P.string().nullish()});async function readPrField(e,t,n,r,i){let a=`${t.serverUrl}/api/v1/repos/${t.repository}/pulls/${String(n)}`,o=await e.fetch(a,{headers:{Authorization:`token ${t.token}`}});o.ok||await throwForgejoFailure(o,{verb:`read PR ${i}`,resource:`#${String(n)}`});let s=r.safeParse(await o.json());if(!s.success)throw new D(`Unexpected PR ${i} response: ${s.error.message}`);return s.data}P.object({head:P.object({ref:P.string()})}),P.object({head:P.object({ref:P.string()}),base:P.object({ref:P.string()})});const fs=P.object({ref:P.string(),sha:P.string(),repo:P.object({full_name:P.string()}).nullish()}),ps=P.object({head:fs,base:fs,draft:P.boolean(),merged:P.boolean(),mergeable:P.boolean().nullish(),merge_commit_sha:P.string().nullish(),state:P.string()});function parsePrDetailOrThrow(e){let t=ps.safeParse(e);if(!t.success)throw new D(`Unexpected PR detail response: ${t.error.message}`);return t.data}const ms=/^[0-9a-f]{7,64}$/;function isMergeCommitSha(e){return e!=null&&ms.test(e)}function normalizePrDetail(e){return{head:{ref:e.head.ref,sha:e.head.sha,repo:e.head.repo?.full_name??null},base:{ref:e.base.ref,sha:e.base.sha,repo:e.base.repo?.full_name??null},draft:e.draft,merged:e.merged,mergeable:e.mergeable??null,mergeCommitSha:isMergeCommitSha(e.merge_commit_sha)?e.merge_commit_sha:null,state:e.state}}async function getForgejoPrDetail(e,t,n){return normalizePrDetail(await readPrField(e,t,n,ps,`detail`))}const hs=P.object({state:P.string(),merged:P.boolean(),draft:P.boolean(),title:P.string(),head:P.object({ref:P.string()}),base:P.object({ref:P.string()}),mergeable:P.boolean().nullish(),html_url:P.string().optional()});async function getPrEditState(e,t,n){let r=await readPrField(e,t,n,hs,`edit state`);return{state:r.state,merged:r.merged,draft:r.draft,title:r.title,head:r.head.ref,base:r.base.ref,mergeable:r.mergeable??null,url:r.html_url??prWebUrl(t,n)}}async function retargetPr(e,t,n,r){let i=`${t.serverUrl}/api/v1/repos/${t.repository}/pulls/${String(n)}`,a=await e.fetch(i,{method:`PATCH`,headers:{Authorization:`token ${t.token}`,"Content-Type":`application/json`},body:JSON.stringify({base:r})},{idempotent:!0});a.ok||await throwForgejoFailure(a,{verb:`retarget PR`,resource:`#${String(n)}`})}async function reopenPr(e,t,n){let r=`${t.serverUrl}/api/v1/repos/${t.repository}/pulls/${String(n)}`,i=await e.fetch(r,{method:`PATCH`,headers:{Authorization:`token ${t.token}`,"Content-Type":`application/json`},body:JSON.stringify({state:`open`})},{idempotent:!0});i.ok||await throwForgejoFailure(i,{verb:`reopen PR`,resource:`#${String(n)}`})}const gs=P.object({title:P.string(),body:P.string().nullish()});async function getPrContent(e,t,n){let r=await readPrField(e,t,n,gs,`content`);return{title:r.title,body:r.body??``}}P.object({title:P.string(),draft:P.boolean()});async function updatePr(e,t,n,r){if(r.title===void 0&&r.body===void 0)return;let i=`${t.serverUrl}/api/v1/repos/${t.repository}/pulls/${String(n)}`,a=await e.fetch(i,{method:`PATCH`,headers:{Authorization:`token ${t.token}`,"Content-Type":`application/json`},body:JSON.stringify({title:r.title,body:r.body})},{idempotent:!0});a.ok||await throwForgejoFailure(a,{verb:`update PR`,resource:`#${String(n)}`})}const _s=P.object({id:P.number(),body:P.string(),commit_id:P.string().nullish(),user:P.object({login:P.string()}).nullish(),html_url:P.string().nullish(),submitted_at:P.string().nullish()});P.array(_s),P.object({head:P.object({sha:P.string()})});const vs=P.object({body:P.string(),path:P.string().optional(),diff_hunk:P.string().optional(),user:P.object({login:P.string()}).nullish()});P.array(vs),P.array(P.object({id:P.number()}));function childOutput(e){return[e.stdout,e.stderr].filter(e=>e.trim()!==``).join(`
|
|
6057
6061
|
`)}function defaultBranchRef(e){return`refs/heads/${e.defaultBranch}`}function readRemoteRef(e,t,n,r){let i=e.exec(`git`,[...n.args,`ls-remote`,n.url,r],{cwd:t.cwd});return i.exitCode===0?i.stdout.split(`
|
|
6058
|
-
`).find(e=>e.trim().endsWith(`\t${r}`))?.split(` `)[0]?.trim()??``:null}function isSuperseded(e,t,n,r){let i=readRemoteRef(e,t,n,defaultBranchRef(t));return i===null||i===``||r===``?(debug(t,`Supersession check: ${t.defaultBranch} tip or base commit unreadable -- proceeding`),!1):i!==r&&(
|
|
6062
|
+
`).find(e=>e.trim().endsWith(`\t${r}`))?.split(` `)[0]?.trim()??``:null}function isSuperseded(e,t,n,r){let i=readRemoteRef(e,t,n,defaultBranchRef(t));return i===null||i===``||r===``?(debug(t,`Supersession check: ${t.defaultBranch} tip or base commit unreadable -- proceeding`),!1):i!==r&&(I.warn(`Superseded release run: this job versioned ${r}, but ${t.defaultBranch} has advanced to ${i}. A newer run is versioning a superset of these changesets -- skipping to avoid overwriting its version commit on ${versionPrBranch(t.defaultBranch)}.`),!0)}const ys=/^## (\d+\.\d+\.\d+(?:-[^\s)]+)?)$/gm;function todayIso(){return(/* @__PURE__ */ new Date()).toISOString().slice(0,10)}function stampDates(e,t){return e.replace(ys,`## $1 (${t})`)}function stampChangelogDates(e,t,n,r){let i=todayIso(),a=r?n.map(e=>w.join(t,`packages`,e,`CHANGELOG.md`)):[w.join(t,`CHANGELOG.md`)];for(let t of a){let n=e.readFile(t);if(!n)continue;let r=stampDates(n,i);r!==n&&e.writeFile(t,r)}}function extractLatestEntry(e){let t=e.split(`
|
|
6059
6063
|
`),n=-1,r=t.length;for(let e=0;e<t.length;e++)if(t[e]?.startsWith(`## `)){if(n===-1)n=e;else{r=e;break}}return n===-1?null:t.slice(n,r).join(`
|
|
6060
6064
|
`).trim()}function readRootPackage(e,t){let n=e.readFile(w.join(t,`package.json`));if(!n)return null;let r=parsePackageJson(n);return!r?.name||!r.version?null:{name:r.name,version:r.version}}function buildPrContent(e,t,n){let r=e.listWorkspacePackages(t);if(!(n.length>0||r.length>0)){let n=readRootPackage(e,t);if(n){let r=e.readFile(w.join(t,`CHANGELOG.md`)),i=r?extractLatestEntry(r):null;return{title:`chore: release ${n.name}@${n.version}`,body:i??``}}return{title:`chore: version packages`,body:``}}let i=new Map(n.map(e=>[e.name,e.version])),a=r.filter(e=>i.get(e.name)!==e.version);if(a.length===0)return{title:`chore: version packages`,body:``};let o=`chore: release ${a.map(e=>`${e.name}@${e.version}`).join(`, `)}`,s=[];for(let n of a){let r=w.join(t,`packages`,n.dir,`CHANGELOG.md`),i=e.readFile(r),a=i?extractLatestEntry(i):null;if(a){let e=a.replace(/^## .+/,`## ${n.name}@${n.version}`);s.push(e)}}return{title:o,body:s.join(`
|
|
6061
6065
|
|
|
6062
|
-
`)}}async function runVersionMode(e,t){
|
|
6063
|
-
`),debug(t,`Temporarily disabled changeset commit:true`)}}let d=e.exec(`pnpm`,[`changeset`,`version`],{cwd:t.cwd});if(debugExec(t,`pnpm changeset version`,d),u&&e.writeFile(l,u),d.exitCode!==0)throw new T(`pnpm changeset version failed (exit code ${String(d.exitCode)}):\n${childOutput(d)}`);let f=e.listWorkspacePackages(t.cwd),p=c.length>0||f.length>0;if(debug(t,`Repo type: ${p?`monorepo`:`single-package`}`),p){let n=new Map(c.map(e=>[e.name,e.version])),r=f.filter(e=>n.get(e.name)!==e.version).map(e=>e.dir);debug(t,`Changed packages: ${r.length>0?r.join(`, `):`(none)`}`),stampChangelogDates(e,t.cwd,r,!0)}else stampChangelogDates(e,t.cwd,[],!1);let m=e.exec(`pnpm`,[`install`,`--no-frozen-lockfile`],{cwd:t.cwd});if(debugExec(t,`pnpm install --no-frozen-lockfile`,m),m.exitCode!==0)throw new T(`pnpm install --no-frozen-lockfile failed (exit code ${String(m.exitCode)}):\n${childOutput(m)}`);let{title:h,body:g}=buildPrContent(e,t.cwd,c);debug(t,`PR title: ${h}`);let _=e.exec(`git`,[`add`,`-A`],{cwd:t.cwd});if(_.exitCode!==0)throw new T(`git add failed: ${_.stderr||_.stdout}`);let v=e.listChangesetFiles(t.cwd);v.length>0&&
|
|
6064
|
-
`).filter(e=>e.trim()!==``)),o=[];for(let n of r){if(!a.has(n.path))continue;let r=showManifest(e,t.cwd,`HEAD~1`,n.path),i=showManifest(e,t.cwd,`HEAD`,n.path);if(r===void 0||i===void 0)continue;let s=r.version,c=i.version;s!==void 0&&c!==void 0&&s!==c&&i.name!==void 0&&o.push({name:i.name,version:c,tag:releaseTag({name:i.name,version:c,root:n.root}),private:i.private??!1,access:readAccess(i.publishConfig)})}return o}function readAccess(e){if(e===void 0)return;let t=ns.safeParse(e);return t.success?t.data.access:void 0}const rs=N.object({login:N.string(),email:N.string().nullish()});async function getAuthenticatedUser(e,t,n=null){let r=await e.fetch(`${t.serverUrl}/api/v1/user`,{headers:authHeaders(t),signal:n});if(!r.ok)return{ok:!1,httpStatus:r.status,statusText:r.statusText};let i=rs.safeParse(await r.json());if(!i.success)throw new D(`Unexpected /user response: ${i.error.message}`);return{ok:!0,login:i.data.login,email:i.data.email||null}}function noreplyEmail(e,t){return`${t}@noreply.${e.replace(/^https?:\/\//,``)}`}const is=12e4;function sleep(e){return new Promise(t=>{setTimeout(t,e)})}function ciActorName(e){return e===`github`?`github-actions[bot]`:`forgejo-actions[bot]`}function ciActorEmail(e){let t=ciActorName(e);return e===`github`?`${t}@users.noreply.github.com`:`${t}@noreply.localhost`}async function readUser(e,t,n,r,i){let a;try{a=await getAuthenticatedUser(e,t,n)}catch(e){if(!(e instanceof D))throw e;F.warn(`Could not parse Forgejo user response${i}`);return}if(!a.ok)F.warn(`Could not resolve ${r} (${String(a.httpStatus)} ${a.statusText})${i}`);else return a}async function resolveForgejoIdentity(e,t,n=null){let r=await readUser(e,t,n,`Forgejo identity`,` -- falling back to bot identity`);if(r)return{name:r.login,email:r.email??noreplyEmail(t.serverUrl,r.login)}}async function configureGitIdentity(e,t,n,r,i=null){let a,o,s=t===`forgejo`&&r?await resolveForgejoIdentity(e,r,i):void 0;s?{name:a,email:o}=s:(a=ciActorName(t),o=ciActorEmail(t));let c={cwd:n,timeoutMs:J,signal:i};return await e.execStream(`git`,[`config`,`user.name`,a],c),await e.execStream(`git`,[`config`,`user.email`,o],c),{name:a,email:o}}const as=A({meta:{name:`release:changesets`,description:`Changesets version/publish for Forgejo CI`},args:{"dry-run":{type:`boolean`,description:`Skip push, API calls, and publishing side effects`},verbose:{type:`boolean`,description:`Enable detailed debug logging (also enabled by TOOLING_DEBUG env var)`},json:{type:`boolean`,description:`Emit one JSON document: mode (version | publish | none), tags, pr (created | updated | none, or null), versioned (created | updated | none | failed, or null), dryRun. Every key is always present. tags is empty unless mode is publish; pr is null unless mode is version; versioned is null unless mode is publish and pending changesets were versioned after publishing.`}},async run({args:e}){let t=createCliOutput(e.json===!0),r=e[`dry-run`]===!0,i=await runRelease(buildReleaseConfig({dryRun:r,verbose:e.verbose===!0||isEnvVerbose()}),createRealExecutor$1(),processCiEventSource());if(t.json(releasePayload(i,r)),i.mode===`publish`){let e=process.env.GITHUB_OUTPUT;if(e)try{let t=i.tags[0]??``;n(e,`published=true\ntag=${t}\nversion=${versionFromTag(t)}\n`)}catch{}}i.mode===`none`&&(process.exitCode=0)}});function versionFromTag(e){if(e===``)return``;if(e.startsWith(`v`)&&!e.includes(`@`))return e.slice(1);let t=e.lastIndexOf(`@`);return t<=0?``:e.slice(t+1)}function releasePayload(e,t){return e.mode===`version`?{mode:`version`,tags:[],pr:e.pr,versioned:null,dryRun:t}:e.mode===`publish`?{mode:`publish`,tags:e.tags,pr:null,versioned:e.versioned??null,dryRun:t}:{mode:`none`,tags:[],pr:null,versioned:null,dryRun:t}}function buildReleaseConfig(e){let t=resolveConnection(process.cwd());if(t.type!==`forgejo`)throw new T(`release:changesets requires a Forgejo repository`);return{...t.conn,cwd:process.cwd(),defaultBranch:readConfiguredDefaultBranch(process.cwd()),dryRun:e.dryRun??!1,verbose:e.verbose??!1}}function getCurrentBranch(e,t){let n=process.env.GITHUB_REF;return n?.startsWith(`refs/heads/`)?n.slice(11):e.exec(`git`,[`rev-parse`,`--abbrev-ref`,`HEAD`],{cwd:t}).stdout.trim()}async function runRelease(e,t,n){debug(e,`Repository: ${e.repository} on ${e.serverUrl}`),debug(e,`Config: dryRun=${String(e.dryRun)}`);let r=getCurrentBranch(t,e.cwd);if(debug(e,`Current branch: ${r}`),r!==e.defaultBranch)return debug(e,`Skipping release: ${r} is not the configured default branch (${e.defaultBranch})`),{mode:`none`};refuseForgeDefaultMismatch(e.defaultBranch,n,`release:changesets`);let i=await configureGitIdentity(t,`forgejo`,e.cwd,e);F.info(`Git identity: ${i.name} <${i.email}>`);let a=t.listChangesetFiles(e.cwd);debug(e,`Changeset files found: ${a.length>0?a.join(`, `):`(none)`}`);let o=readBumpedSet(t,e),s=headBumpedVersion(o);return s&&a.length>0?(F.info(`HEAD bumped a version and changesets are still pending (${a.join(`, `)}) -- publishing the merged version first, then versioning the rest.`),debug(e,`Entering publish mode, then version mode`),publishThenVersion(t,e,o)):a.length>0?(debug(e,`Entering version mode`),runVersionMode(t,e)):s?(debug(e,`Entering publish mode`),runPublishMode(t,e,o)):(F.info(`No changesets, and HEAD bumped no package version -- nothing to release. (Publishing runs on the commit that merges a 'version packages' PR.)`),debug(e,`Publish guard: HEAD is not a version-bump commit -- skipping publish`),{mode:`none`})}async function publishThenVersion(e,t,n){let r=await runPublishMode(e,t,n);if(r.mode!==`publish`)return runVersionMode(e,t);let i=e.exec(`git`,[`rev-parse`,`HEAD`],{cwd:t.cwd}),a=i.exitCode===0?i.stdout.trim():``;if(a===``){let e=`Could not read HEAD after publishing, so the changesets still pending are not versioned by this run: ${i.stderr||i.stdout} The version PR waits for the next push to main rather than versioning a checkout this run could not put back.`;return F.warn(e),note(e,`Version PR not rewritten`),{...r,versioned:`failed`}}try{let n=await runVersionMode(e,t);return{...r,versioned:n.mode===`version`?n.pr:`none`}}catch(e){let t=`The packages are published and tagged, but the version PR was not rewritten by this run: ${O(e)}. The next push to main rewrites it.`;return F.warn(t),note(t,`Version PR not rewritten`),{...r,versioned:`failed`}}finally{restorePublishedCheckout(e,t,a)}}function headBumpedVersion(e){return e.length>0}function restorePublishedCheckout(e,t,n){debug(t,`Restoring the checkout to the published commit ${n}`);let r=e.exec(`git`,[`reset`,`--hard`,n],{cwd:t.cwd});if(r.exitCode!==0)throw new T(`Could not restore the checkout to the published commit ${n}: ${r.stderr||r.stdout}`)}const os=N.object({id:N.number(),index_in_repo:N.number().nullish(),workflow_id:N.string().nullish(),title:N.string().nullish(),prettyref:N.string().nullish(),commit_sha:N.string().nullish(),event:N.string().nullish(),status:N.string().nullish(),started:N.string().nullish(),stopped:N.string().nullish(),duration:N.number().nullish(),html_url:N.string().nullish()});N.object({workflow_runs:N.array(os)});const ss=N.object({id:N.number(),name:N.string(),status:N.string()});N.array(ss),N.object({workflow_runs:N.array(os)});async function dispatchWorkflow$1(e,t,n){let r=n.repository??t.repository,i=`${t.serverUrl}/api/v1/repos/${r}/actions/workflows/${encodeURIComponent(n.workflow)}/dispatches`,a={ref:n.ref};Object.keys(n.inputs).length>0&&(a.inputs=n.inputs);let o=await e.fetch(i,{method:`POST`,headers:jsonHeaders(t),body:JSON.stringify(a)});if(!o.ok)throw new T(await forgejoErrorMessage(o,{verb:`dispatch workflow`,resource:n.workflow,ref:n.ref}));return{repository:r,workflow:n.workflow,ref:n.ref,inputs:n.inputs}}async function dispatchWorkflow(e,t,n){return e.type===`forgejo`?dispatchForgejo(e.conn,t,n):dispatchGitHub(t,n)}async function dispatchForgejo(e,t,n){let r=await dispatchWorkflow$1(n,e,{...t.repo===void 0?{}:{repository:t.repo},workflow:t.workflow,ref:t.ref,inputs:t.inputs});return F.info(`Dispatched ${r.workflow} on ${r.repository} (ref: ${r.ref})`),{host:`forgejo`,repo:r.repository,workflow:r.workflow,ref:r.ref,inputs:r.inputs}}function dispatchGitHub(e,t){let n=Object.entries(e.inputs).flatMap(([e,t])=>[`-f`,`${e}=${t}`]),r=e.repo?[`--repo`,e.repo]:[],i=t.exec(`gh`,[`workflow`,`run`,e.workflow,...r,`--ref`,e.ref,...n],{cwd:process.cwd()});if(i.exitCode!==0)throw new T(`Failed to dispatch workflow on GitHub: ${i.stderr||i.stdout||`unknown error`}`);let a=e.repo??parseRepositoryUrl(process.cwd())?.repository??null;return F.info(`Dispatched ${e.workflow} on ${a??`current repository`} (ref: ${e.ref})`),{host:`github`,repo:a,workflow:e.workflow,ref:e.ref,inputs:e.inputs}}const cs=A({meta:{name:`release:trigger`,description:`Trigger the release CI workflow. Dispatches release.yml through the Forgejo API, or with gh workflow run on GitHub.`},args:{ref:{type:`string`,description:`Git ref to trigger on (default: .tooling.json#defaultBranch, else main)`,required:!1},bump:{type:`string`,description:`Version bump type: auto, major, minor, patch, or first-release`,required:!1},prerelease:{type:`string`,description:`Create a prerelease with the given tag (e.g., beta, alpha)`,required:!1},json:{type:`boolean`,description:`Emit one JSON document: status (dispatched), host (forgejo | github), repo (owner/repo, or null), workflow, ref, inputs. status is always dispatched; repo is null when GitHub cannot name it.`}},async run({args:e}){let t=createCliOutput(e.json===!0),n=e.ref??readConfiguredDefaultBranch(process.cwd()),r={};e.bump&&(r.bump=e.bump),e.prerelease&&(r.prerelease=e.prerelease);let i=await dispatchWorkflow(resolveConnection(process.cwd()),{repo:void 0,workflow:`release.yml`,ref:n,inputs:r},createRealExecutor$1());t.json({status:`dispatched`,...i})}}),ls=N.object({id:N.number(),name:N.string(),color:N.string().optional(),description:N.string().optional(),exclusive:N.boolean().optional()}),us=N.array(ls);async function fetchAllForgejoLabels(e,t){let n=[];for(let r=1;r<=20;r++){let i=await e.fetch(`${t.serverUrl}/api/v1/repos/${t.repository}/labels?limit=50&page=${String(r)}`,{headers:authHeaders(t)});i.ok||await throwForgejoFailure(i,{verb:`list labels`,resource:t.repository},repoNotFoundMessage(t));let a=us.safeParse(await i.json());if(!a.success)throw new D(`Unexpected label-list response: ${a.error.message}`);if(n.push(...a.data),!morePagesFollow(i,a.data.length,n.length,50))break}return n}async function resolveLabelIds(e,t,n){if(n.length===0)return[];let r=await fetchAllForgejoLabels(e,t);return n.map(e=>{let n=r.find(t=>t.name===e);if(n===void 0){let n=r.map(e=>e.name).join(`, `);throw new T(`No label named "${e}" found among the repository's labels in ${t.repository} (organization-level labels are not searched). Known labels: ${n}`)}return n.id})}const ds=N.strictObject({name:N.string().min(1),color:N.string().regex(/^#[0-9a-fA-F]{6}$/),description:N.string(),exclusive:N.boolean().optional()});N.record(N.string(),N.array(ds));const fs=N.object({id:N.number(),type:N.string(),body:N.string().nullish(),created_at:N.string(),label:N.object({name:N.string()}).nullish(),user:N.object({login:N.string()}).nullish()});N.array(fs).nullable();async function resolveLabelId(e,t,n,r){let i=r?.get(n);if(i!==void 0)return i;let[a]=await resolveLabelIds(e,t,[n]);if(a===void 0)throw new D(`Label id resolution returned nothing for "${n}"`);return a}async function addForgejoIssueLabel(e,t,n,r,i){let a=await resolveLabelId(e,t,r,i),o=await e.fetch(`${issuesBase(t)}/${String(n)}/labels`,{method:`POST`,headers:jsonHeaders(t),body:JSON.stringify({labels:[a]})},{idempotent:!0});o.ok||await throwForgejoFailure(o,{verb:`add label`,resource:`#${String(n)}`},issueNotFoundMessage(t,n))}async function removeForgejoIssueLabel(e,t,n,r,i){let a=await resolveLabelId(e,t,r,i),o=await e.fetch(`${issuesBase(t)}/${String(n)}/labels/${String(a)}`,{method:`DELETE`,headers:authHeaders(t)},{idempotent:!0});o.ok||await throwForgejoFailure(o,{verb:`remove label`,resource:`#${String(n)}`},issueNotFoundMessage(t,n))}async function replaceForgejoIssueLabels(e,t,n,r){let i=await e.fetch(`${issuesBase(t)}/${String(n)}/labels`,{method:`PUT`,headers:jsonHeaders(t),body:JSON.stringify({labels:r})},{idempotent:!0});i.ok||await throwForgejoFailure(i,{verb:`replace labels`,resource:`#${String(n)}`},issueNotFoundMessage(t,n))}const ps=N.object({id:N.number(),body:N.string().nullish(),user:N.object({login:N.string()}).nullish(),created_at:N.string(),updated_at:N.string().nullish(),html_url:N.string().nullish(),assets:un.nullish()}),ms=N.array(ps);function parseCommentOrThrow(e){let t=ps.safeParse(e);if(!t.success)throw new D(`Unexpected comment response: ${t.error.message}`);return t.data}function parseCommentListOrThrow(e){let t=ms.safeParse(e);if(!t.success)throw new D(`Unexpected comment-list response: ${t.error.message}`);return t.data}function normalizeComment(e){return{id:e.id,author:e.user?.login??``,createdAt:e.created_at,updatedAt:e.updated_at??e.created_at,body:e.body??``,...e.html_url===void 0||e.html_url===null?{}:{url:e.html_url},attachments:(e.assets??[]).map(normalizeAttachment)}}async function listForgejoComments(e,t,n,r={}){let i=[];for(let a=1;a<=20;a++){let o=new URLSearchParams({limit:`50`,page:String(a)}),s=await e.fetch(`${issuesBase(t)}/${String(n)}/comments?${o.toString()}`,{headers:authHeaders(t)});s.ok||await throwForgejoFailure(s,{verb:`list comments`,resource:`#${String(n)}`},issueNotFoundMessage(t,n));let c=parseCommentListOrThrow(await s.json());if(i.push(...c.map(normalizeComment)),!morePagesFollow(s,c.length,i.length,50))break;a===20&&(H.warn(`Comment listing for #${String(n)} hit the 20-page cap; results may be truncated`),r.onPageCap?.())}return i}const hs=ps.extend({issue_url:N.string().nullish(),pull_request_url:N.string().nullish(),updated_at:N.string().nullish()});N.array(hs);async function addForgejoComment(e,t,n,r){let i=await e.fetch(`${issuesBase(t)}/${String(n)}/comments`,{method:`POST`,headers:jsonHeaders(t),body:JSON.stringify({body:r})});return i.ok||await throwForgejoFailure(i,{verb:`comment on issue`,resource:`#${String(n)}`},issueNotFoundMessage(t,n)),normalizeComment(parseCommentOrThrow(await i.json()))}const gs=/(?:^|[\s([])(clos(?:e|es|ed)|fix(?:es|ed)?|resolv(?:e|es|ed))(?::[ \t]*|[ \t]+)((?:[\w.-]+\/[\w.-]+)?#\d+)(?![\w-])/gim;function capitalize(e){return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}function extractClosingRefs(e){let t=/* @__PURE__ */ new Map;for(let n of e)for(let[,e,r]of n.matchAll(gs)){if(e===void 0||r===void 0)continue;let n=r.toLowerCase();t.has(n)||t.set(n,{text:`${capitalize(e)} ${r}`,issue:r})}return[...t.values()]}function issuesClosedBy(e,t){return issuesInRepository(extractClosingRefs([e]).map(e=>e.issue),t)}function issuesInRepository(e,t){let n=/* @__PURE__ */ new Set;for(let r of e){let e=r.toLowerCase(),i=e.lastIndexOf(`#`),a=e.slice(0,i);(a===``||a===t.toLowerCase())&&n.add(Number(e.slice(i+1)))}let r=[...n];return r.sort((e,t)=>e-t),r}function closedIssues(e){return new Set(extractClosingRefs([e]).map(e=>e.issue.toLowerCase()))}function droppedClosingRefs(e,t){let n=closedIssues(t);return extractClosingRefs(e).filter(e=>!n.has(e.issue.toLowerCase()))}function carryForwardClosingRefs(e,t){let n=droppedClosingRefs([e],t);if(n.length===0)return t;let r=n.map(e=>e.text).join(`
|
|
6065
|
-
`);return t.trim()===``?r:`${t}\n\n${r}`}function parseIssueList(e){let t=/* @__PURE__ */ new Set;for(let n of e.split(`,`)){let r=/^#?([1-9]\d*)$/.exec(n.trim());if(r?.[1]===void 0)throw new T(`--closes takes issue numbers separated by commas, such as 12 or 12,15; got ${JSON.stringify(e)}.`);t.add(Number(r[1]))}return[...t]}function repositoryFromUrl(e){if(!URL.canParse(e))return null;let t=new URL(e).pathname.split(`/`).filter(e=>e!==``);return t.length<2?null:`${t[0]}/${t[1]}`}const _s=N.object({number:N.number(),title:N.string(),state:N.string(),html_url:N.string(),body:N.string().nullish(),user:N.object({login:N.string()}).nullish(),labels:N.array(N.object({name:N.string()})).nullish(),assignees:N.array(N.object({login:N.string()})).nullish(),created_at:N.string(),updated_at:N.string(),closed_at:N.string().nullish(),pull_request:N.unknown().nullish(),assets:N.array(ln).nullish()}),vs=N.array(_s);function parseIssueOrThrow(e){let t=_s.safeParse(e);if(!t.success)throw new D(`Unexpected issue response: ${t.error.message}`);return t.data}function parseIssueListOrThrow(e){let t=vs.safeParse(e);if(!t.success)throw new D(`Unexpected issue-list response: ${t.error.message}`);return t.data}function normalizeIssue(e){return{number:e.number,title:e.title,state:e.state,url:e.html_url,author:e.user?.login??``,labels:(e.labels??[]).map(e=>e.name),createdAt:e.created_at,updatedAt:e.updated_at,closedAt:e.closed_at??null,body:e.body??``,isPullRequest:e.pull_request!==null&&e.pull_request!==void 0,attachments:(e.assets??[]).map(normalizeAttachment),assignees:(e.assignees??[]).map(e=>e.login)}}function backingIssueNumber(e){let t=/Closes #(\d+)/i.exec(e);if(t===null)return null;let n=Number(t[1]);return Number.isNaN(n)?null:n}function toIssueSummaries(e,t=`issues`){let n=e.map(normalizeIssue).map(({body:e,...t})=>{let n=t,r=t.isPullRequest?backingIssueNumber(e):null;if(r!==null&&(n.backingIssue=r),t.isPullRequest){let r=repositoryFromUrl(t.url),i=r===null?[]:issuesClosedBy(e,r);i.length>0&&(n.closesIssues=i)}return n});return t===`issues`?n.filter(e=>!e.isPullRequest):n}async function getForgejoIssue(e,t,n){let r=await e.fetch(`${issuesBase(t)}/${String(n)}`,{headers:authHeaders(t)});return r.ok||await throwForgejoFailure(r,{verb:`get issue`,resource:`#${String(n)}`},issueNotFoundMessage(t,n)),normalizeIssue(parseIssueOrThrow(await r.json()))}const ys=N.object({number:N.number(),state:N.string(),repository:N.object({full_name:N.string()}).nullish()});N.array(ys);function issueListParams(e,t){let n=t.type??e,r=new URLSearchParams(n===`all`?{}:{type:n});return r.set(`state`,t.state),r.set(`limit`,String(t.limit)),t.label!==void 0&&r.set(`labels`,t.label),t.page!==void 0&&r.set(`page`,String(t.page)),t.since!==void 0&&r.set(`since`,t.since),t.sort!==void 0&&r.set(`sort`,t.sort),t.q!==void 0&&r.set(`q`,t.q),r}async function fetchIssueListPage(e,t,n){let r=await e.fetch(`${issuesBase(t)}?${n.toString()}`,{headers:authHeaders(t)});return r.ok||await throwForgejoFailure(r,{verb:`list issues`,resource:t.repository},repoNotFoundMessage(t)),{raw:parseIssueListOrThrow(await r.json()),res:r}}function normalizeDetailedIssues(e,t){let n=e.map(normalizeIssue);return t===`issues`?n.filter(e=>!e.isPullRequest):n}async function listForgejoIssuesDetailedPaged(e,t,n,r){let i=[];for(let a=1;a<=20;a++){let{raw:o}=await fetchIssueListPage(e,t,issueListParams(n.type,{...n,limit:50,page:a}));if(i.push(...normalizeDetailedIssues(o,n.type)),o.length===0||i.length>=n.limit)break;a===20&&(H.warn(`Detailed issue listing on ${t.repository} hit the 20-page cap without an empty page; results may be truncated`),r?.onPageCap?.())}return i}const bs=N.object({full_name:N.string(),default_branch:N.string().nullish(),archived:N.boolean().nullish(),permissions:N.object({push:N.boolean().optional(),admin:N.boolean().optional()}).nullish()});N.array(bs);async function createForgejoIssue(e,t,n){let r=[],i=[];for(let e of n.labels){let t=n.labelIds?.get(e);t===void 0?i.push(e):r.push(t)}i.length>0&&r.push(...await resolveLabelIds(e,t,i));let a={title:n.title,body:n.body,...r.length>0?{labels:r}:{},...n.assignees!==void 0&&n.assignees.length>0?{assignees:n.assignees}:{}},o=await e.fetch(issuesBase(t),{method:`POST`,headers:jsonHeaders(t),body:JSON.stringify(a)});return o.ok||await throwForgejoFailure(o,{verb:`create issue`,resource:n.title},repoNotFoundMessage(t)),normalizeIssue(parseIssueOrThrow(await o.json()))}async function updateForgejoIssue(e,t,n,r){let i=await e.fetch(`${issuesBase(t)}/${String(n)}`,{method:`PATCH`,headers:jsonHeaders(t),body:JSON.stringify({title:r.title,body:r.body})},{idempotent:!0});return i.ok||await throwForgejoFailure(i,{verb:`update issue`,resource:`#${String(n)}`},issueNotFoundMessage(t,n)),normalizeIssue(parseIssueOrThrow(await i.json()))}async function setForgejoIssueState(e,t,n,r){let i=await e.fetch(`${issuesBase(t)}/${String(n)}`,{method:`PATCH`,headers:jsonHeaders(t),body:JSON.stringify({state:r})},{idempotent:!0});return i.ok||await throwForgejoFailure(i,{verb:r===`closed`?`close issue`:`reopen issue`,resource:`#${String(n)}`},issueNotFoundMessage(t,n)),normalizeIssue(parseIssueOrThrow(await i.json()))}var IssueNumberRequiredError=class extends T{constructor(){super(`An issue number or issue URL is required.`)}};function requireIssueNumber(e){if(e.number===void 0)throw new IssueNumberRequiredError;return e.number}function forgejoIssueApi(e,t){return{get:n=>getForgejoIssue(e,t,n),list:async(n,r)=>(await listForgejoIssuesDetailedPaged(e,t,{...n,type:`issues`},r)).slice(0,n.limit).map(({body:e,...t})=>t),comments:(n,r)=>listForgejoComments(e,t,n,r),create:n=>createForgejoIssue(e,t,n),update:(n,r)=>updateForgejoIssue(e,t,n,r),setState:(n,r)=>setForgejoIssueState(e,t,n,r),addComment:(n,r)=>addForgejoComment(e,t,n,r),pullRequest:n=>getForgejoPrDetail(e,t,n)}}const Y=12e4;async function ghJson(e,t,n,r,i){let{notFoundMessage:a,input:o,signal:s}=i,c={cwd:n,timeoutMs:Y,signal:s??null},l=await t.execStream(`gh`,r,o===void 0?c:{...c,input:o});if(l.exitCode!==0){let e=l.stderr||l.stdout;throw/HTTP 404/.test(e)?new ForgeAccessError(a):/HTTP 40[13]/.test(e)?new ForgeAccessError(`GitHub rejected the credentials for "gh ${r.join(` `)}": ${e}. Check the token's validity and scopes.`):/HTTP 422/.test(e)?new T(`GitHub rejected the request payload for "gh ${r.join(` `)}" as invalid (422): ${e}. Retrying with the same input cannot succeed (e.g. a nonexistent label or an assignee the repository will not accept).`):/HTTP 410/.test(e)?new T(`GitHub returned 410 Gone for "gh ${r.join(` `)}": ${e}. Issues are likely disabled on this repository; retrying will not help.`):new E(`gh ${r.join(` `)} failed: ${e}`)}try{return e(JSON.parse(l.stdout))}catch(e){throw e instanceof SyntaxError?new D(`gh ${r.join(` `)} did not return JSON: ${l.stdout}`):e}}function githubApi(e,t,n,r=null){let i=`repos/${n}`,a=`Repository ${n} not found (or the token cannot see it)`,issueNotFound=e=>`Issue #${String(e)} not found in ${n}`,pullRequestNotFound=e=>`Pull request #${String(e)} not found in ${n}`;return{async get(n){return normalizeIssue(await ghJson(parseIssueOrThrow,e,t,[`api`,`${i}/issues/${String(n)}`],{notFoundMessage:issueNotFound(n),signal:r}))},async list(o,s){let c=[];for(let l=1;l<=20;l++){let u=new URLSearchParams({state:o.state,per_page:`50`,page:String(l)});o.label!==void 0&&u.set(`labels`,o.label);let d=await ghJson(parseIssueListOrThrow,e,t,[`api`,`${i}/issues?${u.toString()}`],{notFoundMessage:a,signal:r});if(c.push(...toIssueSummaries(d)),d.length===0||c.length>=o.limit)break;l===20&&(F.warn(`Issue listing on ${n} hit the 20-page cap; results may be truncated`),s?.onPageCap?.())}return c.slice(0,o.limit)},async comments(a,o){let s=[];for(let c=1;c<=10;c++){let l=new URLSearchParams({per_page:`100`,page:String(c)}),u=await ghJson(parseCommentListOrThrow,e,t,[`api`,`${i}/issues/${String(a)}/comments?${l.toString()}`],{notFoundMessage:issueNotFound(a),signal:r});if(s.push(...u.map(normalizeComment)),u.length<100)break;c===10&&(F.warn(`Comment listing for #${String(a)} in ${n} hit the 10-page cap; results may be truncated`),o?.onPageCap?.())}return s},async create(n){return normalizeIssue(await ghJson(parseIssueOrThrow,e,t,[`api`,`--method`,`POST`,`${i}/issues`,`--input`,`-`],{notFoundMessage:a,input:JSON.stringify({title:n.title,body:n.body,labels:n.labels,...n.assignees!==void 0&&n.assignees.length>0?{assignees:n.assignees}:{}}),signal:r}))},async update(n,a){return normalizeIssue(await ghJson(parseIssueOrThrow,e,t,[`api`,`--method`,`PATCH`,`${i}/issues/${String(n)}`,`--input`,`-`],{notFoundMessage:issueNotFound(n),input:JSON.stringify({title:a.title,body:a.body}),signal:r}))},async setState(n,a){return normalizeIssue(await ghJson(parseIssueOrThrow,e,t,[`api`,`--method`,`PATCH`,`${i}/issues/${String(n)}`,`--input`,`-`],{notFoundMessage:issueNotFound(n),input:JSON.stringify({state:a}),signal:r}))},async addComment(n,a){return normalizeComment(await ghJson(parseCommentOrThrow,e,t,[`api`,`--method`,`POST`,`${i}/issues/${String(n)}/comments`,`--input`,`-`],{notFoundMessage:issueNotFound(n),input:JSON.stringify({body:a}),signal:r}))},async pullRequest(n){return normalizePrDetail(await ghJson(parsePrDetailOrThrow,e,t,[`api`,`${i}/pulls/${String(n)}`],{notFoundMessage:pullRequestNotFound(n),signal:r}))}}}function requireForgejoTransport(e,t,n,r){let i=resolveIssueTransport(e,t,n);if(i.target.hostname===`github.com`)throw new T(r);if(i.conn===void 0)throw new D(`Resolved a non-github.com target (${i.target.hostname}) with no Forgejo connection.`);return{api:i.api,target:i.target,conn:i.conn}}function resolveIssueTransport(e,t,n,r,i=null){if(n!==void 0){if(n.hostname===`github.com`)return{api:githubApi(e,t,n.repository,i),target:n};let a=r??resolveForgeToken(`issue commands`),o={serverUrl:n.serverUrl,repository:n.repository,token:a};return{api:forgejoIssueApi(e,o),target:n,conn:o}}if(r!==void 0){let n=resolveConnectionCoordinates(t);if(n!==null){let t={...n,token:r},i={serverUrl:t.serverUrl,repository:t.repository,hostname:new URL(t.serverUrl).hostname};return{api:forgejoIssueApi(e,t),target:i,conn:t}}}let a=resolveConnection(t);if(a.type===`github`){let n=resolveOperationalRepo(t);if(n===null)throw new T(`Could not determine the repository from this directory.`);let r={serverUrl:`${n.protocol}//${n.hostname}`,repository:n.repository,hostname:n.hostname};return{api:githubApi(e,t,n.repository,i),target:r}}let o={...a.conn,token:r??a.conn.token},s={serverUrl:o.serverUrl,repository:o.repository,hostname:new URL(o.serverUrl).hostname};return{api:forgejoIssueApi(e,o),target:s,conn:o}}const xs=[`agent`,`agent-flags`,`agent-note`,`priority`,`other`];function scopeOf(e){let t=e.indexOf(`/`);if(t<0)return`other`;let n=e.slice(0,t);return n===`agent`||n===`agent-flags`||n===`agent-note`||n===`priority`?n:`other`}function groupLabels(e,t){let n=[];for(let r of xs){let i=e.filter(e=>scopeOf(e)===r).toSorted((e,t)=>e.localeCompare(t)).map(e=>({name:e,description:t.get(e)??null}));i.length!==0&&n.push({scope:r,labels:i})}return n}const Ss=/^agent\/[a-z-]+-running$/,Cs=/^agent\/[a-z]+$/,ws=`agent-flags/human-driven`,Ts=[ws,`agent-flags/hand-authored`];function liftedFacts(e){let t=e.filter(e=>Ss.test(e)).toSorted(),n=Ts.find(t=>e.includes(t))??null;return{runLive:t,heldByHand:n!==null,heldBy:n}}function labelNamesOf(e){let t=[];for(let n of[...e.pr,...e.issue])for(let e of n.labels)t.push(e.name);return t}function ownerOf(e){let t=e.filter(e=>e.startsWith(`agent/`)).toSorted(),n=t.find(e=>Ss.test(e));if(n!==void 0)return{owner:`agent`,label:n,hold:`running`};if(Ts.some(t=>e.includes(t)))return{owner:`person`};let r=t.find(e=>Cs.test(e));if(r!==void 0)return{owner:`agent`,label:r,hold:`queued`};let i=t[0];return i===void 0?{owner:`unclaimed`}:{owner:`agent`,label:i,hold:`parked`}}function decideClaim(e,t){if(!t)return{kind:`answer`,exitCode:0,result:{outcome:`not-agent-repo`,reason:`Nothing was claimed: this repository's default branch does not set agent.enabled, so the agent does not work it and there is nothing to claim against.`}};if(e.owner===null)return{kind:`answer`,exitCode:1,result:{outcome:`failed`,reason:`A label read failed, so a run may be live on this object unseen. Nothing was claimed; retry once the forge read works.`}};let n=ownershipOf(e);return n.kind===`running`?{kind:`answer`,exitCode:1,result:{outcome:`refused`,label:n.label,reason:`A run is live on this object (${n.label}); a claim does not stop it.`}}:n.kind===`person`?{kind:`answer`,exitCode:0,result:{outcome:`already-claimed`}}:n.kind===`agent`&&n.hold!==`parked`?{kind:`answer`,exitCode:1,result:{outcome:`refused`,label:n.label,reason:`The agent holds this object (${n.label}). Claim it from the control panel's "Claim for hand work", which strips the trigger, or remove the agent label by hand and run pnpm exec bst work:start again.`}}:n.kind===`agent`&&e.runLive===null?{kind:`answer`,exitCode:1,result:{outcome:`failed`,reason:`A label read failed, so a run may be live or queued beside ${n.label} unseen. Nothing was claimed; retry once the forge read works.`}}:{kind:`write`}}function ownershipOf(e){if(e.labels.state===`ok`){let t=ownerOf(labelNamesOf(e.labels));return t.owner===`agent`?t.hold===`running`?{kind:`running`,label:t.label}:{kind:`agent`,label:t.label,hold:t.hold}:t.owner===`person`?{kind:`person`}:{kind:`unclaimed`}}if(e.owner===`agent`){let t=e.runLive?.[0];return t===void 0?{kind:`agent`,label:`an agent label`,hold:`unread`}:{kind:`running`,label:t}}return e.owner===`person`?{kind:`person`}:{kind:`unclaimed`}}async function writeClaim(e,t,n,r){try{let{conn:i}=requireForgejoTransport(e,t,n,`bst work:start claims work on Forgejo, the forge the agent drives; a GitHub checkout has no agent to hand work to.`),a=(await fetchAllForgejoLabels(e,i)).find(e=>e.name===ws);return a===void 0?{outcome:`failed`,reason:`The forge has no label named ${ws}. Provision the agent's labels first with pnpm exec bst-agent agent:labels --repo ${i.repository}, or the control panel's Provision labels.`}:(await addForgejoIssueLabel(e,i,r,ws,/* @__PURE__ */ new Map([[ws,a.id]])),{outcome:`claimed`,label:ws})}catch(e){return{outcome:`failed`,reason:O(e)}}}async function readAgentConsent(e,t){let n=await e.resolveBase(t);if(n!==`origin/${t}`)return{enabled:agentEnabledIn(readWorkingTree(e.topLevel)),source:`working-tree`};let r=await e.show(n,`.tooling.json`);return r===null?{enabled:!1,source:`default-branch`}:{enabled:agentEnabledIn(r),source:`default-branch`}}function readWorkingTree(e){try{return p(w.join(e,`.tooling.json`),`utf8`)}catch{return}}var NothingToUpdateError=class extends T{constructor(){super(`Nothing to change: neither a title nor a body was given.`)}},IssueTitleRequiredError=class extends T{constructor(){super(`An issue title is required.`)}},InvalidListQueryError=class extends T{field;value;constructor(e,t){super(`The list ${e} is not valid (got "${t}").`),this.field=e,this.value=t}};async function viewIssue(e,t){let n=parseIssueRef(t.ref),r=requireIssueNumber(n),{api:i}=e(resolveIssueTarget(n.target,t.repo)),a=!1,[o,s]=await Promise.all([i.get(r),i.comments(r,{onPageCap:()=>{a=!0}})]);if(!o.isPullRequest)return{...o,comments:s,commentsTruncated:a};try{return{...o,comments:s,commentsTruncated:a,pr:await i.pullRequest(r)}}catch(e){if(!(e instanceof ForgeAccessError))throw e;return{...o,comments:s,commentsTruncated:a,prUnavailable:{reason:ae(e.message)}}}}function formatPrHead(e){return e.head.repo===null?`${e.head.ref} (head repo gone)`:e.head.repo===e.base.repo?e.head.ref:`${e.head.repo}:${e.head.ref}`}function formatMergeable(e){return e===null?`mergeable: unknown`:e?`mergeable`:`not mergeable`}function formatPrLine(e){let t=e.head.sha.slice(0,12),n=`pr: ${formatPrHead(e)} -> ${e.base.ref} head ${t}`;return e.draft&&(n+=` draft`),e.merged&&(n+=` merged`),n+=` ${formatMergeable(e.mergeable)}`,n}function formatPrUnavailableLine(e){let t=e.reason.indexOf(`
|
|
6066
|
+
`)}}async function runVersionMode(e,t){I.info(`Changesets detected -- versioning packages`);let n=buildGitAuth(t),r=versionPrBranch(t.defaultBranch),i=`refs/heads/${r}`,a=e.exec(`git`,[`rev-parse`,`HEAD`],{cwd:t.cwd}),o=a.exitCode===0?a.stdout.trim():``,s=t.dryRun?null:readRemoteRef(e,t,n,i);if(s===null&&!t.dryRun)throw new T(`Could not read the current tip of ${r} from the remote, so this run cannot take a push lease. Refusing to force-push without one -- an unleased push is what allows a concurrent run's version commit to be silently discarded.`);debug(t,`Base commit: ${o||`(unknown)`}`),debug(t,`Lease tip for ${r}: ${s===null?`(dry-run)`:s||`(absent)`}`);let c=e.listWorkspacePackages(t.cwd);debug(t,`Packages before versioning: ${c.map(e=>`${e.name}@${e.version}`).join(`, `)||`(none)`}`);let l=w.join(t.cwd,`.changeset`,`config.json`),u=e.readFile(l);if(u){let n=parseChangesetConfig(u);if(n?.commit){let r={...n,commit:!1};e.writeFile(l,JSON.stringify(r,null,2)+`
|
|
6067
|
+
`),debug(t,`Temporarily disabled changeset commit:true`)}}let d=e.exec(`pnpm`,[`changeset`,`version`],{cwd:t.cwd});if(debugExec(t,`pnpm changeset version`,d),u&&e.writeFile(l,u),d.exitCode!==0)throw new T(`pnpm changeset version failed (exit code ${String(d.exitCode)}):\n${childOutput(d)}`);let f=e.listWorkspacePackages(t.cwd),p=c.length>0||f.length>0;if(debug(t,`Repo type: ${p?`monorepo`:`single-package`}`),p){let n=new Map(c.map(e=>[e.name,e.version])),r=f.filter(e=>n.get(e.name)!==e.version).map(e=>e.dir);debug(t,`Changed packages: ${r.length>0?r.join(`, `):`(none)`}`),stampChangelogDates(e,t.cwd,r,!0)}else stampChangelogDates(e,t.cwd,[],!1);let m=e.exec(`pnpm`,[`install`,`--no-frozen-lockfile`],{cwd:t.cwd});if(debugExec(t,`pnpm install --no-frozen-lockfile`,m),m.exitCode!==0)throw new T(`pnpm install --no-frozen-lockfile failed (exit code ${String(m.exitCode)}):\n${childOutput(m)}`);let{title:h,body:g}=buildPrContent(e,t.cwd,c);debug(t,`PR title: ${h}`);let _=e.exec(`git`,[`add`,`-A`],{cwd:t.cwd});if(_.exitCode!==0)throw new T(`git add failed: ${_.stderr||_.stdout}`);let v=e.listChangesetFiles(t.cwd);v.length>0&&I.warn(`Changeset files still present after versioning: ${v.join(`, `)}`),debug(t,`Changeset files after versioning: ${v.length>0?v.join(`, `):`(none -- all consumed)`}`);let y=e.exec(`git`,[`commit`,`-m`,`chore: version packages`],{cwd:t.cwd});if(debugExec(t,`git commit`,y),y.exitCode!==0)return I.info(`Nothing to commit after versioning`),{mode:`version`,pr:`none`};if(t.dryRun)return I.info(`[dry-run] Would push and create/update PR`),{mode:`version`,pr:`none`};if(isSuperseded(e,t,n,o))return{mode:`version`,pr:`none`};if(s===null)throw new D(`Push lease was never observed on a non-dry-run release`);debug(t,`Force-pushing version commit to ${r} (lease: ${s||`(absent)`})`);let b=e.exec(`git`,[...n.args,`push`,n.url,`HEAD:${i}`,`--force-with-lease=${i}:${s}`],{cwd:t.cwd});if(debugExec(t,`git push`,b),b.exitCode!==0)throw new T(`git push to ${r} failed (exit code ${String(b.exitCode)}). If the lease was rejected, the branch moved after this run started (expected ${s||`the branch to be absent`}) -- another run pushed a version commit, and overwriting it would discard that release. This job fails rather than clobber it.\n${b.stderr||b.stdout}`);let x={serverUrl:t.serverUrl,repository:t.repository,token:t.token},S=await findOpenPr(e,x,r);if(debug(t,`Existing open PR for ${r}: ${S===null?`(none)`:`#${String(S)}`}`),S===null)try{return await createPr(e,x,{title:h,head:r,base:t.defaultBranch,body:g}),I.info(`Created version PR`),{mode:`version`,pr:`created`}}catch(n){debug(t,`createPr failed, retrying as update: ${k(n)}`);let i=await findOpenPr(e,x,r);if(i===null)throw n;return await updatePr(e,x,i,{title:h,body:g}),I.info(`Updated version PR #${String(i)} (recovered from race condition)`),{mode:`version`,pr:`updated`}}return await updatePr(e,x,S,{title:h,body:g}),I.info(`Updated version PR #${String(S)}`),{mode:`version`,pr:`updated`}}const bs=P.looseObject({tag:P.string().optional()}),xs=P.looseObject({access:P.string().optional()});function refuseAccessRead(e,t){return new T(`Could not read the npm access from ${e}: ${t}. Refusing to publish, because falling back to \`restricted\` would change the access of a package the config declares public.`)}function changesetFallbackAccess(e,t){let n=w.join(t.cwd,`.changeset`,`config.json`),r=e.readFile(n);if(r===null)return;let i;try{i=JSON.parse(r)}catch(e){throw refuseAccessRead(n,k(e))}let a=xs.safeParse(i);if(!a.success){let e=a.error.issues[0];throw refuseAccessRead(n,`${e&&e.path.length>0?e.path.join(`.`):`the config`} has the wrong type`)}return a.data.access}function distTag(e,t){let n=w.join(t.cwd,`.changeset`,`pre.json`),r=e.readFile(n);if(r===null)return`latest`;let i;try{i=JSON.parse(r)}catch(e){throw new T(`Could not read the dist-tag from ${n}: ${k(e)}. Refusing to publish, because a prerelease published to \`latest\` moves the public dist-tag.`)}let a=bs.safeParse(i),o=a.success?a.data.tag:void 0;if(o===void 0||o===``)throw new T(`${n} carries no dist-tag. Refusing to publish, because a prerelease published to \`latest\` moves the public dist-tag.`);return o}function accessOf(e,t){let n=e.access??t??`restricted`;if(n!==`public`&&n!==`restricted`)throw new T(`Unknown npm access "${n}" for ${e.name}. Expected "public" or "restricted".`);return n}function publishBumpedPackages(e,t,n){let r=n.filter(e=>!e.private);if(r.length===0){I.info(`Nothing to publish: every bumped package is private`);return}let i=changesetFallbackAccess(e,t),a=distTag(e,t);for(let n of[`restricted`,`public`]){let o=r.filter(e=>accessOf(e,i)===n);if(o.length===0)continue;let s=[`-r`,`publish`,...o.flatMap(e=>[`--filter`,e.name]),`--access`,n,`--tag`,a,`--no-git-checks`],c=[`pnpm`,...s].join(` `);if(t.dryRun){I.info(`[dry-run] Would run ${c}`);continue}let l=e.exec(`pnpm`,s,{cwd:t.cwd});if(debugExec(t,c,l),l.exitCode!==0)throw new T(`pnpm publish failed (exit code ${String(l.exitCode)}):\n${childOutput(l)}`)}}function moveBoundedFloatingTags(e,t,n,r,i){return moveFloatingTags(e,{cwd:t.cwd,git:{args:n.args,url:n.url},dryRun:i,verbose:t.verbose},r)}function floatingFamilies(e,t,n){let r=/* @__PURE__ */ new Set([...t,...n]),i=[];for(let t of e)r.has(exactTag(t.name,t.version))&&i.push({family:changesetsTagFamily(t.name),version:t.version});return i}function prereleaseTag(e,t){for(let n of e){let e=n.family.versionOfExact(t);if(e!==void 0)return isPrerelease$1(e)}return!1}async function prereleaseReleaseExists(e,t,n){let r=await getReleaseByTag(e,t,n);if(!r)return!1;if(r.prerelease===!1&&!isEpochReleaseDate(r.created_at))try{await markReleasePrerelease(e,t,r.id,n),I.info(`Flagged the existing release for ${n} as a prerelease`)}catch(e){I.warn(`Could not flag the existing release for ${n} as a prerelease -- set the flag by hand so the forge's Latest pointer skips it: ${k(e)}`)}return!0}function pushTagToRemote(e,t,n,r,i){if(i.has(r))return;if(debug(t,`Pushing tag ${r} to origin`),e.exec(`git`,[`tag`,`-l`,r],{cwd:t.cwd}).stdout.trim()===``){let n=e.exec(`git`,[`tag`,r],{cwd:t.cwd});if(n.exitCode!==0)throw new T(`Failed to create tag ${r}: ${n.stderr||n.stdout}`)}let a=e.exec(`git`,[...n.args,`push`,n.url,`refs/tags/${r}`],{cwd:t.cwd});if(a.exitCode!==0)throw new T(`Failed to push tag ${r}: ${a.stderr||a.stdout}`)}async function runPublishMode(e,t,n){I.info(`Publishing the packages HEAD bumped that are not yet on the registry`),publishBumpedPackages(e,t,n);let r=n.map(e=>e.tag);debug(t,`Expected tags from the bumped set: ${r.length>0?r.join(`, `):`(none)`}`);let i=e.listWorkspacePackages(t.cwd),a=buildGitAuth(t),o=parseRemoteTags(e.exec(`git`,[...a.args,`ls-remote`,`--tags`,a.url],{cwd:t.cwd}).stdout);debug(t,`Remote tags: ${o.length>0?o.join(`, `):`(none)`}`);let s=new Set(o),c=reconcileTags(r,o);debug(t,`Reconciled tags to push: ${c.length>0?c.join(`, `):`(none)`}`);let l=i.map(e=>({family:changesetsTagFamily(e.name),version:e.version})),u=new Map(n.map(e=>[e.tag,isPrerelease$1(e.version)]));function prereleaseFor(e){let t=u.get(e);return t===void 0?prereleaseTag(l,e):t}if(t.dryRun)return reportFloatingTagOutcome(moveBoundedFloatingTags(e,t,a,floatingFamilies(i,s,c),!0),!0),c.length===0?(I.info(`No packages were published`),{mode:`none`}):(I.info(`Tags to process: ${c.join(`, `)}`),I.info(`[dry-run] Would push tags and create releases`),{mode:`publish`,tags:c});let d={serverUrl:t.serverUrl,repository:t.repository,token:t.token},f=[.../* @__PURE__ */ new Set([...computeExpectedTags(i),...r])].filter(e=>s.has(e)&&!c.includes(e));debug(t,`Expected tags already on remote: ${f.length>0?f.join(`, `):`(none)`}`);let p=[];for(let n of f)(prereleaseFor(n)?await prereleaseReleaseExists(e,d,n):await findRelease(e,d,n))||(debug(t,`Tag ${n} exists on remote but has no release -- will create`),p.push(n));let m=[...c,...p],h=new Set(r),g=p.some(e=>h.has(e));if(m.length===0)return I.info(`No packages were published`),reportFloatingTagOutcome(moveBoundedFloatingTags(e,t,a,floatingFamilies(i,s,[]),!1),!1),{mode:`none`};I.info(`Tags to process: ${m.join(`, `)}`);let _=[];for(let n of m)try{pushTagToRemote(e,t,a,n,s),debug(t,`Ensuring Forgejo release for ${n}`);let{status:r}=await ensureRelease(e,d,n,{target:resolveTagCommit(e,t.cwd,n),prerelease:prereleaseFor(n)});r===`exists`?I.warn(`Release for ${n} already exists -- skipping`):I.info(`Created release for ${n}`)}catch(e){_.push({tag:n,error:e}),I.warn(`Failed to process ${n}: ${k(e)}`)}if(_.length>0){let e=_.map(e=>e.tag).join(`, `);throw new E(`Failed to create releases for: ${e}`)}return reportFloatingTagOutcome(moveBoundedFloatingTags(e,t,a,floatingFamilies(i,s,m),!1),!1),c.length===0&&!g?(I.info(`No packages were published`),{mode:`none`}):{mode:`publish`,tags:m}}const Ss=P.looseObject({name:P.string().optional(),version:P.string().optional(),private:P.boolean().optional(),publishConfig:P.unknown().optional()}),Cs=P.looseObject({access:P.string().optional()});function parseManifest(e){let t;try{t=JSON.parse(e)}catch{return}let n=Ss.safeParse(t);return n.success?n.data:void 0}function candidates(e,t){let n=e.listWorkspacePackages(t);return n.length>0?n.map(e=>({path:`packages/${e.dir}/package.json`,root:!1})):[{path:`package.json`,root:!0}]}function showManifest(e,t,n,r){let i=e.exec(`git`,[`show`,`${n}:${r}`],{cwd:t});if(i.exitCode===0)return parseManifest(i.stdout)}function readBumpedSet(e,t){let n=e.exec(`git`,[`rev-parse`,`--verify`,`--quiet`,`HEAD~1`],{cwd:t.cwd});if(n.exitCode!==0||n.stdout.trim()===``)return[];let r=candidates(e,t.cwd),i=e.exec(`git`,[`-c`,`core.quotePath=false`,`diff`,`--name-only`,`HEAD~1`,`HEAD`,`--`,...r.map(e=>e.path)],{cwd:t.cwd}),a=new Set(i.stdout.split(`
|
|
6068
|
+
`).filter(e=>e.trim()!==``)),o=[];for(let n of r){if(!a.has(n.path))continue;let r=showManifest(e,t.cwd,`HEAD~1`,n.path),i=showManifest(e,t.cwd,`HEAD`,n.path);if(r===void 0||i===void 0)continue;let s=r.version,c=i.version;s!==void 0&&c!==void 0&&s!==c&&i.name!==void 0&&o.push({name:i.name,version:c,tag:releaseTag({name:i.name,version:c,root:n.root}),private:i.private??!1,access:readAccess(i.publishConfig)})}return o}function readAccess(e){if(e===void 0)return;let t=Cs.safeParse(e);return t.success?t.data.access:void 0}const ws=P.object({login:P.string(),email:P.string().nullish()});async function getAuthenticatedUser(e,t,n=null){let r=await e.fetch(`${t.serverUrl}/api/v1/user`,{headers:authHeaders(t),signal:n});if(!r.ok)return{ok:!1,httpStatus:r.status,statusText:r.statusText};let i=ws.safeParse(await r.json());if(!i.success)throw new D(`Unexpected /user response: ${i.error.message}`);return{ok:!0,login:i.data.login,email:i.data.email||null}}function noreplyEmail(e,t){return`${t}@noreply.${e.replace(/^https?:\/\//,``)}`}const Ts=12e4;function sleep(e){return new Promise(t=>{setTimeout(t,e)})}function ciActorName(e){return e===`github`?`github-actions[bot]`:`forgejo-actions[bot]`}function ciActorEmail(e){let t=ciActorName(e);return e===`github`?`${t}@users.noreply.github.com`:`${t}@noreply.localhost`}async function readUser(e,t,n,r,i){let a;try{a=await getAuthenticatedUser(e,t,n)}catch(e){if(!(e instanceof D))throw e;I.warn(`Could not parse Forgejo user response${i}`);return}if(!a.ok)I.warn(`Could not resolve ${r} (${String(a.httpStatus)} ${a.statusText})${i}`);else return a}async function resolveForgejoIdentity(e,t,n=null){let r=await readUser(e,t,n,`Forgejo identity`,` -- falling back to bot identity`);if(r)return{name:r.login,email:r.email??noreplyEmail(t.serverUrl,r.login)}}async function configureGitIdentity(e,t,n,r,i=null){let a,o,s=t===`forgejo`&&r?await resolveForgejoIdentity(e,r,i):void 0;s?{name:a,email:o}=s:(a=ciActorName(t),o=ciActorEmail(t));let c={cwd:n,timeoutMs:X,signal:i};return await e.execStream(`git`,[`config`,`user.name`,a],c),await e.execStream(`git`,[`config`,`user.email`,o],c),{name:a,email:o}}const Es=j({meta:{name:`release:changesets`,description:`Changesets version/publish for Forgejo CI`},args:{"dry-run":{type:`boolean`,description:`Skip push, API calls, and publishing side effects`},verbose:{type:`boolean`,description:`Enable detailed debug logging (also enabled by TOOLING_DEBUG env var)`},json:{type:`boolean`,description:`Emit one JSON document: mode (version | publish | none), tags, pr (created | updated | none, or null), versioned (created | updated | none | failed, or null), dryRun. Every key is always present. tags is empty unless mode is publish; pr is null unless mode is version; versioned is null unless mode is publish and pending changesets were versioned after publishing.`}},async run({args:e}){let t=createCliOutput(e.json===!0),r=e[`dry-run`]===!0,i=await runRelease(buildReleaseConfig({dryRun:r,verbose:e.verbose===!0||isEnvVerbose()}),createRealExecutor$1(),processCiEventSource());if(t.json(releasePayload(i,r)),i.mode===`publish`){let e=process.env.GITHUB_OUTPUT;if(e)try{let t=i.tags[0]??``;n(e,`published=true\ntag=${t}\nversion=${versionFromTag(t)}\n`)}catch{}}i.mode===`none`&&(process.exitCode=0)}});function versionFromTag(e){if(e===``)return``;if(e.startsWith(`v`)&&!e.includes(`@`))return e.slice(1);let t=e.lastIndexOf(`@`);return t<=0?``:e.slice(t+1)}function releasePayload(e,t){return e.mode===`version`?{mode:`version`,tags:[],pr:e.pr,versioned:null,dryRun:t}:e.mode===`publish`?{mode:`publish`,tags:e.tags,pr:null,versioned:e.versioned??null,dryRun:t}:{mode:`none`,tags:[],pr:null,versioned:null,dryRun:t}}function buildReleaseConfig(e){let t=resolveConnection(process.cwd());if(t.type!==`forgejo`)throw new T(`release:changesets requires a Forgejo repository`);return{...t.conn,cwd:process.cwd(),defaultBranch:readConfiguredDefaultBranch(process.cwd()),dryRun:e.dryRun??!1,verbose:e.verbose??!1}}function getCurrentBranch(e,t){let n=process.env.GITHUB_REF;return n?.startsWith(`refs/heads/`)?n.slice(11):e.exec(`git`,[`rev-parse`,`--abbrev-ref`,`HEAD`],{cwd:t}).stdout.trim()}async function runRelease(e,t,n){debug(e,`Repository: ${e.repository} on ${e.serverUrl}`),debug(e,`Config: dryRun=${String(e.dryRun)}`);let r=getCurrentBranch(t,e.cwd);if(debug(e,`Current branch: ${r}`),r!==e.defaultBranch)return debug(e,`Skipping release: ${r} is not the configured default branch (${e.defaultBranch})`),{mode:`none`};refuseForgeDefaultMismatch(e.defaultBranch,n,`release:changesets`);let i=await configureGitIdentity(t,`forgejo`,e.cwd,e);I.info(`Git identity: ${i.name} <${i.email}>`);let a=t.listChangesetFiles(e.cwd);debug(e,`Changeset files found: ${a.length>0?a.join(`, `):`(none)`}`);let o=readBumpedSet(t,e),s=headBumpedVersion(o);return s&&a.length>0?(I.info(`HEAD bumped a version and changesets are still pending (${a.join(`, `)}) -- publishing the merged version first, then versioning the rest.`),debug(e,`Entering publish mode, then version mode`),publishThenVersion(t,e,o)):a.length>0?(debug(e,`Entering version mode`),runVersionMode(t,e)):s?(debug(e,`Entering publish mode`),runPublishMode(t,e,o)):(I.info(`No changesets, and HEAD bumped no package version -- nothing to release. (Publishing runs on the commit that merges a 'version packages' PR.)`),debug(e,`Publish guard: HEAD is not a version-bump commit -- skipping publish`),{mode:`none`})}async function publishThenVersion(e,t,n){let r=await runPublishMode(e,t,n);if(r.mode!==`publish`)return runVersionMode(e,t);let i=e.exec(`git`,[`rev-parse`,`HEAD`],{cwd:t.cwd}),a=i.exitCode===0?i.stdout.trim():``;if(a===``){let e=`Could not read HEAD after publishing, so the changesets still pending are not versioned by this run: ${i.stderr||i.stdout} The version PR waits for the next push to main rather than versioning a checkout this run could not put back.`;return I.warn(e),note(e,`Version PR not rewritten`),{...r,versioned:`failed`}}try{let n=await runVersionMode(e,t);return{...r,versioned:n.mode===`version`?n.pr:`none`}}catch(e){let t=`The packages are published and tagged, but the version PR was not rewritten by this run: ${k(e)}. The next push to main rewrites it.`;return I.warn(t),note(t,`Version PR not rewritten`),{...r,versioned:`failed`}}finally{restorePublishedCheckout(e,t,a)}}function headBumpedVersion(e){return e.length>0}function restorePublishedCheckout(e,t,n){debug(t,`Restoring the checkout to the published commit ${n}`);let r=e.exec(`git`,[`reset`,`--hard`,n],{cwd:t.cwd});if(r.exitCode!==0)throw new T(`Could not restore the checkout to the published commit ${n}: ${r.stderr||r.stdout}`)}P.object({version:P.string()});const Ds=P.object({id:P.number(),index_in_repo:P.number().nullish(),workflow_id:P.string().nullish(),title:P.string().nullish(),prettyref:P.string().nullish(),commit_sha:P.string().nullish(),event:P.string().nullish(),status:P.string().nullish(),started:P.string().nullish(),stopped:P.string().nullish(),duration:P.number().nullish(),html_url:P.string().nullish()});P.object({workflow_runs:P.array(Ds)});const Os=P.object({id:P.number(),name:P.string(),status:P.string()});P.array(Os);const ks=P.object({number:P.number(),name:P.string(),status:P.string(),started:P.string().nullish(),stopped:P.string().nullish()});P.object({id:P.number(),name:P.string(),status:P.string(),steps:P.array(ks).nullish()}),P.object({workflow_runs:P.array(Ds)});async function dispatchWorkflow$1(e,t,n){let r=n.repository??t.repository,i=`${t.serverUrl}/api/v1/repos/${r}/actions/workflows/${encodeURIComponent(n.workflow)}/dispatches`,a={ref:n.ref};Object.keys(n.inputs).length>0&&(a.inputs=n.inputs);let o=await e.fetch(i,{method:`POST`,headers:jsonHeaders(t),body:JSON.stringify(a)});if(!o.ok)throw new T(await forgejoErrorMessage(o,{verb:`dispatch workflow`,resource:n.workflow,ref:n.ref}));return{repository:r,workflow:n.workflow,ref:n.ref,inputs:n.inputs}}async function dispatchWorkflow(e,t,n){return e.type===`forgejo`?dispatchForgejo(e.conn,t,n):dispatchGitHub(t,n)}async function dispatchForgejo(e,t,n){let r=await dispatchWorkflow$1(n,e,{...t.repo===void 0?{}:{repository:t.repo},workflow:t.workflow,ref:t.ref,inputs:t.inputs});return I.info(`Dispatched ${r.workflow} on ${r.repository} (ref: ${r.ref})`),{host:`forgejo`,repo:r.repository,workflow:r.workflow,ref:r.ref,inputs:r.inputs}}function dispatchGitHub(e,t){let n=Object.entries(e.inputs).flatMap(([e,t])=>[`-f`,`${e}=${t}`]),r=e.repo?[`--repo`,e.repo]:[],i=t.exec(`gh`,[`workflow`,`run`,e.workflow,...r,`--ref`,e.ref,...n],{cwd:process.cwd()});if(i.exitCode!==0)throw new T(`Failed to dispatch workflow on GitHub: ${i.stderr||i.stdout||`unknown error`}`);let a=e.repo??parseRepositoryUrl(process.cwd())?.repository??null;return I.info(`Dispatched ${e.workflow} on ${a??`current repository`} (ref: ${e.ref})`),{host:`github`,repo:a,workflow:e.workflow,ref:e.ref,inputs:e.inputs}}const As=j({meta:{name:`release:trigger`,description:`Trigger the release CI workflow. Dispatches release.yml through the Forgejo API, or with gh workflow run on GitHub.`},args:{ref:{type:`string`,description:`Git ref to trigger on (default: .tooling.json#defaultBranch, else main)`,required:!1},bump:{type:`string`,description:`Version bump type: auto, major, minor, patch, or first-release`,required:!1},prerelease:{type:`string`,description:`Create a prerelease with the given tag (e.g., beta, alpha)`,required:!1},json:{type:`boolean`,description:`Emit one JSON document: status (dispatched), host (forgejo | github), repo (owner/repo, or null), workflow, ref, inputs. status is always dispatched; repo is null when GitHub cannot name it.`}},async run({args:e}){let t=createCliOutput(e.json===!0),n=e.ref??readConfiguredDefaultBranch(process.cwd()),r={};e.bump&&(r.bump=e.bump),e.prerelease&&(r.prerelease=e.prerelease);let i=await dispatchWorkflow(resolveConnection(process.cwd()),{repo:void 0,workflow:`release.yml`,ref:n,inputs:r},createRealExecutor$1());t.json({status:`dispatched`,...i})}});async function readAgentConsent(e,t){let n=await e.resolveBase(t);if(n!==`origin/${t}`)return{enabled:agentEnabledIn(readWorkingTree(e.topLevel)),source:`working-tree`};let r=await e.show(n,`.tooling.json`);return r===null?{enabled:!1,source:`default-branch`}:{enabled:agentEnabledIn(r),source:`default-branch`}}function readWorkingTree(e){try{return p(w.join(e,`.tooling.json`),`utf8`)}catch{return}}const js=P.object({id:P.number(),body:P.string().nullish(),user:P.object({login:P.string()}).nullish(),created_at:P.string(),updated_at:P.string().nullish(),html_url:P.string().nullish(),assets:nn.nullish()}),Ms=P.array(js);function parseCommentOrThrow(e){let t=js.safeParse(e);if(!t.success)throw new D(`Unexpected comment response: ${t.error.message}`);return t.data}function parseCommentListOrThrow(e){let t=Ms.safeParse(e);if(!t.success)throw new D(`Unexpected comment-list response: ${t.error.message}`);return t.data}function normalizeComment(e){return{id:e.id,author:e.user?.login??``,createdAt:e.created_at,updatedAt:e.updated_at??e.created_at,body:e.body??``,...e.html_url===void 0||e.html_url===null?{}:{url:e.html_url},attachments:(e.assets??[]).map(normalizeAttachment)}}async function listForgejoComments(e,t,n,r={}){let i=[];for(let a=1;a<=20;a++){let o=new URLSearchParams({limit:`50`,page:String(a)}),s=await e.fetch(`${issuesBase(t)}/${String(n)}/comments?${o.toString()}`,{headers:authHeaders(t)});s.ok||await throwForgejoFailure(s,{verb:`list comments`,resource:`#${String(n)}`},issueNotFoundMessage(t,n));let c=parseCommentListOrThrow(await s.json());if(i.push(...c.map(normalizeComment)),!morePagesFollow(s,c.length,i.length,50))break;a===20&&(U.warn(`Comment listing for #${String(n)} hit the 20-page cap; results may be truncated`),r.onPageCap?.())}return i}const Ns=js.extend({issue_url:P.string().nullish(),pull_request_url:P.string().nullish(),updated_at:P.string().nullish()});P.array(Ns);async function addForgejoComment(e,t,n,r){let i=await e.fetch(`${issuesBase(t)}/${String(n)}/comments`,{method:`POST`,headers:jsonHeaders(t),body:JSON.stringify({body:r})});return i.ok||await throwForgejoFailure(i,{verb:`comment on issue`,resource:`#${String(n)}`},issueNotFoundMessage(t,n)),normalizeComment(parseCommentOrThrow(await i.json()))}const Ps=P.object({id:P.number(),name:P.string(),color:P.string().optional(),description:P.string().optional(),exclusive:P.boolean().optional()}),Fs=P.array(Ps);async function fetchAllForgejoLabels(e,t){let n=[];for(let r=1;r<=20;r++){let i=await e.fetch(`${t.serverUrl}/api/v1/repos/${t.repository}/labels?limit=50&page=${String(r)}`,{headers:authHeaders(t)});i.ok||await throwForgejoFailure(i,{verb:`list labels`,resource:t.repository},repoNotFoundMessage(t));let a=Fs.safeParse(await i.json());if(!a.success)throw new D(`Unexpected label-list response: ${a.error.message}`);if(n.push(...a.data),!morePagesFollow(i,a.data.length,n.length,50))break}return n}async function resolveLabelIds(e,t,n){if(n.length===0)return[];let r=await fetchAllForgejoLabels(e,t);return n.map(e=>{let n=r.find(t=>t.name===e);if(n===void 0){let n=r.map(e=>e.name).join(`, `);throw new T(`No label named "${e}" found among the repository's labels in ${t.repository} (organization-level labels are not searched). Known labels: ${n}`)}return n.id})}const Is=P.strictObject({name:P.string().min(1),color:P.string().regex(/^#[0-9a-fA-F]{6}$/),description:P.string(),exclusive:P.boolean().optional()});P.record(P.string(),P.array(Is));const Ls=P.object({id:P.number(),type:P.string(),body:P.string().nullish(),created_at:P.string(),label:P.object({name:P.string()}).nullish(),user:P.object({login:P.string()}).nullish()});P.array(Ls).nullable();async function resolveLabelId(e,t,n,r){let i=r?.get(n);if(i!==void 0)return i;let[a]=await resolveLabelIds(e,t,[n]);if(a===void 0)throw new D(`Label id resolution returned nothing for "${n}"`);return a}async function addForgejoIssueLabel(e,t,n,r,i){let a=await resolveLabelId(e,t,r,i),o=await e.fetch(`${issuesBase(t)}/${String(n)}/labels`,{method:`POST`,headers:jsonHeaders(t),body:JSON.stringify({labels:[a]})},{idempotent:!0});o.ok||await throwForgejoFailure(o,{verb:`add label`,resource:`#${String(n)}`},issueNotFoundMessage(t,n))}async function removeForgejoIssueLabel(e,t,n,r,i){let a=await resolveLabelId(e,t,r,i),o=await e.fetch(`${issuesBase(t)}/${String(n)}/labels/${String(a)}`,{method:`DELETE`,headers:authHeaders(t)},{idempotent:!0});o.ok||await throwForgejoFailure(o,{verb:`remove label`,resource:`#${String(n)}`},issueNotFoundMessage(t,n))}async function replaceForgejoIssueLabels(e,t,n,r){let i=await e.fetch(`${issuesBase(t)}/${String(n)}/labels`,{method:`PUT`,headers:jsonHeaders(t),body:JSON.stringify({labels:r})},{idempotent:!0});i.ok||await throwForgejoFailure(i,{verb:`replace labels`,resource:`#${String(n)}`},issueNotFoundMessage(t,n))}const Rs=/(?:^|[\s([])(clos(?:e|es|ed)|fix(?:es|ed)?|resolv(?:e|es|ed))(?::[ \t]*|[ \t]+)((?:[\w.-]+\/[\w.-]+)?#\d+)(?![\w-])/gim;function capitalize(e){return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}function extractClosingRefs(e){let t=/* @__PURE__ */ new Map;for(let n of e)for(let[,e,r]of n.matchAll(Rs)){if(e===void 0||r===void 0)continue;let n=r.toLowerCase();t.has(n)||t.set(n,{text:`${capitalize(e)} ${r}`,issue:r})}return[...t.values()]}function issuesClosedBy(e,t){return issuesInRepository(extractClosingRefs([e]).map(e=>e.issue),t)}function issuesInRepository(e,t){let n=/* @__PURE__ */ new Set;for(let r of e){let e=r.toLowerCase(),i=e.lastIndexOf(`#`),a=e.slice(0,i);(a===``||a===t.toLowerCase())&&n.add(Number(e.slice(i+1)))}let r=[...n];return r.sort((e,t)=>e-t),r}function closedIssues(e){return new Set(extractClosingRefs([e]).map(e=>e.issue.toLowerCase()))}function droppedClosingRefs(e,t){let n=closedIssues(t);return extractClosingRefs(e).filter(e=>!n.has(e.issue.toLowerCase()))}function carryForwardClosingRefs(e,t){let n=droppedClosingRefs([e],t);if(n.length===0)return t;let r=n.map(e=>e.text).join(`
|
|
6069
|
+
`);return t.trim()===``?r:`${t}\n\n${r}`}function parseIssueList(e){let t=/* @__PURE__ */ new Set;for(let n of e.split(`,`)){let r=/^#?([1-9]\d*)$/.exec(n.trim());if(r?.[1]===void 0)throw new T(`--closes takes issue numbers separated by commas, such as 12 or 12,15; got ${JSON.stringify(e)}.`);t.add(Number(r[1]))}return[...t]}function repositoryFromUrl(e){if(!URL.canParse(e))return null;let t=new URL(e).pathname.split(`/`).filter(e=>e!==``);return t.length<2?null:`${t[0]}/${t[1]}`}const zs=P.object({number:P.number(),title:P.string(),state:P.string(),html_url:P.string(),body:P.string().nullish(),user:P.object({login:P.string()}).nullish(),labels:P.array(P.object({name:P.string()})).nullish(),assignees:P.array(P.object({login:P.string()})).nullish(),created_at:P.string(),updated_at:P.string(),closed_at:P.string().nullish(),pull_request:P.unknown().nullish(),assets:P.array(tn).nullish()}),Bs=P.array(zs);function parseIssueOrThrow(e){let t=zs.safeParse(e);if(!t.success)throw new D(`Unexpected issue response: ${t.error.message}`);return t.data}function parseIssueListOrThrow(e){let t=Bs.safeParse(e);if(!t.success)throw new D(`Unexpected issue-list response: ${t.error.message}`);return t.data}function normalizeIssue(e){return{number:e.number,title:e.title,state:e.state,url:e.html_url,author:e.user?.login??``,labels:(e.labels??[]).map(e=>e.name),createdAt:e.created_at,updatedAt:e.updated_at,closedAt:e.closed_at??null,body:e.body??``,isPullRequest:e.pull_request!==null&&e.pull_request!==void 0,attachments:(e.assets??[]).map(normalizeAttachment),assignees:(e.assignees??[]).map(e=>e.login)}}function backingIssueNumber(e){let t=/Closes #(\d+)/i.exec(e);if(t===null)return null;let n=Number(t[1]);return Number.isNaN(n)?null:n}function toIssueSummaries(e,t=`issues`){let n=e.map(normalizeIssue).map(({body:e,...t})=>{let n=t,r=t.isPullRequest?backingIssueNumber(e):null;if(r!==null&&(n.backingIssue=r),t.isPullRequest){let r=repositoryFromUrl(t.url),i=r===null?[]:issuesClosedBy(e,r);i.length>0&&(n.closesIssues=i)}return n});return t===`issues`?n.filter(e=>!e.isPullRequest):n}async function getForgejoIssue(e,t,n){let r=await e.fetch(`${issuesBase(t)}/${String(n)}`,{headers:authHeaders(t)});return r.ok||await throwForgejoFailure(r,{verb:`get issue`,resource:`#${String(n)}`},issueNotFoundMessage(t,n)),normalizeIssue(parseIssueOrThrow(await r.json()))}const Vs=P.object({number:P.number(),state:P.string(),repository:P.object({full_name:P.string()}).nullish()});P.array(Vs);function issueListParams(e,t){let n=t.type??e,r=new URLSearchParams(n===`all`?{}:{type:n});return r.set(`state`,t.state),r.set(`limit`,String(t.limit)),t.label!==void 0&&r.set(`labels`,t.label),t.page!==void 0&&r.set(`page`,String(t.page)),t.since!==void 0&&r.set(`since`,t.since),t.sort!==void 0&&r.set(`sort`,t.sort),t.q!==void 0&&r.set(`q`,t.q),r}async function fetchIssueListPage(e,t,n){let r=await e.fetch(`${issuesBase(t)}?${n.toString()}`,{headers:authHeaders(t)});return r.ok||await throwForgejoFailure(r,{verb:`list issues`,resource:t.repository},repoNotFoundMessage(t)),{raw:parseIssueListOrThrow(await r.json()),res:r}}function normalizeDetailedIssues(e,t){let n=e.map(normalizeIssue);return t===`issues`?n.filter(e=>!e.isPullRequest):n}async function listForgejoIssuesDetailedPaged(e,t,n,r){let i=[];for(let a=1;a<=20;a++){let{raw:o}=await fetchIssueListPage(e,t,issueListParams(n.type,{...n,limit:50,page:a}));if(i.push(...normalizeDetailedIssues(o,n.type)),o.length===0||i.length>=n.limit)break;a===20&&(U.warn(`Detailed issue listing on ${t.repository} hit the 20-page cap without an empty page; results may be truncated`),r?.onPageCap?.())}return i}const Hs=P.object({full_name:P.string(),default_branch:P.string().nullish(),archived:P.boolean().nullish(),permissions:P.object({push:P.boolean().optional(),admin:P.boolean().optional()}).nullish()});P.array(Hs);async function createForgejoIssue(e,t,n){let r=[],i=[];for(let e of n.labels){let t=n.labelIds?.get(e);t===void 0?i.push(e):r.push(t)}i.length>0&&r.push(...await resolveLabelIds(e,t,i));let a={title:n.title,body:n.body,...r.length>0?{labels:r}:{},...n.assignees!==void 0&&n.assignees.length>0?{assignees:n.assignees}:{}},o=await e.fetch(issuesBase(t),{method:`POST`,headers:jsonHeaders(t),body:JSON.stringify(a)});return o.ok||await throwForgejoFailure(o,{verb:`create issue`,resource:n.title},repoNotFoundMessage(t)),normalizeIssue(parseIssueOrThrow(await o.json()))}async function updateForgejoIssue(e,t,n,r){let i=await e.fetch(`${issuesBase(t)}/${String(n)}`,{method:`PATCH`,headers:jsonHeaders(t),body:JSON.stringify({title:r.title,body:r.body})},{idempotent:!0});return i.ok||await throwForgejoFailure(i,{verb:`update issue`,resource:`#${String(n)}`},issueNotFoundMessage(t,n)),normalizeIssue(parseIssueOrThrow(await i.json()))}async function setForgejoIssueState(e,t,n,r){let i=await e.fetch(`${issuesBase(t)}/${String(n)}`,{method:`PATCH`,headers:jsonHeaders(t),body:JSON.stringify({state:r})},{idempotent:!0});return i.ok||await throwForgejoFailure(i,{verb:r===`closed`?`close issue`:`reopen issue`,resource:`#${String(n)}`},issueNotFoundMessage(t,n)),normalizeIssue(parseIssueOrThrow(await i.json()))}var IssueNumberRequiredError=class extends T{constructor(){super(`An issue number or issue URL is required.`)}};function requireIssueNumber(e){if(e.number===void 0)throw new IssueNumberRequiredError;return e.number}function forgejoIssueApi(e,t){return{get:n=>getForgejoIssue(e,t,n),list:async(n,r)=>(await listForgejoIssuesDetailedPaged(e,t,{...n,type:`issues`},r)).slice(0,n.limit).map(({body:e,...t})=>t),comments:(n,r)=>listForgejoComments(e,t,n,r),create:n=>createForgejoIssue(e,t,n),update:(n,r)=>updateForgejoIssue(e,t,n,r),setState:(n,r)=>setForgejoIssueState(e,t,n,r),addComment:(n,r)=>addForgejoComment(e,t,n,r),pullRequest:n=>getForgejoPrDetail(e,t,n)}}const Z=12e4;async function ghJson(e,t,n,r,i){let{notFoundMessage:a,input:o,signal:s}=i,c={cwd:n,timeoutMs:Z,signal:s??null},l=await t.execStream(`gh`,r,o===void 0?c:{...c,input:o});if(l.exitCode!==0){let e=l.stderr||l.stdout;throw/HTTP 404/.test(e)?new ForgeAccessError(a):/HTTP 40[13]/.test(e)?new ForgeAccessError(`GitHub rejected the credentials for "gh ${r.join(` `)}": ${e}. Check the token's validity and scopes.`):/HTTP 422/.test(e)?new T(`GitHub rejected the request payload for "gh ${r.join(` `)}" as invalid (422): ${e}. Retrying with the same input cannot succeed (e.g. a nonexistent label or an assignee the repository will not accept).`):/HTTP 410/.test(e)?new T(`GitHub returned 410 Gone for "gh ${r.join(` `)}": ${e}. Issues are likely disabled on this repository; retrying will not help.`):new E(`gh ${r.join(` `)} failed: ${e}`)}try{return e(JSON.parse(l.stdout))}catch(e){throw e instanceof SyntaxError?new D(`gh ${r.join(` `)} did not return JSON: ${l.stdout}`):e}}function githubApi(e,t,n,r=null){let i=`repos/${n}`,a=`Repository ${n} not found (or the token cannot see it)`,issueNotFound=e=>`Issue #${String(e)} not found in ${n}`,pullRequestNotFound=e=>`Pull request #${String(e)} not found in ${n}`;return{async get(n){return normalizeIssue(await ghJson(parseIssueOrThrow,e,t,[`api`,`${i}/issues/${String(n)}`],{notFoundMessage:issueNotFound(n),signal:r}))},async list(o,s){let c=[];for(let l=1;l<=20;l++){let u=new URLSearchParams({state:o.state,per_page:`50`,page:String(l)});o.label!==void 0&&u.set(`labels`,o.label);let d=await ghJson(parseIssueListOrThrow,e,t,[`api`,`${i}/issues?${u.toString()}`],{notFoundMessage:a,signal:r});if(c.push(...toIssueSummaries(d)),d.length===0||c.length>=o.limit)break;l===20&&(I.warn(`Issue listing on ${n} hit the 20-page cap; results may be truncated`),s?.onPageCap?.())}return c.slice(0,o.limit)},async comments(a,o){let s=[];for(let c=1;c<=10;c++){let l=new URLSearchParams({per_page:`100`,page:String(c)}),u=await ghJson(parseCommentListOrThrow,e,t,[`api`,`${i}/issues/${String(a)}/comments?${l.toString()}`],{notFoundMessage:issueNotFound(a),signal:r});if(s.push(...u.map(normalizeComment)),u.length<100)break;c===10&&(I.warn(`Comment listing for #${String(a)} in ${n} hit the 10-page cap; results may be truncated`),o?.onPageCap?.())}return s},async create(n){return normalizeIssue(await ghJson(parseIssueOrThrow,e,t,[`api`,`--method`,`POST`,`${i}/issues`,`--input`,`-`],{notFoundMessage:a,input:JSON.stringify({title:n.title,body:n.body,labels:n.labels,...n.assignees!==void 0&&n.assignees.length>0?{assignees:n.assignees}:{}}),signal:r}))},async update(n,a){return normalizeIssue(await ghJson(parseIssueOrThrow,e,t,[`api`,`--method`,`PATCH`,`${i}/issues/${String(n)}`,`--input`,`-`],{notFoundMessage:issueNotFound(n),input:JSON.stringify({title:a.title,body:a.body}),signal:r}))},async setState(n,a){return normalizeIssue(await ghJson(parseIssueOrThrow,e,t,[`api`,`--method`,`PATCH`,`${i}/issues/${String(n)}`,`--input`,`-`],{notFoundMessage:issueNotFound(n),input:JSON.stringify({state:a}),signal:r}))},async addComment(n,a){return normalizeComment(await ghJson(parseCommentOrThrow,e,t,[`api`,`--method`,`POST`,`${i}/issues/${String(n)}/comments`,`--input`,`-`],{notFoundMessage:issueNotFound(n),input:JSON.stringify({body:a}),signal:r}))},async pullRequest(n){return normalizePrDetail(await ghJson(parsePrDetailOrThrow,e,t,[`api`,`${i}/pulls/${String(n)}`],{notFoundMessage:pullRequestNotFound(n),signal:r}))}}}function requireForgejoTransport(e,t,n,r){let i=resolveIssueTransport(e,t,n);if(i.target.hostname===`github.com`)throw new T(r);if(i.conn===void 0)throw new D(`Resolved a non-github.com target (${i.target.hostname}) with no Forgejo connection.`);return{api:i.api,target:i.target,conn:i.conn}}function resolveIssueTransport(e,t,n,r,i=null){if(n!==void 0){if(n.hostname===`github.com`)return{api:githubApi(e,t,n.repository,i),target:n};let a=r??resolveForgeToken(`issue commands`),o={serverUrl:n.serverUrl,repository:n.repository,token:a};return{api:forgejoIssueApi(e,o),target:n,conn:o}}if(r!==void 0){let n=resolveConnectionCoordinates(t);if(n!==null){let t={...n,token:r},i={serverUrl:t.serverUrl,repository:t.repository,hostname:new URL(t.serverUrl).hostname};return{api:forgejoIssueApi(e,t),target:i,conn:t}}}let a=resolveConnection(t);if(a.type===`github`){let n=resolveOperationalRepo(t);if(n===null)throw new T(`Could not determine the repository from this directory.`);let r={serverUrl:`${n.protocol}//${n.hostname}`,repository:n.repository,hostname:n.hostname};return{api:githubApi(e,t,n.repository,i),target:r}}let o={...a.conn,token:r??a.conn.token},s={serverUrl:o.serverUrl,repository:o.repository,hostname:new URL(o.serverUrl).hostname};return{api:forgejoIssueApi(e,o),target:s,conn:o}}const Us=[`agent`,`agent-flags`,`agent-note`,`priority`,`closed`,`other`];function scopeOf(e){let t=e.indexOf(`/`);if(t<0)return`other`;let n=e.slice(0,t);return n===`agent`||n===`agent-flags`||n===`agent-note`||n===`priority`||n===`closed`?n:`other`}function groupLabels(e,t){let n=[];for(let r of Us){let i=e.filter(e=>scopeOf(e)===r).toSorted((e,t)=>e.localeCompare(t)).map(e=>({name:e,description:t.get(e)??null}));i.length!==0&&n.push({scope:r,labels:i})}return n}const Ws=/^agent\/[a-z-]+-running$/;function isRunningLabel(e){return Ws.test(e)}const Gs=/^agent\/[a-z]+$/,Ks=`agent-flags/human-driven`,qs=[Ks,`agent-flags/hand-authored`];function liftedFacts(e){let t=e.filter(e=>Ws.test(e)).toSorted(),n=qs.find(t=>e.includes(t))??null;return{runLive:t,heldByHand:n!==null,heldBy:n}}function labelNamesOf(e){let t=[];for(let n of[...e.pr,...e.issue])for(let e of n.labels)t.push(e.name);return t}function ownerOf(e){let t=e.filter(e=>e.startsWith(`agent/`)).toSorted(),n=t.find(e=>Ws.test(e));if(n!==void 0)return{owner:`agent`,label:n,hold:`running`};if(qs.some(t=>e.includes(t)))return{owner:`person`};let r=t.find(e=>Gs.test(e));if(r!==void 0)return{owner:`agent`,label:r,hold:`queued`};let i=t[0];return i===void 0?{owner:`unclaimed`}:{owner:`agent`,label:i,hold:`parked`}}const Js=/* @__PURE__ */ new Set([`spec`,`plan`,`implement`,`repair`,`review`,`analyze`]),Ys=/* @__PURE__ */ new Set([`blocked`,`stuck`,`failed`]),Xs={merge:`the Merge click (nothing merges into a default branch without it)`,fixSelected:`Fix selected on the findings checklist`,approveCiDefinition:`approving the pull request's CI-definition change on the panel`,reviewEgress:`reviewing the unit's egress list on the panel`,landed:`nothing: the work has landed`,analyzeOnPullRequest:`nothing this panel offers on a pull request: an analysis there is advice, and Promote to spec is an issue-row move`};function panel(e){return{kind:`panel`,step:e}}function trigger(e){return{kind:`trigger`,label:`agent/${e}`}}function resumeStepFor(e,t){if(!e.startsWith(`agent/`))return null;let n=e.slice(6).split(`-`),r=n[0]??``;if(!Js.has(r)||n.length===1)return null;let i=n.slice(1).join(`-`);return i===`running`?null:i===`ready`&&r===`spec`?trigger(`plan`):i===`ready`&&r===`plan`?trigger(`implement`):Ys.has(i)&&r!==`repair`?trigger(r):r===`repair`&&(i===`done`||i===`failed`)?trigger(`implement`):r===`analyze`&&(i===`ready`||i===`rejected`)?t===`issue`?trigger(`spec`):panel(Xs.analyzeOnPullRequest):i===`mergeable`?panel(Xs.merge):i===`merged`?panel(Xs.landed):i===`held`?panel(Xs.approveCiDefinition):i===`egress`?panel(Xs.reviewEgress):r===`review`&&i===`ready`?panel(Xs.fixSelected):null}const Zs=/^agent\/[a-z]+$/;function answer(e,t){return{kind:`answer`,result:e,exitCode:t}}function namesOf(e){let t=[];for(let n of e)for(let e of n.labels)t.push(e.name);return t}function holdsAmong(e){return qs.filter(t=>e.includes(t))}function stageOf(e){let t=e.agentLabels.find(e=>Zs.test(e));if(t!==void 0)return{label:t,queued:!0};let n=[...e.agentLabels].toSorted()[0];return n===void 0?null:{label:n,queued:!1}}function ambiguousHalf(e){for(let t of e){let e=t.agentLabels.filter(e=>!Zs.test(e));if(e.length>1)return{number:t.number,labels:e}}return null}function queuedOnSibling(e){for(let t of e){let e=t.labels.find(e=>Zs.test(e));if(e!==void 0)return{number:t.number,label:e}}return null}function decideEnd(e,t,n,r){if(!t)return answer({outcome:`not-agent-repo`,reason:`Nothing was released: this repository's default branch does not set agent.enabled, so the agent does not work it and nothing is held against it.`},0);let i=unreadAnswer(e,n);if(i!==null)return i;let a=liveAnswer(e,n);if(a!==null)return a;let o=halvesOf(e),s=heldObjects(o,n);if(s.length===0)return answer({outcome:`not-claimed`,reason:`No object holding this unit carries the flag, so nothing was released.`},0);let c=/* @__PURE__ */ new Map;for(let e of o){let t=stageOf(e);t!==null&&c.set(e.half,t)}let l=carrierOf(o,c,r.refNumber),u={halves:o,held:s,siblings:n instanceof Error?[]:n,stages:c,carrier:l,options:r};return r.resume?decideResume(u):decidePaused(u)}function unreadAnswer(e,t){return e.owner!==null&&e.labels.state===`ok`&&e.object.state===`ok`&&e.runLive!==null&&e.heldByHand!==null&&!(t instanceof Error)?null:answer({outcome:`failed`,reason:`A label read failed, so an object holding this unit may have gone unseen and a run may be live beside it. Nothing was released; retry once the forge read works.`},1)}function liveAnswer(e,t){let n=e.runLive===null?void 0:e.runLive[0];if(n!==void 0)return answer({outcome:`refused`,label:n,reason:`A run is live on this unit (${n}); a release does not stop it. Stop it from the panel first.`},1);if(t instanceof Error)return null;let r=t.find(e=>e.labels.some(isRunningLabel));if(r===void 0)return null;let i=r.labels.find(isRunningLabel)??`an agent running label`;return answer({outcome:`refused`,label:i,reason:`A run is live on pull request #${String(r.number)}, which also holds this issue (${i}); release it there from the panel first.`},1)}function decidePaused(e){for(let t of e.stages.values())if(t.queued)return answer({outcome:`refused`,label:t.label,reason:`${t.label} is already queued on this unit, so releasing it would start a run. Run pnpm exec bst work:end ${String(e.options.refNumber)} --resume to let it start, or remove ${t.label} first to pause.`},1);let t=queuedOnSibling(e.siblings);return t===null?write(e,null,{outcome:`released`}):answer({outcome:`refused`,label:t.label,reason:`${t.label} is already queued on pull request #${String(t.number)}, which holds this unit, so releasing it would start a run. Run pnpm exec bst work:end ${String(e.options.refNumber)} --resume to let it start, or remove ${t.label} first to pause.`},1)}function decideResume(e){let t=queuedOnSibling(e.siblings),n=t!==null&&e.stages.size===0?t.number:void 0,r=[...e.stages.values()];t!==null&&r.push({label:t.label,queued:!0});let i=[...new Map(r.map(e=>[e.label,e])).values()];if(i.length===0)return answer({outcome:`refused`,reason:`Nothing to resume: this unit carries no agent label. Apply a trigger label, such as agent/implement, to start the agent on it.`},1);if(i.length>1)return answer({outcome:`refused`,reason:`This unit carries different agent labels (${i.map(e=>e.label).join(` and `)}), so which one is the unit's live stage is a person's read. Remove the stale one, then run this again.`},1);let a=ambiguousHalf(e.halves);if(a!==null)return answer({outcome:`refused`,reason:`#${String(a.number)} carries more than one agent label (${a.labels.join(` and `)}), so which one is the unit's live stage is a person's read. Remove the stale one, then run this again.`},1);let o=i[0];if(o===void 0)return write(e,null,{outcome:`released`});let s=e.halves.filter(t=>e.stages.get(t.half)?.label===o.label);if(o.queued)return write(e,null,{outcome:`resumed`,label:o.label},n);let c=e.carrier??s[0];if(c===void 0)return answer({outcome:`refused`,label:o.label,reason:`No half carries ${o.label}, so there is nothing to resume.`},1);let l=resumeStepFor(o.label,c.half);return l===null||l.kind===`panel`?answer({outcome:`refused`,label:o.label,reason:redirectReason(o.label,l,e.options.refNumber)},1):write(e,{on:c.number,add:l.label,remove:s.map(e=>({number:e.number,name:o.label}))},{outcome:`resumed`,label:l.label})}function redirectReason(e,t,n){let r=`Run pnpm exec bst work:end ${String(n)} without --resume to release it`;return t===null?`No resume step is known for ${e}. ${r}, then choose the next step on the control panel.`:t.kind===`trigger`?`Resuming ${e} writes ${t.label}.`:`Resuming ${e} is ${t.step}, which only the panel can do. ${r}, then take that step there.`}function write(e,t,n,r){return{kind:`write`,plan:{commentOn:r??e.carrier?.number??e.options.refNumber,trigger:t,flags:flagOrder(e,r),success:n}}}function halvesOf(e){let t=e.object;if(t.state!==`ok`)return[];let n=e.labels.state===`ok`?e.labels:{pr:[],issue:[]},r=[],i=t.issue;if(i!==null){let e=namesOf(n.issue);r.push({half:`issue`,number:i.number,agentLabels:e.filter(e=>e.startsWith(`agent/`)),holds:holdsAmong(e)})}let a=t.pr;if(a!==null){let e=namesOf(n.pr);r.push({half:`pr`,number:a.number,agentLabels:e.filter(e=>e.startsWith(`agent/`)),holds:holdsAmong(e)})}return r}function heldObjects(e,t){let n=[],r=t instanceof Error?[]:t;for(let e of r){let t=holdsAmong(e.labels);t.length>0&&n.push({number:e.number,holds:t})}for(let t of e)t.holds.length>0&&n.push({number:t.number,holds:t.holds});return n}function carrierOf(e,t,n){let r=e.filter(e=>t.has(e.half));if(r.length===1)return r[0];if(r.length>1){let e=r.find(e=>e.number===n);return e===void 0?r.find(e=>e.half===`pr`)??r[0]:e}}function protectedLast(e,t){let{halves:n,held:r}=e,i=n.find(e=>e.half===`issue`),a=r.find(e=>e.number===i?.number);return a===void 0?r.find(e=>e.number===t):a}function flagOrder(e,t){let{halves:n,held:r,carrier:i,options:a}=e,o=i??n.find(e=>e.number===a.refNumber)??n.find(e=>e.half===`pr`)??n[0],s=(t===void 0?o:protectedLast(e,t)??o)?.number,c=t===void 0||t===s?void 0:r.find(e=>e.number===t),l=[...r.filter(e=>e.number!==s&&e!==c),...c===void 0?[]:[c],...r.filter(e=>e.number===s)],u=[];for(let e of l)for(let t of e.holds)u.push({number:e.number,name:t});return u}async function writeEnd(e,t,n,r,i){let a=[],o=`no write`;try{let{conn:s}=requireForgejoTransport(e,t,n,`bst work:end releases work on Forgejo, the forge the agent drives; a GitHub checkout has no agent to hand work back to.`),c=await fetchAllForgejoLabels(e,s),l=new Map(c.map(e=>[e.name,e.id])),u=r.trigger;if(u!==null&&!l.has(u.add))return{outcome:`failed`,reason:`The forge has no label named ${u.add}. Provision the agent's labels first with pnpm exec bst-agent agent:labels --repo ${s.repository}, or the control panel's Provision labels.`};if(i!==void 0&&(o=`the comment on #${String(r.commentOn)}`,await addForgejoComment(e,s,r.commentOn,i),a.push(`${o} posted`)),u!==null){o=`adding ${u.add} to #${String(u.on)}`,await addForgejoIssueLabel(e,s,u.on,u.add,l),a.push(`${u.add} added to #${String(u.on)}`);for(let t of u.remove)l.has(t.name)&&(o=`removing ${t.name} from #${String(t.number)}`,await removeForgejoIssueLabel(e,s,t.number,t.name,l),a.push(`${t.name} removed from #${String(t.number)}`))}for(let t of r.flags)l.has(t.name)&&(o=`removing ${t.name} from #${String(t.number)}`,await removeForgejoIssueLabel(e,s,t.number,t.name,l),a.push(`${t.name} removed from #${String(t.number)}`));return r.success}catch(e){return{outcome:`failed`,reason:`Could not finish ${o}: ${k(e)} `+(a.length===0?`Nothing was written.`:`Already done: ${a.join(`; `)}.`)+` Run the same command again to finish.`}}}var NothingToUpdateError=class extends T{constructor(){super(`Nothing to change: neither a title nor a body was given.`)}},IssueTitleRequiredError=class extends T{constructor(){super(`An issue title is required.`)}},InvalidListQueryError=class extends T{field;value;constructor(e,t){super(`The list ${e} is not valid (got "${t}").`),this.field=e,this.value=t}};async function viewIssue(e,t){let n=parseIssueRef(t.ref),r=requireIssueNumber(n),{api:i}=e(resolveIssueTarget(n.target,t.repo)),a=!1,[o,s]=await Promise.all([i.get(r),i.comments(r,{onPageCap:()=>{a=!0}})]);if(!o.isPullRequest)return{...o,comments:s,commentsTruncated:a};try{return{...o,comments:s,commentsTruncated:a,pr:await i.pullRequest(r)}}catch(e){if(!(e instanceof ForgeAccessError))throw e;return{...o,comments:s,commentsTruncated:a,prUnavailable:{reason:ae(e.message)}}}}function formatPrHead(e){return e.head.repo===null?`${e.head.ref} (head repo gone)`:e.head.repo===e.base.repo?e.head.ref:`${e.head.repo}:${e.head.ref}`}function formatMergeable(e){return e===null?`mergeable: unknown`:e?`mergeable`:`not mergeable`}function formatPrLine(e){let t=e.head.sha.slice(0,12),n=`pr: ${formatPrHead(e)} -> ${e.base.ref} head ${t}`;return e.draft&&(n+=` draft`),e.merged&&(n+=` merged`),n+=` ${formatMergeable(e.mergeable)}`,n}function formatPrUnavailableLine(e){let t=e.reason.indexOf(`
|
|
6066
6070
|
`);return`pr: unavailable -- ${t===-1?e.reason:e.reason.slice(0,t)}`}function formatIssue(e){let t=[],n=e.labels.length>0?` labels: ${e.labels.join(`, `)}`:``;if(t.push(`#${String(e.number)} ${e.title} [${e.state}]`),t.push(`${e.author} - ${e.createdAt}${n}`),e.assignees.length>0&&t.push(`assigned: ${e.assignees.join(`, `)}`),t.push(e.url),e.pr===void 0?e.prUnavailable!==void 0&&t.push(formatPrUnavailableLine(e.prUnavailable)):t.push(formatPrLine(e.pr)),t.push(``),t.push(e.body===``?`(no description)`:e.body),e.attachments.length>0){t.push(``),t.push(`-- ${String(e.attachments.length)} attachment(s) --`);for(let n of e.attachments)t.push(`${n.name} (${String(n.size)} bytes)`)}if(e.comments.length>0){t.push(``),t.push(`-- ${String(e.comments.length)} comment(s) --`);for(let n of e.comments)t.push(``),t.push(`${n.author} - ${n.createdAt}`),t.push(n.body);e.commentsTruncated&&(t.push(``),t.push(`(comment listing hit the page cap; the thread may be truncated)`))}return t.join(`
|
|
6067
6071
|
`)}function parseState(e){if(e===`open`||e===`closed`||e===`all`)return e;throw new InvalidListQueryError(`state`,e)}function parseLimit(e){let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new InvalidListQueryError(`limit`,e);return t}function normalizeLabel(e){if(e!==void 0&&e.trim()!==``)return e}async function listIssues(e,t){let n=normalizeLabel(t.label),r={state:parseState(t.state),limit:parseLimit(t.limit),...n===void 0?{}:{label:n}},{api:i}=e(parseRepoTarget(t.repo)),a=!1;return{issues:await i.list(r,{onPageCap:()=>{a=!0}}),truncated:a}}async function commentOnIssue(e,t){let n=parseIssueRef(t.ref),r=requireIssueNumber(n),{api:i,target:a}=e(resolveIssueTarget(n.target,t.repo)),o=`${a.serverUrl}/${a.repository}/issues/${String(r)}`;return t.dryRun||await i.addComment(r,t.body),{number:r,url:o}}function formatIssueComment(e,t){return`${t?`[dry-run] Would comment`:`Commented`} on issue #${String(e.number)}`}async function updateIssue(e,t){let n=parseIssueRef(t.ref),r=requireIssueNumber(n),i={title:t.title,body:t.body},a=[`title`,`body`].filter(e=>i[e]!==void 0);if(a.length===0)throw new NothingToUpdateError;let{api:o}=e(resolveIssueTarget(n.target,t.repo)),s=await o.get(r),c={title:s.title,body:s.body},l={title:i.title??s.title,body:i.body??s.body};if(t.dryRun)return{number:r,url:s.url,previous:c,current:l,changed:a};let u=await o.update(r,i);return{number:r,url:u.url,previous:c,current:{title:u.title,body:u.body},changed:a}}function formatIssueUpdate(e,t){let n=[`${t?`Would update`:`Updated`} issue #${String(e.number)} (${e.url})`],r=[`title`,`body`].filter(t=>!e.changed.includes(t));if(e.changed.includes(`title`)&&(e.previous.title===e.current.title?n.push(` title: unchanged (already that value)`):(n.push(` title: ${e.previous.title}`),n.push(` -> ${e.current.title}`))),e.changed.includes(`body`)){if(e.previous.body===e.current.body)n.push(` body: unchanged (already that value)`);else{let t=e.previous.body===``?0:e.previous.body.split(`
|
|
6068
6072
|
`).length,r=e.current.body===``?0:e.current.body.split(`
|
|
6069
6073
|
`).length;n.push(` body: replaced (${String(t)} line(s) -> ${String(r)} line(s))`)}}return r.length>0&&n.push(` ${r.join(` and `)} left as authored`),n.join(`
|
|
6070
6074
|
`)}function droppedAssignees(e,t){let n=new Set(t.map(e=>e.toLowerCase()));return e.filter(e=>!n.has(e.toLowerCase()))}async function createIssue(e,t){let n=t.title.trim();if(n===``)throw new IssueTitleRequiredError;let{api:r}=e(parseRepoTarget(t.repo));if(t.dryRun)return{number:0,url:``,assignees:t.assignees};let i=await r.create({title:n,body:t.body,labels:t.labels,...t.assignees.length>0?{assignees:t.assignees}:{}});if(t.assignees.length>0){let e=droppedAssignees(t.assignees,i.assignees);if(e.length>0)throw new T(`Issue #${String(i.number)} (${i.url}) was created, but the forge did not assign ${e.join(`, `)}. The issue exists -- do not retry the create.`)}return{number:i.number,url:i.url,assignees:t.assignees}}function formatIssueCreate(e,t,n){if(n)return[`[dry-run] Would open an issue titled "${t}"${e.assignees.length>0?` assigned to ${e.assignees.join(`, `)}`:``}`];let r=[`Opened issue #${String(e.number)}`];return e.url!==``&&r.push(e.url),r}function formatIssueList(e){let t=[];return e.issues.length===0?t.push(`No issues found.`):t.push(e.issues.map(e=>{let t=e.labels.length>0?` [${e.labels.join(`, `)}]`:``;return`#${String(e.number).padEnd(5)} ${e.state.padEnd(6)} ${e.title}${t}`}).join(`
|
|
6071
6075
|
`)),e.truncated&&(t.push(``),t.push(`(issue listing hit the page cap; results may be truncated)`)),t.join(`
|
|
6072
|
-
`)}N.object({default_branch:N.string()}),N.object({commit:N.object({id:N.string()})}),N.object({total_commits:N.number(),commits:N.array(N.unknown())}),N.object({sha:N.string()}),N.object({sha:N.string(),created:N.string()}),N.array(N.unknown());function branchNotFoundMessage(e,t){return`Branch ${t} not found in ${e.repository}`}const Es=N.object({full_name:N.string()});N.object({description:N.string().optional()});async function getRepoFullName(e,t){let n=await e.fetch(repoBase(t),{headers:authHeaders(t)});n.ok||await throwForgejoFailure(n,{verb:`read repo`,resource:t.repository},repoNotFoundMessage(t));let r=Es.safeParse(await n.json());if(!r.success)throw new D(`Unexpected repo response: ${r.error.message}`);return r.data.full_name}async function branchExists(e,t,n){let r=`${repoBase(t)}/branches/${encodeURIComponent(n)}`,i=await e.fetch(r,{headers:authHeaders(t)});return i.status!==404&&(i.ok||await throwForgejoFailure(i,{verb:`check branch`,resource:n},branchNotFoundMessage(t,n)),!0)}function forgejoPrHost(e,t){return{wipTitles:!0,findOpen:(n,r)=>findOpenPrEntry(e,t,n,r),listForBranch:(n,r,i)=>listBranchPulls(e,t,n,r,i),readLive:n=>getPrContent(e,t,n),async create(n){let r=await createPr(e,t,{title:n.title,head:n.branch,base:n.base,body:n.body});return{number:r.number,url:r.htmlUrl}},async update(n,r){return await updatePr(e,t,n,r),{url:prWebUrl(t,n)}}}}function forgejoPrEditHost(e,t){return{wipTitles:!0,readLive:n=>getPrEditState(e,t,n),branchExists:n=>branchExists(e,t,n),listForBranch:(n,r,i)=>listBranchPulls(e,t,n,r,i),setBase:(n,r)=>retargetPr(e,t,n,r),ready:(n,r)=>updatePr(e,t,n,{title:r.title}),reopen:n=>reopenPr(e,t,n)}}function githubPrHost(e,t,n){return{wipTitles:!1,findOpen:r=>findOpenGitHubPr(e,t,r,n),listForBranch:(r,i)=>listGitHubBranchPrs(e,t,r,i,{repoArgs:[],signal:n}),readLive:r=>readGitHubPrContent(e,t,r,n),async create(r,i){let a=[`pr`,`create`,`--base`,r.base,`--head`,r.branch,`--title`,r.title,`--body`,r.body];i===!0&&a.push(`--draft`);let o=await e.execStream(`gh`,a,{cwd:t,timeoutMs:Y,signal:n});if(o.exitCode!==0)throw new T(`Failed to create PR: ${o.stderr||o.stdout}`);let s=urlFromGhStdout(o.stdout);return{number:prNumberFromUrl(s),url:s}},async update(r,i,a){let o=ghEditFlags(i),s;if(o.length===0)s=await readGitHubPrUrl(e,t,r,n);else{let i=await e.execStream(`gh`,[`pr`,`edit`,String(r),...o],{cwd:t,timeoutMs:Y,signal:n});if(i.exitCode!==0)throw new T(`Failed to update PR #${String(r)}: ${i.stderr}`);s=urlFromGhStdout(i.stdout)}if(a===!1){let i=await e.execStream(`gh`,[`pr`,`ready`,String(r)],{cwd:t,timeoutMs:Y,signal:n});if(i.exitCode!==0)throw new T(`Failed to mark PR #${String(r)} ready: ${i.stderr||i.stdout}`)}return{url:s}}}}function parseGhJson(e,t){let n;try{n=JSON.parse(e)}catch{throw new D(`'${t}' printed something that is not JSON: ${e.trim().slice(0,200)||`no output`}`)}let r=N.json().safeParse(n);if(!r.success)throw new D(`Unexpected '${t}' response: ${r.error.message} (${e.trim().slice(0,200)||`no output`})`);return r.data}const Ds=N.object({title:N.string(),body:N.string().nullish()});async function readGitHubPrContent(e,t,n,r){let i=await e.execStream(`gh`,[`pr`,`view`,String(n),`--json`,`title,body`],{cwd:t,timeoutMs:Y,signal:r});if(i.exitCode!==0)throw new T(`Failed to read PR #${String(n)}: ${i.stderr||i.stdout}`);let a=Ds.safeParse(parseGhJson(i.stdout,`gh pr view`));if(!a.success)throw new D(`Unexpected 'gh pr view' response: ${a.error.message}`);return{title:a.data.title,body:a.data.body??``}}const Os=N.array(N.object({number:N.number(),baseRefName:N.string(),isCrossRepository:N.boolean()})),ks=N.array(N.object({number:N.number(),baseRefName:N.string(),isCrossRepository:N.boolean(),state:N.enum([`OPEN`,`CLOSED`,`MERGED`])}));async function findOpenGitHubPr(e,t,n,r){let i=await e.execStream(`gh`,[`pr`,`list`,`--head`,n,`--state`,`open`,`--json`,`number,baseRefName,isCrossRepository`],{cwd:t,timeoutMs:Y,signal:r});if(i.exitCode!==0)throw new E(`'gh pr list' exited ${String(i.exitCode)}: ${i.stderr.trim()||`no output`} -- cannot tell whether ${n} has an open PR`);let a=i.stdout.trim();if(a===``)return null;let o=Os.safeParse(parseGhJson(a,`gh pr list`));if(!o.success)throw new D(`Unexpected 'gh pr list' response: ${o.error.message}`);let s=o.data.find(e=>e.isCrossRepository===!1);return s===void 0?null:{number:s.number,base:s.baseRefName}}async function listGitHubBranchPrs(e,t,n,r,i){let a=await e.execStream(`gh`,[`pr`,`list`,`--head`,n,`--state`,r,`--limit`,`100`,`--json`,`number,baseRefName,isCrossRepository,state`,...i.repoArgs],{cwd:t,timeoutMs:Y,signal:i.signal});if(a.exitCode!==0)throw new E(`'gh pr list' exited ${String(a.exitCode)}: ${a.stderr.trim()||`no output`} -- cannot tell how many pull requests ${n} has`);let o=a.stdout.trim();if(o===``)return[];let s=ks.safeParse(parseGhJson(o,`gh pr list`));if(!s.success)throw new D(`Unexpected 'gh pr list' response: ${s.error.message}`);if(s.data.length>=100)throw new T(`'gh pr list' for branch "${n}" filled its 100-row page, so it cannot say how many pull requests that branch has; pass the pull request NUMBER instead of autodetecting it.`);let c=[];for(let e of s.data)e.isCrossRepository||c.push({number:e.number,base:e.baseRefName,merged:e.state===`MERGED`});return c}function ghEditFlags(e){return[...e.title===void 0?[]:[`--title`,e.title],...e.body===void 0?[]:[`--body`,e.body]]}async function readGitHubPrUrl(e,t,n,r){let i=await e.execStream(`gh`,[`pr`,`view`,String(n),`--json`,`url`,`--jq`,`.url`],{cwd:t,timeoutMs:Y,signal:r});return i.exitCode===0?urlFromGhStdout(i.stdout):null}function prNumberFromUrl(e){if(e===null)return null;let t=/\/pull\/(\d+)\/?$/u.exec(e);return t?.[1]===void 0?null:Number.parseInt(t[1],10)}function urlFromGhStdout(e){let t=e.trim();return t===``?null:t.split(/\r?\n/u).map(e=>e.trim()).filter(e=>e!==``).findLast(e=>/^https?:\/\/\S*\/pull\/\d+\/?$/u.test(e))??t}const As=N.object({state:N.enum([`OPEN`,`CLOSED`,`MERGED`]),isDraft:N.boolean(),title:N.string(),headRefName:N.string(),baseRefName:N.string(),mergeable:N.enum([`MERGEABLE`,`CONFLICTING`,`UNKNOWN`]),url:N.string()});function ghPrState(e){return e===`MERGED`?{state:`closed`,merged:!0}:e===`CLOSED`?{state:`closed`,merged:!1}:{state:`open`,merged:!1}}function ghMergeable(e){return e===`MERGEABLE`||e!==`CONFLICTING`&&null}function runGh$1(e,t,n){return e.execStream(`gh`,n,{cwd:t,timeoutMs:Y,signal:null})}function githubPrEditHost(e,t,n){let r=[`-R`,n];return{wipTitles:!1,async readLive(n){let i=await runGh$1(e,t,[`pr`,`view`,String(n),...r,`--json`,`state,isDraft,title,headRefName,baseRefName,mergeable,url`]);if(i.exitCode!==0)throw new T(`Failed to read PR #${String(n)}: ${i.stderr||i.stdout}`);let a=As.safeParse(parseGhJson(i.stdout,`gh pr view`));if(!a.success)throw new D(`Unexpected 'gh pr view' response: ${a.error.message}`);let o=a.data;return{...ghPrState(o.state),draft:o.isDraft,title:o.title,head:o.headRefName,base:o.baseRefName,mergeable:ghMergeable(o.mergeable),url:o.url}},listForBranch:(n,i)=>listGitHubBranchPrs(e,t,n,i,{repoArgs:r,signal:null}),async branchExists(r){let i=await runGh$1(e,t,[`api`,`repos/${n}/branches/${encodeURIComponent(r)}`]);if(i.exitCode===0)return!0;if(/HTTP 404/.test(i.stderr))return!1;throw new T(`Failed to check for branch "${r}": ${i.stderr||i.stdout}`)},async setBase(n,i){let a=await runGh$1(e,t,[`pr`,`edit`,String(n),...r,`--base`,i]);if(a.exitCode!==0)throw new T(`Failed to retarget PR #${String(n)}: ${a.stderr||a.stdout}`)},async reopen(n){let i=await runGh$1(e,t,[`pr`,`reopen`,String(n),...r]);if(i.exitCode!==0)throw new T(`Failed to reopen PR #${String(n)}: ${i.stderr||i.stdout}`)},async ready(n,i){if(i.draft){let i=await runGh$1(e,t,[`pr`,`ready`,String(n),...r]);if(i.exitCode!==0)throw new T(`Failed to mark PR #${String(n)} ready: ${i.stderr||i.stdout}`)}if(i.titleChanged){let a=await runGh$1(e,t,[`pr`,`edit`,String(n),...r,`--title`,i.title]);if(a.exitCode!==0)throw new T(`Failed to retitle PR #${String(n)}: ${a.stderr||a.stdout}`)}}}}function prsClosingIssue(e,t,n){let r=[];for(let i of e)issuesClosedBy(i.body,n).includes(t)&&r.push(i.number);return r.toSorted((e,t)=>t-e)}function closingIssueNumber(e,t){let n=e.indexOf(`#`);return n<0||n>0&&(t===null||e.slice(0,n).toLowerCase()!==t.toLowerCase())?null:Number(e.slice(n+1))}function closedIssueNumbers(e,t){let n=[];for(let r of extractClosingRefs([e])){let e=closingIssueNumber(r.issue,t);e===null||n.includes(e)||n.push(e)}return n}function descriptionsOf(e){let t=/* @__PURE__ */ new Map;for(let n of e){let e=n.description;typeof e==`string`&&e.trim()!==``&&t.set(n.name,e)}return t}const js=N.array(N.object({number:N.number(),body:N.string().nullish(),title:N.string().nullish()})),Ms=N.array(N.object({name:N.string(),description:N.string().nullish()}));async function runGh(e,t,n,r){let i=await e.execStream(`gh`,n,{cwd:t,timeoutMs:Y,signal:null});if(i.exitCode!==0)throw new E(`${r} exited ${String(i.exitCode)}: ${i.stderr.trim()||`no output`}`);return i.stdout}async function githubOpenPrsClosing(e,t,n,r){let i=(await runGh(e,t,[`pr`,`list`,`--repo`,n,`--state`,`open`,`--limit`,`200`,`--json`,`number,body,title`],`gh pr list`)).trim();if(i===``)return[];let a;try{a=js.safeParse(JSON.parse(i))}catch{throw new D(`Unexpected 'gh pr list' response: not JSON`)}if(!a.success)throw new D(`Unexpected 'gh pr list' response: ${a.error.message}`);let o=a.data.map(e=>({number:e.number,body:e.body??``})),s=new Map(a.data.map(e=>[e.number,e.title??null]));return prsClosingIssue(o,r,n).map(e=>({number:e,title:s.get(e)??null}))}async function githubLabelDescriptions(e,t,n){let r=await runGh(e,t,[`api`,`--paginate`,`--slurp`,`repos/${n}/labels`],`gh api`),i;try{i=N.array(Ms).safeParse(JSON.parse(r))}catch{throw new D(`Unexpected 'gh api' labels response: not JSON`)}if(!i.success)throw new D(`Unexpected 'gh api' labels response: ${i.error.message}`);return descriptionsOf(i.data.flat().map(e=>({name:e.name,description:e.description??void 0})))}function viewNumber(e,t){return viewIssue(e,{ref:String(t)})}function numberOf(e){return e===null?null:e.number}function workForgeFromConnection(e,t){let n=t.repository,r={serverUrl:t.serverUrl,repository:n,hostname:new URL(t.serverUrl).hostname},resolver=()=>({api:forgejoIssueApi(e,t),target:r}),i=forgejoPrHost(e,t);return{repository:n,view:e=>viewNumber(resolver,e),openPrForBranch:async e=>numberOf(await i.findOpen(e,null)),async openPrsClosing(r){let i=await listForgejoIssuesDetailedPaged(e,t,{type:`pulls`,state:`open`,limit:200}),a=new Map(i.map(e=>[e.number,e.title]));return prsClosingIssue(i,r,n).map(e=>({number:e,title:a.get(e)??null}))},async labelDescriptions(){return descriptionsOf(await fetchAllForgejoLabels(e,t))}}}function resolveWorkForge(e,t,n){let r=resolveIssueTransport(e,t,n),i=r.target.repository,resolver=n=>resolveIssueTransport(e,t,n);if(r.conn!==void 0)return workForgeFromConnection(e,r.conn);let a=githubPrHost(e,t,null);return{repository:i,view:e=>viewNumber(resolver,e),openPrForBranch:async e=>numberOf(await a.findOpen(e,null)),openPrsClosing:n=>githubOpenPrsClosing(e,t,i,n),labelDescriptions:()=>githubLabelDescriptions(e,t,i)}}function failed(e,t){let n=t.trim();return new E(`git ${e} failed: ${n===``?`no stderr`:n}`)}function lines(e){return e.split(`
|
|
6073
|
-
`).filter(e=>e.trim()!==``)}function basename(e){let t=e.split(`/`);return t[t.length-1]??e}async function createWorkGit(e,t){let n=await e.execStream(`git`,[`rev-parse`,`--show-toplevel`],{cwd:t,timeoutMs:J,signal:null});if(n.exitCode!==0)throw failed(`rev-parse --show-toplevel`,n.stderr);let r=n.stdout.trim();async function run(e,t){let n=await ask(e);if(n.exitCode!==0)throw failed(t,n.stderr);return n.stdout}function ask(t,n=J){return e.execStream(`git`,t,{cwd:r,timeoutMs:n,signal:null})}return{topLevel:r,async currentBranch(){let e=(await run([`rev-parse`,`--abbrev-ref`,`HEAD`],`rev-parse --abbrev-ref HEAD`)).trim();return e===`HEAD`?null:e},async headSha(){return(await run([`rev-parse`,`HEAD`],`rev-parse HEAD`)).trim()},async fetchPullHead(e){let t=`refs/pull/${e}/head`,n=await ask([`fetch`,`--no-tags`,`--refmap=`,`origin`,t],is);if(n.exitCode!==0)throw failed(`fetch origin ${t}`,n.stderr);return(await run([`rev-parse`,`FETCH_HEAD`],`rev-parse FETCH_HEAD`)).trim()},async resolveBase(e){let t=`origin/${e}`;return(await ask([`rev-parse`,`--verify`,`--quiet`,t])).exitCode===0?t:e},async changedPaths(e,t){let n=`${e}...${t}`;return lines(await run([`diff`,`--name-only`,`--diff-filter=d`,n],`diff ${n}`))},async show(e,t){let n=await ask([`show`,`${e}:${t}`]);return n.exitCode===0?n.stdout:null},async listDir(e,t){let n=await ask([`ls-tree`,`--name-only`,e,`${t}/`]);return n.exitCode===0?lines(n.stdout).map(basename):[]},async commits(e,t,n){let r=`${e}..${t}`,i=lines(await run([`log`,`--format=%H%x1f%s`,`-n`,String(n+1),r],`log ${r}`)),a=i.length>n;return{entries:i.slice(0,n).map(e=>{let t=e.indexOf(``);return t<0?{sha:e.trim(),subject:``}:{sha:e.slice(0,t),subject:e.slice(t+1).trim()}}),truncated:a}},async commitDate(e){return(await run([`log`,`-1`,`--format=%cI`,e],`log -1 --format=%cI ${e}`)).trim()},async originRepository(){let e=await ask([`remote`,`get-url`,`origin`]);return e.exitCode===0?repositoryFromRemoteUrl(e.stdout):null}}}function tryResolveWorkForge(e,t,n){try{return resolveWorkForge(e,t,n)}catch(e){return e instanceof Error?e:new D(String(e))}}function sameRepository(e,t){return e.toLowerCase()===t.toLowerCase()}function refNamesAnotherRepository(e,t){return new T(`Usage: this command reads this checkout's repository (${e}); the ref names ${t}`)}async function prepareWorkStatus(e,t){let n=e===``?null:parseIssueRef(e),r=createRealExecutor$1(),i=await createWorkGit(r,t),a=n?.target;if(a!==void 0){let e=await i.originRepository();if(e!==null&&!sameRepository(a.repository,e))throw refNamesAnotherRepository(e,a.repository)}let o=tryResolveWorkForge(r,i.topLevel);if(a!==void 0&&!(o instanceof Error)){if(!sameRepository(a.repository,o.repository))throw refNamesAnotherRepository(o.repository,a.repository);o=tryResolveWorkForge(r,i.topLevel,a)}return{ref:n,executor:r,git:i,forge:o}}const X=`docs`,Ns=`retired`,Z=[Ns,`completed`],Ps=`specs`,Fs=/* @__PURE__ */ new Set([`plans`,Ps]),Is=/^plan-.*\.md$/;function isEnforced(e,t){return typeof t==`boolean`?t:t.includes(e)}function listDocs(e,t,n){let r=e.readDir(t);return r?r.filter(e=>!e.isDirectory&&e.name.endsWith(`.md`)).filter(e=>n?.test(e.name)??!0).map(e=>`${t}/${e.name}`).toSorted():[]}function conventionalActiveDirs(e){let t=[],walk=(n,r)=>{if(r>4)return;let i=e.readDir(n);if(i)for(let e of i){if(!e.isDirectory||Z.includes(e.name))continue;let i=`${n}/${e.name}`;Fs.has(e.name)&&t.push(i),walk(i,r+1)}};return walk(X,1),t.toSorted()}function classifyConventionalDoc(e){if(!e.endsWith(`.md`))return null;let t=e.split(`/`);if(t[0]!==X||t.some(e=>e===``||e===`.`||e===`..`))return null;let n=t.slice(0,-1);if(n.length===1&&Is.test(t[1]??``))return{kind:`legacy-plan`,retired:!1};if(n.length===2&&Z.includes(n[1]??``))return{kind:`legacy-plan`,retired:!0};let r=n.length-1,i=!1;if(Z.includes(n[r]??``)&&(i=!0,--r),r<1)return null;let a=n[r]??``;if(!Fs.has(a)||r>4)return null;for(let e=1;e<r;e++)if(Z.includes(n[e]??``))return null;return a===Ps?{kind:`spec`,retired:i}:{kind:`plan`,retired:i}}function classifyTrackedDoc(e,t){let n=classifyConventionalDoc(e);if(n!==null)return n;if(!e.endsWith(`.md`))return null;let r=w.posix.dirname(e),i=Z.includes(w.posix.basename(r)),a=i?w.posix.dirname(r):r,o=w.posix.basename(a);return!Fs.has(o)||!t.includes(a)?null:{kind:o===Ps?`spec`:`plan`,retired:i}}function retireDestination(e,t){let n=w.posix.dirname(e),r=w.posix.basename(e);return Z.includes(w.posix.basename(n))?e:n===X&&Is.test(r)?`${X}/${Ns}/${t}-${r.slice(5)}`:`${n}/${Ns}/${r}`}function candidatePairs(e,t){let n=[];for(let r of[...conventionalActiveDirs(e),...t.extraDirs])n.push({active:r,retired:`${r}/${Ns}`,retiredDirs:Z.map(e=>`${r}/${e}`),enforced:isEnforced(r,t.enforced)});return n.push({active:X,retired:`${X}/${Ns}`,retiredDirs:Z.map(e=>`${X}/${e}`),activePattern:Is,enforced:isEnforced(X,t.enforced)}),n}function matchableActiveDirs(e,t){let n=/* @__PURE__ */ new Set;for(let r of candidatePairs(e,t))e.readDir(r.active)!==void 0&&n.add(r.active);return[...n].toSorted()}function discoverPairs(e,t){let n=/* @__PURE__ */ new Set;return candidatePairs(e,t).filter(t=>n.has(t.active)||!(listDocs(e,t.active,t.activePattern).length>0||t.retiredDirs.some(t=>listDocs(e,t).length>0))?!1:(n.add(t.active),!0))}function describeForgeError(e){if(e instanceof RepoTargetEmptyError)return`--repo was given with no repository URL (expected e.g. https://host/owner/repo).`;if(e instanceof RepoTargetMismatchError)return`--repo disagrees with the issue URL: --repo names ${e.given}, the issue URL names ${e.fromReference}.`}const Ls=[{codepoint:`U+2018`,name:`LEFT SINGLE QUOTATION MARK`,tier:1,char:`‘`,replacement:`'`},{codepoint:`U+2019`,name:`RIGHT SINGLE QUOTATION MARK`,tier:1,char:`’`,replacement:`'`},{codepoint:`U+201C`,name:`LEFT DOUBLE QUOTATION MARK`,tier:1,char:`“`,replacement:`"`},{codepoint:`U+201D`,name:`RIGHT DOUBLE QUOTATION MARK`,tier:1,char:`”`,replacement:`"`},{codepoint:`U+2026`,name:`HORIZONTAL ELLIPSIS`,tier:1,char:`…`,replacement:`...`},{codepoint:`U+2013`,name:`EN DASH`,tier:1,char:`–`,replacement:`-`},{codepoint:`U+00A0`,name:`NO-BREAK SPACE`,tier:1,char:`\xA0`,replacement:` `}],Rs=[{codepoint:`U+2500`,name:`BOX DRAWINGS LIGHT HORIZONTAL`,tier:1,char:`─`,replacement:`-`},{codepoint:`U+2501`,name:`BOX DRAWINGS HEAVY HORIZONTAL`,tier:1,char:`━`,replacement:`-`},{codepoint:`U+2502`,name:`BOX DRAWINGS LIGHT VERTICAL`,tier:1,char:`│`,replacement:`|`},{codepoint:`U+2503`,name:`BOX DRAWINGS HEAVY VERTICAL`,tier:1,char:`┃`,replacement:`|`},{codepoint:`U+250C`,name:`BOX DRAWINGS LIGHT DOWN AND RIGHT`,tier:1,char:`┌`,replacement:`+`},{codepoint:`U+2510`,name:`BOX DRAWINGS LIGHT DOWN AND LEFT`,tier:1,char:`┐`,replacement:`+`},{codepoint:`U+2514`,name:`BOX DRAWINGS LIGHT UP AND RIGHT`,tier:1,char:`└`,replacement:`+`},{codepoint:`U+2518`,name:`BOX DRAWINGS LIGHT UP AND LEFT`,tier:1,char:`┘`,replacement:`+`},{codepoint:`U+251C`,name:`BOX DRAWINGS LIGHT VERTICAL AND RIGHT`,tier:1,char:`├`,replacement:`+`},{codepoint:`U+2524`,name:`BOX DRAWINGS LIGHT VERTICAL AND LEFT`,tier:1,char:`┤`,replacement:`+`},{codepoint:`U+252C`,name:`BOX DRAWINGS LIGHT DOWN AND HORIZONTAL`,tier:1,char:`┬`,replacement:`+`},{codepoint:`U+2534`,name:`BOX DRAWINGS LIGHT UP AND HORIZONTAL`,tier:1,char:`┴`,replacement:`+`},{codepoint:`U+253C`,name:`BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL`,tier:1,char:`┼`,replacement:`+`},{codepoint:`U+2550`,name:`BOX DRAWINGS DOUBLE HORIZONTAL`,tier:1,char:`═`,replacement:`-`},{codepoint:`U+2551`,name:`BOX DRAWINGS DOUBLE VERTICAL`,tier:1,char:`║`,replacement:`|`},{codepoint:`U+256D`,name:`BOX DRAWINGS LIGHT ARC DOWN AND RIGHT`,tier:1,char:`╭`,replacement:`+`},{codepoint:`U+256E`,name:`BOX DRAWINGS LIGHT ARC DOWN AND LEFT`,tier:1,char:`╮`,replacement:`+`},{codepoint:`U+256F`,name:`BOX DRAWINGS LIGHT ARC UP AND LEFT`,tier:1,char:`╯`,replacement:`+`},{codepoint:`U+2570`,name:`BOX DRAWINGS LIGHT ARC UP AND RIGHT`,tier:1,char:`╰`,replacement:`+`}],zs=[{codepoint:`U+2014`,name:`EM DASH`,tier:2,char:`—`,replacement:`--`}],Bs=[{codepoint:`U+2192`,name:`RIGHTWARDS ARROW`,tier:1,char:`→`,replacement:`->`},{codepoint:`U+2190`,name:`LEFTWARDS ARROW`,tier:1,char:`←`,replacement:`<-`},{codepoint:`U+2194`,name:`LEFT RIGHT ARROW`,tier:1,char:`↔`,replacement:`<->`},{codepoint:`U+21B3`,name:`DOWNWARDS ARROW WITH TIP RIGHTWARDS`,tier:1,char:`↳`,replacement:`->`},{codepoint:`U+21D2`,name:`RIGHTWARDS DOUBLE ARROW`,tier:1,char:`⇒`,replacement:`=>`},{codepoint:`U+21D0`,name:`LEFTWARDS DOUBLE ARROW`,tier:1,char:`⇐`,replacement:`<=`}],Vs=[{codepoint:`U+2713`,name:`CHECK MARK`,tier:2,char:`✓`,replacement:`[ok]`},{codepoint:`U+2717`,name:`BALLOT X`,tier:2,char:`✗`,replacement:`[x]`},{codepoint:`U+26A0`,name:`WARNING SIGN`,tier:2,char:`⚠`,replacement:`!`},{codepoint:`U+00B7`,name:`MIDDLE DOT`,tier:2,char:`·`,replacement:`-`},{codepoint:`U+25B6`,name:`BLACK RIGHT-POINTING TRIANGLE`,tier:2,char:`▶`,replacement:`>`},{codepoint:`U+25BA`,name:`BLACK RIGHT-POINTING POINTER`,tier:2,char:`►`,replacement:`>`},{codepoint:`U+25C4`,name:`BLACK LEFT-POINTING POINTER`,tier:2,char:`◄`,replacement:`<`},{codepoint:`U+25C0`,name:`BLACK LEFT-POINTING TRIANGLE`,tier:2,char:`◀`,replacement:`<`},{codepoint:`U+0394`,name:`GREEK CAPITAL LETTER DELTA`,tier:2,char:`Δ`,replacement:`delta`}];function rangeOffenders(e,t,n,r){let i=[];for(let a=e;a<=t;a+=1)i.push({codepoint:`U+${a.toString(16).toUpperCase().padStart(4,`0`)}`,name:n,tier:1,char:String.fromCodePoint(a),group:r});return i}const Hs=[{codepoint:`U+202A`,name:`LEFT-TO-RIGHT EMBEDDING`,tier:1,char:``,group:`invisible`},{codepoint:`U+202B`,name:`RIGHT-TO-LEFT EMBEDDING`,tier:1,char:``,group:`invisible`},{codepoint:`U+202C`,name:`POP DIRECTIONAL FORMATTING`,tier:1,char:``,group:`invisible`},{codepoint:`U+202D`,name:`LEFT-TO-RIGHT OVERRIDE`,tier:1,char:``,group:`invisible`},{codepoint:`U+202E`,name:`RIGHT-TO-LEFT OVERRIDE`,tier:1,char:``,group:`invisible`},{codepoint:`U+2066`,name:`LEFT-TO-RIGHT ISOLATE`,tier:1,char:``,group:`invisible`},{codepoint:`U+2067`,name:`RIGHT-TO-LEFT ISOLATE`,tier:1,char:``,group:`invisible`},{codepoint:`U+2068`,name:`FIRST STRONG ISOLATE`,tier:1,char:``,group:`invisible`},{codepoint:`U+2069`,name:`POP DIRECTIONAL ISOLATE`,tier:1,char:``,group:`invisible`},{codepoint:`U+200B`,name:`ZERO WIDTH SPACE`,tier:1,char:``,group:`invisible`},{codepoint:`U+2060`,name:`WORD JOINER`,tier:1,char:``,group:`invisible`},{codepoint:`U+2061`,name:`FUNCTION APPLICATION`,tier:1,char:``,group:`invisible`},{codepoint:`U+2062`,name:`INVISIBLE TIMES`,tier:1,char:``,group:`invisible`},{codepoint:`U+2063`,name:`INVISIBLE SEPARATOR`,tier:1,char:``,group:`invisible`},{codepoint:`U+2064`,name:`INVISIBLE PLUS`,tier:1,char:``,group:`invisible`},{codepoint:`U+FEFF`,name:`ZERO WIDTH NO-BREAK SPACE`,tier:1,char:``,group:`invisible`},{codepoint:`U+00AD`,name:`SOFT HYPHEN`,tier:1,char:``,group:`invisible`},{codepoint:`U+115F`,name:`HANGUL CHOSEONG FILLER`,tier:1,char:`ᅟ`,group:`invisible`},{codepoint:`U+1160`,name:`HANGUL JUNGSEONG FILLER`,tier:1,char:`ᅠ`,group:`invisible`},{codepoint:`U+3164`,name:`HANGUL FILLER`,tier:1,char:`ㅤ`,group:`invisible`},{codepoint:`U+FFA0`,name:`HALFWIDTH HANGUL FILLER`,tier:1,char:`ᅠ`,group:`invisible`},...rangeOffenders(917504,917631,`TAG CHARACTER`,`invisible`),...rangeOffenders(0,8,`C0 CONTROL`,`invisible`),...rangeOffenders(11,12,`C0 CONTROL`,`invisible`),...rangeOffenders(14,31,`C0 CONTROL`,`invisible`),{codepoint:`U+007F`,name:`DELETE`,tier:1,char:``,group:`invisible`}],Us=[{codepoint:`U+200C`,name:`ZERO WIDTH NON-JOINER`,tier:1,char:``,group:`script`},{codepoint:`U+200D`,name:`ZERO WIDTH JOINER`,tier:1,char:``,group:`script`},{codepoint:`U+200E`,name:`LEFT-TO-RIGHT MARK`,tier:1,char:``,group:`script`},{codepoint:`U+200F`,name:`RIGHT-TO-LEFT MARK`,tier:1,char:``,group:`script`},{codepoint:`U+061C`,name:`ARABIC LETTER MARK`,tier:1,char:``,group:`script`},{codepoint:`U+3000`,name:`IDEOGRAPHIC SPACE`,tier:1,char:` `,group:`script`}],Ws=[{codepoint:`U+2000`,name:`EN QUAD`,tier:1,char:` `,group:`space`,replacement:` `},{codepoint:`U+2001`,name:`EM QUAD`,tier:1,char:` `,group:`space`,replacement:` `},{codepoint:`U+2002`,name:`EN SPACE`,tier:1,char:` `,group:`space`,replacement:` `},{codepoint:`U+2003`,name:`EM SPACE`,tier:1,char:` `,group:`space`,replacement:` `},{codepoint:`U+2004`,name:`THREE-PER-EM SPACE`,tier:1,char:` `,group:`space`,replacement:` `},{codepoint:`U+2005`,name:`FOUR-PER-EM SPACE`,tier:1,char:` `,group:`space`,replacement:` `},{codepoint:`U+2006`,name:`SIX-PER-EM SPACE`,tier:1,char:` `,group:`space`,replacement:` `},{codepoint:`U+2007`,name:`FIGURE SPACE`,tier:1,char:` `,group:`space`,replacement:` `},{codepoint:`U+2008`,name:`PUNCTUATION SPACE`,tier:1,char:` `,group:`space`,replacement:` `},{codepoint:`U+2009`,name:`THIN SPACE`,tier:1,char:` `,group:`space`,replacement:` `},{codepoint:`U+200A`,name:`HAIR SPACE`,tier:1,char:` `,group:`space`,replacement:` `},{codepoint:`U+205F`,name:`MEDIUM MATHEMATICAL SPACE`,tier:1,char:` `,group:`space`,replacement:` `}],Gs=[{codepoint:`U+2010`,name:`HYPHEN`,tier:1,char:`‐`,replacement:`-`},{codepoint:`U+2011`,name:`NON-BREAKING HYPHEN`,tier:1,char:`‑`,replacement:`-`},{codepoint:`U+2012`,name:`FIGURE DASH`,tier:1,char:`‒`,replacement:`-`},{codepoint:`U+2015`,name:`HORIZONTAL BAR`,tier:2,char:`―`,replacement:`--`}],Ks=[...Ls,...Rs,...Bs,...Vs,...zs,...Hs,...Us,...Ws,...Gs],qs={math:[{codepoint:`U+00D7`,name:`MULTIPLICATION SIGN`,tier:1,char:`×`,replacement:`x`},{codepoint:`U+2212`,name:`MINUS SIGN`,tier:1,char:`−`,replacement:`-`},{codepoint:`U+2265`,name:`GREATER-THAN OR EQUAL TO`,tier:1,char:`≥`,replacement:`>=`},{codepoint:`U+2264`,name:`LESS-THAN OR EQUAL TO`,tier:1,char:`≤`,replacement:`<=`},{codepoint:`U+2260`,name:`NOT EQUAL TO`,tier:1,char:`≠`,replacement:`!=`}]};function resolveOffenders(e){let t=(e?.deny??[]).flatMap(e=>qs[e]??[]),n=new Set((e?.allow??[]).map(e=>e.toUpperCase()));return[...Ks,...t].filter(e=>!n.has(e.codepoint))}function offendersByChar(e){return new Map(e.map(e=>[e.char,e]))}const Js=new Map([...Ks,...Object.values(qs).flat()].map(e=>[e.codepoint,e.name]));function offenderNameByCodepoint(e){return Js.get(e)}var SpanLexer=class{spans=[];spanStart=0;spanContext;constructor(e){this.spanContext=e}flushTo(e,t){t!==this.spanContext&&(e>this.spanStart&&this.spans.push({start:this.spanStart,end:e,context:this.spanContext}),this.spanStart=e,this.spanContext=t)}finish(e){return e>this.spanStart&&this.spans.push({start:this.spanStart,end:e,context:this.spanContext}),this.spans}};const Ys=/* @__PURE__ */ new Set([`(`,`[`,`{`,`,`,`;`,`:`,`?`,`=`,`+`,`-`,`*`,`%`,`<`,`>`,`!`,`&`,`|`,`^`,`~`,`}`]),Xs=/* @__PURE__ */ new Set([`return`,`typeof`,`instanceof`,`in`,`of`,`new`,`delete`,`void`,`throw`,`case`,`do`,`else`,`yield`,`await`,`extends`,`default`]);function isIdentifierChar(e){return/[A-Za-z0-9_$]/.test(e)}function isJsxNameStart(e){return e!==void 0&&/[A-Za-z_$>]/.test(e)}function resumeAfterTagClose(e){return e[e.length-1]?.kind===`jsx-children`?`jsx-text`:`code`}var JsTsLexer=class extends SpanLexer{text;jsx;n;i=0;mode=`code`;expectsExpression=!0;regexInClass=!1;stack=[];bailed=!1;constructor(e,t){super(`code`),this.text=e,this.jsx=t,this.n=e.length}run(){for(;this.i<this.n&&!this.bailed;)this.step();if(this.bailed)return null;this.mode===`line-comment`&&(this.mode=`code`);let e=this.finish(this.n);return this.mode!==`code`||this.stack.length>0?null:e}bail(){this.bailed=!0}char(e=0){return this.text[this.i+e]??``}step(){switch(this.mode){case`code`:return this.stepCode();case`line-comment`:return this.stepLineComment();case`block-comment`:return this.stepBlockComment();case`string-single`:case`string-double`:return this.stepString();case`regex`:return this.stepRegex();case`template-text`:return this.stepTemplateText();case`jsx-tag`:case`jsx-close-tag`:return this.stepJsxTag();case`jsx-attr-single`:case`jsx-attr-double`:return this.stepJsxAttr();case`jsx-text`:return this.stepJsxText()}}stepCode(){this.flushTo(this.i,`code`);let e=this.char(),t=this.char(1);if(e===`/`&&(t===`/`||t===`*`))return this.startComment(t);if(e===`/`&&this.expectsExpression)return this.startRegex();if(e===`"`||e===`'`)return this.startString(e);if(e==="`")return this.startTemplate();if(!(e===`}`&&this.stack.length>0&&this.stepCloseBrace())){if(e===`{`)return this.stepOpenBrace();if(this.jsx&&e===`<`&&this.expectsExpression&&isJsxNameStart(t))this.mode=`jsx-tag`,this.i+=1;else{if(isIdentifierChar(e))return this.stepIdentifierOrNumber();/\s/.test(e)||(this.expectsExpression=Ys.has(e)),this.i+=1}}}startComment(e){this.mode=e===`/`?`line-comment`:`block-comment`,this.i+=2}startRegex(){this.mode=`regex`,this.regexInClass=!1,this.i+=1}startString(e){this.mode=e===`"`?`string-double`:`string-single`,this.expectsExpression=!1,this.i+=1}startTemplate(){let e=!this.expectsExpression;this.stack.push({kind:`template`,tagged:e}),this.mode=`template-text`,this.expectsExpression=!1,this.flushTo(this.i+1,e?`tagged-template`:`template`),this.i+=1}stepCloseBrace(){let e=this.stack[this.stack.length-1];return e?.kind===`template-expr`?this.closeTemplateExprBrace(e):e?.kind===`jsx-expr`&&this.closeJsxExprBrace(e)}closeTemplateExprBrace(e){return e.depth>0?(--e.depth,this.expectsExpression=!1,this.i+=1,!0):(this.stack.pop(),this.mode=`template-text`,this.expectsExpression=!1,this.flushTo(this.i+1,e.tagged?`tagged-template`:`template`),this.i+=1,!0)}closeJsxExprBrace(e){return e.depth>0?(--e.depth,this.expectsExpression=!1,this.i+=1,!0):(this.stack.pop(),this.mode=e.returnTo===`jsx-text`?`jsx-text`:`jsx-tag`,this.expectsExpression=!1,this.flushTo(this.i+1,this.mode===`jsx-text`?`jsx-text`:`code`),this.i+=1,!0)}stepOpenBrace(){let e=this.stack[this.stack.length-1];(e?.kind===`template-expr`||e?.kind===`jsx-expr`)&&(e.depth+=1),this.expectsExpression=!0,this.i+=1}stepIdentifierOrNumber(){let e=this.i;for(;e<this.n&&isIdentifierChar(this.text[e]??``);)e+=1;let t=this.text.slice(this.i,e);this.expectsExpression=Xs.has(t),this.i=e}stepLineComment(){this.flushTo(this.i,`comment`),this.char()===`
|
|
6076
|
+
`)}P.object({default_branch:P.string()}),P.object({commit:P.object({id:P.string()})}),P.object({total_commits:P.number(),commits:P.array(P.unknown())}),P.object({sha:P.string()}),P.object({sha:P.string(),created:P.string()}),P.array(P.unknown());function branchNotFoundMessage(e,t){return`Branch ${t} not found in ${e.repository}`}const Qs=P.object({full_name:P.string()});P.object({description:P.string().optional()});async function getRepoFullName(e,t){let n=await e.fetch(repoBase(t),{headers:authHeaders(t)});n.ok||await throwForgejoFailure(n,{verb:`read repo`,resource:t.repository},repoNotFoundMessage(t));let r=Qs.safeParse(await n.json());if(!r.success)throw new D(`Unexpected repo response: ${r.error.message}`);return r.data.full_name}async function branchExists(e,t,n){let r=`${repoBase(t)}/branches/${encodeURIComponent(n)}`,i=await e.fetch(r,{headers:authHeaders(t)});return i.status!==404&&(i.ok||await throwForgejoFailure(i,{verb:`check branch`,resource:n},branchNotFoundMessage(t,n)),!0)}function forgejoPrHost(e,t){return{wipTitles:!0,findOpen:(n,r)=>findOpenPrEntry(e,t,n,r),listForBranch:(n,r,i)=>listBranchPulls(e,t,n,r,i),readLive:n=>getPrContent(e,t,n),async create(n){let r=await createPr(e,t,{title:n.title,head:n.branch,base:n.base,body:n.body});return{number:r.number,url:r.htmlUrl}},async update(n,r){return await updatePr(e,t,n,r),{url:prWebUrl(t,n)}}}}function forgejoPrEditHost(e,t){return{wipTitles:!0,readLive:n=>getPrEditState(e,t,n),branchExists:n=>branchExists(e,t,n),listForBranch:(n,r,i)=>listBranchPulls(e,t,n,r,i),setBase:(n,r)=>retargetPr(e,t,n,r),ready:(n,r)=>updatePr(e,t,n,{title:r.title}),reopen:n=>reopenPr(e,t,n)}}function githubPrHost(e,t,n){return{wipTitles:!1,findOpen:r=>findOpenGitHubPr(e,t,r,n),listForBranch:(r,i)=>listGitHubBranchPrs(e,t,r,i,{repoArgs:[],signal:n}),readLive:r=>readGitHubPrContent(e,t,r,n),async create(r,i){let a=[`pr`,`create`,`--base`,r.base,`--head`,r.branch,`--title`,r.title,`--body`,r.body];i===!0&&a.push(`--draft`);let o=await e.execStream(`gh`,a,{cwd:t,timeoutMs:Z,signal:n});if(o.exitCode!==0)throw new T(`Failed to create PR: ${o.stderr||o.stdout}`);let s=urlFromGhStdout(o.stdout);return{number:prNumberFromUrl(s),url:s}},async update(r,i,a){let o=ghEditFlags(i),s;if(o.length===0)s=await readGitHubPrUrl(e,t,r,n);else{let i=await e.execStream(`gh`,[`pr`,`edit`,String(r),...o],{cwd:t,timeoutMs:Z,signal:n});if(i.exitCode!==0)throw new T(`Failed to update PR #${String(r)}: ${i.stderr}`);s=urlFromGhStdout(i.stdout)}if(a===!1){let i=await e.execStream(`gh`,[`pr`,`ready`,String(r)],{cwd:t,timeoutMs:Z,signal:n});if(i.exitCode!==0)throw new T(`Failed to mark PR #${String(r)} ready: ${i.stderr||i.stdout}`)}return{url:s}}}}function parseGhJson(e,t){let n;try{n=JSON.parse(e)}catch{throw new D(`'${t}' printed something that is not JSON: ${e.trim().slice(0,200)||`no output`}`)}let r=P.json().safeParse(n);if(!r.success)throw new D(`Unexpected '${t}' response: ${r.error.message} (${e.trim().slice(0,200)||`no output`})`);return r.data}const $s=P.object({title:P.string(),body:P.string().nullish()});async function readGitHubPrContent(e,t,n,r){let i=await e.execStream(`gh`,[`pr`,`view`,String(n),`--json`,`title,body`],{cwd:t,timeoutMs:Z,signal:r});if(i.exitCode!==0)throw new T(`Failed to read PR #${String(n)}: ${i.stderr||i.stdout}`);let a=$s.safeParse(parseGhJson(i.stdout,`gh pr view`));if(!a.success)throw new D(`Unexpected 'gh pr view' response: ${a.error.message}`);return{title:a.data.title,body:a.data.body??``}}const ec=P.array(P.object({number:P.number(),baseRefName:P.string(),isCrossRepository:P.boolean()})),tc=P.array(P.object({number:P.number(),baseRefName:P.string(),isCrossRepository:P.boolean(),state:P.enum([`OPEN`,`CLOSED`,`MERGED`])}));async function findOpenGitHubPr(e,t,n,r){let i=await e.execStream(`gh`,[`pr`,`list`,`--head`,n,`--state`,`open`,`--json`,`number,baseRefName,isCrossRepository`],{cwd:t,timeoutMs:Z,signal:r});if(i.exitCode!==0)throw new E(`'gh pr list' exited ${String(i.exitCode)}: ${i.stderr.trim()||`no output`} -- cannot tell whether ${n} has an open PR`);let a=i.stdout.trim();if(a===``)return null;let o=ec.safeParse(parseGhJson(a,`gh pr list`));if(!o.success)throw new D(`Unexpected 'gh pr list' response: ${o.error.message}`);let s=o.data.find(e=>e.isCrossRepository===!1);return s===void 0?null:{number:s.number,base:s.baseRefName}}async function listGitHubBranchPrs(e,t,n,r,i){let a=await e.execStream(`gh`,[`pr`,`list`,`--head`,n,`--state`,r,`--limit`,`100`,`--json`,`number,baseRefName,isCrossRepository,state`,...i.repoArgs],{cwd:t,timeoutMs:Z,signal:i.signal});if(a.exitCode!==0)throw new E(`'gh pr list' exited ${String(a.exitCode)}: ${a.stderr.trim()||`no output`} -- cannot tell how many pull requests ${n} has`);let o=a.stdout.trim();if(o===``)return[];let s=tc.safeParse(parseGhJson(o,`gh pr list`));if(!s.success)throw new D(`Unexpected 'gh pr list' response: ${s.error.message}`);if(s.data.length>=100)throw new T(`'gh pr list' for branch "${n}" filled its 100-row page, so it cannot say how many pull requests that branch has; pass the pull request NUMBER instead of autodetecting it.`);let c=[];for(let e of s.data)e.isCrossRepository||c.push({number:e.number,base:e.baseRefName,merged:e.state===`MERGED`});return c}function ghEditFlags(e){return[...e.title===void 0?[]:[`--title`,e.title],...e.body===void 0?[]:[`--body`,e.body]]}async function readGitHubPrUrl(e,t,n,r){let i=await e.execStream(`gh`,[`pr`,`view`,String(n),`--json`,`url`,`--jq`,`.url`],{cwd:t,timeoutMs:Z,signal:r});return i.exitCode===0?urlFromGhStdout(i.stdout):null}function prNumberFromUrl(e){if(e===null)return null;let t=/\/pull\/(\d+)\/?$/u.exec(e);return t?.[1]===void 0?null:Number.parseInt(t[1],10)}function urlFromGhStdout(e){let t=e.trim();return t===``?null:t.split(/\r?\n/u).map(e=>e.trim()).filter(e=>e!==``).findLast(e=>/^https?:\/\/\S*\/pull\/\d+\/?$/u.test(e))??t}const nc=P.object({state:P.enum([`OPEN`,`CLOSED`,`MERGED`]),isDraft:P.boolean(),title:P.string(),headRefName:P.string(),baseRefName:P.string(),mergeable:P.enum([`MERGEABLE`,`CONFLICTING`,`UNKNOWN`]),url:P.string()});function ghPrState(e){return e===`MERGED`?{state:`closed`,merged:!0}:e===`CLOSED`?{state:`closed`,merged:!1}:{state:`open`,merged:!1}}function ghMergeable(e){return e===`MERGEABLE`||e!==`CONFLICTING`&&null}function runGh$1(e,t,n){return e.execStream(`gh`,n,{cwd:t,timeoutMs:Z,signal:null})}function githubPrEditHost(e,t,n){let r=[`-R`,n];return{wipTitles:!1,async readLive(n){let i=await runGh$1(e,t,[`pr`,`view`,String(n),...r,`--json`,`state,isDraft,title,headRefName,baseRefName,mergeable,url`]);if(i.exitCode!==0)throw new T(`Failed to read PR #${String(n)}: ${i.stderr||i.stdout}`);let a=nc.safeParse(parseGhJson(i.stdout,`gh pr view`));if(!a.success)throw new D(`Unexpected 'gh pr view' response: ${a.error.message}`);let o=a.data;return{...ghPrState(o.state),draft:o.isDraft,title:o.title,head:o.headRefName,base:o.baseRefName,mergeable:ghMergeable(o.mergeable),url:o.url}},listForBranch:(n,i)=>listGitHubBranchPrs(e,t,n,i,{repoArgs:r,signal:null}),async branchExists(r){let i=await runGh$1(e,t,[`api`,`repos/${n}/branches/${encodeURIComponent(r)}`]);if(i.exitCode===0)return!0;if(/HTTP 404/.test(i.stderr))return!1;throw new T(`Failed to check for branch "${r}": ${i.stderr||i.stdout}`)},async setBase(n,i){let a=await runGh$1(e,t,[`pr`,`edit`,String(n),...r,`--base`,i]);if(a.exitCode!==0)throw new T(`Failed to retarget PR #${String(n)}: ${a.stderr||a.stdout}`)},async reopen(n){let i=await runGh$1(e,t,[`pr`,`reopen`,String(n),...r]);if(i.exitCode!==0)throw new T(`Failed to reopen PR #${String(n)}: ${i.stderr||i.stdout}`)},async ready(n,i){if(i.draft){let i=await runGh$1(e,t,[`pr`,`ready`,String(n),...r]);if(i.exitCode!==0)throw new T(`Failed to mark PR #${String(n)} ready: ${i.stderr||i.stdout}`)}if(i.titleChanged){let a=await runGh$1(e,t,[`pr`,`edit`,String(n),...r,`--title`,i.title]);if(a.exitCode!==0)throw new T(`Failed to retitle PR #${String(n)}: ${a.stderr||a.stdout}`)}}}}function prsClosingIssue(e,t,n){let r=[];for(let i of e)issuesClosedBy(i.body,n).includes(t)&&r.push(i.number);return r.toSorted((e,t)=>t-e)}function closingIssueNumber(e,t){let n=e.indexOf(`#`);return n<0||n>0&&(t===null||e.slice(0,n).toLowerCase()!==t.toLowerCase())?null:Number(e.slice(n+1))}function closedIssueNumbers(e,t){let n=[];for(let r of extractClosingRefs([e])){let e=closingIssueNumber(r.issue,t);e===null||n.includes(e)||n.push(e)}return n}function descriptionsOf(e){let t=/* @__PURE__ */ new Map;for(let n of e){let e=n.description;typeof e==`string`&&e.trim()!==``&&t.set(n.name,e)}return t}const rc=P.array(P.object({number:P.number(),body:P.string().nullish(),title:P.string().nullish()})),ic=P.array(P.object({name:P.string(),description:P.string().nullish()}));async function runGh(e,t,n,r){let i=await e.execStream(`gh`,n,{cwd:t,timeoutMs:Z,signal:null});if(i.exitCode!==0)throw new E(`${r} exited ${String(i.exitCode)}: ${i.stderr.trim()||`no output`}`);return i.stdout}async function githubOpenPrsClosing(e,t,n,r){let i=(await runGh(e,t,[`pr`,`list`,`--repo`,n,`--state`,`open`,`--limit`,`200`,`--json`,`number,body,title`],`gh pr list`)).trim();if(i===``)return[];let a;try{a=rc.safeParse(JSON.parse(i))}catch{throw new D(`Unexpected 'gh pr list' response: not JSON`)}if(!a.success)throw new D(`Unexpected 'gh pr list' response: ${a.error.message}`);let o=a.data.map(e=>({number:e.number,body:e.body??``})),s=new Map(a.data.map(e=>[e.number,e.title??null]));return prsClosingIssue(o,r,n).map(e=>({number:e,title:s.get(e)??null}))}async function githubLabelDescriptions(e,t,n){let r=await runGh(e,t,[`api`,`--paginate`,`--slurp`,`repos/${n}/labels`],`gh api`),i;try{i=P.array(ic).safeParse(JSON.parse(r))}catch{throw new D(`Unexpected 'gh api' labels response: not JSON`)}if(!i.success)throw new D(`Unexpected 'gh api' labels response: ${i.error.message}`);return descriptionsOf(i.data.flat().map(e=>({name:e.name,description:e.description??void 0})))}function viewNumber(e,t){return viewIssue(e,{ref:String(t)})}function numberOf(e){return e===null?null:e.number}function workForgeFromConnection(e,t){let n=t.repository,r={serverUrl:t.serverUrl,repository:n,hostname:new URL(t.serverUrl).hostname},resolver=()=>({api:forgejoIssueApi(e,t),target:r}),i=forgejoPrHost(e,t);return{repository:n,view:e=>viewNumber(resolver,e),openPrForBranch:async e=>numberOf(await i.findOpen(e,null)),async openPrsClosing(r){let i=await listForgejoIssuesDetailedPaged(e,t,{type:`pulls`,state:`open`,limit:200}),a=new Map(i.map(e=>[e.number,e.title]));return prsClosingIssue(i,r,n).map(e=>({number:e,title:a.get(e)??null}))},async labelDescriptions(){return descriptionsOf(await fetchAllForgejoLabels(e,t))}}}function resolveWorkForge(e,t,n){let r=resolveIssueTransport(e,t,n),i=r.target.repository,resolver=n=>resolveIssueTransport(e,t,n);if(r.conn!==void 0)return workForgeFromConnection(e,r.conn);let a=githubPrHost(e,t,null);return{repository:i,view:e=>viewNumber(resolver,e),openPrForBranch:async e=>numberOf(await a.findOpen(e,null)),openPrsClosing:n=>githubOpenPrsClosing(e,t,i,n),labelDescriptions:()=>githubLabelDescriptions(e,t,i)}}function failed(e,t){let n=t.trim();return new E(`git ${e} failed: ${n===``?`no stderr`:n}`)}function lines(e){return e.split(`
|
|
6077
|
+
`).filter(e=>e.trim()!==``)}function basename(e){let t=e.split(`/`);return t[t.length-1]??e}async function createWorkGit(e,t){let n=await e.execStream(`git`,[`rev-parse`,`--show-toplevel`],{cwd:t,timeoutMs:X,signal:null});if(n.exitCode!==0)throw failed(`rev-parse --show-toplevel`,n.stderr);let r=n.stdout.trim();async function run(e,t){let n=await ask(e);if(n.exitCode!==0)throw failed(t,n.stderr);return n.stdout}function ask(t,n=X){return e.execStream(`git`,t,{cwd:r,timeoutMs:n,signal:null})}return{topLevel:r,async currentBranch(){let e=(await run([`rev-parse`,`--abbrev-ref`,`HEAD`],`rev-parse --abbrev-ref HEAD`)).trim();return e===`HEAD`?null:e},async headSha(){return(await run([`rev-parse`,`HEAD`],`rev-parse HEAD`)).trim()},async fetchPullHead(e){let t=`refs/pull/${e}/head`,n=await ask([`fetch`,`--no-tags`,`--refmap=`,`origin`,t],Ts);if(n.exitCode!==0)throw failed(`fetch origin ${t}`,n.stderr);return(await run([`rev-parse`,`FETCH_HEAD`],`rev-parse FETCH_HEAD`)).trim()},async resolveBase(e){let t=`origin/${e}`;return(await ask([`rev-parse`,`--verify`,`--quiet`,t])).exitCode===0?t:e},async changedPaths(e,t){let n=`${e}...${t}`;return lines(await run([`diff`,`--name-only`,`--diff-filter=d`,n],`diff ${n}`))},async show(e,t){let n=await ask([`show`,`${e}:${t}`]);return n.exitCode===0?n.stdout:null},async listDir(e,t){let n=await ask([`ls-tree`,`--name-only`,e,`${t}/`]);return n.exitCode===0?lines(n.stdout).map(basename):[]},async commits(e,t,n){let r=`${e}..${t}`,i=lines(await run([`log`,`--format=%H%x1f%s`,`-n`,String(n+1),r],`log ${r}`)),a=i.length>n;return{entries:i.slice(0,n).map(e=>{let t=e.indexOf(``);return t<0?{sha:e.trim(),subject:``}:{sha:e.slice(0,t),subject:e.slice(t+1).trim()}}),truncated:a}},async commitDate(e){return(await run([`log`,`-1`,`--format=%cI`,e],`log -1 --format=%cI ${e}`)).trim()},async originRepository(){let e=await ask([`remote`,`get-url`,`origin`]);return e.exitCode===0?repositoryFromRemoteUrl(e.stdout):null}}}function tryResolveWorkForge(e,t,n){try{return resolveWorkForge(e,t,n)}catch(e){return e instanceof Error?e:new D(String(e))}}function sameRepository(e,t){return e.toLowerCase()===t.toLowerCase()}function refNamesAnotherRepository(e,t){return new T(`Usage: this command reads this checkout's repository (${e}); the ref names ${t}`)}async function prepareWorkStatus(e,t){let n=e===``?null:parseIssueRef(e),r=createRealExecutor$1(),i=await createWorkGit(r,t),a=n?.target;if(a!==void 0){let e=await i.originRepository();if(e!==null&&!sameRepository(a.repository,e))throw refNamesAnotherRepository(e,a.repository)}let o=tryResolveWorkForge(r,i.topLevel);if(a!==void 0&&!(o instanceof Error)){if(!sameRepository(a.repository,o.repository))throw refNamesAnotherRepository(o.repository,a.repository);o=tryResolveWorkForge(r,i.topLevel,a)}return{ref:n,executor:r,git:i,forge:o}}const Q=`docs`,ac=`retired`,oc=[ac,`completed`],sc=`specs`,cc=/* @__PURE__ */ new Set([`plans`,sc]),lc=/^plan-.*\.md$/;function isEnforced(e,t){return typeof t==`boolean`?t:t.includes(e)}function listDocs(e,t,n){let r=e.readDir(t);return r?r.filter(e=>!e.isDirectory&&e.name.endsWith(`.md`)).filter(e=>n?.test(e.name)??!0).map(e=>`${t}/${e.name}`).toSorted():[]}function conventionalActiveDirs(e){let t=[],walk=(n,r)=>{if(r>4)return;let i=e.readDir(n);if(i)for(let e of i){if(!e.isDirectory||oc.includes(e.name))continue;let i=`${n}/${e.name}`;cc.has(e.name)&&t.push(i),walk(i,r+1)}};return walk(Q,1),t.toSorted()}function classifyConventionalDoc(e){if(!e.endsWith(`.md`))return null;let t=e.split(`/`);if(t[0]!==Q||t.some(e=>e===``||e===`.`||e===`..`))return null;let n=t.slice(0,-1);if(n.length===1&&lc.test(t[1]??``))return{kind:`legacy-plan`,retired:!1};if(n.length===2&&oc.includes(n[1]??``))return{kind:`legacy-plan`,retired:!0};let r=n.length-1,i=!1;if(oc.includes(n[r]??``)&&(i=!0,--r),r<1)return null;let a=n[r]??``;if(!cc.has(a)||r>4)return null;for(let e=1;e<r;e++)if(oc.includes(n[e]??``))return null;return a===sc?{kind:`spec`,retired:i}:{kind:`plan`,retired:i}}function classifyTrackedDoc(e,t){let n=classifyConventionalDoc(e);if(n!==null)return n;if(!e.endsWith(`.md`))return null;let r=w.posix.dirname(e),i=oc.includes(w.posix.basename(r)),a=i?w.posix.dirname(r):r,o=w.posix.basename(a);return!cc.has(o)||!t.includes(a)?null:{kind:o===sc?`spec`:`plan`,retired:i}}function retireDestination(e,t){let n=w.posix.dirname(e),r=w.posix.basename(e);return oc.includes(w.posix.basename(n))?e:n===Q&&lc.test(r)?`${Q}/${ac}/${t}-${r.slice(5)}`:`${n}/${ac}/${r}`}function candidatePairs(e,t){let n=[];for(let r of[...conventionalActiveDirs(e),...t.extraDirs])n.push({active:r,retired:`${r}/${ac}`,retiredDirs:oc.map(e=>`${r}/${e}`),enforced:isEnforced(r,t.enforced)});return n.push({active:Q,retired:`${Q}/${ac}`,retiredDirs:oc.map(e=>`${Q}/${e}`),activePattern:lc,enforced:isEnforced(Q,t.enforced)}),n}function matchableActiveDirs(e,t){let n=/* @__PURE__ */ new Set;for(let r of candidatePairs(e,t))e.readDir(r.active)!==void 0&&n.add(r.active);return[...n].toSorted()}function discoverPairs(e,t){let n=/* @__PURE__ */ new Set;return candidatePairs(e,t).filter(t=>n.has(t.active)||!(listDocs(e,t.active,t.activePattern).length>0||t.retiredDirs.some(t=>listDocs(e,t).length>0))?!1:(n.add(t.active),!0))}function describeForgeError(e){if(e instanceof RepoTargetEmptyError)return`--repo was given with no repository URL (expected e.g. https://host/owner/repo).`;if(e instanceof RepoTargetMismatchError)return`--repo disagrees with the issue URL: --repo names ${e.given}, the issue URL names ${e.fromReference}.`}const uc=[{codepoint:`U+2018`,name:`LEFT SINGLE QUOTATION MARK`,tier:1,char:`‘`,replacement:`'`},{codepoint:`U+2019`,name:`RIGHT SINGLE QUOTATION MARK`,tier:1,char:`’`,replacement:`'`},{codepoint:`U+201C`,name:`LEFT DOUBLE QUOTATION MARK`,tier:1,char:`“`,replacement:`"`},{codepoint:`U+201D`,name:`RIGHT DOUBLE QUOTATION MARK`,tier:1,char:`”`,replacement:`"`},{codepoint:`U+2026`,name:`HORIZONTAL ELLIPSIS`,tier:1,char:`…`,replacement:`...`},{codepoint:`U+2013`,name:`EN DASH`,tier:1,char:`–`,replacement:`-`},{codepoint:`U+00A0`,name:`NO-BREAK SPACE`,tier:1,char:`\xA0`,replacement:` `}],dc=[{codepoint:`U+2500`,name:`BOX DRAWINGS LIGHT HORIZONTAL`,tier:1,char:`─`,replacement:`-`},{codepoint:`U+2501`,name:`BOX DRAWINGS HEAVY HORIZONTAL`,tier:1,char:`━`,replacement:`-`},{codepoint:`U+2502`,name:`BOX DRAWINGS LIGHT VERTICAL`,tier:1,char:`│`,replacement:`|`},{codepoint:`U+2503`,name:`BOX DRAWINGS HEAVY VERTICAL`,tier:1,char:`┃`,replacement:`|`},{codepoint:`U+250C`,name:`BOX DRAWINGS LIGHT DOWN AND RIGHT`,tier:1,char:`┌`,replacement:`+`},{codepoint:`U+2510`,name:`BOX DRAWINGS LIGHT DOWN AND LEFT`,tier:1,char:`┐`,replacement:`+`},{codepoint:`U+2514`,name:`BOX DRAWINGS LIGHT UP AND RIGHT`,tier:1,char:`└`,replacement:`+`},{codepoint:`U+2518`,name:`BOX DRAWINGS LIGHT UP AND LEFT`,tier:1,char:`┘`,replacement:`+`},{codepoint:`U+251C`,name:`BOX DRAWINGS LIGHT VERTICAL AND RIGHT`,tier:1,char:`├`,replacement:`+`},{codepoint:`U+2524`,name:`BOX DRAWINGS LIGHT VERTICAL AND LEFT`,tier:1,char:`┤`,replacement:`+`},{codepoint:`U+252C`,name:`BOX DRAWINGS LIGHT DOWN AND HORIZONTAL`,tier:1,char:`┬`,replacement:`+`},{codepoint:`U+2534`,name:`BOX DRAWINGS LIGHT UP AND HORIZONTAL`,tier:1,char:`┴`,replacement:`+`},{codepoint:`U+253C`,name:`BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL`,tier:1,char:`┼`,replacement:`+`},{codepoint:`U+2550`,name:`BOX DRAWINGS DOUBLE HORIZONTAL`,tier:1,char:`═`,replacement:`-`},{codepoint:`U+2551`,name:`BOX DRAWINGS DOUBLE VERTICAL`,tier:1,char:`║`,replacement:`|`},{codepoint:`U+256D`,name:`BOX DRAWINGS LIGHT ARC DOWN AND RIGHT`,tier:1,char:`╭`,replacement:`+`},{codepoint:`U+256E`,name:`BOX DRAWINGS LIGHT ARC DOWN AND LEFT`,tier:1,char:`╮`,replacement:`+`},{codepoint:`U+256F`,name:`BOX DRAWINGS LIGHT ARC UP AND LEFT`,tier:1,char:`╯`,replacement:`+`},{codepoint:`U+2570`,name:`BOX DRAWINGS LIGHT ARC UP AND RIGHT`,tier:1,char:`╰`,replacement:`+`}],fc=[{codepoint:`U+2014`,name:`EM DASH`,tier:2,char:`—`,replacement:`--`}],pc=[{codepoint:`U+2192`,name:`RIGHTWARDS ARROW`,tier:1,char:`→`,replacement:`->`},{codepoint:`U+2190`,name:`LEFTWARDS ARROW`,tier:1,char:`←`,replacement:`<-`},{codepoint:`U+2194`,name:`LEFT RIGHT ARROW`,tier:1,char:`↔`,replacement:`<->`},{codepoint:`U+21B3`,name:`DOWNWARDS ARROW WITH TIP RIGHTWARDS`,tier:1,char:`↳`,replacement:`->`},{codepoint:`U+21D2`,name:`RIGHTWARDS DOUBLE ARROW`,tier:1,char:`⇒`,replacement:`=>`},{codepoint:`U+21D0`,name:`LEFTWARDS DOUBLE ARROW`,tier:1,char:`⇐`,replacement:`<=`}],mc=[{codepoint:`U+2713`,name:`CHECK MARK`,tier:2,char:`✓`,replacement:`[ok]`},{codepoint:`U+2717`,name:`BALLOT X`,tier:2,char:`✗`,replacement:`[x]`},{codepoint:`U+26A0`,name:`WARNING SIGN`,tier:2,char:`⚠`,replacement:`!`},{codepoint:`U+00B7`,name:`MIDDLE DOT`,tier:2,char:`·`,replacement:`-`},{codepoint:`U+25B6`,name:`BLACK RIGHT-POINTING TRIANGLE`,tier:2,char:`▶`,replacement:`>`},{codepoint:`U+25BA`,name:`BLACK RIGHT-POINTING POINTER`,tier:2,char:`►`,replacement:`>`},{codepoint:`U+25C4`,name:`BLACK LEFT-POINTING POINTER`,tier:2,char:`◄`,replacement:`<`},{codepoint:`U+25C0`,name:`BLACK LEFT-POINTING TRIANGLE`,tier:2,char:`◀`,replacement:`<`},{codepoint:`U+0394`,name:`GREEK CAPITAL LETTER DELTA`,tier:2,char:`Δ`,replacement:`delta`}];function rangeOffenders(e,t,n,r){let i=[];for(let a=e;a<=t;a+=1)i.push({codepoint:`U+${a.toString(16).toUpperCase().padStart(4,`0`)}`,name:n,tier:1,char:String.fromCodePoint(a),group:r});return i}const hc=[{codepoint:`U+202A`,name:`LEFT-TO-RIGHT EMBEDDING`,tier:1,char:``,group:`invisible`},{codepoint:`U+202B`,name:`RIGHT-TO-LEFT EMBEDDING`,tier:1,char:``,group:`invisible`},{codepoint:`U+202C`,name:`POP DIRECTIONAL FORMATTING`,tier:1,char:``,group:`invisible`},{codepoint:`U+202D`,name:`LEFT-TO-RIGHT OVERRIDE`,tier:1,char:``,group:`invisible`},{codepoint:`U+202E`,name:`RIGHT-TO-LEFT OVERRIDE`,tier:1,char:``,group:`invisible`},{codepoint:`U+2066`,name:`LEFT-TO-RIGHT ISOLATE`,tier:1,char:``,group:`invisible`},{codepoint:`U+2067`,name:`RIGHT-TO-LEFT ISOLATE`,tier:1,char:``,group:`invisible`},{codepoint:`U+2068`,name:`FIRST STRONG ISOLATE`,tier:1,char:``,group:`invisible`},{codepoint:`U+2069`,name:`POP DIRECTIONAL ISOLATE`,tier:1,char:``,group:`invisible`},{codepoint:`U+200B`,name:`ZERO WIDTH SPACE`,tier:1,char:``,group:`invisible`},{codepoint:`U+2060`,name:`WORD JOINER`,tier:1,char:``,group:`invisible`},{codepoint:`U+2061`,name:`FUNCTION APPLICATION`,tier:1,char:``,group:`invisible`},{codepoint:`U+2062`,name:`INVISIBLE TIMES`,tier:1,char:``,group:`invisible`},{codepoint:`U+2063`,name:`INVISIBLE SEPARATOR`,tier:1,char:``,group:`invisible`},{codepoint:`U+2064`,name:`INVISIBLE PLUS`,tier:1,char:``,group:`invisible`},{codepoint:`U+FEFF`,name:`ZERO WIDTH NO-BREAK SPACE`,tier:1,char:``,group:`invisible`},{codepoint:`U+00AD`,name:`SOFT HYPHEN`,tier:1,char:``,group:`invisible`},{codepoint:`U+115F`,name:`HANGUL CHOSEONG FILLER`,tier:1,char:`ᅟ`,group:`invisible`},{codepoint:`U+1160`,name:`HANGUL JUNGSEONG FILLER`,tier:1,char:`ᅠ`,group:`invisible`},{codepoint:`U+3164`,name:`HANGUL FILLER`,tier:1,char:`ㅤ`,group:`invisible`},{codepoint:`U+FFA0`,name:`HALFWIDTH HANGUL FILLER`,tier:1,char:`ᅠ`,group:`invisible`},...rangeOffenders(917504,917631,`TAG CHARACTER`,`invisible`),...rangeOffenders(0,8,`C0 CONTROL`,`invisible`),...rangeOffenders(11,12,`C0 CONTROL`,`invisible`),...rangeOffenders(14,31,`C0 CONTROL`,`invisible`),{codepoint:`U+007F`,name:`DELETE`,tier:1,char:``,group:`invisible`}],gc=[{codepoint:`U+200C`,name:`ZERO WIDTH NON-JOINER`,tier:1,char:``,group:`script`},{codepoint:`U+200D`,name:`ZERO WIDTH JOINER`,tier:1,char:``,group:`script`},{codepoint:`U+200E`,name:`LEFT-TO-RIGHT MARK`,tier:1,char:``,group:`script`},{codepoint:`U+200F`,name:`RIGHT-TO-LEFT MARK`,tier:1,char:``,group:`script`},{codepoint:`U+061C`,name:`ARABIC LETTER MARK`,tier:1,char:``,group:`script`},{codepoint:`U+3000`,name:`IDEOGRAPHIC SPACE`,tier:1,char:` `,group:`script`}],_c=[{codepoint:`U+2000`,name:`EN QUAD`,tier:1,char:` `,group:`space`,replacement:` `},{codepoint:`U+2001`,name:`EM QUAD`,tier:1,char:` `,group:`space`,replacement:` `},{codepoint:`U+2002`,name:`EN SPACE`,tier:1,char:` `,group:`space`,replacement:` `},{codepoint:`U+2003`,name:`EM SPACE`,tier:1,char:` `,group:`space`,replacement:` `},{codepoint:`U+2004`,name:`THREE-PER-EM SPACE`,tier:1,char:` `,group:`space`,replacement:` `},{codepoint:`U+2005`,name:`FOUR-PER-EM SPACE`,tier:1,char:` `,group:`space`,replacement:` `},{codepoint:`U+2006`,name:`SIX-PER-EM SPACE`,tier:1,char:` `,group:`space`,replacement:` `},{codepoint:`U+2007`,name:`FIGURE SPACE`,tier:1,char:` `,group:`space`,replacement:` `},{codepoint:`U+2008`,name:`PUNCTUATION SPACE`,tier:1,char:` `,group:`space`,replacement:` `},{codepoint:`U+2009`,name:`THIN SPACE`,tier:1,char:` `,group:`space`,replacement:` `},{codepoint:`U+200A`,name:`HAIR SPACE`,tier:1,char:` `,group:`space`,replacement:` `},{codepoint:`U+205F`,name:`MEDIUM MATHEMATICAL SPACE`,tier:1,char:` `,group:`space`,replacement:` `}],vc=[{codepoint:`U+2010`,name:`HYPHEN`,tier:1,char:`‐`,replacement:`-`},{codepoint:`U+2011`,name:`NON-BREAKING HYPHEN`,tier:1,char:`‑`,replacement:`-`},{codepoint:`U+2012`,name:`FIGURE DASH`,tier:1,char:`‒`,replacement:`-`},{codepoint:`U+2015`,name:`HORIZONTAL BAR`,tier:2,char:`―`,replacement:`--`}],yc=[...uc,...dc,...pc,...mc,...fc,...hc,...gc,..._c,...vc],bc={math:[{codepoint:`U+00D7`,name:`MULTIPLICATION SIGN`,tier:1,char:`×`,replacement:`x`},{codepoint:`U+2212`,name:`MINUS SIGN`,tier:1,char:`−`,replacement:`-`},{codepoint:`U+2265`,name:`GREATER-THAN OR EQUAL TO`,tier:1,char:`≥`,replacement:`>=`},{codepoint:`U+2264`,name:`LESS-THAN OR EQUAL TO`,tier:1,char:`≤`,replacement:`<=`},{codepoint:`U+2260`,name:`NOT EQUAL TO`,tier:1,char:`≠`,replacement:`!=`}]};function resolveOffenders(e){let t=(e?.deny??[]).flatMap(e=>bc[e]??[]),n=new Set((e?.allow??[]).map(e=>e.toUpperCase()));return[...yc,...t].filter(e=>!n.has(e.codepoint))}function offendersByChar(e){return new Map(e.map(e=>[e.char,e]))}const xc=new Map([...yc,...Object.values(bc).flat()].map(e=>[e.codepoint,e.name]));function offenderNameByCodepoint(e){return xc.get(e)}var SpanLexer=class{spans=[];spanStart=0;spanContext;constructor(e){this.spanContext=e}flushTo(e,t){t!==this.spanContext&&(e>this.spanStart&&this.spans.push({start:this.spanStart,end:e,context:this.spanContext}),this.spanStart=e,this.spanContext=t)}finish(e){return e>this.spanStart&&this.spans.push({start:this.spanStart,end:e,context:this.spanContext}),this.spans}};const Sc=/* @__PURE__ */ new Set([`(`,`[`,`{`,`,`,`;`,`:`,`?`,`=`,`+`,`-`,`*`,`%`,`<`,`>`,`!`,`&`,`|`,`^`,`~`,`}`]),Cc=/* @__PURE__ */ new Set([`return`,`typeof`,`instanceof`,`in`,`of`,`new`,`delete`,`void`,`throw`,`case`,`do`,`else`,`yield`,`await`,`extends`,`default`]);function isIdentifierChar(e){return/[A-Za-z0-9_$]/.test(e)}function isJsxNameStart(e){return e!==void 0&&/[A-Za-z_$>]/.test(e)}function resumeAfterTagClose(e){return e[e.length-1]?.kind===`jsx-children`?`jsx-text`:`code`}var JsTsLexer=class extends SpanLexer{text;jsx;n;i=0;mode=`code`;expectsExpression=!0;regexInClass=!1;stack=[];bailed=!1;constructor(e,t){super(`code`),this.text=e,this.jsx=t,this.n=e.length}run(){for(;this.i<this.n&&!this.bailed;)this.step();if(this.bailed)return null;this.mode===`line-comment`&&(this.mode=`code`);let e=this.finish(this.n);return this.mode!==`code`||this.stack.length>0?null:e}bail(){this.bailed=!0}char(e=0){return this.text[this.i+e]??``}step(){switch(this.mode){case`code`:return this.stepCode();case`line-comment`:return this.stepLineComment();case`block-comment`:return this.stepBlockComment();case`string-single`:case`string-double`:return this.stepString();case`regex`:return this.stepRegex();case`template-text`:return this.stepTemplateText();case`jsx-tag`:case`jsx-close-tag`:return this.stepJsxTag();case`jsx-attr-single`:case`jsx-attr-double`:return this.stepJsxAttr();case`jsx-text`:return this.stepJsxText()}}stepCode(){this.flushTo(this.i,`code`);let e=this.char(),t=this.char(1);if(e===`/`&&(t===`/`||t===`*`))return this.startComment(t);if(e===`/`&&this.expectsExpression)return this.startRegex();if(e===`"`||e===`'`)return this.startString(e);if(e==="`")return this.startTemplate();if(!(e===`}`&&this.stack.length>0&&this.stepCloseBrace())){if(e===`{`)return this.stepOpenBrace();if(this.jsx&&e===`<`&&this.expectsExpression&&isJsxNameStart(t))this.mode=`jsx-tag`,this.i+=1;else{if(isIdentifierChar(e))return this.stepIdentifierOrNumber();/\s/.test(e)||(this.expectsExpression=Sc.has(e)),this.i+=1}}}startComment(e){this.mode=e===`/`?`line-comment`:`block-comment`,this.i+=2}startRegex(){this.mode=`regex`,this.regexInClass=!1,this.i+=1}startString(e){this.mode=e===`"`?`string-double`:`string-single`,this.expectsExpression=!1,this.i+=1}startTemplate(){let e=!this.expectsExpression;this.stack.push({kind:`template`,tagged:e}),this.mode=`template-text`,this.expectsExpression=!1,this.flushTo(this.i+1,e?`tagged-template`:`template`),this.i+=1}stepCloseBrace(){let e=this.stack[this.stack.length-1];return e?.kind===`template-expr`?this.closeTemplateExprBrace(e):e?.kind===`jsx-expr`&&this.closeJsxExprBrace(e)}closeTemplateExprBrace(e){return e.depth>0?(--e.depth,this.expectsExpression=!1,this.i+=1,!0):(this.stack.pop(),this.mode=`template-text`,this.expectsExpression=!1,this.flushTo(this.i+1,e.tagged?`tagged-template`:`template`),this.i+=1,!0)}closeJsxExprBrace(e){return e.depth>0?(--e.depth,this.expectsExpression=!1,this.i+=1,!0):(this.stack.pop(),this.mode=e.returnTo===`jsx-text`?`jsx-text`:`jsx-tag`,this.expectsExpression=!1,this.flushTo(this.i+1,this.mode===`jsx-text`?`jsx-text`:`code`),this.i+=1,!0)}stepOpenBrace(){let e=this.stack[this.stack.length-1];(e?.kind===`template-expr`||e?.kind===`jsx-expr`)&&(e.depth+=1),this.expectsExpression=!0,this.i+=1}stepIdentifierOrNumber(){let e=this.i;for(;e<this.n&&isIdentifierChar(this.text[e]??``);)e+=1;let t=this.text.slice(this.i,e);this.expectsExpression=Cc.has(t),this.i=e}stepLineComment(){this.flushTo(this.i,`comment`),this.char()===`
|
|
6074
6078
|
`&&(this.mode=`code`,this.expectsExpression=!0),this.i+=1}stepBlockComment(){this.flushTo(this.i,`comment`),this.char()===`*`&&this.char(1)===`/`?(this.mode=`code`,this.expectsExpression=!1,this.i+=2):this.i+=1}stepString(){this.flushTo(this.i,`string`);let e=this.char();if(e===`
|
|
6075
6079
|
`)return this.bail();e===`\\`?this.i+=2:(e===(this.mode===`string-single`?`'`:`"`)&&(this.mode=`code`),this.i+=1)}stepRegex(){this.flushTo(this.i,`regex`);let e=this.char();if(e===`
|
|
6076
|
-
`)return this.bail();if(e===`\\`)this.i+=2;else{if(e===`[`)this.regexInClass=!0;else if(e===`]`)this.regexInClass=!1;else if(e===`/`&&!this.regexInClass)return this.endRegex();this.i+=1}}endRegex(){for(this.i+=1;this.i<this.n&&/[a-zA-Z]/.test(this.char());)this.i+=1;this.mode=`code`,this.expectsExpression=!1}stepTemplateText(){let e=this.stack[this.stack.length-1],t=e?.kind===`template`&&e.tagged;this.flushTo(this.i,t?`tagged-template`:`template`);let n=this.char();if(n===`\\`)this.i+=2;else{if(n==="`")return this.endTemplate();if(n===`$`&&this.char(1)===`{`)return this.startTemplateExpr(t);this.i+=1}}endTemplate(){this.stack.pop(),this.mode=`code`,this.expectsExpression=!1,this.flushTo(this.i+1,`code`),this.i+=1}startTemplateExpr(e){this.stack.push({kind:`template-expr`,tagged:e,depth:0}),this.mode=`code`,this.expectsExpression=!0,this.flushTo(this.i+2,`code`),this.i+=2}stepJsxTag(){this.flushTo(this.i,`code`);let e=this.char();if(e===`"`||e===`'`)this.mode=e===`"`?`jsx-attr-double`:`jsx-attr-single`,this.i+=1;else if(e===`{`)this.stack.push({kind:`jsx-expr`,depth:0,returnTo:`jsx-tag`}),this.mode=`code`,this.expectsExpression=!0,this.i+=1;else{if(e===`/`&&this.char(1)===`>`)return this.closeSelfClosingTag();if(e===`>`)return this.closeOpenOrCloseTag();this.i+=1}}closeSelfClosingTag(){this.i+=2,this.mode=resumeAfterTagClose(this.stack),this.expectsExpression=!1}closeOpenOrCloseTag(){if(this.mode===`jsx-close-tag`)return this.closeClosingTag();this.stack.push({kind:`jsx-children`}),this.mode=`jsx-text`,this.i+=1}closeClosingTag(){if(this.stack[this.stack.length-1]?.kind!==`jsx-children`)return this.bail();this.stack.pop(),this.i+=1,this.mode=resumeAfterTagClose(this.stack),this.expectsExpression=!1}stepJsxAttr(){this.flushTo(this.i,`jsx-attribute`);let e=this.mode===`jsx-attr-single`?`'`:`"`;this.char()===e&&(this.mode=`jsx-tag`,this.flushTo(this.i+1,`code`)),this.i+=1}stepJsxText(){this.flushTo(this.i,`jsx-text`);let e=this.char();if(e===`<`)return this.startTagFromJsxText();if(e===`{`)return this.startJsxExprFromText();this.i+=1}startTagFromJsxText(){let e=this.char(1);e===`/`?(this.mode=`jsx-close-tag`,this.flushTo(this.i,`code`),this.i+=2):isJsxNameStart(e)?(this.mode=`jsx-tag`,this.flushTo(this.i,`code`),this.i+=1):this.bail()}startJsxExprFromText(){if(this.stack[this.stack.length-1]?.kind!==`jsx-children`)return this.bail();this.stack.push({kind:`jsx-expr`,depth:0,returnTo:`jsx-text`}),this.mode=`code`,this.expectsExpression=!0,this.flushTo(this.i+1,`code`),this.i+=1}};function classifyJsTs(e,t){return new JsTsLexer(e,t).run()}const
|
|
6080
|
+
`)return this.bail();if(e===`\\`)this.i+=2;else{if(e===`[`)this.regexInClass=!0;else if(e===`]`)this.regexInClass=!1;else if(e===`/`&&!this.regexInClass)return this.endRegex();this.i+=1}}endRegex(){for(this.i+=1;this.i<this.n&&/[a-zA-Z]/.test(this.char());)this.i+=1;this.mode=`code`,this.expectsExpression=!1}stepTemplateText(){let e=this.stack[this.stack.length-1],t=e?.kind===`template`&&e.tagged;this.flushTo(this.i,t?`tagged-template`:`template`);let n=this.char();if(n===`\\`)this.i+=2;else{if(n==="`")return this.endTemplate();if(n===`$`&&this.char(1)===`{`)return this.startTemplateExpr(t);this.i+=1}}endTemplate(){this.stack.pop(),this.mode=`code`,this.expectsExpression=!1,this.flushTo(this.i+1,`code`),this.i+=1}startTemplateExpr(e){this.stack.push({kind:`template-expr`,tagged:e,depth:0}),this.mode=`code`,this.expectsExpression=!0,this.flushTo(this.i+2,`code`),this.i+=2}stepJsxTag(){this.flushTo(this.i,`code`);let e=this.char();if(e===`"`||e===`'`)this.mode=e===`"`?`jsx-attr-double`:`jsx-attr-single`,this.i+=1;else if(e===`{`)this.stack.push({kind:`jsx-expr`,depth:0,returnTo:`jsx-tag`}),this.mode=`code`,this.expectsExpression=!0,this.i+=1;else{if(e===`/`&&this.char(1)===`>`)return this.closeSelfClosingTag();if(e===`>`)return this.closeOpenOrCloseTag();this.i+=1}}closeSelfClosingTag(){this.i+=2,this.mode=resumeAfterTagClose(this.stack),this.expectsExpression=!1}closeOpenOrCloseTag(){if(this.mode===`jsx-close-tag`)return this.closeClosingTag();this.stack.push({kind:`jsx-children`}),this.mode=`jsx-text`,this.i+=1}closeClosingTag(){if(this.stack[this.stack.length-1]?.kind!==`jsx-children`)return this.bail();this.stack.pop(),this.i+=1,this.mode=resumeAfterTagClose(this.stack),this.expectsExpression=!1}stepJsxAttr(){this.flushTo(this.i,`jsx-attribute`);let e=this.mode===`jsx-attr-single`?`'`:`"`;this.char()===e&&(this.mode=`jsx-tag`,this.flushTo(this.i+1,`code`)),this.i+=1}stepJsxText(){this.flushTo(this.i,`jsx-text`);let e=this.char();if(e===`<`)return this.startTagFromJsxText();if(e===`{`)return this.startJsxExprFromText();this.i+=1}startTagFromJsxText(){let e=this.char(1);e===`/`?(this.mode=`jsx-close-tag`,this.flushTo(this.i,`code`),this.i+=2):isJsxNameStart(e)?(this.mode=`jsx-tag`,this.flushTo(this.i,`code`),this.i+=1):this.bail()}startJsxExprFromText(){if(this.stack[this.stack.length-1]?.kind!==`jsx-children`)return this.bail();this.stack.push({kind:`jsx-expr`,depth:0,returnTo:`jsx-text`}),this.mode=`code`,this.expectsExpression=!0,this.flushTo(this.i+1,`code`),this.i+=1}};function classifyJsTs(e,t){return new JsTsLexer(e,t).run()}const wc={extensions:[`.js`,`.mjs`,`.cjs`,`.ts`,`.mts`,`.cts`],definition:{classify:e=>classifyJsTs(e,!1)}},Tc={extensions:[`.jsx`,`.tsx`],definition:{classify:e=>classifyJsTs(e,!0)}};var KtJavaLexer=class extends SpanLexer{text;kotlin;rawStringContext;n;i=0;mode=`code`;stack=[];bailed=!1;constructor(e,t){super(`code`),this.text=e,this.kotlin=t,this.rawStringContext=t?`raw-string`:`text-block`,this.n=e.length}run(){for(;this.i<this.n&&!this.bailed;)this.step();if(this.bailed)return null;this.mode===`line-comment`&&(this.mode=`code`);let e=this.finish(this.n);return this.mode!==`code`||this.stack.length>0?null:e}bail(){this.bailed=!0}char(e=0){return this.text[this.i+e]??``}step(){switch(this.mode){case`code`:return this.stepCode();case`line-comment`:return this.stepLineComment();case`block-comment`:return this.stepBlockComment();case`string`:return this.stepString();case`raw-string`:return this.stepRawString();case`char`:return this.stepChar()}}stepCode(){this.flushTo(this.i,`code`);let e=this.char();if(e===`/`&&this.char(1)===`/`)return this.enter(`line-comment`,2);if(e===`/`&&this.char(1)===`*`)return this.enter(`block-comment`,2);if(e===`"`&&this.char(1)===`"`&&this.char(2)===`"`)return this.flushTo(this.i+3,this.rawStringContext),this.enter(`raw-string`,3);if(e===`"`)return this.enter(`string`,1);if(e===`'`)return this.enter(`char`,1);if(e===`}`&&this.stack.length>0)return this.stepCloseBrace();if(e===`{`)return this.stepOpenBrace();this.i+=1}enter(e,t){this.mode=e,this.i+=t}stepCloseBrace(){let e=this.stack[this.stack.length-1];e?e.depth>0?(--e.depth,this.i+=1):(this.stack.pop(),this.mode=`string`,this.flushTo(this.i+1,`string`),this.i+=1):this.i+=1}stepOpenBrace(){let e=this.stack[this.stack.length-1];e&&(e.depth+=1),this.i+=1}stepLineComment(){this.flushTo(this.i,`comment`),this.char()===`
|
|
6077
6081
|
`&&(this.mode=`code`),this.i+=1}stepBlockComment(){if(this.flushTo(this.i,`comment`),this.char()===`*`&&this.char(1)===`/`)return this.enter(`code`,2);this.i+=1}stepString(){this.flushTo(this.i,`string`);let e=this.char();if(e===`
|
|
6078
6082
|
`)return this.bail();if(e===`\\`)this.i+=2;else{if(this.kotlin&&e===`$`&&this.char(1)===`{`)return this.startStringExpr();if(e===`"`)return this.enter(`code`,1);this.i+=1}}startStringExpr(){this.stack.push({depth:0}),this.flushTo(this.i+2,`code`),this.enter(`code`,2)}stepChar(){this.flushTo(this.i,`string`);let e=this.char();if(e===`
|
|
6079
|
-
`)return this.bail();if(e===`\\`)this.i+=2;else{if(e===`'`)return this.enter(`code`,1);this.i+=1}}stepRawString(){if(this.flushTo(this.i,this.rawStringContext),this.char()===`"`&&this.char(1)===`"`&&this.char(2)===`"`)return this.flushTo(this.i+3,`code`),this.enter(`code`,3);this.i+=1}};function classifyKtJava(e,t){return new KtJavaLexer(e,t).run()}const
|
|
6083
|
+
`)return this.bail();if(e===`\\`)this.i+=2;else{if(e===`'`)return this.enter(`code`,1);this.i+=1}}stepRawString(){if(this.flushTo(this.i,this.rawStringContext),this.char()===`"`&&this.char(1)===`"`&&this.char(2)===`"`)return this.flushTo(this.i+3,`code`),this.enter(`code`,3);this.i+=1}};function classifyKtJava(e,t){return new KtJavaLexer(e,t).run()}const Ec={extensions:[`.kt`,`.kts`],definition:{classify:e=>classifyKtJava(e,!0)}},Dc={extensions:[`.java`],definition:{classify:e=>classifyKtJava(e,!1)}},Oc=/[A-Za-z!?]/,kc=/[A-Za-z0-9:_-]/;var MarkupLexer=class extends SpanLexer{text;html;n;i=0;mode=`text`;tagKind=`open`;pendingTagName=``;islandCloseTag=``;bailed=!1;constructor(e,t){super(`markup-text`),this.text=e,this.html=t,this.n=e.length}run(){for(;this.i<this.n&&!this.bailed;)this.step();if(this.bailed)return null;let e=this.finish(this.n);return this.mode===`text`?e:null}bail(){this.bailed=!0}char(e=0){return this.text[this.i+e]??``}step(){switch(this.mode){case`text`:return this.stepText();case`tag`:return this.stepTag();case`attr-single`:case`attr-double`:return this.stepAttr();case`comment`:return this.stepComment();case`cdata`:return this.stepCdata();case`island`:return this.stepIsland()}}stepText(){if(this.flushTo(this.i,`markup-text`),this.char()!==`<`)this.i+=1;else{if(this.text.startsWith(`<!--`,this.i))return this.startComment();if(this.text.startsWith(`<![CDATA[`,this.i))return this.startCdata();if(this.char(1)===`/`)return this.startCloseTag();if(Oc.test(this.char(1)))return this.startOpenTag();this.bail()}}startComment(){this.flushTo(this.i,`code`),this.i+=4,this.mode=`comment`}stepComment(){this.flushTo(this.i,`xml-comment`),this.text.startsWith(`-->`,this.i)?(this.flushTo(this.i,`code`),this.i+=3,this.mode=`text`):this.i+=1}startCdata(){this.flushTo(this.i,`code`),this.i+=9,this.mode=`cdata`}stepCdata(){this.flushTo(this.i,`cdata`),this.text.startsWith(`]]>`,this.i)?(this.flushTo(this.i,`code`),this.i+=3,this.mode=`text`):this.i+=1}startOpenTag(){this.tagKind=`open`,this.enterTagName()}startCloseTag(){this.flushTo(this.i,`code`),this.i+=2,this.tagKind=`close`,this.mode=`tag`,this.pendingTagName=``}enterTagName(){this.flushTo(this.i,`code`),this.i+=1;let e=this.i;for(;e<this.n&&kc.test(this.text[e]??``);)e+=1;this.pendingTagName=this.text.slice(this.i,e).toLowerCase(),this.i=e,this.mode=`tag`}stepTag(){this.flushTo(this.i,`code`);let e=this.char();if(e===`"`)return this.enterAttr(`attr-double`);if(e===`'`)return this.enterAttr(`attr-single`);if(e===`/`&&this.char(1)===`>`)return this.closeSelfClosingTag();if(e===`>`)return this.closeTag();this.i+=1}enterAttr(e){this.mode=e,this.i+=1}closeSelfClosingTag(){this.i+=2,this.mode=`text`}closeTag(){this.i+=1,this.tagKind===`close`?this.mode=`text`:this.html&&(this.pendingTagName===`script`||this.pendingTagName===`style`)?(this.islandCloseTag=this.pendingTagName,this.mode=`island`):this.mode=`text`}stepAttr(){this.flushTo(this.i,`markup-attribute`);let e=this.mode===`attr-single`?`'`:`"`;this.char()===e&&(this.mode=`tag`,this.flushTo(this.i+1,`code`)),this.i+=1}stepIsland(){if(this.flushTo(this.i,`unclassified`),this.char()===`<`&&this.char(1)===`/`&&this.matchesIslandClose())return this.closeIsland();this.i+=1}matchesIslandClose(){let e=this.i+2,t=e+this.islandCloseTag.length;if(this.text.slice(e,t).toLowerCase()!==this.islandCloseTag)return!1;let n=this.text[t]??``;return n===`>`||n===`/`||/\s/.test(n)}closeIsland(){this.flushTo(this.i,`code`);let e=this.i;for(;e<this.n&&this.text[e]!==`>`;)e+=1;this.i=Math.min(e+1,this.n),this.mode=`text`}};function classifyMarkup(e,t){return new MarkupLexer(e,t).run()}const Ac={extensions:[`.xml`,`.svg`],definition:{classify:e=>classifyMarkup(e,!1)}},jc={extensions:[`.html`,`.htm`],definition:{classify:e=>classifyMarkup(e,!0)}};function triesJsonParse(e){try{return JSON.parse(e),!0}catch{return!1}}function triesJsoncParse(e){let t=[];return _e(e,t),t.length===0}function triesJson5Parse(e){try{return me.parse(e),!0}catch{return!1}}function triesYamlParse(e){return De(e).every(e=>e.errors.length===0)}function conditionalParseVerify(e){return(t,n)=>!e(t)||e(n)}var JsonLexer=class extends SpanLexer{text;commentsAllowed;n;i=0;mode=`code`;bailed=!1;constructor(e,t){super(`code`),this.text=e,this.commentsAllowed=t,this.n=e.length}run(){for(;this.i<this.n&&!this.bailed;)this.step();if(this.bailed)return null;this.mode===`line-comment`&&(this.mode=`code`);let e=this.finish(this.n);return this.mode===`code`?e:null}bail(){this.bailed=!0}char(e=0){return this.text[this.i+e]??``}step(){switch(this.mode){case`code`:return this.stepCode();case`line-comment`:return this.stepLineComment();case`block-comment`:return this.stepBlockComment();case`string-single`:case`string-double`:return this.stepString()}}stepCode(){this.flushTo(this.i,`code`);let e=this.char();this.commentsAllowed&&e===`/`&&this.char(1)===`/`?(this.mode=`line-comment`,this.i+=2):this.commentsAllowed&&e===`/`&&this.char(1)===`*`?(this.mode=`block-comment`,this.i+=2):e===`"`?(this.mode=`string-double`,this.i+=1):(e===`'`&&(this.mode=`string-single`),this.i+=1)}stepLineComment(){this.flushTo(this.i,`comment`),this.char()===`
|
|
6080
6084
|
`&&(this.mode=`code`),this.i+=1}stepBlockComment(){this.flushTo(this.i,`comment`),this.char()===`*`&&this.char(1)===`/`?(this.mode=`code`,this.i+=2):this.i+=1}stepString(){this.flushTo(this.i,`string`);let e=this.char();if(e===`
|
|
6081
|
-
`)return this.bail();e===`\\`?this.i+=2:(e===(this.mode===`string-single`?`'`:`"`)&&(this.mode=`code`),this.i+=1)}};const strictThenJsonc=(e,t)=>conditionalParseVerify(triesJsonParse)(e,t)&&conditionalParseVerify(triesJsoncParse)(e,t);function classifyJsonFamily(e,t){return new JsonLexer(e,t).run()}function classifyAsProse(e){return[{start:0,end:e.length,context:`prose`}]}const
|
|
6082
|
-
`),a=[],o=0;for(let t=0;t<i.length;t+=1){let n=i[t]??``;if(!hasIgnoreMarker(n))for(let{column:i,offender:s}of lineOffenders(n,r))(o+i!==0||s.codepoint!==`U+FEFF`)&&a.push({offset:o+i,hit:{path:e,line:t+1,column:i+1,offender:s}});o+=n.length+1}return a}function lineOffenders(e,t){let n=[],r=0;for(;r<e.length;){let i=String.fromCodePoint(e.codePointAt(r)??0),a=t.get(i);a!==void 0&&n.push({column:r,offender:a}),r+=i.length}return n}function createRealScanExecutor(e){return{listTrackedFiles(){return
|
|
6083
|
-
`).map(e=>e.trim()).filter(e=>e!==``)},isBinaryPath(t){try{return
|
|
6084
|
-
`),c=0;for(let t=0;t<s.length;t+=1){let n=s[t]??``;if(!hasIgnoreMarker(n)){let r={rel:e,spans:i,lineStart:c,lineIdx:t,line:n};for(let e of a)o.push(...matchesForRule(r,e))}c+=n.length+1}return o}const
|
|
6085
|
+
`)return this.bail();e===`\\`?this.i+=2:(e===(this.mode===`string-single`?`'`:`"`)&&(this.mode=`code`),this.i+=1)}};const strictThenJsonc=(e,t)=>conditionalParseVerify(triesJsonParse)(e,t)&&conditionalParseVerify(triesJsoncParse)(e,t);function classifyJsonFamily(e,t){return new JsonLexer(e,t).run()}function classifyAsProse(e){return[{start:0,end:e.length,context:`prose`}]}const Mc=[wc,Tc,Ec,Dc,Ac,jc,{extensions:[`.json`],definition:{classify:e=>classifyJsonFamily(e,!0),verify:strictThenJsonc}},{extensions:[`.jsonc`],definition:{classify:e=>classifyJsonFamily(e,!0),verify:conditionalParseVerify(triesJsoncParse)}},{extensions:[`.json5`],definition:{classify:e=>classifyJsonFamily(e,!0),verify:conditionalParseVerify(triesJson5Parse)}},{extensions:[`.yml`,`.yaml`],definition:{classify:classifyAsProse,verify:conditionalParseVerify(triesYamlParse)}}],proseSpan=e=>[{start:0,end:e.length,context:`prose`}],Nc={extensions:[`.md`,`.markdown`,`.txt`,`.adoc`,`.rst`],definition:{classify:proseSpan}},Pc=/* @__PURE__ */ new Map;for(let{extensions:e,definition:t}of[Nc,...Mc])for(let n of e)Pc.set(n.toLowerCase(),t);function resolveFamily(e,t){if(t.length>0&&F(t)(e))return{classify:proseSpan};let n=w.extname(e).toLowerCase();if(n!==``)return Pc.get(n)}function classifyFile(e,t,n=[]){return resolveFamily(e,n)?.classify(t)??[{start:0,end:t.length,context:`unclassified`}]}function contextAt(e,t){return spanCovering(e,t)?.context??`unclassified`}function spanCovering(e,t){for(let n of e)if(t>=n.start&&t<n.end)return n}const Fc=[`chars-ignore-line`,`ascii-ignore-line`];function hasIgnoreMarker(e){return Fc.some(t=>e.includes(t))}function looksBinary(e){let t=Math.min(e.length,8e3);for(let n=0;n<t;n+=1)if(e[n]===0)return!0;return!1}function scanWithOffsets(e,t,n){let r=offendersByChar(n),i=t.split(`
|
|
6086
|
+
`),a=[],o=0;for(let t=0;t<i.length;t+=1){let n=i[t]??``;if(!hasIgnoreMarker(n))for(let{column:i,offender:s}of lineOffenders(n,r))(o+i!==0||s.codepoint!==`U+FEFF`)&&a.push({offset:o+i,hit:{path:e,line:t+1,column:i+1,offender:s}});o+=n.length+1}return a}function lineOffenders(e,t){let n=[],r=0;for(;r<e.length;){let i=String.fromCodePoint(e.codePointAt(r)??0),a=t.get(i);a!==void 0&&n.push({column:r,offender:a}),r+=i.length}return n}function createRealScanExecutor(e){return{listTrackedFiles(){return N(`git`,[`ls-files`],{cwd:e,stdio:[`ignore`,`pipe`,`ignore`]}).toString(`utf-8`).split(`
|
|
6087
|
+
`).map(e=>e.trim()).filter(e=>e!==``)},isBinaryPath(t){try{return N(`git`,[`check-attr`,`text`,`--`,t],{cwd:e,stdio:[`ignore`,`pipe`,`ignore`]}).toString(`utf-8`).trim().endsWith(`: unset`)}catch{return!1}},readFileBuffer(t){try{return p(w.join(e,...t.split(`/`)))}catch{return}}}}const Ic=/\\u\{[0-9a-fA-F]{1,6}\}|\\u[0-9a-fA-F]{4}|\\x[0-9a-fA-F]{2}/g,Lc=/&#(?:[xX][0-9a-fA-F]{1,6}|[0-9]{1,7});/g,Rc=/* @__PURE__ */ new Set([`jsx-text`,`jsx-attribute`,`markup-text`,`markup-attribute`]),zc=/* @__PURE__ */ new Set([`string`,`template`]),Bc=/* @__PURE__ */ new Set([...Tc.extensions,...jc.extensions,...Ac.extensions]),Vc=new Set(Tc.extensions);function codepointHex(e){return e.toString(16).toUpperCase().padStart(4,`0`)}function isScalarValue(e){return!Number.isNaN(e)&&e<=1114111&&!(e>=55296&&e<=57343)}function escapeRawHex(e){let t=e.startsWith(`\\u{`)?e.slice(3,-1):e.slice(2);return Number.parseInt(t,16)}function escapeCodepoint(e){let t=escapeRawHex(e);return isScalarValue(t)?t:void 0}function entityCodepoint(e){let t=e.slice(2,-1),n=t.startsWith(`x`)||t.startsWith(`X`),r=Number.parseInt(n?t.slice(1):t,n?16:10);if(!(!isScalarValue(r)||r<128))return r}function hasCandidateToken(e){return e.includes(`\\u`)||e.includes(`\\x`)||e.includes(`&#`)}const Hc={rule:`js-escape-in-markup`,tokenRe:Ic,contexts:Rc,decode:escapeCodepoint,expectedFor:e=>`&#x${codepointHex(e)};`},Uc={rule:`entity-in-js-string`,tokenRe:Lc,contexts:zc,decode:entityCodepoint,expectedFor:e=>e<=65535?`\\u${codepointHex(e)}`:`\\u{${codepointHex(e)}}`};function scanPlacement(e,t,n=[]){let r=w.extname(e).toLowerCase();if(!Bc.has(r)||!hasCandidateToken(t))return[];let i=classifyFile(e,t,n),a=Vc.has(r)?[Hc,Uc]:[Hc],o=[],s=t.split(`
|
|
6088
|
+
`),c=0;for(let t=0;t<s.length;t+=1){let n=s[t]??``;if(!hasIgnoreMarker(n)){let r={rel:e,spans:i,lineStart:c,lineIdx:t,line:n};for(let e of a)o.push(...matchesForRule(r,e))}c+=n.length+1}return o}const Wc=55296,Gc=56320;function detectSurrogatePair(e,t){let n=e[t],r=e[t+1];if(!r||(n.index??0)+n[0].length!==r.index)return;let i=escapeRawHex(n[0]);if(i<Wc||i>56319)return;let a=escapeRawHex(r[0]);if(!(a<Gc||a>57343))return{hiMatch:n,loMatch:r,hi:i,lo:a}}function matchesForRule(e,t){let n=[...e.line.matchAll(t.tokenRe)],r=[];for(let i=0;i<n.length;i+=1){let a=t.rule===`js-escape-in-markup`?detectSurrogatePair(n,i):void 0;if(a){let n=buildPairedSurrogateFinding(e,a,t);n&&r.push(n),i+=1;continue}let o=buildFinding(e,n[i],t);o&&r.push(o)}return r}function buildFinding(e,t,n){let r=t[0],i=t.index??e.line.indexOf(r),a=e.lineStart+i,o=contextAt(e.spans,a);if(!n.contexts.has(o)||contextAt(e.spans,a+r.length-1)!==o)return;let s=n.decode(r);if(s!==void 0)return finishFinding(e,{col:i,context:o,found:r,code:s},n)}function buildPairedSurrogateFinding(e,t,n){let r=t.hiMatch[0]+t.loMatch[0],i=t.hiMatch.index??e.line.indexOf(t.hiMatch[0]),a=e.lineStart+i,o=contextAt(e.spans,a);if(n.contexts.has(o)&&contextAt(e.spans,a+r.length-1)===o)return finishFinding(e,{col:i,context:o,found:r,code:(t.hi-Wc)*1024+(t.lo-Gc)+65536},n)}function finishFinding(e,t,n){let r=`U+${codepointHex(t.code)}`;return{path:e.rel,line:e.lineIdx+1,column:t.col+1,rule:n.rule,context:t.context,found:t.found,codepoint:r,expected:n.expectedFor(t.code),name:offenderNameByCodepoint(r)}}function unicodeEscape(e){let t=``;for(let n=0;n<e.char.length;n+=1){let r=e.char.charCodeAt(n).toString(16).toUpperCase().padStart(4,`0`);t+=`\\u${r}`}return t}function kotlinSplice(e){let t=e.char.length>1?`"`:`'`;return`\${${t}${unicodeEscape(e)}${t}}`}function xmlEntity(e){return`&#x${e.codepoint.slice(2)};`}function decideAction(e,t){switch(t){case`string`:case`template`:case`regex`:return{action:`escape`,replacement:unicodeEscape(e)};case`jsx-text`:case`jsx-attribute`:case`markup-text`:case`markup-attribute`:return{action:`escape`,replacement:xmlEntity(e)};case`prose`:case`comment`:case`xml-comment`:case`cdata`:return e.group===`invisible`?{action:`flag`,reason:`an invisible or deceptive character; removing it can change what the line means`}:e.replacement===void 0?{action:`flag`,reason:`no ASCII replacement is safe to pick unattended; edit it by hand`}:{action:`flatten`,replacement:e.replacement};case`raw-string`:return{action:`flag`,reason:`Kotlin raw strings do not process \\u escapes`,suggestion:kotlinSplice(e)};case`text-block`:return{action:`flag`,reason:`a Java text block; hand-edit required`};case`tagged-template`:return{action:`flag`,reason:`a tagged template's tag may read .raw, where an escape is not the same value`};case`code`:return e.group===`script`?{action:`flag`,reason:`a character some scripts need, in a code position; not this tool's job`}:{action:`flag`,reason:`non-ASCII character in a code position (e.g. an identifier); not this tool's job`};case`unclassified`:return{action:`flag`,reason:`this position was not classified with confidence; hand-edit required`};default:throw new D(`unhandled ascii context: ${String(t)}`)}}function isFixedNow(e,t,n){return t.action===`flag`?!1:e.tier===1||t.action===`escape`||n}function violatesXmlCommentInvariant(e){return e.includes(`--`)||e.endsWith(`-`)}function precedingBackslashRun(e,t){let n=0;for(let r=t-1;r>=0&&e[r]===`\\`;--r)n+=1;return n}function guardAgainstDoubleEscape(e,t,n){return n.action!==`escape`||n.replacement?.startsWith(`\\`)!==!0||precedingBackslashRun(e,t)%2==0?n:{action:`flag`,reason:`this character is already escaped by a preceding backslash; escaping it again would change the string's value`}}function toDecision(e){return{hit:e.hit,context:e.context,action:e.action,applied:e.applied,replacement:e.replacement,reason:e.reason,suggestion:e.suggestion}}function splice(e,t){let n=``,r=0;for(let i of t)i.applied&&i.replacement!==void 0&&(n+=e.slice(r,i.offset)+i.replacement,r=i.offset+i.hit.offender.char.length);return n+=e.slice(r),n}function verifyRewrite(e,t,n,r,i){let a=classifyFile(e,n,i);for(let e of r)if(e.applied&&contextAt(a,e.newOffset)!==e.context)return!1;let o=resolveFamily(e,i);return!(o?.verify&&!o.verify(t,n))}var XmlCommentGuard=class{committed=/* @__PURE__ */ new Map;poisonedComments=/* @__PURE__ */ new Set;check(e,t,n,r,i){if(r.action!==`flatten`||r.replacement===void 0)return r;let a=spanCovering(e,n);if(!a||a.context!==`xml-comment`)return r;let o=this.committed.get(a)??[],s=spliceWithin(t,a.start,a.end,o),c=String.fromCodePoint(t.codePointAt(n)??0).length,l=[...o,{offset:n,length:c,replacement:r.replacement}].toSorted((e,t)=>e.offset-t.offset);return violatesXmlCommentInvariant(spliceWithin(t,a.start,a.end,l))&&!violatesXmlCommentInvariant(s)?(this.poisonedComments.add(a),{action:`flag`,reason:`flattening would produce '--' or leave a trailing '-', which is illegal inside an XML comment`,suggestion:`-`}):(i&&this.committed.set(a,l),r)}};function spliceWithin(e,t,n,r){let i=``,a=t;for(let t of r)i+=e.slice(a,t.offset)+t.replacement,a=t.offset+t.length;return i+e.slice(a,n)}function fixText(e,t){let n=scanWithOffsets(t.path,e,t.offenders);if(n.length===0)return{text:e,changed:!1,decisions:[]};let r=t.fixAmbiguous===!0,i=t.treatAsProse??[],a=classifyFile(t.path,e,i),o=new XmlCommentGuard,s=[];for(let{offset:t,hit:i}of n){let n=contextAt(a,t);if(i.offender.group===`script`&&n!==`code`)continue;let c=decideAction(i.offender,n),l=isFixedNow(i.offender,c,r),u=guardAgainstDoubleEscape(e,t,o.check(a,e,t,c,l));s.push({offset:t,hit:i,context:n,span:spanCovering(a,t),decision:u})}let c=[],l=0;for(let e of s){let t=e.decision.action===`flatten`&&e.span&&o.poisonedComments.has(e.span)?{action:`flag`,reason:`another offender in this XML comment cannot flatten safely; flattening only some of the comment would leave it worse than untouched`,suggestion:`-`}:e.decision,n=isFixedNow(e.hit.offender,t,r),i=e.offset+l;n&&t.replacement!==void 0&&(l+=t.replacement.length-e.hit.offender.char.length),c.push({offset:e.offset,newOffset:i,hit:e.hit,context:e.context,action:t.action,applied:n,replacement:t.replacement,reason:t.reason,suggestion:t.suggestion})}if(!c.some(e=>e.applied))return{text:e,changed:!1,decisions:c.map(toDecision)};let u=splice(e,c);return verifyRewrite(t.path,e,u,c,i)?{text:u,changed:!0,decisions:c.map(toDecision)}:{text:e,changed:!1,decisions:c.map(e=>({hit:e.hit,context:e.context,action:`flag`,applied:!1,reason:`a rewrite of this file would not survive verification; hand-edit required`,suggestion:e.suggestion}))}}const Kc=new TextDecoder(`utf-8`,{fatal:!0});function isValidUtf8(e){try{return Kc.decode(e),!0}catch{return!1}}const qc={codepoint:`U+FFFD`,name:`REPLACEMENT CHARACTER (invalid UTF-8 byte)`,tier:1,char:`�`};function refuseLossyDecode(e){return{text:e.text,changed:!1,decisions:e.decisions.map(e=>({...e,action:`flag`,applied:!1,replacement:void 0,reason:`the file is not valid UTF-8, so no rewrite of it is safe; fix its encoding first`}))}}function fixFiles(e,t){let n=F(t.exclude??[]),r=[];for(let i of e.listTrackedFiles()){if((t.exclude??[]).length>0&&n(i)||e.isBinaryPath(i))continue;let a=e.readFileBuffer(i);if(!a||looksBinary(a))continue;let o=a.toString(`utf-8`),s=scanPlacement(i,o,t.treatAsProse),c=isValidUtf8(a),l=fixText(o,{offenders:c?t.offenders:[...t.offenders,qc],path:i,fixAmbiguous:t.fixAmbiguous,treatAsProse:t.treatAsProse}),{text:u,changed:d,decisions:f}=c?l:refuseLossyDecode(l);d&&t.dryRun!==!0&&e.writeFileBuffer(i,Buffer.from(u,`utf-8`));let p=f.filter(e=>!e.applied).map(e=>e.hit);r.push({path:i,changed:d,decisions:f,remainingHits:p,placement:s})}return r}function createRealFixExecutor(e){return{...createRealScanExecutor(e),writeFileBuffer(t,n){C(w.join(e,...t.split(`/`)),n)}}}const $=`.agent/findings`;function findingSlug(e){let t=e.toLowerCase().replaceAll(/[^a-z0-9]+/g,`-`).replaceAll(/^-+|-+$/g,``).slice(0,60).replaceAll(/-+$/g,``);return t===``?`finding`:t}const Jc=/^(\d{4}-\d{2}-\d{2})-(pr|issue)(\d+)-([a-z0-9-]+)\.md$/;function parseFindingFileName(e){let t=Jc.exec(e);if(!t)return null;let[,n,r,i,a]=t;return n===void 0||i===void 0||a===void 0||r!==`pr`&&r!==`issue`?null:{date:n,origin:{kind:r,number:Number(i)},slug:a}}function isManual(e){return e.phase===`manual`}function composeFindingFile(e,t){let n=t.sourceKind===`pr`?`PR`:`issue`,r=[`# ${toGateText(e.title)}`,``,`- Class: ${e.class}`,`- Phase: ${t.phase}`];return isManual(t)?r.push(`- Source ${n}: #${String(t.sourceIssueNumber)}`):r.push(`- Source ${n}: #${String(t.sourceIssueNumber)} (${t.sourceIssueUrl})`,`- Pull request: ${t.prUrl??`none -- the run produced no commits`}`,`- Transcript directory: ${t.transcriptDir}`),r.push(``,toGateText(e.body)),r.join(`
|
|
6085
6089
|
`)+`
|
|
6086
|
-
`}function toGateText(e){let t=fixText(e,{offenders:
|
|
6087
|
-
`),r=fencedLines(n),i=/* @__PURE__ */ new Map;for(let e of t)i.set(e.line,e);let a=[],o=[],s=n.map(()=>null),c=null,inEffect=()=>{let e=o[o.length-1];return e===void 0?c:e.index},walkHeading=(e,t)=>{let n=(e[1]??``).length;for(;o.length>0&&(o[o.length-1]?.level??0)>=n;)o.pop();c=null;let r=(e[2]??``).trim(),i=taskLabelId(r);if(i===null){s[t]=inEffect();return}let l={key:r,task:planTask(r,i),boxes:[]},u=a.length;a.push(l),o.push({level:n,unit:l,index:u}),s[t]=u};for(let[e,t]of n.entries()){let n=t??``;if(r[e]===!0){s[e]=inEffect();continue}let l=
|
|
6088
|
-
`),n=fencedLines(t),r=[];for(let e=0;e<t.length;e++){if(n[e]===!0)continue;let i=
|
|
6089
|
-
`),r=fencedLines(n),i=null;for(let e=0;e<n.length;e++){let a=n[e]??``;if(e===t)return taskLabelId(
|
|
6090
|
-
`))if(n.trim()!==``&&(t.push(n.trim()),t.length===5))break;return t.join(` / `)}function isAtOrAfter(e,t){let n=Date.parse(e),r=Date.parse(t);return Number.isNaN(n)?!1:Number.isNaN(r)?!0:n>=r}function feedbackSince(e,t,n,r){let i=null,a=0,isAgent=e=>hasAgentMarker(e.body)&&(r===void 0||e.author===r);for(let t of e)isAgent(t)&&(a+=1,t.on===`pr`&&Uc.some(e=>t.body.startsWith(e))&&(i===null||Date.parse(t.createdAt)>Date.parse(i))&&(i=t.createdAt));let o=i??t,s=i===null?`head-commit`:`agent-comment`,c=e.filter(e=>!isAgent(e)&&(e.on===`issue`||isAtOrAfter(e.createdAt,o))).toSorted((e,t)=>Date.parse(e.createdAt)-Date.parse(t.createdAt)),l=c.length>n;return{cutoff:o,cutoffSource:s,agentComments:a,comments:c.slice(0,n).map(e=>({on:e.on,author:e.author,createdAt:e.createdAt,url:e.url??null,excerpt:excerpt(e.body)})),truncated:l}}function ok(e){return{state:`ok`,...e}}function absent(e){return{state:`absent`,reason:e}}function unavailableWith(e){return{state:`unavailable`,reason:e}}function unavailable$1(e){return unavailableWith(reasonText(e))}async function section(e){try{return await e()}catch(e){return unavailable$1(e)}}function reasonText(e){let t=describeForgeError(e);return t===void 0?e instanceof Error?e.message:`the read failed`:t}function linkedIssueNumber(e){return closedIssueNumbers(e.body,repositoryOf(e.url))[0]??null}function repositoryOf(e){let t=e.indexOf(`://`);if(t<0)return null;let n=e.slice(t+3).split(`/`);if(n.length<3)return null;let r=n[1],i=n[2];return r===void 0||i===void 0||i===``?null:`${r}/${i}`}function prFacts(e){let t=e.pr;return{number:e.number,title:e.title,draft:t?.draft??!1,base:t?.base.ref??``,head:t?.head.sha??``,url:e.url}}function issueFacts(e){return{number:e.number,title:e.title,state:e.state,url:e.url}}async function resolveTarget$1(e,t,n,r,i){let a={kind:r===null?`branch`:`issue`,branch:null,head:null,base:null,pr:null,issue:null,gitAbsent:null,forgeDown:null,prFailed:null,otherOpenPrs:[],issueFailed:null,gitFailed:null,failed:null};if(r===null)await resolveBranch(a,e,t,n);else if(t instanceof Error)a.failed=reasonText(t);else try{await resolveRef(a,e,t,r,{defaultBranch:n,checkoutHead:i})}catch(e){a.failed=reasonText(e)}return a}async function resolveBranch(e,t,n,r){try{e.branch=await t.currentBranch(),e.head=await t.headSha(),e.base=await t.resolveBase(r)}catch(t){e.failed=reasonText(t);return}if(n instanceof Error){e.forgeDown=reasonText(n);return}let i=e.branch;if(i===null)return;try{let t=await n.openPrForBranch(i);if(t===null)return;e.pr=await n.view(t),e.kind=`pr`}catch(t){e.forgeDown=reasonText(t);return}await readLinkedIssue(e,n,e.pr);let a=e.pr?.pr?.base.ref;if(a!==void 0&&a!==``&&a!==r)try{e.base=await t.resolveBase(a)}catch(t){e.failed=reasonText(t)}}async function readLinkedIssue(e,t,n){let r=n===null?null:linkedIssueNumber(n);if(r!==null)try{e.issue=await t.view(r)}catch(t){e.issueFailed=reasonText(t)}}async function readCheckoutHead(e,t){try{e.head=await t.headSha(),e.branch=await t.currentBranch()}catch(t){e.gitFailed=reasonText(t)}}async function readHead(e,t,n,r){if(r)await readCheckoutHead(e,t);else try{e.head=await t.fetchPullHead(n)}catch(t){e.gitFailed=reasonText(t)}}async function resolveRef(e,t,n,r,{defaultBranch:i,checkoutHead:a}){if(r.number===void 0){e.failed=`the reference carries no issue or pull request number`;return}let o=await n.view(r.number);if(o.isPullRequest)e.pr=o,e.kind=`pr`,await readHead(e,t,o.number,a),await readLinkedIssue(e,n,o);else{e.issue=o,e.kind=`issue`;let r,i=[];try{i=await n.openPrsClosing(o.number),r=i[0]?.number,r!==void 0&&(e.pr=await n.view(r))}catch(t){e.prFailed=reasonText(t),e.gitFailed=e.prFailed;return}e.otherOpenPrs=i.slice(1),r===void 0?a?await readCheckoutHead(e,t):e.gitAbsent=`no open pull request closes this issue (issue #${String(o.number)})`:await readHead(e,t,r,a)}let s=e.pr?.pr?.base.ref;e.base=await t.resolveBase(s===void 0||s===``?i:s)}function sourcedComments(e,t){let n=[];for(let t of e?.comments??[])n.push({...t,on:`pr`});for(let e of t?.comments??[])n.push({...e,on:`issue`});return n}function labelNames(e){let t=/* @__PURE__ */ new Set;for(let n of e)if(n!==null)for(let e of n.labels)t.add(e);return[...t]}function gitState(e){return e.failed===null?e.gitFailed===null?e.gitAbsent===null?e.head===null||e.base===null?absent(`no head to read`):null:absent(e.gitAbsent):unavailableWith(e.gitFailed):unavailableWith(e.failed)}function objectSection({resolved:e,forgeDown:t}){if(t!==null)return unavailableWith(t);if(e.pr===null&&e.issue===null)return absent(`no pull request or issue for ${e.branch===null?`this checkout`:`branch ${e.branch}`}`);let n={pr:e.pr===null?null:prFacts(e.pr),issue:e.issue===null?null:issueFacts(e.issue)};return e.prFailed!==null&&(n.prUnavailable=e.prFailed),e.issueFailed!==null&&(n.issueUnavailable=e.issueFailed),e.otherOpenPrs.length>0&&(n.otherOpenPrs=e.otherOpenPrs),ok(n)}function liftedFactsOf(e,t){let n=labelNames([e.pr,e.issue]),r=liftedFacts(n),i=ownerOf(n),a=t===null&&e.prFailed===null&&e.issueFailed===null;return{runLive:a||r.runLive.length>0?r.runLive:null,heldByHand:a||r.heldByHand?r.heldByHand:null,heldBy:a||r.heldBy!==null?r.heldBy:null,owner:a||i.owner===`agent`?i.owner:null}}async function docsSection({git:e,docsExtraDirs:t,resolved:n}){let r=gitState(n);if(r!==null)return r;let i=n.base??``,a=n.head??``,o=[],s=[];for(let n of await e.changedPaths(i,a)){let r=classifyTrackedDoc(n,t);if(r===null)continue;if(r.kind===`spec`){o.push({path:n,retired:r.retired});continue}let i=await e.show(a,n);if(i===null)continue;let c=planStatus(i,n);s.push({path:n,status:{...c,total:c.checked+c.outstanding+c.declined+c.deferred}})}return ok({base:i,specs:o,plans:s})}async function labelsSection({forgeApi:e,resolved:t,forgeDown:n}){if(n!==null)return unavailableWith(n);if(t.pr===null&&t.issue===null)return absent(`no pull request or issue to carry labels`);let r=/* @__PURE__ */ new Map,i=null;try{r=(e===null?null:await e.labelDescriptions())??/* @__PURE__ */ new Map}catch(e){i=reasonText(e)}let a={pr:groupLabels(t.pr?.labels??[],r),issue:groupLabels(t.issue?.labels??[],r)};return i!==null&&(a.descriptionsUnavailable=i),ok(a)}async function feedbackSection({git:e,resolved:t,forgeDown:n,agentLogin:r}){if(n!==null)return unavailableWith(n);if(t.pr===null&&t.issue===null)return absent(`no pull request or issue thread to read`);let i=t.head===null?``:await e.commitDate(t.head);return ok(feedbackSince(sourcedComments(t.pr,t.issue),i,20,r))}async function findingsSection({git:e,resolved:t,forgeDown:n}){let r=gitState(t);if(r!==null)return r;if(t.pr===null&&t.issue===null)return n===null?absent(`no pull request or issue to match findings against`):unavailableWith(n);let i=t.head??``,a=t.pr?.number??null,o=t.issue?.number??null,s=[];for(let t of await e.listDir(i,Q)){let n=parseFindingFileName(t);if(n===null||!(n.origin.kind===`pr`&&n.origin.number===a||n.origin.kind===`issue`&&n.origin.number===o))continue;let r=await e.show(i,`${Q}/${t}`),c=r===null?null:parseFindingHeader(r);s.push({name:t,class:c?.class??null,title:c?.title??null})}return ok({entries:s})}async function commitsSection({git:e,resolved:t}){let n=gitState(t);if(n!==null)return n;let r=t.base??``,i=t.head??``,a=await e.commits(r,i,20);return ok({base:r,cap:20,truncated:a.truncated,entries:a.entries})}async function buildWorkStatus(e,t){let{git:n,forge:r,docsExtraDirs:i,defaultBranch:a,agentLogin:o,checkoutHead:s=!1}=e,c=await resolveTarget$1(n,r,a,t,s),l=c.failed??c.forgeDown,u={git:n,forgeApi:r instanceof Error?null:r,docsExtraDirs:i,resolved:c,forgeDown:l,...o===void 0?{}:{agentLogin:o}},d=liftedFactsOf(c,l);return{target:{kind:c.kind,branch:c.branch,head:c.head},runLive:d.runLive,heldByHand:d.heldByHand,heldBy:d.heldBy,owner:d.owner,object:await section(()=>objectSection(u)),docs:await section(()=>docsSection(u)),labels:await section(()=>labelsSection(u)),feedback:await section(()=>feedbackSection(u)),findings:await section(()=>findingsSection(u)),commits:await section(()=>commitsSection(u))}}const Gc=`Advice, not a gate: this is what the reads found, not a verdict.`;function short(e){return e.length<=10?e:e.slice(0,10)}function block(e,t,n){return t.state===`absent`?[`${e}: none -- ${t.reason}`]:t.state===`unavailable`?[`${e}: unavailable -- ${t.reason}`]:[`${e}:`,...n(t)]}function objectRows(e){let t=[];if(e.pr!==null&&t.push(` PR #${String(e.pr.number)} "${e.pr.title}"${e.pr.draft?` (draft)`:``} ${e.pr.base} -> ${short(e.pr.head)} ${e.pr.url}`),e.issue!==null&&t.push(` issue #${String(e.issue.number)} [${e.issue.state}] "${e.issue.title}" ${e.issue.url}`),e.otherOpenPrs!==void 0){let n=e.otherOpenPrs.map(e=>`#${String(e.number)}${e.title===null?``:` "${e.title}"`}`);t.push(` other open PRs closing this issue: ${n.join(`, `)}`)}return e.prUnavailable!==void 0&&t.push(` PR unavailable -- ${e.prUnavailable}`),e.issueUnavailable!==void 0&&t.push(` issue unavailable -- ${e.issueUnavailable}`),t}function docsRows(e){let t=[` base ${e.base}`];for(let n of e.specs)t.push(` spec ${n.path}${n.retired?` (retired)`:``}`);for(let n of e.plans)t.push(` plan ${n.path}: ${String(n.status.checked)} of ${String(n.status.total)} checked, ${String(n.status.outstanding)} outstanding${n.status.declined>0?`, ${String(n.status.declined)} declined`:``}`);return e.specs.length===0&&e.plans.length===0&&t.push(` no spec or plan changed on this branch`),t}function labelRows(e){let t=[];for(let[n,r]of[[`pull request`,e.pr],[`issue`,e.issue]])if(r.length!==0){t.push(` ${n}:`);for(let e of r)for(let n of e.labels){let r=n.description===null?``:` -- ${n.description}`;t.push(` ${n.name}${r} [${e.scope}]`)}}return e.descriptionsUnavailable!==void 0&&t.push(` descriptions unavailable -- ${e.descriptionsUnavailable}`),t}function nothingInFlight(e){let{object:t,docs:n,commits:r}=e;return t.state!==`absent`||n.state!==`ok`||r.state!==`ok`||n.specs.length>0||n.plans.length>0||r.entries.length>0||e.runLive===null||e.runLive.length>0||e.heldByHand!==!1?null:`nothing in flight: no pull request or issue, no spec or plan changed, no commits ahead of ${r.base}`}function heading({kind:e,branch:t,head:n}){let r=e===`branch`&&t!==null?[]:[e];return t!==null&&r.push(`branch ${t}`),n!==null&&r.push(`head ${short(n)}`),`work:status ${r.join(`, `)}`}function claimableNumber(e){return e.object.state===`ok`?e.target.kind===`issue`?e.object.issue?.number??null:e.object.pr?.number??e.object.issue?.number??null:null}function renderWorkStatus(e,t){let n=nothingInFlight(e);if(n!==null)return[heading(e.target),n].join(`
|
|
6091
|
-
`);let r=[heading(e.target)];for(let t of e.runLive??[])r.push(`RUN LIVE: ${t} -- a run is working this object; do not start another.`);if((e.runLive===null||e.heldByHand===null)&&r.push(`UNKNOWN: whether a run is live or a human holds this -- not every label could be read.`),e.heldBy!==null&&r.push(`HELD BY HAND: ${e.heldBy} -- a human claimed this one; do not drive it.`),t?.agentEnabled===!0&&e.owner===`unclaimed`){let t=claimableNumber(e);t!==null&&r.push(`UNCLAIMED: no agent label and no hand claim -- run \`pnpm exec bst work:start ${String(t)}\` before you work this.`)}return r.push(...block(`object`,e.object,objectRows)),r.push(...block(`docs`,e.docs,docsRows)),r.push(...block(`labels`,e.labels,labelRows)),r.push(...block(`feedback`,e.feedback,e=>{let t=e.cutoffSource===`agent-comment`?`last agent comment`:`head commit`,n=[` since ${e.cutoff} (the ${t}), ${String(e.agentComments)} agent comment(s) held back`];for(let t of e.comments)n.push(` ${t.on} ${t.author} ${t.createdAt}: ${t.excerpt}`);return e.comments.length===0&&n.push(` nothing new from a human`),e.truncated&&n.push(` (more -- the cap is reached)`),n})),r.push(...block(`findings`,e.findings,e=>{let t=[];for(let n of e.entries){let e=n.class===null?``:` [${n.class}]`;t.push(` ${n.name}${e} ${n.title??``}`.trimEnd())}return t.length===0&&t.push(` none filed against this object`),t})),r.push(...block(`commits`,e.commits,e=>{let t=e.truncated?` (cap ${String(e.cap)} reached)`:``,n=[` ${String(e.entries.length)} since ${e.base}${t}`];for(let t of e.entries)n.push(` ${short(t.sha)} ${t.subject}`);return n})),r.push(e.feedback.state===`ok`?`${
|
|
6092
|
-
`)}function claimLine(e){return e.outcome===`claimed`?`claim: claimed -- ${e.label??`agent-flags/human-driven`} is on this object.`:e.outcome===`already-claimed`?`claim: already-claimed -- the flag is already on it; nothing was written.`:e.outcome===`not-agent-repo`?`claim: not-agent-repo -- ${e.reason??`nothing was claimed.`}`:`claim: ${e.outcome} -- ${e.reason??`nothing was claimed.`}`}function claimFailed(e){return e.outcome===`refused`||e.outcome===`failed`}const Kc=A({meta:{name:`work:start`,description:`Claim an issue or pull request for hand work: put agent-flags/human-driven on it so the agent leaves it alone`},args:{ref:{type:`positional`,required:!0,description:`Issue or pull request number or URL to claim`},json:{type:`boolean`,description:`Emit one JSON document: the whole work:status report plus a claim member {outcome, label?, reason?}. The report's object section carries otherOpenPrs ([{number, title}], newest first, title null when the forge has none), the other open pull requests whose bodies close the issue, absent when there are none. outcome is claimed (the flag was written), already-claimed (it was already on the object, nothing written), not-agent-repo (the default branch does not set agent.enabled, nothing written), refused (a live run or a queued agent trigger holds it; exit 1), or failed (a read or write could not be done; exit 1). refused and failed carry ok: false and an error member of kind runtime, and the report survives beside them.`},verbose:{type:`boolean`,description:`Emit detailed debug logging`}},async run({args:e}){let{ref:t,executor:n,git:r,forge:i}=await prepareWorkStatus(typeof e.ref==`string`?e.ref.trim():``,process.cwd()),a=t?.number;if(a===void 0)throw new T(`Usage: pnpm exec bst work:start needs an issue or pull request number or URL`);let o=resolveDocsConfig(r.topLevel),s=resolveDefaultBranch({cwd:r.topLevel}),c=await buildWorkStatus({git:r,forge:i,docsExtraDirs:o.extraDirs,defaultBranch:s},t),l=await readAgentConsent(r,s),u=decideClaim(c,l.enabled),d,f;u.kind===`write`?(d=await writeClaim(n,r.topLevel,t?.target,a),f=+!!claimFailed(d)):(d=u.result,f=u.exitCode);let p=createCliOutput(e.json===!0),m=claimFailed(d);p.json({ok:!m,...c,claim:d,...m?{error:{kind:`runtime`,message:d.reason??d.outcome}}:{}}),p.text(renderWorkStatus(c,{agentEnabled:l.enabled})),p.text(claimLine(d)),f!==0&&(process.exitCode=f)}}),qc=A({meta:{name:`work:status`,description:`Orient a session on a branch, issue or pull request: PR, issue, plan progress, labels, new feedback, findings`},args:{ref:{type:`positional`,required:!1,description:`Issue or pull request number or URL; default: the current branch`},json:{type:`boolean`,description:`Emit one JSON document: target, runLive, heldByHand, heldBy (the hold label the report found, null when none or unread), owner (agent, person or unclaimed; each null when not every label could be read), and six sections (object, docs, labels, feedback, findings, commits), each {state: ok} with its fields, {state: absent, reason} or {state: unavailable, reason}. The object section also carries otherOpenPrs ([{number, title}], newest first, title null when the forge has none), the other open pull requests whose bodies close the issue, absent when there are none. The output is advice, not a gate: the feedback cutoff is the newest agent run or review comment on the pull request and is approximate, and review comments on diff lines are not in the thread this reads.`},verbose:{type:`boolean`,description:`Emit detailed debug logging`}},async run({args:e}){let{ref:t,git:n,forge:r}=await prepareWorkStatus(typeof e.ref==`string`?e.ref.trim():``,process.cwd()),i=resolveDocsConfig(n.topLevel),a=resolveDefaultBranch({cwd:n.topLevel}),o=await buildWorkStatus({git:n,forge:r,docsExtraDirs:i.extraDirs,defaultBranch:a},t),s=await readAgentConsent(n,a),c=createCliOutput(e.json===!0);c.json({ok:!0,...o}),c.text(renderWorkStatus(o,{agentEnabled:s.enabled}))}});function collectInputArgs(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r!==void 0){if(r===`--`)break;if(r===`--input`){let r=e[n+1];if(r===void 0)throw new T("Missing value for --input: expected `--input key=value`");t.push(r),n+=1}else r.startsWith(`--input=`)&&t.push(r.slice(8))}}return t}function parseInputs(e){let t={};for(let n of e){let e=n.indexOf(`=`);if(e<=0)throw new T(`Invalid --input "${n}": expected key=value`);t[n.slice(0,e)]=n.slice(e+1)}return t}const Jc=A({meta:{name:`workflow:dispatch`,description:`Trigger a workflow_dispatch event for a workflow in any repo on the same git host. The resolved token must have rights on --repo when it differs from the current repo.`},args:{repo:{type:`string`,description:`Target repository as owner/repo (default: the current repo)`,required:!1},workflow:{type:`string`,description:`Workflow filename (e.g. deploy.yml) or numeric ID`,required:!0},ref:{type:`string`,description:`Git ref to dispatch on (default: main)`,required:!1},input:{type:`string`,description:`Workflow input as key=value (repeatable)`,required:!1},json:{type:`boolean`,description:`Emit one JSON document: status (dispatched), host (forgejo | github), repo (owner/repo, or null), workflow, ref, inputs. status is always dispatched; repo is null when GitHub cannot name it.`}},async run({args:e,rawArgs:t}){let n=createCliOutput(e.json===!0);if(!e.workflow)throw new T(`--workflow is required`);let r=e.ref??`main`,i=parseInputs(collectInputArgs(t)),a=await dispatchWorkflow(resolveConnection(process.cwd()),{repo:e.repo,workflow:e.workflow,ref:r,inputs:i},createRealExecutor$1());n.json({status:`dispatched`,...a})}});async function mergePr(e,t,n,r){let i=`${t.serverUrl}/api/v1/repos/${t.repository}/pulls/${String(n)}/merge`,a={Do:r?.method??`merge`,delete_branch_after_merge:r?.deleteBranch??!0};r?.expectedHeadSha!==void 0&&(a.head_commit_id=r.expectedHeadSha);let o=await e.fetch(i,{method:`POST`,headers:{Authorization:`token ${t.token}`,"Content-Type":`application/json`},body:JSON.stringify(a)});o.ok||await throwForgejoFailure(o,{verb:`merge PR`,resource:`#${String(n)}`})}const Yc=N.object({state:N.string(),draft:N.boolean(),mergeable:N.boolean().nullable(),head:N.object({sha:N.string()}),merge_base:N.string(),changed_files:N.number().nullish(),base:N.object({ref:N.string()}),labels:N.array(N.object({name:N.string()})).nullable(),updated_at:N.string().nullish()});async function readMergeGate(e,t,n){let r=`${t.serverUrl}/api/v1/repos/${t.repository}/pulls/${String(n)}`,i=await e.fetch(r,{headers:{Authorization:`token ${t.token}`}});i.ok||await throwForgejoFailure(i,{verb:`read PR merge gate`,resource:`#${String(n)}`});let a=Yc.safeParse(await i.json());if(!a.success)throw new D(`Unexpected PR merge-gate response: ${a.error.message}`);return{open:a.data.state===`open`,draft:a.data.draft,mergeable:a.data.mergeable??!1,headSha:a.data.head.sha,mergeBase:a.data.merge_base,changedFiles:a.data.changed_files??null,baseRef:a.data.base.ref,labels:(a.data.labels??[]).map(e=>e.name),updatedAt:a.data.updated_at??null}}async function confirmMergeable(e,t,n,r){let i=await readMergeGate(e,t,n);if(i.mergeable)return{verdict:`mergeable`,gate:i,firstGate:i,rechecked:!1,evidence:null};if(r.settleOnFirstRead?.(i)===!0)return{verdict:`unconfirmed`,gate:i,firstGate:i,rechecked:!1,evidence:null};r.beforeRecheck?.(i),await r.sleep(r.delayMs);let a=await readMergeGate(e,t,n);return a.mergeable?{verdict:`mergeable`,gate:a,firstGate:i,rechecked:!0,evidence:null}:a.headSha===i.headSha&&a.mergeBase===i.mergeBase?{verdict:`conflicted`,gate:a,firstGate:i,rechecked:!0,evidence:`The forge reported it unmergeable on two reads ${String(r.delayMs)}ms apart, at head ${a.headSha}.`}:{verdict:`unconfirmed`,gate:a,firstGate:i,rechecked:!0,evidence:a.headSha===i.headSha?`Its merge base moved from ${i.mergeBase} to ${a.mergeBase} between the two reads.`:`Its head moved from ${i.headSha} to ${a.headSha} between the two reads.`}}N.object({draft:N.boolean(),mergeable:N.boolean().nullable(),merge_base:N.string(),base:N.object({ref:N.string(),sha:N.string()})});function envMsOverride(e,t){if(e===void 0)return t;let n=Number(e.trim());return!Number.isSafeInteger(n)||n<=0?t:Math.min(n,t)}function evaluateVersionPr(e){let t=`PR #${String(e.prNumber)}`;return e.open?e.draft?{ok:!1,retryable:!1,reason:`${t} is a draft.`}:e.emptiness===`empty`?{ok:!1,retryable:!1,reason:`${t}'s diff against base is empty -- refusing to merge it and leaving its branch alone.`}:e.mergeable===`unconfirmed`?{ok:!1,retryable:!0,recheck:!0,reason:withEvidence(`${t}'s mergeability is still being computed -- re-run once the forge finishes checking.`,e.mergeabilityEvidence)}:e.mergeable===`conflicted`?{ok:!1,retryable:!1,reason:withEvidence(`${t} is not mergeable.`,e.mergeabilityEvidence)}:{ok:!0,headSha:e.headSha}:{ok:!1,retryable:!1,reason:`${t} is not open.`}}function withEvidence(e,t){return t===void 0?e:`${e} ${t}`}function needsRecheck(e){return!e.ok&&`recheck`in e}function emptinessFromGate(e){return e.headSha===e.mergeBase||e.changedFiles===0?`empty`:`non-empty`}function headShaOrThrow(e){if(e.ok)return e.headSha;throw e.retryable?new E(e.reason):new T(e.reason)}function stateFromGate(e,t,n,r){return{prNumber:e,open:t.open,draft:t.draft,mergeable:n,headSha:t.headSha,emptiness:emptinessFromGate(t),mergeabilityEvidence:r}}function logGateRead(e,t){F.info(`changesets:merge: PR #${String(e)} at ${t.headSha} (${t.changedFiles===null?`changed-files unknown`:`${String(t.changedFiles)} changed files`})`)}const Xc={ok:!0,retryable:null,reason:null};async function mergeVersionPrForgejo(e,t,n){let r=versionPrBranch(n.defaultBranch),i=await findOpenPr(e,t,r);if(i===null)throw new T(`No open PR found for branch ${r}`);let a=n.sleep??sleep,o=envMsOverride(process.env.BST_TEST_VERSION_MERGE_RECHECK_MS,2e3),s=await confirmMergeable(e,t,i,{delayMs:o,sleep:a,settleOnFirstRead:e=>!needsRecheck(evaluateVersionPr(stateFromGate(i,e,`unconfirmed`))),beforeRecheck:e=>{logGateRead(i,e),F.info(`changesets:merge: PR #${String(i)}'s mergeability is not confirmed yet -- re-reading after ${String(o)}ms`)}}),{gate:c,rechecked:l}=s;logGateRead(i,c);let u=headShaOrThrow(evaluateVersionPr(stateFromGate(i,c,s.verdict,s.evidence??void 0))),d={host:`forgejo`,number:i,headSha:u,mergeBase:c.mergeBase,changedFiles:c.changedFiles,branch:r,rechecked:l,verdict:{...Xc}};return n.dryRun?(F.info(`[dry-run] Would merge PR #${String(i)} at ${u} and delete branch ${r}`),{...d,status:`would-merge`}):(await mergePr(e,t,i,{method:`merge`,deleteBranch:!0,expectedHeadSha:u}),F.info(`Merged PR #${String(i)} and deleted branch ${r}`),{...d,status:`merged`})}const Zc=N.object({number:N.number(),state:N.string(),isDraft:N.boolean(),mergeable:N.string(),headRefOid:N.string(),changedFiles:N.number()});function mergeVersionPrGitHub(e,t){let n=versionPrBranch(t.defaultBranch),r=e.exec(`gh`,[`pr`,`view`,n,`--json`,`number,state,isDraft,mergeable,headRefOid,changedFiles`],{cwd:process.cwd()});if(r.exitCode!==0)throw new T(`Failed to read PR for branch ${n}: ${r.stderr||r.stdout||`unknown error`}`);let i=Zc.safeParse(JSON.parse(r.stdout));if(!i.success)throw new T(`Unexpected 'gh pr view' response for branch ${n}: ${i.error.message}`);let a=i.data,o=a.changedFiles===0?`empty`:`non-empty`,s=a.mergeable===`CONFLICTING`?`conflicted`:`mergeable`;F.info(`changesets:merge: PR #${String(a.number)} at ${a.headRefOid} (${String(a.changedFiles)} changed files)`);let c=headShaOrThrow(evaluateVersionPr({prNumber:a.number,open:a.state===`OPEN`,draft:a.isDraft,mergeable:s,headSha:a.headRefOid,emptiness:o})),l={host:`github`,number:a.number,headSha:c,mergeBase:null,changedFiles:a.changedFiles,branch:n,rechecked:!1,verdict:{...Xc}};if(t.dryRun)return F.info(`[dry-run] Would merge PR #${String(a.number)} at ${c} and delete branch ${n}`),{...l,status:`would-merge`};let u=e.exec(`gh`,[`pr`,`merge`,n,`--merge`,`--delete-branch`,`--match-head-commit`,c],{cwd:process.cwd()});if(u.exitCode!==0)throw new T(`Failed to merge PR: ${u.stderr||u.stdout||`unknown error`}`);return F.info(`Merged changesets PR and deleted branch ${n}`),{...l,status:`merged`}}const Qc=A({meta:{name:`changesets:merge`,description:`Merge the open changesets version PR. Reads the PR live, refuses a draft or an empty diff with no override, and pins the merge to the head commit it read.`},args:{"dry-run":{type:`boolean`,description:`Show what would be merged without actually merging`},json:{type:`boolean`,description:`Emit one JSON document: status (merged | would-merge), host (forgejo | github), number, headSha, mergeBase (or null), changedFiles (or null), branch, rechecked, verdict ({ok, retryable, reason}). would-merge is a dry run's status; mergeBase is null on GitHub, changedFiles is null when the forge gave no count, and rechecked is true when Forgejo's confirming re-read ran. Every refusal is an error, so a result always has verdict.ok true.`}},async run({args:e}){let t=createCliOutput(e.json===!0),n=e[`dry-run`]===!0,r=resolveConnection(process.cwd()),i=createRealExecutor$1(),a=readConfiguredDefaultBranch(process.cwd()),o=r.type===`forgejo`?await mergeVersionPrForgejo(i,r.conn,{dryRun:n,defaultBranch:a}):mergeVersionPrGitHub(i,{dryRun:n,defaultBranch:a});t.json(o)}}),$c=/* @__PURE__ */ new Set([`main`,`master`]);function stateWord(e){return e===`open`?`open`:`closed, unmerged`}async function refuseProtectedBranch(e,t,n){let{cwd:r,branch:i}=t,a=t.defaultBranchOverride,o=pickDefaultBranch(a,a===void 0||a===``?await resolveOriginHead(e,r,t.signal):void 0);if($c.has(i)||i===o)throw new T(n(i));return o}var BranchPrError=class extends T{reason;branch;state;numbers;openNumbers;constructor(e){let t=e.openNumbers??[];super(branchPrMessage(e,t)),this.reason=e.reason,this.branch=e.branch,this.state=e.state,this.numbers=e.numbers,this.openNumbers=t}};function branchPrMessage(e,t){let n=e.numbers.map(e=>`#${String(e)}`).join(`, `);if(e.reason===`several`)return`${e.branch} has ${String(e.numbers.length)} ${stateWord(e.state)} pull requests (${n}), so there is no way to tell which one you mean. Pass the pull request NUMBER.`;if(t.length===1)return`${e.branch} has no ${stateWord(e.state)} pull request; #${String(t[0])} is already open. Pass the pull request NUMBER.`;if(t.length>1){let n=t.map(e=>`#${String(e)}`).join(`, `);return`${e.branch} has no ${stateWord(e.state)} pull request; it has open pull requests (${n}). Pass the pull request NUMBER.`}return`${e.branch} has no ${stateWord(e.state)} pull request. Pass the pull request NUMBER.`}async function resolveBranchPr$1(e,t,n){let r=await currentBranch(e,n.cwd,n.signal);await refuseProtectedBranch(e,{cwd:n.cwd,branch:r,...n.defaultBranchOverride===void 0?{}:{defaultBranchOverride:n.defaultBranchOverride},signal:n.signal},e=>`Autodetect will not run on the protected branch "${e}" -- pass the pull request NUMBER.`);let i=await listBranchNumbers(t,r,n.state,n.signal),a=i[0];if(i.length===1&&a!==void 0)return{branch:r,number:a};if(i.length>1)throw new BranchPrError({reason:`several`,branch:r,state:n.state,numbers:i});let o=n.state===`closed-unmerged`?await listBranchNumbers(t,r,`open`,n.signal):[];throw new BranchPrError({reason:`none`,branch:r,state:n.state,numbers:[],openNumbers:o})}async function listBranchNumbers(e,t,n,r){return n===`open`?(await e.listForBranch(t,`open`,r)).map(e=>e.number):(await e.listForBranch(t,`closed`,r)).filter(e=>!e.merged).map(e=>e.number)}function refuseRepoWithoutNumber(e,t){if(t!==void 0&&e===void 0)throw new T(`--repo names ${t}, and the current branch says nothing about another repository -- pass the pull request NUMBER.`)}const el=/* @__PURE__ */ new Set([`feat`,`fix`,`chore`,`docs`,`refactor`,`test`,`perf`,`build`,`ci`,`style`,`revert`]);function words(e){return e.replaceAll(`-`,` `).replaceAll(`_`,` `)}function humanizeBranch(e){let t=e.indexOf(`/`);if(t===-1)return words(e);let n=e.slice(0,t),r=e.slice(t+1);return el.has(n)?`${n}: ${words(r)}`:`${words(n)} ${words(r.replaceAll(`/`,` `))}`}function withWipPrefix(e,t){return t&&!hasWipPrefix(e)?`WIP: ${e}`:e}function derivePrContent(e){let[t]=e.subjects,n=e.subjects.length===1&&t!==void 0?t:humanizeBranch(e.branch),r=e.title??n,i=e.wipTitles?withWipPrefix(r,e.draft):r;if(e.body!==void 0)return{title:i,body:e.body,droppedRefs:droppedClosingRefs(e.messages,e.body)};let a=e.subjects.map(e=>`- ${e}`).join(`
|
|
6090
|
+
`}function toGateText(e){let t=fixText(e,{offenders:yc,path:`finding.md`,fixAmbiguous:!0}).text;return nameInvisibleCharacters(t)}function nameInvisibleCharacters(e){let t=new Map(yc.filter(e=>e.group===`invisible`).map(e=>[e.char,e.codepoint])),n=``;for(let r of Array.from(e))n+=t.get(r)??r;return n}const Yc=/^#\s+(.+)$/m,Xc=/^-\s*Class:\s*(.+)$/m,Zc=/^-\s*Phase:\s*(.+)$/m;function parseFindingHeader(e){return{title:Yc.exec(e)?.[1]?.trim()??null,class:Xc.exec(e)?.[1]?.trim()??null,phase:Zc.exec(e)?.[1]?.trim()??null}}function countDeferralNotes(e){return e.split(/\r?\n/).filter(e=>e.startsWith(`**Deferred`)).length}const Qc=/^(#{1,6})[ \t]+(.*)$/,$c=/^([ \t]*)[-*] \[[ xX]\][ \t]*(.*)$/,el=/^Task[ \t]+([0-9]+)([a-z]?)(?![0-9A-Za-z])/,tl=/^[ \t]*(`{3,}|~{3,})/,nl=/^[ \t]*(`{3,}|~{3,})[ \t]*$/;function closesFence(e,t,n){let r=nl.exec(e)?.[1];return r!==void 0&&r[0]===t&&r.length>=n}function fencedLines(e){let t=e.map(()=>!1),n,r=0;for(let i=0;i<e.length;i++){let a=e[i]??``;if(n===void 0){let e=tl.exec(a),o=e?.[1];if(e===null||o===void 0)continue;let s=a.slice(e[0].length);if(o[0]==="`"&&s.includes("`"))continue;n=o[0],r=o.length,t[i]=!0}else t[i]=!0,closesFence(a,n,r)&&(n=void 0,r=0)}return t}function taskLabelId(e){let t=el.exec(e.replace(/^(\*\*|__)/,``)),n=t?.[1];return n===void 0||String(Number(n))!==n?null:`${n}${t?.[2]??``}`}const rl=/^[ \t]*(?::|\.|--?)?[ \t]*/;function planTask(e,t){let n=e.replace(/^(\*\*|__)/,``).replace(/(\*\*|__)$/,``);return{label:t,title:n.slice(n.indexOf(t)+t.length).replace(rl,``).trim()}}function walkUnits(e,t){let n=e.split(`
|
|
6091
|
+
`),r=fencedLines(n),i=/* @__PURE__ */ new Map;for(let e of t)i.set(e.line,e);let a=[],o=[],s=n.map(()=>null),c=null,inEffect=()=>{let e=o[o.length-1];return e===void 0?c:e.index},walkHeading=(e,t)=>{let n=(e[1]??``).length;for(;o.length>0&&(o[o.length-1]?.level??0)>=n;)o.pop();c=null;let r=(e[2]??``).trim(),i=taskLabelId(r);if(i===null){s[t]=inEffect();return}let l={key:r,task:planTask(r,i),boxes:[]},u=a.length;a.push(l),o.push({level:n,unit:l,index:u}),s[t]=u};for(let[e,t]of n.entries()){let n=t??``;if(r[e]===!0){s[e]=inEffect();continue}let l=Qc.exec(n);if(l!==null){walkHeading(l,e);continue}let u=i.get(e);if(u===void 0){s[e]=inEffect();continue}let d=o[o.length-1];if(d!==void 0){d.unit.boxes.push(u),s[e]=d.index;continue}let f=a.length;a.push({key:u.title,task:null,boxes:[u]}),s[e]=f,c=f}return{units:a,unitAtLine:s}}function groupPlanUnits(e,t){return walkUnits(e,t).units}const il=/^[ \t]*[-*] \[([ xX])\][ \t]*(.*)$/,al=/^#{1,6} /,ol=/^[ \t]*(?:[-*][ \t]+)?\*\*Declined:\*\*[ \t]*(.*)$/,sl=/^[ \t]*(?:[-*][ \t]+)?\*\*(Progress|Blocked|Declined|Deferred):\*\*[ \t]*(.*)$/,cl=/^[ \t]*(?:[-*][ \t]+)?\*\*Deferred:\*\*[ \t]*(.*)$/,ll=/^[ \t]*(?::|\.|--|-)?[ \t]*/,ul=/^(?:\*\*|__)?Retire this plan(?![A-Za-z0-9])/;function describeDeferralCheck(e){switch(e){case`empty-reason`:return`the note names no reason`;case`no-target-label`:return`the note names no target task`;case`no-own-task`:return`the box names no task of its own`;case`target-not-found`:return`no task in the plan carries that label`;case`target-not-later`:return`the target task does not come later in the plan`;case`target-is-retire`:return`the target is the retire task`;case`no-carried-box`:return`the target task holds no box carried from this one`}}function isOutstanding(e,t){return e.checked||e.declined||e.deferred?!1:!(e.retireTask&&t?.planRetired===!0)}function noteKind(e){return e===`Progress`?`progress`:e===`Blocked`?`blocked`:e===`Deferred`?`deferred`:`declined`}const dl=/^[ \t]*(?:[-*+][ \t]|[0-9]+[.)][ \t]|\*\*(?:Progress|Blocked|Declined|Deferred):\*\*|<!--)/,fl=/(?:^|[^A-Za-z])(?:e\.g|i\.e|etc|vs|cf)$/i;function boxParagraph(e,t,n,r,i){let a=[i];for(let i=n+1;i<r;i++){let n=e[i]??``;if(t[i]===!0||n.trim()===``||al.test(n)||dl.test(n))break;a.push(n.trim())}return a.join(` `).trim()}function firstSentence$1(e){let t=!1;for(let n=0;n<e.length;n++){let r=e[n];if(r==="`"&&(t=!t),t||r!==`.`&&r!==`!`&&r!==`?`)continue;let i=n+1;for(;i<e.length&&/[*_)"']/.test(e[i]??``);)i++;if(!(i<e.length&&!/\s/.test(e[i]??``))&&!(r===`.`&&fl.test(e.slice(0,n))))return e.slice(0,i)}return e}function stripStrong(e){return e.split(/(`[^`]*`)/).map(e=>e.startsWith("`")?e:e.replaceAll(`**`,``)).join(``).trim()}function unwrapEmphasis(e){let t=/^(\*\*|__)/.exec(e)?.[1];return t===void 0||!e.endsWith(t)?e:e.slice(t.length,-t.length).trim()}function deferredLineOf(e,t,n,r){for(let i=n+1;i<r;i++){if(t[i]===!0)continue;let n=cl.exec(e[i]??``);if(n!==null)return boxParagraph(e,t,i,r,(n[1]??``).trim())}return null}function readDeferralNote(e){if(e===``)return{target:null,reason:``,failed:`empty-reason`};let t=taskLabelId(e);if(t===null)return{target:null,reason:``,failed:`no-target-label`};let n=e.slice(e.indexOf(t)+t.length).replace(ll,``).trim();return n===``?{target:t,reason:``,failed:`empty-reason`}:{target:t,reason:n,failed:null}}function ownTaskLabel(e,t){let n=t.find(t=>t.boxes.some(t=>t.line===e.line)),r=n?.task?.label??null;return r===null?n?.task===void 0?null:taskLabelId(e.title):r}function holdsCarriedBox(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),r=RegExp(`^Carried from Task ${n}(?![0-9A-Za-z]):`);return e.boxes.some(e=>r.test(e.title))}function resolveDeferrals(e,t){for(let{box:n,deferredLine:r}of e){if(r===null||n.checked||n.declined)continue;let e=readDeferralNote(r);if(n.deferral=e,e.failed!==null||e.target===null)continue;let i=t.findIndex(e=>e.boxes.some(e=>e.line===n.line)),a=ownTaskLabel(n,t);if(a===null){n.deferral={...e,failed:`no-own-task`};continue}let o=t.flatMap((t,n)=>t.task?.label===e.target?[n]:[]);if(o.length!==1){n.deferral={...e,failed:`target-not-found`};continue}let s=o[0]??-1;if(s<=i){n.deferral={...e,failed:`target-not-later`};continue}let c=t[s];c!==void 0&&(c.boxes.some(e=>e.retireTask)||c.task!==null&&ul.test(c.task.title)?n.deferral={...e,failed:`target-is-retire`}:holdsCarriedBox(c,a)?n.deferred=!0:n.deferral={...e,failed:`no-carried-box`})}}function parsePlanBoxes(e){let t=e.split(`
|
|
6092
|
+
`),n=fencedLines(t),r=[];for(let e=0;e<t.length;e++){if(n[e]===!0)continue;let i=il.exec(t[e]??``);i!==null&&r.push({index:e,checked:(i[1]??``).toLowerCase()===`x`,rawTitle:(i[2]??``).trim()})}let i=r.map((e,i)=>{let a=r[i+1]?.index??t.length,o=a;for(let r=e.index+1;r<a;r++)if(n[r]!==!0&&al.test(t[r]??``)){o=r;break}let s=stripStrong(unwrapEmphasis(firstSentence$1(boxParagraph(t,n,e.index,o,e.rawTitle)))),c=ul.test(s);if(e.checked)return{box:{line:e.index,checked:!0,declined:!1,reason:null,title:s,retireTask:c,notes:[],deferred:!1,deferral:null},deferredLine:null};let l=[];for(let r=e.index+1;r<o;r++){if(n[r]===!0)continue;let e=sl.exec(t[r]??``);if(e===null)continue;let i=boxParagraph(t,n,r,o,(e[2]??``).trim());i!==``&&l.push({kind:noteKind(e[1]??``),text:i})}let u=null;for(let r=e.index+1;r<o;r++){if(n[r]===!0)continue;let e=ol.exec(t[r]??``);if(e===null)continue;let i=boxParagraph(t,n,r,o,(e[1]??``).trim());if(i!==``){u=i;break}}return{box:{line:e.index,checked:!1,declined:u!==null,reason:u,title:s,retireTask:c,notes:l,deferred:!1,deferral:null},deferredLine:deferredLineOf(t,n,e.index,o)}});return i.some(e=>e.deferredLine!==null)&&resolveDeferrals(i,groupPlanUnits(e,i.map(e=>e.box))),i.map(e=>e.box)}function countOutstandingBoxes(e,t){return parsePlanBoxes(e).filter(e=>isOutstanding(e,t)).length}const pl=/(^|\/)retired\//;function enclosingTaskLabel(e,t){let n=e.split(`
|
|
6093
|
+
`),r=fencedLines(n),i=null;for(let e=0;e<n.length;e++){let a=n[e]??``;if(e===t)return taskLabelId($c.exec(a)?.[2]??``)??i;if(r[e]===!0)continue;let o=$c.exec(a)?.[2]??Qc.exec(a)?.[2],s=o===void 0?null:taskLabelId(o);s!==null&&(i=s)}return null}function planStatus(e,t){let n=pl.test(t.split(`\\`).join(`/`)),r=parsePlanBoxes(e),i=r.filter(e=>isOutstanding(e,{planRetired:n})),a=r.flatMap(e=>e.notes.map(t=>({task:e.title,kind:t.kind,text:t.text}))),o=r.flatMap(e=>e.deferral===null?[]:[{task:e.title,target:e.deferral.target,failed:e.deferral.failed}]),s=i[0];return{plan:t,retired:n,checked:r.filter(e=>e.checked).length,outstanding:i.length,declined:r.filter(e=>e.declined).length,deferred:r.filter(e=>e.deferred).length,deferrals:o,next:s===void 0||s.title===``?null:s.title,nextTask:s===void 0?null:enclosingTaskLabel(e,s.line),onlyRetireLeft:i.length>0&&i.every(e=>e.retireTask),notes:a}}const ml=`**agent:run**`,hl=`**agent:review**`,gl=[ml,hl],_l=[ml,hl,`**bst agent**`,`**agent daemon**`,`**agent:fix**`,`**agent:gate**`,`**agent:follow-ups**`,`**agent:analyze**`,`**agent:handoff**`,`**agent:status**`];function hasAgentMarker(e){return _l.some(t=>e.startsWith(t))}function excerpt(e){let t=[];for(let n of e.split(`
|
|
6094
|
+
`))if(n.trim()!==``&&(t.push(n.trim()),t.length===5))break;return t.join(` / `)}function isAtOrAfter(e,t){let n=Date.parse(e),r=Date.parse(t);return Number.isNaN(n)?!1:Number.isNaN(r)?!0:n>=r}function feedbackSince(e,t,n,r){let i=null,a=0,isAgent=e=>hasAgentMarker(e.body)&&(r===void 0||e.author===r);for(let t of e)isAgent(t)&&(a+=1,t.on===`pr`&&gl.some(e=>t.body.startsWith(e))&&(i===null||Date.parse(t.createdAt)>Date.parse(i))&&(i=t.createdAt));let o=i??t,s=i===null?`head-commit`:`agent-comment`,c=e.filter(e=>!isAgent(e)&&(e.on===`issue`||isAtOrAfter(e.createdAt,o))).toSorted((e,t)=>Date.parse(e.createdAt)-Date.parse(t.createdAt)),l=c.length>n;return{cutoff:o,cutoffSource:s,agentComments:a,comments:c.slice(0,n).map(e=>({on:e.on,author:e.author,createdAt:e.createdAt,url:e.url??null,excerpt:excerpt(e.body)})),truncated:l}}function ok(e){return{state:`ok`,...e}}function absent(e){return{state:`absent`,reason:e}}function unavailableWith(e){return{state:`unavailable`,reason:e}}function unavailable$1(e){return unavailableWith(reasonText(e))}async function section(e){try{return await e()}catch(e){return unavailable$1(e)}}function reasonText(e){let t=describeForgeError(e);return t===void 0?e instanceof Error?e.message:`the read failed`:t}function linkedIssueNumber(e){return closedIssueNumbers(e.body,repositoryOf(e.url))[0]??null}function repositoryOf(e){let t=e.indexOf(`://`);if(t<0)return null;let n=e.slice(t+3).split(`/`);if(n.length<3)return null;let r=n[1],i=n[2];return r===void 0||i===void 0||i===``?null:`${r}/${i}`}function prFacts(e){let t=e.pr;return{number:e.number,title:e.title,draft:t?.draft??!1,base:t?.base.ref??``,head:t?.head.sha??``,url:e.url}}function issueFacts(e){return{number:e.number,title:e.title,state:e.state,url:e.url}}async function resolveTarget$1(e,t,n,r,i){let a={kind:r===null?`branch`:`issue`,branch:null,head:null,base:null,pr:null,issue:null,gitAbsent:null,forgeDown:null,prFailed:null,otherOpenPrs:[],issueFailed:null,gitFailed:null,failed:null};if(r===null)await resolveBranch(a,e,t,n);else if(t instanceof Error)a.failed=reasonText(t);else try{await resolveRef(a,e,t,r,{defaultBranch:n,checkoutHead:i})}catch(e){a.failed=reasonText(e)}return a}async function resolveBranch(e,t,n,r){try{e.branch=await t.currentBranch(),e.head=await t.headSha(),e.base=await t.resolveBase(r)}catch(t){e.failed=reasonText(t);return}if(n instanceof Error){e.forgeDown=reasonText(n);return}let i=e.branch;if(i===null)return;try{let t=await n.openPrForBranch(i);if(t===null)return;e.pr=await n.view(t),e.kind=`pr`}catch(t){e.forgeDown=reasonText(t);return}await readLinkedIssue(e,n,e.pr);let a=e.pr?.pr?.base.ref;if(a!==void 0&&a!==``&&a!==r)try{e.base=await t.resolveBase(a)}catch(t){e.failed=reasonText(t)}}async function readLinkedIssue(e,t,n){let r=n===null?null:linkedIssueNumber(n);if(r!==null)try{e.issue=await t.view(r)}catch(t){e.issueFailed=reasonText(t)}}async function readCheckoutHead(e,t){try{e.head=await t.headSha(),e.branch=await t.currentBranch()}catch(t){e.gitFailed=reasonText(t)}}async function readHead(e,t,n,r){if(r)await readCheckoutHead(e,t);else try{e.head=await t.fetchPullHead(n)}catch(t){e.gitFailed=reasonText(t)}}async function resolveRef(e,t,n,r,{defaultBranch:i,checkoutHead:a}){if(r.number===void 0){e.failed=`the reference carries no issue or pull request number`;return}let o=await n.view(r.number);if(o.isPullRequest)e.pr=o,e.kind=`pr`,await readHead(e,t,o.number,a),await readLinkedIssue(e,n,o);else{e.issue=o,e.kind=`issue`;let r,i=[];try{i=await n.openPrsClosing(o.number),r=i[0]?.number,r!==void 0&&(e.pr=await n.view(r))}catch(t){e.prFailed=reasonText(t),e.gitFailed=e.prFailed;return}e.otherOpenPrs=i.slice(1),r===void 0?a?await readCheckoutHead(e,t):e.gitAbsent=`no open pull request closes this issue (issue #${String(o.number)})`:await readHead(e,t,r,a)}let s=e.pr?.pr?.base.ref;e.base=await t.resolveBase(s===void 0||s===``?i:s)}function sourcedComments(e,t){let n=[];for(let t of e?.comments??[])n.push({...t,on:`pr`});for(let e of t?.comments??[])n.push({...e,on:`issue`});return n}function labelNames(e){let t=/* @__PURE__ */ new Set;for(let n of e)if(n!==null)for(let e of n.labels)t.add(e);return[...t]}function gitState(e){return e.failed===null?e.gitFailed===null?e.gitAbsent===null?e.head===null||e.base===null?absent(`no head to read`):null:absent(e.gitAbsent):unavailableWith(e.gitFailed):unavailableWith(e.failed)}function objectSection({resolved:e,forgeDown:t}){if(t!==null)return unavailableWith(t);if(e.pr===null&&e.issue===null)return absent(`no pull request or issue for ${e.branch===null?`this checkout`:`branch ${e.branch}`}`);let n={pr:e.pr===null?null:prFacts(e.pr),issue:e.issue===null?null:issueFacts(e.issue)};return e.prFailed!==null&&(n.prUnavailable=e.prFailed),e.issueFailed!==null&&(n.issueUnavailable=e.issueFailed),e.otherOpenPrs.length>0&&(n.otherOpenPrs=e.otherOpenPrs),ok(n)}function liftedFactsOf(e,t){let n=labelNames([e.pr,e.issue]),r=liftedFacts(n),i=ownerOf(n),a=t===null&&e.prFailed===null&&e.issueFailed===null;return{runLive:a||r.runLive.length>0?r.runLive:null,heldByHand:a||r.heldByHand?r.heldByHand:null,heldBy:a||r.heldBy!==null?r.heldBy:null,owner:a||i.owner===`agent`?i.owner:null}}async function docsSection({git:e,docsExtraDirs:t,resolved:n}){let r=gitState(n);if(r!==null)return r;let i=n.base??``,a=n.head??``,o=[],s=[];for(let n of await e.changedPaths(i,a)){let r=classifyTrackedDoc(n,t);if(r===null)continue;if(r.kind===`spec`){o.push({path:n,retired:r.retired});continue}let i=await e.show(a,n);if(i===null)continue;let c=planStatus(i,n);s.push({path:n,status:{...c,total:c.checked+c.outstanding+c.declined+c.deferred}})}return ok({base:i,specs:o,plans:s})}async function labelsSection({forgeApi:e,resolved:t,forgeDown:n}){if(n!==null)return unavailableWith(n);if(t.pr===null&&t.issue===null)return absent(`no pull request or issue to carry labels`);let r=/* @__PURE__ */ new Map,i=null;try{r=(e===null?null:await e.labelDescriptions())??/* @__PURE__ */ new Map}catch(e){i=reasonText(e)}let a={pr:groupLabels(t.pr?.labels??[],r),issue:groupLabels(t.issue?.labels??[],r)};return i!==null&&(a.descriptionsUnavailable=i),ok(a)}async function feedbackSection({git:e,resolved:t,forgeDown:n,agentLogin:r}){if(n!==null)return unavailableWith(n);if(t.pr===null&&t.issue===null)return absent(`no pull request or issue thread to read`);let i=t.head===null?``:await e.commitDate(t.head);return ok(feedbackSince(sourcedComments(t.pr,t.issue),i,20,r))}async function findingsSection({git:e,resolved:t,forgeDown:n}){let r=gitState(t);if(r!==null)return r;if(t.pr===null&&t.issue===null)return n===null?absent(`no pull request or issue to match findings against`):unavailableWith(n);let i=t.head??``,a=t.pr?.number??null,o=t.issue?.number??null,s=[];for(let t of await e.listDir(i,$)){let n=parseFindingFileName(t);if(n===null||!(n.origin.kind===`pr`&&n.origin.number===a||n.origin.kind===`issue`&&n.origin.number===o))continue;let r=await e.show(i,`${$}/${t}`),c=r===null?null:parseFindingHeader(r);s.push({name:t,class:c?.class??null,title:c?.title??null})}return ok({entries:s})}async function commitsSection({git:e,resolved:t}){let n=gitState(t);if(n!==null)return n;let r=t.base??``,i=t.head??``,a=await e.commits(r,i,20);return ok({base:r,cap:20,truncated:a.truncated,entries:a.entries})}async function buildWorkStatus(e,t){let{git:n,forge:r,docsExtraDirs:i,defaultBranch:a,agentLogin:o,checkoutHead:s=!1}=e,c=await resolveTarget$1(n,r,a,t,s),l=c.failed??c.forgeDown,u={git:n,forgeApi:r instanceof Error?null:r,docsExtraDirs:i,resolved:c,forgeDown:l,...o===void 0?{}:{agentLogin:o}},d=liftedFactsOf(c,l);return{target:{kind:c.kind,branch:c.branch,head:c.head},runLive:d.runLive,heldByHand:d.heldByHand,heldBy:d.heldBy,owner:d.owner,object:await section(()=>objectSection(u)),docs:await section(()=>docsSection(u)),labels:await section(()=>labelsSection(u)),feedback:await section(()=>feedbackSection(u)),findings:await section(()=>findingsSection(u)),commits:await section(()=>commitsSection(u))}}const vl=`Advice, not a gate: this is what the reads found, not a verdict.`;function short(e){return e.length<=10?e:e.slice(0,10)}function block(e,t,n){return t.state===`absent`?[`${e}: none -- ${t.reason}`]:t.state===`unavailable`?[`${e}: unavailable -- ${t.reason}`]:[`${e}:`,...n(t)]}function objectRows(e){let t=[];if(e.pr!==null&&t.push(` PR #${String(e.pr.number)} "${e.pr.title}"${e.pr.draft?` (draft)`:``} ${e.pr.base} -> ${short(e.pr.head)} ${e.pr.url}`),e.issue!==null&&t.push(` issue #${String(e.issue.number)} [${e.issue.state}] "${e.issue.title}" ${e.issue.url}`),e.otherOpenPrs!==void 0){let n=e.otherOpenPrs.map(e=>`#${String(e.number)}${e.title===null?``:` "${e.title}"`}`);t.push(` other open PRs closing this issue: ${n.join(`, `)}`)}return e.prUnavailable!==void 0&&t.push(` PR unavailable -- ${e.prUnavailable}`),e.issueUnavailable!==void 0&&t.push(` issue unavailable -- ${e.issueUnavailable}`),t}function docsRows(e){let t=[` base ${e.base}`];for(let n of e.specs)t.push(` spec ${n.path}${n.retired?` (retired)`:``}`);for(let n of e.plans)t.push(` plan ${n.path}: ${String(n.status.checked)} of ${String(n.status.total)} checked, ${String(n.status.outstanding)} outstanding${n.status.declined>0?`, ${String(n.status.declined)} declined`:``}`);return e.specs.length===0&&e.plans.length===0&&t.push(` no spec or plan changed on this branch`),t}function labelRows(e){let t=[];for(let[n,r]of[[`pull request`,e.pr],[`issue`,e.issue]])if(r.length!==0){t.push(` ${n}:`);for(let e of r)for(let n of e.labels){let r=n.description===null?``:` -- ${n.description}`;t.push(` ${n.name}${r} [${e.scope}]`)}}return e.descriptionsUnavailable!==void 0&&t.push(` descriptions unavailable -- ${e.descriptionsUnavailable}`),t}function nothingInFlight(e){let{object:t,docs:n,commits:r}=e;return t.state!==`absent`||n.state!==`ok`||r.state!==`ok`||n.specs.length>0||n.plans.length>0||r.entries.length>0||e.runLive===null||e.runLive.length>0||e.heldByHand!==!1?null:`nothing in flight: no pull request or issue, no spec or plan changed, no commits ahead of ${r.base}`}function heading({kind:e,branch:t,head:n}){let r=e===`branch`&&t!==null?[]:[e];return t!==null&&r.push(`branch ${t}`),n!==null&&r.push(`head ${short(n)}`),`work:status ${r.join(`, `)}`}function claimableNumber(e){return e.object.state===`ok`?e.target.kind===`issue`?e.object.issue?.number??null:e.object.pr?.number??e.object.issue?.number??null:null}function renderWorkStatus(e,t){let n=nothingInFlight(e);if(n!==null)return[heading(e.target),n].join(`
|
|
6095
|
+
`);let r=[heading(e.target)];for(let t of e.runLive??[])r.push(`RUN LIVE: ${t} -- a run is working this object; do not start another.`);if((e.runLive===null||e.heldByHand===null)&&r.push(`UNKNOWN: whether a run is live or a human holds this -- not every label could be read.`),e.heldBy!==null&&r.push(`HELD BY HAND: ${e.heldBy} -- a human claimed this one; do not drive it.`),t?.agentEnabled===!0&&e.owner===`unclaimed`){let t=claimableNumber(e);t!==null&&r.push(`UNCLAIMED: no agent label and no hand claim -- run \`pnpm exec bst work:start ${String(t)}\` before you work this.`)}return r.push(...block(`object`,e.object,objectRows)),r.push(...block(`docs`,e.docs,docsRows)),r.push(...block(`labels`,e.labels,labelRows)),r.push(...block(`feedback`,e.feedback,e=>{let t=e.cutoffSource===`agent-comment`?`last agent comment`:`head commit`,n=[` since ${e.cutoff} (the ${t}), ${String(e.agentComments)} agent comment(s) held back`];for(let t of e.comments)n.push(` ${t.on} ${t.author} ${t.createdAt}: ${t.excerpt}`);return e.comments.length===0&&n.push(` nothing new from a human`),e.truncated&&n.push(` (more -- the cap is reached)`),n})),r.push(...block(`findings`,e.findings,e=>{let t=[];for(let n of e.entries){let e=n.class===null?``:` [${n.class}]`;t.push(` ${n.name}${e} ${n.title??``}`.trimEnd())}return t.length===0&&t.push(` none filed against this object`),t})),r.push(...block(`commits`,e.commits,e=>{let t=e.truncated?` (cap ${String(e.cap)} reached)`:``,n=[` ${String(e.entries.length)} since ${e.base}${t}`];for(let t of e.entries)n.push(` ${short(t.sha)} ${t.subject}`);return n})),r.push(e.feedback.state===`ok`?`${vl} The feedback cutoff is the newest agent run or review comment on the pull request and is approximate, and review comments pinned to diff lines are not in the thread this reads.`:vl),r.join(`
|
|
6096
|
+
`)}function releaseLine(e){return e.outcome===`released`?`release: released -- ${Ks} is off every object holding this unit.`:e.outcome===`resumed`?`release: resumed -- ${e.label??`a trigger`} is queued for the agent.`:e.outcome===`not-claimed`?`release: not-claimed -- ${e.reason??`nothing was held.`}`:e.outcome===`not-agent-repo`?`release: not-agent-repo -- ${e.reason??`nothing was released.`}`:`release: ${e.outcome} -- ${e.reason??`nothing was released.`}`}function releaseFailed(e){return e.outcome===`refused`||e.outcome===`failed`}async function readSiblings(e,t,n){if(!n)return[];if(e instanceof Error)return e;if(t.object.state!==`ok`)return[];let r=t.object.otherOpenPrs??[],i=[];try{for(let t of r){let n=await e.view(t.number);i.push({number:t.number,labels:n.labels})}}catch(e){return e instanceof Error?e:new D(String(e))}return i}const yl=j({meta:{name:`work:end`,description:`Hand claimed work back: remove agent-flags/human-driven from every object holding the unit, and with --resume queue the agent's next step`},args:{ref:{type:`positional`,required:!0,description:`Issue or pull request number or URL to release`},resume:{type:`boolean`,description:`Also queue the agent's next step, from a fixed table. Refuses, writing nothing, where the next step is a panel click (Merge, Fix selected, approving a CI-definition change or an egress list)`},comment:{type:`string`,description:`Post this comment before any label changes, on the half carrying the unit's agent label, or on the ref's object when neither half carries one. An answer to a blocked question goes here`},json:{type:`boolean`,description:`Emit one JSON document: the whole work:status report plus a release member {outcome, label?, reason?}. outcome is released (the flag came off, nothing queued; exit 0), resumed (the flag came off and label names the trigger written; exit 0), not-claimed (no object holding the unit carried the flag, nothing written; exit 0), not-agent-repo (the default branch does not set agent.enabled, nothing written; exit 0), refused (a live run, a --resume step the table refuses, or a paused release over a queued trigger; exit 1), or failed (a read or write could not be done; reason says which write had landed; exit 1). refused and failed carry ok: false and an error member of kind runtime, and the report survives beside them.`},verbose:{type:`boolean`,description:`Emit detailed debug logging`}},async run({args:e}){let t=typeof e.ref==`string`?e.ref.trim():``,n=typeof e.comment==`string`?e.comment:void 0;if(n!==void 0&&n.trim()===``)throw new T(`Usage: pnpm exec bst work:end --comment needs text to post`);let{ref:r,executor:i,git:a,forge:o}=await prepareWorkStatus(t,process.cwd()),s=r?.number;if(s===void 0)throw new T(`Usage: pnpm exec bst work:end needs an issue or pull request number or URL`);let c=resolveDocsConfig(a.topLevel),l=resolveDefaultBranch({cwd:a.topLevel}),u=await buildWorkStatus({git:a,forge:o,docsExtraDirs:c.extraDirs,defaultBranch:l},r),d=await readAgentConsent(a,l),f=await readSiblings(o,u,d.enabled),p=decideEnd(u,d.enabled,f,{resume:e.resume===!0,refNumber:s}),m,h;p.kind===`write`?(m=await writeEnd(i,a.topLevel,r?.target,p.plan,n),h=+!!releaseFailed(m)):(m=p.result,h=p.exitCode);let g=createCliOutput(e.json===!0),_=releaseFailed(m);g.json({ok:!_,...u,release:m,..._?{error:{kind:`runtime`,message:m.reason??m.outcome}}:{}}),g.text(renderWorkStatus(u,{agentEnabled:d.enabled})),g.text(releaseLine(m)),h!==0&&(process.exitCode=h)}});function decideClaim(e,t){if(!t)return{kind:`answer`,exitCode:0,result:{outcome:`not-agent-repo`,reason:`Nothing was claimed: this repository's default branch does not set agent.enabled, so the agent does not work it and there is nothing to claim against.`}};if(e.owner===null)return{kind:`answer`,exitCode:1,result:{outcome:`failed`,reason:`A label read failed, so a run may be live on this object unseen. Nothing was claimed; retry once the forge read works.`}};let n=ownershipOf(e);return n.kind===`running`?{kind:`answer`,exitCode:1,result:{outcome:`refused`,label:n.label,reason:`A run is live on this object (${n.label}); a claim does not stop it.`}}:n.kind===`person`?{kind:`answer`,exitCode:0,result:{outcome:`already-claimed`}}:n.kind===`agent`&&n.hold!==`parked`?{kind:`answer`,exitCode:1,result:{outcome:`refused`,label:n.label,reason:`The agent holds this object (${n.label}). Claim it from the control panel's "Claim for hand work", which strips the trigger, or remove the agent label by hand and run pnpm exec bst work:start again.`}}:n.kind===`agent`&&e.runLive===null?{kind:`answer`,exitCode:1,result:{outcome:`failed`,reason:`A label read failed, so a run may be live or queued beside ${n.label} unseen. Nothing was claimed; retry once the forge read works.`}}:{kind:`write`}}function ownershipOf(e){if(e.labels.state===`ok`){let t=ownerOf(labelNamesOf(e.labels));return t.owner===`agent`?t.hold===`running`?{kind:`running`,label:t.label}:{kind:`agent`,label:t.label,hold:t.hold}:t.owner===`person`?{kind:`person`}:{kind:`unclaimed`}}if(e.owner===`agent`){let t=e.runLive?.[0];return t===void 0?{kind:`agent`,label:`an agent label`,hold:`unread`}:{kind:`running`,label:t}}return e.owner===`person`?{kind:`person`}:{kind:`unclaimed`}}async function writeClaim(e,t,n,r){try{let{conn:i}=requireForgejoTransport(e,t,n,`bst work:start claims work on Forgejo, the forge the agent drives; a GitHub checkout has no agent to hand work to.`),a=(await fetchAllForgejoLabels(e,i)).find(e=>e.name===Ks);return a===void 0?{outcome:`failed`,reason:`The forge has no label named ${Ks}. Provision the agent's labels first with pnpm exec bst-agent agent:labels --repo ${i.repository}, or the control panel's Provision labels.`}:(await addForgejoIssueLabel(e,i,r,Ks,/* @__PURE__ */ new Map([[Ks,a.id]])),{outcome:`claimed`,label:Ks})}catch(e){return{outcome:`failed`,reason:k(e)}}}function claimLine(e){return e.outcome===`claimed`?`claim: claimed -- ${e.label??`agent-flags/human-driven`} is on this object.`:e.outcome===`already-claimed`?`claim: already-claimed -- the flag is already on it; nothing was written.`:e.outcome===`not-agent-repo`?`claim: not-agent-repo -- ${e.reason??`nothing was claimed.`}`:`claim: ${e.outcome} -- ${e.reason??`nothing was claimed.`}`}function claimFailed(e){return e.outcome===`refused`||e.outcome===`failed`}const bl=j({meta:{name:`work:start`,description:`Claim an issue or pull request for hand work: put agent-flags/human-driven on it so the agent leaves it alone`},args:{ref:{type:`positional`,required:!0,description:`Issue or pull request number or URL to claim`},json:{type:`boolean`,description:`Emit one JSON document: the whole work:status report plus a claim member {outcome, label?, reason?}. The report's object section carries otherOpenPrs ([{number, title}], newest first, title null when the forge has none), the other open pull requests whose bodies close the issue, absent when there are none. outcome is claimed (the flag was written), already-claimed (it was already on the object, nothing written), not-agent-repo (the default branch does not set agent.enabled, nothing written), refused (a live run or a queued agent trigger holds it; exit 1), or failed (a read or write could not be done; exit 1). refused and failed carry ok: false and an error member of kind runtime, and the report survives beside them.`},verbose:{type:`boolean`,description:`Emit detailed debug logging`}},async run({args:e}){let{ref:t,executor:n,git:r,forge:i}=await prepareWorkStatus(typeof e.ref==`string`?e.ref.trim():``,process.cwd()),a=t?.number;if(a===void 0)throw new T(`Usage: pnpm exec bst work:start needs an issue or pull request number or URL`);let o=resolveDocsConfig(r.topLevel),s=resolveDefaultBranch({cwd:r.topLevel}),c=await buildWorkStatus({git:r,forge:i,docsExtraDirs:o.extraDirs,defaultBranch:s},t),l=await readAgentConsent(r,s),u=decideClaim(c,l.enabled),d,f;u.kind===`write`?(d=await writeClaim(n,r.topLevel,t?.target,a),f=+!!claimFailed(d)):(d=u.result,f=u.exitCode);let p=createCliOutput(e.json===!0),m=claimFailed(d);p.json({ok:!m,...c,claim:d,...m?{error:{kind:`runtime`,message:d.reason??d.outcome}}:{}}),p.text(renderWorkStatus(c,{agentEnabled:l.enabled})),p.text(claimLine(d)),f!==0&&(process.exitCode=f)}}),xl=j({meta:{name:`work:status`,description:`Orient a session on a branch, issue or pull request: PR, issue, plan progress, labels, new feedback, findings`},args:{ref:{type:`positional`,required:!1,description:`Issue or pull request number or URL; default: the current branch`},json:{type:`boolean`,description:`Emit one JSON document: target, runLive, heldByHand, heldBy (the hold label the report found, null when none or unread), owner (agent, person or unclaimed; each null when not every label could be read), and six sections (object, docs, labels, feedback, findings, commits), each {state: ok} with its fields, {state: absent, reason} or {state: unavailable, reason}. The object section also carries otherOpenPrs ([{number, title}], newest first, title null when the forge has none), the other open pull requests whose bodies close the issue, absent when there are none. The output is advice, not a gate: the feedback cutoff is the newest agent run or review comment on the pull request and is approximate, and review comments on diff lines are not in the thread this reads.`},verbose:{type:`boolean`,description:`Emit detailed debug logging`}},async run({args:e}){let{ref:t,git:n,forge:r}=await prepareWorkStatus(typeof e.ref==`string`?e.ref.trim():``,process.cwd()),i=resolveDocsConfig(n.topLevel),a=resolveDefaultBranch({cwd:n.topLevel}),o=await buildWorkStatus({git:n,forge:r,docsExtraDirs:i.extraDirs,defaultBranch:a},t),s=await readAgentConsent(n,a),c=createCliOutput(e.json===!0);c.json({ok:!0,...o}),c.text(renderWorkStatus(o,{agentEnabled:s.enabled}))}});function collectInputArgs(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r!==void 0){if(r===`--`)break;if(r===`--input`){let r=e[n+1];if(r===void 0)throw new T("Missing value for --input: expected `--input key=value`");t.push(r),n+=1}else r.startsWith(`--input=`)&&t.push(r.slice(8))}}return t}function parseInputs(e){let t={};for(let n of e){let e=n.indexOf(`=`);if(e<=0)throw new T(`Invalid --input "${n}": expected key=value`);t[n.slice(0,e)]=n.slice(e+1)}return t}const Sl=j({meta:{name:`workflow:dispatch`,description:`Trigger a workflow_dispatch event for a workflow in any repo on the same git host. The resolved token must have rights on --repo when it differs from the current repo.`},args:{repo:{type:`string`,description:`Target repository as owner/repo (default: the current repo)`,required:!1},workflow:{type:`string`,description:`Workflow filename (e.g. deploy.yml) or numeric ID`,required:!0},ref:{type:`string`,description:`Git ref to dispatch on (default: main)`,required:!1},input:{type:`string`,description:`Workflow input as key=value (repeatable)`,required:!1},json:{type:`boolean`,description:`Emit one JSON document: status (dispatched), host (forgejo | github), repo (owner/repo, or null), workflow, ref, inputs. status is always dispatched; repo is null when GitHub cannot name it.`}},async run({args:e,rawArgs:t}){let n=createCliOutput(e.json===!0);if(!e.workflow)throw new T(`--workflow is required`);let r=e.ref??`main`,i=parseInputs(collectInputArgs(t)),a=await dispatchWorkflow(resolveConnection(process.cwd()),{repo:e.repo,workflow:e.workflow,ref:r,inputs:i},createRealExecutor$1());n.json({status:`dispatched`,...a})}});async function mergePr(e,t,n,r){let i=`${t.serverUrl}/api/v1/repos/${t.repository}/pulls/${String(n)}/merge`,a={Do:r?.method??`merge`,delete_branch_after_merge:r?.deleteBranch??!0};r?.expectedHeadSha!==void 0&&(a.head_commit_id=r.expectedHeadSha);let o=await e.fetch(i,{method:`POST`,headers:{Authorization:`token ${t.token}`,"Content-Type":`application/json`},body:JSON.stringify(a)});o.ok||await throwForgejoFailure(o,{verb:`merge PR`,resource:`#${String(n)}`})}const Cl=P.object({state:P.string(),draft:P.boolean(),mergeable:P.boolean().nullable(),head:P.object({sha:P.string()}),merge_base:P.string(),changed_files:P.number().nullish(),base:P.object({ref:P.string()}),labels:P.array(P.object({name:P.string()})).nullable(),updated_at:P.string().nullish()});async function readMergeGate(e,t,n){let r=`${t.serverUrl}/api/v1/repos/${t.repository}/pulls/${String(n)}`,i=await e.fetch(r,{headers:{Authorization:`token ${t.token}`}});i.ok||await throwForgejoFailure(i,{verb:`read PR merge gate`,resource:`#${String(n)}`});let a=Cl.safeParse(await i.json());if(!a.success)throw new D(`Unexpected PR merge-gate response: ${a.error.message}`);return{open:a.data.state===`open`,draft:a.data.draft,mergeable:a.data.mergeable??!1,headSha:a.data.head.sha,mergeBase:a.data.merge_base,changedFiles:a.data.changed_files??null,baseRef:a.data.base.ref,labels:(a.data.labels??[]).map(e=>e.name),updatedAt:a.data.updated_at??null}}async function confirmMergeable(e,t,n,r){let i=await readMergeGate(e,t,n);if(i.mergeable)return{verdict:`mergeable`,gate:i,firstGate:i,rechecked:!1,evidence:null};if(r.settleOnFirstRead?.(i)===!0)return{verdict:`unconfirmed`,gate:i,firstGate:i,rechecked:!1,evidence:null};r.beforeRecheck?.(i),await r.sleep(r.delayMs);let a=await readMergeGate(e,t,n);return a.mergeable?{verdict:`mergeable`,gate:a,firstGate:i,rechecked:!0,evidence:null}:a.headSha===i.headSha&&a.mergeBase===i.mergeBase?{verdict:`conflicted`,gate:a,firstGate:i,rechecked:!0,evidence:`The forge reported it unmergeable on two reads ${String(r.delayMs)}ms apart, at head ${a.headSha}.`}:{verdict:`unconfirmed`,gate:a,firstGate:i,rechecked:!0,evidence:a.headSha===i.headSha?`Its merge base moved from ${i.mergeBase} to ${a.mergeBase} between the two reads.`:`Its head moved from ${i.headSha} to ${a.headSha} between the two reads.`}}P.object({draft:P.boolean(),mergeable:P.boolean().nullable(),merge_base:P.string(),base:P.object({ref:P.string(),sha:P.string()})});function envMsOverride(e,t){if(e===void 0)return t;let n=Number(e.trim());return!Number.isSafeInteger(n)||n<=0?t:Math.min(n,t)}function evaluateVersionPr(e){let t=`PR #${String(e.prNumber)}`;return e.open?e.draft?{ok:!1,retryable:!1,reason:`${t} is a draft.`}:e.emptiness===`empty`?{ok:!1,retryable:!1,reason:`${t}'s diff against base is empty -- refusing to merge it and leaving its branch alone.`}:e.mergeable===`unconfirmed`?{ok:!1,retryable:!0,recheck:!0,reason:withEvidence(`${t}'s mergeability is still being computed -- re-run once the forge finishes checking.`,e.mergeabilityEvidence)}:e.mergeable===`conflicted`?{ok:!1,retryable:!1,reason:withEvidence(`${t} is not mergeable.`,e.mergeabilityEvidence)}:{ok:!0,headSha:e.headSha}:{ok:!1,retryable:!1,reason:`${t} is not open.`}}function withEvidence(e,t){return t===void 0?e:`${e} ${t}`}function needsRecheck(e){return!e.ok&&`recheck`in e}function emptinessFromGate(e){return e.headSha===e.mergeBase||e.changedFiles===0?`empty`:`non-empty`}function headShaOrThrow(e){if(e.ok)return e.headSha;throw e.retryable?new E(e.reason):new T(e.reason)}function stateFromGate(e,t,n,r){return{prNumber:e,open:t.open,draft:t.draft,mergeable:n,headSha:t.headSha,emptiness:emptinessFromGate(t),mergeabilityEvidence:r}}function logGateRead(e,t){I.info(`changesets:merge: PR #${String(e)} at ${t.headSha} (${t.changedFiles===null?`changed-files unknown`:`${String(t.changedFiles)} changed files`})`)}const wl={ok:!0,retryable:null,reason:null};async function mergeVersionPrForgejo(e,t,n){let r=versionPrBranch(n.defaultBranch),i=await findOpenPr(e,t,r);if(i===null)throw new T(`No open PR found for branch ${r}`);let a=n.sleep??sleep,o=envMsOverride(process.env.BST_TEST_VERSION_MERGE_RECHECK_MS,2e3),s=await confirmMergeable(e,t,i,{delayMs:o,sleep:a,settleOnFirstRead:e=>!needsRecheck(evaluateVersionPr(stateFromGate(i,e,`unconfirmed`))),beforeRecheck:e=>{logGateRead(i,e),I.info(`changesets:merge: PR #${String(i)}'s mergeability is not confirmed yet -- re-reading after ${String(o)}ms`)}}),{gate:c,rechecked:l}=s;logGateRead(i,c);let u=headShaOrThrow(evaluateVersionPr(stateFromGate(i,c,s.verdict,s.evidence??void 0))),d={host:`forgejo`,number:i,headSha:u,mergeBase:c.mergeBase,changedFiles:c.changedFiles,branch:r,rechecked:l,verdict:{...wl}};return n.dryRun?(I.info(`[dry-run] Would merge PR #${String(i)} at ${u} and delete branch ${r}`),{...d,status:`would-merge`}):(await mergePr(e,t,i,{method:`merge`,deleteBranch:!0,expectedHeadSha:u}),I.info(`Merged PR #${String(i)} and deleted branch ${r}`),{...d,status:`merged`})}const Tl=P.object({number:P.number(),state:P.string(),isDraft:P.boolean(),mergeable:P.string(),headRefOid:P.string(),changedFiles:P.number()});function mergeVersionPrGitHub(e,t){let n=versionPrBranch(t.defaultBranch),r=e.exec(`gh`,[`pr`,`view`,n,`--json`,`number,state,isDraft,mergeable,headRefOid,changedFiles`],{cwd:process.cwd()});if(r.exitCode!==0)throw new T(`Failed to read PR for branch ${n}: ${r.stderr||r.stdout||`unknown error`}`);let i=Tl.safeParse(JSON.parse(r.stdout));if(!i.success)throw new T(`Unexpected 'gh pr view' response for branch ${n}: ${i.error.message}`);let a=i.data,o=a.changedFiles===0?`empty`:`non-empty`,s=a.mergeable===`CONFLICTING`?`conflicted`:`mergeable`;I.info(`changesets:merge: PR #${String(a.number)} at ${a.headRefOid} (${String(a.changedFiles)} changed files)`);let c=headShaOrThrow(evaluateVersionPr({prNumber:a.number,open:a.state===`OPEN`,draft:a.isDraft,mergeable:s,headSha:a.headRefOid,emptiness:o})),l={host:`github`,number:a.number,headSha:c,mergeBase:null,changedFiles:a.changedFiles,branch:n,rechecked:!1,verdict:{...wl}};if(t.dryRun)return I.info(`[dry-run] Would merge PR #${String(a.number)} at ${c} and delete branch ${n}`),{...l,status:`would-merge`};let u=e.exec(`gh`,[`pr`,`merge`,n,`--merge`,`--delete-branch`,`--match-head-commit`,c],{cwd:process.cwd()});if(u.exitCode!==0)throw new T(`Failed to merge PR: ${u.stderr||u.stdout||`unknown error`}`);return I.info(`Merged changesets PR and deleted branch ${n}`),{...l,status:`merged`}}const El=j({meta:{name:`changesets:merge`,description:`Merge the open changesets version PR. Reads the PR live, refuses a draft or an empty diff with no override, and pins the merge to the head commit it read.`},args:{"dry-run":{type:`boolean`,description:`Show what would be merged without actually merging`},json:{type:`boolean`,description:`Emit one JSON document: status (merged | would-merge), host (forgejo | github), number, headSha, mergeBase (or null), changedFiles (or null), branch, rechecked, verdict ({ok, retryable, reason}). would-merge is a dry run's status; mergeBase is null on GitHub, changedFiles is null when the forge gave no count, and rechecked is true when Forgejo's confirming re-read ran. Every refusal is an error, so a result always has verdict.ok true.`}},async run({args:e}){let t=createCliOutput(e.json===!0),n=e[`dry-run`]===!0,r=resolveConnection(process.cwd()),i=createRealExecutor$1(),a=readConfiguredDefaultBranch(process.cwd()),o=r.type===`forgejo`?await mergeVersionPrForgejo(i,r.conn,{dryRun:n,defaultBranch:a}):mergeVersionPrGitHub(i,{dryRun:n,defaultBranch:a});t.json(o)}}),Dl=/* @__PURE__ */ new Set([`main`,`master`]);function stateWord(e){return e===`open`?`open`:`closed, unmerged`}async function refuseProtectedBranch(e,t,n){let{cwd:r,branch:i}=t,a=t.defaultBranchOverride,o=pickDefaultBranch(a,a===void 0||a===``?await resolveOriginHead(e,r,t.signal):void 0);if(Dl.has(i)||i===o)throw new T(n(i));return o}var BranchPrError=class extends T{reason;branch;state;numbers;openNumbers;constructor(e){let t=e.openNumbers??[];super(branchPrMessage(e,t)),this.reason=e.reason,this.branch=e.branch,this.state=e.state,this.numbers=e.numbers,this.openNumbers=t}};function branchPrMessage(e,t){let n=e.numbers.map(e=>`#${String(e)}`).join(`, `);if(e.reason===`several`)return`${e.branch} has ${String(e.numbers.length)} ${stateWord(e.state)} pull requests (${n}), so there is no way to tell which one you mean. Pass the pull request NUMBER.`;if(t.length===1)return`${e.branch} has no ${stateWord(e.state)} pull request; #${String(t[0])} is already open. Pass the pull request NUMBER.`;if(t.length>1){let n=t.map(e=>`#${String(e)}`).join(`, `);return`${e.branch} has no ${stateWord(e.state)} pull request; it has open pull requests (${n}). Pass the pull request NUMBER.`}return`${e.branch} has no ${stateWord(e.state)} pull request. Pass the pull request NUMBER.`}async function resolveBranchPr$1(e,t,n){let r=await currentBranch(e,n.cwd,n.signal);await refuseProtectedBranch(e,{cwd:n.cwd,branch:r,...n.defaultBranchOverride===void 0?{}:{defaultBranchOverride:n.defaultBranchOverride},signal:n.signal},e=>`Autodetect will not run on the protected branch "${e}" -- pass the pull request NUMBER.`);let i=await listBranchNumbers(t,r,n.state,n.signal),a=i[0];if(i.length===1&&a!==void 0)return{branch:r,number:a};if(i.length>1)throw new BranchPrError({reason:`several`,branch:r,state:n.state,numbers:i});let o=n.state===`closed-unmerged`?await listBranchNumbers(t,r,`open`,n.signal):[];throw new BranchPrError({reason:`none`,branch:r,state:n.state,numbers:[],openNumbers:o})}async function listBranchNumbers(e,t,n,r){return n===`open`?(await e.listForBranch(t,`open`,r)).map(e=>e.number):(await e.listForBranch(t,`closed`,r)).filter(e=>!e.merged).map(e=>e.number)}function refuseRepoWithoutNumber(e,t){if(t!==void 0&&e===void 0)throw new T(`--repo names ${t}, and the current branch says nothing about another repository -- pass the pull request NUMBER.`)}const Ol=/* @__PURE__ */ new Set([`feat`,`fix`,`chore`,`docs`,`refactor`,`test`,`perf`,`build`,`ci`,`style`,`revert`]);function words(e){return e.replaceAll(`-`,` `).replaceAll(`_`,` `)}function humanizeBranch(e){let t=e.indexOf(`/`);if(t===-1)return words(e);let n=e.slice(0,t),r=e.slice(t+1);return Ol.has(n)?`${n}: ${words(r)}`:`${words(n)} ${words(r.replaceAll(`/`,` `))}`}function withWipPrefix(e,t){return t&&!hasWipPrefix(e)?`WIP: ${e}`:e}function derivePrContent(e){let[t]=e.subjects,n=e.subjects.length===1&&t!==void 0?t:humanizeBranch(e.branch),r=e.title??n,i=e.wipTitles?withWipPrefix(r,e.draft):r;if(e.body!==void 0)return{title:i,body:e.body,droppedRefs:droppedClosingRefs(e.messages,e.body)};let a=e.subjects.map(e=>`- ${e}`).join(`
|
|
6093
6097
|
`),o=droppedClosingRefs(e.messages,a);return{title:i,body:o.length===0?a:`${a}\n\n${o.map(e=>e.text).join(`
|
|
6094
|
-
`)}`,droppedRefs:[]}}var PrModeError=class extends T{reason;branch;existing;numbers;mode;constructor(e,t,n,r=[],i=null){super(prModeMessage(e,t,n,r)),this.reason=e,this.branch=t,this.existing=n,this.numbers=[...r],this.mode=i}};function prModeMessage(e,t,n,r){if(e===`already-open`)return`${t} already has an open PR (#${String(n)}).`;if(e===`several-open`){let e=r.map(e=>`#${String(e)}`).join(`, `);return`${t} has ${String(r.length)} open PRs (${e}), so there is no way to tell which one to update.`}return e===`not-branch-pr`?`#${String(n)} is not an open PR of ${t}.`:`${t} has no open PR to update.`}function choosePrForMode(e,t,n,r){let i=t.map(e=>e.number);if(r!==void 0){let a=t.find(e=>e.number===r);if(a===void 0)throw new PrModeError(`not-branch-pr`,n,r,i,e);return refuseBaseless(a,n)}
|
|
6095
|
-
`),r=droppedClosingRefs([n],e.effective.body).map(e=>Number(e.issue.slice(1)));if(r.length===0)return{plan:e,added:r};let i=carryForwardClosingRefs(n,e.effective.body);return{plan:{...e,patch:{...e.patch,body:i},effective:{...e.effective,body:i}},added:r}}async function planUpsert(e,t,n,r){let i;if(i=t===null?{patch:{title:n.title,body:n.body},effective:n,previousBody:null}:planPrUpdate(r,n,prUpdateNeedsLive(r)?await e.readLive(t,r.signal??null):null,e.wipTitles),r.closes===void 0)return{plan:i,closesAdded:void 0};let a=addClosingIssues(i,r.closes);return{plan:a.plan,closesAdded:a.added}}async function runPrUpsert$1(e,t,n){let{cwd:r}=n,i=n.mode??`upsert`,a=n.signal??null,o=await currentBranch(e,r,a),s=await refuseProtectedBranch(e,{cwd:r,branch:o,...n.defaultBranchOverride===void 0?{}:{defaultBranchOverride:n.defaultBranchOverride},signal:a},e=>`Refusing to open a PR from the protected branch "${e}" -- create a branch first.`),c=n.base??s,l=await baseRef(e,r,c,a),u=await commitSubjects(e,r,l,a);if(u.length===0)throw new T(`No commits on ${o} that are not already on ${c}.`);let d=await commitMessages(e,r,l,a);await hasUncommittedChanges(e,r,a)&&H.warn(`Working tree has uncommitted changes -- they will not be part of this PR.`);let f=derivePrContent({branch:o,subjects:u,messages:d,title:n.title,body:n.body,draft:n.draft===!0,wipTitles:t.wipTitles});n.onResolved?.({mode:i,branch:o,base:c});let p=choosePrForMode(i,await t.listForBranch(o,`open`,a),o,n.expectedNumber),m=p?.number??null;!n.dryRun&&n.skipPush!==!0&&await pushBranch(e,r,o,n.pushEnv,n.forceWithLease);let{plan:h,closesAdded:g}=await planUpsert(t,m,f,n),_=checkClosingLinks(d,h,n.allowUnlink===!0);n.onClosingLinks?.(_);let v={branch:o,base:p?.base??c,...h.effective,...g===void 0?{}:{closesAdded:g}};if(n.dryRun)return{action:m===null?`would-create`:`would-update`,number:null,url:null,...v};if(m===null){let e=await t.create(v,n.draft);return{action:`created`,number:e.number,url:e.url,...v}}return{action:`updated`,number:m,url:(await t.update(m,h.patch,n.draft)).url,...v}}function describePrModeError(e,t){if(e.reason===`already-open`){let n=t.create.split(` `).at(-1)??t.create;return`${e.branch} already has an open PR (#${String(e.existing)}) -- use \`${t.update}\` to push new commits to it. (${n} refuses rather than rewrite its title and body from the branch's commits, which is how an authored description gets replaced by "${humanizeBranch(e.branch)}".)`}if(e.reason===`several-open`){let n=e.numbers.map(e=>`#${String(e)}`).join(`, `);return e.mode===`upsert`?`${e.branch} has ${String(e.numbers.length)} open PRs, so nothing can tell which one to update -- close all but one of ${n}, or pass NUMBER to \`${t.update}\` by hand.`:`${e.branch} has ${String(e.numbers.length)} open PRs (${n}), so nothing can tell which one to update -- pass one NUMBER to \`${t.update}\`.`}return e.reason===`not-branch-pr`?`#${String(e.existing)} is not an open PR of ${e.branch} -- ${describeBranchPrs(e.numbers)}. Update the branch's own PR, or run \`${t.create}\` to open one.`:`${e.branch} has no open PR to update -- use \`${t.create}\` to open one.`}function describeBranchPrs(e){return e.length===0?`it has none`:`it has ${e.map(e=>`#${String(e)}`).join(`, `)}`}function describeClosingLinks(e,t){let n=[];if(e.fromCommits.length>0){let r=e.fromCommits.map(e=>e.text).join(`, `);n.push(`The commits say ${r}, but the PR body does not -- the issue may not close on merge. Link it with ${t.closes}.`)}if(e.unlinked.length>0){let r=e.unlinked.map(e=>e.text).join(`, `);n.push(`${t.allowUnlink}: dropping ${r} from the PR body as instructed.`)}return n}function describeLostClosingRefs(e,t){return`Refusing to update: this would remove ${e.lost.map(e=>e.text).join(`, `)} from the PR body, and the new body does not close it -- the issue would stay open when the PR merges, and nothing else reports that. Keep the line in the body you are passing, or pass ${t.allowUnlink} if the PR really should stop closing it.`}function rewordPrUpsertError(e,t){if(e instanceof PrModeError)return new T(describePrModeError(e,t.commands));if(e instanceof LostClosingRefsError){let n={fromCommits:e.fromCommits,unlinked:[]};for(let e of describeClosingLinks(n,t.flags))t.warn(e);return new T(describeLostClosingRefs(e,t.flags))}return e}function prTarget(e){return`${e.branch} -> ${e.base}`}function prLabel(e){return e.number===null?`PR`:`PR #${String(e.number)}`}function isDryRun(e){return e.action===`would-create`||e.action===`would-update`}function formatPrCreate(e){let t=e.action===`created`||e.action===`would-create`;if(isDryRun(e)){let n=t?`create`:`update`;return{lines:[`[dry-run] Would push ${prTarget(e)} and ${n} its PR: ${e.title}`],body:{heading:`[dry-run] Body`,text:e.body}}}let n=[`${t?`Created`:`Updated`} ${prLabel(e)} (${prTarget(e)})`];return e.url!==null&&n.push(e.url),{lines:n,body:null}}function formatPrUpdate(e,t,n){let r=e.closesAdded??[];if(isDryRun(e))return{lines:[`[dry-run] Would push ${prTarget(e)} to ${prLabel(e)}`],body:{heading:t||r.length>0?`[dry-run] Body`:`[dry-run] Body (unchanged)`,text:e.body}};let i=[`Updated ${prLabel(e)} (${prTarget(e)})`];return r.length>0?i.push(`Linked ${r.map(e=>`#${String(e)}`).join(`, `)} with a Closes line.`):t||i.push(`Title and body left as authored -- pass ${n.title}/${n.body} to change them.`),e.url!==null&&i.push(e.url),{lines:i,body:null}}const tl={create:`pnpm exec bst pr:create`,update:`pnpm exec bst pr:update`},nl={closes:`--closes`,allowUnlink:`--allow-unlink`};function executorGit(e){return{run:(t,{cwd:n,env:r,timeoutMs:i,signal:a})=>e.execStream(`git`,[...t],r===void 0?{cwd:n,timeoutMs:i,signal:a}:{cwd:n,env:r,timeoutMs:i,signal:a})}}async function runPrUpsert(e,t){let{connection:n,verbose:r,...i}=t,a=n.type===`forgejo`?forgejoPrHost(e,n.conn):githubPrHost(e,t.cwd,t.signal??null),o=loadToolingConfig(t.cwd)?.defaultBranch;try{return await runPrUpsert$1(executorGit(e),a,{...i,...o===void 0?{}:{defaultBranchOverride:o},onResolved:({mode:e,branch:t,base:i})=>{debug({verbose:r},`pr:${e} ${t} (diff base ${i}, ${n.type})`)},onClosingLinks:warnClosingLinks})}catch(e){throw rewordPrUpsertError(e,{commands:tl,flags:nl,warn:e=>{F.warn(e)}})}}function warnClosingLinks(e){for(let t of describeClosingLinks(e,nl))F.warn(t)}function tryRead(e,t){try{return e()}catch(e){throw new T(`Could not read ${t}: ${ie(e)}`)}}function readBodySource(e,t,n={}){let r=n.flags??{text:`--body`,file:`--body-file`};if(e!==void 0&&t!==void 0)throw new T(`Pass either ${r.text} or ${r.file}, not both.`);if(e!==void 0)return e;if(t!==void 0){if(t===`-`)return tryRead(n.readStdin??(()=>p(0,`utf-8`)),`stdin`);if(!o(t))throw new T(`${r.file} not found: ${t}`);return tryRead(()=>p(t,`utf-8`),`${r.file} "${t}"`)}}function unclaimedLine(e){return`#${String(e)} is not claimed, and the agent can take it. Run pnpm exec bst work:start ${String(e)} before you work it.`}function agentLine(e,t,n){let r=`pnpm exec bst work:start ${String(e)}`,i=`Check with whoever drives the agent before you go on.`;return n===`running`?`#${String(e)} is running under the agent (${t}). ${i}`:n===`queued`?`#${String(e)} has a run queued on it by the agent (${t}). ${i}`:`#${String(e)} is parked by the agent at ${t}, and nothing runs there until a person acts. Run ${r} to claim it beside the terminal.`}async function classifyClosedIssues(e,t){let n=[],r=[];for(let i of e){let e;try{e=await t(i)}catch(e){n.push({issue:i,owner:null}),r.push(`The claim state of #${String(i)} could not be read: ${O(e)}.`);continue}let a=ownerOf(e);a.owner===`agent`?(n.push({issue:i,owner:`agent`,label:a.label}),r.push(agentLine(i,a.label,a.hold))):(n.push({issue:i,owner:a.owner}),a.owner===`unclaimed`&&r.push(unclaimedLine(i)))}return{claims:n,lines:r}}async function readClosedIssueClaims(e,t){let{cwd:n,connection:r,body:i}=t;if(r.type!==`forgejo`)return null;let a=r.conn.repository,o=closedIssueNumbers(i,a);if(o.length===0)return null;try{let t=await createWorkGit(e,n);if(!(await readAgentConsent(t,resolveDefaultBranch({cwd:t.topLevel}))).enabled)return null;let i=workForgeFromConnection(e,r.conn);return await classifyClosedIssues(o,async e=>(await i.view(e)).labels)}catch(e){return debug({verbose:isEnvVerbose()},`pr:create claim check skipped: ${O(e)}`),null}}const rl=A({meta:{name:`pr:create`,description:`Push the current branch and open its pull request. Refuses to run on main, master or the default branch.`},args:{title:{type:`string`,description:`PR title (default: derived from the branch's commits)`},body:{type:`string`,description:`PR body (default: a list of the branch's commits)`},"body-file":{type:`string`,description:`Read the PR body from a file ('-' for stdin)`},base:{type:`string`,description:`Base branch for a new PR (default: the repo's default branch); with --upsert on an already-open PR it selects only the diff range`},draft:{type:`boolean`,description:`Open the PR as a draft`},upsert:{type:`boolean`,description:`Update the PR instead of failing when the branch already has one open`},"allow-unlink":{type:`boolean`,description:`With --upsert: permit a --body that drops a closing keyword the PR carries`},closes:{type:`string`,description:`Issues the PR closes, comma-separated (12 or 12,15): adds a Closes #<n> line to the body for each one it does not already close`},"dry-run":{type:`boolean`,description:`Show what would happen without pushing`},json:{type:`boolean`,description:`Emit one JSON document: action (created | updated | would-create | would-update), number (or null), url (or null), branch, base, title, body, droppedRefs? ([{text, issue}]), closesAdded? (with --closes: the issues it added a Closes line for), dryRun, claims? ([{issue, owner: unclaimed | agent | person | null, label?}]) -- present after a create in an agent-enabled Forgejo repo whose body closes an issue; owner null means the labels could not be read. bst pr:create is the one command that reports claims; bst-fj pr:create does not. A create or would-create carries droppedRefs; on a dry run, number and url are null.`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:e}){let t=createCliOutput(e.json===!0),n=readBodySource(e.body??void 0,e[`body-file`]??void 0),r=createRealExecutor$1(),i=resolveConnection(process.cwd()),a=await runPrUpsert(r,{cwd:process.cwd(),connection:i,mode:e.upsert===!0?`upsert`:`create`,title:e.title??void 0,body:n,base:e.base??void 0,allowUnlink:e[`allow-unlink`]===!0,closes:e.closes===void 0?void 0:parseIssueList(e.closes),draft:e.draft===!0||void 0,dryRun:e[`dry-run`]===!0,verbose:e.verbose===!0||isEnvVerbose()}),o=a.action===`created`?await readClosedIssueClaims(r,{cwd:process.cwd(),connection:i,body:a.body}):null;t.json({...a,dryRun:e[`dry-run`]===!0,...o===null?{}:{claims:o.claims}});let s=formatPrCreate(a);for(let e of s.lines)F.info(e);if(s.body!==null&¬e(s.body.text,s.body.heading),o!==null)for(let e of o.lines)F.warn(e)}});function isOpen(e){return e.state===`open`&&e.merged===!1}function notOpenMessage(e,t){let n=`#${String(e)}`;return t.merged?`Pull request ${n} is merged, so it has no base or draft state left to change.`:`Pull request ${n} is ${t.state}, so it has no base or draft state left to change. Run \`pr:reopen ${String(e)}\` first if this work is still live.`}async function runPrRetarget(e,t){let n=await e.readLive(t.number);if(!isOpen(n))throw new T(notOpenMessage(t.number,n));if(t.base===n.head)throw new T(`Pull request #${String(t.number)} cannot target its own head branch "${t.base}" -- choose a branch it is meant to merge into.`);if(t.base===n.base)return{action:`unchanged`,number:t.number,url:n.url,previousBase:n.base,base:n.base,head:n.head,mergeable:n.mergeable,dryRun:t.dryRun};if(!await e.branchExists(t.base))throw new T(`Branch "${t.base}" does not exist in this repository, so pull request #${String(t.number)} cannot target it -- push the branch, or pass a base the forge has.`);if(t.dryRun)return{action:`would-retarget`,number:t.number,url:n.url,previousBase:n.base,base:t.base,head:n.head,mergeable:n.mergeable,dryRun:!0};await e.setBase(t.number,t.base);let r=await e.readLive(t.number);if(r.base!==t.base)throw new T(`Pull request #${String(t.number)} still reports its base as "${r.base}" after the request to move it to "${t.base}" -- this forge accepted the field and ignored it, so change the base in its web interface.`);let i=r.mergeable;return i===!1&&(await t.sleep(t.recheckDelayMs),i=(await e.readLive(t.number)).mergeable),{action:`retargeted`,number:t.number,url:r.url,previousBase:n.base,base:t.base,head:n.head,mergeable:i,dryRun:!1}}async function runPrReady(e,t){let n=await e.readLive(t.number);if(!isOpen(n))throw new T(notOpenMessage(t.number,n));let r=t.title;if(r!==void 0){if(r.trim()===``)throw new T(`--title is empty -- pass the title to write, or omit --title to drop the WIP marker from pull request #${String(t.number)}'s current title.`);if(hasWipPrefix(r)){let t=e.wipTitles?`which on this forge keeps the pull request a draft`:`so the pull request would still read as work in progress`;throw new T(`--title ${JSON.stringify(r)} carries a WIP marker, ${t} -- pass the title you want it to read without one.`)}}let i=r??stripWipPrefix(n.title);if(i.trim()===``)throw new T(`Pull request #${String(t.number)} would be left with an empty title, which neither forge accepts -- pass --title with the title to write.`);if(e.wipTitles&&n.draft&&r===void 0&&!hasWipPrefix(n.title))throw new T(`Pull request #${String(t.number)} is a draft and its title ${JSON.stringify(n.title)} carries no WIP marker this tool recognises, so there is nothing to strip -- pass --title "<title>" to write the title that clears the draft.`);let a=i!==n.title;if(!n.draft&&!a)return{action:`already-ready`,number:t.number,url:n.url,previousTitle:n.title,title:n.title,draft:n.draft,dryRun:t.dryRun};if(t.dryRun)return{action:n.draft?`would-ready`:`would-retitle`,number:t.number,url:n.url,previousTitle:n.title,title:i,draft:n.draft,dryRun:!0};await e.ready(t.number,{draft:n.draft,title:i,titleChanged:a});let o=await e.readLive(t.number);if(o.draft)throw new T(`Pull request #${String(t.number)} is still a draft after the title ${JSON.stringify(i)} was written -- its draft state is set by something other than the title, so clear it in the forge's interface.`);return{action:n.draft?`readied`:`retitled`,number:t.number,url:o.url,previousTitle:n.title,title:o.title,draft:o.draft,dryRun:!1}}async function runPrReopen(e,t){let n=await e.readLive(t.number);if(n.merged===!0)throw new T(`Pull request #${String(t.number)} was merged, so there is nothing to reopen -- open a new pull request for further work.`);if(n.state===`open`)return{action:`already-open`,number:t.number,url:n.url,title:n.title,head:n.head,base:n.base,draft:n.draft,dryRun:t.dryRun};if(n.state!==`closed`)throw new T(`Pull request #${String(t.number)} reports the state "${n.state}", which this command has no rule for -- it reopens a pull request reported as closed, and guesses at no state it did not expect.`);if(t.dryRun)return{action:`would-reopen`,number:t.number,url:n.url,title:n.title,head:n.head,base:n.base,draft:n.draft,dryRun:!0};await e.reopen(t.number);let r=await e.readLive(t.number);if(!isOpen(r))throw new T(`Pull request #${String(t.number)} still reports \`${r.state}\` after the request to reopen it -- reopen it in the forge's web interface.`);return{action:`reopened`,number:t.number,url:r.url,title:r.title,head:r.head,base:r.base,draft:r.draft,dryRun:!1}}function mergeabilityLine(e){return e===!0?`Mergeability: mergeable.`:e===!1?`Mergeability: not mergeable -- advice, not a verdict.`:`Mergeability: unknown -- the forge has not computed it.`}function renderPrRetarget(e){let t=`#${String(e.number)}`,n=[];return e.action===`retargeted`?n.push(`Pull request ${t} now targets "${e.base}" (was "${e.previousBase}").`):e.action===`unchanged`?n.push(`Pull request ${t} already targets "${e.base}".`):n.push(`Dry run: pull request ${t} would move from "${e.previousBase}" to "${e.base}".`),n.push(mergeabilityLine(e.mergeable)),n.join(`
|
|
6098
|
+
`)}`,droppedRefs:[]}}var PrModeError=class extends T{reason;branch;existing;numbers;mode;constructor(e,t,n,r=[],i=null){super(prModeMessage(e,t,n,r)),this.reason=e,this.branch=t,this.existing=n,this.numbers=[...r],this.mode=i}};function prModeMessage(e,t,n,r){if(e===`already-open`)return`${t} already has an open PR (#${String(n)}).`;if(e===`several-open`){let e=r.map(e=>`#${String(e)}`).join(`, `);return`${t} has ${String(r.length)} open PRs (${e}), so there is no way to tell which one to update.`}return e===`not-branch-pr`?`#${String(n)} is not an open PR of ${t}.`:`${t} has no open PR to update.`}function choosePrForMode(e,t,n,r){let i=t.map(e=>e.number),a=t[0];if(e===`create`&&a!==void 0)throw new PrModeError(`already-open`,n,a.number,i,e);if(r!==void 0){let a=t.find(e=>e.number===r);if(a===void 0)throw new PrModeError(`not-branch-pr`,n,r,i,e);return refuseBaseless(a,n)}if(e===`update`&&t.length===0)throw new PrModeError(`none-open`,n,null,i,e);if(t.length>1)throw new PrModeError(`several-open`,n,null,i,e);return a===void 0?null:refuseBaseless(a,n)}function refuseBaseless(e,t){if(e.base===null)throw new D(`Open PR #${String(e.number)} on ${t} carries no base branch`);return e}function prUpdateNeedsLive(e){return e.title===void 0||e.body===void 0||e.draft===void 0||e.managedBodyMarkers!==void 0}function planPrUpdate(e,t,n,r){if(e.managedBodyMarkers!==void 0&&n!==null)return planManagedUpdate(e,t,n,r);let i=e.title===void 0?void 0:t.title,a={...i===void 0?{}:{title:r&&e.draft===void 0&&n!==null?keepWipPrefix(n.title,i):i},...e.body===void 0?{}:{body:t.body}};return{patch:a,effective:{title:a.title??n?.title??``,body:a.body??n?.body??``},previousBody:n?.body??null}}function planManagedUpdate(e,t,n,r){let i=(e.managedBodyMarkers??[]).some(e=>n.body.startsWith(e)),a=i&&e.title!==void 0,o=i&&e.body!==void 0,s;s=a?e.draft===void 0&&r?keepWipPrefix(n.title,t.title):t.title:reconcileWipTitle(r,e.draft,n.title);let c=o?carryForwardClosingRefs(n.body,t.body):carryForwardClosingRefs(t.body,n.body);return{patch:{...s===n.title?{}:{title:s},...c===n.body?{}:{body:c}},effective:{title:s,body:c},previousBody:n.body}}function reconcileWipTitle(e,t,n){if(!e||t===void 0)return n;if(t)return hasWipPrefix(n)?n:`WIP: ${n}`;let r=stripWipPrefix(n);return r===``?(U.warn(`Preserving PR title ${JSON.stringify(n)}: stripping its WIP prefix would leave it empty -- retitle it by hand.`),n):r}function keepWipPrefix(e,t){return hasWipPrefix(e)&&!hasWipPrefix(t)?`WIP: ${t}`:t}var LostClosingRefsError=class extends T{lost;fromCommits;constructor(e,t){super(`This update would remove ${e.map(e=>e.text).join(`, `)} from the PR body, and the new body does not close it.`),this.lost=e,this.fromCommits=t}};function checkClosingLinks(e,t,n){let r=droppedClosingRefs(e,t.effective.body);if(t.previousBody===null)return{fromCommits:r,unlinked:[]};let i=droppedClosingRefs([t.previousBody],t.effective.body);if(i.length>0&&!n)throw new LostClosingRefsError(i,r);return{fromCommits:r,unlinked:i}}function addClosingIssues(e,t){let n=t.map(e=>`Closes #${String(e)}`).join(`
|
|
6099
|
+
`),r=droppedClosingRefs([n],e.effective.body).map(e=>Number(e.issue.slice(1)));if(r.length===0)return{plan:e,added:r};let i=carryForwardClosingRefs(n,e.effective.body);return{plan:{...e,patch:{...e.patch,body:i},effective:{...e.effective,body:i}},added:r}}async function planUpsert(e,t,n,r){let i;if(i=t===null?{patch:{title:n.title,body:n.body},effective:n,previousBody:null}:planPrUpdate(r,n,prUpdateNeedsLive(r)?await e.readLive(t,r.signal??null):null,e.wipTitles),r.closes===void 0)return{plan:i,closesAdded:void 0};let a=addClosingIssues(i,r.closes);return{plan:a.plan,closesAdded:a.added}}async function runPrUpsert$1(e,t,n){let{cwd:r}=n,i=n.mode??`upsert`,a=n.signal??null,o=await currentBranch(e,r,a),s=await refuseProtectedBranch(e,{cwd:r,branch:o,...n.defaultBranchOverride===void 0?{}:{defaultBranchOverride:n.defaultBranchOverride},signal:a},e=>`Refusing to open a PR from the protected branch "${e}" -- create a branch first.`),c=n.base??s,l=await baseRef(e,r,c,a),u=await commitSubjects(e,r,l,a);if(u.length===0)throw new T(`No commits on ${o} that are not already on ${c}.`);let d=await commitMessages(e,r,l,a);await hasUncommittedChanges(e,r,a)&&U.warn(`Working tree has uncommitted changes -- they will not be part of this PR.`);let f=derivePrContent({branch:o,subjects:u,messages:d,title:n.title,body:n.body,draft:n.draft===!0,wipTitles:t.wipTitles});n.onResolved?.({mode:i,branch:o,base:c});let p=choosePrForMode(i,await t.listForBranch(o,`open`,a),o,n.expectedNumber),m=p?.number??null;!n.dryRun&&n.skipPush!==!0&&await pushBranch(e,r,o,n.pushEnv,n.forceWithLease);let{plan:h,closesAdded:g}=await planUpsert(t,m,f,n),_=checkClosingLinks(d,h,n.allowUnlink===!0);n.onClosingLinks?.(_);let v={branch:o,base:p?.base??c,...h.effective,...g===void 0?{}:{closesAdded:g}};if(n.dryRun)return{action:m===null?`would-create`:`would-update`,number:null,url:null,...v};if(m===null){let e=await t.create(v,n.draft);return{action:`created`,number:e.number,url:e.url,...v}}return{action:`updated`,number:m,url:(await t.update(m,h.patch,n.draft)).url,...v}}function describePrModeError(e,t){if(e.reason===`already-open`){let n=t.create.split(` `).at(-1)??t.create;return`${e.branch} already has an open PR (#${String(e.existing)}) -- use \`${t.update}\` to push new commits to it. (${n} refuses rather than rewrite its title and body from the branch's commits, which is how an authored description gets replaced by "${humanizeBranch(e.branch)}".)`}if(e.reason===`several-open`){let n=e.numbers.map(e=>`#${String(e)}`).join(`, `);return e.mode===`upsert`?`${e.branch} has ${String(e.numbers.length)} open PRs, so nothing can tell which one to update -- close all but one of ${n}, or pass NUMBER to \`${t.update}\` by hand.`:`${e.branch} has ${String(e.numbers.length)} open PRs (${n}), so nothing can tell which one to update -- pass one NUMBER to \`${t.update}\`.`}return e.reason===`not-branch-pr`?`#${String(e.existing)} is not an open PR of ${e.branch} -- ${describeBranchPrs(e.numbers)}. Update the branch's own PR, or run \`${t.create}\` to open one.`:`${e.branch} has no open PR to update -- use \`${t.create}\` to open one.`}function describeBranchPrs(e){return e.length===0?`it has none`:`it has ${e.map(e=>`#${String(e)}`).join(`, `)}`}function describeClosingLinks(e,t){let n=[];if(e.fromCommits.length>0){let r=e.fromCommits.map(e=>e.text).join(`, `);n.push(`The commits say ${r}, but the PR body does not -- the issue may not close on merge. Link it with ${t.closes}.`)}if(e.unlinked.length>0){let r=e.unlinked.map(e=>e.text).join(`, `);n.push(`${t.allowUnlink}: dropping ${r} from the PR body as instructed.`)}return n}function describeLostClosingRefs(e,t){return`Refusing to update: this would remove ${e.lost.map(e=>e.text).join(`, `)} from the PR body, and the new body does not close it -- the issue would stay open when the PR merges, and nothing else reports that. Keep the line in the body you are passing, or pass ${t.allowUnlink} if the PR really should stop closing it.`}function rewordPrUpsertError(e,t){if(e instanceof PrModeError)return new T(describePrModeError(e,t.commands));if(e instanceof LostClosingRefsError){let n={fromCommits:e.fromCommits,unlinked:[]};for(let e of describeClosingLinks(n,t.flags))t.warn(e);return new T(describeLostClosingRefs(e,t.flags))}return e}function prTarget(e){return`${e.branch} -> ${e.base}`}function prLabel(e){return e.number===null?`PR`:`PR #${String(e.number)}`}function isDryRun(e){return e.action===`would-create`||e.action===`would-update`}function formatPrCreate(e){let t=e.action===`created`||e.action===`would-create`;if(isDryRun(e)){let n=t?`create`:`update`;return{lines:[`[dry-run] Would push ${prTarget(e)} and ${n} its PR: ${e.title}`],body:{heading:`[dry-run] Body`,text:e.body}}}let n=[`${t?`Created`:`Updated`} ${prLabel(e)} (${prTarget(e)})`];return e.url!==null&&n.push(e.url),{lines:n,body:null}}function formatPrUpdate(e,t,n){let r=e.closesAdded??[];if(isDryRun(e))return{lines:[`[dry-run] Would push ${prTarget(e)} to ${prLabel(e)}`],body:{heading:t||r.length>0?`[dry-run] Body`:`[dry-run] Body (unchanged)`,text:e.body}};let i=[`Updated ${prLabel(e)} (${prTarget(e)})`];return r.length>0?i.push(`Linked ${r.map(e=>`#${String(e)}`).join(`, `)} with a Closes line.`):t||i.push(`Title and body left as authored -- pass ${n.title}/${n.body} to change them.`),e.url!==null&&i.push(e.url),{lines:i,body:null}}const kl={create:`pnpm exec bst pr:create`,update:`pnpm exec bst pr:update`},Al={closes:`--closes`,allowUnlink:`--allow-unlink`};function executorGit(e){return{run:(t,{cwd:n,env:r,timeoutMs:i,signal:a})=>e.execStream(`git`,[...t],r===void 0?{cwd:n,timeoutMs:i,signal:a}:{cwd:n,env:r,timeoutMs:i,signal:a})}}async function runPrUpsert(e,t){let{connection:n,verbose:r,...i}=t,a=n.type===`forgejo`?forgejoPrHost(e,n.conn):githubPrHost(e,t.cwd,t.signal??null),o=loadToolingConfig(t.cwd)?.defaultBranch;try{return await runPrUpsert$1(executorGit(e),a,{...i,...o===void 0?{}:{defaultBranchOverride:o},onResolved:({mode:e,branch:t,base:i})=>{debug({verbose:r},`pr:${e} ${t} (diff base ${i}, ${n.type})`)},onClosingLinks:warnClosingLinks})}catch(e){throw rewordPrUpsertError(e,{commands:kl,flags:Al,warn:e=>{I.warn(e)}})}}function warnClosingLinks(e){for(let t of describeClosingLinks(e,Al))I.warn(t)}function tryRead(e,t){try{return e()}catch(e){throw new T(`Could not read ${t}: ${O(e)}`)}}function readBodySource(e,t,n={}){let r=n.flags??{text:`--body`,file:`--body-file`};if(e!==void 0&&t!==void 0)throw new T(`Pass either ${r.text} or ${r.file}, not both.`);if(e!==void 0)return e;if(t!==void 0){if(t===`-`)return tryRead(n.readStdin??(()=>p(0,`utf-8`)),`stdin`);if(!o(t))throw new T(`${r.file} not found: ${t}`);return tryRead(()=>p(t,`utf-8`),`${r.file} "${t}"`)}}function unclaimedLine(e){return`#${String(e)} is not claimed, and the agent can take it. Run pnpm exec bst work:start ${String(e)} before you work it.`}function agentLine(e,t,n){let r=`pnpm exec bst work:start ${String(e)}`,i=`Check with whoever drives the agent before you go on.`;return n===`running`?`#${String(e)} is running under the agent (${t}). ${i}`:n===`queued`?`#${String(e)} has a run queued on it by the agent (${t}). ${i}`:`#${String(e)} is parked by the agent at ${t}, and nothing runs there until a person acts. Run ${r} to claim it beside the terminal.`}async function classifyClosedIssues(e,t){let n=[],r=[];for(let i of e){let e;try{e=await t(i)}catch(e){n.push({issue:i,owner:null}),r.push(`The claim state of #${String(i)} could not be read: ${k(e)}.`);continue}let a=ownerOf(e);a.owner===`agent`?(n.push({issue:i,owner:`agent`,label:a.label}),r.push(agentLine(i,a.label,a.hold))):(n.push({issue:i,owner:a.owner}),a.owner===`unclaimed`&&r.push(unclaimedLine(i)))}return{claims:n,lines:r}}async function readClosedIssueClaims(e,t){let{cwd:n,connection:r,body:i}=t;if(r.type!==`forgejo`)return null;let a=r.conn.repository,o=closedIssueNumbers(i,a);if(o.length===0)return null;try{let t=await createWorkGit(e,n);if(!(await readAgentConsent(t,resolveDefaultBranch({cwd:t.topLevel}))).enabled)return null;let i=workForgeFromConnection(e,r.conn);return await classifyClosedIssues(o,async e=>(await i.view(e)).labels)}catch(e){return debug({verbose:isEnvVerbose()},`pr:create claim check skipped: ${k(e)}`),null}}const jl=j({meta:{name:`pr:create`,description:`Push the current branch and open its pull request. Refuses to run on main, master or the default branch.`},args:{title:{type:`string`,description:`PR title (default: derived from the branch's commits)`},body:{type:`string`,description:`PR body (default: a list of the branch's commits)`},"body-file":{type:`string`,description:`Read the PR body from a file ('-' for stdin)`},base:{type:`string`,description:`Base branch for a new PR (default: the repo's default branch); with --upsert on an already-open PR it selects only the diff range`},draft:{type:`boolean`,description:`Open the PR as a draft`},upsert:{type:`boolean`,description:`Update the PR instead of failing when the branch already has one open`},"allow-unlink":{type:`boolean`,description:`With --upsert: permit a --body that drops a closing keyword the PR carries`},closes:{type:`string`,description:`Issues the PR closes, comma-separated (12 or 12,15): adds a Closes #<n> line to the body for each one it does not already close`},"dry-run":{type:`boolean`,description:`Show what would happen without pushing`},json:{type:`boolean`,description:`Emit one JSON document: action (created | updated | would-create | would-update), number (or null), url (or null), branch, base, title, body, droppedRefs? ([{text, issue}]), closesAdded? (with --closes: the issues it added a Closes line for), dryRun, claims? ([{issue, owner: unclaimed | agent | person | null, label?}]) -- present after a create in an agent-enabled Forgejo repo whose body closes an issue; owner null means the labels could not be read. bst pr:create is the one command that reports claims; bst-fj pr:create does not. A create or would-create carries droppedRefs; on a dry run, number and url are null.`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:e}){let t=createCliOutput(e.json===!0),n=readBodySource(e.body??void 0,e[`body-file`]??void 0),r=createRealExecutor$1(),i=resolveConnection(process.cwd()),a=await runPrUpsert(r,{cwd:process.cwd(),connection:i,mode:e.upsert===!0?`upsert`:`create`,title:e.title??void 0,body:n,base:e.base??void 0,allowUnlink:e[`allow-unlink`]===!0,closes:e.closes===void 0?void 0:parseIssueList(e.closes),draft:e.draft===!0||void 0,dryRun:e[`dry-run`]===!0,verbose:e.verbose===!0||isEnvVerbose()}),o=a.action===`created`?await readClosedIssueClaims(r,{cwd:process.cwd(),connection:i,body:a.body}):null;t.json({...a,dryRun:e[`dry-run`]===!0,...o===null?{}:{claims:o.claims}});let s=formatPrCreate(a);for(let e of s.lines)I.info(e);if(s.body!==null&¬e(s.body.text,s.body.heading),o!==null)for(let e of o.lines)I.warn(e)}});function isOpen(e){return e.state===`open`&&e.merged===!1}function notOpenMessage(e,t){let n=`#${String(e)}`;return t.merged?`Pull request ${n} is merged, so it has no base or draft state left to change.`:`Pull request ${n} is ${t.state}, so it has no base or draft state left to change. Run \`pr:reopen ${String(e)}\` first if this work is still live.`}async function runPrRetarget(e,t){let n=await e.readLive(t.number);if(!isOpen(n))throw new T(notOpenMessage(t.number,n));if(t.base===n.head)throw new T(`Pull request #${String(t.number)} cannot target its own head branch "${t.base}" -- choose a branch it is meant to merge into.`);if(t.base===n.base)return{action:`unchanged`,number:t.number,url:n.url,previousBase:n.base,base:n.base,head:n.head,mergeable:n.mergeable,dryRun:t.dryRun};if(!await e.branchExists(t.base))throw new T(`Branch "${t.base}" does not exist in this repository, so pull request #${String(t.number)} cannot target it -- push the branch, or pass a base the forge has.`);if(t.dryRun)return{action:`would-retarget`,number:t.number,url:n.url,previousBase:n.base,base:t.base,head:n.head,mergeable:n.mergeable,dryRun:!0};await e.setBase(t.number,t.base);let r=await e.readLive(t.number);if(r.base!==t.base)throw new T(`Pull request #${String(t.number)} still reports its base as "${r.base}" after the request to move it to "${t.base}" -- this forge accepted the field and ignored it, so change the base in its web interface.`);let i=r.mergeable;return i===!1&&(await t.sleep(t.recheckDelayMs),i=(await e.readLive(t.number)).mergeable),{action:`retargeted`,number:t.number,url:r.url,previousBase:n.base,base:t.base,head:n.head,mergeable:i,dryRun:!1}}async function runPrReady(e,t){let n=await e.readLive(t.number);if(!isOpen(n))throw new T(notOpenMessage(t.number,n));let r=t.title;if(r!==void 0){if(r.trim()===``)throw new T(`--title is empty -- pass the title to write, or omit --title to drop the WIP marker from pull request #${String(t.number)}'s current title.`);if(hasWipPrefix(r)){let t=e.wipTitles?`which on this forge keeps the pull request a draft`:`so the pull request would still read as work in progress`;throw new T(`--title ${JSON.stringify(r)} carries a WIP marker, ${t} -- pass the title you want it to read without one.`)}}let i=r??stripWipPrefix(n.title);if(i.trim()===``)throw new T(`Pull request #${String(t.number)} would be left with an empty title, which neither forge accepts -- pass --title with the title to write.`);if(e.wipTitles&&n.draft&&r===void 0&&!hasWipPrefix(n.title))throw new T(`Pull request #${String(t.number)} is a draft and its title ${JSON.stringify(n.title)} carries no WIP marker this tool recognises, so there is nothing to strip -- pass --title "<title>" to write the title that clears the draft.`);let a=i!==n.title;if(!n.draft&&!a)return{action:`already-ready`,number:t.number,url:n.url,previousTitle:n.title,title:n.title,draft:n.draft,dryRun:t.dryRun};if(t.dryRun)return{action:n.draft?`would-ready`:`would-retitle`,number:t.number,url:n.url,previousTitle:n.title,title:i,draft:n.draft,dryRun:!0};await e.ready(t.number,{draft:n.draft,title:i,titleChanged:a});let o=await e.readLive(t.number);if(o.draft)throw new T(`Pull request #${String(t.number)} is still a draft after the title ${JSON.stringify(i)} was written -- its draft state is set by something other than the title, so clear it in the forge's interface.`);return{action:n.draft?`readied`:`retitled`,number:t.number,url:o.url,previousTitle:n.title,title:o.title,draft:o.draft,dryRun:!1}}async function runPrReopen(e,t){let n=await e.readLive(t.number);if(n.merged===!0)throw new T(`Pull request #${String(t.number)} was merged, so there is nothing to reopen -- open a new pull request for further work.`);if(n.state===`open`)return{action:`already-open`,number:t.number,url:n.url,title:n.title,head:n.head,base:n.base,draft:n.draft,dryRun:t.dryRun};if(n.state!==`closed`)throw new T(`Pull request #${String(t.number)} reports the state "${n.state}", which this command has no rule for -- it reopens a pull request reported as closed, and guesses at no state it did not expect.`);if(t.dryRun)return{action:`would-reopen`,number:t.number,url:n.url,title:n.title,head:n.head,base:n.base,draft:n.draft,dryRun:!0};await e.reopen(t.number);let r=await e.readLive(t.number);if(!isOpen(r))throw new T(`Pull request #${String(t.number)} still reports \`${r.state}\` after the request to reopen it -- reopen it in the forge's web interface.`);return{action:`reopened`,number:t.number,url:r.url,title:r.title,head:r.head,base:r.base,draft:r.draft,dryRun:!1}}function mergeabilityLine(e){return e===!0?`Mergeability: mergeable.`:e===!1?`Mergeability: not mergeable -- advice, not a verdict.`:`Mergeability: unknown -- the forge has not computed it.`}function renderPrRetarget(e){let t=`#${String(e.number)}`,n=[];return e.action===`retargeted`?n.push(`Pull request ${t} now targets "${e.base}" (was "${e.previousBase}").`):e.action===`unchanged`?n.push(`Pull request ${t} already targets "${e.base}".`):n.push(`Dry run: pull request ${t} would move from "${e.previousBase}" to "${e.base}".`),n.push(mergeabilityLine(e.mergeable)),n.join(`
|
|
6096
6100
|
`)}function renderPrReady(e){let t=`#${String(e.number)}`;return e.action===`readied`?`Pull request ${t} is no longer a draft, reading as "${e.title}".`:e.action===`retitled`?`Pull request ${t} now reads "${e.title}".`:e.action===`already-ready`?`Pull request ${t} is already ready and reads "${e.title}".`:e.action===`would-ready`?`Dry run: pull request ${t} would stop being a draft, reading "${e.title}".`:`Dry run: pull request ${t} would read "${e.title}".`}function renderPrReopen(e){let t=`#${String(e.number)}`;if(e.action===`reopened`){let n=[`Pull request ${t} is open again (head "${e.head}" -> "${e.base}").`];return e.draft&&n.push(`It is still a draft -- run pr:ready ${String(e.number)} when it is ready for review.`),n.join(`
|
|
6097
|
-
`)}return e.action===`already-open`?`Pull request ${t} is already open.`:`Dry run: pull request ${t} would be reopened.`}function parsePrNumber(e){let t=Number(e);if(!/^\d+$/.test(e)||!Number.isSafeInteger(t)||t<1)throw new T(`Invalid pull request number "${e}" (expected a positive integer).`);return t}function resolvePrEditTarget(e,t,n){let r=resolveIssueTransport(e,t,parseRepoTarget(n));if(r.target.hostname===`github.com`)return{host:githubPrEditHost(e,t,r.target.repository),issues:r.api};if(r.conn===void 0)throw new D(`Resolved a non-github.com target (${r.target.hostname}) with no Forgejo connection.`);return{host:forgejoPrEditHost(e,r.conn),issues:r.api}}function resolvePrEditHost(e,t,n){return resolvePrEditTarget(e,t,n).host}async function resolvePrEditNumber(e,t,n,r,i){if(r!==void 0)return{number:parsePrNumber(r),autodetected:!1};let a=loadToolingConfig(t)?.defaultBranch;return{number:(await resolveBranchPr$1(executorGit(e),n,{cwd:t,state:i,...a===void 0?{}:{defaultBranchOverride:a},signal:null})).number,autodetected:!0}}const il=A({meta:{name:`pr:ready`,description:`Mark a draft pull request ready, dropping one WIP: prefix or taking --title, and confirm the forge no longer reports a draft, on Forgejo or GitHub`},args:{number:{type:`positional`,required:!1,description:`Pull request number (default: the current branch's open pull request)`},title:{type:`string`,description:`Write this title instead of stripping the WIP prefix from the current one`},repo:{type:`string`,description:`Repository URL (default: this repo)`},"dry-run":{type:`boolean`,description:`Run every read and report, but do not write`},json:{type:`boolean`,description:`Emit one JSON document: action (readied | retitled | already-ready | would-ready | would-retitle), number, url, previousTitle, title, draft, dryRun; a refusal is an error, never this document.`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:e}){let t=createCliOutput(e.json===!0);refuseRepoWithoutNumber(e.number,e.repo);let n=createRealExecutor$1(),r=resolvePrEditHost(n,process.cwd(),e.repo??void 0),{number:i}=await resolvePrEditNumber(n,process.cwd(),r,e.number,`open`),a=await runPrReady(r,{number:i,title:e.title??void 0,dryRun:e[`dry-run`]===!0});t.json(a),t.text(renderPrReady(a))}}),al=A({meta:{name:`pr:reopen`,description:`Reopen a closed, unmerged pull request and confirm the forge reports it open, on Forgejo or GitHub. An already-open pull request is reported without writing; a merged one, or an issue, is refused`},args:{number:{type:`positional`,required:!1,description:`Pull request number (default: the current branch's closed pull request)`},repo:{type:`string`,description:`Repository URL (default: this repo)`},"dry-run":{type:`boolean`,description:`Run every read and report, but do not write`},json:{type:`boolean`,description:`Emit one JSON document: action (reopened | already-open | would-reopen), number, url, title, head, base, draft, dryRun; a refusal is an error, never this document.`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:e}){let t=createCliOutput(e.json===!0);refuseRepoWithoutNumber(e.number,e.repo);let n=createRealExecutor$1(),{host:r,issues:i}=resolvePrEditTarget(n,process.cwd(),e.repo??void 0),{number:a,autodetected:o}=await resolvePrEditNumber(n,process.cwd(),r,e.number,`closed-unmerged`);if(!o&&!(await i.get(a)).isPullRequest)throw new T(`#${String(a)} is an issue, not a pull request -- pr:reopen refuses to write issue state. Use \`pnpm exec bst issue:reopen ${String(a)}\` to reopen it.`);let s=await runPrReopen(r,{number:a,dryRun:e[`dry-run`]===!0});t.json(s),t.text(renderPrReopen(s))}}),ol=A({meta:{name:`pr:retarget`,description:`Change an open pull request's base branch, confirm the forge took it, and report its mergeability as advice on Forgejo or GitHub`},args:{number:{type:`positional`,required:!1,description:`Pull request number (default: the current branch's open pull request)`},base:{type:`string`,required:!0,description:`The branch to retarget the pull request onto`},repo:{type:`string`,description:`Repository URL (default: this repo)`},"dry-run":{type:`boolean`,description:`Run every read and report, but do not write`},json:{type:`boolean`,description:`Emit one JSON document: action (retargeted | unchanged | would-retarget), number, url, previousBase, base, head, mergeable (true | false | null, advice only), dryRun; a refusal is an error, never this document.`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:e}){let t=createCliOutput(e.json===!0);refuseRepoWithoutNumber(e.number,e.repo);let n=createRealExecutor$1(),r=resolvePrEditHost(n,process.cwd(),e.repo??void 0),{number:i}=await resolvePrEditNumber(n,process.cwd(),r,e.number,`open`),a=await runPrRetarget(r,{number:i,base:e.base,dryRun:e[`dry-run`]===!0,recheckDelayMs:2e3,sleep});t.json(a),t.text(renderPrRetarget(a))}}),sl=A({meta:{name:`pr:update`,description:`Push the current branch to its open pull request. Refuses to run on main, master or the default branch. Fails when no PR is open; use pr:create then. Never changes the PR's draft state.`},args:{number:{type:`positional`,required:!1,description:`Pull request number; must be the current branch's open pull request (default: that pull request)`},title:{type:`string`,description:`Replace the PR title (default: leave it unchanged); on Forgejo a draft keeps its WIP: prefix`},body:{type:`string`,description:`Replace the PR body (default: leave it unchanged)`},"body-file":{type:`string`,description:`Read the new PR body from a file ('-' for stdin)`},base:{type:`string`,description:`Base branch to diff against (default: the repo's); never repoints the PR (pr:retarget does)`},"allow-unlink":{type:`boolean`,description:`Permit a --body that drops a closing keyword the current body carries`},closes:{type:`string`,description:`Issues the PR closes, comma-separated (12 or 12,15): adds a Closes #<n> line to the body for each one it does not already close`},"dry-run":{type:`boolean`,description:`Show what would happen without pushing`},json:{type:`boolean`,description:`Emit one JSON document: action (updated | would-update), number (or null), url (or null), branch, base, title, body, closesAdded? (with --closes: the issues it added a Closes line for), dryRun, rewrites. On a dry run, number and url are null.`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:e}){let t=createCliOutput(e.json===!0),n=readBodySource(e.body??void 0,e[`body-file`]??void 0),r=e.title!==void 0||n!==void 0,i=await runPrUpsert(createRealExecutor$1(),{cwd:process.cwd(),connection:resolveConnection(process.cwd()),mode:`update`,expectedNumber:e.number===void 0?void 0:parsePrNumber(e.number),title:e.title??void 0,body:n,base:e.base??void 0,allowUnlink:e[`allow-unlink`]===!0,closes:e.closes===void 0?void 0:parseIssueList(e.closes),draft:void 0,dryRun:e[`dry-run`]===!0,verbose:e.verbose===!0||isEnvVerbose()});t.json({...i,rewrites:r,dryRun:e[`dry-run`]===!0});let a=formatPrUpdate(i,r,{title:`--title`,body:`--body`});for(let e of a.lines)F.info(e);a.body!==null&¬e(a.body.text,a.body.heading)}});function observedTagPrefix(e,t){if(e.endsWith(t)){let n=e.slice(0,e.length-t.length);if(!/[\d.]$/.test(n))return n}return F.warn(`Could not read a tag prefix from ${e} for version ${t}; the floating tags will look for v${t}`),`v`}function resolveReleaseBump(e,t,n){if(e||t)return{firstRelease:e,releaseAs:t};let r=n?.trim();return!r||r===`auto`?{firstRelease:!1,releaseAs:void 0}:r===`first-release`?{firstRelease:!0,releaseAs:void 0}:{firstRelease:!1,releaseAs:r}}function buildArgs(e){let t=[`exec`,`commit-and-tag-version`];return e.dryRun&&t.push(`--dry-run`),e.firstRelease&&t.push(`--first-release`),e.releaseAs&&t.push(`--release-as`,e.releaseAs),e.prerelease&&t.push(`--prerelease`,e.prerelease),t}function readVersion(e,t){let n=e.readFile(w.join(t,`package.json`));if(!n)throw new T(`Could not read package.json`);let r=parsePackageJson(n);if(!r?.version)throw new T(`No version field found in package.json`);return r.version}function platformType(e){return e.platform?.type===`github`?`github`:`forgejo`}function resolveAuthCoordinates(e,t,n){if(t.platform?.type===`forgejo`)return{serverUrl:t.platform.conn.serverUrl,repository:t.platform.conn.repository,token:n};let r=process.env.GITHUB_SERVER_URL?.trim(),i=process.env.GITHUB_REPOSITORY?.trim();if(r&&i)return{serverUrl:r,repository:i,token:n};let a=e.readFile(w.join(t.cwd,`package.json`));if(!a)return;let o=parsePackageJson(a)?.repository,s=typeof o==`string`?o:o?.url;if(!s)return;let c=parseGitUrl(s);if(c)return{serverUrl:`${c.protocol}//${c.hostname}`,repository:c.repository,token:n}}function recoverFromExistingTag(e,t,n){let r=/tag '([^']+)' already exists/.exec(n);if(!r?.[1])throw new T(`commit-and-tag-version failed and could not extract tag name from output:\n${n}`);let i=r[1];F.warn(`Tag ${i} already exists -- checking if it points to HEAD (previous failed release)`);let a=e.exec(`git`,[`rev-parse`,i],{cwd:t.cwd}),o=e.exec(`git`,[`rev-parse`,`HEAD`],{cwd:t.cwd});if(a.exitCode!==0||o.exitCode!==0)throw new T(`commit-and-tag-version failed and could not verify tag ${i}:\n${n}`);if(a.stdout.trim()!==o.stdout.trim())throw new T(`commit-and-tag-version failed: tag ${i} already exists but points to a different commit.\nTag: ${a.stdout.trim()}\nHEAD: ${o.stdout.trim()}\nDelete the tag manually if you want to re-release, or use --release-as to pick a different version.`);F.info(`Tag ${i} points to HEAD -- recovering from previous failed release`)}async function runSimpleRelease(e,t){let n=releaseTargetConflict(resolveStack(t.cwd),`simple`,t.cwd);if(n)throw new T(`release:simple bumps package.json, but this repo's version-of-record is ${n}. A release would tag a version the ${n} artifact never gets. Release this repo through its own toolchain, or set releaseStrategy away from "simple".`);let r=platformType(t);debug(t,`Platform: ${r}`),debug(t,`Config: dryRun=${String(t.dryRun)} noPush=${String(t.noPush)} noSlidingTags=${String(t.noSlidingTags)} noRelease=${String(t.noRelease)}`),t.firstRelease&&debug(t,`Flag: --first-release`),t.releaseAs&&debug(t,`Flag: --release-as ${t.releaseAs}`),t.prerelease&&debug(t,`Flag: --prerelease ${t.prerelease}`);let i=await configureGitIdentity(e,r,t.cwd,t.platform?.type===`forgejo`?t.platform.conn:void 0);F.info(`Git identity: ${i.name} <${i.email}>`);let a=buildArgs(t);F.info(`Running: pnpm ${a.join(` `)}`);let o=e.exec(`pnpm`,a,{cwd:t.cwd});if(debugExec(t,`commit-and-tag-version`,o),o.exitCode!==0){let n=o.stderr||o.stdout;if(n.includes(`already exists`))recoverFromExistingTag(e,t,n);else throw new T(`commit-and-tag-version failed (exit code ${String(o.exitCode)}):\n${n}`)}let s=readVersion(e,t.cwd);debug(t,`New version: ${s}`);let c=e.exec(`git`,[`describe`,`--tags`,`--abbrev=0`],{cwd:t.cwd});debugExec(t,`git describe`,c);let l=c.stdout.trim();if(!l)throw new T(`Could not determine the new tag from git describe`);if(F.info(`Version ${s} tagged as ${l}`),t.dryRun){let e=isPrerelease$1(s),n=[];return!t.noSlidingTags&&!e&&(n=computeSlidingTags(s)),F.info(`[dry-run] Would push to origin with --follow-tags`),e&&!t.noSlidingTags?F.info(`[dry-run] Floating tags will not move: ${s} is a prerelease`):n.length>0&&F.info(`[dry-run] Would create sliding tags: ${n.join(`, `)}`),!t.noRelease&&t.platform&&F.info(`[dry-run] Would create ${t.platform.type} release for ${l}`),{version:s,tag:l,slidingTags:n,pushed:!1,releaseCreated:!1}}let u=!1,d=resolveAuthCoordinates(e,t,t.releaseToken),f;if(d?(f=buildGitAuth(d),debug(t,`Built git auth for ${d.repository}`)):debug(t,`Skipping git auth: could not resolve server URL / repository`),!t.noPush){let n=e.exec(`git`,[`rev-parse`,`--abbrev-ref`,`HEAD`],{cwd:t.cwd}).stdout.trim()||`main`;debug(t,`Pushing ${l} to origin/${n} with --follow-tags`);let r=f?[...f.args,`push`,`--follow-tags`,f.url,n]:[`push`,`--follow-tags`,`origin`,n],i=e.exec(`git`,r,{cwd:t.cwd});if(debugExec(t,`git push`,i),i.exitCode!==0)throw new T(`git push failed (exit code ${String(i.exitCode)}):\n${i.stderr||i.stdout}`);u=!0,F.info(`Pushed to origin`)}let p=[];!t.noSlidingTags&&u&&(p=computeSlidingTags(s),debug(t,`Evaluating floating tags: ${p.join(`, `)}`),reportFloatingTagOutcome(moveFloatingTags(e,{cwd:t.cwd,git:f?{args:f.args,url:f.url}:{args:[],url:`origin`},dryRun:!1,verbose:t.verbose},[{family:simpleTagFamily(observedTagPrefix(l,s)),version:s}]),!1));let m=!1;return!t.noRelease&&t.platform&&(debug(t,`Creating ${t.platform.type} release for ${l}`),m=await createPlatformRelease(e,t,l,s)),{version:s,tag:l,slidingTags:p,pushed:u,releaseCreated:m}}async function createPlatformRelease(e,t,n,r){if(!t.platform)return!1;if(t.platform.type===`forgejo`){let i=resolveTagCommit(e,t.cwd,n),{status:a}=await ensureRelease(e,t.platform.conn,n,{target:i,prerelease:isPrerelease$1(r)});return a===`exists`?(debug(t,`Release for ${n} already exists, skipping`),!1):(F.info(`Created Forgejo release for ${n}`),!0)}let i=[`release`,`create`,n,`--generate-notes`];isPrerelease$1(r)&&i.push(`--prerelease`);let a=e.exec(`gh`,i,{cwd:t.cwd});return debugExec(t,`gh release create`,a),a.exitCode===0?(F.info(`Created GitHub release for ${n}`),!0):(F.warn(`Warning: Failed to create GitHub release: ${a.stderr||a.stdout}`),!1)}const cl=A({meta:{name:`release:simple`,description:`Run commit-and-tag-version, push, create sliding tags, and create a platform release`},args:{"dry-run":{type:`boolean`,description:`Pass --dry-run to commit-and-tag-version and skip all remote operations`},verbose:{type:`boolean`,description:`Enable detailed debug logging (also enabled by TOOLING_DEBUG env var)`},push:{type:`boolean`,default:!0,description:`Push the release commit and tags to the remote (default). --no-push runs commit-and-tag-version and skips push and every other remote operation.`},"sliding-tags":{type:`boolean`,default:!0,description:`Create the floating tags latest, vX and vX.Y for a release (default); a prerelease never moves them. --no-sliding-tags skips them entirely.`},release:{type:`boolean`,default:!0,description:`Create the Forgejo/GitHub release (default). --no-release skips release creation, and with it the platform lookup.`},"first-release":{type:`boolean`,description:`Pass --first-release to commit-and-tag-version (skip version bump)`},"release-as":{type:`string`,description:`Force a specific version (passed to commit-and-tag-version --release-as)`},prerelease:{type:`string`,description:`Create a prerelease with the given tag (e.g., beta, alpha)`},json:{type:`boolean`,description:`Emit one JSON document: version, tag, slidingTags, pushed, releaseCreated, dryRun. slidingTags are the floating tags this run checked, including any it left in place.`}},async run({args:e}){let t=createCliOutput(e.json===!0),r=process.cwd(),i=e.verbose===!0||isEnvVerbose(),a=e.release===!1,o;if(!a){let e=resolveConnection(r);o=e.type===`forgejo`?{type:`forgejo`,conn:e.conn}:{type:`github`}}let s=resolveReleaseBump(e[`first-release`]===!0,e[`release-as`],process.env.RELEASE_BUMP),c={cwd:r,dryRun:e[`dry-run`]===!0,verbose:i,noPush:e.push===!1,noSlidingTags:e[`sliding-tags`]===!1,noRelease:a,firstRelease:s.firstRelease,releaseAs:s.releaseAs,prerelease:e.prerelease??process.env.RELEASE_PRERELEASE??void 0,platform:o,releaseToken:resolveSimpleReleaseToken()},l=await runSimpleRelease(createRealExecutor$1(),c);if(t.json({...l,dryRun:c.dryRun}),l.pushed){let e=process.env.GITHUB_OUTPUT;if(e)try{n(e,`pushed=true\ntag=${l.tag}\n`)}catch{}}}}),ll=A({meta:{name:`release:assets`,description:`Build and upload release assets configured in .tooling.json or by convention. Before any build it also stamps each .tooling.json#versionStamp entry with the release version, and fails when an entry matches no line or more than one.`},args:{"dry-run":{type:`boolean`,description:`Build assets but do not upload`},verbose:{type:`boolean`,description:`Enable detailed debug logging (also enabled by TOOLING_DEBUG env var)`}},async run({args:e}){let t=process.cwd(),n=e[`dry-run`]===!0,r;if(!n){let e=resolveConnection(t);r=e.type===`forgejo`?{type:`forgejo`,conn:e.conn}:{type:`github`}}let i={cwd:t,dryRun:n,verbose:e.verbose===!0||isEnvVerbose(),toolingConfig:loadToolingConfig(t),platform:r};await runReleaseAssets(createRealExecutor$1(),i)}});function createSnapshotForge(e,t,n){return t.type===`github`?githubForge(e,n):forgejoForge(e,t.conn)}function gh(e,t,n,r){let i=e.exec(`gh`,n,{cwd:t});if(i.exitCode!==0)throw new E(`GitHub ${r} failed (exit ${String(i.exitCode)}):\n${childOutput(i)}`);return i}const ul=N.array(N.looseObject({tagName:N.string(),createdAt:N.string().nullish()}));function parseGitHubReleaseList(e){let t;try{t=JSON.parse(e)}catch{throw new D(`Unexpected GitHub release list output: ${e.slice(0,200)}`)}let n=ul.safeParse(t);if(!n.success)throw new D(`Unexpected GitHub release list response: ${n.error.message}`);return n.data.map(e=>({tag:e.tagName,createdAt:e.createdAt??null}))}function githubForge(e,t){return{async releaseExists(n){return e.exec(`gh`,[`release`,`view`,n],{cwd:t}).exitCode===0},async createPrerelease(n,r){gh(e,t,[`release`,`create`,n,`--prerelease`,`--target`,r.target,`--title`,n,`--notes`,r.notes],`release create ${n}`),F.info(`Created prerelease ${n} (GitHub)`)},async uploadAsset(n,r){gh(e,t,[`release`,`upload`,n,r.path,`--clobber`],`release upload ${r.name} to ${n}`),F.info(`Uploaded ${r.name} to ${n} (GitHub)`)},async listReleases(){return parseGitHubReleaseList(gh(e,t,[`release`,`list`,`--json`,`tagName,createdAt`,`--limit`,`100`],`release list`).stdout)},async deleteRelease(n){gh(e,t,[`release`,`delete`,n,`--cleanup-tag`,`--yes`],`release delete ${n}`),F.info(`Deleted ${n} (GitHub)`)}}}function forgejoForge(e,t){return{async releaseExists(n){return findRelease(e,t,n)},async createPrerelease(n,r){await createRelease(e,t,n,{prerelease:!0,target:r.target,name:n,body:r.notes}),F.info(`Created prerelease ${n} (Forgejo)`)},async uploadAsset(n,r){let i=e.readFileBuffer(r.path);if(i===null)throw new T(`Snapshot asset file not found: ${r.path}`);await uploadReleaseAsset(e,t,n,{assetName:r.name,fileBuffer:i,replace:!0}),F.info(`Uploaded ${r.name} to ${n} (Forgejo)`)},async listReleases(){return(await listReleases(e,t,{limit:100})).map(e=>({tag:e.tag,createdAt:e.createdAt}))},async deleteRelease(n){let r=await getReleaseByTag(e,t,n);r!==null&&await deleteRelease(e,t,r.id),await deleteTag(e,t,n),F.info(`Deleted ${n} (Forgejo)`)}}}const dl=`.bst-changeset-status.json`,fl=N.looseObject({releases:N.array(N.looseObject({name:N.string(),newVersion:N.string()})),changesets:N.array(N.looseObject({summary:N.string(),releases:N.array(N.looseObject({name:N.string()}))}))});function readChangesetStatus(e,t){let n=e.exec(`pnpm`,[`changeset`,`status`,`--output`,dl],{cwd:t}),r=w.join(t,dl);try{if(n.exitCode!==0)throw new T(`\`changeset status\` failed (exit ${String(n.exitCode)}) -- a snapshot needs the version the pending changesets would give, and there is no fallback version:\n`+childOutput(n));let t=e.readFile(r);if(t===null)throw new T(`\`changeset status\` exited zero but wrote no ${dl}:\n`+childOutput(n));let i=parseStatus(t);if(i===null)throw new T(`\`changeset status\` wrote a ${dl} this run cannot read:\n`+childOutput(n));return i}finally{e.removeDir(r)}}function parseStatus(e){let t;try{t=JSON.parse(e)}catch{return null}let n=fl.safeParse(t);return n.success?n.data:null}const pl=/^(\d+)\.(\d+)\.(\d+)/;function snapshotVersion(e){return`${baseVersion(e.nextVersion)??raisePatch(e.currentVersion)}-${e.preid}.${e.build}`}function baseVersion(e){if(e===null)return null;let t=pl.exec(e);return t===null?e:t[0]}function raisePatch(e){let[t,n,r]=pl.exec(e)?.slice(1)??[];if(t===void 0||n===void 0||r===void 0)throw new T(`Cannot snapshot ${e}: it carries no x.y.z core to raise a patch from, and no pending changeset gives this package a next version.`);return`${t}.${n}.${String(Number(r)+1)}`}async function runReleaseSnapshot(e,t){let n=readSnapshotSettings(t);refusePreTagPreid(e,t,n);let r=isMonorepoRepo(e,t);refuseUnownedEntries(t,r);let i=resolvePackages(e,t,n,r),a=resolveBuild(t),o=resolveTarget(t),s=readChangesetStatus(e,t.cwd);debug(t,`Snapshotting ${String(i.length)} package(s) at build ${a}`);let c={executor:e,buildExecutor:t.captureBuildOutput?capturingExecutor(e):e,forge:t.dryRun?inertForge():createRealForge(e,t),config:t,status:s,settings:n,target:o,build:a,isMonorepo:r},l=[],u=!t.dryRun&&i.length>0;for(let e of i){let t=await snapshotPackage(c,e);l.push(t.result),u&&=t.exists}let d={published:u,packages:l};return appendOutputs(e,t,d),d}function readSnapshotSettings(e){let t=e.toolingConfig?.snapshot;if(t===void 0)throw new T("release:snapshot needs a `snapshot` block in .tooling.json. Its `preid` is the prerelease identifier every snapshot version carries, and bst will not pick one for your channel.");return{preid:t.preid,keep:t.keep??3,packages:t.packages}}function refusePreTagPreid(e,t,n){let r=e.readFile(w.join(t.cwd,lo));if(r===null)return;let i=parsePreTag(r);if(i===void 0)throw new T(`${lo} exists but has no readable \`tag\`, so this run cannot tell whether the snapshot preid collides with the pre-mode tag. Fix or remove the file.`);if(i===n.preid)throw new T(`.tooling.json#snapshot.preid "${n.preid}" equals the tag in ${lo}, so the snapshot prune could delete real prereleases. Pick a different preid.`)}function isMonorepoRepo(e,t){let n=t.toolingConfig?.structure;return n===void 0?e.readFile(w.join(t.cwd,`pnpm-workspace.yaml`))!==null:n===`monorepo`}function refuseUnownedEntries(e,t){if(!t)return;let n=(e.toolingConfig?.releaseAssets??[]).filter(e=>e.package===void 0);if(n.length>0){let e=n[0];throw new T(`release:snapshot cannot build a releaseAssets entry that names no package in a monorepo: ${JSON.stringify(e)}. A snapshot uploads to one package's prerelease, so name the package the entry builds for.`)}let r=(e.toolingConfig?.versionStamp??[]).find(e=>e.package===void 0);if(r!==void 0)throw new T(`release:snapshot cannot stamp a versionStamp entry that names no package in a monorepo: ${JSON.stringify(r)}. A snapshot cuts one version per package, so name the package whose release this entry stamps.`)}function resolvePackages(e,t,n,r){if(r){let r=n.packages;if(r===void 0||r.length===0)throw new T("release:snapshot needs `snapshot.packages` in a monorepo: which packages a tester installs is the repo owner's call, and bst does not guess it.");let i=e.listWorkspacePackages(t.cwd);return r.map(e=>{let n=i.find(t=>t.name===e);if(n===void 0)throw unknownPackageName(e);return{name:e,currentVersion:n.version,dir:w.join(t.cwd,`packages`,n.dir),root:!1}})}let i=rootPackage(e,t.cwd);for(let e of n.packages??[])if(e!==i.name)throw unknownPackageName(e);return[i]}function unknownPackageName(e){return new T(`snapshot.packages names ${e}, which is not a workspace package of this repo. Spell it as its package.json does.`)}function rootPackage(e,t){let n=w.join(t,`package.json`),r=e.readFile(n),i=r===null?void 0:parsePackageJson(r);if(i?.name===void 0||i.version===void 0)throw new T(`release:snapshot cannot snapshot the root package: ${n} carries no name or no version, and a snapshot version is raised from the version it holds.`);return{name:i.name,currentVersion:i.version,dir:t,root:!0}}function resolveBuild(e){let t=process.env.GITHUB_RUN_NUMBER??e.build;if(t===void 0||t===``)throw new T(`release:snapshot needs a build number: GITHUB_RUN_NUMBER is what a CI job supplies, and outside CI --build <n> is the only source. Two cuts sharing a suffix collide on one tag.`);return t}function resolveTarget(e){let t=process.env.GITHUB_SHA??``;if(t===``&&!e.dryRun)throw new T(`release:snapshot needs GITHUB_SHA: the prerelease targets the exact commit the job checked out, so the tag names the code it was built from. --dry-run is the only run that may go without it.`);return t}function createRealForge(e,t){if(t.platform===void 0)throw new T(`Platform connection is required for a snapshot release`);return createSnapshotForge(e,t.platform,t.cwd)}function inertForge(){return{async releaseExists(){return!1},async createPrerelease(){},async uploadAsset(){},async listReleases(){return[]},async deleteRelease(){}}}async function snapshotPackage(e,t){let n=snapshotVersion({currentVersion:t.currentVersion,nextVersion:nextVersionFor(e.status,t.name),preid:e.settings.preid,build:e.build}),r=releaseTag({name:t.name,version:n,root:t.root}),i={packageName:t.name,version:n,tag:r,prerelease:!0,buildNumber:e.build};if(e.config.dryRun)return F.info(`[dry-run] ${t.name} -> ${r} (no forge call)`),{result:{name:t.name,version:n,tag:r},exists:!1};writeWorkingTreeVersion(e,w.join(t.dir,`package.json`),n);let a=stampOwnedVersionFiles(e.executor,e.config.cwd,e.config.toolingConfig,i,e.isMonorepo),o=ownedTargets(e.executor,e.config.cwd,e.config.toolingConfig,t.name,e.isMonorepo),s=buildTargets(e.buildExecutor,o,i,e.config);verifyStamp(e.executor,a),await e.forge.releaseExists(r)?F.info(`Prerelease ${r} already exists, uploading its assets with replacement`):await e.forge.createPrerelease(r,{target:e.target,notes:releaseNotes(e.status,t.name)});for(let t of s)await e.forge.uploadAsset(r,{path:t.path,name:t.name??w.basename(t.path)});return await pruneSnapshots(e.forge,t,e.settings),{result:{name:t.name,version:n,tag:r},exists:!0}}function nextVersionFor(e,t){return e.releases.find(e=>e.name===t)?.newVersion??null}function releaseNotes(e,t){return e.changesets.filter(e=>e.releases.some(e=>e.name===t)).map(e=>`- ${e.summary.trim()}`).join(`
|
|
6098
|
-
`)}function writeWorkingTreeVersion(e,t,n){let r=e.executor.readFile(t);if(r===null)throw new T(`Cannot write the snapshot version: ${t} is not readable.`);e.executor.writeFile(t,he(r,ge(r,[`version`],n,{}))),debug(e.config,`Wrote ${n} into ${t} (working tree only)`)}async function pruneSnapshots(e,t,n){let r=t.root?`v`:`${t.name}@`,i=RegExp(`^${escapeRegExp$1(r)}\\d+\\.\\d+\\.\\d+-${escapeRegExp$1(n.preid)}\\.\\d+$`),a=(await e.listReleases()).filter(e=>i.test(e.tag)).toSorted(byNewestFirst);for(let t of a.slice(n.keep))await e.deleteRelease(t.tag)}function escapeRegExp$1(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function buildOf(e){return Number(e.tag.slice(e.tag.lastIndexOf(`.`)+1))}function byNewestFirst(e,t){let n=buildOf(t)-buildOf(e);if(n!==0)return n;let r=e.createdAt??``,i=t.createdAt??``;return r===i?0:r<i?1:-1}function capturingExecutor(e){return{...e,execInherit(t,n,r){let i=e.exec(t,n,r);if(i.exitCode!==0)throw new T(`Asset build failed (exit ${String(i.exitCode)}):\n${childOutput(i)}`)}}}function appendOutputs(e,t,n){let r=process.env.GITHUB_OUTPUT;if(r===void 0||r===``)return;let i=n.packages[0];e.appendFile(r,`published=${String(n.published)}\nversion=${i?.version??``}\ntag=${i?.tag??``}\npackages=${JSON.stringify(n.packages)}\n`),debug(t,`Wrote snapshot outputs to ${r}`)}const
|
|
6101
|
+
`)}return e.action===`already-open`?`Pull request ${t} is already open.`:`Dry run: pull request ${t} would be reopened.`}function parsePrNumber(e){let t=Number(e);if(!/^\d+$/.test(e)||!Number.isSafeInteger(t)||t<1)throw new T(`Invalid pull request number "${e}" (expected a positive integer).`);return t}function resolvePrEditTarget(e,t,n){let r=resolveIssueTransport(e,t,parseRepoTarget(n));if(r.target.hostname===`github.com`)return{host:githubPrEditHost(e,t,r.target.repository),issues:r.api};if(r.conn===void 0)throw new D(`Resolved a non-github.com target (${r.target.hostname}) with no Forgejo connection.`);return{host:forgejoPrEditHost(e,r.conn),issues:r.api}}function resolvePrEditHost(e,t,n){return resolvePrEditTarget(e,t,n).host}async function resolvePrEditNumber(e,t,n,r,i){if(r!==void 0)return{number:parsePrNumber(r),autodetected:!1};let a=loadToolingConfig(t)?.defaultBranch;return{number:(await resolveBranchPr$1(executorGit(e),n,{cwd:t,state:i,...a===void 0?{}:{defaultBranchOverride:a},signal:null})).number,autodetected:!0}}const Ml=j({meta:{name:`pr:ready`,description:`Mark a draft pull request ready, dropping one WIP: prefix or taking --title, and confirm the forge no longer reports a draft, on Forgejo or GitHub`},args:{number:{type:`positional`,required:!1,description:`Pull request number (default: the current branch's open pull request)`},title:{type:`string`,description:`Write this title instead of stripping the WIP prefix from the current one`},repo:{type:`string`,description:`Repository URL (default: this repo)`},"dry-run":{type:`boolean`,description:`Run every read and report, but do not write`},json:{type:`boolean`,description:`Emit one JSON document: action (readied | retitled | already-ready | would-ready | would-retitle), number, url, previousTitle, title, draft, dryRun; a refusal is an error, never this document.`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:e}){let t=createCliOutput(e.json===!0);refuseRepoWithoutNumber(e.number,e.repo);let n=createRealExecutor$1(),r=resolvePrEditHost(n,process.cwd(),e.repo??void 0),{number:i}=await resolvePrEditNumber(n,process.cwd(),r,e.number,`open`),a=await runPrReady(r,{number:i,title:e.title??void 0,dryRun:e[`dry-run`]===!0});t.json(a),t.text(renderPrReady(a))}}),Nl=j({meta:{name:`pr:reopen`,description:`Reopen a closed, unmerged pull request and confirm the forge reports it open, on Forgejo or GitHub. An already-open pull request is reported without writing; a merged one, or an issue, is refused`},args:{number:{type:`positional`,required:!1,description:`Pull request number (default: the current branch's closed pull request)`},repo:{type:`string`,description:`Repository URL (default: this repo)`},"dry-run":{type:`boolean`,description:`Run every read and report, but do not write`},json:{type:`boolean`,description:`Emit one JSON document: action (reopened | already-open | would-reopen), number, url, title, head, base, draft, dryRun; a refusal is an error, never this document.`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:e}){let t=createCliOutput(e.json===!0);refuseRepoWithoutNumber(e.number,e.repo);let n=createRealExecutor$1(),{host:r,issues:i}=resolvePrEditTarget(n,process.cwd(),e.repo??void 0),{number:a,autodetected:o}=await resolvePrEditNumber(n,process.cwd(),r,e.number,`closed-unmerged`);if(!o&&!(await i.get(a)).isPullRequest)throw new T(`#${String(a)} is an issue, not a pull request -- pr:reopen refuses to write issue state. Use \`pnpm exec bst issue:reopen ${String(a)}\` to reopen it.`);let s=await runPrReopen(r,{number:a,dryRun:e[`dry-run`]===!0});t.json(s),t.text(renderPrReopen(s))}}),Pl=j({meta:{name:`pr:retarget`,description:`Change an open pull request's base branch, confirm the forge took it, and report its mergeability as advice on Forgejo or GitHub`},args:{number:{type:`positional`,required:!1,description:`Pull request number (default: the current branch's open pull request)`},base:{type:`string`,required:!0,description:`The branch to retarget the pull request onto`},repo:{type:`string`,description:`Repository URL (default: this repo)`},"dry-run":{type:`boolean`,description:`Run every read and report, but do not write`},json:{type:`boolean`,description:`Emit one JSON document: action (retargeted | unchanged | would-retarget), number, url, previousBase, base, head, mergeable (true | false | null, advice only), dryRun; a refusal is an error, never this document.`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:e}){let t=createCliOutput(e.json===!0);refuseRepoWithoutNumber(e.number,e.repo);let n=createRealExecutor$1(),r=resolvePrEditHost(n,process.cwd(),e.repo??void 0),{number:i}=await resolvePrEditNumber(n,process.cwd(),r,e.number,`open`),a=await runPrRetarget(r,{number:i,base:e.base,dryRun:e[`dry-run`]===!0,recheckDelayMs:2e3,sleep});t.json(a),t.text(renderPrRetarget(a))}}),Fl=j({meta:{name:`pr:update`,description:`Push the current branch to its open pull request. Refuses to run on main, master or the default branch. Fails when no PR is open; use pr:create then. Never changes the PR's draft state.`},args:{number:{type:`positional`,required:!1,description:`Pull request number; must be the current branch's open pull request (default: that pull request)`},title:{type:`string`,description:`Replace the PR title (default: leave it unchanged); on Forgejo a draft keeps its WIP: prefix`},body:{type:`string`,description:`Replace the PR body (default: leave it unchanged)`},"body-file":{type:`string`,description:`Read the new PR body from a file ('-' for stdin)`},base:{type:`string`,description:`Base branch to diff against (default: the repo's); never repoints the PR (pr:retarget does)`},"allow-unlink":{type:`boolean`,description:`Permit a --body that drops a closing keyword the current body carries`},closes:{type:`string`,description:`Issues the PR closes, comma-separated (12 or 12,15): adds a Closes #<n> line to the body for each one it does not already close`},"dry-run":{type:`boolean`,description:`Show what would happen without pushing`},json:{type:`boolean`,description:`Emit one JSON document: action (updated | would-update), number (or null), url (or null), branch, base, title, body, closesAdded? (with --closes: the issues it added a Closes line for), dryRun, rewrites. On a dry run, number and url are null.`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:e}){let t=createCliOutput(e.json===!0),n=readBodySource(e.body??void 0,e[`body-file`]??void 0),r=e.title!==void 0||n!==void 0,i=await runPrUpsert(createRealExecutor$1(),{cwd:process.cwd(),connection:resolveConnection(process.cwd()),mode:`update`,expectedNumber:e.number===void 0?void 0:parsePrNumber(e.number),title:e.title??void 0,body:n,base:e.base??void 0,allowUnlink:e[`allow-unlink`]===!0,closes:e.closes===void 0?void 0:parseIssueList(e.closes),draft:void 0,dryRun:e[`dry-run`]===!0,verbose:e.verbose===!0||isEnvVerbose()});t.json({...i,rewrites:r,dryRun:e[`dry-run`]===!0});let a=formatPrUpdate(i,r,{title:`--title`,body:`--body`});for(let e of a.lines)I.info(e);a.body!==null&¬e(a.body.text,a.body.heading)}});function observedTagPrefix(e,t){if(e.endsWith(t)){let n=e.slice(0,e.length-t.length);if(!/[\d.]$/.test(n))return n}return I.warn(`Could not read a tag prefix from ${e} for version ${t}; the floating tags will look for v${t}`),`v`}function resolveReleaseBump(e,t,n){if(e||t)return{firstRelease:e,releaseAs:t};let r=n?.trim();return!r||r===`auto`?{firstRelease:!1,releaseAs:void 0}:r===`first-release`?{firstRelease:!0,releaseAs:void 0}:{firstRelease:!1,releaseAs:r}}function buildArgs(e){let t=[`exec`,`commit-and-tag-version`];return e.dryRun&&t.push(`--dry-run`),e.firstRelease&&t.push(`--first-release`),e.releaseAs&&t.push(`--release-as`,e.releaseAs),e.prerelease&&t.push(`--prerelease`,e.prerelease),t}function readVersion(e,t){let n=e.readFile(w.join(t,`package.json`));if(!n)throw new T(`Could not read package.json`);let r=parsePackageJson(n);if(!r?.version)throw new T(`No version field found in package.json`);return r.version}function platformType(e){return e.platform?.type===`github`?`github`:`forgejo`}function resolveAuthCoordinates(e,t,n){if(t.platform?.type===`forgejo`)return{serverUrl:t.platform.conn.serverUrl,repository:t.platform.conn.repository,token:n};let r=process.env.GITHUB_SERVER_URL?.trim(),i=process.env.GITHUB_REPOSITORY?.trim();if(r&&i)return{serverUrl:r,repository:i,token:n};let a=e.readFile(w.join(t.cwd,`package.json`));if(!a)return;let o=parsePackageJson(a)?.repository,s=typeof o==`string`?o:o?.url;if(!s)return;let c=parseGitUrl(s);if(c)return{serverUrl:`${c.protocol}//${c.hostname}`,repository:c.repository,token:n}}function recoverFromExistingTag(e,t,n){let r=/tag '([^']+)' already exists/.exec(n);if(!r?.[1])throw new T(`commit-and-tag-version failed and could not extract tag name from output:\n${n}`);let i=r[1];I.warn(`Tag ${i} already exists -- checking if it points to HEAD (previous failed release)`);let a=e.exec(`git`,[`rev-parse`,i],{cwd:t.cwd}),o=e.exec(`git`,[`rev-parse`,`HEAD`],{cwd:t.cwd});if(a.exitCode!==0||o.exitCode!==0)throw new T(`commit-and-tag-version failed and could not verify tag ${i}:\n${n}`);if(a.stdout.trim()!==o.stdout.trim())throw new T(`commit-and-tag-version failed: tag ${i} already exists but points to a different commit.\nTag: ${a.stdout.trim()}\nHEAD: ${o.stdout.trim()}\nDelete the tag manually if you want to re-release, or use --release-as to pick a different version.`);I.info(`Tag ${i} points to HEAD -- recovering from previous failed release`)}async function runSimpleRelease(e,t){let n=releaseTargetConflict(resolveStack(t.cwd),`simple`,t.cwd);if(n)throw new T(`release:simple bumps package.json, but this repo's version-of-record is ${n}. A release would tag a version the ${n} artifact never gets. Release this repo through its own toolchain, or set releaseStrategy away from "simple".`);let r=platformType(t);debug(t,`Platform: ${r}`),debug(t,`Config: dryRun=${String(t.dryRun)} noPush=${String(t.noPush)} noSlidingTags=${String(t.noSlidingTags)} noRelease=${String(t.noRelease)}`),t.firstRelease&&debug(t,`Flag: --first-release`),t.releaseAs&&debug(t,`Flag: --release-as ${t.releaseAs}`),t.prerelease&&debug(t,`Flag: --prerelease ${t.prerelease}`);let i=await configureGitIdentity(e,r,t.cwd,t.platform?.type===`forgejo`?t.platform.conn:void 0);I.info(`Git identity: ${i.name} <${i.email}>`);let a=buildArgs(t);I.info(`Running: pnpm ${a.join(` `)}`);let o=e.exec(`pnpm`,a,{cwd:t.cwd});if(debugExec(t,`commit-and-tag-version`,o),o.exitCode!==0){let n=o.stderr||o.stdout;if(n.includes(`already exists`))recoverFromExistingTag(e,t,n);else throw new T(`commit-and-tag-version failed (exit code ${String(o.exitCode)}):\n${n}`)}let s=readVersion(e,t.cwd);debug(t,`New version: ${s}`);let c=e.exec(`git`,[`describe`,`--tags`,`--abbrev=0`],{cwd:t.cwd});debugExec(t,`git describe`,c);let l=c.stdout.trim();if(!l)throw new T(`Could not determine the new tag from git describe`);if(I.info(`Version ${s} tagged as ${l}`),t.dryRun){let e=isPrerelease$1(s),n=[];return!t.noSlidingTags&&!e&&(n=computeSlidingTags(s)),I.info(`[dry-run] Would push to origin with --follow-tags`),e&&!t.noSlidingTags?I.info(`[dry-run] Floating tags will not move: ${s} is a prerelease`):n.length>0&&I.info(`[dry-run] Would create sliding tags: ${n.join(`, `)}`),!t.noRelease&&t.platform&&I.info(`[dry-run] Would create ${t.platform.type} release for ${l}`),{version:s,tag:l,slidingTags:n,pushed:!1,releaseCreated:!1}}let u=!1,d=resolveAuthCoordinates(e,t,t.releaseToken),f;if(d?(f=buildGitAuth(d),debug(t,`Built git auth for ${d.repository}`)):debug(t,`Skipping git auth: could not resolve server URL / repository`),!t.noPush){let n=e.exec(`git`,[`rev-parse`,`--abbrev-ref`,`HEAD`],{cwd:t.cwd}).stdout.trim()||`main`;debug(t,`Pushing ${l} to origin/${n} with --follow-tags`);let r=f?[...f.args,`push`,`--follow-tags`,f.url,n]:[`push`,`--follow-tags`,`origin`,n],i=e.exec(`git`,r,{cwd:t.cwd});if(debugExec(t,`git push`,i),i.exitCode!==0)throw new T(`git push failed (exit code ${String(i.exitCode)}):\n${i.stderr||i.stdout}`);u=!0,I.info(`Pushed to origin`)}let p=[];!t.noSlidingTags&&u&&(p=computeSlidingTags(s),debug(t,`Evaluating floating tags: ${p.join(`, `)}`),reportFloatingTagOutcome(moveFloatingTags(e,{cwd:t.cwd,git:f?{args:f.args,url:f.url}:{args:[],url:`origin`},dryRun:!1,verbose:t.verbose},[{family:simpleTagFamily(observedTagPrefix(l,s)),version:s}]),!1));let m=!1;return!t.noRelease&&t.platform&&(debug(t,`Creating ${t.platform.type} release for ${l}`),m=await createPlatformRelease(e,t,l,s)),{version:s,tag:l,slidingTags:p,pushed:u,releaseCreated:m}}async function createPlatformRelease(e,t,n,r){if(!t.platform)return!1;if(t.platform.type===`forgejo`){let i=resolveTagCommit(e,t.cwd,n),{status:a}=await ensureRelease(e,t.platform.conn,n,{target:i,prerelease:isPrerelease$1(r)});return a===`exists`?(debug(t,`Release for ${n} already exists, skipping`),!1):(I.info(`Created Forgejo release for ${n}`),!0)}let i=[`release`,`create`,n,`--generate-notes`];isPrerelease$1(r)&&i.push(`--prerelease`);let a=e.exec(`gh`,i,{cwd:t.cwd});return debugExec(t,`gh release create`,a),a.exitCode===0?(I.info(`Created GitHub release for ${n}`),!0):(I.warn(`Warning: Failed to create GitHub release: ${a.stderr||a.stdout}`),!1)}const Il=j({meta:{name:`release:simple`,description:`Run commit-and-tag-version, push, create sliding tags, and create a platform release`},args:{"dry-run":{type:`boolean`,description:`Pass --dry-run to commit-and-tag-version and skip all remote operations`},verbose:{type:`boolean`,description:`Enable detailed debug logging (also enabled by TOOLING_DEBUG env var)`},push:{type:`boolean`,default:!0,description:`Push the release commit and tags to the remote (default). --no-push runs commit-and-tag-version and skips push and every other remote operation.`},"sliding-tags":{type:`boolean`,default:!0,description:`Create the floating tags latest, vX and vX.Y for a release (default); a prerelease never moves them. --no-sliding-tags skips them entirely.`},release:{type:`boolean`,default:!0,description:`Create the Forgejo/GitHub release (default). --no-release skips release creation, and with it the platform lookup.`},"first-release":{type:`boolean`,description:`Pass --first-release to commit-and-tag-version (skip version bump)`},"release-as":{type:`string`,description:`Force a specific version (passed to commit-and-tag-version --release-as)`},prerelease:{type:`string`,description:`Create a prerelease with the given tag (e.g., beta, alpha)`},json:{type:`boolean`,description:`Emit one JSON document: version, tag, slidingTags, pushed, releaseCreated, dryRun. slidingTags are the floating tags this run checked, including any it left in place.`}},async run({args:e}){let t=createCliOutput(e.json===!0),r=process.cwd(),i=e.verbose===!0||isEnvVerbose(),a=e.release===!1,o;if(!a){let e=resolveConnection(r);o=e.type===`forgejo`?{type:`forgejo`,conn:e.conn}:{type:`github`}}let s=resolveReleaseBump(e[`first-release`]===!0,e[`release-as`],process.env.RELEASE_BUMP),c={cwd:r,dryRun:e[`dry-run`]===!0,verbose:i,noPush:e.push===!1,noSlidingTags:e[`sliding-tags`]===!1,noRelease:a,firstRelease:s.firstRelease,releaseAs:s.releaseAs,prerelease:e.prerelease??process.env.RELEASE_PRERELEASE??void 0,platform:o,releaseToken:resolveSimpleReleaseToken()},l=await runSimpleRelease(createRealExecutor$1(),c);if(t.json({...l,dryRun:c.dryRun}),l.pushed){let e=process.env.GITHUB_OUTPUT;if(e)try{n(e,`pushed=true\ntag=${l.tag}\n`)}catch{}}}}),Ll=j({meta:{name:`release:assets`,description:`Build and upload release assets configured in .tooling.json or by convention. Before any build it also stamps each .tooling.json#versionStamp entry with the release version, and fails when an entry matches no line or more than one.`},args:{"dry-run":{type:`boolean`,description:`Build assets but do not upload`},verbose:{type:`boolean`,description:`Enable detailed debug logging (also enabled by TOOLING_DEBUG env var)`}},async run({args:e}){let t=process.cwd(),n=e[`dry-run`]===!0,r;if(!n){let e=resolveConnection(t);r=e.type===`forgejo`?{type:`forgejo`,conn:e.conn}:{type:`github`}}let i={cwd:t,dryRun:n,verbose:e.verbose===!0||isEnvVerbose(),toolingConfig:loadToolingConfig(t),platform:r};await runReleaseAssets(createRealExecutor$1(),i)}});function createSnapshotForge(e,t,n){return t.type===`github`?githubForge(e,n):forgejoForge(e,t.conn)}function gh(e,t,n,r){let i=e.exec(`gh`,n,{cwd:t});if(i.exitCode!==0)throw new E(`GitHub ${r} failed (exit ${String(i.exitCode)}):\n${childOutput(i)}`);return i}const Rl=P.array(P.looseObject({tagName:P.string(),createdAt:P.string().nullish()}));function parseGitHubReleaseList(e){let t;try{t=JSON.parse(e)}catch{throw new D(`Unexpected GitHub release list output: ${e.slice(0,200)}`)}let n=Rl.safeParse(t);if(!n.success)throw new D(`Unexpected GitHub release list response: ${n.error.message}`);return n.data.map(e=>({tag:e.tagName,createdAt:e.createdAt??null}))}function githubForge(e,t){return{async releaseExists(n){return e.exec(`gh`,[`release`,`view`,n],{cwd:t}).exitCode===0},async createPrerelease(n,r){gh(e,t,[`release`,`create`,n,`--prerelease`,`--target`,r.target,`--title`,n,`--notes`,r.notes],`release create ${n}`),I.info(`Created prerelease ${n} (GitHub)`)},async uploadAsset(n,r){gh(e,t,[`release`,`upload`,n,r.path,`--clobber`],`release upload ${r.name} to ${n}`),I.info(`Uploaded ${r.name} to ${n} (GitHub)`)},async listReleases(){return parseGitHubReleaseList(gh(e,t,[`release`,`list`,`--json`,`tagName,createdAt`,`--limit`,`100`],`release list`).stdout)},async deleteRelease(n){gh(e,t,[`release`,`delete`,n,`--cleanup-tag`,`--yes`],`release delete ${n}`),I.info(`Deleted ${n} (GitHub)`)}}}function forgejoForge(e,t){return{async releaseExists(n){return findRelease(e,t,n)},async createPrerelease(n,r){await createRelease(e,t,n,{prerelease:!0,target:r.target,name:n,body:r.notes}),I.info(`Created prerelease ${n} (Forgejo)`)},async uploadAsset(n,r){let i=e.readFileBuffer(r.path);if(i===null)throw new T(`Snapshot asset file not found: ${r.path}`);await uploadReleaseAsset(e,t,n,{assetName:r.name,fileBuffer:i,replace:!0}),I.info(`Uploaded ${r.name} to ${n} (Forgejo)`)},async listReleases(){return(await listReleases(e,t,{limit:100})).map(e=>({tag:e.tag,createdAt:e.createdAt}))},async deleteRelease(n){let r=await getReleaseByTag(e,t,n);r!==null&&await deleteRelease(e,t,r.id),await deleteTag(e,t,n),I.info(`Deleted ${n} (Forgejo)`)}}}const zl=`.bst-changeset-status.json`,Bl=P.looseObject({releases:P.array(P.looseObject({name:P.string(),newVersion:P.string()})),changesets:P.array(P.looseObject({summary:P.string(),releases:P.array(P.looseObject({name:P.string()}))}))});function readChangesetStatus(e,t){let n=e.exec(`pnpm`,[`changeset`,`status`,`--output`,zl],{cwd:t}),r=w.join(t,zl);try{if(n.exitCode!==0)throw new T(`\`changeset status\` failed (exit ${String(n.exitCode)}) -- a snapshot needs the version the pending changesets would give, and there is no fallback version:\n`+childOutput(n));let t=e.readFile(r);if(t===null)throw new T(`\`changeset status\` exited zero but wrote no ${zl}:\n`+childOutput(n));let i=parseStatus(t);if(i===null)throw new T(`\`changeset status\` wrote a ${zl} this run cannot read:\n`+childOutput(n));return i}finally{e.removeDir(r)}}function parseStatus(e){let t;try{t=JSON.parse(e)}catch{return null}let n=Bl.safeParse(t);return n.success?n.data:null}const Vl=/^(\d+)\.(\d+)\.(\d+)/;function snapshotVersion(e){return`${baseVersion(e.nextVersion)??raisePatch(e.currentVersion)}-${e.preid}.${e.build}`}function baseVersion(e){if(e===null)return null;let t=Vl.exec(e);return t===null?e:t[0]}function raisePatch(e){let[t,n,r]=Vl.exec(e)?.slice(1)??[];if(t===void 0||n===void 0||r===void 0)throw new T(`Cannot snapshot ${e}: it carries no x.y.z core to raise a patch from, and no pending changeset gives this package a next version.`);return`${t}.${n}.${String(Number(r)+1)}`}async function runReleaseSnapshot(e,t){let n=readSnapshotSettings(t);refusePreTagPreid(e,t,n);let r=isMonorepoRepo(e,t);refuseUnownedEntries(t,r);let i=resolvePackages(e,t,n,r),a=resolveBuild(t),o=resolveTarget(t),s=readChangesetStatus(e,t.cwd);debug(t,`Snapshotting ${String(i.length)} package(s) at build ${a}`);let c={executor:e,buildExecutor:t.captureBuildOutput?capturingExecutor(e):e,forge:t.dryRun?inertForge():createRealForge(e,t),config:t,status:s,settings:n,target:o,build:a,isMonorepo:r},l=[],u=!t.dryRun&&i.length>0;for(let e of i){let t=await snapshotPackage(c,e);l.push(t.result),u&&=t.exists}let d={published:u,packages:l};return appendOutputs(e,t,d),d}function readSnapshotSettings(e){let t=e.toolingConfig?.snapshot;if(t===void 0)throw new T("release:snapshot needs a `snapshot` block in .tooling.json. Its `preid` is the prerelease identifier every snapshot version carries, and bst will not pick one for your channel.");return{preid:t.preid,keep:t.keep??3,packages:t.packages}}function refusePreTagPreid(e,t,n){let r=e.readFile(w.join(t.cwd,co));if(r===null)return;let i=parsePreTag(r);if(i===void 0)throw new T(`${co} exists but has no readable \`tag\`, so this run cannot tell whether the snapshot preid collides with the pre-mode tag. Fix or remove the file.`);if(i===n.preid)throw new T(`.tooling.json#snapshot.preid "${n.preid}" equals the tag in ${co}, so the snapshot prune could delete real prereleases. Pick a different preid.`)}function isMonorepoRepo(e,t){let n=t.toolingConfig?.structure;return n===void 0?e.readFile(w.join(t.cwd,`pnpm-workspace.yaml`))!==null:n===`monorepo`}function refuseUnownedEntries(e,t){if(!t)return;let n=(e.toolingConfig?.releaseAssets??[]).filter(e=>e.package===void 0);if(n.length>0){let e=n[0];throw new T(`release:snapshot cannot build a releaseAssets entry that names no package in a monorepo: ${JSON.stringify(e)}. A snapshot uploads to one package's prerelease, so name the package the entry builds for.`)}let r=(e.toolingConfig?.versionStamp??[]).find(e=>e.package===void 0);if(r!==void 0)throw new T(`release:snapshot cannot stamp a versionStamp entry that names no package in a monorepo: ${JSON.stringify(r)}. A snapshot cuts one version per package, so name the package whose release this entry stamps.`)}function resolvePackages(e,t,n,r){if(r){let r=n.packages;if(r===void 0||r.length===0)throw new T("release:snapshot needs `snapshot.packages` in a monorepo: which packages a tester installs is the repo owner's call, and bst does not guess it.");let i=e.listWorkspacePackages(t.cwd);return r.map(e=>{let n=i.find(t=>t.name===e);if(n===void 0)throw unknownPackageName(e);return{name:e,currentVersion:n.version,dir:w.join(t.cwd,`packages`,n.dir),root:!1}})}let i=rootPackage(e,t.cwd);for(let e of n.packages??[])if(e!==i.name)throw unknownPackageName(e);return[i]}function unknownPackageName(e){return new T(`snapshot.packages names ${e}, which is not a workspace package of this repo. Spell it as its package.json does.`)}function rootPackage(e,t){let n=w.join(t,`package.json`),r=e.readFile(n),i=r===null?void 0:parsePackageJson(r);if(i?.name===void 0||i.version===void 0)throw new T(`release:snapshot cannot snapshot the root package: ${n} carries no name or no version, and a snapshot version is raised from the version it holds.`);return{name:i.name,currentVersion:i.version,dir:t,root:!0}}function resolveBuild(e){let t=process.env.GITHUB_RUN_NUMBER??e.build;if(t===void 0||t===``)throw new T(`release:snapshot needs a build number: GITHUB_RUN_NUMBER is what a CI job supplies, and outside CI --build <n> is the only source. Two cuts sharing a suffix collide on one tag.`);return t}function resolveTarget(e){let t=process.env.GITHUB_SHA??``;if(t===``&&!e.dryRun)throw new T(`release:snapshot needs GITHUB_SHA: the prerelease targets the exact commit the job checked out, so the tag names the code it was built from. --dry-run is the only run that may go without it.`);return t}function createRealForge(e,t){if(t.platform===void 0)throw new T(`Platform connection is required for a snapshot release`);return createSnapshotForge(e,t.platform,t.cwd)}function inertForge(){return{async releaseExists(){return!1},async createPrerelease(){},async uploadAsset(){},async listReleases(){return[]},async deleteRelease(){}}}async function snapshotPackage(e,t){let n=snapshotVersion({currentVersion:t.currentVersion,nextVersion:nextVersionFor(e.status,t.name),preid:e.settings.preid,build:e.build}),r=releaseTag({name:t.name,version:n,root:t.root}),i={packageName:t.name,version:n,tag:r,prerelease:!0,buildNumber:e.build};if(e.config.dryRun)return I.info(`[dry-run] ${t.name} -> ${r} (no forge call)`),{result:{name:t.name,version:n,tag:r},exists:!1};writeWorkingTreeVersion(e,w.join(t.dir,`package.json`),n);let a=stampOwnedVersionFiles(e.executor,e.config.cwd,e.config.toolingConfig,i,e.isMonorepo),o=ownedTargets(e.executor,e.config.cwd,e.config.toolingConfig,t.name,e.isMonorepo),s=buildTargets(e.buildExecutor,o,i,e.config);verifyStamp(e.executor,a),await e.forge.releaseExists(r)?I.info(`Prerelease ${r} already exists, uploading its assets with replacement`):await e.forge.createPrerelease(r,{target:e.target,notes:releaseNotes(e.status,t.name)});for(let t of s)await e.forge.uploadAsset(r,{path:t.path,name:t.name??w.basename(t.path)});return await pruneSnapshots(e.forge,t,e.settings),{result:{name:t.name,version:n,tag:r},exists:!0}}function nextVersionFor(e,t){return e.releases.find(e=>e.name===t)?.newVersion??null}function releaseNotes(e,t){return e.changesets.filter(e=>e.releases.some(e=>e.name===t)).map(e=>`- ${e.summary.trim()}`).join(`
|
|
6102
|
+
`)}function writeWorkingTreeVersion(e,t,n){let r=e.executor.readFile(t);if(r===null)throw new T(`Cannot write the snapshot version: ${t} is not readable.`);e.executor.writeFile(t,he(r,ge(r,[`version`],n,{}))),debug(e.config,`Wrote ${n} into ${t} (working tree only)`)}async function pruneSnapshots(e,t,n){let r=t.root?`v`:`${t.name}@`,i=RegExp(`^${escapeRegExp$1(r)}\\d+\\.\\d+\\.\\d+-${escapeRegExp$1(n.preid)}\\.\\d+$`),a=(await e.listReleases()).filter(e=>i.test(e.tag)).toSorted(byNewestFirst);for(let t of a.slice(n.keep))await e.deleteRelease(t.tag)}function escapeRegExp$1(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function buildOf(e){return Number(e.tag.slice(e.tag.lastIndexOf(`.`)+1))}function byNewestFirst(e,t){let n=buildOf(t)-buildOf(e);if(n!==0)return n;let r=e.createdAt??``,i=t.createdAt??``;return r===i?0:r<i?1:-1}function capturingExecutor(e){return{...e,execInherit(t,n,r){let i=e.exec(t,n,r);if(i.exitCode!==0)throw new T(`Asset build failed (exit ${String(i.exitCode)}):\n${childOutput(i)}`)}}}function appendOutputs(e,t,n){let r=process.env.GITHUB_OUTPUT;if(r===void 0||r===``)return;let i=n.packages[0];e.appendFile(r,`published=${String(n.published)}\nversion=${i?.version??``}\ntag=${i?.tag??``}\npackages=${JSON.stringify(n.packages)}\n`),debug(t,`Wrote snapshot outputs to ${r}`)}const Hl=j({meta:{name:`release:snapshot`,description:"Cut the snapshot-channel prereleases configured in .tooling.json#snapshot: one prerelease per listed package at <version>-<preid>.<build>, with its assets, pruned back to `keep`. Never commits, never moves a floating tag."},args:{build:{type:`string`,description:`Build number for the snapshot suffix. Outside CI, where GITHUB_RUN_NUMBER is unset, this is the only source and the command refuses without it`},"dry-run":{type:`boolean`,description:`Compute and print the cut; write nothing and call no forge`},json:{type:`boolean`,description:`Emit one JSON document: published (boolean) and packages (array of { name, version, tag }). Every key is always present. Asset builds run captured so the document is the only thing on either stream.`},verbose:{type:`boolean`,description:`Enable detailed debug logging (also enabled by TOOLING_DEBUG env var)`}},async run({args:e}){let t=createCliOutput(e.json===!0),n=process.cwd(),r=e[`dry-run`]===!0,i;if(!r){let e=resolveConnection(n);i=e.type===`forgejo`?{type:`forgejo`,conn:e.conn}:{type:`github`}}let a={cwd:n,dryRun:r,verbose:e.verbose===!0||isEnvVerbose(),toolingConfig:loadToolingConfig(n),platform:i,build:e.build,captureBuildOutput:e.json===!0},o=await runReleaseSnapshot(createRealExecutor$1(),a);t.json(o)}}),Ul=j({meta:{name:`checks:failures`,description:`Print the failure digest the last checks:run saved, for the CI step that shows a red run's cause without opening the check log`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Target directory (default: current directory)`,required:!1},json:{type:`boolean`,description:`Emit one JSON document: recorded (boolean), steps ({name, stream, excerpt, truncatedLines}), and reason when the file could not be read.`}},run({args:e}){let t=createCliOutput(e.json===!0),n=w.resolve(e.dir??`.`),r=w.join(n,_o),i=readFailures(n);i.kind===`recorded`?(t.json({recorded:!0,steps:i.failures}),t.text(renderDigest(i.failures).join(`
|
|
6103
|
+
`))):i.kind===`missing`?(t.json({recorded:!1,steps:[]}),t.text(`No failure digest recorded at ${r}.`)):(t.json({recorded:!1,steps:[],reason:i.reason}),t.text(`Failure digest at ${r} is unreadable: ${i.reason}`))}});function runViaShim(e,t){let n=Ft(`pnpm`,e,{cwd:t,maxBuffer:Sn,encoding:`utf-8`,stdio:[`ignore`,`pipe`,`pipe`]}),r=n.stdout??``;return n.error?{stdout:r,stderr:k(n.error),exitCode:1}:{stdout:r,stderr:n.stderr??``,exitCode:n.status??1}}function createRealLintTypesExecutor(){return{run(e,t){let n=execCapture$2(`pnpm`,e,{cwd:t,stdin:`ignore`,keepPartialStdoutOnKill:!1});return n.error!==void 0&&shouldRetryViaShim(n.error)?runViaShim(e,t):{stdout:n.stdout,stderr:n.stderr,exitCode:n.status}}}}function formatRuleCode(e){if(e===void 0)return`(no rule code)`;let t=/^([^()]+)\(([^()]+)\)$/.exec(e);return t?`${t[1]}/${t[2]}`:e}function formatFindingLine(e){let t=e.labels[0]?.span;return`${t?.line!==void 0&&t.column!==void 0?`${e.filename}:${String(t.line)}:${String(t.column)}`:e.filename} ${formatRuleCode(e.code)} ${e.message}`}const Wl=[' - Turn a rule off in this repo\'s own oxlint.config.ts (e.g. "typescript/<rule>": "off") -- plain `pnpm lint` ignores type-aware rules entirely, so this never weakens it.',` - Skip the step entirely with .tooling.json#checks.skip: ["lint:types"].`];function buildFindingsText(e,t,n){if(e.length===0)return`lint:types (${t}): no type-aware findings.`;let r=[`lint:types (${t}): ${String(e.length)} type-aware finding(s):`,...e.map(formatFindingLine),``];return t===`enforce`?r.push(`lint:types is in the enforce phase: these findings block.`):r.push(n?`These block now: .tooling.json#lint.strictTypeAware is set.`:`These will block once a future release of the tooling flips lint:types from the report phase to the enforce phase.`),r.push(...Wl),r.join(`
|
|
6099
6104
|
`)}function findingsExitCode(e,t,n){return e===0?0:t===`enforce`||n?1:0}function missingBinaryText(e,t){let n=[`lint:types: oxlint-tsgolint (the type-aware lint backend) was not found.`,e,"Install it with `pnpm install` -- it is a managed devDependency once this repo is synced."].join(`
|
|
6100
|
-
`);return t?`${n}\n.tooling.json#lint.strictTypeAware is set, so a missing binary is a hard failure rather than a notice.`:n}function buildLintTypesResult(e,t,n){if(e.outcome===`missing-binary`)return{payload:{phase:t,strictTypeAware:n,findings:[],missingBinary:!0,detail:e.detail},text:missingBinaryText(e.detail,n),exitCode:+!!n,marker:null};let r=findingsExitCode(e.findings.length,t,n);return{payload:{phase:t,strictTypeAware:n,findings:e.findings,missingBinary:!1},text:buildFindingsText(e.findings,t,n),exitCode:r,marker:e.findings.length>0&&r===0?formatWarnMarker(e.findings.length):null}}const
|
|
6101
|
-
`);return{payload:{errors:r,warnings:n,findings:e.diagnostics},text:i,exitCode:t,marker:t===0&&n>0?formatWarnMarker(n):null}}const
|
|
6105
|
+
`);return t?`${n}\n.tooling.json#lint.strictTypeAware is set, so a missing binary is a hard failure rather than a notice.`:n}function buildLintTypesResult(e,t,n){if(e.outcome===`missing-binary`)return{payload:{phase:t,strictTypeAware:n,findings:[],missingBinary:!0,detail:e.detail},text:missingBinaryText(e.detail,n),exitCode:+!!n,marker:null};let r=findingsExitCode(e.findings.length,t,n);return{payload:{phase:t,strictTypeAware:n,findings:e.findings,missingBinary:!1},text:buildFindingsText(e.findings,t,n),exitCode:r,marker:e.findings.length>0&&r===0?formatWarnMarker(e.findings.length):null}}const Gl=P.object({offset:P.number(),length:P.number(),line:P.number().optional(),column:P.number().optional()}),Kl=P.object({span:Gl}),ql=P.object({message:P.string(),code:P.string().optional(),filename:P.string(),labels:P.array(Kl).default([]),severity:P.string().optional()}),Jl=P.object({diagnostics:P.array(ql)});function rawSnippet(e){return e.length>500?`${e.slice(0,500)}...`:e}function parseOxlintJson(e){let t;try{t=JSON.parse(e)}catch(t){throw new T(`oxlint -f json output is not valid JSON: ${k(t)}\nOutput: ${rawSnippet(e)}`)}let n=Jl.safeParse(t);if(!n.success)throw new T(`oxlint -f json output doesn't match the expected shape: ${n.error.message}\nOutput: ${rawSnippet(e)}`);return n.data}function diagnosticKey(e){let t=e.labels[0]?.span;return JSON.stringify([e.filename,e.code,t?.offset,t?.length,e.message])}function subtractDiagnostics(e,t){let n=new Set(t.map(diagnosticKey));return e.filter(e=>!n.has(diagnosticKey(e)))}function oxlintArgs(e,t){let n=[`exec`,`oxlint`,`-f`,`json`,`--quiet`],r=e?[`--type-aware`]:[];return[...n,...r,...t,`.`]}function requireJsonOutput(e,t){if(e.stdout.trim()!==``)return e.stdout;throw new T(`${t} exited ${String(e.exitCode)} with no JSON output: ${rawSnippet(e.stderr)}`)}function runLintTypes(e,t,n=[]){let r=e.run(oxlintArgs(!0,n),t),i;try{i=parseOxlintJson(requireJsonOutput(r,`oxlint --type-aware`))}catch(e){let t=`${r.stdout}${r.stderr}`;if(t.includes(`Failed to find tsgolint executable`))return{outcome:`missing-binary`,detail:t.trim()};throw e}let a=parseOxlintJson(requireJsonOutput(e.run(oxlintArgs(!1,n),t),`oxlint`));return{outcome:`findings`,findings:subtractDiagnostics(i.diagnostics,a.diagnostics)}}const Yl=j({meta:{name:`lint:types`,description:`Run oxlint --type-aware (backed by oxlint-tsgolint) and report every type-aware finding, selected by subtracting a plain oxlint run. Enforce phase: prints findings and exits 1 when there are any. .tooling.json#lint.strictTypeAware makes a missing oxlint-tsgolint binary a failure instead of a notice.`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Project directory (default: current directory)`,required:!1},json:{type:`boolean`,description:`Emit one JSON document: phase (report | enforce), strictTypeAware, findings ([{message, code?, filename, labels ([{span: {offset, length, line?, column?}}]), severity?}]), missingBinary, detail? (present only when missingBinary is true).`}},run({args:e,rawArgs:t}){let n=createCliOutput(e.json===!0),r=t.indexOf(`--`),i=r===-1?[]:t.slice(r+1),a=r===-1?e.dir:t.slice(0,r).find(e=>!e.startsWith(`-`)),o=w.resolve(a??`.`),s=loadToolingConfig(o)?.lint?.strictTypeAware===!0,{payload:c,text:l,exitCode:u,marker:d}=buildLintTypesResult(runLintTypes(createRealLintTypesExecutor(),o,i),`enforce`,s);n.json(c),l!==``&&n.text(l),d!==null&&n.text(d),process.exitCode=u}});function buildLintReportResult(e,t){let n=e.diagnostics.filter(e=>e.severity===`warning`).length,r=e.diagnostics.length-n,i=e.diagnostics.length===0?``:[...e.diagnostics.map(formatFindingLine),`oxlint: ${String(r)} error(s), ${String(n)} warning(s)`].join(`
|
|
6106
|
+
`);return{payload:{errors:r,warnings:n,findings:e.diagnostics},text:i,exitCode:t,marker:t===0&&n>0?formatWarnMarker(n):null}}const Xl=j({meta:{name:`lint:report`,description:"Run oxlint for the checks:run pipeline: report every finding, exit with oxlint's own exit code, and print the ::bst-checks:: warn marker when the run passes with warnings so the lint step reports warned instead of silently ok. The checks:run lint step runs it instead of lint when the repo defines a lint:report script. Developers run plain `pnpm lint`; this is the pipeline's and the machine reader's surface."},args:{dir:{type:`positional`,valueHint:`dir`,description:`Project directory (default: current directory)`,required:!1},json:{type:`boolean`,description:`Emit one JSON document: errors, warnings, findings ([{message, code?, filename, labels ([{span: {offset, length, line?, column?}}]), severity?}]; no severity counts as an error).`}},run({args:e,rawArgs:t}){let n=createCliOutput(e.json===!0),r=t.indexOf(`--`),i=r===-1?[]:t.slice(r+1),a=r===-1?e.dir:t.slice(0,r).find(e=>!e.startsWith(`-`)),o=w.resolve(a??`.`),s=createRealLintTypesExecutor().run([`exec`,`oxlint`,`-f`,`json`,...i,`.`],o),{payload:c,text:l,exitCode:u,marker:d}=buildLintReportResult(parseOxlintJson(requireJsonOutput(s,`oxlint`)),s.exitCode);n.json(c),l!==``&&n.text(l),d!==null&&n.text(d),process.exitCode=u}});function requireDockerCredentials(e){let t=process.env.DOCKER_USERNAME,n=process.env.DOCKER_PASSWORD;if(t&&n)return{username:t,password:n};let r=[...t?[]:[`DOCKER_USERNAME`],...n?[]:[`DOCKER_PASSWORD`]].join(` / `),{username:i,password:a}=dockerSecretNames(e);throw new T(`Missing required environment variable(s): ${r}. On CI, these env vars are populated from registry-specific secrets -- for registry "${e}", that's secrets.${i} / secrets.${a}. Set those on the repository (try \`pnpm exec bst setup:secrets\`), or export DOCKER_USERNAME / DOCKER_PASSWORD locally.`)}function resolveRegistryConfig(e){let t=process.env.DOCKER_REGISTRY_HOST,n=process.env.DOCKER_REGISTRY_NAMESPACE;if(t&&n)return{registryHost:t,registryNamespace:n};let r=loadToolingConfig(e),i=r?.registryHost,a=r?.registryNamespace;if(i&&a)return{registryHost:t??i,registryNamespace:n??a};let o=resolveOperationalRepo(e);if(o){let e=registryHostFromHostname(o.hostname),r=o.repository.split(`/`)[0],s=t??i??e;return{registryHost:s,registryNamespace:n??a??`${s}/${r}`}}throw new T(`Could not determine docker registry. Set DOCKER_REGISTRY_HOST and DOCKER_REGISTRY_NAMESPACE, or add registryHost/registryNamespace to .tooling.json, or ensure package.json has a repository URL.`)}const Zl=j({meta:{name:`docker:publish`,description:`Build, tag, and push all discovered Docker images`},args:{"dry-run":{type:`boolean`,description:`Build and tag images but skip login, push, and logout`},image:{type:`string`,description:`Publish only this image, by its final image name, without the release bound (repeatable)`},verbose:{type:`boolean`,description:`Emit detailed debug logging`}},async run({args:e,rawArgs:t}){let n=process.cwd(),{registryHost:r,registryNamespace:i}=resolveRegistryConfig(n),{username:a,password:o}=requireDockerCredentials(r),s={cwd:n,registryHost:r,registryNamespace:i,username:a,password:o,dryRun:e[`dry-run`]===!0,verbose:e.verbose===!0||isEnvVerbose(),releaseStrategy:loadToolingConfig(n)?.releaseStrategy??`none`,images:collectFlagValues(t,`--image`)};runDockerPublish(createRealExecutor$1(),s)}});function detectSubpackage(e){let t=w.dirname(e);return w.basename(t)===`packages`&&o(w.join(t,`..`,`package.json`))?{root:w.dirname(t),packageDir:`packages/${w.basename(e)}`}:{root:e,packageDir:void 0}}const Ql=j({meta:{name:`docker:build`,description:`Build Docker images for packages with docker config in .tooling.json`},args:{package:{type:`string`,description:`Build a single package by directory path (e.g. packages/server). Useful as an image:build script.`},verbose:{type:`boolean`,description:`Emit detailed debug logging`},_:{type:`positional`,required:!1,description:`Extra arguments passed to docker build (after --)`}},async run({args:e}){let t=createRealExecutor$1(),n=e._??[],r=Array.isArray(n)?n.map(String):[String(n)],i=e.verbose===!0||isEnvVerbose(),a=process.cwd(),o=e.package;if(!o){let e=detectSubpackage(a);a=e.root,o=e.packageDir}runDockerBuild(t,{cwd:a,packageDir:o,extraArgs:r.filter(e=>e.length>0),verbose:i})}});function execCapture(e,t,n){let r={cwd:n?.cwd,env:n?.env?{...process.env,...n.env}:void 0,encoding:`utf-8`,stdio:[`pipe`,`pipe`,`pipe`],maxBuffer:67108864},i=pe(e,t,r);shouldRetryViaShim(i.error)&&(i=Ft(e,t,r));let a=i.stderr??``;return i.error&&(a=a.trim()===``?i.error.message:`${a}\n${i.error.message}`),{stdout:i.stdout??``,stderr:a,exitCode:i.status??1}}function createRealExecutor(){return{exec:execCapture,async execStream(e,t,n,r,i){let a=execCapture(e,t,n);if(r)for(let e of a.stdout.split(`
|
|
6102
6107
|
`))e.length>0&&r(e);if(i)for(let e of a.stderr.split(`
|
|
6103
|
-
`))e.length>0&&i(e);return a},execInherit(e,t,n){let r={cwd:n?.cwd,env:n?.env?{...process.env,...n.env}:void 0,stdio:`inherit`,detached:n?.detached??!1},i=pe(e,t,r);if(shouldRetryViaShim(i.error)&&(i=Ft(e,t,r)),i.error)throw i.error;if(i.status!==0)throw new D(`Command failed with exit code ${String(i.status)}: ${[e,...t].join(` `)}`)},fetch:globalThis.fetch,now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e)),onSignal(e,t){return process.on(e,t),()=>{process.removeListener(e,t)}},onExit(e){return process.on(`exit`,e),()=>{process.removeListener(`exit`,e)}},log:e=>console.log(e),logError:e=>console.error(e)}}function findFreePort(){return new Promise((e,t)=>{let n=Ne.createServer();n.unref(),n.once(`error`,t),n.listen(0,()=>{let r=n.address();if(r===null||typeof r==`string`){n.close(),t(new D(`Could not determine an allocated free port`));return}let{port:i}=r;n.close(()=>{e(i)})})})}const
|
|
6104
|
-
`).join(`,`)}]`,t=r.safeParse(JSON.parse(e));return t.success?t.data:[]}catch{return[]}}const Dl=`curlimages/curl:8.23.0@sha256:3fb7e13e5d179a845c97d78204f3f1064d1907037f26a3ebf91710571151fd93`;function getContainerHealth(e,t){return e.find(e=>e.Service===t)?.Health??`unknown`}function getContainerExitCode(e,t){let n=e.find(e=>e.Service===t);if(n?.State===`exited`)return n.ExitCode}function getContainerId(e,t){return e.find(e=>e.Service===t)?.ID}async function checkHttpHealthViaNetwork(e,t,n,r,i){let a=getContainerId(i,r);if(a===void 0)return!1;let o=e.exec(`docker`,[`run`,`--rm`,`--network`,`container:${a}`,Dl,`curl`,`-s`,`-o`,`/dev/null`,`-w`,`%{http_code}`,`--connect-timeout`,`5`,`--max-time`,`5`,n.url],{cwd:t.cwd,env:t.env});if(o.exitCode===125)throw new D(`docker run failed to start the probe image ${Dl}: ${o.stderr.trim()||`(no stderr captured)`}`);let s=Number.parseInt(o.stdout,10),c={status:Number.isNaN(s)?0:s,ok:s>=200&&s<300};return await n.validate(c)}async function checkHttpHealth(e,t,n,r){if(n.viaNetworkService!==void 0)return checkHttpHealthViaNetwork(e,t,n,n.viaNetworkService,r);try{let t=await e.fetch(n.url);return await n.validate(t)}catch{return!1}}function withFilledVariables(e,t){let n=fillUnsetVariables(e,t.compose),r=Object.keys(n);return r.length===0?t:(e.log(`Unset compose variables set to an empty string: ${r.join(`, `)}. To supply real values, put them in ${t.compose.envFile??`docker-compose.check.env`} beside the compose file.`),{...t,compose:{...t.compose,env:{...t.compose.env,...n}}})}async function updateHttpHealth(e,t,n,r,i){for(let a of n)r.get(a.name)||await checkHttpHealth(e,t,a,i)&&(r.set(a.name,!0),e.log(`${a.name} is healthy!`))}function runSmoketestStep(e,t,n,r){if(!t.smoketest)return null;let{compose:i}=t;e.log(`Running smoketest: ${t.smoketest.join(` `)}`);try{return runSmoketest(e,t),e.log(`Smoketest passed!`),null}catch(t){let a=O(t);e.logError(`Smoketest failed: ${a}`),composePsDump(e,i);for(let t of i.services)composeLogs(e,i,t);return n(),{success:!1,reason:`smoketest-failed`,message:a,elapsedMs:e.now()-r}}}async function runDockerCheck(e,t){let n=withFilledVariables(e,t),r=n.timeoutMs??12e4,i=n.pollIntervalMs??5e3,{compose:a}=n,o={verbose:n.verbose??!1};debug(o,`Compose files: ${a.composeFiles.join(`, `)}`),debug(o,`Services: ${a.services.join(`, `)}`),debug(o,`Health checks: ${n.healthChecks.map(e=>e.name).join(`, `)||`(none)`}`),debug(o,`Timeout: ${String(r)}ms, poll interval: ${String(i)}ms`);let s=!1,cleanup=()=>{s||(s=!0,composeDown(e,a))},gracefulShutdown=()=>{s?e.log(`Cleanup already done or in progress, please wait...`):(e.log(`Interrupted -- shutting down compose stack...`),cleanup(),process.exit(1))},c=e.onSignal(`SIGINT`,gracefulShutdown),l=e.onSignal(`SIGTERM`,gracefulShutdown),u=e.onSignal(`SIGHUP`,gracefulShutdown),d=e.onExit(cleanup);try{n.buildCommand&&(e.log(`Building images...`),buildImages(e,n)),e.log(`Starting compose stack...`);let t=e.now();try{composeUp(e,a)}catch(n){let r=O(n);e.logError(`Compose stack failed to start -- dumping logs`),composePsDump(e,a);for(let t of a.services)composeLogs(e,a,t);return composeHealthLogs(e,a),cleanup(),{success:!1,reason:`startup-failed`,message:r,elapsedMs:e.now()-t}}e.log(`Waiting for stack to be healthy (max ${r/1e3}s)...`);let s=t,c=!1,l=new Map(n.healthChecks.map(e=>[e.name,!1]));for(;e.now()-t<r;){let r=composePs(e,a);debug(o,`compose ps: ${r.length} container(s)`);let u=!0,d=!1;for(let n of a.services){let i=getContainerHealth(r,n);if(debug(o,`Container ${n}: ${i||`(no healthcheck)`}`),i!==``&&i!==`unknown`&&(d=!0),i===`unhealthy`)return e.logError(`Container ${n} is unhealthy`),composePsDump(e,a),composeLogs(e,a,n),composeHealthLogs(e,a),cleanup(),{success:!1,reason:`unhealthy-container`,message:n,elapsedMs:e.now()-t};i===`starting`&&(u=!1);let s=getContainerExitCode(r,n);if(s!==void 0&&s!==0){let r=`${n} exited with code ${String(s)}`;return e.logError(`Container ${r}`),composePsDump(e,a),composeLogs(e,a,n),cleanup(),{success:!1,reason:`container-exited`,message:r,elapsedMs:e.now()-t}}}if(await updateHttpHealth(e,a,n.healthChecks,l,r),u&&[...l.values()].every(Boolean)){if(!c&&n.healthChecks.length===0&&!d){c=!0,debug(o,`Nothing gates this stack -- settle poll before declaring success`),await e.sleep(i);continue}return runSmoketestStep(e,n,cleanup,t)||(e.log(`Check successful! All systems operational.`),cleanup(),{success:!0,elapsedMs:e.now()-t})}let f=e.now();if(f-s>=5e3){s=f;let n=Math.floor((f-t)/1e3),i=[a.services.map(e=>`${e}=${getContainerHealth(r,e)}`).join(`, `),[...l.entries()].map(([e,t])=>`${e}=${t?`OK`:`Pending`}`).join(`, `)].filter(Boolean).join(` | `);e.log(`Waiting... (${n}s elapsed). ${i}`)}await e.sleep(i)}e.logError(`Timeout waiting for stack to become healthy`),composePsDump(e,a);for(let t of a.services)composeLogs(e,a,t);return composeHealthLogs(e,a),cleanup(),{success:!1,reason:`timeout`,message:`Exceeded timeout`,elapsedMs:e.now()-t}}catch(e){return cleanup(),{success:!1,reason:`error`,message:O(e),elapsedMs:0}}finally{c(),l(),u(),d()}}function deriveProjectName(e,t=process.env){return`${sanitize(e)}-check-${sanitize(t.GITHUB_RUN_ID??t.CI_RUN_ID??String(process.pid))}`}function sanitize(e){return e.replace(/^@[^/]+\//,``).toLowerCase().replace(/[^a-z0-9_-]+/g,`-`).replace(/^-+|-+$/g,``)||`repo`}function toHttpHealthChecks(e){return e.map(e=>({name:e.name,url:e.url,validate:async t=>e.status?t.status===e.status:t.ok,viaNetworkService:e.viaNetworkService}))}function writeTempOverlay(e){let t=d(w.join(be(),`tooling-check-`)),n=w.join(t,`overlay.yaml`);return C(n,e,`utf-8`),n}const Ol=A({meta:{name:`docker:check`,description:`Check Docker Compose stack health by auto-detecting services from compose files`},args:{timeout:{type:`string`,description:`Maximum time to wait for health checks, in ms (default: 120000)`},"poll-interval":{type:`string`,description:`Interval between polling attempts, in ms (default: 5000)`},verbose:{type:`boolean`,description:`Emit detailed debug logging`}},async run({args:e}){let t=process.cwd(),n=createFileReader(),r=n.readFile(w.join(t,`package.json`)),i=r?parsePackageJson(r):void 0,a=deriveProjectName(i?.name??w.basename(t)),o=createRealExecutor(),s=loadToolingConfig(t);if(s?.dockerCheck===!1){F.info(`Docker check is disabled in .tooling.json`);return}let c={...computeCheckDefaults(t),...s?.dockerCheck};if(!c.composeFiles||c.composeFiles.length===0){F.warn(`No compose files found -- nothing to health-check. Add docker-compose.yaml (plus a docker-compose.check.yaml overlay) in ./ or docker/ to enable docker:check.`),F.warn(`To suppress this warning, set "dockerCheck": false in .tooling.json.`);return}if(!c.checkOverlay){let e=c.composeCwd??t,n=deriveCheckOverlayName(c.composeFiles[0]??`docker-compose.yaml`);F.warn(`Compose files found but no check overlay. Create ${w.relative(t,w.join(e,n))} to enable docker:check.`),F.warn(`To suppress this warning, set "dockerCheck": false in .tooling.json.`);return}if(!c.services||c.services.length===0)throw new T(`No services found in compose files.`);let l=c.composeCwd??t,u=parseCheckComposeServices(l,c.composeFiles,c.checkOverlay),d=u.filter(startsUnderCheckProfile),f=findOverlayHealthcheckTimingOverrides(l,c.checkOverlay);f.length>0&&F.warn(`Check-overlay healthcheck timing overrides the fast docker:check intervals for: ${f.join(`, `)}. Remove interval/timeout/retries/start_period/start_interval from the overlay's healthcheck to restore them.`);let p=[];if(i?.name){let e=detectDockerPackages(n,t,i.name);for(let t of e)p.push(t.imageName);let r=crossReferenceDockerImages(e.map(e=>({dir:e.dir,imageName:e.imageName,dockerfileAbs:w.resolve(t,e.docker.dockerfile)})),u);for(let e of r)e.kind===`unreferenced`?F.warn(`Docker package "${e.dir}" (image: ${e.imageName}) is not referenced in any compose service.`):F.warn(`Docker package "${e.dir}" is built by a compose service with no \`image: ${e.imageName}\` -- docker:check rebuilds it instead of reusing the docker:build output (double build). Add \`image: ${e.imageName}\` to that service.`)}let m=writeTempOverlay(generateCheckOverlay(d,p)),h=[...c.composeFiles,m,c.checkOverlay],g=d.filter(e=>e.portEnvVar===`PORT`),_;if(g.length>0){g.length>1&&F.warn(`Multiple services reference \${PORT} (${g.map(e=>e.name).join(`, `)}); they cannot share a host port.`);let e=process.env.PORT??(c.envFile===void 0?void 0:composeEnvFileValue(l,c.envFile,`PORT`));if(e!==void 0)F.info(`PORT is already set (${e}) -- using the configured value.`);else{let e=await findFreePort();_={PORT:String(e)},F.info(`Allocated free host port ${String(e)} for \${PORT}.`)}}try{let t=await runDockerCheck(o,{compose:{cwd:l,composeFiles:h,projectName:a,envFile:c.envFile,env:_,services:c.services},buildCommand:c.buildCommand,buildCwd:c.buildCwd,healthChecks:c.healthChecks?toHttpHealthChecks(c.healthChecks):[],smoketest:c.smoketest,smoketestCwd:c.smoketestCwd,timeoutMs:e.timeout?Number.parseInt(e.timeout,10):c.timeoutMs,pollIntervalMs:e[`poll-interval`]?Number.parseInt(e[`poll-interval`],10):c.pollIntervalMs,verbose:e.verbose===!0||isEnvVerbose()});if(!t.success)throw new T(`Check failed (${t.reason}): ${t.message}`)}finally{try{y(w.dirname(m),{recursive:!0})}catch{}}}});function parseMaxAgeHours(e){let t=Number(e);if(e.trim()===``||!Number.isFinite(t)||t<0)throw new T(`--max-age must be a non-negative number of hours, got "${e}"`);return t}const kl=A({meta:{name:`docker:sweep`,description:`Reclaim containers, networks and volumes leaked by past docker:check runs, and the agent's own leaked containers, sidecars and networks`},args:{"dry-run":{type:`boolean`,description:`Report what would be reclaimed without removing anything`},json:{type:`boolean`,description:`Emit one JSON document: containers, networks, volumes, failed, dryRun.`},"max-age":{type:`string`,description:`Only reclaim resources older than this many hours (default: 4). 0 removes the age guard, so a container still running is reclaimed too`}},run({args:e}){let t=e[`max-age`]===void 0?144e5:parseMaxAgeHours(e[`max-age`])*36e5,n=createCliOutput(e.json===!0),r=runSweep({...createRealExecutor(),log:e=>n.notice(e)},{dryRun:e[`dry-run`]===!0,maxAgeMs:t});n.json(r);let i=r.dryRun?`Would reclaim`:`Reclaimed`,a=r.failed.length===0?``:` ${String(r.failed.length)} removal(s) failed.`;n.text(`${i} ${String(r.containers.length)} container(s), ${String(r.networks.length)} network(s), ${String(r.volumes.length)} volume(s).${a}`)}});function findProjectRoot(e){let t=w.resolve(e);for(;;){if(o(w.join(t,`.claude`)))return t;let n=w.dirname(t);if(n===t)return e;t=n}}const Al=N.object({timestamp:N.string(),sessionId:N.string(),cwd:N.string().optional(),command:N.string(),decision:N.enum([`allow`,`deny`,`passthrough`,`none`]).transform(e=>e===`passthrough`?`none`:e),rule:N.string().nullable(),reason:N.string().nullable(),permissionMode:N.string().optional()});function countDecisions(e){let t={allow:0,deny:0,none:0};for(let n of e)t[n.decision]++;return t}function countByMode(e){let t={};for(let n of e)n.permissionMode!==void 0&&(t[n.permissionMode]=(t[n.permissionMode]??0)+1);return t}function parseTailCount(e){let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new T(`--tail must be a positive whole number of entries, got "${e}"`);return t}function parseAuditLog(e){if(!o(e))return[];let t=p(e,`utf-8`).split(`
|
|
6105
|
-
`).filter(Boolean),n=[];for(let e of t)try{let t=Al.safeParse(JSON.parse(e));t.success&&n.push(t.data)}catch{}return n}function topCommands(e,t){let n=/* @__PURE__ */ new Map;for(let t of e){let e=n.get(t.command);e?e.count++:n.set(t.command,{command:t.command,count:1,rule:t.rule})}return[...n.values()].toSorted((e,t)=>t.count-e.count).slice(0,t)}function printSection(e,t,n,r){let i=topCommands(n,r);if(i.length!==0){e.text(t);for(let{command:t,count:n,rule:r}of i){let i=r?` [${r}]`:``;e.text(` ${String(n).padStart(4)}x ${t}${i}`)}e.text(``)}}const jl=A({meta:{name:`hooks:audit`,description:`Summarize the bst-hook audit log`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Project directory (default: current directory)`,required:!1},tail:{type:`string`,description:`Show the last N raw entries`},decision:{type:`string`,description:`Filter by decision: allow, deny, or none (passthrough is an alias for none)`},json:{type:`boolean`,description:`Emit one JSON document: entries ([{timestamp, sessionId, cwd?, command, decision (allow | deny | none), rule (or null), reason (or null), permissionMode?}]), counts ({allow, deny, none}), byMode? ({<mode>: count}). --tail limits entries, not counts; an empty log gives entries alone.`}},async run({args:e}){let t=createCliOutput(e.json===!0),n=e.dir?w.resolve(e.dir):findProjectRoot(process.cwd()),r=w.join(n,`.claude/hooks/bst-hook.audit.local.jsonl`),i=e.tail===void 0?null:parseTailCount(e.tail),a=parseAuditLog(r);if(a.length===0){t.json({entries:[]}),t.text(`No audit log entries found.`);return}let o=e.decision===`passthrough`?`none`:e.decision;if(o&&(a=a.filter(e=>e.decision===o)),e.json===!0){let e=countByMode(a);t.json({entries:i===null?a:a.slice(-i),counts:countDecisions(a),...Object.keys(e).length>0?{byMode:e}:{}});return}if(i!==null){for(let e of a.slice(-i)){let n=new Date(e.timestamp).toLocaleString(),r=e.rule?` [${e.rule}]`:``;t.text(`${n} ${e.decision.padEnd(12)}${e.command}${r}`)}return}let s=countDecisions(a);t.text(`${String(a.length)} entries: ${String(s.allow)} allow, ${String(s.deny)} deny, ${String(s.none)} none`),t.text(``);let c=countByMode(a);if(Object.keys(c).length>0){t.text(`By permission mode:`);for(let[e,n]of Object.entries(c).toSorted((e,t)=>t[1]-e[1]))t.text(` ${String(n).padStart(4)}x ${e}`);t.text(``)}let l=a.filter(e=>e.decision===`deny`),u=a.filter(e=>e.decision===`none`);printSection(t,`Denied commands:`,l,10),printSection(t,`None commands:`,u,10)}});function buildMinimalConfig(e){let t=o(w.join(e,`pnpm-workspace.yaml`));return{name:w.basename(e),structure:t?`monorepo`:`single`,stack:detectStack(e),builder:detectBuilder(e,readPackageJson(e)),useEslintPlugin:!0,formatter:`oxfmt`,setupVitest:!1,ci:`none`,setupRenovate:!1,releaseStrategy:`none`,publishNpm:!1,publishDocker:!1,projectType:`default`,detectPackageTypes:!1,targetDir:e}}async function runHookGenerators(e){let t=[];return t.push(...await generateClaudeHooks(e)),t.push(...await generateClaudeSettings(e)),t}const Ml=A({meta:{name:`hooks:sync`,description:`Deploy or update the bst-hook and Claude settings (without touching other tooling)`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Target directory (default: current directory)`,required:!1},check:{type:`boolean`,description:`Dry-run mode: report drift without writing files`},json:{type:`boolean`,description:`Emit one JSON document: status (up-to-date | synced | drift | failed), check, actionable, all, failed, exitCode.`}},async run({args:e}){let t=createCliOutput(e.json===!0),n=buildMinimalConfig(w.resolve(e.dir??`.`)),r=e.check?await runHooksCheck(n):await runHooksSync(n);t.json(r),process.exitCode=r.exitCode}});async function runHooksSync(e){let{ctx:t}=createContext(e,async()=>`overwrite`),n=await runHookGenerators(t),r=failedResults(n);reportFailures(r,`hooks:sync`);let i=n.filter(e=>e.action===`created`),a=n.filter(e=>e.action===`updated`),o=n.filter(e=>e.action===`removed`),s=[...i,...a,...o];if(!(s.length>0))return r.length===0&&F.success(`Hooks are up to date.`),{status:r.length>0?`failed`:`up-to-date`,check:!1,actionable:s,all:n,failed:r,exitCode:+(r.length>0)};for(let e of s)F.info(`${e.action}: ${e.filePath} -- ${e.description}`);return r.length===0&&F.success(`Hooks synced.`),{status:r.length>0?`failed`:`synced`,check:!1,actionable:s,all:n,failed:r,exitCode:+(r.length>0)}}async function runHooksCheck(e){let{ctx:t,pendingWrites:n}=createDryRunContext(e),r=await runHookGenerators(t),i=failedResults(r);reportFailures(i,`hooks:sync`);let a=r.filter(t=>{if(t.action===`removed`)return!0;if(t.action!==`created`&&t.action!==`updated`)return!1;let r=n.get(t.filePath);if(r!==void 0&&t.action===`updated`){let n=w.join(e.targetDir,t.filePath),i=o(n)?p(n,`utf-8`):void 0;if(i&&contentEqual(t.filePath,i,r))return!1}return!0});if(a.length===0&&i.length===0)return F.success(`Hooks are up to date.`),{status:`up-to-date`,check:!0,actionable:a,all:r,failed:i,exitCode:0};if(a.length>0){F.warn(`${String(a.length)} file(s) would be changed by hooks:sync`);for(let e of a)F.info(` ${e.action}: ${e.filePath} -- ${e.description}`)}return{status:i.length>0?`failed`:`drift`,check:!0,actionable:a,all:r,failed:i,exitCode:1}}const Nl=N.record(N.string(),N.unknown());function previousState(e){let t=e.agent?.enabled;return t===void 0?`absent`:t===!0?`true`:`false`}function withAgentEnabled(e){let t=Nl.safeParse(e.agent),n=t.success?{...t.data}:{};return n.enabled=!0,{...e,agent:n}}const Pl=/* @__PURE__ */ new Set([`created`,`updated`,`removed`,`archived`]);async function runSetupAgent(e,t){let n=loadToolingConfigStrict(e);if(n===void 0)throw new T(`No .tooling.json in ${e}. Run pnpm exec bst repo:sync first to create one, so the repo's own conventions are chosen before the agent is enabled.`);let r=previousState(n),i=`already-enabled`;if(r!==`true`){let t=w.join(e,`.tooling.json`),r;try{r=JSON.parse(p(t,`utf8`))}catch(e){throw new T(`Could not read ${t} as JSON: ${O(e)}`)}let a=Nl.safeParse(r);if(!a.success)throw new T(`Could not read ${t} as a config object: ${a.error.message}`);let o=withAgentEnabled(a.data),s=`${JSON.stringify(o,null,2)}\n`;parseToolingConfigStrict(s,t);let c=createContext(mergeWithSavedConfig(buildDefaultConfig(e,{}),n),async()=>`overwrite`);c.ctx.write(`.tooling.json`,c.ctx.format(`.tooling.json`,s)),i=`written`}i===`written`?F.success(`Set agent.enabled to true in .tooling.json`):F.info(`agent.enabled is already true`);let a=await runUpdateReport(e,{},{installOutput:t.installOutput}),o=failedResults(a.results),s=a.results.filter(e=>Pl.has(e.action)).map(e=>({filePath:e.filePath,action:e.action})),c;return c=a.status===`stopped`||o.length>0?`failed`:s.length>0?`changed`:`up-to-date`,c===`failed`?F.error(`The sync failed. Fix what it reported, then run pnpm exec bst setup:agent again.`):F.info(`Commit these changes and land them on the default branch; the agent reads consent there within about a minute.`),{dir:e,consent:i,previous:r,sync:{status:c,changed:s,failed:o,install:a.install},exitCode:+(c===`failed`)}}const Fl=A({meta:{name:`setup:agent`,description:`Enable the agent for this repository: set agent.enabled to true in .tooling.json, then run the same sync as repo:sync, which installs @bensandee/agent-cli and generates the files the agent reads. Commits nothing -- land the change on the default branch yourself.`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Directory to enable (default: current directory)`,required:!1},json:{type:`boolean`,description:`Output the report as JSON: dir, consent, previous, sync { status, changed, failed, install }, exitCode`}},async run({args:e}){let t=await runSetupAgent(w.resolve(e.dir??`.`),{installOutput:e.json===!0||isJsonMode()?`capture`:`inherit`});createCliOutput(e.json===!0).json(t),process.exitCode=t.exitCode}});function isCancelled(e){return j.isCancel(e)}const Il=[`read:user`,`write:organization`,`write:package`,`write:repository`,`write:issue`];function createForgejoSecretsProvider(e,t){return{async setSecret(n,r,i){await setActionSecret(e,t,r,i)}}}function createForgejoUserSecretsProvider(e,t,n){let r=`Basic ${btoa(`${t.username}:${t.password}`)}`,i=n;return{async setSecret(n,a,o){try{await setUserActionSecret(e,{serverUrl:t.serverUrl,authorization:r,secretName:a,secretValue:o,otp:i})}catch(n){if(!(n instanceof OtpRequiredError))throw n;F.info(i?`2FA code expired.`:`2FA is required for user-level secrets.`);let s=await j.text({message:`Enter 2FA/TOTP code to set ${a}`,validate:e=>!e||e.length===0?`Code is required`:void 0});isCancelled(s)&&(j.cancel(`Cancelled.`),process.exit(0)),i=s,await setUserActionSecret(e,{serverUrl:t.serverUrl,authorization:r,secretName:a,secretValue:o,otp:i})}}}}function createGitHubSecretsProvider(e){return{async setSecret(t,n,r){let i=e.exec(`gh`,[`secret`,`set`,n,`--body`,r,`-R`,t]);if(i.exitCode!==0)throw new T(`Failed to set GitHub secret ${n}: ${i.stderr}`)}}}function resolveDockerSecretPackages(e,t,n,r,i){return r||!i?[]:detectDockerPackages(e,t,n)}function computeSecretNames(e,t){let n=[`RELEASE_TOKEN`];if(e&&t!==void 0){let{username:e,password:r}=dockerSecretNames(t);n.push(e,r)}return n}async function runSetupSecrets(e,t){let n=t.repository.split(`/`)[1]??t.repository,r=[];if(t.dryRun?F.info(`[dry-run] Would set secret RELEASE_TOKEN on ${t.repository}`):(F.info(`Setting RELEASE_TOKEN secret...`),await e.setSecret(t.repository,`RELEASE_TOKEN`,t.releaseToken),F.success(`Set RELEASE_TOKEN`)),r.push({name:`RELEASE_TOKEN`,value:t.releaseToken}),t.dockerPackages.length>0){F.info(`Detected ${String(t.dockerPackages.length)} Docker package(s) -- setting Docker secrets`);let i=t.repository.split(`/`)[0]??n,a=t.dockerCredentials?.username??i,o=t.dockerCredentials?.password??t.releaseToken;t.dockerCredentials||F.info(`Using defaults for Docker secrets: username="${a}", password=<release token>`);let{username:s,password:c}=dockerSecretNames(t.dockerRegistryHost??null);t.dryRun?(F.info(`[dry-run] Would set secret ${s} on ${t.repository}`),F.info(`[dry-run] Would set secret ${c} on ${t.repository}`)):(await e.setSecret(t.repository,s,a),F.success(`Set ${s}`),await e.setSecret(t.repository,c,o),F.success(`Set ${c}`)),r.push({name:s,value:a}),r.push({name:c,value:o})}return{secrets:r}}async function createForgejoReleaseToken(e,t){let n=t.repository.split(`/`)[1]??t.repository,r=t.userSecrets?`bst-release`:`bst-release-${n}`,i=Il;if(t.dryRun)return F.info(`[dry-run] Would create access token "${r}" for ${t.username}`),F.info(`[dry-run] Scopes: ${i.join(`, `)}`),{token:`dry-run-token`,tokenName:r};F.info(`Creating access token "${r}"...`);let attempt=async n=>{try{return await createAccessToken(e,{serverUrl:t.serverUrl,username:t.username,password:t.password,tokenName:r,scopes:i,otp:n})}catch(e){throw e instanceof Error&&/\b4\d{2}\b/.test(e.message)&&e.message.includes(`already`)?new T(`Access token "${r}" already exists. Delete it in Forgejo settings and re-run, or set secrets manually.`):e}};try{let e=await attempt(t.otp);return F.success(`Created access token "${r}"`),{token:e,tokenName:r,otp:t.otp}}catch(e){if(e instanceof OtpRequiredError){F.info(`2FA is enabled on this account.`);let e=await j.text({message:`Enter 2FA/TOTP code`,validate:e=>!e||e.length===0?`Code is required`:void 0});isCancelled(e)&&(j.cancel(`Cancelled.`),process.exit(0));let t=await attempt(e);return F.success(`Created access token "${r}"`),{token:t,tokenName:r,otp:e}}throw e}}async function setupForgejo(e,t,n,r){let i=await j.select({message:`Where should secrets be stored?`,options:[{value:`repo`,label:`Repository-level`,hint:`scoped to this repository only`},{value:`user`,label:`User-level`,hint:`shared across all your repositories`}]});isCancelled(i)&&(j.cancel(`Cancelled.`),process.exit(0));let a=i===`user`,o=await j.text({message:`Enter Forgejo username`,validate:e=>!e||e.length===0?`Username is required`:void 0});isCancelled(o)&&(j.cancel(`Cancelled.`),process.exit(0));let s=await j.password({message:`Enter Forgejo password`,validate:e=>!e||e.length===0?`Password is required`:void 0});isCancelled(s)&&(j.cancel(`Cancelled.`),process.exit(0));let c=await createForgejoReleaseToken(e,{serverUrl:t,repository:n,username:o,password:s,dryRun:r,userSecrets:a}),l={serverUrl:t,repository:n,token:c.token};return{provider:a?createForgejoUserSecretsProvider(e,{serverUrl:t,username:o,password:s},c.otp):createForgejoSecretsProvider(e,l),releaseToken:c.token,dockerCredentials:{username:o,password:c.token},tokenName:c.tokenName,secretLevel:a?`user`:`repo`}}async function setupGitHub(e){let t=await j.password({message:`GitHub Personal Access Token (PAT)`,validate:e=>!e||e.length===0?`Token is required`:void 0});return isCancelled(t)&&(j.cancel(`Cancelled.`),process.exit(0)),{provider:createGitHubSecretsProvider(e),releaseToken:t}}const Ll=A({meta:{name:`setup:secrets`,description:`One-time setup: create a release token and configure CI secrets (RELEASE_TOKEN, Docker credentials) for Forgejo or GitHub. The forge is detected from the origin remote, then from package.json.`},args:{"dry-run":{type:`boolean`,description:`Show what would be created without making API calls`},docker:{type:`boolean`,default:!0,description:`Configure the Docker registry secrets when the repo publishes images (default). --no-docker skips them even if Docker packages are detected.`}},async run({args:e}){let t=process.cwd(),n=e[`dry-run`]===!0,r=e.docker===!1;j.intro(`setup:secrets`);let i=resolveOperationalRepo(t);if(!i)throw new T("No repository found. Add a git remote `origin` or a `repository` field to package.json.");let a=i.repository,o=i.hostname===`github.com`,s=createRealExecutor$1(),c=a.split(`/`)[1]??a,l=s.readFile(`${t}/package.json`),u=resolveDockerSecretPackages(s,t,(l?parsePackageJson(l):void 0)?.name??c,r,loadToolingConfig(t)?.publishDocker===!0),d=u.length>0,f=d?resolveDockerRegistryHost(t)??void 0:void 0,p=computeSecretNames(d,f),m=o?`GitHub`:`Forgejo`;F.info(`Will configure ${String(p.length)} secret(s) on ${m} (${a}): ${p.join(`, `)}`),o||F.warn(`Note: The generated token grants account-wide access -- it is not scoped to this repository.`);let h,g,_,v,y=`repo`;if(o){let e=await setupGitHub(s);h=e.provider,g=e.releaseToken}else{let e=await setupForgejo(s,`${i.protocol}//${i.hostname}`,a,n);h=e.provider,g=e.releaseToken,_=e.dockerCredentials,v=e.tokenName,y=e.secretLevel}let b=await runSetupSecrets(h,{repository:a,releaseToken:g,dryRun:n,dockerPackages:u,dockerCredentials:_,dockerRegistryHost:f}),x=b.secrets.map(e=>` - ${e.name}=${e.value}`).join(`
|
|
6106
|
-
`),S=y===`user`?`user-level`:`repository-level (${a})`,C=v?`\nAccess token "${v}" created (account-wide, not repo-scoped)`:``;
|
|
6107
|
-
`)}function formatCompareDiff$1(e){let t=[],n=e.floorPp===void 0?``:`, floor ${e.floorPp.toFixed(2)}%`;t.push(`coverage check ${e.pass?`PASS`:`FAIL`} (tolerance ${e.tolerancePp.toFixed(2)}pp${n})`);let r=Math.max(...
|
|
6108
|
+
`))e.length>0&&i(e);return a},execInherit(e,t,n){let r={cwd:n?.cwd,env:n?.env?{...process.env,...n.env}:void 0,stdio:`inherit`,detached:n?.detached??!1},i=pe(e,t,r);if(shouldRetryViaShim(i.error)&&(i=Ft(e,t,r)),i.error)throw i.error;if(i.status!==0)throw new D(`Command failed with exit code ${String(i.status)}: ${[e,...t].join(` `)}`)},fetch:globalThis.fetch,now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e)),onSignal(e,t){return process.on(e,t),()=>{process.removeListener(e,t)}},onExit(e){return process.on(`exit`,e),()=>{process.removeListener(`exit`,e)}},log:e=>console.log(e),logError:e=>console.error(e)}}function findFreePort(){return new Promise((e,t)=>{let n=Ne.createServer();n.unref(),n.once(`error`,t),n.listen(0,()=>{let r=n.address();if(r===null||typeof r==`string`){n.close(),t(new D(`Could not determine an allocated free port`));return}let{port:i}=r;n.close(()=>{e(i)})})})}const $l=P.object({Service:P.string(),Health:P.string(),State:P.string().optional(),ExitCode:P.number().optional(),ID:P.string().optional()});function composeArgs(e){let t=[`compose`,`--project-name`,e.projectName];for(let n of e.composeFiles)t.push(`-f`,n);return t.push(`--profile`,`bst-check`),e.envFile&&t.push(`--env-file`,e.envFile),t}const eu=/The\s+\\?"([^"\\]+)\\?"\s+variable is not set/g;function parseUnsetVariables(e){let t=/* @__PURE__ */ new Set;for(let n of e.matchAll(eu)){let e=n[1];e&&t.add(e)}return[...t]}function fillUnsetVariables(e,t){let n=e.exec(`docker`,[...composeArgs(t),`config`],{cwd:t.cwd,env:t.env}),r={};for(let e of parseUnsetVariables(n.stderr))t.env&&e in t.env||(r[e]=``);return r}function buildImages(e,t){if(!t.buildCommand)return;let[n,...r]=t.buildCommand;n&&e.execInherit(n,r,{cwd:t.buildCwd??t.compose.cwd})}function runSmoketest(e,t){if(!t.smoketest)return;let[n,...r]=t.smoketest;n&&e.execInherit(n,r,{cwd:t.smoketestCwd??t.compose.cwd,env:t.compose.env})}function composeUp(e,t){e.execInherit(`docker`,[...composeArgs(t),`up`,`-d`],{cwd:t.cwd,env:t.env})}function composeDown(e,t){try{e.execInherit(`docker`,[...composeArgs(t),`down`,`-v`,`--remove-orphans`,`--rmi`,`local`],{cwd:t.cwd,env:t.env,detached:!0})}catch{}}function composeLogs(e,t,n){try{let r=[...composeArgs(t),`logs`];n&&r.push(n);let i=e.exec(`docker`,r,{cwd:t.cwd,env:t.env});e.log(n?`-- ${n} logs --`:`-- logs --`),i.stdout.trim()&&e.log(i.stdout),i.stderr.trim()&&e.logError(i.stderr),!i.stdout.trim()&&!i.stderr.trim()&&e.log(`(no log output)`)}catch{}}function composePsDump(e,t){try{let n=e.exec(`docker`,[...composeArgs(t),`ps`,`-a`],{cwd:t.cwd,env:t.env});e.log(`-- compose ps -a --`),n.stdout.trim()&&e.log(n.stdout),n.stderr.trim()&&e.logError(n.stderr),!n.stdout.trim()&&!n.stderr.trim()&&e.log(`(no ps output)`)}catch{}}const tu=P.object({Status:P.string(),FailingStreak:P.number(),Log:P.array(P.object({Start:P.string(),ExitCode:P.number(),Output:P.string()})).nullable().transform(e=>e??[])});function parseHealthState(e){let t;try{t=JSON.parse(e)}catch{return}let n=tu.safeParse(t);return n.success?n.data:void 0}function printServiceHealthLog(e,t,n,r){e.log(`-- ${n} health log --`);try{if(!r){e.log(`(health log unavailable: compose reported no container id)`);return}let n=e.exec(`docker`,[`inspect`,`--format`,`{{json .State.Health}}`,r],{cwd:t.cwd,env:t.env}),i=parseHealthState(n.stdout);if(n.exitCode!==0||!i){e.log(`(health log unavailable)`),n.stderr.trim()&&e.logError(n.stderr);return}if(e.log(`status ${i.Status}, failing streak ${String(i.FailingStreak)}`),i.Log.length===0){e.log(`(no health checks have run yet)`);return}for(let t of i.Log){e.log(`[exit ${String(t.ExitCode)}] ${t.Start}`);let n=t.Output.trimEnd();e.log(n.length>0?n:`(no output)`)}}catch{e.log(`(health log unavailable)`)}}function composeHealthLogs(e,t){try{let n=composePs(e,t);for(let r of t.services){let i=n.find(e=>e.Service===r);i&&(i.Health===`unhealthy`||i.Health===`starting`)&&printServiceHealthLog(e,t,r,i.ID)}}catch{}}function composePs(e,t){let n=e.exec(`docker`,[...composeArgs(t),`ps`,`--format`,`json`,`--all`],{cwd:t.cwd,env:t.env}).stdout.trim();if(!n)return[];let r=P.array($l);try{let e=r.safeParse(JSON.parse(n));if(e.success)return e.data;let t=$l.safeParse(JSON.parse(n));if(t.success)return[t.data]}catch{}try{let e=`[${n.split(`
|
|
6109
|
+
`).join(`,`)}]`,t=r.safeParse(JSON.parse(e));return t.success?t.data:[]}catch{return[]}}const nu=`curlimages/curl:8.23.0@sha256:3fb7e13e5d179a845c97d78204f3f1064d1907037f26a3ebf91710571151fd93`;function getContainerHealth(e,t){return e.find(e=>e.Service===t)?.Health??`unknown`}function getContainerExitCode(e,t){let n=e.find(e=>e.Service===t);if(n?.State===`exited`)return n.ExitCode}function getContainerId(e,t){return e.find(e=>e.Service===t)?.ID}async function checkHttpHealthViaNetwork(e,t,n,r,i){let a=getContainerId(i,r);if(a===void 0)return!1;let o=e.exec(`docker`,[`run`,`--rm`,`--network`,`container:${a}`,nu,`curl`,`-s`,`-o`,`/dev/null`,`-w`,`%{http_code}`,`--connect-timeout`,`5`,`--max-time`,`5`,n.url],{cwd:t.cwd,env:t.env});if(o.exitCode===125)throw new D(`docker run failed to start the probe image ${nu}: ${o.stderr.trim()||`(no stderr captured)`}`);let s=Number.parseInt(o.stdout,10),c={status:Number.isNaN(s)?0:s,ok:s>=200&&s<300};return await n.validate(c)}async function checkHttpHealth(e,t,n,r){if(n.viaNetworkService!==void 0)return checkHttpHealthViaNetwork(e,t,n,n.viaNetworkService,r);try{let t=await e.fetch(n.url);return await n.validate(t)}catch{return!1}}function withFilledVariables(e,t){let n=fillUnsetVariables(e,t.compose),r=Object.keys(n);return r.length===0?t:(e.log(`Unset compose variables set to an empty string: ${r.join(`, `)}. To supply real values, put them in ${t.compose.envFile??`docker-compose.check.env`} beside the compose file.`),{...t,compose:{...t.compose,env:{...t.compose.env,...n}}})}async function updateHttpHealth(e,t,n,r,i){for(let a of n)r.get(a.name)||await checkHttpHealth(e,t,a,i)&&(r.set(a.name,!0),e.log(`${a.name} is healthy!`))}function runSmoketestStep(e,t,n,r){if(!t.smoketest)return null;let{compose:i}=t;e.log(`Running smoketest: ${t.smoketest.join(` `)}`);try{return runSmoketest(e,t),e.log(`Smoketest passed!`),null}catch(t){let a=k(t);e.logError(`Smoketest failed: ${a}`),composePsDump(e,i);for(let t of i.services)composeLogs(e,i,t);return n(),{success:!1,reason:`smoketest-failed`,message:a,elapsedMs:e.now()-r}}}async function runDockerCheck(e,t){let n=withFilledVariables(e,t),r=n.timeoutMs??12e4,i=n.pollIntervalMs??5e3,{compose:a}=n,o={verbose:n.verbose??!1};debug(o,`Compose files: ${a.composeFiles.join(`, `)}`),debug(o,`Services: ${a.services.join(`, `)}`),debug(o,`Health checks: ${n.healthChecks.map(e=>e.name).join(`, `)||`(none)`}`),debug(o,`Timeout: ${String(r)}ms, poll interval: ${String(i)}ms`);let s=!1,cleanup=()=>{s||(s=!0,composeDown(e,a))},gracefulShutdown=()=>{s?e.log(`Cleanup already done or in progress, please wait...`):(e.log(`Interrupted -- shutting down compose stack...`),cleanup(),process.exit(1))},c=e.onSignal(`SIGINT`,gracefulShutdown),l=e.onSignal(`SIGTERM`,gracefulShutdown),u=e.onSignal(`SIGHUP`,gracefulShutdown),d=e.onExit(cleanup);try{n.buildCommand&&(e.log(`Building images...`),buildImages(e,n)),e.log(`Starting compose stack...`);let t=e.now();try{composeUp(e,a)}catch(n){let r=k(n);e.logError(`Compose stack failed to start -- dumping logs`),composePsDump(e,a);for(let t of a.services)composeLogs(e,a,t);return composeHealthLogs(e,a),cleanup(),{success:!1,reason:`startup-failed`,message:r,elapsedMs:e.now()-t}}e.log(`Waiting for stack to be healthy (max ${r/1e3}s)...`);let s=t,c=!1,l=new Map(n.healthChecks.map(e=>[e.name,!1]));for(;e.now()-t<r;){let r=composePs(e,a);debug(o,`compose ps: ${r.length} container(s)`);let u=!0,d=!1;for(let n of a.services){let i=getContainerHealth(r,n);if(debug(o,`Container ${n}: ${i||`(no healthcheck)`}`),i!==``&&i!==`unknown`&&(d=!0),i===`unhealthy`)return e.logError(`Container ${n} is unhealthy`),composePsDump(e,a),composeLogs(e,a,n),composeHealthLogs(e,a),cleanup(),{success:!1,reason:`unhealthy-container`,message:n,elapsedMs:e.now()-t};i===`starting`&&(u=!1);let s=getContainerExitCode(r,n);if(s!==void 0&&s!==0){let r=`${n} exited with code ${String(s)}`;return e.logError(`Container ${r}`),composePsDump(e,a),composeLogs(e,a,n),cleanup(),{success:!1,reason:`container-exited`,message:r,elapsedMs:e.now()-t}}}if(await updateHttpHealth(e,a,n.healthChecks,l,r),u&&[...l.values()].every(Boolean)){if(!c&&n.healthChecks.length===0&&!d){c=!0,debug(o,`Nothing gates this stack -- settle poll before declaring success`),await e.sleep(i);continue}return runSmoketestStep(e,n,cleanup,t)||(e.log(`Check successful! All systems operational.`),cleanup(),{success:!0,elapsedMs:e.now()-t})}let f=e.now();if(f-s>=5e3){s=f;let n=Math.floor((f-t)/1e3),i=[a.services.map(e=>`${e}=${getContainerHealth(r,e)}`).join(`, `),[...l.entries()].map(([e,t])=>`${e}=${t?`OK`:`Pending`}`).join(`, `)].filter(Boolean).join(` | `);e.log(`Waiting... (${n}s elapsed). ${i}`)}await e.sleep(i)}e.logError(`Timeout waiting for stack to become healthy`),composePsDump(e,a);for(let t of a.services)composeLogs(e,a,t);return composeHealthLogs(e,a),cleanup(),{success:!1,reason:`timeout`,message:`Exceeded timeout`,elapsedMs:e.now()-t}}catch(e){return cleanup(),{success:!1,reason:`error`,message:k(e),elapsedMs:0}}finally{c(),l(),u(),d()}}function deriveProjectName(e,t=process.env){return`${sanitize(e)}-check-${sanitize(t.GITHUB_RUN_ID??t.CI_RUN_ID??String(process.pid))}`}function sanitize(e){return e.replace(/^@[^/]+\//,``).toLowerCase().replace(/[^a-z0-9_-]+/g,`-`).replace(/^-+|-+$/g,``)||`repo`}function toHttpHealthChecks(e){return e.map(e=>({name:e.name,url:e.url,validate:async t=>e.status?t.status===e.status:t.ok,viaNetworkService:e.viaNetworkService}))}function writeTempOverlay(e){let t=d(w.join(be(),`tooling-check-`)),n=w.join(t,`overlay.yaml`);return C(n,e,`utf-8`),n}const ru=j({meta:{name:`docker:check`,description:`Check Docker Compose stack health by auto-detecting services from compose files`},args:{timeout:{type:`string`,description:`Maximum time to wait for health checks, in ms (default: 120000)`},"poll-interval":{type:`string`,description:`Interval between polling attempts, in ms (default: 5000)`},verbose:{type:`boolean`,description:`Emit detailed debug logging`}},async run({args:e}){let t=process.cwd(),n=createFileReader(),r=n.readFile(w.join(t,`package.json`)),i=r?parsePackageJson(r):void 0,a=deriveProjectName(i?.name??w.basename(t)),o=createRealExecutor(),s=loadToolingConfig(t);if(s?.dockerCheck===!1){I.info(`Docker check is disabled in .tooling.json`);return}let c={...computeCheckDefaults(t),...s?.dockerCheck};if(!c.composeFiles||c.composeFiles.length===0){I.warn(`No compose files found -- nothing to health-check. Add docker-compose.yaml (plus a docker-compose.check.yaml overlay) in ./ or docker/ to enable docker:check.`),I.warn(`To suppress this warning, set "dockerCheck": false in .tooling.json.`);return}if(!c.checkOverlay){let e=c.composeCwd??t,n=deriveCheckOverlayName(c.composeFiles[0]??`docker-compose.yaml`);I.warn(`Compose files found but no check overlay. Create ${w.relative(t,w.join(e,n))} to enable docker:check.`),I.warn(`To suppress this warning, set "dockerCheck": false in .tooling.json.`);return}if(!c.services||c.services.length===0)throw new T(`No services found in compose files.`);let l=c.composeCwd??t,u=parseCheckComposeServices(l,c.composeFiles,c.checkOverlay),d=u.filter(startsUnderCheckProfile),f=findOverlayHealthcheckTimingOverrides(l,c.checkOverlay);f.length>0&&I.warn(`Check-overlay healthcheck timing overrides the fast docker:check intervals for: ${f.join(`, `)}. Remove interval/timeout/retries/start_period/start_interval from the overlay's healthcheck to restore them.`);let p=[];if(i?.name){let e=detectDockerPackages(n,t,i.name);for(let t of e)p.push(t.imageName);let r=crossReferenceDockerImages(e.map(e=>({dir:e.dir,imageName:e.imageName,dockerfileAbs:w.resolve(t,e.docker.dockerfile)})),u);for(let e of r)e.kind===`unreferenced`?I.warn(`Docker package "${e.dir}" (image: ${e.imageName}) is not referenced in any compose service.`):I.warn(`Docker package "${e.dir}" is built by a compose service with no \`image: ${e.imageName}\` -- docker:check rebuilds it instead of reusing the docker:build output (double build). Add \`image: ${e.imageName}\` to that service.`)}let m=writeTempOverlay(generateCheckOverlay(d,p)),h=[...c.composeFiles,m,c.checkOverlay],g=d.filter(e=>e.portEnvVar===`PORT`),_;if(g.length>0){g.length>1&&I.warn(`Multiple services reference \${PORT} (${g.map(e=>e.name).join(`, `)}); they cannot share a host port.`);let e=process.env.PORT??(c.envFile===void 0?void 0:composeEnvFileValue(l,c.envFile,`PORT`));if(e!==void 0)I.info(`PORT is already set (${e}) -- using the configured value.`);else{let e=await findFreePort();_={PORT:String(e)},I.info(`Allocated free host port ${String(e)} for \${PORT}.`)}}try{let t=await runDockerCheck(o,{compose:{cwd:l,composeFiles:h,projectName:a,envFile:c.envFile,env:_,services:c.services},buildCommand:c.buildCommand,buildCwd:c.buildCwd,healthChecks:c.healthChecks?toHttpHealthChecks(c.healthChecks):[],smoketest:c.smoketest,smoketestCwd:c.smoketestCwd,timeoutMs:e.timeout?Number.parseInt(e.timeout,10):c.timeoutMs,pollIntervalMs:e[`poll-interval`]?Number.parseInt(e[`poll-interval`],10):c.pollIntervalMs,verbose:e.verbose===!0||isEnvVerbose()});if(!t.success)throw new T(`Check failed (${t.reason}): ${t.message}`)}finally{try{y(w.dirname(m),{recursive:!0})}catch{}}}});function parseMaxAgeHours(e){let t=Number(e);if(e.trim()===``||!Number.isFinite(t)||t<0)throw new T(`--max-age must be a non-negative number of hours, got "${e}"`);return t}const iu=j({meta:{name:`docker:sweep`,description:`Reclaim containers, networks and volumes leaked by past docker:check runs, and the agent's own leaked containers, sidecars and networks`},args:{"dry-run":{type:`boolean`,description:`Report what would be reclaimed without removing anything`},json:{type:`boolean`,description:`Emit one JSON document: containers, networks, volumes, failed, dryRun.`},"max-age":{type:`string`,description:`Only reclaim resources older than this many hours (default: 4). 0 removes the age guard, so a container still running is reclaimed too`}},run({args:e}){let t=e[`max-age`]===void 0?144e5:parseMaxAgeHours(e[`max-age`])*36e5,n=createCliOutput(e.json===!0),r=runSweep({...createRealExecutor(),log:e=>n.notice(e)},{dryRun:e[`dry-run`]===!0,maxAgeMs:t});n.json(r);let i=r.dryRun?`Would reclaim`:`Reclaimed`,a=r.failed.length===0?``:` ${String(r.failed.length)} removal(s) failed.`;n.text(`${i} ${String(r.containers.length)} container(s), ${String(r.networks.length)} network(s), ${String(r.volumes.length)} volume(s).${a}`)}});function findProjectRoot(e){let t=w.resolve(e);for(;;){if(o(w.join(t,`.claude`)))return t;let n=w.dirname(t);if(n===t)return e;t=n}}const au=P.object({timestamp:P.string(),sessionId:P.string(),cwd:P.string().optional(),command:P.string(),decision:P.enum([`allow`,`deny`,`passthrough`,`none`]).transform(e=>e===`passthrough`?`none`:e),rule:P.string().nullable(),reason:P.string().nullable(),permissionMode:P.string().optional()});function countDecisions(e){let t={allow:0,deny:0,none:0};for(let n of e)t[n.decision]++;return t}function countByMode(e){let t={};for(let n of e)n.permissionMode!==void 0&&(t[n.permissionMode]=(t[n.permissionMode]??0)+1);return t}function parseTailCount(e){let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new T(`--tail must be a positive whole number of entries, got "${e}"`);return t}function parseAuditLog(e){if(!o(e))return[];let t=p(e,`utf-8`).split(`
|
|
6110
|
+
`).filter(Boolean),n=[];for(let e of t)try{let t=au.safeParse(JSON.parse(e));t.success&&n.push(t.data)}catch{}return n}function topCommands(e,t){let n=/* @__PURE__ */ new Map;for(let t of e){let e=n.get(t.command);e?e.count++:n.set(t.command,{command:t.command,count:1,rule:t.rule})}return[...n.values()].toSorted((e,t)=>t.count-e.count).slice(0,t)}function printSection(e,t,n,r){let i=topCommands(n,r);if(i.length!==0){e.text(t);for(let{command:t,count:n,rule:r}of i){let i=r?` [${r}]`:``;e.text(` ${String(n).padStart(4)}x ${t}${i}`)}e.text(``)}}const ou=j({meta:{name:`hooks:audit`,description:`Summarize the bst-hook audit log`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Project directory (default: current directory)`,required:!1},tail:{type:`string`,description:`Show the last N raw entries`},decision:{type:`string`,description:`Filter by decision: allow, deny, or none (passthrough is an alias for none)`},json:{type:`boolean`,description:`Emit one JSON document: entries ([{timestamp, sessionId, cwd?, command, decision (allow | deny | none), rule (or null), reason (or null), permissionMode?}]), counts ({allow, deny, none}), byMode? ({<mode>: count}). --tail limits entries, not counts; an empty log gives entries alone.`}},async run({args:e}){let t=createCliOutput(e.json===!0),n=e.dir?w.resolve(e.dir):findProjectRoot(process.cwd()),r=w.join(n,`.claude/hooks/bst-hook.audit.local.jsonl`),i=e.tail===void 0?null:parseTailCount(e.tail),a=parseAuditLog(r);if(a.length===0){t.json({entries:[]}),t.text(`No audit log entries found.`);return}let o=e.decision===`passthrough`?`none`:e.decision;if(o&&(a=a.filter(e=>e.decision===o)),e.json===!0){let e=countByMode(a);t.json({entries:i===null?a:a.slice(-i),counts:countDecisions(a),...Object.keys(e).length>0?{byMode:e}:{}});return}if(i!==null){for(let e of a.slice(-i)){let n=new Date(e.timestamp).toLocaleString(),r=e.rule?` [${e.rule}]`:``;t.text(`${n} ${e.decision.padEnd(12)}${e.command}${r}`)}return}let s=countDecisions(a);t.text(`${String(a.length)} entries: ${String(s.allow)} allow, ${String(s.deny)} deny, ${String(s.none)} none`),t.text(``);let c=countByMode(a);if(Object.keys(c).length>0){t.text(`By permission mode:`);for(let[e,n]of Object.entries(c).toSorted((e,t)=>t[1]-e[1]))t.text(` ${String(n).padStart(4)}x ${e}`);t.text(``)}let l=a.filter(e=>e.decision===`deny`),u=a.filter(e=>e.decision===`none`);printSection(t,`Denied commands:`,l,10),printSection(t,`None commands:`,u,10)}});function buildMinimalConfig(e){let t=o(w.join(e,`pnpm-workspace.yaml`));return{name:w.basename(e),structure:t?`monorepo`:`single`,stack:detectStack(e),builder:detectBuilder(e,readPackageJson(e)),useEslintPlugin:!0,formatter:`oxfmt`,setupVitest:!1,ci:`none`,setupRenovate:!1,releaseStrategy:`none`,publishNpm:!1,publishDocker:!1,projectType:`default`,detectPackageTypes:!1,targetDir:e}}async function runHookGenerators(e){let t=[];return t.push(...await generateClaudeHooks(e)),t.push(...await generateClaudeSettings(e)),t}const su=j({meta:{name:`hooks:sync`,description:`Deploy or update the bst-hook and Claude settings (without touching other tooling)`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Target directory (default: current directory)`,required:!1},check:{type:`boolean`,description:`Dry-run mode: report drift without writing files`},json:{type:`boolean`,description:`Emit one JSON document: status (up-to-date | synced | drift | failed), check, actionable, all, failed, exitCode.`}},async run({args:e}){let t=createCliOutput(e.json===!0),n=buildMinimalConfig(w.resolve(e.dir??`.`)),r=e.check?await runHooksCheck(n):await runHooksSync(n);t.json(r),process.exitCode=r.exitCode}});async function runHooksSync(e){let{ctx:t}=createContext(e,async()=>`overwrite`),n=await runHookGenerators(t),r=failedResults(n);reportFailures(r,`hooks:sync`);let i=n.filter(e=>e.action===`created`),a=n.filter(e=>e.action===`updated`),o=n.filter(e=>e.action===`removed`),s=[...i,...a,...o];if(!(s.length>0))return r.length===0&&I.success(`Hooks are up to date.`),{status:r.length>0?`failed`:`up-to-date`,check:!1,actionable:s,all:n,failed:r,exitCode:+(r.length>0)};for(let e of s)I.info(`${e.action}: ${e.filePath} -- ${e.description}`);return r.length===0&&I.success(`Hooks synced.`),{status:r.length>0?`failed`:`synced`,check:!1,actionable:s,all:n,failed:r,exitCode:+(r.length>0)}}async function runHooksCheck(e){let{ctx:t,pendingWrites:n}=createDryRunContext(e),r=await runHookGenerators(t),i=failedResults(r);reportFailures(i,`hooks:sync`);let a=r.filter(t=>{if(t.action===`removed`)return!0;if(t.action!==`created`&&t.action!==`updated`)return!1;let r=n.get(t.filePath);if(r!==void 0&&t.action===`updated`){let n=w.join(e.targetDir,t.filePath),i=o(n)?p(n,`utf-8`):void 0;if(i&&contentEqual(t.filePath,i,r))return!1}return!0});if(a.length===0&&i.length===0)return I.success(`Hooks are up to date.`),{status:`up-to-date`,check:!0,actionable:a,all:r,failed:i,exitCode:0};if(a.length>0){I.warn(`${String(a.length)} file(s) would be changed by hooks:sync`);for(let e of a)I.info(` ${e.action}: ${e.filePath} -- ${e.description}`)}return{status:i.length>0?`failed`:`drift`,check:!0,actionable:a,all:r,failed:i,exitCode:1}}const cu=P.record(P.string(),P.unknown());function previousState(e){let t=e.agent?.enabled;return t===void 0?`absent`:t===!0?`true`:`false`}function withAgentEnabled(e){let t=cu.safeParse(e.agent),n=t.success?{...t.data}:{};return n.enabled=!0,{...e,agent:n}}const lu=/* @__PURE__ */ new Set([`created`,`updated`,`removed`,`archived`]);async function runSetupAgent(e,t){let n=loadToolingConfigStrict(e);if(n===void 0)throw new T(`No .tooling.json in ${e}. Run pnpm exec bst repo:sync first to create one, so the repo's own conventions are chosen before the agent is enabled.`);let r=previousState(n),i=`already-enabled`;if(r!==`true`){let t=w.join(e,`.tooling.json`),r;try{r=JSON.parse(p(t,`utf8`))}catch(e){throw new T(`Could not read ${t} as JSON: ${k(e)}`)}let a=cu.safeParse(r);if(!a.success)throw new T(`Could not read ${t} as a config object: ${a.error.message}`);let o=withAgentEnabled(a.data),s=`${JSON.stringify(o,null,2)}\n`;parseToolingConfigStrict(s,t);let c=createContext(mergeWithSavedConfig(buildDefaultConfig(e,{}),n),async()=>`overwrite`);c.ctx.write(`.tooling.json`,c.ctx.format(`.tooling.json`,s)),i=`written`}i===`written`?I.success(`Set agent.enabled to true in .tooling.json`):I.info(`agent.enabled is already true`);let a=await runUpdateReport(e,{},{installOutput:t.installOutput}),o=failedResults(a.results),s=a.results.filter(e=>lu.has(e.action)).map(e=>({filePath:e.filePath,action:e.action})),c;return c=a.status===`stopped`||o.length>0?`failed`:s.length>0?`changed`:`up-to-date`,c===`failed`?I.error(`The sync failed. Fix what it reported, then run pnpm exec bst setup:agent again.`):I.info(`Commit these changes and land them on the default branch; the agent reads consent there within about a minute.`),{dir:e,consent:i,previous:r,sync:{status:c,changed:s,failed:o,install:a.install},exitCode:+(c===`failed`)}}const uu=j({meta:{name:`setup:agent`,description:`Enable the agent for this repository: set agent.enabled to true in .tooling.json, then run the same sync as repo:sync, which installs @bensandee/agent-cli and generates the files the agent reads. Commits nothing -- land the change on the default branch yourself.`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Directory to enable (default: current directory)`,required:!1},json:{type:`boolean`,description:`Output the report as JSON: dir, consent, previous, sync { status, changed, failed, install }, exitCode`}},async run({args:e}){let t=await runSetupAgent(w.resolve(e.dir??`.`),{installOutput:e.json===!0||isJsonMode()?`capture`:`inherit`});createCliOutput(e.json===!0).json(t),process.exitCode=t.exitCode}});function isCancelled(e){return M.isCancel(e)}const du=[`read:user`,`write:organization`,`write:package`,`write:repository`,`write:issue`];function createForgejoSecretsProvider(e,t){return{async setSecret(n,r,i){await setActionSecret(e,t,r,i)}}}function createForgejoUserSecretsProvider(e,t,n){let r=`Basic ${btoa(`${t.username}:${t.password}`)}`,i=n;return{async setSecret(n,a,o){try{await setUserActionSecret(e,{serverUrl:t.serverUrl,authorization:r,secretName:a,secretValue:o,otp:i})}catch(n){if(!(n instanceof OtpRequiredError))throw n;I.info(i?`2FA code expired.`:`2FA is required for user-level secrets.`);let s=await M.text({message:`Enter 2FA/TOTP code to set ${a}`,validate:e=>!e||e.length===0?`Code is required`:void 0});isCancelled(s)&&(M.cancel(`Cancelled.`),process.exit(0)),i=s,await setUserActionSecret(e,{serverUrl:t.serverUrl,authorization:r,secretName:a,secretValue:o,otp:i})}}}}function createGitHubSecretsProvider(e){return{async setSecret(t,n,r){let i=e.exec(`gh`,[`secret`,`set`,n,`--body`,r,`-R`,t]);if(i.exitCode!==0)throw new T(`Failed to set GitHub secret ${n}: ${i.stderr}`)}}}function resolveDockerSecretPackages(e,t,n,r,i){return r||!i?[]:detectDockerPackages(e,t,n)}function computeSecretNames(e,t){let n=[`RELEASE_TOKEN`];if(e&&t!==void 0){let{username:e,password:r}=dockerSecretNames(t);n.push(e,r)}return n}async function runSetupSecrets(e,t){let n=t.repository.split(`/`)[1]??t.repository,r=[];if(t.dryRun?I.info(`[dry-run] Would set secret RELEASE_TOKEN on ${t.repository}`):(I.info(`Setting RELEASE_TOKEN secret...`),await e.setSecret(t.repository,`RELEASE_TOKEN`,t.releaseToken),I.success(`Set RELEASE_TOKEN`)),r.push({name:`RELEASE_TOKEN`,value:t.releaseToken}),t.dockerPackages.length>0){I.info(`Detected ${String(t.dockerPackages.length)} Docker package(s) -- setting Docker secrets`);let i=t.repository.split(`/`)[0]??n,a=t.dockerCredentials?.username??i,o=t.dockerCredentials?.password??t.releaseToken;t.dockerCredentials||I.info(`Using defaults for Docker secrets: username="${a}", password=<release token>`);let{username:s,password:c}=dockerSecretNames(t.dockerRegistryHost??null);t.dryRun?(I.info(`[dry-run] Would set secret ${s} on ${t.repository}`),I.info(`[dry-run] Would set secret ${c} on ${t.repository}`)):(await e.setSecret(t.repository,s,a),I.success(`Set ${s}`),await e.setSecret(t.repository,c,o),I.success(`Set ${c}`)),r.push({name:s,value:a}),r.push({name:c,value:o})}return{secrets:r}}async function createForgejoReleaseToken(e,t){let n=t.repository.split(`/`)[1]??t.repository,r=t.userSecrets?`bst-release`:`bst-release-${n}`,i=du;if(t.dryRun)return I.info(`[dry-run] Would create access token "${r}" for ${t.username}`),I.info(`[dry-run] Scopes: ${i.join(`, `)}`),{token:`dry-run-token`,tokenName:r};I.info(`Creating access token "${r}"...`);let attempt=async n=>{try{return await createAccessToken(e,{serverUrl:t.serverUrl,username:t.username,password:t.password,tokenName:r,scopes:i,otp:n})}catch(e){throw e instanceof Error&&/\b4\d{2}\b/.test(e.message)&&e.message.includes(`already`)?new T(`Access token "${r}" already exists. Delete it in Forgejo settings and re-run, or set secrets manually.`):e}};try{let e=await attempt(t.otp);return I.success(`Created access token "${r}"`),{token:e,tokenName:r,otp:t.otp}}catch(e){if(e instanceof OtpRequiredError){I.info(`2FA is enabled on this account.`);let e=await M.text({message:`Enter 2FA/TOTP code`,validate:e=>!e||e.length===0?`Code is required`:void 0});isCancelled(e)&&(M.cancel(`Cancelled.`),process.exit(0));let t=await attempt(e);return I.success(`Created access token "${r}"`),{token:t,tokenName:r,otp:e}}throw e}}async function setupForgejo(e,t,n,r){let i=await M.select({message:`Where should secrets be stored?`,options:[{value:`repo`,label:`Repository-level`,hint:`scoped to this repository only`},{value:`user`,label:`User-level`,hint:`shared across all your repositories`}]});isCancelled(i)&&(M.cancel(`Cancelled.`),process.exit(0));let a=i===`user`,o=await M.text({message:`Enter Forgejo username`,validate:e=>!e||e.length===0?`Username is required`:void 0});isCancelled(o)&&(M.cancel(`Cancelled.`),process.exit(0));let s=await M.password({message:`Enter Forgejo password`,validate:e=>!e||e.length===0?`Password is required`:void 0});isCancelled(s)&&(M.cancel(`Cancelled.`),process.exit(0));let c=await createForgejoReleaseToken(e,{serverUrl:t,repository:n,username:o,password:s,dryRun:r,userSecrets:a}),l={serverUrl:t,repository:n,token:c.token};return{provider:a?createForgejoUserSecretsProvider(e,{serverUrl:t,username:o,password:s},c.otp):createForgejoSecretsProvider(e,l),releaseToken:c.token,dockerCredentials:{username:o,password:c.token},tokenName:c.tokenName,secretLevel:a?`user`:`repo`}}async function setupGitHub(e){let t=await M.password({message:`GitHub Personal Access Token (PAT)`,validate:e=>!e||e.length===0?`Token is required`:void 0});return isCancelled(t)&&(M.cancel(`Cancelled.`),process.exit(0)),{provider:createGitHubSecretsProvider(e),releaseToken:t}}const fu=j({meta:{name:`setup:secrets`,description:`One-time setup: create a release token and configure CI secrets (RELEASE_TOKEN, Docker credentials) for Forgejo or GitHub. The forge is detected from the origin remote, then from package.json.`},args:{"dry-run":{type:`boolean`,description:`Show what would be created without making API calls`},docker:{type:`boolean`,default:!0,description:`Configure the Docker registry secrets when the repo publishes images (default). --no-docker skips them even if Docker packages are detected.`}},async run({args:e}){let t=process.cwd(),n=e[`dry-run`]===!0,r=e.docker===!1;M.intro(`setup:secrets`);let i=resolveOperationalRepo(t);if(!i)throw new T("No repository found. Add a git remote `origin` or a `repository` field to package.json.");let a=i.repository,o=i.hostname===`github.com`,s=createRealExecutor$1(),c=a.split(`/`)[1]??a,l=s.readFile(`${t}/package.json`),u=resolveDockerSecretPackages(s,t,(l?parsePackageJson(l):void 0)?.name??c,r,loadToolingConfig(t)?.publishDocker===!0),d=u.length>0,f=d?resolveDockerRegistryHost(t)??void 0:void 0,p=computeSecretNames(d,f),m=o?`GitHub`:`Forgejo`;I.info(`Will configure ${String(p.length)} secret(s) on ${m} (${a}): ${p.join(`, `)}`),o||I.warn(`Note: The generated token grants account-wide access -- it is not scoped to this repository.`);let h,g,_,v,y=`repo`;if(o){let e=await setupGitHub(s);h=e.provider,g=e.releaseToken}else{let e=await setupForgejo(s,`${i.protocol}//${i.hostname}`,a,n);h=e.provider,g=e.releaseToken,_=e.dockerCredentials,v=e.tokenName,y=e.secretLevel}let b=await runSetupSecrets(h,{repository:a,releaseToken:g,dryRun:n,dockerPackages:u,dockerCredentials:_,dockerRegistryHost:f}),x=b.secrets.map(e=>` - ${e.name}=${e.value}`).join(`
|
|
6111
|
+
`),S=y===`user`?`user-level`:`repository-level (${a})`,C=v?`\nAccess token "${v}" created (account-wide, not repo-scoped)`:``;M.outro(`Done! ${String(b.secrets.length)} ${S} secret(s) on ${m}:${C}\n${x}`)}});function buildSimplePayload(e){let t=e.repository??``,n=e.serverUrl??`https://github.com`,r=e.actor??ciActorName(e.platform??`github`);return{action:`published`,release:{tag_name:e.tag,name:e.tag,draft:!1,prerelease:e.prerelease??!1,author:{login:r}},repository:{full_name:t,html_url:t?`${n}/${t}`:``},sender:{login:r}}}function buildPayloadFromEnv(){let e=process.env.GITHUB_REPOSITORY,t=process.env.GITHUB_REF,n=process.env.GITHUB_SERVER_URL??`https://github.com`,r=process.env.GITHUB_ACTOR??`github-actions[bot]`;if(!e||!t)return;let i=t.startsWith(`refs/tags/`)?t.slice(10):t;return{action:`published`,release:{tag_name:i,name:i,draft:!1,prerelease:tagIsPrerelease(i),author:{login:r}},repository:{full_name:e,html_url:`${n}/${e}`},sender:{login:r}}}function computeSignature(e,t){let n=xe(`sha256`,e);return n.update(t),`sha256=${n.digest(`hex`)}`}async function sendWebhook(e){let{url:t,secret:n,payload:r,fetcher:i=globalThis.fetch}=e,a=r?JSON.stringify(r):``,o={"Content-Type":`application/json`};n&&(o[`X-Hub-Signature-256`]=computeSignature(n,a));try{let e=await i(t,{method:`POST`,headers:o,body:a});return e.ok?{ok:!0,status:e.status}:{ok:!1,status:e.status,error:`HTTP ${String(e.status)}: ${await e.text().catch(()=>``)}`}}catch(e){return{ok:!1,error:k(e)}}}function maskSecret(e){if(e===void 0)return`<none>`;let t=e.length;return t===0?`<empty>`:t<=8?`<${String(t)} chars>`:`${e.slice(0,3)}...${e.slice(-3)} (${String(t)} chars)`}const rawLog=e=>console.log(e);async function sendWebhookWithLogging(e,t,n){let r=await sendWebhook({url:e,secret:t,payload:n}),i=`url=${e}, secret=${maskSecret(t)}`;if(r.ok)I.info(`Post-release hook completed successfully (${i})`);else if(I.error(`Post-release hook failed: ${r.error??`unknown error`} (${i})`),process.env.CI&&!isJsonMode()){let e=(r.error??`unknown error`).replaceAll(/[\r\n]+/gu,` `).slice(0,300);rawLog(`::error::Post-release hook failed: ${e}`)}return r}function resolveWebhookPayload(e,t=process.env){return e.tag||e.repository?buildSimplePayload({tag:e.tag??``,repository:e.repository??t.GITHUB_REPOSITORY??``,serverUrl:e[`server-url`]??t.GITHUB_SERVER_URL??`https://github.com`,actor:e.actor??t.GITHUB_ACTOR??`github-actions[bot]`,prerelease:e.prerelease??(e.tag!==void 0&&tagIsPrerelease(e.tag))}):buildPayloadFromEnv()}const pu=j({meta:{name:`webhook:send`,description:`Send a POST request to a webhook URL with GitHub-style HMAC-SHA256 authentication. The request is signed with WEBHOOK_SECRET; with no secret, or an empty one, it goes out unsigned.`},args:{url:{type:`positional`,description:`Webhook URL to POST to. If empty or missing, or if delivery fails, the command is best-effort by default and exits successfully; see --strict.`},tag:{type:`string`,description:`Release tag name (e.g. v1.2.3). Falls back to GITHUB_REF env var.`},repository:{type:`string`,description:`Repository in owner/repo format. Falls back to GITHUB_REPOSITORY env var.`},"server-url":{type:`string`,description:`Server URL (e.g. https://github.com). Falls back to GITHUB_SERVER_URL env var.`},actor:{type:`string`,description:`User or bot that triggered the release. Falls back to GITHUB_ACTOR env var.`},prerelease:{type:`boolean`,description:`Mark the release as a prerelease`},strict:{type:`boolean`,description:`Exit non-zero when delivery fails. Default is best-effort: the failure is logged and annotated, and the command exits 0.`},json:{type:`boolean`,description:`Emit one JSON document: status (delivered | failed | skipped-no-url), strict, url (or null), secret (or null), payload (or null), delivery ({ok, status, error}, or null). url has its credentials redacted and secret is masked; url, payload and delivery are null when skipped, and secret is null when unsigned. A failed best-effort delivery is status failed, not ok false; only --strict makes it exit non-zero.`}},async run({args:e}){let t=createCliOutput(e.json===!0),n=e.strict===!0;if(!e.url){I.info(`No webhook URL configured -- skipping post-release hook`),t.json({status:`skipped-no-url`,strict:n,url:null,secret:null,payload:null,delivery:null});return}let r=process.env.WEBHOOK_SECRET,i=resolveWebhookPayload(e),a=r||void 0,o=await sendWebhookWithLogging(e.url,a,i);t.json({status:o.ok?`delivered`:`failed`,strict:n,url:A(e.url),secret:a===void 0?null:maskSecret(a),payload:i??null,delivery:{ok:o.ok,status:o.status??null,error:o.error??null}}),!o.ok&&n&&(process.exitCode=1)}});function emptySums(){return{linesTotal:0,linesCovered:0,branchesTotal:0,branchesCovered:0}}function addEntry(e,t){e.linesTotal+=t.lines.total,e.linesCovered+=t.lines.covered,e.branchesTotal+=t.branches.total,e.branchesCovered+=t.branches.covered}function pct(e,t){return t===0?0:Math.round(e/t*1e3)/10}function toPackageEntry(e){return{lines:pct(e.linesCovered,e.linesTotal),branches:pct(e.branchesCovered,e.branchesTotal)}}function totalsFrom(e){return{lines:e.lines.pct,statements:e.statements.pct,branches:e.branches.pct,functions:e.functions.pct}}function packageNameFromPath(e,t){let n=e.split(w.sep).join(`/`),r=t.split(w.sep).join(`/`).replace(/\/+$/,``),i=n.startsWith(`${r}/`)?n.slice(r.length+1):n;return/^packages\/([^/]+)\//.exec(i)?.[1]}function deriveBaseline(e,t){let n=totalsFrom(e.total),r=/* @__PURE__ */ new Map,i=t.singlePackageName??w.basename(t.rootDir),a=emptySums(),o=!1;for(let[n,i]of Object.entries(e)){if(n===`total`)continue;let e=packageNameFromPath(n,t.rootDir);if(e){o=!0;let t=r.get(e)??emptySums();addEntry(t,i),r.set(e,t)}else addEntry(a,i)}let s={};if(o)for(let[e,t]of r)s[e]=toPackageEntry(t);else(a.linesTotal>0||a.branchesTotal>0)&&(s[i]=toPackageEntry(a));return{totals:n,packages:s,scope:`include`}}function deriveRecord(e,t){let n=deriveBaseline(e,t);return{sha:t.identity.sha,timestamp:t.identity.timestamp,...n}}function createRealCoverageExecutor(){return{exec(e,t,n){let r=execCapture$2(e,t,{cwd:n?.cwd,env:n?.env,input:n?.input,keepPartialStdoutOnKill:!0});return{stdout:r.stdout,stderr:r.stderr,exitCode:r.status}}}}function pad(e,t){return e.length>=t?e:e+` `.repeat(t-e.length)}function padLeft(e,t){return e.length>=t?e:` `.repeat(t-e.length)+e}function formatPct(e){return`${e.toFixed(1)}%`}function formatDelta(e){return e===0?` 0.00`:`${e>0?`+`:``}${e.toFixed(2)}`}function formatRecordSummary(e){let t=e.totals,n=`lines ${formatPct(t.lines)} | statements ${formatPct(t.statements)} | branches ${formatPct(t.branches)} | functions ${formatPct(t.functions)}`,r=[e.sha?`coverage @ ${e.sha.slice(0,7)}`:`coverage`,n],i=Object.entries(e.packages);if(i.length>0){let e=Math.max(...i.map(([e])=>e.length));r.push(`by package:`);for(let[t,n]of i.toSorted(([e],[t])=>e.localeCompare(t)))r.push(` ${pad(t,e)} lines ${padLeft(formatPct(n.lines),7)} branches ${padLeft(formatPct(n.branches),7)}`)}return r.join(`
|
|
6112
|
+
`)}function formatCompareDiff$1(e){let t=[],n=e.floorPp===void 0?``:`, floor ${e.floorPp.toFixed(2)}%`;t.push(`coverage check ${e.pass?`PASS`:`FAIL`} (tolerance ${e.tolerancePp.toFixed(2)}pp${n})`);let r=Math.max(...Er.map(e=>e.length));for(let n of e.totals){let e=pad(n.pass?`[ok]`:`[x]`,4);t.push(` ${e} ${pad(n.key,r)} baseline ${padLeft(formatPct(n.baseline),7)} current ${padLeft(formatPct(n.current),7)} delta ${padLeft(formatDelta(n.delta),7)}`)}return t.join(`
|
|
6108
6113
|
`)}function formatTrendTable(e){if(e.length===0)return`no coverage history recorded yet`;let t=e.map(e=>({sha:e.sha.slice(0,7),when:formatTimestamp(e.timestamp),totals:e.totals})),n=[`sha`,`when`,`lines`,`statements`,`branches`,`functions`,`lines delta`],r=[Math.max(n[0].length,...t.map(e=>e.sha.length)),Math.max(n[1].length,...t.map(e=>e.when.length)),7,7,7,7,Math.max(n[6]?.length??0,7)],i=[];i.push(joinRow(n,r)),i.push(joinRow(r.map(e=>`-`.repeat(e)),r));let a;for(let e of t){let t=a===void 0?``:formatDelta(round2(e.totals.lines-a));i.push(joinRow([e.sha,e.when,formatPct(e.totals.lines),formatPct(e.totals.statements),formatPct(e.totals.branches),formatPct(e.totals.functions),t],r)),a=e.totals.lines}if(e.length>=2){let t=e[0],n=e[e.length-1];if(t&&n){let r=round2(n.totals.lines-t.totals.lines);i.push(``),i.push(`lines ${formatPct(n.totals.lines)} (${formatDelta(r)} over last ${String(e.length)} records)`)}}return i.join(`
|
|
6109
|
-
`)}function round2(e){return Math.round(e*100)/100}function joinRow(e,t){return e.map((e,n)=>padLeft(e,t[n]??e.length)).join(` `)}function formatTimestamp(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:`${String(t.getUTCFullYear())}-${String(t.getUTCMonth()+1).padStart(2,`0`)}-${String(t.getUTCDate()).padStart(2,`0`)}`}function missingSummaryMessage(e){let t='coverage/coverage-summary.json not found. Run `pnpm test:coverage` first, or add "json-summary" to your vitest reporters.',n=diagnoseCheckScriptForwardingAt(e);return n?`${t}\n\n${n}`:t}function readSummary(e){let t=w.join(e,`coverage/coverage-summary.json`);if(!o(t))throw new T(missingSummaryMessage(e));return p(t,`utf-8`)}function getHeadSha(e){let t=createRealCoverageExecutor().exec(`git`,[`rev-parse`,`HEAD`],{cwd:e});return t.exitCode===0?t.stdout.trim():`unknown`}const
|
|
6110
|
-
`}const
|
|
6111
|
-
`}function healthFileFormatter(e){let t=computeDefaults(e);return createContentFormatter({targetDir:e,formatter:loadToolingConfig(e)?.formatter??t.formatter})}function writeHealthBaseline(e,t){let n=healthFileFormatter(e);C(w.join(e,`health-baseline.json`),n(`health-baseline.json`,serializeHealthBaseline(t,t.moduleCeilings,t.sizeBudgets)))}function normalize(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`./`)?t.slice(2):t}function ancestors(e){let t=[],n=e;for(;;){let e=n.lastIndexOf(`/`);if(e<0)break;n=n.slice(0,e),t.push(n)}return t}function createExcludeMatcher(e){if(e===void 0||e.length===0)return()=>!1;let t=
|
|
6114
|
+
`)}function round2(e){return Math.round(e*100)/100}function joinRow(e,t){return e.map((e,n)=>padLeft(e,t[n]??e.length)).join(` `)}function formatTimestamp(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:`${String(t.getUTCFullYear())}-${String(t.getUTCMonth()+1).padStart(2,`0`)}-${String(t.getUTCDate()).padStart(2,`0`)}`}function missingSummaryMessage(e){let t='coverage/coverage-summary.json not found. Run `pnpm test:coverage` first, or add "json-summary" to your vitest reporters.',n=diagnoseCheckScriptForwardingAt(e);return n?`${t}\n\n${n}`:t}function readSummary(e){let t=w.join(e,`coverage/coverage-summary.json`);if(!o(t))throw new T(missingSummaryMessage(e));return p(t,`utf-8`)}function getHeadSha(e){let t=createRealCoverageExecutor().exec(`git`,[`rev-parse`,`HEAD`],{cwd:e});return t.exitCode===0?t.stdout.trim():`unknown`}const mu=j({meta:{name:`coverage:summary`,description:`Print a human-readable summary of the latest coverage run`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Project directory (default: current directory)`,required:!1},json:{type:`boolean`,description:`Emit one JSON document: sha, timestamp, totals ({lines, statements, branches, functions}), packages ({<name>: {lines, branches}}), scope (include). When coverage is disabled the document is instead enabled (false), disabledReason.`}},run({args:e}){let t=createCliOutput(e.json===!0),n=w.resolve(e.dir??`.`),r=resolveCoverageConfig(n);if(r.disabledReason){t.json({enabled:!1,disabledReason:r.disabledReason}),t.text(`coverage: disabled (${r.disabledReason}).`);return}let i=parseV8Summary(readSummary(n));if(e.json===!0){let e=deriveRecord(i,{rootDir:n,identity:{sha:getHeadSha(n),timestamp:(/* @__PURE__ */ new Date()).toISOString()}});t.json(e);return}let a=deriveBaseline(i,{rootDir:n});t.text(formatRecordSummary({...a,sha:getHeadSha(n)}))}});function serializeBaseline(e){return JSON.stringify(e,null,2)+`
|
|
6115
|
+
`}const hu=`coverage-baseline.json`;function applyBaselineUpdate$1(e,t,n,r,i){let{reset:a,floorPp:o}=i;if(a)C(t,serializeBaseline(r)),e.notice(`Updated ${hu} (--reset: unconditional).`);else if(o!==void 0){let i=mergeTotalsWithFloor(n.totals,r.totals,o);C(t,serializeBaseline({...r,totals:i}));let a=Er.filter(e=>i[e]!==r.totals[e]);e.notice(a.length===0?`Updated ${hu} (floor ${String(o)}%).`:`Updated ${hu} (floor ${String(o)}%; held at baseline below the floor: ${a.join(`, `)}).`)}else isFlatOrUp(n.totals,r.totals)?(C(t,serializeBaseline(r)),e.notice(`Updated ${hu} (all four totals flat-or-up).`)):e.notice(`Skipped baseline update: at least one total dropped below baseline. Add tests or adjust coverage.exclude before updating.`)}const gu=j({meta:{name:`coverage:check`,description:`Compare the latest coverage run against coverage-baseline.json. Exits 1 when a total fails the comparison.`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Project directory (default: current directory)`,required:!1},"update-baseline":{type:`boolean`,description:`Rewrite coverage-baseline.json: with coverage.floorPp set, per metric (at/above the floor or up tracks current; a below-floor dip holds); otherwise only if all four totals are flat-or-up`},reset:{type:`boolean`,description:`With --update-baseline, rewrite coverage-baseline.json unconditionally, even when totals dropped.`},"fail-on-missing-baseline":{type:`boolean`,default:!0,description:`Fail when no baseline exists (default). --no-fail-on-missing-baseline downgrades it to a notice (used during bootstrap).`},json:{type:`boolean`,description:`Emit one JSON document: status (disabled | baseline-created | missing-baseline | compared), reason?, totals?, pass?, tolerancePp?, floorPp?. reason comes only with disabled; totals is {lines, statements, branches, functions} with baseline-created and missing-baseline, and [{key, baseline, current, delta, pass}] after a comparison, which alone carries pass, tolerancePp and floorPp?.`}},run({args:e}){let t=w.resolve(e.dir??`.`),n=createCliOutput(e.json===!0),r=resolveCoverageConfig(t);if(r.disabledReason){n.notice(`coverage: disabled (${r.disabledReason}). Skipping check.`),n.json({status:`disabled`,reason:r.disabledReason});return}let i=w.join(t,`coverage/coverage-summary.json`),a=w.join(t,hu);if(!o(i))throw new T(missingSummaryMessage(t));let s=deriveBaseline(parseV8Summary(p(i,`utf-8`)),{rootDir:t});if(!o(a)){if(e[`update-baseline`]===!0){C(a,serializeBaseline(s)),n.notice(`Created ${hu} (no prior baseline).`),n.json({status:`baseline-created`,totals:s.totals});return}let t=`${hu} not found. Run with --update-baseline to create one from the current run.`;if(e[`fail-on-missing-baseline`]===!1){n.notice(t),n.json({status:`missing-baseline`,totals:s.totals});return}throw new T(t)}let c=parseBaseline(p(a,`utf-8`)),l=compareTotals(c.totals,s.totals,r.tolerancePp,r.floorPp);n.text(formatCompareDiff$1(l)),n.json({status:`compared`,...l}),e[`update-baseline`]===!0&&applyBaselineUpdate$1(n,a,c,s,{reset:e.reset===!0,floorPp:r.floorPp}),l.pass||(process.exitCode=1)}}),_u=`coverage/coverage-summary.json`,vu=j({meta:{name:`coverage:record`,description:`Append the current coverage run to the orphan-branch history`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Project directory (default: current directory)`,required:!1},branch:{type:`string`,description:`Override the orphan branch name (default: from .tooling.json or 'bst/coverage-metrics')`},json:{type:`boolean`,description:`Emit one JSON document: status (recorded | disabled). recorded adds branch, sha, commitSha, bootstrapped, attempts, record. disabled adds reason and means coverage history is off: switched off in .tooling.json, no vitest config, or stack none.`}},run({args:e}){let t=createCliOutput(e.json===!0),n=w.resolve(e.dir??`.`),r=resolveCoverageConfig(n);if(!r.historyEnabled){t.text(`coverage history disabled (.tooling.json: coverage.history === 'none' or coverage === false). Skipping record.`),t.json({status:`disabled`,reason:r.disabledReason??(r.enabled?`coverage.history === 'none'`:`coverage is false (or undetected -- history needs the gate)`)});return}refuseForgeDefaultMismatch(readConfiguredDefaultBranch(n),processCiEventSource(),`coverage:record`);let i=w.join(n,_u);if(!o(i))throw new T(`${_u} not found. Run \`pnpm test:coverage\` before \`coverage:record\`.`);let a=parseV8Summary(p(i,`utf-8`)),s=createRealCoverageExecutor(),c=s.exec(`git`,[`rev-parse`,`HEAD`],{cwd:n});if(c.exitCode!==0)throw new T(`Failed to resolve HEAD sha: ${c.stderr.trim()}`);let l=c.stdout.trim(),u=deriveRecord(a,{rootDir:n,identity:{sha:l,timestamp:(/* @__PURE__ */ new Date()).toISOString()}}),d=e.branch??r.historyBranch;t.text(`Appending coverage record for ${l.slice(0,7)} to ${d}...`);let f=appendRecord(s,{cwd:n,historyBranch:d,authorName:`coverage-bot`,authorEmail:`coverage-bot@noreply.localhost`},u);t.text(`${f.bootstrapped?`Bootstrapped`:`Appended to`} ${d}: commit ${f.commitSha.slice(0,7)}${f.attempts>1?` (after ${String(f.attempts)} attempts)`:``}.`),t.json({status:`recorded`,branch:d,sha:l,commitSha:f.commitSha,bootstrapped:f.bootstrapped,attempts:f.attempts,record:u})}}),yu=j({meta:{name:`coverage:status`,description:`Show recent coverage history (read-only; fetches from the orphan branch)`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Project directory (default: current directory)`,required:!1},limit:{type:`string`,description:`Number of trailing records to render (default: 10)`},branch:{type:`string`,description:`Override the orphan branch name (default: from .tooling.json or 'bst/coverage-metrics')`},json:{type:`boolean`,description:`Emit one JSON document: records ([{sha, timestamp, totals ({lines, statements, branches, functions}), packages ({<name>: {lines, branches}}), scope?}]). records is empty when no history is recorded yet.`}},run({args:e}){let t=createCliOutput(e.json===!0),n=w.resolve(e.dir??`.`),r=resolveCoverageConfig(n),i=e.branch??r.historyBranch,a=e.limit?Math.max(1,Number.parseInt(e.limit,10)||10):10,o=readRecords(createRealCoverageExecutor(),{cwd:n,historyBranch:i});if(o.length===0){t.json({records:[]}),t.text(`no coverage history recorded yet (branch: ${i})`);return}let s=o.slice(-a);t.json({records:s}),t.text(formatTrendTable(s))}});function serializeHealthBaseline(e,t,n){let r={};for(let t of R){let n=e[t];n!==void 0&&(r[t]=n)}return t!==void 0&&Object.keys(t).length>0&&(r.moduleCeilings=t),n!==void 0&&Object.keys(n).length>0&&(r.sizeBudgets=n),JSON.stringify(r,null,2)+`
|
|
6116
|
+
`}function healthFileFormatter(e){let t=computeDefaults(e);return createContentFormatter({targetDir:e,formatter:loadToolingConfig(e)?.formatter??t.formatter})}function writeHealthBaseline(e,t){let n=healthFileFormatter(e);C(w.join(e,`health-baseline.json`),n(`health-baseline.json`,serializeHealthBaseline(t,t.moduleCeilings,t.sizeBudgets)))}function normalize(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`./`)?t.slice(2):t}function ancestors(e){let t=[],n=e;for(;;){let e=n.lastIndexOf(`/`);if(e<0)break;n=n.slice(0,e),t.push(n)}return t}function createExcludeMatcher(e){if(e===void 0||e.length===0)return()=>!1;let t=F(e,{dot:!0});return e=>{let n=normalize(e);return t(n)?!0:ancestors(n).some(e=>t(e))}}function exemptKeyMatcher(e){if(!F.scan(e).isGlob)return t=>t===e;let t=F(e,{dot:!0});return e=>t(e)}function createExemptLookup(e){let t=Object.entries(e).filter(([e])=>F.scan(e).isGlob).map(([e,t])=>({matches:exemptKeyMatcher(e),reason:t}));return n=>e[n]??t.find(e=>e.matches(n))?.reason}const bu=P.object({module:P.string(),resolved:P.string(),circular:P.boolean().optional(),dependencyTypes:P.array(P.string()).optional(),couldNotResolve:P.boolean().optional()}),xu=P.object({source:P.string(),dependencies:P.array(bu)}),Su=P.object({modules:P.array(xu)});function isFirstPartySpecifier(e,t){if(e.startsWith(`.`)||e.startsWith(`#`))return!0;for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}function partitionExempt(e,t){if(t===void 0)return{kept:e,exempt:[]};let n=createExemptLookup(t),r=[],i=[];for(let t of e){let e=n(t.module);e===void 0?r.push(t):i.push({...t,reason:e})}return{kept:r,exempt:i}}function isLocalDep(e,t){if(e.couldNotResolve===!0||e.resolved.includes(`node_modules`))return!1;let n=e.dependencyTypes??[];return n.includes(`core`)?!1:n.length===0||n.includes(`local`)?!0:t}function addImporter(e,t,n){let r=e.get(t);r===void 0&&(r=/* @__PURE__ */ new Set,e.set(t,r)),r.add(n)}function parseGraphDetails(e,t){let{limits:n,exempt:r={},isExcluded=()=>!1,sourceLines:i=/* @__PURE__ */ new Map,crossPackage:a,workspacePackages:o=/* @__PURE__ */ new Set}=t,s;try{s=JSON.parse(e)}catch(e){throw new T(`dependency-cruiser output is not valid JSON: ${k(e)}`)}let c=Su.safeParse(s);if(!c.success)throw new T(`dependency-cruiser output has unexpected shape: ${c.error.message}`);let l=[],u=/* @__PURE__ */ new Map,d=/* @__PURE__ */ new Map,f=/* @__PURE__ */ new Map,p=/* @__PURE__ */ new Set,m=[];for(let e of c.data.modules){if(isExcluded(e.source))continue;p.add(e.source);let t=0,n;for(let r of e.dependencies)r.couldNotResolve===!0&&isFirstPartySpecifier(r.module,o)&&m.push({importer:e.source,specifier:r.module}),isLocalDep(r,a)&&(isExcluded(r.resolved)||(r.circular===!0&&l.push({from:e.source,to:r.resolved}),t++,n===void 0&&(n=[]),n.push(r.resolved),addImporter(f,r.resolved,e.source)));t>0&&(u.set(e.source,t),n!==void 0&&d.set(e.source,n))}let h=/* @__PURE__ */ new Map;for(let[e,t]of f)h.set(e,[...t]);let g=[...f.entries()].map(([e,t])=>({module:e,count:t.size,lines:i.get(e)})).filter(e=>e.count>n.fanInLimit).filter(e=>e.lines===void 0||e.lines>n.moduleSizeLimit).toSorted((e,t)=>t.count-e.count),_=[...u.entries()].map(([e,t])=>({module:e,count:t})).filter(e=>e.count>n.fanOutLimit).toSorted((e,t)=>t.count-e.count),v=partitionExempt(g,r.fanInOutliers),y=partitionExempt(_,r.fanOutOutliers);return{cycles:l,fanIn:v.kept,fanOut:y.kept,fanInExempt:v.exempt,fanOutExempt:y.exempt,fanOutEdges:d,fanInEdges:h,graphModules:p,unresolvedFirstParty:m}}const Cu=P.object({bin:P.record(P.string(),P.string()).optional()});function declaredDepcruiseBin(e){let t;try{t=JSON.parse(p(e,`utf8`))}catch{return}let n=Cu.safeParse(t);if(n.success)return n.data.bin?.depcruise}function resolveDepcruiseBin(){let e=import.meta.resolve(`dependency-cruiser`),t=Pe(e),n=w.dirname(t);for(let e=0;e<10;e++){let e=w.join(n,`package.json`);if(o(e)){let t=declaredDepcruiseBin(e);if(t!==void 0){let e=w.join(n,t);if(o(e))return e}}let t=w.dirname(n);if(t===n)break;n=t}throw new T(`Cannot locate dependency-cruiser bin -- is it installed?`)}function depcruiseGlobs(e){let t=e.extensions.map(e=>e.replace(/^\./,``)).join(`,`),n=e.extensions.length>1?`{${t}}`:t;return e.src.map(e=>`${e.replace(/\/$/,``)}/**/*.${n}`)}function writeCruiseConfig(e,t){let n=w.join(e,`cruise.cjs`),r={doNotFollow:{path:`node_modules`},...t===void 0?{}:{tsConfig:{fileName:t}},enhancedResolveOptions:{exportsFields:[`exports`],conditionNames:[`import`,`require`,`node`,`default`,`types`]}};return C(n,`module.exports = ${JSON.stringify({forbidden:[],options:r},null,2)};\n`),n}function cruisedNothing(e){try{let t=JSON.parse(e);return typeof t==`object`&&!!t&&`modules`in t&&Array.isArray(t.modules)&&t.modules.length===0}catch{return!1}}function runDepcruise(e,t){if(t.extensions.length===0)return{stdout:void 0};let n=resolveDepcruiseBin();if(!t.crossPackage){let r=[n,...depcruiseGlobs(t),`--no-config`,`--do-not-follow`,`node_modules`,`--output-type`,`json`];t.tsConfig&&r.push(`--ts-config`,t.tsConfig);let i=e.exec(`node`,r);return i.stdout.trim()===``||cruisedNothing(i.stdout)?{stdout:void 0,diagnostic:{command:`node ${r.join(` `)}`,stderr:i.stderr}}:{stdout:i.stdout}}let r=d(w.join(be(),`bst-health-`));try{let i=writeCruiseConfig(r,t.tsConfig),a=[n,...depcruiseGlobs(t),`--config`,i,`--output-type`,`json`],o=e.exec(`node`,a);return o.stdout.trim()===``||cruisedNothing(o.stdout)?{stdout:void 0,diagnostic:{command:`node ${a.join(` `)}`,stderr:o.stderr}}:{stdout:o.stdout}}finally{y(r,{recursive:!0,force:!0})}}function collectGraphDetails(e,t,n=()=>!1,r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Set){let{stdout:a,diagnostic:o}=runDepcruise(e,t);return a===void 0?{details:void 0,diagnostic:o}:{details:parseGraphDetails(a,{limits:{fanInLimit:t.fanInLimit,fanOutLimit:t.fanOutLimit,moduleSizeLimit:t.moduleSizeLimit},exempt:t.exempt,isExcluded:n,sourceLines:r,crossPackage:t.crossPackage,workspacePackages:i})}}const wu=P.object({packages:P.array(P.string()).optional()}),Tu=P.object({workspaces:P.union([P.array(P.string()),P.object({packages:P.array(P.string())})]).optional()}),Eu=P.object({name:P.string()});function pnpmWorkspaceGlobs(e){let t=e.readFile(`pnpm-workspace.yaml`);if(t===void 0||t.trim()===``)return[];let n;try{n=Ee(t)}catch{return[]}let r=wu.safeParse(n);return r.success?r.data.packages??[]:[]}function rootWorkspaceGlobs(e){let t=e.readFile(`package.json`);if(t===void 0||t.trim()===``)return[];let n;try{n=JSON.parse(t)}catch{return[]}let r=Tu.safeParse(n);if(!r.success||r.data.workspaces===void 0)return[];let i=r.data.workspaces;return Array.isArray(i)?i:i.packages}const Du=/* @__PURE__ */ new Set([`node_modules`,`.git`,`dist`]);function joinRel(e,t){return e===``?t:`${e}/${t}`}function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function segmentMatcher(e){if(!e.includes(`*`))return t=>t===e;let t=e.split(`*`).map(escapeRegExp).join(`[^/]*`),n=RegExp(`^${t}$`);return e=>n.test(e)}function walkSegments(e,t,n,r){let[i,...a]=t;if(i===void 0){n!==``&&e.readDir(n)!==void 0&&r.add(n);return}let o=e.readDir(n)??[];if(i===`**`){walkSegments(e,a,n,r);for(let t of o)Du.has(t)||walkSegments(e,[`**`,...a],joinRel(n,t),r);return}let s=segmentMatcher(i);for(let t of o)s(t)&&walkSegments(e,a,joinRel(n,t),r)}function expandGlob(e,t){let n=t.replace(/^\.\//,``).replace(/\/+$/,``);if(n===``)return[];if(!n.includes(`*`))return e.readDir(n)===void 0?[]:[n];let r=/* @__PURE__ */ new Set;return walkSegments(e,n.split(`/`),``,r),[...r]}function memberName(e,t){let n=e.readFile(`${t}/package.json`);if(n===void 0||n.trim()===``)return;let r;try{r=JSON.parse(n)}catch{return}let i=Eu.safeParse(r);return i.success?i.data.name:void 0}function listWorkspacePackageNames(e){let t=[...pnpmWorkspaceGlobs(e),...rootWorkspaceGlobs(e)],n=/* @__PURE__ */ new Set;for(let r of t)for(let t of expandGlob(e,r)){let r=memberName(e,t);r!==void 0&&n.add(r)}return n}function buildCollectConfig(e,t){return{src:e.src,extensions:e.extensions,directoryFileLimit:e.directoryFileLimit,fanInLimit:e.fanInLimit,fanOutLimit:e.fanOutLimit,moduleSizeLimit:e.moduleSizeLimit,crossPackage:e.crossPackage,includeGraph:e.graphMetricsEnabled,tsConfig:t.tsConfig,exclude:e.exclude,exempt:e.exempt}}const Ou=/* @__PURE__ */ new Set([`__tests__`,`test`,`tests`]);function isUnrepresentable(e){let t=(e.match(/\*/g)??[]).length;return t===0?!1:t>=2||e.split(`/`).find(e=>e.includes(`*`))!==`*`}function expandSrcDirs(e,t){let n=/* @__PURE__ */ new Set,r=[],i=[],addRoot=e=>{n.has(e)||(n.add(e),r.push(e))};for(let n of t){if(isUnrepresentable(n)){i.push({pattern:n,roots:[],status:`unrepresentable`});continue}if(!n.includes(`*`)){let t=e.readDir(n)!==void 0,r=t?`resolved`:`unmatched`;i.push({pattern:n,roots:t?[n]:[],status:r}),t&&addRoot(n);continue}let t=n.indexOf(`*`),r=n.slice(0,t).replace(/\/$/,``),a=n.slice(t+1).replace(/^\//,``),o=[];for(let t of e.readDir(r)??[]){let n=a?`${r}/${t}/${a}`:`${r}/${t}`;e.readDir(n)!==void 0&&o.push(n)}i.push({pattern:n,roots:o,status:o.length>0?`resolved`:`unmatched`});for(let e of o)addRoot(e)}return{roots:r,entries:i}}function isTestPath(e){let t=w.basename(e);return/\.(test|spec)\.[cm]?[jt]sx?$/.test(t)?!0:e.split(`/`).some(e=>Ou.has(e))}function isDeclaration(e){return e.endsWith(`.d.ts`)}function countSourceLines(e){let t=0,n=!1;for(let r of e.split(`
|
|
6112
6117
|
`)){let e=r.endsWith(`\r`)?r.slice(0,-1):r,i=``,a=0;for(;a<e.length;){if(n){let t=e.indexOf(`*/`,a);if(t===-1){a=e.length;break}n=!1,a=t+2;continue}let t=e.indexOf(`//`,a),r=e.indexOf(`/*`,a);if(t===-1&&r===-1){i+=e.slice(a),a=e.length;break}if(t!==-1&&(r===-1||t<r)){i+=e.slice(a,t),a=e.length;break}i+=e.slice(a,r),n=!0,a=r+2}i.trim().length>0&&t++}return t}function listSourceFiles(e,t,n,r){let i=/* @__PURE__ */ new Set,a=[];for(let o of r)for(let r of e.readDirRecursive(o,t.extensions))isTestPath(r)||isDeclaration(r)||n(r)||i.has(r)||(i.add(r),a.push(r));return a}function listDirectories(e){let t=/* @__PURE__ */ new Set;for(let n of e)t.add(w.dirname(n));return t}function listCrowdedDirectories(e,t){let n=/* @__PURE__ */ new Map;for(let t of e){let e=w.dirname(t);n.set(e,(n.get(e)??0)+1)}return partitionExempt([...n.entries()].filter(([,e])=>e>t.directoryFileLimit).map(([e,t])=>({module:e,count:t})).toSorted((e,t)=>t.count-e.count),t.exempt?.crowdedDirectories)}function countRawLines(e){if(e===``)return 0;let t=e.split(`
|
|
6113
6118
|
`).length;return e.endsWith(`
|
|
6114
|
-
`)?t-1:t}function countLinesByModule(e,t){let n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map;for(let i of t){let t=e.readFile(i);t!==void 0&&(n.set(i,countSourceLines(t)),r.set(i,countRawLines(t)))}return{stripped:n,raw:r}}function rollUpByDirectory(e){let t=/* @__PURE__ */ new Map;for(let[n,r]of e){let e=w.dirname(n);t.set(e,(t.get(e)??0)+r)}return[...t.entries()].filter(([,e])=>e>0).map(([e,t])=>({module:e,count:t})).toSorted((e,t)=>t.count-e.count)}function collectDetails(e,t){let n=createExcludeMatcher(t.exclude),{roots:r,entries:i}=expandSrcDirs(e,t.src),a=listSourceFiles(e,t,n,r),o=listCrowdedDirectories(a,t),s={crowdedDirectories:o.kept,directories:listDirectories(a),sources:{entries:i,roots:r,fileCount:a.length}};if(o.exempt.length>0&&(s.crowdedExempt=o.exempt),t.extensions.length>0){let{stripped:t,raw:n}=countLinesByModule(e,a);s.sourceLinesByModule=t,s.rawLinesByModule=n,s.linesOfCodeByDirectory=rollUpByDirectory(t)}if(t.includeGraph){let r=listWorkspacePackageNames(e),i=collectGraphDetails(e,t,n,s.rawLinesByModule,r);i.details?(s.circularDependencies=i.details.cycles,s.fanInOutliers=i.details.fanIn,s.fanOutOutliers=i.details.fanOut,s.fanInExempt=i.details.fanInExempt,s.fanOutExempt=i.details.fanOutExempt,s.fanOutEdges=i.details.fanOutEdges,s.fanInEdges=i.details.fanInEdges,s.graphModules=i.details.graphModules,s.unresolvedFirstParty=i.details.unresolvedFirstParty):i.diagnostic&&(s.graphDiagnostic=i.diagnostic)}return s}function metricsFromDetails(e){let t={crowdedDirectories:e.crowdedDirectories.length};return e.circularDependencies&&(t.circularDependencies=e.circularDependencies.length),e.fanInOutliers&&(t.fanInOutliers=e.fanInOutliers.length),e.fanOutOutliers&&(t.fanOutOutliers=e.fanOutOutliers.length),t}function ceilingsFromDetails(e){let t={},n={};for(let t of e.fanInOutliers??[])n[t.module]=t.count;Object.keys(n).length>0&&(t.fanInOutliers=n);let r={};for(let t of e.fanOutOutliers??[])r[t.module]=t.count;Object.keys(r).length>0&&(t.fanOutOutliers=r);let i={};for(let t of e.crowdedDirectories)i[t.module]=t.count;return Object.keys(i).length>0&&(t.crowdedDirectories=i),t}function observationsFromDetails(e){return e.linesOfCodeByDirectory?{linesOfCode:e.linesOfCodeByDirectory.reduce((e,t)=>e+t.count,0)}:{}}function offenderEntries(e,t){switch(t){case`crowdedDirectories`:return e.crowdedDirectories;case`circularDependencies`:return e.circularDependencies??[];case`fanInOutliers`:return e.fanInOutliers??[];case`fanOutOutliers`:return e.fanOutOutliers??[]}}function compareSizeBudgets(e,t){let n=[];for(let r of t){let t=e.sizeBudgets?.[r.id];r.measured===void 0?n.push({id:r.id,ceiling:t,pass:!1,reason:r.unmeasured??`not measured`}):t===void 0?n.push({id:r.id,measured:r.measured,pass:!1,reason:`unrecorded`,measurerChanged:r.measurerChanged}):n.push({id:r.id,ceiling:t,measured:r.measured,pass:r.measured<=t,measurerChanged:r.measurerChanged})}return n}function compareMetrics(e,t,n=0,r={},i=[]){let a=
|
|
6119
|
+
`)?t-1:t}function countLinesByModule(e,t){let n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map;for(let i of t){let t=e.readFile(i);t!==void 0&&(n.set(i,countSourceLines(t)),r.set(i,countRawLines(t)))}return{stripped:n,raw:r}}function rollUpByDirectory(e){let t=/* @__PURE__ */ new Map;for(let[n,r]of e){let e=w.dirname(n);t.set(e,(t.get(e)??0)+r)}return[...t.entries()].filter(([,e])=>e>0).map(([e,t])=>({module:e,count:t})).toSorted((e,t)=>t.count-e.count)}function collectDetails(e,t){let n=createExcludeMatcher(t.exclude),{roots:r,entries:i}=expandSrcDirs(e,t.src),a=listSourceFiles(e,t,n,r),o=listCrowdedDirectories(a,t),s={crowdedDirectories:o.kept,directories:listDirectories(a),sources:{entries:i,roots:r,fileCount:a.length}};if(o.exempt.length>0&&(s.crowdedExempt=o.exempt),t.extensions.length>0){let{stripped:t,raw:n}=countLinesByModule(e,a);s.sourceLinesByModule=t,s.rawLinesByModule=n,s.linesOfCodeByDirectory=rollUpByDirectory(t)}if(t.includeGraph){let r=listWorkspacePackageNames(e),i=collectGraphDetails(e,t,n,s.rawLinesByModule,r);i.details?(s.circularDependencies=i.details.cycles,s.fanInOutliers=i.details.fanIn,s.fanOutOutliers=i.details.fanOut,s.fanInExempt=i.details.fanInExempt,s.fanOutExempt=i.details.fanOutExempt,s.fanOutEdges=i.details.fanOutEdges,s.fanInEdges=i.details.fanInEdges,s.graphModules=i.details.graphModules,s.unresolvedFirstParty=i.details.unresolvedFirstParty):i.diagnostic&&(s.graphDiagnostic=i.diagnostic)}return s}function metricsFromDetails(e){let t={crowdedDirectories:e.crowdedDirectories.length};return e.circularDependencies&&(t.circularDependencies=e.circularDependencies.length),e.fanInOutliers&&(t.fanInOutliers=e.fanInOutliers.length),e.fanOutOutliers&&(t.fanOutOutliers=e.fanOutOutliers.length),t}function ceilingsFromDetails(e){let t={},n={};for(let t of e.fanInOutliers??[])n[t.module]=t.count;Object.keys(n).length>0&&(t.fanInOutliers=n);let r={};for(let t of e.fanOutOutliers??[])r[t.module]=t.count;Object.keys(r).length>0&&(t.fanOutOutliers=r);let i={};for(let t of e.crowdedDirectories)i[t.module]=t.count;return Object.keys(i).length>0&&(t.crowdedDirectories=i),t}function observationsFromDetails(e){return e.linesOfCodeByDirectory?{linesOfCode:e.linesOfCodeByDirectory.reduce((e,t)=>e+t.count,0)}:{}}function offenderEntries(e,t){switch(t){case`crowdedDirectories`:return e.crowdedDirectories;case`circularDependencies`:return e.circularDependencies??[];case`fanInOutliers`:return e.fanInOutliers??[];case`fanOutOutliers`:return e.fanOutOutliers??[]}}function compareSizeBudgets(e,t){let n=[];for(let r of t){let t=e.sizeBudgets?.[r.id];r.measured===void 0?n.push({id:r.id,ceiling:t,pass:!1,reason:r.unmeasured??`not measured`}):t===void 0?n.push({id:r.id,measured:r.measured,pass:!1,reason:`unrecorded`,measurerChanged:r.measurerChanged}):n.push({id:r.id,ceiling:t,measured:r.measured,pass:r.measured<=t,measurerChanged:r.measurerChanged})}return n}function compareMetrics(e,t,n=0,r={},i=[]){let a=R.map(r=>{let i=e[r],a=t[r];return i===void 0||a===void 0?{key:r,baseline:i,current:a,delta:void 0,pass:!0}:{key:r,baseline:i,current:a,delta:a-i,pass:a<=i+n}}),o=[];for(let t of z){let i=e.moduleCeilings?.[t];if(i!==void 0)for(let[e,a]of Object.entries(i)){let i=r[t]?.[e];i!==void 0&&o.push({key:t,module:e,baseline:a,current:i,pass:i<=a+n})}}let s=[];if(e.moduleCeilings!==void 0)for(let t of z)for(let[n,i]of Object.entries(r[t]??{}))e.moduleCeilings[t]?.[n]===void 0&&s.push({key:t,module:n,current:i});let c=compareSizeBudgets(e,i);return{pass:a.every(e=>e.pass)&&o.every(e=>e.pass)&&c.every(e=>e.pass),tolerance:n,metrics:a,ceilings:o,uncoveredOutliers:s,sizeResults:c}}function needsBaseMeasurement(e){return e.uncoveredOutliers.length>0}function attributeOutliers(e,t){if(t.status!==`measured`)return{outlierBase:t.status===`unavailable`?{status:`unavailable`,mergeBase:t.mergeBase,reason:t.reason}:{status:`not-needed`},newOutliers:[],baseOutliers:[],unattributedOutliers:[...e]};let n=[],r=[];for(let i of e){let e=t.ceilings[i.key]?.[i.module];e===void 0?n.push(i):r.push({key:i.key,module:i.module,base:e,current:i.current})}return{outlierBase:{status:`measured`,mergeBase:t.mergeBase},newOutliers:n,baseOutliers:r,unattributedOutliers:[]}}function isFlatOrBetter(e,t,n={},r=[]){let i=R.every(n=>{let r=e[n],i=t[n];return r===void 0||i===void 0||i<=r}),a=z.every(t=>{let r=e.moduleCeilings?.[t];return r===void 0||Object.entries(r).every(([e,r])=>{let i=n[t]?.[e];return i===void 0||i<=r})}),o=r.every(t=>{let n=e.sizeBudgets?.[t.id];return n===void 0||t.measured!==void 0&&t.measured<=n});return i&&a&&o}function sizeRaiseValue(e){return Math.floor(e*1.01)+1}const ku=P.record(P.string(),P.unknown()),Au=[{prefix:`fan-in`,key:`fanInOutliers`},{prefix:`fan-out`,key:`fanOutOutliers`},{prefix:`crowding`,key:`crowdedDirectories`}];function refuseDeniableReason(e,t){let n=fixText(`// ${t}`,{offenders:resolveOffenders(),path:`health-raise.ts`}),r=n.decisions.find(e=>!e.applied);if(r!==void 0)throw new T(`health:raise: the reason for --exempt "${e}" carries ${r.hit.offender.codepoint} (${r.hit.offender.name}): ${r.reason??`this gate denies it`}. Rewrite it in ASCII.`);return n.text.slice(3)}function parseExemptLeaf(e){let t=e.indexOf(`:`),n=t<0?``:e.slice(0,t).trim(),r=t<0?``:e.slice(t+1).trim();if(n===`size`)throw new T(`health:raise: --exempt "${e}" names a size budget, which has no module to exempt. Run without --exempt: "health:raise" widens a grown size budget by measurement.`);let i=Au.find(e=>e.prefix===n);if(i===void 0||r===``)throw new T(`health:raise: --exempt "${e}" names no exemptable leaf. Pass one "health:check" printed: "fan-in: <path>", "fan-out: <path>", "crowding: <path>".`);return{key:i.key,path:r}}function copyCeilings$1(e){let t={};for(let n of z){let r=e?.[n];r!==void 0&&(t[n]={...r})}return t}function writeCeiling$1(e,t,n,r){let i=e[t]??{};i[n]=r,e[t]=i}function headlineFor(e,t,n,r){let i=t.metrics.find(e=>e.key===n)?.current;if(i===void 0)return;let a=Math.max(0,i-r);return e[n]===void 0?a:Math.max(e[n]??0,a)}function exemptionWrites(e){let t=[],n=[];for(let r of e.exemptions){let i=parseExemptLeaf(r.leaf);if(i===void 0)continue;let a=e.config.exempt[i.key]?.[i.path];a===void 0?t.push({key:i.key,path:i.path,reason:refuseDeniableReason(r.leaf,r.reason)}):n.push(`health.exempt.${i.key}.${i.path} already reads "${a}"; the reason was not overwritten.`)}return{writes:t,notes:n}}function objectAt(e,t,n){let r=e[t];if(r===void 0)return{};let i=ku.safeParse(r);if(!i.success)throw new T(`health:raise: ${n}#${t} is not an object, so an exemption cannot be written there.`);return{...i.data}}function applyExemptions(e,t){if(t.length===0)return;let n=ku.safeParse(e??{});if(!n.success)throw new T(`health:raise: .tooling.json is not a JSON object, so no exemption can be written.`);let r={...n.data};for(let e of t){let t=objectAt(r,`health`,`.tooling.json`),n=objectAt(t,`exempt`,`.tooling.json#health`),i=objectAt(n,e.key,`.tooling.json#health.exempt`);i[e.path]=e.reason,n[e.key]=i,t.exempt=n,r.health=t}return r}function planHealthRaise(e){let t=copyCeilings$1(e.baseline.moduleCeilings),n=[],r={},i=[],a=exemptionWrites(e);i.push(...a.notes);let isExcused=(e,t)=>a.writes.some(n=>n.key===e&&exemptKeyMatcher(n.path)(t)),o=/* @__PURE__ */ new Map,countExcused=(e,t)=>{isExcused(e,t)&&o.set(e,(o.get(e)??0)+1)};for(let t of e.attribution.newOutliers)countExcused(t.key,t.module);for(let t of e.comparison.ceilings)t.pass||countExcused(t.key,t.module);let s=e.attribution.outlierBase;s.status===`unavailable`&&i.push(`no "(new)" ceiling was written: the merge base ${s.mergeBase} could not be measured (${s.reason}), so nothing could be called a first crossing.`);for(let i of e.attribution.newOutliers){if(isExcused(i.key,i.module))continue;writeCeiling$1(t,i.key,i.module,i.current);let a=headlineFor(e.baseline,e.comparison,i.key,o.get(i.key)??0);a!==void 0&&(r[i.key]=a),n.push({key:i.key,module:i.module,value:i.current,...a===void 0?{}:{headline:a}})}for(let r of e.comparison.ceilings)r.pass||isExcused(r.key,r.module)||(writeCeiling$1(t,r.key,r.module,r.current),n.push({key:r.key,module:r.module,value:r.current}));let c={...e.baseline.sizeBudgets},l=[];for(let t of e.comparison.sizeResults){if(t.pass||t.measured===void 0||t.ceiling===void 0||t.measured<=t.ceiling)continue;let e=sizeRaiseValue(t.measured);c[t.id]=e,l.push({id:t.id,value:e})}return{baseline:widenedBaseline(e.baseline,r,t,c),tooling:applyExemptions(e.tooling,a.writes),ceilings:n,sizes:l,exemptions:a.writes,notes:i}}function widenedBaseline(e,t,n,r){let i={...e};for(let e of R){let n=t[e];n!==void 0&&(i[e]=n)}return i.moduleCeilings=Object.keys(n).length>0?n:void 0,i.sizeBudgets=Object.keys(r).length>0?r:void 0,i}function planHasWrites(e){return e.ceilings.length>0||e.sizes.length>0||e.exemptions.length>0}const ju=R.filter(e=>e!==`crowdedDirectories`),Mu={crowdedDirectories:`crowded directories`,circularDependencies:`circular dependencies`,fanInOutliers:`fan-in outliers`,fanOutOutliers:`fan-out outliers`,linesOfCode:`lines of code`},Nu={crowdedDirectories:`crowding`,fanInOutliers:`fan-in`,fanOutOutliers:`fan-out`};function formatMetricsSummary(e){let t=[`codebase health`];for(let n of R){let r=e[n];r!==void 0&&t.push(` ${Mu[n]}: ${r}`)}for(let n of it){let r=e[n];r!==void 0&&t.push(` ${Mu[n]}: ${r}`)}return e.coverageNote&&t.push(e.coverageNote),t.join(`
|
|
6115
6120
|
`)}function formatStatus(e){if(e.length===0)return`health: no history recorded yet.`;let t=[`health trend (oldest first):`];for(let n of e)t.push(` ${n.sha.slice(0,7)} crowded=${n.crowdedDirectories}`+(n.circularDependencies===void 0?``:` cycles=${n.circularDependencies}`)+(n.linesOfCode===void 0?``:` loc=${n.linesOfCode}`));return t.join(`
|
|
6116
|
-
`)}function capRows(e){return e.length<=25?e:[...e.slice(0,25),`... +${String(e.length-25)} more`]}function offenderRows(e,t){switch(t){case`crowdedDirectories`:return capRows(e.crowdedDirectories.map(e=>`${e.module} (${String(e.count)})`));case`circularDependencies`:return capRows((e.circularDependencies??[]).map(e=>`${e.from} -> ${e.to}`));case`fanInOutliers`:return capRows((e.fanInOutliers??[]).map(e=>e.lines===void 0?`${e.module} (${String(e.count)} importers)`:`${e.module} (${String(e.count)} importers, ${String(e.lines)} lines)`));case`fanOutOutliers`:return capRows((e.fanOutOutliers??[]).map(e=>`${e.module} (${String(e.count)} deps)`))}}function exemptRows(e,t){switch(t){case`fanInOutliers`:return capRows((e.fanInExempt??[]).map(e=>`${e.module} (${String(e.count)} importers) -- ${e.reason}`));case`fanOutOutliers`:return capRows((e.fanOutExempt??[]).map(e=>`${e.module} (${String(e.count)} deps) -- ${e.reason}`));case`crowdedDirectories`:return capRows((e.crowdedExempt??[]).map(e=>`${e.module} (${String(e.count)}) -- ${e.reason}`));case`circularDependencies`:return[]}}function linesOfCodeRows(e){return capRows((e.linesOfCodeByDirectory??[]).map(e=>`${e.module} (${String(e.count)})`))}function formatExplain(e){let t=[`codebase health -- offenders`],section=(n,r)=>{t.push(``,`${
|
|
6117
|
-
`)}function outlierAttributionLines(e,t){let n=[],r=!1;for(let t of e.newOutliers)n.push(` ${
|
|
6118
|
-
`)}function formatGraphUnavailable(e,t,n,r){if(!n||t.circularDependencies!==void 0)return;let i=
|
|
6119
|
-
`)}function diagnosticDetailLines(e){return e===void 0?[` health.extensions is empty, so no dependency-cruiser command ran this run.`]:[` command: ${e.command}`,` stderr: ${e.stderr.trim()===``?`(none)`:e.stderr.trim()}`]}function formatGraphUnavailableForSummary(e,t,n){if(t&&e.circularDependencies===void 0)return[`health: graph metrics unavailable this run (${
|
|
6120
|
-
`)}function formatStaleEntries(e){return e.map(e=>e.kind===`exemption`?`health.exempt: "${e.path}" names no module or directory this run measured, so it suppresses nothing. Delete the entry, or repoint it at wherever ${e.path} moved to.`:`health-baseline: the recorded ${
|
|
6121
|
+
`)}function capRows(e){return e.length<=25?e:[...e.slice(0,25),`... +${String(e.length-25)} more`]}function offenderRows(e,t){switch(t){case`crowdedDirectories`:return capRows(e.crowdedDirectories.map(e=>`${e.module} (${String(e.count)})`));case`circularDependencies`:return capRows((e.circularDependencies??[]).map(e=>`${e.from} -> ${e.to}`));case`fanInOutliers`:return capRows((e.fanInOutliers??[]).map(e=>e.lines===void 0?`${e.module} (${String(e.count)} importers)`:`${e.module} (${String(e.count)} importers, ${String(e.lines)} lines)`));case`fanOutOutliers`:return capRows((e.fanOutOutliers??[]).map(e=>`${e.module} (${String(e.count)} deps)`))}}function exemptRows(e,t){switch(t){case`fanInOutliers`:return capRows((e.fanInExempt??[]).map(e=>`${e.module} (${String(e.count)} importers) -- ${e.reason}`));case`fanOutOutliers`:return capRows((e.fanOutExempt??[]).map(e=>`${e.module} (${String(e.count)} deps) -- ${e.reason}`));case`crowdedDirectories`:return capRows((e.crowdedExempt??[]).map(e=>`${e.module} (${String(e.count)}) -- ${e.reason}`));case`circularDependencies`:return[]}}function linesOfCodeRows(e){return capRows((e.linesOfCodeByDirectory??[]).map(e=>`${e.module} (${String(e.count)})`))}function formatExplain(e){let t=[`codebase health -- offenders`],section=(n,r)=>{t.push(``,`${Mu[n]??n} (${String(r)}):`);let i=offenderRows(e,n);if(i.length===0)t.push(` (none)`);else for(let e of i)t.push(` ${e}`);let a=exemptRows(e,n);if(a.length>0){t.push(` exempt (${String(a.length)}):`);for(let e of a)t.push(` ${e}`)}};if(section(`crowdedDirectories`,e.crowdedDirectories.length),e.circularDependencies&§ion(`circularDependencies`,e.circularDependencies.length),e.fanInOutliers&§ion(`fanInOutliers`,e.fanInOutliers.length),e.fanOutOutliers&§ion(`fanOutOutliers`,e.fanOutOutliers.length),e.linesOfCodeByDirectory){let n=e.linesOfCodeByDirectory.reduce((e,t)=>e+t.count,0);t.push(``,`${Mu.linesOfCode} (${String(n)}):`);let r=linesOfCodeRows(e);if(r.length===0)t.push(` (none)`);else for(let e of r)t.push(` ${e}`)}return t.join(`
|
|
6122
|
+
`)}function outlierAttributionLines(e,t){let n=[],r=!1;for(let t of e.newOutliers)n.push(` ${Nu[t.key]}: ${t.module} -- -> ${t.current} (new)`),r=!0;for(let i of e.baseOutliers)t.has(i.key)&&(n.push(` ${Nu[i.key]}: ${i.module} ${i.base} -> ${i.current} (on base)`),r=!0);for(let i of e.unattributedOutliers)t.has(i.key)&&(n.push(` ${Nu[i.key]}: ${i.module} -- -> ${i.current} (no ceiling)`),r=!0);return r&&(e.outlierBase.status===`measured`?n.push(` outliers attributed against the merge base ${e.outlierBase.mergeBase}`):e.outlierBase.status===`unavailable`&&n.push(` outliers not attributed: the merge base ${e.outlierBase.mergeBase} could not be measured (${e.outlierBase.reason})`)),n}function formatCompareDiff(e,t,n){let r=[];for(let n of e.metrics){if(n.baseline===void 0&&n.current===void 0)continue;let e=n.baseline??`--`,i=n.current??`--`,a;a=n.delta===void 0?``:n.delta===0?` (0)`:` (${n.delta>0?`+`:``}${n.delta})`;let o=n.pass?``:` REGRESSION`;if(r.push(` ${Mu[n.key]}: ${e} -> ${i}${a}${o}`),!n.pass&&t)for(let e of offenderRows(t,n.key))r.push(` ${e}`)}for(let t of e.ceilings)t.pass||r.push(` ${Nu[t.key]}: ${t.module} ${t.baseline} -> ${t.current} (ceiling)`);for(let t of e.sizeResults)if(!t.pass){let e;e=t.measured===void 0?` size: ${t.id} unmeasured (${t.reason??`not measured`})`:t.ceiling===void 0?` size: ${t.id} -- -> ${t.measured} (unrecorded)`:` size: ${t.id} ${t.ceiling} -> ${t.measured} (ceiling)`,r.push(e),t.measurerChanged===!0&&r.push(` size: ${t.id} measured by code this branch changed`)}let i=new Set(e.metrics.filter(e=>e.pass===!1).map(e=>e.key));return r.push(...outlierAttributionLines(n,i)),r.push(e.pass&&n.newOutliers.length===0?`health: PASS`:`health: FAIL`),r.join(`
|
|
6123
|
+
`)}function formatGraphUnavailable(e,t,n,r){if(!n||t.circularDependencies!==void 0)return;let i=ju.filter(t=>e[t]!==void 0);if(i.length!==0)return[`health: the dependency graph was not measured this run, but the baseline records ${i.map(e=>Mu[e]).join(`, `)}.`,...diagnosticDetailLines(r)].join(`
|
|
6124
|
+
`)}function diagnosticDetailLines(e){return e===void 0?[` health.extensions is empty, so no dependency-cruiser command ran this run.`]:[` command: ${e.command}`,` stderr: ${e.stderr.trim()===``?`(none)`:e.stderr.trim()}`]}function formatGraphUnavailableForSummary(e,t,n){if(t&&e.circularDependencies===void 0)return[`health: graph metrics unavailable this run (${ju.map(e=>Mu[e]).join(`, `)}).`,...diagnosticDetailLines(n)].join(`
|
|
6125
|
+
`)}function formatStaleEntries(e){return e.map(e=>e.kind===`exemption`?`health.exempt: "${e.path}" names no module or directory this run measured, so it suppresses nothing. Delete the entry, or repoint it at wherever ${e.path} moved to.`:`health-baseline: the recorded ${Nu[e.metric]??e.metric} ceiling for "${e.path}" (ceiling ${String(e.count??0)}) names a path this run did not measure, so that ratchet is switched off. If the path moved, re-baseline it; if it is gone, --update-baseline drops it.`)}function sourceEntryWarning(e){return e.status===`unrepresentable`?`health.src: "${e.pattern}" is not a pattern the expander can resolve -- it expands a single "*" path segment only (e.g. "packages/*/src"). Rewrite the entry.`:`health.src: "${e.pattern}" matched no existing directory. Fix the path, or the tree it expects to find, whichever moved.`}function formatSourceDiagnosis(e,t){let n=e.entries.filter(e=>e.status!==`resolved`).map(e=>sourceEntryWarning(e));if(e.fileCount>0)return{warnings:n};let r=e.entries.length>0?e.entries.map(e=>`"${e.pattern}"`).join(`, `):`(none)`,i=e.roots.length>0?e.roots.join(`, `):`(none)`,a=e.entries.every(e=>e.status===`unmatched`),o=e.entries.length>0&&e.entries.every(e=>e.status===`resolved`),s;s=t?a?`crowdedDirectories and the linesOfCode observation both read 0 this run -- these same entries are spliced into the dependency-cruiser call verbatim, so the cruise matched nothing either: the dependency graph metrics read 0 or are absent this run too.`:`crowdedDirectories and the linesOfCode observation both read 0 this run -- the dependency graph metrics are unaffected, since health.src is spliced into the dependency-cruiser call verbatim and can still be live: this holds for an entry naming directories dependency-cruiser can expand (e.g. "packages/**/src"), but an entry naming files (e.g. "src/**/*.ts") leaves the cruise glob matching nothing there either.`:`graph metrics are disabled for this repo (no JS/TS stack to cruise), so the dependency graph was never measured either.`;let c=o&&e.roots.length>0?`Every entry resolved to a real directory, so the test-path, ".d.ts", "exclude", or "extensions" filters may have dropped every file rather than health.src itself.`:``;return{warnings:n,emptyScope:[`health.src measured no source files this run.`,`Configured entries: ${r}.`,`Resolved roots: ${i}.`,s,c,`Run "pnpm exec bst health:summary --explain" for the full breakdown.`].filter(e=>e.length>0).join(` `)}}function formatUnresolvedFirstParty(e){let t=e.map(e=>` ${e.importer} -> ${e.specifier}`);return t.push(` An unresolved first-party import leaves the dependency graph, improving every health`,` metric. Fix the import, or the resolve options that were supposed to follow it.`),t.join(`
|
|
6121
6126
|
`)}function formatSlack(e){if(e.length===0)return[];let t=[`slack: ${String(e.length)} recorded ${e.length===1?`value`:`values`} above what this run measures. Run "pnpm exec bst health:tighten" to lower them.`];for(let n of e){let e=slackSuffix(n.kind),r=n.recorded??`--`,i=n.measured??`--`;t.push(` ${n.leaf} ${String(r)} -> ${String(i)} ${e}`)}return t}function slackSuffix(e){return e===`dead-ceiling`?`(dead ceiling)`:e===`uncapped`?`(uncapped)`:`(slack)`}function formatCarriedRaises(e){return[`raises carried by this branch:`,...e.map(e=>` ${e.leaf}: ${e.reference} -> ${e.current}`)].join(`
|
|
6122
|
-
`)}const
|
|
6127
|
+
`)}const Pu=new Set(R.filter(e=>e!==`crowdedDirectories`));function isGraphMetric(e){return Pu.has(e)}function ceilingLeaf(e,t){return`${Nu[e]}: ${t}`}function copyCeilings(e){let t={};for(let n of z){let r=e?.[n];r!==void 0&&(t[n]={...r})}return t}function writeCeiling(e,t,n,r){let i=e[t]??{};i[n]=r,e[t]=i}function dropCeiling(e,t,n){let r=e[t];r!==void 0&&(delete r[n],Object.keys(r).length===0&&delete e[t])}function slackRecords(e){let{comparison:t,attribution:n,baseline:r,graphMeasured:i}=e,a=[];for(let e of R){if(!i&&isGraphMetric(e))continue;let n=r[e],o=t.metrics.find(t=>t.key===e)?.current;n!==void 0&&o!==void 0&&(o>=n||a.push({kind:`count`,key:e,leaf:e,recorded:n,measured:o}))}let o=new Set(t.ceilings.map(e=>ceilingLeaf(e.key,e.module)));for(let e of t.ceilings)!i&&isGraphMetric(e.key)||e.current>=e.baseline||a.push({kind:`ceiling`,key:e.key,module:e.module,leaf:ceilingLeaf(e.key,e.module),recorded:e.baseline,measured:e.current});for(let e of z)if(i||!isGraphMetric(e))for(let[t,n]of Object.entries(r.moduleCeilings?.[e]??{}))o.has(ceilingLeaf(e,t))||a.push({kind:`dead-ceiling`,key:e,module:t,leaf:ceilingLeaf(e,t),recorded:n});for(let e of n.baseOutliers)(i||!isGraphMetric(e.key))&&a.push({kind:`uncapped`,key:e.key,module:e.module,leaf:ceilingLeaf(e.key,e.module),measured:e.current});for(let e of t.sizeResults){let t=r.sizeBudgets?.[e.id];if(t===void 0||e.measured===void 0)continue;let n=sizeRaiseValue(e.measured);t<=n||a.push({kind:`size`,id:e.id,leaf:`size: ${e.id}`,recorded:t,measured:e.measured,to:n})}return a}function slackEntry(e){return e.kind===`uncapped`?{kind:e.kind,leaf:e.leaf,measured:e.measured}:e.kind===`dead-ceiling`?{kind:e.kind,leaf:e.leaf,recorded:e.recorded}:{kind:e.kind,leaf:e.leaf,recorded:e.recorded,measured:e.measured}}function findSlack(e){return slackRecords(e).map(slackEntry)}function planHealthTighten(e){let t=copyCeilings(e.baseline.moduleCeilings),n={...e.baseline.sizeBudgets},r={...e.baseline},i=[],a=[],o=[];for(let s of slackRecords(e))switch(s.kind){case`count`:r[s.key]=s.measured,i.push({leaf:s.leaf,from:s.recorded,to:s.measured});break;case`ceiling`:writeCeiling(t,s.key,s.module,s.measured),i.push({leaf:s.leaf,from:s.recorded,to:s.measured});break;case`dead-ceiling`:dropCeiling(t,s.key,s.module),a.push({key:s.key,module:s.module,value:s.recorded});break;case`uncapped`:writeCeiling(t,s.key,s.module,s.measured),o.push({key:s.key,module:s.module,value:s.measured});break;case`size`:n[s.id]=s.to,i.push({leaf:s.leaf,from:s.recorded,to:s.to})}return r.moduleCeilings=Object.keys(t).length>0?t:void 0,r.sizeBudgets=Object.keys(n).length>0?n:void 0,{baseline:r,lowered:i,removed:a,caps:o}}function baselineUpdateRefusal(e){if(e.newOutliers.length>0)return`Skipped baseline update: an outlier crossed a limit for the first time this run. Record it with "health:raise", which writes the ceiling beside the reason it was earned.`;if(e.unattributedOutliers.length>0){let t=e.outlierBase;return`Skipped baseline update: an outlier has no recorded ceiling and no merge-base measurement to clear it.${t.status===`unavailable`?` The merge base could not be measured: ${t.reason}.`:``} Record it with "health:raise", which writes the ceiling beside the reason it was earned.`}return null}function withMergeBaseCheckout(t,n,r,i){let a=e.mkdtempSync(w.join(ye.tmpdir(),`bst-health-base-`)),o=w.join(a,`tree`),s=w.join(a,`index`);try{e.mkdirSync(o,{recursive:!0});let a=gitOutput(t.exec(`git`,[`rev-parse`,`--absolute-git-dir`],{cwd:n}),`git rev-parse --absolute-git-dir`).trim(),c=gitOutput(t.exec(`git`,[`rev-parse`,`--show-toplevel`],{cwd:n}),`git rev-parse --show-toplevel`).trim(),intoCheckout=e=>t.exec(`git`,[`--git-dir=${a}`,`--work-tree=${o}`,...e],{cwd:o,env:{GIT_INDEX_FILE:s}});return gitOutput(intoCheckout([`read-tree`,r]),`git read-tree ${r.slice(0,12)}`),gitOutput(intoCheckout([`checkout-index`,`-a`]),`git checkout-index -a`),mirrorNodeModules(c,o),i(o)}finally{e.rmSync(a,{recursive:!0,force:!0})}}function gitOutput(e,t){if(e.exitCode===0)return e.stdout;let n=e.stderr.trim().split(`
|
|
6123
6128
|
`)[0]??``;throw new E(`${t} failed: ${n===``?`exit ${String(e.exitCode)}`:n}`)}function mirrorNodeModules(e,t){mirrorTree(e,t,``)}function mirrorTree(t,n,r){mirrorEntries(w.join(t,r,`node_modules`),w.join(n,r,`node_modules`));let i;try{i=e.readdirSync(w.join(n,r),{withFileTypes:!0})}catch{return}for(let e of i)e.isDirectory()&&!e.isSymbolicLink()&&e.name!==`.git`&&e.name!==`node_modules`&&mirrorTree(t,n,w.join(r,e.name))}function mirrorEntries(t,n){let r;try{r=e.readdirSync(t,{withFileTypes:!0})}catch{return}e.mkdirSync(n,{recursive:!0});for(let i of r){let r=w.join(t,i.name),a=w.join(n,i.name);if(i.isSymbolicLink()){let e=safeReadlink(r);if(e!==void 0&&!w.isAbsolute(e)){linkRelative(e,a);continue}}else if(i.isDirectory()&&i.name.startsWith(`@`)){mirrorEntries(r,a);continue}try{e.symlinkSync(r,a,i.isDirectory()?`dir`:`file`)}catch{}}}function safeReadlink(t){try{return e.readlinkSync(t)}catch{return}}function linkRelative(t,n){try{e.symlinkSync(t,n)}catch{}}function unavailable(e){return{status:`unavailable`,reason:firstLine(e)}}function firstLine(e){return e.trim().split(`
|
|
6124
|
-
`)[0]??``}function measureBaseOutliers(e){let t=e.collect??collectDetails;try{return withMergeBaseCheckout(e.executor,e.targetDir,e.mergeBase,n=>{let r=w.join(n,e.prefix),i=buildCollectConfig(e.config,{tsConfig:o(w.join(r,`tsconfig.json`))?`tsconfig.json`:void 0}),a=t(createRealHealthExecutor(r),i),s=a.unresolvedFirstParty;return s!==void 0&&s.length>0?unavailable(`the base cruise could not resolve ${String(s.length)} first-party imports`):e.config.graphMetricsEnabled&&a.circularDependencies===void 0?unavailable(`the base cruise produced no graph metrics`):{status:`measured`,ceilings:ceilingsFromDetails(a)}})}catch(e){return unavailable(O(e))}}function byteLength(e){try{let t=b(e);return t.isFile()?t.size:void 0}catch{return}}function measurerChanged(e,t){let n=[...e.files,`package.json`],r=P(n,{dot:!0});return t.some(e=>r(e))}function measureSizeBudgets(e,t,n){let r=[];for(let[i,a]of Object.entries(t).toSorted(([e],[t])=>e.localeCompare(t)))r.push(measureOne(e,i,a,n));return r}function measureOne(e,t,n,r){if(`file`in n){let r=byteLength(w.join(e,n.file));return r===void 0?{id:t,unmeasured:`no file at ${n.file}`}:{id:t,measured:r}}if(`glob`in n){let r=[];for(let t of c(n.glob,{cwd:e})){let n=byteLength(w.join(e,t));n!==void 0&&r.push(n)}if(r.length===0)return{id:t,unmeasured:`glob ${n.glob} matched no files`};let i=0,a=0;for(let e of r)i+=e,e>a&&(a=e);return{id:t,measured:n.aggregate===`largest`?a:i}}let i=r.executor.exec(`pnpm`,[`run`,`--silent`,n.script],{cwd:e});if(i.exitCode!==0)return{id:t,unmeasured:`script ${n.script} exited ${String(i.exitCode)}`};let a=readMeasureMarker(i.stdout);return a===void 0?{id:t,unmeasured:`script ${n.script} printed no measure marker`}:measurerChanged(n,r.changedNames)?{id:t,measured:a,measurerChanged:!0}:{id:t,measured:a}}const $=`health-baseline.json`;function readTargetReference(e,t,n){let r=detectHealthContext(t),i=readReference(e,{cwd:t,stack:r.stack,isMonorepo:r.isMonorepo,ciEvent:processCiEventSource()});return i.kind===`read`&&i.warning!==void 0&&n.notice(i.warning),i}function reportCarriedRaises(e,t){e.length!==0&&(t.text(formatCarriedRaises(e)),t.text(formatWarnMarker(e.length)))}function assessRaises(e,t,n,r){let i=readTargetReference(e,t,r);if(i.kind===`unavailable`)throw new T(i.reason);let a=i.reference;return a.baseline===void 0?(r.notice(`${$} has no counterpart on the default branch yet, so there is nothing to raise against.`),{fields:{reference:{status:`no-baseline`,mergeBase:a.mergeBase},raises:[]},prefix:a.prefix}):{fields:{reference:{status:`read`,mergeBase:a.mergeBase},raises:findRaises(a,n)},prefix:a.prefix}}function attributeRun(e){let{result:t,executor:n,targetDir:r,fields:i,prefix:a,config:o}=e;if(!needsBaseMeasurement(t))return attributeOutliers(t.uncoveredOutliers,{status:`not-needed`});let s=i.reference.mergeBase,c=measureBaseOutliers({executor:n,targetDir:r,mergeBase:s,prefix:a,config:o}),l=c.status===`measured`?{status:`measured`,mergeBase:s,ceilings:c.ceilings}:{status:`unavailable`,mergeBase:s,reason:c.reason};return attributeOutliers(t.uncoveredOutliers,l)}function changedPathsForMeasurers(e,t,n,r,i){return Object.values(n).some(e=>`script`in e)?branchDiffNames(e,t,r).filter(e=>e.startsWith(i)).map(e=>e.slice(i.length)).filter(e=>e!==``):[]}function refuseUnresolvedImports(e){let t=e.unresolvedFirstParty;if(t!==void 0&&t.length>0)throw new T(formatUnresolvedFirstParty(t))}function refuseEmptyScope(e,t,n,r){let{warnings:i,emptyScope:a}=formatSourceDiagnosis(e.sources,t.graphMetricsEnabled);for(let e of i)r.notice(e);if(a!==void 0&&n!==!1)throw new T(a);a!==void 0&&r.notice(a)}function measureHealth(e,t,n,r={}){let i=createRealHealthExecutor(e),a=collectDetails(i,buildCollectConfig(t,{tsConfig:o(w.join(e,`tsconfig.json`))?`tsconfig.json`:void 0})),s=metricsFromDetails(a),c=ceilingsFromDetails(a);refuseUnresolvedImports(a),refuseEmptyScope(a,t,r.failOnEmptySrc,n);let l=w.join(e,$),u=o(l)?parseHealthBaseline(p(l,`utf-8`)):void 0,d=assessRaises(i,e,{baseline:u,health:t,measured:{metrics:s,ceilings:c}},n),f=measureSizeBudgets(e,t.sizeBudgets,{executor:i,changedNames:changedPathsForMeasurers(i,e,t.sizeBudgets,d.fields.reference.mergeBase,d.prefix)});if(u===void 0)return{executor:i,details:a,current:s,ceilings:c,sizes:f,baselinePath:l,referenceFields:d.fields,prefix:d.prefix,existing:void 0};let m=compareMetrics(u,s,t.tolerance,c,f),h=attributeRun({result:m,executor:i,targetDir:e,fields:d.fields,prefix:d.prefix,config:t});return{executor:i,details:a,current:s,ceilings:c,sizes:f,baselinePath:l,referenceFields:d.fields,prefix:d.prefix,existing:{baseline:u,result:m,attribution:h}}}function wasMeasured(e,t,n){return e===`crowdedDirectories`?n.directories.has(t):n.graphModules?.has(t)??!0}function exemptionWasMeasured(e,t,n){let r=e===`crowdedDirectories`?n.directories:n.graphModules;if(r===void 0)return!0;let i=exemptKeyMatcher(t);return[...r].some(i)}function findStaleEntries(e,t,n){let r=[];for(let n of R){let i=e.moduleCeilings?.[n];if(i!==void 0)for(let[e,a]of Object.entries(i))wasMeasured(n,e,t)||r.push({kind:`ceiling`,metric:n,path:e,count:a})}for(let e of rt)for(let i of Object.keys(n[e]??{}))exemptionWasMeasured(e,i,t)||r.push({kind:`exemption`,metric:e,path:i});return r}function assessSwitchOff(e,t,n,r){let i=readTargetReference(e,t,r);if(i.kind===`unavailable`)return;let a=i.reference;if(!a.health.enabled||a.baseline===void 0)return;let s=w.join(t,$),c=o(s)?parseHealthBaseline(p(s,`utf-8`)):void 0,l=healthOverridesAt(t),u={...n};for(let e of vo)l?.[e]===void 0&&(u[e]=a.health[e]);return{reference:{status:`read`,mergeBase:a.mergeBase},raises:findRaises(a,{baseline:c,health:u})}}function sizeValuesToRecord(e,t,n){let r={...e?.sizeBudgets};for(let e of t)e.measured!==void 0&&(n||r[e.id]===void 0)&&(r[e.id]=e.measured);return Object.keys(r).length>0?r:void 0}function handleMissingBaseline(e,t,n){let{targetDir:r,config:i,details:a,current:o,ceilings:s,sizes:c,out:l}=e;if(t===!0){if(i.graphMetricsEnabled&&a.circularDependencies===void 0){l.notice(`Skipped baseline creation: graph metrics are unavailable this run. Fix the cruise before creating ${$}.`),l.json({status:`graph-unavailable`,...e.referenceFields,metrics:o,sources:a.sources}),reportCarriedRaises(e.referenceFields.raises,l),process.exitCode=1;return}writeHealthBaseline(r,{...o,moduleCeilings:s,sizeBudgets:sizeValuesToRecord(void 0,c,!1)}),l.notice(`Created ${$} (no prior baseline).`),l.json({status:`baseline-created`,...e.referenceFields,metrics:o,sources:a.sources}),reportCarriedRaises(e.referenceFields.raises,l);return}let u=`${$} not found. Run with --update-baseline to create one from the current run.`;if(n===!1)l.notice(u),l.json({status:`missing-baseline`,...e.referenceFields,metrics:o,sources:a.sources}),reportCarriedRaises(e.referenceFields.raises,l);else throw reportCarriedRaises(e.referenceFields.raises,l),new T(u)}function adoptUnrecorded(e,t,n,r){let i={...e};for(let e of L){let t=n[e];i[e]===void 0&&t!==void 0&&(i[e]=t)}return t.moduleCeilings===void 0&&(i.moduleCeilings=r),i}function applyBaselineUpdate(e,t,n){let{targetDir:r,config:i,details:a,current:o,ceilings:s,sizes:c,out:l}=e,{baseline:u,result:d,attribution:f}=t;if(i.graphMetricsEnabled&&a.circularDependencies===void 0)l.notice(`Skipped baseline update: graph metrics are unavailable this run. Fix the cruise before updating.`),process.exitCode=1;else if(n===!0)writeHealthBaseline(r,{...o,moduleCeilings:s,sizeBudgets:sizeValuesToRecord(u,c,!0)}),l.notice(`Reset ${$} to the current run.`);else if(isFlatOrBetter(u,o,s,c)){let e=baselineUpdateRefusal(f);if(e!==null)l.notice(e);else{let e=planHealthTighten({comparison:d,attribution:f,baseline:u,graphMeasured:i.graphMetricsEnabled});writeHealthBaseline(r,{...adoptUnrecorded(e.baseline,u,o,s),sizeBudgets:sizeValuesToRecord(e.baseline,c,!1)}),l.notice(`Updated ${$} (no regressions).`)}}else l.notice(`Skipped baseline update: a metric or ceiling regressed. Fix the regression before updating.`)}function collectRegressions(e,t){let n={};for(let r of e.metrics)r.pass||(n[r.key]=offenderEntries(t,r.key));return n}const ou=A({meta:{name:`health:check`,description:`Compare codebase-health metrics against health-baseline.json. Does nothing unless .tooling.json#health.enabled is true.`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Project directory (default: current directory)`,required:!1},"update-baseline":{type:`boolean`,description:`If no metric regressed, rewrite health-baseline.json`},reset:{type:`boolean`,description:`With --update-baseline, rewrite health-baseline.json unconditionally, even when a metric regressed. For adopting a baseline after a deliberate measurement change, such as health.crossPackage changing what the cruise resolves. Still refused when graph metrics are enabled and this run measured no graph.`},"fail-on-missing-baseline":{type:`boolean`,default:!0,description:`Fail when no baseline exists (default). --no-fail-on-missing-baseline downgrades it to a notice.`},"fail-on-empty-src":{type:`boolean`,default:!0,description:`Fail when the configured health.src scope measured no source files (default). --no-fail-on-empty-src downgrades it to a notice.`},json:{type:`boolean`,description:"Emit one JSON document: status (compared | disabled | baseline-created | missing-baseline | graph-unavailable). disabled carries reference and raises only when the default branch has health enabled -- switching it off is a raise -- and nothing otherwise. Every other status carries reference ({status (read | no-baseline), mergeBase}) and raises ([{leaf, reference, current}]: every way this branch's two health files are higher than the default branch's, which it carries with its own code and a person merges). baseline-created, missing-baseline and graph-unavailable carry metrics ({crowdedDirectories, circularDependencies?, fanInOutliers?, fanOutOutliers?}) and sources. compared carries pass (false when newOutliers holds an entry, even with every count flat), tolerance, metrics (a list: [{key (crowdedDirectories | circularDependencies | fanInOutliers | fanOutOutliers), baseline?, current?, delta?, pass}]), ceilings ([{key (fanInOutliers | fanOutOutliers | crowdedDirectories), module, baseline, current, pass}]), sizeBudgets ([{id, ceiling?, measured?, pass, reason?}] -- every budget .tooling.json#health.sizeBudgets declares; reason is `unrecorded` for a declared budget with no recorded value, or the measurer's own explanation when it measured nothing), outlierBase ({status (measured | not-needed | unavailable), mergeBase?, reason?}), newOutliers ([{key, module, current}], outliers not on the merge base; empty unless measured), baseOutliers ([{key, module, base, current}]) and unattributedOutliers ([{key, module, current}], every outlier with no ceiling when the base was not measured), graphMetricsEnabled, graphMetricsMissing, slack ([{kind (count | ceiling | dead-ceiling | uncapped | size), leaf, recorded?, measured?}] -- every recorded value sitting above what this run measured, in the leaf spelling the failure lines print; information only, never a finding and never the verdict), staleEntries ([{kind (ceiling | exemption), metric, path, count?}]), regressions ({<failing metric key>: [{module, count} | {from, to}]}) and sources. sources is {entries ([{pattern, roots, status (resolved | unmatched | unrepresentable)}]), roots, fileCount}."}},run({args:e}){let t=w.resolve(e.dir??`.`),n=createCliOutput(e.json===!0),r=resolveHealthConfig(t);if(!r.enabled){n.notice(`health: disabled (set .tooling.json#health.enabled to true to enable).`);let e=assessSwitchOff(createRealHealthExecutor(t),t,r,n);n.json({status:`disabled`,...e}),reportCarriedRaises(e?.raises??[],n);return}r.graphMetricsEnabled||n.notice(`health: graph metrics disabled (no JS/TS source to cruise) -- crowdedDirectories only.`);let i=measureHealth(t,r,n,{failOnEmptySrc:e[`fail-on-empty-src`]}),a={targetDir:t,config:r,details:i.details,current:i.current,ceilings:i.ceilings,sizes:i.sizes,out:n,referenceFields:i.referenceFields},o=i.existing;if(o===void 0){handleMissingBaseline(a,e[`update-baseline`],e[`fail-on-missing-baseline`]);return}let{baseline:s,result:c,attribution:l}=o;n.text(formatCompareDiff(c,i.details,l));let u=findSlack({comparison:c,attribution:l,baseline:s,graphMeasured:!(r.graphMetricsEnabled&&i.details.circularDependencies===void 0)});for(let e of formatSlack(u))n.text(e);reportCarriedRaises(i.referenceFields.raises,n);let d=collectRegressions(c,i.details),f=formatGraphUnavailable(s,i.details,r.graphMetricsEnabled,i.details.graphDiagnostic);f!==void 0&&n.notice(f);let p=findStaleEntries(s,i.details,r.exempt);for(let e of formatStaleEntries(p))n.notice(e);let m=c.pass&&l.newOutliers.length===0;n.json({status:`compared`,...i.referenceFields,pass:m,tolerance:c.tolerance,metrics:c.metrics,ceilings:c.ceilings,sizeBudgets:c.sizeResults,outlierBase:l.outlierBase,newOutliers:l.newOutliers,baseOutliers:l.baseOutliers,unattributedOutliers:l.unattributedOutliers,graphMetricsEnabled:r.graphMetricsEnabled,graphMetricsMissing:f!==void 0,slack:u,staleEntries:p,regressions:d,sources:i.details.sources}),e[`update-baseline`]===!0&&applyBaselineUpdate(a,o,e.reset),m&&f===void 0||(process.exitCode=1)}}),su=N.json(),cu=`.tooling.json`;function collectExemptPairs(e){let t=collectFlagValues(e,`--exempt`),n=collectFlagValues(e,`--reason`);if(t.length===0&&n.length>0)throw new T(`health:raise: ${String(n.length)} --reason given with no --exempt to explain.`);if(n.length<t.length)throw new T(`health:raise: ${String(t.length)} --exempt given with only ${String(n.length)} --reason. Every exemption owes its own reason: it is the line a later reader judges.`);return t.map((e,t)=>({leaf:e,reason:n[t]??``}))}function readToolingFile(e){let t=w.join(e,cu);if(!o(t))return;let n=p(t,`utf-8`),r;try{r=JSON.parse(n)}catch(e){let t=e instanceof Error?e.message:`unknown error`;throw new T(`health:raise: ${cu} is not JSON: ${t}. Fix the file and re-run.`)}let i=su.safeParse(r);if(!i.success)throw new T(`health:raise: ${cu} is not JSON: ${i.error.message}`);return i.data}function describePlan$1(e){let t=[];for(let n of e.ceilings){let e=n.headline===void 0?``:`, ${n.key} set to ${String(n.headline)}`;t.push(`health-baseline: ${n.key} ${n.module} ceiling ${String(n.value)}${e}`)}for(let n of e.sizes)t.push(`health-baseline: size budget ${n.id} widened to ${String(n.value)}`);for(let n of e.exemptions)t.push(`${cu}: health.exempt.${n.key}.${n.path} exempted -- ${n.reason}`);for(let n of e.notes)t.push(`health: ${n}`);return t}const lu=A({meta:{name:`health:raise`,description:`Widen the health budgets this branch crossed, by measurement: no number is an argument. Writes health-baseline.json (a new outlier's ceiling plus its headline count, a grown module ceiling, a grown size budget) and, for --exempt pairs, .tooling.json#health.exempt. Does nothing unless .tooling.json#health.enabled is true.`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Project directory (default: current directory)`,required:!1},"dry-run":{type:`boolean`,description:`Print what would be written and write nothing`},exempt:{type:`string`,description:`Exempt this leaf instead of recording a ceiling (repeatable), as "health:check" printed it: "fan-in: src/a.ts"`},reason:{type:`string`,description:`Why this exemption is justified (repeatable; one per --exempt)`},json:{type:`boolean`,description:`Emit one JSON document: status (raised | nothing-to-raise | disabled), dryRun, wrote ([path]), ceilings ([{key, module, value, headline?}]), sizeBudgets ([{id, value}]), exemptions ([{key, path, reason}]), notes ([string]), reference ({status (read | no-baseline), mergeBase}).`}},run({args:e,rawArgs:t}){let n=w.resolve(e.dir??`.`),r=createCliOutput(e.json===!0),i=resolveHealthConfig(n);if(!i.enabled){r.notice(`health: disabled (set .tooling.json#health.enabled to true to enable).`),r.json({status:`disabled`,dryRun:e[`dry-run`]===!0});return}let a=measureHealth(n,i,r);if(a.existing===void 0)throw new T(`health:raise: no health-baseline.json to widen. Run "health:check --update-baseline" first: a raise widens a recorded number, and there is nothing recorded.`);let o=planHealthRaise({comparison:a.existing.result,attribution:a.existing.attribution,baseline:a.existing.baseline,config:i,tooling:readToolingFile(n),exemptions:collectExemptPairs(t)}),s=e[`dry-run`]===!0,c=s?[]:writePlan(n,o);for(let e of describePlan$1(o))r.text(e);r.json({status:planHasWrites(o)?`raised`:`nothing-to-raise`,dryRun:s,wrote:c,ceilings:o.ceilings,sizeBudgets:o.sizes,exemptions:o.exemptions,notes:o.notes,reference:a.referenceFields.reference})}});function writePlan(e,t){let n=[];if((t.ceilings.length>0||t.sizes.length>0)&&(writeHealthBaseline(e,t.baseline),n.push(`health-baseline.json`)),t.tooling!==void 0){let r=healthFileFormatter(e);C(w.join(e,cu),r(cu,JSON.stringify(t.tooling,null,2))),n.push(cu)}return n}const uu=`health-baseline.json`;function describePlan(e){let t=[];for(let n of e.lowered)t.push(`health-baseline: ${n.leaf} ${String(n.from)} -> ${String(n.to)}`);for(let n of e.removed)t.push(`health-baseline: ${n.key}: ${n.module} ceiling ${String(n.value)} removed`);for(let n of e.caps)t.push(`health-baseline: ${n.key}: ${n.module} capped at ${String(n.value)}`);return t}const du=A({meta:{name:`health:tighten`,description:`Shed the slack this branch's own measurement proved the baseline holds, by measurement: no number is an argument. Rewrites health-baseline.json with each recorded count and module ceiling lowered to what the run measured, dead ceilings removed, and current outliers capped; it never touches .tooling.json. Does nothing unless .tooling.json#health.enabled is true.`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Project directory (default: current directory)`,required:!1},"dry-run":{type:`boolean`,description:`Print what would be written and write nothing`},json:{type:`boolean`,description:`Emit one JSON document: status (tightened | nothing-to-tighten | disabled | graph-unavailable), dryRun, wrote ([path]), lowered ([{leaf, from, to}]), removed ([{key, module, value}]), caps ([{key, module, value}]), reference ({status (read | no-baseline), mergeBase}). disabled and graph-unavailable carry no writes.`}},run({args:e}){let t=w.resolve(e.dir??`.`),n=createCliOutput(e.json===!0),r=e[`dry-run`]===!0,i=resolveHealthConfig(t);if(!i.enabled){n.notice(`health: disabled (set .tooling.json#health.enabled to true to enable).`),n.json({status:`disabled`,dryRun:r});return}let a=measureHealth(t,i,n);if(a.existing===void 0)throw new T(`health:tighten: no ${uu} to lower. Run "health:check --update-baseline" first: a tighten lowers a recorded number, and there is nothing recorded.`);if(i.graphMetricsEnabled&&a.details.circularDependencies===void 0){n.notice(`Skipped: graph metrics are unavailable this run. Fix the cruise before tightening ${uu}.`),n.json({status:`graph-unavailable`,dryRun:r,wrote:[]}),process.exitCode=1;return}let o=planHealthTighten({comparison:a.existing.result,attribution:a.existing.attribution,baseline:a.existing.baseline,graphMeasured:i.graphMetricsEnabled}),s=o.lowered.length>0||o.removed.length>0||o.caps.length>0,c=[];s&&!r&&(writeHealthBaseline(t,o.baseline),c.push(uu));for(let e of describePlan(o))n.text(e);n.json({status:s?`tightened`:`nothing-to-tighten`,dryRun:r,wrote:c,lowered:o.lowered,removed:o.removed,caps:o.caps,reference:a.referenceFields.reference})}});function normalizeModulePath(e){let t=e.replace(/\\/g,`/`);for(;t.startsWith(`./`);)t=t.slice(2);for(;t.length>1&&t.endsWith(`/`);)t=t.slice(0,-1);return t}function createFsProbe(e){return t=>{let n=w.join(e,t);return o(n)?b(n).isDirectory()?`dir`:`file`:`missing`}}const defaultFsProbe=e=>createFsProbe(process.cwd())(e);function buildModuleReports(e,t){let{graphMetricsEnabled:n,graphModules:r,fanOutEdges:i,fanInEdges:a,fanInExempt:o=[],fanOutExempt:s=[],isExcluded:c,moduleCeilings:l,probe:u=defaultFsProbe}=t,d=new Map(o.map(e=>[e.module,e.reason])),f=new Map(s.map(e=>[e.module,e.reason]));return e.map(e=>{let t=normalizeModulePath(e);if(!n||r===void 0)return{module:t,status:`graph-unavailable`};if(r.has(t)){let e={module:t,status:`measured`,fanOut:(i?.get(t)??[]).toSorted(),fanIn:(a?.get(t)??[]).toSorted()},n={},r=l?.fanInOutliers?.[t];r!==void 0&&(n.fanInOutliers=r);let o=l?.fanOutOutliers?.[t];o!==void 0&&(n.fanOutOutliers=o),Object.keys(n).length>0&&(e.ceilings=n);let s={},c=d.get(t);c!==void 0&&(s.fanInOutliers=c);let u=f.get(t);return u!==void 0&&(s.fanOutOutliers=u),Object.keys(s).length>0&&(e.exempt=s),e}return c(t)?{module:t,status:`excluded`}:u(t)===`missing`?{module:t,status:`missing`}:{module:t,status:`unmeasured`}})}const fu={excluded:`excluded by health.exclude`,unmeasured:`not in the graph -- outside health.src, an extension health.extensions does not cover, reachable only through type-only imports, or a directory (graph modules are files)`,missing:`no such file`,"graph-unavailable":`graph metrics unavailable this run`};function edgeSection(e,t,n,r){let i=[` ${n===void 0?`${e} (${String(t.length)}):`:`${e} (${String(t.length)}, ceiling ${String(n)}):`}`];if(t.length===0)i.push(` (none)`);else for(let e of t)i.push(` ${e}`);return r!==void 0&&i.push(` exempt: ${r}`),i}function formatModuleReports(e){let t=[];for(let n of e)t.push(``,`module ${n.module}`),n.status===`measured`?t.push(...edgeSection(`fan-out`,n.fanOut??[],n.ceilings?.fanOutOutliers,n.exempt?.fanOutOutliers),...edgeSection(`fan-in`,n.fanIn??[],n.ceilings?.fanInOutliers,n.exempt?.fanInOutliers)):t.push(` ${fu[n.status]}`);return t.join(`
|
|
6125
|
-
`)}function readCoverageNote(e){let t=w.join(e,`coverage-baseline.json`);if(o(t))try{let e=parseBaseline(p(t,`utf-8`)).totals;return`coverage (baseline): lines ${e.lines.toFixed(1)}% | branches ${e.branches.toFixed(1)}% | functions ${e.functions.toFixed(1)}%`}catch{return}}function readModuleCeilings(e){let t=w.join(e,`health-baseline.json`);if(o(t))try{return parseHealthBaseline(p(t,`utf-8`)).moduleCeilings}catch{return}}const
|
|
6129
|
+
`)[0]??``}function measureBaseOutliers(e){let t=e.collect??collectDetails;try{return withMergeBaseCheckout(e.executor,e.targetDir,e.mergeBase,n=>{let r=w.join(n,e.prefix),i=buildCollectConfig(e.config,{tsConfig:o(w.join(r,`tsconfig.json`))?`tsconfig.json`:void 0}),a=t(createRealHealthExecutor(r),i),s=a.unresolvedFirstParty;return s!==void 0&&s.length>0?unavailable(`the base cruise could not resolve ${String(s.length)} first-party imports`):e.config.graphMetricsEnabled&&a.circularDependencies===void 0?unavailable(`the base cruise produced no graph metrics`):{status:`measured`,ceilings:ceilingsFromDetails(a)}})}catch(e){return unavailable(k(e))}}function byteLength(e){try{let t=b(e);return t.isFile()?t.size:void 0}catch{return}}function measurerChanged(e,t){let n=[...e.files,`package.json`],r=F(n,{dot:!0});return t.some(e=>r(e))}function measureSizeBudgets(e,t,n){let r=[];for(let[i,a]of Object.entries(t).toSorted(([e],[t])=>e.localeCompare(t)))r.push(measureOne(e,i,a,n));return r}function measureOne(e,t,n,r){if(`file`in n){let r=byteLength(w.join(e,n.file));return r===void 0?{id:t,unmeasured:`no file at ${n.file}`}:{id:t,measured:r}}if(`glob`in n){let r=[];for(let t of c(n.glob,{cwd:e})){let n=byteLength(w.join(e,t));n!==void 0&&r.push(n)}if(r.length===0)return{id:t,unmeasured:`glob ${n.glob} matched no files`};let i=0,a=0;for(let e of r)i+=e,e>a&&(a=e);return{id:t,measured:n.aggregate===`largest`?a:i}}let i=r.executor.exec(`pnpm`,[`run`,`--silent`,n.script],{cwd:e});if(i.exitCode!==0)return{id:t,unmeasured:`script ${n.script} exited ${String(i.exitCode)}`};let a=readMeasureMarker(i.stdout);return a===void 0?{id:t,unmeasured:`script ${n.script} printed no measure marker`}:measurerChanged(n,r.changedNames)?{id:t,measured:a,measurerChanged:!0}:{id:t,measured:a}}const Fu=`health-baseline.json`;function readTargetReference(e,t,n){let r=detectHealthContext(t),i=readReference(e,{cwd:t,stack:r.stack,isMonorepo:r.isMonorepo,ciEvent:processCiEventSource()});return i.kind===`read`&&i.warning!==void 0&&n.notice(i.warning),i}function reportCarriedRaises(e,t){e.length!==0&&(t.text(formatCarriedRaises(e)),t.text(formatWarnMarker(e.length)))}function assessRaises(e,t,n,r){let i=readTargetReference(e,t,r);if(i.kind===`unavailable`)throw new T(i.reason);let a=i.reference;return a.baseline===void 0?(r.notice(`${Fu} has no counterpart on the default branch yet, so there is nothing to raise against.`),{fields:{reference:{status:`no-baseline`,mergeBase:a.mergeBase},raises:[]},prefix:a.prefix}):{fields:{reference:{status:`read`,mergeBase:a.mergeBase},raises:findRaises(a,n)},prefix:a.prefix}}function attributeRun(e){let{result:t,executor:n,targetDir:r,fields:i,prefix:a,config:o}=e;if(!needsBaseMeasurement(t))return attributeOutliers(t.uncoveredOutliers,{status:`not-needed`});let s=i.reference.mergeBase,c=measureBaseOutliers({executor:n,targetDir:r,mergeBase:s,prefix:a,config:o}),l=c.status===`measured`?{status:`measured`,mergeBase:s,ceilings:c.ceilings}:{status:`unavailable`,mergeBase:s,reason:c.reason};return attributeOutliers(t.uncoveredOutliers,l)}function changedPathsForMeasurers(e,t,n,r,i){return Object.values(n).some(e=>`script`in e)?branchDiffNames(e,t,r).filter(e=>e.startsWith(i)).map(e=>e.slice(i.length)).filter(e=>e!==``):[]}function refuseUnresolvedImports(e){let t=e.unresolvedFirstParty;if(t!==void 0&&t.length>0)throw new T(formatUnresolvedFirstParty(t))}function refuseEmptyScope(e,t,n,r){let{warnings:i,emptyScope:a}=formatSourceDiagnosis(e.sources,t.graphMetricsEnabled);for(let e of i)r.notice(e);if(a!==void 0&&n!==!1)throw new T(a);a!==void 0&&r.notice(a)}function measureHealth(e,t,n,r={}){let i=createRealHealthExecutor(e),a=collectDetails(i,buildCollectConfig(t,{tsConfig:o(w.join(e,`tsconfig.json`))?`tsconfig.json`:void 0})),s=metricsFromDetails(a),c=ceilingsFromDetails(a);refuseUnresolvedImports(a),refuseEmptyScope(a,t,r.failOnEmptySrc,n);let l=w.join(e,Fu),u=o(l)?parseHealthBaseline(p(l,`utf-8`)):void 0,d=assessRaises(i,e,{baseline:u,health:t,measured:{metrics:s,ceilings:c}},n),f=measureSizeBudgets(e,t.sizeBudgets,{executor:i,changedNames:changedPathsForMeasurers(i,e,t.sizeBudgets,d.fields.reference.mergeBase,d.prefix)});if(u===void 0)return{executor:i,details:a,current:s,ceilings:c,sizes:f,baselinePath:l,referenceFields:d.fields,prefix:d.prefix,existing:void 0};let m=compareMetrics(u,s,t.tolerance,c,f),h=attributeRun({result:m,executor:i,targetDir:e,fields:d.fields,prefix:d.prefix,config:t});return{executor:i,details:a,current:s,ceilings:c,sizes:f,baselinePath:l,referenceFields:d.fields,prefix:d.prefix,existing:{baseline:u,result:m,attribution:h}}}function wasMeasured(e,t,n){return e===`crowdedDirectories`?n.directories.has(t):n.graphModules?.has(t)??!0}function exemptionWasMeasured(e,t,n){let r=e===`crowdedDirectories`?n.directories:n.graphModules;if(r===void 0)return!0;let i=exemptKeyMatcher(t);return[...r].some(i)}function findStaleEntries(e,t,n){let r=[];for(let n of z){let i=e.moduleCeilings?.[n];if(i!==void 0)for(let[e,a]of Object.entries(i))wasMeasured(n,e,t)||r.push({kind:`ceiling`,metric:n,path:e,count:a})}for(let e of rt)for(let i of Object.keys(n[e]??{}))exemptionWasMeasured(e,i,t)||r.push({kind:`exemption`,metric:e,path:i});return r}function assessSwitchOff(e,t,n,r){let i=readTargetReference(e,t,r);if(i.kind===`unavailable`)return;let a=i.reference;if(!a.health.enabled||a.baseline===void 0)return;let s=w.join(t,Fu),c=o(s)?parseHealthBaseline(p(s,`utf-8`)):void 0,l=healthOverridesAt(t),u={...n};for(let e of Co)l?.[e]===void 0&&(u[e]=a.health[e]);return{reference:{status:`read`,mergeBase:a.mergeBase},raises:findRaises(a,{baseline:c,health:u})}}function sizeValuesToRecord(e,t,n){let r={...e?.sizeBudgets};for(let e of t)e.measured!==void 0&&(n||r[e.id]===void 0)&&(r[e.id]=e.measured);return Object.keys(r).length>0?r:void 0}function handleMissingBaseline(e,t,n){let{targetDir:r,config:i,details:a,current:o,ceilings:s,sizes:c,out:l}=e;if(t===!0){if(i.graphMetricsEnabled&&a.circularDependencies===void 0){l.notice(`Skipped baseline creation: graph metrics are unavailable this run. Fix the cruise before creating ${Fu}.`),l.json({status:`graph-unavailable`,...e.referenceFields,metrics:o,sources:a.sources}),reportCarriedRaises(e.referenceFields.raises,l),process.exitCode=1;return}writeHealthBaseline(r,{...o,moduleCeilings:s,sizeBudgets:sizeValuesToRecord(void 0,c,!1)}),l.notice(`Created ${Fu} (no prior baseline).`),l.json({status:`baseline-created`,...e.referenceFields,metrics:o,sources:a.sources}),reportCarriedRaises(e.referenceFields.raises,l);return}let u=`${Fu} not found. Run with --update-baseline to create one from the current run.`;if(n===!1)l.notice(u),l.json({status:`missing-baseline`,...e.referenceFields,metrics:o,sources:a.sources}),reportCarriedRaises(e.referenceFields.raises,l);else throw reportCarriedRaises(e.referenceFields.raises,l),new T(u)}function adoptUnrecorded(e,t,n,r){let i={...e};for(let e of R){let t=n[e];i[e]===void 0&&t!==void 0&&(i[e]=t)}return t.moduleCeilings===void 0&&(i.moduleCeilings=r),i}function applyBaselineUpdate(e,t,n){let{targetDir:r,config:i,details:a,current:o,ceilings:s,sizes:c,out:l}=e,{baseline:u,result:d,attribution:f}=t;if(i.graphMetricsEnabled&&a.circularDependencies===void 0)l.notice(`Skipped baseline update: graph metrics are unavailable this run. Fix the cruise before updating.`),process.exitCode=1;else if(n===!0)writeHealthBaseline(r,{...o,moduleCeilings:s,sizeBudgets:sizeValuesToRecord(u,c,!0)}),l.notice(`Reset ${Fu} to the current run.`);else if(isFlatOrBetter(u,o,s,c)){let e=baselineUpdateRefusal(f);if(e!==null)l.notice(e);else{let e=planHealthTighten({comparison:d,attribution:f,baseline:u,graphMeasured:i.graphMetricsEnabled});writeHealthBaseline(r,{...adoptUnrecorded(e.baseline,u,o,s),sizeBudgets:sizeValuesToRecord(e.baseline,c,!1)}),l.notice(`Updated ${Fu} (no regressions).`)}}else l.notice(`Skipped baseline update: a metric or ceiling regressed. Fix the regression before updating.`)}function collectRegressions(e,t){let n={};for(let r of e.metrics)r.pass||(n[r.key]=offenderEntries(t,r.key));return n}const Iu=j({meta:{name:`health:check`,description:`Compare codebase-health metrics against health-baseline.json. Does nothing unless .tooling.json#health.enabled is true.`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Project directory (default: current directory)`,required:!1},"update-baseline":{type:`boolean`,description:`If no metric regressed, rewrite health-baseline.json`},reset:{type:`boolean`,description:`With --update-baseline, rewrite health-baseline.json unconditionally, even when a metric regressed. For adopting a baseline after a deliberate measurement change, such as health.crossPackage changing what the cruise resolves. Still refused when graph metrics are enabled and this run measured no graph.`},"fail-on-missing-baseline":{type:`boolean`,default:!0,description:`Fail when no baseline exists (default). --no-fail-on-missing-baseline downgrades it to a notice.`},"fail-on-empty-src":{type:`boolean`,default:!0,description:`Fail when the configured health.src scope measured no source files (default). --no-fail-on-empty-src downgrades it to a notice.`},json:{type:`boolean`,description:"Emit one JSON document: status (compared | disabled | baseline-created | missing-baseline | graph-unavailable). disabled carries reference and raises only when the default branch has health enabled -- switching it off is a raise -- and nothing otherwise. Every other status carries reference ({status (read | no-baseline), mergeBase}) and raises ([{leaf, reference, current}]: every way this branch's two health files are higher than the default branch's, which it carries with its own code and a person merges). baseline-created, missing-baseline and graph-unavailable carry metrics ({crowdedDirectories, circularDependencies?, fanInOutliers?, fanOutOutliers?}) and sources. compared carries pass (false when newOutliers holds an entry, even with every count flat), tolerance, metrics (a list: [{key (crowdedDirectories | circularDependencies | fanInOutliers | fanOutOutliers), baseline?, current?, delta?, pass}]), ceilings ([{key (fanInOutliers | fanOutOutliers | crowdedDirectories), module, baseline, current, pass}]), sizeBudgets ([{id, ceiling?, measured?, pass, reason?}] -- every budget .tooling.json#health.sizeBudgets declares; reason is `unrecorded` for a declared budget with no recorded value, or the measurer's own explanation when it measured nothing), outlierBase ({status (measured | not-needed | unavailable), mergeBase?, reason?}), newOutliers ([{key, module, current}], outliers not on the merge base; empty unless measured), baseOutliers ([{key, module, base, current}]) and unattributedOutliers ([{key, module, current}], every outlier with no ceiling when the base was not measured), graphMetricsEnabled, graphMetricsMissing, slack ([{kind (count | ceiling | dead-ceiling | uncapped | size), leaf, recorded?, measured?}] -- every recorded value sitting above what this run measured, in the leaf spelling the failure lines print; information only, never a finding and never the verdict), staleEntries ([{kind (ceiling | exemption), metric, path, count?}]), regressions ({<failing metric key>: [{module, count} | {from, to}]}) and sources. sources is {entries ([{pattern, roots, status (resolved | unmatched | unrepresentable)}]), roots, fileCount}."}},run({args:e}){let t=w.resolve(e.dir??`.`),n=createCliOutput(e.json===!0),r=resolveHealthConfig(t);if(!r.enabled){n.notice(`health: disabled (set .tooling.json#health.enabled to true to enable).`);let e=assessSwitchOff(createRealHealthExecutor(t),t,r,n);n.json({status:`disabled`,...e}),reportCarriedRaises(e?.raises??[],n);return}r.graphMetricsEnabled||n.notice(`health: graph metrics disabled (no JS/TS source to cruise) -- crowdedDirectories only.`);let i=measureHealth(t,r,n,{failOnEmptySrc:e[`fail-on-empty-src`]}),a={targetDir:t,config:r,details:i.details,current:i.current,ceilings:i.ceilings,sizes:i.sizes,out:n,referenceFields:i.referenceFields},o=i.existing;if(o===void 0){handleMissingBaseline(a,e[`update-baseline`],e[`fail-on-missing-baseline`]);return}let{baseline:s,result:c,attribution:l}=o;n.text(formatCompareDiff(c,i.details,l));let u=findSlack({comparison:c,attribution:l,baseline:s,graphMeasured:!(r.graphMetricsEnabled&&i.details.circularDependencies===void 0)});for(let e of formatSlack(u))n.text(e);reportCarriedRaises(i.referenceFields.raises,n);let d=collectRegressions(c,i.details),f=formatGraphUnavailable(s,i.details,r.graphMetricsEnabled,i.details.graphDiagnostic);f!==void 0&&n.notice(f);let p=findStaleEntries(s,i.details,r.exempt);for(let e of formatStaleEntries(p))n.notice(e);let m=c.pass&&l.newOutliers.length===0;n.json({status:`compared`,...i.referenceFields,pass:m,tolerance:c.tolerance,metrics:c.metrics,ceilings:c.ceilings,sizeBudgets:c.sizeResults,outlierBase:l.outlierBase,newOutliers:l.newOutliers,baseOutliers:l.baseOutliers,unattributedOutliers:l.unattributedOutliers,graphMetricsEnabled:r.graphMetricsEnabled,graphMetricsMissing:f!==void 0,slack:u,staleEntries:p,regressions:d,sources:i.details.sources}),e[`update-baseline`]===!0&&applyBaselineUpdate(a,o,e.reset),m&&f===void 0||(process.exitCode=1)}}),Lu=P.json(),Ru=`.tooling.json`;function collectExemptPairs(e){let t=collectFlagValues(e,`--exempt`),n=collectFlagValues(e,`--reason`);if(t.length===0&&n.length>0)throw new T(`health:raise: ${String(n.length)} --reason given with no --exempt to explain.`);if(n.length<t.length)throw new T(`health:raise: ${String(t.length)} --exempt given with only ${String(n.length)} --reason. Every exemption owes its own reason: it is the line a later reader judges.`);return t.map((e,t)=>({leaf:e,reason:n[t]??``}))}function readToolingFile(e){let t=w.join(e,Ru);if(!o(t))return;let n=p(t,`utf-8`),r;try{r=JSON.parse(n)}catch(e){let t=e instanceof Error?e.message:`unknown error`;throw new T(`health:raise: ${Ru} is not JSON: ${t}. Fix the file and re-run.`)}let i=Lu.safeParse(r);if(!i.success)throw new T(`health:raise: ${Ru} is not JSON: ${i.error.message}`);return i.data}function describePlan$1(e){let t=[];for(let n of e.ceilings){let e=n.headline===void 0?``:`, ${n.key} set to ${String(n.headline)}`;t.push(`health-baseline: ${n.key} ${n.module} ceiling ${String(n.value)}${e}`)}for(let n of e.sizes)t.push(`health-baseline: size budget ${n.id} widened to ${String(n.value)}`);for(let n of e.exemptions)t.push(`${Ru}: health.exempt.${n.key}.${n.path} exempted -- ${n.reason}`);for(let n of e.notes)t.push(`health: ${n}`);return t}const zu=j({meta:{name:`health:raise`,description:`Widen the health budgets this branch crossed, by measurement: no number is an argument. Writes health-baseline.json (a new outlier's ceiling plus its headline count, a grown module ceiling, a grown size budget) and, for --exempt pairs, .tooling.json#health.exempt. Does nothing unless .tooling.json#health.enabled is true.`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Project directory (default: current directory)`,required:!1},"dry-run":{type:`boolean`,description:`Print what would be written and write nothing`},exempt:{type:`string`,description:`Exempt this leaf instead of recording a ceiling (repeatable), as "health:check" printed it: "fan-in: src/a.ts"`},reason:{type:`string`,description:`Why this exemption is justified (repeatable; one per --exempt)`},json:{type:`boolean`,description:`Emit one JSON document: status (raised | nothing-to-raise | disabled), dryRun, wrote ([path]), ceilings ([{key, module, value, headline?}]), sizeBudgets ([{id, value}]), exemptions ([{key, path, reason}]), notes ([string]), reference ({status (read | no-baseline), mergeBase}).`}},run({args:e,rawArgs:t}){let n=w.resolve(e.dir??`.`),r=createCliOutput(e.json===!0),i=resolveHealthConfig(n);if(!i.enabled){r.notice(`health: disabled (set .tooling.json#health.enabled to true to enable).`),r.json({status:`disabled`,dryRun:e[`dry-run`]===!0});return}let a=measureHealth(n,i,r);if(a.existing===void 0)throw new T(`health:raise: no health-baseline.json to widen. Run "health:check --update-baseline" first: a raise widens a recorded number, and there is nothing recorded.`);let o=planHealthRaise({comparison:a.existing.result,attribution:a.existing.attribution,baseline:a.existing.baseline,config:i,tooling:readToolingFile(n),exemptions:collectExemptPairs(t)}),s=e[`dry-run`]===!0,c=s?[]:writePlan(n,o);for(let e of describePlan$1(o))r.text(e);r.json({status:planHasWrites(o)?`raised`:`nothing-to-raise`,dryRun:s,wrote:c,ceilings:o.ceilings,sizeBudgets:o.sizes,exemptions:o.exemptions,notes:o.notes,reference:a.referenceFields.reference})}});function writePlan(e,t){let n=[];if((t.ceilings.length>0||t.sizes.length>0)&&(writeHealthBaseline(e,t.baseline),n.push(`health-baseline.json`)),t.tooling!==void 0){let r=healthFileFormatter(e);C(w.join(e,Ru),r(Ru,JSON.stringify(t.tooling,null,2))),n.push(Ru)}return n}const Bu=`health-baseline.json`;function describePlan(e){let t=[];for(let n of e.lowered)t.push(`health-baseline: ${n.leaf} ${String(n.from)} -> ${String(n.to)}`);for(let n of e.removed)t.push(`health-baseline: ${n.key}: ${n.module} ceiling ${String(n.value)} removed`);for(let n of e.caps)t.push(`health-baseline: ${n.key}: ${n.module} capped at ${String(n.value)}`);return t}const Vu=j({meta:{name:`health:tighten`,description:`Shed the slack this branch's own measurement proved the baseline holds, by measurement: no number is an argument. Rewrites health-baseline.json with each recorded count and module ceiling lowered to what the run measured, dead ceilings removed, and current outliers capped; it never touches .tooling.json. Does nothing unless .tooling.json#health.enabled is true.`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Project directory (default: current directory)`,required:!1},"dry-run":{type:`boolean`,description:`Print what would be written and write nothing`},json:{type:`boolean`,description:`Emit one JSON document: status (tightened | nothing-to-tighten | disabled | graph-unavailable), dryRun, wrote ([path]), lowered ([{leaf, from, to}]), removed ([{key, module, value}]), caps ([{key, module, value}]), reference ({status (read | no-baseline), mergeBase}). disabled and graph-unavailable carry no writes.`}},run({args:e}){let t=w.resolve(e.dir??`.`),n=createCliOutput(e.json===!0),r=e[`dry-run`]===!0,i=resolveHealthConfig(t);if(!i.enabled){n.notice(`health: disabled (set .tooling.json#health.enabled to true to enable).`),n.json({status:`disabled`,dryRun:r});return}let a=measureHealth(t,i,n);if(a.existing===void 0)throw new T(`health:tighten: no ${Bu} to lower. Run "health:check --update-baseline" first: a tighten lowers a recorded number, and there is nothing recorded.`);if(i.graphMetricsEnabled&&a.details.circularDependencies===void 0){n.notice(`Skipped: graph metrics are unavailable this run. Fix the cruise before tightening ${Bu}.`),n.json({status:`graph-unavailable`,dryRun:r,wrote:[]}),process.exitCode=1;return}let o=planHealthTighten({comparison:a.existing.result,attribution:a.existing.attribution,baseline:a.existing.baseline,graphMeasured:i.graphMetricsEnabled}),s=o.lowered.length>0||o.removed.length>0||o.caps.length>0,c=[];s&&!r&&(writeHealthBaseline(t,o.baseline),c.push(Bu));for(let e of describePlan(o))n.text(e);n.json({status:s?`tightened`:`nothing-to-tighten`,dryRun:r,wrote:c,lowered:o.lowered,removed:o.removed,caps:o.caps,reference:a.referenceFields.reference})}});function normalizeModulePath(e){let t=e.replace(/\\/g,`/`);for(;t.startsWith(`./`);)t=t.slice(2);for(;t.length>1&&t.endsWith(`/`);)t=t.slice(0,-1);return t}function createFsProbe(e){return t=>{let n=w.join(e,t);return o(n)?b(n).isDirectory()?`dir`:`file`:`missing`}}const defaultFsProbe=e=>createFsProbe(process.cwd())(e);function buildModuleReports(e,t){let{graphMetricsEnabled:n,graphModules:r,fanOutEdges:i,fanInEdges:a,fanInExempt:o=[],fanOutExempt:s=[],isExcluded:c,moduleCeilings:l,probe:u=defaultFsProbe}=t,d=new Map(o.map(e=>[e.module,e.reason])),f=new Map(s.map(e=>[e.module,e.reason]));return e.map(e=>{let t=normalizeModulePath(e);if(!n||r===void 0)return{module:t,status:`graph-unavailable`};if(r.has(t)){let e={module:t,status:`measured`,fanOut:(i?.get(t)??[]).toSorted(),fanIn:(a?.get(t)??[]).toSorted()},n={},r=l?.fanInOutliers?.[t];r!==void 0&&(n.fanInOutliers=r);let o=l?.fanOutOutliers?.[t];o!==void 0&&(n.fanOutOutliers=o),Object.keys(n).length>0&&(e.ceilings=n);let s={},c=d.get(t);c!==void 0&&(s.fanInOutliers=c);let u=f.get(t);return u!==void 0&&(s.fanOutOutliers=u),Object.keys(s).length>0&&(e.exempt=s),e}return c(t)?{module:t,status:`excluded`}:u(t)===`missing`?{module:t,status:`missing`}:{module:t,status:`unmeasured`}})}const Hu={excluded:`excluded by health.exclude`,unmeasured:`not in the graph -- outside health.src, an extension health.extensions does not cover, reachable only through type-only imports, or a directory (graph modules are files)`,missing:`no such file`,"graph-unavailable":`graph metrics unavailable this run`};function edgeSection(e,t,n,r){let i=[` ${n===void 0?`${e} (${String(t.length)}):`:`${e} (${String(t.length)}, ceiling ${String(n)}):`}`];if(t.length===0)i.push(` (none)`);else for(let e of t)i.push(` ${e}`);return r!==void 0&&i.push(` exempt: ${r}`),i}function formatModuleReports(e){let t=[];for(let n of e)t.push(``,`module ${n.module}`),n.status===`measured`?t.push(...edgeSection(`fan-out`,n.fanOut??[],n.ceilings?.fanOutOutliers,n.exempt?.fanOutOutliers),...edgeSection(`fan-in`,n.fanIn??[],n.ceilings?.fanInOutliers,n.exempt?.fanInOutliers)):t.push(` ${Hu[n.status]}`);return t.join(`
|
|
6130
|
+
`)}function readCoverageNote(e){let t=w.join(e,`coverage-baseline.json`);if(o(t))try{let e=parseBaseline(p(t,`utf-8`)).totals;return`coverage (baseline): lines ${e.lines.toFixed(1)}% | branches ${e.branches.toFixed(1)}% | functions ${e.functions.toFixed(1)}%`}catch{return}}function readModuleCeilings(e){let t=w.join(e,`health-baseline.json`);if(o(t))try{return parseHealthBaseline(p(t,`utf-8`)).moduleCeilings}catch{return}}const Uu=j({meta:{name:`health:summary`,description:`Print current codebase-health metrics (and coverage context)`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Project directory (default: current directory)`,required:!1},json:{type:`boolean`,description:`Emit one JSON document: crowdedDirectories, circularDependencies?, fanInOutliers?, fanOutOutliers?, sources ({entries, roots, fileCount}), linesOfCode?, graphMetricsEnabled, graphMetricsMissing. The four metrics are counts; with --explain they are offender lists instead (fanInOutliers as [{module, count, lines?}], crowdedDirectories and fanOutOutliers as [{module, count}], circularDependencies as [{from, to}]), joined by crowdedExempt?, fanInExempt? and fanOutExempt? ([{module, count, reason}]), linesOfCodeByDirectory? ([{module, count}]), unresolvedFirstParty? ([{importer, specifier}], the first-party imports this run's cruise could not resolve) and, with --module, modules ([{module, status, fanOut?, fanIn?, ceilings?, exempt?}]). When health is disabled the document is only enabled (false).`},explain:{type:`boolean`,description:`List the offending files/modules behind each metric`},module:{type:`string`,description:`Print fan-out/fan-in edges for this module (repeatable; requires --explain)`}},run({args:e,rawArgs:t}){let n=createCliOutput(e.json===!0),r=collectFlagValues(t,`--module`).map(normalizeModulePath);if(r.length>0&&e.explain!==!0)throw new T(`--module requires --explain`);let i=w.resolve(e.dir??`.`),a=resolveHealthConfig(i);if(!a.enabled){n.json({enabled:!1}),n.text(`health: disabled (set .tooling.json#health.enabled to true to enable).`);return}let s=collectDetails(createRealHealthExecutor(i),buildCollectConfig(a,{tsConfig:o(w.join(i,`tsconfig.json`))?`tsconfig.json`:void 0}));s.unresolvedFirstParty!==void 0&&s.unresolvedFirstParty.length>0&&n.notice(formatUnresolvedFirstParty(s.unresolvedFirstParty));let{warnings:c,emptyScope:l}=formatSourceDiagnosis(s.sources,a.graphMetricsEnabled);for(let e of c)n.notice(e);l!==void 0&&n.notice(l);let u=formatGraphUnavailableForSummary(s,a.graphMetricsEnabled,s.graphDiagnostic);u!==void 0&&n.notice(u);let d;if(r.length>0&&(d=buildModuleReports(r,{graphMetricsEnabled:a.graphMetricsEnabled,graphModules:s.graphModules,fanOutEdges:s.fanOutEdges,fanInEdges:s.fanInEdges,fanInExempt:s.fanInExempt,fanOutExempt:s.fanOutExempt,isExcluded:createExcludeMatcher(a.exclude),moduleCeilings:readModuleCeilings(i),probe:createFsProbe(i)})),e.json===!0){let{sourceLinesByModule:t,rawLinesByModule:r,fanOutEdges:i,fanInEdges:o,graphModules:c,directories:l,graphDiagnostic:f,...p}=s;n.json({...e.explain===!0?{...p,...d===void 0?{}:{modules:d}}:{...metricsFromDetails(s),sources:s.sources},...observationsFromDetails(s),graphMetricsEnabled:a.graphMetricsEnabled,graphMetricsMissing:u!==void 0});return}let f=metricsFromDetails(s);n.text(formatMetricsSummary({...f,...observationsFromDetails(s),coverageNote:readCoverageNote(i)})),a.graphMetricsEnabled||n.text(` graph metrics: disabled (no JS/TS source to cruise)`),e.explain===!0&&(n.text(``),n.text(formatExplain(s))),d!==void 0&&n.text(formatModuleReports(d))}}),Wu=`health-history.jsonl`;function appendHealthRecord(e,t,n){return appendRecord(e,{...t,historyFile:Wu,scope:`health`},n)}function readHealthRecords(e,t){return readRecordsGeneric(e,{...t,historyFile:Wu},parseHealthHistoryLine)}const Gu=j({meta:{name:`health:record`,description:`Append the current codebase health metrics to the orphan-branch history`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Project directory (default: current directory)`,required:!1},json:{type:`boolean`,description:`Emit one JSON document: status (recorded | disabled | skipped-empty-scope). recorded adds branch, sha, commitSha, bootstrapped, attempts, record, sources. disabled adds reason and means health history is switched off in .tooling.json. skipped-empty-scope adds branch, sha, sources, and records nothing because health.src matched no source files.`}},run({args:e}){let t=createCliOutput(e.json===!0),n=w.resolve(e.dir??`.`),r=resolveHealthConfig(n);if(!r.historyEnabled){t.text(`health: history disabled (.tooling.json: health.history === 'none' or health.enabled === false). Skipping record.`),t.json({status:`disabled`,reason:r.enabled?`health.history === 'none'`:`health.enabled is not true (history needs the gate)`});return}refuseForgeDefaultMismatch(readConfiguredDefaultBranch(n),processCiEventSource(),`health:record`);let i=createRealHealthExecutor(n),a=i.exec(`git`,[`rev-parse`,`HEAD`],{cwd:n});if(a.exitCode!==0)throw new T(`Failed to resolve HEAD sha: ${a.stderr.trim()}`);let s=a.stdout.trim(),c=collectDetails(i,buildCollectConfig(r,{tsConfig:o(w.join(n,`tsconfig.json`))?`tsconfig.json`:void 0})),{warnings:l,emptyScope:u}=formatSourceDiagnosis(c.sources,r.graphMetricsEnabled);for(let e of l)t.notice(e);if(u!==void 0){t.notice(u),t.notice(`Skipping record: ${r.historyBranch} would gain a permanent false-zero entry.`),t.json({status:`skipped-empty-scope`,branch:r.historyBranch,sha:s,sources:c.sources});return}let d={...metricsFromDetails(c),...observationsFromDetails(c),sha:s,timestamp:(/* @__PURE__ */ new Date()).toISOString()};t.text(`Appending health record for ${s.slice(0,7)} to ${r.historyBranch}...`);let f=appendHealthRecord(i,{cwd:n,historyBranch:r.historyBranch,authorName:`health-bot`,authorEmail:`health-bot@noreply.localhost`},d);t.text(`${f.bootstrapped?`Bootstrapped`:`Appended to`} ${r.historyBranch}: commit ${f.commitSha.slice(0,7)}${f.attempts>1?` (after ${String(f.attempts)} attempts)`:``}.`),t.json({status:`recorded`,branch:r.historyBranch,sha:s,commitSha:f.commitSha,bootstrapped:f.bootstrapped,attempts:f.attempts,record:d,sources:c.sources})}}),Ku=j({meta:{name:`health:status`,description:`Show recent codebase health history (read-only; fetches from the orphan branch)`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Project directory (default: current directory)`,required:!1},limit:{type:`string`,description:`Number of trailing records to render (default: 10)`},json:{type:`boolean`,description:`Emit one JSON document: records ([{sha, timestamp, crowdedDirectories, circularDependencies?, fanInOutliers?, fanOutOutliers?, linesOfCode?}]). records is empty when no history is recorded yet.`}},run({args:e}){let t=createCliOutput(e.json===!0),n=w.resolve(e.dir??`.`),r=resolveHealthConfig(n),i=e.limit?Math.max(1,Number.parseInt(e.limit,10)||10):10,a=readHealthRecords(createRealHealthExecutor(n),{cwd:n,historyBranch:r.historyBranch});if(a.length===0){t.json({records:[]}),t.text(`health: no history recorded yet.`);return}let o=a.slice(-i);t.json({records:o}),t.text(formatStatus(o))}}),qu=P.object({chars:tolerantBlock(B).optional(),ascii:tolerantBlock(B).optional()}),Ju=[`docs/**/retired/**`,`**/CHANGELOG.md`,`.claude/hooks/bst-hook.mjs`,`.claude/hooks/bst-hook-guide.md`];function parseCharsConfig(e,t){let n=parseToolingConfigSlice(e,qu,{block:`chars`,path:t}),r=n?.chars??n?.ascii;return{exclude:[.../* @__PURE__ */ new Set([...Ju,...r?.exclude??[]])],deny:r?.deny??[],allow:r?.allow??[],treatAsProse:r?.treatAsProse??[]}}function resolveCharsConfig(e){let t=w.join(e,`.tooling.json`);return parseCharsConfig(o(t)?p(t,`utf-8`):void 0,w.relative(process.cwd(),t)||t)}function displayChar(e){return e.group===void 0?e.char:`<${e.codepoint}>`}function formatHitLine(e){let{hit:t,context:n,action:r}=e,{path:i,line:a,column:o,offender:s}=t,c=`${i}:${String(a)}:${String(o)} ${s.codepoint} ${s.name}`;if(r===`flag`){let t=e.reason??`no safe mechanical rewrite for this context`,r=e.suggestion===void 0?``:`; suggested: ${e.suggestion}`;return`${c} '${displayChar(s)}' [${n}] flagged: ${t}${r}`}let l=e.replacement??s.replacement??``,u=s.tier===2&&r===`flatten`?` (ambiguous)`:``;return`${c} '${displayChar(s)}' -> '${l}' [${n}/${r}]${u}`}function formatPlacementLine(e){let{path:t,line:n,column:r,codepoint:i,name:a,found:o,context:s,expected:c}=e;return`${`${t}:${String(n)}:${String(r)} ${i}${a===void 0?``:` ${a}`}`} '${o}' in ${s} is not decoded there; write '${c}'`}function formatReport$1(e,t=[]){return e.length===0&&t.length===0?`chars:check: no offenders found.`:[...e.map(formatHitLine),...t.map(formatPlacementLine)].join(`
|
|
6126
6131
|
`)}function toJsonReport(e,t=[]){return{status:e.length===0&&t.length===0?`clean`:`violations`,count:e.length,placementCount:t.length,placement:t,hits:e.map(e=>{let t=e.action===`flag`?{}:{replacement:e.replacement??e.hit.offender.replacement};return{path:e.hit.path,line:e.hit.line,column:e.hit.column,codepoint:e.hit.offender.codepoint,name:e.hit.offender.name,char:e.hit.offender.char,...t,tier:e.hit.offender.tier,ambiguous:e.hit.offender.tier===2,context:e.context,action:e.action,reason:e.reason,suggestion:e.suggestion}})}}function reportDecisions(e,t=[]){return{payload:toJsonReport(e,t),text:formatReport$1(e,t),exitCode:e.length+t.length===0?0:1}}function runCharsCheck(e,t,n,r,i=[]){let a=r.fix===!0&&r.dryRun!==!0,o=fixFiles(e,{offenders:t,exclude:n,fixAmbiguous:r.fixAmbiguous,treatAsProse:i,dryRun:!a}),s=o.flatMap(e=>e.decisions),c=o.flatMap(e=>e.placement);if(r.fix!==!0)return reportDecisions(s,c);let l=s.filter(e=>!e.applied);if(r.dryRun!==!0)return reportDecisions(l,c);let u=s.filter(e=>e.applied),d=u.length===0&&l.length===0&&c.length===0?0:1,f=[u.length===0?`chars:check --fix --dry-run: no fixable offenders found.`:`chars:check --fix --dry-run: would fix ${String(u.length)} offender(s):`,...u.map(formatHitLine)];return(l.length>0||c.length>0)&&f.push(`remaining (not fixed):`,...l.map(formatHitLine),...c.map(formatPlacementLine)),{payload:{dryRun:!0,plannedFixes:toJsonReport(u).hits,remaining:toJsonReport(l).hits,placementCount:c.length,placement:c},text:f.join(`
|
|
6127
|
-
`),exitCode:d}}const
|
|
6128
|
-
`)){let[,e]=n.split(` `);e?.startsWith(`refs/heads/`)&&t.push(e.slice(11))}return t}function closedPrWindowMs(e){return(e.mergedDays+14)*864e5}async function listPrunePulls(e,t,n,r,i){let a=!1,[o,s]=await Promise.all([listPulls(e,t,{state:`open`,signal:i,onPageCap:()=>{a=!0}}),listPulls(e,t,{state:`closed`,updatedSince:n,signal:i})]);if(a)throw new T(`Open PR listing on ${t.repository} hit its page cap; refusing to prune, since a missed open PR could delete its branch`);let c=[...o,...s],l=new Set(c.map(e=>e.number));return[...c,...r.filter(e=>!l.has(e.number))]}async function runBranchPrune(e,t,n,r){let i=
|
|
6132
|
+
`),exitCode:d}}const Yu={dir:{type:`positional`,valueHint:`dir`,description:`Project directory (default: current directory)`,required:!1},fix:{type:`boolean`,description:`Rewrite tier-1 offenders in place`},"fix-ambiguous":{type:`boolean`,description:`With --fix, also rewrite tier-2 offenders (e.g. em dash -> --)`},"dry-run":{type:`boolean`,description:`With --fix, print the planned edits without writing`},json:{type:`boolean`,description:`Emit one JSON document: status (clean | violations), count, hits ([{path, line, column, codepoint, name, char, replacement?, tier (1 | 2), ambiguous, context, action (flatten | escape | flag), reason?, suggestion?}]), placementCount, placement ([{path, line, column, rule (js-escape-in-markup | entity-in-js-string), context, found, codepoint, expected, name?}]). context is one of prose | comment | xml-comment | string | template | tagged-template | raw-string | text-block | regex | jsx-text | jsx-attribute | markup-text | markup-attribute | cdata | code | unclassified. With --fix --dry-run the document is instead dryRun (true), plannedFixes (hits), remaining (hits), placementCount, placement.`},verbose:{type:`boolean`,description:`Emit detailed debug logging`}};function runCharsCheckCli(e){let t=createCliOutput(e.json===!0),n=w.resolve(e.dir??`.`),r={verbose:e.verbose===!0||isEnvVerbose()},i=resolveCharsConfig(n),a=resolveOffenders(i);debug(r,`chars:check: ${String(a.length)} offender(s) in the effective deny-list`);let{payload:o,text:s,exitCode:c}=runCharsCheck(createRealFixExecutor(n),a,i.exclude,{fix:e.fix===!0,fixAmbiguous:e[`fix-ambiguous`]===!0,dryRun:e[`dry-run`]===!0},i.treatAsProse);t.json(o),s!==``&&t.text(s),process.exitCode=c}const Xu=j({meta:{name:`chars:check`,description:`Scan tracked text files for the characters this gate denies: LLM-tell punctuation (curly quotes, ellipsis, en and em dashes, arrows, box-drawing, status glyphs) and invisible or deceptive characters (bidi controls, zero-width and tag characters, odd spaces). Letters in any language pass -- an accented e, Persian, Hindi, an emoji sequence and CJK text are all fine. Each hit is reported with its context-correct fix: an escape in a string, an entity in markup, an ASCII lookalike in prose, or a flag naming why no mechanical rewrite is safe. Skipped on purpose: excluded globs (the built-in docs/**/retired/**, **/CHANGELOG.md and the generated bst-hook files, plus .tooling.json#chars.exclude), files .gitattributes marks binary, and files with a null byte in their first 8000 bytes. It also reports an escape (such as \\uXXXX or an entity) written where its context does not decode it; that report always exits 1 and is never auto-fixed. It runs in checks:run unless .tooling.json#chars.enabled is false, and always runs when invoked directly. To keep one character, add its code point to .tooling.json#chars.allow. To skip files, add globs to .tooling.json#chars.exclude. To skip one line, put the text chars-ignore-line on it, in any comment syntax.`},args:Yu,run({args:e}){runCharsCheckCli(e)}}),Zu=j({meta:{name:`ascii:check`,description:`Deprecated alias of chars:check`,hidden:!0},args:Yu,run({args:e}){createCliOutput(e.json===!0).text(`ascii:check is now chars:check; the old name works until 2026-12-15.`),runCharsCheckCli(e)}});P.object({content:P.string(),encoding:P.literal(`base64`)});function encodeRepoPath(e){let t=e.split(`/`);if(t.some(e=>e===``||e===`.`||e===`..`))throw new D(`Refusing a repository path with a relative segment: ${e}`);return t.map(encodeURIComponent).join(`/`)}const Qu=P.looseObject({name:P.string(),sha:P.string(),type:P.string()});P.array(Qu);const $u=P.looseObject({branchPrune:Jt.optional()});function readBranchPruneBlockFromDisk(e){let t=w.join(e,`.tooling.json`);if(!o(t))return;let n=p(t,`utf-8`),r=w.relative(process.cwd(),t)||t;return parseToolingConfigSlice(n,$u,{block:`branchPrune`,path:r})?.branchPrune}const ed=/* @__PURE__ */ new Set([`bst/coverage-metrics`,`bst/health-metrics`,`bst/egress-metrics`]),td=[`changeset-release/`,`renovate/`],nd=/^agent\/(?:repair|rebase|failover)-backup\/(.+)\/[0-9a-f]+$/;function parseBackupParent(e){return nd.exec(e)?.[1]??null}function keep(e,t){return{action:`keep`,entry:{branch:e,reason:t}}}function del(e){return{action:`delete`,entry:e}}function daysSince(e,t){return(t-Date.parse(e))/864e5}function pushedAfterMerge(e,t){if(e===null||t===null)return!1;let n=Date.parse(e),r=Date.parse(t);return Number.isNaN(n)||Number.isNaN(r)?!1:n>r+36e5}function hardNeverTouchReason(e,t){if(e===t)return`the default branch`;if(ed.has(e))return`orphan data branch (never merges to default)`;let n=td.find(t=>e.startsWith(t));return n===void 0?null:`matches built-in never-touch prefix "${n}"`}function resolveBranchPr(e,t){let n=t.get(e)??[],r=n.find(e=>e.state===`open`);if(r)return{status:`open`,pr:r};let i=n.filter(e=>e.mergedAt!==null).toSorted((e,t)=>Date.parse(t.mergedAt??``)-Date.parse(e.mergedAt??``))[0];if(i)return{status:`merged`,pr:i};let a=n.toSorted((e,t)=>t.number-e.number)[0];return a?{status:`closed-unmerged`,pr:a}:{status:`none`}}function classifyWorkBranch(e,t,n,r){let i=e.name,a=resolveBranchPr(i,t);if(a.status===`none`)return keep(i,`no PR found for this branch in the listing`);if(a.status===`open`)return keep(i,`open PR #${String(a.pr.number)}`);if(a.status===`closed-unmerged`)return keep(i,`PR #${String(a.pr.number)} closed without merging`);let o=`PR #${String(a.pr.number)}`;if(pushedAfterMerge(e.commitDate,a.pr.mergedAt))return keep(i,`has commits after ${o} merged`);let s=daysSince(a.pr.mergedAt??``,n);return s>=r.mergedDays?del({branch:i,reason:`${o} merged ${s.toFixed(1)}d ago (>= ${String(r.mergedDays)}d)`,prNumber:a.pr.number,mergedAt:a.pr.mergedAt??void 0}):keep(i,`${o} merged only ${s.toFixed(1)}d ago (< ${String(r.mergedDays)}d)`)}function backupAgeFallback(e,t,n,r,i){let a=e.name;if(e.commitDate===null)return keep(a,`${t}, and this ref's commit date is unknown`);let o=daysSince(e.commitDate,n);return o>=r.backupDays?del({branch:a,reason:`${t}, and this ref is ${o.toFixed(1)}d old (>= ${String(r.backupDays)}d)`,prNumber:i?.prNumber,mergedAt:i?.mergedAt}):keep(a,`${t}, and this ref is only ${o.toFixed(1)}d old (< ${String(r.backupDays)}d)`)}function classifyBackupRef(e,t,n,r,i){let a=e.name,o=resolveBranchPr(t,n);if(o.status===`open`)return keep(a,`parent branch ${t} has an open PR #${String(o.pr.number)}`);if(o.status===`merged`){if(pushedAfterMerge(e.commitDate,o.pr.mergedAt)&&daysSince(o.pr.mergedAt??``,r)>=i.mergedDays)return backupAgeFallback(e,`parent branch ${t}'s PR #${String(o.pr.number)} merged before this ref's last commit`,r,i,{prNumber:o.pr.number,mergedAt:o.pr.mergedAt??void 0});let n=daysSince(o.pr.mergedAt??``,r),s=`parent branch ${t}'s PR #${String(o.pr.number)}`;return n>=i.mergedDays?del({branch:a,reason:`${s} merged ${n.toFixed(1)}d ago (>= ${String(i.mergedDays)}d)`,prNumber:o.pr.number,mergedAt:o.pr.mergedAt??void 0}):keep(a,`${s} merged only ${n.toFixed(1)}d ago (< ${String(i.mergedDays)}d)`)}return backupAgeFallback(e,`parent branch ${t} has no merged PR`,r,i)}function classifyBranch(e,t,n,r,i){let a=hardNeverTouchReason(e.name,i.defaultBranch);if(a!==null)return keep(e.name,a);if(e.protected)return keep(e.name,`protected on the forge`);if(n(e.name))return keep(e.name,`matches a config-added exclusion`);let o=parseBackupParent(e.name);return o===null?classifyWorkBranch(e,t,r,i):classifyBackupRef(e,o,t,r,i)}function selectBranchesToPrune(e,t,n,r){let i=/* @__PURE__ */ new Map;for(let e of t){if(e.headRepo===null||e.headRepo.toLowerCase()!==r.repository.toLowerCase())continue;let t=i.get(e.headRef);t?t.push(e):i.set(e.headRef,[e])}let a=F([...r.exclude]),o=[],s=[];for(let t of e){let e=classifyBranch(t,i,a,n,r);e.action===`delete`?o.push(e.entry):s.push(e.entry)}let c=o.length>50,l=c?o.slice(0,50):o,u=c?o.slice(50).map(e=>({branch:e.branch,reason:`per-run deletion cap (50) reached`})):[];return{delete:l,keep:[...s,...u],truncated:c}}const rd=P.object({name:P.string(),protected:P.boolean().optional(),commit:P.object({id:P.string().optional(),timestamp:P.string().optional()}).optional()});async function listBranches(e,t,n={}){let r=n.signal,i=n.maxPages??20,a=[];for(let n=1;n<=i;n++){r?.throwIfAborted();let i=new URLSearchParams({limit:`50`,page:String(n)}),o=await e.fetch(`${repoBase(t)}/branches?${i.toString()}`,{headers:authHeaders(t),signal:r});o.ok||await throwForgejoFailure(o,{verb:`list branches`,resource:t.repository});let s=rd.array().safeParse(await o.json());if(!s.success)throw new D(`Unexpected branch list response: ${s.error.message}`);if(s.data.length===0)return{branches:a,truncated:!1};for(let e of s.data)a.push({name:e.name,protected:e.protected??!1,commitSha:e.commit?.id??null,commitDate:e.commit?.timestamp??null})}return{branches:a,truncated:!0}}const id={403:`forbidden`,423:`locked`,404:`not-found`},ad=P.object({message:P.string()});async function refusalMessage(e){let t=await responseBodyText(e);try{let e=ad.safeParse(JSON.parse(t));if(e.success)return e.data.message}catch{}return t}async function deleteBranch(e,t,n){let r=await e.fetch(`${repoBase(t)}/branches/${encodeRepoPath(n)}`,{method:`DELETE`,headers:authHeaders(t)});if(r.ok)return{ok:!0};let i=id[r.status];return i===void 0?throwForgejoFailure(r,{verb:`delete branch`,resource:`${t.repository}/${n}`}):{ok:!1,reason:i,status:r.status,message:await refusalMessage(r)}}function parseLsRemoteHeadNames(e){let t=[];for(let n of e.split(`
|
|
6133
|
+
`)){let[,e]=n.split(` `);e?.startsWith(`refs/heads/`)&&t.push(e.slice(11))}return t}function closedPrWindowMs(e){return(e.mergedDays+14)*864e5}async function listPrunePulls(e,t,n,r,i){let a=!1,[o,s]=await Promise.all([listPulls(e,t,{state:`open`,signal:i,onPageCap:()=>{a=!0}}),listPulls(e,t,{state:`closed`,updatedSince:n,signal:i})]);if(a)throw new T(`Open PR listing on ${t.repository} hit its page cap; refusing to prune, since a missed open PR could delete its branch`);let c=[...o,...s],l=new Set(c.map(e=>e.number));return[...c,...r.filter(e=>!l.has(e.number))]}async function runBranchPrune(e,t,n,r){let i=I.child({repo:t.repository}),a=buildGitAuth(t),o=r.signal??null,s=await e.execStream(`git`,[...a.args,`ls-remote`,`--heads`,a.url],{timeoutMs:Ts,signal:o});if(s.exitCode!==0)throw new T(`git ls-remote --heads failed: ${s.stderr||s.stdout}`);let c=parseLsRemoteHeadNames(s.stdout),l={defaultBranch:r.defaultBranch,mergedDays:r.mergedDays??7,backupDays:r.backupDays??30,exclude:r.exclude,repository:t.repository},[u,d]=await Promise.all([listPrunePulls(e,t,n-closedPrWindowMs(l),r.knownClosedPulls??[],o),listBranches(e,t,{signal:o??void 0,maxPages:20})]);d.truncated&&i.warn(`Branch listing on ${t.repository} hit the 20-page cap without an empty page; results may be truncated`);let f=new Map(d.branches.map(e=>[e.name,e])),p=selectBranchesToPrune(c.map(e=>{let t=f.get(e);return{name:e,protected:t?.protected??!1,commitDate:t?.commitDate??null}}),u,n,l);p.truncated&&i.warn(`branch:prune: per-run deletion cap (50) reached -- some eligible branches were deferred to the next run rather than deleted in one pass`);let m=[],h=[];if(!r.dryRun&&p.delete.length>0)for(let n of p.delete){let r=await deleteOneBranch(e,t,n,i);r.ok?m.push(r.branch):h.push({branch:r.branch,error:r.error})}return{selection:p,deleted:m,failed:h}}async function deleteOneBranch(e,t,n,r){let i=n.prNumber===void 0?``:` (PR #${String(n.prNumber)}${n.mergedAt?`, merged ${n.mergedAt}`:``})`,a;try{let o=await deleteBranch(e,t,n.branch);if(o.ok)return r.info(`branch:prune: deleted ${n.branch}${i} -- ${n.reason}`),{ok:!0,branch:n.branch};a=`${o.reason} (${String(o.status)})${o.message===``?``:`: ${o.message}`}`}catch(e){a=k(e)}return r.warn(`branch:prune: failed to delete ${n.branch}${i}: ${a}`),{ok:!1,branch:n.branch,error:a}}function parseDaysFlag(e,t){let n=Number(t);if(!Number.isInteger(n)||n<0)throw new T(`--${e} must be a non-negative integer, got "${t}"`);return n}const od=j({meta:{name:`branch:prune`,description:`Reclaim merged work branches and stale agent repair/rebase/failover backup refs from the forge (Forgejo only). It never deletes the default branch, changeset-release/*, renovate/*, bst/coverage-metrics, bst/health-metrics, bst/egress-metrics, a protected branch, or a branch with an open PR. .tooling.json#branchPrune.exclude only adds to that list. It deletes at most 50 branches per run.`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Project directory (default: current directory)`,required:!1},"dry-run":{type:`boolean`,description:`Print the delete/keep plan with reasons; delete nothing`},json:{type:`boolean`,description:`Emit one JSON document: selection ({delete ([{branch, reason, prNumber?, mergedAt?}]), keep ([{branch, reason}]), truncated}), deleted (branch names), failed ([{branch, error}]).`},"merged-days":{type:`string`,description:`Days after a work branch's PR merged before deleting it; also applies to a backup ref whose parent branch's PR merged (default 7)`},"backup-days":{type:`string`,description:`Days before deleting a backup ref whose parent has no merged PR to key on (default 30)`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:e}){let t=w.resolve(e.dir??`.`),n=resolveConnection(t);if(n.type!==`forgejo`)throw new T(`branch:prune requires a Forgejo repository`);let r=loadToolingConfig(t),i=readBranchPruneBlockFromDisk(t),a=createRealExecutor$1(),o=resolveDefaultBranch({cwd:t,configOverride:r?.defaultBranch}),s=e[`merged-days`]?parseDaysFlag(`merged-days`,e[`merged-days`]):void 0,c=e[`backup-days`]?parseDaysFlag(`backup-days`,e[`backup-days`]):void 0,l=await getRepoFullName(a,n.conn),u=await runBranchPrune(a,{...n.conn,repository:l},Date.now(),{defaultBranch:o,mergedDays:s??i?.mergedDays??7,backupDays:c??i?.backupDays??30,exclude:i?.exclude??[],dryRun:e[`dry-run`]===!0});if(e.json===!0){createCliOutput(!0).json(u);return}let d=e.verbose===!0||isEnvVerbose();if(e[`dry-run`]===!0){I.info(`branch:prune --dry-run: would delete ${String(u.selection.delete.length)} branch(es)`);for(let e of u.selection.delete)I.info(` delete ${e.branch} -- ${e.reason}`);if(d)for(let e of u.selection.keep)I.info(` keep ${e.branch} -- ${e.reason}`)}else I.info(`branch:prune: deleted ${String(u.deleted.length)} branch(es)`),u.failed.length>0&&I.warn(`branch:prune: ${String(u.failed.length)} deletion(s) failed`)}}),sd=/^[A-Z][0-9]+$/,cd=/^R[0-9]*$/,ld=/^C[0-9]*$/;function pathCountFor(e){return cd.test(e)||ld.test(e)||sd.test(e)?2:1}function singlePathStatus(e){return e===`A`||e===`M`||e===`D`||e===`T`?e:null}function normalizeRecord(e,t){let[n,r]=t;if(cd.test(e))return n===void 0||r===void 0?[]:[{status:`D`,path:n},{status:`A`,path:r}];if(ld.test(e))return r===void 0?[]:[{status:`A`,path:r}];let i=singlePathStatus(e);return i===null||n===void 0?[]:[{status:i,path:n}]}function parseNameStatus(e){let t=e.split(`\0`);for(;t.length>0&&t.at(-1)===``;)t.pop();let n=[],r=0;for(;r<t.length;){let e=t[r]??``,i=t.slice(r+1,r+1+pathCountFor(e));r+=1+i.length,n.push(...normalizeRecord(e,i))}return n}function planDiffArgs(e){return[`diff`,`--name-status`,`-z`,`${e}...HEAD`]}const ud=/(?<![a-zA-Z0-9_])(?:issue|pr)-[1-9][0-9]*(?![0-9])/;function markerFor(e){return RegExp(`(?<![a-zA-Z0-9_])${e.kind}-${String(e.number)}(?![0-9])`)}function matchMarkerPaths(e,t){if(t===null)return e.filter(e=>e.startsWith(`docs/`)&&ud.test(e));let n=t.map(markerFor);return e.filter(e=>e.startsWith(`docs/`)&&n.some(t=>t.test(e)))}function isPlanPath(e){let t=classifyConventionalDoc(e);return t!==null&&t.kind!==`spec`}function livePlanPaths(e){return e.filter(e=>isPlanPath(e)&&!classifyConventionalDoc(e)?.retired)}function modifiedLivePlans(e){let t=[];for(let n of e)n.status===`M`&&isPlanPath(n.path)&&!classifyConventionalDoc(n.path)?.retired&&t.push(n.path);return t}function addedPlans(e){let t=[],n=[];for(let r of e){if(r.status!==`A`)continue;let e=classifyConventionalDoc(r.path);e!==null&&e.kind!==`spec`&&(e.retired?n.push(r.path):t.push(r.path))}return{live:t,retired:n}}function touchedLivePlans(e){let t=[];for(let n of e)n.status!==`D`&&isPlanPath(n.path)&&!classifyConventionalDoc(n.path)?.retired&&t.push(n.path);return t}function locatePlan(e){let{entries:t,trackedPaths:n,refs:r,isOpen:i}=e,[a]=matchMarkerPaths(r===null?touchedLivePlans(t):livePlanPaths(n),r);if(a!==void 0)return{kind:`found`,path:a};let o=addedPlans(t),[s,c]=o.live;if(s!==void 0&&c===void 0)return{kind:`found`,path:s};if(s!==void 0&&c!==void 0)return{kind:`ambiguous`,candidates:o.live};if(o.retired.length>0)return{kind:`none`};let l=modifiedLivePlans(t).filter(i),[u,d]=l;return u!==void 0&&d===void 0?{kind:`found`,path:u}:u!==void 0&&d!==void 0?{kind:`ambiguous`,candidates:l}:{kind:`none`}}function claimsPartialDelivery(e){let t=statusOf(e);return t!==void 0&&wa.test(t)}function statusOf(e){let t=e.split(`
|
|
6129
6134
|
`).slice(0,30).join(`
|
|
6130
|
-
`);return
|
|
6131
|
-
`);return new Set(relativeLinks(a,t).map(e=>e.target))}function collectPlanLinks(e,t){let n=[];for(let r of t){let t=listDocs(e,r.active,r.activePattern).map(e=>({file:e,isRetired:!1})),i=r.retiredDirs.flatMap(t=>listDocs(e,t)).map(e=>({file:e,isRetired:!0}));for(let{file:r,isRetired:a}of[...t,...i]){let t=e.readFile(r);if(t===void 0)continue;let i=implementsLinkTargets(t,w.posix.dirname(r));n.push({file:r,isRetired:a,targets:i})}}return n}function collectSpecRetirementViolations(e,t,n,r){let i=t.filter(e=>w.posix.basename(e.active)===`specs`),a=t.filter(e=>w.posix.basename(e.active)===`plans`);if(i.length===0||a.length===0)return[];let o=collectPlanLinks(e,a),s=[];for(let t of i){let i=r.strict===!0||t.enforced;for(let r of listDocs(e,t.active,t.activePattern)){let t=o.filter(e=>e.targets.has(r));if(t.length===0||!t.every(e=>e.isRetired))continue;let a=e.readFile(r);if(a!==void 0&&claimsPartialDelivery(a))continue;let c={file:r,rule:`R6 spec-not-retired`,message:`Implementing plan(s) have landed but this spec is still active: ${t.map(e=>e.file).join(`, `)}.`,fix:'If those plans completed this spec, retire it too: `pnpm exec bst docs:retire <spec> --status <verb> --shipped "<text>"`. If further phases are still planned, leave it open -- that is why it stays active.'};s.push({...c,severity:severityOf(c,i,n.staleEnforced)})}}return s}function collectPlanLocateViolations(e){let t=e.branchNameStatus();if(t===void 0)return[];let n=touchedLivePlans(t);if(n.length===0)return[];let r=locatePlan({entries:t,trackedPaths:[],refs:null,isOpen:t=>{let n=e.readFile(t);return n!==void 0&&countOutstandingBoxes(n)>0}}),i=[];r.kind===`none`?i.push(...n.map(e=>({file:e,message:`The execute lookup finds no plan for this branch: ${e} was touched but not added, its name carries no issue-/pr- marker, and either it has no outstanding task or the branch added a retired plan beside it, which the execute lookup works instead.`}))):r.kind===`ambiguous`&&i.push(...r.candidates.map(e=>({file:e,message:`The execute lookup cannot choose a plan for this branch: ${String(r.candidates.length)} live plans carry no issue-/pr- marker.`})));let a=[];for(let e of i){let t={file:e.file,rule:`R9 plan-unlocatable`,message:e.message,fix:"If this branch works this plan, rename it with `git mv` to a name carrying `issue-<n>` or `pr-<n>`. If it only edits a plan another branch works, ignore this."};a.push({...t,severity:severityOf(t,!0,!0)})}return a}function collectViolations(e,t,n){let r=discoverPairs(e,t),i=[],a=0,o=0;for(let s of r){let r=checkPair(e,s,t,n);i.push(...r.violations),a+=r.active,o+=r.retired}i.push(...collectSpecRetirementViolations(e,r,t,n)),i.push(...collectPlanLocateViolations(e));let s=matchableActiveDirs(e,t),c=Array.isArray(t.enforced)?t.enforced.filter(e=>!s.includes(e)):[];return{violations:i,activeCount:a,retiredCount:o,pairCount:r.length,pass:!i.some(e=>e.severity===`fatal`),activeDirs:s,unmatchedEnforced:c}}const
|
|
6132
|
-
`)){let e=n.indexOf(`#`),r=(e===-1?n:n.slice(0,e)).trim().toLowerCase();
|
|
6135
|
+
`);return Ma.exec(t)?.[2]?.trim().replace(Fa,``)}function isTerminalStatus(e){return xa.test(e)&&!Ca.test(e)}function checkStatus(e,t){let{file:n,body:r,isRetired:i,retiredDir:a}=e,o=[],s=isTerminalStatus(t);return s&&!i&&o.push({file:n,rule:`R2 done-but-not-retired`,message:`Status says "${t}" but the doc is still in the active directory.`,fix:`Retire it: move to \`${a}/\` (see \`.agent/guides/plan-lifecycle.md\`).`}),!s&&i&&o.push({file:n,rule:`R2 retired-but-not-done`,message:`Doc lives in \`${a}/\` but its status ("${t}") doesn't say completed/shipped/superseded/rejected.`,fix:"Set `Status: **completed YYYY-MM-DD**` (or superseded/abandoned/rejected) -- or move it back to the active dir if it isn't actually done."}),i&&s&&!Sa.test(t)&&o.push({file:n,rule:`R3 undated-retirement`,message:`Retired doc's status ("${t}") has no YYYY-MM-DD date.`,fix:"Date it: `Status: **completed 2026-07-12**`."}),i&&s&&!Aa.test(r)&&o.push({file:n,rule:`R3 missing-retire-paragraph`,message:"Retired doc has no `Shipped:` / `Superseded:` / `Abandoned:` / `Rejected:` paragraph.",fix:`Add one after the Status line naming what landed and where the post-implementation truth now lives (CLAUDE.md, the source files, ...).`}),i&&s&&!hasHistoricalBanner(r)&&o.push({file:n,rule:`R8 missing-historical-banner`,message:`Retired doc has no historical banner saying it is not current state.`,fix:"Run `pnpm exec bst docs:delink` on the retired directory -- it inserts the banner and de-links source paths in one pass. Do not hand-write it: the wording is fixed so it stays greppable."}),o}function checkLinks(e){let t=w.posix.dirname(e.file),n=[];for(let r of relativeLinks(e.body,t))e.isRetired&&!resolvesInsideDocs(r.target)?n.push({file:e.file,rule:`R7 retired-source-link`,message:`Retired doc links out of \`docs/\` (\`${r.raw}\` -> ${r.target}). A file move elsewhere breaks it.`,fix:"Run `pnpm exec bst docs:delink` on the retired directory -- it converts the link to a plain code span. A retired doc records what was decided; it should not track where the code lives now."}):e.linkExists(r.target)||n.push({file:e.file,rule:`R4 broken-link`,message:`Relative link \`${r.raw}\` doesn't resolve (looked for ${r.target}).`,fix:"Fix the path -- a doc moved into `retired/` sits one level deeper, so each `../` needs one more `../`. If the link points at something the work deleted, it can never be re-pathed: de-link it (plain code span)."});return n}function checkDoc(e){let t=[],n=statusOf(e.body);return n===void 0?t.push({file:e.file,rule:`R1 status-missing`,message:"No `Status:` line in the first 30 lines.",fix:"Add one under the H1, e.g. `Status: **approved 2026-07-12**` (active) or `Status: **completed 2026-07-12**` (retired)."}):t.push(...checkStatus(e,n)),t.push(...checkLinks(e)),!e.isRetired&&e.staleDays>0&&e.ageDays!==void 0&&e.ageDays>e.staleDays&&t.push({file:e.file,rule:`R5 stale`,message:`Active doc, but its content hasn't changed in ${String(e.ageDays)} days (limit ${String(e.staleDays)}).`,fix:`Check it against the tree. If the work shipped, retire it. If it's still open, edit the doc to say where it stands -- that resets the clock.`}),t}function ageDays(e,t,n){let r=e.lastContentChangeISO(t);if(r===void 0)return;let i=new Date(r).getTime();if(!Number.isNaN(i))return Math.floor((n.getTime()-i)/864e5)}function severityOf(e,t,n){return e.rule.startsWith(`R7`)||e.rule.startsWith(`R9`)||!t||e.rule.startsWith(`R5`)&&!n?`advisory`:`fatal`}function checkPair(e,t,n,r){let i=r.strict===!0||t.enforced,linkExists=t=>e.exists(t),a=[],o=listDocs(e,t.active,t.activePattern),s=t.retiredDirs.flatMap(t=>listDocs(e,t));for(let[c,l]of[[o,!1],[s,!0]])for(let o of c){let s=e.readFile(o);if(s===void 0)continue;let c=checkDoc({file:o,body:s,isRetired:l,retiredDir:t.retired,linkExists,ageDays:l?void 0:ageDays(e,o,r.now),staleDays:n.staleDays});for(let e of c)a.push({...e,severity:severityOf(e,i,n.staleEnforced)})}return{violations:a,active:o.length,retired:s.length}}const dd=/^(?:(>[ \t]*)|[ \t]*)(?:\*\*)?Implements(?:\*\*)?:.*$/m,fd=/^(?:(>[ \t]*)|[ \t]*)(?:\*\*)?Spec(?:\*\*)?:.*$/m;function implementsLinkTargets(e,t){let n=stripCode(e),r=dd.exec(n)??fd.exec(n);if(r===null)return/* @__PURE__ */ new Set;let{lines:i}=continuationLines(n,r.index+r[0].length,r[1]!==void 0),a=[r[0],...i].join(`
|
|
6136
|
+
`);return new Set(relativeLinks(a,t).map(e=>e.target))}function collectPlanLinks(e,t){let n=[];for(let r of t){let t=listDocs(e,r.active,r.activePattern).map(e=>({file:e,isRetired:!1})),i=r.retiredDirs.flatMap(t=>listDocs(e,t)).map(e=>({file:e,isRetired:!0}));for(let{file:r,isRetired:a}of[...t,...i]){let t=e.readFile(r);if(t===void 0)continue;let i=implementsLinkTargets(t,w.posix.dirname(r));n.push({file:r,isRetired:a,targets:i})}}return n}function collectSpecRetirementViolations(e,t,n,r){let i=t.filter(e=>w.posix.basename(e.active)===`specs`),a=t.filter(e=>w.posix.basename(e.active)===`plans`);if(i.length===0||a.length===0)return[];let o=collectPlanLinks(e,a),s=[];for(let t of i){let i=r.strict===!0||t.enforced;for(let r of listDocs(e,t.active,t.activePattern)){let t=o.filter(e=>e.targets.has(r));if(t.length===0||!t.every(e=>e.isRetired))continue;let a=e.readFile(r);if(a!==void 0&&claimsPartialDelivery(a))continue;let c={file:r,rule:`R6 spec-not-retired`,message:`Implementing plan(s) have landed but this spec is still active: ${t.map(e=>e.file).join(`, `)}.`,fix:'If those plans completed this spec, retire it too: `pnpm exec bst docs:retire <spec> --status <verb> --shipped "<text>"`. If further phases are still planned, leave it open -- that is why it stays active.'};s.push({...c,severity:severityOf(c,i,n.staleEnforced)})}}return s}function collectPlanLocateViolations(e){let t=e.branchNameStatus();if(t===void 0)return[];let n=touchedLivePlans(t);if(n.length===0)return[];let r=locatePlan({entries:t,trackedPaths:[],refs:null,isOpen:t=>{let n=e.readFile(t);return n!==void 0&&countOutstandingBoxes(n)>0}}),i=[];r.kind===`none`?i.push(...n.map(e=>({file:e,message:`The execute lookup finds no plan for this branch: ${e} was touched but not added, its name carries no issue-/pr- marker, and either it has no outstanding task or the branch added a retired plan beside it, which the execute lookup works instead.`}))):r.kind===`ambiguous`&&i.push(...r.candidates.map(e=>({file:e,message:`The execute lookup cannot choose a plan for this branch: ${String(r.candidates.length)} live plans carry no issue-/pr- marker.`})));let a=[];for(let e of i){let t={file:e.file,rule:`R9 plan-unlocatable`,message:e.message,fix:"If this branch works this plan, rename it with `git mv` to a name carrying `issue-<n>` or `pr-<n>`. If it only edits a plan another branch works, ignore this."};a.push({...t,severity:severityOf(t,!0,!0)})}return a}function collectViolations(e,t,n){let r=discoverPairs(e,t),i=[],a=0,o=0;for(let s of r){let r=checkPair(e,s,t,n);i.push(...r.violations),a+=r.active,o+=r.retired}i.push(...collectSpecRetirementViolations(e,r,t,n)),i.push(...collectPlanLocateViolations(e));let s=matchableActiveDirs(e,t),c=Array.isArray(t.enforced)?t.enforced.filter(e=>!s.includes(e)):[];return{violations:i,activeCount:a,retiredCount:o,pairCount:r.length,pass:!i.some(e=>e.severity===`fatal`),activeDirs:s,unmatchedEnforced:c}}const pd=/^[0-9a-f]{40}$|^[0-9a-f]{64}$/;function parseIgnoreRevs(e){let t=/* @__PURE__ */ new Set;for(let n of e.split(`
|
|
6137
|
+
`)){let e=n.indexOf(`#`),r=(e===-1?n:n.slice(0,e)).trim().toLowerCase();pd.test(r)&&t.add(r)}return t}function parseStatusLine(e){for(let t of e.split(`
|
|
6133
6138
|
`)){if(t.trim()===``)continue;let e=t.split(` `),n=(e[0]??``).charAt(0),r=e[1]??``;if(n===``||r===``)return;let i=e[2];return n===`R`&&i!==void 0?{code:n,oldPath:r,newPath:i}:{code:n,oldPath:r,newPath:r}}}function parseFollowLog(e){let t=[];for(let n of e.split(``)){if(n.trim()===``)continue;let e=n.indexOf(`
|
|
6134
|
-
`),r=e===-1?n:n.slice(0,e),i=e===-1?``:n.slice(e+1),a=r.split(``),o=(a[0]??``).trim();if(o===``)continue;let s=(a[1]??``).trim(),c=s===``?[]:s.split(/\s+/),l=(a[2]??``).trim();t.push({commit:o,parents:c,authorDate:l,status:parseStatusLine(i)})}return t}function entryOutcome(e,t,n){if(n.parents.length>1)return{kind:`date`,date:n.authorDate};if(n.parents.length===0||n.status?.code===`A`)return t.shallow.has(n.commit)?{kind:`unknown`}:{kind:`date`,date:n.authorDate};if(t.ignore.has(n.commit))return{kind:`skip`};let r=n.status;if(r!==void 0&&(r.code===`M`||r.code===`R`)){let t=e.blobDiffStatus(n.commit,r.oldPath,r.newPath);return t===0?{kind:`skip`}:t===1?{kind:`date`,date:n.authorDate}:{kind:`unknown`}}return{kind:`date`,date:n.authorDate}}function lastContentChange(e,t,n){let r=4,i=0;for(;;){let a=e.log(t,r);if(a===void 0)return;let o=parseFollowLog(a);for(let t of o.slice(i)){let r=entryOutcome(e,n,t);if(r.kind===`date`)return r.date;if(r.kind===`unknown`)return}if(o.length<r)return;i=o.length,r*=8}}function gitOut$1(e,t){try{return
|
|
6139
|
+
`),r=e===-1?n:n.slice(0,e),i=e===-1?``:n.slice(e+1),a=r.split(``),o=(a[0]??``).trim();if(o===``)continue;let s=(a[1]??``).trim(),c=s===``?[]:s.split(/\s+/),l=(a[2]??``).trim();t.push({commit:o,parents:c,authorDate:l,status:parseStatusLine(i)})}return t}function entryOutcome(e,t,n){if(n.parents.length>1)return{kind:`date`,date:n.authorDate};if(n.parents.length===0||n.status?.code===`A`)return t.shallow.has(n.commit)?{kind:`unknown`}:{kind:`date`,date:n.authorDate};if(t.ignore.has(n.commit))return{kind:`skip`};let r=n.status;if(r!==void 0&&(r.code===`M`||r.code===`R`)){let t=e.blobDiffStatus(n.commit,r.oldPath,r.newPath);return t===0?{kind:`skip`}:t===1?{kind:`date`,date:n.authorDate}:{kind:`unknown`}}return{kind:`date`,date:n.authorDate}}function lastContentChange(e,t,n){let r=4,i=0;for(;;){let a=e.log(t,r);if(a===void 0)return;let o=parseFollowLog(a);for(let t of o.slice(i)){let r=entryOutcome(e,n,t);if(r.kind===`date`)return r.date;if(r.kind===`unknown`)return}if(o.length<r)return;i=o.length,r*=8}}function gitOut$1(e,t){try{return N(`git`,t,{cwd:e,encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`]})}catch{return}}function gitStatus(e,t){try{return N(`git`,t,{cwd:e,stdio:[`ignore`,`ignore`,`ignore`]}),0}catch(e){return e instanceof Error&&`status`in e&&typeof e.status==`number`?e.status:void 0}}function readShallowCommits(e){if(gitOut$1(e,[`rev-parse`,`--is-shallow-repository`])?.trim()!==`true`)return/* @__PURE__ */ new Set;let t=gitOut$1(e,[`rev-parse`,`--git-path`,`shallow`])?.trim();if(t===void 0||t===``)return/* @__PURE__ */ new Set;let n=w.isAbsolute(t)?t:w.resolve(e,t),r;try{r=p(n,`utf-8`)}catch{return/* @__PURE__ */ new Set}let i=/* @__PURE__ */ new Set;for(let e of r.split(`
|
|
6135
6140
|
`)){let t=e.trim();t!==``&&i.add(t)}return i}function buildContentAgeSource(e){let t=gitOut$1(e,[`rev-parse`,`--show-toplevel`])?.trim();if(t===void 0||t===``)return;let n=``;try{n=p(w.join(t,`.git-blame-ignore-revs`),`utf-8`)}catch{}return{git:{log:(t,n)=>gitOut$1(e,[`-c`,`core.quotePath=false`,`log`,`--follow`,`--max-count=${String(n)}`,`--format=%x1e%H%x1f%P%x1f%aI`,`--name-status`,`--`,t]),blobDiffStatus:(t,n,r)=>gitStatus(e,[`diff`,`--quiet`,`-w`,`--ignore-blank-lines`,`${t}^:${n}`,`${t}:${r}`])},context:{ignore:parseIgnoreRevs(n),shallow:readShallowCommits(e)}}}function resolveCommit$1(e,t){let n=gitOut$1(e,[`rev-parse`,`--verify`,`-q`,`${t}^{commit}`])?.trim();return n===void 0||n===``?void 0:n}function branchNameStatus(e){let t;try{t=readConfiguredDefaultBranch(e)}catch{return}let n=[`origin/${t}`,t].find(t=>resolveCommit$1(e,t)!==void 0);if(n===void 0)return;let r=gitOut$1(e,[`rev-parse`,`HEAD`])?.trim();if(gitOut$1(e,[`symbolic-ref`,`-q`,`--short`,`HEAD`])?.trim()===t||r===void 0||r===``||r===resolveCommit$1(e,n)||gitOut$1(e,[`merge-base`,n,`HEAD`])===void 0)return;let i=gitOut$1(e,planDiffArgs(n));return i===void 0?void 0:parseNameStatus(i)}function createRealDocsExecutor(e){let full=t=>w.join(e,...t.split(`/`)),t,n=!1;return{exists:e=>o(full(e)),readFile(e){try{return p(full(e),`utf-8`)}catch{return}},readDir(e){try{return h(full(e),{withFileTypes:!0}).map(e=>({name:e.name,isDirectory:e.isDirectory()}))}catch{return}},lastContentChangeISO(r){if(n||(n=!0,t=buildContentAgeSource(e)),t!==void 0)return lastContentChange(t.git,r,t.context)},branchNameStatus:()=>branchNameStatus(e)}}function group(e){let t=/* @__PURE__ */ new Map;for(let n of e){let e=t.get(n.file);e?e.push(n):t.set(n.file,[n])}let n=[];for(let e of[...t.keys()].toSorted()){n.push(` ${e}`);for(let r of t.get(e)??[])n.push(` [${r.rule}] ${r.message}`),n.push(` fix: ${r.fix}`);n.push(``)}return n}function formatReport(e){let t=e.violations.filter(e=>e.severity===`advisory`),n=e.violations.filter(e=>e.severity===`fatal`),r=[];if(e.unmatchedEnforced.length>0){let t=e.activeDirs.length>0?e.activeDirs.join(`, `):`(none discovered)`;r.push(`! docs: .tooling.json#docs.enforced names ${e.unmatchedEnforced.map(e=>`"${e}"`).join(`, `)} which match no discovered active dir -- that pair is still advisory, not enforced. Discovered active dirs: ${t}.`,``)}return t.length>0&&r.push(`! docs: ${String(t.length)} violation(s) -- reported, not enforced. Enforce a directory by naming it in .tooling.json#docs.enforced once it is clean.`,``,...group(t)),n.length===0?(r.push(t.length>0?`docs: 0 fatal, ${String(t.length)} advisory -- ${String(e.activeCount)} active, ${String(e.retiredCount)} retired doc(s). Nothing blocks the build; the advisories above are real drift.`:`docs OK -- ${String(e.activeCount)} active, ${String(e.retiredCount)} retired doc(s); statuses match their directories, retirements are dated, links resolve.`),r.join(`
|
|
6136
6141
|
`)):(r.push(`[x] docs: ${String(n.length)} violation(s).`,``,...group(n),"The plan-lifecycle guide (`.agent/guides/plan-lifecycle.md`) is the spec for all of this.",`Reminder: a doc's DIRECTORY is the source of truth for done-ness -- not its Status line, not its checkboxes.`),r.join(`
|
|
6137
|
-
`))}function runDocsCheck(e,t,n){let r={verbose:n.verbose??!1};if(!t.enabled)return debug(r,`docs: disabled via .tooling.json#docs: false`),{payload:{enabled:!1},text:``,exitCode:0,warnCount:0};let i=collectViolations(e,t,{now:n.now,strict:n.strict});debug(r,`docs: ${String(i.pairCount)} pair(s), ${String(i.violations.length)} violation(s)`);let a=i.violations.filter(e=>e.rule.startsWith(`R9`)).length;return i.pairCount===0?{payload:i,text:``,exitCode:0,warnCount:a}:{payload:i,text:formatReport(i),exitCode:+!i.pass,warnCount:a}}const
|
|
6138
|
-
`)}}const
|
|
6139
|
-
`&&n++;return n}function delinkLinks(e,t){let n=[],r=[];for(let i of relativeLinksWithOffsets(e,t)){if(resolvesInsideDocs(i.target))continue;let t=codeSpanFor(i.text,i.target);r.push({start:i.linkStart,end:i.linkEnd,text:t}),n.push({line:lineOf$1(e,i.linkStart),raw:i.raw,replacement:t})}let i=e;for(let e of r.toSorted((e,t)=>t.start-e.start))i=i.slice(0,e.start)+e.text+i.slice(e.end);return{content:i,edits:n}}function delinkDocument(e,t){let{content:n,edits:r}=delinkLinks(e,t);if(hasHistoricalBanner(n))return{content:n,linkEdits:r,bannerAdded:!1};let i=datedStatusValue(n);if(i===void 0)return{content:n,linkEdits:r,bannerAdded:!1,skipped:`no dated terminal Status: line -- fix the R2/R3 violation first, then re-run`};let a=matchStatusBlock(n);return a===void 0?{content:n,linkEdits:r,bannerAdded:!1,skipped:`no Status: line to anchor the banner to`}:{content:insertBlockAtBoundary(n,enclosingBlockEnd(n,a.blockEnd,a.quoted),formatHistoricalBanner(i)),linkEdits:r,bannerAdded:!0}}function isUnder(e,t){let n=t.endsWith(`/`)?t.slice(0,-1):t;return e.startsWith(`${n}/`)}function buildDelinkPlan(e,t){let n=[];for(let r of e.listMarkdownFiles()){if(!t.some(e=>isUnder(r,e)))continue;let i=e.readFile(r);if(i===void 0)continue;let a=delinkDocument(i,w.posix.dirname(r));(a.content!==i||a.skipped!==void 0)&&n.push({...a,file:r})}return{files:n}}function applyDelinkPlan(e,t){for(let n of t.files)n.content!==e.readFile(n.file)&&e.writeFile(n.file,n.content)}const
|
|
6140
|
-
`).map(e=>e.trim()).filter(e=>e!==``).toSorted()}let t=[];return walkMarkdownFiles(e,`.`,t),t.toSorted()},move(t,n){let r=full(t),i=full(n);if(u(w.dirname(i),{recursive:!0}),isInsideGitRepo(e)&&isTracked(t,e))
|
|
6142
|
+
`))}function runDocsCheck(e,t,n){let r={verbose:n.verbose??!1};if(!t.enabled)return debug(r,`docs: disabled via .tooling.json#docs: false`),{payload:{enabled:!1},text:``,exitCode:0,warnCount:0};let i=collectViolations(e,t,{now:n.now,strict:n.strict});debug(r,`docs: ${String(i.pairCount)} pair(s), ${String(i.violations.length)} violation(s)`);let a=i.violations.filter(e=>e.rule.startsWith(`R9`)).length;return i.pairCount===0?{payload:i,text:``,exitCode:0,warnCount:a}:{payload:i,text:formatReport(i),exitCode:+!i.pass,warnCount:a}}const md=j({meta:{name:`docs:check`,description:`Enforce the plan/spec lifecycle: a doc's directory is the source of truth for whether it is done. Checks that statuses agree with directories, retirements are dated and say where the truth went, relative links resolve, and active docs aren't stale. On a branch, it also warns (rule R9) when the branch works a plan that the execute lookup cannot find; that finding is always advisory. Findings are advisory (exit 0) unless the directory is in .tooling.json#docs.enforced (a list, or true for all) or --strict is passed; staleness stays advisory unless .tooling.json#docs.staleEnforced is set, and a link out of docs/ in a retired doc is always advisory. A retired doc should also carry the historical banner and have no links out of docs/; pnpm exec bst docs:delink fixes both. It CANNOT tell whether the code a plan describes actually shipped -- it verifies that a doc's metadata is self-consistent, not that it is true. Deciding a plan is done still means reading the source it names.`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Project directory (default: current directory)`,required:!1},strict:{type:`boolean`,description:`Treat every discovered pair as enforced, ignoring .tooling.json#docs.enforced (a retired doc's link out of docs/, rule R7, and an unlocatable plan, rule R9, stay advisory)`},json:{type:`boolean`,description:`Emit one JSON document: violations ([{file, rule, message, fix, severity (fatal | advisory)}]), activeCount, retiredCount, pairCount, pass, activeDirs, unmatchedEnforced. activeDirs lists every existing doc directory an enforced entry can match, holding docs or not; unmatchedEnforced the .tooling.json#docs.enforced entries that match none of them. When docs are disabled in .tooling.json the document is only enabled (false).`},verbose:{type:`boolean`,description:`Emit detailed debug logging`}},run({args:e}){let t=w.resolve(e.dir??`.`),n=createCliOutput(e.json===!0),{payload:r,text:i,exitCode:a,warnCount:o}=runDocsCheck(createRealDocsExecutor(t),resolveDocsConfig(t),{now:/* @__PURE__ */ new Date,strict:e.strict===!0,verbose:e.verbose===!0||isEnvVerbose()});n.json(r),i!==``&&n.text(i),o>0&&n.text(formatWarnMarker(o)),process.exitCode=a}}),hd=/(?<![\w./#-])#([0-9]+)(?![0-9A-Za-z_-])/g,gd=/\b(?:pull request|pr)\s+#?([0-9]+)\b/gi,_d=/\/(?:issues|pulls)\/([0-9]+)(?![0-9])/g;function forgeRefPattern(e){let t=e?.replace(/\/+$/,``);return t===void 0||t===``?_d:RegExp(`${escapeRegex(t)}/(?:issues|pulls)/([0-9]+)(?![0-9])`,`g`)}function titleOf(e){return/^# +(.*\S)[ \t]*$/m.exec(stripCode(e))?.[1]??null}function refsOf$1(e,t){let n=stripCode(e),r=/* @__PURE__ */ new Set;for(let e of[hd,gd,forgeRefPattern(t)]){e.lastIndex=0;for(let t of n.matchAll(e)){let e=(t[1]??t[0]).replaceAll(`#`,``),n=Number(e);Number.isSafeInteger(n)&&r.add(n)}}return[...r].toSorted((e,t)=>e-t)}function linksOf(e,t){let n=/* @__PURE__ */ new Set;for(let r of relativeLinks(e,t))resolvesInsideDocs(r.target)&&n.add(r.target);return[...n].toSorted()}function classOf(e){return e!==void 0&&wa.test(e)?`partial`:e!==void 0&&Ca.test(e)?`not-started`:`other`}function kindOf(e){return classifyConventionalDoc(e)?.kind??`configured`}function readOpenDoc(e,t,n){let r=e.readFile(t);if(r===void 0)return;let i=statusOf(r);return{path:t,kind:kindOf(t),title:titleOf(r),status:i??null,statusClass:classOf(i),lastChangedISO:e.lastContentChangeISO(t),refs:refsOf$1(r,n),links:linksOf(r,w.posix.dirname(t))}}function byPath(e,t){return e.path<t.path?-1:+(e.path>t.path)}function listOpenDocs(e,t,n={}){if(!t.enabled)return[];let r=[];for(let i of discoverPairs(e,t))for(let t of listDocs(e,i.active,i.activePattern)){let i=readOpenDoc(e,t,n.repoUrl);i!==void 0&&r.push(i)}return r.toSorted(byPath)}function dayOf(e){if(e===void 0)return`unknown`;let t=e.slice(0,10);return/^\d{4}-\d{2}-\d{2}$/.test(t)?t:`unknown`}function refsOf(e){return e.length===0?`-`:e.map(e=>`#${String(e)}`).join(`,`)}function runDocsList(e,t){let n=listOpenDocs(e,t),r=n.map(e=>`${e.path} ${e.statusClass} ${dayOf(e.lastChangedISO)} ${refsOf(e.refs)}`);return{payload:{ok:!0,docs:n},text:r.join(`
|
|
6143
|
+
`)}}const vd=j({meta:{name:`docs:list`,description:`List the active specs and plans -- exactly the docs docs:check counts as active -- with what can be read mechanically from each: kind, title, raw Status value and its class (not-started, partial, other), the date its content last changed, the issue and pull request numbers it names, and the docs it links to. Reports and never writes; a Status line is data here, never a filter. Docs on a branch other than the default branch are not catalogued.`},args:{dir:{type:`positional`,valueHint:`dir`,description:`Project directory (default: current directory)`,required:!1},json:{type:`boolean`,description:`Emit one JSON document: ok, docs ([{path, kind (spec | plan | legacy-plan | configured), title, status, statusClass (not-started | partial | other), lastChangedISO, refs, links}]).`},verbose:{type:`boolean`,description:`Emit detailed debug logging`}},run({args:e}){let t=w.resolve(e.dir??`.`),n=createCliOutput(e.json===!0),{payload:r,text:i}=runDocsList(createRealDocsExecutor(t),resolveDocsConfig(t));debug({verbose:e.verbose===!0||isEnvVerbose()},`docs:list: ${String(r.docs.length)} open doc(s)`),n.json(r),i!==``&&n.text(i)}});function textRestatesTarget(e,t){let n=e.replaceAll("`",``).trim();return n===``||n===t||n===w.posix.basename(t)||t.endsWith(`/${n}`)}function codeSpanFor(e,t){return textRestatesTarget(e,t)?`\`${t}\``:`\`${e.replaceAll("`",``).trim()}\` (\`${t}\`)`}function lineOf$1(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++)e[r]===`
|
|
6144
|
+
`&&n++;return n}function delinkLinks(e,t){let n=[],r=[];for(let i of relativeLinksWithOffsets(e,t)){if(resolvesInsideDocs(i.target))continue;let t=codeSpanFor(i.text,i.target);r.push({start:i.linkStart,end:i.linkEnd,text:t}),n.push({line:lineOf$1(e,i.linkStart),raw:i.raw,replacement:t})}let i=e;for(let e of r.toSorted((e,t)=>t.start-e.start))i=i.slice(0,e.start)+e.text+i.slice(e.end);return{content:i,edits:n}}function delinkDocument(e,t){let{content:n,edits:r}=delinkLinks(e,t);if(hasHistoricalBanner(n))return{content:n,linkEdits:r,bannerAdded:!1};let i=datedStatusValue(n);if(i===void 0)return{content:n,linkEdits:r,bannerAdded:!1,skipped:`no dated terminal Status: line -- fix the R2/R3 violation first, then re-run`};let a=matchStatusBlock(n);return a===void 0?{content:n,linkEdits:r,bannerAdded:!1,skipped:`no Status: line to anchor the banner to`}:{content:insertBlockAtBoundary(n,enclosingBlockEnd(n,a.blockEnd,a.quoted),formatHistoricalBanner(i)),linkEdits:r,bannerAdded:!0}}function isUnder(e,t){let n=t.endsWith(`/`)?t.slice(0,-1):t;return e.startsWith(`${n}/`)}function buildDelinkPlan(e,t){let n=[];for(let r of e.listMarkdownFiles()){if(!t.some(e=>isUnder(r,e)))continue;let i=e.readFile(r);if(i===void 0)continue;let a=delinkDocument(i,w.posix.dirname(r));(a.content!==i||a.skipped!==void 0)&&n.push({...a,file:r})}return{files:n}}function applyDelinkPlan(e,t){for(let n of t.files)n.content!==e.readFile(n.file)&&e.writeFile(n.file,n.content)}const yd=/* @__PURE__ */ new Set([`node_modules`,`dist`,`.tooling-archived`,`.git`]);function runGit$1(e,t){try{return N(`git`,e,{cwd:t,stdio:[`ignore`,`pipe`,`ignore`]}).toString(`utf-8`)}catch{return}}function isInsideGitRepo(e){return runGit$1([`rev-parse`,`--is-inside-work-tree`],e)?.trim()===`true`}function isTracked(e,t){return runGit$1([`ls-files`,`--error-unmatch`,e],t)!==void 0}function walkMarkdownFiles(e,t,n){let r=w.join(e,t),i;try{i=h(r,{withFileTypes:!0})}catch{return}for(let r of i)if(r.isDirectory()){if(yd.has(r.name))continue;walkMarkdownFiles(e,t===`.`?r.name:`${t}/${r.name}`,n)}else r.name.endsWith(`.md`)&&n.push(t===`.`?r.name:`${t}/${r.name}`)}function createRealRelocateExecutor(e){let full=t=>w.join(e,...t.split(`/`));return{exists:e=>o(full(e)),readFile(e){try{return p(full(e),`utf-8`)}catch{return}},writeFile(e,t){let n=full(e);u(w.dirname(n),{recursive:!0}),C(n,t,`utf-8`)},listMarkdownFiles(){if(isInsideGitRepo(e)){let t=runGit$1([`ls-files`,`*.md`],e);if(t!==void 0)return t.split(`
|
|
6145
|
+
`).map(e=>e.trim()).filter(e=>e!==``).toSorted()}let t=[];return walkMarkdownFiles(e,`.`,t),t.toSorted()},move(t,n){let r=full(t),i=full(n);if(u(w.dirname(i),{recursive:!0}),isInsideGitRepo(e)&&isTracked(t,e))N(`git`,[`mv`,t,n],{cwd:e,stdio:[`ignore`,`pipe`,`pipe`]});else try{v(r,i)}catch(e){if(typeof e==`object`&&e&&`code`in e&&e.code===`EXDEV`){a(r,i),S(r);return}throw e}}}}const bd=/* @__PURE__ */ new Set([`retired`,`completed`]);function assertRetiredDirs(e){if(e.length===0)throw new T(`docs:delink: at least one retired/ directory is required`);for(let t of e){let e=(t.endsWith(`/`)?t.slice(0,-1):t).split(`/`).at(-1);if(e===void 0||!bd.has(e))throw new T(`docs:delink: refusing to de-link an active directory: ${t}. Only a retired/ (or legacy completed/) directory can be de-linked -- an active doc's source links are live.`)}}function runDocsDelink(e,t,n){let r={verbose:n.verbose??!1};assertRetiredDirs(t);let i=buildDelinkPlan(e,t),a=i.files.reduce((e,t)=>e+t.linkEdits.length,0),o=i.files.filter(e=>e.bannerAdded).length,s=i.files.filter(e=>e.skipped!==void 0);debug(r,`docs:delink: ${String(i.files.length)} file(s), ${String(a)} link(s)`);let c={files:i.files.map(e=>({file:e.file,links:e.linkEdits.length,bannerAdded:e.bannerAdded,skipped:e.skipped})),linkCount:a,bannerCount:o,skippedCount:s.length,dryRun:n.dryRun===!0},l=[];for(let e of i.files){for(let t of e.linkEdits)l.push(` ${e.file}:${String(t.line)}: ${t.raw} -> ${t.replacement}`);e.bannerAdded&&l.push(` ${e.file}: + historical banner`),e.skipped!==void 0&&l.push(` ${e.file}: skipped -- ${e.skipped}`)}return i.files.length===0?(l.push(`docs:delink: nothing to do.`),{payload:c,text:l.join(`
|
|
6141
6146
|
`),exitCode:0}):(l.push(`docs:delink: ${String(a)} link(s) de-linked, ${String(o)} banner(s) added, ${String(s.length)} skipped.`),n.dryRun===!0?l.push(`docs:delink: dry run -- nothing written.`):(applyDelinkPlan(e,i),l.push(`docs:delink: done.`)),{payload:c,text:l.join(`
|
|
6142
|
-
`),exitCode:0})}const
|
|
6147
|
+
`),exitCode:0})}const xd=j({meta:{name:`docs:delink`,description:`Make retired docs inert: convert every markdown link that resolves outside docs/ into a plain code span, and insert the historical banner. Idempotent. It accepts only a retired/ (or legacy completed/) directory. pnpm exec bst docs:delink <retired-dir>...`},args:{"dry-run":{type:`boolean`,description:`Print the planned edits without writing`},json:{type:`boolean`,description:`Emit one JSON document: files ([{file, links, bannerAdded, skipped?}]), linkCount, bannerCount, skippedCount, dryRun. skipped is present only when the file was skipped.`},verbose:{type:`boolean`,description:`Emit detailed debug logging`}},run({args:e}){let t=createCliOutput(e.json===!0),{payload:n,text:r,exitCode:i}=runDocsDelink(createRealRelocateExecutor(process.cwd()),e._,{dryRun:e[`dry-run`]===!0,verbose:e.verbose===!0||isEnvVerbose()});t.json(n),r!==``&&t.text(r),process.exitCode=i}});function lineOf(e,t){let n=1;for(let r=0;r<t;r++)e[r]===`
|
|
6143
6148
|
`&&n++;return n}function encodeLinkPath(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}function rewriteBody(e,t){let{resolveDir:n,writeDir:r,moveMap:i,filePath:a,onlyMovedTargets:o}=t,s=relativeLinksWithOffsets(e,n),c=[],l=[];for(let t of s){if(t.raw.startsWith(`/`))continue;let n=i.get(t.target);if(o&&n===void 0)continue;let s=n??t.target,u=encodeLinkPath(w.posix.relative(r,s));u!==t.raw.slice(0,t.length)&&(l.push({index:t.index,length:t.length,text:u}),c.push({file:a,line:lineOf(e,t.index),oldTarget:t.target,newTarget:s}))}l.sort((e,t)=>t.index-e.index);let u=e;for(let e of l)u=u.slice(0,e.index)+e.text+u.slice(e.index+e.length);return c.sort((e,t)=>e.line-t.line),{content:u,edits:c}}function buildRelocatePlan(e,t){let n=/* @__PURE__ */ new Map,r=[];for(let{from:i,to:a}of t){if(n.has(i))throw new T(`docs:relocate: duplicate source ${i}`);if(n.set(i,a),e.exists(i)&&i!==a)r.push({from:i,to:a,status:`pending`});else if(e.exists(a))r.push({from:i,to:a,status:`already-done`});else throw new T(`docs:relocate: source not found: ${i}`)}let i=[];for(let t of r){let r=t.status===`pending`?t.from:t.to,a=e.readFile(r);if(a===void 0)throw new T(`docs:relocate: cannot read ${r}`);let{content:o,edits:s}=rewriteBody(a,{resolveDir:w.posix.dirname(r),writeDir:w.posix.dirname(t.to),moveMap:n,filePath:t.to,onlyMovedTargets:!1});s.length>0&&i.push({file:t.to,content:o,edits:s})}let a=new Set(r.flatMap(e=>[e.from,e.to]));for(let t of e.listMarkdownFiles()){if(a.has(t))continue;let r=e.readFile(t);if(r===void 0)continue;let o=w.posix.dirname(t),{content:s,edits:c}=rewriteBody(r,{resolveDir:o,writeDir:o,moveMap:n,filePath:t,onlyMovedTargets:!0});c.length>0&&i.push({file:t,content:s,edits:c})}let o=/* @__PURE__ */ new Set;for(let e of i){if(o.has(e.file))throw new T(`docs:relocate: internal error -- ${e.file} edited twice`);o.add(e.file)}return{moves:r,rewrites:i}}function applyRelocatePlan(e,t){for(let n of t.moves)n.status===`pending`&&e.move(n.from,n.to);for(let n of t.rewrites)e.writeFile(n.file,n.content)}function isExistingDirectory(e,t){return e.exists(t)&&e.readFile(t)===void 0}function resolveMoves(e,t,n){if(t.length===0)throw new T(`docs:relocate: at least one source is required`);for(let e of t)if(!e.endsWith(`.md`))throw new T(`docs:relocate: source must be a .md file: ${e}`);let r=n.endsWith(`/`)||isExistingDirectory(e,n);if(t.length>1&&!r)throw new T(`docs:relocate: multiple sources require an existing directory (or a trailing /) destination, got: ${n}`);if(!r){let[e]=t;if(e===void 0)throw new T(`docs:relocate: at least one source is required`);return[{from:e,to:w.posix.normalize(n)}]}let i=n.endsWith(`/`)?n.slice(0,-1):n;return t.map(e=>({from:e,to:`${i}/${w.posix.basename(e)}`}))}function runDocsRelocate(e,t,n,r){let i={verbose:r.verbose??!1},a=resolveMoves(e,t,n);for(let t of a)if(e.exists(t.from)&&e.exists(t.to))throw new T(`docs:relocate: refusing to overwrite existing destination: ${t.to}`);let o=buildRelocatePlan(e,a);debug(i,`docs:relocate: ${String(o.moves.length)} move(s), ${String(o.rewrites.length)} file(s) to rewrite`);let s={moves:o.moves.map(e=>({from:e.from,to:e.to,status:e.status})),rewrites:o.rewrites.map(e=>({file:e.file,edits:e.edits.map(e=>({line:e.line,oldTarget:e.oldTarget,newTarget:e.newTarget}))})),dryRun:r.dryRun===!0},c=[];for(let e of o.moves)c.push(e.status===`pending`?`move: ${e.from} -> ${e.to}`:`move: ${e.from} -> ${e.to} (already done)`);for(let e of o.rewrites)for(let t of e.edits)c.push(` ${t.file}:${String(t.line)}: ${t.oldTarget} -> ${t.newTarget}`);return r.dryRun===!0?c.push(`docs:relocate: dry run -- nothing written.`):(applyRelocatePlan(e,o),c.push(`docs:relocate: done.`)),{payload:s,text:c.join(`
|
|
6144
|
-
`),exitCode:0}}const
|
|
6145
|
-
`),exitCode:0}}const Yu=A({meta:{name:`docs:retire`,description:`Retire a plan/spec doc: move it to its retired/ location (computed by convention, or --dest), rewrite the markdown links that break as a result, set a dated terminal Status: line, and ensure the retire paragraph. After the lifecycle edits it also de-links links out of docs/ and adds the historical banner, as docs:delink does. pnpm exec bst docs:retire <plan.md> --status <verb> --shipped <text>.`},args:{status:{type:`string`,description:`Terminal verb: ${Fa.join(` | `)}`,required:!0},date:{type:`string`,description:`Retirement date, YYYY-MM-DD (defaults to the date of an existing terminal Status: line, else today, local time)`},shipped:{type:`string`,description:`Body of the retire paragraph (required unless one is already present)`},dest:{type:`string`,description:`Override the computed retired/ destination`},"dry-run":{type:`boolean`,description:`Print the planned move and edits without writing`},json:{type:`boolean`,description:`Emit one JSON document: verb, date, src, dest, move, lifecycle, rewrites, delink ({linkEdits, bannerAdded, skipped}), changed, dryRun. changed is false when the run writes nothing.`},verbose:{type:`boolean`,description:`Emit detailed debug logging`}},run({args:e}){let t=createCliOutput(e.json===!0),[n]=e._;if(n===void 0)throw new T(`Usage: pnpm exec bst docs:retire <plan.md> --status <verb> --shipped <text>`);let{payload:r,text:i,exitCode:a}=runDocsRetire(createRealRelocateExecutor(process.cwd()),n,{status:e.status,date:e.date,shipped:e.shipped,dest:e.dest,dryRun:e[`dry-run`]===!0,verbose:e.verbose===!0||isEnvVerbose()});t.json(r),i!==``&&t.text(i),t.text(`docs:retire: only .md files were scanned for inbound references.`),process.exitCode=a}});function describeIssueNumberRequired(e){return`An issue number or issue URL is required, e.g. \`${e}\`.`}function describeInvalidListQuery(e,t){return e.field===`state`?`${t.state} must be one of open, closed, all (got "${e.value}")`:`${t.limit} must be a positive integer (got "${e.value}")`}function describeNothingToUpdate(e){return`Nothing to change -- pass ${e.title} and/or ${e.body}/${e.bodyFile}. (Omitting them leaves the issue exactly as authored; this command never derives a replacement.)`}function describeEmptyComment(e){return`${e.text} / ${e.file} resolved to empty text -- pass a comment or omit the flag.`}function describePullRequestState(e,t){return`#${String(e.number)} is a pull request, not an issue -- ${t.command} refuses to write pull-request state. ${t.advice}`}function describeNoLabelsGiven(e,t){return`No labels given, which would strip every label off #${String(e.number)}. Pass ${t} if that is what you mean, or name the labels the issue should end up with.`}function describeAttachmentExists(e,t){return`"${e.filePath}" already exists -- pass ${t} to overwrite it.`}function resolverFor(e,t,n){return r=>{let i=resolveIssueTransport(e,t,r);return n(),i}}async function withNumberExample(e,t){try{return await t()}catch(t){throw t instanceof IssueNumberRequiredError?new T(describeIssueNumberRequired(e)):t}}async function runIssueView(e,t){let n=resolverFor(e,t.cwd,()=>{debug(t,`issue:view #${String(parseIssueRef(t.ref).number)}`)}),r=await withNumberExample(`pnpm exec bst issue:view 273`,()=>viewIssue(n,{ref:t.ref,...t.repo===void 0?{}:{repo:t.repo}}));return r.prUnavailable!==void 0&&debug(t,`issue:view #${String(r.number)} pulls read refused: ${r.prUnavailable.reason}`),r}async function runIssueList(e,t){let n=resolverFor(e,t.cwd,()=>{debug(t,`issue:list state=${t.state} limit=${t.limit}`)});try{return await listIssues(n,{state:t.state,limit:t.limit,...t.label===void 0?{}:{label:t.label},...t.repo===void 0?{}:{repo:t.repo}})}catch(e){throw e instanceof InvalidListQueryError?new T(describeInvalidListQuery(e,{state:`--state`,limit:`--limit`})):e}}async function runIssueComment(e,t){let n=resolverFor(e,t.cwd,()=>{debug(t,`issue:comment #${String(parseIssueRef(t.ref).number)}`)});return withNumberExample(`pnpm exec bst issue:comment 273`,()=>commentOnIssue(n,{ref:t.ref,body:t.body,dryRun:t.dryRun,...t.repo===void 0?{}:{repo:t.repo}}))}async function runIssueUpdate(e,t){let n=resolverFor(e,t.cwd,()=>{let e=[`title`,`body`].filter(e=>t[e]!==void 0);debug(t,`issue:update #${String(parseIssueRef(t.ref).number)} [${e.join(`, `)}]`)});try{return await withNumberExample(`pnpm exec bst issue:update 273 --title '...'`,()=>updateIssue(n,{ref:t.ref,dryRun:t.dryRun,...t.title===void 0?{}:{title:t.title},...t.body===void 0?{}:{body:t.body},...t.repo===void 0?{}:{repo:t.repo}}))}catch(e){throw e instanceof NothingToUpdateError?new T(describeNothingToUpdate({title:`--title`,body:`--body`,bodyFile:`--body-file`})):e}}async function runIssueCreate(e,t){let n=resolverFor(e,t.cwd,()=>{debug(t,`issue:create "${t.title.trim()}"`)});try{return await createIssue(n,{title:t.title,body:t.body,labels:t.labels,assignees:t.assignees,dryRun:t.dryRun,...t.repo===void 0?{}:{repo:t.repo}})}catch(e){throw e instanceof IssueTitleRequiredError?new T(`--title is required.`):e}}const Xu=A({meta:{name:`issue:view`,description:`Show an issue and its comments (accepts a number or an issue URL). Comments come oldest first. Review comments on a pull request are not included.`},args:{ref:{type:`positional`,required:!0,description:`Issue number or issue URL`},repo:{type:`string`,description:`Repository URL (default: this repo)`},json:{type:`boolean`,description:`Emit one JSON document: number, title, state, url, author, labels, createdAt, updatedAt, closedAt, body, isPullRequest, assignees, attachments, comments ([{id, author, createdAt, updatedAt?, body, url?}]), commentsTruncated, pr? ({head ({ref, sha, repo (or null)}), base ({ref, sha, repo (or null)}), draft, merged, mergeable (true | false | null), state}), prUnavailable? ({reason}). On a pull request exactly one of pr and prUnavailable is present, and neither is otherwise; repo is null for a deleted fork; commentsTruncated is true when the comment read hit its cap of about 1000.`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:e}){let t=await runIssueView(createRealExecutor$1(),{cwd:process.cwd(),ref:e.ref,repo:e.repo??void 0,verbose:e.verbose===!0||isEnvVerbose()});e.json===!0?createCliOutput(!0).json(t):F.info(formatIssue(t))}}),Zu=A({meta:{name:`issue:list`,description:`List a repository's issues (pull requests are excluded)`},args:{state:{type:`string`,default:`open`,description:`open | closed | all`},label:{type:`string`,description:`Filter by label name`},limit:{type:`string`,default:`30`,description:`Maximum issues to return (at most 1000 are read); --json reports truncated: true when that cap cut the list short`},repo:{type:`string`,description:`Repository URL (default: this repo)`},json:{type:`boolean`,description:`Emit one JSON document: issues ([{number, title, state, url, author, labels, createdAt, updatedAt, closedAt (null while open), isPullRequest, assignees, attachments ([{id, name, size, createdAt, downloadUrl}])}]), truncated.`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:e}){let t=await runIssueList(createRealExecutor$1(),{cwd:process.cwd(),state:e.state,label:e.label??void 0,limit:e.limit,repo:e.repo??void 0,verbose:e.verbose===!0||isEnvVerbose()});e.json===!0?createCliOutput(!0).json({issues:t.issues,truncated:t.truncated}):F.info(formatIssueList(t))}}),Qu=A({meta:{name:`issue:comment`,description:`Post a new comment on an issue (append-only)`},args:{ref:{type:`positional`,required:!0,description:`Issue number or issue URL`},body:{type:`string`,description:`Comment body`},"body-file":{type:`string`,description:`Read the body from a file ('-' for stdin)`},repo:{type:`string`,description:`Repository URL (default: this repo)`},json:{type:`boolean`,description:`Emit one JSON document: number, url.`},"dry-run":{type:`boolean`,description:`Show what would happen without writing`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:e}){let t=readBodySource(e.body??void 0,e[`body-file`]??void 0);if(t===void 0)throw new T(`One of --body or --body-file is required.`);let n=await runIssueComment(createRealExecutor$1(),{cwd:process.cwd(),ref:e.ref,body:t,repo:e.repo??void 0,dryRun:e[`dry-run`]===!0,verbose:e.verbose===!0||isEnvVerbose()});e.json===!0?createCliOutput(!0).json(n):F.info(formatIssueComment(n,e[`dry-run`]===!0))}});function collectLabelArgs(e){return collectFlagValues(e,`--label`)}function resolveIssueAssignees(e,t,n){let r=resolveRepeatableFlag(e,`--assignee`,`--no-assignee`,{noun:`assignee username`,example:`alice`,fallback:`the config default`});return r.kind===`negated`?[]:r.kind===`values`?r.values:t===void 0?loadToolingConfig(n)?.issues?.assignees??[]:[]}const $u=A({meta:{name:`issue:create`,description:`Open a new issue`},args:{title:{type:`string`,required:!0,description:`Issue title`},body:{type:`string`,description:`Issue body`},"body-file":{type:`string`,description:`Read the body from a file ('-' for stdin)`},label:{type:`string`,description:`Label name (repeatable)`},repo:{type:`string`,description:`Repository URL (default: this repo)`},assignee:{type:`string`,description:`Assignee username (repeatable; --no-assignee opens the issue unassigned). Replaces the .tooling.json issues.assignees default, which applies only without --repo`},json:{type:`boolean`,description:`Emit one JSON document: number, url, assignees. A dry run reports number 0 and an empty url.`},"dry-run":{type:`boolean`,description:`Show what would happen without writing`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:e,rawArgs:t}){let n=collectLabelArgs(t),r=e.repo??void 0,i=resolveIssueAssignees(t,r,process.cwd()),a=readBodySource(e.body??void 0,e[`body-file`]??void 0)??``,o=await runIssueCreate(createRealExecutor$1(),{cwd:process.cwd(),title:e.title,body:a,labels:n,assignees:i,repo:r,dryRun:e[`dry-run`]===!0,verbose:e.verbose===!0||isEnvVerbose()});if(e.json===!0)createCliOutput(!0).json(o);else for(let t of formatIssueCreate(o,e.title,e[`dry-run`]===!0))F.info(t)}}),ed=A({meta:{name:`issue:update`,description:`Edit an existing issue's title and/or body`},args:{ref:{type:`positional`,required:!0,description:`Issue number or issue URL`},title:{type:`string`,description:`Replace the title (default: leave it unchanged)`},body:{type:`string`,description:`Replace the body (default: leave it unchanged)`},"body-file":{type:`string`,description:`Read the new body from a file ('-' for stdin)`},repo:{type:`string`,description:`Repository URL (default: this repo)`},json:{type:`boolean`,description:`Emit one JSON document: number, url, previous ({title, body}), current ({title, body}), changed ([title | body]). A dry run reports current as it would be and writes nothing.`},"dry-run":{type:`boolean`,description:`Report what would change, mutate nothing`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:e}){let t=readBodySource(e.body??void 0,e[`body-file`]??void 0),n=await runIssueUpdate(createRealExecutor$1(),{cwd:process.cwd(),ref:e.ref,title:e.title??void 0,body:t,repo:e.repo??void 0,dryRun:e[`dry-run`]===!0,verbose:e.verbose===!0||isEnvVerbose()});e.json===!0?createCliOutput(!0).json(n):(F.info(formatIssueUpdate(n,e[`dry-run`]===!0)),e[`dry-run`]===!0&&n.changed.includes(`body`)&¬e(n.previous.body===``?`(empty)`:n.previous.body,`[dry-run] Current body`))}});function isReadableFile(e){try{return p(e),!0}catch{return!1}}const td={exists:isReadableFile,write:(e,t)=>{u(w.dirname(e),{recursive:!0}),C(e,t)}};var AttachmentExistsError=class extends T{filePath;constructor(e){super(`"${e}" already exists.`),this.filePath=e}};function sanitizeAttachmentName(e){let t=Array.from(e).filter(e=>{let t=e.codePointAt(0)??0;return!(t<=31||t===127)}).join(``),n=w.basename(t.replaceAll(`\\`,`/`));if(n===``||n===`.`||n===`..`)throw new T(`Refusing to write an attachment with an unusable filename: "${e}"`);return n}function resolveTargetPath(e,t,n){let r=sanitizeAttachmentName(t),i=w.extname(r),a=r.slice(0,r.length-i.length),o=r,s=2;for(;n.has(o);)o=`${a}-${String(s)}${i}`,s+=1;n.add(o);let c=w.resolve(e,o),l=w.resolve(e);if(c!==l&&!c.startsWith(l+w.sep))throw new T(`Refusing to write outside ${e}: "${t}"`);return c}async function downloadAttachment(e,t,n){let r=await e.fetch(n.downloadUrl,{headers:{Authorization:`token ${t}`}},{timeoutMs:Dn});if(r.status===401||r.status===403||r.status===404)throw new T(`Cannot download "${n.name}" (HTTP ${String(r.status)}) -- the token needs issue scope and access to this repository.`);if(r.status===410||r.status===422)throw new T(`Cannot download "${n.name}": HTTP ${String(r.status)} -- this attachment is permanently unavailable; retrying will not help.`);if(!r.ok)throw new E(`Failed to download "${n.name}": HTTP ${String(r.status)}`);let i=new Uint8Array(await r.arrayBuffer());if(i.byteLength!==n.size)throw new T(`Refusing to write "${n.name}": expected ${String(n.size)} bytes but received ${String(i.byteLength)}. The server returned a 200 with the wrong content -- most likely a login page, meaning the token cannot see this attachment.`);return i}async function downloadIssueAttachments(e,t){let n=parseIssueRef(t.ref),r=requireIssueNumber(n),{fetcher:i,conn:a}=e(resolveIssueTarget(n.target,t.repo)),o=t.files??td,s=await getForgejoIssue(i,a,r),c=await listForgejoComments(i,a,r),l=[...s.attachments,...c.flatMap(e=>e.attachments)],u=t.outDir,d=/* @__PURE__ */ new Set,f=[];for(let e of l){let n=resolveTargetPath(u,e.name,d);if(!t.force&&o.exists(n))throw new AttachmentExistsError(n);if(!t.dryRun){let t=await downloadAttachment(i,a.token,e);o.write(n,t)}f.push({name:w.basename(n),size:e.size,path:n})}return{dir:u,files:f}}function formatDownload(e,t){let n=[],r=t?`[dry-run] Would download`:`Downloaded`;n.push(`${r} ${String(e.files.length)} attachment(s) to ${e.dir}`);for(let t of e.files)n.push(` ${t.name} (${String(t.size)} bytes)`);return n.join(`
|
|
6146
|
-
`)}async function runIssueDownload(e,t){try{return await downloadIssueAttachments(n=>{let r=requireForgejoTransport(e,t.cwd,n,`GitHub exposes no issue-attachment API -- attachments there are Markdown links in the issue body. issue:download is Forgejo-only.`);return debug(t,`issue:download #${String(parseIssueRef(t.ref).number)}`),{fetcher:e,conn:r.conn,target:r.target}},{ref:t.ref,outDir:w.resolve(t.cwd,t.out),force:t.force,dryRun:t.dryRun,files:{exists:t=>e.readFile(t)!==null,write:(t,n)=>{e.writeFileBuffer(t,n)}},...t.repo===void 0?{}:{repo:t.repo}})}catch(e){throw e instanceof IssueNumberRequiredError?new T(describeIssueNumberRequired(`pnpm exec bst issue:download 273`)):e instanceof AttachmentExistsError?new T(describeAttachmentExists(e,`--force`)):e}}const
|
|
6147
|
-
`)}async function runIssueLabel(e,t){try{return await labelIssue(n=>{let r=requireForgejoTransport(e,t.cwd,n,"issue:label / issue:unlabel are Forgejo-only -- label mutation is not wired through the GitHub transport. Use the GitHub UI or `gh` for a github.com issue.");return debug(t,`issue:${t.action===`add`?`label`:`unlabel`} #${String(parseIssueRef(t.ref).number)} ${t.label}`),{fetcher:e,conn:r.conn,target:r.target}},{ref:t.ref,label:t.label,action:t.action,dryRun:t.dryRun,...t.repo===void 0?{}:{repo:t.repo}})}catch(e){if(e instanceof IssueNumberRequiredError){let e=t.action===`add`?`issue:label`:`issue:unlabel`;throw new T(describeIssueNumberRequired(`pnpm exec bst ${e} 273 agent/implement`))}throw e}}function defineIssueLabelCommand(e){return
|
|
6148
|
-
`)}async function runIssueState(e,t){try{return await setIssueState(n=>{let r=resolveIssueTransport(e,t.cwd,n);return debug(t,`issue:${t.action} #${String(parseIssueRef(t.ref).number)}`),r},{ref:t.ref,action:t.action,dryRun:t.dryRun,...t.comment===void 0?{}:{comment:t.comment},...t.repo===void 0?{}:{repo:t.repo}})}catch(e){if(e instanceof IssueNumberRequiredError)throw new T(describeIssueNumberRequired(`pnpm exec bst issue:${t.action} 273`));if(e instanceof EmptyCommentError)throw new T(describeEmptyComment({text:`--comment`,file:`--comment-file`}));if(e instanceof PullRequestStateError){let t=e.action===`close`?`Run \`pnpm exec bst-fj pr:close ${String(e.number)}\` to close it; that bin installs with \`@bensandee/forgejo-cli\`. On GitHub, \`gh pr close ${String(e.number)}\`.`:`Run \`pnpm exec bst pr:reopen ${String(e.number)}\` to reopen it.`;throw new T(describePullRequestState(e,{command:`issue:${e.action}`,advice:t}))}throw e}}function defineIssueStateCommand(e){return
|
|
6149
|
-
`)}const
|
|
6149
|
+
`),exitCode:0}}const Sd=j({meta:{name:`docs:relocate`,description:`Move one or more .md files and rewrite the markdown links that break as a result -- both the moved files' own relative links and every inbound link elsewhere in the repo that pointed at them. Idempotent. Argument grammar mirrors POSIX mv: pnpm exec bst docs:relocate <src>... <dest>.`},args:{"dry-run":{type:`boolean`,description:`Print the planned move and edits without writing`},json:{type:`boolean`,description:`Emit one JSON document: moves ([{from, to, status (pending | already-done)}]), rewrites ([{file, edits ([{line, oldTarget, newTarget}])}]), dryRun.`},verbose:{type:`boolean`,description:`Emit detailed debug logging`}},run({args:e}){let t=createCliOutput(e.json===!0),n=e._;if(n.length<2)throw new T(`Usage: pnpm exec bst docs:relocate <src>... <dest>`);let r=n.at(-1);if(r===void 0)throw new T(`Usage: pnpm exec bst docs:relocate <src>... <dest>`);let i=n.slice(0,-1),{payload:a,text:o,exitCode:s}=runDocsRelocate(createRealRelocateExecutor(process.cwd()),i,r,{dryRun:e[`dry-run`]===!0,verbose:e.verbose===!0||isEnvVerbose()});t.json(a),o!==``&&t.text(o),t.text(`docs:relocate: only .md files were scanned for inbound references.`),process.exitCode=s}});function localToday(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}const Cd=/^\d{4}-\d{2}-\d{2}$/;function validateRetireArgs(e,t,n){if(!isRetireVerb(n.status))throw new T(`docs:retire: unrecognized --status "${n.status}" (expected one of: ${Ta.join(`, `)})`);let r=n.status;if(n.date!==void 0&&!Cd.test(n.date))throw new T(`docs:retire: --date must be YYYY-MM-DD, got: ${n.date}`);let i;if(n.shipped!==void 0){let e=splitRetireLeadIn(n.shipped);if(e.verb!==void 0&&e.verb!==r)throw new T(`docs:retire: --status ${r} but --shipped starts with "${Ea[e.verb]}:"; drop the lead-in or fix --status`);if(e.body.trim()===``)throw new T(`docs:retire: --shipped has no text after the lead-in: ${JSON.stringify(n.shipped)}`);i={body:e.body,leadInDropped:e.body!==n.shipped}}if(!t.endsWith(`.md`))throw new T(`docs:retire: source must be a .md file: ${t}`);let a=n.dest===void 0?retireDestination(t,r):w.posix.normalize(n.dest);if(t!==a&&e.exists(t)&&e.exists(a))throw new T(`docs:retire: refusing to overwrite existing destination: ${a}`);return{verb:r,dest:a,shipped:i}}function nextChunk(e,t){let n=e.slice(t),r=/^\n+(.*?)(?:\n\n|\n*$)/s.exec(n);if(r===null)return;let i=r[1]??``;return{end:t+(/^\n+/.exec(r[0])?.[0].length??0)+i.length,text:i}}function scanRetireParagraph(e,t){let n=nextChunk(e,t);if(n!==void 0&&Aa.test(n.text))return n}function skipHistoricalBanner(e,t){let n=nextChunk(e,t);return n===void 0||!Na.test(n.text)?t:n.end}function findRetireParagraph(e,t,n){return scanRetireParagraph(e,t)??scanRetireParagraph(e,n)}const wd=/^>\s?/;function stripLeadingBlockquote(e){return e.replace(wd,``)}function applyLifecycleEdits(e,t,n,r,i){let a=[],o=[];function record(e,t){a.push(t),o.push({kind:e,description:t,applied:e!==`retire-paragraph-present`})}let s=matchStatusBlock(e);if(!s)throw new T(`docs:retire: ${t} has no Status: line in its header -- refusing to guess where it belongs`);let c=s.rawValue.trim(),l=formatDatedStatus(n,r),u=s.continuation.length>0,d=u?[s.rawValue.trim(),...s.continuation.map(stripLeadingBlockquote)]:void 0,f=e,p=s.lineEnd;if(c!==l||u){let e=s.prefix+l;f=f.slice(0,s.lineStart)+e+f.slice(s.blockEnd),p=s.lineStart+e.length,c!==l&&record(`status-line`,`${t}: Status: ${c} -> ${l}`),d!==void 0&&record(`status-collapse`,`${t}: collapsed ${String(d.length)}-line Status block into one line`)}let m=skipHistoricalBanner(f,enclosingBlockEnd(f,p,s.quoted)),h=findRetireParagraph(f,p,m),g;if(h===void 0){if(i===void 0)throw new T(`docs:retire: --shipped is required to add the "${Ea[n]}:" paragraph (doc has none yet)`);let e=`> ${Ea[n]}: ${i.body}`;f=insertBlockAtBoundary(f,m,e);let r=i.leadInDropped?` (dropped the "${Ea[n]}:" lead-in --shipped repeated)`:``;record(`retire-paragraph`,`${t}: add "${Ea[n]}:" paragraph${r}`),g=m+2+e.length}else g=h.end,i!==void 0&&!h.text.includes(i.body.trim())&&record(`retire-paragraph-present`,`${t}: retire paragraph already present -- the --shipped text was not written`);if(d!==void 0){let e=`\n\n> Prior status: ${d[0]}`+d.slice(1).map(e=>`\n> ${e}`).join(``);f=f.slice(0,g)+e+f.slice(g),record(`prior-status-preserved`,`${t}: preserved ${String(d.length)}-line prior status text below the retire paragraph`)}return{content:f,summary:a,edits:o}}function formatRetireLines(e,t,n,r){let i=[],a=n.moves[0];i.push(a?.status===`pending`?`move: ${e} -> ${t}`:`move: ${e} -> ${t} (already done)`);for(let e of n.rewrites)for(let t of e.edits)i.push(` ${t.file}:${String(t.line)}: ${t.oldTarget} -> ${t.newTarget}`);for(let e of r)i.push(` ${e}`);return i}function runDocsRetire(e,t,n){let r={verbose:n.verbose??!1},{verb:i,dest:a,shipped:o}=validateRetireArgs(e,t,n),s=buildRelocatePlan(e,[{from:t,to:a}]),c=s.moves[0];if(c===void 0)throw new T(`docs:retire: internal error -- no move planned`);let l=s.rewrites.find(e=>e.file===a),u=l?.content??e.readFile(c.status===`pending`?t:a);if(u===void 0)throw new T(`docs:retire: cannot read ${c.status===`pending`?t:a}`);let d=n.date??datedStatusValue(u)??localToday(/* @__PURE__ */ new Date),{content:f,summary:p,edits:m}=applyLifecycleEdits(u,a,i,d,o),h=delinkDocument(f,w.posix.dirname(a)),g=h.content;h.linkEdits.length>0&&p.push(`de-linked ${String(h.linkEdits.length)} link(s) pointing outside docs/`),h.bannerAdded&&p.push(`added the historical banner`),h.skipped!==void 0&&p.push(`banner skipped -- ${h.skipped}`),debug(r,`docs:retire: move ${t} -> ${a}, ${String(p.length)} lifecycle edit(s)`);let _=s.rewrites.filter(e=>e.file!==a);(l!==void 0||g!==u)&&_.push({file:a,content:g,edits:l?.edits??[]});let v=c.status===`pending`||_.length>0,y={verb:i,date:d,src:t,dest:a,move:{from:c.from,to:c.to,status:c.status},lifecycle:m,rewrites:s.rewrites.map(e=>({file:e.file,edits:e.edits.map(e=>({line:e.line,oldTarget:e.oldTarget,newTarget:e.newTarget}))})),delink:{linkEdits:h.linkEdits.length,bannerAdded:h.bannerAdded,skipped:h.skipped??null},changed:v,dryRun:n.dryRun===!0},b=formatRetireLines(t,a,s,p);return n.dryRun===!0?b.push(`docs:retire: dry run -- nothing written.`):(applyRelocatePlan(e,{moves:s.moves,rewrites:_}),b.push(`docs:retire: done.`)),{payload:y,text:b.join(`
|
|
6150
|
+
`),exitCode:0}}const Td=j({meta:{name:`docs:retire`,description:`Retire a plan/spec doc: move it to its retired/ location (computed by convention, or --dest), rewrite the markdown links that break as a result, set a dated terminal Status: line, and ensure the retire paragraph. After the lifecycle edits it also de-links links out of docs/ and adds the historical banner, as docs:delink does. pnpm exec bst docs:retire <plan.md> --status <verb> --shipped <text>.`},args:{status:{type:`string`,description:`Terminal verb: ${Ta.join(` | `)}`,required:!0},date:{type:`string`,description:`Retirement date, YYYY-MM-DD (defaults to the date of an existing terminal Status: line, else today, local time)`},shipped:{type:`string`,description:`Text after the retire paragraph's lead-in, which the command writes itself -- --status completed --shipped "parts 1-6 in #123." writes "> Shipped: parts 1-6 in #123." (required unless one is already present)`},dest:{type:`string`,description:`Override the computed retired/ destination`},"dry-run":{type:`boolean`,description:`Print the planned move and edits without writing`},json:{type:`boolean`,description:`Emit one JSON document: verb, date, src, dest, move, lifecycle, rewrites, delink ({linkEdits, bannerAdded, skipped}), changed, dryRun. changed is false when the run writes nothing.`},verbose:{type:`boolean`,description:`Emit detailed debug logging`}},run({args:e}){let t=createCliOutput(e.json===!0),[n]=e._;if(n===void 0)throw new T(`Usage: pnpm exec bst docs:retire <plan.md> --status <verb> --shipped <text>`);let{payload:r,text:i,exitCode:a}=runDocsRetire(createRealRelocateExecutor(process.cwd()),n,{status:e.status,date:e.date,shipped:e.shipped,dest:e.dest,dryRun:e[`dry-run`]===!0,verbose:e.verbose===!0||isEnvVerbose()});t.json(r),i!==``&&t.text(i),t.text(`docs:retire: only .md files were scanned for inbound references.`),process.exitCode=a}});function describeIssueNumberRequired(e){return`An issue number or issue URL is required, e.g. \`${e}\`.`}function describeInvalidListQuery(e,t){return e.field===`state`?`${t.state} must be one of open, closed, all (got "${e.value}")`:`${t.limit} must be a positive integer (got "${e.value}")`}function describeNothingToUpdate(e){return`Nothing to change -- pass ${e.title} and/or ${e.body}/${e.bodyFile}. (Omitting them leaves the issue exactly as authored; this command never derives a replacement.)`}function describeEmptyComment(e){return`${e.text} / ${e.file} resolved to empty text -- pass a comment or omit the flag.`}function describePullRequestState(e,t){return`#${String(e.number)} is a pull request, not an issue -- ${t.command} refuses to write pull-request state. ${t.advice}`}function describeNoLabelsGiven(e,t){return`No labels given, which would strip every label off #${String(e.number)}. Pass ${t} if that is what you mean, or name the labels the issue should end up with.`}function describeAttachmentExists(e,t){return`"${e.filePath}" already exists -- pass ${t} to overwrite it.`}function resolverFor(e,t,n){return r=>{let i=resolveIssueTransport(e,t,r);return n(),i}}async function withNumberExample(e,t){try{return await t()}catch(t){throw t instanceof IssueNumberRequiredError?new T(describeIssueNumberRequired(e)):t}}async function runIssueView(e,t){let n=resolverFor(e,t.cwd,()=>{debug(t,`issue:view #${String(parseIssueRef(t.ref).number)}`)}),r=await withNumberExample(`pnpm exec bst issue:view 273`,()=>viewIssue(n,{ref:t.ref,...t.repo===void 0?{}:{repo:t.repo}}));return r.prUnavailable!==void 0&&debug(t,`issue:view #${String(r.number)} pulls read refused: ${r.prUnavailable.reason}`),r}async function runIssueList(e,t){let n=resolverFor(e,t.cwd,()=>{debug(t,`issue:list state=${t.state} limit=${t.limit}`)});try{return await listIssues(n,{state:t.state,limit:t.limit,...t.label===void 0?{}:{label:t.label},...t.repo===void 0?{}:{repo:t.repo}})}catch(e){throw e instanceof InvalidListQueryError?new T(describeInvalidListQuery(e,{state:`--state`,limit:`--limit`})):e}}async function runIssueComment(e,t){let n=resolverFor(e,t.cwd,()=>{debug(t,`issue:comment #${String(parseIssueRef(t.ref).number)}`)});return withNumberExample(`pnpm exec bst issue:comment 273`,()=>commentOnIssue(n,{ref:t.ref,body:t.body,dryRun:t.dryRun,...t.repo===void 0?{}:{repo:t.repo}}))}async function runIssueUpdate(e,t){let n=resolverFor(e,t.cwd,()=>{let e=[`title`,`body`].filter(e=>t[e]!==void 0);debug(t,`issue:update #${String(parseIssueRef(t.ref).number)} [${e.join(`, `)}]`)});try{return await withNumberExample(`pnpm exec bst issue:update 273 --title '...'`,()=>updateIssue(n,{ref:t.ref,dryRun:t.dryRun,...t.title===void 0?{}:{title:t.title},...t.body===void 0?{}:{body:t.body},...t.repo===void 0?{}:{repo:t.repo}}))}catch(e){throw e instanceof NothingToUpdateError?new T(describeNothingToUpdate({title:`--title`,body:`--body`,bodyFile:`--body-file`})):e}}async function runIssueCreate(e,t){let n=resolverFor(e,t.cwd,()=>{debug(t,`issue:create "${t.title.trim()}"`)});try{return await createIssue(n,{title:t.title,body:t.body,labels:t.labels,assignees:t.assignees,dryRun:t.dryRun,...t.repo===void 0?{}:{repo:t.repo}})}catch(e){throw e instanceof IssueTitleRequiredError?new T(`--title is required.`):e}}const Ed=j({meta:{name:`issue:view`,description:`Show an issue and its comments (accepts a number or an issue URL). Comments come oldest first. Review comments on a pull request are not included.`},args:{ref:{type:`positional`,required:!0,description:`Issue number or issue URL`},repo:{type:`string`,description:`Repository URL (default: this repo)`},json:{type:`boolean`,description:`Emit one JSON document: number, title, state, url, author, labels, createdAt, updatedAt, closedAt, body, isPullRequest, assignees, attachments, comments ([{id, author, createdAt, updatedAt?, body, url?}]), commentsTruncated, pr? ({head ({ref, sha, repo (or null)}), base ({ref, sha, repo (or null)}), draft, merged, mergeable (true | false | null), state}), prUnavailable? ({reason}). On a pull request exactly one of pr and prUnavailable is present, and neither is otherwise; repo is null for a deleted fork; commentsTruncated is true when the comment read hit its cap of about 1000.`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:e}){let t=await runIssueView(createRealExecutor$1(),{cwd:process.cwd(),ref:e.ref,repo:e.repo??void 0,verbose:e.verbose===!0||isEnvVerbose()});e.json===!0?createCliOutput(!0).json(t):I.info(formatIssue(t))}}),Dd=j({meta:{name:`issue:list`,description:`List a repository's issues (pull requests are excluded)`},args:{state:{type:`string`,default:`open`,description:`open | closed | all`},label:{type:`string`,description:`Filter by label name`},limit:{type:`string`,default:`30`,description:`Maximum issues to return (at most 1000 are read); --json reports truncated: true when that cap cut the list short`},repo:{type:`string`,description:`Repository URL (default: this repo)`},json:{type:`boolean`,description:`Emit one JSON document: issues ([{number, title, state, url, author, labels, createdAt, updatedAt, closedAt (null while open), isPullRequest, assignees, attachments ([{id, name, size, createdAt, downloadUrl}])}]), truncated.`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:e}){let t=await runIssueList(createRealExecutor$1(),{cwd:process.cwd(),state:e.state,label:e.label??void 0,limit:e.limit,repo:e.repo??void 0,verbose:e.verbose===!0||isEnvVerbose()});e.json===!0?createCliOutput(!0).json({issues:t.issues,truncated:t.truncated}):I.info(formatIssueList(t))}}),Od=j({meta:{name:`issue:comment`,description:`Post a new comment on an issue (append-only)`},args:{ref:{type:`positional`,required:!0,description:`Issue number or issue URL`},body:{type:`string`,description:`Comment body`},"body-file":{type:`string`,description:`Read the body from a file ('-' for stdin)`},repo:{type:`string`,description:`Repository URL (default: this repo)`},json:{type:`boolean`,description:`Emit one JSON document: number, url.`},"dry-run":{type:`boolean`,description:`Show what would happen without writing`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:e}){let t=readBodySource(e.body??void 0,e[`body-file`]??void 0);if(t===void 0)throw new T(`One of --body or --body-file is required.`);let n=await runIssueComment(createRealExecutor$1(),{cwd:process.cwd(),ref:e.ref,body:t,repo:e.repo??void 0,dryRun:e[`dry-run`]===!0,verbose:e.verbose===!0||isEnvVerbose()});e.json===!0?createCliOutput(!0).json(n):I.info(formatIssueComment(n,e[`dry-run`]===!0))}});function collectLabelArgs(e){return collectFlagValues(e,`--label`)}function resolveIssueAssignees(e,t,n){let r=resolveRepeatableFlag(e,`--assignee`,`--no-assignee`,{noun:`assignee username`,example:`alice`,fallback:`the config default`});return r.kind===`negated`?[]:r.kind===`values`?r.values:t===void 0?loadToolingConfig(n)?.issues?.assignees??[]:[]}const kd=j({meta:{name:`issue:create`,description:`Open a new issue`},args:{title:{type:`string`,required:!0,description:`Issue title`},body:{type:`string`,description:`Issue body`},"body-file":{type:`string`,description:`Read the body from a file ('-' for stdin)`},label:{type:`string`,description:`Label name (repeatable)`},repo:{type:`string`,description:`Repository URL (default: this repo)`},assignee:{type:`string`,description:`Assignee username (repeatable; --no-assignee opens the issue unassigned). Replaces the .tooling.json issues.assignees default, which applies only without --repo`},json:{type:`boolean`,description:`Emit one JSON document: number, url, assignees. A dry run reports number 0 and an empty url.`},"dry-run":{type:`boolean`,description:`Show what would happen without writing`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:e,rawArgs:t}){let n=collectLabelArgs(t),r=e.repo??void 0,i=resolveIssueAssignees(t,r,process.cwd()),a=readBodySource(e.body??void 0,e[`body-file`]??void 0)??``,o=await runIssueCreate(createRealExecutor$1(),{cwd:process.cwd(),title:e.title,body:a,labels:n,assignees:i,repo:r,dryRun:e[`dry-run`]===!0,verbose:e.verbose===!0||isEnvVerbose()});if(e.json===!0)createCliOutput(!0).json(o);else for(let t of formatIssueCreate(o,e.title,e[`dry-run`]===!0))I.info(t)}}),Ad=j({meta:{name:`issue:update`,description:`Edit an existing issue's title and/or body`},args:{ref:{type:`positional`,required:!0,description:`Issue number or issue URL`},title:{type:`string`,description:`Replace the title (default: leave it unchanged)`},body:{type:`string`,description:`Replace the body (default: leave it unchanged)`},"body-file":{type:`string`,description:`Read the new body from a file ('-' for stdin)`},repo:{type:`string`,description:`Repository URL (default: this repo)`},json:{type:`boolean`,description:`Emit one JSON document: number, url, previous ({title, body}), current ({title, body}), changed ([title | body]). A dry run reports current as it would be and writes nothing.`},"dry-run":{type:`boolean`,description:`Report what would change, mutate nothing`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:e}){let t=readBodySource(e.body??void 0,e[`body-file`]??void 0),n=await runIssueUpdate(createRealExecutor$1(),{cwd:process.cwd(),ref:e.ref,title:e.title??void 0,body:t,repo:e.repo??void 0,dryRun:e[`dry-run`]===!0,verbose:e.verbose===!0||isEnvVerbose()});e.json===!0?createCliOutput(!0).json(n):(I.info(formatIssueUpdate(n,e[`dry-run`]===!0)),e[`dry-run`]===!0&&n.changed.includes(`body`)&¬e(n.previous.body===``?`(empty)`:n.previous.body,`[dry-run] Current body`))}});function isReadableFile(e){try{return p(e),!0}catch{return!1}}const jd={exists:isReadableFile,write:(e,t)=>{u(w.dirname(e),{recursive:!0}),C(e,t)}};var AttachmentExistsError=class extends T{filePath;constructor(e){super(`"${e}" already exists.`),this.filePath=e}};function sanitizeAttachmentName(e){let t=Array.from(e).filter(e=>{let t=e.codePointAt(0)??0;return!(t<=31||t===127)}).join(``),n=w.basename(t.replaceAll(`\\`,`/`));if(n===``||n===`.`||n===`..`)throw new T(`Refusing to write an attachment with an unusable filename: "${e}"`);return n}function resolveTargetPath(e,t,n){let r=sanitizeAttachmentName(t),i=w.extname(r),a=r.slice(0,r.length-i.length),o=r,s=2;for(;n.has(o);)o=`${a}-${String(s)}${i}`,s+=1;n.add(o);let c=w.resolve(e,o),l=w.resolve(e);if(c!==l&&!c.startsWith(l+w.sep))throw new T(`Refusing to write outside ${e}: "${t}"`);return c}async function downloadAttachment(e,t,n){let r=await e.fetch(n.downloadUrl,{headers:{Authorization:`token ${t}`}},{timeoutMs:bn});if(r.status===401||r.status===403||r.status===404)throw new T(`Cannot download "${n.name}" (HTTP ${String(r.status)}) -- the token needs issue scope and access to this repository.`);if(r.status===410||r.status===422)throw new T(`Cannot download "${n.name}": HTTP ${String(r.status)} -- this attachment is permanently unavailable; retrying will not help.`);if(!r.ok)throw new E(`Failed to download "${n.name}": HTTP ${String(r.status)}`);let i=new Uint8Array(await r.arrayBuffer());if(i.byteLength!==n.size)throw new T(`Refusing to write "${n.name}": expected ${String(n.size)} bytes but received ${String(i.byteLength)}. The server returned a 200 with the wrong content -- most likely a login page, meaning the token cannot see this attachment.`);return i}async function downloadIssueAttachments(e,t){let n=parseIssueRef(t.ref),r=requireIssueNumber(n),{fetcher:i,conn:a}=e(resolveIssueTarget(n.target,t.repo)),o=t.files??jd,s=await getForgejoIssue(i,a,r),c=await listForgejoComments(i,a,r),l=[...s.attachments,...c.flatMap(e=>e.attachments)],u=t.outDir,d=/* @__PURE__ */ new Set,f=[];for(let e of l){let n=resolveTargetPath(u,e.name,d);if(!t.force&&o.exists(n))throw new AttachmentExistsError(n);if(!t.dryRun){let t=await downloadAttachment(i,a.token,e);o.write(n,t)}f.push({name:w.basename(n),size:e.size,path:n})}return{dir:u,files:f}}function formatDownload(e,t){let n=[],r=t?`[dry-run] Would download`:`Downloaded`;n.push(`${r} ${String(e.files.length)} attachment(s) to ${e.dir}`);for(let t of e.files)n.push(` ${t.name} (${String(t.size)} bytes)`);return n.join(`
|
|
6151
|
+
`)}async function runIssueDownload(e,t){try{return await downloadIssueAttachments(n=>{let r=requireForgejoTransport(e,t.cwd,n,`GitHub exposes no issue-attachment API -- attachments there are Markdown links in the issue body. issue:download is Forgejo-only.`);return debug(t,`issue:download #${String(parseIssueRef(t.ref).number)}`),{fetcher:e,conn:r.conn,target:r.target}},{ref:t.ref,outDir:w.resolve(t.cwd,t.out),force:t.force,dryRun:t.dryRun,files:{exists:t=>e.readFile(t)!==null,write:(t,n)=>{e.writeFileBuffer(t,n)}},...t.repo===void 0?{}:{repo:t.repo}})}catch(e){throw e instanceof IssueNumberRequiredError?new T(describeIssueNumberRequired(`pnpm exec bst issue:download 273`)):e instanceof AttachmentExistsError?new T(describeAttachmentExists(e,`--force`)):e}}const Md=j({meta:{name:`issue:download`,description:`Download an issue's attachments (Forgejo only)`},args:{ref:{type:`positional`,required:!0,description:`Issue number or issue URL`},out:{type:`string`,default:`.`,description:`Directory to download into`},force:{type:`boolean`,description:`Overwrite existing files`},repo:{type:`string`,description:`Repository URL (default: this repo)`},json:{type:`boolean`,description:`Emit one JSON document: dir, files ([{name, size, path}]). A dry run lists the files it would write and writes nothing.`},"dry-run":{type:`boolean`,description:`List what would be downloaded, write nothing`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:e}){let t=await runIssueDownload(createRealExecutor$1(),{cwd:process.cwd(),ref:e.ref,out:e.out,force:e.force===!0,repo:e.repo??void 0,dryRun:e[`dry-run`]===!0,verbose:e.verbose===!0||isEnvVerbose()});e.json===!0?createCliOutput(!0).json(t):I.info(formatDownload(t,e[`dry-run`]===!0))}});async function labelIssue(e,t){let n=parseIssueRef(t.ref),r=requireIssueNumber(n),{fetcher:i,target:a,conn:o}=e(resolveIssueTarget(n.target,t.repo)),s=`${a.serverUrl}/${a.repository}/issues/${String(r)}`;return t.dryRun||(t.action===`add`?await addForgejoIssueLabel(i,o,r,t.label):await removeForgejoIssueLabel(i,o,r,t.label)),{number:r,label:t.label,action:t.action,url:s}}function formatIssueLabel(e,t){let n=e.action===`add`,r;r=n?t?`Would add`:`Added`:t?`Would remove`:`Removed`;let i=n?`to`:`from`;return`${r} label "${e.label}" ${i} #${String(e.number)} (${e.url})`}var NoLabelsGivenError=class extends T{number;constructor(e){super(`No labels given, which would strip every label off #${String(e)}.`),this.number=e}};async function setIssueLabels(e,t){let n=parseIssueRef(t.ref),r=requireIssueNumber(n);if(t.labels.length===0&&t.clear!==!0)throw new NoLabelsGivenError(r);let{fetcher:i,target:a,conn:o}=e(resolveIssueTarget(n.target,t.repo)),s=`${a.serverUrl}/${a.repository}/issues/${String(r)}`,c=(await getForgejoIssue(i,o,r)).labels,l=diffLabels(c,t.labels);return t.dryRun||await replaceForgejoIssueLabels(i,o,r,await resolveLabelIds(i,o,t.labels)),{number:r,labels:t.labels,previous:c,url:s,...l}}function diffLabels(e,t){let n=new Set(e),r=new Set(t);return{added:t.filter(e=>!n.has(e)),removed:e.filter(e=>!r.has(e))}}function formatIssueSetLabels(e,t){let n=`${t?`Would set`:`Set`} labels [${e.labels.length===0?`(none)`:e.labels.join(`, `)}] on #${String(e.number)} (${e.url})`;if(e.added.length===0&&e.removed.length===0)return`${n}\n no change (the issue already carries exactly these)`;let r=[n];return e.removed.length>0&&r.push(` ${t?`would remove`:`removed`}: ${e.removed.join(`, `)}`),e.added.length>0&&r.push(` ${t?`would add`:`added`}: ${e.added.join(`, `)}`),r.join(`
|
|
6152
|
+
`)}async function runIssueLabel(e,t){try{return await labelIssue(n=>{let r=requireForgejoTransport(e,t.cwd,n,"issue:label / issue:unlabel are Forgejo-only -- label mutation is not wired through the GitHub transport. Use the GitHub UI or `gh` for a github.com issue.");return debug(t,`issue:${t.action===`add`?`label`:`unlabel`} #${String(parseIssueRef(t.ref).number)} ${t.label}`),{fetcher:e,conn:r.conn,target:r.target}},{ref:t.ref,label:t.label,action:t.action,dryRun:t.dryRun,...t.repo===void 0?{}:{repo:t.repo}})}catch(e){if(e instanceof IssueNumberRequiredError){let e=t.action===`add`?`issue:label`:`issue:unlabel`;throw new T(describeIssueNumberRequired(`pnpm exec bst ${e} 273 agent/implement`))}throw e}}function defineIssueLabelCommand(e){return j({meta:{name:e===`add`?`issue:label`:`issue:unlabel`,description:e===`add`?`Add a label to an issue (Forgejo only)`:`Remove a label from an issue (Forgejo only)`},args:{ref:{type:`positional`,required:!0,description:`Issue number or issue URL`},label:{type:`positional`,required:!0,description:e===`add`?`Label name to add`:`Label name to remove`},repo:{type:`string`,description:`Target repository URL (default: this repo's origin)`},json:{type:`boolean`,description:`Emit one JSON document: number, label, action (add | remove), url.`},"dry-run":{type:`boolean`,description:`Report what would change, mutate nothing`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:t}){let n=await runIssueLabel(createRealExecutor$1(),{cwd:process.cwd(),ref:t.ref,label:t.label,action:e,repo:t.repo,dryRun:t[`dry-run`]===!0,verbose:t.verbose===!0||isEnvVerbose()});t.json===!0?createCliOutput(!0).json(n):I.info(formatIssueLabel(n,t[`dry-run`]===!0))}})}const Nd=defineIssueLabelCommand(`add`),Pd=defineIssueLabelCommand(`remove`);async function runIssueSetLabels(e,t){try{return await setIssueLabels(n=>{let r=requireForgejoTransport(e,t.cwd,n,"issue:set-labels is Forgejo-only -- label mutation is not wired through the GitHub transport. Use the GitHub UI or `gh` for a github.com issue.");return debug(t,`issue:set-labels #${String(parseIssueRef(t.ref).number)} [${t.labels.join(`, `)}]`),{fetcher:e,conn:r.conn,target:r.target}},{ref:t.ref,labels:t.labels,dryRun:t.dryRun,...t.clear===void 0?{}:{clear:t.clear},...t.repo===void 0?{}:{repo:t.repo}})}catch(e){throw e instanceof IssueNumberRequiredError?new T(describeIssueNumberRequired(`pnpm exec bst issue:set-labels 273 agent/plan`)):e instanceof NoLabelsGivenError?new T(describeNoLabelsGiven(e,`--clear`)):e}}const Fd=j({meta:{name:`issue:set-labels`,description:`Replace an issue's entire label set in one atomic call (Forgejo only)`},args:{ref:{type:`positional`,required:!0,description:`Issue number or issue URL`},labels:{type:`positional`,required:!1,description:`The label names the issue should end up with; any label you omit is removed`},clear:{type:`boolean`,description:`Permit an empty label list (remove every label). Required for that case`},repo:{type:`string`,description:`Target repository URL (default: this repo's origin)`},json:{type:`boolean`,description:`Emit one JSON document: number, labels, previous, added, removed, url. A dry run reports the change it would make and writes nothing.`},"dry-run":{type:`boolean`,description:`Report what would change, mutate nothing`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:e}){let t=e._.slice(1),n=await runIssueSetLabels(createRealExecutor$1(),{cwd:process.cwd(),ref:e.ref,labels:t,clear:e.clear===!0,repo:e.repo,dryRun:e[`dry-run`]===!0,verbose:e.verbose===!0||isEnvVerbose()});e.json===!0?createCliOutput(!0).json(n):I.info(formatIssueSetLabels(n,e[`dry-run`]===!0))}});var EmptyCommentError=class extends T{constructor(){super(`The comment resolved to empty text.`)}};function rejectEmptyComment(e){if(e!==void 0&&e.trim()===``)throw new EmptyCommentError}var PullRequestStateError=class extends T{number;action;constructor(e,t){super(`#${String(e)} is a pull request, not an issue; its state is not written here.`),this.number=e,this.action=t}},NotAPullRequestError=class extends T{number;constructor(e){super(`#${String(e)} is an issue, not a pull request.`),this.number=e}},StateNotTakenError=class extends T{number;expected;actual;constructor(e,t,n){super(`The forge did not change #${String(e)}: it is still ${n}, not ${t}.`),this.number=e,this.expected=t,this.actual=n}};const Id={close:`closed`,reopen:`open`};async function changeState(e,t,n,r){let i=await e.get(t);if(r===`issue`&&i.isPullRequest)throw new PullRequestStateError(t,n.action);if(r===`pull-request`&&!i.isPullRequest)throw new NotAPullRequestError(t);let a=n.comment!==void 0,o=Id[n.action],buildResult=(e,r,o,s,c)=>({number:t,url:e,action:n.action,state:{previous:i.state,current:r},changed:o,...a?{comment:{posted:s}}:{},...c===void 0?{}:{merged:c}});if(i.state===o){let n=r===`pull-request`?(await e.pullRequest(t)).merged:void 0;return buildResult(i.url,i.state,!1,!1,n)}if(n.dryRun)return buildResult(i.url,o,!0,!0);a&&await e.addComment(t,n.comment??``);let s;try{if(s=await e.setState(t,o),s.state!==o)throw new StateNotTakenError(t,o,s.state)}catch(e){throw a&&e instanceof Error&&(e.message=`The comment on #${String(t)} was already posted; a retry will duplicate it. `+e.message),e}return buildResult(s.url,s.state,!0,!0)}async function setIssueState(e,t){let n=parseIssueRef(t.ref),r=requireIssueNumber(n);rejectEmptyComment(t.comment);let{api:i}=e(resolveIssueTarget(n.target,t.repo));return changeState(i,r,t,`issue`)}const Ld={close:`Closed`,reopen:`Reopened`};function formatIssueState(e,t){let n=[];return e.changed?t?n.push(`Would ${e.action} #${String(e.number)}: ${e.state.previous} -> ${e.state.current} (${e.url})`):n.push(`${Ld[e.action]} #${String(e.number)}: ${e.state.previous} -> ${e.state.current} (${e.url})`):n.push(`#${String(e.number)} is already ${e.state.current} -- nothing to ${e.action}. (${e.url})`),e.comment!==void 0&&(e.comment.posted?n.push(t?` would post a comment before writing state`:` comment posted`):n.push(` comment: not posted (issue was already in that state)`)),n.join(`
|
|
6153
|
+
`)}async function runIssueState(e,t){try{return await setIssueState(n=>{let r=resolveIssueTransport(e,t.cwd,n);return debug(t,`issue:${t.action} #${String(parseIssueRef(t.ref).number)}`),r},{ref:t.ref,action:t.action,dryRun:t.dryRun,...t.comment===void 0?{}:{comment:t.comment},...t.repo===void 0?{}:{repo:t.repo}})}catch(e){if(e instanceof IssueNumberRequiredError)throw new T(describeIssueNumberRequired(`pnpm exec bst issue:${t.action} 273`));if(e instanceof EmptyCommentError)throw new T(describeEmptyComment({text:`--comment`,file:`--comment-file`}));if(e instanceof PullRequestStateError){let t=e.action===`close`?`Run \`pnpm exec bst-fj pr:close ${String(e.number)}\` to close it; that bin installs with \`@bensandee/forgejo-cli\`. On GitHub, \`gh pr close ${String(e.number)}\`.`:`Run \`pnpm exec bst pr:reopen ${String(e.number)}\` to reopen it.`;throw new T(describePullRequestState(e,{command:`issue:${e.action}`,advice:t}))}throw e}}function defineIssueStateCommand(e){return j({meta:{name:e===`close`?`issue:close`:`issue:reopen`,description:e===`close`?`Close an issue, optionally posting a comment first. An issue already closed is reported, not an error, and no comment is posted. A pull request is refused.`:`Reopen an issue, optionally posting a comment first. An issue already open is reported, not an error, and no comment is posted. A pull request is refused.`},args:{ref:{type:`positional`,required:!0,description:`Issue number or issue URL`},comment:{type:`string`,description:`Post this comment before writing state`},"comment-file":{type:`string`,description:`Read the comment from a file ('-' for stdin)`},repo:{type:`string`,description:`Target repository URL (default: this repo's origin)`},json:{type:`boolean`,description:`Emit one JSON document: number, url, action (close | reopen), state ({previous, current}), changed, comment? ({posted}; present only when a comment was given).`},"dry-run":{type:`boolean`,description:`Report what would change, mutate nothing`},verbose:{type:`boolean`,description:`Emit detailed debug output`}},async run({args:t}){let n=readBodySource(t.comment??void 0,t[`comment-file`]??void 0,{flags:{text:`--comment`,file:`--comment-file`}}),r=await runIssueState(createRealExecutor$1(),{cwd:process.cwd(),ref:t.ref,action:e,comment:n,repo:t.repo??void 0,dryRun:t[`dry-run`]===!0,verbose:t.verbose===!0||isEnvVerbose()});t.json===!0?createCliOutput(!0).json(r):(I.info(formatIssueState(r,t[`dry-run`]===!0)),t[`dry-run`]===!0&&n!==void 0&&r.comment?.posted===!0&¬e(n,`[dry-run] Comment that would be posted`))}})}const Rd=defineIssueStateCommand(`close`),zd=defineIssueStateCommand(`reopen`),Bd=/^(pr|issue)#(\d+)$/,Vd=[`nit`,`pre-existing`];function parseSource(e){let t=Bd.exec(e),n=t?.[1],r=t?.[2];if(n===void 0||r===void 0||n!==`pr`&&n!==`issue`)throw new T(`findings:add: --source must look like pr#<n> or issue#<n>, got: "${e}"`);return{kind:n,number:Number(r)}}function validateClass(e){if(e===`human-decision`)throw new T(`findings:add: class human-decision does not go in the ledger -- file an issue instead (a human-decision finding needs a human triaging it, not a queued file).`);if(e===`nit`||e===`pre-existing`)return e;throw new T(`findings:add: --class must be one of ${Vd.join(`, `)}, got: "${e}"`)}function runFindingsAdd(e,t){let n=parseSource(t.source),r=validateClass(t.class),i=localToday(/* @__PURE__ */ new Date),a=`${i}-${n.kind}${String(n.number)}-${findingSlug(t.title)}.md`,s=parseFindingFileName(a);if(s===null||s.date!==i||s.origin.kind!==n.kind||s.origin.number!==n.number)throw new T(`findings:add: internal error -- generated filename "${a}" did not round-trip`);let c=`${$}/${a}`,l=w.join(e,c);if(o(l))throw new T(`findings:add: refusing to overwrite an existing finding: ${c}`);let d=w.join(e,$),f=!o(d)||!b(d).isDirectory(),p=composeFindingFile({title:t.title,class:r,body:t.body},{phase:`manual`,sourceKind:n.kind,sourceIssueNumber:n.number,sourceIssueUrl:null});return t.dryRun||(u(d,{recursive:!0}),C(l,p,`utf-8`)),{ok:!0,path:c,title:t.title,class:r,origin:n,createdLedgerDir:f,dryRun:t.dryRun}}function resolveBody(e){if(e===void 0&&process.stdin.isTTY===!0)throw new T(`findings:add: refusing to read a finding body from an interactive terminal -- pass --body-file, or pipe the body in on stdin.`);let t=readBodySource(void 0,e??`-`,{flags:{text:`--body`,file:`--body-file`}});if(t===void 0)throw new T(`findings:add: internal error -- body resolved to undefined`);return t}const Hd=j({meta:{name:`findings:add`,description:`Author one finding into .agent/findings/, correct-by-construction. Usage: pnpm exec bst findings:add --class <nit|pre-existing> --source <pr|issue>#<n> --title <t>. The first finding creates .agent/findings/, which turns on the agent's backlog run for the repo; set .tooling.json#agent.backlog to false to stop it.`},args:{class:{type:`string`,required:!0,description:`nit | pre-existing`},source:{type:`string`,required:!0,description:`The PR/issue that surfaced this finding: pr#<n> | issue#<n>`},title:{type:`string`,required:!0,description:`The finding's title`},"body-file":{type:`string`,description:`Read the finding's body from this file (default: stdin)`},"dry-run":{type:`boolean`,description:`Print the planned path without writing`},json:{type:`boolean`,description:`Emit one JSON document: path, title, class (nit | pre-existing), origin ({kind (pr | issue), number}), createdLedgerDir, dryRun.`}},run({args:e}){let t=e[`dry-run`]===!0,n=t&&e[`body-file`]===void 0?``:resolveBody(e[`body-file`]),r=runFindingsAdd(process.cwd(),{class:e.class,source:e.source,title:e.title,body:n,dryRun:t}),i=createCliOutput(e.json===!0);i.json(r),r.dryRun?i.text(`[dry-run] Would write ${r.path}`):(i.text(`Wrote ${r.path}`),r.createdLedgerDir&&i.notice(`Created ${$}/ -- the backlog sweep is now armed for this repo.`))}});function readFindingSummary(e){let t;try{t=p(e,`utf-8`)}catch{return{title:null,class:null,deferrals:0}}let n=parseFindingHeader(t);return{title:n.title,class:n.class,deferrals:countDeferralNotes(t)}}function ageInDays(e){let t=Date.parse(`${e}T00:00:00Z`);return Number.isNaN(t)?0:Math.max(0,Math.floor((Date.now()-t)/864e5))}function runFindingsList(e){let t=w.join(e,$);if(!o(t)||!b(t).isDirectory())return{ok:!0,entries:[],strays:[]};let n=[],r=[];for(let e of h(t).toSorted()){let i=parseFindingFileName(e);if(i===null){r.push(e);continue}let a=readFindingSummary(w.join(t,e));n.push({file:e,date:i.date,origin:i.origin,class:a.class,title:a.title,ageDays:ageInDays(i.date),deferrals:a.deferrals})}return{ok:!0,entries:n,strays:r}}function renderText(e){let t=[];e.entries.length===0&&e.strays.length===0&&t.push(`No pending findings.`);for(let n of e.entries){let e=n.deferrals>0?` (deferred ${String(n.deferrals)}x)`:``;t.push(`${n.file} [${n.class??`?`}] ${n.title??`(untitled)`} (${String(n.ageDays)}d)${e}`)}for(let n of e.strays)t.push(`STRAY (does not parse, silently invisible to the backlog sweep): ${n}`);return t.join(`
|
|
6154
|
+
`)}const Ud=j({meta:{name:`findings:list`,description:`List the pending findings in .agent/findings/, plus any strays.`},args:{json:{type:`boolean`,description:`Emit one JSON document: entries ([{file, date, origin ({kind (pr | issue), number}), class (or null), title (or null), ageDays, deferrals}]), strays (file names that do not parse). class and title are null when the file is unreadable.`}},run({args:e}){let t=runFindingsList(process.cwd()),n=createCliOutput(e.json===!0);n.json(t),n.text(renderText(t))}});function resolveFindingPath(e,t){let n=w.join(e,$),r=t.includes(`/`)?t:`${$}/${t}`,i=w.resolve(e,r),a=w.relative(n,i);if(a.startsWith(`..`)||w.isAbsolute(a))throw new T(`findings:resolve: refuses a name outside ${$}/: ${t}`);return i}function candidateFindingPath(e,t){let n=resolveFindingPath(e,t);if(o(n)||t.endsWith(`.md`))return n;let r=resolveFindingPath(e,`${t}.md`);return o(r)?r:n}function runFindingsResolve(e,t,n){if(t.length===0)throw new T(`findings:resolve: at least one finding file is required`);let r=t.map(t=>({name:t,fullPath:candidateFindingPath(e,t)})),i=r.filter(({fullPath:e})=>!o(e)).map(({name:e})=>e);if(i.length>0)throw new T(`findings:resolve: no such finding file(s): ${i.join(`, `)}`);let a=r.map(({fullPath:t})=>w.relative(e,t)),s=n.defer===void 0?`delete`:`defer`;if(n.dryRun)return{ok:!0,action:s,dryRun:!0,files:a};if(n.defer!==void 0){let e=localToday(/* @__PURE__ */ new Date);for(let{fullPath:t}of r){let r=p(t,`utf-8`);C(t,`${r}\n**Deferred (${e}):** ${n.defer}\n`)}}else for(let{fullPath:e}of r)y(e);return{ok:!0,action:s,dryRun:!1,files:a}}const Wd=j({meta:{name:`findings:resolve`,description:`Delete finding file(s) from .agent/findings/, or --defer to append a note instead. pnpm exec bst findings:resolve <name>... [--defer <note>].`},args:{defer:{type:`string`,description:`Append a deferred note instead of deleting`},"dry-run":{type:`boolean`,description:`Preview the action without writing`},json:{type:`boolean`,description:`Emit one JSON document: action (delete | defer), dryRun, files.`}},run({args:e}){let t=runFindingsResolve(process.cwd(),e._,{defer:e.defer,dryRun:e[`dry-run`]===!0}),n=createCliOutput(e.json===!0);n.json(t);let r;r=t.dryRun?t.action===`defer`?`Would defer`:`Would delete`:t.action===`defer`?`Deferred`:`Deleted`;for(let e of t.files)n.text(`${r} ${e}`)}});function runGit(e,t){try{return{ok:!0,stdout:N(`git`,e,{cwd:t,encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`],maxBuffer:536870912})}}catch{return{ok:!1,stdout:``}}}function unretiredId(e){let t=e.split(`/`),n=t.length<2?-1:t.lastIndexOf(`retired`,t.length-2);return n<0?null:[...t.slice(0,n),...t.slice(n+1)].join(`/`)}function claims(e,t){let n=w.join(e,`plan-path`);if(o(n)){let e=p(n,`utf-8`).replace(/\n$/,``);return e===t||e===unretiredId(t)}return u(e,{recursive:!0}),C(n,`${t}\n`),!0}function*candidateNames(e,t){yield e,yield`${e}-${t}`;for(let n=2;;n++)yield`${e}-${t}-${String(n)}`}function resolvePlanWorkspace(e,t){let n=w.resolve(t,e);if(!o(n))throw new T(`no such plan file: ${e}`);let r=runGit([`rev-parse`,`--show-toplevel`],t);if(!r.ok)throw new T(`not inside a git repository: ${t}`);let i=_(r.stdout.trim()),a=_(n),s=w.basename(a,`.md`);if(s===``||s===`.`||s===`..`)throw new T(`cannot derive a workspace name from: ${e}`);let c=a.startsWith(`${i}${w.sep}`)?w.relative(i,a).split(w.sep).join(`/`):a,l=w.join(i,...`.superpowers/sdd`.split(`/`));for(let e of candidateNames(s,w.basename(w.dirname(a)))){let t=w.join(l,e);if(claims(t,c))return C(w.join(l,`.gitignore`),`*
|
|
6150
6155
|
`),t}return l}function resolveOutPath(e,t){let n=w.resolve(t,e),r=w.dirname(n);if(!o(r))throw new T(`--out directory does not exist: ${r}`);return n}function resolveCommit(e,t,n){let r=runGit([`rev-parse`,`--verify`,`--quiet`,`${e}^{commit}`],n);if(!r.ok)throw new T(`bad ${t}: ${e}`);return r.stdout.trim()}function gitOut(e,t){let n=runGit(e,t);if(!n.ok)throw new T(`git ${e[0]??``} failed in ${t}`);return n.stdout}function forkRedirect(e,t,n,r,i){let a=runGit([`merge-base`,n,r],i);return a.ok?`; they share merge-base ${a.stdout.trim()} -- if ${e} is a branch that moved on, run \`git merge-base ${e} ${t}\` and pass that SHA as <base>`:``}function writeReviewPackage(e,t,n,r,i){let a=i===void 0?void 0:resolveOutPath(i,r),o=resolveCommit(t,`base`,r),s=resolveCommit(n,`head`,r);if(!runGit([`merge-base`,`--is-ancestor`,o,s],r).ok){let e=forkRedirect(t,n,o,s,r);throw new T(`head is not a descendant of base: ${t}..${n}${e}`)}let c=`${o}..${s}`,l=Number(gitOut([`rev-list`,`--count`,c],r).trim());if(l===0)throw new T(`empty commit range: ${t}..${n}`);let u=[`# Review package: ${t}..${n}`,``,`## Commits`,gitOut([`log`,`--oneline`,c],r),`## Files changed`,gitOut([`diff`,`--stat`,c],r),`## Diff`,gitOut([`diff`,`-U10`,c],r)].join(`
|
|
6151
6156
|
`),d=`review-${o.slice(0,7)}..${s.slice(0,7)}.diff`,f=a??w.join(resolvePlanWorkspace(e,r),d);return C(f,u),{path:f,commits:l,bytes:Buffer.byteLength(u)}}function isTaskLabel(e,t){return taskLabelId(e)===t}function extractTask(e,t){let n=e.split(`
|
|
6152
|
-
`),r=fencedLines(n),i=-1,a=null,o=n.length;for(let e=0;e<n.length;e++){if(r[e]===!0)continue;let s=n[e]??``,c=
|
|
6157
|
+
`),r=fencedLines(n),i=-1,a=null,o=n.length;for(let e=0;e<n.length;e++){if(r[e]===!0)continue;let s=n[e]??``,c=Qc.exec(s),l=$c.exec(s);if(a===null){c!==null&&isTaskLabel(c[2]??``,t)?(i=e,a={kind:`heading`,level:(c[1]??``).length}):l!==null&&isTaskLabel(l[2]??``,t)&&(i=e,a={kind:`box`,indent:(l[1]??``).length});continue}let u=a.kind===`heading`&&c!==null&&(c[1]??``).length<=a.level,d=a.kind===`box`&&(c!==null||l!==null&&(l[1]??``).length<=a.indent);if(u||d){o=e;break}}return i<0?null:`${n.slice(i,o).join(`
|
|
6153
6158
|
`).trimEnd()}\n`}function writeTaskBrief(e,t,n,r){let i;try{i=p(w.resolve(n,e),`utf-8`)}catch{throw new T(`no such plan file: ${e}`)}let a=extractTask(i,t);if(a===null)throw new T(`task ${t} not found in ${e} (no heading or checkbox starting "Task ${t}")`);let o=r===void 0?w.join(resolvePlanWorkspace(e,n),`task-${t}-brief.md`):resolveOutPath(r,n);return C(o,a),{path:o,lines:a.split(`
|
|
6154
|
-
`).length-1}}const
|
|
6155
|
-
`)}const
|
|
6156
|
-
`)}async function runCli(e){let t=e.subCommands,n=
|
|
6159
|
+
`).length-1}}const Gd={type:`positional`,required:!0,description:`Path to the plan document`};function nonEmpty(e,t,n){if(e===``)throw new T(`${n}: <${t}> must not be empty`);return e}const Kd=j({meta:{name:`plan:workspace`,description:`Print (and create) a plan's scratch directory. It sits under .superpowers/sdd/ and is ignored by version control.`},args:{plan:Gd,json:{type:`boolean`,description:`Emit one JSON document: path.`}},run({args:e}){let t=resolvePlanWorkspace(nonEmpty(e.plan,`plan`,`plan:workspace`),process.cwd()),n=createCliOutput(e.json===!0);n.json({ok:!0,path:t}),n.text(t)}}),qd=j({meta:{name:`plan:brief`,description:`Write one plan task's text to a brief file`},args:{plan:Gd,"task-number":{type:`positional`,required:!0,description:`The task's label, as its heading or checkbox names it: a number, or a number and one lowercase letter (18a)`},out:{type:`string`,description:`Write here instead of the plan workspace`},json:{type:`boolean`,description:`Emit one JSON document: path, lines.`}},run({args:e}){let t=nonEmpty(e.plan,`plan`,`plan:brief`),n=e[`task-number`];if(!/^[1-9][0-9]*[a-z]?$/.test(n))throw new T(`plan:brief: <task-number> must be a positive integer, optionally followed by one lowercase letter (18, 18a), got: ${n}`);let r=writeTaskBrief(t,n,process.cwd(),e.out),i=createCliOutput(e.json===!0);i.json({ok:!0,...r}),i.text(`wrote ${r.path}: ${String(r.lines)} lines`)}}),Jd=j({meta:{name:`plan:review-package`,description:`Write the commit list, stat, and diff for base..head to one file. Refuses an empty range, or a head that does not descend from base.`},args:{plan:Gd,base:{type:`positional`,required:!0,description:`The commit the task started from`},head:{type:`positional`,required:!0,description:`The task's last commit`},out:{type:`string`,description:`Write here instead of the plan workspace`},json:{type:`boolean`,description:`Emit one JSON document: path, commits, bytes.`}},run({args:e}){let t=writeReviewPackage(nonEmpty(e.plan,`plan`,`plan:review-package`),nonEmpty(e.base,`base`,`plan:review-package`),nonEmpty(e.head,`head`,`plan:review-package`),process.cwd(),e.out),n=createCliOutput(e.json===!0);n.json({ok:!0,...t}),n.text(`wrote ${t.path}: ${String(t.commits)} commit(s), ${String(t.bytes)} bytes`)}});function renderStatus(e){let t=e.next??`(none)`,n=e.nextTask===null||taskLabelId(t)===e.nextTask?``:`Task ${e.nextTask} -- `,r=[`${e.plan}${e.retired?` (retired)`:``}: ${String(e.checked)} done, ${String(e.outstanding)} outstanding, ${String(e.declined)} declined`,`next: ${n}${t}${e.onlyRetireLeft?` -- only the retire task is left`:``}`];e.deferred>0&&r.splice(1,0,`${String(e.deferred)} deferred to a later task`);for(let t of e.notes)r.push(` [${t.kind}] ${t.task}: ${t.text}`);for(let t of e.deferrals)t.failed!==null&&r.push(` [deferred -- not counted] ${t.task}: ${describeDeferralCheck(t.failed)}.`);return r.join(`
|
|
6160
|
+
`)}const Yd=j({meta:{name:`plan:status`,description:`Report a plan's progress from its checkboxes`},args:{plan:Gd,json:{type:`boolean`,description:`Emit one JSON document: plan, retired, checked, outstanding, declined, deferred, deferrals ([{task, target (a task label string or null), failed (empty-reason | no-target-label | no-own-task | target-not-found | target-not-later | target-is-retire | no-carried-box, or null when valid)}]), next (or null), nextTask (a task label string such as "3" or "18a", or null), onlyRetireLeft, notes ([{task, kind (progress | blocked | declined | deferred), text}]). next is null when there is none; nextTask is null when no task label encloses it.`}},run({args:e}){let t=nonEmpty(e.plan,`plan`,`plan:status`),n;try{n=p(w.resolve(process.cwd(),t),`utf-8`)}catch{throw new T(`plan:status: no such plan file: ${t}`)}let r=planStatus(n,t),i=createCliOutput(e.json===!0);i.json({ok:!0,...r}),i.text(renderStatus(r))}});function probeCliPath(e){try{let t=b(e,{throwIfNoEntry:!1});return t===void 0?`missing`:t.isDirectory()?`directory`:`file`}catch{return`missing`}}function classifyWithHook(e,t,n){let r=classifyThrown(e,t),i=n?.(e);return i===void 0?r:{...r,message:ae(i)}}function drain(e){return new Promise(t=>{e.write(``,()=>t())})}function applyVerbosityFromArgs(e){setLogLevel(resolveLogLevel({verbose:e.includes(`--verbose`)||e.includes(`-v`),trace:e.includes(`--trace`)}))}function guardCommand(e,t,n){let{run:r,subCommands:i}=e,a={...e};return r!==void 0&&(a.run=async e=>{try{return await r(e)}catch(e){if(!(!t&&e instanceof Error&&(e.name===`FatalError`||e.name===`TransientError`)))throw e;console.error(classifyWithHook(e,!1,n).message),process.exitCode=1;return}}),i!==void 0&&(a.subCommands=async()=>{let e=typeof i==`function`?await i():await i,r={};for(let[i,a]of Object.entries(e))r[i]=async()=>guardCommand(typeof a==`function`?await a():await a,t,n);return r}),a}function firstSentence(e){let t=/^[\s\S]*?\.(?=\s+[A-Z])/.exec(e);return t===null?e:t[0]}async function renderTableUsage(e,t){return oe(shortenChildren(e),t)}function shortenChildren(e){let{subCommands:t}=e;return t===void 0?e:{...e,subCommands:async()=>{let e=typeof t==`function`?await t():await t,n={};for(let[t,r]of Object.entries(e))n[t]=async()=>{let e=typeof r==`function`?await r():await r,t=typeof e.meta==`function`?await e.meta():await e.meta,n=t?.description;return{...shortenChildren(e),meta:{...t,...n===void 0?{}:{description:firstSentence(n).replace(/\s+/g,` `)}}}};return n}}}async function showTableUsage(e,t){console.log(await renderTableUsage(e,t)+`
|
|
6161
|
+
`)}async function runCli(e){let t=e.subCommands,n=j({meta:{name:e.name,version:e.version,description:e.description},subCommands:t}),exitWithJsonError=async(t,n,r,i)=>{recordJsonError(buildErrorDocument({command:t,version:e.version,kind:n,message:r,detail:i})),(process.exitCode??0)===0&&(process.exitCode=1),flushJsonOutput(),await Promise.all([drain(process.stdout),drain(process.stderr)]),process.exit(process.exitCode??0)},r=process.argv.slice(2);applyVerbosityFromArgs(r);let i=resolveCommandName(r);if(!resolveJsonMode(r)){let i=findUnknownFlags(r,t,probeCliPath);i.kind!==`none`&&(console.error(formatFlagCheckMessage(i)),process.exitCode=1,await Promise.all([drain(process.stdout),drain(process.stderr)]),process.exit(process.exitCode??0)),e.banner!==void 0&&console.error(e.banner),await ce(guardCommand(n,verboseRequested(r),e.describeError),{showUsage:showTableUsage}),await Promise.all([drain(process.stdout),drain(process.stderr)]),process.exit(process.exitCode??0)}setJsonMode(!0),setJsonNoticeSink(e=>createCliOutput(!0).notice(e)),installJsonExitNet(e.name,i,e.version,jsonDocumentWritten);let a=findUnknownFlags(r,t,probeCliPath);a.kind!==`none`&&await exitWithJsonError(a.command,`usage`,formatFlagCheckMessage(a));let o=asCommandDef(i!==void 0&&i in t?t[i]:void 0);if(i===void 0||o===void 0||!commandDeclaresJson(o)){let e;e=i===void 0?`No command specified.`:o===void 0?`Unknown command ${i}.`:`Command ${i} does not support --json.`,await exitWithJsonError(i,`usage`,e)}try{await se(n,{rawArgs:r})}catch(t){let n=classifyWithHook(t,verboseRequested(r),e.describeError);await exitWithJsonError(i,n.kind,n.message,n.detail)}flushJsonOutput()||await exitWithJsonError(i,`runtime`,`${i} --json completed without recording a JSON payload. This is a bug in the command's --json support -- it does not necessarily mean the command's underlying action failed.`),await Promise.all([drain(process.stdout),drain(process.stderr)]),process.exit(process.exitCode??0)}setLogLevel(resolveLogLevel({})),setForgejoLogger(I);const Xd=`0.109.0`,Zd={"repo:sync":cs,"checks:run":Io,"checks:failures":Ul,"lint:types":Yl,"lint:report":Xl,"release:changesets":Es,"release:trigger":As,"workflow:dispatch":Sl,"changesets:merge":El,"pr:create":jl,"pr:ready":Ml,"pr:reopen":Nl,"pr:retarget":Pl,"pr:update":Fl,"release:simple":Il,"release:assets":Ll,"release:snapshot":Hl,"docker:publish":Zl,"docker:build":Ql,"docker:check":ru,"docker:sweep":iu,"hooks:audit":ou,"hooks:sync":su,"setup:secrets":fu,"setup:agent":uu,"webhook:send":pu,"coverage:summary":mu,"coverage:check":gu,"coverage:record":vu,"coverage:status":yu,"health:check":Iu,"health:raise":zu,"health:tighten":Vu,"health:summary":Uu,"health:record":Gu,"health:status":Ku,"chars:check":Xu,"ascii:check":Zu,"branch:prune":od,"docs:check":md,"docs:list":vd,"docs:delink":xd,"docs:relocate":Sd,"docs:retire":Td,"issue:view":Ed,"issue:list":Dd,"issue:comment":Od,"issue:create":kd,"issue:update":Ad,"issue:download":Md,"issue:label":Nd,"issue:unlabel":Pd,"issue:set-labels":Fd,"issue:close":Rd,"issue:reopen":zd,"findings:add":Hd,"findings:list":Ud,"findings:resolve":Wd,"plan:workspace":Kd,"plan:brief":qd,"plan:review-package":Jd,"plan:status":Yd,"work:status":xl,"work:start":bl,"work:end":yl};async function runBstCli(e={}){await runCli({name:`bst`,version:Xd,description:`Bootstrap and maintain standardized TypeScript project tooling`,banner:`@bensandee/tooling v${Xd}`,subCommands:{...Zd,...e},describeError:describeForgeError})}applyVerbosityFromArgs(process.argv.slice(2)),I.debug(describeEnvFileLoad(Le)),await runBstCli();export{};
|