@bensandee/tooling 0.113.0 → 0.114.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 +17 -14
- package/package.json +1 -1
package/dist/bin.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
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 T from"node:path";import{parseArgs as te,parseEnv as E,stripVTControlCharacters as ne}from"node:util";import{FatalError as D,TransientError as O,UnexpectedError as k,describeError as re,describeError as A,redact as ie,redact as j}from"@bensandee/common";import{defineCommand as M,renderUsage as ae,runCommand as oe,runMain as se}from"citty";import*as N from"@clack/prompts";import{isCancel as ce,select as le}from"@clack/prompts";import{execFileSync as P,execSync as ue,spawn as de,spawnSync as fe}from"node:child_process";import{z as F}from"zod";import pe from"json5";import{applyEdits as me,modify as he,parse as ge}from"jsonc-parser";import _e from"cross-spawn";import ve,{constants as 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 I 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=ie(re(e));if(!t)return{kind:n,message:r};let i=e instanceof Error&&typeof e.stack==`string`?ie(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=T.resolve(e),n;try{n=p(t,`utf8`)}catch(e){let n=e instanceof Error?e.message:String(e);throw new D(`${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(E(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.113.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(j(i));return}let a=[];(e.timestamps??!1)&&a.push(stamp()),t&&a.push(t),a.push(j(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}]`,j(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(N.log);const qe=!!process.env.CI,out=e=>console.log(e),L=Ke;function note(e,t){isJsonMode()||(qe?(t&&out(`--- ${t} ---`),out(e)):N.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 R=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&&(R.hasPayload&&Ke.debug(`output: a second json() call overwrote the first -- last call wins.`),R.payload=e,R.hasPayload=!0)},text:e=>{t||stdout(e)},notice:e=>{t?R.notices.push(j(e)):stdout(e)}}}function recordJsonError(e){R.error=e,R.hasError=!0}function buildFlushDocument(){let e;if(R.hasError?e=R.error:R.hasPayload&&(e=R.payload),e!==void 0){if(R.notices.length===0)return e;if(isJsonRecord(e)){let{notices:t}=e;return{...e,notices:isStringArray(t)?[...t,...R.notices]:R.notices}}return{payload:e,notices:R.notices}}}function flushJsonOutput(){let e=buildFlushDocument();return e!==void 0&&(stdout(JSON.stringify(e)),R.wrote=!0,!0)}function jsonDocumentWritten(){return R.wrote}function defaultGitRunner(e,t,n){try{let r=P(`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=F.union([F.string(),F.object({url:F.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 D(`${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}let i=F.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 D(`FORGEJO_REPOSITORY environment variable is required`);if(!i)throw new D(`RELEASE_TOKEN environment variable is required`)}return null}if(o.hostname===`github.com`)return null;if(!i)throw new D(`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 D(`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 D(`Not an issue number or issue URL: "${t}" (expected e.g. 273 or https://host/owner/repo/issues/273)`)}var RepoTargetEmptyError=class extends D{constructor(){super(`No repository URL was given.`)}},RepoTargetMismatchError=class extends D{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 D(`Not a repository URL: "${e}"`);let[,n,r]=t;if(n===void 0||r===void 0)throw new D(`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=F.record(F.string(),F.string()),Qe=F.looseObject({name:F.string(),version:F.string().optional(),onFail:F.string().optional()}),$e=F.looseObject({name:F.string().optional(),version:F.string().optional(),private:F.boolean().optional(),type:F.string().optional(),scripts:Ze.optional(),dependencies:Ze.optional(),devDependencies:Ze.optional(),peerDependencies:Ze.optional(),bin:F.union([F.string(),Ze]).optional(),exports:F.unknown().optional(),main:F.string().optional(),types:F.string().optional(),typings:F.string().optional(),engines:Ze.optional(),devEngines:F.looseObject({runtime:F.union([Qe,F.array(Qe)]).optional()}).optional(),repository:F.union([F.string(),F.looseObject({url:F.string()})]).optional(),packageManager:F.string().optional(),publishConfig:F.unknown().optional()}),et=F.looseObject({extends:F.union([F.string(),F.array(F.string())]).optional(),include:F.array(F.string()).optional(),exclude:F.array(F.string()).optional(),files:F.array(F.string()).optional(),references:F.array(F.looseObject({path:F.string()})).optional(),compilerOptions:F.record(F.string(),F.unknown()).optional()}),tt=F.looseObject({$schema:F.string().optional(),extends:F.array(F.string()).optional()});function parseTsconfig(e){let t=et.safeParse(ge(e));return t.success?t.data:{}}function parseRenovateJson(e){try{let t=tt.safeParse(pe.parse(e));return t.success?t.data:{}}catch{return{}}}const nt=F.looseObject({commit:F.union([F.boolean(),F.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 z=[`crowdedDirectories`,`circularDependencies`,`fanInOutliers`,`fanOutOutliers`],rt=[`fanInOutliers`,`fanOutOutliers`,`crowdedDirectories`],B=[`fanInOutliers`,`fanOutOutliers`,`crowdedDirectories`],it=[`linesOfCode`],at=F.object({linesOfCode:F.number().int().nonnegative().optional()}),ot=F.object({crowdedDirectories:F.number().int().nonnegative(),circularDependencies:F.number().int().nonnegative().optional(),fanInOutliers:F.number().int().nonnegative().optional(),fanOutOutliers:F.number().int().nonnegative().optional()}),st=ot.extend(at.shape).extend({sha:F.string(),timestamp:F.string()}),ct=new Set(B),lt=F.preprocess(e=>typeof e==`object`&&e?Object.fromEntries(Object.entries(e).filter(([e])=>ct.has(e))):e,F.partialRecord(F.enum(B),F.record(F.string(),F.number().int().nonnegative()))),ut=ot.extend({moduleCeilings:lt.optional(),sizeBudgets:F.record(F.string(),F.number().int().nonnegative()).optional()});function parseHealthBaseline(e){let t;try{t=JSON.parse(e)}catch(e){throw new D(`health-baseline.json is not valid JSON: ${A(e)}`)}let n=ut.safeParse(t);if(!n.success)throw new D(`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 D(`Could not parse ${r} as JSON: ${A(e)}`)}let a=t.safeParse(i,{reportInput:!0});if(!a.success){let e=a.error.issues.flatMap(e=>formatIssue$1(e).split(`
|
|
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=ie(re(e));if(!t)return{kind:n,message:r};let i=e instanceof Error&&typeof e.stack==`string`?ie(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=T.resolve(e),n;try{n=p(t,`utf8`)}catch(e){let n=e instanceof Error?e.message:String(e);throw new D(`${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(E(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.114.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(j(i));return}let a=[];(e.timestamps??!1)&&a.push(stamp()),t&&a.push(t),a.push(j(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}]`,j(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(N.log);const qe=!!process.env.CI,out=e=>console.log(e),L=Ke;function note(e,t){isJsonMode()||(qe?(t&&out(`--- ${t} ---`),out(e)):N.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 R=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&&(R.hasPayload&&Ke.debug(`output: a second json() call overwrote the first -- last call wins.`),R.payload=e,R.hasPayload=!0)},text:e=>{t||stdout(e)},notice:e=>{t?R.notices.push(j(e)):stdout(e)}}}function recordJsonError(e){R.error=e,R.hasError=!0}function buildFlushDocument(){let e;if(R.hasError?e=R.error:R.hasPayload&&(e=R.payload),e!==void 0){if(R.notices.length===0)return e;if(isJsonRecord(e)){let{notices:t}=e;return{...e,notices:isStringArray(t)?[...t,...R.notices]:R.notices}}return{payload:e,notices:R.notices}}}function flushJsonOutput(){let e=buildFlushDocument();return e!==void 0&&(stdout(JSON.stringify(e)),R.wrote=!0,!0)}function jsonDocumentWritten(){return R.wrote}function defaultGitRunner(e,t,n){try{let r=P(`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=F.union([F.string(),F.object({url:F.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 D(`${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}let i=F.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 D(`FORGEJO_REPOSITORY environment variable is required`);if(!i)throw new D(`RELEASE_TOKEN environment variable is required`)}return null}if(o.hostname===`github.com`)return null;if(!i)throw new D(`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 D(`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 D(`Not an issue number or issue URL: "${t}" (expected e.g. 273 or https://host/owner/repo/issues/273)`)}var RepoTargetEmptyError=class extends D{constructor(){super(`No repository URL was given.`)}},RepoTargetMismatchError=class extends D{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 D(`Not a repository URL: "${e}"`);let[,n,r]=t;if(n===void 0||r===void 0)throw new D(`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=F.record(F.string(),F.string()),Qe=F.looseObject({name:F.string(),version:F.string().optional(),onFail:F.string().optional()}),$e=F.looseObject({name:F.string().optional(),version:F.string().optional(),private:F.boolean().optional(),type:F.string().optional(),scripts:Ze.optional(),dependencies:Ze.optional(),devDependencies:Ze.optional(),peerDependencies:Ze.optional(),bin:F.union([F.string(),Ze]).optional(),exports:F.unknown().optional(),main:F.string().optional(),types:F.string().optional(),typings:F.string().optional(),engines:Ze.optional(),devEngines:F.looseObject({runtime:F.union([Qe,F.array(Qe)]).optional()}).optional(),repository:F.union([F.string(),F.looseObject({url:F.string()})]).optional(),packageManager:F.string().optional(),publishConfig:F.unknown().optional()}),et=F.looseObject({extends:F.union([F.string(),F.array(F.string())]).optional(),include:F.array(F.string()).optional(),exclude:F.array(F.string()).optional(),files:F.array(F.string()).optional(),references:F.array(F.looseObject({path:F.string()})).optional(),compilerOptions:F.record(F.string(),F.unknown()).optional()}),tt=F.looseObject({$schema:F.string().optional(),extends:F.array(F.string()).optional()});function parseTsconfig(e){let t=et.safeParse(ge(e));return t.success?t.data:{}}function parseRenovateJson(e){try{let t=tt.safeParse(pe.parse(e));return t.success?t.data:{}}catch{return{}}}const nt=F.looseObject({commit:F.union([F.boolean(),F.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 z=[`crowdedDirectories`,`circularDependencies`,`fanInOutliers`,`fanOutOutliers`],rt=[`fanInOutliers`,`fanOutOutliers`,`crowdedDirectories`],B=[`fanInOutliers`,`fanOutOutliers`,`crowdedDirectories`],it=[`linesOfCode`],at=F.object({linesOfCode:F.number().int().nonnegative().optional()}),ot=F.object({crowdedDirectories:F.number().int().nonnegative(),circularDependencies:F.number().int().nonnegative().optional(),fanInOutliers:F.number().int().nonnegative().optional(),fanOutOutliers:F.number().int().nonnegative().optional()}),st=ot.extend(at.shape).extend({sha:F.string(),timestamp:F.string()}),ct=new Set(B),lt=F.preprocess(e=>typeof e==`object`&&e?Object.fromEntries(Object.entries(e).filter(([e])=>ct.has(e))):e,F.partialRecord(F.enum(B),F.record(F.string(),F.number().int().nonnegative()))),ut=ot.extend({moduleCeilings:lt.optional(),sizeBudgets:F.record(F.string(),F.number().int().nonnegative()).optional()});function parseHealthBaseline(e){let t;try{t=JSON.parse(e)}catch(e){throw new D(`health-baseline.json is not valid JSON: ${A(e)}`)}let n=ut.safeParse(t);if(!n.success)throw new D(`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 D(`Could not parse ${r} as JSON: ${A(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 D(`Invalid ${r} (${n.block}) -- ${i}:\n${e.join(`
|
|
5
5
|
`)}`)}return a.data}function tolerantBlock(e){return F.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
6
|
`)}return` ${t}: ${e.message}`}const dt=/^[a-z0-9][a-z0-9-]*$/,ft=F.union([F.object({file:F.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.`}),F.object({glob:F.string().min(1).meta({description:`Glob matched against repo-relative paths under the target.`}),aggregate:F.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.`}),F.object({script:F.string().min(1).meta({description:"Package script run as `pnpm run --silent <script>`; it reports one number through the reserved measure marker."}),files:F.array(F.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=F.strictObject({enabled:F.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:F.array(F.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:F.array(F.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:F.array(F.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:F.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:F.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:F.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:F.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:F.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:F.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:F.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:F.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:F.record(F.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:F.partialRecord(F.enum(rt),F.record(F.string(),F.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."})}),V=F.strictObject({enabled:F.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:F.array(F.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:F.array(F.string()).optional().meta({description:`Named offender categories to add to the default deny-list (e.g. "math")`}),allow:F.array(F.string()).optional().meta({description:`Codepoints (as U+XXXX) to drop from the effective deny-list`}),treatAsProse:F.array(F.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=F.strictObject({strictTypeAware:F.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=F.strictObject({ignore:F.array(F.string()).optional().meta({description:`Globs of changed paths that cannot affect any test, dropped from the selection. Unions with bst's defaults (docs/**, .changeset/**, .agent/findings/**), which it never replaces.`}),fullSuite:F.array(F.string()).optional().meta({description:`Globs of changed paths that force the full suite instead of a selection, e.g. a package whose source is injected into every test at build time.`}),alwaysRun:F.array(F.string()).optional().meta({description:`Test files run on every selective step, whatever the change. For a test that reads the tree, dist/, or starts a built bin: the import graph cannot see those edges.`})}),gt=tolerantBlock(ht),_t=F.strictObject({add:F.array(F.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:F.array(F.string()).optional().meta({description:`Check steps to skip, unioned with the built-in CI defaults (never replacing them). Supports glob patterns.`}),runOnVersionPr:F.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.`}),selectiveTests:F.union([F.literal(!1),ht]).optional().meta({description:"Run only the tests a branch reaches through imports, on an in-run gate (`checks:run --changed`). `false` disables the setting for the repo; the object tunes the selection. Omit to use bst's defaults. A full suite is always what CI, the host backstop and `pnpm check` run -- this only ever narrows the test step of a step that opted in."})}),vt=F.strictObject({history:F.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:F.string().optional().meta({description:`Orphan branch name for coverage history (default: 'bst/coverage-metrics')`}),tolerancePp:F.number().nonnegative().optional().meta({description:`Tolerance in percentage points for baseline comparison (default: 0.1)`}),floorPp:F.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:F.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:F.array(F.string()).optional().meta({description:`Glob patterns replacing the default coverage source scope (['src/**']) in the generated vitest.config.ts.`}),exclude:F.array(F.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).`})}),yt=F.strictObject({history:F.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:F.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.'})}),bt=F.enum([`typescript`,`javascript`,`none`]),xt=F.array(F.string()),St=F.strictObject({name:F.string().meta({description:`Service name`}),url:F.string().meta({description:`Health check URL`}),status:F.number().int().optional().meta({description:`Expected HTTP status code`})}),Ct=F.strictObject({composeFiles:F.array(F.string()).optional().meta({description:`Compose files to use`}),envFile:F.string().optional().meta({description:`Environment file for compose`}),services:F.array(F.string()).optional().meta({description:`Services to check (default: all)`}),healthChecks:F.array(St).optional().meta({description:`Health check definitions`}),buildCommand:F.array(F.string()).optional().meta({description:`Command to build images before checking (e.g. ["pnpm", "image:build"])`}),buildCwd:F.string().optional().meta({description:`Working directory for build command`}),smoketest:F.array(F.string()).optional().meta({description:`Command to run as a smoketest after health checks pass (e.g. ["pnpm", "test:smoke"])`}),smoketestCwd:F.string().optional().meta({description:`Working directory for smoketest command`}),timeoutMs:F.number().int().positive().optional().meta({description:`Overall timeout in milliseconds`}),pollIntervalMs:F.number().int().positive().optional().meta({description:`Poll interval in milliseconds`})}),wt=F.strictObject({dockerfile:F.string().optional().meta({description:`Path to Dockerfile relative to package (falls back to convention when omitted)`}),context:F.string().optional().meta({description:`Docker build context relative to package (falls back to convention, default '.')`}),buildArgs:F.record(F.string(),F.string()).optional().meta({description:"Build args passed to `docker build` for this package. Values support ${VAR} and ${VAR:-default} expansion against process.env."}),imageName:F.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:F.string().optional().meta({description:`Version used for docker:publish tags; overrides the version resolved from the enclosing package.`}),publish:F.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.`})}),Tt=F.record(F.string(),wt),Et=F.record(F.string(),tolerantBlock(wt)),Dt=F.object({...Ct.shape,healthChecks:F.array(tolerantBlock(St)).optional()}),Ot=/^(?!refs\/)(?!.*\/\/)(?!.*\.\.)(?!.*\/$)(?!.*\.lock$)[A-Za-z0-9][A-Za-z0-9._/-]*$/,kt=F.string().regex(Ot,`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`),At=F.looseObject({agent:F.looseObject({enabled:F.boolean().optional()}).optional()});function agentEnabledIn(e){try{return parseToolingConfigSlice(e,At,{block:`agent`})?.agent?.enabled===!0}catch{return!1}}const jt=/* @__PURE__ */ new Set([`node_modules`,`vendor`,`dist`,`public`,`build`,`coverage`,`venv`,`__pycache__`,`target`,`out`,`tmp`]),Mt=/* @__PURE__ */ new Set([`.ts`,`.tsx`,`.mts`,`.cts`]),Nt=/* @__PURE__ */ new Set([`.js`,`.jsx`,`.mjs`,`.cjs`]);function sourceGlob(e,t=`src`){return`${t}/**/*.{${[...e===`typescript`?Mt:Nt].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(`.`)||jt.has(i.name))continue;scanSource(w.join(e,i.name),r,n);continue}if(isRootConfigFile(r))continue;let a=w.extname(i.name);if(Mt.has(a)){n.ts=!0;return}Nt.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,F.object({stack:bt.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 Pt={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=Pt[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 Ft=/* @__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 Ft)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 N.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){N.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 N.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)&&(N.cancel(`Cancelled.`),process.exit(0)),l=e,l!==`none`){let e=await N.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)&&(N.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 N.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)&&(N.cancel(`Cancelled.`),process.exit(0)),f=e}let b=detectCiPlatform(e);if(s&&b===`none`&&!y){let e=await N.select({message:`CI workflow`,initialValue:`forgejo`,options:[{value:`forgejo`,label:`Forgejo Actions`},{value:`github`,label:`GitHub Actions`},{value:`none`,label:`None`}]});isCancelled$1(e)&&(N.cancel(`Cancelled.`),process.exit(0)),m=e}let x=r.hasReleaseItConfig||r.hasSimpleReleaseConfig||r.hasChangesetsConfig;if(s&&!x&&!y){let e=await N.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)&&(N.cancel(`Cancelled.`),process.exit(0)),g=e}let S=t?.publishNpm??!1;if(s&&g!==`none`&&getPublishablePackages(e,c).length>0){let e=await N.confirm({message:`Publish packages to npm?`,initialValue:!1});isCancelled$1(e)&&(N.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 N.confirm({message:`Publish Docker images to a registry?`,initialValue:!1});isCancelled$1(e)&&(N.cancel(`Cancelled.`),process.exit(0)),C=e}return N.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 It=/* @__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`&&It.has(n)}const Lt=_e.sync,Rt=_e;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=fe(i,a,s);if(shouldRetryViaShim(c.error)&&(c=Lt(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 D(`Path traversal detected: ${t} resolves outside target directory`)}function normalizeEol(e){return e.replaceAll(`\r
|
|
@@ -37,7 +37,7 @@ 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 nr=F.object({registryHost:F.string().optional()});function resolveGenTimeHost(e){let t=e.read(`.tooling.json`);if(t)try{let e=nr.safeParse(JSON.parse(t));if(e.success&&e.data.registryHost&&e.data.registryHost.length>0)return e.data.registryHost}catch(e){L.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 rr=F.object({postReleaseHook:F.string().optional(),postReleaseHookSecrets:F.array(F.string()).optional()}),ir=F.object({releaseAssets:F.array(Ut).optional()}),ar=F.object({versionStamp:F.array(Wt).optional()}),or=F.object({deploy:Kt.optional()});function getDeployConfig(e){let t=e.read(`.tooling.json`);if(t)try{let e=or.safeParse(JSON.parse(t));return e.success?e.data.deploy:void 0}catch(e){L.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=rr.safeParse(JSON.parse(t));return e.success?e.data.postReleaseHook:void 0}catch(e){L.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=rr.safeParse(JSON.parse(t));return e.success?e.data.postReleaseHookSecrets:void 0}catch(e){L.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=ir.safeParse(JSON.parse(t));return e.success?!!e.data.releaseAssets&&e.data.releaseAssets.length>0:!1}catch(e){return L.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=ar.safeParse(JSON.parse(t));return e.success?!!e.data.versionStamp&&e.data.versionStamp.length>0:!1}catch(e){return L.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 sr=[`.ts`,`.tsx`],cr=[`.js`,`.jsx`,`.mjs`,`.cjs`];function defaultExtensions(e){return e===`typescript`?sr:e===`javascript`?cr:[]}const lr=F.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`),lr,{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,lr,{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 ur=[`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=ur.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 dr=`@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(dr)}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 fr=F.object({unmanagedDevDependencies:xt.optional()});function readUnmanagedDevDepNames(e){let t=parseToolingConfigSlice(e.read(`.tooling.json`),fr,{block:`unmanagedDevDependencies`});return new Set(t?.unmanagedDevDependencies??[])}const pr=`@bensandee/forgejo-cli`;function wantsForgejoCli(e){return e.config.ci!==`forgejo`||isWorkspacePackage(e,`@bensandee/forgejo-cli`)?!1:!readUnmanagedDevDepNames(e).has(pr)}const mr=`commit-and-tag-version`;function wantsCommitAndTagVersion(e){return e.config.releaseStrategy===`simple`&&!readUnmanagedDevDepNames(e).has(mr)}const hr=`24.13.0`,gr=`>=${hr}`;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 _r={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`},vr={test:`vitest run`,"test:coverage":`vitest run --coverage`,lint:`oxlint`,"lint:report":`bst lint:report`,knip:`knip`},yr={test:`pnpm -r test`,"test:coverage":`vitest run --coverage`,lint:`oxlint`,"lint:report":`bst lint:report`,knip:`knip`},br={typecheck:`tsc --noEmit`,"lint:types":`bst lint:types`},xr={typecheck:`pnpm -r --parallel run typecheck`,"lint:types":`bst lint:types`},Sr={build:`tsdown`,dev:`tsdown --watch`},Cr={build:`pnpm -r build`};function standardScripts(e){let t=e.structure===`monorepo`,n={..._r};return e.stack!==`none`&&Object.assign(n,t?yr:vr),e.stack===`typescript`&&Object.assign(n,t?xr:br),e.stack!==`none`&&e.builder===`tsdown`&&Object.assign(n,t?Cr:Sr),n}const wr={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[mr]={"@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 wr&&!matchesManagedScript(r[e]??``,wr[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 Tr=/* @__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 Tr)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`)):L.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`),F.object({chars:V.optional(),ascii:V.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:gr},n.push(`set engines.node ${gr}`)),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.113.0`),e.config.useEslintPlugin&&e.config.stack!==`none`&&(n[`@bensandee/eslint-plugin`]=isWorkspacePackage(e,`@bensandee/eslint-plugin`)?`workspace:*`:`0.18.0`),wantsAgentCli(e)&&(n[dr]=`0.4.0`),wantsForgejoCli(e)&&(n[pr]=`0.11.2`),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&&L.warn(`package.json: pnpm-forwarded check flags may be dropped. ${c}`);let l=diagnoseToolchainScripts(o.scripts??{});return l&&L.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)+`
|
|
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 nr=F.object({registryHost:F.string().optional()});function resolveGenTimeHost(e){let t=e.read(`.tooling.json`);if(t)try{let e=nr.safeParse(JSON.parse(t));if(e.success&&e.data.registryHost&&e.data.registryHost.length>0)return e.data.registryHost}catch(e){L.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 rr=F.object({postReleaseHook:F.string().optional(),postReleaseHookSecrets:F.array(F.string()).optional()}),ir=F.object({releaseAssets:F.array(Ut).optional()}),ar=F.object({versionStamp:F.array(Wt).optional()}),or=F.object({deploy:Kt.optional()});function getDeployConfig(e){let t=e.read(`.tooling.json`);if(t)try{let e=or.safeParse(JSON.parse(t));return e.success?e.data.deploy:void 0}catch(e){L.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=rr.safeParse(JSON.parse(t));return e.success?e.data.postReleaseHook:void 0}catch(e){L.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=rr.safeParse(JSON.parse(t));return e.success?e.data.postReleaseHookSecrets:void 0}catch(e){L.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=ir.safeParse(JSON.parse(t));return e.success?!!e.data.releaseAssets&&e.data.releaseAssets.length>0:!1}catch(e){return L.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=ar.safeParse(JSON.parse(t));return e.success?!!e.data.versionStamp&&e.data.versionStamp.length>0:!1}catch(e){return L.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 sr=[`.ts`,`.tsx`],cr=[`.js`,`.jsx`,`.mjs`,`.cjs`];function defaultExtensions(e){return e===`typescript`?sr:e===`javascript`?cr:[]}const lr=F.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`),lr,{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,lr,{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 ur=[`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=ur.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 dr=`@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(dr)}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 fr=F.object({unmanagedDevDependencies:xt.optional()});function readUnmanagedDevDepNames(e){let t=parseToolingConfigSlice(e.read(`.tooling.json`),fr,{block:`unmanagedDevDependencies`});return new Set(t?.unmanagedDevDependencies??[])}const pr=`@bensandee/forgejo-cli`;function wantsForgejoCli(e){return e.config.ci!==`forgejo`||isWorkspacePackage(e,`@bensandee/forgejo-cli`)?!1:!readUnmanagedDevDepNames(e).has(pr)}const mr=`commit-and-tag-version`;function wantsCommitAndTagVersion(e){return e.config.releaseStrategy===`simple`&&!readUnmanagedDevDepNames(e).has(mr)}const hr=`24.13.0`,gr=`>=${hr}`;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 _r={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`},vr={test:`vitest run`,"test:coverage":`vitest run --coverage`,lint:`oxlint`,"lint:report":`bst lint:report`,knip:`knip`},yr={test:`pnpm -r test`,"test:coverage":`vitest run --coverage`,lint:`oxlint`,"lint:report":`bst lint:report`,knip:`knip`},br={typecheck:`tsc --noEmit`,"lint:types":`bst lint:types`},xr={typecheck:`pnpm -r --parallel run typecheck`,"lint:types":`bst lint:types`},Sr={build:`tsdown`,dev:`tsdown --watch`},Cr={build:`pnpm -r build`};function standardScripts(e){let t=e.structure===`monorepo`,n={..._r};return e.stack!==`none`&&Object.assign(n,t?yr:vr),e.stack===`typescript`&&Object.assign(n,t?xr:br),e.stack!==`none`&&e.builder===`tsdown`&&Object.assign(n,t?Cr:Sr),n}const wr={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[mr]={"@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 wr&&!matchesManagedScript(r[e]??``,wr[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 Tr=/* @__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 Tr)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`)):L.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`),F.object({chars:V.optional(),ascii:V.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:gr},n.push(`set engines.node ${gr}`)),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.114.0`),e.config.useEslintPlugin&&e.config.stack!==`none`&&(n[`@bensandee/eslint-plugin`]=isWorkspacePackage(e,`@bensandee/eslint-plugin`)?`workspace:*`:`0.18.0`),wantsAgentCli(e)&&(n[dr]=`0.4.0`),wantsForgejoCli(e)&&(n[pr]=`0.11.2`),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&&L.warn(`package.json: pnpm-forwarded check flags may be dropped. ${c}`);let l=diagnoseToolchainScripts(o.scripts??{});return l&&L.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
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:gr},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
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=me(n,he(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 L.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 Er=[`src`,`test`,`*.ts`],Dr=[`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!==Dr.length||!n.every((e,t)=>e===Dr[t]))return;let r=w.join(w.dirname(t),`test`);e.exists(r)&&L.warn(`${t}: "include" is ${formatInclude(n)}, so a test/ directory beside it sits outside tsc --noEmit and its types go unchecked. Consider "include": ${formatInclude(Er)}.`)}const Or=`@bensandee/config/tsconfig/node`;function extendsNodePreset(e){return e===void 0?!1:Array.isArray(e)?e.includes(Or):e===Or}const kr=`verbatimModuleSyntax`;function buildGeneratedTsconfig(e,t,n={}){let r=n.dir??`.`,i=n.include??Er,a={extends:t,...n.verbatimModuleSyntax?{compilerOptions:{[kr]:!0}}:{},...e.exists(w.join(r,`src`))?{include:[...i]}:{}};return JSON.stringify(a,null,2)+`
|
|
43
43
|
`}function withMergedVerbatimKey(e){let t=parseTsconfig(e);return t.compilerOptions={...t.compilerOptions,[kr]:!0},JSON.stringify(t,null,2)+`
|
|
@@ -6069,9 +6069,9 @@ Otherwise, read \`.agent/guides/merge-prep.md\` and follow it. That guide holds
|
|
|
6069
6069
|
`)}const za=/\d{4}-\d{2}-\d{2}/;function datedStatusValue(e){let t=e.split(`
|
|
6070
6070
|
`).slice(0,30).join(`
|
|
6071
6071
|
`),n=La.exec(t)?.[2]?.trim().replace(Ba,``);if(n!==void 0&&Da.test(n))return za.exec(n)?.[0]}const Ba=/^\*{1,2}\s*/;function formatDatedStatus(e,t){return`**${e} ${t}**`}function matchStatusBlock(e){let t=La.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(`
|
|
6072
|
-
`)+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 Va=[`### 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)."],Ha=["- 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.`],Ua="- Relative imports carry `.ts` with no build step or `nodenext` resolution; otherwise prefer extensionless.";function importRule(e){return e.structure===`monorepo`?Ua:e.builder===`none`||e.projectType===`node`?"- Relative imports always carry the `.ts` extension.":e.builder===`custom`?Ua:"- Prefer extensionless imports; if an extension is required, use `.ts` over `.js`."}const Wa="- 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 Wa+(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`.",Wa,``,`#### 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 Ga={red:`Red:`,noTest:`No test:`},Ka=[`# 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: \`${Ga.red} <test name> failed: <reason>\` when the test ran red first, or \`${Ga.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 \`${Ga.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(`
|
|
6073
|
-
`),qa=[`# 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.
|
|
6074
|
-
`),Ja=[`# 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 \`${Ga.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 \`${Ga.red}\` or \`${Ga.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(`
|
|
6072
|
+
`)+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 Va=[`### 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)."],Ha=["- 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.`],Ua="- Relative imports carry `.ts` with no build step or `nodenext` resolution; otherwise prefer extensionless.";function importRule(e){return e.structure===`monorepo`?Ua:e.builder===`none`||e.projectType===`node`?"- Relative imports always carry the `.ts` extension.":e.builder===`custom`?Ua:"- Prefer extensionless imports; if an extension is required, use `.ts` over `.js`."}const Wa="- 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 Wa+(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`.",Wa,``,`#### 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; a plan-only unit has one approved document, the plan): 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 Ga={red:`Red:`,noTest:`No test:`},Ka=[`# 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: \`${Ga.red} <test name> failed: <reason>\` when the test ran red first, or \`${Ga.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 \`${Ga.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(`
|
|
6073
|
+
`),qa=[`# 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. The one call also ticks the `Retire this plan` box, retires each live spec the `Implements:` line links, and stages what it moved or rewrote, so you tick nothing by hand, run no second retire, and `git add` nothing afterwards. It leaves a spec open when another live plan implements it or the status of the spec says it is partly delivered; otherwise the spec takes the verb of the plan. Pass `--no-specs` to retire the plan alone when it implements one phase of its spec, or is superseded while the spec lives on. The `## Decisions` of a retired plan is a record: do not edit it.',``,"`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(Ca)} and none of ${codeList(wa)}, so a status naming a shipped phase stays active while it also says an open word. A spec whose status says ${codeList(Ta)} 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(`
|
|
6074
|
+
`),Ja=[`# 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. A plan-only unit (next section) has one approved document, the plan: approving it lets you write the code.`,``,`## Which tier`,``,`**Full tier: spec, then plan.** Use it when any of these hold:`,``,`- there are real alternatives a person should weigh before tasks are worth writing;`,`- the change touches an invariant this repo's CLAUDE.md lists, or crosses package boundaries;`,"- it changes a public contract: a wire format, generated output for synced repos, or a command's `--json` shape;",`- the work has several independent parts;`,`- the likely failure is a wrong approach rather than a wrong detail.`,``,"**Plan-only tier: one plan, approved once.** Everything else: a fix whose location is known, a follow-up to approved work, work whose approach is plain once the problem is stated. The plan lives under `docs/plans/` and opens, before its tasks, with `## Why` (the problem and who it is for, in a few sentences), `## Done when` (the checkable outcomes) and `## Rejected alternatives` (each with its reason, an established tool among them where one fits). It may carry `## Egress` (the outside hosts the work needs, or `None`). It links no spec.",``,"Whoever writes the first document picks the tier and says so in one line under its title: `Tier: plan-only -- <reason>` or `Tier: full -- <reason>`. A session proposes the tier before writing; a person who disagrees says so at review.",``,"**Keep small documents small.** A plan of five tasks or fewer has no separate rules section (a rule that recurs goes in the one task that needs it, or in `## Why`) and a Starting position (the tree facts the plan builds on, checked against a named commit) of ten lines or fewer. A spec for work of that size keeps each section to what its decision needs.",``,`## 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 \`${Ga.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.`,``,`### The Decisions section`,``,"End the plan with a `## Decisions` section after the retire task. It holds no task and no checkboxes, so the last task still retires the plan. One line per ruling: what was decided, why, and what it costs if wrong. Record rulings only (a deviation from the plan, a contradiction resolved, a person's call acted on), never actions: the forge and `git log` hold those. Write the line in the same commit as the task it affected. Only while the plan is live: after it retires, a run records its rulings in its comment and does not edit the retired plan.",``,`## 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 \`${Ga.red}\` or \`${Ga.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(`
|
|
6075
6075
|
`);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(`
|
|
6076
6076
|
`)}function mergePrepEnabled(e){return parseToolingConfigSlice(e.read(`.tooling.json`),F.object({mergePrep:F.literal(!1).optional()}),{block:`mergePrep`})?.mergePrep!==!1}const Ya=[`# 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>`."],Xa=[`- **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=[...Ya];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(...Xa),t.join(`
|
|
6077
6077
|
`)}const Za=[`# 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=[...Za];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(`
|
|
@@ -6083,7 +6083,7 @@ Otherwise, read \`.agent/guides/merge-prep.md\` and follow it. That guide holds
|
|
|
6083
6083
|
`;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(`
|
|
6084
6084
|
`),i=r.slice(0,n.startLine),a=r.slice(n.endLine+1),o=i.join(`
|
|
6085
6085
|
`).replace(/\n+$/,``),s=a.join(`
|
|
6086
|
-
`).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 $a=`.agent/guides`;function agentGuides(e,t,n,r,i){return[{name:`testing.md`,trigger:`change source, or write or change a test`,body:Ka,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:Ja,enabled:!0},{name:`subagents.md`,trigger:`hand work to a subagent, or run a plan through subagents`,body:`# Subagents
|
|
6086
|
+
`).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 $a=`.agent/guides`;function agentGuides(e,t,n,r,i){return[{name:`testing.md`,trigger:`change source, or write or change a test`,body:Ka,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 -- which also retires the specs it completes. 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:Ja,enabled:!0},{name:`subagents.md`,trigger:`hand work to a subagent, or run a plan through subagents`,body:`# Subagents
|
|
6087
6087
|
|
|
6088
6088
|
**A subagent knows only what you hand it.** Write the brief as its whole world: never your session's history, and never "see above".
|
|
6089
6089
|
|
|
@@ -6103,11 +6103,11 @@ Run subagents at the same time only for problems that share no files and no stat
|
|
|
6103
6103
|
|
|
6104
6104
|
- The plan's checkboxes are the progress record. Tick a task's box and commit once its review is clean. After a context reset, \`pnpm exec bst plan:status <plan>\` names the next open task; trust it and \`git log\` over your memory, and never re-run a ticked task.
|
|
6105
6105
|
- \`pnpm exec bst plan:workspace <plan>\` prints the plan's own git-ignored scratch directory for briefs, reports, review packages, and fix-round notes. Nothing that must outlive the run goes there.
|
|
6106
|
-
- Before the first task, check the plan for tasks that contradict each other or the spec. Rule on each (the spec wins) and record the ruling
|
|
6106
|
+
- Before the first task, check the plan for tasks that contradict each other or the spec. Rule on each (the spec wins) and record the ruling in the plan's \`## Decisions\`.
|
|
6107
6107
|
- Per task: note the base commit, run \`pnpm exec bst plan:brief <plan> <n>\`, and give one implementer the brief file it writes plus a report file to write back. Then run \`pnpm exec bst plan:review-package <plan> <base> <head>\` and have a separate reviewer judge that file against the brief, for both spec compliance and quality. Never tell a reviewer what not to flag.
|
|
6108
|
-
- 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
|
|
6109
|
-
- 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.
|
|
6110
|
-
- Keep every ruling where the human will read it:
|
|
6108
|
+
- 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 in the plan's \`## Decisions\`. 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.
|
|
6109
|
+
- 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 in the plan's \`## Decisions\` with what it costs if wrong.
|
|
6110
|
+
- Keep every ruling where the human will read it: while the plan is live, record each in its \`## Decisions\` with what it costs if wrong and copy that section into the pull request body; once it is retired, list them all in your final message and in the pull request body.
|
|
6111
6111
|
- 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:qa,enabled:!0},{name:`debugging.md`,trigger:`fix a bug, a failing test, or unexpected behaviour`,body:`# Debugging
|
|
6112
6112
|
|
|
6113
6113
|
**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.
|
|
@@ -6165,7 +6165,7 @@ Project guidance for Claude Code.
|
|
|
6165
6165
|
|
|
6166
6166
|
All notable changes to this project will be documented in this file.
|
|
6167
6167
|
`,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)+`
|
|
6168
|
-
`;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){L.error(`${String(e.length)} file(s) could not be synced by ${t} -- fix them by hand:`);for(let t of e)L.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.
|
|
6168
|
+
`;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){L.error(`${String(e.length)} file(s) could not be synced by ${t} -- fix them by hand:`);for(let t of e)L.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.114.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(`
|
|
6169
6169
|
`);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(`
|
|
6170
6170
|
`)}`),r.push(`## Ground rules
|
|
6171
6171
|
|
|
@@ -6312,8 +6312,11 @@ export default defineConfig({ extends: [recommended] });
|
|
|
6312
6312
|
`),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(`
|
|
6313
6313
|
`),exitCode:0})}const Vd=M({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]===`
|
|
6314
6314
|
`&&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 D(`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 D(`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 D(`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 D(`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 D(`docs:relocate: at least one source is required`);for(let e of t)if(!e.endsWith(`.md`))throw new D(`docs:relocate: source must be a .md file: ${e}`);let r=n.endsWith(`/`)||isExistingDirectory(e,n);if(t.length>1&&!r)throw new D(`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 D(`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 D(`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(`
|
|
6315
|
-
`),exitCode:0}}const Hd=M({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 D(`Usage: pnpm exec bst docs:relocate <src>... <dest>`);let r=n.at(-1);if(r===void 0)throw new D(`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`)}`}
|
|
6316
|
-
`),exitCode:0}}const Gd=M({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: ${Aa.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 D(`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 D(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 D(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 D(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 D(`--title is required.`):e}}const Kd=M({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):L.info(formatIssue(t))}}),qd=M({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}):L.info(formatIssueList(t))}}),Jd=M({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 D(`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):L.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 Yd=M({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))L.info(t)}}),Xd=M({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):(L.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 Zd={exists:isReadableFile,write:(e,t)=>{u(w.dirname(e),{recursive:!0}),C(e,t)}};var AttachmentExistsError=class extends D{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 D(`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 D(`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:Cn});if(r.status===401||r.status===403||r.status===404)throw new D(`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 D(`Cannot download "${n.name}": HTTP ${String(r.status)} -- this attachment is permanently unavailable; retrying will not help.`);if(!r.ok)throw new O(`Failed to download "${n.name}": HTTP ${String(r.status)}`);let i=new Uint8Array(await r.arrayBuffer());if(i.byteLength!==n.size)throw new D(`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??Zd,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(`
|
|
6315
|
+
`),exitCode:0}}const Hd=M({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 D(`Usage: pnpm exec bst docs:relocate <src>... <dest>`);let r=n.at(-1);if(r===void 0)throw new D(`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`)}`}function git(e,t){try{return P(`git`,e,{cwd:t,stdio:[`ignore`,`pipe`,`pipe`]}),null}catch(e){return(typeof e==`object`&&e&&`stderr`in e?String(e.stderr):String(e)).trim().split(`
|
|
6316
|
+
`)[0]??``}}function createGitRetireStager(e){return{stage(t){if(git([`rev-parse`,`--is-inside-work-tree`],e)!==null)return{skipped:`not a git checkout`};let n=t.filter(t=>o(w.join(e,...t.split(`/`)))||git([`ls-files`,`--error-unmatch`,t],e)===null);if(n.length===0)return{staged:[]};let r=git([`add`,`-A`,`--`,...n],e);return r===null?{staged:[...n]}:{skipped:`git add failed: ${r}`}}}}const Ud=/^\d{4}-\d{2}-\d{2}$/;function validateRetireArgs(e,t,n){if(!isRetireVerb(n.status))throw new D(`docs:retire: unrecognized --status "${n.status}" (expected one of: ${Aa.join(`, `)})`);let r=n.status;if(n.date!==void 0&&!Ud.test(n.date))throw new D(`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 D(`docs:retire: --status ${r} but --shipped starts with "${ja[e.verb]}:"; drop the lead-in or fix --status`);if(e.body.trim()===``)throw new D(`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 D(`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 D(`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&&Fa.test(n.text))return n}function skipHistoricalBanner(e,t){let n=nextChunk(e,t);return n===void 0||!Ra.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 D(`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 D(`docs:retire: --shipped is required to add the "${ja[n]}:" paragraph (${t} has none yet)`);let e=`> ${ja[n]}: ${i.body}`;f=insertBlockAtBoundary(f,m,e);let r=i.leadInDropped?` (dropped the "${ja[n]}:" lead-in --shipped repeated)`:``;record(`retire-paragraph`,`${t}: add "${ja[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 tickRetireBox(e,t){let n=parsePlanBoxes(e).filter(e=>e.retireTask&&!e.checked&&!e.declined),[r]=n;if(r===void 0)return{content:e,ticked:!1};if(n.length>1)throw new D(`docs:retire: ${t} has ${String(n.length)} unchecked "Retire this plan" boxes; tick or remove all but one`);let i=e.split(`
|
|
6317
|
+
`);return i[r.line]=(i[r.line]??``).replace(`[ ]`,`[x]`),{content:i.join(`
|
|
6318
|
+
`),ticked:!0}}function isLivePlanPath(e,t){let n=classifyTrackedDoc(e,t);return n!==null&&!n.retired&&n.kind!==`spec`}function cascadeSpecs(e,t,n,r){let i=e.exists(t)?t:n,a=e.readFile(i);if(a===void 0)return{retire:[],leftOpen:[]};let{extraDirs:o}=resolveDocsConfigFromReader({read:t=>e.readFile(t)}),s,plansImplementing=r=>(s??=e.listMarkdownFiles().filter(e=>e!==t&&e!==n&&isLivePlanPath(e,o)).map(t=>({file:t,targets:implementsLinkTargets(e.readFile(t)??``,w.posix.dirname(t))})),s.filter(e=>e.targets.has(r)).map(e=>e.file)),c={retire:[],leftOpen:[]},l=[...implementsLinkTargets(a,w.posix.dirname(i))].toSorted();for(let i of l){if(i===t||i===n||!i.endsWith(`.md`))continue;let a=e.readFile(i);if(a===void 0)continue;let s=retireDestination(i,r);if(s===i||isLivePlanPath(i,o))continue;let l=plansImplementing(i);if(l.length>0)c.leftOpen.push({path:i,reason:`another live plan implements it: ${l.join(`, `)}`});else if(claimsPartialDelivery(a))c.leftOpen.push({path:i,reason:`its status claims partial delivery`});else{if(e.exists(s))throw new D(`docs:retire: refusing to overwrite existing destination: ${s} (for linked spec ${i})`);c.retire.push({src:i,dest:s,tick:!1})}}return c}function rewritesOf(e,t,n){let r=[];for(let i of e.rewrites){let e=i.edits.filter(e=>e.newTarget===t||i.file===t&&!n.has(e.newTarget)).map(e=>({line:e.line,oldTarget:e.oldTarget,newTarget:e.newTarget}));e.length>0&&r.push({file:i.file,edits:e})}return r}function retireDocument(e){let{exec:t,target:n,relocatePlan:r,verb:i,shipped:a,opts:o}=e,{src:s,dest:c}=n,l=r.moves.find(e=>e.from===s);if(l===void 0)throw new D(`docs:retire: internal error -- no move planned for ${s}`);let u=new Set(r.moves.map(e=>e.to)),d=r.rewrites.find(e=>e.file===c),f=l.status===`pending`?s:c,p=d?.content??t.readFile(f);if(p===void 0)throw new D(`docs:retire: cannot read ${f}`);let m=o.date??datedStatusValue(p)??e.fallbackDate??localToday(/* @__PURE__ */ new Date),{content:h,ticked:g}=n.tick?tickRetireBox(p,s):{content:p,ticked:!1},{content:_,summary:v,edits:y}=applyLifecycleEdits(h,c,i,m,a),b=delinkDocument(_,w.posix.dirname(c)),x=b.content;b.linkEdits.length>0&&v.push(`de-linked ${String(b.linkEdits.length)} link(s) pointing outside docs/`),b.bannerAdded&&v.push(`added the historical banner`),b.skipped!==void 0&&v.push(`banner skipped -- ${b.skipped}`);let S=d!==void 0||x!==p?{file:c,content:x,edits:d?.edits??[]}:void 0,C=rewritesOf(r,c,u);return{payload:{verb:i,date:m,src:s,dest:c,move:{from:l.from,to:l.to,status:l.status},lifecycle:y,rewrites:C,delink:{linkEdits:b.linkEdits.length,bannerAdded:b.bannerAdded,skipped:b.skipped??null},changed:l.status===`pending`||S!==void 0||C.length>0,ticked:g,dryRun:o.dryRun===!0,specs:[],leftOpen:[],staged:[]},write:S,summary:v}}function formatRetireLines(e,t){let n=[];n.push(e.move.status===`pending`?`move: ${e.src} -> ${e.dest}`:`move: ${e.src} -> ${e.dest} (already done)`);for(let t of e.rewrites)for(let e of t.edits)n.push(` ${t.file}:${String(e.line)}: ${e.oldTarget} -> ${e.newTarget}`);for(let e of t)n.push(` ${e}`);return n}function runDocsRetire(e,t,n){let r={verbose:n.verbose??!1},{verb:i,dest:a,shipped:o}=validateRetireArgs(e,t,n),s=n.specs===!1?{retire:[],leftOpen:[]}:cascadeSpecs(e,t,a,i),c={src:t,dest:a,tick:!0},l=buildRelocatePlan(e,[c,...s.retire].map(e=>({from:e.src,to:e.dest}))),u=retireDocument({target:c,relocatePlan:l,verb:i,shipped:o,fallbackDate:void 0,exec:e,opts:n}),d=s.retire.map(t=>retireDocument({target:t,relocatePlan:l,verb:i,shipped:o,fallbackDate:u.payload.date,exec:e,opts:n})),f=[u,...d];debug(r,`docs:retire: move ${t} -> ${a} and ${String(d.length)} spec(s), ${String(s.leftOpen.length)} left open`);let p=new Set(f.map(e=>e.payload.dest)),m=l.rewrites.filter(e=>!p.has(e.file));for(let e of f)e.write!==void 0&&m.push(e.write);let h={...u.payload,changed:l.moves.some(e=>e.status===`pending`)||m.length>0,specs:d.map(e=>e.payload),leftOpen:s.leftOpen},g=f.flatMap(e=>formatRetireLines(e.payload,e.summary));for(let e of s.leftOpen)g.push(`left open: ${e.path} -- ${e.reason}`);let _=[];if(n.dryRun===!0)g.push(`docs:retire: dry run -- nothing written.`);else{applyRelocatePlan(e,{moves:l.moves,rewrites:m}),g.push(`docs:retire: done.`);let t=new Set(m.map(e=>e.file));for(let e of l.moves)t.add(e.to),e.status===`pending`&&t.add(e.from);if(n.stager!==void 0&&h.changed){let e=n.stager.stage([...t].toSorted());`skipped`in e?_.push(`docs:retire: nothing staged -- ${e.skipped}`):(h.staged=e.staged,g.push(`docs:retire: staged ${String(e.staged.length)} path(s).`))}}return{payload:h,notices:_,text:g.join(`
|
|
6319
|
+
`),exitCode:0}}const Gd=M({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. A plan's run also retires each spec its Implements: line links, in the same move (--no-specs turns that off). pnpm exec bst docs:retire <plan.md> --status <verb> --shipped <text>.`},args:{status:{type:`string`,description:`Terminal verb: ${Aa.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 of the plan (specs keep theirs)`},specs:{type:`boolean`,default:!0,description:`Also retire each spec the plan's Implements: line links, unless another live plan implements it or its status claims partial delivery. --no-specs turns this off`},"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, ticked, dryRun, specs, leftOpen ([{path, reason}]), staged (the moved files' new paths and rewritten files staged in git, not the removed old paths; empty on a dry run or outside a git checkout). The top-level fields describe the plan; specs holds the same record for each linked spec retired with it. changed is false when the run writes nothing; ticked is true when the plan's Retire this plan box was (or, on a dry run, would be) ticked.`},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 D(`Usage: pnpm exec bst docs:retire <plan.md> --status <verb> --shipped <text>`);let{payload:r,notices:i,text:a,exitCode:o}=runDocsRetire(createRealRelocateExecutor(process.cwd()),n,{status:e.status,date:e.date,shipped:e.shipped,dest:e.dest,dryRun:e[`dry-run`]===!0,specs:e.specs,stager:createGitRetireStager(process.cwd()),verbose:e.verbose===!0||isEnvVerbose()});t.json(r);for(let e of i)t.notice(e);a!==``&&t.text(a),t.text(`docs:retire: only .md files were scanned for inbound references.`),process.exitCode=o}});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 D(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 D(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 D(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 D(`--title is required.`):e}}const Kd=M({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):L.info(formatIssue(t))}}),qd=M({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}):L.info(formatIssueList(t))}}),Jd=M({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 D(`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):L.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 Yd=M({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))L.info(t)}}),Xd=M({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):(L.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 Zd={exists:isReadableFile,write:(e,t)=>{u(w.dirname(e),{recursive:!0}),C(e,t)}};var AttachmentExistsError=class extends D{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 D(`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 D(`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:Cn});if(r.status===401||r.status===403||r.status===404)throw new D(`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 D(`Cannot download "${n.name}": HTTP ${String(r.status)} -- this attachment is permanently unavailable; retrying will not help.`);if(!r.ok)throw new O(`Failed to download "${n.name}": HTTP ${String(r.status)}`);let i=new Uint8Array(await r.arrayBuffer());if(i.byteLength!==n.size)throw new D(`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??Zd,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(`
|
|
6317
6320
|
`)}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 D(describeIssueNumberRequired(`pnpm exec bst issue:download 273`)):e instanceof AttachmentExistsError?new D(describeAttachmentExists(e,`--force`)):e}}const Qd=M({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):L.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 D{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(`
|
|
6318
6321
|
`)}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 D(describeIssueNumberRequired(`pnpm exec bst ${e} 273 agent/implement`))}throw e}}function defineIssueLabelCommand(e){return M({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):L.info(formatIssueLabel(n,t[`dry-run`]===!0))}})}const $d=defineIssueLabelCommand(`add`),ef=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 D(describeIssueNumberRequired(`pnpm exec bst issue:set-labels 273 agent/plan`)):e instanceof NoLabelsGivenError?new D(describeNoLabelsGiven(e,`--clear`)):e}}const tf=M({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):L.info(formatIssueSetLabels(n,e[`dry-run`]===!0))}});var EmptyCommentError=class extends D{constructor(){super(`The comment resolved to empty text.`)}};function rejectEmptyComment(e){if(e!==void 0&&e.trim()===``)throw new EmptyCommentError}var PullRequestStateError=class extends D{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 D{number;constructor(e){super(`#${String(e)} is an issue, not a pull request.`),this.number=e}},StateNotTakenError=class extends D{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 nf={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=nf[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 rf={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(`${rf[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(`
|
|
6319
6322
|
`)}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 D(describeIssueNumberRequired(`pnpm exec bst issue:${t.action} 273`));if(e instanceof EmptyCommentError)throw new D(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 D(describePullRequestState(e,{command:`issue:${e.action}`,advice:t}))}throw e}}function defineIssueStateCommand(e){return M({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):(L.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 af=defineIssueStateCommand(`close`),of=defineIssueStateCommand(`reopen`),sf=/^(pr|issue)#(\d+)$/,cf=[`nit`,`pre-existing`];function parseSource(e){let t=sf.exec(e),n=t?.[1],r=t?.[2];if(n===void 0||r===void 0||n!==`pr`&&n!==`issue`)throw new D(`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 D(`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 D(`findings:add: --class must be one of ${cf.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 D(`findings:add: internal error -- generated filename "${a}" did not round-trip`);let c=`${Q}/${a}`,l=w.join(e,c);if(o(l))throw new D(`findings:add: refusing to overwrite an existing finding: ${c}`);let d=w.join(e,Q),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 D(`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 D(`findings:add: internal error -- body resolved to undefined`);return t}const lf=M({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 ${Q}/ -- 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,Q);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(`
|
|
@@ -6324,4 +6327,4 @@ export default defineConfig({ extends: [recommended] });
|
|
|
6324
6327
|
`).trimEnd()}\n`}function writeTaskBrief(e,t,n,r){let i;try{i=p(w.resolve(n,e),`utf-8`)}catch{throw new D(`no such plan file: ${e}`)}let a=extractTask(i,t);if(a===null)throw new D(`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(`
|
|
6325
6328
|
`).length-1}}const ff={type:`positional`,required:!0,description:`Path to the plan document`};function nonEmpty(e,t,n){if(e===``)throw new D(`${n}: <${t}> must not be empty`);return e}const pf=M({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:ff,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)}}),mf=M({meta:{name:`plan:brief`,description:`Write one plan task's text to a brief file`},args:{plan:ff,"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 D(`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`)}}),hf=M({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:ff,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(`
|
|
6326
6329
|
`)}const gf=M({meta:{name:`plan:status`,description:`Report a plan's progress from its checkboxes`},args:{plan:ff,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 D(`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:ie(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 ae(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)+`
|
|
6327
|
-
`)}async function runCli(e){let t=e.subCommands,n=M({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 se(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 oe(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(L);const _f=`0.
|
|
6330
|
+
`)}async function runCli(e){let t=e.subCommands,n=M({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 se(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 oe(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(L);const _f=`0.114.0`,vf={"repo:sync":gs,"checks:run":Uo,"checks:failures":cu,"checks:select":du,"lint:types":_u,"lint:report":vu,"release:changesets":Ps,"release:trigger":Rs,"workflow:dispatch":Nl,"changesets:merge":Vl,"changesets:status":Wl,"changesets:post-status":Gl,"pr:create":Xl,"pr:ready":Zl,"pr:reopen":Ql,"pr:retarget":$l,"pr:update":eu,"release:simple":tu,"release:assets":nu,"release:snapshot":su,"docker:publish":yu,"docker:build":bu,"docker:check":Tu,"docker:sweep":Eu,"hooks:audit":Ou,"hooks:sync":ku,"setup:secrets":Pu,"setup:agent":Mu,"webhook:send":Fu,"coverage:summary":Iu,"coverage:check":Ru,"coverage:record":Bu,"coverage:status":Vu,"health:check":rd,"health:raise":od,"health:tighten":cd,"health:summary":ud,"health:record":fd,"health:status":pd,"chars:check":_d,"ascii:check":vd,"branch:prune":Ed,"docs:check":Pd,"docs:list":Rd,"docs:delink":Vd,"docs:relocate":Hd,"docs:retire":Gd,"issue:view":Kd,"issue:list":qd,"issue:comment":Jd,"issue:create":Yd,"issue:update":Xd,"issue:download":Qd,"issue:label":$d,"issue:unlabel":ef,"issue:set-labels":tf,"issue:close":af,"issue:reopen":of,"findings:add":lf,"findings:list":uf,"findings:resolve":df,"plan:workspace":pf,"plan:brief":mf,"plan:review-package":hf,"plan:status":gf,"work:status":Ml,"work:start":jl,"work:end":Al};async function runBstCli(e={}){await runCli({name:`bst`,version:_f,description:`Bootstrap and maintain standardized TypeScript project tooling`,banner:`@bensandee/tooling v${_f}`,subCommands:{...vf,...e},describeError:describeForgeError})}applyVerbosityFromArgs(process.argv.slice(2)),L.debug(describeEnvFileLoad(Le)),await runBstCli();export{};
|