buddy-agent-harness 1.1.0 → 1.3.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/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.cursor-plugin/plugin.json +1 -1
- package/CHANGELOG.md +25 -0
- package/dist/cli.mjs +86 -9
- package/dist/index.d.mts +10 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +92 -8
- package/dist/index.mjs.map +1 -1
- package/dist/skill-scripts/doctor.mjs +27 -27
- package/dist/skill-scripts/init.mjs +27 -27
- package/dist/skill-scripts/mcp.mjs +27 -27
- package/llms.txt +6 -5
- package/package.json +2 -1
- package/plugin.json +1 -1
- package/skills/doctor-buddy-agent-harness/README.md +1 -1
- package/skills/doctor-buddy-agent-harness/SKILL.md +9 -2
- package/skills/doctor-buddy-agent-harness/references/worktrees.md +17 -0
- package/skills/doctor-buddy-agent-harness/scripts/doctor.mjs +27 -27
- package/skills/enhance/SKILL.md +25 -16
- package/skills/enhance/references/agent-worktrees.md +59 -0
- package/skills/enhance/references/delegation.md +1 -1
- package/skills/enhance/references/list-identifiers.md +2 -2
- package/skills/enhance/references/references-as-links.history.md +9 -0
- package/skills/enhance/references/references-as-links.md +76 -0
- package/skills/enhance/references/session-scope.md +2 -2
- package/skills/enhance/scripts/doctor.mjs +27 -27
- package/skills/init-buddy-agent-harness/SKILL.md +8 -5
- package/skills/init-buddy-agent-harness/references/agent-worktrees.md +59 -0
- package/skills/init-buddy-agent-harness/scripts/doctor.mjs +27 -27
- package/skills/init-buddy-agent-harness/scripts/init.mjs +27 -27
- package/skills/repair/README.md +2 -2
- package/skills/repair/SKILL.md +3 -3
- package/skills/repair/scripts/doctor.mjs +27 -27
- package/skills/repair/scripts/mcp.mjs +27 -27
- package/src/diagnose-bridges/doctor-guidance.ts +66 -1
- package/src/diagnose-bridges/doctor.command.ts +2 -0
- package/src/diagnose-bridges/git-bridge-state.ts +5 -0
- package/src/diagnose-worktrees/diagnose-worktrees.ts +69 -0
- package/src/index.ts +1 -0
|
@@ -159,13 +159,13 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
159
159
|
|
|
160
160
|
`)}\n`:``}function composedSections(e){let t=[];e.preambleSources.length&&t.push({path:`(before the first heading)`,sources:e.preambleSources});let visit=(e,n)=>{let r=pathOf(n,e.title);t.push({path:r,sources:e.sources});for(let t of e.children)visit(t,r)};for(let t of e.children)visit(t,``);return t}function headingPaths(e){let t=[],visit=(e,n)=>{let r=pathOf(n,e.title);t.push(r);for(let t of e.children)visit(t,r)};for(let t of parseSections(e,()=>{}).children)visit(t,``);return t}function pickSections(e,t){let n=topLevel(e),r=fenceTracker(),i=[];for(let t of e.split(`
|
|
161
161
|
`)){let e=r(t)?null:En.exec(t);if(e&&e[1].length===n){i.push({key:sectionKey$1(e[2]??``),lines:[t]});continue}i.at(-1)?.lines.push(t)}let a=new Map(t.map(e=>[sectionKey$1(e.heading),e])),o=new Set,s=[];for(let e of i){let t=a.get(e.key);if(!t||o.has(e.key))continue;o.add(e.key);let[n,...r]=e.lines;if(t.merge===void 0){s.push(n,...r);continue}let i=r.findIndex(e=>e.trim()),c=i!==-1&&Tn.test(r[i])?r.filter((e,t)=>t!==i):r;s.push(n,`<!-- merge: ${t.merge} -->`,...c)}let c=t.filter(e=>!o.has(sectionKey$1(e.heading))).map(({heading:e})=>e);return{body:s.join(`
|
|
162
|
-
`),missing:c}}const On={"merge-sections":void 0,"first-wins":`replace`};function isLegacyMerge(e){return e===`merge-sections`||e===`first-wins`}function overriddenPlugins(e){let t=typeof e==`string`?[e]:Array.isArray(e)?e:void 0;if(t?.length&&t.every(e=>typeof e==`string`&&e.trim()))return[...new Set(t.map(e=>e.split(`/`)[0].trim()))]}function stepTargets(e){let t=typeof e==`string`?[e]:Array.isArray(e)?e:void 0;if(!t)return;let n=[];for(let e of t)if(typeof e==`string`)n.push(e);else if(isRecord$1(e)&&Object.keys(e).length===1)n.push(Object.keys(e)[0]);else return;return n}const flow=e=>`[${e.join(`, `)}]`;function legacyRewrite(e,t,n,r){let i=[],a={},o=e.merge;if(isLegacyMerge(o)){let e=On[o];a.merge=n===`project`?void 0:e,i.push({form:o,from:`merge: ${o}`,to:n===`project`?`no merge: a project section carries none`:e===void 0?`no merge: patch is the default`:`merge: ${e}`,reads:`it reads as patch`})}if(`overrides`in e&&i.push(overridesFinding(e,n,a)),n===`project`&&e.extends!==void 0&&!hasBody(t)){let t=stepTargets(e.extends);i.push({form:`project-selection`,from:`extends: ${t?flow(t):JSON.stringify(e.extends)}`,manual:`a pick now applies to the whole repository: run \`reference customize ${r} --extends ${t?.join(` `)??`<step>...`}\` at the root, then delete this file`,reads:`its extends is ignored`})}return{findings:i,keys:a}}function overridesFinding(e,t,n){let r=e.overrides,i=overriddenPlugins(r),a=`overrides: ${i?flow(Array.isArray(r)?r:[String(r)]):JSON.stringify(r)}`,o=`it is ignored`;if(t===`project`)return n.overrides=void 0,{form:`overrides`,from:a,to:`removed: a project section carries no extends`,reads:o};if(!i)return{form:`overrides`,from:a,manual:"`overrides` is not a list of plugin names",reads:o};let s=e.extends;if(s===void 0)return n.overrides=void 0,n.extends=i,{form:`overrides`,from:a,to:`extends: ${flow(i)}`,reads:o};let c=stepTargets(s),l=i.filter(e=>!c?.includes(e));return c&&!l.length?(n.overrides=void 0,{form:`overrides`,from:a,to:`removed: extends already names each plugin`,reads:o}):{form:`overrides`,from:a,manual:`\`extends\` is also written and does not name ${l.join(`, `)}; add ${l.length>1?`them`:`it`} to \`extends\` where it belongs, then remove \`overrides\``,reads:o}}function defaultLayoutFinding(e){return{form:`default-layout`,from:`references/${e}.md`,to:`references/${e}.default.md`,reads:`it is not read as the default`}}function warnLegacy(e,t,n){let r=e.note===void 0?``:`, and ${e.note}`,i=e.to===void 0?``:`; its 2.0 form is ${e.to}${r}`,a=e.manual===void 0?t:`To fix it, ${e.manual}${e.note===void 0?``:`; ${e.note}`}.`;n(`reference-legacy-format`,`\`${e.from}\` is a version 1 form, and ${e.reads}${i}. ${a}`)}function directoryEntries(e){try{return o(e,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))}catch{return[]}}function qualifiedOverrides(e,t){let n=[];for(let r of directoryEntries(e)){let i=r.name;if(!r.isDirectory()||!H.test(i))continue;let a=directoryEntries(C(e,i));if(!a.some(e=>e.name===`README.md`))for(let r of a){if(!r.isFile()||!r.name.endsWith(`.md`))continue;let a=r.name.slice(0,-3);!H.test(a)||a.endsWith(`.default`)||a.endsWith(`.meta`)||(t===void 0||a===t)&&n.push({plugin:i,name:a,path:C(e,i,r.name),file:`${i}/${r.name}`})}}return n}function qualifiedOverrideFinding(e,t){let{plugin:n,name:r,file:i}=e,a={form:`qualified-override`,from:i,reads:`no released version read it, so the override never applied`,note:`applying the plan turns it on`};return t===`project`?{...a,manual:`pick plugin ${n} for the whole repository with \`reference customize ${r} --extends ${n}\` at the root, since a project section carries no extends; then move this file's body into ${r}.md in this folder and delete this file`}:{...a,to:`${r}.md with extends: [${n}]`}}const kn=[`merge`,`implements`];function sidecarFile(e,t){return`${t}${e.tier==="default"?U:``}${Sn}.md`}function readSidecar(e,t,n,{without:r,display:i,warnAt:a,read:o}){let s=sidecarFile(e,t),c=C(e.dir,s),l=c===r?void 0:o(c);if(l===void 0)return;let u=a(i(c));if(n===`markdown`){u(`metadata-ignored`,`it is ignored: a metadata file goes beside a non-Markdown file, and a Markdown contribution carries its keys in its own frontmatter`);return}let{metadata:d,body:f}=parseDocument(l,u),p=d.extends!==void 0;if(n===void 0&&!p){u(`metadata-ignored`,`it is ignored: no non-Markdown file for "${t}" is beside it, and it writes no extends to select one`);return}hasBody(f)&&u(`metadata-ignored`,`its body is ignored: a metadata file holds frontmatter only`);let m={...d};for(let e of kn)e in m&&(delete m[e],u(`metadata-ignored`,e===`merge`?"`merge` in it is ignored: a non-Markdown contribution always replaces what is below it":"`implements` in it is ignored: an interface's sections are Markdown"));return{path:c,file:s,frontmatter:d,metadata:m,selects:p}}function readExtends(e,t){if(e===void 0)return;let malformed=e=>{t(`extends-invalid`,`\`extends\` ${e}; it is read as not written`)},n=typeof e==`string`?[e]:Array.isArray(e)?e:void 0;if(!n)return malformed(`is not a list of plugins`);let r=[];for(let e of n){let n=readStep(e,t);if(typeof n==`string`)return malformed(n);r.push(n)}return r}const An=[`merge`,`extends`,`sections`];function readStep(e,t){if(typeof e==`string`)return H.test(e)?{target:e}:`names "${e}", which is not a plugin name or default`;if(!isRecord$1(e)||Object.keys(e).length!==1)return`holds ${JSON.stringify(e)}, which is not a step`;let[n,r]=Object.entries(e)[0];if(!H.test(n))return`names "${n}", which is not a plugin name or default`;if(r==null)return{target:n};let i={target:n};if(typeof r==`string`)return i.merge=readStepMerge(r,n,t),i;if(!isRecord$1(r)||Object.keys(r).some(e=>!An.includes(e)))return`gives "${n}" keys other than merge, extends, and sections`;if(r.merge!==void 0&&(i.merge=readStepMerge(r.merge,n,t)),r.extends!==void 0){let e=readExtends(r.extends,t);if(!e)return`gives "${n}" a malformed extends`;i.extends=e}if(r.sections!==void 0){let e=readStepSections(r.sections,n,t);if(!e)return`gives "${n}" sections that are not a list of headings`;i.sections=e}return i}function readStepSections(e,t,n){let r=typeof e==`string`?[e]:Array.isArray(e)?e:void 0;if(!r)return;let i=[];for(let e of r){if(typeof e==`string`&&e.trim()){i.push({heading:e.trim()});continue}if(!isRecord$1(e)||Object.keys(e).length!==1)return;let[r,a]=Object.entries(e)[0];if(!r.trim())return;let o={heading:r.trim()};a!=null&&(o.merge=readStepMerge(a,`${t} > ${r}`,n)),i.push(o)}return i}function readStepMerge(e,t,n){return isMergeOperation(e)?e:(n(`merge-unknown`,`unknown merge "${String(e)}" on the step ${t}; read as patch`),`patch`)}function expand(e,t,n,r,i){let a={entries:[],missing:[],allMissing:!1,replaced:[]},o=new Set,s=new Set,normalize=(e,t,n)=>{let r=[];for(let o of e){if(o.target===n){i(`extends-self`,`${t} lists itself in its extends; that entry is ignored`);continue}r.at(-1)?.target!==o.target&&(r.some(({target:e})=>e===o.target)&&!a.ambiguous&&(a.ambiguous={cause:`repeat`,message:`${t}'s extends lists ${o.target} at two places`}),r.push(o))}return r},c=normalize(e,t),l=new Set(c.map(({target:e})=>e)),visit=(e,c,u)=>{if(a.ambiguous||o.has(e.target))return;if(s.has(e.target)){n===`plugins`&&(a.ambiguous={cause:`cycle`,message:`the plugins' own extends form a cycle: ${[...u,e.target].join(` → `)}`});return}if(!c&&l.has(e.target))return;let d=r(e.target);if(`reason`in d){a.missing.push({target:e.target,reason:d.reason}),e.target!=="default"&&i(`extends-step-missing`,`the step ${e.target} in ${u.at(-1)??t}'s extends ${d.reason}; it is skipped`);return}s.add(e.target);let f=d.steps??[];if(e.extends){let t=new Set(e.extends.map(({target:e})=>e));for(let{target:n}of f)t.has(n)||a.replaced.push({target:n,step:e.target})}for(let t of normalize(e.extends??f,`plugin ${e.target}`,e.target))visit(t,!1,[...u,e.target]);s.delete(e.target);let p=e.merge??d.merge??`patch`,m=e.merge?`step`:d.merge?`contribution`:`default`,h={target:e.target,contribution:d,operation:p,from:m};e.sections&&(h.sections=e.sections),a.entries.push(h),o.add(e.target)};for(let e of c)visit(e,!0,[]);return a.allMissing=c.length>0&&c.every(({target:e})=>!o.has(e))&&c.some(({target:e})=>e!=="default"),a}const noWarn=()=>{};function plan(e,t,n,r,i,a){let o;for(let n of t){if(!n.steps)continue;if(e.plugin!==void 0){n.entry.extendsOutcome=`not used (qualified name)`;continue}if(o){expand(n.steps,n.label,`written`,r,noWarn).entries.map(({target:e})=>e).join(` `)!==o.targets&&(n.entry.extendsOutcome=`not used (${o.builder.label}'s extends builds the stack)`,a(`extends-not-used`,`${n.label} builds a different stack from ${o.builder.label}, whose extends is used`));continue}let t=expand(n.steps,n.label,`written`,r,a);if(t.ambiguous)return{status:`ambiguous`,...t.ambiguous};if(t.allMissing){n.entry.extendsOutcome=`not used (every step is missing)`,a(`extends-all-missing`,`every step in ${n.label}'s extends is missing; it is read as not written`);continue}o={entries:t.entries,builtBy:n.label,replaced:t.replaced,replacedBy:n.label,builder:n,targets:t.entries.map(({target:e})=>e).join(` `)}}if(o)return o;if(e.plugin!==void 0){let t=r(e.plugin);if(`reason`in t)return{status:`missing`,message:`the plugin ${e.plugin} ${t.reason}`};let n=expand([{target:e.plugin}],`plugin ${e.plugin}`,`plugins`,r,a);return n.ambiguous?{status:`ambiguous`,...n.ambiguous}:{entries:n.entries,builtBy:`qualified name`,replaced:[],replacedBy:``}}return planFromPlugins(n,r,i,e.name,a)}function planFromPlugins(e,t,n,r,i){let defaultEntry=()=>n?[{target:`default`,contribution:n,operation:n.merge??`patch`,from:n.merge?`contribution`:`default`}]:[],a=[...e.keys()];if(!a.length)return{entries:defaultEntry(),builtBy:`none`,replaced:[],replacedBy:``};let o=new Map;for(let e of a){let n=expand([{target:e}],`plugin ${e}`,`plugins`,t,noWarn);if(n.ambiguous)return{status:`ambiguous`,...n.ambiguous};o.set(e,new Set(n.entries.map(({target:e})=>e).filter(t=>t!==e)))}let s=a.filter(e=>!a.some(t=>t!==e&&o.get(t)?.has(e))),unordered=()=>({status:`ambiguous`,cause:`unordered`,message:`the plugins ${a.join(`, `)} hold it, and no extends orders them`});if(s.length!==1)return unordered();let c=s[0],l=expand([{target:c}],`plugin ${c}`,`plugins`,t,i);if(l.ambiguous)return{status:`ambiguous`,...l.ambiguous};let u=new Set(l.entries.map(({target:e})=>e));if(a.some(e=>!u.has(e)))return unordered();let d=l.entries;if(n&&!u.has(`default`)){d.unshift(...defaultEntry());let e=a.join(`, `);i(`default-not-selected`,`${a.length>1?`the plugins`:`the plugin`} ${e} ${a.length>1?`answer`:`answers`} over the default of ${n.layer.skill}, and no extends names either; run "reference customize ${r} --extends <option>..." to choose (options: ${[...a,`default`].join(`, `)})`)}return{entries:d,builtBy:c&&(e.get(c)?.steps?.length??0)>0?`plugin ${c}'s extends`:`none`,replaced:[],replacedBy:``}}function readDeclined(e,t){if(e==null)return[];if(!Array.isArray(e))return t(`frontmatter-invalid`,"`declined` is not a list; it is read as declining nothing"),[];let n=e.filter(e=>typeof e==`string`&&H.test(e));return n.length!==e.length&&t(`frontmatter-invalid`,"an entry in `declined` is not a plugin name; it is left out"),n}function pickValues(e){if(!e.some(e=>e.extends!==void 0||e.sections!==void 0))return e.map(({target:e,merge:t})=>t?`${e}:${t}`:e)}function namesDefault(e){return(e??[]).some(e=>e.target==="default"||namesDefault(e.extends))}function tryRead$2(e){try{return a(e,`utf8`)}catch{return}}function candidateFiles(e,t){return e.tier==="default"?[`${t}${U}.md`,...V.map(({extension:e})=>`${t}${U}${e}`)]:[`${t}.md`,`${t}/README.md`,...V.map(({extension:e})=>`${t}${e}`)]}function contributionLabel(e,t,n){return e.tier===`plugin`?`plugin ${e.plugin}`:e.tier==="default"?`default of ${e.skill}`:`${e.tier} ${n(t)}`}function readContribution(e,t,n,{display:r,without:i,warnAt:a,older:o=[]}){if(e.tier!=="default"){let n=C(e.dir,`${t}${U}.md`);n!==i&&tryRead$2(n)!==void 0&&a(r(n))(`default-in-tier`,`it is ignored: a default goes in a skill's references/ folder`)}(e.tier===`repo`||e.tier===`user`)&&warnQualifiedOverrides$1(e,t,{display:r,without:i,warnAt:a});let s=e.tier===`plugin`||e.tier==="default",[c,...l]=[t,...s?[]:o].flatMap(t=>candidateFiles(e,t).flatMap(n=>{let r=C(e.dir,n),a=r===i?void 0:tryRead$2(r);return a===void 0?[]:[{file:n,path:r,raw:a,as:t}]}));for(let e of l)a(r(e.path))(`file-ignored`,`it is ignored: ${c?.file} answers first in that folder`);let u=c?formatOfFile(c.file):void 0,d={without:i,display:r,warnAt:a,read:tryRead$2},f=readSidecar(e,c?.as??t,u,d);if(!c&&!f&&!s){for(let i of o)if(f=readSidecar(e,i,void 0,d),f){renamed(n,i,t,f.path,r,a);break}}if(c&&c.as!==t&&renamed(n,c.as,t,c.path,r,a),!c&&!f&&e.tier==="default"&&warnDefaultLayout(e,t,{display:r,without:i,warnAt:a}),!c)return f?sidecarSelection(e,n,f,r,a):void 0;let p=contributionLabel(e,c.path,r),m=a(p);if(u!==`markdown`){Object.assign(n,{path:c.path,file:c.file,outcome:``});let t=c.raw.trim().length>0;t||(n.empty=!0);let i=f?.metadata??{};return f&&(n.frontmatter=f.frontmatter),typeof i.description==`string`&&(n.description=i.description),{layer:e,entry:n,label:p,path:c.path,metadata:i,body:c.raw,hasBody:t,whole:!0,format:u,merge:`replace`,steps:f?readExtends(f.metadata.extends,a(r(f.path))):void 0}}let{metadata:h,body:g}=parseDocument(c.raw,m),_=legacyFix(e,t,r);for(let e of legacyRewrite(h,g,`contribution`,t).findings)warnLegacy(e,_,m);let v=readMergeOperation(h,m),y=readExtends(h.extends,m);Object.assign(n,{path:c.path,file:c.file,frontmatter:h,outcome:``}),typeof h.description==`string`&&(n.description=h.description);let b=hasBody(g);return b||(n.empty=!0),y&&!b&&v!==`remove`&&(n.selection=!0),{layer:e,entry:n,label:p,path:c.path,metadata:h,body:g,hasBody:b,format:u,whole:!1,merge:v,steps:y}}function legacyFix(e,t,n){return e.tier===`plugin`?`Plugin ${e.plugin}'s author rewrites it with \`reference migrate --plugin <its source folder>\`; until then, customize the name.`:e.tier==="default"?`Its skill's author rewrites it with \`reference migrate ${t} --default ${n(b(e.dir))}\`.`:e.tier===`managed`?"An admin rewrites it; `reference migrate` never changes a managed file.":"Run `reference migrate` to rewrite it."}function warnQualifiedOverrides$1(e,t,{display:n,without:r,warnAt:i}){for(let a of qualifiedOverrides(e.dir,t))a.path!==r&&warnLegacy(qualifiedOverrideFinding(a,`contribution`),legacyFix(e,t,n),i(contributionLabel(e,a.path,n)))}function warnDefaultLayout(e,t,{display:n,without:r,warnAt:i}){let a=C(e.dir,`${t}.md`);a!==r&&tryRead$2(a)!==void 0&&warnLegacy(defaultLayoutFinding(t),legacyFix(e,t,n),i(n(a)))}function renamed(e,t,n,r,i,a){e.alias=t,a(i(r))(`reference-renamed`,`it is filed under the older name "${t}" and applies as "${n}"; rename it to the new name`)}function sidecarSelection(e,t,n,r,i){let a=contributionLabel(e,n.path,r),o=readExtends(n.metadata.extends,i(a));return Object.assign(t,{path:n.path,file:n.file,frontmatter:n.frontmatter,outcome:``}),typeof n.metadata.description==`string`&&(t.description=n.metadata.description),t.empty=!0,o&&(t.selection=!0),{layer:e,entry:t,label:a,path:n.path,metadata:n.metadata,body:``,hasBody:!1,format:`markdown`,whole:!1,merge:void 0,steps:o}}function layerNames(e){if(e.skipped)return[];let t;try{t=o(e.dir,{withFileTypes:!0})}catch{return[]}let n=new Set,r=e.tier==="default";for(let i of t){let t;if(r){let e=[`${U}.md`,...V.map(e=>`${U}${e.extension}`)].find(e=>i.name.endsWith(e));e&&(t=i.name.slice(0,-e.length))}else!i.isDirectory()&&[`.md`,...V.map(e=>e.extension)].some(e=>i.name.endsWith(e))?t=i.name.slice(0,i.name.lastIndexOf(`.`)):!i.isFile()&&tryRead$2(C(e.dir,i.name,`README.md`))!==void 0&&(t=i.name);t===void 0||parseReferenceName(t).invalid||n.add(t)}return[...n]}const jn=`.interface`,Mn=/^([a-z0-9]+(?:[-.][a-z0-9]+)*)@(\d+)$/i;function interfaceIdOf(e){return e.endsWith(`.interface`)&&e.length>10?e.slice(0,-10):void 0}function isVersion(e){return typeof e==`number`&&Number.isInteger(e)&&e>0}function describe(e){return JSON.stringify(e)??String(e)}function newForm(e,t){return t===`required`||t===!0?`{heading: ${e}, required: true}`:`{heading: ${e}}`}function readSection(e){if(typeof e==`string`&&e.trim())return{heading:e.trim(),required:!1};if(!isRecord$1(e))return{problems:[`section ${describe(e)} is not a heading`]};let t=e.heading;if(t===void 0){let t=Object.keys(e),[n]=t;return t.length===1&&n?.trim()?{problems:[`section ${describe(e)} is in the old form; write it as ${newForm(n.trim(),e[n])}`]}:{problems:[`section ${describe(e)} has no heading`]}}if(typeof t!=`string`||!t.trim())return{problems:[`section ${describe(e)}: heading is not text`]};let n=t.trim(),r=[],i=e.required;i!==void 0&&typeof i!=`boolean`&&r.push(`section "${n}": required is ${describe(i)}; it is true or false`);let a=e.holds;if(a!==void 0&&(typeof a!=`string`||!a.trim()||a.trim().includes(`
|
|
163
|
-
`))&&r.push(`section "${n}": holds is ${describe(a)}; it is one line of text`),r.length)return{problems:r};let o={heading:n,required:i===!0};return typeof a==`string`&&(o.holds=a.trim()),o}function sectionKey(e){return e.trim().replace(/\s+/g,` `).toLowerCase()}function readInterface(e,t){let n=t.interface;if(!isRecord$1(n))return{problems:[n===void 0?"has no `interface:` block in its frontmatter":"`interface:` is not a mapping"]};let r=[],i=n.cardinality;i!==`one`&&i!==`many`&&r.push(`cardinality is ${JSON.stringify(i)}; it is one or many`);let a=n.version;isVersion(a)||r.push(`version is ${JSON.stringify(a)}; it is a positive integer`);let o=n.versions,s=isVersion(a)?[a]:[];o!==void 0&&(Array.isArray(o)&&o.length&&o.every(isVersion)?s=o:r.push(`versions is not a list of positive integers`));let c=n.sections,l=[];if(!Array.isArray(c)||!c.length)r.push(`sections is not a list of headings`);else{let e=new Set;for(let t of c){let n=readSection(t);if(`problems`in n){r.push(...n.problems);continue}let i=sectionKey(n.heading);e.has(i)&&r.push(`section "${n.heading}" is listed more than once`),e.add(i),l.push(n)}}return r.length?{problems:r}:{value:{id:e,cardinality:i,version:a,versions:s,sections:l},problems:r}}function readImplements(e){let t=e.implements;if(t===void 0)return{problems:[]};let n=Array.isArray(t)?t:[t];if(n.length!==1)return{problems:[n.length?`implements lists ${n.length} interfaces; an implementation implements one`:`implements is an empty list`]};let[r]=n,i=typeof r==`string`?
|
|
164
|
-
`)?e:`${e}\n`}function trimLeadingBlank(e){return e.replace(/^(?:[ \t]*\r?\n)+/,``)}const
|
|
165
|
-
`)?e.request:`${e.request}\n`),t}const In=[`merge`,`extends`,`implements`,`aliases`],Ln=[`sources`,`request`];function names(e){try{return new Set(o(e))}catch{return new Set}}function filesFor(e,t,n){let r=names(e.dir),at=n=>({folder:e,file:n,as:t,path:C(e.dir,...n.split(`/`)),relative:`${e.folder}/.agents/references/${n}`});return{markdown:[`${t}.md`,`${t}/README.md`].filter(e=>r.has(e.split(`/`)[0])).map(at).filter(({path:e})=>e!==n&&tryRead$2(e)!==void 0),data:V.map(({extension:e})=>`${t}${e}`).filter(e=>r.has(e)).map(at).filter(({path:e})=>e!==n)}}function folderEntries(e,t){let n=new Map,at=e=>{let t=n.get(e);return t||(t={folder:e,ignored:!1,plugins:[]},n.set(e,t)),t};for(let t of e.folders)at(t.folder).own=t;for(let t of e.ignored)Object.assign(at(t.folder),{own:t,ignored:!0});for(let e of t)at(e.folder).plugins.push(e);return[...n.values()].sort((e,t)=>comparePaths(e.folder,t.folder))}function readProjectSections(e,t){let{root:n,cache:r,catalog:i,held:a=new Set}=t,o=projectFolders(n,r),s=packagePlugins(n,r,a),c={...t,older:t.older??[],catalog:i&&withPackagePlugins(i,s),dropping:droppingOperation(t.managed),listed:e=>!o.listed||o.listed.has(e.relative)},l={sections:[],trace:[]};for(let t of folderEntries(o,s)){for(let n of pluginHits(e,t,c))readPluginSection(e,n,c,l);t.own&&readOwnSection(e,t.own,t.ignored,c,l)}return l}function withPackagePlugins(e,t){if(!t.length)return e;let n=new Map(e.plugins);for(let{plugin:e,version:r}of t)n.has(e)||n.set(e,{plugin:e,version:r,origin:`package`});return{...e,plugins:n}}function pluginHits(e,t,n){let r=[];for(let i of[...t.plugins].sort((e,t)=>e.plugin.localeCompare(t.plugin))){let a={folder:t.folder,dir:packagePluginReferences(i)},[o]=[e,...n.older].flatMap(e=>filesFor(a,e,n.without).markdown);if(!o)continue;let{metadata:s,body:c}=parseDocument(tryRead$2(o.path)??``,n.warnAt(`plugin ${n.display(o.path)}`)),l=readExtends(s.extends,()=>{})??[];r.push({plugin:i,hit:o,metadata:s,body:c,after:l.map(({target:e})=>e)})}let i=[],a=new Set(r.map(({plugin:e})=>e.plugin));for(;r.length;){let e=new Set(i.map(({plugin:e})=>e.plugin)),t=r.findIndex(({after:t})=>t.every(t=>!a.has(t)||e.has(t)));i.push(...r.splice(t===-1?0:t,1))}return i}function readPluginSection(e,t,n,r){let{plugin:i,hit:a,metadata:o,body:s}=t,c={folder:i.folder,path:a.path,file:a.file,frontmatter:o,outcome:`used`,plugin:i.plugin};i.version!==void 0&&(c.version=i.version),a.as!==e&&(c.alias=a.as),r.trace.push(c);let l=`plugin ${n.display(a.path)}`;if(n.format!==void 0&&n.format!==`markdown`){c.outcome=`not used (format differs from ${n.format})`,n.warnAt(l)(`project-section-not-markdown`,`it is not delivered: the main document of "${e}" is ${n.format}, which has no project sections`);return}if(n.dropping){c.outcome=`shadowed by ${n.dropping.label} (${n.dropping.operation})`;return}if(!hasBody(s)){c.outcome=`not used (no body)`;return}let u={...o};for(let e of[...In,...Ln,`declined`])delete u[e];let d=applyManaged(s,l,n.managed,n.warnAt);d.sections&&(c.sections=d.sections),r.sections.push({folder:i.folder,path:a.path,content:d.content,metadata:u,plugin:i.plugin})}function warnQualifiedOverrides(e,t,n){let{display:r,without:i,warnAt:a,listed:o}=n;for(let n of qualifiedOverrides(t.dir,e)){let s={folder:t,file:n.file,as:e,path:n.path,relative:`${t.folder}/.agents/references/${n.file}`};n.path!==i&&o(s)&&warnLegacy(qualifiedOverrideFinding(n,`project`),``,a(`project ${r(n.path)}`))}}function readOwnSection(e,t,n,r,i){let{trace:a,sections:o}=i,{format:s,display:c,without:l,warnAt:u,catalog:d,older:f,listed:p,dropping:m,managed:h}=r;n||warnQualifiedOverrides(e,t,r);let g=[e,...f].map(e=>filesFor(t,e,l)),_=g.flatMap(e=>e.markdown),v=g.flatMap(e=>e.data);if(n||![..._,...v].some(p)){(_.length||v.length)&&a.push({folder:t.folder,path:t.dir,outcome:`not read (ignored)`});return}for(let t of v.filter(p))u(c(t.path))(`project-section-not-markdown`,`it is not delivered: a project section is Markdown, written as ${e}.md`);let[y,...b]=_.filter(p);if(!y)return;for(let e of b)u(c(e.path))(`file-ignored`,`it is ignored: ${y.file} answers first in that folder`);let x={folder:t.folder,path:y.path,file:y.file,outcome:`used`};a.push(x);let S=`project ${c(y.path)}`;if(y.as!==e&&(x.alias=y.as,u(c(y.path))(`reference-renamed`,`it is filed under the older name "${y.as}" and applies as "${e}"; rename it to the new name`)),s!==void 0&&s!==`markdown`){x.outcome=`not used (format differs from ${s})`,u(S)(`project-section-not-markdown`,`it is not delivered: the main document of "${e}" is ${s}, which has no project sections`);return}let{metadata:C,body:w}=parseDocument(tryRead$2(y.path)??``,u(S));x.frontmatter=C;let T={...C},E=legacyRewrite(C,w,`project`,e).findings;for(let e of E)warnLegacy(e,"Run `reference migrate` to rewrite it.",u(S));let D=new Set(E.flatMap(({form:e})=>e===`project-selection`?[`extends`]:e===`overrides`?[`overrides`]:[`merge`]));delete T.overrides;for(let e of In)e in T&&(delete T[e],!D.has(e)&&u(S)(`project-section-key-ignored`,`\`${e}\` is ignored in the project section for ${t.folder}: a project section states only what differs in its folder`));if(m){x.outcome=`shadowed by ${m.label} (${m.operation})`;return}if(!hasBody(w)){x.outcome=`not used (no body)`;return}for(let e of Ln)delete T[e];let O=applyManaged(w,S,h,u);O.sections&&(x.sections=O.sections);let k=d&&checkGenerated(C,d,u(S));k&&(k.sources.length&&(x.sources=k.sources),k.request!==void 0&&(x.request=k.request),k.stale&&(x.outcome=`stale`,u(S)(`reference-stale`,staleMessage(e,k.sources)))),o.push({folder:t.folder,path:y.path,content:O.content,metadata:T})}function droppingOperation(e){if(e?.entry.outcome!==`used`)return;let t=e.merge??`patch`;if(t===`remove`||t===`replace`&&e.hasBody)return{label:e.label,operation:t}}function applyManaged(e,t,n,r){let i=withNewline(trimLeadingBlank(stripMergeMarkers(e)));if(n?.entry.outcome!==`used`||!n.hasBody||n.whole)return{content:i};let a=n.merge??`patch`;if(a===`remove`||a===`replace`)return{content:i};let o=applyContribution(emptyComposed(),e,`patch`,t,r(t)),s=applyContribution(o,n.body,a,n.label,r(n.label),{matchedOnly:!0}),c=renderComposed(s);return c===renderComposed(o)?{content:i}:{content:c,sections:composedSections(s).map(({path:e,sources:t})=>({path:e,contributions:t}))}}function projectSectionNames(e,t,n=new Set){let r=projectFolders(e,t),i=new Set;for(let e of r.folders)for(let t of layerNames({tier:`project`,dir:e.dir})){let{markdown:n}=filesFor(e,t,void 0);n.some(e=>!r.listed||r.listed.has(e.relative))&&i.add(t)}for(let r of packagePlugins(e,t,n)){let e=packagePluginReferences(r);for(let t of layerNames({tier:`plugin`,dir:e}))filesFor({folder:r.folder,dir:e},t,void 0).markdown.length&&i.add(t)}return[...i]}function projectQualifiedNames(e,t){let n=projectFolders(e,t);return n.folders.flatMap(e=>qualifiedOverrides(e.dir).filter(({file:t})=>!n.listed||n.listed.has(`${e.folder}/.agents/references/${t}`)).map(({name:e})=>e))}const Rn=`_renames.yaml`,zn=new WeakMap;function bare(e){if(typeof e!=`string`)return;let t=parseReferenceName(e.trim());return t.invalid||t.plugin!==void 0?void 0:t.name}function renameTable(e){let t=Array.isArray(e)?void 0:e,n=t&&zn.get(t);if(n)return n;let r=Array.isArray(e)?e:e.layers,i=new Map,a=[],o=new Set;for(let e of r){if(e.tier!==`plugin`||e.skipped||e.plugin===void 0)continue;let t=C(e.dir,Rn);if(o.has(t))continue;o.add(t);let n=tryRead$2(t);if(n===void 0)continue;let r=e.plugin,s;try{s=(0,en.parse)(n)}catch{s=void 0}if(s==null){n.trim()&&a.push({code:`rename-invalid`,message:`plugin ${r}: ${t} is not YAML; it is ignored`});continue}if(!isRecord$1(s)){a.push({code:`rename-invalid`,message:`plugin ${r}: ${t} is not a mapping of older names to new names; it is ignored`});continue}for(let[e,t]of Object.entries(s)){let n=bare(e),o=bare(t);if(n===void 0||o===void 0||n===o){a.push({code:`rename-invalid`,message:`plugin ${r}: the rename ${JSON.stringify(e)}: ${JSON.stringify(t)} in ${Rn} is not a pair of bare reference names; it is ignored`});continue}let s=i.get(n)??[];s.some(e=>e.to===o&&e.plugin===r)||s.push({from:n,to:o,plugin:r}),i.set(n,s)}}let s={byOld:i,warnings:a};return t&&zn.set(t,s),s}function layersOf(e){return Array.isArray(e)?{layers:[...e],harnesses:[]}:e}function emptyTrace(e){return{stack:[],builtBy:`none`,contributions:[],sections:[],layers:[],harnesses:[...e],projectSections:[]}}function stackOrder(e,t){let rank=e=>{if(e.tier!==`plugin`&&e.tier!=="default")return-1;let n=t.indexOf(e.tier==="default"?`default`:e.plugin??``);return n===-1?t.length:t.length-1-n};return e.map((e,t)=>({layer:e,index:t,rank:rank(e)})).sort((e,t)=>e.rank-t.rank||e.index-t.index).map(({layer:e})=>e)}function resolveReference(e,t,n={}){return resolveAdjusted(e,t,n,void 0)}function resolveAdjusted(e,t,{display:n=e=>e,without:r,below:i,projectSections:a=!0},o){let s=typeof e==`string`?parseReferenceName(e):e,{layers:c,harnesses:l,root:u,projects:d}=layersOf(t),f=emptyTrace(l),p=[],m={name:s.raw,status:`missing`,projectSections:[],warnings:p,trace:f};if(s.invalid)return{...m,status:`invalid`,code:`reference-invalid`,message:s.invalid};let h=new Set,warnAt=e=>(t,n)=>{let r=e?`${e}: ${n}`:n;h.has(`${t} ${r}`)||(h.add(`${t} ${r}`),p.push({code:t,message:r}))},g=warnAt(``),_=aliasIndex(t),v=resolveAlias(s,_,g);if(v.kind===`ambiguous`)return{...m,status:`ambiguous`,code:`reference-ambiguous`,message:v.message,cause:`alias`,options:v.names};let y=v.kind===`renamed`?v.ref:s;v.kind===`renamed`&&(f.alias={name:v.alias,resolvedAs:y.name});let b=olderNames(y.name,_,g);v.kind===`own`&&warnTableRename(y,t,_,g);let x=i===void 0?-1:c.findIndex(e=>e.dir===i),S=x===-1?c:c.slice(x+1),C=[];for(let e of S){e.warning&&g(e.warning.code,e.warning.message);let t={tier:e.tier,path:e.dir,outcome:`missing`};if(e.plugin!==void 0&&(t.plugin=e.plugin),e.skill!==void 0&&(t.skill=e.skill),f.layers.push(t),e.skipped){t.outcome=`not read (${e.skipped})`;continue}let i=readContribution(e,y.name,t,{display:n,without:r,warnAt,older:b}),a=o?o(e,i,t):i;a?C.push(a):e.tier==="default"&&(t.outcome=`not read (no default)`)}warnMisplacedAliases(C,warnAt);let w=new Map;for(let e of C.filter(({layer:e})=>e.tier===`plugin`)){let t=e.layer.plugin,r=w.get(t);r?e.entry.outcome=`not read (plugin ${t} answers from ${n(r.path)})`:w.set(t,e)}let T=C.find(({layer:e})=>e.tier==="default"),E=C.filter(({layer:e})=>e.tier!==`plugin`&&e.tier!=="default"),D=new Set(S.flatMap(({plugin:e,skipped:t})=>e&&!t?[e]:[])),lookup=e=>e==="default"?T??{reason:`has no default`}:w.get(e)??{reason:D.has(e)?`holds no ${y.name}`:`is not installed`},options=()=>[...[...w.keys()].map(e=>`${e}/${y.name}`),...T?[`default`]:[]];if(interfaceIdOf(y.name)!==void 0)return resolveInterface(y,C,w,T,m,g,options);let sectionsOver=e=>{if(u===void 0||i!==void 0||!a)return{sections:[],trace:[]};let o=E.find(({layer:e})=>e.tier===`managed`),s=sourceCatalog(t,{tier:`project`}),c=readProjectSections(y.name,{root:u,cache:d,managed:o,format:e,display:n,without:r,warnAt,catalog:s,older:b,held:heldPlugins(layersOf(t))});return f.projectSections=c.trace,c},O=plan(y,E,w,lookup,T,g);if(`status`in O){if(O.status===`ambiguous`){for(let{entry:e}of C)e.outcome===``&&(e.outcome=`ambiguous`);return{...m,status:`ambiguous`,code:`reference-ambiguous`,message:O.message,cause:O.cause,options:options()}}for(let{entry:e}of C)e.outcome===``&&(e.outcome=`not used (qualified name)`);return{...m,status:`missing`,code:`reference-missing`,message:O.message}}!S.some(({tier:e})=>e==="default")&&C.some(({steps:e})=>namesDefault(e))&&f.layers.push({tier:`default`,path:`(no skill folder given)`,outcome:`not read (no default)`}),f.stack=O.entries.map(({target:e})=>e),f.builtBy=O.builtBy,f.layers=stackOrder(f.layers,f.stack);let k=new Set(f.stack);for(let[e,t]of[...w.entries(),...T?[[`default`,T]]:[]]){if(k.has(e))continue;let n=O.replaced.find(t=>t.target===e);t.entry.outcome=y.plugin===void 0?n?`not used (${n.step}'s extends replaced by ${O.replacedBy})`:`not used (not in extends)`:`not used (qualified name)`}y.plugin===void 0&&warnUndecided(y.name,O,w,k,warnAt);let{composed:ee,applied:A,removedBy:te,used:ne,whole:re}=composeOrder([...O.entries,...[...E].reverse().map(e=>({contribution:e,operation:e.merge??`patch`,from:e.merge?`contribution`:`default`}))],warnAt);if(markStale(y.name,ne,t,warnAt),f.sections=ee.removed.map(({path:e,by:t})=>({path:e,contributions:[],removedBy:t})),!A.length){let e=sectionsOver(void 0).sections;if(e.length)return{...m,status:`found`,content:``,format:`markdown`,metadata:{},projectSections:e};if(te)return f.removedBy=te.label,{...m,status:`missing`,code:`reference-removed`,message:`"${y.name}" is turned off by ${te.label} (remove)`};let t=y.plugin===void 0?`no tier holds a document for "${y.name}"`:`the plugin ${y.plugin} holds no document for "${y.name}"`;return{...m,status:`missing`,code:`reference-missing`,message:t}}let ie=ne.filter(({entry:e})=>e.outcome===`used`||e.outcome===`stale`);if(f.contributions=A.map(({layer:e,entry:t})=>{let n={tier:e.tier,path:t.path,operation:t.operation};return t.plugin!==void 0&&(n.plugin=t.plugin),t.skill!==void 0&&(n.skill=t.skill),n}),f.sections=[...composedSections(ee).map(({path:e,sources:t})=>({path:e,contributions:t})),...f.sections],re)return sectionsOver(re.format),{...m,status:`found`,content:re.body,format:re.format,metadata:composedMetadata(ie)};let ae=A.length===1&&!ee.removed.length?A[0].body:void 0,j=ae!==void 0&&stripMergeMarkers(ae)===ae?withNewline(trimLeadingBlank(ae)):renderComposed(ee);return{...m,status:`found`,content:j,format:`markdown`,metadata:composedMetadata(ie),projectSections:sectionsOver(`markdown`).sections}}function markStale(e,t,n,r){for(let i of t){let{layer:t,entry:a}=i;if(a.outcome!==`used`||t.tier!==`repo`&&t.tier!==`user`)continue;let o=r(i.label),s=checkGenerated(i.metadata,sourceCatalog(n,{tier:t.tier}),o);s&&(s.sources.length&&(a.sources=s.sources),s.request!==void 0&&(a.request=s.request),s.stale&&(a.outcome=`stale`,o(`reference-stale`,staleMessage(e,s.sources))))}}function warnUndecided(e,t,n,r,i){let a=t.builder;if(!a||a.layer.tier!==`repo`&&a.layer.tier!==`user`)return;let o=new Set(readDeclined(a.metadata.declined,i(a.label))),s=[];for(let[e,t]of n)r.has(e)||(a.layer.tier!==`user`||t.layer.origin!==`dependency`)&&(o.has(e)?t.entry.outcome=`not used (declined by ${a.label})`:s.push(e));if(!s.length)return;let c=a.layer.tier===`user`?` --scope user`:``,l=pickValues(a.steps??[]),u=l?`run "reference customize ${e}${c} --extends ${[...l,...s].join(` `)}" to add ${s.length>1?`them`:`it`}, or "reference customize ${e}${c} --extends ${l.join(` `)}" to leave ${s.length>1?`them`:`it`} out`:`add ${s.length>1?`them`:`it`} to the extends with "reference customize ${e}${c} --extends-file <file>", or write the same extends again to leave ${s.length>1?`them`:`it`} out`,d=s.join(`, `);i(a.label)(`plugin-not-selected`,`${s.length>1?`the plugins`:`the plugin`} ${d} ${s.length>1?`hold`:`holds`} "${e}" but ${s.length>1?`are`:`is`} neither in its extends nor declined, so ${s.length>1?`they are`:`it is`} not used; ${u}`)}function resolveInterface(e,t,n,r,i,a,o){for(let e of t)(e.merge!==void 0||e.steps!==void 0)&&a(`interface-not-composed`,`${e.label}: merge and extends on an interface document are ignored; an interface is never composed`);if(e.plugin===void 0&&n.size>1){for(let{entry:e}of t)e.outcome===``&&(e.outcome=`ambiguous`);return{...i,status:`ambiguous`,code:`reference-ambiguous`,message:`the plugins ${[...n.keys()].join(`, `)} each hold the interface document`,cause:`unordered`,options:o()}}let s=e.plugin===void 0?[...n.values()]:n.has(e.plugin)?[n.get(e.plugin)]:[];if(e.plugin!==void 0){for(let[t,r]of n)t!==e.plugin&&(r.entry.outcome=`not used (qualified name)`);if(!s.length)return{...i,status:`missing`,code:`reference-missing`,message:`the plugin ${e.plugin} holds no "${e.name}"`}}let c=t.filter(({layer:e})=>e.tier!==`plugin`&&e.tier!=="default"),[l,...u]=[...e.plugin===void 0&&r?[r]:[],...s,...[...c].reverse()];if(!l)return{...i,status:`missing`,code:`reference-missing`,message:`no tier holds a document for "${e.name}"`};for(let e of u)e.entry.outcome=`not used (an interface document is never composed)`,a(`interface-not-composed`,`${e.label} is ignored: an interface document is never composed; define a new interface id instead`);r&&r!==l&&(r.entry.outcome=`not used (qualified name)`),l.entry.outcome=`used`,l.entry.operation=`replace`,l.entry.operationFrom=`default`;let{trace:d}=i;return l.layer.tier===`plugin`&&(d.stack=[l.layer.plugin]),l.layer.tier==="default"&&(d.stack=[`default`]),d.contributions=[{tier:l.layer.tier,...l.entry.plugin?{plugin:l.entry.plugin}:{},...l.entry.skill?{skill:l.entry.skill}:{},path:l.path,operation:`replace`}],{...i,status:`found`,content:withNewline(trimLeadingBlank(stripMergeMarkers(l.body))),metadata:composedMetadata([l])}}function referenceNames(e){return[...new Set(layersOf(e).layers.flatMap(layerNames))].sort((e,t)=>e.localeCompare(t))}function warnTableRename(e,t,n,r){if(n.owned.has(e.name))return;let i=(renameTable(t).byOld.get(e.name)??[]).filter(t=>e.plugin===void 0||t.plugin===e.plugin);if(!i.length)return;let a=[...new Set(i.map(({plugin:e})=>`plugin ${e}`))].join(` and `),o=[...new Set(i.map(({to:e})=>`"${e}"`))].join(` or `);r(`reference-renamed`,`${a} renamed "${e.name}" to ${o}: load ${o} instead, and run \`reference migrate\` to rename the files filed under "${e.name}"`)}function skillHoldings(e){return(Array.isArray(e)?[]:e.skills?.skills??[]).flatMap(e=>layerNames(defaultLayer(e.folder)).map(t=>({name:t,skill:e}))).sort((e,t)=>e.name.localeCompare(t.name)||e.skill.name.localeCompare(t.skill.name))}function defaultsUnverified(e){return Array.isArray(e)?void 0:e.skills?.unverified}function withDefault(e,t){let n=Array.isArray(e)?{layers:[...e],harnesses:[]}:e;return{...n,layers:[...n.layers.filter(({tier:e})=>e!=="default"),defaultLayer(t)]}}function patternMatcher(e){let t=e.split(`*`).map(e=>e.replace(/[.+?^${}()|[\]\\]/g,`\\$&`));return RegExp(`^${t.join(`.*`)}$`,`s`)}function firstLine$1(e){return typeof e==`string`&&e.split(`
|
|
166
|
-
`)[0]?.trim()||``}function collect(e,t,n){for(let r of n){let n=`${r.code} ${r.message}`;t.has(n)||e.push(r),t.add(n)}}function layerRow(e,t){let n={name:e,tier:t.tier,path:t.path,description:firstLine$1(t.description),outcome:t.outcome};return t.plugin!==void 0&&(n.plugin=t.plugin),t.skill!==void 0&&(n.skill=t.skill),t.selection?n.kind=`selection`:isGenerated(t.frontmatter)&&(n.kind=`generated`),n}function projectRow(e,t){return{name:e,tier:`project`,path:t.path,description:firstLine$1(t.frontmatter?.description),outcome:t.outcome,kind:`project-section`,folder:t.folder,...t.plugin===void 0?{}:{plugin:t.plugin}}}function catalogNames(e){let t=Array.isArray(e)?void 0:e,n=t?.root===void 0?[]:projectSectionNames(t.root,t.projects,heldPlugins(t)),r=aliasIndex(e);return[...new Set([...referenceNames(e),...n].map(e=>shownName(e,r)))]}function listReferences(e,t={}){let{pattern:n,...r}=t,i=n===void 0?void 0:patternMatcher(n),a={references:[],layers:[],warnings:[]},o=defaultsUnverified(e);o&&(a.defaults=o);let s=new Set,c=skillHoldings(e),l=[...new Set([...catalogNames(e),...c.map(({name:e})=>e)])].sort((e,t)=>e.localeCompare(t));for(let t of l){if(i&&!i.test(t))continue;let n=c.filter(e=>e.name===t),o=resolveReference(t,e,r);!(o.trace.layers.some(({file:e,tier:t})=>e&&t!=="default")||o.trace.projectSections.some(({file:e})=>e))&&n[0]&&(o=resolveReference(t,withDefault(e,n[0].skill.folder),r)),collect(a.warnings,s,o.warnings);let l={name:t,description:o.status===`found`?firstLine$1(o.metadata?.description):``,status:o.status};if(o.code&&(l.code=o.code),o.format&&o.format!==`markdown`&&(l.format=o.format),o.options){let e=n.map(({skill:e})=>`default of ${e.name}`);l.options=[...new Set([...o.options.filter(e=>e!=="default"),...e])]}a.references.push(l);for(let e of o.trace.layers)e.file!==void 0&&e.tier!=="default"&&a.layers.push(layerRow(t,e));for(let e of o.trace.projectSections)e.file!==void 0&&a.layers.push(projectRow(t,e));for(let{skill:i}of n)a.layers.push(defaultRow(t,i.name,i.folder,e,r))}return a}function defaultRow(e,t,n,r,i){return{...layerRow(e,resolveReference(e,withDefault(r,n),i).trace.layers.find(({tier:e,file:t})=>e==="default"&&t)),reachedBy:`the default step, when ${t} loads ${e}`}}const
|
|
162
|
+
`),missing:c}}const On={"merge-sections":void 0,"first-wins":`replace`};function isLegacyMerge(e){return e===`merge-sections`||e===`first-wins`}function overriddenPlugins(e){let t=typeof e==`string`?[e]:Array.isArray(e)?e:void 0;if(t?.length&&t.every(e=>typeof e==`string`&&e.trim()))return[...new Set(t.map(e=>e.split(`/`)[0].trim()))]}function stepTargets(e){let t=typeof e==`string`?[e]:Array.isArray(e)?e:void 0;if(!t)return;let n=[];for(let e of t)if(typeof e==`string`)n.push(e);else if(isRecord$1(e)&&Object.keys(e).length===1)n.push(Object.keys(e)[0]);else return;return n}const flow=e=>`[${e.join(`, `)}]`;function legacyRewrite(e,t,n,r){let i=[],a={},o=e.merge;if(isLegacyMerge(o)){let e=On[o];a.merge=n===`project`?void 0:e,i.push({form:o,from:`merge: ${o}`,to:n===`project`?`no merge: a project section carries none`:e===void 0?`no merge: patch is the default`:`merge: ${e}`,reads:`it reads as patch`})}if(`overrides`in e&&i.push(overridesFinding(e,n,a)),n===`project`&&e.extends!==void 0&&!hasBody(t)){let t=stepTargets(e.extends);i.push({form:`project-selection`,from:`extends: ${t?flow(t):JSON.stringify(e.extends)}`,manual:`a pick now applies to the whole repository: run \`reference customize ${r} --extends ${t?.join(` `)??`<step>...`}\` at the root, then delete this file`,reads:`its extends is ignored`})}return{findings:i,keys:a}}function overridesFinding(e,t,n){let r=e.overrides,i=overriddenPlugins(r),a=`overrides: ${i?flow(Array.isArray(r)?r:[String(r)]):JSON.stringify(r)}`,o=`it is ignored`;if(t===`project`)return n.overrides=void 0,{form:`overrides`,from:a,to:`removed: a project section carries no extends`,reads:o};if(!i)return{form:`overrides`,from:a,manual:"`overrides` is not a list of plugin names",reads:o};let s=e.extends;if(s===void 0)return n.overrides=void 0,n.extends=i,{form:`overrides`,from:a,to:`extends: ${flow(i)}`,reads:o};let c=stepTargets(s),l=i.filter(e=>!c?.includes(e));return c&&!l.length?(n.overrides=void 0,{form:`overrides`,from:a,to:`removed: extends already names each plugin`,reads:o}):{form:`overrides`,from:a,manual:`\`extends\` is also written and does not name ${l.join(`, `)}; add ${l.length>1?`them`:`it`} to \`extends\` where it belongs, then remove \`overrides\``,reads:o}}function defaultLayoutFinding(e){return{form:`default-layout`,from:`references/${e}.md`,to:`references/${e}.default.md`,reads:`it is not read as the default`}}function warnLegacy(e,t,n){let r=e.note===void 0?``:`, and ${e.note}`,i=e.to===void 0?``:`; its 2.0 form is ${e.to}${r}`,a=e.manual===void 0?t:`To fix it, ${e.manual}${e.note===void 0?``:`; ${e.note}`}.`;n(`reference-legacy-format`,`\`${e.from}\` is a version 1 form, and ${e.reads}${i}. ${a}`)}function directoryEntries(e){try{return o(e,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))}catch{return[]}}function qualifiedOverrides(e,t){let n=[];for(let r of directoryEntries(e)){let i=r.name;if(!r.isDirectory()||!H.test(i))continue;let a=directoryEntries(C(e,i));if(!a.some(e=>e.name===`README.md`))for(let r of a){if(!r.isFile()||!r.name.endsWith(`.md`))continue;let a=r.name.slice(0,-3);!H.test(a)||a.endsWith(`.default`)||a.endsWith(`.meta`)||(t===void 0||a===t)&&n.push({plugin:i,name:a,path:C(e,i,r.name),file:`${i}/${r.name}`})}}return n}function qualifiedOverrideFinding(e,t){let{plugin:n,name:r,file:i}=e,a={form:`qualified-override`,from:i,reads:`no released version read it, so the override never applied`,note:`applying the plan turns it on`};return t===`project`?{...a,manual:`pick plugin ${n} for the whole repository with \`reference customize ${r} --extends ${n}\` at the root, since a project section carries no extends; then move this file's body into ${r}.md in this folder and delete this file`}:{...a,to:`${r}.md with extends: [${n}]`}}const kn=[`merge`,`implements`];function sidecarFile(e,t){return`${t}${e.tier==="default"?U:``}${Sn}.md`}function readSidecar(e,t,n,{without:r,display:i,warnAt:a,read:o}){let s=sidecarFile(e,t),c=C(e.dir,s),l=c===r?void 0:o(c);if(l===void 0)return;let u=a(i(c));if(n===`markdown`){u(`metadata-ignored`,`it is ignored: a metadata file goes beside a non-Markdown file, and a Markdown contribution carries its keys in its own frontmatter`);return}let{metadata:d,body:f}=parseDocument(l,u),p=d.extends!==void 0;if(n===void 0&&!p){u(`metadata-ignored`,`it is ignored: no non-Markdown file for "${t}" is beside it, and it writes no extends to select one`);return}hasBody(f)&&u(`metadata-ignored`,`its body is ignored: a metadata file holds frontmatter only`);let m={...d};for(let e of kn)e in m&&(delete m[e],u(`metadata-ignored`,e===`merge`?"`merge` in it is ignored: a non-Markdown contribution always replaces what is below it":"`implements` in it is ignored: an interface's sections are Markdown"));return{path:c,file:s,frontmatter:d,metadata:m,selects:p}}function readExtends(e,t){if(e===void 0)return;let malformed=e=>{t(`extends-invalid`,`\`extends\` ${e}; it is read as not written`)},n=typeof e==`string`?[e]:Array.isArray(e)?e:void 0;if(!n)return malformed(`is not a list of plugins`);let r=[];for(let e of n){let n=readStep(e,t);if(typeof n==`string`)return malformed(n);r.push(n)}return r}const An=[`merge`,`extends`,`sections`];function readStep(e,t){if(typeof e==`string`)return H.test(e)?{target:e}:`names "${e}", which is not a plugin name or default`;if(!isRecord$1(e)||Object.keys(e).length!==1)return`holds ${JSON.stringify(e)}, which is not a step`;let[n,r]=Object.entries(e)[0];if(!H.test(n))return`names "${n}", which is not a plugin name or default`;if(r==null)return{target:n};let i={target:n};if(typeof r==`string`)return i.merge=readStepMerge(r,n,t),i;if(!isRecord$1(r)||Object.keys(r).some(e=>!An.includes(e)))return`gives "${n}" keys other than merge, extends, and sections`;if(r.merge!==void 0&&(i.merge=readStepMerge(r.merge,n,t)),r.extends!==void 0){let e=readExtends(r.extends,t);if(!e)return`gives "${n}" a malformed extends`;i.extends=e}if(r.sections!==void 0){let e=readStepSections(r.sections,n,t);if(!e)return`gives "${n}" sections that are not a list of headings`;i.sections=e}return i}function readStepSections(e,t,n){let r=typeof e==`string`?[e]:Array.isArray(e)?e:void 0;if(!r)return;let i=[];for(let e of r){if(typeof e==`string`&&e.trim()){i.push({heading:e.trim()});continue}if(!isRecord$1(e)||Object.keys(e).length!==1)return;let[r,a]=Object.entries(e)[0];if(!r.trim())return;let o={heading:r.trim()};a!=null&&(o.merge=readStepMerge(a,`${t} > ${r}`,n)),i.push(o)}return i}function readStepMerge(e,t,n){return isMergeOperation(e)?e:(n(`merge-unknown`,`unknown merge "${String(e)}" on the step ${t}; read as patch`),`patch`)}function expand(e,t,n,r,i){let a={entries:[],missing:[],allMissing:!1,replaced:[]},o=new Set,s=new Set,normalize=(e,t,n)=>{let r=[];for(let o of e){if(o.target===n){i(`extends-self`,`${t} lists itself in its extends; that entry is ignored`);continue}r.at(-1)?.target!==o.target&&(r.some(({target:e})=>e===o.target)&&!a.ambiguous&&(a.ambiguous={cause:`repeat`,message:`${t}'s extends lists ${o.target} at two places`}),r.push(o))}return r},c=normalize(e,t),l=new Set(c.map(({target:e})=>e)),visit=(e,c,u)=>{if(a.ambiguous||o.has(e.target))return;if(s.has(e.target)){n===`plugins`&&(a.ambiguous={cause:`cycle`,message:`the plugins' own extends form a cycle: ${[...u,e.target].join(` → `)}`});return}if(!c&&l.has(e.target))return;let d=r(e.target);if(`reason`in d){a.missing.push({target:e.target,reason:d.reason}),e.target!=="default"&&i(`extends-step-missing`,`the step ${e.target} in ${u.at(-1)??t}'s extends ${d.reason}; it is skipped`);return}s.add(e.target);let f=d.steps??[];if(e.extends){let t=new Set(e.extends.map(({target:e})=>e));for(let{target:n}of f)t.has(n)||a.replaced.push({target:n,step:e.target})}for(let t of normalize(e.extends??f,`plugin ${e.target}`,e.target))visit(t,!1,[...u,e.target]);s.delete(e.target);let p=e.merge??d.merge??`patch`,m=e.merge?`step`:d.merge?`contribution`:`default`,h={target:e.target,contribution:d,operation:p,from:m};e.sections&&(h.sections=e.sections),a.entries.push(h),o.add(e.target)};for(let e of c)visit(e,!0,[]);return a.allMissing=c.length>0&&c.every(({target:e})=>!o.has(e))&&c.some(({target:e})=>e!=="default"),a}const noWarn=()=>{};function plan(e,t,n,r,i,a){let o;for(let n of t){if(!n.steps)continue;if(e.plugin!==void 0){n.entry.extendsOutcome=`not used (qualified name)`;continue}if(o){expand(n.steps,n.label,`written`,r,noWarn).entries.map(({target:e})=>e).join(` `)!==o.targets&&(n.entry.extendsOutcome=`not used (${o.builder.label}'s extends builds the stack)`,a(`extends-not-used`,`${n.label} builds a different stack from ${o.builder.label}, whose extends is used`));continue}let t=expand(n.steps,n.label,`written`,r,a);if(t.ambiguous)return{status:`ambiguous`,...t.ambiguous};if(t.allMissing){n.entry.extendsOutcome=`not used (every step is missing)`,a(`extends-all-missing`,`every step in ${n.label}'s extends is missing; it is read as not written`);continue}o={entries:t.entries,builtBy:n.label,replaced:t.replaced,replacedBy:n.label,builder:n,targets:t.entries.map(({target:e})=>e).join(` `)}}if(o)return o;if(e.plugin!==void 0){let t=r(e.plugin);if(`reason`in t)return{status:`missing`,message:`the plugin ${e.plugin} ${t.reason}`};let n=expand([{target:e.plugin}],`plugin ${e.plugin}`,`plugins`,r,a);return n.ambiguous?{status:`ambiguous`,...n.ambiguous}:{entries:n.entries,builtBy:`qualified name`,replaced:[],replacedBy:``}}return planFromPlugins(n,r,i,e.name,a)}function planFromPlugins(e,t,n,r,i){let defaultEntry=()=>n?[{target:`default`,contribution:n,operation:n.merge??`patch`,from:n.merge?`contribution`:`default`}]:[],a=[...e.keys()];if(!a.length)return{entries:defaultEntry(),builtBy:`none`,replaced:[],replacedBy:``};let o=new Map;for(let e of a){let n=expand([{target:e}],`plugin ${e}`,`plugins`,t,noWarn);if(n.ambiguous)return{status:`ambiguous`,...n.ambiguous};o.set(e,new Set(n.entries.map(({target:e})=>e).filter(t=>t!==e)))}let s=a.filter(e=>!a.some(t=>t!==e&&o.get(t)?.has(e))),unordered=()=>({status:`ambiguous`,cause:`unordered`,message:`the plugins ${a.join(`, `)} hold it, and no extends orders them`});if(s.length!==1)return unordered();let c=s[0],l=expand([{target:c}],`plugin ${c}`,`plugins`,t,i);if(l.ambiguous)return{status:`ambiguous`,...l.ambiguous};let u=new Set(l.entries.map(({target:e})=>e));if(a.some(e=>!u.has(e)))return unordered();let d=l.entries;if(n&&!u.has(`default`)){d.unshift(...defaultEntry());let e=a.join(`, `);i(`default-not-selected`,`${a.length>1?`the plugins`:`the plugin`} ${e} ${a.length>1?`answer`:`answers`} over the default of ${n.layer.skill}, and no extends names either; run "reference customize ${r} --extends <option>..." to choose (options: ${[...a,`default`].join(`, `)})`)}return{entries:d,builtBy:c&&(e.get(c)?.steps?.length??0)>0?`plugin ${c}'s extends`:`none`,replaced:[],replacedBy:``}}function readDeclined(e,t){if(e==null)return[];if(!Array.isArray(e))return t(`frontmatter-invalid`,"`declined` is not a list; it is read as declining nothing"),[];let n=e.filter(e=>typeof e==`string`&&H.test(e));return n.length!==e.length&&t(`frontmatter-invalid`,"an entry in `declined` is not a plugin name; it is left out"),n}function pickValues(e){if(!e.some(e=>e.extends!==void 0||e.sections!==void 0))return e.map(({target:e,merge:t})=>t?`${e}:${t}`:e)}function namesDefault(e){return(e??[]).some(e=>e.target==="default"||namesDefault(e.extends))}function tryRead$2(e){try{return a(e,`utf8`)}catch{return}}function candidateFiles(e,t){return e.tier==="default"?[`${t}${U}.md`,...V.map(({extension:e})=>`${t}${U}${e}`)]:[`${t}.md`,`${t}/README.md`,...V.map(({extension:e})=>`${t}${e}`)]}function contributionLabel(e,t,n){return e.tier===`plugin`?`plugin ${e.plugin}`:e.tier==="default"?`default of ${e.skill}`:`${e.tier} ${n(t)}`}function readContribution(e,t,n,{display:r,without:i,warnAt:a,older:o=[]}){if(e.tier!=="default"){let n=C(e.dir,`${t}${U}.md`);n!==i&&tryRead$2(n)!==void 0&&a(r(n))(`default-in-tier`,`it is ignored: a default goes in a skill's references/ folder`)}(e.tier===`repo`||e.tier===`user`)&&warnQualifiedOverrides$1(e,t,{display:r,without:i,warnAt:a});let s=e.tier===`plugin`||e.tier==="default",[c,...l]=[t,...s?[]:o].flatMap(t=>candidateFiles(e,t).flatMap(n=>{let r=C(e.dir,n),a=r===i?void 0:tryRead$2(r);return a===void 0?[]:[{file:n,path:r,raw:a,as:t}]}));for(let e of l)a(r(e.path))(`file-ignored`,`it is ignored: ${c?.file} answers first in that folder`);let u=c?formatOfFile(c.file):void 0,d={without:i,display:r,warnAt:a,read:tryRead$2},f=readSidecar(e,c?.as??t,u,d);if(!c&&!f&&!s){for(let i of o)if(f=readSidecar(e,i,void 0,d),f){renamed(n,i,t,f.path,r,a);break}}if(c&&c.as!==t&&renamed(n,c.as,t,c.path,r,a),!c&&!f&&e.tier==="default"&&warnDefaultLayout(e,t,{display:r,without:i,warnAt:a}),!c)return f?sidecarSelection(e,n,f,r,a):void 0;let p=contributionLabel(e,c.path,r),m=a(p);if(u!==`markdown`){Object.assign(n,{path:c.path,file:c.file,outcome:``});let t=c.raw.trim().length>0;t||(n.empty=!0);let i=f?.metadata??{};return f&&(n.frontmatter=f.frontmatter),typeof i.description==`string`&&(n.description=i.description),{layer:e,entry:n,label:p,path:c.path,metadata:i,body:c.raw,hasBody:t,whole:!0,format:u,merge:`replace`,steps:f?readExtends(f.metadata.extends,a(r(f.path))):void 0}}let{metadata:h,body:g}=parseDocument(c.raw,m),_=legacyFix(e,t,r);for(let e of legacyRewrite(h,g,`contribution`,t).findings)warnLegacy(e,_,m);let v=readMergeOperation(h,m),y=readExtends(h.extends,m);Object.assign(n,{path:c.path,file:c.file,frontmatter:h,outcome:``}),typeof h.description==`string`&&(n.description=h.description);let b=hasBody(g);return b||(n.empty=!0),y&&!b&&v!==`remove`&&(n.selection=!0),{layer:e,entry:n,label:p,path:c.path,metadata:h,body:g,hasBody:b,format:u,whole:!1,merge:v,steps:y}}function legacyFix(e,t,n){return e.tier===`plugin`?`Plugin ${e.plugin}'s author rewrites it with \`reference migrate --plugin <its source folder>\`; until then, customize the name.`:e.tier==="default"?`Its skill's author rewrites it with \`reference migrate ${t} --default ${n(b(e.dir))}\`.`:e.tier===`managed`?"An admin rewrites it; `reference migrate` never changes a managed file.":"Run `reference migrate` to rewrite it."}function warnQualifiedOverrides$1(e,t,{display:n,without:r,warnAt:i}){for(let a of qualifiedOverrides(e.dir,t))a.path!==r&&warnLegacy(qualifiedOverrideFinding(a,`contribution`),legacyFix(e,t,n),i(contributionLabel(e,a.path,n)))}function warnDefaultLayout(e,t,{display:n,without:r,warnAt:i}){let a=C(e.dir,`${t}.md`);a!==r&&tryRead$2(a)!==void 0&&warnLegacy(defaultLayoutFinding(t),legacyFix(e,t,n),i(n(a)))}function renamed(e,t,n,r,i,a){e.alias=t,a(i(r))(`reference-renamed`,`it is filed under the older name "${t}" and applies as "${n}"; rename it to the new name`)}function sidecarSelection(e,t,n,r,i){let a=contributionLabel(e,n.path,r),o=readExtends(n.metadata.extends,i(a));return Object.assign(t,{path:n.path,file:n.file,frontmatter:n.frontmatter,outcome:``}),typeof n.metadata.description==`string`&&(t.description=n.metadata.description),t.empty=!0,o&&(t.selection=!0),{layer:e,entry:t,label:a,path:n.path,metadata:n.metadata,body:``,hasBody:!1,format:`markdown`,whole:!1,merge:void 0,steps:o}}function layerNames(e){if(e.skipped)return[];let t;try{t=o(e.dir,{withFileTypes:!0})}catch{return[]}let n=new Set,r=e.tier==="default";for(let i of t){let t;if(r){let e=[`${U}.md`,...V.map(e=>`${U}${e.extension}`)].find(e=>i.name.endsWith(e));e&&(t=i.name.slice(0,-e.length))}else!i.isDirectory()&&[`.md`,...V.map(e=>e.extension)].some(e=>i.name.endsWith(e))?t=i.name.slice(0,i.name.lastIndexOf(`.`)):!i.isFile()&&tryRead$2(C(e.dir,i.name,`README.md`))!==void 0&&(t=i.name);t===void 0||parseReferenceName(t).invalid||n.add(t)}return[...n]}const W=`.interface`,jn=/^([a-z0-9]+(?:[-.][a-z0-9]+)*)@(\d+)$/i;function interfaceIdOf(e){return e.endsWith(`.interface`)&&e.length>10?e.slice(0,-10):void 0}function isVersion(e){return typeof e==`number`&&Number.isInteger(e)&&e>0}function describe(e){return JSON.stringify(e)??String(e)}function newForm(e,t){return t===`required`||t===!0?`{heading: ${e}, required: true}`:`{heading: ${e}}`}function readSection(e){if(typeof e==`string`&&e.trim())return{heading:e.trim(),required:!1};if(!isRecord$1(e))return{problems:[`section ${describe(e)} is not a heading`]};let t=e.heading;if(t===void 0){let t=Object.keys(e),[n]=t;return t.length===1&&n?.trim()?{problems:[`section ${describe(e)} is in the old form; write it as ${newForm(n.trim(),e[n])}`]}:{problems:[`section ${describe(e)} has no heading`]}}if(typeof t!=`string`||!t.trim())return{problems:[`section ${describe(e)}: heading is not text`]};let n=t.trim(),r=[],i=e.required;i!==void 0&&typeof i!=`boolean`&&r.push(`section "${n}": required is ${describe(i)}; it is true or false`);let a=e.holds;if(a!==void 0&&(typeof a!=`string`||!a.trim()||a.trim().includes(`
|
|
163
|
+
`))&&r.push(`section "${n}": holds is ${describe(a)}; it is one line of text`),r.length)return{problems:r};let o={heading:n,required:i===!0};return typeof a==`string`&&(o.holds=a.trim()),o}function sectionKey(e){return e.trim().replace(/\s+/g,` `).toLowerCase()}function readInterface(e,t){let n=t.interface;if(!isRecord$1(n))return{problems:[n===void 0?"has no `interface:` block in its frontmatter":"`interface:` is not a mapping"]};let r=[],i=n.cardinality;i!==`one`&&i!==`many`&&r.push(`cardinality is ${JSON.stringify(i)}; it is one or many`);let a=n.version;isVersion(a)||r.push(`version is ${JSON.stringify(a)}; it is a positive integer`);let o=n.versions,s=isVersion(a)?[a]:[];o!==void 0&&(Array.isArray(o)&&o.length&&o.every(isVersion)?s=o:r.push(`versions is not a list of positive integers`));let c=n.sections,l=[];if(!Array.isArray(c)||!c.length)r.push(`sections is not a list of headings`);else{let e=new Set;for(let t of c){let n=readSection(t);if(`problems`in n){r.push(...n.problems);continue}let i=sectionKey(n.heading);e.has(i)&&r.push(`section "${n.heading}" is listed more than once`),e.add(i),l.push(n)}}return r.length?{problems:r}:{value:{id:e,cardinality:i,version:a,versions:s,sections:l},problems:r}}function readImplements(e){let t=e.implements;if(t===void 0)return{problems:[]};let n=Array.isArray(t)?t:[t];if(n.length!==1)return{problems:[n.length?`implements lists ${n.length} interfaces; an implementation implements one`:`implements is an empty list`]};let[r]=n,i=typeof r==`string`?jn.exec(r.trim()):null;return i?{entry:{id:i[1],version:Number(i[2])},problems:[]}:{problems:[`implements ${JSON.stringify(r)} is not <id>@<version>`]}}function fitsName(e,t){return e.cardinality===`one`?t===e.id:t.startsWith(`${e.id}.`)&&t.length>e.id.length+1&&!t.endsWith(`.interface`)}function documentSections(e){let t=[],visit=e=>{if(e.depth===0){let n=e.text.find(e=>e.trim());t.push({title:e.title,unsupported:n?.trim().startsWith(`**Unsupported.**`)??!1})}for(let t of e.children)visit(t)};for(let t of parseSections(e,()=>{}).children)visit(t);return t}function checkImplementation(e,{name:t,version:n,content:r,accept:i=e.versions,declaredId:a=e.id}){let o=[],fail=(t,n)=>o.push({check:t,interface:e.id,message:n});i.includes(n)||fail(`version`,`unknown version ${n}`),fitsName({id:a,cardinality:e.cardinality},t)||fail(`name`,`name ${t} is not ${e.cardinality===`one`?a:`${a}.<key>`}`);let s=documentSections(r),c=e.sections.map(({heading:e})=>sectionKey(e)),l=e.sections.filter(({heading:e})=>{let t=s.find(t=>sectionKey(t.title)===sectionKey(e));return!t||t.unsupported}),u=l.filter(({required:e})=>!e).map(({heading:e})=>e),d=-1,f=``,p=new Set;for(let e of s){let t=sectionKey(e.title),n=c.indexOf(t);n!==-1&&(p.has(t)?fail(`order`,`section ${e.title} appears more than once`):n<d&&fail(`order`,`section ${e.title} comes after ${f}`),p.add(t),n>d&&(d=n,f=e.title))}let m=l.filter(({required:e})=>e).map(({heading:e})=>e);return m.length&&fail(`required`,`required ${m.length===1?`section`:`sections`} ${m.join(`, `)} ${m.length===1?`is`:`are`} left out or marked **Unsupported.**`),{failures:o,unsupported:u}}const Mn=new WeakMap,quiet=()=>()=>{};function ownerLabel(e){return e.tier===`plugin`?`plugin ${e.plugin}`:`default of ${e.skill}`}function push(e,t,n){let r=e.get(t);r?r.push(n):e.set(t,[n])}function listed(e){return e==null?[]:Array.isArray(e)?e:[e]}function aliasIndex(e){let t=Array.isArray(e)?void 0:e,n=t&&Mn.get(t);if(n)return n;let r=Array.isArray(e)?e:e.layers,i=new Map,a=new Map,o=new Map,s=new Map,c=new Map;for(let e of r)if(!(e.tier!==`plugin`&&e.tier!=="default"||e.skipped))for(let t of layerNames(e)){let n=readContribution(e,t,{tier:e.tier,path:e.dir,outcome:``},{display:e=>e,without:void 0,warnAt:quiet});if(!n)continue;let r={name:t,tier:e.tier,path:aliasFile(n)};e.plugin!==void 0&&(r.plugin=e.plugin),e.skill!==void 0&&(r.skill=e.skill),push(o,t,ownerLabel(r));let l=interfaceIdOf(t);for(let e of listed(n.metadata.aliases)){let o=typeof e==`string`?e.trim():void 0,u=o===void 0?void 0:parseReferenceName(o);if(o===void 0||!u||u.invalid||u.plugin!==void 0||o===(l??t)){push(s,t,{code:`alias-invalid`,message:`${ownerLabel(r)}: the alias ${JSON.stringify(e)} is not a reference name of its own; it is ignored`});continue}l!==void 0&&push(c,l,{alias:o,owner:r});for(let e of l===void 0?[o]:documentNames$1(o,n.metadata)){push(i,e,r);let n=a.get(t)??[];n.includes(e)||a.set(t,[...n,e])}}}let l={byAlias:i,byName:a,owned:o,warnings:s,interfaces:c};return t&&Mn.set(t,l),l}function documentNames$1(e,t){let n=t.interface;return isRecord$1(n)&&n.cardinality===`many`?[e,`${e}${W}`]:[`${e}${W}`]}__name(documentNames$1,`documentNames`);function aliasFile(e){return e.entry.frontmatter&&e.whole?e.path.replace(/\.[^./]+$/,`.meta.md`):e.path}function resolveAlias(e,t,n){if(e.invalid)return{kind:`own`};let r=(t.byAlias.get(e.name)??[]).filter(t=>e.plugin===void 0||t.plugin===e.plugin);if(!r.length)return{kind:`own`};let i=t.owned.get(e.name);if(i)return n(`alias-not-used`,notUsedMessage(e.name,i,r)),{kind:`own`};let a=[...new Set(r.map(({name:e})=>e))].sort((e,t)=>e.localeCompare(t));if(a.length>1)return{kind:`ambiguous`,names:e.plugin===void 0?a:a.map(t=>`${e.plugin}/${t}`),message:`"${e.name}" is an older name of ${a.join(` and `)}; load one of them by its own name`};let o=a[0];n(`reference-renamed`,`"${e.raw}" is renamed "${o}"; load "${o}" instead`);let s={raw:e.raw,name:o};return e.plugin!==void 0&&(s.plugin=e.plugin),{kind:`renamed`,ref:s,alias:e.name}}function notUsedMessage(e,t,n){return`the alias "${e}" that ${[...new Set(n.map(e=>`${ownerLabel(e)}'s "${e.name}"`))].join(` and `)} lists is not used: ${t.join(` and `)} ${t.length>1?`hold`:`holds`} "${e}" as its own name`}function olderNames(e,t,n){for(let r of t.warnings.get(e)??[])n(r.code,r.message);let r=[];for(let i of t.byName.get(e)??[]){let e=t.byAlias.get(i)??[],a=t.owned.get(i);if(a){n(`alias-not-used`,notUsedMessage(i,a,e));continue}new Set(e.map(e=>e.name)).size>1||r.push(i)}return r}function shownName(e,t){if(t.owned.has(e))return e;let n=new Set((t.byAlias.get(e)??[]).map(e=>e.name));return n.size===1?[...n][0]:e}function warnMisplacedAliases(e,t){for(let n of e){let{tier:e}=n.layer;e!==`plugin`&&e!=="default"&&`aliases`in n.metadata&&t(n.label)(`alias-invalid`,"`aliases` is ignored: only the owner's contribution, a plugin's or a skill's default, renames a name")}}function picked(e,t){let{contribution:n,sections:r}=e;if(!r||n.whole)return n;let i=pickSections(n.body,r);for(let e of i.missing)t(n.label)(`section-not-held`,`the step's sections list "${e}", which it does not hold; that entry is skipped`);return{...n,body:i.body,hasBody:hasBody(i.body)}}function composeOrder(e,t){let n=emptyComposed(),r=[],i,a=[],o;for(let s of e){let{operation:e,from:c}=s,l=picked(s,t),{entry:u}=l;if(l.whole&&l.hasBody){u.operation=`replace`,u.operationFrom=`default`;for(let e of r)e.entry.outcome=`shadowed by ${l.label} (replace)`;r=[l],n={...emptyComposed(),removed:n.removed},o=l,i=void 0,u.outcome=`used`,a.push(l);continue}if(o&&e!==`remove`&&l.hasBody){u.operation=e,u.operationFrom=c,u.outcome=`not used (format differs from ${o.format})`,t(l.label)(`format-mismatch`,`it is ignored: ${o.label} is ${o.format}, which a Markdown contribution cannot compose with`);continue}e===`remove`&&(o=void 0),u.operation=e,u.operationFrom=c;let d=t(l.label);if(e===`remove`){l.hasBody&&d(`remove-body-ignored`,`a merge: remove contribution has a body; it is ignored`);for(let e of r)e.entry.outcome=`shadowed by ${l.label} (remove)`;for(let e of composedSections(n))e.path!==`(before the first heading)`&&n.removed.push({path:e.path,by:l.label});let e=n.removed;r=[],n={...emptyComposed(),removed:e},i=l,u.outcome=`used`,a.push(l);continue}if(!l.hasBody){u.outcome=u.extendsOutcome??`used`,u.extendsOutcome||a.push(l);continue}if(e===`replace`){for(let e of r)e.entry.outcome=`shadowed by ${l.label} (replace)`;r=[]}n=applyContribution(n,l.body,e,l.label,d),r.push(l),i=void 0,u.outcome=`used`,a.push(l)}return{composed:n,applied:r,removedBy:i,used:a,whole:o}}const Nn=[`merge`,`extends`,`sources`,`request`];function composedMetadata(e){let t=Object.assign({},...e.map(({metadata:e})=>e));for(let e of Nn)delete t[e];return t}function withNewline(e){return e.endsWith(`
|
|
164
|
+
`)?e:`${e}\n`}function trimLeadingBlank(e){return e.replace(/^(?:[ \t]*\r?\n)+/,``)}const G=[`.agents`,`references`];function lsFiles(e,...t){return A(`git`,[`ls-files`,`-z`,...t,`--exclude-standard`],{cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`],maxBuffer:268435456}).split(`\0`).filter(Boolean)}function gitListing(e){try{let t=lsFiles(e,`-coi`,`--directory`),n=new Set(t);return{files:lsFiles(e,`-co`).filter(e=>!n.has(e)),ignored:t}}catch{return}}function folderOf(e){let t=e.split(`/`);for(let e=1;e+G.length<t.length;e++)if(t[e]===G[0]&&t[e+1]===G[1])return t.slice(0,e).join(`/`)}function ignoredFolderOf(e,t){if(!t.endsWith(`/`))return folderOf(t);let n=t.slice(0,-1).split(`/`);n.at(-1)===G[1]&&n.at(-2)===G[0]?n.splice(-2):n.at(-1)===G[0]&&n.splice(-1);let r=n.join(`/`);return r&&isDirectory$3(C(e,...n,...G))?r:void 0}function entries$1(e){try{return o(e,{withFileTypes:!0})}catch{return[]}}function walk(e){let t=[],n=[],visit=r=>{let i=entries$1(C(e,r));r&&!r.split(`/`).includes(`node_modules`)&&i.some(e=>e.isFile()&&e.name===`package.json`)&&n.push(r);for(let n of i){if(!n.isDirectory())continue;let i=r?`${r}/${n.name}`:n.name;if(n.name!==G[0]){visit(i);continue}r&&entries$1(C(e,i,G[1])).length&&t.push(r);for(let t of entries$1(C(e,i)))t.isDirectory()&&t.name!==G[1]&&visit(`${i}/${t.name}`)}};return visit(``),{folders:t,packages:n}}function comparePaths(e,t){let n=e.split(`/`),r=t.split(`/`);for(let e=0;e<Math.min(n.length,r.length);e++){let t=n[e],i=r[e];if(t!==i)return t<i?-1:1}return n.length-r.length}function located(e,t){return[...t].sort(comparePaths).map(t=>({folder:t,dir:C(e,...t.split(`/`),...G)})).filter(({dir:e})=>isDirectory$3(e))}function discover(e){let t=gitListing(e);if(t===void 0){let t=walk(e);return{folders:located(e,t.folders),ignored:[],packages:t.packages.sort(comparePaths)}}let n=new Set(t.files.flatMap(e=>folderOf(e)??[])),r=new Set(t.ignored.flatMap(t=>{let r=ignoredFolderOf(e,t);return r===void 0||n.has(r)?[]:[r]})),i=t.files.flatMap(e=>e.endsWith(`/package.json`)?[e.slice(0,-13)]:[]);return{folders:located(e,n),ignored:located(e,r),listed:new Set(t.files),packages:i.sort(comparePaths)}}function projectFolders(e,t=new Map){let n=E(e),r=t.get(n);if(r)return r;let i=discover(n);return t.set(n,i),i}function gitIgnores(e,t){try{return A(`git`,[`check-ignore`,`-q`,`--`,t],{cwd:e,stdio:`ignore`}),!0}catch{return!1}}const Pn=new WeakMap;function readJson$3(e){try{return JSON.parse(a(e,`utf8`))}catch{return}}__name(readJson$3,`readJson`);function declared(e,t){let n=[];for(let r of t){let t=C(e,...r.split(`/`),`package.json`),i=readJson$3(t);for(let e of declaredDependencies(i)){let i=packageDir(e,t),a=i&&pluginManifestName(i);i&&a&&(n.some(e=>e.plugin===a&&r.startsWith(`${e.folder}/`))||n.some(e=>e.plugin===a&&e.folder===r)||n.push({folder:r,plugin:a,root:i,version:pluginVersion(i)}))}}return n}function packagePlugins(e,t,n){let r=projectFolders(e,t),i=Pn.get(r);return i||(i=declared(e,r.packages),Pn.set(r,i)),i.filter(({plugin:e})=>!n.has(e))}function packagePluginReferences(e){return C(e.root,`references`)}function heldPlugins({layers:e,plugins:t=[]}){return new Set([...e.flatMap(({tier:e,plugin:t,skipped:n})=>e===`plugin`&&t&&!n?[t]:[]),...t.flatMap(({plugin:e,origin:t})=>t===`package`?[]:[e])])}function isRecord$2(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}__name(isRecord$2,`isRecord`);function text$1(e){if(typeof e==`string`)return e.trim()?e.trim():void 0;if(typeof e==`number`)return String(e)}__name(text$1,`text`);function readSource(e){if(!isRecord$2(e))return;let t=text$1(e.plugin),n=text$1(e.version),r=text$1(e.default);if(r!==void 0)return{default:r,...t===void 0?{}:{plugin:t},...t!==void 0&&n!==void 0?{version:n}:{}};if(t!==void 0)return n===void 0?{plugin:t}:{plugin:t,version:n}}function readGeneratedRecord(e,t){let n={},r=e.request;typeof r==`string`&&r.trim()&&(n.request=r);let i=e.sources;if(i==null)return n;if(!Array.isArray(i))return t?.(`frontmatter-invalid`,"`sources` is not a list; it is read as recording no sources"),n;let a=i.flatMap(e=>{let n=readSource(e);return n||t?.(`frontmatter-invalid`,"a source in `sources` is not {plugin, version} or {default, plugin, version}; it is left out"),n?[n]:[]});return a.length&&(n.sources=a),n}function isGenerated(e){return e!==void 0&&readGeneratedRecord(e).request!==void 0}function sourceCatalog(e,{tier:t}){let n=Array.isArray(e)?e:e.layers,r=Array.isArray(e)?n.flatMap(({tier:e,plugin:t,version:n,origin:r,skipped:i})=>e===`plugin`&&t!==void 0&&!i?[{plugin:t,version:n,origin:r}]:[]):e.plugins??n.flatMap(({tier:e,plugin:t,version:n,origin:r,skipped:i})=>e===`plugin`&&t!==void 0&&!i?[{plugin:t,version:n,origin:r}]:[]),i=new Map;for(let e of r)(t!==`user`||e.origin!==`dependency`)&&(i.has(e.plugin)||i.set(e.plugin,e));let a=n.flatMap(({tier:e,skill:t,skipped:n})=>e==="default"&&t!==void 0&&!n?[t]:[]),o=Array.isArray(e)?void 0:e.skills;return{plugins:i,skills:o&&!o.unverified?new Set([...a,...o.skills.map(({name:e})=>e)]):void 0}}function compareSources(e,{plugins:t,skills:n}){return e.map(e=>{let r={status:`current`};if(`default`in e&&(r.default=e.default),e.plugin!==void 0&&(r.plugin=e.plugin),e.version!==void 0&&(r.recorded=e.version),e.plugin===void 0)return`default`in e&&n&&!n.has(e.default)&&(r.status=`missing`),r;let i=t.get(e.plugin);return i?(i.version!==void 0&&(r.installed=i.version),e.version!==void 0&&e.version!==i.version&&(r.status=`changed`),r):(r.status=`missing`,r)})}function describeSource(e){let t=e.default===void 0?`plugin ${e.plugin}`:`the default of ${e.default}`;return e.status===`missing`?e.plugin!==void 0&&e.default!==void 0?`${t} (plugin ${e.plugin}) is not installed`:`${t} is not installed`:`${t}${e.default===void 0?``:` (plugin ${e.plugin})`} is ${e.installed??`installed with no version`}, recorded ${e.recorded}`}function staleMessage(e,t){return`it is stale: ${t.filter(({status:e})=>e!==`current`).map(describeSource).join(`; `)}. Customize mode revises "${e}" from its recorded request`}function checkGenerated(e,t,n){let r=readGeneratedRecord(e,n);if(r.sources===void 0&&r.request===void 0)return;let i=compareSources(r.sources??[],t),a={sources:i,stale:i.some(({status:e})=>e!==`current`)};return r.request!==void 0&&(a.request=r.request),a}function recordedSources(e,t,n){return e.flatMap(e=>{if(e==="default"){if(!n)return[];let e=n.plugin===void 0?void 0:t.plugins.get(n.plugin);return e?[e.version===void 0?{default:n.skill,plugin:e.plugin}:{default:n.skill,plugin:e.plugin,version:e.version}]:[{default:n.skill}]}let r=t.plugins.get(e);return r?[r.version===void 0?{plugin:e}:{plugin:e,version:r.version}]:[]})}function generatedFrontmatter(e){let t={};return e.sources?.length&&(t.sources=e.sources.map(e=>({...e}))),e.request!==void 0&&(t.request=e.request.endsWith(`
|
|
165
|
+
`)?e.request:`${e.request}\n`),t}const Fn=[`merge`,`extends`,`implements`,`aliases`],In=[`sources`,`request`];function names(e){try{return new Set(o(e))}catch{return new Set}}function filesFor(e,t,n){let r=names(e.dir),at=n=>({folder:e,file:n,as:t,path:C(e.dir,...n.split(`/`)),relative:`${e.folder}/.agents/references/${n}`});return{markdown:[`${t}.md`,`${t}/README.md`].filter(e=>r.has(e.split(`/`)[0])).map(at).filter(({path:e})=>e!==n&&tryRead$2(e)!==void 0),data:V.map(({extension:e})=>`${t}${e}`).filter(e=>r.has(e)).map(at).filter(({path:e})=>e!==n)}}function folderEntries(e,t){let n=new Map,at=e=>{let t=n.get(e);return t||(t={folder:e,ignored:!1,plugins:[]},n.set(e,t)),t};for(let t of e.folders)at(t.folder).own=t;for(let t of e.ignored)Object.assign(at(t.folder),{own:t,ignored:!0});for(let e of t)at(e.folder).plugins.push(e);return[...n.values()].sort((e,t)=>comparePaths(e.folder,t.folder))}function readProjectSections(e,t){let{root:n,cache:r,catalog:i,held:a=new Set}=t,o=projectFolders(n,r),s=packagePlugins(n,r,a),c={...t,older:t.older??[],catalog:i&&withPackagePlugins(i,s),dropping:droppingOperation(t.managed),listed:e=>!o.listed||o.listed.has(e.relative)},l={sections:[],trace:[]};for(let t of folderEntries(o,s)){for(let n of pluginHits(e,t,c))readPluginSection(e,n,c,l);t.own&&readOwnSection(e,t.own,t.ignored,c,l)}return l}function withPackagePlugins(e,t){if(!t.length)return e;let n=new Map(e.plugins);for(let{plugin:e,version:r}of t)n.has(e)||n.set(e,{plugin:e,version:r,origin:`package`});return{...e,plugins:n}}function pluginHits(e,t,n){let r=[];for(let i of[...t.plugins].sort((e,t)=>e.plugin.localeCompare(t.plugin))){let a={folder:t.folder,dir:packagePluginReferences(i)},[o]=[e,...n.older].flatMap(e=>filesFor(a,e,n.without).markdown);if(!o)continue;let{metadata:s,body:c}=parseDocument(tryRead$2(o.path)??``,n.warnAt(`plugin ${n.display(o.path)}`)),l=readExtends(s.extends,()=>{})??[];r.push({plugin:i,hit:o,metadata:s,body:c,after:l.map(({target:e})=>e)})}let i=[],a=new Set(r.map(({plugin:e})=>e.plugin));for(;r.length;){let e=new Set(i.map(({plugin:e})=>e.plugin)),t=r.findIndex(({after:t})=>t.every(t=>!a.has(t)||e.has(t)));i.push(...r.splice(t===-1?0:t,1))}return i}function readPluginSection(e,t,n,r){let{plugin:i,hit:a,metadata:o,body:s}=t,c={folder:i.folder,path:a.path,file:a.file,frontmatter:o,outcome:`used`,plugin:i.plugin};i.version!==void 0&&(c.version=i.version),a.as!==e&&(c.alias=a.as),r.trace.push(c);let l=`plugin ${n.display(a.path)}`;if(n.format!==void 0&&n.format!==`markdown`){c.outcome=`not used (format differs from ${n.format})`,n.warnAt(l)(`project-section-not-markdown`,`it is not delivered: the main document of "${e}" is ${n.format}, which has no project sections`);return}if(n.dropping){c.outcome=`shadowed by ${n.dropping.label} (${n.dropping.operation})`;return}if(!hasBody(s)){c.outcome=`not used (no body)`;return}let u={...o};for(let e of[...Fn,...In,`declined`])delete u[e];let d=applyManaged(s,l,n.managed,n.warnAt);d.sections&&(c.sections=d.sections),r.sections.push({folder:i.folder,path:a.path,content:d.content,metadata:u,plugin:i.plugin})}function warnQualifiedOverrides(e,t,n){let{display:r,without:i,warnAt:a,listed:o}=n;for(let n of qualifiedOverrides(t.dir,e)){let s={folder:t,file:n.file,as:e,path:n.path,relative:`${t.folder}/.agents/references/${n.file}`};n.path!==i&&o(s)&&warnLegacy(qualifiedOverrideFinding(n,`project`),``,a(`project ${r(n.path)}`))}}function readOwnSection(e,t,n,r,i){let{trace:a,sections:o}=i,{format:s,display:c,without:l,warnAt:u,catalog:d,older:f,listed:p,dropping:m,managed:h}=r;n||warnQualifiedOverrides(e,t,r);let g=[e,...f].map(e=>filesFor(t,e,l)),_=g.flatMap(e=>e.markdown),v=g.flatMap(e=>e.data);if(n||![..._,...v].some(p)){(_.length||v.length)&&a.push({folder:t.folder,path:t.dir,outcome:`not read (ignored)`});return}for(let t of v.filter(p))u(c(t.path))(`project-section-not-markdown`,`it is not delivered: a project section is Markdown, written as ${e}.md`);let[y,...b]=_.filter(p);if(!y)return;for(let e of b)u(c(e.path))(`file-ignored`,`it is ignored: ${y.file} answers first in that folder`);let x={folder:t.folder,path:y.path,file:y.file,outcome:`used`};a.push(x);let S=`project ${c(y.path)}`;if(y.as!==e&&(x.alias=y.as,u(c(y.path))(`reference-renamed`,`it is filed under the older name "${y.as}" and applies as "${e}"; rename it to the new name`)),s!==void 0&&s!==`markdown`){x.outcome=`not used (format differs from ${s})`,u(S)(`project-section-not-markdown`,`it is not delivered: the main document of "${e}" is ${s}, which has no project sections`);return}let{metadata:C,body:w}=parseDocument(tryRead$2(y.path)??``,u(S));x.frontmatter=C;let T={...C},E=legacyRewrite(C,w,`project`,e).findings;for(let e of E)warnLegacy(e,"Run `reference migrate` to rewrite it.",u(S));let D=new Set(E.flatMap(({form:e})=>e===`project-selection`?[`extends`]:e===`overrides`?[`overrides`]:[`merge`]));delete T.overrides;for(let e of Fn)e in T&&(delete T[e],!D.has(e)&&u(S)(`project-section-key-ignored`,`\`${e}\` is ignored in the project section for ${t.folder}: a project section states only what differs in its folder`));if(m){x.outcome=`shadowed by ${m.label} (${m.operation})`;return}if(!hasBody(w)){x.outcome=`not used (no body)`;return}for(let e of In)delete T[e];let O=applyManaged(w,S,h,u);O.sections&&(x.sections=O.sections);let k=d&&checkGenerated(C,d,u(S));k&&(k.sources.length&&(x.sources=k.sources),k.request!==void 0&&(x.request=k.request),k.stale&&(x.outcome=`stale`,u(S)(`reference-stale`,staleMessage(e,k.sources)))),o.push({folder:t.folder,path:y.path,content:O.content,metadata:T})}function droppingOperation(e){if(e?.entry.outcome!==`used`)return;let t=e.merge??`patch`;if(t===`remove`||t===`replace`&&e.hasBody)return{label:e.label,operation:t}}function applyManaged(e,t,n,r){let i=withNewline(trimLeadingBlank(stripMergeMarkers(e)));if(n?.entry.outcome!==`used`||!n.hasBody||n.whole)return{content:i};let a=n.merge??`patch`;if(a===`remove`||a===`replace`)return{content:i};let o=applyContribution(emptyComposed(),e,`patch`,t,r(t)),s=applyContribution(o,n.body,a,n.label,r(n.label),{matchedOnly:!0}),c=renderComposed(s);return c===renderComposed(o)?{content:i}:{content:c,sections:composedSections(s).map(({path:e,sources:t})=>({path:e,contributions:t}))}}function projectSectionNames(e,t,n=new Set){let r=projectFolders(e,t),i=new Set;for(let e of r.folders)for(let t of layerNames({tier:`project`,dir:e.dir})){let{markdown:n}=filesFor(e,t,void 0);n.some(e=>!r.listed||r.listed.has(e.relative))&&i.add(t)}for(let r of packagePlugins(e,t,n)){let e=packagePluginReferences(r);for(let t of layerNames({tier:`plugin`,dir:e}))filesFor({folder:r.folder,dir:e},t,void 0).markdown.length&&i.add(t)}return[...i]}function projectQualifiedNames(e,t){let n=projectFolders(e,t);return n.folders.flatMap(e=>qualifiedOverrides(e.dir).filter(({file:t})=>!n.listed||n.listed.has(`${e.folder}/.agents/references/${t}`)).map(({name:e})=>e))}const Ln=`_renames.yaml`,Rn=new WeakMap;function bare(e){if(typeof e!=`string`)return;let t=parseReferenceName(e.trim());return t.invalid||t.plugin!==void 0?void 0:t.name}function renameTable(e){let t=Array.isArray(e)?void 0:e,n=t&&Rn.get(t);if(n)return n;let r=Array.isArray(e)?e:e.layers,i=new Map,a=[],o=new Set;for(let e of r){if(e.tier!==`plugin`||e.skipped||e.plugin===void 0)continue;let t=C(e.dir,Ln);if(o.has(t))continue;o.add(t);let n=tryRead$2(t);if(n===void 0)continue;let r=e.plugin,s;try{s=(0,en.parse)(n)}catch{s=void 0}if(s==null){n.trim()&&a.push({code:`rename-invalid`,message:`plugin ${r}: ${t} is not YAML; it is ignored`});continue}if(!isRecord$1(s)){a.push({code:`rename-invalid`,message:`plugin ${r}: ${t} is not a mapping of older names to new names; it is ignored`});continue}for(let[e,t]of Object.entries(s)){let n=bare(e),o=bare(t);if(n===void 0||o===void 0||n===o){a.push({code:`rename-invalid`,message:`plugin ${r}: the rename ${JSON.stringify(e)}: ${JSON.stringify(t)} in ${Ln} is not a pair of bare reference names; it is ignored`});continue}let s=i.get(n)??[];s.some(e=>e.to===o&&e.plugin===r)||s.push({from:n,to:o,plugin:r}),i.set(n,s)}}let s={byOld:i,warnings:a};return t&&Rn.set(t,s),s}function layersOf(e){return Array.isArray(e)?{layers:[...e],harnesses:[]}:e}function emptyTrace(e){return{stack:[],builtBy:`none`,contributions:[],sections:[],layers:[],harnesses:[...e],projectSections:[]}}function stackOrder(e,t){let rank=e=>{if(e.tier!==`plugin`&&e.tier!=="default")return-1;let n=t.indexOf(e.tier==="default"?`default`:e.plugin??``);return n===-1?t.length:t.length-1-n};return e.map((e,t)=>({layer:e,index:t,rank:rank(e)})).sort((e,t)=>e.rank-t.rank||e.index-t.index).map(({layer:e})=>e)}function resolveReference(e,t,n={}){return resolveAdjusted(e,t,n,void 0)}function resolveAdjusted(e,t,{display:n=e=>e,without:r,below:i,projectSections:a=!0},o){let s=typeof e==`string`?parseReferenceName(e):e,{layers:c,harnesses:l,root:u,projects:d}=layersOf(t),f=emptyTrace(l),p=[],m={name:s.raw,status:`missing`,projectSections:[],warnings:p,trace:f};if(s.invalid)return{...m,status:`invalid`,code:`reference-invalid`,message:s.invalid};let h=new Set,warnAt=e=>(t,n)=>{let r=e?`${e}: ${n}`:n;h.has(`${t} ${r}`)||(h.add(`${t} ${r}`),p.push({code:t,message:r}))},g=warnAt(``),_=aliasIndex(t),v=resolveAlias(s,_,g);if(v.kind===`ambiguous`)return{...m,status:`ambiguous`,code:`reference-ambiguous`,message:v.message,cause:`alias`,options:v.names};let y=v.kind===`renamed`?v.ref:s;v.kind===`renamed`&&(f.alias={name:v.alias,resolvedAs:y.name});let b=olderNames(y.name,_,g);v.kind===`own`&&warnTableRename(y,t,_,g);let x=i===void 0?-1:c.findIndex(e=>e.dir===i),S=x===-1?c:c.slice(x+1),C=[];for(let e of S){e.warning&&g(e.warning.code,e.warning.message);let t={tier:e.tier,path:e.dir,outcome:`missing`};if(e.plugin!==void 0&&(t.plugin=e.plugin),e.skill!==void 0&&(t.skill=e.skill),f.layers.push(t),e.skipped){t.outcome=`not read (${e.skipped})`;continue}let i=readContribution(e,y.name,t,{display:n,without:r,warnAt,older:b}),a=o?o(e,i,t):i;a?C.push(a):e.tier==="default"&&(t.outcome=`not read (no default)`)}warnMisplacedAliases(C,warnAt);let w=new Map;for(let e of C.filter(({layer:e})=>e.tier===`plugin`)){let t=e.layer.plugin,r=w.get(t);r?e.entry.outcome=`not read (plugin ${t} answers from ${n(r.path)})`:w.set(t,e)}let T=C.find(({layer:e})=>e.tier==="default"),E=C.filter(({layer:e})=>e.tier!==`plugin`&&e.tier!=="default"),D=new Set(S.flatMap(({plugin:e,skipped:t})=>e&&!t?[e]:[])),lookup=e=>e==="default"?T??{reason:`has no default`}:w.get(e)??{reason:D.has(e)?`holds no ${y.name}`:`is not installed`},options=()=>[...[...w.keys()].map(e=>`${e}/${y.name}`),...T?[`default`]:[]];if(interfaceIdOf(y.name)!==void 0)return resolveInterface(y,C,w,T,m,g,options);let sectionsOver=e=>{if(u===void 0||i!==void 0||!a)return{sections:[],trace:[]};let o=E.find(({layer:e})=>e.tier===`managed`),s=sourceCatalog(t,{tier:`project`}),c=readProjectSections(y.name,{root:u,cache:d,managed:o,format:e,display:n,without:r,warnAt,catalog:s,older:b,held:heldPlugins(layersOf(t))});return f.projectSections=c.trace,c},O=plan(y,E,w,lookup,T,g);if(`status`in O){if(O.status===`ambiguous`){for(let{entry:e}of C)e.outcome===``&&(e.outcome=`ambiguous`);return{...m,status:`ambiguous`,code:`reference-ambiguous`,message:O.message,cause:O.cause,options:options()}}for(let{entry:e}of C)e.outcome===``&&(e.outcome=`not used (qualified name)`);return{...m,status:`missing`,code:`reference-missing`,message:O.message}}!S.some(({tier:e})=>e==="default")&&C.some(({steps:e})=>namesDefault(e))&&f.layers.push({tier:`default`,path:`(no skill folder given)`,outcome:`not read (no default)`}),f.stack=O.entries.map(({target:e})=>e),f.builtBy=O.builtBy,f.layers=stackOrder(f.layers,f.stack);let k=new Set(f.stack);for(let[e,t]of[...w.entries(),...T?[[`default`,T]]:[]]){if(k.has(e))continue;let n=O.replaced.find(t=>t.target===e);t.entry.outcome=y.plugin===void 0?n?`not used (${n.step}'s extends replaced by ${O.replacedBy})`:`not used (not in extends)`:`not used (qualified name)`}y.plugin===void 0&&warnUndecided(y.name,O,w,k,warnAt);let{composed:ee,applied:A,removedBy:te,used:ne,whole:re}=composeOrder([...O.entries,...[...E].reverse().map(e=>({contribution:e,operation:e.merge??`patch`,from:e.merge?`contribution`:`default`}))],warnAt);if(markStale(y.name,ne,t,warnAt),f.sections=ee.removed.map(({path:e,by:t})=>({path:e,contributions:[],removedBy:t})),!A.length){let e=sectionsOver(void 0).sections;if(e.length)return{...m,status:`found`,content:``,format:`markdown`,metadata:{},projectSections:e};if(te)return f.removedBy=te.label,{...m,status:`missing`,code:`reference-removed`,message:`"${y.name}" is turned off by ${te.label} (remove)`};let t=y.plugin===void 0?`no tier holds a document for "${y.name}"`:`the plugin ${y.plugin} holds no document for "${y.name}"`;return{...m,status:`missing`,code:`reference-missing`,message:t}}let ie=ne.filter(({entry:e})=>e.outcome===`used`||e.outcome===`stale`);if(f.contributions=A.map(({layer:e,entry:t})=>{let n={tier:e.tier,path:t.path,operation:t.operation};return t.plugin!==void 0&&(n.plugin=t.plugin),t.skill!==void 0&&(n.skill=t.skill),n}),f.sections=[...composedSections(ee).map(({path:e,sources:t})=>({path:e,contributions:t})),...f.sections],re)return sectionsOver(re.format),{...m,status:`found`,content:re.body,format:re.format,metadata:composedMetadata(ie)};let ae=A.length===1&&!ee.removed.length?A[0].body:void 0,j=ae!==void 0&&stripMergeMarkers(ae)===ae?withNewline(trimLeadingBlank(ae)):renderComposed(ee);return{...m,status:`found`,content:j,format:`markdown`,metadata:composedMetadata(ie),projectSections:sectionsOver(`markdown`).sections}}function markStale(e,t,n,r){for(let i of t){let{layer:t,entry:a}=i;if(a.outcome!==`used`||t.tier!==`repo`&&t.tier!==`user`)continue;let o=r(i.label),s=checkGenerated(i.metadata,sourceCatalog(n,{tier:t.tier}),o);s&&(s.sources.length&&(a.sources=s.sources),s.request!==void 0&&(a.request=s.request),s.stale&&(a.outcome=`stale`,o(`reference-stale`,staleMessage(e,s.sources))))}}function warnUndecided(e,t,n,r,i){let a=t.builder;if(!a||a.layer.tier!==`repo`&&a.layer.tier!==`user`)return;let o=new Set(readDeclined(a.metadata.declined,i(a.label))),s=[];for(let[e,t]of n)r.has(e)||(a.layer.tier!==`user`||t.layer.origin!==`dependency`)&&(o.has(e)?t.entry.outcome=`not used (declined by ${a.label})`:s.push(e));if(!s.length)return;let c=a.layer.tier===`user`?` --scope user`:``,l=pickValues(a.steps??[]),u=l?`run "reference customize ${e}${c} --extends ${[...l,...s].join(` `)}" to add ${s.length>1?`them`:`it`}, or "reference customize ${e}${c} --extends ${l.join(` `)}" to leave ${s.length>1?`them`:`it`} out`:`add ${s.length>1?`them`:`it`} to the extends with "reference customize ${e}${c} --extends-file <file>", or write the same extends again to leave ${s.length>1?`them`:`it`} out`,d=s.join(`, `);i(a.label)(`plugin-not-selected`,`${s.length>1?`the plugins`:`the plugin`} ${d} ${s.length>1?`hold`:`holds`} "${e}" but ${s.length>1?`are`:`is`} neither in its extends nor declined, so ${s.length>1?`they are`:`it is`} not used; ${u}`)}function resolveInterface(e,t,n,r,i,a,o){for(let e of t)(e.merge!==void 0||e.steps!==void 0)&&a(`interface-not-composed`,`${e.label}: merge and extends on an interface document are ignored; an interface is never composed`);if(e.plugin===void 0&&n.size>1){for(let{entry:e}of t)e.outcome===``&&(e.outcome=`ambiguous`);return{...i,status:`ambiguous`,code:`reference-ambiguous`,message:`the plugins ${[...n.keys()].join(`, `)} each hold the interface document`,cause:`unordered`,options:o()}}let s=e.plugin===void 0?[...n.values()]:n.has(e.plugin)?[n.get(e.plugin)]:[];if(e.plugin!==void 0){for(let[t,r]of n)t!==e.plugin&&(r.entry.outcome=`not used (qualified name)`);if(!s.length)return{...i,status:`missing`,code:`reference-missing`,message:`the plugin ${e.plugin} holds no "${e.name}"`}}let c=t.filter(({layer:e})=>e.tier!==`plugin`&&e.tier!=="default"),[l,...u]=[...e.plugin===void 0&&r?[r]:[],...s,...[...c].reverse()];if(!l)return{...i,status:`missing`,code:`reference-missing`,message:`no tier holds a document for "${e.name}"`};for(let e of u)e.entry.outcome=`not used (an interface document is never composed)`,a(`interface-not-composed`,`${e.label} is ignored: an interface document is never composed; define a new interface id instead`);r&&r!==l&&(r.entry.outcome=`not used (qualified name)`),l.entry.outcome=`used`,l.entry.operation=`replace`,l.entry.operationFrom=`default`;let{trace:d}=i;return l.layer.tier===`plugin`&&(d.stack=[l.layer.plugin]),l.layer.tier==="default"&&(d.stack=[`default`]),d.contributions=[{tier:l.layer.tier,...l.entry.plugin?{plugin:l.entry.plugin}:{},...l.entry.skill?{skill:l.entry.skill}:{},path:l.path,operation:`replace`}],{...i,status:`found`,content:withNewline(trimLeadingBlank(stripMergeMarkers(l.body))),metadata:composedMetadata([l])}}function referenceNames(e){return[...new Set(layersOf(e).layers.flatMap(layerNames))].sort((e,t)=>e.localeCompare(t))}function warnTableRename(e,t,n,r){if(n.owned.has(e.name))return;let i=(renameTable(t).byOld.get(e.name)??[]).filter(t=>e.plugin===void 0||t.plugin===e.plugin);if(!i.length)return;let a=[...new Set(i.map(({plugin:e})=>`plugin ${e}`))].join(` and `),o=[...new Set(i.map(({to:e})=>`"${e}"`))].join(` or `);r(`reference-renamed`,`${a} renamed "${e.name}" to ${o}: load ${o} instead, and run \`reference migrate\` to rename the files filed under "${e.name}"`)}function skillHoldings(e){return(Array.isArray(e)?[]:e.skills?.skills??[]).flatMap(e=>layerNames(defaultLayer(e.folder)).map(t=>({name:t,skill:e}))).sort((e,t)=>e.name.localeCompare(t.name)||e.skill.name.localeCompare(t.skill.name))}function defaultsUnverified(e){return Array.isArray(e)?void 0:e.skills?.unverified}function withDefault(e,t){let n=Array.isArray(e)?{layers:[...e],harnesses:[]}:e;return{...n,layers:[...n.layers.filter(({tier:e})=>e!=="default"),defaultLayer(t)]}}function patternMatcher(e){let t=e.split(`*`).map(e=>e.replace(/[.+?^${}()|[\]\\]/g,`\\$&`));return RegExp(`^${t.join(`.*`)}$`,`s`)}function firstLine$1(e){return typeof e==`string`&&e.split(`
|
|
166
|
+
`)[0]?.trim()||``}function collect(e,t,n){for(let r of n){let n=`${r.code} ${r.message}`;t.has(n)||e.push(r),t.add(n)}}function layerRow(e,t){let n={name:e,tier:t.tier,path:t.path,description:firstLine$1(t.description),outcome:t.outcome};return t.plugin!==void 0&&(n.plugin=t.plugin),t.skill!==void 0&&(n.skill=t.skill),t.selection?n.kind=`selection`:isGenerated(t.frontmatter)&&(n.kind=`generated`),n}function projectRow(e,t){return{name:e,tier:`project`,path:t.path,description:firstLine$1(t.frontmatter?.description),outcome:t.outcome,kind:`project-section`,folder:t.folder,...t.plugin===void 0?{}:{plugin:t.plugin}}}function catalogNames(e){let t=Array.isArray(e)?void 0:e,n=t?.root===void 0?[]:projectSectionNames(t.root,t.projects,heldPlugins(t)),r=aliasIndex(e);return[...new Set([...referenceNames(e),...n].map(e=>shownName(e,r)))]}function listReferences(e,t={}){let{pattern:n,...r}=t,i=n===void 0?void 0:patternMatcher(n),a={references:[],layers:[],warnings:[]},o=defaultsUnverified(e);o&&(a.defaults=o);let s=new Set,c=skillHoldings(e),l=[...new Set([...catalogNames(e),...c.map(({name:e})=>e)])].sort((e,t)=>e.localeCompare(t));for(let t of l){if(i&&!i.test(t))continue;let n=c.filter(e=>e.name===t),o=resolveReference(t,e,r);!(o.trace.layers.some(({file:e,tier:t})=>e&&t!=="default")||o.trace.projectSections.some(({file:e})=>e))&&n[0]&&(o=resolveReference(t,withDefault(e,n[0].skill.folder),r)),collect(a.warnings,s,o.warnings);let l={name:t,description:o.status===`found`?firstLine$1(o.metadata?.description):``,status:o.status};if(o.code&&(l.code=o.code),o.format&&o.format!==`markdown`&&(l.format=o.format),o.options){let e=n.map(({skill:e})=>`default of ${e.name}`);l.options=[...new Set([...o.options.filter(e=>e!=="default"),...e])]}a.references.push(l);for(let e of o.trace.layers)e.file!==void 0&&e.tier!=="default"&&a.layers.push(layerRow(t,e));for(let e of o.trace.projectSections)e.file!==void 0&&a.layers.push(projectRow(t,e));for(let{skill:i}of n)a.layers.push(defaultRow(t,i.name,i.folder,e,r))}return a}function defaultRow(e,t,n,r,i){return{...layerRow(e,resolveReference(e,withDefault(r,n),i).trace.layers.find(({tier:e,file:t})=>e==="default"&&t)),reachedBy:`the default step, when ${t} loads ${e}`}}const zn=[`name`,`prefix`,`close name`,`description`,`heading`,`body`];function distance(e,t){let n=Array.from({length:t.length+1},(e,t)=>t);for(let r=1;r<=e.length;r++){let i=[r];for(let a=1;a<=t.length;a++){let o=n[a-1]+(e[r-1]===t[a-1]?0:1);i.push(Math.min(n[a]+1,i[a-1]+1,o))}n=i}return n[t.length]}function headings(e){let t=!1,n=[];for(let r of e.split(`
|
|
167
167
|
`))/^ {0,3}(`{3,}|~{3,})/.test(r)?t=!t:!t&&/^ {0,3}#{1,6}\s/.test(r)&&n.push(r);return n.join(`
|
|
168
|
-
`)}function tagText(e){return Array.isArray(e)?e.map(String).join(` `):typeof e==`string`?e:``}function matchKind(e,t,n){let r=e.slice(e.lastIndexOf(`/`)+1).toLowerCase();if(r===n||e.toLowerCase()===n)return`name`;if(r.startsWith(n))return`prefix`;if(r.includes(n)||distance(r,n)<=Math.max(1,Math.floor(n.length/4)))return`close name`;let i=n.split(/\s+/),holds=e=>{let t=e.toLowerCase();return i.every(e=>t.includes(e))},a=t.metadata??{};return holds(`${typeof a.description==`string`?a.description:``} ${tagText(a.tags)}`)?`description`:textMatch(t.content??``,holds)}function textMatch(e,t){if(t(headings(e)))return`heading`;if(t(e))return`body`}function sectionMatchKind(e,t){let n=t.split(/\s+/),holds=e=>{let t=e.toLowerCase();return n.every(e=>t.includes(e))},{metadata:r}=e;return holds(`${typeof r.description==`string`?r.description:``} ${tagText(r.tags)}`)?`description`:textMatch(e.content,holds)}function searchReferences(e,t,n={}){let r=e.trim().toLowerCase();if(!r)throw new ReferenceFailure(`query-missing`,`search needs a query: what the reference is about.`,{help:"Run `reference list` for every name."});let i=[],a=new Set,considerSections=e=>{let t=parseReferenceName(e.name).name;for(let n of e.projectSections){let o=`${t}\0${n.folder}\0${n.plugin??``}`;if(a.has(o))continue;a.add(o);let s=sectionMatchKind(n,r);s&&i.push({name:e.name,description:firstLine$1(n.metadata.description),match:s,tier:`project`,folder:n.folder,...n.plugin===void 0?{}:{plugin:n.plugin}})}},consider=(e,t)=>{if(e.status!==`found`)return;considerSections(e);let n=matchKind(e.name,e,r);if(!n)return;let a=e.trace.contributions.at(-1),o={name:e.name,description:firstLine$1(e.metadata?.description),match:n,tier:a?.tier??`plugin`};a?.plugin!==void 0&&(o.plugin=a.plugin),a?.skill!==void 0&&(o.skill=a.skill),t!==void 0&&(o.loadedBy=t),i.push(o)},o=new Map;for(let e of catalogNames(t)){let r=resolveReference(e,t,n);if(o.set(e,r.content),r.status!==`ambiguous`)consider(r);else for(let e of r.options??[])e!=="default"&&consider(resolveReference(e,t,n))}for(let{name:e,skill:r}of skillHoldings(t)){let i=resolveReference(e,withDefault(t,r.folder),n);i.trace.layers.some(({tier:e,outcome:t})=>e==="default"&&t===`used`)&&i.content!==o.get(e)&&consider(i,r.name)}i.sort((e,t)=>Bn.indexOf(e.match)-Bn.indexOf(t.match)||e.name.localeCompare(t.name)||comparePaths(e.folder??``,t.folder??``));let s=defaultsUnverified(t);return s?{matches:i,defaults:s}:{matches:i}}function isTiered(e){return e===`managed`||e===`repo`||e===`project`||e===`user`}function hides(e){return!e.file||e.outcome!==`used`&&e.outcome!==`stale`?!1:e.operation===`remove`||e.operation===`replace`&&!e.empty}function stackTarget(e){return e.tier==="default"?`default`:e.plugin??``}function above(e,t,n){let r=e.trace.layers,i=r.findIndex(e=>e.path===t||e.path===n),a=r[i];if(!a)return[];let tiersAbove=e=>r.slice(0,e).filter(({tier:e})=>isTiered(e)).reverse();if(isTiered(a.tier))return tiersAbove(i);let{stack:o}=e.trace,s=o.indexOf(stackTarget(a));return[...s===-1?[]:r.filter(e=>!isTiered(e.tier)&&o.indexOf(stackTarget(e))>s).sort((e,t)=>o.indexOf(stackTarget(e))-o.indexOf(stackTarget(t))),...tiersAbove(r.length)]}function hiderLabel(e,t=e=>e){return`${e.tier}${e.plugin?` ${e.plugin}`:``} ${t(e.path)} (${e.operation})`}function hidingLayer(e,t,n){return above(e,t,n).find(hides)}function projectHidingLayer(e){return e.trace.layers.find(e=>e.tier===`managed`&&hides(e))}const Vn={"frontmatter-invalid":`defect`,"merge-unknown":`defect`,"marker-unknown":`defect`,"marker-unmatched":`defect`,"heading-repeated":`defect`,"remove-body-ignored":`defect`,"extends-invalid":`defect`,"extends-self":`defect`,"extends-step-missing":`environment`,"extends-all-missing":`environment`,"extends-not-used":`environment`,"section-not-held":`environment`,"default-not-selected":`environment`,"plugin-not-selected":`environment`,"default-folder-missing":`environment`,"default-in-tier":`defect`,"file-ignored":`defect`,"format-mismatch":`defect`,"metadata-ignored":`defect`,"project-section-key-ignored":`project-section`,"interface-not-composed":`defect`,"interface-check":`environment`,"base-moved":`environment`,"reference-stale":`environment`,"reference-renamed":`environment`,"alias-not-used":`environment`,"rename-invalid":`environment`,"reference-legacy-format":`defect`,"alias-invalid":`defect`,"project-section-not-markdown":`project-section`,"reference-hidden":`environment`,"repo-hides-user":`environment`};function splitComposeWarnings(e){let t=[],n=[];for(let r of e){let e=Vn[r.code];e===`defect`?t.push(r):e===`environment`&&n.push(r)}return{defects:t,passed:n}}function hiddenWarnings(e,t){let n=[],message=(e,n)=>`${t(e)} is hidden: ${n} applies above it, so load does not read it until that contribution changes`;for(let r of e.trace.layers){if(r.tier!==`repo`&&r.tier!==`user`||!r.file)continue;let i=hidingLayer(e,r.path,r.path);i&&n.push({code:r.tier===`user`&&i.tier===`repo`?`repo-hides-user`:`reference-hidden`,message:message(r.path,hiderLabel(i,t))})}let r=projectHidingLayer(e);if(r)for(let i of e.trace.projectSections)i.file&&i.plugin===void 0&&i.outcome.startsWith(`shadowed by`)&&n.push({code:`reference-hidden`,message:message(i.path,hiderLabel(r,t))});return n}function baseMovedWarnings(e,t){let n=[],r;for(let i of e.trace.layers){if(i.tier!==`plugin`&&i.tier!=="default"||!i.file||!i.frontmatter||i.outcome!==`used`&&i.outcome!==`stale`)continue;let{sources:e}=readGeneratedRecord(i.frontmatter);if(!e)continue;r??=sourceCatalog(t,{tier:`plugin`});let a=i.tier===`plugin`?`plugin ${i.plugin}`:`default of ${i.skill}`;for(let t of compareSources(e,r)){if(t.status!==`changed`)continue;let e=t.default===void 0?`plugin ${t.plugin}`:`the default of ${t.default} (plugin ${t.plugin})`;n.push({code:`base-moved`,message:`${a}: it records ${e} at ${t.recorded}, and ${t.installed??`a version with no number`} is installed; review it against the installed base and record the new version`})}}return n}function interfaceLookup(e,t={}){let n=new Map;return r=>{let i=n.get(r);if(i)return i;let a=lookUp(r,e,t);return n.set(r,a),a}}function lookUp(e,t,n){let r=resolveReference(`${e}${jn}`,t,n),i=interfaceIdOf(r.trace.alias?.resolvedAs??``);if(i!==void 0){let e=readFound(i,r);return e.value?{...e,renamed:i}:e}if(r.status===`missing`){let r=[...aliasIndex(t).interfaces].filter(([,t])=>t.some(({alias:t})=>t===e)).map(([e])=>e);if(r.length>1)return lookupFailure(e,`${e} is an older id of ${r.join(` and `)}; implement one of them by its own id`);if(r.length===1){let e=r[0],i=readFound(e,resolveReference(`${e}${jn}`,t,n));return i.value?{...i,renamed:e}:i}}return readFound(e,r)}function lookupFailure(e,t){return{failure:{check:`interface-found`,interface:e,message:t}}}function readFound(e,t){let n=`${e}${jn}`;if(t.status===`invalid`)return lookupFailure(e,`${e} is not an interface id`);if(t.status===`missing`)return lookupFailure(e,`no interface document ${n}`);if(t.status===`ambiguous`)return lookupFailure(e,`${n} is ambiguous between ${(t.options??[]).join(` and `)}`);let{value:r,problems:i}=readInterface(e,t.metadata??{});return r?{value:r}:lookupFailure(e,`${n} is malformed: ${i.join(`; `)}`)}function bareName$1(e){let t=e.trace.alias?.resolvedAs??e.name;return t.slice(t.lastIndexOf(`/`)+1)}function kindOf(e){let t=e.metadata??{};return interfaceIdOf(bareName$1(e))!==void 0||t.interface!==void 0?`interface`:t.implements===void 0?`none`:`implementation`}function composeFailure(e){let{defects:t}=splitComposeWarnings(e);if(t.length)return{check:`compose`,message:`composing it raised ${t.length===1?`a warning`:`${t.length} warnings`}: ${t.map(({code:e,message:t})=>`${e}: ${t}`).join(`; `)}`}}function checkResolved(e,t,n){let r={failures:[],unsupported:[],warnings:[]};if(e.status!==`found`)return r;let{failures:i,warnings:a}=r,o=bareName$1(e),s=e.metadata??{};if(kindOf(e)===`interface`){let e=interfaceIdOf(o);if(e===void 0)i.push({check:`interface`,message:`${o} has an \`interface:\` block; an interface document is named <id>${jn}`});else for(let t of readInterface(e,s).problems)i.push({check:`interface`,interface:e,message:t})}else{let{entry:c,problems:l}=readImplements(s);for(let e of l)i.push({check:`interface-found`,message:e});if(c){let s=t(c.id);if(s.value){let t=s.value.id;s.renamed!==void 0&&a.push({code:`reference-renamed`,message:`implements names ${c.id}@${c.version}, an older id of ${t}; declare implements: ${t}@${c.version}`});let l=checkImplementation(s.value,{name:o,version:c.version,content:e.content??``,accept:n?.id===t?n.versions:void 0,declaredId:c.id});i.push(...l.failures),r.unsupported=l.unsupported}else i.push(s.failure)}}let c=composeFailure(e.warnings);return c&&i.push(c),r}function dedupe(e){let t=new Set;return e.filter(({code:e,message:n})=>{let r=`${e} ${n}`;return!t.has(r)&&(t.add(r),!0)})}const warningKey=({code:e,message:t})=>`${e} ${t}`;function sectionWarnings({main:e,full:t}){if(t===e)return[];let n=new Set(e.warnings.map(warningKey));return t.warnings.filter(e=>!n.has(warningKey(e)))}function entryOf(e,t,n=[]){let{main:r,full:i}=e,a=r.status===`found`||i.status===`found`,o=r.status===`found`?checkResolved(r,t):{failures:[],unsupported:[],warnings:[]},s=[...o.failures];if(r.status!==`found`){!a&&r.code!==`reference-removed`&&s.push({check:r.code,message:r.message??r.status});let e=composeFailure(r.warnings);e&&s.push(e)}return{name:r.name,kind:r.status===`found`?kindOf(r):`none`,status:a?s.length?`failed`:`passed`:r.status,failures:s,unsupported:o.unsupported,warnings:dedupe([...o.warnings,...splitComposeWarnings(r.warnings).passed,...sectionWarnings(e),...n])}}function pluginCopies(e,t){let n=[...new Set(t.trace.layers.flatMap(({plugin:e,file:t})=>e!==void 0&&t?[e]:[]))];return n.length>1?n.map(t=>`${t}/${e}`):[]}function checkReferences(e,t={}){let{names:n,...r}=t,i=r.display??(e=>e),a={...r,projectSections:!1},o=interfaceLookup(e,r),s=Array.isArray(e)?void 0:e,c=new Set(s?.root===void 0?[]:[...projectSectionNames(s.root,s.projects,heldPlugins(s)),...projectQualifiedNames(s.root,s.projects)]),resolve=t=>{let n=parseReferenceName(t),i=resolveReference(n,e,a);return{main:i,full:n.plugin===void 0&&c.has(n.name)?resolveReference(n,e,r):i}},fileWarnings=({main:t,full:n})=>[...hiddenWarnings(n,i),...baseMovedWarnings(t,e)];if(n?.length)return n.map(e=>{let t=resolve(e);return entryOf(t,o,fileWarnings(t))});let l=[],u=new Map;for(let t of catalogNames(e)){let n=resolve(t);u.set(t,n.main.content),l.push(entryOf(n,o,fileWarnings(n)));for(let r of pluginCopies(t,n.main).map(resolve))l.push(entryOf(r,o,baseMovedWarnings(r.main,e)))}for(let{name:t,skill:n}of skillHoldings(e)){let r=withDefault(e,n.folder),i=resolveReference(t,r,a),s=i.trace.layers.some(({tier:e,outcome:t})=>e==="default"&&t===`used`);if(i.status!==`found`||!s)continue;let c=baseMovedWarnings(i,r);(i.content!==u.get(t)||c.length)&&l.push({...entryOf({main:i,full:i},o,c),loadedBy:n.name})}return l}function implementationTemplate(e){let t=e.sections.map(({heading:e,holds:t})=>`## ${e}\n\n**Unsupported.** ${t??`Replace this line with the section, or say in one sentence why it is not supported.`}\n`);return parseTemplate(`---\ndescription: What this ${e.id} implementation covers, and when an agent should read it.\nimplements: ${e.id}@${e.version}\n---\n\n${t.join(`
|
|
168
|
+
`)}function tagText(e){return Array.isArray(e)?e.map(String).join(` `):typeof e==`string`?e:``}function matchKind(e,t,n){let r=e.slice(e.lastIndexOf(`/`)+1).toLowerCase();if(r===n||e.toLowerCase()===n)return`name`;if(r.startsWith(n))return`prefix`;if(r.includes(n)||distance(r,n)<=Math.max(1,Math.floor(n.length/4)))return`close name`;let i=n.split(/\s+/),holds=e=>{let t=e.toLowerCase();return i.every(e=>t.includes(e))},a=t.metadata??{};return holds(`${typeof a.description==`string`?a.description:``} ${tagText(a.tags)}`)?`description`:textMatch(t.content??``,holds)}function textMatch(e,t){if(t(headings(e)))return`heading`;if(t(e))return`body`}function sectionMatchKind(e,t){let n=t.split(/\s+/),holds=e=>{let t=e.toLowerCase();return n.every(e=>t.includes(e))},{metadata:r}=e;return holds(`${typeof r.description==`string`?r.description:``} ${tagText(r.tags)}`)?`description`:textMatch(e.content,holds)}function searchReferences(e,t,n={}){let r=e.trim().toLowerCase();if(!r)throw new ReferenceFailure(`query-missing`,`search needs a query: what the reference is about.`,{help:"Run `reference list` for every name."});let i=[],a=new Set,considerSections=e=>{let t=parseReferenceName(e.name).name;for(let n of e.projectSections){let o=`${t}\0${n.folder}\0${n.plugin??``}`;if(a.has(o))continue;a.add(o);let s=sectionMatchKind(n,r);s&&i.push({name:e.name,description:firstLine$1(n.metadata.description),match:s,tier:`project`,folder:n.folder,...n.plugin===void 0?{}:{plugin:n.plugin}})}},consider=(e,t)=>{if(e.status!==`found`)return;considerSections(e);let n=matchKind(e.name,e,r);if(!n)return;let a=e.trace.contributions.at(-1),o={name:e.name,description:firstLine$1(e.metadata?.description),match:n,tier:a?.tier??`plugin`};a?.plugin!==void 0&&(o.plugin=a.plugin),a?.skill!==void 0&&(o.skill=a.skill),t!==void 0&&(o.loadedBy=t),i.push(o)},o=new Map;for(let e of catalogNames(t)){let r=resolveReference(e,t,n);if(o.set(e,r.content),r.status!==`ambiguous`)consider(r);else for(let e of r.options??[])e!=="default"&&consider(resolveReference(e,t,n))}for(let{name:e,skill:r}of skillHoldings(t)){let i=resolveReference(e,withDefault(t,r.folder),n);i.trace.layers.some(({tier:e,outcome:t})=>e==="default"&&t===`used`)&&i.content!==o.get(e)&&consider(i,r.name)}i.sort((e,t)=>zn.indexOf(e.match)-zn.indexOf(t.match)||e.name.localeCompare(t.name)||comparePaths(e.folder??``,t.folder??``));let s=defaultsUnverified(t);return s?{matches:i,defaults:s}:{matches:i}}function isTiered(e){return e===`managed`||e===`repo`||e===`project`||e===`user`}function hides(e){return!e.file||e.outcome!==`used`&&e.outcome!==`stale`?!1:e.operation===`remove`||e.operation===`replace`&&!e.empty}function stackTarget(e){return e.tier==="default"?`default`:e.plugin??``}function above(e,t,n){let r=e.trace.layers,i=r.findIndex(e=>e.path===t||e.path===n),a=r[i];if(!a)return[];let tiersAbove=e=>r.slice(0,e).filter(({tier:e})=>isTiered(e)).reverse();if(isTiered(a.tier))return tiersAbove(i);let{stack:o}=e.trace,s=o.indexOf(stackTarget(a));return[...s===-1?[]:r.filter(e=>!isTiered(e.tier)&&o.indexOf(stackTarget(e))>s).sort((e,t)=>o.indexOf(stackTarget(e))-o.indexOf(stackTarget(t))),...tiersAbove(r.length)]}function hiderLabel(e,t=e=>e){return`${e.tier}${e.plugin?` ${e.plugin}`:``} ${t(e.path)} (${e.operation})`}function hidingLayer(e,t,n){return above(e,t,n).find(hides)}function projectHidingLayer(e){return e.trace.layers.find(e=>e.tier===`managed`&&hides(e))}const Bn={"frontmatter-invalid":`defect`,"merge-unknown":`defect`,"marker-unknown":`defect`,"marker-unmatched":`defect`,"heading-repeated":`defect`,"remove-body-ignored":`defect`,"extends-invalid":`defect`,"extends-self":`defect`,"extends-step-missing":`environment`,"extends-all-missing":`environment`,"extends-not-used":`environment`,"section-not-held":`environment`,"default-not-selected":`environment`,"plugin-not-selected":`environment`,"default-folder-missing":`environment`,"default-in-tier":`defect`,"file-ignored":`defect`,"format-mismatch":`defect`,"metadata-ignored":`defect`,"project-section-key-ignored":`project-section`,"interface-not-composed":`defect`,"interface-check":`environment`,"base-moved":`environment`,"reference-stale":`environment`,"reference-renamed":`environment`,"alias-not-used":`environment`,"rename-invalid":`environment`,"reference-legacy-format":`defect`,"alias-invalid":`defect`,"project-section-not-markdown":`project-section`,"reference-hidden":`environment`,"repo-hides-user":`environment`};function splitComposeWarnings(e){let t=[],n=[];for(let r of e){let e=Bn[r.code];e===`defect`?t.push(r):e===`environment`&&n.push(r)}return{defects:t,passed:n}}function hiddenWarnings(e,t){let n=[],message=(e,n)=>`${t(e)} is hidden: ${n} applies above it, so load does not read it until that contribution changes`;for(let r of e.trace.layers){if(r.tier!==`repo`&&r.tier!==`user`||!r.file)continue;let i=hidingLayer(e,r.path,r.path);i&&n.push({code:r.tier===`user`&&i.tier===`repo`?`repo-hides-user`:`reference-hidden`,message:message(r.path,hiderLabel(i,t))})}let r=projectHidingLayer(e);if(r)for(let i of e.trace.projectSections)i.file&&i.plugin===void 0&&i.outcome.startsWith(`shadowed by`)&&n.push({code:`reference-hidden`,message:message(i.path,hiderLabel(r,t))});return n}function baseMovedWarnings(e,t){let n=[],r;for(let i of e.trace.layers){if(i.tier!==`plugin`&&i.tier!=="default"||!i.file||!i.frontmatter||i.outcome!==`used`&&i.outcome!==`stale`)continue;let{sources:e}=readGeneratedRecord(i.frontmatter);if(!e)continue;r??=sourceCatalog(t,{tier:`plugin`});let a=i.tier===`plugin`?`plugin ${i.plugin}`:`default of ${i.skill}`;for(let t of compareSources(e,r)){if(t.status!==`changed`)continue;let e=t.default===void 0?`plugin ${t.plugin}`:`the default of ${t.default} (plugin ${t.plugin})`;n.push({code:`base-moved`,message:`${a}: it records ${e} at ${t.recorded}, and ${t.installed??`a version with no number`} is installed; review it against the installed base and record the new version`})}}return n}function interfaceLookup(e,t={}){let n=new Map;return r=>{let i=n.get(r);if(i)return i;let a=lookUp(r,e,t);return n.set(r,a),a}}function lookUp(e,t,n){let r=resolveReference(`${e}${W}`,t,n),i=interfaceIdOf(r.trace.alias?.resolvedAs??``);if(i!==void 0){let e=readFound(i,r);return e.value?{...e,renamed:i}:e}if(r.status===`missing`){let r=[...aliasIndex(t).interfaces].filter(([,t])=>t.some(({alias:t})=>t===e)).map(([e])=>e);if(r.length>1)return lookupFailure(e,`${e} is an older id of ${r.join(` and `)}; implement one of them by its own id`);if(r.length===1){let e=r[0],i=readFound(e,resolveReference(`${e}${W}`,t,n));return i.value?{...i,renamed:e}:i}}return readFound(e,r)}function lookupFailure(e,t){return{failure:{check:`interface-found`,interface:e,message:t}}}function readFound(e,t){let n=`${e}${W}`;if(t.status===`invalid`)return lookupFailure(e,`${e} is not an interface id`);if(t.status===`missing`)return lookupFailure(e,`no interface document ${n}`);if(t.status===`ambiguous`)return lookupFailure(e,`${n} is ambiguous between ${(t.options??[]).join(` and `)}`);let{value:r,problems:i}=readInterface(e,t.metadata??{});return r?{value:r}:lookupFailure(e,`${n} is malformed: ${i.join(`; `)}`)}function bareName$1(e){let t=e.trace.alias?.resolvedAs??e.name;return t.slice(t.lastIndexOf(`/`)+1)}function kindOf(e){let t=e.metadata??{};return interfaceIdOf(bareName$1(e))!==void 0||t.interface!==void 0?`interface`:t.implements===void 0?`none`:`implementation`}function composeFailure(e){let{defects:t}=splitComposeWarnings(e);if(t.length)return{check:`compose`,message:`composing it raised ${t.length===1?`a warning`:`${t.length} warnings`}: ${t.map(({code:e,message:t})=>`${e}: ${t}`).join(`; `)}`}}function checkResolved(e,t,n){let r={failures:[],unsupported:[],warnings:[]};if(e.status!==`found`)return r;let{failures:i,warnings:a}=r,o=bareName$1(e),s=e.metadata??{};if(kindOf(e)===`interface`){let e=interfaceIdOf(o);if(e===void 0)i.push({check:`interface`,message:`${o} has an \`interface:\` block; an interface document is named <id>${W}`});else for(let t of readInterface(e,s).problems)i.push({check:`interface`,interface:e,message:t})}else{let{entry:c,problems:l}=readImplements(s);for(let e of l)i.push({check:`interface-found`,message:e});if(c){let s=t(c.id);if(s.value){let t=s.value.id;s.renamed!==void 0&&a.push({code:`reference-renamed`,message:`implements names ${c.id}@${c.version}, an older id of ${t}; declare implements: ${t}@${c.version}`});let l=checkImplementation(s.value,{name:o,version:c.version,content:e.content??``,accept:n?.id===t?n.versions:void 0,declaredId:c.id});i.push(...l.failures),r.unsupported=l.unsupported}else i.push(s.failure)}}let c=composeFailure(e.warnings);return c&&i.push(c),r}function dedupe(e){let t=new Set;return e.filter(({code:e,message:n})=>{let r=`${e} ${n}`;return!t.has(r)&&(t.add(r),!0)})}const warningKey=({code:e,message:t})=>`${e} ${t}`;function sectionWarnings({main:e,full:t}){if(t===e)return[];let n=new Set(e.warnings.map(warningKey));return t.warnings.filter(e=>!n.has(warningKey(e)))}function entryOf(e,t,n=[]){let{main:r,full:i}=e,a=r.status===`found`||i.status===`found`,o=r.status===`found`?checkResolved(r,t):{failures:[],unsupported:[],warnings:[]},s=[...o.failures];if(r.status!==`found`){!a&&r.code!==`reference-removed`&&s.push({check:r.code,message:r.message??r.status});let e=composeFailure(r.warnings);e&&s.push(e)}return{name:r.name,kind:r.status===`found`?kindOf(r):`none`,status:a?s.length?`failed`:`passed`:r.status,failures:s,unsupported:o.unsupported,warnings:dedupe([...o.warnings,...splitComposeWarnings(r.warnings).passed,...sectionWarnings(e),...n])}}function pluginCopies(e,t){let n=[...new Set(t.trace.layers.flatMap(({plugin:e,file:t})=>e!==void 0&&t?[e]:[]))];return n.length>1?n.map(t=>`${t}/${e}`):[]}function checkReferences(e,t={}){let{names:n,...r}=t,i=r.display??(e=>e),a={...r,projectSections:!1},o=interfaceLookup(e,r),s=Array.isArray(e)?void 0:e,c=new Set(s?.root===void 0?[]:[...projectSectionNames(s.root,s.projects,heldPlugins(s)),...projectQualifiedNames(s.root,s.projects)]),resolve=t=>{let n=parseReferenceName(t),i=resolveReference(n,e,a);return{main:i,full:n.plugin===void 0&&c.has(n.name)?resolveReference(n,e,r):i}},fileWarnings=({main:t,full:n})=>[...hiddenWarnings(n,i),...baseMovedWarnings(t,e)];if(n?.length)return n.map(e=>{let t=resolve(e);return entryOf(t,o,fileWarnings(t))});let l=[],u=new Map;for(let t of catalogNames(e)){let n=resolve(t);u.set(t,n.main.content),l.push(entryOf(n,o,fileWarnings(n)));for(let r of pluginCopies(t,n.main).map(resolve))l.push(entryOf(r,o,baseMovedWarnings(r.main,e)))}for(let{name:t,skill:n}of skillHoldings(e)){let r=withDefault(e,n.folder),i=resolveReference(t,r,a),s=i.trace.layers.some(({tier:e,outcome:t})=>e==="default"&&t===`used`);if(i.status!==`found`||!s)continue;let c=baseMovedWarnings(i,r);(i.content!==u.get(t)||c.length)&&l.push({...entryOf({main:i,full:i},o,c),loadedBy:n.name})}return l}function implementationTemplate(e){let t=e.sections.map(({heading:e,holds:t})=>`## ${e}\n\n**Unsupported.** ${t??`Replace this line with the section, or say in one sentence why it is not supported.`}\n`);return parseTemplate(`---\ndescription: What this ${e.id} implementation covers, and when an agent should read it.\nimplements: ${e.id}@${e.version}\n---\n\n${t.join(`
|
|
169
169
|
`)}`,`the ${e.id} interface`)}function readTemplate(e){if(e===void 0)return parseTemplate(`---
|
|
170
170
|
description: What this reference covers, and when an agent should read it.
|
|
171
171
|
tags: [topic]
|
|
@@ -178,8 +178,8 @@ Write the guidance here. Give each topic its own top-level \`##\` section.
|
|
|
178
178
|
`:``;return`---\n${i.toString({lineWidth:0,flowCollectionPadding:!1})}---\n${a}${r}`}function baseLayers(e,t){let n=t.scope===`user`,r=e.layers.filter(e=>n?e.tier!==`repo`&&(e.tier!==`plugin`||e.origin!==`dependency`):e.tier!==`user`),i=n?e.plugins?.filter(({origin:e})=>e!==`dependency`):e.plugins;return{...e,layers:r,...i?{plugins:i}:{}}}function structureOnly(e,t){return e.entry.empty=!0,{...e,body:``,hasBody:!1,merge:void 0,steps:t}}function resolveBase(e,t,n,r,i={}){let a=i.display??(e=>e),adjust=(t,i,o)=>{if(t.tier===`managed`){if(!i)return;if(i.whole){o.outcome=`not read (managed text is left out)`;return}return structureOnly(i,i.steps)}if(n.scope===`project`||t.dir!==n.dir)return i;let s=r===void 0?i?.steps:r??void 0;if(!s){i&&(o.outcome=`not read (the target is left out)`);return}return i&&!i.whole?structureOnly(i,s):(Object.assign(o,{path:n.path,file:`${e.name}.md`,outcome:``,selection:!0}),{layer:t,entry:o,label:contributionLabel(t,n.path,a),path:n.path,metadata:{},body:``,hasBody:!1,format:`markdown`,whole:!1,merge:void 0,steps:s})},o=resolveAdjusted(e,baseLayers(t,n),i,adjust),s=n.folder,c=s===void 0?[]:o.projectSections.filter(e=>s.startsWith(`${e.folder}/`)||e.folder===s&&e.plugin!==void 0);return{...o,projectSections:c}}function generatorBase(e,t){let n=t?implementationTemplate(t).body.trim():void 0,r=[n,e.status===`found`?(e.content??``).trim():``].filter(e=>!!e),i={content:r.length?`${r.join(`
|
|
179
179
|
|
|
180
180
|
`)}\n`:``,projectSections:e.status===`found`?e.projectSections:[],resolved:e};return n!==void 0&&(i.stub=`${n}\n`),i}function firstLine(e){return typeof e==`string`&&e.split(`
|
|
181
|
-
`)[0]?.trim()||``}function belongsElsewhere(e,t,n){return t!==void 0&&t!==n&&(e===t||e.startsWith(`${t}.`))}function ownTier(e){return e.trace.layers.find(e=>(e.tier===`repo`||e.tier===`user`)&&e.file&&(e.outcome===`used`||e.outcome===`stale`)&&!e.selection&&!e.empty)?.tier}function holders(e){return[...new Set(e.trace.layers.flatMap(({tier:e,plugin:t,file:n})=>e===`plugin`&&t!==void 0&&n?[t]:[]))]}function referenceImplementations(e,t,n={}){return isFamilyName(e)||e.includes(`*`)?familyImplementations(e,t,n):interfaceImplementations(e,t,n)}function familyInterfaces(e,t,n={}){let r=parseFamily(e);if(r.invalid!==void 0)throw new ReferenceFailure(`name-invalid`,r.invalid);let i=interfaceLookup(t,n),a=aliasIndex(t),o=new Set;for(let e of referenceNames(t)){let t=interfaceIdOf(shownName(e,a));if(t===void 0||!t.startsWith(`${r.prefix}.`))continue;let n=i(t).value;n&&o.add(n.id)}if(!o.size)throw new ReferenceFailure(`interface-unknown`,`no interface document matches ${e}.`,{help:"Run `reference list` for the names found."});return[...o].sort((e,t)=>e.localeCompare(t))}function familyImplementations(e,t,n={}){return{family:e,interfaces:familyInterfaces(e,t,n).map(e=>interfaceImplementations(e,t,n))}}function interfaceImplementations(e,t,n){let{accept:r,...i}=n,a={...i,projectSections:!1},o=parseReferenceName(`${e}${jn}`);if(o.invalid||o.plugin!==void 0)throw new ReferenceFailure(`interface-unknown`,`"${e}" is not an interface id.`);let s=interfaceLookup(t,i),c=s(e),l=c.value;if(!l)throw new ReferenceFailure(`interface-unknown`,c.failure?.message??`no interface ${e}`);let u=aliasIndex(t),d=[l.id,...(u.interfaces.get(l.id)??[]).map(({alias:e})=>e)],f=[...r?.length?r:l.versions],p={interface:l.id,cardinality:l.cardinality,accept:f,implementations:[],excluded:[],warnings:[]},m=new Set,warn=e=>{for(let t of e){let e=`${t.code} ${t.message}`;m.has(e)||p.warnings.push(t),m.add(e)}};c.renamed!==void 0&&warn([{code:`reference-renamed`,message:`${e} is an older id of ${l.id}; ask for ${l.id} instead`}]);let inNamespace=e=>d.some(t=>e===t||e.startsWith(`${t}.`)),relevant=(e,t)=>{let n=readImplements(t.metadata??{}).entry?.id;return n!==void 0&&d.includes(n)?!0:inNamespace(e)&&!d.some(t=>belongsElsewhere(e,n,t))},consider=({pin:e,name:t,resolved:n,tier:r})=>{warn(n.warnings);let i=readImplements(n.metadata??{}).entry;if(!i||!d.includes(i.id)){let n=fitsNamespace(l.cardinality,d,t)?``:` and is not named ${l.cardinality===`one`?l.id:`${l.id}.<key>`}`;p.excluded.push({name:e,reasons:[`declares no implements ${l.id}@<version>${n}`]});return}let a=checkResolved(n,s,{id:l.id,versions:f});if(warn(a.warnings),a.failures.length){p.excluded.push({name:e,reasons:a.failures.map(({check:e,message:t})=>`${e}: ${t}`)});return}p.implementations.push({pin:e,description:firstLine(n.metadata?.description),unsupported:a.unsupported,name:t,tier:r,version:i.version})},qualified=(e,n)=>resolveReference(parseReferenceName(`${e}/${n}`),t,a),h=[...new Set(referenceNames(t).map(e=>shownName(e,u)))];for(let e of h){if(interfaceIdOf(e)!==void 0)continue;let n=resolveReference(e,t,a);if(n.status===`ambiguous`){for(let r of n.options??[]){if(r==="default")continue;let i=resolveReference(parseReferenceName(r),t,a);i.status===`found`&&relevant(e,i)&&(warn(i.warnings),p.excluded.push({name:r,reasons:[`ambiguous: ${n.message}; each is left out until a customizer picks one`]}))}continue}if(n.status!==`found`||!relevant(e,n))continue;let r=holders(n),i=l.cardinality===`many`?ownTier(n):void 0;if(i!==void 0){consider({pin:e,name:e,resolved:n,tier:i});for(let t of r)p.excluded.push({name:`${t}/${e}`,reasons:[`the ${i} implementation answers ${e}; a consumer loads it by that name`]});continue}let o=n.trace.stack.filter(e=>e!=="default").at(-1);if(o!==void 0){consider({pin:`${o}/${e}`,name:e,resolved:qualified(o,e),tier:`plugin`});for(let t of r)t!==o&&p.excluded.push({name:`${t}/${e}`,reasons:[`${e} loads the stack of ${o}, the pick; load ${o}/${e}`]})}}if(l.cardinality===`one`){let e=implementationInUse(l.id,t,a,p.implementations);e!==void 0&&(p.inUse=e)}return p}function implementationInUse(e,t,n,r){let i=resolveReference(parseReferenceName(e),t,n);if(i.status!==`found`)return;let a=i.trace.stack.filter(e=>e!=="default").at(-1);return a===void 0?i.trace.stack.includes(`default`)?`default`:void 0:r.find(({pin:t})=>t===`${a}/${e}`)?.pin}function fitsNamespace(e,t,n){return t.some(t=>e===`one`?n===t:n.startsWith(`${t}.`)&&n.length>t.length+1)}function bareName(e){requireName(e);let t=parseReferenceName(e);if(t.invalid)throw new ReferenceFailure(`name-invalid`,t.invalid);if(t.plugin!==void 0)throw new ReferenceFailure(`reference-qualified`,`a contribution is written under the bare name, which every tier resolves; ask for "${t.name}".`);return t}function insideRepository(e,t){let n=canonical(E(t)),r=canonical(e);return r!==n&&!r.startsWith(n+D)?!1:!r.slice(n.length).split(D).includes(`node_modules`)}function below(e,t){let n=T(e,t);return n&&!n.startsWith(`..`)&&!S(n)?n:void 0}function inFolder(e,t){let n=E(e),r=below(E(t),n)??below(canonical(E(t)),canonical(n));if(r===void 0)throw new ReferenceFailure(`in-not-below-root`,`--in names ${n}, which is ${n===E(t)?`the root itself`:`outside the root`}; a project section is written for a folder strictly below the root ${E(t)}.`);return{folder:r.split(D).join(`/`),path:n}}function checkPlaces(e,t){if([e.scope,e.in,e.plugin,e.default].filter(e=>e!==void 0).length>1)throw new ReferenceFailure(`options-conflict`,`pass one of ${t}.`)}function checkScope(e){if(e!==void 0&&e!==`repo`&&e!==`user`)throw new ReferenceFailure(`option-invalid`,`--scope is repo or user; got "${e}".`)}function sourceFolder(e,t,n){let r=E(e);if(!(n===`plugin`?pluginManifestName(r):skillName(r)!==void 0))throw new ReferenceFailure(`folder-invalid`,n===`plugin`?`${r} holds no plugin manifest, so it is not a plugin folder.`:`${r} holds no SKILL.md, so it is not a skill folder.`);if(!insideRepository(r,t))throw new ReferenceFailure(`folder-invalid`,`${r} is outside the repository, such as an installed copy; write to the ${n}'s source instead.`);return r}function writeTarget$1(e,t){let{root:n,home:r,scope:i,plugin:a,default:o}=t;if(a!==void 0){let t=C(sourceFolder(a,n,`plugin`),`references`);return{scope:`plugin`,dir:t,path:C(t,`${e.name}.md`)}}if(o!==void 0){let t=C(sourceFolder(o,n,`skill`),`references`);return{scope:`default`,dir:t,path:C(t,`${e.name}.default.md`)}}if(t.in!==void 0){let{folder:r,path:i}=inFolder(t.in,n),a=C(i,`.agents`,`references`);return{scope:`project`,dir:a,path:C(a,`${e.name}.md`),folder:r,folderPath:i}}let s=i===`user`?userReferencesDir(r):repoReferencesDir(E(n));return{scope:i===`user`?`user`:`repo`,dir:s,path:C(s,`${e.name}.md`)}}__name(writeTarget$1,`writeTarget`);function targetFiles(e,t){return candidateFiles({tier:e.scope==="default"?`default`:`repo`},t).map(t=>C(e.dir,...t.split(`/`)))}function answeringFile(e,t,r){return targetFiles(e,t).find(e=>e!==r&&n(e))}function metadataFile(e,t){return C(e.dir,`${t}${e.scope==="default"?`.default`:``}.meta.md`)}function reachOf(e){return e.scope===`user`?`only you, in every repository`:e.scope===`project`?`everyone working in ${e.folder}`:`everyone working in this repository`}const Hn=`a project section carries no merge (K24); drop --merge or --in.`;function readPicks(e,t){if(e.includes(`none`)){if(e.length>1)throw new ReferenceFailure(`option-invalid`,`--extends none removes the picks, so it takes no other step; got ${e.join(` `)}.`);return`none`}if(!e.length)throw new ReferenceFailure(`option-invalid`,`--extends names one or more steps, or none.`);return{values:e.map(e=>{let n=e.indexOf(`:`),r=n===-1?e:e.slice(0,n),i=n===-1?void 0:e.slice(n+1),a=r.endsWith(`/${t}`)?r.slice(0,-t.length-1):r;if(!H.test(a))throw new ReferenceFailure(`option-invalid`,`--extends takes a plugin, \`<plugin>/${t}\`, or default, each optionally \`:<merge>\`; got "${e}".`);if(i===void 0)return a;if(!isMergeOperation(i))throw new ReferenceFailure(`option-invalid`,`the merge in "${e}" is replace, patch, combine, or remove; got "${i}".`);return{[a]:i}})}}function customizeUsage(e,t){let n=e.extends!==void 0||e.extendsFile!==void 0,r=e.request!==void 0||e.body!==void 0;if(!e.base&&!n&&!r)throw new ReferenceFailure(`change-missing`,`say what to change: --extends or --extends-file picks what the name builds on, and --request with --body writes a generated body.`,{help:`Run \`reference customize ${t.name} --base\` for what the generator reads.`});let conflict=e=>new ReferenceFailure(`options-conflict`,e);if(e.plugin!==void 0)throw conflict("customize never writes a file a plugin ships; an author writes one with `create --plugin`.");if(e.scope!==void 0&&e.in!==void 0)throw conflict(`pass --scope or --in, not both: a customization goes to one place.`);if(e.in!==void 0&&e.merge!==void 0)throw conflict(Hn);if(e.in!==void 0&&n)throw conflict(`a project section has no stack, so it takes no picks; pick for the main document with --scope.`);if(e.extends!==void 0&&e.extendsFile!==void 0)throw conflict(`pass --extends or --extends-file, not both.`);if(e.implements!==void 0&&n)throw conflict(`an implementation is a whole document that replaces the stack, so it takes no picks.`);if(e.base&&(r||e.merge!==void 0||e.dryRun))throw conflict(`--base writes nothing; it takes only --extends or --extends-file, --scope or --in, --default, and --implements.`);if(r&&e.extends?.includes(`none`))throw conflict(`--extends none removes the picks and writes no body; pass it without --request and --body.`);if(r&&(e.request===void 0||e.body===void 0))throw new ReferenceFailure(`options-missing`,e.request===void 0?`--body needs --request: a generated body records the request it was written from.`:`--request needs --body: the command writes the body the generator wrote, and runs no model.`);checkScope(e.scope),checkMerge(e.merge);let i=e.extends===void 0?void 0:readPicks(e.extends,t.name);return e.in!==void 0&&inFolder(e.in,e.root),i?{picks:i}:{}}function checkMerge(e){if(e!==void 0&&!isMergeOperation(e))throw new ReferenceFailure(`option-invalid`,`--merge is replace, patch, combine, or remove; got "${e}".`)}function checkUsage(e){let t=bareName(e.name);if(e.command===`customize`)return{name:t,merge:e.merge,...customizeUsage(e,t)};if(checkPlaces(e,`--scope, --in, --plugin, and --default`),e.command===`create`&&e.in!==void 0&&e.merge!==void 0)throw new ReferenceFailure(`options-conflict`,Hn);checkScope(e.scope),checkMerge(e.merge);let n=e.merge;if(e.in!==void 0&&inFolder(e.in,e.root),e.command===`create`){if(n===`remove`&&e.template!==void 0)throw new ReferenceFailure(`remove-with-template`,`--merge remove writes no body, so it takes no --template.`);if(e.template!==void 0&&e.implements!==void 0)throw new ReferenceFailure(`template-with-implements`,`pass --template or --implements, not both.`)}return{name:t,merge:n}}function lookUpInterface(e,t,n){let r=parseReferenceName(e);if(r.invalid||r.plugin!==void 0)throw new ReferenceFailure(`interface-invalid`,`"${e}" is not an interface id.`);let i=interfaceLookup(t,n)(e);if(!i.value)throw new ReferenceFailure(`interface-invalid`,i.failure?.message??`no interface ${e}`);return i.value}function tryRead$1(e){try{return a(e,`utf8`)}catch{return}}function operationOf(e,t,n,r){if(t.scope===`project`)return;if(e.implements!==void 0)return`replace`;if(t.scope===`plugin`||t.scope==="default")return n;let i=r.metadata.merge;return n??(isMergeOperation(i)?i:void 0)??`patch`}function validateWrite(e,t,n={}){let r=checkUsage(e);if(!t)return r;let{name:i,merge:a}=r,o=n.display??(e=>e);if(!isDirectory$3(e.root))throw new ReferenceFailure(`root-missing`,`the root ${e.root} does not exist or is not a folder.`,{details:{root:e.root}});if(e.command===`customize`)return planCustomize(e,r,t,n);let s=writeTarget$1(i,e);if(e.command===`delete`)return checkFolder(s,i.name),{name:i,merge:a,target:s,before:resolveReference(i,t,n),extended:[]};let c=e.implements!==void 0||a===`remove`?{content:``,metadata:{},body:``}:readTemplate(e.template),l=titleOf(c);if(l)throw new ReferenceFailure(`template-title`,`the template's top level is the single heading "${l}" holding the others; patch matches by heading path, so make its sections top-level.`);let u=e.implements===void 0?void 0:lookUpInterface(e.implements,t,n);checkNamespace(u,s,i);let d=u?implementationTemplate(u):c;checkFolder(s,i.name);let f=resolveReference(i,t,n);checkMarkdown(f,s,i);let p={name:i,merge:a,target:s,template:d,before:f,extended:[]};u&&(p.iface=u);let m=tryRead$1(s.path),h=m===void 0?void 0:parseDocument(m,()=>{});if(p.operation=operationOf(e,s,a,d),p.extended=(readExtends(h?.metadata.extends,()=>{})??readExtends(d.metadata.extends,()=>{})??[]).map(({target:e})=>e).filter(e=>e!=="default"),(s.scope===`plugin`||s.scope==="default")&&p.operation===`replace`&&p.extended.length)throw new ReferenceFailure(`extends-replace`,`a ${s.scope===`plugin`?`plugin's file`:`skill's default`} that extends ${p.extended.join(`, `)} states only the sections it changes, so it takes no merge: replace; to replace the base entirely, write a snapshot of your own with no extends on it.`);if(h&&hasBody(h.body))throw new ReferenceFailure(`file-exists`,`${o(s.path)} already holds "${i.name}"; change it with the reference skill's Update mode.`,{details:{path:o(s.path)}});let g=answeringFile(s,i.name,s.path)??selectingSidecar(s,i.name);if(g)throw new ReferenceFailure(`file-exists`,`${o(g)} already answers "${i.name}" in that folder; change it there, or delete it first.`,{details:{path:o(g)}});return m!==void 0&&(p.existing=m),p}function selectingSidecar(e,t){if(e.scope===`project`)return;let n=metadataFile(e,t),r=tryParse(tryRead$1(n));return r&&r.metadata.extends!==void 0?n:void 0}function checkFolder(e,t){if(e.scope===`project`&&e.folderPath!==void 0&&e.folder!==void 0){if(!isDirectory$3(e.folderPath))throw new ReferenceFailure(`in-folder-missing`,`--in names ${e.folderPath}, which does not exist.`,{details:{folder:e.folder}});if(gitIgnores(e.folderPath,e.path))throw new ReferenceFailure(`in-folder-ignored`,`git ignores ${e.folder}/.agents/references/${t}.md, so load would never read a project section there.`,{details:{folder:e.folder}})}}function checkNamespace(e,t,n){if(!e||t.scope===`project`||fitsName(e,n.name))return;let r=e.cardinality===`one`?e.id:`${e.id}.<key>`;throw new ReferenceFailure(`name-outside-interface`,`an implementation of ${e.id} is named ${r}, not "${n.name}".`,{help:`Name it ${r}, or write it for one folder with --in.`})}function checkMarkdown(e,t,n){if(t.scope===`project`&&e.status===`found`&&e.format!==`markdown`)throw new ReferenceFailure(`in-not-markdown`,`the main document of "${n.name}" is ${e.format}, which has no project sections; customize the main document instead.`)}function readGiven(e,t){try{return a(e,`utf8`)}catch(n){throw new ReferenceFailure(`file-unreadable`,`cannot read the ${t} file ${e}: ${n.message}`,{details:{path:e}})}}function isStep(e){if(typeof e==`string`)return H.test(e);if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);if(t.length!==1)return!1;let[n,r]=t[0];if(!H.test(n))return!1;if(r==null)return!0;if(typeof r==`string`)return isMergeOperation(r);if(typeof r!=`object`||Array.isArray(r))return!1;let i=r;return Object.keys(i).some(e=>e!==`merge`&&e!==`extends`&&e!==`sections`)||i.merge!==void 0&&!isMergeOperation(i.merge)||i.sections!==void 0&&!Array.isArray(i.sections)?!1:i.extends===void 0||Array.isArray(i.extends)&&i.extends.every(isStep)}function readExtendsFile(e){let invalid=t=>new ReferenceFailure(`extends-file-invalid`,`the --extends-file ${e} ${t}.`,{details:{path:e}}),t;try{t=a(e,`utf8`)}catch(e){throw invalid(`cannot be read: ${e.message}`)}let n;try{n=(0,en.parse)(t)}catch(e){throw invalid(`is not YAML: ${e.message}`)}let r=n&&typeof n==`object`&&!Array.isArray(n)?n.extends:n;if(!Array.isArray(r)||!r.length||!r.every(isStep))throw invalid("is not a YAML `extends` list: each step a plugin or default, with only merge, extends, and sections");return{values:r}}function stepsOf(e){if(e===void 0)return;if(e===`none`)return null;let strip=e=>{if(typeof e!=`object`||!e)return e;let[t,n]=Object.entries(e)[0];if(typeof n!=`object`||!n)return e;let{sections:r,extends:i,...a}=n;return{[t]:Array.isArray(i)?{...a,extends:i.map(strip)}:a}};return readExtends(e.values.map(strip),()=>{})??[]}function checkSteps(e,t,n,r){let i=new Set(r.layers.flatMap(({tier:e,plugin:t,skipped:n})=>e===`plugin`&&t&&!n?[t]:[])),a=new Set(n.trace.layers.flatMap(({tier:e,plugin:t,file:n})=>e===`plugin`&&t!==void 0&&n&&i.has(t)?[t]:[])),o=e.map(({target:e})=>e).filter(e=>e!=="default"&&!a.has(e));if(o.length)throw new ReferenceFailure(`step-invalid`,`${o.join(`, `)} ${o.length===1?`is`:`are`} neither default nor a plugin holding "${t}"${a.size?`; the plugins holding it are ${[...a].join(`, `)}`:``}.`,{details:{steps:o}})}function coveringInterface(e,t,n){let r=interfaceLookup(t,n),i=e.split(`.`);for(let t=i.length;t>=1;t--){let n=r(i.slice(0,t).join(`.`)).value;if(n&&fitsName(n,e))return n}}function tryParse(e){return e===void 0?void 0:parseDocument(e,()=>{})}function customizeFiles(e,t,n){let r=e.scope===`project`?[e.path,C(e.dir,t,`README.md`)]:[e.path,C(e.dir,t,`README.md`),...V.map(({extension:n})=>C(e.dir,`${t}${n}`))],i=answeringFile(e,t),a=i!==void 0&&r.includes(i)?i:void 0,o=C(e.dir,t,`README.md`),s=e.path,c=`markdown`;if(a!==void 0&&a!==o)s=a,c=formatOfFile(a);else if(a===void 0&&e.scope!==`project`&&n.status===`found`&&n.format!==void 0&&n.format!==`markdown`){c=n.format;let r=[...n.trace.contributions].reverse().find(({path:e})=>formatOfFile(e)===c),i=r?x(r.path):V.find(e=>e.format===c)?.extension;s=C(e.dir,`${t}${i}`)}return{file:s,format:c,holder:c===`markdown`?s:metadataFile(e,t),other:a===o?o:void 0}}function quietInterface(e,t,n){let r=Array.isArray(e)?e[0]:e,i=typeof r==`string`?/^(.+)@\d+$/.exec(r.trim())?.[1]:void 0;return i===void 0?void 0:interfaceLookup(t,n)(i).value}function planCustomize(e,t,n,r){let{name:i}=t,a=r.display??(e=>e),o=writeTarget$1(i,{root:e.root,home:e.home,scope:e.scope,in:e.in}),s=e.request===void 0?void 0:readGiven(e.request,`--request`),c=e.body===void 0?void 0:readGiven(e.body,`--body`),l=e.extendsFile===void 0?t.picks:readExtendsFile(e.extendsFile),u=e.implements===void 0?void 0:lookUpInterface(e.implements,n,r);checkNamespace(u,o,i),checkFolder(o,i.name);let d=resolveReference(i,n,r);checkMarkdown(d,o,i);let f=stepsOf(l);f&&checkSteps(f,i.name,d,baseLayers(n,o));let p=customizeFiles(o,i.name,d),m=tryRead$1(p.file),h=p.holder===p.file?m:tryRead$1(p.holder),g=tryParse(h),_=u||o.scope===`project`?void 0:g?.metadata.implements,v=u??(_===void 0?void 0:quietInterface(_,n,r)),y=resolveBase(i,n,o,f,r),b=s!==void 0||!!e.base;if(b&&l===void 0&&y.status===`ambiguous`)throw new ReferenceFailure(`pick-required`,`"${i.name}" is ambiguous: ${y.message}; pick what it builds on before the request is applied.`,{details:{options:y.options??[]},help:`Pass --extends with the picks, bottom first, from: ${(y.options??[]).join(`, `)}.`});if(b&&!v&&_===void 0&&y.status===`missing`){let e=coveringInterface(i.name,n,r);if(e)throw new ReferenceFailure(`implements-required`,`"${i.name}" is in the namespace of the interface ${e.id}, and nothing implements it; name the interface.`,{details:{interface:e.id},help:`Run \`reference customize ${i.name} --implements ${e.id} --request <file> --body <file>\`.`})}let x=p.format===`markdown`?hasBody(g?.body??``):!!m?.trim();if(s!==void 0&&x&&!isGenerated(g?.metadata))throw new ReferenceFailure(`body-not-generated`,`${a(p.file)} holds a body that records no request, written with create or by hand; customizing would replace it.`,{details:{path:a(p.file)},help:`Change it with the reference skill's Update mode, or delete it first.`});if(p.other&&!e.base)throw new ReferenceFailure(`file-exists`,`${a(p.other)} already answers "${i.name}" in that folder; change it there, or delete it first.`,{details:{path:a(p.other)}});let S={...t,picks:l,target:o,before:d,base:y,file:p.file,format:p.format,holder:p.holder};return f!==void 0&&(S.steps=f),s!==void 0&&(S.request=s),c!==void 0&&(S.body=c),v&&(S.iface=v),u?S.implementsValue=`${u.id}@${u.version}`:typeof _==`string`&&(S.implementsValue=_),m!==void 0&&(S.existing=m),h!==void 0&&(S.held=h),S}function tryRead(e){try{return a(e,`utf8`)}catch{return}}function describeAnswer(e,t=e=>e){if(e.status===`found`){let n=e.trace.contributions.at(-1),r=n?n.tier===`plugin`?`plugin ${n.plugin}`:n.tier==="default"?`the default of ${n.skill}`:`the ${n.tier} file ${t(n.path)}`:void 0,i=e.trace.stack.length?`, on the stack ${e.trace.stack.join(` → `)}`:``,a=[...new Set(e.projectSections.map(({folder:e})=>e))];if(!r)return`"${e.name}" is answered only by the project sections of ${a.join(`, `)}.`;let o=a.length?`, with the project sections of ${a.join(`, `)}`:``;return`"${e.name}" is answered by ${r}${i}${o}.`}return e.status===`ambiguous`?`"${e.name}" is ambiguous: ${e.message}; the options are ${(e.options??[]).join(`, `)}.`:`"${e.name}" is ${e.status}: ${e.message}.`}const Un=[`merge`,`extends`,`implements`,`aliases`];function selectionKeys(e,t){let n=parseDocument(e,()=>{}).metadata,r={};for(let[e,i]of Object.entries(t.metadata))e!==`merge`&&!(e in n)&&(r[e]=i);return r}function withBody(e,t){let n=t.replace(/^(?:[ \t]*\r?\n)+/,``);return n?`${e.replace(/\s*$/,``)}\n\n${n}`:e}function hiddenWarning(e,t,n,r){let i=t.scope===`project`?projectHidingLayer(e):hidingLayer(e,t.dir,t.path);if(i)return{code:t.scope===`user`&&i.tier===`repo`?`repo-hides-user`:`reference-hidden`,message:`${r(n)} is written, but ${hiderLabel(i,r)} applies above it, so load does not read it until that contribution changes.`}}function createContribution(e,t,n={}){let r=validateWrite({command:`create`,...t},e,n),{name:a,target:o,existing:s,operation:c}=r,l=r.template,u=n.display??(e=>e),d=[],f={merge:c};if(o.scope===`project`)for(let e of Un)f[e]=void 0,!r.iface&&e in l.metadata&&d.push({code:`project-section-key-ignored`,message:`\`${e}\` is dropped from the project section for ${o.folder}: a project section states only what differs in its folder.`});if((o.scope===`plugin`||o.scope==="default")&&r.extended.length){let t=recordedSources(r.extended,sourceCatalog(e,{tier:o.scope}));Object.assign(f,generatedFrontmatter({sources:t}))}let p=s===void 0?editFrontmatter(l.content,f):withBody(editFrontmatter(s,{...selectionKeys(s,l),...f}),l.body),h=hiddenWarning(r.before,o,o.path,u);h&&d.push(h);let g=hasDescription(parseDocument(p,()=>{}))?[]:["it has no `description` in its frontmatter, so `list` and `search` show it blank"],_={name:a.name,scope:o.scope,path:o.path,content:p,dryRun:!!t.dryRun,hints:g,warnings:d};return o.folder!==void 0&&(_.folder=o.folder),_.dryRun?_:(i(o.dir,{recursive:!0}),m(o.path,p,s===void 0?{flag:`wx`}:{}),(o.scope===`project`||r.before.trace.layers.some(e=>e.path===o.dir||e.path===o.path))&&(_.after=resolveReference(a,{...e,projects:new Map},n)),_)}function placeOf(e){return e.scope===`project`?`project section for ${e.folder}`:e.scope==="default"?`default`:`${e.scope} contribution`}function deleteContribution(e,t,r={}){let{name:i,target:a,before:o}=validateWrite({command:`delete`,...t},e,r),s=r.display??(e=>e),c=!!t.dryRun,l=answeringFile(a,i.name,r.without),f=metadataFile(a,i.name),p=f!==r.without&&n(f),m=l??(p?f:void 0),h={name:i.name,scope:a.scope};if(a.folder!==void 0&&(h.folder=a.folder),!m)return{...h,path:a.path,dryRun:c,code:`no-file`,message:`${s(a.path)} does not exist, so there is no ${placeOf(a)} of "${i.name}" to delete; nothing was deleted. ${describeAnswer(o,r.display)} An installed plugin's, a managed, or an installed skill's contribution is never deleted.`,after:o};let g=l&&formatOfFile(l)!==`markdown`&&p?f:void 0,_=formatOfFile(m)===`markdown`?m:g,v=_===void 0?void 0:readExtends(parseDocument(tryRead(_)??``,()=>{}).metadata.extends,()=>{});if(!c&&(u(m),g&&u(g),b(m)!==a.dir))try{d(b(m))}catch{}let y={...h,path:m,dryRun:c,after:resolveReference(i,{...e,projects:new Map},{...r,without:c?m:void 0})};return g&&(y.metadataFile=g),v&&(y.selection=v.map(({target:e})=>e)),y}function defaultSkill(e){let t=e.layers.find(({tier:e,skipped:t})=>e==="default"&&!t);if(t?.skill===void 0)return;let n=b(t.dir),r=e.layers.find(({tier:e,plugin:t,dir:r})=>e===`plugin`&&t!==void 0&&n.startsWith(b(r)+D));return r?.plugin===void 0?{skill:t.skill}:{skill:t.skill,plugin:r.plugin}}function bodyOf(e){let t=e.held===void 0?void 0:parseDocument(e.held,()=>{}),n=e.format===`markdown`?hasBody(t?.body??``):!!e.existing?.trim();return{metadata:t?.metadata??{},held:n}}function write(e,t){i(b(e),{recursive:!0}),m(e,t)}function writePicks(e,t,n,r){let i=r.display??(e=>e),{name:a,holder:o,picks:s,before:c}=e;n.path=o;let{metadata:l,held:d}=bodyOf(e);if(s===`none`){if(e.held===void 0||!(`extends`in l))return{...n,action:`cleared`,code:`no-selection`,message:`${i(o)} holds no selection of "${a.name}", so nothing was removed. ${describeAnswer(c,r.display)}`,after:c};let s=editFrontmatter(e.held,{extends:void 0,declined:void 0}),d=!s.trim();return n.action=`cleared`,d?n.deleted=!0:n.content=s,n.dryRun?n:(d?u(o):write(o,s),after(n,e,t,r))}let f=s?s.values:[],p=editFrontmatter(e.held??``,{extends:f,declined:declinedBy(e,f)});Object.assign(n,{action:`selection`,content:p,extends:f});let m=hiddenWarning(c,e.target,o,i);return m&&n.warnings.push(m),e.base.trace.builtBy.startsWith(`managed `)&&n.warnings.push({code:`extends-not-used`,message:`the picks are written to ${i(o)}, but ${e.base.trace.builtBy}'s extends builds the stack, so they are not used while it does.`}),d&&isGenerated(l)&&n.hints.push(`its body was generated from a request against the old stack; customize "${a.name}" again with that request (\`reference customize ${a.name} --request <file> --body <file>\`) to regenerate it on the new picks.`),n.dryRun?n:(write(o,p),after(n,e,t,r))}function packageSources(e){let t=new Set(e.trace.stack),n=new Set(e.projectSections.flatMap(({plugin:e})=>e===void 0?[]:[e])),r=new Map;for(let{plugin:i,version:a}of e.trace.projectSections)i===void 0||!n.has(i)||t.has(i)||r.has(i)||r.set(i,a===void 0?{plugin:i}:{plugin:i,version:a});return[...r.values()]}function writeGenerated(e,t,n,r){let i=r.display??(e=>e),{target:a,base:o,picks:s}=e,c=a.scope===`project`,l=!c&&e.implementsValue!==void 0,{metadata:u}=bodyOf(e),d=s&&s!==`none`?s.values:u.extends,f=l||o.status!==`found`?[]:[...recordedSources(o.trace.stack,sourceCatalog(baseLayers(t,a),{tier:a.scope===`user`?`user`:`repo`}),defaultSkill(t)),...c?packageSources(o):[]],p=!c&&!l&&d!==void 0,m={extends:p?d:void 0,declined:p?declinedBy(e,d):void 0,sources:void 0,request:void 0,...generatedFrontmatter({sources:f,request:e.request})},h=e.body;n.action=`generated`,n.path=e.file,e.format===`markdown`?n.content=editFrontmatter(h,{merge:c?void 0:l?`replace`:e.merge??`patch`,implements:l?e.implementsValue:void 0,...m}):(n.content=h,n.metadataFile=e.holder,n.metadataContent=editFrontmatter(e.held??``,{merge:void 0,implements:void 0,...m}));let g=hiddenWarning(e.before,a,e.file,i);return g&&n.warnings.push(g),n.dryRun?n:(write(e.file,n.content),n.metadataContent!==void 0&&write(e.holder,n.metadataContent),after(n,e,t,r))}function declinedBy(e,t){let n=readExtends(t,()=>{});if(!n)return;let r=new Map;for(let{tier:t,plugin:n,file:i,outcome:a,frontmatter:o}of e.base.trace.layers)t!==`plugin`||n===void 0||i===void 0||a.startsWith(`not read`)||r.has(n)||r.set(n,o?.extends);let i=new Set,place=e=>{for(let t of e)i.has(t.target)||(i.add(t.target),place(t.extends??readExtends(r.get(t.target),()=>{})??[]))};place(n);let a=[...r.keys()].filter(e=>!i.has(e));return a.length?a:void 0}function after(e,t,n,r){return{...e,after:resolveReference(t.name,{...n,projects:new Map},r)}}function givesSections(e){return Array.isArray(e)?e.some(givesSections):typeof e!=`object`||!e?!1:Object.values(e).some(e=>{if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return t.sections!==void 0||givesSections(t.extends)})}function customizeFamily(e,t,n={}){let r=parseFamily(t.name);if(r.invalid!==void 0)throw new ReferenceFailure(`name-invalid`,r.invalid);let i=validateWrite({command:`customize`,...t,name:r.prefix});if([t.base,t.request,t.body,t.implements,t.merge].some(e=>e!==void 0))throw new ReferenceFailure(`options-conflict`,`a family takes only picks: --extends or --extends-file, with --scope and --dry-run; a body, a merge, or a base is per name.`);let a=t.extendsFile===void 0?i.picks:readExtendsFile(t.extendsFile);if(a!==void 0&&a!==`none`&&givesSections(a.values))throw new ReferenceFailure(`step-invalid`,`a step of ${t.name} gives sections, which differ per interface; pick for one interface at a time to change sections.`);let o=interfaceLookup(e,n),s=familyInterfaces(t.name,e,n).map(r=>{if(o(r).value?.cardinality===`many`)return{interface:r,outcome:`skipped`,reason:`${r} is a many interface, which has no single pick.`};let i={...t,name:r};try{let t=validateWrite({command:`customize`,...i},e,n);if(a!==`none`&&t.base.status!==`found`)return{interface:r,outcome:`kept`,reason:`no step holds ${r}; it keeps what it had.`}}catch(e){if(e instanceof ReferenceFailure&&e.code===`step-invalid`)return{interface:r,outcome:`kept`,reason:`${e.message} It keeps what it had.`};throw e}return{interface:r,outcome:`written`,answer:i}}).map(({answer:t,...r})=>t===void 0?r:{...r,result:customizeSingle(e,t,n)});return{family:t.name,scope:t.scope??`repo`,dryRun:!!t.dryRun,interfaces:s}}function customizeContribution(e,t,n={}){return isFamilyName(t.name)||t.name.includes(`*`)?customizeFamily(e,t,n):customizeSingle(e,t,n)}function customizeSingle(e,t,n){let r=validateWrite({command:`customize`,...t},e,n),i={name:r.name.name,scope:r.target.scope,action:`base`,path:r.file,dryRun:!!t.dryRun,hints:[],warnings:[]};return r.target.folder!==void 0&&(i.folder=r.target.folder),t.base?{...i,base:generatorBase(r.base,r.iface)}:r.request===void 0?writePicks(r,e,i,n):writeGenerated(r,e,i,n)}const Wn=V.map(({extension:e})=>e);function entries(e){try{return o(e,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))}catch{return[]}}function valid(e){return!parseReferenceName(e).invalid}function heldFiles(e){let t=[],n=e.tier==="default",r=n?U:``;for(let i of entries(e.dir)){let a=i.name,o=C(e.dir,a);if(i.isDirectory()){!n&&valid(a)&&tryRead$2(C(o,`README.md`))!==void 0&&t.push({name:a,path:C(o,`README.md`),suffix:`/README.md`,kind:`markdown`,folderForm:!0});continue}if(a===`_renames.yaml`)continue;let s=`${r}${Sn}.md`;if(a.endsWith(s)){let e=a.slice(0,-s.length);valid(e)&&t.push({name:e,path:o,suffix:s,kind:`metadata`,folderForm:!1});continue}let c=`${r}.md`;if(a.endsWith(c)){let e=a.slice(0,-c.length);valid(e)&&t.push({name:e,path:o,suffix:c,kind:`markdown`,folderForm:!1});continue}let l=Wn.find(e=>a.endsWith(`${r}${e}`));if(l){let e=a.slice(0,-`${r}${l}`.length);valid(e)&&t.push({name:e,path:o,suffix:`${r}${l}`,kind:`data`,folderForm:!1})}}return t}function placesOf(e,t,n){if(n.plugin!==void 0&&n.default!==void 0)throw new ReferenceFailure(`options-conflict`,`pass one of --plugin and --default.`);if(n.plugin!==void 0)return[{tier:`plugin`,dir:C(sourceFolder(n.plugin,t,`plugin`),`references`)}];if(n.default!==void 0)return[{tier:`default`,dir:C(sourceFolder(n.default,t,`skill`),`references`)}];let r=[{tier:`repo`,dir:repoReferencesDir(t)},{tier:`user`,dir:userReferencesDir(n.home)},...projectFolders(t,e.projects).folders.map(({folder:e,dir:t})=>({tier:`project`,dir:t,folder:e}))],i=new Set;return r.filter(({dir:e})=>{let t=E(e);return!i.has(t)&&(i.add(t),!0)})}function renameSources(e){let t=renameTable(e),n=aliasIndex(e);return e=>{if(n.owned.has(e))return[];let r=new Map,add=(e,t)=>r.set(e,(r.get(e)??new Set).add(t));for(let n of t.byOld.get(e)??[])add(n.to,`plugin ${n.plugin}'s ${Rn}`);for(let t of n.byAlias.get(e)??[])add(t.name,`the aliases of ${t.tier===`plugin`?`plugin ${t.plugin}`:`the default of ${t.skill}`}`);return[...r].map(([e,t])=>({to:e,by:[...t].join(` and `)}))}}function holdsName(e,t){let r=e.tier==="default"?U:``;return[`${t}${r}.md`,...e.tier==="default"?[]:[C(t,`README.md`)],...Wn.map(e=>`${t}${r}${e}`),`${t}${r}${Sn}.md`].some(t=>n(C(e.dir,t)))}function migrateReferences(e,t){let r=E(t.root??e.root??process.cwd()),i=t.names?.length?new Set(t.names.map(e=>bareName(e).name)):void 0,a=placesOf(e,r,t),o=renameSources(e),s=new Set(e.layers.flatMap(({tier:e,plugin:t,skipped:n})=>e===`plugin`&&t&&!n?[t]:[])),c=[],u=[];for(let e of a){let t=e.folder===void 0?{}:{folder:e.folder},r=e.tier===`repo`||e.tier===`user`||e.tier===`project`,a=new Set,l=heldFiles(e);e.tier==="default"&&l.push(...oldDefaults(e,i,l));for(let s of l){let l=r?o(s.name):[];if(i&&!i.has(s.name)&&!l.some(({to:e})=>i.has(e)))continue;let d={path:s.path,tier:e.tier,...t,name:s.name},f={path:s.path};if(s.kind===`markdown`){let t=tryRead$2(s.path)??``,{metadata:n,body:r}=parseDocument(t,()=>{}),{findings:i,keys:a}=legacyRewrite(n,r,e.tier===`project`?`project`:`contribution`,s.name);for(let e of i)c.push(rowOf(d,e));Object.keys(a).length&&(f.content=editFrontmatter(t,a))}if(s.suffix===`.md`&&e.tier==="default"){let t=C(e.dir,`${s.name}${U}.md`),r=defaultLayoutFinding(s.name);if(n(t)){let{to:e,...t}=r;c.push(rowOf(d,{...t,manual:`${s.name}${U}.md is there too and answers the name; the old file is not read, so delete it by hand once nothing in it is needed`}))}else c.push(rowOf(d,r)),Object.assign(f,{moveFrom:s.path,moveTo:t})}l.length&&renameRow(e,s,l,a,d,c,f),(f.content!==void 0||f.moveTo!==void 0)&&u.push(f)}if(r)for(let n of qualifiedOverrides(e.dir)){if(i&&!i.has(n.name))continue;let r=qualifiedRow(e,n,s,a,{path:n.path,tier:e.tier,...t,name:n.name},c);r&&u.push(r)}}let d=!1;if(t.write)for(let e of u)e.content!==void 0&&m(e.path,e.content),e.moveFrom!==void 0&&e.moveTo!==void 0&&l(e.moveFrom,e.moveTo),e.prune!==void 0&&pruneEmpty(e.prune),d=!0;return{rows:c,written:d,warnings:[...renameTable(e).warnings]}}function rowOf(e,t){let n={...e,form:t.form,from:t.from},r=t.note===void 0?``:`; ${t.reads}, and ${t.note}`;return t.to!==void 0&&(n.to=`${t.to}${r}`),t.manual!==void 0&&(n.manual=`${t.manual}${r}`),n}function oldDefaults(e,t,n){return t?[...t].flatMap(t=>{let r=C(e.dir,`${t}.md`);return tryRead$2(r)===void 0||n.some(e=>e.path===r)?[]:[{name:t,path:r,suffix:`.md`,kind:`markdown`,folderForm:!1}]}):[]}function renameRow(e,t,n,r,i,a,o){let s=t.folderForm?`${t.name}/`:`${t.name}${t.suffix}`,c={...i,form:`renamed`,from:s,by:n.map(({by:e})=>e).join(`; `)};if(n.length>1){a.push({...c,manual:`it is renamed differently: ${n.map(({to:e,by:t})=>`"${e}" by ${t}`).join(`, `)}; rename it by hand to the one that applies`});return}let{to:l}=n[0],u=t.kind===`metadata`||t.kind===`data`;if(holdsName(e,l)&&!r.has(l)||r.has(l)&&!u){a.push({...c,manual:`"${l}" already has a file in that folder; merge the two by hand, then delete this one`});return}r.add(l);let d=t.folderForm?`${l}/`:`${l}${t.suffix}`;a.push({...c,to:d});let f=t.folderForm?b(t.path):t.path;Object.assign(o,{moveFrom:f,moveTo:C(e.dir,t.folderForm?l:`${l}${t.suffix}`)})}function pruneEmpty(e){try{o(e).length||d(e)}catch{}}function qualifiedRow(e,t,n,r,i,a){let{plugin:o,name:s}=t,c=qualifiedOverrideFinding(t,e.tier===`project`?`project`:`contribution`),{to:l,...u}=c,manual=e=>{a.push(rowOf(i,{...u,manual:e}))};if(l===void 0)return manual(c.manual);if(!n.has(o))return manual(`plugin ${o} is not installed; it would become ${l}, extending a plugin that is not there: install ${o} and run migrate again, or delete this file`);if(holdsName(e,s)||r.has(s))return manual(`"${s}" already has a file in that folder; move this file's sections into it and add ${o} to its extends, then delete this one`);let d=tryRead$2(t.path)??``,{metadata:f,body:p}=parseDocument(d,()=>{}),m=[`extends`,`overrides`].find(e=>e in f);if(m!==void 0)return manual(`it also writes \`${m}\`; move it to ${s}.md by hand, with an extends that names ${o}`);r.add(s),a.push(rowOf(i,c));let{findings:h,keys:g}=legacyRewrite(f,p,`contribution`,s);for(let e of h)a.push(rowOf(i,e));return{path:t.path,content:editFrontmatter(d,{...g,extends:[o]}),moveFrom:t.path,moveTo:C(e.dir,`${s}.md`),prune:b(t.path)}}function whereReference(e,t,{root:n,display:r=e=>e,in:i}){typeof e==`string`&&requireName(e);let a=i===void 0?void 0:inFolder(i,n),o=typeof e==`string`?parseReferenceName(e):e,s=resolveReference(o,t,{display:r}),c={name:o.raw,status:s.status,files:[],headings:s.status===`found`&&s.format===`markdown`?headingPaths(s.content??``):[],used:s.trace.stack,layers:s.trace.layers,warnings:s.warnings};if(s.options&&(c.options=s.options),o.invalid)return c;let l=(Array.isArray(t)?t:t.layers).find(({tier:e})=>e===`user`)?.dir,u=[{scope:`repo`,dir:repoReferencesDir(n),path:``},...l?[{scope:`user`,dir:l,path:``}]:[],...a?[{scope:`project`,dir:C(a.path,`.agents`,`references`),path:``,folder:a.folder}]:[]];for(let e of u){let t=answeringFile(e,o.name)??C(e.dir,`${o.name}.md`),i=e.scope===`project`?projectHidingLayer(s):hidingLayer(s,e.dir,t),a={scope:e.folder??e.scope,path:e.scope===`user`?r(t):T(n,t),reaches:reachOf(e)};i&&(a.hiddenBy=hiderLabel(i,r)),c.files.push(a)}return c}function skillsProjection(e,t,n=skillsDirectories(e)?.[t]){let r=n??[],[i]=r;if(i===void 0)throw Error(`cyber-agentkit records no ${t} skills directories for ${e}.`);return r.includes(`.agents/skills`)?{}:{skillsDirectory:i}}const Gn=`.agents/AGENTS.md`,Kn=[{name:`claude-code`,project:{detect:`.claude`,...skillsProjection(`claude-code`,`project`),shadowedBy:[`CLAUDE.md`,`.claude/CLAUDE.md`,`CLAUDE.local.md`],mcpConfig:{path:`.mcp.json`,key:`mcpServers`,format:`json`,dialect:`claude-code`},nonstandard:[{path:`.claude/commands`,shape:`directory`,kind:`command`},{path:`.claude/rules`,shape:`directory`,kind:`rule`},{path:`.claude/agents`,shape:`directory`,kind:`subagent`}]},user:{detect:`.claude`,...skillsProjection(`claude-code`,`user`),relocatedBy:`CLAUDE_CONFIG_DIR`,emptyRelocatesToStart:!0,instructionBridge:{kind:`import`,path:`.claude/CLAUDE.md`,line:`@~/${Gn}`}}},{name:`cursor`,project:{detect:`.cursor`,...skillsProjection(`cursor`,`project`),mcpConfig:{path:`.cursor/mcp.json`,key:`mcpServers`,format:`json`,dialect:`cursor`},nonstandard:[{path:`.cursorrules`,shape:`file`,kind:`instructions`},{path:`.cursor/rules`,shape:`directory`,kind:`rule`},{path:`.cursor/commands`,shape:`directory`,kind:`command`},{path:`.cursor/skills`,shape:`directory`,kind:`skill`}]},user:{detect:`.cursor`,...skillsProjection(`cursor`,`user`)}},{name:`codex`,project:{detect:`.codex`,...skillsProjection(`codex`,`project`),mcpConfig:{path:`.codex/config.toml`,key:`mcp_servers`,format:`toml`,dialect:`codex`,shared:!0},nonstandard:[{path:`.codex/skills`,shape:`directory`,kind:`skill`}]},user:{detect:`.codex`,...skillsProjection(`codex`,`user`),instructionBridge:{kind:`symlink`,path:`.codex/AGENTS.md`},shadowedBy:[`.codex/AGENTS.override.md`],relocatedBy:`CODEX_HOME`}},{name:`copilot-cli`,project:{detect:`.github/skills`,...skillsProjection(`copilot-cli`,`project`),nonstandard:[{path:`.github/copilot-instructions.md`,shape:`file`,kind:`instructions`},{path:`.github/instructions`,shape:`directory`,kind:`instructions`},{path:`.github/skills`,shape:`directory`,kind:`skill`}]},user:{detect:`.copilot`,...skillsProjection(`copilot-cli`,`user`),relocatedBy:`COPILOT_HOME`,instructionBridge:{kind:`symlink`,path:`.copilot/copilot-instructions.md`}}},{name:`gemini-cli`,project:{detect:`.gemini`,...skillsProjection(`gemini-cli`,`project`),instructionBridge:{kind:`settings-entry`,path:`.gemini/settings.json`,key:`context.fileName`},mcpConfig:{path:`.gemini/settings.json`,key:`mcpServers`,format:`json`,dialect:`gemini-cli`,shared:!0},nonstandard:[{path:`GEMINI.md`,shape:`file`,kind:`instructions`},{path:`.gemini/skills`,shape:`directory`,kind:`skill`}]},user:{detect:`.gemini`,...skillsProjection(`gemini-cli`,`user`),instructionBridge:{kind:`symlink`,path:`.gemini/GEMINI.md`}}},{name:`devin-desktop`,project:{detect:`.devin`}},{name:`windsurf`,project:{detect:`.windsurf`,skillsDirectory:`.windsurf/skills`,nonstandard:[{path:`.windsurfrules`,shape:`file`,kind:`instructions`},{path:`.windsurf/rules`,shape:`directory`,kind:`rule`}]},deprecated:`devin-desktop`}],qn=new Set(Kn.map(e=>e.name));function isHarnessName(e){return qn.has(e)}function parseHarnesses(e){let t=(e??``).split(`,`).map(e=>e.trim()).filter(Boolean),n=t.filter(e=>!isHarnessName(e));if(n.length)throw Error(`Unsupported harness: ${n.join(`, `)}. Supported: ${Kn.map(e=>e.name).join(`, `)}.`);return t.filter(isHarnessName)}const Jn=[`claude-code`,`cursor`];function directoryExists(e){try{return r(e).isDirectory()}catch{return!1}}function selectHarnesses(e,t){let n=new Set([...Jn,...t]);return Kn.filter(t=>n.has(t.name)||directoryExists(C(e,t.project.detect)))}function fail(e,t,n){throw isCliError(e)?e:new M(e instanceof Error?e.message:t,{code:`command-failed`,exitCode:j.error,...n?{help:n}:{},cause:e})}function answerThenFail(e,t){let n=printAnswer(e,t);throw n!==void 0&&process.stdout.write(n),M.reported(j.error)}function collapseHome$1(e,t){return e&&t.startsWith(e+D)?`~${t.slice(e.length)}`:t}__name(collapseHome$1,`collapseHome`);function displayBinPath(e,t){return t?collapseHome$1(e,t):`buddy-agent-harness`}function parseHarnessOption(e){try{return parseHarnesses(e)}catch(e){throw new M(e.message,{code:`unsupported-harness`,exitCode:j.usage,help:`Pass --harness as a comma-separated list of the supported names.`,cause:e})}}const Yn=new Set([`deps`,`dependencies`,`local`,`plugins`,`marketplace`,`plugin`,`default`]);function isGenericName(e){return Yn.has(e.toLowerCase())}function marketplaceName(e){return e.replace(/^@/,``).replace(/\//g,`-`).replace(/[^a-zA-Z0-9-_.]/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``)||`agent-plugins`}function buildCatalog({name:e,owner:t,plugins:n}){let r=[...n].sort((e,t)=>e.plugin.localeCompare(t.plugin)).map(({plugin:e,package:t,version:n,description:r})=>{let i={source:`npm`,package:t,version:n};return r?{name:e,source:i,description:r}:{name:e,source:i}});return{name:e,owner:{name:t},description:`Plugins provided by this repository’s dependencies. Generated — do not edit.`,plugins:r}}function serializeCatalog(e){return`${JSON.stringify(e,null,` `)}\n`}function readJson$1(e){try{return JSON.parse(a(e,`utf8`))}catch{return}}__name(readJson$1,`readJson`);function readDepPlugin(e,t){let n=packageDir(e,t);if(!n)return{ok:!1,package:e,reason:`unresolved`};let r=readJson$1(C(n,`plugin.json`));if(!r||typeof r!=`object`)return{ok:!1,package:e,reason:`no-manifest`};let i=r,a=typeof i.name==`string`?i.name:void 0;if(!a)return{ok:!1,package:e,reason:`unnamed`};let o=readJson$1(C(n,`package.json`)),s=typeof o?.version==`string`?o.version:void 0;if(!s)return{ok:!1,package:e,reason:`no-manifest`};let c=typeof i.description==`string`?i.description:void 0;return{ok:!0,plugin:c?{package:e,plugin:a,version:s,description:c}:{package:e,plugin:a,version:s}}}function isPnp(){return!!process.versions.pnp}const Xn=C(`.agents`,`buddy-agent-harness`),Zn=C(Xn,`.claude-plugin`,`marketplace.json`);function readManifest(e){return JSON.parse(a(e,`utf8`))}function deriveCatalog(e){let t=C(e,`package.json`),n=readManifest(t),r=[],i=[];for(let e of declaredDependencies(n)){let n=readDepPlugin(e,t);n.ok?r.push(n.plugin):n.reason===`unresolved`&&i.push({package:e,reason:n.reason})}let a=typeof n.name==`string`?n.name:`unknown`,o=marketplaceName(a);return{catalog:buildCatalog({name:o,owner:a,plugins:r}),plugins:r,unresolved:i,genericName:isGenericName(o),pnp:isPnp()}}function catalogStatus(e,t){let n;try{n=a(C(e,Zn),`utf8`)}catch{n=void 0}return n===serializeCatalog(t)?`unchanged`:n===void 0?`created`:`updated`}function writeCatalog(e,t){let n=catalogStatus(e,t);if(n===`unchanged`)return n;let r=C(e,Zn);return i(b(r),{recursive:!0}),m(r,serializeCatalog(t)),n}function readJson(e){try{return JSON.parse(a(e,`utf8`))}catch{return}}function directories(e){try{return o(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}function claudeConfigDir(e,t=process.env){return t.CLAUDE_CONFIG_DIR||C(e,`.claude`)}function readClaudeState(e){let t=readJson(C(e,`plugins`,`installed_plugins.json`)),n=[];for(let[e,r]of Object.entries(t?.plugins??{}))if(Array.isArray(r))for(let t of r){if(!t||typeof t!=`object`)continue;let r=t,i=typeof r.version==`string`?r.version:void 0,a=typeof r.scope==`string`?r.scope:void 0;if(!i||!a)continue;let o=typeof r.projectPath==`string`?r.projectPath:void 0;n.push(o?{id:e,version:i,scope:a,projectPath:o}:{id:e,version:i,scope:a})}let r=readJson(C(e,`plugins`,`known_marketplaces.json`)),i=[];for(let[e,t]of Object.entries(r??{}))i.push({name:e,path:typeof t?.source?.path==`string`?t.source.path:``});return{installed:n,marketplaces:i}}const Qn={name:`claude-code`,scoped:!0,installedOnMachine:(e,t=process.env)=>n(claudeConfigDir(e,t)),state:(e,t=process.env)=>readClaudeState(claudeConfigDir(e,t)),register:e=>`claude plugin marketplace add ./${e} --scope project`,install:e=>`claude plugin install ${e} --scope project`,update:e=>`claude plugin update ${e} --scope project`,uninstall:e=>`claude plugin uninstall ${e} --scope project`,refreshMarketplace:e=>`claude plugin marketplace update ${e}`};function codexHome(e,t=process.env){return t.CODEX_HOME||C(e,`.codex`)}function readCodexState(e){let t=C(e,`plugins`,`cache`),n=[];for(let e of directories(t))for(let r of directories(C(t,e)))for(let i of directories(C(t,e,r)))n.push({id:`${r}@${e}`,version:i,scope:`user`});let r=[],i=``;try{i=a(C(e,`config.toml`),`utf8`)}catch{i=``}let o;for(let e of i.split(`
|
|
182
|
-
`)){let t=/^\s*\[marketplaces\.(?:"([^"]+)"|([^\]]+))\]\s*$/.exec(e);if(t){o={name:t[1]??t[2],path:``},r.push(o);continue}if(/^\s*\[/.test(e)){o=void 0;continue}let n=o?/^\s*source\s*=\s*"([^"]*)"\s*$/.exec(e):void 0;n?.[1]&&o&&(o.path=n[1])}return{installed:n,marketplaces:r}}const $n=[Qn,{name:`codex`,scoped:!1,installedOnMachine:(e,t=process.env)=>n(codexHome(e,t)),state:(e,t=process.env)=>readCodexState(codexHome(e,t)),register:e=>`codex plugin marketplace add ./${e}`,install:e=>`codex plugin add ${e}`,update:e=>`codex plugin add ${e}`,uninstall:e=>`codex plugin remove ${e}`,refreshMarketplace:()=>``}];function ours(e,t,n,r){let i=`@${t}`;return e.filter(e=>e.id.endsWith(i)&&(!r||e.projectPath===n))}function reconcile({catalog:e,catalogDir:t,root:n,installed:r,marketplaces:i,scoped:a=!0}){let o=i.find(t=>t.name===e.name),s=[],c=t.split(/[\\/]/).filter(Boolean),l=o?c.every(e=>o.path.includes(e)):!1,u=o&&!l?o.path:void 0;o||s.push({kind:`register`,subject:e.name,detail:`marketplace is not registered with this harness`});let d=ours(r,e.name,n,a),f=new Map(d.map(e=>[e.id,e]));for(let t of e.plugins){let n=`${t.name}@${e.name}`,r=f.get(n);if(!r){s.push({kind:`install`,subject:n,detail:`not installed; catalog pins ${t.source.version}`});continue}r.version!==t.source.version&&s.push({kind:`update`,subject:n,detail:`installed ${r.version}, catalog pins ${t.source.version}`})}let p=new Set(e.plugins.map(t=>`${t.name}@${e.name}`));for(let e of d)p.has(e.id)||s.push({kind:`uninstall`,subject:e.id,detail:`installed but no longer in the catalog; it will report a load failure until removed`});return{actions:s,...u?{collision:u}:{},unregistered:!o}}function commandFor(e,t,n){switch(t.kind){case`register`:return e.register(Xn);case`install`:return e.install(t.subject);case`update`:{let r=e.refreshMarketplace(n),i=e.update(t.subject);return r?`${r} && ${i}`:i}case`uninstall`:return e.uninstall(t.subject)}}function notesFor(e){let t=[];e.pnp&&t.push(`Yarn Plug’n’Play is active: dependencies live inside zip archives, so no harness can install from them. Set nodeLinker: node-modules, or unplug the plugin dependencies.`),e.genericName&&t.push(`Marketplace name "${e.catalog.name}" is generic. Registering a second marketplace under a name already in use replaces the first silently, and the install that follows reports "already installed" — the repository then runs the other one's versions.`);for(let{package:n}of e.unresolved)t.push(`Declared dependency "${n}" is not installed; install dependencies before generating.`);return t}const er=command({name:`dep-plugins`,description:`Derive the marketplace catalog for plugins shipped by this repository’s dependencies, so a harness can install them. Writes the catalog; installing is the harness’s own job.`,options:{root:{description:`Repository directory. Defaults to the current directory.`,type:N.string().optional()},check:{description:`Report whether the catalog is current without writing it. For CI and postinstall.`,type:N.boolean().optional()}},examples:[{command:`buddy-agent-harness dep-plugins`,description:`Write the marketplace catalog for dependency plugins`},{command:`buddy-agent-harness dep-plugins --check`,description:`Fail when the catalog is stale (CI)`}],run(e){try{let t=e.root??process.cwd(),n=deriveCatalog(t),r=e.check?catalogStatus(t,n.catalog)===`unchanged`?`current`:`would-change`:writeCatalog(t,n.catalog),i=_(),a=notesFor(n),o=$n.filter(e=>e.installedOnMachine(i)),s=[],c=[];for(let e of o){let r=e.state(i),o=reconcile({catalog:n.catalog,catalogDir:Xn,root:E(t),installed:r.installed,marketplaces:r.marketplaces,scoped:e.scoped});o.collision&&a.push(`${e.name}: marketplace "${n.catalog.name}" is already registered against ${o.collision}. Registering over it replaces the other repository's silently, and the install that follows reports "already installed" — rename this repository's marketplace instead.`),s.push({runtime:e.name,status:o.actions.length?`${o.actions.length} to apply`:`in sync`});for(let t of o.actions)c.push({runtime:e.name,do:commandFor(e,t,n.catalog.name),subject:t.subject,why:t.detail})}n.plugins.length&&a.push(`Copilot CLI rejects an npm marketplace source, so it cannot install from this catalog. It needs a path-sourced catalog, which cannot reach node_modules from a subdirectory.`);let l=result({catalog:Zn,marketplace:n.catalog.name,outcome:r,plugins:n.plugins.length?n.plugins.map(({plugin:e,package:t,version:n})=>({name:e,package:t,version:n})):`0 dependencies ship a plugin — nothing to install`,harness:s.length?s:`no supported harness detected on this machine`,actions:c.length?c:`0 actions — every detected harness matches the catalog`,...a.length?{notes:a}:{}});return r===`would-change`?answerThenFail(l,this.format):l}catch(e){return fail(e,`Catalog generation failed.`)}}});function filesUnder(e){try{return o(e,{recursive:!0,withFileTypes:!0}).filter(e=>e.isFile()).map(t=>T(e,C(t.parentPath,t.name)).split(D).join(w.sep)).sort()}catch{return[]}}function locatorText({file:e,server:t,field:n,position:r}){return r?`${e}#L${r.line}:${r.column}`:t===void 0?e:`${e}#servers.${t}${n===void 0?``:`.${n}`}`}function repairsOf(e){return Object.entries(e).map(([e,t])=>({problem:e,...t}))}const tr=`buddy-agent-harness`,nr=`/buddy-agent-harness:init-buddy-agent-harness`,pnpmSkillRef=e=>`\`${e}\` (pnpm install: \`pnpm-${tr}-${e.slice(e.indexOf(`:`)+1)}\`)`,G=pnpmSkillRef(nr),K=pnpmSkillRef(`/buddy-agent-harness:repair`),rr=`.agents/buddy-agent-harness/mcp.toml`,ir={"no-canonical":{detail:`the canonical skill directory does not exist, so no bridge can resolve`,repair:(e,t)=>({command:`${t} init`,instruction:`run \`${t} init\` to create .agents/skills and the bridges into it`}),skillRepair:()=>`run ${G}, which creates \`.agents/skills\` and the bridges`},missing:{detail:`no bridge at this path — the harness sees zero project skills`,repair:({file:e},t)=>({command:`${t} init`,instruction:`run \`${t} init\` to create the bridge at ${e}`}),skillRepair:()=>`run ${G}`},degraded:{detail:`expected a directory but found a regular file — checkout without core.symlinks`,repair:({file:e},t)=>({command:`${t} init --copy --force ${e}`,instruction:`run \`${t} init --copy --force ${e}\` to rebuild ${e} as a real directory`}),skillRepair:({file:e})=>`run \`${nr} --copy --force ${e}\``},stale:{detail:`symlink does not resolve to .agents/skills`,repair:({file:e},t)=>({command:`${t} init --force ${e}`,instruction:`run \`${t} init --force ${e}\` to repoint ${e} at .agents/skills`}),skillRepair:({file:e})=>`run \`${nr} --force ${e}\``},"diverged-bridge":{detail:`only the bridge changed since the two last agreed — an agent wrote through the copy`,repair:({file:e},t)=>({command:``,instruction:`replace .agents/skills with ${e} to keep the newer edit, then run \`${t} init --force ${e}\``}),skillRepair:({file:e})=>`replace .agents/skills with ${e} to keep the newer edit, then run \`${nr} --force ${e}\``},"diverged-canonical":{detail:`only .agents/skills changed since the two last agreed — the copy is stale`,repair:({file:e},t)=>({command:`${t} init --copy --force ${e}`,instruction:`run \`${t} init --copy --force ${e}\` to rebuild ${e} from the newer .agents/skills`}),skillRepair:({file:e})=>`run \`${nr} --copy --force ${e}\``},"diverged-both":{detail:`both sides changed since they last agreed — rebuilding would discard one of them`,repair:({file:e})=>({command:``,instruction:`reconcile .agents/skills with ${e} by hand — rebuilding would discard one of them; \`git diff --no-index .agents/skills ${e}\` shows what differs`}),skillRepair:({file:e})=>`run \`git diff --no-index .agents/skills ${e}\` and reconcile by hand`},"diverged-unknown":{detail:`contents differ and no commit where they agreed was found — which side moved is unknown`,repair:({file:e})=>({command:``,instruction:`reconcile .agents/skills with ${e} by hand — which side moved is unknown; \`git diff --no-index .agents/skills ${e}\` shows what differs`}),skillRepair:({file:e})=>`run \`git diff --no-index .agents/skills ${e}\` and reconcile by hand`},"unpinned-copy":{detail:`tracked copy without the skip-worktree bit — the tree is dirty with content that must not be committed`,repair:({file:e})=>({command:`git ls-files -z ${e} | xargs -0 git update-index --skip-worktree`,instruction:`run \`git ls-files -z ${e} | xargs -0 git update-index --skip-worktree\` to restore the skip-worktree bit`}),skillRepair:({file:e})=>`run \`git ls-files -z ${e} | xargs -0 git update-index --skip-worktree\``}};repairsOf(ir);const ar={"no-instructions":{detail:`no AGENTS.md at the repository root, so the instructions this repository has reach one harness at most`,repair:()=>({command:``,instruction:`hand this to ${G}, which consolidates what the repository has into AGENTS.md, or derives it`}),skillRepair:()=>`run ${G}, which consolidates or derives AGENTS.md`},"instructions-missing":{detail:`no instruction bridge at this path — the harness reads none of AGENTS.md`,repair:({file:e})=>({command:``,instruction:`hand ${e} to ${G}, which writes the bridge into it`}),skillRepair:()=>`run ${G}`},"instructions-unbridged":{detail:`the file is present but names AGENTS.md nowhere — the harness reads none of it`,repair:({file:e})=>({command:``,instruction:`hand ${e} to ${G}, which adds the bridge without discarding what the file already says`}),skillRepair:()=>`run ${G}, which adds the bridge without discarding what the file already says`},"instructions-shadowing":{detail:`this file suppresses the AGENTS.md beside it — the harness reads this instead, and none of AGENTS.md`,repair:({file:e})=>({command:``,instruction:`hand ${e} to ${G}, which consolidates what it says into AGENTS.md, or adds an @AGENTS.md import above it where the file has to stay`}),skillRepair:()=>`run ${G}, which consolidates the file into AGENTS.md or imports AGENTS.md from it`},"instructions-superseded":{detail:`a bridge from before the harness read AGENTS.md itself — it still works, and nothing needs it`,repair:({file:e})=>({command:``,instruction:`remove ${e}, or keep it for sessions that cannot read AGENTS.md directly — ${G} offers the choice`}),skillRepair:()=>`run ${G}, which offers to remove it`},"instructions-unreadable":{detail:`the settings file does not parse, so the harness reads none of it`,repair:({file:e})=>({command:``,instruction:`fix the JSON in ${e} by hand, then hand it to ${G}`}),skillRepair:()=>`fix the JSON by hand, then run ${G}`}};repairsOf(ar);const or=`~/${Gn}`;function globalBridgeStep(e,t=`~/${e.path}`){return e.kind===`import`?`add the line \`${e.line}\` to ${t}`:`run \`ln -s ${or} ${t}\``}function userSpellings(e,t){let n=`${e.detect}/`;return e.relocatedBy!==void 0&&t.startsWith(n)?[`~/${t}`,`$${e.relocatedBy}/${t.slice(n.length)}`]:[`~/${t}`]}function userBridgeAt(e){for(let{user:t}of Kn){let n=t?.instructionBridge;if(t&&n&&userSpellings(t,n.path).includes(e))return n}}function stepAt(e,t){let n=userBridgeAt(e);return n===void 0?`add the bridge the harness page names for ${e}`:`${t&&n.kind!==`import`?`move what ${e} says into ${or} and remove it, then `:``}${globalBridgeStep(n,e)}`}const sr=`hand the user this step, since nothing here writes outside the repository:`,cr={"global-instructions-missing":{detail:`no user-scope instruction file at this path — the harness loads none of ${or}`,repair:({file:e})=>({command:``,instruction:`${sr} ${stepAt(e,!1)}`}),skillRepair:()=>`hand the user the step the harness page names for that file; write nothing yourself`},"global-instructions-unbridged":{detail:`the file holds its own content and does not load ${or} — text placed there reaches no session of this harness`,repair:({file:e})=>({command:``,instruction:`${sr} ${stepAt(e,!0)}`}),skillRepair:()=>`hand the user the step the harness page names for that file, keeping what the file says; write nothing yourself`},"global-instructions-overridden":{detail:`the harness reads this file in place of its own user-scope file, so whatever that file loads goes unread, and this one does not load ${or}`,repair:({file:e})=>({command:``,instruction:`${sr} move what ${e} says into ${or} and remove it`}),skillRepair:()=>`hand the user the move of what that file says into the global file, and its removal; write nothing yourself`},"global-instructions-emptied":{detail:`the variable is set but empty, which this harness reads as the directory it starts in rather than as unset — its user-scope file is whichever one sits there, not the one in its own folder`,repair:({file:e})=>({command:``,instruction:`${sr} unset ${e.slice(1)} where your shell sets it, or set it to the folder you meant`}),skillRepair:()=>`hand the user the step of unsetting that variable; write nothing yourself`}};repairsOf(cr);const lr={"deprecated-harness":{detail:`a projection under a harness name that has been superseded — the replacement reads .agents/skills natively and needs no projection at all`,repair:({file:e})=>({command:``,instruction:`remove ${e} and enable the harness that replaced it — ${K} offers the correction`}),skillRepair:()=>`run ${K}`},"ignored-bridge":{detail:`a .gitignore rule matches this bridge — an untracked bridge swallows a real edit silently`,repair:({file:e})=>({command:``,instruction:`narrow or remove the .gitignore rule matching ${e} — ${K} offers the correction`}),skillRepair:()=>`run ${K}`},"unread-local-override":{detail:`no harness reads this filename, so everything in it is invisible to every agent`,repair:({file:e})=>({command:``,instruction:`move ${e} to CLAUDE.local.md, or consolidate it into AGENTS.md — ${K} offers the correction`}),skillRepair:()=>`run ${K}`},"unloadable-skill":{detail:`frontmatter that does not parse, or no description — either one makes a harness skip the skill outright`,repair:({file:e})=>({command:``,instruction:`quote the description in ${e}, or add one — ${K} offers the correction`}),skillRepair:()=>`run ${K}`}};repairsOf(lr);const ur={"mcp-golden-unreadable":{detail:`the golden MCP set does not parse — the locator gives the line and column, and nothing else can be said about it`,repair:e=>({command:``,instruction:`fix the TOML at ${locatorText(e)}`}),skillRepair:e=>`fix the TOML at ${locatorText(e)} by hand — the reported line and column are all that can be quoted, because the parser's own message repeats the offending line and that line is the one holding the credential`},"mcp-target-unreadable":{detail:`this harness config does not parse, so the harness starts none of its servers and nothing in it can be compared`,repair:e=>({command:``,instruction:`fix the syntax of ${locatorText(e)}`}),skillRepair:e=>`fix the syntax of ${locatorText(e)} by hand`},"mcp-unprojected":{detail:`the golden set declares this server and the harness config does not carry it`,repair:({file:e,server:t})=>({command:``,instruction:`add the server ${t} to ${e}, or drop it from the golden set — ${K} offers the correction`}),skillRepair:e=>`hand ${locatorText(e)} to ${K}, which projects it from its golden entry with \`mcp project\` — or drop it from the golden set`},"mcp-undeclared":{detail:`the harness config carries this server and the golden set does not declare it`,repair:({file:e,server:t})=>({command:``,instruction:`add the server ${t} to ${rr}, or drop it from ${e} — ${K} offers the import`}),skillRepair:e=>`hand ${locatorText(e)} to ${K}, which imports it field by field with \`mcp reconcile\`, refusing any literal credential — or drop it from ${e.file}`},"mcp-diverged-target":{detail:`only the harness config changed since the two last agreed — the edit was made through the copy`,repair:e=>({command:``,instruction:`reconcile the value at ${locatorText(e)} back into ${rr} — ${K} offers the import`}),skillRepair:e=>`hand ${locatorText(e)} to ${K}, which imports the field into ${rr} with \`mcp reconcile\` once approved`},"mcp-diverged-golden":{detail:`only the golden set changed since the two last agreed — the harness copy is stale`,repair:e=>({command:``,instruction:`update ${locatorText(e)} from the golden entry — ${K} offers the correction`}),skillRepair:e=>`hand ${locatorText(e)} to ${K}, which updates it from the golden entry with \`mcp project\``},"mcp-diverged-both":{detail:`both sides changed since they last agreed — merging either way would discard the other`,repair:e=>({command:``,instruction:`reconcile ${locatorText(e)} against ${rr} by hand`}),skillRepair:e=>`reconcile ${locatorText(e)} against ${rr} by hand — never merge a three-way conflict automatically`},"mcp-diverged-unknown":{detail:`the two disagree and no baseline says which side moved — neither history nor a last-projected record covers this server`,repair:e=>({command:``,instruction:`compare ${locatorText(e)} against ${rr} by hand`}),skillRepair:e=>`compare ${locatorText(e)} against ${rr} by hand`},"mcp-literal-secret":{detail:`a credential-bearing field holds a literal rather than a reference to an environment variable`,repair:e=>({command:``,instruction:`move the value at ${locatorText(e)} into an environment variable and reference it`}),skillRepair:e=>`move the value at ${locatorText(e)} into an environment variable and reference it — read the value from the file, never from this report, and never repeat it back`},"mcp-committed-secret":{detail:`a credential-bearing field holds a literal in a git-tracked file — the credential is committed, and moving it does not un-commit it`,repair:e=>({command:``,instruction:`rotate the credential behind ${locatorText(e)}, then reference it from an environment variable`}),skillRepair:e=>`rotate the credential behind ${locatorText(e)} at its issuer, then reference it from an environment variable — it is in the repository's history, so moving it is not enough`}};repairsOf(ur);const dr={"nonstandard-instructions":{detail:`instruction content only one harness reads — AGENTS.md carries the same prose to all of them`,repair:({file:e})=>({command:``,instruction:`consolidate ${e} into AGENTS.md — ${G} offers the consolidation, and keeps the content reachable where this harness needs it`}),skillRepair:({file:e})=>`hand ${e} to ${G}, which consolidates it into AGENTS.md`},"nonstandard-rule":{detail:`a path-scoped rule only one harness reads — a skill reaches every harness where the scoping is incidental`,repair:({file:e})=>({command:``,instruction:`convert ${e} into a skill under .agents/skills where its guidance is not tied to the paths it names — ${G} offers the conversion; keep it where the path scoping is the point`}),skillRepair:({file:e})=>`hand ${e} to ${G} to convert into a skill, unless the path scoping is load-bearing`},"nonstandard-command":{detail:`a harness command file — a skill is the portable form, and this harness reads skills too`,repair:({file:e})=>({command:``,instruction:`move ${e} to .agents/skills/<name>/SKILL.md — ${G} offers the move`}),skillRepair:({file:e})=>`hand ${e} to ${G}, which moves it to .agents/skills`},"nonstandard-skill":{detail:`a skill under a harness directory rather than the canonical one, where only that harness finds it`,repair:({file:e})=>({command:``,instruction:`move ${e} to .agents/skills and project it back where the harness needs one — ${G} offers the move`}),skillRepair:({file:e})=>`hand ${e} to ${G}, which moves it to .agents/skills`},"nonstandard-subagent":{detail:`a subagent definition with no cross-harness form — nothing outside this harness can read it, and no canonical form exists yet`,repair:({file:e})=>({command:``,instruction:`leave ${e} where it is and record that it reaches one harness only — no portable form exists to convert it to`}),skillRepair:({file:e})=>`leave ${e} in place — no portable form exists yet, so this is work for a person rather than a skill`}};repairsOf(dr);const fr={...ir,...ar,...cr,...lr,...ur,...dr};repairsOf(fr);function repairFor(e){return{problem:e,...fr[e]}}const pr=`.agents/skills`,mr=`AGENTS.local.md`;function frontmatterFault(e){let t=/^---\n([\s\S]*?)\n---/.exec(e);if(!t)return`unparseable`;let n=/^description:[ \t]*(.*)$/m.exec(t[1])?.[1]?.trim();if(!n)return`no-description`;if(!/^(['"]).*\1$/.test(n)&&/:\s/.test(n))return`unparseable`}function diagnoseConfiguration({root:e,git:t,cli:r}){let i=[],add=(e,t)=>{let{detail:n,repair:a}=repairFor(t);i.push({path:e,problem:t,detail:n,repair:a({file:e},r)})},o=selectHarnesses(e,[]);for(let t of o){let r=t.project.skillsDirectory;t.deprecated&&r&&n(C(e,r))&&add(r,`deprecated-harness`)}for(let r of o){let i=r.project.skillsDirectory;i&&n(C(e,i))&&t.isIgnored(i)&&add(i,`ignored-bridge`)}n(C(e,mr))&&add(mr,`unread-local-override`);for(let t of filesUnder(C(e,pr)).filter(e=>e.endsWith(`SKILL.md`)))frontmatterFault(a(C(e,pr,t),`utf8`))&&add(`${pr}/${t}`,`unloadable-skill`);return i}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const hr=[`transport`,`command`,`args`,`env`,`url`,`headers`,`description`,`enabled`,`timeout`,`source`],gr=new Set([`env`,`headers`]);function sameValue(e,t,n){if(gr.has(e)&&isRecord(t)&&isRecord(n)){let e=Object.keys(t);return e.length===Object.keys(n).length&&e.every(e=>t[e]===n[e])}return JSON.stringify(t)===JSON.stringify(n)}function divergingFields(e,t,n=new Set(hr)){return hr.filter(r=>{if(!n.has(r))return!1;let i=e[r];if(i===void 0)return!1;if(gr.has(r)&&isRecord(i)&&isRecord(t[r])){let e=t[r];return Object.keys(i).some(t=>i[t]!==e[t])}return!sameValue(r,i,t[r])})}function sameField(e,t,n){return sameValue(e,t?.[e],n?.[e])}function stringMap(e){if(!isRecord(e))return;let t=Object.entries(e).filter(([,e])=>typeof e==`string`);return t.length?Object.fromEntries(t):void 0}const _r=new Set([`stdio`,`http`,`sse`]);function transportOf(e){let t=e.type??e.transport;if(typeof t==`string`&&_r.has(t))return t;if(typeof e.url==`string`)return`http`;if(typeof e.command==`string`)return`stdio`}function serverFrom(e){let t=Array.isArray(e.args)&&e.args.every(e=>typeof e==`string`),n=transportOf(e),r=stringMap(e.env),i=stringMap(e.headers);return{...n?{transport:n}:{},...typeof e.command==`string`?{command:e.command}:{},...t?{args:e.args}:{},...r?{env:r}:{},...typeof e.url==`string`?{url:e.url}:{},...i?{headers:i}:{},...typeof e.description==`string`?{description:e.description}:{},...typeof e.enabled==`boolean`?{enabled:e.enabled}:{},...typeof e.timeout==`number`?{timeout:e.timeout}:{},...typeof e.source==`string`?{source:e.source}:{}}}const vr=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/,yr=/\$\{[^}]*\}|\$[A-Za-z_]/;var Refusal=class extends Error{field;reason;constructor(e,t){super(t),this.field=e,this.reason=t}};function refuse(e,t){throw new Refusal(e,t)}function rendering(e){try{return{kind:`entry`,entry:e()}}catch(e){if(!(e instanceof Refusal))throw e;return{kind:`refused`,field:e.field,reason:e.reason}}}function assertRunnable(e){(e.transport===`stdio`?!e.command:!e.url)&&refuse(e.transport===`stdio`?`command`:`url`,`the golden set leaves it unset and the target requires it`)}function defined(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function mapValues(e,t){return e&&Object.fromEntries(Object.entries(e).map(([e,n])=>[e,t(n)]))}function noReferenceIn(e,t,n){for(let r of t){let t=e[r];(Array.isArray(t)?t:[t]).some(e=>typeof e==`string`&&yr.test(e))&&refuse(r,`${n} documents no reference expansion here`)}}const br={fields:new Set([`transport`,`command`,`args`,`env`,`url`,`headers`,`description`,`timeout`]),read:serverFrom,write:e=>rendering(()=>(assertRunnable(e),defined({type:e.transport,command:e.command,args:e.args,env:e.env,url:e.url,headers:e.headers,description:e.description,timeout:e.timeout})))};function toCursor(e,t){return e.replace(/\$\{([^}]*)\}|\$[A-Za-z_]/g,(e,n)=>((n===void 0||!vr.test(e))&&refuse(t,`Cursor expands only a plain variable reference, with no default`),`\${env:${n}}`))}function fromCursor(e){return e.replace(/\$\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g,(e,t)=>`\${${t}}`)}function fromCursorEntry(e){let strings=e=>typeof e==`string`?fromCursor(e):e,map=e=>isRecord(e)?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,strings(t)])):e;return{...e,command:strings(e.command),args:Array.isArray(e.args)?e.args.map(strings):e.args,env:map(e.env),url:strings(e.url),headers:map(e.headers)}}const xr={fields:new Set([`command`,`args`,`env`,`url`,`headers`]),read:e=>serverFrom(fromCursorEntry(e)),write:e=>rendering(()=>(assertRunnable(e),defined({type:e.transport===`stdio`?`stdio`:void 0,command:e.command&&toCursor(e.command,`command`),args:e.args?.map(e=>toCursor(e,`args`)),env:mapValues(e.env,e=>toCursor(e,`env`)),url:e.url&&toCursor(e.url,`url`),headers:mapValues(e.headers,e=>toCursor(e,`headers`))})))},Sr=/^Bearer \$\{([A-Za-z_][A-Za-z0-9_]*)\}$/;function codexEnv(e){let t={},n=[];for(let[r,i]of Object.entries(e??{}))vr.exec(i)?.[1]===r?n.push(r):yr.test(i)?refuse(`env`,`Codex passes a variable through only under its own name`):t[r]=i;return defined({env:Object.keys(t).length?t:void 0,env_vars:n.length?n:void 0})}function codexHeaders(e){let t={},n={},r;for(let[i,a]of Object.entries(e??{})){let e=vr.exec(a)?.[1],o=Sr.exec(a)?.[1];o&&i===`Authorization`?r=o:e?n[i]=e:yr.test(a)?refuse(`headers`,`Codex fills a header only from a whole variable reference, or Bearer and one`):t[i]=a}return defined({http_headers:Object.keys(t).length?t:void 0,env_http_headers:Object.keys(n).length?n:void 0,bearer_token_env_var:r})}function stringRecord(e){return isRecord(e)?Object.fromEntries(Object.entries(e).filter(([,e])=>typeof e==`string`)):{}}function fromCodex(e){let t=Array.isArray(e.env_vars)?e.env_vars.filter(e=>typeof e==`string`):[],n={...stringRecord(e.env),...Object.fromEntries(t.map(e=>[e,`\${${e}}`]))},r=e.bearer_token_env_var,i={...stringRecord(e.http_headers),...Object.fromEntries(Object.entries(stringRecord(e.env_http_headers)).map(([e,t])=>[e,`\${${t}}`])),...typeof r==`string`?{Authorization:`Bearer \${${r}}`}:{}},a=e.tool_timeout_sec;return{command:e.command,args:e.args,env:n,url:e.url,headers:i,enabled:e.enabled,timeout:typeof a==`number`?Math.round(a*1e3):void 0}}const Cr={fields:new Set([`transport`,`command`,`args`,`env`,`url`,`headers`,`enabled`,`timeout`]),defaults:{timeout:6e4},read:e=>serverFrom(fromCodex(e)),write:e=>rendering(()=>(e.transport===`sse`&&refuse(`transport`,`Codex supports no SSE transport`),assertRunnable(e),noReferenceIn(e,[`command`,`args`,`url`],`Codex`),defined({command:e.command,args:e.args,...codexEnv(e.env),url:e.url,...codexHeaders(e.headers),enabled:e.enabled,tool_timeout_sec:e.timeout===void 0?void 0:e.timeout/1e3})))};function fromGemini(e){let{httpUrl:t,url:n,...r}=e;return typeof t==`string`?{...r,type:`http`,url:t}:typeof n==`string`?{...r,type:`sse`,url:n}:r}const q={"claude-code":br,cursor:xr,codex:Cr,"gemini-cli":{fields:new Set([`transport`,`command`,`args`,`env`,`url`,`headers`,`timeout`]),defaults:{timeout:6e5},read:e=>serverFrom(fromGemini(e)),write:e=>rendering(()=>(assertRunnable(e),defined({command:e.command,args:e.args,env:e.env,url:e.transport===`sse`?e.url:void 0,httpUrl:e.transport===`http`?e.url:void 0,headers:e.headers,timeout:e.timeout})))}};function stripJsonComments(e){let t=``,n=0,r=!1,i=!1;for(;n<e.length;){let a=e[n];if(r){t+=a,i?i=!1:a===`\\`?i=!0:a===`"`&&(r=!1),n+=1;continue}if(a===`"`){r=!0,t+=a,n+=1;continue}if(a===`/`&&e[n+1]===`/`){for(;n<e.length&&e[n]!==`
|
|
181
|
+
`)[0]?.trim()||``}function belongsElsewhere(e,t,n){return t!==void 0&&t!==n&&(e===t||e.startsWith(`${t}.`))}function ownTier(e){return e.trace.layers.find(e=>(e.tier===`repo`||e.tier===`user`)&&e.file&&(e.outcome===`used`||e.outcome===`stale`)&&!e.selection&&!e.empty)?.tier}function holders(e){return[...new Set(e.trace.layers.flatMap(({tier:e,plugin:t,file:n})=>e===`plugin`&&t!==void 0&&n?[t]:[]))]}function referenceImplementations(e,t,n={}){return isFamilyName(e)||e.includes(`*`)?familyImplementations(e,t,n):interfaceImplementations(e,t,n)}function familyInterfaces(e,t,n={}){let r=parseFamily(e);if(r.invalid!==void 0)throw new ReferenceFailure(`name-invalid`,r.invalid);let i=interfaceLookup(t,n),a=aliasIndex(t),o=new Set;for(let e of referenceNames(t)){let t=interfaceIdOf(shownName(e,a));if(t===void 0||!t.startsWith(`${r.prefix}.`))continue;let n=i(t).value;n&&o.add(n.id)}if(!o.size)throw new ReferenceFailure(`interface-unknown`,`no interface document matches ${e}.`,{help:"Run `reference list` for the names found."});return[...o].sort((e,t)=>e.localeCompare(t))}function familyImplementations(e,t,n={}){return{family:e,interfaces:familyInterfaces(e,t,n).map(e=>interfaceImplementations(e,t,n))}}function interfaceImplementations(e,t,n){let{accept:r,...i}=n,a={...i,projectSections:!1},o=parseReferenceName(`${e}${W}`);if(o.invalid||o.plugin!==void 0)throw new ReferenceFailure(`interface-unknown`,`"${e}" is not an interface id.`);let s=interfaceLookup(t,i),c=s(e),l=c.value;if(!l)throw new ReferenceFailure(`interface-unknown`,c.failure?.message??`no interface ${e}`);let u=aliasIndex(t),d=[l.id,...(u.interfaces.get(l.id)??[]).map(({alias:e})=>e)],f=[...r?.length?r:l.versions],p={interface:l.id,cardinality:l.cardinality,accept:f,implementations:[],excluded:[],warnings:[]},m=new Set,warn=e=>{for(let t of e){let e=`${t.code} ${t.message}`;m.has(e)||p.warnings.push(t),m.add(e)}};c.renamed!==void 0&&warn([{code:`reference-renamed`,message:`${e} is an older id of ${l.id}; ask for ${l.id} instead`}]);let inNamespace=e=>d.some(t=>e===t||e.startsWith(`${t}.`)),relevant=(e,t)=>{let n=readImplements(t.metadata??{}).entry?.id;return n!==void 0&&d.includes(n)?!0:inNamespace(e)&&!d.some(t=>belongsElsewhere(e,n,t))},consider=({pin:e,name:t,resolved:n,tier:r})=>{warn(n.warnings);let i=readImplements(n.metadata??{}).entry;if(!i||!d.includes(i.id)){let n=fitsNamespace(l.cardinality,d,t)?``:` and is not named ${l.cardinality===`one`?l.id:`${l.id}.<key>`}`;p.excluded.push({name:e,reasons:[`declares no implements ${l.id}@<version>${n}`]});return}let a=checkResolved(n,s,{id:l.id,versions:f});if(warn(a.warnings),a.failures.length){p.excluded.push({name:e,reasons:a.failures.map(({check:e,message:t})=>`${e}: ${t}`)});return}p.implementations.push({pin:e,description:firstLine(n.metadata?.description),unsupported:a.unsupported,name:t,tier:r,version:i.version})},qualified=(e,n)=>resolveReference(parseReferenceName(`${e}/${n}`),t,a),h=[...new Set(referenceNames(t).map(e=>shownName(e,u)))];for(let e of h){if(interfaceIdOf(e)!==void 0)continue;let n=resolveReference(e,t,a);if(n.status===`ambiguous`){for(let r of n.options??[]){if(r==="default")continue;let i=resolveReference(parseReferenceName(r),t,a);i.status===`found`&&relevant(e,i)&&(warn(i.warnings),p.excluded.push({name:r,reasons:[`ambiguous: ${n.message}; each is left out until a customizer picks one`]}))}continue}if(n.status!==`found`||!relevant(e,n))continue;let r=holders(n),i=l.cardinality===`many`?ownTier(n):void 0;if(i!==void 0){consider({pin:e,name:e,resolved:n,tier:i});for(let t of r)p.excluded.push({name:`${t}/${e}`,reasons:[`the ${i} implementation answers ${e}; a consumer loads it by that name`]});continue}let o=n.trace.stack.filter(e=>e!=="default").at(-1);if(o!==void 0){consider({pin:`${o}/${e}`,name:e,resolved:qualified(o,e),tier:`plugin`});for(let t of r)t!==o&&p.excluded.push({name:`${t}/${e}`,reasons:[`${e} loads the stack of ${o}, the pick; load ${o}/${e}`]})}}if(l.cardinality===`one`){let e=implementationInUse(l.id,t,a,p.implementations);e!==void 0&&(p.inUse=e)}return p}function implementationInUse(e,t,n,r){let i=resolveReference(parseReferenceName(e),t,n);if(i.status!==`found`)return;let a=i.trace.stack.filter(e=>e!=="default").at(-1);return a===void 0?i.trace.stack.includes(`default`)?`default`:void 0:r.find(({pin:t})=>t===`${a}/${e}`)?.pin}function fitsNamespace(e,t,n){return t.some(t=>e===`one`?n===t:n.startsWith(`${t}.`)&&n.length>t.length+1)}function bareName(e){requireName(e);let t=parseReferenceName(e);if(t.invalid)throw new ReferenceFailure(`name-invalid`,t.invalid);if(t.plugin!==void 0)throw new ReferenceFailure(`reference-qualified`,`a contribution is written under the bare name, which every tier resolves; ask for "${t.name}".`);return t}function insideRepository(e,t){let n=canonical(E(t)),r=canonical(e);return r!==n&&!r.startsWith(n+D)?!1:!r.slice(n.length).split(D).includes(`node_modules`)}function below(e,t){let n=T(e,t);return n&&!n.startsWith(`..`)&&!S(n)?n:void 0}function inFolder(e,t){let n=E(e),r=below(E(t),n)??below(canonical(E(t)),canonical(n));if(r===void 0)throw new ReferenceFailure(`in-not-below-root`,`--in names ${n}, which is ${n===E(t)?`the root itself`:`outside the root`}; a project section is written for a folder strictly below the root ${E(t)}.`);return{folder:r.split(D).join(`/`),path:n}}function checkPlaces(e,t){if([e.scope,e.in,e.plugin,e.default].filter(e=>e!==void 0).length>1)throw new ReferenceFailure(`options-conflict`,`pass one of ${t}.`)}function checkScope(e){if(e!==void 0&&e!==`repo`&&e!==`user`)throw new ReferenceFailure(`option-invalid`,`--scope is repo or user; got "${e}".`)}function sourceFolder(e,t,n){let r=E(e);if(!(n===`plugin`?pluginManifestName(r):skillName(r)!==void 0))throw new ReferenceFailure(`folder-invalid`,n===`plugin`?`${r} holds no plugin manifest, so it is not a plugin folder.`:`${r} holds no SKILL.md, so it is not a skill folder.`);if(!insideRepository(r,t))throw new ReferenceFailure(`folder-invalid`,`${r} is outside the repository, such as an installed copy; write to the ${n}'s source instead.`);return r}function writeTarget$1(e,t){let{root:n,home:r,scope:i,plugin:a,default:o}=t;if(a!==void 0){let t=C(sourceFolder(a,n,`plugin`),`references`);return{scope:`plugin`,dir:t,path:C(t,`${e.name}.md`)}}if(o!==void 0){let t=C(sourceFolder(o,n,`skill`),`references`);return{scope:`default`,dir:t,path:C(t,`${e.name}.default.md`)}}if(t.in!==void 0){let{folder:r,path:i}=inFolder(t.in,n),a=C(i,`.agents`,`references`);return{scope:`project`,dir:a,path:C(a,`${e.name}.md`),folder:r,folderPath:i}}let s=i===`user`?userReferencesDir(r):repoReferencesDir(E(n));return{scope:i===`user`?`user`:`repo`,dir:s,path:C(s,`${e.name}.md`)}}__name(writeTarget$1,`writeTarget`);function targetFiles(e,t){return candidateFiles({tier:e.scope==="default"?`default`:`repo`},t).map(t=>C(e.dir,...t.split(`/`)))}function answeringFile(e,t,r){return targetFiles(e,t).find(e=>e!==r&&n(e))}function metadataFile(e,t){return C(e.dir,`${t}${e.scope==="default"?`.default`:``}.meta.md`)}function reachOf(e){return e.scope===`user`?`only you, in every repository`:e.scope===`project`?`everyone working in ${e.folder}`:`everyone working in this repository`}const Vn=`a project section carries no merge (K24); drop --merge or --in.`;function readPicks(e,t){if(e.includes(`none`)){if(e.length>1)throw new ReferenceFailure(`option-invalid`,`--extends none removes the picks, so it takes no other step; got ${e.join(` `)}.`);return`none`}if(!e.length)throw new ReferenceFailure(`option-invalid`,`--extends names one or more steps, or none.`);return{values:e.map(e=>{let n=e.indexOf(`:`),r=n===-1?e:e.slice(0,n),i=n===-1?void 0:e.slice(n+1),a=r.endsWith(`/${t}`)?r.slice(0,-t.length-1):r;if(!H.test(a))throw new ReferenceFailure(`option-invalid`,`--extends takes a plugin, \`<plugin>/${t}\`, or default, each optionally \`:<merge>\`; got "${e}".`);if(i===void 0)return a;if(!isMergeOperation(i))throw new ReferenceFailure(`option-invalid`,`the merge in "${e}" is replace, patch, combine, or remove; got "${i}".`);return{[a]:i}})}}function customizeUsage(e,t){let n=e.extends!==void 0||e.extendsFile!==void 0,r=e.request!==void 0||e.body!==void 0;if(!e.base&&!n&&!r)throw new ReferenceFailure(`change-missing`,`say what to change: --extends or --extends-file picks what the name builds on, and --request with --body writes a generated body.`,{help:`Run \`reference customize ${t.name} --base\` for what the generator reads.`});let conflict=e=>new ReferenceFailure(`options-conflict`,e);if(e.plugin!==void 0)throw conflict("customize never writes a file a plugin ships; an author writes one with `create --plugin`.");if(e.scope!==void 0&&e.in!==void 0)throw conflict(`pass --scope or --in, not both: a customization goes to one place.`);if(e.in!==void 0&&e.merge!==void 0)throw conflict(Vn);if(e.in!==void 0&&n)throw conflict(`a project section has no stack, so it takes no picks; pick for the main document with --scope.`);if(e.extends!==void 0&&e.extendsFile!==void 0)throw conflict(`pass --extends or --extends-file, not both.`);if(e.implements!==void 0&&n)throw conflict(`an implementation is a whole document that replaces the stack, so it takes no picks.`);if(e.base&&(r||e.merge!==void 0||e.dryRun))throw conflict(`--base writes nothing; it takes only --extends or --extends-file, --scope or --in, --default, and --implements.`);if(r&&e.extends?.includes(`none`))throw conflict(`--extends none removes the picks and writes no body; pass it without --request and --body.`);if(r&&(e.request===void 0||e.body===void 0))throw new ReferenceFailure(`options-missing`,e.request===void 0?`--body needs --request: a generated body records the request it was written from.`:`--request needs --body: the command writes the body the generator wrote, and runs no model.`);checkScope(e.scope),checkMerge(e.merge);let i=e.extends===void 0?void 0:readPicks(e.extends,t.name);return e.in!==void 0&&inFolder(e.in,e.root),i?{picks:i}:{}}function checkMerge(e){if(e!==void 0&&!isMergeOperation(e))throw new ReferenceFailure(`option-invalid`,`--merge is replace, patch, combine, or remove; got "${e}".`)}function checkUsage(e){let t=bareName(e.name);if(e.command===`customize`)return{name:t,merge:e.merge,...customizeUsage(e,t)};if(checkPlaces(e,`--scope, --in, --plugin, and --default`),e.command===`create`&&e.in!==void 0&&e.merge!==void 0)throw new ReferenceFailure(`options-conflict`,Vn);checkScope(e.scope),checkMerge(e.merge);let n=e.merge;if(e.in!==void 0&&inFolder(e.in,e.root),e.command===`create`){if(n===`remove`&&e.template!==void 0)throw new ReferenceFailure(`remove-with-template`,`--merge remove writes no body, so it takes no --template.`);if(e.template!==void 0&&e.implements!==void 0)throw new ReferenceFailure(`template-with-implements`,`pass --template or --implements, not both.`)}return{name:t,merge:n}}function lookUpInterface(e,t,n){let r=parseReferenceName(e);if(r.invalid||r.plugin!==void 0)throw new ReferenceFailure(`interface-invalid`,`"${e}" is not an interface id.`);let i=interfaceLookup(t,n)(e);if(!i.value)throw new ReferenceFailure(`interface-invalid`,i.failure?.message??`no interface ${e}`);return i.value}function tryRead$1(e){try{return a(e,`utf8`)}catch{return}}function operationOf(e,t,n,r){if(t.scope===`project`)return;if(e.implements!==void 0)return`replace`;if(t.scope===`plugin`||t.scope==="default")return n;let i=r.metadata.merge;return n??(isMergeOperation(i)?i:void 0)??`patch`}function validateWrite(e,t,n={}){let r=checkUsage(e);if(!t)return r;let{name:i,merge:a}=r,o=n.display??(e=>e);if(!isDirectory$3(e.root))throw new ReferenceFailure(`root-missing`,`the root ${e.root} does not exist or is not a folder.`,{details:{root:e.root}});if(e.command===`customize`)return planCustomize(e,r,t,n);let s=writeTarget$1(i,e);if(e.command===`delete`)return checkFolder(s,i.name),{name:i,merge:a,target:s,before:resolveReference(i,t,n),extended:[]};let c=e.implements!==void 0||a===`remove`?{content:``,metadata:{},body:``}:readTemplate(e.template),l=titleOf(c);if(l)throw new ReferenceFailure(`template-title`,`the template's top level is the single heading "${l}" holding the others; patch matches by heading path, so make its sections top-level.`);let u=e.implements===void 0?void 0:lookUpInterface(e.implements,t,n);checkNamespace(u,s,i);let d=u?implementationTemplate(u):c;checkFolder(s,i.name);let f=resolveReference(i,t,n);checkMarkdown(f,s,i);let p={name:i,merge:a,target:s,template:d,before:f,extended:[]};u&&(p.iface=u);let m=tryRead$1(s.path),h=m===void 0?void 0:parseDocument(m,()=>{});if(p.operation=operationOf(e,s,a,d),p.extended=(readExtends(h?.metadata.extends,()=>{})??readExtends(d.metadata.extends,()=>{})??[]).map(({target:e})=>e).filter(e=>e!=="default"),(s.scope===`plugin`||s.scope==="default")&&p.operation===`replace`&&p.extended.length)throw new ReferenceFailure(`extends-replace`,`a ${s.scope===`plugin`?`plugin's file`:`skill's default`} that extends ${p.extended.join(`, `)} states only the sections it changes, so it takes no merge: replace; to replace the base entirely, write a snapshot of your own with no extends on it.`);if(h&&hasBody(h.body))throw new ReferenceFailure(`file-exists`,`${o(s.path)} already holds "${i.name}"; change it with the reference skill's Update mode.`,{details:{path:o(s.path)}});let g=answeringFile(s,i.name,s.path)??selectingSidecar(s,i.name);if(g)throw new ReferenceFailure(`file-exists`,`${o(g)} already answers "${i.name}" in that folder; change it there, or delete it first.`,{details:{path:o(g)}});return m!==void 0&&(p.existing=m),p}function selectingSidecar(e,t){if(e.scope===`project`)return;let n=metadataFile(e,t),r=tryParse(tryRead$1(n));return r&&r.metadata.extends!==void 0?n:void 0}function checkFolder(e,t){if(e.scope===`project`&&e.folderPath!==void 0&&e.folder!==void 0){if(!isDirectory$3(e.folderPath))throw new ReferenceFailure(`in-folder-missing`,`--in names ${e.folderPath}, which does not exist.`,{details:{folder:e.folder}});if(gitIgnores(e.folderPath,e.path))throw new ReferenceFailure(`in-folder-ignored`,`git ignores ${e.folder}/.agents/references/${t}.md, so load would never read a project section there.`,{details:{folder:e.folder}})}}function checkNamespace(e,t,n){if(!e||t.scope===`project`||fitsName(e,n.name))return;let r=e.cardinality===`one`?e.id:`${e.id}.<key>`;throw new ReferenceFailure(`name-outside-interface`,`an implementation of ${e.id} is named ${r}, not "${n.name}".`,{help:`Name it ${r}, or write it for one folder with --in.`})}function checkMarkdown(e,t,n){if(t.scope===`project`&&e.status===`found`&&e.format!==`markdown`)throw new ReferenceFailure(`in-not-markdown`,`the main document of "${n.name}" is ${e.format}, which has no project sections; customize the main document instead.`)}function readGiven(e,t){try{return a(e,`utf8`)}catch(n){throw new ReferenceFailure(`file-unreadable`,`cannot read the ${t} file ${e}: ${n.message}`,{details:{path:e}})}}function isStep(e){if(typeof e==`string`)return H.test(e);if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);if(t.length!==1)return!1;let[n,r]=t[0];if(!H.test(n))return!1;if(r==null)return!0;if(typeof r==`string`)return isMergeOperation(r);if(typeof r!=`object`||Array.isArray(r))return!1;let i=r;return Object.keys(i).some(e=>e!==`merge`&&e!==`extends`&&e!==`sections`)||i.merge!==void 0&&!isMergeOperation(i.merge)||i.sections!==void 0&&!Array.isArray(i.sections)?!1:i.extends===void 0||Array.isArray(i.extends)&&i.extends.every(isStep)}function readExtendsFile(e){let invalid=t=>new ReferenceFailure(`extends-file-invalid`,`the --extends-file ${e} ${t}.`,{details:{path:e}}),t;try{t=a(e,`utf8`)}catch(e){throw invalid(`cannot be read: ${e.message}`)}let n;try{n=(0,en.parse)(t)}catch(e){throw invalid(`is not YAML: ${e.message}`)}let r=n&&typeof n==`object`&&!Array.isArray(n)?n.extends:n;if(!Array.isArray(r)||!r.length||!r.every(isStep))throw invalid("is not a YAML `extends` list: each step a plugin or default, with only merge, extends, and sections");return{values:r}}function stepsOf(e){if(e===void 0)return;if(e===`none`)return null;let strip=e=>{if(typeof e!=`object`||!e)return e;let[t,n]=Object.entries(e)[0];if(typeof n!=`object`||!n)return e;let{sections:r,extends:i,...a}=n;return{[t]:Array.isArray(i)?{...a,extends:i.map(strip)}:a}};return readExtends(e.values.map(strip),()=>{})??[]}function checkSteps(e,t,n,r){let i=new Set(r.layers.flatMap(({tier:e,plugin:t,skipped:n})=>e===`plugin`&&t&&!n?[t]:[])),a=new Set(n.trace.layers.flatMap(({tier:e,plugin:t,file:n})=>e===`plugin`&&t!==void 0&&n&&i.has(t)?[t]:[])),o=e.map(({target:e})=>e).filter(e=>e!=="default"&&!a.has(e));if(o.length)throw new ReferenceFailure(`step-invalid`,`${o.join(`, `)} ${o.length===1?`is`:`are`} neither default nor a plugin holding "${t}"${a.size?`; the plugins holding it are ${[...a].join(`, `)}`:``}.`,{details:{steps:o}})}function coveringInterface(e,t,n){let r=interfaceLookup(t,n),i=e.split(`.`);for(let t=i.length;t>=1;t--){let n=r(i.slice(0,t).join(`.`)).value;if(n&&fitsName(n,e))return n}}function tryParse(e){return e===void 0?void 0:parseDocument(e,()=>{})}function customizeFiles(e,t,n){let r=e.scope===`project`?[e.path,C(e.dir,t,`README.md`)]:[e.path,C(e.dir,t,`README.md`),...V.map(({extension:n})=>C(e.dir,`${t}${n}`))],i=answeringFile(e,t),a=i!==void 0&&r.includes(i)?i:void 0,o=C(e.dir,t,`README.md`),s=e.path,c=`markdown`;if(a!==void 0&&a!==o)s=a,c=formatOfFile(a);else if(a===void 0&&e.scope!==`project`&&n.status===`found`&&n.format!==void 0&&n.format!==`markdown`){c=n.format;let r=[...n.trace.contributions].reverse().find(({path:e})=>formatOfFile(e)===c),i=r?x(r.path):V.find(e=>e.format===c)?.extension;s=C(e.dir,`${t}${i}`)}return{file:s,format:c,holder:c===`markdown`?s:metadataFile(e,t),other:a===o?o:void 0}}function quietInterface(e,t,n){let r=Array.isArray(e)?e[0]:e,i=typeof r==`string`?/^(.+)@\d+$/.exec(r.trim())?.[1]:void 0;return i===void 0?void 0:interfaceLookup(t,n)(i).value}function planCustomize(e,t,n,r){let{name:i}=t,a=r.display??(e=>e),o=writeTarget$1(i,{root:e.root,home:e.home,scope:e.scope,in:e.in}),s=e.request===void 0?void 0:readGiven(e.request,`--request`),c=e.body===void 0?void 0:readGiven(e.body,`--body`),l=e.extendsFile===void 0?t.picks:readExtendsFile(e.extendsFile),u=e.implements===void 0?void 0:lookUpInterface(e.implements,n,r);checkNamespace(u,o,i),checkFolder(o,i.name);let d=resolveReference(i,n,r);checkMarkdown(d,o,i);let f=stepsOf(l);f&&checkSteps(f,i.name,d,baseLayers(n,o));let p=customizeFiles(o,i.name,d),m=tryRead$1(p.file),h=p.holder===p.file?m:tryRead$1(p.holder),g=tryParse(h),_=u||o.scope===`project`?void 0:g?.metadata.implements,v=u??(_===void 0?void 0:quietInterface(_,n,r)),y=resolveBase(i,n,o,f,r),b=s!==void 0||!!e.base;if(b&&l===void 0&&y.status===`ambiguous`)throw new ReferenceFailure(`pick-required`,`"${i.name}" is ambiguous: ${y.message}; pick what it builds on before the request is applied.`,{details:{options:y.options??[]},help:`Pass --extends with the picks, bottom first, from: ${(y.options??[]).join(`, `)}.`});if(b&&!v&&_===void 0&&y.status===`missing`){let e=coveringInterface(i.name,n,r);if(e)throw new ReferenceFailure(`implements-required`,`"${i.name}" is in the namespace of the interface ${e.id}, and nothing implements it; name the interface.`,{details:{interface:e.id},help:`Run \`reference customize ${i.name} --implements ${e.id} --request <file> --body <file>\`.`})}let x=p.format===`markdown`?hasBody(g?.body??``):!!m?.trim();if(s!==void 0&&x&&!isGenerated(g?.metadata))throw new ReferenceFailure(`body-not-generated`,`${a(p.file)} holds a body that records no request, written with create or by hand; customizing would replace it.`,{details:{path:a(p.file)},help:`Change it with the reference skill's Update mode, or delete it first.`});if(p.other&&!e.base)throw new ReferenceFailure(`file-exists`,`${a(p.other)} already answers "${i.name}" in that folder; change it there, or delete it first.`,{details:{path:a(p.other)}});let S={...t,picks:l,target:o,before:d,base:y,file:p.file,format:p.format,holder:p.holder};return f!==void 0&&(S.steps=f),s!==void 0&&(S.request=s),c!==void 0&&(S.body=c),v&&(S.iface=v),u?S.implementsValue=`${u.id}@${u.version}`:typeof _==`string`&&(S.implementsValue=_),m!==void 0&&(S.existing=m),h!==void 0&&(S.held=h),S}function tryRead(e){try{return a(e,`utf8`)}catch{return}}function describeAnswer(e,t=e=>e){if(e.status===`found`){let n=e.trace.contributions.at(-1),r=n?n.tier===`plugin`?`plugin ${n.plugin}`:n.tier==="default"?`the default of ${n.skill}`:`the ${n.tier} file ${t(n.path)}`:void 0,i=e.trace.stack.length?`, on the stack ${e.trace.stack.join(` → `)}`:``,a=[...new Set(e.projectSections.map(({folder:e})=>e))];if(!r)return`"${e.name}" is answered only by the project sections of ${a.join(`, `)}.`;let o=a.length?`, with the project sections of ${a.join(`, `)}`:``;return`"${e.name}" is answered by ${r}${i}${o}.`}return e.status===`ambiguous`?`"${e.name}" is ambiguous: ${e.message}; the options are ${(e.options??[]).join(`, `)}.`:`"${e.name}" is ${e.status}: ${e.message}.`}const Hn=[`merge`,`extends`,`implements`,`aliases`];function selectionKeys(e,t){let n=parseDocument(e,()=>{}).metadata,r={};for(let[e,i]of Object.entries(t.metadata))e!==`merge`&&!(e in n)&&(r[e]=i);return r}function withBody(e,t){let n=t.replace(/^(?:[ \t]*\r?\n)+/,``);return n?`${e.replace(/\s*$/,``)}\n\n${n}`:e}function hiddenWarning(e,t,n,r){let i=t.scope===`project`?projectHidingLayer(e):hidingLayer(e,t.dir,t.path);if(i)return{code:t.scope===`user`&&i.tier===`repo`?`repo-hides-user`:`reference-hidden`,message:`${r(n)} is written, but ${hiderLabel(i,r)} applies above it, so load does not read it until that contribution changes.`}}function createContribution(e,t,n={}){let r=validateWrite({command:`create`,...t},e,n),{name:a,target:o,existing:s,operation:c}=r,l=r.template,u=n.display??(e=>e),d=[],f={merge:c};if(o.scope===`project`)for(let e of Hn)f[e]=void 0,!r.iface&&e in l.metadata&&d.push({code:`project-section-key-ignored`,message:`\`${e}\` is dropped from the project section for ${o.folder}: a project section states only what differs in its folder.`});if((o.scope===`plugin`||o.scope==="default")&&r.extended.length){let t=recordedSources(r.extended,sourceCatalog(e,{tier:o.scope}));Object.assign(f,generatedFrontmatter({sources:t}))}let p=s===void 0?editFrontmatter(l.content,f):withBody(editFrontmatter(s,{...selectionKeys(s,l),...f}),l.body),h=hiddenWarning(r.before,o,o.path,u);h&&d.push(h);let g=hasDescription(parseDocument(p,()=>{}))?[]:["it has no `description` in its frontmatter, so `list` and `search` show it blank"],_={name:a.name,scope:o.scope,path:o.path,content:p,dryRun:!!t.dryRun,hints:g,warnings:d};return o.folder!==void 0&&(_.folder=o.folder),_.dryRun?_:(i(o.dir,{recursive:!0}),m(o.path,p,s===void 0?{flag:`wx`}:{}),(o.scope===`project`||r.before.trace.layers.some(e=>e.path===o.dir||e.path===o.path))&&(_.after=resolveReference(a,{...e,projects:new Map},n)),_)}function placeOf(e){return e.scope===`project`?`project section for ${e.folder}`:e.scope==="default"?`default`:`${e.scope} contribution`}function deleteContribution(e,t,r={}){let{name:i,target:a,before:o}=validateWrite({command:`delete`,...t},e,r),s=r.display??(e=>e),c=!!t.dryRun,l=answeringFile(a,i.name,r.without),f=metadataFile(a,i.name),p=f!==r.without&&n(f),m=l??(p?f:void 0),h={name:i.name,scope:a.scope};if(a.folder!==void 0&&(h.folder=a.folder),!m)return{...h,path:a.path,dryRun:c,code:`no-file`,message:`${s(a.path)} does not exist, so there is no ${placeOf(a)} of "${i.name}" to delete; nothing was deleted. ${describeAnswer(o,r.display)} An installed plugin's, a managed, or an installed skill's contribution is never deleted.`,after:o};let g=l&&formatOfFile(l)!==`markdown`&&p?f:void 0,_=formatOfFile(m)===`markdown`?m:g,v=_===void 0?void 0:readExtends(parseDocument(tryRead(_)??``,()=>{}).metadata.extends,()=>{});if(!c&&(u(m),g&&u(g),b(m)!==a.dir))try{d(b(m))}catch{}let y={...h,path:m,dryRun:c,after:resolveReference(i,{...e,projects:new Map},{...r,without:c?m:void 0})};return g&&(y.metadataFile=g),v&&(y.selection=v.map(({target:e})=>e)),y}function defaultSkill(e){let t=e.layers.find(({tier:e,skipped:t})=>e==="default"&&!t);if(t?.skill===void 0)return;let n=b(t.dir),r=e.layers.find(({tier:e,plugin:t,dir:r})=>e===`plugin`&&t!==void 0&&n.startsWith(b(r)+D));return r?.plugin===void 0?{skill:t.skill}:{skill:t.skill,plugin:r.plugin}}function bodyOf(e){let t=e.held===void 0?void 0:parseDocument(e.held,()=>{}),n=e.format===`markdown`?hasBody(t?.body??``):!!e.existing?.trim();return{metadata:t?.metadata??{},held:n}}function write(e,t){i(b(e),{recursive:!0}),m(e,t)}function writePicks(e,t,n,r){let i=r.display??(e=>e),{name:a,holder:o,picks:s,before:c}=e;n.path=o;let{metadata:l,held:d}=bodyOf(e);if(s===`none`){if(e.held===void 0||!(`extends`in l))return{...n,action:`cleared`,code:`no-selection`,message:`${i(o)} holds no selection of "${a.name}", so nothing was removed. ${describeAnswer(c,r.display)}`,after:c};let s=editFrontmatter(e.held,{extends:void 0,declined:void 0}),d=!s.trim();return n.action=`cleared`,d?n.deleted=!0:n.content=s,n.dryRun?n:(d?u(o):write(o,s),after(n,e,t,r))}let f=s?s.values:[],p=editFrontmatter(e.held??``,{extends:f,declined:declinedBy(e,f)});Object.assign(n,{action:`selection`,content:p,extends:f});let m=hiddenWarning(c,e.target,o,i);return m&&n.warnings.push(m),e.base.trace.builtBy.startsWith(`managed `)&&n.warnings.push({code:`extends-not-used`,message:`the picks are written to ${i(o)}, but ${e.base.trace.builtBy}'s extends builds the stack, so they are not used while it does.`}),d&&isGenerated(l)&&n.hints.push(`its body was generated from a request against the old stack; customize "${a.name}" again with that request (\`reference customize ${a.name} --request <file> --body <file>\`) to regenerate it on the new picks.`),n.dryRun?n:(write(o,p),after(n,e,t,r))}function packageSources(e){let t=new Set(e.trace.stack),n=new Set(e.projectSections.flatMap(({plugin:e})=>e===void 0?[]:[e])),r=new Map;for(let{plugin:i,version:a}of e.trace.projectSections)i===void 0||!n.has(i)||t.has(i)||r.has(i)||r.set(i,a===void 0?{plugin:i}:{plugin:i,version:a});return[...r.values()]}function writeGenerated(e,t,n,r){let i=r.display??(e=>e),{target:a,base:o,picks:s}=e,c=a.scope===`project`,l=!c&&e.implementsValue!==void 0,{metadata:u}=bodyOf(e),d=s&&s!==`none`?s.values:u.extends,f=l||o.status!==`found`?[]:[...recordedSources(o.trace.stack,sourceCatalog(baseLayers(t,a),{tier:a.scope===`user`?`user`:`repo`}),defaultSkill(t)),...c?packageSources(o):[]],p=!c&&!l&&d!==void 0,m={extends:p?d:void 0,declined:p?declinedBy(e,d):void 0,sources:void 0,request:void 0,...generatedFrontmatter({sources:f,request:e.request})},h=e.body;n.action=`generated`,n.path=e.file,e.format===`markdown`?n.content=editFrontmatter(h,{merge:c?void 0:l?`replace`:e.merge??`patch`,implements:l?e.implementsValue:void 0,...m}):(n.content=h,n.metadataFile=e.holder,n.metadataContent=editFrontmatter(e.held??``,{merge:void 0,implements:void 0,...m}));let g=hiddenWarning(e.before,a,e.file,i);return g&&n.warnings.push(g),n.dryRun?n:(write(e.file,n.content),n.metadataContent!==void 0&&write(e.holder,n.metadataContent),after(n,e,t,r))}function declinedBy(e,t){let n=readExtends(t,()=>{});if(!n)return;let r=new Map;for(let{tier:t,plugin:n,file:i,outcome:a,frontmatter:o}of e.base.trace.layers)t!==`plugin`||n===void 0||i===void 0||a.startsWith(`not read`)||r.has(n)||r.set(n,o?.extends);let i=new Set,place=e=>{for(let t of e)i.has(t.target)||(i.add(t.target),place(t.extends??readExtends(r.get(t.target),()=>{})??[]))};place(n);let a=[...r.keys()].filter(e=>!i.has(e));return a.length?a:void 0}function after(e,t,n,r){return{...e,after:resolveReference(t.name,{...n,projects:new Map},r)}}function givesSections(e){return Array.isArray(e)?e.some(givesSections):typeof e!=`object`||!e?!1:Object.values(e).some(e=>{if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return t.sections!==void 0||givesSections(t.extends)})}function customizeFamily(e,t,n={}){let r=parseFamily(t.name);if(r.invalid!==void 0)throw new ReferenceFailure(`name-invalid`,r.invalid);let i=validateWrite({command:`customize`,...t,name:r.prefix});if([t.base,t.request,t.body,t.implements,t.merge].some(e=>e!==void 0))throw new ReferenceFailure(`options-conflict`,`a family takes only picks: --extends or --extends-file, with --scope and --dry-run; a body, a merge, or a base is per name.`);let a=t.extendsFile===void 0?i.picks:readExtendsFile(t.extendsFile);if(a!==void 0&&a!==`none`&&givesSections(a.values))throw new ReferenceFailure(`step-invalid`,`a step of ${t.name} gives sections, which differ per interface; pick for one interface at a time to change sections.`);let o=interfaceLookup(e,n),s=familyInterfaces(t.name,e,n).map(r=>{if(o(r).value?.cardinality===`many`)return{interface:r,outcome:`skipped`,reason:`${r} is a many interface, which has no single pick.`};let i={...t,name:r};try{let t=validateWrite({command:`customize`,...i},e,n);if(a!==`none`&&t.base.status!==`found`)return{interface:r,outcome:`kept`,reason:`no step holds ${r}; it keeps what it had.`}}catch(e){if(e instanceof ReferenceFailure&&e.code===`step-invalid`)return{interface:r,outcome:`kept`,reason:`${e.message} It keeps what it had.`};throw e}return{interface:r,outcome:`written`,answer:i}}).map(({answer:t,...r})=>t===void 0?r:{...r,result:customizeSingle(e,t,n)});return{family:t.name,scope:t.scope??`repo`,dryRun:!!t.dryRun,interfaces:s}}function customizeContribution(e,t,n={}){return isFamilyName(t.name)||t.name.includes(`*`)?customizeFamily(e,t,n):customizeSingle(e,t,n)}function customizeSingle(e,t,n){let r=validateWrite({command:`customize`,...t},e,n),i={name:r.name.name,scope:r.target.scope,action:`base`,path:r.file,dryRun:!!t.dryRun,hints:[],warnings:[]};return r.target.folder!==void 0&&(i.folder=r.target.folder),t.base?{...i,base:generatorBase(r.base,r.iface)}:r.request===void 0?writePicks(r,e,i,n):writeGenerated(r,e,i,n)}const Un=V.map(({extension:e})=>e);function entries(e){try{return o(e,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))}catch{return[]}}function valid(e){return!parseReferenceName(e).invalid}function heldFiles(e){let t=[],n=e.tier==="default",r=n?U:``;for(let i of entries(e.dir)){let a=i.name,o=C(e.dir,a);if(i.isDirectory()){!n&&valid(a)&&tryRead$2(C(o,`README.md`))!==void 0&&t.push({name:a,path:C(o,`README.md`),suffix:`/README.md`,kind:`markdown`,folderForm:!0});continue}if(a===`_renames.yaml`)continue;let s=`${r}${Sn}.md`;if(a.endsWith(s)){let e=a.slice(0,-s.length);valid(e)&&t.push({name:e,path:o,suffix:s,kind:`metadata`,folderForm:!1});continue}let c=`${r}.md`;if(a.endsWith(c)){let e=a.slice(0,-c.length);valid(e)&&t.push({name:e,path:o,suffix:c,kind:`markdown`,folderForm:!1});continue}let l=Un.find(e=>a.endsWith(`${r}${e}`));if(l){let e=a.slice(0,-`${r}${l}`.length);valid(e)&&t.push({name:e,path:o,suffix:`${r}${l}`,kind:`data`,folderForm:!1})}}return t}function placesOf(e,t,n){if(n.plugin!==void 0&&n.default!==void 0)throw new ReferenceFailure(`options-conflict`,`pass one of --plugin and --default.`);if(n.plugin!==void 0)return[{tier:`plugin`,dir:C(sourceFolder(n.plugin,t,`plugin`),`references`)}];if(n.default!==void 0)return[{tier:`default`,dir:C(sourceFolder(n.default,t,`skill`),`references`)}];let r=[{tier:`repo`,dir:repoReferencesDir(t)},{tier:`user`,dir:userReferencesDir(n.home)},...projectFolders(t,e.projects).folders.map(({folder:e,dir:t})=>({tier:`project`,dir:t,folder:e}))],i=new Set;return r.filter(({dir:e})=>{let t=E(e);return!i.has(t)&&(i.add(t),!0)})}function renameSources(e){let t=renameTable(e),n=aliasIndex(e);return e=>{if(n.owned.has(e))return[];let r=new Map,add=(e,t)=>r.set(e,(r.get(e)??new Set).add(t));for(let n of t.byOld.get(e)??[])add(n.to,`plugin ${n.plugin}'s ${Ln}`);for(let t of n.byAlias.get(e)??[])add(t.name,`the aliases of ${t.tier===`plugin`?`plugin ${t.plugin}`:`the default of ${t.skill}`}`);return[...r].map(([e,t])=>({to:e,by:[...t].join(` and `)}))}}function holdsName(e,t){let r=e.tier==="default"?U:``;return[`${t}${r}.md`,...e.tier==="default"?[]:[C(t,`README.md`)],...Un.map(e=>`${t}${r}${e}`),`${t}${r}${Sn}.md`].some(t=>n(C(e.dir,t)))}function migrateReferences(e,t){let r=E(t.root??e.root??process.cwd()),i=t.names?.length?new Set(t.names.map(e=>bareName(e).name)):void 0,a=placesOf(e,r,t),o=renameSources(e),s=new Set(e.layers.flatMap(({tier:e,plugin:t,skipped:n})=>e===`plugin`&&t&&!n?[t]:[])),c=[],u=[];for(let e of a){let t=e.folder===void 0?{}:{folder:e.folder},r=e.tier===`repo`||e.tier===`user`||e.tier===`project`,a=new Set,l=heldFiles(e);e.tier==="default"&&l.push(...oldDefaults(e,i,l));for(let s of l){let l=r?o(s.name):[];if(i&&!i.has(s.name)&&!l.some(({to:e})=>i.has(e)))continue;let d={path:s.path,tier:e.tier,...t,name:s.name},f={path:s.path};if(s.kind===`markdown`){let t=tryRead$2(s.path)??``,{metadata:n,body:r}=parseDocument(t,()=>{}),{findings:i,keys:a}=legacyRewrite(n,r,e.tier===`project`?`project`:`contribution`,s.name);for(let e of i)c.push(rowOf(d,e));Object.keys(a).length&&(f.content=editFrontmatter(t,a))}if(s.suffix===`.md`&&e.tier==="default"){let t=C(e.dir,`${s.name}${U}.md`),r=defaultLayoutFinding(s.name);if(n(t)){let{to:e,...t}=r;c.push(rowOf(d,{...t,manual:`${s.name}${U}.md is there too and answers the name; the old file is not read, so delete it by hand once nothing in it is needed`}))}else c.push(rowOf(d,r)),Object.assign(f,{moveFrom:s.path,moveTo:t})}l.length&&renameRow(e,s,l,a,d,c,f),(f.content!==void 0||f.moveTo!==void 0)&&u.push(f)}if(r)for(let n of qualifiedOverrides(e.dir)){if(i&&!i.has(n.name))continue;let r=qualifiedRow(e,n,s,a,{path:n.path,tier:e.tier,...t,name:n.name},c);r&&u.push(r)}}let d=!1;if(t.write)for(let e of u)e.content!==void 0&&m(e.path,e.content),e.moveFrom!==void 0&&e.moveTo!==void 0&&l(e.moveFrom,e.moveTo),e.prune!==void 0&&pruneEmpty(e.prune),d=!0;return{rows:c,written:d,warnings:[...renameTable(e).warnings]}}function rowOf(e,t){let n={...e,form:t.form,from:t.from},r=t.note===void 0?``:`; ${t.reads}, and ${t.note}`;return t.to!==void 0&&(n.to=`${t.to}${r}`),t.manual!==void 0&&(n.manual=`${t.manual}${r}`),n}function oldDefaults(e,t,n){return t?[...t].flatMap(t=>{let r=C(e.dir,`${t}.md`);return tryRead$2(r)===void 0||n.some(e=>e.path===r)?[]:[{name:t,path:r,suffix:`.md`,kind:`markdown`,folderForm:!1}]}):[]}function renameRow(e,t,n,r,i,a,o){let s=t.folderForm?`${t.name}/`:`${t.name}${t.suffix}`,c={...i,form:`renamed`,from:s,by:n.map(({by:e})=>e).join(`; `)};if(n.length>1){a.push({...c,manual:`it is renamed differently: ${n.map(({to:e,by:t})=>`"${e}" by ${t}`).join(`, `)}; rename it by hand to the one that applies`});return}let{to:l}=n[0],u=t.kind===`metadata`||t.kind===`data`;if(holdsName(e,l)&&!r.has(l)||r.has(l)&&!u){a.push({...c,manual:`"${l}" already has a file in that folder; merge the two by hand, then delete this one`});return}r.add(l);let d=t.folderForm?`${l}/`:`${l}${t.suffix}`;a.push({...c,to:d});let f=t.folderForm?b(t.path):t.path;Object.assign(o,{moveFrom:f,moveTo:C(e.dir,t.folderForm?l:`${l}${t.suffix}`)})}function pruneEmpty(e){try{o(e).length||d(e)}catch{}}function qualifiedRow(e,t,n,r,i,a){let{plugin:o,name:s}=t,c=qualifiedOverrideFinding(t,e.tier===`project`?`project`:`contribution`),{to:l,...u}=c,manual=e=>{a.push(rowOf(i,{...u,manual:e}))};if(l===void 0)return manual(c.manual);if(!n.has(o))return manual(`plugin ${o} is not installed; it would become ${l}, extending a plugin that is not there: install ${o} and run migrate again, or delete this file`);if(holdsName(e,s)||r.has(s))return manual(`"${s}" already has a file in that folder; move this file's sections into it and add ${o} to its extends, then delete this one`);let d=tryRead$2(t.path)??``,{metadata:f,body:p}=parseDocument(d,()=>{}),m=[`extends`,`overrides`].find(e=>e in f);if(m!==void 0)return manual(`it also writes \`${m}\`; move it to ${s}.md by hand, with an extends that names ${o}`);r.add(s),a.push(rowOf(i,c));let{findings:h,keys:g}=legacyRewrite(f,p,`contribution`,s);for(let e of h)a.push(rowOf(i,e));return{path:t.path,content:editFrontmatter(d,{...g,extends:[o]}),moveFrom:t.path,moveTo:C(e.dir,`${s}.md`),prune:b(t.path)}}function whereReference(e,t,{root:n,display:r=e=>e,in:i}){typeof e==`string`&&requireName(e);let a=i===void 0?void 0:inFolder(i,n),o=typeof e==`string`?parseReferenceName(e):e,s=resolveReference(o,t,{display:r}),c={name:o.raw,status:s.status,files:[],headings:s.status===`found`&&s.format===`markdown`?headingPaths(s.content??``):[],used:s.trace.stack,layers:s.trace.layers,warnings:s.warnings};if(s.options&&(c.options=s.options),o.invalid)return c;let l=(Array.isArray(t)?t:t.layers).find(({tier:e})=>e===`user`)?.dir,u=[{scope:`repo`,dir:repoReferencesDir(n),path:``},...l?[{scope:`user`,dir:l,path:``}]:[],...a?[{scope:`project`,dir:C(a.path,`.agents`,`references`),path:``,folder:a.folder}]:[]];for(let e of u){let t=answeringFile(e,o.name)??C(e.dir,`${o.name}.md`),i=e.scope===`project`?projectHidingLayer(s):hidingLayer(s,e.dir,t),a={scope:e.folder??e.scope,path:e.scope===`user`?r(t):T(n,t),reaches:reachOf(e)};i&&(a.hiddenBy=hiderLabel(i,r)),c.files.push(a)}return c}function skillsProjection(e,t,n=skillsDirectories(e)?.[t]){let r=n??[],[i]=r;if(i===void 0)throw Error(`cyber-agentkit records no ${t} skills directories for ${e}.`);return r.includes(`.agents/skills`)?{}:{skillsDirectory:i}}const Wn=`.agents/AGENTS.md`,Gn=[{name:`claude-code`,project:{detect:`.claude`,...skillsProjection(`claude-code`,`project`),shadowedBy:[`CLAUDE.md`,`.claude/CLAUDE.md`,`CLAUDE.local.md`],mcpConfig:{path:`.mcp.json`,key:`mcpServers`,format:`json`,dialect:`claude-code`},nonstandard:[{path:`.claude/commands`,shape:`directory`,kind:`command`},{path:`.claude/rules`,shape:`directory`,kind:`rule`},{path:`.claude/agents`,shape:`directory`,kind:`subagent`}]},user:{detect:`.claude`,...skillsProjection(`claude-code`,`user`),relocatedBy:`CLAUDE_CONFIG_DIR`,emptyRelocatesToStart:!0,instructionBridge:{kind:`import`,path:`.claude/CLAUDE.md`,line:`@~/${Wn}`}}},{name:`cursor`,project:{detect:`.cursor`,...skillsProjection(`cursor`,`project`),mcpConfig:{path:`.cursor/mcp.json`,key:`mcpServers`,format:`json`,dialect:`cursor`},nonstandard:[{path:`.cursorrules`,shape:`file`,kind:`instructions`},{path:`.cursor/rules`,shape:`directory`,kind:`rule`},{path:`.cursor/commands`,shape:`directory`,kind:`command`},{path:`.cursor/skills`,shape:`directory`,kind:`skill`}]},user:{detect:`.cursor`,...skillsProjection(`cursor`,`user`)}},{name:`codex`,project:{detect:`.codex`,...skillsProjection(`codex`,`project`),mcpConfig:{path:`.codex/config.toml`,key:`mcp_servers`,format:`toml`,dialect:`codex`,shared:!0},nonstandard:[{path:`.codex/skills`,shape:`directory`,kind:`skill`}]},user:{detect:`.codex`,...skillsProjection(`codex`,`user`),instructionBridge:{kind:`symlink`,path:`.codex/AGENTS.md`},shadowedBy:[`.codex/AGENTS.override.md`],relocatedBy:`CODEX_HOME`}},{name:`copilot-cli`,project:{detect:`.github/skills`,...skillsProjection(`copilot-cli`,`project`),nonstandard:[{path:`.github/copilot-instructions.md`,shape:`file`,kind:`instructions`},{path:`.github/instructions`,shape:`directory`,kind:`instructions`},{path:`.github/skills`,shape:`directory`,kind:`skill`}]},user:{detect:`.copilot`,...skillsProjection(`copilot-cli`,`user`),relocatedBy:`COPILOT_HOME`,instructionBridge:{kind:`symlink`,path:`.copilot/copilot-instructions.md`}}},{name:`gemini-cli`,project:{detect:`.gemini`,...skillsProjection(`gemini-cli`,`project`),instructionBridge:{kind:`settings-entry`,path:`.gemini/settings.json`,key:`context.fileName`},mcpConfig:{path:`.gemini/settings.json`,key:`mcpServers`,format:`json`,dialect:`gemini-cli`,shared:!0},nonstandard:[{path:`GEMINI.md`,shape:`file`,kind:`instructions`},{path:`.gemini/skills`,shape:`directory`,kind:`skill`}]},user:{detect:`.gemini`,...skillsProjection(`gemini-cli`,`user`),instructionBridge:{kind:`symlink`,path:`.gemini/GEMINI.md`}}},{name:`devin-desktop`,project:{detect:`.devin`}},{name:`windsurf`,project:{detect:`.windsurf`,skillsDirectory:`.windsurf/skills`,nonstandard:[{path:`.windsurfrules`,shape:`file`,kind:`instructions`},{path:`.windsurf/rules`,shape:`directory`,kind:`rule`}]},deprecated:`devin-desktop`}],Kn=new Set(Gn.map(e=>e.name));function isHarnessName(e){return Kn.has(e)}function parseHarnesses(e){let t=(e??``).split(`,`).map(e=>e.trim()).filter(Boolean),n=t.filter(e=>!isHarnessName(e));if(n.length)throw Error(`Unsupported harness: ${n.join(`, `)}. Supported: ${Gn.map(e=>e.name).join(`, `)}.`);return t.filter(isHarnessName)}const qn=[`claude-code`,`cursor`];function directoryExists(e){try{return r(e).isDirectory()}catch{return!1}}function selectHarnesses(e,t){let n=new Set([...qn,...t]);return Gn.filter(t=>n.has(t.name)||directoryExists(C(e,t.project.detect)))}function fail(e,t,n){throw isCliError(e)?e:new M(e instanceof Error?e.message:t,{code:`command-failed`,exitCode:j.error,...n?{help:n}:{},cause:e})}function answerThenFail(e,t){let n=printAnswer(e,t);throw n!==void 0&&process.stdout.write(n),M.reported(j.error)}function collapseHome$1(e,t){return e&&t.startsWith(e+D)?`~${t.slice(e.length)}`:t}__name(collapseHome$1,`collapseHome`);function displayBinPath(e,t){return t?collapseHome$1(e,t):`buddy-agent-harness`}function parseHarnessOption(e){try{return parseHarnesses(e)}catch(e){throw new M(e.message,{code:`unsupported-harness`,exitCode:j.usage,help:`Pass --harness as a comma-separated list of the supported names.`,cause:e})}}const Jn=new Set([`deps`,`dependencies`,`local`,`plugins`,`marketplace`,`plugin`,`default`]);function isGenericName(e){return Jn.has(e.toLowerCase())}function marketplaceName(e){return e.replace(/^@/,``).replace(/\//g,`-`).replace(/[^a-zA-Z0-9-_.]/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``)||`agent-plugins`}function buildCatalog({name:e,owner:t,plugins:n}){let r=[...n].sort((e,t)=>e.plugin.localeCompare(t.plugin)).map(({plugin:e,package:t,version:n,description:r})=>{let i={source:`npm`,package:t,version:n};return r?{name:e,source:i,description:r}:{name:e,source:i}});return{name:e,owner:{name:t},description:`Plugins provided by this repository’s dependencies. Generated — do not edit.`,plugins:r}}function serializeCatalog(e){return`${JSON.stringify(e,null,` `)}\n`}function readJson$2(e){try{return JSON.parse(a(e,`utf8`))}catch{return}}__name(readJson$2,`readJson`);function readDepPlugin(e,t){let n=packageDir(e,t);if(!n)return{ok:!1,package:e,reason:`unresolved`};let r=readJson$2(C(n,`plugin.json`));if(!r||typeof r!=`object`)return{ok:!1,package:e,reason:`no-manifest`};let i=r,a=typeof i.name==`string`?i.name:void 0;if(!a)return{ok:!1,package:e,reason:`unnamed`};let o=readJson$2(C(n,`package.json`)),s=typeof o?.version==`string`?o.version:void 0;if(!s)return{ok:!1,package:e,reason:`no-manifest`};let c=typeof i.description==`string`?i.description:void 0;return{ok:!0,plugin:c?{package:e,plugin:a,version:s,description:c}:{package:e,plugin:a,version:s}}}function isPnp(){return!!process.versions.pnp}const Yn=C(`.agents`,`buddy-agent-harness`),Xn=C(Yn,`.claude-plugin`,`marketplace.json`);function readManifest(e){return JSON.parse(a(e,`utf8`))}function deriveCatalog(e){let t=C(e,`package.json`),n=readManifest(t),r=[],i=[];for(let e of declaredDependencies(n)){let n=readDepPlugin(e,t);n.ok?r.push(n.plugin):n.reason===`unresolved`&&i.push({package:e,reason:n.reason})}let a=typeof n.name==`string`?n.name:`unknown`,o=marketplaceName(a);return{catalog:buildCatalog({name:o,owner:a,plugins:r}),plugins:r,unresolved:i,genericName:isGenericName(o),pnp:isPnp()}}function catalogStatus(e,t){let n;try{n=a(C(e,Xn),`utf8`)}catch{n=void 0}return n===serializeCatalog(t)?`unchanged`:n===void 0?`created`:`updated`}function writeCatalog(e,t){let n=catalogStatus(e,t);if(n===`unchanged`)return n;let r=C(e,Xn);return i(b(r),{recursive:!0}),m(r,serializeCatalog(t)),n}function readJson$1(e){try{return JSON.parse(a(e,`utf8`))}catch{return}}__name(readJson$1,`readJson`);function directories(e){try{return o(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}function claudeConfigDir(e,t=process.env){return t.CLAUDE_CONFIG_DIR||C(e,`.claude`)}function readClaudeState(e){let t=readJson$1(C(e,`plugins`,`installed_plugins.json`)),n=[];for(let[e,r]of Object.entries(t?.plugins??{}))if(Array.isArray(r))for(let t of r){if(!t||typeof t!=`object`)continue;let r=t,i=typeof r.version==`string`?r.version:void 0,a=typeof r.scope==`string`?r.scope:void 0;if(!i||!a)continue;let o=typeof r.projectPath==`string`?r.projectPath:void 0;n.push(o?{id:e,version:i,scope:a,projectPath:o}:{id:e,version:i,scope:a})}let r=readJson$1(C(e,`plugins`,`known_marketplaces.json`)),i=[];for(let[e,t]of Object.entries(r??{}))i.push({name:e,path:typeof t?.source?.path==`string`?t.source.path:``});return{installed:n,marketplaces:i}}const Zn={name:`claude-code`,scoped:!0,installedOnMachine:(e,t=process.env)=>n(claudeConfigDir(e,t)),state:(e,t=process.env)=>readClaudeState(claudeConfigDir(e,t)),register:e=>`claude plugin marketplace add ./${e} --scope project`,install:e=>`claude plugin install ${e} --scope project`,update:e=>`claude plugin update ${e} --scope project`,uninstall:e=>`claude plugin uninstall ${e} --scope project`,refreshMarketplace:e=>`claude plugin marketplace update ${e}`};function codexHome(e,t=process.env){return t.CODEX_HOME||C(e,`.codex`)}function readCodexState(e){let t=C(e,`plugins`,`cache`),n=[];for(let e of directories(t))for(let r of directories(C(t,e)))for(let i of directories(C(t,e,r)))n.push({id:`${r}@${e}`,version:i,scope:`user`});let r=[],i=``;try{i=a(C(e,`config.toml`),`utf8`)}catch{i=``}let o;for(let e of i.split(`
|
|
182
|
+
`)){let t=/^\s*\[marketplaces\.(?:"([^"]+)"|([^\]]+))\]\s*$/.exec(e);if(t){o={name:t[1]??t[2],path:``},r.push(o);continue}if(/^\s*\[/.test(e)){o=void 0;continue}let n=o?/^\s*source\s*=\s*"([^"]*)"\s*$/.exec(e):void 0;n?.[1]&&o&&(o.path=n[1])}return{installed:n,marketplaces:r}}const Qn=[Zn,{name:`codex`,scoped:!1,installedOnMachine:(e,t=process.env)=>n(codexHome(e,t)),state:(e,t=process.env)=>readCodexState(codexHome(e,t)),register:e=>`codex plugin marketplace add ./${e}`,install:e=>`codex plugin add ${e}`,update:e=>`codex plugin add ${e}`,uninstall:e=>`codex plugin remove ${e}`,refreshMarketplace:()=>``}];function ours(e,t,n,r){let i=`@${t}`;return e.filter(e=>e.id.endsWith(i)&&(!r||e.projectPath===n))}function reconcile({catalog:e,catalogDir:t,root:n,installed:r,marketplaces:i,scoped:a=!0}){let o=i.find(t=>t.name===e.name),s=[],c=t.split(/[\\/]/).filter(Boolean),l=o?c.every(e=>o.path.includes(e)):!1,u=o&&!l?o.path:void 0;o||s.push({kind:`register`,subject:e.name,detail:`marketplace is not registered with this harness`});let d=ours(r,e.name,n,a),f=new Map(d.map(e=>[e.id,e]));for(let t of e.plugins){let n=`${t.name}@${e.name}`,r=f.get(n);if(!r){s.push({kind:`install`,subject:n,detail:`not installed; catalog pins ${t.source.version}`});continue}r.version!==t.source.version&&s.push({kind:`update`,subject:n,detail:`installed ${r.version}, catalog pins ${t.source.version}`})}let p=new Set(e.plugins.map(t=>`${t.name}@${e.name}`));for(let e of d)p.has(e.id)||s.push({kind:`uninstall`,subject:e.id,detail:`installed but no longer in the catalog; it will report a load failure until removed`});return{actions:s,...u?{collision:u}:{},unregistered:!o}}function commandFor(e,t,n){switch(t.kind){case`register`:return e.register(Yn);case`install`:return e.install(t.subject);case`update`:{let r=e.refreshMarketplace(n),i=e.update(t.subject);return r?`${r} && ${i}`:i}case`uninstall`:return e.uninstall(t.subject)}}function notesFor(e){let t=[];e.pnp&&t.push(`Yarn Plug’n’Play is active: dependencies live inside zip archives, so no harness can install from them. Set nodeLinker: node-modules, or unplug the plugin dependencies.`),e.genericName&&t.push(`Marketplace name "${e.catalog.name}" is generic. Registering a second marketplace under a name already in use replaces the first silently, and the install that follows reports "already installed" — the repository then runs the other one's versions.`);for(let{package:n}of e.unresolved)t.push(`Declared dependency "${n}" is not installed; install dependencies before generating.`);return t}const $n=command({name:`dep-plugins`,description:`Derive the marketplace catalog for plugins shipped by this repository’s dependencies, so a harness can install them. Writes the catalog; installing is the harness’s own job.`,options:{root:{description:`Repository directory. Defaults to the current directory.`,type:N.string().optional()},check:{description:`Report whether the catalog is current without writing it. For CI and postinstall.`,type:N.boolean().optional()}},examples:[{command:`buddy-agent-harness dep-plugins`,description:`Write the marketplace catalog for dependency plugins`},{command:`buddy-agent-harness dep-plugins --check`,description:`Fail when the catalog is stale (CI)`}],run(e){try{let t=e.root??process.cwd(),n=deriveCatalog(t),r=e.check?catalogStatus(t,n.catalog)===`unchanged`?`current`:`would-change`:writeCatalog(t,n.catalog),i=_(),a=notesFor(n),o=Qn.filter(e=>e.installedOnMachine(i)),s=[],c=[];for(let e of o){let r=e.state(i),o=reconcile({catalog:n.catalog,catalogDir:Yn,root:E(t),installed:r.installed,marketplaces:r.marketplaces,scoped:e.scoped});o.collision&&a.push(`${e.name}: marketplace "${n.catalog.name}" is already registered against ${o.collision}. Registering over it replaces the other repository's silently, and the install that follows reports "already installed" — rename this repository's marketplace instead.`),s.push({runtime:e.name,status:o.actions.length?`${o.actions.length} to apply`:`in sync`});for(let t of o.actions)c.push({runtime:e.name,do:commandFor(e,t,n.catalog.name),subject:t.subject,why:t.detail})}n.plugins.length&&a.push(`Copilot CLI rejects an npm marketplace source, so it cannot install from this catalog. It needs a path-sourced catalog, which cannot reach node_modules from a subdirectory.`);let l=result({catalog:Xn,marketplace:n.catalog.name,outcome:r,plugins:n.plugins.length?n.plugins.map(({plugin:e,package:t,version:n})=>({name:e,package:t,version:n})):`0 dependencies ship a plugin — nothing to install`,harness:s.length?s:`no supported harness detected on this machine`,actions:c.length?c:`0 actions — every detected harness matches the catalog`,...a.length?{notes:a}:{}});return r===`would-change`?answerThenFail(l,this.format):l}catch(e){return fail(e,`Catalog generation failed.`)}}});function filesUnder(e){try{return o(e,{recursive:!0,withFileTypes:!0}).filter(e=>e.isFile()).map(t=>T(e,C(t.parentPath,t.name)).split(D).join(w.sep)).sort()}catch{return[]}}function locatorText({file:e,server:t,field:n,position:r}){return r?`${e}#L${r.line}:${r.column}`:t===void 0?e:`${e}#servers.${t}${n===void 0?``:`.${n}`}`}function repairsOf(e){return Object.entries(e).map(([e,t])=>({problem:e,...t}))}const er=`buddy-agent-harness`,tr=`/buddy-agent-harness:init-buddy-agent-harness`,pnpmSkillRef=e=>`\`${e}\` (pnpm install: \`pnpm-${er}-${e.slice(e.indexOf(`:`)+1)}\`)`,K=pnpmSkillRef(tr),nr=pnpmSkillRef(`/buddy-agent-harness:enhance`),q=pnpmSkillRef(`/buddy-agent-harness:repair`),rr=`.agents/buddy-agent-harness/mcp.toml`,ir={"no-canonical":{detail:`the canonical skill directory does not exist, so no bridge can resolve`,repair:(e,t)=>({command:`${t} init`,instruction:`run \`${t} init\` to create .agents/skills and the bridges into it`}),skillRepair:()=>`run ${K}, which creates \`.agents/skills\` and the bridges`},missing:{detail:`no bridge at this path — the harness sees zero project skills`,repair:({file:e},t)=>({command:`${t} init`,instruction:`run \`${t} init\` to create the bridge at ${e}`}),skillRepair:()=>`run ${K}`},degraded:{detail:`expected a directory but found a regular file — checkout without core.symlinks`,repair:({file:e},t)=>({command:`${t} init --copy --force ${e}`,instruction:`run \`${t} init --copy --force ${e}\` to rebuild ${e} as a real directory`}),skillRepair:({file:e})=>`run \`${tr} --copy --force ${e}\``},stale:{detail:`symlink does not resolve to .agents/skills`,repair:({file:e},t)=>({command:`${t} init --force ${e}`,instruction:`run \`${t} init --force ${e}\` to repoint ${e} at .agents/skills`}),skillRepair:({file:e})=>`run \`${tr} --force ${e}\``},"diverged-bridge":{detail:`only the bridge changed since the two last agreed — an agent wrote through the copy`,repair:({file:e},t)=>({command:``,instruction:`replace .agents/skills with ${e} to keep the newer edit, then run \`${t} init --force ${e}\``}),skillRepair:({file:e})=>`replace .agents/skills with ${e} to keep the newer edit, then run \`${tr} --force ${e}\``},"diverged-canonical":{detail:`only .agents/skills changed since the two last agreed — the copy is stale`,repair:({file:e},t)=>({command:`${t} init --copy --force ${e}`,instruction:`run \`${t} init --copy --force ${e}\` to rebuild ${e} from the newer .agents/skills`}),skillRepair:({file:e})=>`run \`${tr} --copy --force ${e}\``},"diverged-both":{detail:`both sides changed since they last agreed — rebuilding would discard one of them`,repair:({file:e})=>({command:``,instruction:`reconcile .agents/skills with ${e} by hand — rebuilding would discard one of them; \`git diff --no-index .agents/skills ${e}\` shows what differs`}),skillRepair:({file:e})=>`run \`git diff --no-index .agents/skills ${e}\` and reconcile by hand`},"diverged-unknown":{detail:`contents differ and no commit where they agreed was found — which side moved is unknown`,repair:({file:e})=>({command:``,instruction:`reconcile .agents/skills with ${e} by hand — which side moved is unknown; \`git diff --no-index .agents/skills ${e}\` shows what differs`}),skillRepair:({file:e})=>`run \`git diff --no-index .agents/skills ${e}\` and reconcile by hand`},"unpinned-copy":{detail:`tracked copy without the skip-worktree bit — the tree is dirty with content that must not be committed`,repair:({file:e})=>({command:`git ls-files -z ${e} | xargs -0 git update-index --skip-worktree`,instruction:`run \`git ls-files -z ${e} | xargs -0 git update-index --skip-worktree\` to restore the skip-worktree bit`}),skillRepair:({file:e})=>`run \`git ls-files -z ${e} | xargs -0 git update-index --skip-worktree\``}};repairsOf(ir);const ar={"no-instructions":{detail:`no AGENTS.md at the repository root, so the instructions this repository has reach one harness at most`,repair:()=>({command:``,instruction:`hand this to ${K}, which consolidates what the repository has into AGENTS.md, or derives it`}),skillRepair:()=>`run ${K}, which consolidates or derives AGENTS.md`},"instructions-missing":{detail:`no instruction bridge at this path — the harness reads none of AGENTS.md`,repair:({file:e})=>({command:``,instruction:`hand ${e} to ${K}, which writes the bridge into it`}),skillRepair:()=>`run ${K}`},"instructions-unbridged":{detail:`the file is present but names AGENTS.md nowhere — the harness reads none of it`,repair:({file:e})=>({command:``,instruction:`hand ${e} to ${K}, which adds the bridge without discarding what the file already says`}),skillRepair:()=>`run ${K}, which adds the bridge without discarding what the file already says`},"instructions-shadowing":{detail:`this file suppresses the AGENTS.md beside it — the harness reads this instead, and none of AGENTS.md`,repair:({file:e})=>({command:``,instruction:`hand ${e} to ${K}, which consolidates what it says into AGENTS.md, or adds an @AGENTS.md import above it where the file has to stay`}),skillRepair:()=>`run ${K}, which consolidates the file into AGENTS.md or imports AGENTS.md from it`},"instructions-superseded":{detail:`a bridge from before the harness read AGENTS.md itself — it still works, and nothing needs it`,repair:({file:e})=>({command:``,instruction:`remove ${e}, or keep it for sessions that cannot read AGENTS.md directly — ${K} offers the choice`}),skillRepair:()=>`run ${K}, which offers to remove it`},"instructions-unreadable":{detail:`the settings file does not parse, so the harness reads none of it`,repair:({file:e})=>({command:``,instruction:`fix the JSON in ${e} by hand, then hand it to ${K}`}),skillRepair:()=>`fix the JSON by hand, then run ${K}`}};repairsOf(ar);const or=`~/${Wn}`;function globalBridgeStep(e,t=`~/${e.path}`){return e.kind===`import`?`add the line \`${e.line}\` to ${t}`:`run \`ln -s ${or} ${t}\``}function userSpellings(e,t){let n=`${e.detect}/`;return e.relocatedBy!==void 0&&t.startsWith(n)?[`~/${t}`,`$${e.relocatedBy}/${t.slice(n.length)}`]:[`~/${t}`]}function userBridgeAt(e){for(let{user:t}of Gn){let n=t?.instructionBridge;if(t&&n&&userSpellings(t,n.path).includes(e))return n}}function stepAt(e,t){let n=userBridgeAt(e);return n===void 0?`add the bridge the harness page names for ${e}`:`${t&&n.kind!==`import`?`move what ${e} says into ${or} and remove it, then `:``}${globalBridgeStep(n,e)}`}const sr=`hand the user this step, since nothing here writes outside the repository:`,cr={"global-instructions-missing":{detail:`no user-scope instruction file at this path — the harness loads none of ${or}`,repair:({file:e})=>({command:``,instruction:`${sr} ${stepAt(e,!1)}`}),skillRepair:()=>`hand the user the step the harness page names for that file; write nothing yourself`},"global-instructions-unbridged":{detail:`the file holds its own content and does not load ${or} — text placed there reaches no session of this harness`,repair:({file:e})=>({command:``,instruction:`${sr} ${stepAt(e,!0)}`}),skillRepair:()=>`hand the user the step the harness page names for that file, keeping what the file says; write nothing yourself`},"global-instructions-overridden":{detail:`the harness reads this file in place of its own user-scope file, so whatever that file loads goes unread, and this one does not load ${or}`,repair:({file:e})=>({command:``,instruction:`${sr} move what ${e} says into ${or} and remove it`}),skillRepair:()=>`hand the user the move of what that file says into the global file, and its removal; write nothing yourself`},"global-instructions-emptied":{detail:`the variable is set but empty, which this harness reads as the directory it starts in rather than as unset — its user-scope file is whichever one sits there, not the one in its own folder`,repair:({file:e})=>({command:``,instruction:`${sr} unset ${e.slice(1)} where your shell sets it, or set it to the folder you meant`}),skillRepair:()=>`hand the user the step of unsetting that variable; write nothing yourself`}};repairsOf(cr);const lr={"deprecated-harness":{detail:`a projection under a harness name that has been superseded — the replacement reads .agents/skills natively and needs no projection at all`,repair:({file:e})=>({command:``,instruction:`remove ${e} and enable the harness that replaced it — ${q} offers the correction`}),skillRepair:()=>`run ${q}`},"ignored-bridge":{detail:`a .gitignore rule matches this bridge — an untracked bridge swallows a real edit silently`,repair:({file:e})=>({command:``,instruction:`narrow or remove the .gitignore rule matching ${e} — ${q} offers the correction`}),skillRepair:()=>`run ${q}`},"unread-local-override":{detail:`no harness reads this filename, so everything in it is invisible to every agent`,repair:({file:e})=>({command:``,instruction:`move ${e} to CLAUDE.local.md, or consolidate it into AGENTS.md — ${q} offers the correction`}),skillRepair:()=>`run ${q}`},"unloadable-skill":{detail:`frontmatter that does not parse, or no description — either one makes a harness skip the skill outright`,repair:({file:e})=>({command:``,instruction:`quote the description in ${e}, or add one — ${q} offers the correction`}),skillRepair:()=>`run ${q}`}};repairsOf(lr);const ur={"mcp-golden-unreadable":{detail:`the golden MCP set does not parse — the locator gives the line and column, and nothing else can be said about it`,repair:e=>({command:``,instruction:`fix the TOML at ${locatorText(e)}`}),skillRepair:e=>`fix the TOML at ${locatorText(e)} by hand — the reported line and column are all that can be quoted, because the parser's own message repeats the offending line and that line is the one holding the credential`},"mcp-target-unreadable":{detail:`this harness config does not parse, so the harness starts none of its servers and nothing in it can be compared`,repair:e=>({command:``,instruction:`fix the syntax of ${locatorText(e)}`}),skillRepair:e=>`fix the syntax of ${locatorText(e)} by hand`},"mcp-unprojected":{detail:`the golden set declares this server and the harness config does not carry it`,repair:({file:e,server:t})=>({command:``,instruction:`add the server ${t} to ${e}, or drop it from the golden set — ${q} offers the correction`}),skillRepair:e=>`hand ${locatorText(e)} to ${q}, which projects it from its golden entry with \`mcp project\` — or drop it from the golden set`},"mcp-undeclared":{detail:`the harness config carries this server and the golden set does not declare it`,repair:({file:e,server:t})=>({command:``,instruction:`add the server ${t} to ${rr}, or drop it from ${e} — ${q} offers the import`}),skillRepair:e=>`hand ${locatorText(e)} to ${q}, which imports it field by field with \`mcp reconcile\`, refusing any literal credential — or drop it from ${e.file}`},"mcp-diverged-target":{detail:`only the harness config changed since the two last agreed — the edit was made through the copy`,repair:e=>({command:``,instruction:`reconcile the value at ${locatorText(e)} back into ${rr} — ${q} offers the import`}),skillRepair:e=>`hand ${locatorText(e)} to ${q}, which imports the field into ${rr} with \`mcp reconcile\` once approved`},"mcp-diverged-golden":{detail:`only the golden set changed since the two last agreed — the harness copy is stale`,repair:e=>({command:``,instruction:`update ${locatorText(e)} from the golden entry — ${q} offers the correction`}),skillRepair:e=>`hand ${locatorText(e)} to ${q}, which updates it from the golden entry with \`mcp project\``},"mcp-diverged-both":{detail:`both sides changed since they last agreed — merging either way would discard the other`,repair:e=>({command:``,instruction:`reconcile ${locatorText(e)} against ${rr} by hand`}),skillRepair:e=>`reconcile ${locatorText(e)} against ${rr} by hand — never merge a three-way conflict automatically`},"mcp-diverged-unknown":{detail:`the two disagree and no baseline says which side moved — neither history nor a last-projected record covers this server`,repair:e=>({command:``,instruction:`compare ${locatorText(e)} against ${rr} by hand`}),skillRepair:e=>`compare ${locatorText(e)} against ${rr} by hand`},"mcp-literal-secret":{detail:`a credential-bearing field holds a literal rather than a reference to an environment variable`,repair:e=>({command:``,instruction:`move the value at ${locatorText(e)} into an environment variable and reference it`}),skillRepair:e=>`move the value at ${locatorText(e)} into an environment variable and reference it — read the value from the file, never from this report, and never repeat it back`},"mcp-committed-secret":{detail:`a credential-bearing field holds a literal in a git-tracked file — the credential is committed, and moving it does not un-commit it`,repair:e=>({command:``,instruction:`rotate the credential behind ${locatorText(e)}, then reference it from an environment variable`}),skillRepair:e=>`rotate the credential behind ${locatorText(e)} at its issuer, then reference it from an environment variable — it is in the repository's history, so moving it is not enough`}};repairsOf(ur);const dr={"nonstandard-instructions":{detail:`instruction content only one harness reads — AGENTS.md carries the same prose to all of them`,repair:({file:e})=>({command:``,instruction:`consolidate ${e} into AGENTS.md — ${K} offers the consolidation, and keeps the content reachable where this harness needs it`}),skillRepair:({file:e})=>`hand ${e} to ${K}, which consolidates it into AGENTS.md`},"nonstandard-rule":{detail:`a path-scoped rule only one harness reads — a skill reaches every harness where the scoping is incidental`,repair:({file:e})=>({command:``,instruction:`convert ${e} into a skill under .agents/skills where its guidance is not tied to the paths it names — ${K} offers the conversion; keep it where the path scoping is the point`}),skillRepair:({file:e})=>`hand ${e} to ${K} to convert into a skill, unless the path scoping is load-bearing`},"nonstandard-command":{detail:`a harness command file — a skill is the portable form, and this harness reads skills too`,repair:({file:e})=>({command:``,instruction:`move ${e} to .agents/skills/<name>/SKILL.md — ${K} offers the move`}),skillRepair:({file:e})=>`hand ${e} to ${K}, which moves it to .agents/skills`},"nonstandard-skill":{detail:`a skill under a harness directory rather than the canonical one, where only that harness finds it`,repair:({file:e})=>({command:``,instruction:`move ${e} to .agents/skills and project it back where the harness needs one — ${K} offers the move`}),skillRepair:({file:e})=>`hand ${e} to ${K}, which moves it to .agents/skills`},"nonstandard-subagent":{detail:`a subagent definition with no cross-harness form — nothing outside this harness can read it, and no canonical form exists yet`,repair:({file:e})=>({command:``,instruction:`leave ${e} where it is and record that it reaches one harness only — no portable form exists to convert it to`}),skillRepair:({file:e})=>`leave ${e} in place — no portable form exists yet, so this is work for a person rather than a skill`}};repairsOf(dr);const fr=`${K} offers it, or ${nr} where the repository already has an AGENTS.md`,pr={"worktrees-untracked":{detail:`.claude/worktrees/ is not git-ignored, so every agent worktree Claude Code creates there shows up as untracked in git status`,repair:({file:e})=>({command:``,instruction:`add \`.claude/worktrees/\` to ${e} — ${fr}`}),skillRepair:()=>`run ${K} or ${nr}, which offers the .gitignore line`},"worktrees-scanned":{detail:`this config does not exclude .claude/worktrees, so the tool walks into each agent worktree, a whole checkout with its own config, and Biome stops on the nested root configuration`,repair:({file:e})=>({command:``,instruction:`add \`"!**/.claude/worktrees"\` to \`files.includes\` in ${e} — ${fr}`}),skillRepair:()=>`run ${K} or ${nr}, which offers the exclusion`},"worktree-base-unset":{detail:`worktree.baseRef is unset, so agent worktrees branch from the default branch rather than the current HEAD — work on a feature branch starts without its commits`,repair:({file:e})=>({command:``,instruction:`decide whether agent worktrees should branch from HEAD, and if so set \`"worktree": { "baseRef": "head" }\` in ${e} — ${fr}`}),skillRepair:()=>`run ${K} or ${nr}, which explains the trade-off and offers the setting`}};repairsOf(pr);const mr={...ir,...ar,...cr,...lr,...ur,...dr,...pr};repairsOf(mr);function repairFor(e){return{problem:e,...mr[e]}}const hr=`.agents/skills`,gr=`AGENTS.local.md`;function frontmatterFault(e){let t=/^---\n([\s\S]*?)\n---/.exec(e);if(!t)return`unparseable`;let n=/^description:[ \t]*(.*)$/m.exec(t[1])?.[1]?.trim();if(!n)return`no-description`;if(!/^(['"]).*\1$/.test(n)&&/:\s/.test(n))return`unparseable`}function diagnoseConfiguration({root:e,git:t,cli:r}){let i=[],add=(e,t)=>{let{detail:n,repair:a}=repairFor(t);i.push({path:e,problem:t,detail:n,repair:a({file:e},r)})},o=selectHarnesses(e,[]);for(let t of o){let r=t.project.skillsDirectory;t.deprecated&&r&&n(C(e,r))&&add(r,`deprecated-harness`)}for(let r of o){let i=r.project.skillsDirectory;i&&n(C(e,i))&&t.isIgnored(i)&&add(i,`ignored-bridge`)}n(C(e,gr))&&add(gr,`unread-local-override`);for(let t of filesUnder(C(e,hr)).filter(e=>e.endsWith(`SKILL.md`)))frontmatterFault(a(C(e,hr,t),`utf8`))&&add(`${hr}/${t}`,`unloadable-skill`);return i}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const _r=[`transport`,`command`,`args`,`env`,`url`,`headers`,`description`,`enabled`,`timeout`,`source`],vr=new Set([`env`,`headers`]);function sameValue(e,t,n){if(vr.has(e)&&isRecord(t)&&isRecord(n)){let e=Object.keys(t);return e.length===Object.keys(n).length&&e.every(e=>t[e]===n[e])}return JSON.stringify(t)===JSON.stringify(n)}function divergingFields(e,t,n=new Set(_r)){return _r.filter(r=>{if(!n.has(r))return!1;let i=e[r];if(i===void 0)return!1;if(vr.has(r)&&isRecord(i)&&isRecord(t[r])){let e=t[r];return Object.keys(i).some(t=>i[t]!==e[t])}return!sameValue(r,i,t[r])})}function sameField(e,t,n){return sameValue(e,t?.[e],n?.[e])}function stringMap(e){if(!isRecord(e))return;let t=Object.entries(e).filter(([,e])=>typeof e==`string`);return t.length?Object.fromEntries(t):void 0}const yr=new Set([`stdio`,`http`,`sse`]);function transportOf(e){let t=e.type??e.transport;if(typeof t==`string`&&yr.has(t))return t;if(typeof e.url==`string`)return`http`;if(typeof e.command==`string`)return`stdio`}function serverFrom(e){let t=Array.isArray(e.args)&&e.args.every(e=>typeof e==`string`),n=transportOf(e),r=stringMap(e.env),i=stringMap(e.headers);return{...n?{transport:n}:{},...typeof e.command==`string`?{command:e.command}:{},...t?{args:e.args}:{},...r?{env:r}:{},...typeof e.url==`string`?{url:e.url}:{},...i?{headers:i}:{},...typeof e.description==`string`?{description:e.description}:{},...typeof e.enabled==`boolean`?{enabled:e.enabled}:{},...typeof e.timeout==`number`?{timeout:e.timeout}:{},...typeof e.source==`string`?{source:e.source}:{}}}const br=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/,xr=/\$\{[^}]*\}|\$[A-Za-z_]/;var Refusal=class extends Error{field;reason;constructor(e,t){super(t),this.field=e,this.reason=t}};function refuse(e,t){throw new Refusal(e,t)}function rendering(e){try{return{kind:`entry`,entry:e()}}catch(e){if(!(e instanceof Refusal))throw e;return{kind:`refused`,field:e.field,reason:e.reason}}}function assertRunnable(e){(e.transport===`stdio`?!e.command:!e.url)&&refuse(e.transport===`stdio`?`command`:`url`,`the golden set leaves it unset and the target requires it`)}function defined(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function mapValues(e,t){return e&&Object.fromEntries(Object.entries(e).map(([e,n])=>[e,t(n)]))}function noReferenceIn(e,t,n){for(let r of t){let t=e[r];(Array.isArray(t)?t:[t]).some(e=>typeof e==`string`&&xr.test(e))&&refuse(r,`${n} documents no reference expansion here`)}}const Sr={fields:new Set([`transport`,`command`,`args`,`env`,`url`,`headers`,`description`,`timeout`]),read:serverFrom,write:e=>rendering(()=>(assertRunnable(e),defined({type:e.transport,command:e.command,args:e.args,env:e.env,url:e.url,headers:e.headers,description:e.description,timeout:e.timeout})))};function toCursor(e,t){return e.replace(/\$\{([^}]*)\}|\$[A-Za-z_]/g,(e,n)=>((n===void 0||!br.test(e))&&refuse(t,`Cursor expands only a plain variable reference, with no default`),`\${env:${n}}`))}function fromCursor(e){return e.replace(/\$\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g,(e,t)=>`\${${t}}`)}function fromCursorEntry(e){let strings=e=>typeof e==`string`?fromCursor(e):e,map=e=>isRecord(e)?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,strings(t)])):e;return{...e,command:strings(e.command),args:Array.isArray(e.args)?e.args.map(strings):e.args,env:map(e.env),url:strings(e.url),headers:map(e.headers)}}const Cr={fields:new Set([`command`,`args`,`env`,`url`,`headers`]),read:e=>serverFrom(fromCursorEntry(e)),write:e=>rendering(()=>(assertRunnable(e),defined({type:e.transport===`stdio`?`stdio`:void 0,command:e.command&&toCursor(e.command,`command`),args:e.args?.map(e=>toCursor(e,`args`)),env:mapValues(e.env,e=>toCursor(e,`env`)),url:e.url&&toCursor(e.url,`url`),headers:mapValues(e.headers,e=>toCursor(e,`headers`))})))},wr=/^Bearer \$\{([A-Za-z_][A-Za-z0-9_]*)\}$/;function codexEnv(e){let t={},n=[];for(let[r,i]of Object.entries(e??{}))br.exec(i)?.[1]===r?n.push(r):xr.test(i)?refuse(`env`,`Codex passes a variable through only under its own name`):t[r]=i;return defined({env:Object.keys(t).length?t:void 0,env_vars:n.length?n:void 0})}function codexHeaders(e){let t={},n={},r;for(let[i,a]of Object.entries(e??{})){let e=br.exec(a)?.[1],o=wr.exec(a)?.[1];o&&i===`Authorization`?r=o:e?n[i]=e:xr.test(a)?refuse(`headers`,`Codex fills a header only from a whole variable reference, or Bearer and one`):t[i]=a}return defined({http_headers:Object.keys(t).length?t:void 0,env_http_headers:Object.keys(n).length?n:void 0,bearer_token_env_var:r})}function stringRecord(e){return isRecord(e)?Object.fromEntries(Object.entries(e).filter(([,e])=>typeof e==`string`)):{}}function fromCodex(e){let t=Array.isArray(e.env_vars)?e.env_vars.filter(e=>typeof e==`string`):[],n={...stringRecord(e.env),...Object.fromEntries(t.map(e=>[e,`\${${e}}`]))},r=e.bearer_token_env_var,i={...stringRecord(e.http_headers),...Object.fromEntries(Object.entries(stringRecord(e.env_http_headers)).map(([e,t])=>[e,`\${${t}}`])),...typeof r==`string`?{Authorization:`Bearer \${${r}}`}:{}},a=e.tool_timeout_sec;return{command:e.command,args:e.args,env:n,url:e.url,headers:i,enabled:e.enabled,timeout:typeof a==`number`?Math.round(a*1e3):void 0}}const Tr={fields:new Set([`transport`,`command`,`args`,`env`,`url`,`headers`,`enabled`,`timeout`]),defaults:{timeout:6e4},read:e=>serverFrom(fromCodex(e)),write:e=>rendering(()=>(e.transport===`sse`&&refuse(`transport`,`Codex supports no SSE transport`),assertRunnable(e),noReferenceIn(e,[`command`,`args`,`url`],`Codex`),defined({command:e.command,args:e.args,...codexEnv(e.env),url:e.url,...codexHeaders(e.headers),enabled:e.enabled,tool_timeout_sec:e.timeout===void 0?void 0:e.timeout/1e3})))};function fromGemini(e){let{httpUrl:t,url:n,...r}=e;return typeof t==`string`?{...r,type:`http`,url:t}:typeof n==`string`?{...r,type:`sse`,url:n}:r}const Er={"claude-code":Sr,cursor:Cr,codex:Tr,"gemini-cli":{fields:new Set([`transport`,`command`,`args`,`env`,`url`,`headers`,`timeout`]),defaults:{timeout:6e5},read:e=>serverFrom(fromGemini(e)),write:e=>rendering(()=>(assertRunnable(e),defined({command:e.command,args:e.args,env:e.env,url:e.transport===`sse`?e.url:void 0,httpUrl:e.transport===`http`?e.url:void 0,headers:e.headers,timeout:e.timeout})))}};function stripJsonComments(e){let t=``,n=0,r=!1,i=!1;for(;n<e.length;){let a=e[n];if(r){t+=a,i?i=!1:a===`\\`?i=!0:a===`"`&&(r=!1),n+=1;continue}if(a===`"`){r=!0,t+=a,n+=1;continue}if(a===`/`&&e[n+1]===`/`){for(;n<e.length&&e[n]!==`
|
|
183
183
|
`;)n+=1;continue}if(a===`/`&&e[n+1]===`*`){for(n+=2;n<e.length&&(e[n]!==`*`||e[n+1]!==`/`);)n+=1;n+=2;continue}t+=a,n+=1}return t}function parseJsonWithComments(e){try{return JSON.parse(stripJsonComments(e))}catch{return}}
|
|
184
184
|
/*!
|
|
185
185
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
@@ -267,7 +267,7 @@ function parseString(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s
|
|
|
267
267
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
268
268
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
269
269
|
*/
|
|
270
|
-
let
|
|
270
|
+
let Dr=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;var Or=class TomlDate extends Date{#e=!1;#t=!1;#n=null;constructor(e,t,n){let r=!0,i=!0,a=`Z`,o;if(typeof e==`string`){if(t)prep:{if(t<3){if(+e.slice(11,13)>23){e=``;break prep}t===2?(a=null,e+=`Z`):(o=e.charCodeAt(e.length-1))!==90&&o!==122&&(a=e.slice(e.length-6)),n&&(e=e.slice(0,10)+`T`+e.slice(11))}else t===4&&(e=+e.slice(0,2)>23?``:`0000-01-01T${e}Z`);r=t!==4,i=t!==3}else{let t=e.match(Dr);t?(t[1]||(r=!1,e=`0000-01-01T${e}`),i=!!t[2],i&&e[10]===` `&&(e=e.replace(` `,`T`)),t[2]&&+t[2]>23?e=``:(a=t[3]||null,!a&&i&&(e+=`Z`))):e=``}}super(e),isNaN(this.getTime())||(this.#e=r,this.#t=i,this.#n=a)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`||this.#n===`z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(e,t=`Z`){let n=new TomlDate(e);return n.#n=t,n}static wrapAsLocalDateTime(e){let t=new TomlDate(e);return t.#n=null,t}static wrapAsLocalDate(e){let t=new TomlDate(e);return t.#t=!1,t.#n=null,t}static wrapAsLocalTime(e){let t=new TomlDate(e);return t.#e=!1,t.#n=null,t}};
|
|
271
271
|
/*!
|
|
272
272
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
273
273
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -295,7 +295,7 @@ let wr=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[
|
|
|
295
295
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
296
296
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
297
297
|
*/
|
|
298
|
-
function isDigit$2(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}__name(isDigit$2,`isDigit`);function isEndOfValue(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function extractValue(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||J.x(`document contains excessively nested structures. aborting.`,e);let t=r===91?parseArray(e):parseInlineTable(e);return e.d++,t}return r===34||r===39?parseString(e):r===116?((e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)&&J.x(`invalid value`,e,n),e.p++,!0):r===102?((e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)&&J.x(`invalid value`,e,n),e.p++,!1):r===43||r===45?parseNumber(e,e.p,e.s.charCodeAt(++e.p),44-r,t):e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45?parseDate(e,r,t):e.s.charCodeAt(e.p+2)===58?parseTime(e,r,t):parseNumber(e,e.p,r,0,t)}function parseNumber(e,t,n,r,i){let a=n,o=0,s=!1;if(a===105)return(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)&&J.x(`invalid value`,e,t),e.p++,(r||1)/0;if(a===110)return(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)&&J.x(`invalid value`,e,t),e.p++,NaN;if(a===48){if(++e.p>=e.s.length||isEndOfValue(a=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(a===120)return parseIntegerBaseN(e,t,16,i);if(a===98)return parseIntegerBaseN(e,t,2,i);if(a===111)return parseIntegerBaseN(e,t,8,i)}a===46?o=2:a===101||a===69?o=4:J.x(`illegal leading zero`,e,t)}else isDigit$2(a)||J.x(`invalid value`,e,t);for(;++e.p<e.s.length&&(a=e.s.charCodeAt(e.p),!isEndOfValue(a,i));)o||=1,a===95?(o&1||J.x(`illegal underscore`,e),o+=11,s=!0):o===1&&a===46?o=2:(o===1||o===3)&&(a===101||a===69)?o=4:o===4&&(a===43||a===45)||(isDigit$2(a)?o>9?o-=11:o&1||o++:J.x(`illegal character in numeric literal`,e));if(!o){let t=(n-48)*(r||1);return e.bi===!0?BigInt(t):t}o&1||J.x(`unfinished numeric value`,e,t);let c=e.s.slice(t,e.p);return s&&(c=c.replaceAll(`_`,``)),o>1?parseFloat(c):parseInteger(e,c,10,t)}function parseIntegerBaseN(e,t,n,r){let i,a=1;for(;++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!isEndOfValue(i,r));)i===95?(a&1&&J.x(`illegal underscore`,e),a=3):isDigit$2(i,n)?a&1&&a--:J.x(`illegal character in numeric literal`,e);a&1&&J.x(`unfinished numeric value`,e);let o=e.s.slice(t+2,e.p);return a&&(o=o.replaceAll(`_`,``)),parseInteger(e,o,n,t)}function parseInteger(e,t,n,r){if(e.bi!==!0)int:{let i=parseInt(t,n);if(!Number.isSafeInteger(i)){if(e.bi)break int;J.x(`integer value cannot be represented losslessly`,e,r)}return i}return BigInt(n===10?t:(n===2?`0b`:n===8?`0o`:`0x`)+t)}function parseDate(e,t,n){let r=e.p++,i;if(!isDigit$2(t)||!isDigit$2(e.s.charCodeAt(e.p++))||!isDigit$2(e.s.charCodeAt(e.p++))||!isDigit$2(e.s.charCodeAt(e.p++)))return parseNumber(e,e.p=r,t,0,n);if(e.p+=5,isDigit$2(e.s.charCodeAt(e.p++))||J.x(`invalid date-time: date part is malformed`,e,r),e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(i=!0,!isDigit$2(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116)return readDate(e,e.s.slice(r,e.p),3,!1,r);if(e.s.charCodeAt(e.p+=3)!==58&&J.x(`invalid date-time: time part is malformed`,e,r),e.s.charCodeAt(e.p+=3)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;isDigit$2(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122)return readDate(e,e.s.slice(r,++e.p),1,i,r,`[+00:00]`);if(t===43||t===45)return readDate(e,e.s.slice(r,e.p+=6),1,i,r,!e.ld&&`[`+e.s.slice(e.p-6,e.p)+`]`)}return readDate(e,e.s.slice(r,e.p),2,i,r)}function parseTime(e,t,n){let r=e.p;if(!isDigit$2(t)||!isDigit$2(e.s.charCodeAt(++e.p)))return parseNumber(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;isDigit$2(e.s.charCodeAt(++e.p)););return readDate(e,e.s.slice(r,e.p),4,!1,r)}function readDate(e,t,n,r,i,a){if(e.ld){let a=new
|
|
298
|
+
function isDigit$2(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}__name(isDigit$2,`isDigit`);function isEndOfValue(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function extractValue(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||J.x(`document contains excessively nested structures. aborting.`,e);let t=r===91?parseArray(e):parseInlineTable(e);return e.d++,t}return r===34||r===39?parseString(e):r===116?((e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)&&J.x(`invalid value`,e,n),e.p++,!0):r===102?((e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)&&J.x(`invalid value`,e,n),e.p++,!1):r===43||r===45?parseNumber(e,e.p,e.s.charCodeAt(++e.p),44-r,t):e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45?parseDate(e,r,t):e.s.charCodeAt(e.p+2)===58?parseTime(e,r,t):parseNumber(e,e.p,r,0,t)}function parseNumber(e,t,n,r,i){let a=n,o=0,s=!1;if(a===105)return(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)&&J.x(`invalid value`,e,t),e.p++,(r||1)/0;if(a===110)return(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)&&J.x(`invalid value`,e,t),e.p++,NaN;if(a===48){if(++e.p>=e.s.length||isEndOfValue(a=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(a===120)return parseIntegerBaseN(e,t,16,i);if(a===98)return parseIntegerBaseN(e,t,2,i);if(a===111)return parseIntegerBaseN(e,t,8,i)}a===46?o=2:a===101||a===69?o=4:J.x(`illegal leading zero`,e,t)}else isDigit$2(a)||J.x(`invalid value`,e,t);for(;++e.p<e.s.length&&(a=e.s.charCodeAt(e.p),!isEndOfValue(a,i));)o||=1,a===95?(o&1||J.x(`illegal underscore`,e),o+=11,s=!0):o===1&&a===46?o=2:(o===1||o===3)&&(a===101||a===69)?o=4:o===4&&(a===43||a===45)||(isDigit$2(a)?o>9?o-=11:o&1||o++:J.x(`illegal character in numeric literal`,e));if(!o){let t=(n-48)*(r||1);return e.bi===!0?BigInt(t):t}o&1||J.x(`unfinished numeric value`,e,t);let c=e.s.slice(t,e.p);return s&&(c=c.replaceAll(`_`,``)),o>1?parseFloat(c):parseInteger(e,c,10,t)}function parseIntegerBaseN(e,t,n,r){let i,a=1;for(;++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!isEndOfValue(i,r));)i===95?(a&1&&J.x(`illegal underscore`,e),a=3):isDigit$2(i,n)?a&1&&a--:J.x(`illegal character in numeric literal`,e);a&1&&J.x(`unfinished numeric value`,e);let o=e.s.slice(t+2,e.p);return a&&(o=o.replaceAll(`_`,``)),parseInteger(e,o,n,t)}function parseInteger(e,t,n,r){if(e.bi!==!0)int:{let i=parseInt(t,n);if(!Number.isSafeInteger(i)){if(e.bi)break int;J.x(`integer value cannot be represented losslessly`,e,r)}return i}return BigInt(n===10?t:(n===2?`0b`:n===8?`0o`:`0x`)+t)}function parseDate(e,t,n){let r=e.p++,i;if(!isDigit$2(t)||!isDigit$2(e.s.charCodeAt(e.p++))||!isDigit$2(e.s.charCodeAt(e.p++))||!isDigit$2(e.s.charCodeAt(e.p++)))return parseNumber(e,e.p=r,t,0,n);if(e.p+=5,isDigit$2(e.s.charCodeAt(e.p++))||J.x(`invalid date-time: date part is malformed`,e,r),e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(i=!0,!isDigit$2(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116)return readDate(e,e.s.slice(r,e.p),3,!1,r);if(e.s.charCodeAt(e.p+=3)!==58&&J.x(`invalid date-time: time part is malformed`,e,r),e.s.charCodeAt(e.p+=3)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;isDigit$2(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122)return readDate(e,e.s.slice(r,++e.p),1,i,r,`[+00:00]`);if(t===43||t===45)return readDate(e,e.s.slice(r,e.p+=6),1,i,r,!e.ld&&`[`+e.s.slice(e.p-6,e.p)+`]`)}return readDate(e,e.s.slice(r,e.p),2,i,r)}function parseTime(e,t,n){let r=e.p;if(!isDigit$2(t)||!isDigit$2(e.s.charCodeAt(++e.p)))return parseNumber(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;isDigit$2(e.s.charCodeAt(++e.p)););return readDate(e,e.s.slice(r,e.p),4,!1,r)}function readDate(e,t,n,r,i,a){if(e.ld){let a=new Or(t,n,r);return a.isValid()||J.x(`invalid date`,e,i),a}try{switch(a&&(t+=a),n){case 1:return Temporal.ZonedDateTime.from(t);case 2:return Temporal.PlainDateTime.from(t);case 3:return Temporal.PlainDate.from(t);case 4:return Temporal.PlainTime.from(t)}}catch(t){J.x(t instanceof Error?t.message:``+t,e,i)}}
|
|
299
299
|
/*!
|
|
300
300
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
301
301
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -407,7 +407,7 @@ function peekTable(e,t,n,r,i){let a=n,o=r,s,c=!1,l;for(let n=0;n<t.length;n++){i
|
|
|
407
407
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
408
408
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
409
409
|
*/
|
|
410
|
-
let
|
|
410
|
+
let kr=/^[a-z0-9-_]+$/i,Ar=!!``.isWellFormed;function extendedTypeOf(e){let t=typeof e;if(t===`object`){if(Array.isArray(e))return`array`;if(typeof e.getUTCDate==`function`&&e instanceof Date)return`date`;if(globalThis.Temporal){if(e.until){if(e instanceof Temporal.ZonedDateTime)return`temporal/tz+uc`;if(e instanceof Temporal.PlainDateTime||e instanceof Temporal.PlainDate)return`temporal/uc`;if(e instanceof Temporal.PlainTime||e instanceof Temporal.Instant)return`temporal`;if(e instanceof Temporal.PlainYearMonth)return`temporal/x`}else if(e.toPlainDate&&e instanceof Temporal.PlainMonthDay||e.negated&&e instanceof Temporal.Duration)return`temporal/x`}}return t}function isArrayOfTables(e){for(let t=0;t<e.length;t++)if(extendedTypeOf(e[t])!==`object`)return!1;return e.length!=0}function formatWellFormedStringUnchecked(e){return JSON.stringify(e).replaceAll(``,`\\u007f`)}function formatString(e){return formatWellFormedStringUnchecked(Ar?e.toWellFormed():e)}function formatKey(e){if(kr.test(e))return e;if(Ar&&!e.isWellFormed())throw RangeError(`key contains illegal lone surrogates`);return formatWellFormedStringUnchecked(e)}function stringifyValue(e,t,n,r,i){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);switch(t){case`number`:if(isNaN(e))return`nan`;if(e===1/0)return`inf`;if(e===-1/0)return`-inf`;if(Number.isInteger(e)&&(r||!Number.isSafeInteger(e)))return e.toFixed(1);case`bigint`:case`boolean`:case`temporal`:return e.toString();case`string`:return formatString(e);case`date`:if(isNaN(e.getTime()))throw TypeError(`cannot serialize invalid date`);return e.toISOString();case`object`:return stringifyInlineTable(e,n,r,i);case`array`:return stringifyArray(e,n,r,i);case`temporal/tz+uc`:if(i){let t=e.timeZoneId,n=t.charCodeAt(0);if(n!==43&&n!==45&&(n!==85&&n!==71&&n!==90&&n!==69||t!==`UTC`&&t!==`UCT`&&t!==`Universal`&&t!==`Zulu`&&!t.startsWith(`GMT`)&&t!==`Greenwich`&&!t.startsWith(`Etc/`)))throw TypeError(`Temporal objects with an IANA timezone are not allowed in Temporal strict mode`)}case`temporal/uc`:if(i&&e.calendarId!==`iso8601`)throw TypeError(`Temporal objects with a non-default calendar are not allowed in Temporal strict mode`);return e.toString({calendarName:`never`,timeZoneName:`never`});case`temporal/x`:throw TypeError(`Unsupported `+e[Symbol.toStringTag])}}function stringifyInlineTable(e,t,n,r){let i=Object.keys(e);if(i.length===0)return`{}`;let a=`{ `;for(let o=0;o<i.length;o++){let s=i[o];o&&(a+=`, `),a+=formatKey(s)+` = `+stringifyValue(e[s],extendedTypeOf(e[s]),t-1,n,r)}return a+` }`}function stringifyArray(e,t,n,r){if(e.length===0)return`[]`;let i=`[ `;for(let a=0;a<e.length;a++){if(a&&(i+=`, `),e[a]===null||e[a]===void 0)throw TypeError(`arrays cannot contain null or undefined values`);i+=stringifyValue(e[a],extendedTypeOf(e[a]),t-1,n,r)}return i+` ]`}function stringifyArrayTable(e,t,n,r,i){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let a=``;for(let o=0;o<e.length;o++)a+=`${a&&`
|
|
411
411
|
`}[[${t}]]\n`,a+=stringifyTable(0,e[o],t,n,r,i);return a}function stringifyTable(e,t,n,r,i,a){if(r===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let o=``,s=``,c=Object.keys(t);for(let e=0;e<c.length;e++){let l=c[e];if(t[l]!==null&&t[l]!==void 0){let e=extendedTypeOf(t[l]);if(e===`symbol`||e===`function`)throw TypeError(`cannot serialize values of type '${e}'`);let c=formatKey(l);if(e===`array`&&isArrayOfTables(t[l]))s+=(s&&`
|
|
412
412
|
`)+stringifyArrayTable(t[l],n?`${n}.${c}`:c,r-1,i,a);else if(e===`object`){let e=n?`${n}.${c}`:c;s+=(s&&`
|
|
413
413
|
`)+stringifyTable(e,t[l],e,r-1,i,a)}else o+=c,o+=` = `,o+=stringifyValue(t[l],e,r,i,a),o+=`
|
|
@@ -441,34 +441,34 @@ let Er=/^[a-z0-9-_]+$/i,Dr=!!``.isWellFormed;function extendedTypeOf(e){let t=ty
|
|
|
441
441
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
442
442
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
443
443
|
*/
|
|
444
|
-
const Y=`.agents/buddy-agent-harness/mcp.toml`;function mcpTargets(e){let t=new Set;return selectHarnesses(e,[]).map(e=>e.project.mcpConfig).filter(e=>e!==void 0).filter(e=>!t.has(e.path)&&t.add(e.path))}function serversUnder(e,t,n=serverFrom){let r=isRecord(e)?e[t]:void 0;return isRecord(r)?new Map(Object.entries(r).filter(([,e])=>isRecord(e)).map(([e,t])=>[e,n(t)])):new Map}function positionOf(e){if(!isRecord(e))return;let{line:t,column:n}=e;return typeof t==`number`&&typeof n==`number`?{line:t,column:n}:void 0}function parseGoldenSet(e){if(e===void 0)return{kind:`absent`};try{return{kind:`servers`,servers:serversUnder(parse(e),`servers`)}}catch(e){return{kind:`unreadable`,position:positionOf(e)}}}function parseTarget(e,t){if(t===void 0)return{kind:`absent`};if(e.format===`toml`)try{return{kind:`servers`,servers:serversUnder(parse(t),e.key,
|
|
444
|
+
const Y=`.agents/buddy-agent-harness/mcp.toml`;function mcpTargets(e){let t=new Set;return selectHarnesses(e,[]).map(e=>e.project.mcpConfig).filter(e=>e!==void 0).filter(e=>!t.has(e.path)&&t.add(e.path))}function serversUnder(e,t,n=serverFrom){let r=isRecord(e)?e[t]:void 0;return isRecord(r)?new Map(Object.entries(r).filter(([,e])=>isRecord(e)).map(([e,t])=>[e,n(t)])):new Map}function positionOf(e){if(!isRecord(e))return;let{line:t,column:n}=e;return typeof t==`number`&&typeof n==`number`?{line:t,column:n}:void 0}function parseGoldenSet(e){if(e===void 0)return{kind:`absent`};try{return{kind:`servers`,servers:serversUnder(parse(e),`servers`)}}catch(e){return{kind:`unreadable`,position:positionOf(e)}}}function parseTarget(e,t){if(t===void 0)return{kind:`absent`};if(e.format===`toml`)try{return{kind:`servers`,servers:serversUnder(parse(t),e.key,Er[e.dialect].read)}}catch{return{kind:`unreadable`}}let n=parseJsonWithComments(t);return n===void 0?{kind:`unreadable`}:{kind:`servers`,servers:serversUnder(n,e.key,Er[e.dialect].read)}}const jr=`.agents/buddy-agent-harness/mcp.projected.json`;function parseProjectionRecord(e){let t=e===void 0?void 0:parseJsonWithComments(e),n=isRecord(t)?t.targets:void 0;return isRecord(n)?new Map(Object.entries(n).filter(([,e])=>isRecord(e)).map(([e,t])=>[e,new Map(Object.entries(t).filter(([,e])=>isRecord(e)).map(([e,t])=>[e,t]))])):new Map}function formatProjectionRecord(e){let t=Object.fromEntries([...e].map(([e,t])=>[e,Object.fromEntries(t)]));return`${JSON.stringify({targets:t},null,2)}\n`}var McpBaseline=class{options;constructor(e){this.options=e}parsed=new Map;walked=new Map;directionOf(e,t,n,r,i){let a=this.baseFor(e,t,n);if(a===void 0)return`unknown`;let o=!sameField(n,r,a),s=!sameField(n,i,a);return o&&s?`both`:s?`target`:`golden`}baseFor(e,t,n){return this.options.record.get(e.path)?.get(t)||this.lastAgreed(e,t,n)}lastAgreed(e,t,n){for(let r of this.commitsTouching(e)){let i=this.parseAt(r,Y,parseGoldenSet),a=this.parseAt(r,e.path,t=>parseTarget(e,t));if(i.kind!==`servers`||a.kind!==`servers`)continue;let o=i.servers.get(t),s=a.servers.get(t);if(o&&s&&sameField(n,o,s))return o}}commitsTouching(e){let t=this.walked.get(e.path);if(t)return t;let n=this.options.git.commitsTouching([Y,e.path]);return this.walked.set(e.path,n),n}parseAt(e,t,n){let r=`${e}\u0000${t}`,i=this.parsed.get(r);if(i)return i;let a=n(this.options.git.contentAt(e,t));return this.parsed.set(r,a),a}};const Mr=/token|secret|password|passwd|credential/i,Nr=new Set([`key`,`apikey`,`auth`,`authorization`,`bearer`]);function segmentsOf(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}const Pr=/\$\{[^}]+\}|\$[A-Za-z_][A-Za-z0-9_]*/;function holdsLiteral(e){return!Pr.test(e)}function credentialKey(e){return Mr.test(e)||segmentsOf(e).some(e=>Nr.has(e))}function urlHoldsCredential(e){let t;try{t=new URL(e)}catch{return!1}if(t.password)return!0;for(let[e,n]of t.searchParams)if(credentialKey(e)&&holdsLiteral(n))return!0;return!1}function literalsIn$1(e,t){return Object.entries(t??{}).filter(([e,t])=>credentialKey(e)&&holdsLiteral(t)).map(([t])=>`${e}.${t}`)}__name(literalsIn$1,`literalsIn`);function credentialFields(e){return[...literalsIn$1(`env`,e.env),...literalsIn$1(`headers`,e.headers),...e.url&&urlHoldsCredential(e.url)?[`url`]:[]]}function nonSecretArgs(e){return(e??[]).filter(e=>{let t=e.indexOf(`=`);return t===-1||!(credentialKey(e.slice(0,t))&&holdsLiteral(e.slice(t+1)))})}function read$2(e,t){let r=C(e,t);return n(r)?a(r,`utf8`):void 0}__name(read$2,`read`);const Fr={target:`mcp-diverged-target`,golden:`mcp-diverged-golden`,both:`mcp-diverged-both`,unknown:`mcp-diverged-unknown`};function diagnoseMcp({root:e,git:t,cli:n}){let r=[],add=(e,t)=>{let{detail:i,repair:a}=repairFor(t);r.push({path:locatorText(e),problem:t,detail:i,repair:a(e,n)})},reportSecrets=(e,n)=>{let r=t.trackingOf(e)!==`untracked`;for(let[t,i]of n)for(let n of credentialFields(i))add({file:e,server:t,field:n},r?`mcp-committed-secret`:`mcp-literal-secret`)},i=new Map,a=[];for(let t of mcpTargets(e)){let n=parseTarget(t,read$2(e,t.path));if(n.kind===`unreadable`){add({file:t.path},`mcp-target-unreadable`);continue}n.kind!==`absent`&&(reportSecrets(t.path,n.servers),i.set(t.path,n.servers),a.push(t))}let o=parseGoldenSet(read$2(e,Y));if(o.kind===`unreadable`)return add({file:Y,position:o.position},`mcp-golden-unreadable`),r;if(o.kind===`absent`)return r;reportSecrets(Y,o.servers);let s=new McpBaseline({git:t,record:parseProjectionRecord(read$2(e,jr))});for(let e of a){let t=i.get(e.path);for(let[n,r]of o.servers){let i=t.get(n);if(!i){add({file:e.path,server:n},`mcp-unprojected`);continue}for(let t of divergingFields(r,i,Er[e.dialect].fields))add({file:e.path,server:n,field:t},Fr[s.directionOf(e,n,t,r,i)])}for(let n of t.keys())o.servers.has(n)||add({file:e.path,server:n},`mcp-undeclared`)}return r}const Ir={instructions:`nonstandard-instructions`,rule:`nonstandard-rule`,command:`nonstandard-command`,skill:`nonstandard-skill`,subagent:`nonstandard-subagent`};function scopedByGlobs(e){let t=/^---\n([\s\S]*?)\n---/.exec(e);if(!t)return!1;let n=/^globs:[ \t]*(.*)$/m.exec(t[1])?.[1]?.trim();return n!==void 0&&n.length>0&&n!==`[]`}function skillFiles(e){return filesUnder(e).filter(e=>e.endsWith(`SKILL.md`))}function authoredHere(e){try{return!r(e).isSymbolicLink()}catch{return!1}}function artifactFiles(e,t){let n=C(e,t.path);return authoredHere(n)?t.shape===`file`?[t.path]:(t.kind===`skill`?skillFiles(n):filesUnder(n)).map(e=>w.join(t.path,e)):[]}function diagnoseNonstandard({root:e,cli:t}){let n=[];for(let r of Gn)for(let i of r.project.nonstandard??[])for(let r of artifactFiles(e,i)){let o=i.kind===`rule`&&r.endsWith(`.mdc`)&&!scopedByGlobs(a(C(e,r),`utf8`))?`instructions`:i.kind,s=Ir[o],{detail:c,repair:l}=repairFor(s);n.push({path:r,problem:s,detail:c,repair:l({file:r},t)})}return n.sort((e,t)=>e.path.localeCompare(t.path))}const Lr=[`biome.json`,`biome.jsonc`],Rr=`.claude/settings.json`;function readJson(e){try{return JSON.parse(a(e,`utf8`))}catch{return}}function diagnoseWorktrees({root:e,git:t,cli:r}){if(!n(C(e,`.claude`)))return[];let i=[],add=(e,t)=>{let{detail:n,repair:a}=repairFor(t);i.push({path:e,problem:t,detail:n,repair:a({file:e},r)})};t.isRepository()&&!t.isIgnored(`.claude/worktrees/`)&&add(`.gitignore`,`worktrees-untracked`);for(let t of Lr){let r=C(e,t);n(r)&&!a(r,`utf8`).includes(`.claude/worktrees`)&&add(t,`worktrees-scanned`)}let o=readJson(C(e,Rr)),s=isRecord(o)?o.worktree:void 0;return(!isRecord(s)||s.baseRef===void 0)&&add(Rr,`worktree-base-unset`),i}function collapseHome(e,t){return e&&t.startsWith(e+D)?`~${t.slice(e.length)}`:t}N.string().optional(),N.boolean().optional(),N.string().optional(),N.string(),N.string().optional();const X=`cyber-agentkit reference`,Z={description:"The repository root: its `.agents/references/` is the repo tier, and its `package.json` names the dependency plugins. Defaults to the nearest folder at or above the current directory holding `.git`, else the current directory.",type:N.string().optional()},Q={description:`Add the trace: every layer checked, with its outcome, and how the result was built.`,type:N.boolean().optional()},zr={description:"The calling skill's folder: its `references/<name>.default.md` joins as the `default` tier.",type:N.string().optional()};function layerSource(e){return(t,n)=>referenceLayers$1({root:t.root,cwd:process.cwd(),home:n,platform:process.platform,env:process.env,plugin:e,defaultSkill:t.default})}function compact(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0&&e!==``&&!(Array.isArray(e)&&!e.length)))}function asCliError(e,t){throw isCliError(e)?e:e instanceof ReferenceFailure?new M(e.message,{code:e.code,exitCode:e.usage?j.usage:j.error,details:e.details,help:e.help}):new M(e instanceof Error?e.message:t,{cause:e})}function writeWarnings(e){for(let{code:t,message:n}of e)process.stderr.write(`warning: ${t}: ${n}\n`)}function displayTrace(e,t){let show=e=>collapseHome(t,e);return{...e,contributions:e.contributions.map(e=>({...e,path:show(e.path)})),layers:e.layers.map(e=>({...e,path:show(e.path)})),projectSections:e.projectSections.map(e=>({...e,path:show(e.path)}))}}function recordLines(e,t){let n=(e.sources??[]).map(e=>`${t}source ${e.default===void 0?`plugin ${e.plugin}`:`default ${e.default}${e.plugin?` (plugin ${e.plugin})`:``}`}: recorded ${e.recorded??`no version`}, installed ${e.status===`missing`?`not installed`:e.installed??`no version`} (${e.status})`);return e.request!==void 0&&n.push(`${t}request:`,...e.request.replace(/\n$/,``).split(`
|
|
445
445
|
`).map(e=>`${t} ${e}`)),n}function traceText(e,t){let n=displayTrace(e.trace,t),r=[`${e.name}: ${e.status}; stack: ${n.stack.join(` → `)||`none`}; built by ${n.builtBy}; harnesses: ${n.harnesses.join(`, `)||`none detected`}`];if(e.message&&r.push(` ${e.message}`),n.sections.length){r.push(`sections:`);for(let e of n.sections){let t=e.removedBy?`removed by ${e.removedBy}`:e.contributions.map(({contribution:e,operation:t})=>`${e} (${t})`).join(`, `)||`no text`;r.push(` ${e.path}: ${t}`)}}r.push(`layers:`);for(let e of n.layers){let t=e.plugin?` ${e.plugin}`:e.skill?` ${e.skill}`:``,n=e.operation?`; ${e.operation} from ${e.operationFrom}`:``,i=e.extendsOutcome?`; extends ${e.extendsOutcome}`:``,a=e.selection?`; selection`:``,o=e.frontmatter&&Object.keys(e.frontmatter).length?` ${JSON.stringify(e.frontmatter)}`:``;r.push(` ${e.tier}${t} ${e.path}: ${e.outcome}${n}${i}${a}${o}`),r.push(...recordLines(e,` `))}if(n.projectSections.length){r.push(`project sections:`);for(let e of n.projectSections){let t=e.frontmatter&&Object.keys(e.frontmatter).length?` ${JSON.stringify(e.frontmatter)}`:``,n=e.plugin===void 0?``:` (plugin ${e.plugin}${e.version?`@${e.version}`:``})`;r.push(` ${e.folder}${n} ${e.path}: ${e.outcome}${t}`),r.push(...recordLines(e,` `));for(let t of e.sections??[]){let e=t.contributions.map(({contribution:e,operation:t})=>`${e} (${t})`).join(`, `);r.push(` ${t.path}: ${e||`no text`}`)}}}return`${r.join(`
|
|
446
446
|
`)}\n`}function escapeText(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`)}function escapeAttribute(e){return escapeText(e).replace(/"/g,`"`)}function notFoundTag(e){let t=e.options?.length?`; options: ${e.options.join(`, `)}`:``;return`<reference name="${escapeAttribute(e.name)}" status="${e.status}" code="${e.code}">${escapeText(`${e.message??e.status}${t}`)}</reference>`}function deliveredText(e){let t=e.content??``;return e.projectSections.length?`${[...t.trim()?[t.trimEnd()]:[],...e.projectSections.map(({folder:e,plugin:t,content:n})=>`<project folder="${escapeAttribute(e)}"${t===void 0?``:` plugin="${escapeAttribute(t)}"`}>\n${n}</project>`)].join(`
|
|
447
447
|
|
|
448
|
-
`)}\n`:t}function referenceTag(e,t){return`<reference name="${escapeAttribute(e)}">\n${t}</reference>`}const
|
|
448
|
+
`)}\n`:t}function referenceTag(e,t){return`<reference name="${escapeAttribute(e)}">\n${t}</reference>`}const Br={description:"Tier to write: repo (default), `.agents/references/` at the root, or user, `~/.agents/references/`.",type:N.string().optional()},Vr={description:"A folder strictly below the root, which must exist and not be ignored by git: acts on its project section, `<folder>/.agents/references/<name>.md`.",type:N.string().optional()};function givenRoot(e){return e===void 0?findRoot(process.cwd()):E(e)}const Hr={description:"A plugin's source folder in this repository: acts on its `references/<name>.md`.",type:N.string().optional()},Ur={description:"A skill's source folder in this repository: acts on its `references/<name>.default.md`.",type:N.string().optional()};function checkCommand(e,t=X){return command({name:`check`,description:"Check references, each composed as `load` composes it: an interface document against its shape, an implementation against its interface, and every document for the defects composing it raises. With no names, checks every name found. Every warning `load` raises is reported. A failure is an entry in `failed`, not an error; a warning never fails a check.",arguments:[{name:`names`,description:"Reference names, without the `.md` extension; `<plugin>/<name>` builds that plugin’s own stack.",type:N.array(N.string()).optional()}],options:{root:Z,trace:{...Q,description:`Add every entry checked, with its kind and unsupported sections.`}},examples:[{command:`${t} check`,description:`Check every reference against its interface`}],async run(t){try{let n=_(),r=checkReferences(await e(t,n),{names:t.names??[],display:e=>collapseHome(n,e)}),i=r.filter(e=>e.failures.length),strip=e=>e.map(({check:e,message:t})=>({check:e,message:t}));return result(compact({failed:i.map(({name:e,loadedBy:t,failures:n,warnings:r})=>compact({name:e,loadedBy:t,failures:strip(n),warnings:r})),warned:r.filter(e=>!e.failures.length&&e.warnings.length).map(({name:e,loadedBy:t,warnings:n})=>compact({name:e,loadedBy:t,warnings:n})),passed:r.length-i.length,references:t.trace?r.map(({name:e,loadedBy:t,kind:n,status:r,failures:i,unsupported:a,warnings:o})=>compact({name:e,loadedBy:t,kind:n,status:r,failures:strip(i),unsupported:a,warnings:o})):void 0}))}catch(e){return asCliError(e,`Reference check failed.`)}}})}function createCommand(e,t=X){return command({name:`create`,description:`Start a contribution in the repo or user tier, a folder's project section, or a plugin's or a skill's source folder, from a template or an interface. Never overwrites a file with a body; writes a file a contribution above hides, with a warning.`,arguments:[{name:`name`,description:"Reference name, without the `.md` extension.",type:N.string()}],options:{root:Z,scope:Br,in:Vr,plugin:Hr,default:Ur,merge:{description:`How it applies over what is below: replace, patch (default), combine, or remove. remove writes no body.`,type:N.string().optional()},template:{description:"File whose text is written as it is, frontmatter included. Defaults to a built-in template of top-level `##` sections.",type:N.string().optional()},implements:{description:"Interface id to implement: the interface's sections become `##` headings, each stubbed `**Unsupported.**` with what it holds, and `merge: replace`; with --in, a project section with neither. Not with --template.",type:N.string().optional()},"dry-run":{description:`Print the target path and the exact content, and write nothing.`,type:N.boolean().optional()},trace:{...Q,description:`After the write, add the trace, in which the new file applies.`}},examples:[{command:`${t} create my-topic`,description:`Start a new reference named my-topic`}],async run(t){let n=this.format;try{let r=_(),display=e=>collapseHome(r,e),i={root:givenRoot(t.root),home:r,name:t.name,scope:t.scope,in:t.in,plugin:t.plugin,default:t.default,merge:t.merge,template:t.template,implements:t.implements,dryRun:t[`dry-run`]};validateWrite({command:`create`,...i});let a=await e({root:t.root,default:t.default},r),o=createContribution(a,{...i,root:a.root??i.root},{display}),s=compact({path:display(o.path),folder:o.folder,hint:o.dryRun?`Nothing was written. Run again without --dry-run to write it.`:`Run \`load ${o.name}\` for the composed document.`,content:o.dryRun?o.content:void 0,hints:o.hints,warnings:o.warnings,trace:t.trace&&o.after?displayTrace(o.after.trace,r):void 0});if(n!==`text`)return result(s);writeWarnings(o.warnings);for(let e of o.hints)process.stderr.write(`hint: ${e}\n`);return t.trace&&o.after&&process.stderr.write(traceText(o.after,r)),document(o.dryRun?`${s.path}\n\n${o.content}`:`${s.path}\n\n${s.hint}\n`)}catch(e){return asCliError(e,`Reference creation failed.`)}}})}function baseReport(e){let t=e.base,n=t?.resolved;return compact({status:n?.status??`missing`,stack:n?.trace.stack,content:t?.content??``,projectSections:t?.projectSections.map(({folder:e,content:t})=>({folder:e,content:t}))})}function baseText(e){let t=e.base;return t?!t.content&&!t.projectSections.length&&t.resolved.status!==`found`?`${notFoundTag(t.resolved)}\n`:deliveredText({...t.resolved,content:t.content,projectSections:t.projectSections}):``}function report(e,t,n){let display=e=>collapseHome(n,e),r=e.after;return compact({path:display(e.path),folder:e.folder,metadataFile:e.metadataFile===void 0?void 0:display(e.metadataFile),code:e.code,message:e.message,extends:e.extends,deleted:e.deleted,status:r?.status,stack:r?.trace.stack,answer:r?describeAnswer(r,display):void 0,hint:e.dryRun?`Nothing was written. Run again without --dry-run to write it.`:e.code?void 0:`Run \`load ${e.name}\` for the composed document.`,content:e.dryRun?e.content:void 0,metadataContent:e.dryRun?e.metadataContent:void 0,hints:e.hints,warnings:e.warnings,trace:t.trace&&r&&!e.code?displayTrace(r.trace,n):void 0})}function text(e,t){if(e.code)return`${t.path}\n\n${e.code}: ${e.message}\n`;if(e.dryRun){let n=e.deleted?`would delete the file, left with nothing in it.
|
|
449
449
|
`:e.content??``,r=e.metadataContent===void 0?``:`\n${t.metadataFile}\n\n${e.metadataContent}`;return`${t.path}\n\n${n}${r}`}if(e.action===`cleared`){let n=e.deleted?`selection removed; the file was left empty and deleted`:`selection removed`;return`${t.path}\n\n${n}. ${t.answer}\n`}if(e.action===`selection`)return`${t.path}\n\nextends: ${JSON.stringify(e.extends)}. ${t.answer}\n`;let n=t.metadataFile?` Its record is in ${t.metadataFile}.`:``;return`${t.path}\n\n${t.hint}${n}\n`}function familyReport(e,t,n){return compact({family:e.family,interfaces:e.interfaces.map(({interface:e,outcome:r,reason:i,result:a})=>compact({interface:e,outcome:r,reason:i,...a?report(a,t,n):{}})),hint:e.dryRun?`Nothing was written. Run again without --dry-run to write it.`:"Run `load <interface>` for each composed document."})}function familyText(e,t){return`${e.interfaces.map(({interface:e,outcome:n,reason:r,result:i},a)=>{if(!i)return`${e}: ${n}. ${r}\n`;let o=t.interfaces[a];return`${e}: ${n}.\n${text(i,o)}`}).join(`
|
|
450
|
-
`)}`}function customizeCommand(e,t=X){return command({name:`customize`,description:"Customize a name for the repo or user tier, or a folder's project section, running no model: pick what it builds on (`extends`), write a body generated from a request with its record, or print what the generator reads (--base). Writes a file a contribution above hides, with a warning.",arguments:[{name:`name`,description:"Reference name, without the `.md` extension; or a family, `<prefix>.*`, to pick for every interface under the prefix at once (takes --extends or --extends-file, no `sections`).",type:N.string()},{name:`steps`,description:"More steps for --extends, so `--extends a b` lists both, bottom first.",type:N.array(N.string()).optional()}],options:{root:Z,scope:Fr,in:{...Ir,description:`${Ir.description} Takes no --extends or --merge.`},default:{description:"The calling skill's folder, read only: its `references/<name>.default.md` joins the stack as the `default` tier.",type:N.string().optional()},plugin:{description:"Not accepted: customize never writes a plugin's file; an author uses `create --plugin`.",type:N.string().optional()},extends:{description:"The picks, bottom first: each a plugin holding the name, `<plugin>:<merge>` (such as `house-style:combine`), or `default`; `none` removes them. A file with no body is a selection.",type:N.array(N.string()).optional()},"extends-file":{description:"A YAML file holding the whole `extends` list, with every step key (`merge`, `extends`, `sections`).",type:N.string().optional()},request:{description:"A file holding the customizer's request, in their own words; recorded as `request`. Needs --body.",type:N.string().optional()},body:{description:`A file holding the body the generator wrote; written as given, with the picks, sources, and request recorded. Needs --request.`,type:N.string().optional()},merge:{description:`How the body applies over what is below: patch (default), combine, or replace for a whole document.`,type:N.string().optional()},implements:{description:"Interface id the body implements: a whole document recording `implements` and `merge: replace`; with --in, a project section from the interface's stub.",type:N.string().optional()},base:{description:`Print what the generator reads for the target, and write nothing: the name resolved with the picks, leaving out the target file, managed text, the tier above, and personal text; with --implements, the interface's stub first.`,type:N.boolean().optional()},"dry-run":{description:`Print the target path and the exact content, and write nothing.`,type:N.boolean().optional()},trace:{...Q,description:`After the write, add the trace, in which the written file applies.`}},examples:[{command:`${t} customize my-topic`,description:`Customize a reference for this project`},{command:`${t} customize my-skill.aspects.* --extends house-style`,description:`Pick one plugin for every interface under a prefix`}],async run(t){let n=this.format;try{let r=_(),display=e=>collapseHome(r,e),i=t.extends===void 0?void 0:[...t.extends,...t.steps??[]],a={root:givenRoot(t.root),home:r,name:t.name,scope:t.scope,in:t.in,plugin:t.plugin,default:t.default,extends:i,extendsFile:t[`extends-file`],request:t.request,body:t.body,merge:t.merge,implements:t.implements,base:t.base,dryRun:t[`dry-run`]},o=isFamilyName(t.name)||t.name.includes(`*`)?parseFamily(t.name):void 0;if(validateWrite({command:`customize`,...a,name:o===void 0||o.invalid!==void 0?t.name:o.prefix}),t.steps?.length&&t.extends===void 0)throw new ReferenceFailure(`options-missing`,`${t.steps.join(` `)} follow no --extends; pass --extends before the steps.`);let s=await e({root:t.root,default:t.default},r);if(o!==void 0){let e=customizeContribution(s,{...a,root:s.root??a.root},{display});if(!(`family`in e))throw Error(`${t.name} was customized as a single name, not a family.`);let i=familyReport(e,t,r);if(n!==`text`)return result(i);for(let{result:t}of e.interfaces)writeWarnings(t?.warnings??[]);return document(familyText(e,i))}let c=customizeContribution(s,{...a,root:s.root??a.root},{display});if(`family`in c)throw Error(`${t.name} was customized as a family, not a single name.`);if(c.action===`base`)return n===`text`?document(baseText(c)):result(baseReport(c));let l=report(c,t,r);if(n!==`text`)return result(l);writeWarnings(c.warnings);for(let e of c.hints)process.stderr.write(`hint: ${e}\n`);return t.trace&&c.after&&!c.code&&process.stderr.write(traceText(c.after,r)),document(text(c,l))}catch(e){return asCliError(e,`Reference customization failed.`)}}})}function deleteReport(e,t){let n=e.selection?`the selection extends: [${e.selection.join(`, `)}] went with it; run \`reference customize ${e.name} --extends ${e.selection.join(` `)}\` to restore it`:void 0;return compact({path:collapseHome(t,e.path),folder:e.folder,metadataFile:e.metadataFile===void 0?void 0:collapseHome(t,e.metadataFile),code:e.code,message:e.message,dryRun:e.dryRun||void 0,status:e.after.status,stack:e.after.trace.stack,answer:describeAnswer(e.after,e=>collapseHome(t,e)),selection:n,options:e.after.options})}function deleteCommand(e,t=X){return command({name:`delete`,description:`Delete a repo or user contribution, a folder's project section, or one in a plugin's or a skill's source folder, with a non-Markdown file's metadata file, and report what answers the name afterwards. Never deletes an installed or managed one.`,arguments:[{name:`name`,description:"Reference name, without the `.md` extension.",type:N.string()}],options:{root:Z,scope:{...Fr,description:`Tier to delete from: repo (default) or user.`},in:Ir,plugin:Lr,default:Rr,"dry-run":{description:`Print the file that would be deleted and what would answer the name then, and delete nothing.`,type:N.boolean().optional()}},examples:[{command:`${t} delete my-topic`,description:`Delete your contribution to my-topic`}],async run(t){let n=this.format;try{let r=_(),i={root:givenRoot(t.root),home:r,name:t.name,scope:t.scope,in:t.in,plugin:t.plugin,default:t.default,dryRun:t[`dry-run`]};validateWrite({command:`delete`,...i});let a=await e({root:t.root,default:t.default},r),o=deleteContribution(a,{...i,root:a.root??i.root},{display:e=>collapseHome(r,e)}),s=deleteReport(o,r);if(n!==`text`)return result(s);if(o.code)return document(`${s.path}\n\n${o.code}: ${o.message}\n`);let c=s.selection?` Also, ${s.selection}.`:``,l=s.metadataFile?` Its metadata file ${s.metadataFile} went with it.`:``;return document(`${s.path}\n\n${o.dryRun?`would delete`:`deleted`}. ${s.answer}${l}${c}\n`)}catch(e){return asCliError(e,`Reference deletion failed.`)}}})}function parseAccept(e){if(e===void 0)return;let t=e.split(`,`).map(e=>e.trim());if(!t.length||t.some(e=>!/^[1-9]\d*$/.test(e)))throw new ReferenceFailure(`option-invalid`,`--accept is a comma-separated list of versions, such as 1,2; got "${e}".`,{details:{option:`--accept`,value:e}});return t.map(Number)}function rowsOf(e,t){return e.implementations.map(({pin:e,description:n,unsupported:r,name:i,tier:a,version:o})=>compact(t?{pin:e,description:n,unsupported:r,name:i,tier:a,version:o}:{pin:e,...a===`plugin`?{}:{tier:a},description:n,unsupported:r}))}function reportOf(e,t){let n={implementations:rowsOf(e,t)};return e.inUse!==void 0&&(n.inUse=e.inUse),t&&Object.assign(n,compact({interface:e.interface,cardinality:e.cardinality,accept:e.accept,excluded:e.excluded,warnings:e.warnings})),n}function implementationsCommand(e,t=X){return command({name:`implementations`,description:`List the implementations of an interface a consumer can load, each with its pin, description, and unsupported sections.`,arguments:[{name:`id`,description:"Interface id, the name of its `<id>.interface` document without the suffix; or a family, `<prefix>.*`, for every interface under the prefix.",type:N.string()}],options:{root:Z,accept:{description:"Versions the consumer knows, comma-separated, such as 1,2. Defaults to the interface's `versions`.",type:N.string().optional()},trace:{...Q,description:`Add each one's name, tier, and version, the interface's cardinality and accepted versions, and the ones left out with why.`}},examples:[{command:`${t} implementations my-interface`,description:`List what implements an interface`},{command:`${t} implementations my-skill.aspects.*`,description:`List, for every interface under a prefix, what implements it and which one is in use`}],async run(t){try{let n=parseAccept(t.accept),r=_(),i={accept:n,display:e=>collapseHome(r,e)},a=referenceImplementations(t.id,await e(t,r),i);if(`family`in a){let e=a;return result({family:e.family,interfaces:e.interfaces.map(e=>({...reportOf(e,t.trace),interface:e.interface}))})}let o=reportOf(a,t.trace);return!o.implementations.length&&o.inUse===void 0&&!t.trace?empty(`0 implementations of ${t.id}`,{help:`Run \`reference implementations ${t.id} --trace\` for the ones left out, with why.`}):result(o)}catch(e){return asCliError(e,`Implementation lookup failed.`)}}})}function listCommand(e,t=X){return command({name:`list`,description:`List every reference name, one row each, with its description, and its status when not found. A pattern keeps only the names it matches exactly.`,arguments:[{name:`pattern`,description:"Exact name pattern, where `*` stands for any run of characters, such as `project-tracker.capabilities.*`.",type:N.string().optional()}],options:{root:Z,trace:{...Q,description:`Add one row per name per layer holding it, with its outcome.`}},examples:[{command:`${t} list`,description:`List every reference name`},{command:`${t} list 'project-tracker.*'`,description:`List the names matching a pattern`}],async run(t){try{let n=_(),display=e=>collapseHome(n,e),r=listReferences(await e(t,n),{display,pattern:t.pattern}),i=t.trace&&r.layers.length>0;if(!r.references.length&&!i&&!r.warnings.length)return empty(t.pattern?`0 references match "${t.pattern}"`:`0 references — no layer holds one`,{help:[...r.defaults?[r.defaults]:[],t.pattern?"Run `reference list` with no pattern for every name, or `reference search <query>` by topic.":"Run `reference create <name>` to start one."]});let a={references:r.references.map(e=>compact({name:e.name,description:e.description,format:e.format,status:e.status===`found`?void 0:e.status,code:e.code,options:e.options}))};return r.defaults&&(a.defaults=r.defaults),t.trace&&(a.layers=r.layers.map(e=>compact({...e,path:display(e.path)}))),r.warnings.length&&(a.warnings=r.warnings),result(a)}catch(e){return asCliError(e,`Reference listing failed.`)}}})}function loadEntry(e,t,{metadata:n,trace:r}){return e.status===`found`&&!e.warnings.length&&!e.projectSections.length&&!n&&!r&&e.format===`markdown`?e.content:compact({name:e.name,status:e.status,content:e.content,projectSections:e.projectSections.map(({folder:e,plugin:t,content:n})=>t===void 0?{folder:e,content:n}:{folder:e,plugin:t,content:n}),format:e.format===`markdown`?void 0:e.format,code:e.code,options:e.options,metadata:n?e.metadata:void 0,warnings:e.warnings,trace:r?displayTrace(e.trace,t):void 0})}const zr={toon:e=>encode(e,`toon`),json:e=>encode(e,`json`)};function loadText(e){let tag=e=>e.status===`found`?referenceTag(e.name,deliveredText(e)):notFoundTag(e);if(e.length===1){let[t]=e;return document(t.status===`found`?deliveredText(t):notFoundTag(t))}return document(e.map(tag).join(`
|
|
450
|
+
`)}`}function customizeCommand(e,t=X){return command({name:`customize`,description:"Customize a name for the repo or user tier, or a folder's project section, running no model: pick what it builds on (`extends`), write a body generated from a request with its record, or print what the generator reads (--base). Writes a file a contribution above hides, with a warning.",arguments:[{name:`name`,description:"Reference name, without the `.md` extension; or a family, `<prefix>.*`, to pick for every interface under the prefix at once (takes --extends or --extends-file, no `sections`).",type:N.string()},{name:`steps`,description:"More steps for --extends, so `--extends a b` lists both, bottom first.",type:N.array(N.string()).optional()}],options:{root:Z,scope:Br,in:{...Vr,description:`${Vr.description} Takes no --extends or --merge.`},default:{description:"The calling skill's folder, read only: its `references/<name>.default.md` joins the stack as the `default` tier.",type:N.string().optional()},plugin:{description:"Not accepted: customize never writes a plugin's file; an author uses `create --plugin`.",type:N.string().optional()},extends:{description:"The picks, bottom first: each a plugin holding the name, `<plugin>:<merge>` (such as `house-style:combine`), or `default`; `none` removes them. A file with no body is a selection.",type:N.array(N.string()).optional()},"extends-file":{description:"A YAML file holding the whole `extends` list, with every step key (`merge`, `extends`, `sections`).",type:N.string().optional()},request:{description:"A file holding the customizer's request, in their own words; recorded as `request`. Needs --body.",type:N.string().optional()},body:{description:`A file holding the body the generator wrote; written as given, with the picks, sources, and request recorded. Needs --request.`,type:N.string().optional()},merge:{description:`How the body applies over what is below: patch (default), combine, or replace for a whole document.`,type:N.string().optional()},implements:{description:"Interface id the body implements: a whole document recording `implements` and `merge: replace`; with --in, a project section from the interface's stub.",type:N.string().optional()},base:{description:`Print what the generator reads for the target, and write nothing: the name resolved with the picks, leaving out the target file, managed text, the tier above, and personal text; with --implements, the interface's stub first.`,type:N.boolean().optional()},"dry-run":{description:`Print the target path and the exact content, and write nothing.`,type:N.boolean().optional()},trace:{...Q,description:`After the write, add the trace, in which the written file applies.`}},examples:[{command:`${t} customize my-topic`,description:`Customize a reference for this project`},{command:`${t} customize my-skill.aspects.* --extends house-style`,description:`Pick one plugin for every interface under a prefix`}],async run(t){let n=this.format;try{let r=_(),display=e=>collapseHome(r,e),i=t.extends===void 0?void 0:[...t.extends,...t.steps??[]],a={root:givenRoot(t.root),home:r,name:t.name,scope:t.scope,in:t.in,plugin:t.plugin,default:t.default,extends:i,extendsFile:t[`extends-file`],request:t.request,body:t.body,merge:t.merge,implements:t.implements,base:t.base,dryRun:t[`dry-run`]},o=isFamilyName(t.name)||t.name.includes(`*`)?parseFamily(t.name):void 0;if(validateWrite({command:`customize`,...a,name:o===void 0||o.invalid!==void 0?t.name:o.prefix}),t.steps?.length&&t.extends===void 0)throw new ReferenceFailure(`options-missing`,`${t.steps.join(` `)} follow no --extends; pass --extends before the steps.`);let s=await e({root:t.root,default:t.default},r);if(o!==void 0){let e=customizeContribution(s,{...a,root:s.root??a.root},{display});if(!(`family`in e))throw Error(`${t.name} was customized as a single name, not a family.`);let i=familyReport(e,t,r);if(n!==`text`)return result(i);for(let{result:t}of e.interfaces)writeWarnings(t?.warnings??[]);return document(familyText(e,i))}let c=customizeContribution(s,{...a,root:s.root??a.root},{display});if(`family`in c)throw Error(`${t.name} was customized as a family, not a single name.`);if(c.action===`base`)return n===`text`?document(baseText(c)):result(baseReport(c));let l=report(c,t,r);if(n!==`text`)return result(l);writeWarnings(c.warnings);for(let e of c.hints)process.stderr.write(`hint: ${e}\n`);return t.trace&&c.after&&!c.code&&process.stderr.write(traceText(c.after,r)),document(text(c,l))}catch(e){return asCliError(e,`Reference customization failed.`)}}})}function deleteReport(e,t){let n=e.selection?`the selection extends: [${e.selection.join(`, `)}] went with it; run \`reference customize ${e.name} --extends ${e.selection.join(` `)}\` to restore it`:void 0;return compact({path:collapseHome(t,e.path),folder:e.folder,metadataFile:e.metadataFile===void 0?void 0:collapseHome(t,e.metadataFile),code:e.code,message:e.message,dryRun:e.dryRun||void 0,status:e.after.status,stack:e.after.trace.stack,answer:describeAnswer(e.after,e=>collapseHome(t,e)),selection:n,options:e.after.options})}function deleteCommand(e,t=X){return command({name:`delete`,description:`Delete a repo or user contribution, a folder's project section, or one in a plugin's or a skill's source folder, with a non-Markdown file's metadata file, and report what answers the name afterwards. Never deletes an installed or managed one.`,arguments:[{name:`name`,description:"Reference name, without the `.md` extension.",type:N.string()}],options:{root:Z,scope:{...Br,description:`Tier to delete from: repo (default) or user.`},in:Vr,plugin:Hr,default:Ur,"dry-run":{description:`Print the file that would be deleted and what would answer the name then, and delete nothing.`,type:N.boolean().optional()}},examples:[{command:`${t} delete my-topic`,description:`Delete your contribution to my-topic`}],async run(t){let n=this.format;try{let r=_(),i={root:givenRoot(t.root),home:r,name:t.name,scope:t.scope,in:t.in,plugin:t.plugin,default:t.default,dryRun:t[`dry-run`]};validateWrite({command:`delete`,...i});let a=await e({root:t.root,default:t.default},r),o=deleteContribution(a,{...i,root:a.root??i.root},{display:e=>collapseHome(r,e)}),s=deleteReport(o,r);if(n!==`text`)return result(s);if(o.code)return document(`${s.path}\n\n${o.code}: ${o.message}\n`);let c=s.selection?` Also, ${s.selection}.`:``,l=s.metadataFile?` Its metadata file ${s.metadataFile} went with it.`:``;return document(`${s.path}\n\n${o.dryRun?`would delete`:`deleted`}. ${s.answer}${l}${c}\n`)}catch(e){return asCliError(e,`Reference deletion failed.`)}}})}function parseAccept(e){if(e===void 0)return;let t=e.split(`,`).map(e=>e.trim());if(!t.length||t.some(e=>!/^[1-9]\d*$/.test(e)))throw new ReferenceFailure(`option-invalid`,`--accept is a comma-separated list of versions, such as 1,2; got "${e}".`,{details:{option:`--accept`,value:e}});return t.map(Number)}function rowsOf(e,t){return e.implementations.map(({pin:e,description:n,unsupported:r,name:i,tier:a,version:o})=>compact(t?{pin:e,description:n,unsupported:r,name:i,tier:a,version:o}:{pin:e,...a===`plugin`?{}:{tier:a},description:n,unsupported:r}))}function reportOf(e,t){let n={implementations:rowsOf(e,t)};return e.inUse!==void 0&&(n.inUse=e.inUse),t&&Object.assign(n,compact({interface:e.interface,cardinality:e.cardinality,accept:e.accept,excluded:e.excluded,warnings:e.warnings})),n}function implementationsCommand(e,t=X){return command({name:`implementations`,description:`List the implementations of an interface a consumer can load, each with its pin, description, and unsupported sections.`,arguments:[{name:`id`,description:"Interface id, the name of its `<id>.interface` document without the suffix; or a family, `<prefix>.*`, for every interface under the prefix.",type:N.string()}],options:{root:Z,accept:{description:"Versions the consumer knows, comma-separated, such as 1,2. Defaults to the interface's `versions`.",type:N.string().optional()},trace:{...Q,description:`Add each one's name, tier, and version, the interface's cardinality and accepted versions, and the ones left out with why.`}},examples:[{command:`${t} implementations my-interface`,description:`List what implements an interface`},{command:`${t} implementations my-skill.aspects.*`,description:`List, for every interface under a prefix, what implements it and which one is in use`}],async run(t){try{let n=parseAccept(t.accept),r=_(),i={accept:n,display:e=>collapseHome(r,e)},a=referenceImplementations(t.id,await e(t,r),i);if(`family`in a){let e=a;return result({family:e.family,interfaces:e.interfaces.map(e=>({...reportOf(e,t.trace),interface:e.interface}))})}let o=reportOf(a,t.trace);return!o.implementations.length&&o.inUse===void 0&&!t.trace?empty(`0 implementations of ${t.id}`,{help:`Run \`reference implementations ${t.id} --trace\` for the ones left out, with why.`}):result(o)}catch(e){return asCliError(e,`Implementation lookup failed.`)}}})}function listCommand(e,t=X){return command({name:`list`,description:`List every reference name, one row each, with its description, and its status when not found. A pattern keeps only the names it matches exactly.`,arguments:[{name:`pattern`,description:"Exact name pattern, where `*` stands for any run of characters, such as `project-tracker.capabilities.*`.",type:N.string().optional()}],options:{root:Z,trace:{...Q,description:`Add one row per name per layer holding it, with its outcome.`}},examples:[{command:`${t} list`,description:`List every reference name`},{command:`${t} list 'project-tracker.*'`,description:`List the names matching a pattern`}],async run(t){try{let n=_(),display=e=>collapseHome(n,e),r=listReferences(await e(t,n),{display,pattern:t.pattern}),i=t.trace&&r.layers.length>0;if(!r.references.length&&!i&&!r.warnings.length)return empty(t.pattern?`0 references match "${t.pattern}"`:`0 references — no layer holds one`,{help:[...r.defaults?[r.defaults]:[],t.pattern?"Run `reference list` with no pattern for every name, or `reference search <query>` by topic.":"Run `reference create <name>` to start one."]});let a={references:r.references.map(e=>compact({name:e.name,description:e.description,format:e.format,status:e.status===`found`?void 0:e.status,code:e.code,options:e.options}))};return r.defaults&&(a.defaults=r.defaults),t.trace&&(a.layers=r.layers.map(e=>compact({...e,path:display(e.path)}))),r.warnings.length&&(a.warnings=r.warnings),result(a)}catch(e){return asCliError(e,`Reference listing failed.`)}}})}function loadEntry(e,t,{metadata:n,trace:r}){return e.status===`found`&&!e.warnings.length&&!e.projectSections.length&&!n&&!r&&e.format===`markdown`?e.content:compact({name:e.name,status:e.status,content:e.content,projectSections:e.projectSections.map(({folder:e,plugin:t,content:n})=>t===void 0?{folder:e,content:n}:{folder:e,plugin:t,content:n}),format:e.format===`markdown`?void 0:e.format,code:e.code,options:e.options,metadata:n?e.metadata:void 0,warnings:e.warnings,trace:r?displayTrace(e.trace,t):void 0})}const Wr={toon:e=>encode(e,`toon`),json:e=>encode(e,`json`)};function loadText(e){let tag=e=>e.status===`found`?referenceTag(e.name,deliveredText(e)):notFoundTag(e);if(e.length===1){let[t]=e;return document(t.status===`found`?deliveredText(t):notFoundTag(t))}return document(e.map(tag).join(`
|
|
451
451
|
|
|
452
|
-
`))}function loadCommand(e,t=X){return command({name:`load`,description:`Print one or more references, each composed from its contributions as their extends and merge declare.`,arguments:[{name:`names`,description:"Reference names, without the `.md` extension; `<plugin>/<name>` builds that plugin’s own stack.",type:N.array(N.string())}],options:{root:Z,default:
|
|
453
|
-
`).trimStart()}\n`)):result(s)}catch(e){return asCliError(e,`Reference migration failed.`)}}})}function searchCommand(e,t=X){return command({name:`search`,description:`Find references by name, description, tags, headings, or body, best match first.`,arguments:[{name:`query`,description:`What the reference is about.`,type:N.string()}],options:{root:Z,trace:{...Q,description:`Add the tier and plugin or skill of each match.`},full:{...ze,description:`Show every match, not only the best 10.`}},examples:[{command:`${t} search "worktree leases"`,description:`Find references by topic`}],async run(t){let n=t.query.trim();try{let r=_(),{matches:i,defaults:a}=searchReferences(n,await e(t,r),{display:e=>collapseHome(r,e)});if(!i.length)return empty(`0 references match "${n}"`,{help:[...a?[a]:[],"Try other words, or run `reference list` for every name."]});let o=truncateList(i,{limit:10,full:t.full}),s=compact({count:o.truncated?o.count:void 0,references:o.items.map(({name:e,description:n,match:r,folder:i,tier:a,plugin:o,skill:s,loadedBy:c})=>compact(t.trace?{name:e,description:n,match:r,folder:i,loadedBy:c,tier:a,plugin:o,skill:s}:{name:e,description:n,match:r,folder:i,loadedBy:c})),defaults:a});return o.truncated?result(s,{help:[`Run \`reference search ${JSON.stringify(n)} --full\` for every match.`]}):result(s)}catch(e){return asCliError(e,`Reference search failed.`)}}})}function whereCommand(e,t=X){return command({name:`where`,description:`Give the repo and user files, and with --in a folder's project section, a customization or a selection of a reference is written to, who each reaches and what hides it, the main document's heading paths, and the read-only plugins and default the stack uses.`,arguments:[{name:`name`,description:"Reference name, without the `.md` extension.",type:N.string()}],options:{root:Z,default:
|
|
452
|
+
`))}function loadCommand(e,t=X){return command({name:`load`,description:`Print one or more references, each composed from its contributions as their extends and merge declare.`,arguments:[{name:`names`,description:"Reference names, without the `.md` extension; `<plugin>/<name>` builds that plugin’s own stack.",type:N.array(N.string())}],options:{root:Z,default:zr,metadata:{description:`Make every entry a record with its status and composed frontmatter.`,type:N.boolean().optional()},trace:Q},examples:[{command:`${t} load my-topic`,description:`Print one reference`},{command:`${t} load my-topic other-topic --format json`,description:`Print several as JSON`}],async run(t){let n=this.format;try{if(!t.names.length)throw new ReferenceFailure(`name-missing`,`name at least one reference to load.`,{help:"Run `reference load <name>...`, or `reference list` for every name."});for(let e of t.names)requireName(e);let r=_(),i=await e(t,r),display=e=>collapseHome(r,e),a=interfaceLookup(i,{display}),o=t.names.map(e=>{let t=resolveReference(parseReferenceName(e),i,{display}),n=checkResolved(t,a);t.warnings.push(...n.warnings);for(let e of n.failures)e.check!==`compose`&&t.warnings.push({code:`interface-check`,message:`it fails its interface check (${e.check}): ${e.message}`});return t});if(n===`text`){for(let e of o)writeWarnings(e.warnings),t.trace&&process.stderr.write(traceText(e,r));return loadText(o)}let s={metadata:!!t.metadata,trace:!!t.trace};return result(o.map(e=>loadEntry(e,r,s)),{render:Wr})}catch(e){return asCliError(e,`Reference lookup failed.`)}}})}function rowLine(e){let t=e.folder===void 0?e.tier:`${e.tier} ${e.folder}`,n=e.manual===void 0?`${e.from} → ${e.to}`:`${e.from}: manual: ${e.manual}`,r=e.by===void 0?``:` (by ${e.by})`,i=e.tier===`user`?`; a user file, which no git history restores`:``;return`${e.path} (${t}): ${e.form}: ${n}${r}${i}`}function summary(e,t){let n=e.filter(e=>e.manual!==void 0).length,r=e.length-n,i=n?` ${n} ${n===1?`needs`:`need`} a person, as each says.`:``;return t?`migrated ${r} ${r===1?`change`:`changes`}.${i}`:r?`${r} ${r===1?`change`:`changes`} to make; run \`reference migrate --write\` with the same arguments to apply ${r===1?`it`:`them`}.${i}`:`nothing to apply.${i}`}function migrateCommand(e,t=X){return command({name:`migrate`,description:"Rewrite reference files still in a form version 1 wrote, and rename files under a name a plugin renamed, in the repo and user tiers and every project section, or in one plugin or skill source folder. Prints the plan; `--write` applies it. Never changes a managed or installed file.",arguments:[{name:`names`,description:"Reference names to limit the run to, without the `.md` extension; a file under an older name of one is included.",type:N.array(N.string()).optional()}],options:{root:Z,plugin:{description:"A plugin's source folder in this repository: migrate only its `references/`, in place of the tiers.",type:N.string().optional()},default:{description:"A skill's source folder in this repository: migrate only its `references/`, in place of the tiers. A default at `references/<name>.md` is renamed only for a name given.",type:N.string().optional()},write:{description:"Apply the changes. It edits `user` files too, which no git history restores.",type:N.boolean().optional()}},examples:[{command:`${t} migrate`,description:`Migrate version 1 reference files`}],async run(t){let n=this.format;try{let r=_();if(t.plugin!==void 0&&t.default!==void 0)throw new ReferenceFailure(`options-conflict`,`pass one of --plugin and --default.`);let i=await e({root:t.root},r),a=migrateReferences(i,{root:i.root??givenRoot(t.root),home:r,names:t.names,plugin:t.plugin,default:t.default,write:t.write}),o=a.rows.map(e=>({...e,path:collapseHome(r,e.path)}));if(!o.length&&!a.warnings.length)return empty(`0 changes — no reference file is in a version 1 form or under a renamed name`,{help:["Run `reference check` for every warning `load` raises."]});let s=compact({changes:o,written:a.written?!0:void 0,warnings:a.warnings});return n===`text`?(writeWarnings(a.warnings),document(`${[...o.map(rowLine),``,summary(o,a.written)].join(`
|
|
453
|
+
`).trimStart()}\n`)):result(s)}catch(e){return asCliError(e,`Reference migration failed.`)}}})}function searchCommand(e,t=X){return command({name:`search`,description:`Find references by name, description, tags, headings, or body, best match first.`,arguments:[{name:`query`,description:`What the reference is about.`,type:N.string()}],options:{root:Z,trace:{...Q,description:`Add the tier and plugin or skill of each match.`},full:{...ze,description:`Show every match, not only the best 10.`}},examples:[{command:`${t} search "worktree leases"`,description:`Find references by topic`}],async run(t){let n=t.query.trim();try{let r=_(),{matches:i,defaults:a}=searchReferences(n,await e(t,r),{display:e=>collapseHome(r,e)});if(!i.length)return empty(`0 references match "${n}"`,{help:[...a?[a]:[],"Try other words, or run `reference list` for every name."]});let o=truncateList(i,{limit:10,full:t.full}),s=compact({count:o.truncated?o.count:void 0,references:o.items.map(({name:e,description:n,match:r,folder:i,tier:a,plugin:o,skill:s,loadedBy:c})=>compact(t.trace?{name:e,description:n,match:r,folder:i,loadedBy:c,tier:a,plugin:o,skill:s}:{name:e,description:n,match:r,folder:i,loadedBy:c})),defaults:a});return o.truncated?result(s,{help:[`Run \`reference search ${JSON.stringify(n)} --full\` for every match.`]}):result(s)}catch(e){return asCliError(e,`Reference search failed.`)}}})}function whereCommand(e,t=X){return command({name:`where`,description:`Give the repo and user files, and with --in a folder's project section, a customization or a selection of a reference is written to, who each reaches and what hides it, the main document's heading paths, and the read-only plugins and default the stack uses.`,arguments:[{name:`name`,description:"Reference name, without the `.md` extension.",type:N.string()}],options:{root:Z,default:zr,in:{...Vr,description:`A folder strictly below the root: also give its project section's file.`},trace:{...Q,description:`Add every layer checked, with its outcome.`}},examples:[{command:`${t} where my-topic`,description:`Show which layers hold my-topic`}],async run(t){let n=this.format;try{let r=_(),display=e=>collapseHome(r,e),i=await e(t,r),a=whereReference(t.name,i,{root:i.root??givenRoot(t.root),display,in:t.in}),o=compact({name:a.name,status:a.status,files:a.files,headings:a.headings,used:a.used,options:a.options,hint:a.used.length?`${a.used.join(`, `)} ${a.used.length===1?`is`:`are`} read-only; a customization goes in one of the files.`:void 0,layers:t.trace?a.layers.map(e=>({...e,path:display(e.path)})):void 0,warnings:a.warnings});return n===`text`&&writeWarnings(a.warnings),result(o)}catch(e){return asCliError(e,`Reference placement lookup failed.`)}}})}function createReferenceCommands({plugin:e,path:t=X}={}){let n=layerSource(e);return{load:loadCommand(n,t),list:listCommand(n,t),search:searchCommand(n,t),where:whereCommand(n,t),create:createCommand(n,t),customize:customizeCommand(n,t),delete:deleteCommand(n,t),migrate:migrateCommand(n,t),check:checkCommand(n,t),implementations:implementationsCommand(n,t)}}function createReferenceCommand(e={}){let{load:t,list:n,search:r,where:i,create:a,customize:o,delete:s,migrate:c,check:l,implementations:u}=createReferenceCommands(e);return command({name:`reference`,description:`Read reference documents by name, composed from the managed, repo, user, plugin, and default tiers, create, customize, or delete a contribution, and migrate version 1 files.`,commands:[t,n,r,i,a,o,s,c,u,l]})}function machineWideDir(e,t,n){return e===`darwin`?C(`/Library/Application Support`,n.macos,`governances`):e===`win32`?C(t||`C:\\ProgramData`,n.windows,`governances`):C(`/etc`,n.posix,`governances`)}function managedGovernancesDir(e,t){return machineWideDir(e,t,{posix:`buddy-agent-harness`,macos:`BuddyAgentHarness`,windows:`BuddyAgentHarness`})}function deprecatedManagedGovernancesDir(e,t){return machineWideDir(e,t,{posix:`universal-plugin`,macos:`UniPlugin`,windows:`UniPlugin`})}function projectGovernancesDir(e){return C(e,`.agents`,`governances`)}function userGovernancesDir(e){return C(e,`.agents`,`governances`)}function packageGovernancesDir(e=te(import.meta.url)){let t=b(e);for(;;){if(n(C(t,`package.json`)))return C(t,`governances`);let e=b(t);if(e===t)return C(t,`governances`);t=e}}function governanceLayers({root:e,home:t,platform:n,programData:r}){return[{scope:`project`,dir:projectGovernancesDir(e)},{scope:`user`,dir:userGovernancesDir(t)},{scope:`managed`,dir:managedGovernancesDir(n,r)},{scope:`managed-deprecated`,dir:deprecatedManagedGovernancesDir(n,r)},{scope:`package`,dir:packageGovernancesDir()}]}function overrideLayers(e){return e.filter(e=>e.scope!==`package`)}const Gr=/^[a-z0-9]+(?:[-.][a-z0-9]+)*$/i;function parseGovernanceName(e){if(e.endsWith(`.md`))throw Error(`"${e}" names a file. Ask for the governance by name, without the .md extension.`);if(!Gr.test(e))throw Error(`"${e}" is not a governance name. A name is letters, digits, hyphens, and dots — not a path.`);return e}function tryReadDocument(e){try{return a(e,`utf8`)}catch{return}}function documentNames(e){try{return o(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(e=>e.name.slice(0,-3))}catch{return[]}}function resolveGovernance(e,t){for(let{scope:n,dir:r}of t){let t=C(r,`${e}.md`),i=tryReadDocument(t);if(i!==void 0)return{name:e,scope:n,path:t,content:i}}}function listGovernances(e){let t=new Map;for(let{scope:n,dir:r}of e)for(let e of documentNames(r))t.has(e)||t.set(e,{name:e,scope:n,path:C(r,`${e}.md`)});return[...t.values()].sort((e,t)=>e.name.localeCompare(t.name))}const Kr=`buddy-agent-harness`;function referenceLayers({packageRoot:e=b(packageGovernancesDir()),...t}){return referenceLayers$1({...t,plugin:{name:Kr,root:e}})}const qr=createReferenceCommand({plugin:{name:Kr,root:b(packageGovernancesDir())},path:`buddy-agent-harness reference`});function skillNames(e){return o(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}function pathOccupied(e){try{return r(e),!0}catch{return!1}}function linksTo(e,t){try{return r(e).isSymbolicLink()?c(e)===c(t):!1}catch{return!1}}function countSkills(e){return i(e,{recursive:!0}),skillNames(e).length}function linkTarget(e,t){return v()===`win32`?E(t):T(b(e),t)}function parseForce(e){return e===`true`||e!==`false`&&e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0)}function namesTarget(e,t,n){return E(e,n)===E(t)}function projectSkills({root:e,canonicalSkills:n,harnesses:r,copy:a,force:o}){let s=r.filter(e=>e.project.skillsDirectory).map(t=>({harness:t,target:C(e,t.project.skillsDirectory)})),c=Array.isArray(o)?o:[],l=c.filter(t=>!s.some(({target:n})=>namesTarget(e,n,t)));if(l.length)throw Error(`No skill target matches:\n${l.map(e=>`- ${e}`).join(`
|
|
454
454
|
`)}\nTargets for the enabled harnesses:\n${s.map(({target:t})=>`- ${T(e,t)}`).join(`
|
|
455
455
|
`)}`);let forces=t=>o===!0||c.some(n=>namesTarget(e,t,n)),d=s.filter(({target:e})=>pathOccupied(e)&&!linksTo(e,n)).filter(({target:e})=>!forces(e));if(d.length&&c.length===0)throw Error(`Refusing to replace existing skill targets:\n${d.map(({target:t})=>`- ${T(e,t)}`).join(`
|
|
456
|
-
`)}`);let f=new Set(d.map(({harness:e})=>e.name));for(let{harness:e,target:r}of s)if(!f.has(e.name)&&(i(b(r),{recursive:!0}),!linksTo(r,n))){if(pathOccupied(r)&&u(r,{recursive:!0,force:!0}),a){t(n,r,{recursive:!0});continue}try{p(linkTarget(r,n),r,v()===`win32`?`junction`:void 0)}catch(e){if(pathOccupied(r))throw e;t(n,r,{recursive:!0})}}return{linked:s.filter(({harness:e})=>!f.has(e.name)).map(({harness:e})=>e.name),skipped:s.filter(({harness:e})=>f.has(e.name)).map(({harness:e})=>e.name)}}function isDirectory$1(e){try{return r(e).isDirectory()}catch{return!1}}__name(isDirectory$1,`isDirectory`);function exists$1(e){try{return r(e),!0}catch{return!1}}__name(exists$1,`exists`);function importsGlobal(e,t,n){let r=t.kind===`import`?[t.line,`@${C(n,
|
|
457
|
-
`).some(e=>r.includes(e.trim()))}function base(e,t,n){let r=e.relocatedBy,i=r===void 0?void 0:t[r];return r===void 0||i===void 0?{}:i===``?e.emptyRelocatesToStart?{moved:{root:n,display:`.`},emptied:r}:{}:{moved:{root:E(i),display:`$${r}`}}}function locate(e,t,{moved:n},r){if(!n||r!==t.detect&&!r.startsWith(`${t.detect}/`))return{absolute:C(e,r),display:`~/${r}`};let i=r.slice(t.detect.length);return{absolute:C(n.root,i),display:`${n.display}${i}`}}function readsAsShadow(e){try{return f(e).isFile()&&a(e,`utf8`).trim()!==``}catch{return!1}}function inspect$2(e,t,n){let i;try{i=r(t)}catch{return{kind:`none`,status:`missing`,problem:`global-instructions-missing`}}if(i.isSymbolicLink())return E(b(t),s(t))===C(e,`.agents/AGENTS.md`)?{kind:`symlink`,status:`ok`}:{kind:`symlink`,status:`unbridged`,problem:`global-instructions-unbridged`};let o;try{o=a(t,`utf8`)}catch{return{kind:`file`,status:`unbridged`,problem:`global-instructions-unbridged`}}return importsGlobal(o,n,e)?{kind:`import`,status:`ok`}:{kind:`file`,status:`unbridged`,problem:`global-instructions-unbridged`}}__name(inspect$2,`inspect`);function finding(e,t,n){let{detail:r,repair:i}=repairFor(t);return{path:e,problem:t,detail:r,repair:i({file:e},n)}}function diagnoseGlobalInstructions(e,t,n,r={},i=process.cwd()){let a=exists$1(C(e,
|
|
458
|
-
`).some(e=>e.trim()===`@AGENTS.md`)?{kind:`import`,status:`superseded`,problem:`instructions-superseded`}:{kind:`file`,status:`shadowing`,problem:`instructions-shadowing`}}function diagnoseInstructions(e,t,n){let r=t.map(e=>({name:e.name,bridge:e.project.instructionBridge})).filter(e=>e.bridge?.kind===`settings-entry`),i=[],a=[],o=agentsFileDirectories(e),s=t.some(t=>(t.project.shadowedBy??[]).some(t=>exists(C(e,t))));if((r.length||s)&&!o.includes(``)){let{detail:e,repair:t}=repairFor(`no-instructions`);a.push({path:
|
|
459
|
-
`).filter(Boolean)}var GitBridgeState=class{root;repoRootPrefix;constructor(e){this.root=e,this.repoRootPrefix=git(e,[`rev-parse`,`--show-prefix`])?.trim()}trackingOf(e){if(this.repoRootPrefix===void 0)return`untracked`;let t=lines(git(this.root,[`ls-files`,`-v`,`--`,e]));return t.length?t.every(e=>e.startsWith(`S`))?`skip-worktree`:`tracked`:`untracked`}isIgnored(e){return this.repoRootPrefix!==void 0&&git(this.root,[`check-ignore`,`-q`,`--`,e])!==void 0}commitsTouching(e){return this.repoRootPrefix===void 0?[]:lines(git(this.root,[`rev-list`,`-n`,`200`,`HEAD`,`--`,...e]))}contentAt(e,t){if(this.repoRootPrefix!==void 0)return git(this.root,[`show`,`${e}:${this.repoRootPrefix}${t}`])}directionOf(e,t){if(this.repoRootPrefix===void 0)return`unknown`;let n=this.lastAgreedTree(e,t);if(n===void 0)return`unknown`;let r=!this.matchesTree(e,n),i=!this.matchesTree(t,n);return r&&i?`both`:r?`bridge`:`canonical`}lastAgreedTree(e,t){for(let n of lines(git(this.root,[`rev-list`,`-n`,`200`,`HEAD`,`--`,e,t]))){let r=git(this.root,[`rev-parse`,`-q`,`--verify`,`${n}:${this.repoRootPrefix}${e}`])?.trim();if(r&&r===git(this.root,[`rev-parse`,`-q`,`--verify`,`${n}:${this.repoRootPrefix}${t}`])?.trim())return r}}matchesTree(e,t){let n=new Map(lines(git(this.root,[`ls-tree`,`-r`,t])).map(e=>{let[t,n]=e.split(` `);return[n,t.split(` `)[2]]})),r=filesUnder(C(this.root,e));if(r.length!==n.size||r.some(e=>!n.has(e)))return!1;let i=lines(git(this.root,[`hash-object`,`--stdin-paths`],r.map(t=>C(e,t)).join(`
|
|
460
|
-
`)));return i.length===r.length&&r.every((e,t)=>n.get(e)===i[t])}};const
|
|
461
|
-
`,Yr={description:`Repository or package directory. Defaults to the current directory.`,type:N.string().optional()},Xr={description:`Resolve only the project, user, and machine-wide layers. Never returns a governance this package ships, and exits non-zero when no layer has one.`,type:N.boolean().optional()},Zr=command({name:`governance`,description:"Deprecated: use `reference`. Read the governance documents the project, user, and machine-wide override layers hold. Read-only.",commands:[command({name:`list`,description:`List every governance the override layers hold, each at the layer that would win.`,options:{root:Yr,"overrides-only":Xr},examples:[{command:`buddy-agent-harness governance list`,description:`List the governances the layers hold`}],run(e){process.stderr.write(Jr);try{let t=_(),n=layersFor(e),r=listGovernances(n);return result({layers:n.map(({scope:e,dir:n})=>({scope:e,path:collapseHome$1(t,n),status:e===`managed-deprecated`?`deprecated — move these documents to the managed layer above`:``})),governances:r.length?r.map(({name:e,scope:n,path:r})=>({name:e,scope:n,path:collapseHome$1(t,r)})):`0 governances — no layer holds one`})}catch(e){return fail(e,`Governance listing failed.`)}}}),command({name:`show`,description:`Print one governance document, resolved through the layers in order.`,arguments:[{name:`name`,description:"The governance name, without the `.md` extension.",type:N.string()}],options:{root:Yr,"overrides-only":Xr},examples:[{command:`buddy-agent-harness governance show skill-design`,description:`Print one governance document`}],run(e){let t=this.format;process.stderr.write(Jr);try{let n=parseGovernanceName(e.name),r=resolveGovernance(n,layersFor(e));if(!r)throw new M(e[`overrides-only`]?`no override for governance "${n}" in the project, user, or machine-wide layer.`:`no governance named "${n}" in any layer.`,{code:`governance-not-found`,details:{name:n},help:ref(`reference list`,{},`see what is available`)});let i={name:r.name,scope:r.scope,path:collapseHome$1(_(),r.path),content:r.content};return t===`text`?document(i.content):result(i)}catch(e){return fail(e,`Governance lookup failed.`)}}})]});function keepWhenEmpty(e){o(e).length===0&&m(C(e,`.gitkeep`),``)}function initializeHarnesses({root:e,harnesses:t=[],copy:n=!1,force:r=!1}){let a=C(e,`.agents`,`skills`),o=countSkills(a);i(repoReferencesDir(e),{recursive:!0});let s=referenceNames([{tier:`repo`,dir:repoReferencesDir(e)}]).length;keepWhenEmpty(a),keepWhenEmpty(repoReferencesDir(e));let c=selectHarnesses(e,t),{linked:l,skipped:u}=projectSkills({root:e,canonicalSkills:a,harnesses:c,copy:n,force:r});return{root:e,harnesses:c.map(e=>e.name),native:c.filter(e=>!e.project.skillsDirectory).map(e=>e.name),linked:l,skipped:u,deprecated:c.filter(e=>e.deprecated).map(e=>({name:e.name,replacedBy:e.deprecated})),skills:o,references:s,copied:n}}const Qr=command({name:`init`,description:`Set up canonical agent skills for the harnesses already enabled in a repository.`,options:{root:{description:`Repository or package directory. Defaults to the current directory.`,type:N.string().optional()},harness:{description:`Comma-separated harnesses to enable in addition to Claude Code and Cursor, e.g. codex,gemini-cli.`,type:N.string().optional()},copy:{description:`Copy skills instead of linking them.`,type:N.boolean().optional()},force:{description:`Replace conflicting target skill directories. Names the targets to replace, comma-separated (e.g. .claude/skills); given alone it replaces every conflicting target.`,type:N.string().optional()}},examples:[{command:`buddy-agent-harness init`,description:`Set up skills for Claude Code and Cursor`},{command:`buddy-agent-harness init --harness codex --copy`,description:`Also enable Codex, copying skills instead of linking`}],run(e){try{let t=parseHarnessOption(e.harness);return result(initializeHarnesses({root:e.root??process.cwd(),...t.length?{harnesses:t}:{},...e.copy===void 0?{}:{copy:e.copy},...e.force===void 0?{}:{force:parseForce(e.force)}}))}catch(e){return fail(e,`Harness initialization failed.`)}}}),$r={ArrayExpression:[`elements`],ArrayPattern:[`elements`],ArrowFunctionExpression:[`params`,`body`],AssignmentExpression:[`left`,`right`],AssignmentPattern:[`left`,`right`],AwaitExpression:[`argument`],BinaryExpression:[`left`,`right`],BlockStatement:[`body`],BreakStatement:[`label`],CallExpression:[`callee`,`arguments`],CatchClause:[`param`,`body`],ChainExpression:[`expression`],ClassBody:[`body`],ClassDeclaration:[`id`,`superClass`,`body`],ClassExpression:[`id`,`superClass`,`body`],ConditionalExpression:[`test`,`consequent`,`alternate`],ContinueStatement:[`label`],DebuggerStatement:[],DoWhileStatement:[`body`,`test`],EmptyStatement:[],ExperimentalRestProperty:[`argument`],ExperimentalSpreadProperty:[`argument`],ExportAllDeclaration:[`exported`,`source`,`attributes`],ExportDefaultDeclaration:[`declaration`],ExportNamedDeclaration:[`declaration`,`specifiers`,`source`,`attributes`],ExportSpecifier:[`local`,`exported`],ExpressionStatement:[`expression`],ForInStatement:[`left`,`right`,`body`],ForOfStatement:[`left`,`right`,`body`],ForStatement:[`init`,`test`,`update`,`body`],FunctionDeclaration:[`id`,`params`,`body`],FunctionExpression:[`id`,`params`,`body`],Identifier:[],IfStatement:[`test`,`consequent`,`alternate`],ImportAttribute:[`key`,`value`],ImportDeclaration:[`specifiers`,`source`,`attributes`],ImportDefaultSpecifier:[`local`],ImportExpression:[`source`,`options`],ImportNamespaceSpecifier:[`local`],ImportSpecifier:[`imported`,`local`],JSXAttribute:[`name`,`value`],JSXClosingElement:[`name`],JSXClosingFragment:[],JSXElement:[`openingElement`,`children`,`closingElement`],JSXEmptyExpression:[],JSXExpressionContainer:[`expression`],JSXFragment:[`openingFragment`,`children`,`closingFragment`],JSXIdentifier:[],JSXMemberExpression:[`object`,`property`],JSXNamespacedName:[`namespace`,`name`],JSXOpeningElement:[`name`,`attributes`],JSXOpeningFragment:[],JSXSpreadAttribute:[`argument`],JSXSpreadChild:[`expression`],JSXText:[],LabeledStatement:[`label`,`body`],Literal:[],LogicalExpression:[`left`,`right`],MemberExpression:[`object`,`property`],MetaProperty:[`meta`,`property`],MethodDefinition:[`key`,`value`],NewExpression:[`callee`,`arguments`],ObjectExpression:[`properties`],ObjectPattern:[`properties`],PrivateIdentifier:[],Program:[`body`],Property:[`key`,`value`],PropertyDefinition:[`key`,`value`],RestElement:[`argument`],ReturnStatement:[`argument`],SequenceExpression:[`expressions`],SpreadElement:[`argument`],StaticBlock:[`body`],Super:[],SwitchCase:[`test`,`consequent`],SwitchStatement:[`discriminant`,`cases`],TaggedTemplateExpression:[`tag`,`quasi`],TemplateElement:[],TemplateLiteral:[`quasis`,`expressions`],ThisExpression:[],ThrowStatement:[`argument`],TryStatement:[`block`,`handler`,`finalizer`],UnaryExpression:[`argument`],UpdateExpression:[`argument`],VariableDeclaration:[`declarations`],VariableDeclarator:[`id`,`init`],WhileStatement:[`test`,`body`],WithStatement:[`object`,`body`],YieldExpression:[`argument`]},ei=Object.keys($r);for(let e of ei)Object.freeze($r[e]);Object.freeze($r);function unionWith(e){let t=Object.assign({},$r);for(let n of Object.keys(e))if(Object.hasOwn(t,n)){let r=new Set(e[n]);for(let e of t[n])r.add(e);t[n]=Object.freeze(Array.from(r))}else t[n]=Object.freeze(Array.from(e[n]));return Object.freeze(t)}function last(e){return e[e.length-1]??null}function toKeyName(e){return e.type===`TOMLBare`?e.name:e.value}var TOMLVerImpl=class{constructor(e,t){this.major=e,this.minor=t}lt(e,t){return this.major<e||this.major===e&&this.minor<t}gte(e,t){return this.major>e||this.major===e&&this.minor>=t}};const ti=new TOMLVerImpl(1,0),ni=new TOMLVerImpl(1,1),ri=ni,ii={"1.0":ti,"1.0.0":ti,"1.1":ni,"1.1.0":ni,latest:ni,next:ni};function getTOMLVer(e){return e&&ii[e]||ri}const ai={"unterminated-string":`Unterminated string constant`,"unterminated-table-key":`Unterminated table-key`,"unterminated-array":`Unterminated array`,"unterminated-inline-table":`Unterminated inline table`,"missing-key":`Empty bare keys are not allowed`,"missing-newline":`Must be a newline`,"missing-equals-sign":`Expected equal (=) token`,"missing-value":`Unspecified values are invalid`,"missing-comma":`Expected comma (,) token`,"dupe-keys":`Defining a key multiple times is invalid`,"unexpected-char":`Unexpected character`,"unexpected-token":`Unexpected token`,"invalid-control-character":`Control characters (codes < 0x1f and 0x7f) are not allowed`,"invalid-comment-character":`Invalid code point {{cp}} within comments`,"invalid-key-value-newline":`The key, equals sign, and value must be on the same line`,"invalid-inline-table-newline":`No newlines are allowed between the curly braces unless they are valid within a value`,"invalid-underscore":`Underscores are allowed between digits`,"invalid-space":`Unexpected spaces`,"invalid-three-quotes":`Three or more quotes are not permitted`,"invalid-date":`Unexpected invalid date`,"invalid-time":`Unexpected invalid time`,"invalid-leading-zero":`Leading zeros are not allowed`,"invalid-trailing-comma-in-inline-table":`Trailing comma is not permitted in an inline table`,"invalid-char-in-escape-sequence":`Invalid character in escape sequence`,"invalid-consecutive-dots-in-key":`Consecutive dots are not permitted in keys`,"invalid-code-point":`Invalid code point {{cp}}`,"invalid-trailing-dot-in-key":`Keys cannot end with a dot`,"invalid-leading-dot-in-key":`Keys cannot start with a dot`};function getMessage(e,t){return t?ai[e].replace(/\{\{(.*?)\}\}/gu,(e,n)=>n in t?t[n]:`{{${n}}}`):ai[e]}var ParseError=class extends SyntaxError{constructor(e,t,n,r,i){super(getMessage(e,i)),this.index=t,this.lineNumber=n,this.column=r}};const $={EOF:-1,NULL:0,SOH:1,BACKSPACE:8,TABULATION:9,LINE_FEED:10,FORM_FEED:12,CARRIAGE_RETURN:13,ESCAPE:27,SO:14,US:31,SPACE:32,QUOTATION_MARK:34,HASH:35,SINGLE_QUOTE:39,PLUS_SIGN:43,COMMA:44,DASH:45,DOT:46,DIGIT_0:48,DIGIT_1:49,DIGIT_2:50,DIGIT_3:51,DIGIT_7:55,DIGIT_9:57,COLON:58,EQUALS_SIGN:61,LATIN_CAPITAL_A:65,LATIN_CAPITAL_E:69,LATIN_CAPITAL_F:70,LATIN_CAPITAL_T:84,LATIN_CAPITAL_U:85,LATIN_CAPITAL_Z:90,LEFT_BRACKET:91,BACKSLASH:92,RIGHT_BRACKET:93,UNDERSCORE:95,LATIN_SMALL_A:97,LATIN_SMALL_B:98,LATIN_SMALL_E:101,LATIN_SMALL_F:102,LATIN_SMALL_I:105,LATIN_SMALL_L:108,LATIN_SMALL_N:110,LATIN_SMALL_O:111,LATIN_SMALL_R:114,LATIN_SMALL_S:115,LATIN_SMALL_T:116,LATIN_SMALL_U:117,LATIN_SMALL_X:120,LATIN_SMALL_Z:122,LEFT_BRACE:123,RIGHT_BRACE:125,TILDE:126,DELETE:127,PAD:128,SUPERSCRIPT_TWO:178,SUPERSCRIPT_THREE:179,SUPERSCRIPT_ONE:185,VULGAR_FRACTION_ONE_QUARTER:188,VULGAR_FRACTION_THREE_QUARTERS:190,LATIN_CAPITAL_LETTER_A_WITH_GRAVE:192,LATIN_CAPITAL_LETTER_O_WITH_DIAERESIS:214,LATIN_CAPITAL_LETTER_O_WITH_STROKE:216,LATIN_SMALL_LETTER_O_WITH_DIAERESIS:246,LATIN_SMALL_LETTER_O_WITH_STROKE:248,GREEK_SMALL_REVERSED_DOTTED_LUNATE_SIGMA_SYMBOL:891,GREEK_CAPITAL_LETTER_YOT:895,CP_1FFF:8191,ZERO_WIDTH_NON_JOINER:8204,ZERO_WIDTH_JOINER:8205,UNDERTIE:8255,CHARACTER_TIE:8256,SUPERSCRIPT_ZERO:8304,CP_218F:8591,CIRCLED_DIGIT_ONE:9312,NEGATIVE_CIRCLED_DIGIT_ZERO:9471,GLAGOLITIC_CAPITAL_LETTER_AZU:11264,CP_2FEF:12271,IDEOGRAPHIC_COMMA:12289,CP_D7FF:55295,CP_E000:57344,CJK_COMPATIBILITY_IDEOGRAPH_F900:63744,ARABIC_LIGATURE_SALAAMUHU_ALAYNAA:64975,ARABIC_LIGATURE_SALLA_USED_AS_KORANIC_STOP_SIGN_ISOLATED_FORM:65008,REPLACEMENT_CHARACTER:65533,LINEAR_B_SYLLABLE_B008_A:65536,CP_EFFFF:983039,CP_10FFFF:1114111};function isControl(e){return e>=$.NULL&&e<=$.US}function isWhitespace(e){return e===$.TABULATION||e===$.SPACE}function isEOL(e){return e===$.LINE_FEED||e===$.CARRIAGE_RETURN}function isUpperLetter(e){return e>=$.LATIN_CAPITAL_A&&e<=$.LATIN_CAPITAL_Z}function isLowerLetter(e){return e>=$.LATIN_SMALL_A&&e<=$.LATIN_SMALL_Z}function isLetter(e){return isLowerLetter(e)||isUpperLetter(e)}function isDigit$1(e){return e>=$.DIGIT_0&&e<=$.DIGIT_9}__name(isDigit$1,`isDigit`);function isHexDig(e){return isDigit$1(e)||e>=$.LATIN_SMALL_A&&e<=$.LATIN_SMALL_F||e>=$.LATIN_CAPITAL_A&&e<=$.LATIN_CAPITAL_F}function isOctalDig(e){return e>=$.DIGIT_0&&e<=$.DIGIT_7}function isUnicodeScalarValue(e){return e>=0&&e<=55295||e>=57344&&e<=1114111}function sortedLastIndex(e,t){let n=0,r=e.length;for(;n<r;){let i=n+r>>>1,a=e[i];if(a===t)return i+1;a<t?n=i+1:r=i}return n}var Locations=class{constructor(){this.offsets=[]}addOffset(e){for(let t=this.offsets.length-1;t>=0;t--){let n=this.offsets[t];if(n===e)return;if(n<e)break}this.offsets.push(e)}getLocFromIndex(e){let t=sortedLastIndex(this.offsets,e)+1;return{line:t,column:e-(t===1?0:this.offsets[t-2])}}},CodePointIterator=class{constructor(e){this.locs=new Locations,this.lastCodePoint=$.NULL,this.start=-1,this.end=0,this.text=e}next(){return this.lastCodePoint===$.EOF?$.EOF:this.lastCodePoint=this.moveAt(this.end)}getLocFromIndex(e){return this.locs.getLocFromIndex(e)}eat(e){return this.text.codePointAt(this.end)===e&&(this.next(),!0)}moveAt(e){this.start=this.end=e;let t=this.text.codePointAt(this.start)??$.EOF;if(t===$.EOF)return this.end=this.start,t;if(this.end+=t>=65536?2:1,t===$.LINE_FEED)this.locs.addOffset(this.end);else if(t===$.CARRIAGE_RETURN)return this.text.codePointAt(this.end)===$.LINE_FEED&&(this.end++,this.locs.addOffset(this.end)),$.LINE_FEED;return t}};const oi=typeof BigInt<`u`,si={16:`0x`,10:``,8:`0o`,2:`0b`},ci={[$.QUOTATION_MARK]:$.QUOTATION_MARK,[$.BACKSLASH]:$.BACKSLASH,[$.LATIN_SMALL_B]:$.BACKSPACE,[$.LATIN_SMALL_F]:$.FORM_FEED,[$.LATIN_SMALL_N]:$.LINE_FEED,[$.LATIN_SMALL_R]:$.CARRIAGE_RETURN,[$.LATIN_SMALL_T]:$.TABULATION},li={...ci,[$.LATIN_SMALL_E]:$.ESCAPE};var Tokenizer=class{constructor(e,t){this.backCode=!1,this.lastCodePoint=$.NULL,this.state=`DATA`,this.token=null,this.tokenStart=-1,this.valuesEnabled=!1,this.text=e,this.parserOptions=t||{},this.codePointIterator=new CodePointIterator(e),this.tomlVersion=getTOMLVer(this.parserOptions.tomlVersion),this.ESCAPES=this.tomlVersion.gte(1,1)?li:ci}get start(){return this.codePointIterator.start}get end(){return this.codePointIterator.end}getLocFromIndex(e){return this.codePointIterator.getLocFromIndex(e)}reportParseError(e,t){let n=this.codePointIterator.start,r=this.codePointIterator.getLocFromIndex(n);throw new ParseError(e,n,r.line,r.column,t)}nextToken(){let e=this.token;if(e!=null)return this.token=null,e;let t=this.lastCodePoint;for(;t!==$.EOF&&!this.token;){t=this.nextCode();let e=this[this.state](t);if(!e)throw Error(`Unknown error: pre state=${this.state}`);this.state=e}return e=this.token,this.token=null,e}nextCode(){return this.lastCodePoint===$.EOF?$.EOF:this.backCode?(this.backCode=!1,this.lastCodePoint):this.lastCodePoint=this.codePointIterator.next()}eatCode(e){return this.lastCodePoint===$.EOF?!1:this.backCode?this.lastCodePoint===e&&(this.backCode=!1,!0):this.codePointIterator.eat(e)}moveAt(e){this.backCode&&=!1,this.lastCodePoint=this.codePointIterator.moveAt(e)}back(e){return this.backCode=!0,e}punctuatorToken(){this.startToken(),this.endToken(`Punctuator`,`end`)}startToken(){this.tokenStart=this.codePointIterator.start}endToken(e,t,n,r){let{tokenStart:i}=this,a=this.codePointIterator[t],o=[i,a],s={start:this.codePointIterator.getLocFromIndex(i),end:this.codePointIterator.getLocFromIndex(a)};if(e===`Block`)this.token={type:e,value:this.text.slice(i+1,a),range:o,loc:s};else{let t,c=this.text.slice(i,a);if(e===`BasicString`||e===`LiteralString`||e===`MultiLineBasicString`||e===`MultiLineLiteralString`)t={type:e,value:c,string:n,range:o,loc:s};else if(e===`Integer`){let i=n;t={type:e,value:c,number:parseInt(i,r),bigint:oi?BigInt(si[r]+i):null,range:o,loc:s}}else t=e===`Float`?{type:e,value:c,number:n,range:o,loc:s}:e===`Boolean`?{type:e,value:c,boolean:n,range:o,loc:s}:e===`LocalDate`||e===`LocalTime`||e===`LocalDateTime`||e===`OffsetDateTime`?{type:e,value:c,date:n,range:o,loc:s}:{type:e,value:c,range:o,loc:s};this.token=t}}DATA(e){for(;isWhitespace(e)||isEOL(e);)e=this.nextCode();if(e===$.HASH)return this.startToken(),`COMMENT`;if(e===$.QUOTATION_MARK)return this.startToken(),`BASIC_STRING`;if(e===$.SINGLE_QUOTE)return this.startToken(),`LITERAL_STRING`;if(e===$.DOT||e===$.EQUALS_SIGN||e===$.LEFT_BRACKET||e===$.RIGHT_BRACKET||e===$.LEFT_BRACE||e===$.RIGHT_BRACE||e===$.COMMA)return this.punctuatorToken(),`DATA`;if(this.valuesEnabled){if(e===$.DASH||e===$.PLUS_SIGN)return this.startToken(),`SIGN`;if(e===$.LATIN_SMALL_N||e===$.LATIN_SMALL_I)return this.startToken(),this.back(`NAN_OR_INF`);if(isDigit$1(e))return this.startToken(),this.back(`NUMBER`);if(e===$.LATIN_SMALL_T||e===$.LATIN_SMALL_F)return this.startToken(),this.back(`BOOLEAN`)}else if(isUnquotedKeyChar(e,this.tomlVersion))return this.startToken(),`BARE`;return e===$.EOF?`DATA`:this.reportParseError(`unexpected-char`)}COMMENT(e){let t=this.tomlVersion.gte(1,1)?e=>{isNonEOL(e)||this.reportParseError(`invalid-comment-character`,{cp:JSON.stringify(String.fromCodePoint(e)).slice(1,-1)})}:e=>{isControlOtherThanTab(e)&&this.reportParseErrorControlChar()};for(;!isEOL(e)&&e!==$.EOF;)t(e),e=this.nextCode();return this.endToken(`Block`,`start`),`DATA`}BARE(e){for(;isUnquotedKeyChar(e,this.tomlVersion);)e=this.nextCode();return this.endToken(`Bare`,`start`),this.back(`DATA`)}BASIC_STRING(e){if(e===$.QUOTATION_MARK)return e=this.nextCode(),e===$.QUOTATION_MARK?`MULTI_LINE_BASIC_STRING`:(this.endToken(`BasicString`,`start`,``),this.back(`DATA`));let t=[];for(;e!==$.QUOTATION_MARK&&e!==$.EOF&&e!==$.LINE_FEED;){if(isControlOtherThanTab(e))return this.reportParseErrorControlChar();if(e===$.BACKSLASH){e=this.nextCode();let n=this.ESCAPES[e];if(n){t.push(n),e=this.nextCode();continue}if(e===$.LATIN_SMALL_U){let n=this.parseUnicode(4);t.push(n),e=this.nextCode();continue}if(e===$.LATIN_CAPITAL_U){let n=this.parseUnicode(8);t.push(n),e=this.nextCode();continue}if(e===$.LATIN_SMALL_X&&this.tomlVersion.gte(1,1)){let n=this.parseUnicode(2);t.push(n),e=this.nextCode();continue}return this.reportParseError(`invalid-char-in-escape-sequence`)}t.push(e),e=this.nextCode()}return e===$.QUOTATION_MARK?(this.endToken(`BasicString`,`end`,String.fromCodePoint(...t)),`DATA`):this.reportParseError(`unterminated-string`)}MULTI_LINE_BASIC_STRING(e){let t=[];for(e===$.LINE_FEED&&(e=this.nextCode());e!==$.EOF;){if(e!==$.LINE_FEED&&isControlOtherThanTab(e))return this.reportParseErrorControlChar();if(e===$.QUOTATION_MARK){let e=this.codePointIterator.start;if(this.eatCode($.QUOTATION_MARK)&&this.eatCode($.QUOTATION_MARK))return this.eatCode($.QUOTATION_MARK)&&(t.push($.QUOTATION_MARK),this.eatCode($.QUOTATION_MARK)&&(t.push($.QUOTATION_MARK),this.eatCode($.QUOTATION_MARK)))?(this.moveAt(e),this.reportParseError(`invalid-three-quotes`)):(this.endToken(`MultiLineBasicString`,`end`,String.fromCodePoint(...t)),`DATA`);this.moveAt(e)}if(e===$.BACKSLASH){e=this.nextCode();let n=this.ESCAPES[e];if(n){t.push(n),e=this.nextCode();continue}if(e===$.LATIN_SMALL_U){let n=this.parseUnicode(4);t.push(n),e=this.nextCode();continue}if(e===$.LATIN_CAPITAL_U){let n=this.parseUnicode(8);t.push(n),e=this.nextCode();continue}if(e===$.LATIN_SMALL_X&&this.tomlVersion.gte(1,1)){let n=this.parseUnicode(2);t.push(n),e=this.nextCode();continue}if(e===$.LINE_FEED){for(e=this.nextCode();isWhitespace(e)||e===$.LINE_FEED;)e=this.nextCode();continue}if(isWhitespace(e)){let t=!0,n=this.codePointIterator.start,r;for(;(r=this.nextCode())!==$.EOF&&r!==$.LINE_FEED;)if(!isWhitespace(r)){this.moveAt(n),t=!1;break}if(t){for(e=this.nextCode();isWhitespace(e)||e===$.LINE_FEED;)e=this.nextCode();continue}}return this.reportParseError(`invalid-char-in-escape-sequence`)}t.push(e),e=this.nextCode()}return this.reportParseError(`unterminated-string`)}LITERAL_STRING(e){if(e===$.SINGLE_QUOTE)return e=this.nextCode(),e===$.SINGLE_QUOTE?`MULTI_LINE_LITERAL_STRING`:(this.endToken(`LiteralString`,`start`,``),this.back(`DATA`));let t=[];for(;e!==$.SINGLE_QUOTE&&e!==$.EOF&&e!==$.LINE_FEED;){if(isControlOtherThanTab(e))return this.reportParseErrorControlChar();t.push(e),e=this.nextCode()}return e===$.SINGLE_QUOTE?(this.endToken(`LiteralString`,`end`,String.fromCodePoint(...t)),`DATA`):this.reportParseError(`unterminated-string`)}MULTI_LINE_LITERAL_STRING(e){let t=[];for(e===$.LINE_FEED&&(e=this.nextCode());e!==$.EOF;){if(e!==$.LINE_FEED&&isControlOtherThanTab(e))return this.reportParseErrorControlChar();if(e===$.SINGLE_QUOTE){let e=this.codePointIterator.start;if(this.eatCode($.SINGLE_QUOTE)&&this.eatCode($.SINGLE_QUOTE))return this.eatCode($.SINGLE_QUOTE)&&(t.push($.SINGLE_QUOTE),this.eatCode($.SINGLE_QUOTE)&&(t.push($.SINGLE_QUOTE),this.eatCode($.SINGLE_QUOTE)))?(this.moveAt(e),this.reportParseError(`invalid-three-quotes`)):(this.endToken(`MultiLineLiteralString`,`end`,String.fromCodePoint(...t)),`DATA`);this.moveAt(e)}t.push(e),e=this.nextCode()}return this.reportParseError(`unterminated-string`)}SIGN(e){return e===$.LATIN_SMALL_N||e===$.LATIN_SMALL_I?this.back(`NAN_OR_INF`):isDigit$1(e)?this.back(`NUMBER`):this.reportParseError(`unexpected-char`)}NAN_OR_INF(e){if(e===$.LATIN_SMALL_N){let e=this.codePointIterator.start;if(this.eatCode($.LATIN_SMALL_A)&&this.eatCode($.LATIN_SMALL_N))return this.endToken(`Float`,`end`,NaN),`DATA`;this.moveAt(e)}else if(e===$.LATIN_SMALL_I){let e=this.codePointIterator.start;if(this.eatCode($.LATIN_SMALL_N)&&this.eatCode($.LATIN_SMALL_F))return this.endToken(`Float`,`end`,this.text[this.tokenStart]===`-`?-1/0:1/0),`DATA`;this.moveAt(e)}return this.reportParseError(`unexpected-char`)}NUMBER(e){let t=this.text[this.tokenStart],n=t===`+`?$.PLUS_SIGN:t===`-`?$.DASH:$.NULL;if(e===$.DIGIT_0){if(n===$.NULL){let e=this.codePointIterator.start,t=this.nextCode();if(isDigit$1(t)){let n=this.nextCode();if(n===$.COLON)return this.data={hasDate:!1,year:0,month:0,day:0,hour:Number(String.fromCodePoint($.DIGIT_0,t)),minute:0,second:0},`TIME_MINUTE`;if(isDigit$1(n)){let e=this.nextCode();if(isDigit$1(e)&&this.eatCode($.DASH))return this.data={hasDate:!0,year:Number(String.fromCodePoint($.DIGIT_0,t,n,e)),month:0,day:0,hour:0,minute:0,second:0},`DATE_MONTH`}return this.moveAt(e),this.reportParseError(`invalid-leading-zero`)}this.moveAt(e)}return e=this.nextCode(),e===$.LATIN_SMALL_X||e===$.LATIN_SMALL_O||e===$.LATIN_SMALL_B?n===$.NULL?e===$.LATIN_SMALL_X?`HEX`:e===$.LATIN_SMALL_O?`OCTAL`:`BINARY`:this.reportParseError(`unexpected-char`):e===$.LATIN_SMALL_E||e===$.LATIN_CAPITAL_E?(this.data={minus:n===$.DASH,left:[$.DIGIT_0]},`EXPONENT_RIGHT`):e===$.DOT?(this.data={minus:n===$.DASH,absInt:[$.DIGIT_0]},`FRACTIONAL_RIGHT`):(this.endToken(`Integer`,`start`,`0`,10),this.back(`DATA`))}let{out:r,nextCp:i,hasUnderscore:a}=this.parseDigits(e,isDigit$1);return i===$.DASH&&n===$.NULL&&!a&&r.length===4?(this.data={hasDate:!0,year:Number(String.fromCodePoint(...r)),month:0,day:0,hour:0,minute:0,second:0},`DATE_MONTH`):i===$.COLON&&n===$.NULL&&!a&&r.length===2?(this.data={hasDate:!1,year:0,month:0,day:0,hour:Number(String.fromCodePoint(...r)),minute:0,second:0},`TIME_MINUTE`):i===$.LATIN_SMALL_E||i===$.LATIN_CAPITAL_E?(this.data={minus:n===$.DASH,left:r},`EXPONENT_RIGHT`):i===$.DOT?(this.data={minus:n===$.DASH,absInt:r},`FRACTIONAL_RIGHT`):(this.endToken(`Integer`,`start`,n===$.DASH?String.fromCodePoint($.DASH,...r):String.fromCodePoint(...r),10),this.back(`DATA`))}HEX(e){let{out:t}=this.parseDigits(e,isHexDig);return this.endToken(`Integer`,`start`,String.fromCodePoint(...t),16),this.back(`DATA`)}OCTAL(e){let{out:t}=this.parseDigits(e,isOctalDig);return this.endToken(`Integer`,`start`,String.fromCodePoint(...t),8),this.back(`DATA`)}BINARY(e){let{out:t}=this.parseDigits(e,e=>e===$.DIGIT_0||e===$.DIGIT_1);return this.endToken(`Integer`,`start`,String.fromCodePoint(...t),2),this.back(`DATA`)}FRACTIONAL_RIGHT(e){let{minus:t,absInt:n}=this.data,{out:r,nextCp:i}=this.parseDigits(e,isDigit$1),a=[...n,$.DOT,...r];if(i===$.LATIN_SMALL_E||i===$.LATIN_CAPITAL_E)return this.data={minus:t,left:a},`EXPONENT_RIGHT`;let o=Number(t?String.fromCodePoint($.DASH,...a):String.fromCodePoint(...a));return this.endToken(`Float`,`start`,o),this.back(`DATA`)}EXPONENT_RIGHT(e){let{left:t,minus:n}=this.data,r=!1;(e===$.DASH||e===$.PLUS_SIGN)&&(r=e===$.DASH,e=this.nextCode());let{out:i}=this.parseDigits(e,isDigit$1),a=i;r&&a.unshift($.DASH);let o=Number(n?String.fromCodePoint($.DASH,...t,$.LATIN_SMALL_E,...a):String.fromCodePoint(...t,$.LATIN_SMALL_E,...a));return this.endToken(`Float`,`start`,o),this.back(`DATA`)}BOOLEAN(e){if(e===$.LATIN_SMALL_T){let e=this.codePointIterator.start;if(this.eatCode($.LATIN_SMALL_R)&&this.eatCode($.LATIN_SMALL_U)&&this.eatCode($.LATIN_SMALL_E))return this.endToken(`Boolean`,`end`,!0),`DATA`;this.moveAt(e)}else if(e===$.LATIN_SMALL_F){let e=this.codePointIterator.start;if(this.eatCode($.LATIN_SMALL_A)&&this.eatCode($.LATIN_SMALL_L)&&this.eatCode($.LATIN_SMALL_S)&&this.eatCode($.LATIN_SMALL_E))return this.endToken(`Boolean`,`end`,!1),`DATA`;this.moveAt(e)}return this.reportParseError(`unexpected-char`)}DATE_MONTH(e){let t=this.codePointIterator.start;if(!isDigit$1(e)||(e=this.nextCode(),!isDigit$1(e))||(e=this.nextCode(),e!==$.DASH))return this.reportParseError(`unexpected-char`);let n=this.codePointIterator.start,r=this.data;return r.month=Number(this.text.slice(t,n)),`DATE_DAY`}DATE_DAY(e){let t=this.codePointIterator.start;if(!isDigit$1(e)||(e=this.nextCode(),!isDigit$1(e)))return this.reportParseError(`unexpected-char`);let n=this.codePointIterator.end,r=this.data;if(r.day=Number(this.text.slice(t,n)),!isValidDate(r.year,r.month,r.day))return this.reportParseError(`invalid-date`);if(e=this.nextCode(),e===$.LATIN_CAPITAL_T||e===$.LATIN_SMALL_T)return`TIME_HOUR`;if(e===$.SPACE){let e=this.codePointIterator.start;if(isDigit$1(this.nextCode())&&isDigit$1(this.nextCode()))return this.moveAt(e),`TIME_HOUR`;this.moveAt(e)}let i=getDateFromDateTimeData(r,``);return this.endToken(`LocalDate`,`start`,i),this.back(`DATA`)}TIME_HOUR(e){let t=this.codePointIterator.start;if(!isDigit$1(e)||(e=this.nextCode(),!isDigit$1(e))||(e=this.nextCode(),e!==$.COLON))return this.reportParseError(`unexpected-char`);let n=this.codePointIterator.start,r=this.data;return r.hour=Number(this.text.slice(t,n)),`TIME_MINUTE`}TIME_MINUTE(e){let t=this.codePointIterator.start;if(!isDigit$1(e)||(e=this.nextCode(),!isDigit$1(e)))return this.reportParseError(`unexpected-char`);let n=this.codePointIterator.end,r=this.data;return r.minute=Number(this.text.slice(t,n)),e=this.nextCode(),e===$.COLON?`TIME_SECOND`:this.tomlVersion.lt(1,1)?this.reportParseError(`unexpected-char`):isValidTime(r.hour,r.minute,r.second)?this.processTimeEnd(e,r):this.reportParseError(`invalid-time`)}TIME_SECOND(e){let t=this.codePointIterator.start;if(!isDigit$1(e)||(e=this.nextCode(),!isDigit$1(e)))return this.reportParseError(`unexpected-char`);let n=this.codePointIterator.end,r=this.data;return r.second=Number(this.text.slice(t,n)),isValidTime(r.hour,r.minute,r.second)?(e=this.nextCode(),e===$.DOT?`TIME_SEC_FRAC`:this.processTimeEnd(e,r)):this.reportParseError(`invalid-time`)}TIME_SEC_FRAC(e){if(!isDigit$1(e))return this.reportParseError(`unexpected-char`);let t=this.codePointIterator.start;for(;isDigit$1(e);)e=this.nextCode();let n=this.codePointIterator.start,r=this.data;return r.frac=this.text.slice(t,n),this.processTimeEnd(e,r)}processTimeEnd(e,t){if(t.hasDate){if(e===$.DASH||e===$.PLUS_SIGN)return t.offsetSign=e,`TIME_OFFSET`;if(e===$.LATIN_CAPITAL_Z||e===$.LATIN_SMALL_Z){let e=getDateFromDateTimeData(t,`Z`);return this.endToken(`OffsetDateTime`,`end`,e),`DATA`}let n=getDateFromDateTimeData(t,``);return this.endToken(`LocalDateTime`,`start`,n),this.back(`DATA`)}let n=getDateFromDateTimeData(t,``);return this.endToken(`LocalTime`,`start`,n),this.back(`DATA`)}TIME_OFFSET(e){if(!isDigit$1(e))return this.reportParseError(`unexpected-char`);let t=this.codePointIterator.start;if(e=this.nextCode(),!isDigit$1(e)||(e=this.nextCode(),e!==$.COLON))return this.reportParseError(`unexpected-char`);let n=this.codePointIterator.start;e=this.nextCode();let r=this.codePointIterator.start;if(!isDigit$1(e)||(e=this.nextCode(),!isDigit$1(e)))return this.reportParseError(`unexpected-char`);let i=this.codePointIterator.end,a=Number(this.text.slice(t,n)),o=Number(this.text.slice(r,i));if(!isValidTime(a,o,0))return this.reportParseError(`invalid-time`);let s=this.data,c=getDateFromDateTimeData(s,`${String.fromCodePoint(s.offsetSign)}${padStart(a,2)}:${padStart(o,2)}`);return this.endToken(`OffsetDateTime`,`end`,c),`DATA`}parseDigits(e,t){if(e===$.UNDERSCORE)return this.reportParseError(`invalid-underscore`);if(!t(e))return this.reportParseError(`unexpected-char`);let n=[],r=$.NULL,i=!1;for(;t(e)||e===$.UNDERSCORE;){if(e===$.UNDERSCORE){if(i=!0,r===$.UNDERSCORE)return this.reportParseError(`invalid-underscore`)}else n.push(e);r=e,e=this.nextCode()}return r===$.UNDERSCORE?this.reportParseError(`invalid-underscore`):{out:n,nextCp:e,hasUnderscore:i}}parseUnicode(e){let t=this.codePointIterator.start,n=this.codePointIterator.end,r=0,i;for(;(i=this.nextCode())!==$.EOF;){if(!isHexDig(i))return this.moveAt(t),this.reportParseError(`invalid-char-in-escape-sequence`);if(r++,r>=e)break}let a=this.codePointIterator.end,o=this.text.slice(n,a),s=parseInt(o,16);return isUnicodeScalarValue(s)?s:this.reportParseError(`invalid-code-point`,{cp:o})}reportParseErrorControlChar(){return this.reportParseError(`invalid-control-character`)}};function isUnquotedKeyChar(e,t){return isLetter(e)||isDigit$1(e)||e===$.UNDERSCORE||e===$.DASH?!0:(t.lt(1,1),!1)}function isControlOtherThanTab(e){return isControl(e)&&e!==$.TABULATION||e===$.DELETE}function isNonEOL(e){return e===$.TABULATION||$.SPACE<=e&&e<=$.TILDE||isNonAscii(e)}function isNonAscii(e){return $.PAD<=e&&e<=$.CP_D7FF||$.CP_E000<=e&&e<=$.CP_10FFFF}function isValidDate(e,t,n){return e>=0&&t<=12&&t>=1&&n>=1&&n<=(t===2?e&3||!(e%25)&&e&15?28:29:30+(t+(t>>3)&1))}function isValidTime(e,t,n){return!(e>=24||e<0||t>59||t<0||n>60||n<0)}function getDateFromDateTimeData(e,t){let n=padStart(e.year,4),r=e.month?padStart(e.month,2):`01`,i=e.day?padStart(e.day,2):`01`,a=padStart(e.hour,2),o=padStart(e.minute,2),s=padStart(e.second,2),c=`${n}-${r}-${i}`,l=e.frac?`.${e.frac}`:``,u=new Date(`${c}T${a}:${o}:${s}${l}${t}`);return!isNaN(u.getTime())||e.second!==60?u:new Date(`${c}T${a}:${o}:59${l}${t}`)}function padStart(e,t){return String(e).padStart(t,`0`)}const ui=Symbol(`VALUE_KIND_VALUE`),di=Symbol(`VALUE_KIND_INTERMEDIATE`);var KeysResolver=class{constructor(e){this.rootKeys=new Map,this.tables=[],this.ctx=e}applyResolveKeyForTable(e){let t=this.rootKeys,n=e.key.keys.length-1;for(let r=0;r<n;r++){let n=e.key.keys[r],i=toKeyName(n);e.resolvedKey.push(i);let a=t.get(i);if(!a)a={node:n,keys:new Map},t.set(i,a);else if(a.table===`array`){let t=a.peekIndex;e.resolvedKey.push(t),a=a.keys.get(t)}t=a.keys}let r=e.key.keys[n],i=toKeyName(r);e.resolvedKey.push(i);let a=t.get(i);if(!a){if(e.kind===`array`){e.resolvedKey.push(0);let n={node:r,keys:new Map};t.set(i,{table:e.kind,node:r,keys:new Map([[0,n]]),peekIndex:0}),this.tables.push({node:e,keys:n.keys})}else{let n={table:e.kind,node:r,keys:new Map};t.set(i,n),this.tables.push({node:e,keys:n.keys})}}else if(!a.table){if(e.kind===`array`)this.ctx.reportParseError(`dupe-keys`,r);else{let n={table:e.kind,node:r,keys:a.keys};t.set(i,n),this.tables.push({node:e,keys:n.keys})}}else if(a.table===`array`){if(e.kind===`array`){let t={node:r,keys:new Map},n=a.peekIndex+1;e.resolvedKey.push(n),a.keys.set(n,t),a.peekIndex=n,this.tables.push({node:e,keys:t.keys})}else this.ctx.reportParseError(`dupe-keys`,r)}else this.ctx.reportParseError(`dupe-keys`,r)}verifyDuplicateKeys(e){for(let t of e.body)t.type===`TOMLKeyValue`&&verifyDuplicateKeysForKeyValue(this.ctx,this.rootKeys,t);for(let{node:e,keys:t}of this.tables)for(let n of e.body)verifyDuplicateKeysForKeyValue(this.ctx,t,n)}};function verifyDuplicateKeysForKeyValue(e,t,n){let r=t,i=last(n.key.keys);for(let t of n.key.keys){let n=toKeyName(t),a=r.get(n);a?((a.value===ui||i===t||a.table)&&e.reportParseError(`dupe-keys`,getAfterNode(t,a.node)),a.value=di):(a=i===t?{value:ui,node:t,keys:new Map}:{value:di,node:t,keys:new Map},r.set(n,a)),r=a.keys}n.value.type===`TOMLInlineTable`?verifyDuplicateKeysForInlineTable(e,r,n.value):n.value.type===`TOMLArray`&&verifyDuplicateKeysForArray(e,r,n.value)}function verifyDuplicateKeysForInlineTable(e,t,n){for(let r of n.body)verifyDuplicateKeysForKeyValue(e,t,r)}function verifyDuplicateKeysForArray(e,t,n){let r=t;for(let i=0;i<n.elements.length;i++){let a=n.elements[i],o=r.get(i);o?e.reportParseError(`dupe-keys`,getAfterNode(a,o.node)):(o={value:ui,node:a,keys:new Map},t.set(i,o),a.type===`TOMLInlineTable`?verifyDuplicateKeysForInlineTable(e,o.keys,a):a.type===`TOMLArray`&&verifyDuplicateKeysForArray(e,o.keys,a))}}function getAfterNode(e,t){return e.range[0]<=t.range[0]?t:e}var Context=class{constructor(e){this.tokens=[],this.comments=[],this.back=null,this.stateStack=[],this.needNewLine=!1,this.needSameLine=!1,this.currToken=null,this.prevToken=null,this.valueContainerStack=[],this.tokenizer=new Tokenizer(e.text,e.parserOptions),this.topLevelTable=e.topLevelTable,this.table=e.topLevelTable,this.keysResolver=new KeysResolver(this)}nextToken(e){if(this.prevToken=this.currToken,this.back?(this.currToken=this.back,this.back=null):this.currToken=this._nextTokenFromTokenizer(e),(this.needNewLine||this.needSameLine||e?.needSameLine)&&this.prevToken&&this.currToken){if(this.prevToken.loc.end.line===this.currToken.loc.start.line){if(this.needNewLine)return this.reportParseError(`missing-newline`,this.currToken)}else{let t=this.needSameLine||e?.needSameLine;if(t)return this.reportParseError(t,this.currToken)}}return this.needNewLine=!1,this.needSameLine=!1,this.currToken}_nextTokenFromTokenizer(e){let t=this.tokenizer.valuesEnabled;e?.valuesEnabled&&(this.tokenizer.valuesEnabled=e.valuesEnabled);let n=this.tokenizer.nextToken();for(;n&&n.type===`Block`;)this.comments.push(n),n=this.tokenizer.nextToken();return n&&this.tokens.push(n),this.tokenizer.valuesEnabled=t,n}backToken(){if(this.back)throw Error(`Illegal state`);this.back=this.currToken,this.currToken=this.prevToken}addValueContainer(e){this.valueContainerStack.push(e),this.tokenizer.valuesEnabled=!0}consumeValueContainer(){let e=this.valueContainerStack.pop();return this.tokenizer.valuesEnabled=this.valueContainerStack.length>0,e}applyResolveKeyForTable(e){this.keysResolver.applyResolveKeyForTable(e)}verifyDuplicateKeys(){this.keysResolver.verifyDuplicateKeys(this.topLevelTable)}reportParseError(e,t){let n,r,i;if(t)n=t.range[0],r=t.loc.start.line,i=t.loc.start.column;else{n=this.tokenizer.start;let e=this.tokenizer.getLocFromIndex(n);r=e.line,i=e.column}throw new ParseError(e,n,r,i)}};const fi={VALUE:`missing-value`},pi={BasicString:`basic`,MultiLineBasicString:`basic`,LiteralString:`literal`,MultiLineLiteralString:`literal`},mi={BasicString:`basic`,LiteralString:`literal`},hi={OffsetDateTime:`offset-date-time`,LocalDateTime:`local-date-time`,LocalDate:`local-date`,LocalTime:`local-time`};var TOMLParser=class{constructor(e,t){this.text=e,this.parserOptions=t||{},this.tomlVersion=getTOMLVer(this.parserOptions.tomlVersion)}parse(){let e={type:`Program`,body:[],sourceType:`module`,tokens:[],comments:[],parent:null,range:[0,0],loc:{start:{line:1,column:0},end:{line:1,column:0}}},t={type:`TOMLTopLevelTable`,body:[],parent:e,range:cloneRange(e.range),loc:cloneLoc(e.loc)};e.body=[t];let n=new Context({text:this.text,parserOptions:this.parserOptions,topLevelTable:t}),r=n.nextToken();if(r){for(t.range[0]=r.range[0],t.loc.start=clonePos(r.loc.start);r;){let e=n.stateStack.pop()||`TABLE`;n.stateStack.push(...this[e](r,n)),r=n.nextToken()}let e=n.stateStack.pop()||`TABLE`;if(e in fi)return n.reportParseError(fi[e],null);n.table.type===`TOMLTable`&&applyEndLoc(n.table,last(n.table.body)),applyEndLoc(t,last(t.body))}n.verifyDuplicateKeys(),e.tokens=n.tokens,e.comments=n.comments;let i=n.tokenizer.end,a=n.tokenizer.getLocFromIndex(i);return e.range[1]=i,e.loc.end={line:a.line,column:a.column},e}TABLE(e,t){return isBare(e)||isString(e)?this.processKeyValue(e,t.table,t):isLeftBracket(e)?this.processTable(e,t.topLevelTable,t):t.reportParseError(`unexpected-token`,e)}VALUE(e,t){return isString(e)||isMultiLineString(e)?this.processStringValue(e,t):isNumber(e)?this.processNumberValue(e,t):isBoolean(e)?this.processBooleanValue(e,t):isDateTime(e)?this.processDateTimeValue(e,t):isLeftBracket(e)?this.processArray(e,t):isLeftBrace(e)?this.processInlineTable(e,t):t.reportParseError(`unexpected-token`,e)}processTable(e,t,n){let r={type:`TOMLTable`,kind:`standard`,key:null,resolvedKey:[],body:[],parent:t,range:cloneRange(e.range),loc:cloneLoc(e.loc)};n.table.type===`TOMLTable`&&applyEndLoc(n.table,last(n.table.body)),t.body.push(r),n.table=r;let i=n.nextToken({needSameLine:`invalid-key-value-newline`});if(isLeftBracket(i)){if(e.range[1]<i.range[0])return n.reportParseError(`invalid-space`,i);r.kind=`array`,i=n.nextToken({needSameLine:`invalid-key-value-newline`})}if(isRightBracket(i))return n.reportParseError(`missing-key`,i);if(!i)return n.reportParseError(`unterminated-table-key`,null);if(i=this.processKeyNode(i,r,n).nextToken,!isRightBracket(i))return n.reportParseError(`unterminated-table-key`,i);if(r.kind===`array`){let e=i;if(i=n.nextToken({needSameLine:`invalid-key-value-newline`}),!isRightBracket(i))return n.reportParseError(`unterminated-table-key`,i);if(e.range[1]<i.range[0])return n.reportParseError(`invalid-space`,i)}return applyEndLoc(r,i),n.applyResolveKeyForTable(r),n.needNewLine=!0,[]}processKeyValue(e,t,n){let r={type:`TOMLKeyValue`,key:null,value:null,parent:t,range:cloneRange(e.range),loc:cloneLoc(e.loc)};t.body.push(r);let{nextToken:i}=this.processKeyNode(e,r,n);return isEq(i)?(n.addValueContainer({parent:r,set:e=>(r.value=e,applyEndLoc(r,e),n.needNewLine=!0,[])}),n.needSameLine=`invalid-key-value-newline`,[`VALUE`]):n.reportParseError(`missing-equals-sign`,i)}processKeyNode(e,t,n){isDot(e)&&n.reportParseError(`invalid-leading-dot-in-key`,e);let r={type:`TOMLKey`,keys:[],parent:t,range:cloneRange(e.range),loc:cloneLoc(e.loc)};t.key=r;let i=e,a=null;do{if(isBare(i))this.processBareKey(i,r);else if(isString(i))this.processStringKey(i,r);else break;if(a=null,i=n.nextToken({needSameLine:`invalid-key-value-newline`}),!isDot(i))break;a=i,i=n.nextToken({needSameLine:`invalid-key-value-newline`})}while(i);return a&&n.reportParseError(isDot(i)?`invalid-consecutive-dots-in-key`:`invalid-trailing-dot-in-key`,a),applyEndLoc(r,last(r.keys)),{keyNode:r,nextToken:i}}processBareKey(e,t){let n={type:`TOMLBare`,name:e.value,parent:t,range:cloneRange(e.range),loc:cloneLoc(e.loc)};t.keys.push(n)}processStringKey(e,t){let n={type:`TOMLQuoted`,kind:`string`,value:e.string,style:mi[e.type],multiline:!1,parent:t,range:cloneRange(e.range),loc:cloneLoc(e.loc)};t.keys.push(n)}processStringValue(e,t){let n=t.consumeValueContainer(),r={type:`TOMLValue`,kind:`string`,value:e.string,style:pi[e.type],multiline:isMultiLineString(e),parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)};return n.set(r)}processNumberValue(e,t){let n=t.consumeValueContainer(),r=this.text,[i,a]=e.range,o=null,getNumberText=()=>o??=r.slice(i,a).replace(/_/g,``),s;return s=e.type===`Integer`?{type:`TOMLValue`,kind:`integer`,value:e.number,bigint:e.bigint,get number(){return getNumberText()},parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)}:{type:`TOMLValue`,kind:`float`,value:e.number,get number(){return getNumberText()},parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)},n.set(s)}processBooleanValue(e,t){let n=t.consumeValueContainer(),r={type:`TOMLValue`,kind:`boolean`,value:e.boolean,parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)};return n.set(r)}processDateTimeValue(e,t){let n=t.consumeValueContainer(),r={type:`TOMLValue`,kind:hi[e.type],value:e.date,datetime:e.value,parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)};return n.set(r)}processArray(e,t){let n=t.consumeValueContainer(),r={type:`TOMLArray`,elements:[],parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)},i=t.nextToken({valuesEnabled:!0});return isRightBracket(i)?(applyEndLoc(r,i),n.set(r)):(t.backToken(),this.processArrayValue(r,n,t))}processArrayValue(e,t,n){return n.addValueContainer({parent:e,set:r=>{e.elements.push(r);let i=n.nextToken({valuesEnabled:!0}),a=isComma(i);return a&&(i=n.nextToken({valuesEnabled:!0})),isRightBracket(i)?(applyEndLoc(e,i),t.set(e)):a?(n.backToken(),this.processArrayValue(e,t,n)):n.reportParseError(i?`missing-comma`:`unterminated-array`,i)}}),[`VALUE`]}processInlineTable(e,t){let n=t.consumeValueContainer(),r={type:`TOMLInlineTable`,body:[],parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)},i=this.tomlVersion.gte(1,1)?void 0:`invalid-inline-table-newline`,a=t.nextToken({needSameLine:i});if(a){if(isBare(a)||isString(a))return this.processInlineTableKeyValue(a,r,n,t);if(isRightBrace(a))return applyEndLoc(r,a),n.set(r)}return t.reportParseError(`unexpected-token`,a)}processInlineTableKeyValue(e,t,n,r){let i={type:`TOMLKeyValue`,key:null,value:null,parent:t,range:cloneRange(e.range),loc:cloneLoc(e.loc)};t.body.push(i);let{nextToken:a}=this.processKeyNode(e,i,r);if(!isEq(a))return r.reportParseError(`missing-equals-sign`,a);let o=this.tomlVersion.gte(1,1)?void 0:`invalid-inline-table-newline`;return r.addValueContainer({parent:i,set:e=>{i.value=e,applyEndLoc(i,e);let a=r.nextToken({needSameLine:o});if(isComma(a)){if(a=r.nextToken({needSameLine:o}),a&&(isBare(a)||isString(a)))return this.processInlineTableKeyValue(a,t,n,r);if(isRightBrace(a)){if(this.tomlVersion.lt(1,1))return r.reportParseError(`invalid-trailing-comma-in-inline-table`,a)}else return r.reportParseError(a?`unexpected-token`:`unterminated-inline-table`,a)}return isRightBrace(a)?(applyEndLoc(t,a),n.set(t)):r.reportParseError(a?`missing-comma`:`unterminated-inline-table`,a)}}),r.needSameLine=`invalid-key-value-newline`,[`VALUE`]}};function isDot(e){return isPunctuator(e)&&e.value===`.`}function isEq(e){return isPunctuator(e)&&e.value===`=`}function isLeftBracket(e){return isPunctuator(e)&&e.value===`[`}function isRightBracket(e){return isPunctuator(e)&&e.value===`]`}function isLeftBrace(e){return isPunctuator(e)&&e.value===`{`}function isRightBrace(e){return isPunctuator(e)&&e.value===`}`}function isComma(e){return isPunctuator(e)&&e.value===`,`}function isPunctuator(e){return!!(e&&e.type===`Punctuator`)}function isBare(e){return e.type===`Bare`}function isString(e){return e.type===`BasicString`||e.type===`LiteralString`}function isMultiLineString(e){return e.type===`MultiLineBasicString`||e.type===`MultiLineLiteralString`}function isNumber(e){return e.type===`Integer`||e.type===`Float`}function isBoolean(e){return e.type===`Boolean`}function isDateTime(e){return e.type===`OffsetDateTime`||e.type===`LocalDateTime`||e.type===`LocalDate`||e.type===`LocalTime`}function applyEndLoc(e,t){t&&(e.range[1]=t.range[1],e.loc.end=clonePos(t.loc.end))}function cloneRange(e){return[e[0],e[1]]}function cloneLoc(e){return{start:clonePos(e.start),end:clonePos(e.end)}}function clonePos(e){return{line:e.line,column:e.column}}const gi=unionWith({Program:[`body`],TOMLTopLevelTable:[`body`],TOMLTable:[`key`,`body`],TOMLKeyValue:[`key`,`value`],TOMLKey:[`keys`],TOMLArray:[`elements`],TOMLInlineTable:[`body`],TOMLBare:[],TOMLQuoted:[],TOMLValue:[]});function parseForESLint(e,t){return{ast:new TOMLParser(e,t).parse(),visitorKeys:gi,services:{isTOML:!0}}}function parseTOML(e,t){return parseForESLint(e,t).ast}function nested(e,t){return e.reduceRight((e,t)=>({[t]:e}),t)}function renderTomlTable(e,t){return stringify(nested(e,t))}function appendTomlTable(e,t,n){return`${e}${e===``||e.endsWith(`
|
|
456
|
+
`)}`);let f=new Set(d.map(({harness:e})=>e.name));for(let{harness:e,target:r}of s)if(!f.has(e.name)&&(i(b(r),{recursive:!0}),!linksTo(r,n))){if(pathOccupied(r)&&u(r,{recursive:!0,force:!0}),a){t(n,r,{recursive:!0});continue}try{p(linkTarget(r,n),r,v()===`win32`?`junction`:void 0)}catch(e){if(pathOccupied(r))throw e;t(n,r,{recursive:!0})}}return{linked:s.filter(({harness:e})=>!f.has(e.name)).map(({harness:e})=>e.name),skipped:s.filter(({harness:e})=>f.has(e.name)).map(({harness:e})=>e.name)}}function isDirectory$1(e){try{return r(e).isDirectory()}catch{return!1}}__name(isDirectory$1,`isDirectory`);function exists$1(e){try{return r(e),!0}catch{return!1}}__name(exists$1,`exists`);function importsGlobal(e,t,n){let r=t.kind===`import`?[t.line,`@${C(n,Wn)}`]:[];return e.split(`
|
|
457
|
+
`).some(e=>r.includes(e.trim()))}function base(e,t,n){let r=e.relocatedBy,i=r===void 0?void 0:t[r];return r===void 0||i===void 0?{}:i===``?e.emptyRelocatesToStart?{moved:{root:n,display:`.`},emptied:r}:{}:{moved:{root:E(i),display:`$${r}`}}}function locate(e,t,{moved:n},r){if(!n||r!==t.detect&&!r.startsWith(`${t.detect}/`))return{absolute:C(e,r),display:`~/${r}`};let i=r.slice(t.detect.length);return{absolute:C(n.root,i),display:`${n.display}${i}`}}function readsAsShadow(e){try{return f(e).isFile()&&a(e,`utf8`).trim()!==``}catch{return!1}}function inspect$2(e,t,n){let i;try{i=r(t)}catch{return{kind:`none`,status:`missing`,problem:`global-instructions-missing`}}if(i.isSymbolicLink())return E(b(t),s(t))===C(e,`.agents/AGENTS.md`)?{kind:`symlink`,status:`ok`}:{kind:`symlink`,status:`unbridged`,problem:`global-instructions-unbridged`};let o;try{o=a(t,`utf8`)}catch{return{kind:`file`,status:`unbridged`,problem:`global-instructions-unbridged`}}return importsGlobal(o,n,e)?{kind:`import`,status:`ok`}:{kind:`file`,status:`unbridged`,problem:`global-instructions-unbridged`}}__name(inspect$2,`inspect`);function finding(e,t,n){let{detail:r,repair:i}=repairFor(t);return{path:e,problem:t,detail:r,repair:i({file:e},n)}}function diagnoseGlobalInstructions(e,t,n,r={},i=process.cwd()){let a=exists$1(C(e,Wn)),o=[],s=[];for(let c of Gn){let l=c.user,u=l?.instructionBridge;if(!l||!u)continue;let d=base(l,r,i);if(!t.includes(c.name)&&!isDirectory$1(locate(e,l,d,l.detect).absolute))continue;let f=locate(e,l,d,u.path),p=inspect$2(e,f.absolute,u),m=(l.shadowedBy??[]).map(t=>locate(e,l,d,t)).find(({absolute:e})=>readsAsShadow(e));if(m!==void 0){let t=inspect$2(e,m.absolute,u);if(t.status===`ok`){o.push({harness:c.name,path:m.display,kind:t.kind,status:`ok`});continue}o.push({harness:c.name,path:f.display,kind:p.kind,status:`overridden`}),a&&s.push(finding(m.display,`global-instructions-overridden`,n))}else o.push({harness:c.name,path:f.display,kind:p.kind,status:p.status});a&&d.emptied?s.push(finding(`$${d.emptied}`,`global-instructions-emptied`,n)):a&&p.problem&&s.push(finding(f.display,p.problem,n))}return{globalInstructions:o,findings:s}}const Jr=new Set([`node_modules`]);function agentsFileDirectories(e){let t=[],walk=r=>{n(C(e,r,`AGENTS.md`))&&t.push(r);let i;try{i=o(C(e,r),{withFileTypes:!0})}catch{return}for(let e of i)!e.isDirectory()||e.name.startsWith(`.`)||Jr.has(e.name)||walk(r?w.join(r,e.name):e.name)};return walk(``),t.sort()}const Yr=`AGENTS.md`;function valueAt(e,t){return t.split(`.`).reduce((e,t)=>{if(typeof e==`object`&&e)return e[t]},e)}function exists(e){try{return r(e),!0}catch{return!1}}function inspectSettingsEntry(e,t){let n;try{n=a(e,`utf8`)}catch{return{kind:`none`,status:`missing`,problem:`instructions-missing`}}let r=parseJsonWithComments(n);if(r===void 0)return{kind:`file`,status:`unreadable`,problem:`instructions-unreadable`};let i=valueAt(r,t);return Array.isArray(i)&&i.includes(`AGENTS.md`)?{kind:`settings-entry`,status:`ok`}:{kind:`file`,status:`unbridged`,problem:`instructions-unbridged`}}function inspectShadow(e){let t;try{t=r(e)}catch{return}if(t.isSymbolicLink())return s(e)===`AGENTS.md`?{kind:`symlink`,status:`superseded`,problem:`instructions-superseded`}:{kind:`symlink`,status:`shadowing`,problem:`instructions-shadowing`};let n;try{n=a(e,`utf8`)}catch{return{kind:`file`,status:`unreadable`,problem:`instructions-unreadable`}}return n.split(`
|
|
458
|
+
`).some(e=>e.trim()===`@AGENTS.md`)?{kind:`import`,status:`superseded`,problem:`instructions-superseded`}:{kind:`file`,status:`shadowing`,problem:`instructions-shadowing`}}function diagnoseInstructions(e,t,n){let r=t.map(e=>({name:e.name,bridge:e.project.instructionBridge})).filter(e=>e.bridge?.kind===`settings-entry`),i=[],a=[],o=agentsFileDirectories(e),s=t.some(t=>(t.project.shadowedBy??[]).some(t=>exists(C(e,t))));if((r.length||s)&&!o.includes(``)){let{detail:e,repair:t}=repairFor(`no-instructions`);a.push({path:Yr,problem:`no-instructions`,detail:e,repair:t({file:Yr},n)})}for(let{name:t,bridge:o}of r){let r=inspectSettingsEntry(C(e,o.path),o.key);if(i.push({harness:t,path:o.path,kind:r.kind,status:r.status}),r.problem){let{detail:e,repair:t}=repairFor(r.problem);a.push({path:o.path,problem:r.problem,detail:e,repair:t({file:o.path},n)})}}for(let r of t)for(let t of r.project.shadowedBy??[])for(let s of o){let o=s?w.join(s,t):t,c=inspectShadow(C(e,o));if(!c)continue;i.push({harness:r.name,path:o,kind:c.kind,status:c.status});let{detail:l,repair:u}=repairFor(c.problem);a.push({path:o,problem:c.problem,detail:l,repair:u({file:o},n)})}return{instructions:i,findings:a}}function git(e,t,n){try{return A(`git`,t,{cwd:e,encoding:`utf8`,...n===void 0?{}:{input:n},stdio:[`pipe`,`pipe`,`pipe`]})}catch{return}}function lines(e){return(e??``).split(`
|
|
459
|
+
`).filter(Boolean)}var GitBridgeState=class{root;repoRootPrefix;constructor(e){this.root=e,this.repoRootPrefix=git(e,[`rev-parse`,`--show-prefix`])?.trim()}isRepository(){return this.repoRootPrefix!==void 0}trackingOf(e){if(this.repoRootPrefix===void 0)return`untracked`;let t=lines(git(this.root,[`ls-files`,`-v`,`--`,e]));return t.length?t.every(e=>e.startsWith(`S`))?`skip-worktree`:`tracked`:`untracked`}isIgnored(e){return this.repoRootPrefix!==void 0&&git(this.root,[`check-ignore`,`-q`,`--`,e])!==void 0}commitsTouching(e){return this.repoRootPrefix===void 0?[]:lines(git(this.root,[`rev-list`,`-n`,`200`,`HEAD`,`--`,...e]))}contentAt(e,t){if(this.repoRootPrefix!==void 0)return git(this.root,[`show`,`${e}:${this.repoRootPrefix}${t}`])}directionOf(e,t){if(this.repoRootPrefix===void 0)return`unknown`;let n=this.lastAgreedTree(e,t);if(n===void 0)return`unknown`;let r=!this.matchesTree(e,n),i=!this.matchesTree(t,n);return r&&i?`both`:r?`bridge`:`canonical`}lastAgreedTree(e,t){for(let n of lines(git(this.root,[`rev-list`,`-n`,`200`,`HEAD`,`--`,e,t]))){let r=git(this.root,[`rev-parse`,`-q`,`--verify`,`${n}:${this.repoRootPrefix}${e}`])?.trim();if(r&&r===git(this.root,[`rev-parse`,`-q`,`--verify`,`${n}:${this.repoRootPrefix}${t}`])?.trim())return r}}matchesTree(e,t){let n=new Map(lines(git(this.root,[`ls-tree`,`-r`,t])).map(e=>{let[t,n]=e.split(` `);return[n,t.split(` `)[2]]})),r=filesUnder(C(this.root,e));if(r.length!==n.size||r.some(e=>!n.has(e)))return!1;let i=lines(git(this.root,[`hash-object`,`--stdin-paths`],r.map(t=>C(e,t)).join(`
|
|
460
|
+
`)));return i.length===r.length&&r.every((e,t)=>n.get(e)===i[t])}};const Xr=`.agents/skills`;function pathState(e){try{let t=r(e);return t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`}catch{return`missing`}}function isDirectory(e){try{return f(e).isDirectory()}catch{return!1}}function sameContent(e,t){let n=filesUnder(e),r=filesUnder(t);return n.length===r.length&&n.every((n,i)=>r[i]===n&&a(C(e,n)).equals(a(C(t,n))))}function inspect$1(e,t,n,r){switch(pathState(e)){case`missing`:return{kind:`none`,status:`missing`,problem:`missing`};case`file`:return{kind:`file`,status:`degraded`,problem:`degraded`};case`symlink`:return linksTo(e,n)?{kind:`symlink`,status:`ok`}:{kind:`symlink`,status:`stale`,problem:`stale`};default:if(!sameContent(e,n)){let e=r.directionOf(t,Xr);return{kind:`copy`,status:`diverged`,problem:`diverged-${e}`,direction:e}}return r.trackingOf(t)===`tracked`?{kind:`copy`,status:`ok`,problem:`unpinned-copy`}:{kind:`copy`,status:`ok`}}}__name(inspect$1,`inspect`);function diagnoseBridges({root:e,harnesses:t=[],cli:n,home:r,env:i}){let a=C(e,`.agents`,`skills`),o=new GitBridgeState(e),s=selectHarnesses(e,t),c=s.map(e=>({name:e.name,skillsDirectory:e.project.skillsDirectory})).filter(e=>!!e.skillsDirectory),l=[],u=[],d=[];if(!isDirectory(a)){let{detail:e,repair:t}=repairFor(`no-canonical`);d.push({path:Xr,problem:`no-canonical`,detail:e,repair:t({file:Xr},n)})}for(let t of c){let r=t.skillsDirectory,i=inspect$1(C(e,r),r,a,o);if(l.push({harness:t.name,path:r,kind:i.kind,status:i.status}),i.direction&&u.push({path:r,direction:i.direction}),i.problem){let{detail:e,repair:t}=repairFor(i.problem);d.push({path:r,problem:i.problem,detail:e,repair:t({file:r},n)})}}let f=diagnoseInstructions(e,s,n);d.push(...f.findings);let p=r===void 0?{globalInstructions:[],findings:[]}:diagnoseGlobalInstructions(r,t,n,i,e);return d.push(...p.findings),{bridges:l,instructions:f.instructions,globalInstructions:p.globalInstructions,divergence:u,findings:d}}function buildDoctorReport(e,t,n=[],r=[]){let i=[...t.findings,...n],a=r.length?r:`0 references — no layer outside the plugin tier holds one`;if(!i.length){let n=t.bridges.length+t.instructions.length,r=n===1?`the 1 bridge resolves`:`all ${n} bridges resolve`;return{bin:e,bridges:t.bridges,instructions:t.instructions,globalInstructions:t.globalInstructions,references:a,findings:`0 problems found — ${r} and the configuration around them is current`}}return{bin:e,bridges:t.bridges,instructions:t.instructions,globalInstructions:t.globalInstructions,references:a,...t.divergence.length?{divergence:t.divergence}:{},findings:i.map(({path:e,problem:t,detail:n})=>({path:e,problem:t,detail:n})),help:[...new Map(i.map(e=>[`${e.repair.command}\u0000${e.repair.instruction}`,e.repair])).values()]}}const Zr={root:{description:`Repository or package directory. Defaults to the current directory.`,type:N.string().optional()},harness:{description:`Comma-separated harnesses to check in addition to Claude Code and Cursor, e.g. codex,gemini-cli.`,type:N.string().optional()}};async function diagnoseReport(e){try{let t=parseHarnessOption(e.harness),n=e.root??process.cwd(),r=_(),i=diagnoseBridges({root:n,...t.length?{harnesses:t}:{},cli:er,home:r,env:process.env}),a=new GitBridgeState(n),o=[...diagnoseConfiguration({root:n,git:a,cli:er}),...diagnoseMcp({root:n,git:a,cli:er}),...diagnoseNonstandard({root:n,cli:er}),...diagnoseWorktrees({root:n,git:a,cli:er})],{layers:s}=listReferences(await referenceLayers({root:n,home:r,platform:process.platform,env:process.env})),c=s.filter(({tier:e})=>e!==`plugin`).map(({name:e,tier:t,path:n,outcome:i})=>({name:e,tier:t,path:collapseHome$1(r,n),status:i}));return buildDoctorReport(displayBinPath(r,process.argv[1]),i,o,c)}catch(e){return fail(e,`Harness diagnosis failed.`)}}const Qr=command({name:`doctor`,description:`Report whether this repository's harness bridges still resolve — skills into .agents/skills, instructions into AGENTS.md — and whether each harness's user-scope file loads ~/.agents/AGENTS.md. Read-only.`,options:Zr,examples:[{command:`buddy-agent-harness doctor`,description:`Check the current repository`},{command:`buddy-agent-harness doctor --harness codex,gemini-cli`,description:`Also check Codex and Gemini CLI`}],async run(e){return result(await diagnoseReport(e))}});function layersFor(e){let t=governanceLayers({root:e.root??process.cwd(),home:_(),platform:process.platform,programData:process.env.ProgramData});return e[`overrides-only`]?overrideLayers(t):t}const $r=`warning: "governance" is deprecated and will be removed in the next major version; use "reference load|list" instead.
|
|
461
|
+
`,ei={description:`Repository or package directory. Defaults to the current directory.`,type:N.string().optional()},ti={description:`Resolve only the project, user, and machine-wide layers. Never returns a governance this package ships, and exits non-zero when no layer has one.`,type:N.boolean().optional()},ni=command({name:`governance`,description:"Deprecated: use `reference`. Read the governance documents the project, user, and machine-wide override layers hold. Read-only.",commands:[command({name:`list`,description:`List every governance the override layers hold, each at the layer that would win.`,options:{root:ei,"overrides-only":ti},examples:[{command:`buddy-agent-harness governance list`,description:`List the governances the layers hold`}],run(e){process.stderr.write($r);try{let t=_(),n=layersFor(e),r=listGovernances(n);return result({layers:n.map(({scope:e,dir:n})=>({scope:e,path:collapseHome$1(t,n),status:e===`managed-deprecated`?`deprecated — move these documents to the managed layer above`:``})),governances:r.length?r.map(({name:e,scope:n,path:r})=>({name:e,scope:n,path:collapseHome$1(t,r)})):`0 governances — no layer holds one`})}catch(e){return fail(e,`Governance listing failed.`)}}}),command({name:`show`,description:`Print one governance document, resolved through the layers in order.`,arguments:[{name:`name`,description:"The governance name, without the `.md` extension.",type:N.string()}],options:{root:ei,"overrides-only":ti},examples:[{command:`buddy-agent-harness governance show skill-design`,description:`Print one governance document`}],run(e){let t=this.format;process.stderr.write($r);try{let n=parseGovernanceName(e.name),r=resolveGovernance(n,layersFor(e));if(!r)throw new M(e[`overrides-only`]?`no override for governance "${n}" in the project, user, or machine-wide layer.`:`no governance named "${n}" in any layer.`,{code:`governance-not-found`,details:{name:n},help:ref(`reference list`,{},`see what is available`)});let i={name:r.name,scope:r.scope,path:collapseHome$1(_(),r.path),content:r.content};return t===`text`?document(i.content):result(i)}catch(e){return fail(e,`Governance lookup failed.`)}}})]});function keepWhenEmpty(e){o(e).length===0&&m(C(e,`.gitkeep`),``)}function initializeHarnesses({root:e,harnesses:t=[],copy:n=!1,force:r=!1}){let a=C(e,`.agents`,`skills`),o=countSkills(a);i(repoReferencesDir(e),{recursive:!0});let s=referenceNames([{tier:`repo`,dir:repoReferencesDir(e)}]).length;keepWhenEmpty(a),keepWhenEmpty(repoReferencesDir(e));let c=selectHarnesses(e,t),{linked:l,skipped:u}=projectSkills({root:e,canonicalSkills:a,harnesses:c,copy:n,force:r});return{root:e,harnesses:c.map(e=>e.name),native:c.filter(e=>!e.project.skillsDirectory).map(e=>e.name),linked:l,skipped:u,deprecated:c.filter(e=>e.deprecated).map(e=>({name:e.name,replacedBy:e.deprecated})),skills:o,references:s,copied:n}}const ri=command({name:`init`,description:`Set up canonical agent skills for the harnesses already enabled in a repository.`,options:{root:{description:`Repository or package directory. Defaults to the current directory.`,type:N.string().optional()},harness:{description:`Comma-separated harnesses to enable in addition to Claude Code and Cursor, e.g. codex,gemini-cli.`,type:N.string().optional()},copy:{description:`Copy skills instead of linking them.`,type:N.boolean().optional()},force:{description:`Replace conflicting target skill directories. Names the targets to replace, comma-separated (e.g. .claude/skills); given alone it replaces every conflicting target.`,type:N.string().optional()}},examples:[{command:`buddy-agent-harness init`,description:`Set up skills for Claude Code and Cursor`},{command:`buddy-agent-harness init --harness codex --copy`,description:`Also enable Codex, copying skills instead of linking`}],run(e){try{let t=parseHarnessOption(e.harness);return result(initializeHarnesses({root:e.root??process.cwd(),...t.length?{harnesses:t}:{},...e.copy===void 0?{}:{copy:e.copy},...e.force===void 0?{}:{force:parseForce(e.force)}}))}catch(e){return fail(e,`Harness initialization failed.`)}}}),ii={ArrayExpression:[`elements`],ArrayPattern:[`elements`],ArrowFunctionExpression:[`params`,`body`],AssignmentExpression:[`left`,`right`],AssignmentPattern:[`left`,`right`],AwaitExpression:[`argument`],BinaryExpression:[`left`,`right`],BlockStatement:[`body`],BreakStatement:[`label`],CallExpression:[`callee`,`arguments`],CatchClause:[`param`,`body`],ChainExpression:[`expression`],ClassBody:[`body`],ClassDeclaration:[`id`,`superClass`,`body`],ClassExpression:[`id`,`superClass`,`body`],ConditionalExpression:[`test`,`consequent`,`alternate`],ContinueStatement:[`label`],DebuggerStatement:[],DoWhileStatement:[`body`,`test`],EmptyStatement:[],ExperimentalRestProperty:[`argument`],ExperimentalSpreadProperty:[`argument`],ExportAllDeclaration:[`exported`,`source`,`attributes`],ExportDefaultDeclaration:[`declaration`],ExportNamedDeclaration:[`declaration`,`specifiers`,`source`,`attributes`],ExportSpecifier:[`local`,`exported`],ExpressionStatement:[`expression`],ForInStatement:[`left`,`right`,`body`],ForOfStatement:[`left`,`right`,`body`],ForStatement:[`init`,`test`,`update`,`body`],FunctionDeclaration:[`id`,`params`,`body`],FunctionExpression:[`id`,`params`,`body`],Identifier:[],IfStatement:[`test`,`consequent`,`alternate`],ImportAttribute:[`key`,`value`],ImportDeclaration:[`specifiers`,`source`,`attributes`],ImportDefaultSpecifier:[`local`],ImportExpression:[`source`,`options`],ImportNamespaceSpecifier:[`local`],ImportSpecifier:[`imported`,`local`],JSXAttribute:[`name`,`value`],JSXClosingElement:[`name`],JSXClosingFragment:[],JSXElement:[`openingElement`,`children`,`closingElement`],JSXEmptyExpression:[],JSXExpressionContainer:[`expression`],JSXFragment:[`openingFragment`,`children`,`closingFragment`],JSXIdentifier:[],JSXMemberExpression:[`object`,`property`],JSXNamespacedName:[`namespace`,`name`],JSXOpeningElement:[`name`,`attributes`],JSXOpeningFragment:[],JSXSpreadAttribute:[`argument`],JSXSpreadChild:[`expression`],JSXText:[],LabeledStatement:[`label`,`body`],Literal:[],LogicalExpression:[`left`,`right`],MemberExpression:[`object`,`property`],MetaProperty:[`meta`,`property`],MethodDefinition:[`key`,`value`],NewExpression:[`callee`,`arguments`],ObjectExpression:[`properties`],ObjectPattern:[`properties`],PrivateIdentifier:[],Program:[`body`],Property:[`key`,`value`],PropertyDefinition:[`key`,`value`],RestElement:[`argument`],ReturnStatement:[`argument`],SequenceExpression:[`expressions`],SpreadElement:[`argument`],StaticBlock:[`body`],Super:[],SwitchCase:[`test`,`consequent`],SwitchStatement:[`discriminant`,`cases`],TaggedTemplateExpression:[`tag`,`quasi`],TemplateElement:[],TemplateLiteral:[`quasis`,`expressions`],ThisExpression:[],ThrowStatement:[`argument`],TryStatement:[`block`,`handler`,`finalizer`],UnaryExpression:[`argument`],UpdateExpression:[`argument`],VariableDeclaration:[`declarations`],VariableDeclarator:[`id`,`init`],WhileStatement:[`test`,`body`],WithStatement:[`object`,`body`],YieldExpression:[`argument`]},ai=Object.keys(ii);for(let e of ai)Object.freeze(ii[e]);Object.freeze(ii);function unionWith(e){let t=Object.assign({},ii);for(let n of Object.keys(e))if(Object.hasOwn(t,n)){let r=new Set(e[n]);for(let e of t[n])r.add(e);t[n]=Object.freeze(Array.from(r))}else t[n]=Object.freeze(Array.from(e[n]));return Object.freeze(t)}function last(e){return e[e.length-1]??null}function toKeyName(e){return e.type===`TOMLBare`?e.name:e.value}var TOMLVerImpl=class{constructor(e,t){this.major=e,this.minor=t}lt(e,t){return this.major<e||this.major===e&&this.minor<t}gte(e,t){return this.major>e||this.major===e&&this.minor>=t}};const oi=new TOMLVerImpl(1,0),si=new TOMLVerImpl(1,1),ci=si,li={"1.0":oi,"1.0.0":oi,"1.1":si,"1.1.0":si,latest:si,next:si};function getTOMLVer(e){return e&&li[e]||ci}const ui={"unterminated-string":`Unterminated string constant`,"unterminated-table-key":`Unterminated table-key`,"unterminated-array":`Unterminated array`,"unterminated-inline-table":`Unterminated inline table`,"missing-key":`Empty bare keys are not allowed`,"missing-newline":`Must be a newline`,"missing-equals-sign":`Expected equal (=) token`,"missing-value":`Unspecified values are invalid`,"missing-comma":`Expected comma (,) token`,"dupe-keys":`Defining a key multiple times is invalid`,"unexpected-char":`Unexpected character`,"unexpected-token":`Unexpected token`,"invalid-control-character":`Control characters (codes < 0x1f and 0x7f) are not allowed`,"invalid-comment-character":`Invalid code point {{cp}} within comments`,"invalid-key-value-newline":`The key, equals sign, and value must be on the same line`,"invalid-inline-table-newline":`No newlines are allowed between the curly braces unless they are valid within a value`,"invalid-underscore":`Underscores are allowed between digits`,"invalid-space":`Unexpected spaces`,"invalid-three-quotes":`Three or more quotes are not permitted`,"invalid-date":`Unexpected invalid date`,"invalid-time":`Unexpected invalid time`,"invalid-leading-zero":`Leading zeros are not allowed`,"invalid-trailing-comma-in-inline-table":`Trailing comma is not permitted in an inline table`,"invalid-char-in-escape-sequence":`Invalid character in escape sequence`,"invalid-consecutive-dots-in-key":`Consecutive dots are not permitted in keys`,"invalid-code-point":`Invalid code point {{cp}}`,"invalid-trailing-dot-in-key":`Keys cannot end with a dot`,"invalid-leading-dot-in-key":`Keys cannot start with a dot`};function getMessage(e,t){return t?ui[e].replace(/\{\{(.*?)\}\}/gu,(e,n)=>n in t?t[n]:`{{${n}}}`):ui[e]}var ParseError=class extends SyntaxError{constructor(e,t,n,r,i){super(getMessage(e,i)),this.index=t,this.lineNumber=n,this.column=r}};const $={EOF:-1,NULL:0,SOH:1,BACKSPACE:8,TABULATION:9,LINE_FEED:10,FORM_FEED:12,CARRIAGE_RETURN:13,ESCAPE:27,SO:14,US:31,SPACE:32,QUOTATION_MARK:34,HASH:35,SINGLE_QUOTE:39,PLUS_SIGN:43,COMMA:44,DASH:45,DOT:46,DIGIT_0:48,DIGIT_1:49,DIGIT_2:50,DIGIT_3:51,DIGIT_7:55,DIGIT_9:57,COLON:58,EQUALS_SIGN:61,LATIN_CAPITAL_A:65,LATIN_CAPITAL_E:69,LATIN_CAPITAL_F:70,LATIN_CAPITAL_T:84,LATIN_CAPITAL_U:85,LATIN_CAPITAL_Z:90,LEFT_BRACKET:91,BACKSLASH:92,RIGHT_BRACKET:93,UNDERSCORE:95,LATIN_SMALL_A:97,LATIN_SMALL_B:98,LATIN_SMALL_E:101,LATIN_SMALL_F:102,LATIN_SMALL_I:105,LATIN_SMALL_L:108,LATIN_SMALL_N:110,LATIN_SMALL_O:111,LATIN_SMALL_R:114,LATIN_SMALL_S:115,LATIN_SMALL_T:116,LATIN_SMALL_U:117,LATIN_SMALL_X:120,LATIN_SMALL_Z:122,LEFT_BRACE:123,RIGHT_BRACE:125,TILDE:126,DELETE:127,PAD:128,SUPERSCRIPT_TWO:178,SUPERSCRIPT_THREE:179,SUPERSCRIPT_ONE:185,VULGAR_FRACTION_ONE_QUARTER:188,VULGAR_FRACTION_THREE_QUARTERS:190,LATIN_CAPITAL_LETTER_A_WITH_GRAVE:192,LATIN_CAPITAL_LETTER_O_WITH_DIAERESIS:214,LATIN_CAPITAL_LETTER_O_WITH_STROKE:216,LATIN_SMALL_LETTER_O_WITH_DIAERESIS:246,LATIN_SMALL_LETTER_O_WITH_STROKE:248,GREEK_SMALL_REVERSED_DOTTED_LUNATE_SIGMA_SYMBOL:891,GREEK_CAPITAL_LETTER_YOT:895,CP_1FFF:8191,ZERO_WIDTH_NON_JOINER:8204,ZERO_WIDTH_JOINER:8205,UNDERTIE:8255,CHARACTER_TIE:8256,SUPERSCRIPT_ZERO:8304,CP_218F:8591,CIRCLED_DIGIT_ONE:9312,NEGATIVE_CIRCLED_DIGIT_ZERO:9471,GLAGOLITIC_CAPITAL_LETTER_AZU:11264,CP_2FEF:12271,IDEOGRAPHIC_COMMA:12289,CP_D7FF:55295,CP_E000:57344,CJK_COMPATIBILITY_IDEOGRAPH_F900:63744,ARABIC_LIGATURE_SALAAMUHU_ALAYNAA:64975,ARABIC_LIGATURE_SALLA_USED_AS_KORANIC_STOP_SIGN_ISOLATED_FORM:65008,REPLACEMENT_CHARACTER:65533,LINEAR_B_SYLLABLE_B008_A:65536,CP_EFFFF:983039,CP_10FFFF:1114111};function isControl(e){return e>=$.NULL&&e<=$.US}function isWhitespace(e){return e===$.TABULATION||e===$.SPACE}function isEOL(e){return e===$.LINE_FEED||e===$.CARRIAGE_RETURN}function isUpperLetter(e){return e>=$.LATIN_CAPITAL_A&&e<=$.LATIN_CAPITAL_Z}function isLowerLetter(e){return e>=$.LATIN_SMALL_A&&e<=$.LATIN_SMALL_Z}function isLetter(e){return isLowerLetter(e)||isUpperLetter(e)}function isDigit$1(e){return e>=$.DIGIT_0&&e<=$.DIGIT_9}__name(isDigit$1,`isDigit`);function isHexDig(e){return isDigit$1(e)||e>=$.LATIN_SMALL_A&&e<=$.LATIN_SMALL_F||e>=$.LATIN_CAPITAL_A&&e<=$.LATIN_CAPITAL_F}function isOctalDig(e){return e>=$.DIGIT_0&&e<=$.DIGIT_7}function isUnicodeScalarValue(e){return e>=0&&e<=55295||e>=57344&&e<=1114111}function sortedLastIndex(e,t){let n=0,r=e.length;for(;n<r;){let i=n+r>>>1,a=e[i];if(a===t)return i+1;a<t?n=i+1:r=i}return n}var Locations=class{constructor(){this.offsets=[]}addOffset(e){for(let t=this.offsets.length-1;t>=0;t--){let n=this.offsets[t];if(n===e)return;if(n<e)break}this.offsets.push(e)}getLocFromIndex(e){let t=sortedLastIndex(this.offsets,e)+1;return{line:t,column:e-(t===1?0:this.offsets[t-2])}}},CodePointIterator=class{constructor(e){this.locs=new Locations,this.lastCodePoint=$.NULL,this.start=-1,this.end=0,this.text=e}next(){return this.lastCodePoint===$.EOF?$.EOF:this.lastCodePoint=this.moveAt(this.end)}getLocFromIndex(e){return this.locs.getLocFromIndex(e)}eat(e){return this.text.codePointAt(this.end)===e&&(this.next(),!0)}moveAt(e){this.start=this.end=e;let t=this.text.codePointAt(this.start)??$.EOF;if(t===$.EOF)return this.end=this.start,t;if(this.end+=t>=65536?2:1,t===$.LINE_FEED)this.locs.addOffset(this.end);else if(t===$.CARRIAGE_RETURN)return this.text.codePointAt(this.end)===$.LINE_FEED&&(this.end++,this.locs.addOffset(this.end)),$.LINE_FEED;return t}};const di=typeof BigInt<`u`,fi={16:`0x`,10:``,8:`0o`,2:`0b`},pi={[$.QUOTATION_MARK]:$.QUOTATION_MARK,[$.BACKSLASH]:$.BACKSLASH,[$.LATIN_SMALL_B]:$.BACKSPACE,[$.LATIN_SMALL_F]:$.FORM_FEED,[$.LATIN_SMALL_N]:$.LINE_FEED,[$.LATIN_SMALL_R]:$.CARRIAGE_RETURN,[$.LATIN_SMALL_T]:$.TABULATION},mi={...pi,[$.LATIN_SMALL_E]:$.ESCAPE};var Tokenizer=class{constructor(e,t){this.backCode=!1,this.lastCodePoint=$.NULL,this.state=`DATA`,this.token=null,this.tokenStart=-1,this.valuesEnabled=!1,this.text=e,this.parserOptions=t||{},this.codePointIterator=new CodePointIterator(e),this.tomlVersion=getTOMLVer(this.parserOptions.tomlVersion),this.ESCAPES=this.tomlVersion.gte(1,1)?mi:pi}get start(){return this.codePointIterator.start}get end(){return this.codePointIterator.end}getLocFromIndex(e){return this.codePointIterator.getLocFromIndex(e)}reportParseError(e,t){let n=this.codePointIterator.start,r=this.codePointIterator.getLocFromIndex(n);throw new ParseError(e,n,r.line,r.column,t)}nextToken(){let e=this.token;if(e!=null)return this.token=null,e;let t=this.lastCodePoint;for(;t!==$.EOF&&!this.token;){t=this.nextCode();let e=this[this.state](t);if(!e)throw Error(`Unknown error: pre state=${this.state}`);this.state=e}return e=this.token,this.token=null,e}nextCode(){return this.lastCodePoint===$.EOF?$.EOF:this.backCode?(this.backCode=!1,this.lastCodePoint):this.lastCodePoint=this.codePointIterator.next()}eatCode(e){return this.lastCodePoint===$.EOF?!1:this.backCode?this.lastCodePoint===e&&(this.backCode=!1,!0):this.codePointIterator.eat(e)}moveAt(e){this.backCode&&=!1,this.lastCodePoint=this.codePointIterator.moveAt(e)}back(e){return this.backCode=!0,e}punctuatorToken(){this.startToken(),this.endToken(`Punctuator`,`end`)}startToken(){this.tokenStart=this.codePointIterator.start}endToken(e,t,n,r){let{tokenStart:i}=this,a=this.codePointIterator[t],o=[i,a],s={start:this.codePointIterator.getLocFromIndex(i),end:this.codePointIterator.getLocFromIndex(a)};if(e===`Block`)this.token={type:e,value:this.text.slice(i+1,a),range:o,loc:s};else{let t,c=this.text.slice(i,a);if(e===`BasicString`||e===`LiteralString`||e===`MultiLineBasicString`||e===`MultiLineLiteralString`)t={type:e,value:c,string:n,range:o,loc:s};else if(e===`Integer`){let i=n;t={type:e,value:c,number:parseInt(i,r),bigint:di?BigInt(fi[r]+i):null,range:o,loc:s}}else t=e===`Float`?{type:e,value:c,number:n,range:o,loc:s}:e===`Boolean`?{type:e,value:c,boolean:n,range:o,loc:s}:e===`LocalDate`||e===`LocalTime`||e===`LocalDateTime`||e===`OffsetDateTime`?{type:e,value:c,date:n,range:o,loc:s}:{type:e,value:c,range:o,loc:s};this.token=t}}DATA(e){for(;isWhitespace(e)||isEOL(e);)e=this.nextCode();if(e===$.HASH)return this.startToken(),`COMMENT`;if(e===$.QUOTATION_MARK)return this.startToken(),`BASIC_STRING`;if(e===$.SINGLE_QUOTE)return this.startToken(),`LITERAL_STRING`;if(e===$.DOT||e===$.EQUALS_SIGN||e===$.LEFT_BRACKET||e===$.RIGHT_BRACKET||e===$.LEFT_BRACE||e===$.RIGHT_BRACE||e===$.COMMA)return this.punctuatorToken(),`DATA`;if(this.valuesEnabled){if(e===$.DASH||e===$.PLUS_SIGN)return this.startToken(),`SIGN`;if(e===$.LATIN_SMALL_N||e===$.LATIN_SMALL_I)return this.startToken(),this.back(`NAN_OR_INF`);if(isDigit$1(e))return this.startToken(),this.back(`NUMBER`);if(e===$.LATIN_SMALL_T||e===$.LATIN_SMALL_F)return this.startToken(),this.back(`BOOLEAN`)}else if(isUnquotedKeyChar(e,this.tomlVersion))return this.startToken(),`BARE`;return e===$.EOF?`DATA`:this.reportParseError(`unexpected-char`)}COMMENT(e){let t=this.tomlVersion.gte(1,1)?e=>{isNonEOL(e)||this.reportParseError(`invalid-comment-character`,{cp:JSON.stringify(String.fromCodePoint(e)).slice(1,-1)})}:e=>{isControlOtherThanTab(e)&&this.reportParseErrorControlChar()};for(;!isEOL(e)&&e!==$.EOF;)t(e),e=this.nextCode();return this.endToken(`Block`,`start`),`DATA`}BARE(e){for(;isUnquotedKeyChar(e,this.tomlVersion);)e=this.nextCode();return this.endToken(`Bare`,`start`),this.back(`DATA`)}BASIC_STRING(e){if(e===$.QUOTATION_MARK)return e=this.nextCode(),e===$.QUOTATION_MARK?`MULTI_LINE_BASIC_STRING`:(this.endToken(`BasicString`,`start`,``),this.back(`DATA`));let t=[];for(;e!==$.QUOTATION_MARK&&e!==$.EOF&&e!==$.LINE_FEED;){if(isControlOtherThanTab(e))return this.reportParseErrorControlChar();if(e===$.BACKSLASH){e=this.nextCode();let n=this.ESCAPES[e];if(n){t.push(n),e=this.nextCode();continue}if(e===$.LATIN_SMALL_U){let n=this.parseUnicode(4);t.push(n),e=this.nextCode();continue}if(e===$.LATIN_CAPITAL_U){let n=this.parseUnicode(8);t.push(n),e=this.nextCode();continue}if(e===$.LATIN_SMALL_X&&this.tomlVersion.gte(1,1)){let n=this.parseUnicode(2);t.push(n),e=this.nextCode();continue}return this.reportParseError(`invalid-char-in-escape-sequence`)}t.push(e),e=this.nextCode()}return e===$.QUOTATION_MARK?(this.endToken(`BasicString`,`end`,String.fromCodePoint(...t)),`DATA`):this.reportParseError(`unterminated-string`)}MULTI_LINE_BASIC_STRING(e){let t=[];for(e===$.LINE_FEED&&(e=this.nextCode());e!==$.EOF;){if(e!==$.LINE_FEED&&isControlOtherThanTab(e))return this.reportParseErrorControlChar();if(e===$.QUOTATION_MARK){let e=this.codePointIterator.start;if(this.eatCode($.QUOTATION_MARK)&&this.eatCode($.QUOTATION_MARK))return this.eatCode($.QUOTATION_MARK)&&(t.push($.QUOTATION_MARK),this.eatCode($.QUOTATION_MARK)&&(t.push($.QUOTATION_MARK),this.eatCode($.QUOTATION_MARK)))?(this.moveAt(e),this.reportParseError(`invalid-three-quotes`)):(this.endToken(`MultiLineBasicString`,`end`,String.fromCodePoint(...t)),`DATA`);this.moveAt(e)}if(e===$.BACKSLASH){e=this.nextCode();let n=this.ESCAPES[e];if(n){t.push(n),e=this.nextCode();continue}if(e===$.LATIN_SMALL_U){let n=this.parseUnicode(4);t.push(n),e=this.nextCode();continue}if(e===$.LATIN_CAPITAL_U){let n=this.parseUnicode(8);t.push(n),e=this.nextCode();continue}if(e===$.LATIN_SMALL_X&&this.tomlVersion.gte(1,1)){let n=this.parseUnicode(2);t.push(n),e=this.nextCode();continue}if(e===$.LINE_FEED){for(e=this.nextCode();isWhitespace(e)||e===$.LINE_FEED;)e=this.nextCode();continue}if(isWhitespace(e)){let t=!0,n=this.codePointIterator.start,r;for(;(r=this.nextCode())!==$.EOF&&r!==$.LINE_FEED;)if(!isWhitespace(r)){this.moveAt(n),t=!1;break}if(t){for(e=this.nextCode();isWhitespace(e)||e===$.LINE_FEED;)e=this.nextCode();continue}}return this.reportParseError(`invalid-char-in-escape-sequence`)}t.push(e),e=this.nextCode()}return this.reportParseError(`unterminated-string`)}LITERAL_STRING(e){if(e===$.SINGLE_QUOTE)return e=this.nextCode(),e===$.SINGLE_QUOTE?`MULTI_LINE_LITERAL_STRING`:(this.endToken(`LiteralString`,`start`,``),this.back(`DATA`));let t=[];for(;e!==$.SINGLE_QUOTE&&e!==$.EOF&&e!==$.LINE_FEED;){if(isControlOtherThanTab(e))return this.reportParseErrorControlChar();t.push(e),e=this.nextCode()}return e===$.SINGLE_QUOTE?(this.endToken(`LiteralString`,`end`,String.fromCodePoint(...t)),`DATA`):this.reportParseError(`unterminated-string`)}MULTI_LINE_LITERAL_STRING(e){let t=[];for(e===$.LINE_FEED&&(e=this.nextCode());e!==$.EOF;){if(e!==$.LINE_FEED&&isControlOtherThanTab(e))return this.reportParseErrorControlChar();if(e===$.SINGLE_QUOTE){let e=this.codePointIterator.start;if(this.eatCode($.SINGLE_QUOTE)&&this.eatCode($.SINGLE_QUOTE))return this.eatCode($.SINGLE_QUOTE)&&(t.push($.SINGLE_QUOTE),this.eatCode($.SINGLE_QUOTE)&&(t.push($.SINGLE_QUOTE),this.eatCode($.SINGLE_QUOTE)))?(this.moveAt(e),this.reportParseError(`invalid-three-quotes`)):(this.endToken(`MultiLineLiteralString`,`end`,String.fromCodePoint(...t)),`DATA`);this.moveAt(e)}t.push(e),e=this.nextCode()}return this.reportParseError(`unterminated-string`)}SIGN(e){return e===$.LATIN_SMALL_N||e===$.LATIN_SMALL_I?this.back(`NAN_OR_INF`):isDigit$1(e)?this.back(`NUMBER`):this.reportParseError(`unexpected-char`)}NAN_OR_INF(e){if(e===$.LATIN_SMALL_N){let e=this.codePointIterator.start;if(this.eatCode($.LATIN_SMALL_A)&&this.eatCode($.LATIN_SMALL_N))return this.endToken(`Float`,`end`,NaN),`DATA`;this.moveAt(e)}else if(e===$.LATIN_SMALL_I){let e=this.codePointIterator.start;if(this.eatCode($.LATIN_SMALL_N)&&this.eatCode($.LATIN_SMALL_F))return this.endToken(`Float`,`end`,this.text[this.tokenStart]===`-`?-1/0:1/0),`DATA`;this.moveAt(e)}return this.reportParseError(`unexpected-char`)}NUMBER(e){let t=this.text[this.tokenStart],n=t===`+`?$.PLUS_SIGN:t===`-`?$.DASH:$.NULL;if(e===$.DIGIT_0){if(n===$.NULL){let e=this.codePointIterator.start,t=this.nextCode();if(isDigit$1(t)){let n=this.nextCode();if(n===$.COLON)return this.data={hasDate:!1,year:0,month:0,day:0,hour:Number(String.fromCodePoint($.DIGIT_0,t)),minute:0,second:0},`TIME_MINUTE`;if(isDigit$1(n)){let e=this.nextCode();if(isDigit$1(e)&&this.eatCode($.DASH))return this.data={hasDate:!0,year:Number(String.fromCodePoint($.DIGIT_0,t,n,e)),month:0,day:0,hour:0,minute:0,second:0},`DATE_MONTH`}return this.moveAt(e),this.reportParseError(`invalid-leading-zero`)}this.moveAt(e)}return e=this.nextCode(),e===$.LATIN_SMALL_X||e===$.LATIN_SMALL_O||e===$.LATIN_SMALL_B?n===$.NULL?e===$.LATIN_SMALL_X?`HEX`:e===$.LATIN_SMALL_O?`OCTAL`:`BINARY`:this.reportParseError(`unexpected-char`):e===$.LATIN_SMALL_E||e===$.LATIN_CAPITAL_E?(this.data={minus:n===$.DASH,left:[$.DIGIT_0]},`EXPONENT_RIGHT`):e===$.DOT?(this.data={minus:n===$.DASH,absInt:[$.DIGIT_0]},`FRACTIONAL_RIGHT`):(this.endToken(`Integer`,`start`,`0`,10),this.back(`DATA`))}let{out:r,nextCp:i,hasUnderscore:a}=this.parseDigits(e,isDigit$1);return i===$.DASH&&n===$.NULL&&!a&&r.length===4?(this.data={hasDate:!0,year:Number(String.fromCodePoint(...r)),month:0,day:0,hour:0,minute:0,second:0},`DATE_MONTH`):i===$.COLON&&n===$.NULL&&!a&&r.length===2?(this.data={hasDate:!1,year:0,month:0,day:0,hour:Number(String.fromCodePoint(...r)),minute:0,second:0},`TIME_MINUTE`):i===$.LATIN_SMALL_E||i===$.LATIN_CAPITAL_E?(this.data={minus:n===$.DASH,left:r},`EXPONENT_RIGHT`):i===$.DOT?(this.data={minus:n===$.DASH,absInt:r},`FRACTIONAL_RIGHT`):(this.endToken(`Integer`,`start`,n===$.DASH?String.fromCodePoint($.DASH,...r):String.fromCodePoint(...r),10),this.back(`DATA`))}HEX(e){let{out:t}=this.parseDigits(e,isHexDig);return this.endToken(`Integer`,`start`,String.fromCodePoint(...t),16),this.back(`DATA`)}OCTAL(e){let{out:t}=this.parseDigits(e,isOctalDig);return this.endToken(`Integer`,`start`,String.fromCodePoint(...t),8),this.back(`DATA`)}BINARY(e){let{out:t}=this.parseDigits(e,e=>e===$.DIGIT_0||e===$.DIGIT_1);return this.endToken(`Integer`,`start`,String.fromCodePoint(...t),2),this.back(`DATA`)}FRACTIONAL_RIGHT(e){let{minus:t,absInt:n}=this.data,{out:r,nextCp:i}=this.parseDigits(e,isDigit$1),a=[...n,$.DOT,...r];if(i===$.LATIN_SMALL_E||i===$.LATIN_CAPITAL_E)return this.data={minus:t,left:a},`EXPONENT_RIGHT`;let o=Number(t?String.fromCodePoint($.DASH,...a):String.fromCodePoint(...a));return this.endToken(`Float`,`start`,o),this.back(`DATA`)}EXPONENT_RIGHT(e){let{left:t,minus:n}=this.data,r=!1;(e===$.DASH||e===$.PLUS_SIGN)&&(r=e===$.DASH,e=this.nextCode());let{out:i}=this.parseDigits(e,isDigit$1),a=i;r&&a.unshift($.DASH);let o=Number(n?String.fromCodePoint($.DASH,...t,$.LATIN_SMALL_E,...a):String.fromCodePoint(...t,$.LATIN_SMALL_E,...a));return this.endToken(`Float`,`start`,o),this.back(`DATA`)}BOOLEAN(e){if(e===$.LATIN_SMALL_T){let e=this.codePointIterator.start;if(this.eatCode($.LATIN_SMALL_R)&&this.eatCode($.LATIN_SMALL_U)&&this.eatCode($.LATIN_SMALL_E))return this.endToken(`Boolean`,`end`,!0),`DATA`;this.moveAt(e)}else if(e===$.LATIN_SMALL_F){let e=this.codePointIterator.start;if(this.eatCode($.LATIN_SMALL_A)&&this.eatCode($.LATIN_SMALL_L)&&this.eatCode($.LATIN_SMALL_S)&&this.eatCode($.LATIN_SMALL_E))return this.endToken(`Boolean`,`end`,!1),`DATA`;this.moveAt(e)}return this.reportParseError(`unexpected-char`)}DATE_MONTH(e){let t=this.codePointIterator.start;if(!isDigit$1(e)||(e=this.nextCode(),!isDigit$1(e))||(e=this.nextCode(),e!==$.DASH))return this.reportParseError(`unexpected-char`);let n=this.codePointIterator.start,r=this.data;return r.month=Number(this.text.slice(t,n)),`DATE_DAY`}DATE_DAY(e){let t=this.codePointIterator.start;if(!isDigit$1(e)||(e=this.nextCode(),!isDigit$1(e)))return this.reportParseError(`unexpected-char`);let n=this.codePointIterator.end,r=this.data;if(r.day=Number(this.text.slice(t,n)),!isValidDate(r.year,r.month,r.day))return this.reportParseError(`invalid-date`);if(e=this.nextCode(),e===$.LATIN_CAPITAL_T||e===$.LATIN_SMALL_T)return`TIME_HOUR`;if(e===$.SPACE){let e=this.codePointIterator.start;if(isDigit$1(this.nextCode())&&isDigit$1(this.nextCode()))return this.moveAt(e),`TIME_HOUR`;this.moveAt(e)}let i=getDateFromDateTimeData(r,``);return this.endToken(`LocalDate`,`start`,i),this.back(`DATA`)}TIME_HOUR(e){let t=this.codePointIterator.start;if(!isDigit$1(e)||(e=this.nextCode(),!isDigit$1(e))||(e=this.nextCode(),e!==$.COLON))return this.reportParseError(`unexpected-char`);let n=this.codePointIterator.start,r=this.data;return r.hour=Number(this.text.slice(t,n)),`TIME_MINUTE`}TIME_MINUTE(e){let t=this.codePointIterator.start;if(!isDigit$1(e)||(e=this.nextCode(),!isDigit$1(e)))return this.reportParseError(`unexpected-char`);let n=this.codePointIterator.end,r=this.data;return r.minute=Number(this.text.slice(t,n)),e=this.nextCode(),e===$.COLON?`TIME_SECOND`:this.tomlVersion.lt(1,1)?this.reportParseError(`unexpected-char`):isValidTime(r.hour,r.minute,r.second)?this.processTimeEnd(e,r):this.reportParseError(`invalid-time`)}TIME_SECOND(e){let t=this.codePointIterator.start;if(!isDigit$1(e)||(e=this.nextCode(),!isDigit$1(e)))return this.reportParseError(`unexpected-char`);let n=this.codePointIterator.end,r=this.data;return r.second=Number(this.text.slice(t,n)),isValidTime(r.hour,r.minute,r.second)?(e=this.nextCode(),e===$.DOT?`TIME_SEC_FRAC`:this.processTimeEnd(e,r)):this.reportParseError(`invalid-time`)}TIME_SEC_FRAC(e){if(!isDigit$1(e))return this.reportParseError(`unexpected-char`);let t=this.codePointIterator.start;for(;isDigit$1(e);)e=this.nextCode();let n=this.codePointIterator.start,r=this.data;return r.frac=this.text.slice(t,n),this.processTimeEnd(e,r)}processTimeEnd(e,t){if(t.hasDate){if(e===$.DASH||e===$.PLUS_SIGN)return t.offsetSign=e,`TIME_OFFSET`;if(e===$.LATIN_CAPITAL_Z||e===$.LATIN_SMALL_Z){let e=getDateFromDateTimeData(t,`Z`);return this.endToken(`OffsetDateTime`,`end`,e),`DATA`}let n=getDateFromDateTimeData(t,``);return this.endToken(`LocalDateTime`,`start`,n),this.back(`DATA`)}let n=getDateFromDateTimeData(t,``);return this.endToken(`LocalTime`,`start`,n),this.back(`DATA`)}TIME_OFFSET(e){if(!isDigit$1(e))return this.reportParseError(`unexpected-char`);let t=this.codePointIterator.start;if(e=this.nextCode(),!isDigit$1(e)||(e=this.nextCode(),e!==$.COLON))return this.reportParseError(`unexpected-char`);let n=this.codePointIterator.start;e=this.nextCode();let r=this.codePointIterator.start;if(!isDigit$1(e)||(e=this.nextCode(),!isDigit$1(e)))return this.reportParseError(`unexpected-char`);let i=this.codePointIterator.end,a=Number(this.text.slice(t,n)),o=Number(this.text.slice(r,i));if(!isValidTime(a,o,0))return this.reportParseError(`invalid-time`);let s=this.data,c=getDateFromDateTimeData(s,`${String.fromCodePoint(s.offsetSign)}${padStart(a,2)}:${padStart(o,2)}`);return this.endToken(`OffsetDateTime`,`end`,c),`DATA`}parseDigits(e,t){if(e===$.UNDERSCORE)return this.reportParseError(`invalid-underscore`);if(!t(e))return this.reportParseError(`unexpected-char`);let n=[],r=$.NULL,i=!1;for(;t(e)||e===$.UNDERSCORE;){if(e===$.UNDERSCORE){if(i=!0,r===$.UNDERSCORE)return this.reportParseError(`invalid-underscore`)}else n.push(e);r=e,e=this.nextCode()}return r===$.UNDERSCORE?this.reportParseError(`invalid-underscore`):{out:n,nextCp:e,hasUnderscore:i}}parseUnicode(e){let t=this.codePointIterator.start,n=this.codePointIterator.end,r=0,i;for(;(i=this.nextCode())!==$.EOF;){if(!isHexDig(i))return this.moveAt(t),this.reportParseError(`invalid-char-in-escape-sequence`);if(r++,r>=e)break}let a=this.codePointIterator.end,o=this.text.slice(n,a),s=parseInt(o,16);return isUnicodeScalarValue(s)?s:this.reportParseError(`invalid-code-point`,{cp:o})}reportParseErrorControlChar(){return this.reportParseError(`invalid-control-character`)}};function isUnquotedKeyChar(e,t){return isLetter(e)||isDigit$1(e)||e===$.UNDERSCORE||e===$.DASH?!0:(t.lt(1,1),!1)}function isControlOtherThanTab(e){return isControl(e)&&e!==$.TABULATION||e===$.DELETE}function isNonEOL(e){return e===$.TABULATION||$.SPACE<=e&&e<=$.TILDE||isNonAscii(e)}function isNonAscii(e){return $.PAD<=e&&e<=$.CP_D7FF||$.CP_E000<=e&&e<=$.CP_10FFFF}function isValidDate(e,t,n){return e>=0&&t<=12&&t>=1&&n>=1&&n<=(t===2?e&3||!(e%25)&&e&15?28:29:30+(t+(t>>3)&1))}function isValidTime(e,t,n){return!(e>=24||e<0||t>59||t<0||n>60||n<0)}function getDateFromDateTimeData(e,t){let n=padStart(e.year,4),r=e.month?padStart(e.month,2):`01`,i=e.day?padStart(e.day,2):`01`,a=padStart(e.hour,2),o=padStart(e.minute,2),s=padStart(e.second,2),c=`${n}-${r}-${i}`,l=e.frac?`.${e.frac}`:``,u=new Date(`${c}T${a}:${o}:${s}${l}${t}`);return!isNaN(u.getTime())||e.second!==60?u:new Date(`${c}T${a}:${o}:59${l}${t}`)}function padStart(e,t){return String(e).padStart(t,`0`)}const hi=Symbol(`VALUE_KIND_VALUE`),gi=Symbol(`VALUE_KIND_INTERMEDIATE`);var KeysResolver=class{constructor(e){this.rootKeys=new Map,this.tables=[],this.ctx=e}applyResolveKeyForTable(e){let t=this.rootKeys,n=e.key.keys.length-1;for(let r=0;r<n;r++){let n=e.key.keys[r],i=toKeyName(n);e.resolvedKey.push(i);let a=t.get(i);if(!a)a={node:n,keys:new Map},t.set(i,a);else if(a.table===`array`){let t=a.peekIndex;e.resolvedKey.push(t),a=a.keys.get(t)}t=a.keys}let r=e.key.keys[n],i=toKeyName(r);e.resolvedKey.push(i);let a=t.get(i);if(!a){if(e.kind===`array`){e.resolvedKey.push(0);let n={node:r,keys:new Map};t.set(i,{table:e.kind,node:r,keys:new Map([[0,n]]),peekIndex:0}),this.tables.push({node:e,keys:n.keys})}else{let n={table:e.kind,node:r,keys:new Map};t.set(i,n),this.tables.push({node:e,keys:n.keys})}}else if(!a.table){if(e.kind===`array`)this.ctx.reportParseError(`dupe-keys`,r);else{let n={table:e.kind,node:r,keys:a.keys};t.set(i,n),this.tables.push({node:e,keys:n.keys})}}else if(a.table===`array`){if(e.kind===`array`){let t={node:r,keys:new Map},n=a.peekIndex+1;e.resolvedKey.push(n),a.keys.set(n,t),a.peekIndex=n,this.tables.push({node:e,keys:t.keys})}else this.ctx.reportParseError(`dupe-keys`,r)}else this.ctx.reportParseError(`dupe-keys`,r)}verifyDuplicateKeys(e){for(let t of e.body)t.type===`TOMLKeyValue`&&verifyDuplicateKeysForKeyValue(this.ctx,this.rootKeys,t);for(let{node:e,keys:t}of this.tables)for(let n of e.body)verifyDuplicateKeysForKeyValue(this.ctx,t,n)}};function verifyDuplicateKeysForKeyValue(e,t,n){let r=t,i=last(n.key.keys);for(let t of n.key.keys){let n=toKeyName(t),a=r.get(n);a?((a.value===hi||i===t||a.table)&&e.reportParseError(`dupe-keys`,getAfterNode(t,a.node)),a.value=gi):(a=i===t?{value:hi,node:t,keys:new Map}:{value:gi,node:t,keys:new Map},r.set(n,a)),r=a.keys}n.value.type===`TOMLInlineTable`?verifyDuplicateKeysForInlineTable(e,r,n.value):n.value.type===`TOMLArray`&&verifyDuplicateKeysForArray(e,r,n.value)}function verifyDuplicateKeysForInlineTable(e,t,n){for(let r of n.body)verifyDuplicateKeysForKeyValue(e,t,r)}function verifyDuplicateKeysForArray(e,t,n){let r=t;for(let i=0;i<n.elements.length;i++){let a=n.elements[i],o=r.get(i);o?e.reportParseError(`dupe-keys`,getAfterNode(a,o.node)):(o={value:hi,node:a,keys:new Map},t.set(i,o),a.type===`TOMLInlineTable`?verifyDuplicateKeysForInlineTable(e,o.keys,a):a.type===`TOMLArray`&&verifyDuplicateKeysForArray(e,o.keys,a))}}function getAfterNode(e,t){return e.range[0]<=t.range[0]?t:e}var Context=class{constructor(e){this.tokens=[],this.comments=[],this.back=null,this.stateStack=[],this.needNewLine=!1,this.needSameLine=!1,this.currToken=null,this.prevToken=null,this.valueContainerStack=[],this.tokenizer=new Tokenizer(e.text,e.parserOptions),this.topLevelTable=e.topLevelTable,this.table=e.topLevelTable,this.keysResolver=new KeysResolver(this)}nextToken(e){if(this.prevToken=this.currToken,this.back?(this.currToken=this.back,this.back=null):this.currToken=this._nextTokenFromTokenizer(e),(this.needNewLine||this.needSameLine||e?.needSameLine)&&this.prevToken&&this.currToken){if(this.prevToken.loc.end.line===this.currToken.loc.start.line){if(this.needNewLine)return this.reportParseError(`missing-newline`,this.currToken)}else{let t=this.needSameLine||e?.needSameLine;if(t)return this.reportParseError(t,this.currToken)}}return this.needNewLine=!1,this.needSameLine=!1,this.currToken}_nextTokenFromTokenizer(e){let t=this.tokenizer.valuesEnabled;e?.valuesEnabled&&(this.tokenizer.valuesEnabled=e.valuesEnabled);let n=this.tokenizer.nextToken();for(;n&&n.type===`Block`;)this.comments.push(n),n=this.tokenizer.nextToken();return n&&this.tokens.push(n),this.tokenizer.valuesEnabled=t,n}backToken(){if(this.back)throw Error(`Illegal state`);this.back=this.currToken,this.currToken=this.prevToken}addValueContainer(e){this.valueContainerStack.push(e),this.tokenizer.valuesEnabled=!0}consumeValueContainer(){let e=this.valueContainerStack.pop();return this.tokenizer.valuesEnabled=this.valueContainerStack.length>0,e}applyResolveKeyForTable(e){this.keysResolver.applyResolveKeyForTable(e)}verifyDuplicateKeys(){this.keysResolver.verifyDuplicateKeys(this.topLevelTable)}reportParseError(e,t){let n,r,i;if(t)n=t.range[0],r=t.loc.start.line,i=t.loc.start.column;else{n=this.tokenizer.start;let e=this.tokenizer.getLocFromIndex(n);r=e.line,i=e.column}throw new ParseError(e,n,r,i)}};const _i={VALUE:`missing-value`},vi={BasicString:`basic`,MultiLineBasicString:`basic`,LiteralString:`literal`,MultiLineLiteralString:`literal`},yi={BasicString:`basic`,LiteralString:`literal`},bi={OffsetDateTime:`offset-date-time`,LocalDateTime:`local-date-time`,LocalDate:`local-date`,LocalTime:`local-time`};var TOMLParser=class{constructor(e,t){this.text=e,this.parserOptions=t||{},this.tomlVersion=getTOMLVer(this.parserOptions.tomlVersion)}parse(){let e={type:`Program`,body:[],sourceType:`module`,tokens:[],comments:[],parent:null,range:[0,0],loc:{start:{line:1,column:0},end:{line:1,column:0}}},t={type:`TOMLTopLevelTable`,body:[],parent:e,range:cloneRange(e.range),loc:cloneLoc(e.loc)};e.body=[t];let n=new Context({text:this.text,parserOptions:this.parserOptions,topLevelTable:t}),r=n.nextToken();if(r){for(t.range[0]=r.range[0],t.loc.start=clonePos(r.loc.start);r;){let e=n.stateStack.pop()||`TABLE`;n.stateStack.push(...this[e](r,n)),r=n.nextToken()}let e=n.stateStack.pop()||`TABLE`;if(e in _i)return n.reportParseError(_i[e],null);n.table.type===`TOMLTable`&&applyEndLoc(n.table,last(n.table.body)),applyEndLoc(t,last(t.body))}n.verifyDuplicateKeys(),e.tokens=n.tokens,e.comments=n.comments;let i=n.tokenizer.end,a=n.tokenizer.getLocFromIndex(i);return e.range[1]=i,e.loc.end={line:a.line,column:a.column},e}TABLE(e,t){return isBare(e)||isString(e)?this.processKeyValue(e,t.table,t):isLeftBracket(e)?this.processTable(e,t.topLevelTable,t):t.reportParseError(`unexpected-token`,e)}VALUE(e,t){return isString(e)||isMultiLineString(e)?this.processStringValue(e,t):isNumber(e)?this.processNumberValue(e,t):isBoolean(e)?this.processBooleanValue(e,t):isDateTime(e)?this.processDateTimeValue(e,t):isLeftBracket(e)?this.processArray(e,t):isLeftBrace(e)?this.processInlineTable(e,t):t.reportParseError(`unexpected-token`,e)}processTable(e,t,n){let r={type:`TOMLTable`,kind:`standard`,key:null,resolvedKey:[],body:[],parent:t,range:cloneRange(e.range),loc:cloneLoc(e.loc)};n.table.type===`TOMLTable`&&applyEndLoc(n.table,last(n.table.body)),t.body.push(r),n.table=r;let i=n.nextToken({needSameLine:`invalid-key-value-newline`});if(isLeftBracket(i)){if(e.range[1]<i.range[0])return n.reportParseError(`invalid-space`,i);r.kind=`array`,i=n.nextToken({needSameLine:`invalid-key-value-newline`})}if(isRightBracket(i))return n.reportParseError(`missing-key`,i);if(!i)return n.reportParseError(`unterminated-table-key`,null);if(i=this.processKeyNode(i,r,n).nextToken,!isRightBracket(i))return n.reportParseError(`unterminated-table-key`,i);if(r.kind===`array`){let e=i;if(i=n.nextToken({needSameLine:`invalid-key-value-newline`}),!isRightBracket(i))return n.reportParseError(`unterminated-table-key`,i);if(e.range[1]<i.range[0])return n.reportParseError(`invalid-space`,i)}return applyEndLoc(r,i),n.applyResolveKeyForTable(r),n.needNewLine=!0,[]}processKeyValue(e,t,n){let r={type:`TOMLKeyValue`,key:null,value:null,parent:t,range:cloneRange(e.range),loc:cloneLoc(e.loc)};t.body.push(r);let{nextToken:i}=this.processKeyNode(e,r,n);return isEq(i)?(n.addValueContainer({parent:r,set:e=>(r.value=e,applyEndLoc(r,e),n.needNewLine=!0,[])}),n.needSameLine=`invalid-key-value-newline`,[`VALUE`]):n.reportParseError(`missing-equals-sign`,i)}processKeyNode(e,t,n){isDot(e)&&n.reportParseError(`invalid-leading-dot-in-key`,e);let r={type:`TOMLKey`,keys:[],parent:t,range:cloneRange(e.range),loc:cloneLoc(e.loc)};t.key=r;let i=e,a=null;do{if(isBare(i))this.processBareKey(i,r);else if(isString(i))this.processStringKey(i,r);else break;if(a=null,i=n.nextToken({needSameLine:`invalid-key-value-newline`}),!isDot(i))break;a=i,i=n.nextToken({needSameLine:`invalid-key-value-newline`})}while(i);return a&&n.reportParseError(isDot(i)?`invalid-consecutive-dots-in-key`:`invalid-trailing-dot-in-key`,a),applyEndLoc(r,last(r.keys)),{keyNode:r,nextToken:i}}processBareKey(e,t){let n={type:`TOMLBare`,name:e.value,parent:t,range:cloneRange(e.range),loc:cloneLoc(e.loc)};t.keys.push(n)}processStringKey(e,t){let n={type:`TOMLQuoted`,kind:`string`,value:e.string,style:yi[e.type],multiline:!1,parent:t,range:cloneRange(e.range),loc:cloneLoc(e.loc)};t.keys.push(n)}processStringValue(e,t){let n=t.consumeValueContainer(),r={type:`TOMLValue`,kind:`string`,value:e.string,style:vi[e.type],multiline:isMultiLineString(e),parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)};return n.set(r)}processNumberValue(e,t){let n=t.consumeValueContainer(),r=this.text,[i,a]=e.range,o=null,getNumberText=()=>o??=r.slice(i,a).replace(/_/g,``),s;return s=e.type===`Integer`?{type:`TOMLValue`,kind:`integer`,value:e.number,bigint:e.bigint,get number(){return getNumberText()},parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)}:{type:`TOMLValue`,kind:`float`,value:e.number,get number(){return getNumberText()},parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)},n.set(s)}processBooleanValue(e,t){let n=t.consumeValueContainer(),r={type:`TOMLValue`,kind:`boolean`,value:e.boolean,parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)};return n.set(r)}processDateTimeValue(e,t){let n=t.consumeValueContainer(),r={type:`TOMLValue`,kind:bi[e.type],value:e.date,datetime:e.value,parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)};return n.set(r)}processArray(e,t){let n=t.consumeValueContainer(),r={type:`TOMLArray`,elements:[],parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)},i=t.nextToken({valuesEnabled:!0});return isRightBracket(i)?(applyEndLoc(r,i),n.set(r)):(t.backToken(),this.processArrayValue(r,n,t))}processArrayValue(e,t,n){return n.addValueContainer({parent:e,set:r=>{e.elements.push(r);let i=n.nextToken({valuesEnabled:!0}),a=isComma(i);return a&&(i=n.nextToken({valuesEnabled:!0})),isRightBracket(i)?(applyEndLoc(e,i),t.set(e)):a?(n.backToken(),this.processArrayValue(e,t,n)):n.reportParseError(i?`missing-comma`:`unterminated-array`,i)}}),[`VALUE`]}processInlineTable(e,t){let n=t.consumeValueContainer(),r={type:`TOMLInlineTable`,body:[],parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)},i=this.tomlVersion.gte(1,1)?void 0:`invalid-inline-table-newline`,a=t.nextToken({needSameLine:i});if(a){if(isBare(a)||isString(a))return this.processInlineTableKeyValue(a,r,n,t);if(isRightBrace(a))return applyEndLoc(r,a),n.set(r)}return t.reportParseError(`unexpected-token`,a)}processInlineTableKeyValue(e,t,n,r){let i={type:`TOMLKeyValue`,key:null,value:null,parent:t,range:cloneRange(e.range),loc:cloneLoc(e.loc)};t.body.push(i);let{nextToken:a}=this.processKeyNode(e,i,r);if(!isEq(a))return r.reportParseError(`missing-equals-sign`,a);let o=this.tomlVersion.gte(1,1)?void 0:`invalid-inline-table-newline`;return r.addValueContainer({parent:i,set:e=>{i.value=e,applyEndLoc(i,e);let a=r.nextToken({needSameLine:o});if(isComma(a)){if(a=r.nextToken({needSameLine:o}),a&&(isBare(a)||isString(a)))return this.processInlineTableKeyValue(a,t,n,r);if(isRightBrace(a)){if(this.tomlVersion.lt(1,1))return r.reportParseError(`invalid-trailing-comma-in-inline-table`,a)}else return r.reportParseError(a?`unexpected-token`:`unterminated-inline-table`,a)}return isRightBrace(a)?(applyEndLoc(t,a),n.set(t)):r.reportParseError(a?`missing-comma`:`unterminated-inline-table`,a)}}),r.needSameLine=`invalid-key-value-newline`,[`VALUE`]}};function isDot(e){return isPunctuator(e)&&e.value===`.`}function isEq(e){return isPunctuator(e)&&e.value===`=`}function isLeftBracket(e){return isPunctuator(e)&&e.value===`[`}function isRightBracket(e){return isPunctuator(e)&&e.value===`]`}function isLeftBrace(e){return isPunctuator(e)&&e.value===`{`}function isRightBrace(e){return isPunctuator(e)&&e.value===`}`}function isComma(e){return isPunctuator(e)&&e.value===`,`}function isPunctuator(e){return!!(e&&e.type===`Punctuator`)}function isBare(e){return e.type===`Bare`}function isString(e){return e.type===`BasicString`||e.type===`LiteralString`}function isMultiLineString(e){return e.type===`MultiLineBasicString`||e.type===`MultiLineLiteralString`}function isNumber(e){return e.type===`Integer`||e.type===`Float`}function isBoolean(e){return e.type===`Boolean`}function isDateTime(e){return e.type===`OffsetDateTime`||e.type===`LocalDateTime`||e.type===`LocalDate`||e.type===`LocalTime`}function applyEndLoc(e,t){t&&(e.range[1]=t.range[1],e.loc.end=clonePos(t.loc.end))}function cloneRange(e){return[e[0],e[1]]}function cloneLoc(e){return{start:clonePos(e.start),end:clonePos(e.end)}}function clonePos(e){return{line:e.line,column:e.column}}const xi=unionWith({Program:[`body`],TOMLTopLevelTable:[`body`],TOMLTable:[`key`,`body`],TOMLKeyValue:[`key`,`value`],TOMLKey:[`keys`],TOMLArray:[`elements`],TOMLInlineTable:[`body`],TOMLBare:[],TOMLQuoted:[],TOMLValue:[]});function parseForESLint(e,t){return{ast:new TOMLParser(e,t).parse(),visitorKeys:xi,services:{isTOML:!0}}}function parseTOML(e,t){return parseForESLint(e,t).ast}function nested(e,t){return e.reduceRight((e,t)=>({[t]:e}),t)}function renderTomlTable(e,t){return stringify(nested(e,t))}function appendTomlTable(e,t,n){return`${e}${e===``||e.endsWith(`
|
|
462
462
|
`)?``:`
|
|
463
|
-
`}\n${renderTomlTable(t,n)}`}function keyNames(e){return e.keys.map(e=>e.type===`TOMLBare`?e.name:e.value)}function startsWith(e,t){return t.length<=e.length&&t.every((t,n)=>e[n]===t)}function overlaps(e,t){return startsWith(e,t)||startsWith(t,e)}function replaceTomlTable(e,t,n){let r;try{r=parseTOML(e)}catch{return{kind:`refused`,reason:`unreadable`}}let i=[];for(let e of r.body[0].body){if(e.type===`TOMLKeyValue`){if(overlaps(keyNames(e.key),t))return{kind:`refused`,reason:`shape`};continue}if(startsWith(e.resolvedKey,t)){if(e.kind===`array`)return{kind:`refused`,reason:`shape`};i.push(e);continue}let n=e.resolvedKey;if(e.body.some(e=>overlaps([...n,...keyNames(e.key)],t)))return{kind:`refused`,reason:`shape`}}if(!i.length)return{kind:`refused`,reason:`absent`};if(!i.some(e=>e.resolvedKey.length===t.length))return{kind:`refused`,reason:`shape`};let a=i.map(t=>{let n=e.slice(t.range[1]).search(/\r?\n/);return[t.range[0],n<0?e.length:t.range[1]+n]}),inside=e=>a.some(([t,n])=>t<=e&&e<n);if(r.comments.some(e=>inside(e.range[0])))return{kind:`refused`,reason:`comment`};let[o,...s]=a,c=e;for(let[e,t]of s.reverse()){let n=c.slice(0,e),r=c.slice(t).replace(/^\r?\n/,``);c=/\n\r?\n$/.test(n)?`${n}${r.replace(/^\r?\n/,``)}`:`${n}${r}`}let l=renderTomlTable(t,n).trimEnd();return{kind:`edited`,text:`${c.slice(0,o[0])}${l}${c.slice(o[1])}`}}const
|
|
463
|
+
`}\n${renderTomlTable(t,n)}`}function keyNames(e){return e.keys.map(e=>e.type===`TOMLBare`?e.name:e.value)}function startsWith(e,t){return t.length<=e.length&&t.every((t,n)=>e[n]===t)}function overlaps(e,t){return startsWith(e,t)||startsWith(t,e)}function replaceTomlTable(e,t,n){let r;try{r=parseTOML(e)}catch{return{kind:`refused`,reason:`unreadable`}}let i=[];for(let e of r.body[0].body){if(e.type===`TOMLKeyValue`){if(overlaps(keyNames(e.key),t))return{kind:`refused`,reason:`shape`};continue}if(startsWith(e.resolvedKey,t)){if(e.kind===`array`)return{kind:`refused`,reason:`shape`};i.push(e);continue}let n=e.resolvedKey;if(e.body.some(e=>overlaps([...n,...keyNames(e.key)],t)))return{kind:`refused`,reason:`shape`}}if(!i.length)return{kind:`refused`,reason:`absent`};if(!i.some(e=>e.resolvedKey.length===t.length))return{kind:`refused`,reason:`shape`};let a=i.map(t=>{let n=e.slice(t.range[1]).search(/\r?\n/);return[t.range[0],n<0?e.length:t.range[1]+n]}),inside=e=>a.some(([t,n])=>t<=e&&e<n);if(r.comments.some(e=>inside(e.range[0])))return{kind:`refused`,reason:`comment`};let[o,...s]=a,c=e;for(let[e,t]of s.reverse()){let n=c.slice(0,e),r=c.slice(t).replace(/^\r?\n/,``);c=/\n\r?\n$/.test(n)?`${n}${r.replace(/^\r?\n/,``)}`:`${n}${r}`}let l=renderTomlTable(t,n).trimEnd();return{kind:`edited`,text:`${c.slice(0,o[0])}${l}${c.slice(o[1])}`}}const Si=/^[A-Za-z0-9_-]+$/;function tomlKey(e){return Si.test(e)?e:JSON.stringify(e)}function renderTomlInline(e){return typeof e==`object`&&e&&!Array.isArray(e)?`{ ${Object.entries(e).map(([e,t])=>`${tomlKey(e)} = ${renderTomlInline(t)}`).join(`, `)} }`:stringify({v:e}).slice(4).trimEnd()}function appendInlineTomlTable(e,t,n){let r=e===``||e.endsWith(`
|
|
464
464
|
`)?``:`
|
|
465
465
|
`,i=Object.entries(n).map(([e,t])=>`${tomlKey(e)} = ${renderTomlInline(t)}\n`);return`${e}${r}\n[${t.map(tomlKey).join(`.`)}]\n${i.join(``)}`}function lineEndAt(e,t){let n=e.indexOf(`
|
|
466
466
|
`,t);return n===-1?e.length:n}function setTomlKey(e,t,n,r){let i;try{i=parseTOML(e)}catch{return{kind:`refused`,reason:`unreadable`}}let a=i.body[0].body.filter(e=>e.type===`TOMLTable`),o=a.find(e=>e.kind===`standard`&&e.resolvedKey.length===t.length&&startsWith(e.resolvedKey,t));if(!o)return{kind:`refused`,reason:`absent`};let s=o.body;if(a.some(e=>startsWith(e.resolvedKey,[...t,n]))||s.some(e=>keyNames(e.key)[0]===n&&e.key.keys.length>1))return{kind:`refused`,reason:`shape`};let c=s.find(e=>e.key.keys.length===1&&keyNames(e.key)[0]===n);if(c&&r!==void 0)return{kind:`edited`,text:`${e.slice(0,c.value.range[0])}${renderTomlInline(r)}${e.slice(c.value.range[1])}`};if(c){let t=e.lastIndexOf(`
|
|
467
|
-
`,c.range[0]-1)+1,n=lineEndAt(e,c.range[1]);return{kind:`edited`,text:`${e.slice(0,t)}${e.slice(Math.min(n+1,e.length))}`}}if(r===void 0)return{kind:`edited`,text:e};let l=lineEndAt(e,s.at(-1)?.range[1]??o.range[0]);return{kind:`edited`,text:`${e.slice(0,l)}\n${tomlKey(n)} = ${renderTomlInline(r)}${e.slice(l)}`}}function read$1(e,t){let r=C(e,t);return n(r)?a(r,`utf8`):void 0}__name(read$1,`read`);const
|
|
467
|
+
`,c.range[0]-1)+1,n=lineEndAt(e,c.range[1]);return{kind:`edited`,text:`${e.slice(0,t)}${e.slice(Math.min(n+1,e.length))}`}}if(r===void 0)return{kind:`edited`,text:e};let l=lineEndAt(e,s.at(-1)?.range[1]??o.range[0]);return{kind:`edited`,text:`${e.slice(0,l)}\n${tomlKey(n)} = ${renderTomlInline(r)}${e.slice(l)}`}}function read$1(e,t){let r=C(e,t);return n(r)?a(r,`utf8`):void 0}__name(read$1,`read`);const Ci={both:`both sides changed since the last projection — a three-way conflict for a person to settle, never imported`,unknown:`no baseline says which side changed — compare the two by hand; never imported`};function inferredTransport(e){return e.url===void 0?`stdio`:`http`}function mapValue(e,t){let n=Object.entries(e).flatMap(([e])=>{let n=isRecord(t)?t[e]:void 0;return typeof n==`string`?[[e,n]]:[]});return n.length?Object.fromEntries(n):void 0}function reconcileMcp({root:e,git:t,accept:n}){let r=read$1(e,Y),i=parseGoldenSet(r);if(i.kind!==`servers`)return i;let a=parseProjectionRecord(read$1(e,jr)),o=new McpBaseline({git:t,record:a}),s=[],c=[];for(let t of mcpTargets(e)){let n=parseTarget(t,read$1(e,t.path));if(n.kind===`unreadable`){s.push({path:t.path,action:`refuse`,detail:`the target does not parse`});continue}if(n.kind===`absent`)continue;let r=Er[t.dialect];for(let[e,a]of n.servers){let n=i.servers.get(e),at=n=>locatorText({file:t.path,server:e,field:n}),offer=(i,o)=>{let l=literalsIn(i,o);for(let e of l)s.push({path:at(e),action:`refuse`,detail:`${e} holds a literal credential, which never enters the golden set — set it in the environment and reference it as \${VAR}`});let u=withoutLiterals(i,o,l,n);if(l.length&&(u===void 0||sameField(i,{[i]:u},n)))return;let d=r.defaults?.[i];if(d!==void 0&&sameField(i,{[i]:u},{[i]:d})){s.push({path:at(i),action:`skip`,detail:`${t.dialect} fills this in by default, so it may not be the user's — set it in the golden set by hand if it is`});return}let f={path:at(i),action:`import`,detail:n?`only the harness changed it — approve to take it into the golden set`:`the golden set does not declare this server — approve each field to add it`,value:u===void 0?`(unset)`:`${i} = ${renderTomlInline(u)}`};s.push(f),c.push({row:f,config:t,server:e,field:i,value:u,carried:a,adds:!n})};if(!n){for(let e of _r)r.fields.has(e)&&a[e]!==void 0&&(e!==`transport`||a.transport!==inferredTransport(a))&&offer(e,a[e]);continue}for(let i of divergingFields(n,a,r.fields)){let r=o.directionOf(t,e,i,n,a);r!==`golden`&&(r===`target`?offer(i,i===`env`||i===`headers`?mapValue(n[i],a[i]):a[i]):s.push({path:at(i),action:`skip`,detail:Ci[r]}))}}}if(!n.length)return{kind:`planned`,rows:s,written:!1};let l=approve(c,s,n);if(l.kind===`rejected`)return l;let u=r,d=[];for(let[e,t]of groupByServer(l.offers)){if(t[0]?.adds){let n=Object.fromEntries(_r.flatMap(e=>{let n=t.find(t=>t.field===e);return n?[[e,n.value]]:[]}));u=land(u,appendInlineTomlTable(u,[`servers`,e],n),e,n,t,d);continue}for(let n of t){let t={...parseGoldenSet(u).servers.get(e),[n.field]:n.value};n.value===void 0&&delete t[n.field];let r=setTomlKey(u,[`servers`,e],n.field,n.value);u=land(u,r.kind===`edited`?r.text:void 0,e,t,[n],d)}}return u!==r&&(m(C(e,Y),u),writeRecord$1(e,a,o,d,parseGoldenSet(u))),{kind:`planned`,rows:s,written:!0}}function literalsIn(e,t){return t===void 0?[]:e===`args`?nonSecretArgs(t).length===t.length?[]:[`args`]:e!==`env`&&e!==`headers`&&e!==`url`?[]:credentialFields({[e]:t})}function withoutLiterals(e,t,n,r){if(!n.length)return t;if(e!==`env`&&e!==`headers`)return;let i={...t};for(let t of n){let n=t.slice(e.length+1),a=r?.[e]?.[n];a===void 0?delete i[n]:i[n]=a}return Object.keys(i).length?i:void 0}function approve(e,t,n){let r=[],i=[];for(let a of new Set(n)){let n=e.find(e=>e.row.path===a);if(n)i.push(n);else{let e=t.find(e=>e.path===a);r.push(e?`${a} is ${e.action}, not importable: ${e.detail}`:`${a} names no importable field`)}}for(let[e,t]of groupByServer(i)){for(let n of new Set(t.map(e=>e.field))){let i=t.filter(e=>e.field===n);i.some(e=>!sameField(n,{[n]:e.value},{[n]:i[0]?.value}))&&r.push(`servers.${e}.${n} is approved from more than one target with different values — approve one`)}t[0]?.adds&&!t.some(e=>e.field===`command`||e.field===`url`)&&r.push(`servers.${e} would be added with nothing to run — approve its command or url too`)}return r.length?{kind:`rejected`,reasons:r}:{kind:`approved`,offers:i}}function groupByServer(e){let t=new Map;for(let n of e)t.set(n.server,[...t.get(n.server)??[],n]);return t}function land(e,t,n,r,i,a){let o=parseGoldenSet(e),s=t===void 0?void 0:parseGoldenSet(t),c=s?.kind===`servers`&&_r.every(e=>e===`transport`&&r.transport===void 0||sameField(e,s.servers.get(n),r))&&[...o.servers].every(([e,t])=>e===n||JSON.stringify(s.servers.get(e))===JSON.stringify(t));for(let e of i)e.row.action=c?`imported`:`edit`,e.row.detail=c?`written into the golden set`:`the golden set writes this server in a shape that cannot be edited byte-safely — apply the value by hand`;return c?(a.push(...i),t):e}function writeRecord$1(e,t,n,r,a){for(let e of r){let r=t.get(e.config.path)??new Map,i=r.get(e.server),o=i?{...i,[e.field]:e.value}:baseEntry(e,n,a.servers.get(e.server));o&&(e.value===void 0&&delete o[e.field],r.set(e.server,o),t.set(e.config.path,r))}let o=C(e,jr);i(b(o),{recursive:!0}),m(o,formatProjectionRecord(t))}__name(writeRecord$1,`writeRecord`);function baseEntry(e,t,n){if(e.adds)return{...n};let r={};for(let i of Er[e.config.dialect].fields){if(n[i]===void 0)continue;if(sameField(i,n,e.carried)){r[i]=n[i];continue}let a=t.baseFor(e.config,e.server,i);if(!a)return;r[i]=a[i]}return r}const wi=command({name:`reconcile`,description:`Import a harness-side MCP change into the golden set, one approved field at a time. A dry run unless --accept names a field.`,options:{root:{description:`Repository or package directory. Defaults to the current directory.`,type:N.string().optional()},accept:{description:`Approve one field by the path a dry run lists for it; repeat for each field. There is no approve-all.`,type:N.array(N.string()).optional()}},examples:[{command:`buddy-agent-harness mcp reconcile`,description:`List harness-side changes the golden set lacks`},{command:`buddy-agent-harness mcp reconcile --accept <path>`,description:`Import one approved field`}],run(e){try{let t=e.root??process.cwd(),n=e.accept??[],r=reconcileMcp({root:t,git:new GitBridgeState(t),accept:n});if(r.kind===`unreadable`){let e=r.position?` at line ${r.position.line}, column ${r.position.column}`:``;throw new M(`${Y} does not parse${e}.`,{code:`golden-set-unreadable`,help:`Fix the TOML syntax in ${Y}, then re-run.`})}if(r.kind===`rejected`)throw new M(`nothing written.`,{code:`accept-rejected`,details:{reasons:r.reasons},help:ref(`mcp reconcile`,{},`list the fields that can be approved`)});return r.kind===`absent`?empty(`0 servers — no golden set at ${Y}`,{help:`Create ${Y} first; there is nothing to reconcile into.`}):result({golden:Y,mode:r.written?`written — only the fields named by --accept`:`dry run — nothing written; re-run with --accept <path> for each approved field`,fields:r.rows.length?r.rows:`0 fields — no harness holds a change the golden set lacks`,record:r.written?jr:`not written — dry run`})}catch(e){return fail(e,`MCP reconcile failed.`)}}});function createScanner(e,t=!1){let n=e.length,r=0,i=``,a=0,o=16,s=0,c=0,l=0,u=0,d=0;function scanHexDigits(t,n){let i=0,a=0;for(;i<t||!n;){let t=e.charCodeAt(r);if(t>=48&&t<=57)a=a*16+t-48;else if(t>=65&&t<=70)a=a*16+t-65+10;else if(t>=97&&t<=102)a=a*16+t-97+10;else break;r++,i++}return i<t&&(a=-1),a}function setPosition(e){r=e,i=``,a=0,o=16,d=0}function scanNumber(){let t=r;if(e.charCodeAt(r)===48)r++;else for(r++;r<e.length&&isDigit(e.charCodeAt(r));)r++;if(r<e.length&&e.charCodeAt(r)===46){if(r++,r<e.length&&isDigit(e.charCodeAt(r)))for(r++;r<e.length&&isDigit(e.charCodeAt(r));)r++;else return d=3,e.substring(t,r)}let n=r;if(r<e.length&&(e.charCodeAt(r)===69||e.charCodeAt(r)===101)){if(r++,(r<e.length&&e.charCodeAt(r)===43||e.charCodeAt(r)===45)&&r++,r<e.length&&isDigit(e.charCodeAt(r))){for(r++;r<e.length&&isDigit(e.charCodeAt(r));)r++;n=r}else d=3}return e.substring(t,n)}function scanString(){let t=``,i=r;for(;;){if(r>=n){t+=e.substring(i,r),d=2;break}let a=e.charCodeAt(r);if(a===34){t+=e.substring(i,r),r++;break}if(a===92){if(t+=e.substring(i,r),r++,r>=n){d=2;break}switch(e.charCodeAt(r++)){case 34:t+=`"`;break;case 92:t+=`\\`;break;case 47:t+=`/`;break;case 98:t+=`\b`;break;case 102:t+=`\f`;break;case 110:t+=`
|
|
468
468
|
`;break;case 114:t+=`\r`;break;case 116:t+=` `;break;case 117:let e=scanHexDigits(4,!0);e>=0?t+=String.fromCharCode(e):d=4;break;default:d=5}i=r;continue}if(a>=0&&a<=31){if(isLineBreak(a)){t+=e.substring(i,r),d=2;break}d=6}r++}return t}function scanNext(){if(i=``,d=0,a=r,c=s,u=l,r>=n)return a=n,o=17;let t=e.charCodeAt(r);if(isWhiteSpace(t)){do r++,i+=String.fromCharCode(t),t=e.charCodeAt(r);while(isWhiteSpace(t));return o=15}if(isLineBreak(t))return r++,i+=String.fromCharCode(t),t===13&&e.charCodeAt(r)===10&&(r++,i+=`
|
|
469
|
-
`),s++,l=r,o=14;switch(t){case 123:return r++,o=1;case 125:return r++,o=2;case 91:return r++,o=3;case 93:return r++,o=4;case 58:return r++,o=6;case 44:return r++,o=5;case 34:return r++,i=scanString(),o=10;case 47:let c=r-1;if(e.charCodeAt(r+1)===47){for(r+=2;r<n&&!isLineBreak(e.charCodeAt(r));)r++;return i=e.substring(c,r),o=12}if(e.charCodeAt(r+1)===42){r+=2;let t=n-1,a=!1;for(;r<t;){let t=e.charCodeAt(r);if(t===42&&e.charCodeAt(r+1)===47){r+=2,a=!0;break}r++,isLineBreak(t)&&(t===13&&e.charCodeAt(r)===10&&r++,s++,l=r)}return a||(r++,d=1),i=e.substring(c,r),o=13}return i+=String.fromCharCode(t),r++,o=16;case 45:if(i+=String.fromCharCode(t),r++,r===n||!isDigit(e.charCodeAt(r)))return o=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return i+=scanNumber(),o=11;default:for(;r<n&&isUnknownContentCharacter(t);)r++,t=e.charCodeAt(r);if(a!==r){switch(i=e.substring(a,r),i){case`true`:return o=8;case`false`:return o=9;case`null`:return o=7}return o=16}return i+=String.fromCharCode(t),r++,o=16}}function isUnknownContentCharacter(e){if(isWhiteSpace(e)||isLineBreak(e))return!1;switch(e){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function scanNextNonTrivia(){let e;do e=scanNext();while(e>=12&&e<=15);return e}return{setPosition,getPosition:()=>r,scan:t?scanNextNonTrivia:scanNext,getToken:()=>o,getTokenValue:()=>i,getTokenOffset:()=>a,getTokenLength:()=>r-a,getTokenStartLine:()=>c,getTokenStartCharacter:()=>a-u,getTokenError:()=>d}}function isWhiteSpace(e){return e===32||e===9}function isLineBreak(e){return e===10||e===13}function isDigit(e){return e>=48&&e<=57}var
|
|
469
|
+
`),s++,l=r,o=14;switch(t){case 123:return r++,o=1;case 125:return r++,o=2;case 91:return r++,o=3;case 93:return r++,o=4;case 58:return r++,o=6;case 44:return r++,o=5;case 34:return r++,i=scanString(),o=10;case 47:let c=r-1;if(e.charCodeAt(r+1)===47){for(r+=2;r<n&&!isLineBreak(e.charCodeAt(r));)r++;return i=e.substring(c,r),o=12}if(e.charCodeAt(r+1)===42){r+=2;let t=n-1,a=!1;for(;r<t;){let t=e.charCodeAt(r);if(t===42&&e.charCodeAt(r+1)===47){r+=2,a=!0;break}r++,isLineBreak(t)&&(t===13&&e.charCodeAt(r)===10&&r++,s++,l=r)}return a||(r++,d=1),i=e.substring(c,r),o=13}return i+=String.fromCharCode(t),r++,o=16;case 45:if(i+=String.fromCharCode(t),r++,r===n||!isDigit(e.charCodeAt(r)))return o=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return i+=scanNumber(),o=11;default:for(;r<n&&isUnknownContentCharacter(t);)r++,t=e.charCodeAt(r);if(a!==r){switch(i=e.substring(a,r),i){case`true`:return o=8;case`false`:return o=9;case`null`:return o=7}return o=16}return i+=String.fromCharCode(t),r++,o=16}}function isUnknownContentCharacter(e){if(isWhiteSpace(e)||isLineBreak(e))return!1;switch(e){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function scanNextNonTrivia(){let e;do e=scanNext();while(e>=12&&e<=15);return e}return{setPosition,getPosition:()=>r,scan:t?scanNextNonTrivia:scanNext,getToken:()=>o,getTokenValue:()=>i,getTokenOffset:()=>a,getTokenLength:()=>r-a,getTokenStartLine:()=>c,getTokenStartCharacter:()=>a-u,getTokenError:()=>d}}function isWhiteSpace(e){return e===32||e===9}function isLineBreak(e){return e===10||e===13}function isDigit(e){return e>=48&&e<=57}var Ti;(function(e){e[e.lineFeed=10]=`lineFeed`,e[e.carriageReturn=13]=`carriageReturn`,e[e.space=32]=`space`,e[e._0=48]=`_0`,e[e._1=49]=`_1`,e[e._2=50]=`_2`,e[e._3=51]=`_3`,e[e._4=52]=`_4`,e[e._5=53]=`_5`,e[e._6=54]=`_6`,e[e._7=55]=`_7`,e[e._8=56]=`_8`,e[e._9=57]=`_9`,e[e.a=97]=`a`,e[e.b=98]=`b`,e[e.c=99]=`c`,e[e.d=100]=`d`,e[e.e=101]=`e`,e[e.f=102]=`f`,e[e.g=103]=`g`,e[e.h=104]=`h`,e[e.i=105]=`i`,e[e.j=106]=`j`,e[e.k=107]=`k`,e[e.l=108]=`l`,e[e.m=109]=`m`,e[e.n=110]=`n`,e[e.o=111]=`o`,e[e.p=112]=`p`,e[e.q=113]=`q`,e[e.r=114]=`r`,e[e.s=115]=`s`,e[e.t=116]=`t`,e[e.u=117]=`u`,e[e.v=118]=`v`,e[e.w=119]=`w`,e[e.x=120]=`x`,e[e.y=121]=`y`,e[e.z=122]=`z`,e[e.A=65]=`A`,e[e.B=66]=`B`,e[e.C=67]=`C`,e[e.D=68]=`D`,e[e.E=69]=`E`,e[e.F=70]=`F`,e[e.G=71]=`G`,e[e.H=72]=`H`,e[e.I=73]=`I`,e[e.J=74]=`J`,e[e.K=75]=`K`,e[e.L=76]=`L`,e[e.M=77]=`M`,e[e.N=78]=`N`,e[e.O=79]=`O`,e[e.P=80]=`P`,e[e.Q=81]=`Q`,e[e.R=82]=`R`,e[e.S=83]=`S`,e[e.T=84]=`T`,e[e.U=85]=`U`,e[e.V=86]=`V`,e[e.W=87]=`W`,e[e.X=88]=`X`,e[e.Y=89]=`Y`,e[e.Z=90]=`Z`,e[e.asterisk=42]=`asterisk`,e[e.backslash=92]=`backslash`,e[e.closeBrace=125]=`closeBrace`,e[e.closeBracket=93]=`closeBracket`,e[e.colon=58]=`colon`,e[e.comma=44]=`comma`,e[e.dot=46]=`dot`,e[e.doubleQuote=34]=`doubleQuote`,e[e.minus=45]=`minus`,e[e.openBrace=123]=`openBrace`,e[e.openBracket=91]=`openBracket`,e[e.plus=43]=`plus`,e[e.slash=47]=`slash`,e[e.formFeed=12]=`formFeed`,e[e.tab=9]=`tab`})(Ti||={}),Array(20).fill(0).map((e,t)=>` `.repeat(t)),Array(200).fill(0).map((e,t)=>`
|
|
470
470
|
`+` `.repeat(t)),Array(200).fill(0).map((e,t)=>`\r`+` `.repeat(t)),Array(200).fill(0).map((e,t)=>`\r
|
|
471
471
|
`+` `.repeat(t)),Array(200).fill(0).map((e,t)=>`
|
|
472
472
|
`+` `.repeat(t)),Array(200).fill(0).map((e,t)=>`\r`+` `.repeat(t)),Array(200).fill(0).map((e,t)=>`\r
|
|
473
|
-
`+` `.repeat(t));var
|
|
474
|
-
`,`\n${t.repeat(n)}`)}function objectAt(e,t){let n=e&&(t.length?
|
|
473
|
+
`+` `.repeat(t));var Ei;(function(e){e.DEFAULT={allowTrailingComma:!1}})(Ei||={});function parseTree$1(e,t=[],n=Ei.DEFAULT){let r={type:`array`,offset:-1,length:-1,children:[],parent:void 0};function ensurePropertyComplete(e){r.type===`property`&&(r.length=e-r.offset,r=r.parent)}function onValue(e){return r.children.push(e),e}visit(e,{onObjectBegin:e=>{r=onValue({type:`object`,offset:e,length:-1,parent:r,children:[]})},onObjectProperty:(e,t,n)=>{r=onValue({type:`property`,offset:t,length:-1,parent:r,children:[]}),r.children.push({type:`string`,value:e,offset:t,length:n,parent:r})},onObjectEnd:(e,t)=>{ensurePropertyComplete(e+t),r.length=e+t-r.offset,r=r.parent,ensurePropertyComplete(e+t)},onArrayBegin:(e,t)=>{r=onValue({type:`array`,offset:e,length:-1,parent:r,children:[]})},onArrayEnd:(e,t)=>{r.length=e+t-r.offset,r=r.parent,ensurePropertyComplete(e+t)},onLiteralValue:(e,t,n)=>{onValue({type:getNodeType(e),offset:t,length:n,parent:r,value:e}),ensurePropertyComplete(t+n)},onSeparator:(e,t,n)=>{r.type===`property`&&(e===`:`?r.colonOffset=t:e===`,`&&ensurePropertyComplete(t))},onError:(e,n,r)=>{t.push({error:e,offset:n,length:r})}},n);let i=r.children[0];return i&&delete i.parent,i}__name(parseTree$1,`parseTree`);function findNodeAtLocation$1(e,t){if(!e)return;let n=e;for(let e of t)if(typeof e==`string`){if(n.type!==`object`||!Array.isArray(n.children))return;let t=!1;for(let r of n.children)if(Array.isArray(r.children)&&r.children[0].value===e&&r.children.length===2){n=r.children[1],t=!0;break}if(!t)return}else{let t=e;if(n.type!==`array`||t<0||!Array.isArray(n.children)||t>=n.children.length)return;n=n.children[t]}return n}__name(findNodeAtLocation$1,`findNodeAtLocation`);function visit(e,t,n=Ei.DEFAULT){let r=createScanner(e,!1),i=[],a=0;function toNoArgVisit(e){return e?()=>a===0&&e(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter()):()=>!0}function toOneArgVisit(e){return e?t=>a===0&&e(t,r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter()):()=>!0}function toOneArgVisitWithPath(e){return e?t=>a===0&&e(t,r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter(),()=>i.slice()):()=>!0}function toBeginVisit(e){return e?()=>{a>0?a++:e(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter(),()=>i.slice())===!1&&(a=1)}:()=>!0}function toEndVisit(e){return e?()=>{a>0&&a--,a===0&&e(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter())}:()=>!0}let o=toBeginVisit(t.onObjectBegin),s=toOneArgVisitWithPath(t.onObjectProperty),c=toEndVisit(t.onObjectEnd),l=toBeginVisit(t.onArrayBegin),u=toEndVisit(t.onArrayEnd),d=toOneArgVisitWithPath(t.onLiteralValue),f=toOneArgVisit(t.onSeparator),p=toNoArgVisit(t.onComment),m=toOneArgVisit(t.onError),h=n&&n.disallowComments,g=n&&n.allowTrailingComma;function scanNext(){for(;;){let e=r.scan();switch(r.getTokenError()){case 4:handleError(14);break;case 5:handleError(15);break;case 3:handleError(13);break;case 1:h||handleError(11);break;case 2:handleError(12);break;case 6:handleError(16)}switch(e){case 12:case 13:h?handleError(10):p();break;case 16:handleError(1);break;case 15:case 14:break;default:return e}}}function handleError(e,t=[],n=[]){if(m(e),t.length+n.length>0){let e=r.getToken();for(;e!==17;){if(t.indexOf(e)!==-1){scanNext();break}if(n.indexOf(e)!==-1)break;e=scanNext()}}}function parseString(e){let t=r.getTokenValue();return e?d(t):(s(t),i.push(t)),scanNext(),!0}function parseLiteral(){switch(r.getToken()){case 11:let e=r.getTokenValue(),t=Number(e);isNaN(t)&&(handleError(2),t=0),d(t);break;case 7:d(null);break;case 8:d(!0);break;case 9:d(!1);break;default:return!1}return scanNext(),!0}function parseProperty(){return r.getToken()===10?(parseString(!1),r.getToken()===6?(f(`:`),scanNext(),parseValue()||handleError(4,[],[2,5])):handleError(5,[],[2,5]),i.pop(),!0):(handleError(3,[],[2,5]),!1)}function parseObject(){o(),scanNext();let e=!1;for(;r.getToken()!==2&&r.getToken()!==17;){if(r.getToken()===5){if(e||handleError(4,[],[]),f(`,`),scanNext(),r.getToken()===2&&g)break}else e&&handleError(6,[],[]);parseProperty()||handleError(4,[],[2,5]),e=!0}return c(),r.getToken()===2?scanNext():handleError(7,[2],[]),!0}function parseArray(){l(),scanNext();let e=!0,t=!1;for(;r.getToken()!==4&&r.getToken()!==17;){if(r.getToken()===5){if(t||handleError(4,[],[]),f(`,`),scanNext(),r.getToken()===4&&g)break}else t&&handleError(6,[],[]);e?(i.push(0),e=!1):i[i.length-1]++,parseValue()||handleError(4,[],[4,5]),t=!0}return u(),e||i.pop(),r.getToken()===4?scanNext():handleError(8,[4],[]),!0}function parseValue(){switch(r.getToken()){case 3:return parseArray();case 1:return parseObject();case 10:return parseString(!0);default:return parseLiteral()}}return scanNext(),r.getToken()===17?n.allowEmptyContent?!0:(handleError(4,[],[]),!1):parseValue()?(r.getToken()!==17&&handleError(9,[],[]),!0):(handleError(4,[],[]),!1)}function getNodeType(e){switch(typeof e){case`boolean`:return`boolean`;case`number`:return`number`;case`string`:return`string`;case`object`:return e?Array.isArray(e)?`array`:`object`:`null`;default:return`null`}}var Di;(function(e){e[e.None=0]=`None`,e[e.UnexpectedEndOfComment=1]=`UnexpectedEndOfComment`,e[e.UnexpectedEndOfString=2]=`UnexpectedEndOfString`,e[e.UnexpectedEndOfNumber=3]=`UnexpectedEndOfNumber`,e[e.InvalidUnicode=4]=`InvalidUnicode`,e[e.InvalidEscapeCharacter=5]=`InvalidEscapeCharacter`,e[e.InvalidCharacter=6]=`InvalidCharacter`})(Di||={});var Oi;(function(e){e[e.OpenBraceToken=1]=`OpenBraceToken`,e[e.CloseBraceToken=2]=`CloseBraceToken`,e[e.OpenBracketToken=3]=`OpenBracketToken`,e[e.CloseBracketToken=4]=`CloseBracketToken`,e[e.CommaToken=5]=`CommaToken`,e[e.ColonToken=6]=`ColonToken`,e[e.NullKeyword=7]=`NullKeyword`,e[e.TrueKeyword=8]=`TrueKeyword`,e[e.FalseKeyword=9]=`FalseKeyword`,e[e.StringLiteral=10]=`StringLiteral`,e[e.NumericLiteral=11]=`NumericLiteral`,e[e.LineCommentTrivia=12]=`LineCommentTrivia`,e[e.BlockCommentTrivia=13]=`BlockCommentTrivia`,e[e.LineBreakTrivia=14]=`LineBreakTrivia`,e[e.Trivia=15]=`Trivia`,e[e.Unknown=16]=`Unknown`,e[e.EOF=17]=`EOF`})(Oi||={});const ki=parseTree$1,Ai=findNodeAtLocation$1;var ji;(function(e){e[e.InvalidSymbol=1]=`InvalidSymbol`,e[e.InvalidNumberFormat=2]=`InvalidNumberFormat`,e[e.PropertyNameExpected=3]=`PropertyNameExpected`,e[e.ValueExpected=4]=`ValueExpected`,e[e.ColonExpected=5]=`ColonExpected`,e[e.CommaExpected=6]=`CommaExpected`,e[e.CloseBraceExpected=7]=`CloseBraceExpected`,e[e.CloseBracketExpected=8]=`CloseBracketExpected`,e[e.EndOfFileExpected=9]=`EndOfFileExpected`,e[e.InvalidCommentToken=10]=`InvalidCommentToken`,e[e.UnexpectedEndOfComment=11]=`UnexpectedEndOfComment`,e[e.UnexpectedEndOfString=12]=`UnexpectedEndOfString`,e[e.UnexpectedEndOfNumber=13]=`UnexpectedEndOfNumber`,e[e.InvalidUnicode=14]=`InvalidUnicode`,e[e.InvalidEscapeCharacter=15]=`InvalidEscapeCharacter`,e[e.InvalidCharacter=16]=`InvalidCharacter`})(ji||={});function indentUnit(e){let t=/\n([ \t]+)\S/.exec(e);return t?t[1]:` `}function jsonAt(e,t,n){return JSON.stringify(e,null,t).replaceAll(`
|
|
474
|
+
`,`\n${t.repeat(n)}`)}function objectAt(e,t){let n=e&&(t.length?Ai(e,t):e);return n?.type===`object`?n:void 0}function insertJsonProperty(e,t,n,r){let i=objectAt(ki(e),t);if(!i||Ai(i,[n]))return;let a=t.length+1,o=indentUnit(e),s=`${o.repeat(a)}${JSON.stringify(n)}: ${jsonAt(r,o,a)}`,c=i.children?.at(-1);if(c){let t=c.offset+c.length;return`${e.slice(0,t)},\n${s}${e.slice(t)}`}let l=i.offset+1,u=i.offset+i.length-1;return`${e.slice(0,l)}\n${s}\n${o.repeat(a-1)}${e.slice(u)}`}function replaceJsonValue(e,t,n){let r=ki(e),i=r&&Ai(r,t);if(!i)return{kind:`refused`,reason:`absent`};let a=i.offset+i.length,o=e.slice(i.offset,a);return stripJsonComments(o)===o?{kind:`edited`,text:`${e.slice(0,i.offset)}${jsonAt(n,indentUnit(e),t.length)}${e.slice(a)}`}:{kind:`refused`,reason:`comment`}}function createFile(e,t,n){return e.format===`toml`?renderTomlTable([e.key,t],n):`${JSON.stringify({[e.key]:{[t]:n}},null,2)}\n`}function appendServer(e,t,n,r){return e.format===`toml`?appendTomlTable(t,[e.key,n],r):insertJsonProperty(t,[e.key],n,r)??insertJsonProperty(t,[],e.key,{[n]:r})}function replaceServer(e,t,n,r){let i=e.format===`toml`?replaceTomlTable(t,[e.key,n],r):replaceJsonValue(t,[e.key,n],r);return i.kind===`edited`?i.text:void 0}function renderEntry(e,t,n){return e.format===`toml`?renderTomlTable([e.key,t],n):JSON.stringify({[t]:n},null,2)}function read(e,t){let r=C(e,t);return n(r)?a(r,`utf8`):void 0}const Mi={target:`the target changed since the last projection — reconcile it into the golden set first`,both:`both sides changed since the last projection — a three-way conflict for a person to settle`,unknown:`no baseline says which side changed — compare the two by hand`};function heldBack(e){return[`both`,`unknown`,`target`].find(t=>e.includes(t))}function projectMcp({root:e,git:t,write:n}){let r=parseGoldenSet(read(e,Y));if(r.kind!==`servers`)return r;let i=parseProjectionRecord(read(e,jr)),a=new McpBaseline({git:t,record:i}),o=[],s=[],c=[];for(let t of mcpTargets(e)){let n=read(e,t.path),i=parseTarget(t,n);if(i.kind===`unreadable`){o.push({target:t.path,server:``,action:`refuse`,detail:`the target does not parse`});continue}let l={config:t,source:n,created:n===void 0,servers:i.kind===`servers`?i.servers:new Map,agreed:new Map};c.push(l);let u=Er[t.dialect];for(let[e,n]of r.servers){let row=(n,r)=>o.push({target:t.path,server:e,action:n,detail:r}),r=credentialFields(n)[0];if(r){row(`refuse`,`the golden set holds a literal credential at ${r} — reference it as \${VAR} first`);continue}let i=u.write(n);if(i.kind===`refused`){row(`refuse`,`${i.field}: ${i.reason}`);continue}let c=l.servers.get(e);if(!c){let r=l.source===void 0?createFile(t,e,i.entry):appendServer(t,l.source,e,i.entry);apply(l,e,n,i.entry,r,l.created?`creates the file`:`appends the server`,row,s);continue}let d=divergingFields(n,c,u.fields);if(!d.length){l.agreed.set(e,n);continue}let f=heldBack(d.map(r=>a.directionOf(t,e,r,n,c)));if(f){row(`skip`,Mi[f]);continue}let p=replaceServer(t,l.source,e,i.entry);apply(l,e,n,i.entry,p,`replaces ${d.join(`, `)}`,row,s)}}if(n){for(let t of c)t.source!==void 0&&t.source!==read(e,t.config.path)&&writeTarget(e,t);writeRecord(e,i,c)}return{kind:`planned`,rows:o,entries:s,written:n}}function apply(e,t,n,r,i,a,o,s){let c=!e.servers.has(t),l=i!==void 0&&readsBack(e,t,n,i),u=l?c?`add`:`update`:`edit`;if(s.push({target:e.config.path,server:t,action:u,entry:renderEntry(e.config,t,r)}),!l){o(`edit`,c?`the file has no safe place to add it — apply the entry by hand`:`an in-place change here is applied by hand`);return}e.source=i,e.servers=parseTarget(e.config,i).servers,e.agreed.set(t,n),o(u,a)}function readsBack(e,t,n,r){let i=parseTarget(e.config,r);if(i.kind!==`servers`)return!1;let a=i.servers.get(t),o=Er[e.config.dialect].fields;return!a||divergingFields(n,a,o).length?!1:[...e.servers].every(([e,n])=>{if(e===t)return!0;let r=i.servers.get(e);return r!==void 0&&JSON.stringify(r)===JSON.stringify(n)})}function writeTarget(e,t){let n=C(e,t.config.path);i(b(n),{recursive:!0}),m(n,t.source)}function writeRecord(e,t,n){for(let e of n){let n=t.get(e.config.path)??new Map;for(let[t,r]of e.agreed)n.set(t,r);n.size&&t.set(e.config.path,n)}let r=C(e,jr);i(b(r),{recursive:!0}),m(r,formatProjectionRecord(t))}const Ni={name:`buddy-agent-harness`,description:`Initialize agent harness skill compatibility in consumer repositories.`,commands:[ri,Qr,command({name:`mcp`,description:`Work with the golden MCP server set at .agents/buddy-agent-harness/mcp.toml.`,commands:[command({name:`project`,description:`Project the golden MCP server set into each enabled harness. A dry run unless --write; never overwrites a change made on the harness side.`,options:{root:{description:`Repository or package directory. Defaults to the current directory.`,type:N.string().optional()},write:{description:`Apply the plan and record what was projected. Without it nothing on disk changes.`,type:N.boolean().optional()}},examples:[{command:`buddy-agent-harness mcp project`,description:`Preview what would be projected`},{command:`buddy-agent-harness mcp project --write`,description:`Project the golden set into each harness`}],run(e){try{let t=e.root??process.cwd(),n=e.write===!0,r=projectMcp({root:t,git:new GitBridgeState(t),write:n});if(r.kind===`unreadable`){let e=r.position?` at line ${r.position.line}, column ${r.position.column}`:``;throw new M(`${Y} does not parse${e}.`,{code:`golden-set-unreadable`,help:`Fix the TOML syntax in ${Y}, then re-run.`})}return r.kind===`absent`?empty(`0 servers — no golden set at ${Y}`,{help:[`Create ${Y} with the MCP servers to project.`,ref(`mcp project`,{},`preview the projection`)]}):result({golden:Y,mode:n?`written`:`dry run — nothing written; re-run with --write to apply`,actions:r.rows.length?r.rows:`0 changes — every enabled harness already carries the golden set`,...r.entries.length?{entries:r.entries}:{},record:n?jr:`not written — dry run`})}catch(e){return fail(e,`MCP projection failed.`)}}}),wi]}),$n,qr,ni]};function app(e){let[t,...n]=Ni.commands;return n.reduce((e,t)=>e.command(t),cli({name:Ni.name,version:`1.3.0`,description:Ni.description,format:e}).default({description:"Report whether this repository's harness bridges resolve (the same as `doctor`).",options:Qr.options,async run(e){let{bin:t,...n}=await diagnoseReport({root:e.root,harness:e.harness});return result({...homeHeader({description:Ni.description}),...n})}}).command(t))}const Pi={reference:[`load`,`create`,`delete`],governance:[`show`]};function defaultFormat(e){let t=e.slice(2);if(t.some(e=>e===`--format`||e.startsWith(`--format=`)))return`toon`;let[n,r]=t;return n!==void 0&&r!==void 0&&Pi[n]?.includes(r)?`text`:`toon`}async function run(e){try{let t=await app(defaultFormat(e)).parse(e);return typeof t==`number`?t:j.success}catch(e){return process.stderr.write(`error: ${e instanceof Error?e.message:`Invalid command.`}\n`),j.usage}}process.exitCode=await run([...process.argv.slice(0,2),`init`,...process.argv.slice(2)]);export{};
|