adamantite 0.45.0 → 0.47.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.
Files changed (81) hide show
  1. package/README.md +447 -127
  2. package/dist/index.js +628 -57
  3. package/dist/oxlint.js +1 -0
  4. package/dist/presets/analyze.js +1 -0
  5. package/dist/presets/lint/{react-doctor.d.ts → architecture.d.ts} +1 -1
  6. package/dist/presets/lint/architecture.js +8 -0
  7. package/dist/presets/lint/core.js +1 -2
  8. package/dist/presets/lint/effect.js +26 -1
  9. package/dist/presets/lint/plugin/glob.d.ts +7 -0
  10. package/dist/presets/lint/plugin/glob.js +48 -0
  11. package/dist/presets/lint/plugin/imports.d.ts +4 -0
  12. package/dist/presets/lint/plugin/imports.js +4 -1
  13. package/dist/presets/lint/plugin/index.d.ts +3 -0
  14. package/dist/presets/lint/plugin/index.js +14 -8
  15. package/dist/presets/lint/plugin/options.d.ts +5 -5
  16. package/dist/presets/lint/plugin/options.js +19 -7
  17. package/dist/presets/lint/plugin/resolver.d.ts +8 -0
  18. package/dist/presets/lint/plugin/resolver.js +79 -0
  19. package/dist/presets/lint/plugin/rules/import-owners.d.ts +67 -0
  20. package/dist/presets/lint/plugin/rules/import-owners.js +310 -0
  21. package/dist/presets/lint/plugin/rules/layers.d.ts +136 -0
  22. package/dist/presets/lint/plugin/rules/layers.js +479 -0
  23. package/dist/presets/lint/plugin/rules/no-query-data-in-state.js +1 -1
  24. package/dist/presets/lint/plugin/rules/no-react-state-hooks.d.ts +0 -5
  25. package/dist/presets/lint/plugin/rules/no-react-state-hooks.js +3 -47
  26. package/dist/presets/lint/plugin/rules/query-from-loader.js +2 -2
  27. package/dist/presets/lint/plugin/rules/require-suppression-reason.d.ts +5 -0
  28. package/dist/presets/lint/plugin/rules/require-suppression-reason.js +32 -0
  29. package/dist/presets/lint/react-strict.js +22 -2
  30. package/dist/presets/lint/strict.js +35 -2
  31. package/dist/presets/lint/{antislop.d.ts → tailwind.d.ts} +1 -1
  32. package/dist/presets/lint/{shadcn.js → tailwind.js} +1 -1
  33. package/dist/presets/lint/vendor/antislop/license.md +26 -1
  34. package/dist/presets/lint/vendor/antislop/plugin.d.mts +3 -0
  35. package/dist/presets/lint/vendor/antislop/plugin.mjs +959 -33
  36. package/dist/presets/lint/vendor/antislop-effect/license.md +27 -0
  37. package/dist/presets/lint/vendor/antislop-effect/plugin.d.mts +17 -0
  38. package/dist/presets/lint/vendor/antislop-effect/plugin.mjs +579 -0
  39. package/dist/presets/{lint → rules}/custom.d.ts +3 -20
  40. package/dist/presets/{lint → rules}/custom.js +50 -46
  41. package/dist/presets/rules/folder.d.ts +34 -0
  42. package/dist/presets/rules/folder.js +52 -0
  43. package/dist/presets/rules/index.d.ts +2 -9
  44. package/dist/presets/rules/index.js +1 -29
  45. package/dist/presets/rules/load.d.ts +8 -0
  46. package/dist/presets/rules/load.js +29 -0
  47. package/dist/presets/rules/plugin.d.ts +3 -0
  48. package/dist/presets/rules/plugin.js +1 -0
  49. package/dist/presets/rules/testing.d.ts +2 -0
  50. package/dist/presets/rules/testing.js +14 -0
  51. package/dist/presets/tsconfig.json +3 -0
  52. package/dist/presets/typescript/resets/array-includes.d.ts +15 -0
  53. package/dist/presets/typescript/resets/array-index-of.d.ts +23 -0
  54. package/dist/presets/typescript/resets/eval.d.ts +1 -0
  55. package/dist/presets/typescript/resets/fetch.d.ts +3 -0
  56. package/dist/presets/typescript/resets/filter-boolean.d.ts +24 -0
  57. package/dist/presets/typescript/resets/helpers.d.ts +15 -0
  58. package/dist/presets/typescript/resets/index.d.ts +20 -0
  59. package/dist/presets/typescript/resets/is-array.d.ts +3 -0
  60. package/dist/presets/typescript/resets/json-parse.d.ts +14 -0
  61. package/dist/presets/typescript/resets/license.md +12 -0
  62. package/dist/presets/typescript/resets/map-constructor.d.ts +3 -0
  63. package/dist/presets/typescript/resets/map-groupby.d.ts +3 -0
  64. package/dist/presets/typescript/resets/map-has.d.ts +9 -0
  65. package/dist/presets/typescript/resets/object-assign.d.ts +8 -0
  66. package/dist/presets/typescript/resets/object-get-prototype-of.d.ts +3 -0
  67. package/dist/presets/typescript/resets/object-groupby.d.ts +6 -0
  68. package/dist/presets/typescript/resets/object-values.d.ts +8 -0
  69. package/dist/presets/typescript/resets/reflect.d.ts +12 -0
  70. package/dist/presets/typescript/resets/set-has.d.ts +9 -0
  71. package/dist/presets/typescript/resets/storage.d.ts +3 -0
  72. package/dist/presets/typescript.json +13 -0
  73. package/dist/runtime-CVZPDpfE.js +11 -0
  74. package/package.json +81 -19
  75. package/skills/adamantite/SKILL.md +110 -207
  76. package/skills/adamantite/references/custom-rules.md +120 -0
  77. package/skills/adamantite/references/lint-rules.md +152 -0
  78. package/skills/adamantite/references/setup.md +70 -0
  79. package/dist/presets/lint/antislop.js +0 -28
  80. package/dist/presets/lint/react-doctor.js +0 -20
  81. package/dist/presets/lint/shadcn.d.ts +0 -5
package/dist/index.js CHANGED
@@ -1,21 +1,20 @@
1
- import*as e from"@effect/platform-node/NodeRuntime";import*as t from"effect/Effect";import*as n from"effect/Exit";import*as r from"effect/process/ChildProcessSpawner";import*as i from"effect/Runtime";import*as a from"effect/Stdio";import*as o from"@effect/platform-node/NodeServices";import*as s from"effect/Array";import*as c from"effect/cli/Command";import*as l from"effect/Layer";import*as u from"effect/cli/Flag";import*as d from"effect/Option";import f from"node:process";import{stripVTControlCharacters as p,styleText as m}from"node:util";import*as h from"effect/Console";import*as g from"effect/Context";import*as _ from"effect/process/ChildProcess";import*as v from"effect/Result";import*as y from"effect/Data";import{pipe as b}from"effect/Function";import*as x from"effect/Predicate";import*as S from"effect/String";import{applyEdits as ee,findNodeAtLocation as te,modify as ne,parse as re,parseTree as ie,printParseErrorCode as ae,visit as oe}from"jsonc-parser";import*as C from"effect/FileSystem";import*as w from"effect/Path";import*as se from"effect/Record";import{defu as ce}from"defu";import*as le from"effect/Equal";import{Visitor as ue,parseSync as de}from"oxc-parser";import*as T from"effect/cli/Argument";import{addDevDependency as fe,detectPackageManager as pe,runScriptCommand as me}from"nypm";import*as E from"effect/Schema";import*as D from"effect/Order";import{delimiter as he}from"node:path";import*as ge from"effect/Config";import*as O from"@clack/prompts";import*as _e from"effect/Terminal";function ve(e){return x.isError(e)?b(p(e.message),S.split(/\r\n|[\r\n]/),s.map(e=>S.trimEnd(e)),s.filter(e=>S.isNonEmpty(e))):[]}function k(e){return b(ve(e),s.head,d.map(e=>{let t=S.trim(e);return/[.!?]$/.test(t)?` Cause: ${t}`:` Cause: ${t}.`}),d.getOrElse(()=>``))}function ye(e){let t=ve(e);if(!s.isReadonlyArrayNonEmpty(t))return``;let n=s.takeRight(t,20);return`\n${(n.length<t.length?[`…`,...n]:n).join(`
2
- `)}`}function be(e=[]){return e.length===0?`- Unknown JSON/JSONC parsing error`:e.slice(0,3).map(e=>`- ${ae(e.error)} (offset: ${e.offset})`).join(`
3
- `)}var xe=class extends y.TaggedError(`CliNotFound`){get message(){return`Command \`${this.command}\` not found. ${this.hint??`Please install it and try again.`}`}},Se=class extends y.TaggedError(`CommandFailed`){get message(){return`Command \`${this.command}\` failed with exit code ${this.exitCode}.`}},Ce=class extends y.TaggedError(`CustomRuleExists`){get message(){return`The custom rule \`${this.path}\` already exists. Choose another name or edit the file.`}},we=class extends y.TaggedError(`FailedToCreateDirectory`){get message(){return`Failed to create directory ${this.path?`\`${this.path}\``:`the target directory`}.${k(this.cause)}`}},Te=class extends y.TaggedError(`FailedToInstallDependency`){get message(){return`Failed to install dependencies${this.packages?.length?`: ${this.packages.join(`, `)}`:``}.${ye(this.cause)}`}},Ee=class extends y.TaggedError(`FailedToInstallExtension`){get message(){let e=this.extension?`\`${this.extension}\``:`the target extension`;return x.isNumber(this.cause)?`Failed to install ${e}. The \`code\` CLI exited with code ${this.cause}.`:`Failed to install ${e}.${k(this.cause)}`}},De=class extends y.TaggedError(`FailedToMergeConfig`){get message(){return`Failed to merge configuration.${k(this.cause)}`}},Oe=class extends y.TaggedError(`FailedToParseFile`){get message(){return[`Failed to parse ${this.path?`\`${this.path}\``:`the target file`}.`,`Please fix the JSON/JSONC syntax and run the command again.`,``,`Parse details:`,be(this.errors)].join(`
4
- `)}},ke=class extends y.TaggedError(`FailedToParseSource`){get message(){return[`Failed to parse \`${this.path}\`.`,...this.errors.map(e=>`- ${e}`)].join(`
5
- `)}},Ae=class extends y.TaggedError(`FailedToReadFile`){get message(){return`Failed to read ${this.path?`\`${this.path}\``:`the target file`}.${k(this.cause)}`}},je=class extends y.TaggedError(`FailedToWriteFile`){get message(){return`Failed to write ${this.path?`\`${this.path}\``:`the target file`}.${k(this.cause)}`}},Me=class extends y.TaggedError(`InvalidConfigFormat`){get message(){return`Invalid config format in ${this.path?`\`${this.path}\``:`the target config file`}. The config must be a JSON object (for example: {}).`}},Ne=class extends y.TaggedError(`InvalidAnalyzeOptions`){get message(){return`Invalid analyze options. ${this.reason}`}},Pe=class extends y.TaggedError(`InvalidFixOptions`){get message(){return`Invalid fix options. ${this.reason}`}},A=class extends y.TaggedError(`InvalidInitOptions`){get message(){return`Invalid init options. ${this.reason}`}},Fe=class extends y.TaggedError(`InvalidRuleName`){get message(){return`Invalid rule name \`${this.rule}\`. Use kebab-case that starts with a letter, such as \`no-process-env\`.`}},Ie=class extends y.TaggedError(`NoPackageManager`){get message(){return`No package manager detected. Please run this command from a project with a lockfile.${k(this.cause)}`}};y.TaggedError(`MissingPackageVersion`);var Le=class extends y.TaggedError(`OperationCancelled`){get message(){return`Operation cancelled.${this.reason?` Reason: ${this.reason}`:``}`}},Re=class extends y.TaggedError(`PassthroughNotSupported`){get message(){return`Command \`adamantite ${this.command}\` does not invoke a single underlying CLI and cannot accept passthrough arguments.`}},ze=class extends y.TaggedError(`VscodeCliNotFound`){get message(){return`VS Code CLI (\`code\`) not found. Please install it to manage extensions.${k(this.cause)}`}};const Be=(e,t)=>h.log(`${m(`bold`,e)} ${m(`dim`,`· adamantite (${t})`)}`),Ve=()=>[f.env.NODE_OPTIONS,`--disable-warning=MODULE_TYPELESS_PACKAGE_JSON`].filter(Boolean).join(` `),He=t.fn(`CommandRunner.exitCode`)(function*({args:e,command:n,cwd:r,detached:i,env:a,stderr:o=`inherit`,stdin:s=`ignore`,stdout:c=`inherit`}){return yield*t.scoped(t.gen(function*(){return yield*(yield*_.make(n,e,{cwd:r,detached:i,env:{...a,NODE_OPTIONS:Ve()},extendEnv:!0,stderr:o,stdin:s,stdout:c})).exitCode})).pipe(t.mapError(e=>e.reason._tag===`NotFound`?new xe({command:n}):e))});var j=class e extends g.Service()(`CommandRunner`){static make(e){let n=t.fn(`CommandRunner.run`)(function*(t){t.title!==void 0&&(yield*Be(t.title,t.command));let n=yield*e(t);if(n!==r.ExitCode(0))return yield*new Se({command:t.command,exitCode:n})}),i=e=>e.map((e,r)=>r===0?n(e):t.andThen(h.log(``),n(e)));return{exitCode:e,run:n,runAll:t.fn(`CommandRunner.runAll`)(function*(e){let n=yield*t.all(i(e),{concurrency:1,mode:`result`});yield*t.fromResult(v.all(n))}),runUntilFailure:t.fn(`CommandRunner.runUntilFailure`)(function*(e){yield*t.all(i(e),{concurrency:1,discard:!0})})}}static layer=l.effect(this)(t.gen(function*(){let n=yield*r.ChildProcessSpawner;return e.make(e=>He(e).pipe(t.provideService(r.ChildProcessSpawner,n)))}))};const Ue=g.Reference(`adamantite/ForwardedArguments`,{defaultValue:()=>[]});function M(e){return e}const We=e=>C.FileSystem.pipe(t.flatMap(t=>t.makeDirectory(e,{recursive:!0})),t.mapError(t=>new we({cause:t,path:e}))),N=e=>C.FileSystem.pipe(t.flatMap(t=>t.readFileString(e)),t.mapError(t=>new Ae({cause:t,path:e}))),P=e=>C.FileSystem.pipe(t.flatMap(t=>t.readFileString(e)),t.map(e=>b(e,d.some)),t.catch(n=>n.reason._tag===`NotFound`?t.succeedNone:t.fail(new Ae({cause:n,path:e})))),Ge=e=>C.FileSystem.pipe(t.flatMap(t=>t.readDirectory(e)),t.map(e=>b(e,d.some)),t.catch(n=>n.reason._tag===`NotFound`||n.reason._tag===`BadResource`?t.succeed(d.none()):t.fail(new Ae({cause:n,path:e})))),F=(e,n)=>C.FileSystem.pipe(t.flatMap(t=>t.writeFileString(e,n)),t.mapError(t=>new je({cause:t,path:e}))),Ke=(e,t)=>F(e,`${JSON.stringify(t,null,2)}\n`),I=(e,n)=>t.suspend(()=>{let r=[],i=re(e,r,{allowTrailingComma:!0});return r.length>0?t.fail(new Oe({errors:r,path:n})):t.succeed(i)}),L=e=>x.isObject(e),qe=e=>Array.isArray(e),Je=(e,n)=>t.try({catch:e=>new De({cause:e}),try:()=>ce(e,n)}),Ye=/^([ \t]+)"/mu;function Xe(e){let t=Ye.exec(e)?.[1]??` `,n=e.includes(`\r
6
- `)?`\r
7
- `:`
8
- `;return t.startsWith(` `)?{eol:n,insertSpaces:!1,tabSize:1}:{eol:n,insertSpaces:!0,tabSize:t.length}}function Ze(e,t){return Object.hasOwn(e,t)?e[t]:void 0}function Qe(e,t,n){return L(e)&&L(t)?[...Object.keys(e),...Object.keys(t).filter(t=>!Object.hasOwn(e,t))].flatMap(r=>Qe(Ze(e,r),Ze(t,r),[...n,r])):le.equals(e,t)?[]:[[n,t]]}const $e=/^(?<comma>[ \t]*,)?(?<comment>(?:[ \t]*(?:\/\/[^\r\n]*|\/\*[^\r\n]*?\*\/))+)/u;function et(e,t){let n=t.at(-1),r=ie(e),i=r&&te(r,t.slice(0,-1)),a=i?.type===`object`?(i.children??[]).filter(e=>e.children?.[0]?.value===n):[];return a.length>1?a[0]:void 0}function tt(e,t){let n=t.offset+t.length,r;oe(e,{onSeparator:(e,t)=>{r===void 0&&e===`,`&&t>=n&&(r=t)}});let i=r===void 0?e:e.slice(0,r)+e.slice(r+1),a=i.slice(0,t.offset)+i.slice(n),o=a.lastIndexOf(`
9
- `,t.offset-1)+1,s=a.indexOf(`
10
- `,t.offset),c=s===-1?a.length:s+1;return a.slice(o,c).trim()===``?a.slice(0,o)+a.slice(c):a}function nt(e,t){let n=e;for(let e of t.keys()){let r=t.slice(0,e+1);for(let e=et(n,r);e;e=et(n,r))n=tt(n,e)}return n}function rt(e,t,n,r){let i=e=>ee(e,ne(e,t,n,{formattingOptions:r})),a=ie(e),o=t.slice(0,-1),s=a&&te(a,o)?.children?.at(-1),c=s?.children?.[0]?.value;if(n===void 0||a===void 0||te(a,t)!==void 0||s?.type!==`property`||!x.isString(c))return i(e);let l=s.offset+s.length,u=$e.exec(e.slice(l));if(u?.groups?.comment===void 0)return i(e);let d=l+(u.groups.comma?.length??0),f=u.groups.comment,p=i(e.slice(0,d)+e.slice(d+f.length)),m=ie(p),h=m&&te(m,[...o,c])?.parent,g=h?h.offset+h.length:d,_=g+(/^[ \t]*,/u.exec(p.slice(g))?.[0].length??0);return p.slice(0,_)+f+p.slice(_)}function it(e,t){let n=re(e,[],{allowTrailingComma:!0}),r=Xe(e);return Qe(n,t,[]).reduce((e,[t,n])=>rt(nt(e,t),t,n,r),e)}const at=/^workspace:/,ot=/^[\^~]/;function st(e){return e.trim().replace(at,``).replace(ot,``)}const R=(e=f.cwd())=>t.gen(function*(){let t=(yield*w.Path).join(e,`package.json`),n=yield*N(t);return yield*I(n,t)}),ct=(e,n)=>t.gen(function*(){let t=(yield*w.Path).join(e,`package.json`),r=yield*N(t);yield*F(t,it(r,n))});function lt(e){return e===`bun`||e===`deno`||e===`npm`||e===`pnpm`||e===`yarn`}const z={analyze:`adamantite analyze`,check:`adamantite check`,fix:`adamantite fix`};function ut(e){let t=e.scripts??{};return b(se.keys(z),s.filter(e=>t[e]===z[e]))}function dt(e,t){let n=e.scripts??{};return s.filterMap(t,e=>{let t=n[e];return t!==void 0&&t!==``&&t!==z[e]?v.succeed({command:t,script:e}):v.failVoid})}const ft=/^(?:packages|"packages"|'packages')\s*:/u;function pt(e){return e.replace(/(?:^|\s+)#.*$/u,``).trim()}function mt(e){let t=e.replace(/^\uFEFF/u,``).split(/\r?\n/u),n=t.findIndex(e=>ft.test(e));if(n===-1)return!1;let r=pt((t[n]??``).replace(ft,``));if(r===`[`){for(let e of t.slice(n+1)){let t=pt(e);if(t.length!==0)return t!==`]`}return!1}if(r&&!r.startsWith(`#`))return!/^\[\s*\]$/u.test(r);for(let e of t.slice(n+1)){if(/^\s*-\s*[^#\s]/u.test(e))return!0;if(/^\S/u.test(e)&&!e.startsWith(`#`))return!1}return!1}const B=(e=f.cwd())=>t.gen(function*(){let t=yield*w.Path,n=yield*P(t.join(e,`pnpm-workspace.yaml`));if(d.isSome(n)&&mt(n.value))return!0;let r=(yield*R(e)).workspaces;return((s.isArray(r)?r:r?.packages)?.length??0)>0});function ht(e){return e.replace(/^(["'])(.*)\1$/u,`$2`)}function gt(e){let t=e.replace(/^\uFEFF/u,``).split(/\r?\n/u),n=t.findIndex(e=>ft.test(e));if(n===-1)return[];let r=pt((t[n]??``).replace(ft,``));if(r.startsWith(`[`)){let e=[r,...t.slice(n+1).map(e=>pt(e))].join(` `),i=e.indexOf(`]`);return e.slice(1,i===-1?void 0:i).split(`,`).map(e=>ht(e.trim())).filter(e=>e.length>0)}let i=[];for(let e of t.slice(n+1)){let t=/^\s*-\s*(.+)$/u.exec(pt(e))?.[1];if(t!==void 0)i.push(ht(t.trim()));else if(/^\S/u.test(e)&&!e.startsWith(`#`))break}return i}function _t(e){return e.replaceAll(/[$()+.[\\\]^{|}]/gu,String.raw`\$&`)}function vt(e){let t=e.replace(/^\.\//u,``).replace(/\/+$/u,``).split(`/`),n=``;for(let[e,r]of t.entries()){let i=e===0||t[e-1]===`**`?``:`/`;r===`**`?e<t.length-1?n+=`${i}(?:[^/]+/)*`:n+=e===0?`(?:[^/]+(?:/[^/]+)*)?`:`(?:/[^/]+)*`:n+=`${i}${_t(r).replaceAll(`*`,`[^/]*`).replaceAll(`?`,`[^/]`)}`}return RegExp(`^${n}$`,`u`)}function yt(e){let t=e.replace(/^\.\//u,``).replace(/\/+$/u,``).split(`/`),n=t.findIndex(e=>/[*?]/u.test(e));return n===-1?{base:t.join(`/`),depth:0}:{base:t.slice(0,n).join(`/`),depth:t.includes(`**`)?1/0:t.length-n}}const bt=/* @__PURE__ */ new Set([`node_modules`]),xt=(e,n,r)=>t.gen(function*(){let i=yield*w.Path,a=yield*Ge(i.resolve(e,n));return d.isNone(a)?[]:r===0?[n]:[n,...(yield*t.forEach(a.value.filter(e=>!e.startsWith(`.`)&&!bt.has(e)),t=>xt(e,n===``?t:`${n}/${t}`,r-1),{concurrency:`unbounded`})).flat()]}),St=(e=f.cwd())=>t.gen(function*(){let n=yield*w.Path,r=yield*P(n.join(e,`pnpm-workspace.yaml`)),i=(yield*R(e)).workspaces,a=d.match(r,{onNone:()=>s.isArray(i)?i:i?.packages??[],onSome:e=>gt(e)}),o=a.filter(e=>!e.startsWith(`!`)),c=a.filter(e=>e.startsWith(`!`)).map(e=>vt(e.slice(1))),l=yield*t.forEach(o,n=>t.gen(function*(){let{base:t,depth:r}=yt(n),i=vt(n);return(yield*xt(e,t,r)).filter(e=>e!==``&&i.test(e))}),{concurrency:`unbounded`}),u=s.dedupe(l.flat()).filter(e=>!c.some(t=>t.test(e)));return(yield*t.forEach(u,r=>P(n.join(e,r,`package.json`)).pipe(t.map(t=>d.isSome(t)?[n.resolve(e,r)]:[])),{concurrency:`unbounded`})).flat()});function Ct(e){return e.endsWith(`.jsonc`)?`jsonc`:e.endsWith(`.json`)?`json`:`ts`}function wt(e,t){return s.findFirst(e.legacyConfigs,e=>Ct(e)===t)}function Tt(e){let t=wt(e,`json`),n=wt(e,`jsonc`);return b(d.zipWith(t,n,e=>`${e}(c)`),d.orElse(()=>n),d.orElse(()=>t),d.getOrElse(()=>``))}function Et(e,t,n,r){return n===null||r.length===0?[]:n.format===`ts`?[`Found both \`${t.config}\` and \`${Tt(t)}\`. Adamantite will use \`${t.config}\`.`]:b(d.zipWith(wt(t,`json`),wt(t,`jsonc`),(t,n)=>`Found both \`${t}\` and \`${n}\`. Multiple legacy ${e} configs exist; Adamantite will treat \`${n}\` as the source of truth in its findings.`),d.toArray)}const Dt=t.fn(`detectToolingConfig`)(function*(e,n,r){let i=yield*C.FileSystem,a=yield*w.Path,o=[r.config,...r.legacyConfigs].map(t=>({file:t,format:Ct(t),path:a.join(e,t)})),c=yield*t.forEach(o,e=>i.exists(e.path),{concurrency:`unbounded`}),l=o.filter((e,t)=>c[t]),u=b(s.findFirst(l,e=>e.format===`ts`),d.orElse(()=>s.findFirst(l,e=>e.format===`jsonc`)),d.orElse(()=>s.findFirst(l,e=>e.format===`json`)),d.getOrNull),f=l.filter(e=>e!==u&&e.format!==`ts`);return{active:u,legacy:f,warnings:Et(n,r,u,f)}});function Ot(e,t,n){let r=e.devDependencies?.[t.name]??e.dependencies?.[t.name];return r?st(r)===t.version?[]:[{currentVersion:r,description:`Update \`${t.name}\` from \`${r}\` to \`${t.version}\`.`,package:t.name,targetVersion:t.version,type:`update_package`}]:[{description:`Install \`${t.name}@${t.version}\` for ${n}.`,package:t.name,targetVersion:t.version,type:`install_package`}]}function kt(e,t){return e.map(e=>({currentState:e.type===`install_package`?`The required package \`${e.package}\` is not installed.`:`The installed \`${e.package}\` version is \`${e.currentVersion}\`, but Adamantite requires \`${e.targetVersion}\`.`,goal:[`Run \`adamantite update\` so \`${e.package}@${e.targetVersion}\` is installed.`],id:`${e.type===`install_package`?`missing`:`outdated`}-${e.package}`,integration:t,title:e.type===`install_package`?`Missing ${e.package}`:`Outdated ${e.package}`}))}function At(e,t){if(e.active===null)return[{currentState:`The managed \`${t.configFile}\` file is missing.`,goal:[`Create \`${t.configFile}\` with the reference content.`,`Do not create a legacy JSON or JSONC ${t.toolName} config.`],id:`missing-${t.toolName}-config`,integration:t.toolName,reference:{content:t.configContent,language:`ts`},title:`Missing ${t.toolName} configuration`}];if(e.active.format!==`ts`)return[{currentState:`Legacy \`${e.active.file}\` is the active ${t.toolName} configuration.`,goal:[`Port the project settings into \`${t.configFile}\` using the reference content as the base.`,`Delete every legacy ${t.toolName} JSON or JSONC config after its settings are preserved.`],id:`legacy-${t.toolName}-config`,integration:t.toolName,notes:[`Preserve project-specific settings. Do not replace them with the reference defaults.`],reference:{content:t.configContent,language:`ts`},title:`Legacy ${t.toolName} configuration`}];let n=[];return e.legacy.length>0&&n.push({currentState:`Legacy ${t.toolName} config files remain next to \`${t.configFile}\`: ${e.legacy.map(({file:e})=>`\`${e}\``).join(`, `)}.`,goal:[`Delete the legacy files after you confirm that \`${t.configFile}\` preserves their project-specific settings.`],id:`shadowed-legacy-${t.toolName}-config`,integration:t.toolName,title:`Legacy ${t.toolName} files remain`}),t.inspection?.kind===`invalid`&&n.push({currentState:`\`${t.configFile}\` does not meet Adamantite's required shape. ${t.inspection.reason}`,goal:[t.invalidGoal??t.inspection.goal??`Update \`${t.configFile}\` so it includes the required Adamantite preset while preserving project-specific settings.`],id:`invalid-${t.toolName}-config`,integration:t.toolName,notes:[`Treat the reference as a known-good example, not an exact replacement.`],reference:{content:t.configContent,language:`ts`},title:`Invalid ${t.toolName} configuration`}),n}function jt(e,t){let n=ut(e);return t.some(e=>n.includes(e))}function Mt(e){return M({assess:(n,r)=>t.gen(function*(){let t=jt(r,e.scripts)&&(!e.monorepoOnly||(yield*B(n)))&&(e.isRequired===void 0||(yield*e.isRequired(n))),i=e.legacyFindings?.(r)??[];if(!t)return i.length>0?{applicable:!0,findings:[...i],packageActions:[],warnings:[]}:{applicable:!1,warnings:[]};let a=Ot(r,e,e.purpose);return{applicable:!0,findings:[...kt(a,e.name),...i],packageActions:a,warnings:[]}}),kind:`tooling`,name:e.name,version:e.version})}const Nt=t.fn(`detectToolingWorkspace`)(function*(e){return{isMonorepo:yield*B(e)}});function Pt(e){let n=[{path:e.configFiles.config,type:`config`},...e.configFiles.legacyConfigs.map(e=>({path:e,type:`legacy_config`}))],r=t=>Dt(t,e.name,e.configFiles);return M({assess:(n,i)=>t.gen(function*(){let t=e.legacyFindings?.(i)??[];if(!jt(i,e.scripts))return t.length>0?{applicable:!0,findings:t,packageActions:[],warnings:[]}:{applicable:!1,warnings:[]};let a=yield*r(n),o=Ot(i,e,e.purpose),s=yield*e.detectWorkspace(n),c=e.configContent(s),l=a.active?.format===`ts`?e.inspectConfig(yield*N(a.active.path),s):void 0;return{applicable:!0,findings:[...kt(o,e.name),...At(a,{configContent:c,configFile:e.configFiles.config,inspection:l,toolName:e.name}),...t],packageActions:o,warnings:a.warnings}}),config:e.configFiles.config,create:n=>t.gen(function*(){let t=yield*w.Path;yield*F(t.join(n,e.configFiles.config),e.configContent(yield*e.detectWorkspace(n)))}),detect:r,files:n,kind:`tooling`,name:e.name,version:e.version})}const Ft=[`respectEslintDisableDirectives`,`typeAware`,`typeCheck`],It="`oxlint.config.ts` must export an object literal directly, with or without `defineConfig(...)`, for Adamantite to inspect `options`.",Lt="`oxlint.config.ts` has an `options` property, but it is not an object literal that Adamantite can inspect.",Rt=[`react`,`react-strict`,`react-doctor`,`tanstack`,`nextjs`,`vue`,`effect`,`jest`,`vitest`,`node`,`strict`,`antislop`,`shadcn`];function zt(e){return e.replaceAll(/-([a-z])/g,(e,t)=>t.toUpperCase())}function Bt(e=[]){let t=e.includes(`core`)?e:[`core`,...e];return[`import { defineConfig } from "oxlint"`,...t.map(e=>`import ${zt(e)} from "${e===`core`?`adamantite/lint`:`adamantite/lint/${e}`}"`),`import custom from "adamantite/lint/custom"`,``,`export default defineConfig({`,` extends: [${[...t.map(e=>zt(e)),`custom()`].join(`, `)}],`,` ignorePatterns: core.ignorePatterns,`,` options: {`,...Ft.map(e=>` ${e}: true,`),` },`,`})`,``].join(`
11
- `)}const Vt=d.liftThrowable(e=>de(`oxlint.config.ts`,e,{astType:`ts`,lang:`ts`,sourceType:`module`}));function Ht(e){return Vt(e).pipe(d.flatMap(e=>e.errors.length===0?d.fromNullishOr(e.program):d.none()))}const Ut=`adamantite/lint/`,Wt=`${Ut}custom`;function Gt(e){return b(Ht(e),d.map(e=>e.body.flatMap(e=>e.type===`ImportDeclaration`&&e.source.value.startsWith(Ut)&&e.source.value!==Wt?[e.source.value.slice(16)]:[])),d.getOrElse(()=>[]))}function Kt(e){return e.type===`Identifier`?b(e.name,d.some):e.type===`Literal`&&x.isString(e.value)?b(e.value,d.some):d.none()}function qt(e){return e.type===`ObjectExpression`?b(e,d.some):e.type!==`CallExpression`||e.callee.type!==`Identifier`||e.callee.name!==`defineConfig`?d.none():b(e.arguments.length===1?s.head(e.arguments):d.none(),d.filter(e=>e.type===`ObjectExpression`))}function Jt(e){return b(e.body,s.filter(e=>e.type===`ExportDefaultDeclaration`),e=>e.length===1?s.head(e):d.none(),d.flatMap(e=>qt(e.declaration)))}function Yt(e,t){let n=null;for(let r of e.properties){if(r.type===`SpreadElement`||r.computed)return{status:`invalid`};let e=d.contains(Kt(r.key),t);if(r.method||r.kind!==`init`){if(e)return{status:`invalid`}}else if(e){if(n)return{status:`invalid`};n=r}}return n?{property:n,status:`found`}:{status:`missing`}}function Xt(e){for(let t of Ft){let n=Yt(e,t);if(n.status===`invalid`)return{kind:`invalid`,reason:"`oxlint.config.ts` has an `options` object Adamantite cannot inspect. Make sure each required option is a plain `key: true | false` property. Avoid spreads (`...rest`), computed keys (`[name]: ...`), duplicate keys, methods/getters/setters, and non-boolean-literal values."};if(n.status===`missing`||n.property.value.type!==`Literal`||n.property.value.value!==!0)return{kind:`invalid`,reason:`The required Oxlint options are missing or are not set to true.`}}return{kind:`configured`}}function Zt(e){let t=Ht(e);if(d.isNone(t))return{kind:`invalid`,reason:It};let n=Jt(t.value);if(d.isNone(n))return{kind:`invalid`,reason:It};let r=Yt(n.value,`options`);return r.status===`invalid`?{kind:`invalid`,reason:Lt}:r.status===`missing`?{kind:`invalid`,reason:`The required Oxlint options are missing.`}:r.property.value.type===`ObjectExpression`?Xt(r.property.value):{kind:`invalid`,reason:Lt}}function Qt(e,t){for(let n of e.body)if(n.type===`ImportDeclaration`&&n.source.value===t){for(let e of n.specifiers)if(e.type===`ImportDefaultSpecifier`)return e.local.name}return null}function $t(e,t){for(let n of e.body)if(n.type===`VariableDeclaration`){for(let e of n.declarations)if(e.id.type===`Identifier`&&e.id.name===t)return e.init}return null}function en(e,t,n){let r=!1;return new ue({Identifier:e=>{e.start>=n.start&&e.end<=n.end&&e.name===t&&(r=!0)}}).visit(e),r}function tn(e,t){let n=e.body.filter(e=>e.type===`ExportDefaultDeclaration`);if(n.length!==1)return!1;let r=n[0]?.declaration;if(!r)return!1;if(r.type!==`Identifier`)return en(e,t,r);if(r.name===t)return!0;let i=$t(e,r.name);return i!==null&&en(e,t,i)}function nn(e,t){let n=de(`config.ts`,e,{astType:`ts`,lang:`ts`,sourceType:`module`});if(n.errors.length>0)return{kind:`invalid`,reason:`The file is not valid TypeScript.`};let r=Qt(n.program,t.moduleName);return r?tn(n.program,r)?{kind:`configured`}:{kind:`invalid`,reason:`The imported ${t.presetName} preset is not used by the exported configuration.`}:{kind:`invalid`,reason:`The file must import the ${t.presetName} preset from \`${t.moduleName}\`.`}}const rn={isMonorepo:!1,usesEffectPreset:!1},an={effect:/ignoreDependencies\s*:\s*\[[^\]]*?@effect\/language-service/u,monorepo:/ignoreDependencies\s*:\s*\[[^\]]*?sherif/u},on={effect:/ignoreDependencies\s*:\s*(?:ignoreDependencies\.effect|\[[^\]]*?ignoreDependencies\.effect)/u,monorepo:/ignoreDependencies\s*:\s*(?:ignoreDependencies\.monorepo|\[[^\]]*?ignoreDependencies\.monorepo)/u},sn=/import\s[^;]*?\{[^}]*\bignoreDependencies\b[^}]*\}\s*from\s*["']adamantite\/analyze["']/u,cn={effect:"the `effect` lint preset names the `@effect/language-service` plugin in `tsconfig.json`, and no package has that name",monorepo:"Knip cannot see that `adamantite analyze` runs Sherif in a monorepo"};function ln(e){return[`monorepo`,`effect`].filter(t=>t===`monorepo`?e.isMonorepo:e.usesEffectPreset)}function un(e,t){return an[t].test(e)||on[t].test(e)&&sn.test(e)}function dn(e){let[t]=e;return e.length===1&&t!==void 0?`ignoreDependencies.${t}`:`[${e.map(e=>`...ignoreDependencies.${e}`).join(`, `)}]`}const fn=t.fn(`detectKnipWorkspace`)(function*(e){let t=yield*w.Path,n=yield*P(t.join(e,`oxlint.config.ts`));return{...yield*Nt(e),usesEffectPreset:d.match(n,{onNone:()=>!1,onSome:e=>Gt(e).includes(`effect`)})}});function pn(e,t){let n=nn(e,{moduleName:`adamantite/analyze`,presetName:`Adamantite analyze`});if(n.kind!==`configured`)return n;let r=ln(t),i=r.filter(t=>!un(e,t));if(i.length===0)return n;let a=`\`ignoreDependencies: ${dn(r)}\``;return{goal:`Set ${a} in \`knip.config.ts\`, with the named \`ignoreDependencies\` import from \`adamantite/analyze\`, and keep the other settings.`,kind:`invalid`,reason:`The file must set ${a} from \`adamantite/analyze\`, because ${i.map(e=>cn[e]).join(`, and `)}.`}}function mn(e=rn){let t=ln(e);return[`import type { KnipConfig } from "knip"`,t.length>0?`import analyze, { ignoreDependencies } from "adamantite/analyze"`:`import analyze from "adamantite/analyze"`,``,...t.length>0?[`const config: KnipConfig = {`,` ...analyze,`,` ignoreDependencies: ${dn(t)},`,`}`]:[`const config: KnipConfig = analyze`],``,`export default config`,``].join(`
12
- `)}var V=Pt({configContent:mn,configFiles:{config:`knip.config.ts`,legacyConfigs:[`knip.json`,`knip.jsonc`]},detectWorkspace:fn,inspectConfig:pn,name:`knip`,purpose:"the managed `analyze` script",scripts:[`analyze`],version:`6.42.0`});const hn=/* @__PURE__ */ new Set([`check:monorepo`,`fix:monorepo`]),gn=/^adamantite\s+monorepo(?:\s|$)/u,_n=/* @__PURE__ */ new Map([[`--fail-on-warnings`,{key:`failOnWarnings`,takesValue:!1}],[`--ignore-dependency`,{key:`ignoreDependency`,takesValue:!0}],[`--ignore-package`,{key:`ignorePackage`,takesValue:!0}],[`--ignore-rule`,{key:`ignoreRule`,takesValue:!0}],[`--no-install`,{key:`noInstall`,takesValue:!1}],[`--select`,{key:`select`,takesValue:!0}],[`-i`,{key:`ignoreDependency`,takesValue:!0}],[`-p`,{key:`ignorePackage`,takesValue:!0}],[`-r`,{key:`ignoreRule`,takesValue:!0}],[`-s`,{key:`select`,takesValue:!0}]]);function vn(e){return Object.entries(e.scripts??{}).flatMap(([e,t])=>t!==void 0&&(hn.has(e)||gn.test(t.trim()))?[{command:t,name:e}]:[])}function yn(e){let t=e.command.trim().split(/\s+/u),n=[];for(let[e,r]of t.entries()){let[i=r,a]=r.split(`=`,2),o=_n.get(i);if(!o)continue;if(!o.takesValue){n.push(`Set \`sherif.${o.key}\` to \`true\` in the root \`package.json\`.`);continue}let s=a??t[e+1];s!==void 0&&n.push(o.key===`select`?`Set \`sherif.select\` to \`"${s}"\` in the root \`package.json\`.`:`Add \`"${s}"\` to the \`sherif.${o.key}\` array in the root \`package.json\`.`)}return n}function bn(e){let t=vn(e);if(t.length===0)return[];let n=ut(e).includes(`analyze`);return[{currentState:`Legacy monorepo scripts are present in \`package.json\`: ${t.map(({command:e,name:t})=>`\`${t}\` (\`${e}\`)`).join(`, `)}.${n?``:" The project has no managed `analyze` script."}`,goal:[...n?[]:["Adopt the managed `analyze` script with `adamantite init --non-interactive --script analyze`. It runs Sherif in a detected monorepo."],...s.dedupe(t.flatMap(e=>yn(e))),...t.map(({name:e})=>`Remove the \`${e}\` script from \`package.json\`.`)],id:`legacy-monorepo-scripts`,integration:`sherif`,notes:["`adamantite analyze` replaces `check:monorepo`, and `adamantite analyze --only monorepo --fix` replaces `fix:monorepo`. `adamantite analyze --fix` without `--only` also lets Knip remove unused files and dependencies.","`adamantite analyze` runs Sherif without flags. Sherif reads project exceptions from the `sherif` field of the root `package.json`, with the CLI options in camelCase: `ignoreDependency`, `ignoreRule`, `ignorePackage`, `select`, `noInstall`, and `failOnWarnings`.","Doctor does not assess `AGENTS.md`. Remove the lines that mention the monorepo scripts from its Adamantite section."],title:`Legacy monorepo scripts`}]}var H=Mt({legacyFindings:bn,monorepoOnly:!0,name:`sherif`,purpose:"the managed `analyze` script in a monorepo",scripts:[`analyze`],version:`1.13.0`});const xn=[{command:H.name,fixArguments:[`--fix`],name:`monorepo`,stdin:`inherit`,strictArguments:[],title:`📦 Analyzing the monorepo`},{command:V.name,fixArguments:[`--fix`,`--allow-remove-files`],name:`unused`,stdin:`ignore`,strictArguments:[`--production`,`--strict`],title:`🧹 Analyzing unused code`}],Sn=u.Boolean(`fix`).pipe(u.withDefault(!1),u.withDescription(`Automatically fix issues in every stage that runs`)),Cn=u.Boolean(`strict`).pipe(u.withDefault(!1),u.withDescription(`Enable strict mode for the unused stage (knip)`)),wn=u.Literals(`only`,[`monorepo`,`unused`]).pipe(u.optional,u.withDescription("Run one stage: `monorepo` (sherif, monorepos only) or `unused` (knip). Arguments after `--` go to that stage"));var Tn=c.make(`analyze`,{fix:Sn,only:wn,strict:Cn}).pipe(c.withDescription(`Find monorepo issues using sherif, then unused dependencies, exports, and files using knip`),c.withExamples([{command:`adamantite analyze -- --directory packages/app`,description:`Run knip from a specific directory`},{command:`adamantite analyze --only monorepo --fix -- --select highest`,description:`Fix only the monorepo issues and use the highest version on a mismatch`}]),c.withHandler(({fix:e,only:n,strict:r})=>t.gen(function*(){let i=yield*Ue,a=yield*j,o=d.getOrUndefined(n),s=yield*B().pipe(t.catchTags({FailedToParseFile:()=>t.succeed(!1),FailedToReadFile:()=>t.succeed(!1)}));if(o===`monorepo`){if(r)return yield*new Ne({reason:"`--strict` applies to the unused stage. Remove it or `--only monorepo`."});if(!s)return yield*new Ne({reason:"`--only monorepo` needs a monorepo, and no monorepo was detected."})}let c=xn.filter(e=>o===void 0?e.name===`unused`||s:e.name===o),l=o??`unused`,u=c.map(t=>({args:[...e?t.fixArguments:[],...r?t.strictArguments:[],...t.name===l?i:[]],command:t.command,stdin:t.stdin,title:t.title}));yield*(e?a.runUntilFailure(u):a.runAll(u)).pipe(t.mapError(e=>e._tag===`CliNotFound`&&e.command===H.name?new xe({command:e.command,hint:"Run `adamantite update` to install it."}):e))})));function En(e){return nn(e,{moduleName:`adamantite/format`,presetName:`Adamantite format`})}function Dn(){return[`import { defineConfig } from "oxfmt"`,`import format from "adamantite/format"`,``,`export default defineConfig(format)`,``].join(`
13
- `)}var U=Pt({configContent:Dn,configFiles:{config:`oxfmt.config.ts`,legacyConfigs:[`.oxfmtrc.json`,`.oxfmtrc.jsonc`]},detectWorkspace:Nt,inspectConfig:En,legacyFindings:e=>e.scripts?.format===`adamantite format`?[{currentState:"The legacy managed `format` script is present in `package.json`.",goal:["Remove the `format` script from `package.json`."],id:`legacy-format-script`,integration:`oxfmt`,notes:["The managed `check` script verifies formatting and the managed `fix` script applies it.","Doctor does not assess `AGENTS.md`. Remove the `format` line from its Adamantite section."],title:`Legacy format script`}]:[],name:`oxfmt`,purpose:"the managed `check` and `fix` scripts",scripts:[`check`,`fix`],version:`0.73.0`});const On=`oxlint.config.ts`,kn=`.oxlintrc.json`,An=[{path:On,type:`config`},{path:kn,type:`legacy_config`}],jn={config:On,legacyConfigs:[kn]},Mn=`1.88.0`,Nn=e=>Dt(e,`oxlint`,jn);var W=M({assess:(e,n)=>t.gen(function*(){let t=ut(n);if(!t.includes(`check`)&&!t.includes(`fix`))return{applicable:!1,warnings:[]};let r=yield*Nn(e),i=Ot(n,{name:`oxlint`,version:Mn},`the managed lint scripts`),a=r.active,o;a?.format===`ts`&&(o=Zt(yield*N(a.path)));let s=Bt();return{applicable:!0,findings:[...kt(i,`oxlint`),...At(r,{configContent:s,configFile:On,inspection:o,invalidGoal:"Set `respectEslintDisableDirectives`, `typeAware`, and `typeCheck` to `true` in the `options` object. Preserve every other project setting.",toolName:`oxlint`})],packageActions:i,warnings:r.warnings}}),config:On,create:(e,n=[])=>t.gen(function*(){let t=yield*w.Path,r=Bt(n);yield*F(t.join(e,On),r)}),detect:Nn,files:An,kind:`tooling`,name:`oxlint`,version:Mn});const Pn=T.File(`files`,{mustExist:!0}).pipe(T.withDescription(`Specific files to check (optional)`),T.variadic()),Fn=u.Literals(`only`,[`format`,`lint`]).pipe(u.optional,u.withDescription("Run one stage: `format` (oxfmt) or `lint` (oxlint). Arguments after `--` go to that stage"));var In=c.make(`check`,{files:Pn,only:Fn}).pipe(c.withDescription(`Check formatting, code issues, and type errors`),c.withHandler(({files:e,only:n})=>t.gen(function*(){let t=yield*Ue,r=yield*j,i=d.getOrUndefined(n),a=i??`lint`,o=[{args:[`--check`,...e],command:U.name,name:`format`,title:`✨ Checking formatting`},{args:[...e],command:W.name,name:`lint`,title:`🔍 Linting`}];yield*r.runAll(o.filter(e=>i===void 0||e.name===i).map(e=>({args:[...e.args,...e.name===a?t:[]],command:e.command,title:e.title})))})));const Ln=[`check`,`analyze`];function Rn(e,t){return Ln.filter(e=>t.includes(e)).map(t=>({command:me(e,t),name:t}))}function zn(e){return Ln.some(t=>e.includes(t))}var Bn=class extends g.Service()(`DependencyInstaller`){static layer=l.succeed(this)({addDevDependencies:t.fn(`DependencyInstaller.addDevDependencies`)((e,n,r)=>t.tryPromise({catch:t=>new Te({cause:t,packages:e}),try:()=>fe(e,{...r,cwd:n})}).pipe(t.asVoid)),detectPackageManager:t.fn(`DependencyInstaller.detectPackageManager`)(e=>t.tryPromise({catch:e=>new Ie({cause:e}),try:()=>pe(e)}).pipe(t.map(e=>e??null)))})};function Vn(e,t){return t&&e!==`npm`}const Hn=(e,n)=>t.gen(function*(){let t=yield*Bn,r=yield*B(e),i=yield*t.detectPackageManager(e);yield*t.addDevDependencies(n,e,{silent:!0,workspace:Vn(i?.name,r)})});function Un(e){return{_tag:`File`,path:e}}function Wn(e){return{_tag:`Version`,value:e}}const Gn=[`.node-version`,`.nvmrc`],Kn=E.Struct({volta:E.Struct({node:E.NonEmptyString})}),qn=E.Struct({engines:E.Struct({node:E.NonEmptyString})}),Jn=E.Struct({name:E.NonEmptyString,version:E.NonEmptyString});function Yn(e){return e.split(`
14
- `).map(e=>e.split(`#`)[0]?.trim()??``).some(e=>/^node(?:js)?\s+\S/.test(e))}function Xn(e){return E.is(Jn)(e)&&e.name.toLowerCase()===`node`}function Zn(e){if(E.is(Kn)(e))return!0;if(x.isObject(e)&&x.isObject(e.devEngines)){let t=e.devEngines.runtime;if((Array.isArray(t)?t:[t]).some(e=>Xn(e)))return!0}return E.is(qn)(e)}var Qn=class extends g.Service()(`NodeVersionResolver`){static layer=l.effect(this,t.gen(function*(){let e=yield*C.FileSystem,n=yield*w.Path,r=(r,i)=>P(n.join(r,i)).pipe(t.provideService(C.FileSystem,e));return{resolve:t.fn(`NodeVersionResolver.resolve`)(function*(e){for(let t of Gn){let n=yield*r(e,t);if(d.exists(n,e=>S.isNonEmpty(e.trim())))return Un(t)}let t=yield*r(e,`.tool-versions`);if(d.exists(t,e=>Yn(e)))return Un(`.tool-versions`);let i=yield*r(e,`package.json`);return d.isSome(i)&&Zn(yield*I(i.value,n.join(e,`package.json`)))?Un(`package.json`):Wn(`lts/*`)})}}))};const $n=/^\s*node-version:\s*"?\d/m,er=/^[>|](?:[1-9][+-]?|[+-][1-9]?)?(?:\s+#.*)?$/,tr=/\b(?:(?:bun|npm|pnpm|yarn)(?:\s+(?!run\b)\S+)*\s+run\s+check|deno(?:\s+(?!task\b)\S+)*\s+task\s+check)\b/,nr=/\b(?:(?:bun|npm|pnpm|yarn)(?:\s+(?!run\b)\S+)*\s+run\s+format|deno(?:\s+(?!task\b)\S+)*\s+task\s+format)(?:\s+--)?\s+--check\b/,rr=/\b(?:(?:bun|npm|pnpm|yarn)(?:\s+(?!run\b)\S+)*\s+run\s+(?:check|fix):monorepo|deno(?:\s+(?!task\b)\S+)*\s+task\s+(?:check|fix):monorepo|adamantite\s+monorepo)(?=\s|$)/,ir=/^(\s*)(?:-\s*)?(?:command|run):\s*(.*)$/;function ar(e,t){let n=e.split(`
15
- `);for(let[e,r]of n.entries()){let i=ir.exec(r);if(!i)continue;let a=i[1]?.length??0,o=(i[2]??``).trim();if(t.test(o))return!0;if(er.test(o))for(let r of n.slice(e+1)){let e=r.trim();if(e.length!==0){if(r.length-r.trimStart().length<=a)break;if(t.test(e))return!0}}}return!1}function or(e){return` - name: Setup Node.js
1
+ import{$ as e,A as t,At as n,B as r,C as i,Ct as a,D as o,Dt as s,E as c,Et as l,F as u,G as d,H as f,I as p,J as m,K as h,L as g,M as _,Mt as v,N as ee,O as y,Ot as te,P as b,Q as ne,R as x,S as re,St as ie,T as ae,Tt as oe,U as S,V as C,W as se,X as ce,Y as w,Z as le,_ as ue,_t as de,a as fe,at as pe,bt as me,c as he,ct as ge,d as _e,dt as ve,et as ye,f as be,ft as xe,g as Se,gt as Ce,h as we,ht as Te,i as Ee,it as De,j as Oe,jt as ke,k as Ae,kt as je,l as Me,lt as Ne,m as Pe,mt as Fe,n as Ie,nt as Le,ot as Re,p as ze,pt as Be,q as Ve,r as He,rt as Ue,s as We,st as Ge,t as Ke,tt as qe,u as Je,ut as Ye,vt as Xe,w as Ze,wt as Qe,x as $e,xt as et,y as tt,yt as nt,z as rt}from"./runtime-CVZPDpfE.js";import*as it from"@effect/platform-node/NodeRuntime";import*as T from"effect/Effect";import*as at from"effect/Exit";import*as E from"effect/process/ChildProcessSpawner";import*as ot from"effect/Runtime";import*as st from"effect/Stdio";import*as ct from"@effect/platform-node/NodeServices";import*as D from"effect/Array";import*as O from"effect/cli/Command";import*as k from"effect/Layer";import A from"node:process";import*as j from"effect/cli/Flag";import*as M from"effect/Option";import*as N from"effect/Context";import*as P from"effect/Path";import*as F from"effect/Predicate";import{styleText as lt}from"node:util";import*as ut from"effect/Console";import*as dt from"effect/process/ChildProcess";import*as ft from"effect/Result";import*as I from"effect/Data";import{pipe as L}from"effect/Function";import*as pt from"effect/String";import*as R from"effect/FileSystem";import*as mt from"effect/Equal";import*as z from"effect/Schema";import*as ht from"effect/encoding/Yaml";import*as gt from"effect/SchemaTransformation";import*as _t from"effect/Record";import*as vt from"effect/RegExp";import{Visitor as yt,parseSync as bt}from"oxc-parser";import*as B from"effect/Order";import*as xt from"effect/Config";import*as St from"effect/Match";import*as V from"effect/cli/Argument";import{addDevDependency as Ct,detectPackageManager as wt,runScriptCommand as Tt}from"nypm";import*as H from"effect/Stream";import*as U from"@clack/prompts";import*as Et from"effect/Cause";import{posix as W,win32 as Dt}from"node:path";import*as Ot from"effect/Brand";import*as kt from"effect/Terminal";const At=N.Reference(`adamantite/ForwardedArguments`,{defaultValue:()=>[]}),jt=(e,t)=>ut.log(`${lt(`bold`,e)} ${lt(`dim`,`· adamantite (${t})`)}`),Mt=()=>[A.env.NODE_OPTIONS,`--disable-warning=MODULE_TYPELESS_PACKAGE_JSON`].filter(Boolean).join(` `),Nt=T.fn(`CommandRunner.exitCode`)(function*(e){let{command:t}=e;return yield*T.scoped(T.gen(function*(){return yield*(yield*dt.make(t,e.args,{cwd:e.cwd,detached:e.stdin!==`inherit`&&void 0,env:{...e.env,NODE_OPTIONS:Mt()},extendEnv:!0,stderr:e.stderr??`inherit`,stdin:e.stdin??`ignore`,stdout:e.stdout??`inherit`})).exitCode})).pipe(T.catchReason(`PlatformError`,`NotFound`,()=>T.fail(new qe({command:t}))))});var Pt=class e extends N.Service()(`CommandRunner`){static make(e){let t=T.fn(`CommandRunner.run`)(function*(t){t.title!==void 0&&(yield*jt(t.title,t.name??t.command));let n=yield*e(t);if(n!==E.ExitCode(0))return yield*new Le({command:t.command,exitCode:n})}),n=e=>e.map((e,n)=>n===0?t(e):T.andThen(ut.log(``),t(e)));return{exitCode:e,run:t,runAll:T.fn(`CommandRunner.runAll`)(function*(e){let t=yield*T.all(n(e),{concurrency:1,mode:`result`});yield*T.fromResult(ft.all(t))}),runUntilFailure:T.fn(`CommandRunner.runUntilFailure`)(function*(e){yield*T.all(n(e),{concurrency:1,discard:!0})})}}static layer=k.effect(this)(T.gen(function*(){let t=yield*E.ChildProcessSpawner;return e.make(e=>Nt(e).pipe(T.provideService(E.ChildProcessSpawner,t)))}))};function G(e){return e}var Ft=class extends I.TaggedClass(`Missing`){},It=class extends I.TaggedClass(`Current`){},Lt=class extends I.TaggedClass(`Legacy`){};function Rt(e){return e.endsWith(`.jsonc`)?`jsonc`:e.endsWith(`.json`)?`json`:`ts`}function zt(e,t){return D.findFirst(e.legacyConfigs,e=>Rt(e)===t)}function Bt(e){let t=zt(e,`json`),n=zt(e,`jsonc`);return L(M.zipWith(t,n,e=>`${e}(c)`),M.orElse(()=>n),M.orElse(()=>t),M.getOrElse(()=>``))}function Vt(e,t,n,r){return n instanceof Ft||r.length===0?[]:n instanceof It?[`Found both \`${t.config}\` and \`${Bt(t)}\`. Adamantite will use \`${t.config}\`.`]:L(M.zipWith(zt(t,`json`),zt(t,`jsonc`),(t,n)=>`Found both \`${t}\` and \`${n}\`. Multiple legacy ${e} configs exist. Doctor uses \`${n}\` when checking the setup.`),M.toArray)}const Ht=T.fn(`detectToolingConfig`)(function*(e,t,n){let r=yield*R.FileSystem,i=yield*P.Path,a=[n.config,...n.legacyConfigs].map(t=>({file:t,format:Rt(t),path:i.join(e,t)})),o=yield*T.forEach(a,e=>r.exists(e.path),{concurrency:`unbounded`}),s=a.filter((e,t)=>o[t]),c=({file:e,path:t})=>({file:e,path:t}),l=L(D.findFirst(s,e=>e.format===`ts`),M.orElse(()=>D.findFirst(s,e=>e.format===`jsonc`)),M.orElse(()=>D.findFirst(s,e=>e.format===`json`))),u=M.match(l,{onNone:()=>new Ft,onSome:e=>e.format===`ts`?new It({file:c(e)}):new Lt({file:c(e)})}),d=s.flatMap(e=>e.format!==`ts`&&!M.exists(l,t=>t===e)?[c(e)]:[]);return{active:u,legacy:d,warnings:Vt(t,n,u,d)}}),Ut={findings:[],packageActions:[],warnings:[]};function Wt({packageJson:e,workspace:{catalogs:t}},n,r,i){let a=e.devDependencies?.[n.name]??e.dependencies?.[n.name];if(!a)return{findings:[{currentState:`The required package \`${n.name}\` is not installed.`,goal:[`Run \`adamantite update\` so \`${n.name}@${n.version}\` is installed.`],id:`missing-${n.name}`,integration:i,title:`Missing ${n.name}`}],packageActions:[{description:`Install \`${n.name}@${n.version}\` for ${r}.`,package:n.name,targetVersion:n.version,type:`install_package`}],warnings:[]};function o(e){return{findings:[],packageActions:[],warnings:[`\`${n.name}\` is declared as \`${e}\`, so Adamantite cannot check it against the required version \`${n.version}\`.`]}}function s(e,t){let r=e==="default"?"the `catalog`":`the \`${e}\` catalog`;return{findings:[{currentState:`${r} of \`pnpm-workspace.yaml\` sets \`${n.name}\` to \`${t}\`, but Adamantite requires \`${n.version}\`.`,goal:[`Set \`${n.name}\` to \`${n.version}\` in ${r} of \`pnpm-workspace.yaml\`, then install the dependencies.`],id:`outdated-${n.name}`,integration:i,notes:["Keep the `catalog:` specifier in `package.json`. `adamantite update` does not change catalogs."],title:`Outdated ${n.name}`}],packageActions:[],warnings:[]}}return ee(b(a),{Catalog:({catalog:e})=>{let r=t[e]?.[n.name];return r===void 0?o(a):ee(b(r),{Catalog:()=>o(a),Unreadable:()=>o(a),Version:({version:t})=>t===n.version?Ut:s(e,r)})},Unreadable:()=>o(a),Version:({version:e})=>e===n.version?Ut:{findings:[{currentState:`The installed \`${n.name}\` version is \`${a}\`, but Adamantite requires \`${n.version}\`.`,goal:[`Run \`adamantite update\` so \`${n.name}@${n.version}\` is installed.`],id:`outdated-${n.name}`,integration:i,title:`Outdated ${n.name}`}],packageActions:[{currentVersion:a,description:`Update \`${n.name}\` from \`${a}\` to \`${n.version}\`.`,package:n.name,targetVersion:n.version,type:`update_package`}],warnings:[]}})}function Gt(e,t){if(e.active instanceof Ft)return[{currentState:`The managed \`${t.configFile}\` file is missing.`,goal:[`Create \`${t.configFile}\` with the reference content.`,`Do not create a legacy JSON or JSONC ${t.toolName} config.`],id:`missing-${t.toolName}-config`,integration:t.toolName,reference:{content:t.configContent,language:`ts`},title:`Missing ${t.toolName} configuration`}];if(e.active instanceof Lt)return[{currentState:`Legacy \`${e.active.file.file}\` is the active ${t.toolName} configuration.`,goal:[`Move the project settings into \`${t.configFile}\` using the reference content as the base.`,`Delete every legacy ${t.toolName} JSON or JSONC config after its settings are preserved.`],id:`legacy-${t.toolName}-config`,integration:t.toolName,notes:[`Preserve project-specific settings. Do not replace them with the reference defaults.`],reference:{content:t.configContent,language:`ts`},title:`Legacy ${t.toolName} configuration`}];let n=[];return e.legacy.length>0&&n.push({currentState:`Legacy ${t.toolName} config files remain next to \`${t.configFile}\`: ${e.legacy.map(({file:e})=>`\`${e}\``).join(`, `)}.`,goal:[`Delete the legacy files after you confirm that \`${t.configFile}\` preserves their project-specific settings.`],id:`shadowed-legacy-${t.toolName}-config`,integration:t.toolName,title:`Legacy ${t.toolName} files remain`}),t.inspection?.kind===`invalid`&&n.push({currentState:`\`${t.configFile}\` does not meet Adamantite's required shape. ${t.inspection.reason}`,goal:[t.inspection.goal],id:`invalid-${t.toolName}-config`,integration:t.toolName,notes:[`Treat the reference as a known-good example, not an exact replacement.`],reference:{content:t.configContent,language:`ts`},title:`Invalid ${t.toolName} configuration`}),n}function Kt(e,n){let r=t(e);return n.some(e=>r.includes(e))}function qt(e){return G({assess:t=>T.sync(()=>{let{packageJson:n}=t,r=Kt(n,e.scripts)&&(!e.monorepoOnly||t.workspace.isMonorepo)&&(e.isRequired===void 0||e.isRequired(t)),i=e.legacyFindings?.(n)??[];if(!r)return i.length>0?{applicable:!0,findings:[...i],packageActions:[],warnings:[]}:{applicable:!1};let a=Wt(t,e,e.purpose,e.name);return{applicable:!0,findings:[...a.findings,...i],packageActions:a.packageActions,warnings:a.warnings}}),kind:`tooling`,name:e.name,version:e.version})}const Jt=T.fn(`readToolingFacts`)(function*(e){let t=yield*P.Path,[n,r]=yield*T.all([$e(e),C(t.join(e,`oxlint.config.ts`))],{concurrency:`unbounded`});return{isMonorepo:n,lintConfig:r}});function Yt(e){let t=[{path:e.configFiles.config,type:`config`},...e.configFiles.legacyConfigs.map(e=>({path:e,type:`legacy_config`}))],n=t=>Ht(t,e.name,e.configFiles);return G({assess:t=>T.gen(function*(){let{cwd:i,lintConfig:a,packageJson:o,workspace:{isMonorepo:s}}=t;if(!Kt(o,e.scripts))return{applicable:!1};let c=yield*n(i),l=e.workspace({isMonorepo:s,lintConfig:a}),u=Wt(t,e,e.purpose,e.name),d=e.configContent(l),f=c.active instanceof It?e.inspectConfig(yield*r(c.active.file.path),l):void 0;return{applicable:!0,findings:[...u.findings,...Gt(c,{configContent:d,configFile:e.configFiles.config,inspection:f,toolName:e.name})],packageActions:u.packageActions,warnings:[...u.warnings,...c.warnings]}}),config:e.configFiles.config,create:t=>T.gen(function*(){let n=yield*P.Path;yield*S(n.join(t,e.configFiles.config),e.configContent(e.workspace(yield*Jt(t))))}),detect:n,files:t,kind:`tooling`,name:e.name,version:e.version})}function K(e){return`adamantite${e.slice(1)}`}const Xt=K(`./rules`),q=`.adamantite/lint`,Zt=/* @__PURE__ */ new Set([`.js`,`.mjs`,`.mts`,`.ts`]);function Qt(e){let t=/\.[^.]+$/.exec(e)?.[0]??``;return Zt.has(t)&&!e.startsWith(`_`)&&!/\.(?:d\.m?ts|test\.[^.]+)$/.test(e)}function $t(e){return!e.startsWith(`_`)&&/\.test\.(?:js|mjs|mts|ts)$/.test(e)}var en=class extends I.TaggedClass(`Dynamic`){},tn=class extends I.TaggedClass(`Literal`){};const nn=new en;function rn(e,t){return bt(e,t,{preserveParens:!1,sourceType:`module`})}function an(e){return e.body.flatMap(e=>e.type===`ImportDeclaration`&&e.source.value===Xt?e.specifiers:[]).filter(e=>e.type===`ImportDefaultSpecifier`).map(e=>e.local.name)}function on(e,t){let n=rn(e,t);return n.errors.length>0?!1:n.program.body.some(e=>e.type===`ImportDeclaration`?e.source.value===`adamantite/lint/custom`||e.source.value===Xt&&e.specifiers.some(e=>e.type===`ImportSpecifier`&&(e.imported.type===`Identifier`?e.imported.name:e.imported.value)!==`CustomRulesOptions`):e.type===`ExportNamedDeclaration`&&e.source!==null?e.source.value===`adamantite/lint/custom`||e.source.value===Xt&&e.specifiers.some(e=>{let t=e.local.type===`Identifier`?e.local.name:e.local.value;return t!=="default"&&t!==`CustomRulesOptions`}):e.type===`ExportAllDeclaration`&&e.source.value===`adamantite/lint/custom`)}function sn(e){return e.type===`Literal`&&F.isString(e.value)?e.value:e.type===`TemplateLiteral`&&e.expressions.length===0?e.quasis[0]?.value.cooked??null:null}function cn(e){return e.type===`Literal`&&F.isString(e.value)?e.value:null}function ln(e,t,n){let r=L(e,D.findLast(e=>(e.key.type===`Identifier`?e.key.name:cn(e.key))===t));return M.fromNullOr(M.match(r,{onNone:()=>n,onSome:({value:e})=>sn(e)}))}function un(e){let t=e.filter(e=>e.type!==`SpreadElement`&&!e.computed);return t.length<e.length?nn:M.match(ln(t,`dir`,q),{onNone:()=>nn,onSome:e=>new tn({dir:e,name:ln(t,`name`,`project`)})})}function dn(e,t){let n=rn(e,t),r=an(n.program);if(n.errors.length>0||r.length===0)return[];let i=[];return new yt({CallExpression(e){if(e.callee.type!==`Identifier`||!r.includes(e.callee.name))return;let[t]=e.arguments;t===void 0?i.push(un([])):t.type===`ObjectExpression`?i.push(un(t.properties)):i.push(nn)}}).visit(n.program),i}function fn(e,t){return e.slice(0,t).split(`
2
+ `).length}function pn(e){switch(e.type){case`TSInterfaceDeclaration`:case`TSTypeAliasDeclaration`:return!0;case`TSModuleDeclaration`:return mn(e);case`ClassDeclaration`:case`FunctionDeclaration`:case`TSEnumDeclaration`:case`VariableDeclaration`:return e.declare===!0;case`ExportNamedDeclaration`:return e.declaration===null?e.exportKind===`type`:pn(e.declaration);default:return!1}}function mn(e){return e.kind===`global`||e.declare||e.body===null||e.body.body.every(e=>e.type!==`ExpressionStatement`&&pn(e))}function hn(e){return e.body.some(e=>e.type===`ExportDefaultDeclaration`?e.declaration.type!==`TSInterfaceDeclaration`:e.type===`ExportNamedDeclaration`&&e.exportKind!==`type`&&e.specifiers.some(e=>e.exportKind!==`type`&&(e.exported.type===`Literal`?e.exported.value==="default":e.exported.name==="default")))}function gn(e,t){let n=rn(e,t);return n.errors.length>0?[]:n.program.body.flatMap(e=>{switch(e.type){case`ImportDeclaration`:return e.importKind===`type`?[]:[e.source.value];case`ExportAllDeclaration`:case`ExportNamedDeclaration`:return e.source===null||e.exportKind===`type`?[]:[e.source.value];default:return[]}})}function _n(e,t){let n=rn(e,t);if(n.errors.length>0)return n.errors.map(e=>`Syntax error: ${e.message}`);let r=[],i=(e,n)=>{r.push(`Line ${fn(t,e)}: ${n} needs a TypeScript transform, which type stripping does not do.`)};return new yt({TSEnumDeclaration(e){e.declare||i(e.start,"`enum`")},TSExportAssignment(e){i(e.start,"`export =`")},TSImportEqualsDeclaration(e){e.importKind!==`type`&&i(e.start,"`import x = ...`")},TSModuleDeclaration(e){mn(e)||i(e.start,"A `namespace` with values")},TSParameterProperty(e){i(e.start,`A parameter property`)}}).visit(n.program),hn(n.program)||r.push(`The file has no default export. Export the rule as default.`),r}const vn=[`respectEslintDisableDirectives`,`typeAware`,`typeCheck`],yn="`oxlint.config.ts` must export an object literal directly, with or without `defineConfig(...)`, for Adamantite to inspect `options`.",bn="`oxlint.config.ts` has an `options` property, but it is not an object literal that Adamantite can inspect.",xn="Set `respectEslintDisableDirectives`, `typeAware`, and `typeCheck` to `true` in the `options` object. Preserve every other project setting.";function Sn(e){return e.replaceAll(/-([a-z])/g,(e,t)=>t.toUpperCase())}function Cn(e=[]){let t=[`core`,...e];return[`import { defineConfig } from "oxlint"`,...t.map(e=>`import ${Sn(e)} from "${K(e===`core`?`./lint`:`./lint/${e}`)}"`),`import custom from "${K(`./rules`)}"`,``,`export default defineConfig({`,` extends: [${[...t.map(e=>Sn(e)),`custom()`].join(`, `)}],`,` ignorePatterns: core.ignorePatterns,`,` options: {`,...vn.map(e=>` ${e}: true,`),` },`,`})`,``].join(`
3
+ `)}const wn=M.liftThrowable(e=>bt(`oxlint.config.ts`,e,{astType:`ts`,lang:`ts`,sourceType:`module`}));function Tn(e){return wn(e).pipe(M.flatMap(e=>e.errors.length===0?M.fromNullishOr(e.program):M.none()))}const En=`${K(`./lint`)}/`;function Dn(e){return L(Tn(e),M.map(e=>e.body.flatMap(e=>e.type===`ImportDeclaration`&&e.source.value.startsWith(En)&&e.source.value!==`adamantite/lint/custom`?[e.source.value.slice(En.length)]:[])),M.getOrElse(()=>[]))}function On(e,t){return M.exists(e,e=>Dn(e).includes(t))}function kn(e){return e.type===`Identifier`?L(e.name,M.some):e.type===`Literal`&&F.isString(e.value)?L(e.value,M.some):M.none()}function An(e){return e.type===`ObjectExpression`?L(e,M.some):e.type!==`CallExpression`||e.callee.type!==`Identifier`||e.callee.name!==`defineConfig`?M.none():L(e.arguments.length===1?D.head(e.arguments):M.none(),M.filter(e=>e.type===`ObjectExpression`))}function jn(e){return L(e.body,D.filter(e=>e.type===`ExportDefaultDeclaration`),e=>e.length===1?D.head(e):M.none(),M.flatMap(e=>An(e.declaration)))}function Mn(e,t){let n=null;for(let r of e.properties){if(r.type===`SpreadElement`||r.computed)return{status:`invalid`};let e=M.contains(kn(r.key),t);if(r.method||r.kind!==`init`){if(e)return{status:`invalid`}}else if(e){if(n)return{status:`invalid`};n=r}}return n?{property:n,status:`found`}:{status:`missing`}}function Nn(e){for(let t of vn){let n=Mn(e,t);if(n.status===`invalid`)return{goal:xn,kind:`invalid`,reason:"`oxlint.config.ts` has an `options` object Adamantite cannot inspect. Make sure each required option is a plain `key: true | false` property. Avoid spreads (`...rest`), computed keys (`[name]: ...`), duplicate keys, methods/getters/setters, and non-boolean-literal values."};if(n.status===`missing`||n.property.value.type!==`Literal`||n.property.value.value!==!0)return{goal:xn,kind:`invalid`,reason:`The required Oxlint options are missing or are not set to true.`}}return{kind:`configured`}}function Pn(e){let t=Tn(e);if(M.isNone(t))return{goal:"Fix the syntax errors in `oxlint.config.ts`. Preserve every project setting.",kind:`invalid`,reason:yn};let n=jn(t.value);if(M.isNone(n))return{goal:"Export the config object literal directly from `oxlint.config.ts`, with or without `defineConfig(...)`. Preserve every project setting.",kind:`invalid`,reason:yn};let r=Mn(n.value,`options`);return r.status===`invalid`?{goal:xn,kind:`invalid`,reason:bn}:r.status===`missing`?{goal:xn,kind:`invalid`,reason:`The required Oxlint options are missing.`}:r.property.value.type===`ObjectExpression`?Nn(r.property.value):{goal:xn,kind:`invalid`,reason:bn}}function Fn(e,t){for(let n of e.body)if(n.type===`ImportDeclaration`&&n.source.value===t){for(let e of n.specifiers)if(e.type===`ImportDefaultSpecifier`)return e.local.name}return null}function In(e,t){for(let n of e.body)if(n.type===`VariableDeclaration`){for(let e of n.declarations)if(e.id.type===`Identifier`&&e.id.name===t)return e.init}return null}function Ln(e,t,n){let r=!1;return new yt({Identifier:e=>{e.start>=n.start&&e.end<=n.end&&e.name===t&&(r=!0)}}).visit(e),r}function Rn(e,t){let n=e.body.filter(e=>e.type===`ExportDefaultDeclaration`);if(n.length!==1)return!1;let r=n[0]?.declaration;if(!r)return!1;if(r.type!==`Identifier`)return Ln(e,t,r);if(r.name===t)return!0;let i=In(e,r.name);return i!==null&&Ln(e,t,i)}function zn(e,t){let n=`Import the ${t.presetName} preset from \`${t.moduleName}\`, and use it in the exported config. Preserve every project-specific setting.`,r=bt(`config.ts`,e,{astType:`ts`,lang:`ts`,sourceType:`module`});if(r.errors.length>0)return{goal:`Fix the syntax errors in the file. Preserve every project-specific setting.`,kind:`invalid`,reason:`The file is not valid TypeScript.`};let i=Fn(r.program,t.moduleName);return i?Rn(r.program,i)?{kind:`configured`}:{goal:n,kind:`invalid`,reason:`The imported ${t.presetName} preset is not used by the exported configuration.`}:{goal:n,kind:`invalid`,reason:`The file must import the ${t.presetName} preset from \`${t.moduleName}\`.`}}const Bn=[`monorepo`,`effect`],Vn={effect:[`@effect/language-service`],monorepo:[`sherif`]},Hn={effect:e=>e.usesEffectPreset,monorepo:e=>e.isMonorepo},Un={effect:"the `effect` lint preset names the `@effect/language-service` plugin in `tsconfig.json`, and no package has that name",monorepo:"Knip cannot see that `adamantite analyze` runs Sherif in a monorepo"},Wn={isMonorepo:!1,usesEffectPreset:!1};function Gn(e,t){return new RegExp(String.raw`ignoreDependencies\s*:\s*\[[^\]]*?${vt.escape(t)}`,`u`).test(e)}function Kn(e,t){return new RegExp(String.raw`ignoreDependencies\s*:\s*(?:ignoreDependencies\.${t}|\[[^\]]*?ignoreDependencies\.${t})`,`u`).test(e)}const qn=/import\s[^;]*?\{[^}]*\bignoreDependencies\b[^}]*\}\s*from\s*["']adamantite\/analyze["']/u;function Jn(e){return Bn.filter(t=>Hn[t](e))}function Yn(e,t){return Vn[t].every(t=>Gn(e,t))||Kn(e,t)&&qn.test(e)}function Xn(e){let[t]=e;return e.length===1&&t!==void 0?`ignoreDependencies.${t}`:`[${e.map(e=>`...ignoreDependencies.${e}`).join(`, `)}]`}function Zn({isMonorepo:e,lintConfig:t}){return{isMonorepo:e,usesEffectPreset:On(t,`effect`)}}function Qn(e,t){let n=zn(e,{moduleName:K(`./analyze`),presetName:`Adamantite analyze`});if(n.kind!==`configured`)return n;let r=Jn(t),i=r.filter(t=>!Yn(e,t));if(i.length===0)return n;let a=`\`ignoreDependencies: ${Xn(r)}\``;return{goal:`Set ${a} in \`knip.config.ts\`, with the named \`ignoreDependencies\` import from \`adamantite/analyze\`, and keep the other settings.`,kind:`invalid`,reason:`The file must set ${a} from \`adamantite/analyze\`, because ${i.map(e=>Un[e]).join(`, and `)}.`}}function $n(e=Wn){let t=Jn(e);return[`import type { KnipConfig } from "knip"`,t.length>0?`import analyze, { ignoreDependencies } from "${K(`./analyze`)}"`:`import analyze from "${K(`./analyze`)}"`,``,...t.length>0?[`const config: KnipConfig = {`,` ...analyze,`,` ignoreDependencies: ${Xn(t)},`,`}`]:[`const config: KnipConfig = analyze`],``,`export default config`,``].join(`
4
+ `)}function er(e){return{args:[...e.fix?[`--fix`,`--allow-remove-files`]:[],...e.strict?[`--production`,`--strict`]:[],...e.forwardedArguments],command:`knip`,cwd:e.cwd,stdin:`ignore`,title:`🧹 Analyzing unused code`}}var tr={analyze:er,...Yt({configContent:$n,configFiles:{config:`knip.config.ts`,legacyConfigs:[`knip.json`,`knip.jsonc`]},inspectConfig:Qn,name:`knip`,purpose:"the managed `analyze` script",scripts:Oe(`knip`),version:`6.42.0`,workspace:Zn})};function nr(e){return{args:[`--check`,...e.files,...e.forwardedArguments],command:`oxfmt`,cwd:e.cwd,title:`✨ Checking formatting`}}function rr(e){return{args:[`--write`,...e.files,...e.forwardedArguments],command:`oxfmt`,cwd:e.cwd,title:`✨ Formatting`}}function ir(e){return zn(e,{moduleName:K(`./format`),presetName:`Adamantite format`})}function ar(){return`import { defineConfig } from "oxfmt"
5
+ import format from "adamantite/format"
6
+
7
+ export default defineConfig(format)
8
+ `}var or={check:nr,fix:rr,...Yt({configContent:ar,configFiles:{config:`oxfmt.config.ts`,legacyConfigs:[`.oxfmtrc.json`,`.oxfmtrc.jsonc`]},inspectConfig:ir,name:`oxfmt`,purpose:"the managed `check` and `fix` scripts",scripts:Oe(`oxfmt`),version:`0.76.0`,workspace:({isMonorepo:e})=>({isMonorepo:e})})};function sr(e){let t=tt(e.cwd),n=e.forwardedArguments.some(e=>e===`--deny-warnings`||e.startsWith(`--max-warnings`)),r=e.allowWarnings||n?[]:[`--deny-warnings`];return{...t,args:[...t.args,...e.files,...r,...e.forwardedArguments],title:`🔍 Linting`}}const cr={all:[`--fix-suggestions`,`--fix-dangerously`],dangerous:[`--fix-dangerously`],safe:[],suggested:[`--fix-suggestions`]};function lr(e){let t=tt(e.cwd);return{...t,args:[...t.args,`--fix`,...cr[e.level],...e.files,...e.forwardedArguments],title:`🔧 Fixing lint issues`}}const ur=z.decodeUnknownOption(z.Struct({header:z.Struct({glibcVersionRuntime:z.optional(z.String)}),sharedObjects:z.Array(z.String)}));function dr(e,t){return[{currentState:e,goal:t,id:`unavailable-oxlint-runtime`,integration:`oxlint`,notes:["Verification: run `adamantite check --only lint` after the repair."],title:`Oxlint runtime unavailable`}]}const fr=T.fn(`assessOxlintRuntime`)(function*(e){let t=t=>e.packageJson.devDependencies?.[t]??e.packageJson.dependencies?.[t];return t(`oxlint`)?yield*T.gen(function*(){let n=yield*fe(e.cwd),{backend:r,binding:i}=n;if(t(`tsrs`)&&r instanceof Ke)return dr(`Oxlint cannot resolve the declared tsrs backend or its launcher.`,[`Install the target project's dependencies so that the tsrs-lint launcher is available.`]);for(let n of We)if(n.runtime instanceof Se&&t(n.name)){let t=yield*we(e.cwd,n.name);if(M.isNone(t))return yield*new ie({packageName:n.name,project:e.cwd})}if(i instanceof Ie&&!(r instanceof Ee))return[];let a=yield*R.FileSystem,o=yield*P.Path,s=yield*Pe,c=`${A.platform}-${A.arch}`,l=`gnu`;if(A.platform===`linux`){let e=yield*C(`/usr/bin/ldd`),t=M.isNone(e)?ur(A.report.getReport()):M.none();l=(M.isSome(e)?e.value.includes(`musl`):M.isSome(t)&&!t.value.header.glibcVersionRuntime&&t.value.sharedObjects.some(e=>e.includes(`libc.musl-`)||e.includes(`ld-musl-`)))?`musl`:`gnu`}let u=c+({android:A.arch===`arm`?`-eabi`:``,linux:`-${l}${A.arch===`arm`?`eabihf`:``}`,win32:A.arch===`x64`&&(`shlib_suffix`in A.config.variables&&A.config.variables.shlib_suffix===`dll.a`||`node_target_type`in A.config.variables&&A.config.variables.node_target_type===`shared_library`)?`-gnu`:`-msvc`}[A.platform]??``);if(i instanceof He){let e=yield*xt.String(`NAPI_RS_NATIVE_LIBRARY_PATH`).pipe(xt.withDefault(``)),t=A.platform===`darwin`?[`darwin-universal`,u]:[u],r=[...e?[e]:t.flatMap(e=>[`./oxlint.${e}.node`,`@oxlint/binding-${e}`]),`./oxlint.wasi.cjs`,`@oxlint/binding-wasm32-wasi`],i=yield*T.findFirst(r,e=>T.gen(function*(){let t=yield*s.resolve(o.join(n.oxlint,`dist`),e);return M.isNone(t)||!(yield*a.exists(t.value))?!1:e!==`./oxlint.wasi.cjs`||(yield*a.exists(o.join(n.oxlint,`dist`,`oxlint.wasm32-wasi.wasm`)))||(yield*a.exists(o.join(n.oxlint,`dist`,`oxlint.wasm32-wasi.debug.wasm`)))}));if(M.isNone(i))return dr(`Oxlint cannot resolve its installed native binding.`,[`Install the target project's optional dependencies for this platform, or restore its local binding.`])}if(r instanceof Ee){let t=yield*we(e.cwd,`tsrs`),n=yield*xt.String(`TSRS_BINARY`).pipe(xt.withDefault(``)),i=`${c}${A.platform===`linux`?`-${l}`:``}`,s=M.isSome(t)&&!n?yield*we(t.value,`@tsrs/${i}`):M.none(),u=n===``?M.isSome(s)?o.join(s.value,A.platform===`win32`?`tsrs.exe`:`tsrs`):void 0:n;if(!(yield*a.exists(r.launcher))||u===void 0||!(yield*a.exists(u)))return dr(`Oxlint cannot resolve the installed tsrs binary or its launcher.`,[`Install the target project's optional dependencies for this platform, or restore TSRS_BINARY.`])}return[]}).pipe(T.catchTags({EffectBuildMissing:e=>T.succeed(dr(e.message,["Run `adamantite update` to align Oxlint, tsrs, and @effect/tsgo with supported builds."])),EffectPlatformUnsupported:e=>T.succeed(dr(e.message,["Lint on a platform that `@effect/tsgo` has builds for, or remove `@effect/tsgo` and the effect preset."])),NativeRuntimeConflict:e=>T.succeed(dr(e.message,[`Install at most one Oxlint plugin that replaces each native part of the Oxlint runtime.`])),PackageNotInstalled:e=>T.succeed(t(e.packageName)?dr(e.message,[`Install the target project's dependencies, then run Doctor again.`]):[])})):[]}),pr=`oxlint.config.ts`,mr=`.oxlintrc.json`,hr=[{path:pr,type:`config`},{path:mr,type:`legacy_config`}],gr={config:pr,legacyConfigs:[mr]},_r=`1.91.0`,vr={antislop:{currentState:"`oxlint.config.ts` imports the retired `adamantite/lint/antislop` preset.",goal:["Replace `adamantite/lint/antislop` with `adamantite/lint/strict`. If strict is already imported, remove the antislop import and its `extends` entry.","Keep `anti-slop/*` rule settings, rule severity, rule options, and all other project settings. The rule namespace stays the same.",'strict sets `anti-slop/no-chained-type-assertions`, `anti-slop/no-widen-then-assert`, and `anti-slop/require-safety-comment-for-type-assertion` in an override for test files, which takes priority over top-level `rules`. Move a project setting for these three rules into an `overrides` entry with `files: ["**/*.{test,spec}.{ts,tsx,mts,cts}", "**/__tests__/**"]`.',"The strict preset also bans type assertions outside tests, console calls other than `console.info`, task comments, and deep destructuring, and it requires a reason on each suppression. Follow those reports when updating the code.","Use `--preset strict` in init commands. Run `adamantite check`, then run `adamantite doctor` again."],id:`strict-preset-migration`,integration:`oxlint`,title:`The antislop rules now belong to strict`},"react-doctor":{currentState:"`oxlint.config.ts` imports the retired `adamantite/lint/react-doctor` preset.",goal:["Replace `adamantite/lint/react-doctor` with `adamantite/lint/react-strict`. If react-strict is already imported, use its existing binding and remove the old import.","Keep the `react` preset and exactly one `react-strict` entry in extends. Keep `oxlint-plugin-react-doctor` as a devDependency. Run `adamantite update` if the package is missing or off its managed version.","Preserve project settings, custom rules, rule severity, and rule options, including `react-doctor/*` overrides. The upstream rule namespace stays the same.",`The react-strict preset also reports state, effect, and memoization hooks outside hook modules. Follow those reports when updating feature code.`,"Run `adamantite check`, then run Doctor again."],id:`react-doctor-preset-migration`,integration:`oxlint`,title:`React Doctor rules now belong to react-strict`},shadcn:{currentState:"`oxlint.config.ts` imports the removed `adamantite/lint/shadcn` preset.",goal:["Replace `adamantite/lint/shadcn` with `adamantite/lint/tailwind` in `oxlint.config.ts`. Keep the local import name and its `extends` entry.","Keep the managed `@shadcn/lint` package, `shadcn/*` rule names, `settings.shadcn` keys, rule severity, rule options, and all other project settings.","Use `--preset tailwind` in init commands. Run `adamantite check`, then run `adamantite doctor` again."],id:`tailwind-preset-migration`,integration:`oxlint`,title:`The shadcn preset was renamed to tailwind`}},yr=e=>Ht(e,`oxlint`,gr);var br=G({assess:e=>T.gen(function*(){let{cwd:n,lintConfig:r,packageJson:i}=e,a=t(i);if(!y(a,`oxlint`))return{applicable:!1};let o=yield*yr(n),s=yield*fr(e),c=Wt(e,{name:`oxlint`,version:_r},`the managed lint scripts`,`oxlint`),l=o.active instanceof It?r.pipe(M.map(e=>Pn(e)),M.getOrUndefined):void 0,u=Cn(),d=Me.flatMap(e=>On(r,e)?[vr[e]]:[]);return{applicable:!0,findings:[...c.findings,...s,...d,...Gt(o,{configContent:u,configFile:pr,inspection:l,toolName:`oxlint`})],packageActions:c.packageActions,warnings:[...c.warnings,...o.warnings]}}),check:sr,config:pr,create:(e,t=[])=>T.gen(function*(){let n=yield*P.Path,r=Cn(t);yield*S(n.join(e,pr),r)}),detect:yr,files:hr,fix:lr,kind:`tooling`,name:`oxlint`,version:_r});function xr(e){return{args:[...e.fix?[`--fix`]:[],...e.forwardedArguments],command:`sherif`,cwd:e.cwd,stdin:`inherit`,title:`📦 Analyzing the monorepo`}}var Sr={analyze:xr,...qt({monorepoOnly:!0,name:`sherif`,purpose:"the managed `analyze` script in a monorepo",scripts:Oe(`sherif`),version:`1.13.0`})};const Cr=T.fn(`Toolchain.check`)(function*({allowWarnings:e=!1,cwd:t,files:n=[],forwardedArguments:r=[],only:i}){if(i===`format`&&e)return yield*new Be({reason:"`--allow-warnings` applies to the lint stage. Remove it or `--only format`."});let a=yield*Pt,o=i??`lint`,s={format:or.check({cwd:t,files:n,forwardedArguments:o===`format`?r:[]}),lint:br.check({allowWarnings:e,cwd:t,files:n,forwardedArguments:o===`lint`?r:[]})};yield*a.runAll(i===void 0?[s.format,s.lint]:[s[i]])}),wr=T.fn(`Toolchain.fix`)(function*({cwd:e,files:t=[],forwardedArguments:n=[],level:r=`safe`,only:i}){if(i===`format`&&r!==`safe`)return yield*new Te({reason:"`--suggested`, `--dangerous`, and `--all` apply to the lint stage. Remove them or `--only format`."});let a=yield*Pt,o=D.dedupe(t),s=i??`lint`,c={format:or.fix({cwd:e,files:o,forwardedArguments:s===`format`?n:[]}),lint:br.fix({cwd:e,files:o,forwardedArguments:s===`lint`?n:[],level:r})};yield*a.runAll(i===void 0?[c.lint,c.format]:[c[i]])}),Tr=T.fn(`Toolchain.analyze`)(function*({cwd:e,fix:t=!1,forwardedArguments:n=[],only:r,strict:i=!1}){let a=yield*Pt,o=yield*P.Path,s=r!==`unused`&&(yield*g(o.join(e,`package.json`)))&&(yield*$e(e).pipe(T.catchTags({FailedToParseFile:()=>T.succeed(!1),InvalidPackageJson:()=>T.succeed(!1)})));if(r===`monorepo`){if(i)return yield*new xe({reason:"`--strict` applies to the unused stage. Remove it or `--only monorepo`."});if(!s)return yield*new xe({reason:"`--only monorepo` requires a monorepo. Run from the monorepo root, or use `--only unused` for a single-package project."})}let c=r??`unused`,l={monorepo:Sr.analyze({cwd:e,fix:t,forwardedArguments:c===`monorepo`?n:[]}),unused:tr.analyze({cwd:e,fix:t,forwardedArguments:c===`unused`?n:[],strict:i})},u=r===void 0?[...s?[l.monorepo]:[],l.unused]:[l[r]];yield*(t?a.runUntilFailure(u):a.runAll(u)).pipe(T.mapError(e=>F.isTagged(e,`CliNotFound`)&&e.command===Sr.name?new qe({command:e.command,hint:"Run `adamantite update` to install it."}):e))}),Er=j.Boolean(`fix`).pipe(j.withDefault(!1),j.withDescription(`Apply fixes in each selected stage`)),Dr=j.Boolean(`strict`).pipe(j.withDefault(!1),j.withDescription(`Enable Knip's strict mode when checking unused code`)),Or=j.Literals(`only`,[`monorepo`,`unused`]).pipe(j.optional,j.withDescription(`Run only monorepo (Sherif) or unused (Knip). Pass tool arguments after --`));var kr=O.make(`analyze`,{fix:Er,only:Or,strict:Dr}).pipe(O.withDescription(`Check monorepo consistency with Sherif and find unused code with Knip`),O.withExamples([{command:`adamantite analyze -- --directory packages/app`,description:`Run Knip from a specific directory`},{command:`adamantite analyze --only monorepo --fix -- --select highest`,description:`Fix monorepo issues and use the highest version when versions differ`}]),O.withHandler(({fix:e,only:t,strict:n})=>T.gen(function*(){yield*Tr({cwd:A.cwd(),fix:e,forwardedArguments:yield*At,only:M.getOrUndefined(t),strict:n})})));const Ar=V.File(`files`,{mustExist:!0}).pipe(V.withDescription(`Files to check. Omit to check the project`),V.variadic()),jr=j.Literals(`only`,[`format`,`lint`]).pipe(j.optional,j.withDescription(`Run only format (Oxfmt) or lint (Oxlint). Pass tool arguments after --`)),Mr=j.Boolean(`allow-warnings`).pipe(j.withDefault(!1),j.withDescription(`Allow the lint check to pass when Oxlint reports only warnings`));var Nr=O.make(`check`,{allowWarnings:Mr,files:Ar,only:jr}).pipe(O.withDescription(`Check formatting, lint issues, and TypeScript types`),O.withHandler(({allowWarnings:e,files:t,only:n})=>T.gen(function*(){yield*Cr({allowWarnings:e,cwd:A.cwd(),files:t,forwardedArguments:yield*At,only:M.getOrUndefined(n)})})));const Pr=`# ADAMANTITE:START`,Fr=`# ADAMANTITE:END`;var Ir=class extends I.TaggedClass(`Block`){},Lr=class extends I.TaggedClass(`None`){},Rr=class extends I.TaggedClass(`Malformed`){};function zr(e,t){return e.flatMap((e,n)=>e.trim()===t?[n]:[])}function Br(e){let t=e.split(`
9
+ `),n=zr(t,Pr),r=zr(t,Fr),[i]=n,[a]=r;return i===void 0&&a===void 0?new Lr:n.length>1||r.length>1?new Rr({reason:`It has more than one \`${Pr}\` or \`${Fr}\` comment.`}):a===void 0||i!==void 0&&a<i?new Rr({reason:`It has \`${Pr}\` without \`${Fr}\` after it.`}):i===void 0?new Rr({reason:`It has \`${Fr}\` without \`${Pr}\` before it.`}):new Ir({after:t.slice(a).join(`
10
+ `),before:t.slice(0,i+1).join(`
11
+ `),body:t.slice(i+1,a).join(`
12
+ `)})}function Vr(e,t){return[e.before,...t===``?[]:[t],e.after].join(`
13
+ `)}function Hr(e,t){return e.replaceAll(/\{\{(\w+)\}\}/g,(e,n)=>Object.hasOwn(t,n)?t[n]??e:e)}function Ur(e,t){return i.flatMap(n=>t.includes(n)?[{command:Tt(e,n),name:n}]:[])}function Wr(){return i.reduce((e,t)=>e.flatMap(e=>[e,[...e,t]]),[[]]).filter(e=>e.length>0)}function Gr(e){return i.some(t=>e.includes(t))}var Kr=class extends N.Service()(`DependencyInstaller`){static layer=k.succeed(this)({addDevDependencies:T.fn(`DependencyInstaller.addDevDependencies`)((e,t,n)=>T.tryPromise({catch:t=>new Re({cause:t,packages:e}),try:()=>Ct(e,{...n,cwd:t})}).pipe(T.asVoid)),detectPackageManager:T.fn(`DependencyInstaller.detectPackageManager`)(e=>T.tryPromise({catch:e=>new me({cause:e}),try:()=>wt(e)}).pipe(T.map(e=>e??null)))})};function qr(e,t){return t&&e!==`npm`}const Jr=(e,t)=>T.gen(function*(){let n=yield*Kr,r=yield*Pe,[i,a]=yield*T.all([$e(e),n.detectPackageManager(e)],{concurrency:`unbounded`});yield*n.addDevDependencies(t,e,{silent:!0,workspace:qr(a?.name,i)}).pipe(T.ensuring(r.clearCache))});var Yr=class extends I.TaggedClass(`File`){},Xr=class extends I.TaggedClass(`Version`){};const Zr=[`.node-version`,`.nvmrc`],Qr=z.Struct({volta:z.Struct({node:z.NonEmptyString})}),$r=z.Struct({engines:z.Struct({node:z.NonEmptyString})}),ei=z.Struct({name:z.NonEmptyString,version:z.NonEmptyString});function ti(e){return e.split(`
14
+ `).map(e=>e.split(`#`)[0]?.trim()??``).some(e=>/^node(?:js)?\s+\S/.test(e))}function ni(e){return z.is(ei)(e)&&e.name.toLowerCase()===`node`}function ri(e){if(z.is(Qr)(e))return!0;if(F.isObject(e)&&F.isObject(e.devEngines)){let t=e.devEngines.runtime;if((Array.isArray(t)?t:[t]).some(e=>ni(e)))return!0}return z.is($r)(e)}const ii=[...Zr.map(e=>new Yr({path:e})),new Yr({path:`.tool-versions`}),new Yr({path:`package.json`}),new Xr({value:`lts/*`})];var ai=class extends N.Service()(`NodeVersionResolver`){static layer=k.effect(this,T.gen(function*(){let e=yield*R.FileSystem,t=yield*P.Path,n=(n,r)=>C(t.join(n,r)).pipe(T.provideService(R.FileSystem,e));return{resolve:T.fn(`NodeVersionResolver.resolve`)(function*(e){for(let t of Zr){let r=yield*n(e,t);if(M.exists(r,e=>pt.isNonEmpty(e.trim())))return new Yr({path:t})}let r=yield*n(e,`.tool-versions`);if(M.exists(r,e=>ti(e)))return new Yr({path:`.tool-versions`});let i=yield*n(e,`package.json`);return M.isSome(i)&&ri(yield*w(i.value,t.join(e,`package.json`)))?new Yr({path:`package.json`}):new Xr({value:`lts/*`})})}}))};function oi(e){return c.map(t=>{let[n,r]=Tt(t,`script`).split(` `);return`${n}(?:\\s+(?!${r}\\b)\\S+)*\\s+${r}\\s+${e}`}).join(`|`)}const si=new RegExp(String.raw`\b(?:${oi(`check`)})\b`),ci=`.github/workflows`,li=[{path:`${ci}/adamantite.yml`,type:`ci`}],ui=z.Struct({steps:z.optionalKey(z.Array(z.Struct({run:z.optionalKey(z.String),with:z.optionalKey(z.Struct({"node-version":z.optionalKey(z.Union([z.String,z.Finite]))}))}))),strategy:z.optionalKey(z.Struct({matrix:z.optionalKey(z.Unknown)}))}),di=z.Struct({jobs:z.Record(z.String,ui)}),fi=z.Struct({include:z.Array(z.Struct({command:z.optionalKey(z.String)}))});var pi=class extends I.TaggedClass(`Missing`){},mi=class extends I.TaggedClass(`Managed`){},hi=class extends I.TaggedClass(`Legacy`){},gi=class extends I.TaggedClass(`Malformed`){};const _i=(e,t)=>T.try({catch:e=>new Ne({cause:e,path:t}),try:()=>ht.parse(e)}),vi=(e,t)=>_i(e,t).pipe(T.flatMap(e=>z.decodeUnknownEffect(di)(e)),T.map(({jobs:e})=>Object.values(e)),T.option),yi=z.Struct({jobs:z.NullOr(z.Record(z.String,z.Unknown))}),bi=(e,t)=>_i(e,t).pipe(T.flatMap(e=>z.decodeUnknownEffect(yi)(e)),T.map(({jobs:e})=>e??{})),xi=(e,t)=>T.gen(function*(){let n=e.before.replaceAll(`\r`,``),r=yield*bi(n,t),i=yield*bi(`${n}\n${e.body.replaceAll(`\r`,``)}`,t);return yield*z.decodeUnknownEffect(z.Array(ui))(Object.entries(i).flatMap(([e,t])=>_t.has(r,e)?[]:[t]))}).pipe(T.option),Si=e=>T.gen(function*(){let t=yield*P.Path,n=yield*rt(t.join(e,ci)),r=D.sort(M.getOrElse(n,()=>[]).filter(e=>/\.ya?ml$/u.test(e)),B.String).map(e=>`${ci}/${e}`),i=D.getSomes(yield*T.forEach(r,n=>f(t.join(e,n)).pipe(T.map(e=>M.map(e,e=>({block:Br(e),content:e,path:n})))))),[a]=i.flatMap(({block:e,path:t})=>e instanceof Rr?[{path:t,reason:e.reason}]:[]);if(a)return new gi({paths:[a.path],reason:a.reason});let o=i.flatMap(({block:e,path:t})=>e instanceof Ir?[{block:e,path:t}]:[]);if(o.length>1)return new gi({paths:o.map(e=>e.path),reason:`More than one workflow file has a managed block.`});let[s]=o;if(s){let n=yield*xi(s.block,t.join(e,s.path));return M.match(n,{onNone:()=>new gi({paths:[s.path],reason:`The jobs between the markers do not parse as workflow jobs.`}),onSome:e=>new mi({block:s.block,jobs:e,path:s.path})})}let c=i.find(e=>e.path===li[0].path);if(c){let n=yield*vi(c.content,t.join(e,c.path));return new hi({content:c.content,jobs:M.getOrElse(n,()=>[]),path:c.path})}return new pi});function Ci(e){let t=e.flatMap(e=>e.steps??[]),n=e.flatMap(e=>M.match(z.decodeUnknownOption(fi)(e.strategy?.matrix),{onNone:()=>[],onSome:({include:e})=>e.flatMap(e=>e.command??[])}));return{commands:[...t.flatMap(e=>e.run??[]),...n],nodeVersions:t.flatMap(e=>e.with?.[`node-version`]??[])}}function wi(e){return` - name: Setup Node.js
16
15
  uses: actions/setup-node@v7
17
16
  with:
18
- ${e._tag===`File`?`node-version-file: "${e.path}"`:`node-version: "${e.value}"`}`}function sr(e){return{bun:`${or(e)}
17
+ ${e instanceof Yr?`node-version-file: "${e.path}"`:`node-version: "${e.value}"`}`}function Ti(e){return{bun:`${wi(e)}
19
18
 
20
19
  - name: Setup Bun
21
20
  uses: oven-sh/setup-bun@v2
@@ -35,22 +34,23 @@ import*as e from"@effect/platform-node/NodeRuntime";import*as t from"effect/Effe
35
34
  uses: denoland/setup-deno@v2
36
35
 
37
36
  - name: Install dependencies
38
- run: deno install --frozen`,npm:`${or(e)}
37
+ run: deno install --frozen`,npm:`${wi(e)}
39
38
  cache: "npm"
40
39
 
41
40
  - name: Install dependencies
42
41
  run: npm ci`,pnpm:` - name: Setup pnpm
43
42
  uses: pnpm/action-setup@v6
44
43
 
45
- ${or(e)}
44
+ ${wi(e)}
46
45
  cache: "pnpm"
47
46
 
48
47
  - name: Install dependencies
49
- run: pnpm install --frozen-lockfile`,yarn:`${or(e)}
48
+ run: pnpm install --frozen-lockfile`,yarn:`${wi(e)}
50
49
  cache: "yarn"
51
50
 
52
51
  - name: Install dependencies
53
- run: yarn install --frozen-lockfile`}}function cr({packageManager:e,scripts:t},n){let r=Rn(e,t);return r.length===0?null:`${`name: adamantite
52
+ run: yarn install --frozen-lockfile`}}function Ei({packageManager:e,scripts:t},n){let r=Ur(e,t);if(r.length===0)return null;let i=r.map(e=>` - name: ${e.name}\n command: ${e.command}`).join(`
53
+ `);return Hr(`name: adamantite
54
54
 
55
55
  on:
56
56
  push:
@@ -67,6 +67,7 @@ concurrency:
67
67
  cancel-in-progress: true
68
68
 
69
69
  jobs:
70
+ {{start}}
70
71
  verify:
71
72
  name: \${{ matrix.name }}
72
73
  runs-on: ubuntu-latest
@@ -75,61 +76,631 @@ jobs:
75
76
  fail-fast: false
76
77
  matrix:
77
78
  include:
78
- ${r.map(e=>` - name: ${e.name}\n command: ${e.command}`).join(`
79
- `)}
79
+ {{matrix}}
80
80
 
81
81
  steps:
82
82
  - name: Checkout
83
83
  uses: actions/checkout@v7
84
84
 
85
- ${sr(n)[e]}
85
+ {{setup}}
86
86
 
87
87
  - name: Run \${{ matrix.name }}
88
- run: \${{ matrix.command }}`}\n`}const lr={currentState:"The workflow still runs the legacy `format` script with `--check`.",goal:["Remove the workflow step or matrix entry that runs the `format` script with `--check`."],id:`legacy-format-workflow-step`,integration:`github`,notes:["The managed `check` script verifies formatting. Preserve unrelated workflow jobs and project-specific settings."],title:`Legacy format workflow step`},ur={currentState:"The workflow still runs a legacy monorepo script or `adamantite monorepo`.",goal:["Remove the workflow step or matrix entry that runs `check:monorepo`, `fix:monorepo`, or `adamantite monorepo`.","Make the workflow run the managed `analyze` script. It runs Sherif in a detected monorepo."],id:`legacy-monorepo-workflow-step`,integration:`github`,notes:[`Preserve unrelated workflow jobs and project-specific settings.`],title:`Legacy monorepo workflow step`},dr=[{path:`.github/workflows/adamantite.yml`,type:`ci`}],fr=(e,n)=>t.gen(function*(){let t=yield*w.Path,r=yield*Qn,i=t.join(e,dr[0].path),a=cr(n,yield*r.resolve(e));a&&(yield*F(i,a))});var pr=M({assess:(e,n)=>t.gen(function*(){let t=(yield*w.Path).join(e,dr[0].path),r=yield*P(t);if(r._tag===`None`)return{applicable:!1,warnings:[]};let i=ut(n),a=$n.test(r.value),o=i.includes(`check`)&&!ar(r.value,tr),s=[...ar(r.value,nr)?[lr]:[],...ar(r.value,rr)?[ur]:[]];if(!a&&!o)return{applicable:!0,findings:s,packageActions:[],warnings:[]};if(!zn(i))return{applicable:!0,findings:s,packageActions:[],warnings:[`No CI-compatible managed scripts were found, so the GitHub Actions workflow cannot be regenerated.`]};let c=yield*(yield*Bn).detectPackageManager(e);return c?lt(c.name)?{applicable:!0,findings:[{currentState:[...a?[`The workflow contains a hard-coded Node.js version.`]:[],...o?["The workflow does not run the managed `check` script."]:[]].join(` `),goal:["Make the workflow run the managed `check` script.",`Use the project's Node.js version declaration instead of a hard-coded version.`],id:`outdated-adamantite-workflow`,integration:`github`,notes:[`The detected package manager is \`${c.name}\`. Preserve unrelated workflow jobs and project-specific settings.`],title:`Outdated Adamantite workflow`},...s],packageActions:[],warnings:[]}:{applicable:!0,findings:s,packageActions:[],warnings:[`\`${c.name}\` is not a supported package manager for CI workflow generation, so the GitHub Actions workflow cannot be regenerated.`]}:{applicable:!0,findings:s,packageActions:[],warnings:[`Could not detect a package manager, so the GitHub Actions workflow cannot be regenerated.`]}}),create:(e,n)=>t.gen(function*(){let t=yield*w.Path;yield*We(t.dirname(t.join(e,dr[0].path))),yield*fr(e,n)}),detect:e=>t.gen(function*(){let t=yield*C.FileSystem,n=yield*w.Path;return yield*t.exists(n.join(e,dr[0].path))}),files:dr,kind:`ci`,name:`github`,update:fr});const G=[{path:`.zed/settings.json`,type:`config`}],mr={languages:{Astro:{format_on_save:`on`,prettier:{allowed:!0,plugins:[`prettier-plugin-astro`]}},CSS:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}}],prettier:{allowed:!1}},HTML:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}}],prettier:{allowed:!1}},JSON:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}}],prettier:{allowed:!1}},JSONC:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}}],prettier:{allowed:!1}},JavaScript:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}},{code_action:`source.fixAll.oxc`}],prettier:{allowed:!1}},MDX:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}}],prettier:{allowed:!1}},Markdown:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}}],prettier:{allowed:!1}},TSX:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}},{code_action:`source.fixAll.oxc`}],prettier:{allowed:!1}},TypeScript:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}},{code_action:`source.fixAll.oxc`}],prettier:{allowed:!1}},YAML:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}}],prettier:{allowed:!1}}},lsp:{oxfmt:{initialization_options:{settings:{"fmt.configPath":null,run:`onSave`}}},oxlint:{initialization_options:{settings:{configPath:null,fixKind:`safe_fix`,run:`onType`,typeAware:!0,unusedDisableDirectives:`deny`}}}}},hr={configPath:null,"fmt.experimental":!0,typeAware:!1,unusedDisableDirectives:!1};function gr(e){let t=e.lsp,n=L(t)?t.oxfmt:void 0,r=L(n)?n.initialization_options:void 0,i=L(r)?r.settings:void 0;if(!L(i))return[];let a=Object.entries(hr);return Object.entries(i).filter(([e,t])=>a.some(([n,r])=>n===e&&r===t)).map(([e])=>e)}function _r(e){return!L(e)||!qe(e.plugins)?e:Object.fromEntries([...Object.entries(e),[`plugins`,s.dedupe(e.plugins)]])}function vr(e){let t=e.languages;if(!L(t))return e;let n=Object.fromEntries(Object.entries(t).map(([e,t])=>!(e in mr.languages)||!L(t)?[e,t]:[e,Object.fromEntries(Object.entries(t).map(([e,t])=>e===`formatter`&&qe(t)?[e,s.dedupe(t)]:e===`prettier`?[e,_r(t)]:[e,t]))]));return Object.fromEntries([...Object.entries(e),[`languages`,n]])}var K=M({assess:(e,n)=>t.gen(function*(){let t=(yield*w.Path).join(e,G[0].path),n=yield*P(t);if(n._tag===`None`)return{applicable:!1,warnings:[]};let r=yield*I(n.value,t),i=L(r)?gr(r):[];return{applicable:!0,findings:i.length===0?[]:[{currentState:`\`${G[0].path}\` contains stale oxfmt settings: ${i.map(e=>`\`${e}\``).join(`, `)}.`,goal:[`Remove only the stale oxfmt entries that still have Adamantite's old default values.`,`Preserve entries that the project changed.`],id:`legacy-zed-oxfmt-settings`,integration:`zed`,title:`Legacy Zed oxfmt settings`}],packageActions:[],warnings:[]}}),config:G[0].path,create:e=>t.gen(function*(){let t=yield*w.Path,n=t.join(e,G[0].path);yield*We(t.dirname(n)),yield*Ke(n,mr)}),detect:e=>t.gen(function*(){let t=yield*C.FileSystem,n=yield*w.Path;return yield*t.exists(n.join(e,G[0].path))}),files:G,kind:`editor`,name:`zed`,update:e=>t.gen(function*(){let t=(yield*w.Path).join(e,G[0].path),n=yield*N(t),r=yield*I(n,t);if(!x.isObject(r))return yield*new Me({path:t});let i=vr(yield*Je(mr,r));yield*F(t,it(n,i))})});const yr=`project`,br=`.adamantite/rules`,xr=/* @__PURE__ */ new Set([`.js`,`.mjs`,`.mts`,`.ts`]);function Sr(e){let t=/\.[^.]+$/.exec(e)?.[0]??``;return xr.has(t)&&!e.startsWith(`_`)&&!/\.d\.m?ts$/.test(e)}function Cr(e,t){return de(e,t,{preserveParens:!1,sourceType:`module`})}function wr(e,t){return e.body.flatMap(e=>e.type===`ImportDeclaration`&&e.source.value===t?e.specifiers:[]).find(e=>e.type===`ImportDefaultSpecifier`)?.local.name}function Tr(e){return e.type===`Literal`&&x.isString(e.value)?e.value:e.type===`TemplateLiteral`&&e.expressions.length===0?e.quasis[0]?.value.cooked??null:null}function Er(e){return e.type===`Literal`&&x.isString(e.value)?e.value:null}function Dr(e){let t=br,n=yr;for(let r of e.properties){if(r.type===`SpreadElement`||r.computed)return{dir:null,name:null};let e=r.key.type===`Identifier`?r.key.name:Er(r.key);e===`dir`?t=Tr(r.value):e===`name`&&(n=Tr(r.value))}return{dir:t,name:n}}function Or(e,t){let n=Cr(e,t),r=wr(n.program,`adamantite/lint/custom`);if(n.errors.length>0||r===void 0)return[];let i=[];return new ue({CallExpression(e){if(e.callee.type!==`Identifier`||e.callee.name!==r)return;let[t]=e.arguments;t===void 0?i.push({dir:br,name:yr}):t.type===`ObjectExpression`?i.push(Dr(t)):i.push({dir:null,name:null})}}).visit(n.program),i}function kr(e,t){return e.slice(0,t).split(`
89
- `).length}function Ar(e){switch(e.type){case`TSInterfaceDeclaration`:case`TSTypeAliasDeclaration`:return!0;case`TSModuleDeclaration`:return jr(e);case`ClassDeclaration`:case`FunctionDeclaration`:case`TSEnumDeclaration`:case`VariableDeclaration`:return e.declare===!0;case`ExportNamedDeclaration`:return e.declaration===null?e.exportKind===`type`:Ar(e.declaration);default:return!1}}function jr(e){return e.kind===`global`||e.declare||e.body===null||e.body.body.every(e=>e.type!==`ExpressionStatement`&&Ar(e))}function Mr(e){return e.body.some(e=>e.type===`ExportDefaultDeclaration`?e.declaration.type!==`TSInterfaceDeclaration`:e.type===`ExportNamedDeclaration`&&e.exportKind!==`type`&&e.specifiers.some(e=>e.exportKind!==`type`&&(e.exported.type===`Literal`?e.exported.value==="default":e.exported.name==="default")))}function Nr(e,t){let n=Cr(e,t);return n.errors.length>0?[]:n.program.body.flatMap(e=>{switch(e.type){case`ImportDeclaration`:return e.importKind===`type`?[]:[e.source.value];case`ExportAllDeclaration`:case`ExportNamedDeclaration`:return e.source===null||e.exportKind===`type`?[]:[e.source.value];default:return[]}})}function Pr(e,t){let n=Cr(e,t);if(n.errors.length>0)return n.errors.map(e=>`Syntax error: ${e.message}`);let r=[],i=(e,n)=>{r.push(`Line ${kr(t,e)}: ${n} needs a TypeScript transform, which type stripping does not do.`)};return new ue({TSEnumDeclaration(e){e.declare||i(e.start,"`enum`")},TSExportAssignment(e){i(e.start,"`export =`")},TSImportEqualsDeclaration(e){e.importKind!==`type`&&i(e.start,"`import x = ...`")},TSModuleDeclaration(e){jr(e)||i(e.start,"A `namespace` with values")},TSParameterProperty(e){i(e.start,`A parameter property`)}}).visit(n.program),Mr(n.program)||r.push(`The file has no default export. Export the rule as default.`),r}const Fr=`.adamantite/rules`,Ir=/^[a-z][\da-z]*(?:-[\da-z]+)*$/;function Lr(e){return`import { defineRule } from "adamantite/rules"
90
-
91
- export default defineRule({
92
- meta: {
93
- docs: { description: "TODO: describe what ${e} reports." },
94
- messages: { unexpected: "TODO: tell the author what to do instead." },
95
- schema: [],
96
- type: "problem",
97
- },
98
- createOnce(context) {
99
- return {
100
- // Run \`adamantite rule ast <file>\` to find the node types to visit.
101
- DebuggerStatement(node) {
102
- context.report({ messageId: "unexpected", node })
103
- },
104
- }
105
- },
106
- })
107
- `}const Rr=t.fn(`addCustomRule`)(function*(e,n,r=Fr){if(!Ir.test(n))return yield*new Fe({rule:n});let i=yield*C.FileSystem,a=yield*w.Path,o=a.resolve(e,r),s=a.join(o,`${n}.ts`),c=a.join(o,`AGENTS.md`),l=e=>i.exists(e).pipe(t.mapError(t=>new Ae({cause:t,path:e})));return(yield*l(s))?yield*new Ce({path:s}):(yield*We(o),yield*F(s,Lr(n)),(yield*l(c))?{agentsPath:void 0,rulePath:s}:(yield*F(c,'# Custom rules\n\nEach file in the rules folder, `.adamantite/rules/` by default, is an Oxlint rule that this\nproject owns. `custom()` from `adamantite/lint/custom` loads the folder and enables each\nrule as `error` under the `project` plugin: `no-process-env.ts` becomes\n`project/no-process-env`. Add a file to add a rule. Delete the file to remove the rule.\n`adamantite rule add <name>` writes a correct stub.\n\n- A file that starts with `_`, such as `_helpers.ts`, is a helper, not a rule. Subfolders are\n not read.\n- Export the rule as default with `defineRule` from `adamantite/rules`. The same module exports\n the `Context`, `Rule`, `Visitor`, and `ESTree` node types.\n- Use `createOnce`. It runs one time for each lint run, not one time for each file. Reset\n per-file state in `before`, and report collected results in `after`. `context.filename`,\n `context.sourceCode`, and `context.settings` are not available in the body of\n `createOnce`. Read them in `before` or in a visitor.\n- Write erasable TypeScript only. Oxlint loads rule files with Node.js type stripping, so\n `enum`, a `namespace` with values, parameter properties, and `import x = require()` stop\n the lint run.\n- Rules get no type information. Use only the AST and `context.sourceCode`.\n- Report with a `messageId`, and put each message in `meta.messages`. Describe the options in\n `meta.schema`, and read them from `context.options`.\n- A rule that throws prints an error for each file, and the lint run still exits 0. After you\n change a rule, run the lint and read all of its output.\n- To find node names, run `adamantite rule ast <file>` on real code. It prints the same\n ESTree-shaped AST that rules visit.\n- To test a rule, use `RuleTester` from `oxlint/plugins-dev`. Adamantite does not run rule\n tests.\n- Oxlint caches the rules for each run. Restart the editor language server after you change a\n rule.\n- TypeScript does not check `.adamantite/rules/` by default, because its name starts with a dot. Add\n `".adamantite/rules"` to `include` in `tsconfig.json` to check it.\n- In a monorepo, give each rules folder its own plugin name, such as `custom({ name: "web" })`:\n Oxlint rejects two plugins with the same name in one run. A relative `dir` resolves from the\n file that calls `custom()`, so a shared tooling package can own the rules with\n `custom({ dir: "rules", name: "acme" })`. A nested Oxlint config replaces the root config, so\n a package that needs the root rules extends the root config.\n'),{agentsPath:c,rulePath:s}))}),zr=`custom-rules`,Br=[`oxlint.config.ts`,`oxlint.config.mts`,`oxlint.config.js`,`oxlint.config.mjs`],Vr=[`.ts`,`.mts`,`.cts`,`.js`,`.mjs`,`.cjs`],Hr=/* @__PURE__ */ new Set([`default`,`import`,`node`]);function Ur(e){if(e!=null)return x.isString(e)?e:s.isArray(e)?e.map(e=>Ur(e)).find(e=>e!==void 0):Object.entries(e).filter(([e])=>Hr.has(e)).map(([,e])=>Ur(e)).find(e=>e!==void 0)}const Wr=D.combine(D.mapInput(D.flip(D.Number),([e])=>e.indexOf(`*`)),D.mapInput(D.flip(D.Number),([e])=>e.length));function Gr(e,t){let{exports:n}=e;if(n===void 0)return t===``?e.main??`index`:t;let r=t===``?`.`:`./${t}`;if(n===null||x.isString(n)||s.isArray(n))return r===`.`?Ur(n):void 0;let i=Object.keys(n).some(e=>e.startsWith(`.`))?n:{".":n};if(r in i)return Ur(i[r]);let a=s.sort(Object.entries(i),Wr).map(([e,t])=>{let[n,i,...a]=e.split(`*`);return n!==void 0&&i!==void 0&&a.length===0&&r.startsWith(n)&&r.endsWith(i)&&r.length>n.length+i.length?{match:r.slice(n.length,r.length-i.length),target:t}:null}).find(e=>e!==null);return a===void 0?void 0:Ur(a.target)?.replaceAll(`*`,a.match)}const Kr=t.fn(`readWorkspacePackage`)(function*(e){let t=yield*R(e);return t.name===void 0?d.none():d.some({directory:e,exports:t.exports,main:t.main,name:t.name})}),qr=t.fn(`readFirstFile`)(function*(e){for(let n of e){let e=yield*P(n).pipe(t.orElseSucceed(()=>d.none()));if(d.isSome(e))return d.some({content:e.value,file:n})}return d.none()}),Jr=t.fn(`resolveImport`)(function*(e,t,n){let r=yield*w.Path,i;if(t.startsWith(`.`)||r.isAbsolute(t))i=r.resolve(r.dirname(e),t);else{let e=n.find(e=>t===e.name||t.startsWith(`${e.name}/`));if(e===void 0)return{_tag:`external`};let a=Gr(e,t.slice(e.name.length+1));if(a===void 0)return{_tag:`unresolved`};i=r.resolve(e.directory,a)}if(i.split(r.sep).includes(`node_modules`))return{_tag:`external`};let a=i,o=i.replace(/\.[cm]?js$/u,``),s=yield*qr([i,...Vr.map(e=>`${o}${e}`),...Vr.map(e=>r.join(a,`index${e}`))]);return d.match(s,{onNone:()=>({_tag:`unresolved`}),onSome:e=>({_tag:`found`,module:e})})}),Yr=t.fn(`findCustomRulesCalls`)(function*(e){let n=yield*w.Path,r=s.getSomes(yield*t.forEach(e,e=>Kr(e),{concurrency:`unbounded`})),i=s.getSomes(yield*t.forEach(e,e=>qr(Br.map(t=>n.join(e,t))),{concurrency:`unbounded`})),a=/* @__PURE__ */ new Set,o=[],c=[],l=i;for(;l.length>0;){let e=l.filter(e=>!a.has(e.file));for(let t of e)a.add(t.file),t.content.includes(`adamantite/lint/custom`)&&o.push(...Or(t.file,t.content).map(e=>({dir:e.dir===null?null:n.resolve(n.dirname(t.file),e.dir),name:e.name,source:t.file})));let i=e.flatMap(e=>Nr(e.file,e.content).map(t=>({from:e.file,specifier:t}))),s=yield*t.forEach(i,({from:e,specifier:t})=>Jr(e,t,r),{concurrency:`unbounded`});l=[];for(let[e,t]of s.entries()){let n=i[e];t._tag===`found`?l.push(t.module):t._tag===`unresolved`&&n!==void 0&&c.push(n)}}return{calls:o,unresolvedImports:c}}),Xr=t.fn(`readRulesFolder`)(function*(e){return(yield*Ge(e)).pipe(d.map(t=>({dir:e,ruleFiles:t.filter(e=>Sr(e))})))});var Zr=M({assess:e=>t.gen(function*(){let n=yield*w.Path,r=t=>n.relative(e,t)||`.`,i=[e,...(yield*B(e))?yield*St(e):[]],{calls:a,unresolvedImports:o}=yield*Yr(i),c=i.map(e=>n.join(e,Fr)),l=s.dedupe(a.flatMap(e=>e.dir===null?[]:[e.dir])),u=s.getSomes(yield*t.forEach(s.dedupe([...c,...l]),e=>Xr(e),{concurrency:`unbounded`})).filter(e=>e.ruleFiles.length>0);if(a.length===0&&u.length===0&&o.length===0)return{applicable:!1,warnings:[]};let d=a.filter(e=>e.dir===null||e.name===null),f=[...o.map(({from:e,specifier:t})=>`Doctor cannot resolve the import of \`${t}\` in \`${r(e)}\`, so it does not check the \`custom()\` calls and rules folders behind it.`),...d.map(e=>`Doctor cannot read the \`dir\` or \`name\` of a \`custom()\` call in \`${r(e.source)}\`, because it is not a string literal. Doctor does not check that rules folder.`)],p=[];if(d.length===0&&o.length===0)for(let e of u)l.includes(e.dir)||p.push({currentState:`\`${r(e.dir)}\` has ${e.ruleFiles.length} rule file(s), but no \`custom()\` call loads it, so Oxlint does not run them.`,goal:[`Load \`${r(e.dir)}\` with \`custom()\` from \`adamantite/lint/custom\` in the Oxlint config of \`${r(n.dirname(n.dirname(e.dir)))}\`. A relative \`dir\` resolves from the file that calls \`custom()\`.`,"Give each rules folder its own plugin name with the `name` option, because Oxlint rejects two plugins with the same name in one run.",`Preserve every other setting in the Oxlint config.`],id:`custom-rules-not-loaded:${r(e.dir)}`,integration:zr,reference:{content:`import { defineConfig } from "oxlint"
108
- import core from "adamantite/lint"
109
- import custom from "adamantite/lint/custom"
88
+ run: \${{ matrix.command }}
89
+ {{end}}
90
+ `,{end:Fr,matrix:i,setup:Ti(n)[e],start:Pr})}function Di(e){let t=Br(e);if(!(t instanceof Ir))throw TypeError(`The GitHub Actions workflow template has no managed block.`);return t.body}function Oi(){return ii.flatMap(e=>_t.keys(Ti(e)).flatMap(t=>Wr().flatMap(n=>Ei({packageManager:t,scripts:n},e)??[])))}function ki(e){return e.replaceAll(`\r
91
+ `,`
92
+ `).replaceAll(`\r`,``).trimEnd()}function Ai(e){let t=ki(e);return Oi().some(e=>ki(Di(e))===t)}function ji(e){let t=ki(e);return Oi().some(e=>ki(e.split(`
93
+ `).filter(e=>e.trim()!==`# ADAMANTITE:START`&&e.trim()!==`# ADAMANTITE:END`).join(`
94
+ `))===t)}var Mi=G({assess:({cwd:e,packageJson:n})=>T.gen(function*(){let r=yield*Si(e);if(r instanceof pi)return{applicable:!1};if(r instanceof gi)return{applicable:!0,findings:[{currentState:`Adamantite cannot read the managed block in ${r.paths.map(e=>`\`${e}\``).join(`, `)}. ${r.reason}`,goal:[`Put the jobs that run the Adamantite scripts between one \`${Pr}\` comment and one \`${Fr}\` comment, in one workflow file.`],id:`malformed-adamantite-workflow`,integration:`github`,notes:[`Preserve the other jobs and project-specific settings.`],title:`Malformed Adamantite workflow block`}],packageActions:[],warnings:[]};let i=t(n),a=Ci(r.jobs),s=a.nodeVersions.some(e=>/^\d/.test(String(e))),c=i.includes(`check`)&&!a.commands.some(e=>si.test(e));if(!s&&!c)return{applicable:!0,findings:[],packageActions:[],warnings:[]};if(!Gr(i))return{applicable:!0,findings:[],packageActions:[],warnings:[`No CI-compatible managed scripts were found, so the GitHub Actions workflow cannot be regenerated.`]};let l=yield*(yield*Kr).detectPackageManager(e);return l?o(l.name)?{applicable:!0,findings:[{currentState:[...s?[`The managed jobs in \`${r.path}\` contain a hard-coded Node.js version.`]:[],...c?[`The managed jobs in \`${r.path}\` do not run the managed \`check\` script.`]:[]].join(` `),goal:[...i.includes(`check`)?["Make a managed job run the managed `check` script."]:[],`Use the project's Node.js version declaration instead of a hard-coded version.`],id:`outdated-adamantite-workflow`,integration:`github`,notes:[`The detected package manager is \`${l.name}\`.`,r instanceof hi?`\`${r.path}\` has no \`${Pr}\` and \`${Fr}\` comments, so Adamantite checks all its jobs. Put the jobs that run the Adamantite scripts between these comments, and preserve the other jobs and project-specific settings.`:`Adamantite checks only the jobs between \`${Pr}\` and \`${Fr}\`. Change only those jobs, and preserve the other jobs and project-specific settings.`],title:`Outdated Adamantite workflow`}],packageActions:[],warnings:[]}:{applicable:!0,findings:[],packageActions:[],warnings:[`\`${l.name}\` is not a supported package manager for CI workflow generation, so the GitHub Actions workflow cannot be regenerated.`]}:{applicable:!0,findings:[],packageActions:[],warnings:[`Could not detect a package manager, so the GitHub Actions workflow cannot be regenerated.`]}}),create:(e,t)=>T.gen(function*(){let n=yield*P.Path,r=yield*ai,i=n.join(e,li[0].path),a=Ei(t,yield*r.resolve(e));a!==null&&(yield*x(n.dirname(i)),yield*S(i,a))}),detect:Si,files:li,kind:`ci`,name:`github`,update:(e,t)=>T.gen(function*(){let n=yield*P.Path,r=yield*ai,i=yield*Si(e),a=Ei(t,yield*r.resolve(e));if(a===null||i instanceof gi)return`kept`;if(i instanceof pi)return yield*S(n.join(e,li[0].path),a),`updated`;if(i instanceof hi)return ji(i.content)?(yield*S(n.join(e,i.path),a),`updated`):`kept`;if(!Ai(i.block.body))return`kept`;let o=Di(a),s=i.block.before.endsWith(`\r`);return yield*S(n.join(e,i.path),Vr(i.block,s?`${o.replaceAll(`
95
+ `,`\r
96
+ `)}\r`:o)),`updated`})});const J={agents:`agents`,editor:`editor`,nonInteractive:`non-interactive`,preset:`preset`,script:`script`};function Ni({agents:e=!1,editors:t=[],presets:n=[],scripts:r}){return[`adamantite init`,`--${J.nonInteractive}`,...r.map(e=>`--${J.script} ${e}`),...n.map(e=>`--${J.preset} ${e}`),...t.map(e=>`--${J.editor} ${e}`),...e?[`--${J.agents}`]:[]].join(` `)}const Pi=Ni({editors:[`vscode`],scripts:[`check`]}),Fi=`node_modules/.cache/adamantite/effect`,Ii=`adamantite-sdk.json`,Li=z.Struct({gitHead:z.NonEmptyString,version:z.NonEmptyString}),Ri=T.fn(`findNativeTypescript`)(function*(e){for(let t of[`typescript`,`@typescript/native`]){let n=yield*we(e,t);if(M.isSome(n)){let e=yield*u(n.value);if(Number(e.version?.split(`.`)[0])>=7)return z.decodeUnknownOption(Li)(e)}}return M.none()}),zi=T.fn(`resolveSdkSource`)(function*(e,t,n){let i=yield*P.Path,a=yield*R.FileSystem,o=yield*Ri(e);if(M.isNone(o))return yield*new pe({reason:`The Effect editor SDK needs an installed native TypeScript package with its gitHead. Install TypeScript 7 or later, then run \`${Pi}\`.`});let{gitHead:s,version:c}=o.value,l=`${A.platform}-${A.arch}`,u=yield*we(t,`@effect/tsgo-${l}`);if(M.isNone(u))return yield*new pe({reason:`The Effect editor SDK cannot find \`@effect/tsgo-${l}\`. Install the optional dependencies on a supported platform.`});let d=i.join(u.value,`lib`,`upstream.json`),f=yield*w(yield*r(d),d),p=h(f)&&f.components,m=h(p)&&p.typescript,g=h(f)&&f.tags,_=h(g)&&g.typescript;if(!h(f)||f.schemaVersion!==5||!h(m)||!h(_))return yield*new Fe({path:d});let v=A.platform===`win32`?`tsc.exe`:`tsc`;for(let[e,t]of Object.entries(m)){if(!h(t)||t.gitHead!==s)continue;let r=e===_.latest?i.join(u.value,`lib`):i.join(u.value,`artifacts`,`typescript`,e);if((yield*a.exists(i.join(r,v)))&&(yield*a.exists(i.join(r,`lib.d.ts`))))return{effectVersion:n,executable:v,gitHead:s,platform:l,source:r,typescriptVersion:c}}return yield*new pe({reason:`@effect/tsgo ${n} has no editor compiler matching TypeScript ${c} (${s}). Install a supported TypeScript version, then run \`${Pi}\`.`})}),Bi=T.fn(`sdkIsCurrent`)(function*(e,t){let n=yield*P.Path,r=yield*R.FileSystem,i=n.join(e,Fi),a=n.join(i,Ii),o=yield*C(a);if(M.isNone(o))return!1;let s=yield*w(o.value,a).pipe(T.catchTag(`FailedToParseFile`,()=>T.succeed(null)));if(!h(s)||!Object.entries(t).every(([e,t])=>s[e]===t))return!1;let c=yield*r.readDirectory(t.source);return(yield*T.forEach(c.filter(e=>e===t.executable||e.endsWith(`.d.ts`)),e=>r.exists(n.join(i,e)))).every(Boolean)}),Vi=T.fn(`readEffectEditor`)(function*(e){let t=yield*we(e,`@effect/tsgo`);if(M.isNone(t))return M.none();let n=yield*P.Path,i=yield*u(t.value),a=n.join(t.value,`oxlint-schema.json`),o=yield*w(yield*r(a),a),s=h(o)&&o.definitions,c=h(s)&&s.DummyRuleMap,l=h(c)&&c.properties;if(!h(l))return yield*new Fe({path:a});let d=Object.fromEntries(Object.keys(l).filter(e=>e.startsWith(`effecttsgo/`)).map(e=>[e,{severity:`off`}])),f=zi(e,t.value,i.version??`unknown`);return M.some({prepareSdk:T.gen(function*(){let t=yield*f;if(yield*Bi(e,t))return;let r=yield*R.FileSystem,i=n.join(e,Fi);yield*r.remove(i,{force:!0,recursive:!0}),yield*r.makeDirectory(n.dirname(i),{recursive:!0}),yield*r.copy(t.source,i),yield*se(n.join(i,Ii),t)}),rulesCustomization:d,sdkIsCurrent:f.pipe(T.flatMap(t=>Bi(e,t)))})}),Y=[{path:`.vscode/settings.json`,type:`config`}],Hi={"[css]":{"editor.defaultFormatter":`oxc.oxc-vscode`},"[graphql]":{"editor.defaultFormatter":`oxc.oxc-vscode`},"[javascript]":{"editor.defaultFormatter":`oxc.oxc-vscode`},"[javascriptreact]":{"editor.defaultFormatter":`oxc.oxc-vscode`},"[json]":{"editor.defaultFormatter":`oxc.oxc-vscode`},"[jsonc]":{"editor.defaultFormatter":`oxc.oxc-vscode`},"[typescript]":{"editor.defaultFormatter":`oxc.oxc-vscode`},"[typescriptreact]":{"editor.defaultFormatter":`oxc.oxc-vscode`},"editor.codeActionsOnSave":{"source.fixAll.oxc":`explicit`},"editor.defaultFormatter":`oxc.oxc-vscode`,"editor.formatOnPaste":!0,"editor.formatOnSave":!0,"oxc.path.oxlint":ue,"oxc.typeAware":!0};var Ui=G({assess:({cwd:e})=>T.gen(function*(){let t=(yield*P.Path).join(e,Y[0].path),n=yield*C(t);if(M.isNone(n))return{applicable:!1};let r=yield*w(n.value,t);if(!h(r))return yield*new Fe({path:t});let i=r[`oxc.path.oxlint`],a=Hi[`oxc.path.oxlint`],o=i===a?[]:[{currentState:`\`${Y[0].path}\` sets \`oxc.path.oxlint\` to ${i===void 0?`no value`:`\`${yield*ce(i)}\``}. VS Code does not start Oxlint through Adamantite's Oxlint entry.`,goal:[`Set \`oxc.path.oxlint\` to \`${a}\` in \`${Y[0].path}\`. Preserve every other setting.`],id:`vscode-oxlint-entry`,integration:`vscode`,reference:{content:`${yield*Ve({"oxc.path.oxlint":a})}\n`,language:`json`},title:`VS Code does not use the Oxlint entry`}],s=yield*Vi(e);if(M.isSome(s)){let e=r[`oxc.lint.customization`],t=h(e)&&Object.keys(s.value.rulesCustomization).every(t=>{let n=e[t];return h(n)&&n.severity===`off`});(r[`js/ts.tsdk.path`]!==`node_modules/.cache/adamantite/effect`||!t)&&o.push({currentState:`\`${Y[0].path}\` does not select the Effect editor SDK with duplicate Oxlint Effect reports hidden.`,goal:[`Set \`js/ts.tsdk.path\` to \`${Fi}\` and merge the reference \`oxc.lint.customization\` entries. Preserve other settings and rule customizations.`],id:`vscode-effect-server`,integration:`vscode`,reference:{content:`${yield*Ve({"js/ts.tsdk.path":Fi,"oxc.lint.customization":s.value.rulesCustomization})}\n`,language:`json`},title:`VS Code does not use the Effect language server`});let n=yield*s.value.sdkIsCurrent.pipe(T.map(e=>e?void 0:`\`${Fi}\` is missing or does not match the installed Effect compiler.`),T.catchTag(`EffectEditorUnavailable`,e=>T.succeed(e.message)));n!==void 0&&o.push({currentState:n,goal:[`Install a supported native TypeScript version and the Effect optional dependencies. Run \`${Ni({editors:[`vscode`],scripts:[`check`]})}\` to prepare the SDK cache, then restart the TypeScript server.`],id:`vscode-effect-sdk`,integration:`vscode`,title:`The Effect editor SDK needs preparation`})}return{applicable:!0,findings:o,packageActions:[],warnings:[]}}),config:Y[0].path,create:e=>T.gen(function*(){let t=yield*P.Path,n=t.join(e,Y[0].path),r=yield*Vi(e),i=M.isSome(r)?{...Hi,"js/ts.tsdk.path":Fi,"oxc.lint.customization":r.value.rulesCustomization}:Hi;M.isSome(r)&&(yield*r.value.prepareSdk),yield*x(t.dirname(n)),yield*se(n,i)}),detect:e=>T.gen(function*(){let t=yield*R.FileSystem,n=yield*P.Path;return yield*t.exists(n.join(e,Y[0].path))}),extension:(e=[],t=[])=>T.gen(function*(){let n=[];y(e,`oxlint`)&&n.push(`oxc.oxc-vscode`),y(e,`knip`)&&n.push(`webpro.vscode-knip`),t.includes(`effect`)&&n.push(`TypeScriptTeam.native-preview`);for(let e of n)yield*(yield*Pt).run({args:[`--install-extension`,e],command:`code`}).pipe(T.mapError(t=>F.isTagged(t,`CliNotFound`)&&t.command===`code`?new v({cause:t}):new Ge({cause:F.isTagged(t,`CommandFailed`)?t.exitCode:t,extension:e})))}),files:Y,kind:`editor`,name:`vscode`,update:e=>T.gen(function*(){let t=(yield*P.Path).join(e,Y[0].path),n=yield*r(t),i=yield*w(n,t);if(!F.isObject(i))return yield*new Fe({path:t});let a=yield*Vi(e),o=yield*m({fallback:Hi,preferred:i}),s=M.isSome(a)?[[`js/ts.tsdk.path`,Fi],[`oxc.lint.customization`,yield*m({fallback:h(i[`oxc.lint.customization`])?i[`oxc.lint.customization`]:{},preferred:a.value.rulesCustomization})]]:[];M.isSome(a)&&(yield*a.value.prepareSdk);let c=Object.fromEntries([...Object.entries(o),[`oxc.path.oxlint`,Hi[`oxc.path.oxlint`]],...s]);yield*S(t,le(n,c))})});const X=[{path:`.zed/settings.json`,type:`config`}],Wi={languages:{Astro:{format_on_save:`on`,prettier:{allowed:!0,plugins:[`prettier-plugin-astro`]}},CSS:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}}],prettier:{allowed:!1}},HTML:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}}],prettier:{allowed:!1}},JSON:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}}],prettier:{allowed:!1}},JSONC:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}}],prettier:{allowed:!1}},JavaScript:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}},{code_action:`source.fixAll.oxc`}],prettier:{allowed:!1}},MDX:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}}],prettier:{allowed:!1}},Markdown:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}}],prettier:{allowed:!1}},TSX:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}},{code_action:`source.fixAll.oxc`}],prettier:{allowed:!1}},TypeScript:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}},{code_action:`source.fixAll.oxc`}],prettier:{allowed:!1}},YAML:{format_on_save:`on`,formatter:[{language_server:{name:`oxfmt`}}],prettier:{allowed:!1}}},lsp:{oxfmt:{initialization_options:{settings:{"fmt.configPath":null,run:`onSave`}}},oxlint:{binary:{arguments:[ue,`--lsp`],path:`node`},initialization_options:{settings:{configPath:null,fixKind:`safe_fix`,run:`onType`,typeAware:!0,unusedDisableDirectives:`deny`}}}}},Gi={configPath:null,"fmt.experimental":!0,typeAware:!1,unusedDisableDirectives:!1},Ki=/* @__PURE__ */ new Set([`typescript-ls`,`tsgo`,`vtsls`,`typescript-language-server`]),qi=T.fn(`resolveEffectCli`)(function*(e){let t=yield*R.FileSystem,n=yield*P.Path,r=n.resolve(e);for(;;){let i=n.join(r,`node_modules`,`@effect`,`tsgo`);if(yield*t.exists(n.join(i,`package.json`)))return n.relative(e,n.join(i,`dist`,`effect-tsgo.cjs`)).replaceAll(`\\`,`/`);let a=n.dirname(r);if(a===r)return yield*new pe({reason:`Zed cannot find the installed Effect CLI in node_modules. Install @effect/tsgo, then run \`${Ni({editors:[`zed`],scripts:[`check`]})}\`.`});r=a}}),Ji=T.fn(`setEffectSettings`)(function*(e,t,n){let r={arguments:[yield*qi(e),`tsc`,`--lsp`,`--stdio`],path:`node`},i=h(t.languages)?t.languages:{},a={};for(let e of[`JavaScript`,`JSX`,`TypeScript`,`TSX`]){let t=h(i[e])?i[e]:{},n=(yield*z.decodeUnknownEffect(z.Array(z.String))(t.language_servers??[`...`])).filter(e=>!Ki.has(e.replace(/^!/,``)));a[e]=Object.fromEntries([...Object.entries(t),[`language_servers`,D.dedupe([`typescript-ls`,`!vtsls`,`!typescript-language-server`,...n])]])}let o=h(t.lsp)?t.lsp:{},s=h(o.tsgo)?o.tsgo:{},c=h(o[`typescript-ls`])?o[`typescript-ls`]:{},l=yield*m({fallback:s,preferred:c}),u=h(o.oxlint)?o.oxlint:{},d=h(u.initialization_options)?u.initialization_options:{},f=h(d.settings)?d.settings:{},p=h(f.rulesCustomization)?f.rulesCustomization:{},g=yield*m({fallback:p,preferred:n});return Object.fromEntries([...Object.entries(t),[`languages`,Object.fromEntries([...Object.entries(i),...Object.entries(a)])],[`lsp`,Object.fromEntries([...Object.entries(o).filter(([e])=>e!==`tsgo`),[`typescript-ls`,Object.fromEntries([...Object.entries(l),[`binary`,r]])],[`oxlint`,Object.fromEntries([...Object.entries(u),[`initialization_options`,Object.fromEntries([...Object.entries(d),[`settings`,Object.fromEntries([...Object.entries(f),[`rulesCustomization`,g]])]])]])]])]])});function Yi(e){let t=e.lsp,n=h(t)?t.oxfmt:void 0,r=h(n)?n.initialization_options:void 0,i=h(r)?r.settings:void 0;if(!h(i))return[];let a=Object.entries(Gi);return Object.entries(i).filter(([e,t])=>a.some(([n,r])=>n===e&&r===t)).map(([e])=>e)}function Xi(e){return!h(e)||!d(e.plugins)?e:Object.fromEntries([...Object.entries(e),[`plugins`,D.dedupe(e.plugins)]])}function Zi(e){let t=e.languages;if(!h(t))return e;let n=Object.fromEntries(Object.entries(t).map(([e,t])=>!(e in Wi.languages)||!h(t)?[e,t]:[e,Object.fromEntries(Object.entries(t).map(([e,t])=>e===`formatter`&&d(t)?[e,D.dedupe(t)]:e===`prettier`?[e,Xi(t)]:[e,t]))]));return Object.fromEntries([...Object.entries(e),[`languages`,n]])}function Qi(e){let t=h(e.lsp)?e.lsp:{},n=h(t.oxlint)?t.oxlint:{};return Object.fromEntries([...Object.entries(e),[`lsp`,Object.fromEntries([...Object.entries(t),[`oxlint`,Object.fromEntries([...Object.entries(n),[`binary`,Wi.lsp.oxlint.binary]])]])]])}var $i=G({assess:({cwd:e})=>T.gen(function*(){let t=(yield*P.Path).join(e,X[0].path),n=yield*C(t);if(M.isNone(n))return{applicable:!1};let r=yield*w(n.value,t);if(!h(r))return yield*new Fe({path:t});let i=Yi(r),a=h(r.lsp)?r.lsp:void 0,o=(h(a?.oxlint)?a.oxlint:void 0)?.binary,s=Wi.lsp.oxlint.binary,c=h(o)&&o.path===s.path&&mt.equals(o.arguments,s.arguments),l=yield*Vi(e),u=[];if(M.isSome(l)){let t=yield*Ji(e,r,l.value.rulesCustomization);mt.equals(r,t)||u.push({currentState:`\`${X[0].path}\` does not select the installed Effect language server with duplicate Oxlint Effect reports hidden.`,goal:["Select `typescript-ls` for JavaScript, JSX, TypeScript, and TSX. Use the reference server binary and Oxlint rule customizations. Move old `lsp.tsgo` settings to `lsp.typescript-ls`, and preserve other settings and language servers."],id:`zed-effect-server`,integration:`zed`,reference:{content:`${yield*Ve(yield*Ji(e,{},l.value.rulesCustomization))}\n`,language:`json`},title:`Zed does not use the Effect language server`})}return{applicable:!0,findings:[...u,...i.length===0?[]:[{currentState:`\`${X[0].path}\` contains stale oxfmt settings: ${i.map(e=>`\`${e}\``).join(`, `)}.`,goal:[`Remove only the stale oxfmt entries that still have Adamantite's old default values.`,`Preserve entries that the project changed.`],id:`legacy-zed-oxfmt-settings`,integration:`zed`,title:`Legacy Zed oxfmt settings`}],...c?[]:[{currentState:`\`${X[0].path}\` sets \`lsp.oxlint.binary\` to ${o===void 0?`no value`:`\`${yield*ce(o)}\``}. Zed does not start Oxlint through Adamantite's Oxlint entry.`,goal:[`Set \`lsp.oxlint.binary\` to \`${yield*ce(s)}\` in \`${X[0].path}\`. Preserve every other setting.`],id:`zed-oxlint-entry`,integration:`zed`,reference:{content:`${yield*Ve({lsp:{oxlint:{binary:s}}})}\n`,language:`json`},title:`Zed does not use the Oxlint entry`}]],packageActions:[],warnings:[]}}),config:X[0].path,create:e=>T.gen(function*(){let t=yield*P.Path,n=t.join(e,X[0].path),r=yield*Vi(e),i=M.isSome(r)?yield*Ji(e,Wi,r.value.rulesCustomization):Wi;yield*x(t.dirname(n)),yield*se(n,i)}),detect:e=>T.gen(function*(){let t=yield*R.FileSystem,n=yield*P.Path;return yield*t.exists(n.join(e,X[0].path))}),files:X,kind:`editor`,name:`zed`,update:e=>T.gen(function*(){let t=(yield*P.Path).join(e,X[0].path),n=yield*r(t),i=yield*w(n,t);if(!F.isObject(i))return yield*new Fe({path:t});let a=yield*m({fallback:Wi,preferred:i}),o=yield*Vi(e),s=Qi(Zi(a)),c=M.isSome(o)?yield*Ji(e,s,o.value.rulesCustomization):s;yield*S(t,le(n,c))})});const ea=[`oxlint.config.ts`,`oxlint.config.mts`,`oxlint.config.js`,`oxlint.config.mjs`];var ta=class extends I.TaggedClass(`external`){},na=class extends I.TaggedClass(`found`){},ra=class extends I.TaggedClass(`unresolved`){};const ia=T.fn(`readPackageName`)(function*(e){let t=yield*u(e);return M.fromUndefinedOr(t.name)}),aa=T.fn(`readFirstFile`)(function*(e){let t=yield*T.forEach(e,e=>f(e).pipe(T.map(t=>L(t,M.map(t=>({content:t,file:e}))))),{concurrency:`unbounded`});return D.head(D.getSomes(t))}),oa=T.fn(`resolveImport`)(function*(e,t,n){let r=yield*P.Path,i=yield*Pe,a=t.startsWith(`.`)||t.startsWith(`#`)||r.isAbsolute(t)||[...n].some(e=>t===e||t.startsWith(`${e}/`)),o=yield*i.resolve(r.dirname(e),t);if(M.isNone(o))return a?new ra:new ta;if(o.value.split(r.sep).includes(`node_modules`))return new ta;let s=yield*aa([o.value]);return M.match(s,{onNone:()=>new ra,onSome:e=>new na({module:e})})}),sa=T.fn(`discoverCustomRules`)(function*(e,t=e){let n=yield*P.Path;yield*(yield*Pe).clearCache;let[r,i]=yield*T.all([T.forEach(e,e=>ia(e),{concurrency:`unbounded`}),T.forEach(e,e=>aa(ea.map(t=>n.join(e,t))),{concurrency:`unbounded`})],{concurrency:`unbounded`}),a=new Set(D.getSomes(r)),o=D.getSomes(i),s=new Set(t.flatMap(e=>D.sort(o.filter(t=>{let r=n.dirname(t.file);return e===r||e.startsWith(r+n.sep)}),B.mapInput(B.flip(B.Number),e=>n.dirname(e.file).length)).slice(0,1))),c=o.filter(e=>s.has(e)),l=/* @__PURE__ */ new Set,u=[],d=[],f=[],p=[],m=c;for(;m.length>0;){let e=m.filter(e=>!l.has(e.file));for(let t of e)if(l.add(t.file),on(t.file,t.content)&&d.push(t.file),t.content.includes(Xt))for(let e of dn(t.file,t.content))e instanceof en?f.push(t.file):u.push({dir:n.resolve(n.dirname(t.file),e.dir),name:e.name,source:t.file});let t=e.flatMap(e=>gn(e.file,e.content).map(t=>({from:e.file,specifier:t}))),r=yield*T.forEach(t,({from:e,specifier:t})=>oa(e,t,a),{concurrency:`unbounded`});m=[];for(let[e,n]of r.entries()){let r=t[e];n instanceof na?m.push(n.module):n instanceof ra&&r!==void 0&&p.push(r)}}return{calls:u,configs:c.map(e=>e.file),legacyImports:d,unresolvedCalls:f,unresolvedImports:p}});function ca(e){return e.unresolvedCalls.length===0&&e.unresolvedImports.length===0}const la=`oxlint-custom`,ua=`import { defineConfig } from "oxlint"
97
+ import core from "${K(`./lint`)}"
98
+ import custom from "${K(`./rules`)}"
110
99
 
111
100
  export default defineConfig({
112
101
  extends: [core, custom()],
113
102
  })
114
- `,language:`ts`},title:`Custom rules in \`${r(e.dir)}\` are not loaded`});for(let e of u)for(let t of e.ruleFiles){let i=n.join(e.dir,t),a=Pr(i,yield*N(i));a.length!==0&&p.push({currentState:`\`${r(i)}\` cannot load as a rule, so the whole lint run fails with "Failed to parse oxlint configuration file":\n${a.map(e=>` - ${e}`).join(`
115
- `)}`,goal:["The file parses, uses only TypeScript that type stripping can erase (no `enum`, `namespace` with values, parameter properties, or `import x = require()`), and exports the rule as default.",`Keep the behavior of the rule.`],id:`custom-rule-cannot-load:${r(i)}`,integration:zr,notes:["A file that starts with `_` is a helper, not a rule. Rename a helper file so that it starts with `_`."],title:`Custom rule \`${r(i)}\` cannot load`})}let m=a.filter(e=>e.dir!==null&&u.some(t=>t.dir===e.dir)&&e.name!==null);for(let[e,t]of Object.entries(s.groupBy(m,e=>e.name??``))){let n=s.dedupe(t.map(e=>e.dir??``));n.length<2||p.push({currentState:`${n.length} rules folders use the plugin name \`${e}\`: ${n.map(e=>`\`${r(e)}\``).join(`, `)}. Oxlint rejects two plugins with the same name in one run.`,goal:[`Each \`custom()\` call that loads one of these folders passes a \`name\` that no other rules folder uses, such as \`custom({ name: "web" })\`. The calls are in ${s.dedupe(t.map(e=>`\`${r(e.source)}\``)).join(`, `)}.`,"Rule names in `oxlint-disable` comments and `rules` settings use the new plugin name."],id:`custom-rules-duplicate-name:${e}`,integration:zr,title:`Rules folders share the plugin name \`${e}\``})}return{applicable:!0,findings:p,packageActions:[],warnings:f}}),kind:`tooling`,name:zr});const Qr=t.fn(`checkImportsLintPreset`)(function*(e,t){let n=yield*w.Path,r=yield*P(n.join(e,`oxlint.config.ts`));return d.match(r,{onNone:()=>!1,onSome:e=>Gt(e).includes(t)})});function $r(e){let{assess:n,name:r,preset:i,version:a,...o}=e,s=Mt({isRequired:e=>Qr(e,i),name:r,purpose:`the \`adamantite/lint/${i}\` preset`,scripts:[`check`,`fix`],version:a});return{...o,...s,assess:(e,r)=>t.gen(function*(){let t=yield*s.assess(e,r);if(!t.applicable||n===void 0)return t;let i=yield*n(e,r);return{...t,findings:[...t.findings,...i.findings],warnings:[...t.warnings,...i.warnings]}}),preset:i}}const ei=[`patch`,`--oxlint`,`--typescript`],ti=t.fn(`runEffectTsgoPatch`)(function*(e,t){let n=yield*w.Path,r=yield*j,i=t.quiet?`ignore`:`inherit`,a=yield*ge.String(`PATH`).pipe(ge.withDefault(``)),o=[n.join(e,`node_modules`,`.bin`),a].filter(Boolean).join(he);yield*r.run({args:ei,command:`effect-tsgo`,cwd:e,env:{PATH:o},stderr:i,stdout:i})}),ni=`prepare`,q=`adamantite prepare`;function ri(e){return e?.includes(q)??!1}function ii(e,t){let n=e.scripts?.[ni];return ri(n)?[]:[{currentState:n===void 0?`\`package.json\` has no \`${ni}\` script, so nothing patches Oxlint for the \`effecttsgo\` rules after an install.`:`The \`${ni}\` script (\`${n}\`) does not run \`${q}\`.`,goal:[`Make the \`${ni}\` script in \`package.json\` run \`${q}\`. Put it first, then \`&&\`, then the existing commands in parentheses, such as \`${q} && (husky || true)\`. A command such as \`cd ..\` then cannot move it out of the project directory, and a fallback such as \`|| true\` cannot hide a failed patch.`,`Run \`${q}\` once, so the installed Oxlint, oxlint-tsgolint, and TypeScript binaries are patched.`],id:`missing-effect-tsgo-prepare`,integration:t,notes:["Without the patch, Oxlint stops with `Unknown plugin: 'effecttsgo'`.","Package managers run `prepare` after a bare install, such as `npm install` or `npm ci`, which restores the unpatched binaries. `adamantite init` and `adamantite update` patch after the installs that they run.","A production-only install, such as `npm ci --omit=dev`, also runs `prepare` but does not install Adamantite. Use `--ignore-scripts` for those installs."],title:`Missing adamantite prepare step`}]}const ai=t.fn(`updatePrepareScript`)(function*(e){let t=yield*R(e),n=t.scripts?.[ni]?.trim();if(ri(n))return`present`;let r=n!==void 0&&n!==``;return t.scripts={...t.scripts,[ni]:r?`${q} && (${n})`:q},yield*ct(e,t),r?`merged`:`added`}),J=`tsconfig.json`,oi=`@effect/language-service`,si={diagnostics:!1,name:oi},ci=`${JSON.stringify({compilerOptions:{plugins:[si]}},null,2)}\n`;function li(e){return qe(e)?e.find(e=>L(e)&&e.name===oi):void 0}const ui=t.fn(`assessTsconfigPlugin`)(function*(e,n){if(yield*B(e))return{findings:[],warnings:[`Skipping the root \`${J}\` check for \`${n}\`: in a monorepo, add \`${JSON.stringify(si)}\` to \`compilerOptions.plugins\` in each package's \`${J}\` or in a shared base config.`]};let r=(yield*w.Path).join(e,J),i=yield*P(r),a=i._tag===`None`?void 0:yield*I(i.value,r).pipe(t.map(e=>L(e)&&L(e.compilerOptions)?li(e.compilerOptions.plugins):void 0));return a?.diagnostics===!1?{findings:[],warnings:[]}:{findings:[{currentState:a===void 0?`\`${J}\` does not configure the \`${oi}\` plugin.`:`The \`${oi}\` plugin in \`${J}\` reports its own diagnostics, so \`tsc\` and the editor repeat every Oxlint report.`,goal:[`Add \`${JSON.stringify(si)}\` to \`compilerOptions.plugins\` in \`${J}\`, or set \`diagnostics\` to \`false\` in the existing entry. Keep every other plugin and option.`],id:`missing-effect-language-service-plugin`,integration:n,notes:["The `effecttsgo` rules read their options, such as `allowedUnstableApis`, from this entry."],reference:{content:ci,language:`json`},title:`Effect language service is not configured`}],warnings:[]}}),di=t.fn(`updateTsconfigPlugin`)(function*(e){if(yield*B(e))return`monorepo`;let t=(yield*w.Path).join(e,J),n=yield*P(t);if(n._tag===`None`)return`missing`;let r=yield*I(n.value,t);if(!L(r))return yield*new Me({path:t});let i=r.compilerOptions??{};if(!L(i))return yield*new Me({path:t});let a=i.plugins??[];if(!qe(a))return yield*new Me({path:t});let o=li(a),s=o?a.map(e=>e===o?{...o,diagnostics:!1}:e):[...a,si];return yield*F(t,it(n.value,{...r,compilerOptions:{...i,plugins:s}})),`updated`}),fi=`@effect/tsgo`;var Y=$r({assess:(e,n)=>t.gen(function*(){let t=yield*ui(e,fi);return{findings:[...ii(n,fi),...t.findings],warnings:t.warnings}}),detect:e=>Qr(e,`effect`),name:fi,patch:ti,preset:`effect`,update:e=>t.gen(function*(){return{prepare:yield*ai(e),tsconfig:yield*di(e)}}),version:`0.54.0`}),pi=$r({name:`oxlint-plugin-react-doctor`,preset:`react-doctor`,version:`0.9.18`});const mi=[$r({name:`@shadcn/lint`,preset:`shadcn`,version:`0.2.1`}),pi,Y];var hi=Mt({name:`oxlint-tsgolint`,purpose:`the managed lint scripts`,scripts:[`check`,`fix`],version:`7.0.2004`});const gi=[{path:`tsconfig.json`,type:`config`}],X=`adamantite/typescript`,_i={extends:X},vi=["Skipping `tsconfig.json` setup: a root config in a monorepo makes TypeScript treat all packages as one project.",`To use the TypeScript preset, add \`"extends": "${X}"\` to each package's \`tsconfig.json\` or to a shared base config.`];function yi(e){return x.isString(e)?e===X?e:[e,X]:s.isArray(e)?e.includes(X)?e:[...e,X]:X}var Z=M({assess:(e,n)=>t.gen(function*(){let t=ut(n);if(!t.includes(`check`)&&!t.includes(`fix`))return{applicable:!1,warnings:[]};if(yield*B(e))return{applicable:!0,findings:[],packageActions:[],warnings:vi};let r=(yield*w.Path).join(e,gi[0].path),i=yield*P(r);if(i._tag===`None`)return{applicable:!0,findings:[{currentState:"`tsconfig.json` is missing.",goal:["Create `tsconfig.json` and set `extends` to include `adamantite/typescript`."],id:`missing-tsconfig`,integration:`tsconfig`,reference:{content:`${JSON.stringify(_i,null,2)}\n`,language:`json`},title:`Missing TypeScript configuration`}],packageActions:[],warnings:[]};let a=yield*I(i.value,r);return{applicable:!0,findings:x.isObject(a)&&(a.extends===X||s.isArray(a.extends)&&a.extends.includes(X))?[]:[{currentState:"`tsconfig.json` does not extend `adamantite/typescript`.",goal:["Add `adamantite/typescript` to `extends`. Preserve every existing TypeScript option and existing base config."],id:`missing-adamantite-tsconfig-extends`,integration:`tsconfig`,reference:{content:`${JSON.stringify(_i,null,2)}\n`,language:`json`},title:`TypeScript preset is not configured`}],packageActions:[],warnings:[]}}),config:gi[0].path,create:e=>t.gen(function*(){let t=yield*w.Path;yield*Ke(t.join(e,gi[0].path),_i)}),detect:e=>t.gen(function*(){let t=yield*C.FileSystem,n=yield*w.Path;return yield*t.exists(n.join(e,gi[0].path))}),files:gi,kind:`workspace`,name:`tsconfig`,update:e=>t.gen(function*(){let t=(yield*w.Path).join(e,gi[0].path),n=yield*N(t),r=yield*I(n,t);if(!x.isObject(r))return yield*new Me({path:t});let i=yield*Je(_i,r),a=Object.fromEntries([...Object.entries(i),[`extends`,yi(`extends`in r?r.extends:void 0)]]);yield*F(t,it(n,a))})});const bi=[V,U,W,Zr,...mi,H,hi,Z,pr,K],xi=t.fn(`collectApplicableAssessments`)(function*(e,n,r){return yield*t.forEach(e,e=>e.assess(n,r).pipe(t.map(t=>t.applicable?d.some({assessment:t,name:e.name}):d.none())),{concurrency:`unbounded`}).pipe(t.map(e=>s.getSomes(e)))});function Si(e,t,n){return xi(e,t,n)}const Ci=t.fn(`assessProject`)(function*(e,t){let n=t??(yield*R(e)),r=yield*Si(bi,e,n);return{applicableIntegrations:r.map(({name:e})=>e),findings:r.flatMap(({assessment:e})=>e.findings),packageActions:r.flatMap(({assessment:e})=>e.packageActions),warnings:r.flatMap(({assessment:e})=>e.warnings)}});function wi(e,t){return e.findings.length===0?Ti(e.warnings,t):Ei(e.findings,e.warnings,t)}function Ti(e,t){return[`# Adamantite doctor warnings`,``,`This project uses Adamantite ${t} to manage linting, formatting, and type tooling.`,"`adamantite doctor` found no repair findings, but reported these warnings:",``,...e.map(e=>`- ${e}`),``].join(`
116
- `)}function Ei(e,t,n){let r=e.map((e,t)=>{let n=e.goal.map(e=>` - ${e}`).join(`
103
+ `,da=T.fn(`readRulesFolder`)(function*(e){return(yield*rt(e)).pipe(M.map(t=>({dir:e,ruleFiles:t.filter(e=>Qt(e))})))});var fa=G({assess:({customRules:e,cwd:t,workspace:n})=>T.gen(function*(){let i=yield*P.Path,a=e=>i.relative(t,e)||`.`,o=[t,...n.packageDirectories],{calls:s,legacyImports:c,unresolvedCalls:l,unresolvedImports:u}=e,d=ca(e),f=o.map(e=>i.join(e,q)),p=D.dedupe(s.map(e=>e.dir)),m=o.map(e=>i.join(e,`.adamantite/rules`)),h=yield*T.forEach(D.dedupe([...f,...m,...p]),e=>da(e),{concurrency:`unbounded`}),g=D.getSomes(h),_=g.filter(e=>e.ruleFiles.length>0),v=D.dedupeWith(s.filter(e=>e.dir!==i.join(i.dirname(e.source),`.adamantite/lint`)&&!g.some(t=>t.dir===e.dir)),(e,t)=>e.dir===t.dir),ee=_.filter(e=>d&&m.includes(e.dir)&&!p.includes(e.dir));if(d&&s.length===0&&_.length===0&&c.length===0)return{applicable:!1};let y=s.filter(e=>M.isNone(e.name)),te=[...u.map(({from:e,specifier:t})=>`Doctor cannot resolve the import of \`${t}\` in \`${a(e)}\`, so it does not check the \`custom()\` calls and rules folders behind it. For a workspace package, install the dependencies and run Doctor again.`),...l.map(e=>`Doctor cannot read the \`dir\` of a \`custom()\` call in \`${a(e)}\`, because it is not a string literal. Doctor does not check that rules folder.`),...y.map(e=>`Doctor cannot read the \`name\` of a \`custom()\` call in \`${a(e.source)}\`, because it is not a string literal. Doctor does not check that its plugin name differs from the other rules folders.`)],b=v.map(e=>({currentState:`The \`custom()\` call in \`${a(e.source)}\` loads \`${a(e.dir)}\`, but that folder does not exist, so Oxlint runs none of its rules.`,goal:[`Set \`dir\` to the folder that holds the rules, or move the rules to \`${a(e.dir)}\`. A relative \`dir\` resolves from the file that calls \`custom()\`.`,`Preserve every other setting in the Oxlint config.`],id:`custom-rules-folder-missing:${a(e.dir)}`,integration:la,title:`The rules folder \`${a(e.dir)}\` does not exist`}));if(d)for(let e of _)p.includes(e.dir)||ee.includes(e)||b.push({currentState:`No \`custom()\` call loads the rules in \`${a(e.dir)}\`, so Oxlint does not run them.`,goal:[`Load \`${a(e.dir)}\` with \`custom()\` from \`adamantite/rules\` in the Oxlint config of \`${a(i.dirname(i.dirname(e.dir)))}\`. A relative \`dir\` resolves from the file that calls \`custom()\`.`,"Give each rules folder its own plugin name with the `name` option, because Oxlint rejects two plugins with the same name in one run.",`Preserve every other setting in the Oxlint config.`],id:`custom-rules-not-loaded:${a(e.dir)}`,integration:la,reference:{content:ua,language:`ts`},title:`Custom rules in \`${a(e.dir)}\` are not loaded`});let ne=yield*T.forEach(_.flatMap(e=>e.ruleFiles.map(t=>i.join(e.dir,t))),e=>r(e).pipe(T.map(t=>({legacyImports:on(e,t),problems:_n(e,t),rulePath:e}))),{concurrency:`unbounded`}),x=D.dedupe([...c,...ne.filter(e=>e.legacyImports).map(e=>e.rulePath)]);(x.length>0||ee.length>0)&&b.push({currentState:[...x.map(e=>`\`${a(e)}\` imports the old custom-rules API.`),...ee.map(e=>`\`${a(e.dir)}\` is the previous default rules folder, and no current \`custom()\` call loads it.`)].join(`
104
+ `),goal:['Import the rules-folder preset as `import custom from "adamantite/rules"`. Replace `adamantite/lint/custom` imports and keep `custom()` in the Oxlint config extends.',"Import `definePlugin`, `defineRule`, `eslintCompatPlugin`, and the Oxlint authoring types from `adamantite/rules/plugin`. Keep `RuleTester` at `adamantite/rules/testing`.",'Move `.adamantite/rules` to `.adamantite/lint`, or keep its path with `custom({ dir: ".adamantite/rules" })` and `rule add --dir .adamantite/rules`. A relative `dir` resolves from the file that calls `custom()`.',"If you keep `.adamantite/rules` or another explicit rules folder, add its rule and optional test patterns to Knip oxlint.entry. The preset defaults cover only `.adamantite/lint`.",`Update relative imports, tsconfig include paths, and Knip oxlint.entry patterns when a folder moves. Keep explicit rules folders and their options.`,"Keep optional saved tests beside their rules as `<name>.test.ts`, and update their relative imports. For tests saved elsewhere, use `adamantite rule test --path <file>` and keep their Knip entry settings. Add a test only on request with `adamantite rule test add [name]`.",`Saved RuleTester tests use node:test. Exclude them from Vitest/Jest discovery. If TypeScript checks them, enable compilerOptions.allowImportingTsExtensions for .ts rule imports.`,"Agents verify rules with RuleTester from `adamantite/rules/testing`, using stdin or a temporary file, and remove their temporary cases and fixtures. Preserve user-owned optional tests and CI steps. `adamantite rule test` runs saved tests only when explicitly invoked.","Preserve rule behavior, plugin names, rule severity, rule options, and all other config settings. Run `adamantite check`, then run Doctor again."],id:`custom-rules-api-migration`,integration:la,reference:{content:ua,language:`ts`},title:`Custom rules need migration to the current agent workflow`});for(let{problems:e,rulePath:t}of ne)e.length!==0&&b.push({currentState:`\`${a(t)}\` cannot load as a rule, so the whole lint run fails with "Failed to parse oxlint configuration file":\n${e.map(e=>` - ${e}`).join(`
105
+ `)}`,goal:["The file parses, uses only TypeScript that type stripping can erase (no `enum`, `namespace` with values, parameter properties, or `import x = require()`), and exports the rule as default.",`Keep the behavior of the rule.`],id:`custom-rule-cannot-load:${a(t)}`,integration:la,notes:["A file that starts with `_` is a helper, not a rule. Rename a helper file so that it starts with `_`."],title:`Custom rule \`${a(t)}\` cannot load`});let re=s.flatMap(({dir:e,name:t,source:n})=>M.isSome(t)&&_.some(t=>t.dir===e)?[{dir:e,name:t.value,source:n}]:[]);for(let[e,t]of Object.entries(D.groupBy(re,e=>e.name))){let n=D.dedupe(t.map(e=>e.dir));n.length<2||b.push({currentState:`${n.length.toLocaleString(`en-US`)} rules folders use the plugin name \`${e}\`: ${n.map(e=>`\`${a(e)}\``).join(`, `)}. Oxlint rejects two plugins with the same name in one run.`,goal:[`Each \`custom()\` call that loads one of these folders passes a \`name\` that no other rules folder uses, such as \`custom({ name: "web" })\`. The calls are in ${D.dedupe(t.map(e=>`\`${a(e.source)}\``)).join(`, `)}.`,"Rule names in `oxlint-disable` comments and `rules` settings use the new plugin name."],id:`custom-rules-duplicate-name:${e}`,integration:la,title:`Rules folders share the plugin name \`${e}\``})}return{applicable:!0,findings:b,packageActions:[],warnings:te}}),kind:`tooling`,name:la});function pa(e){let{assess:t,name:n,preset:r,version:i,...a}=e,o=qt({isRequired:({lintConfig:e})=>On(e,r),name:n,purpose:`the \`adamantite/lint/${r}\` preset`,scripts:Oe(`oxlint`),version:i});return{...a,...o,assess:e=>T.gen(function*(){let n=yield*o.assess(e);if(!n.applicable||t===void 0)return n;let r=yield*t(e);return{...n,findings:[...n.findings,...r.findings],warnings:[...n.warnings,...r.warnings]}}),preset:r}}const ma={"@effect/tsgo":`0.67.3`,"@shadcn/lint":`0.2.1`,"oxlint-plugin-react-doctor":`0.9.18`},ha=be.flatMap(e=>`plugin`in e?[pa({...e.plugin,preset:e.name,version:ma[e.plugin.name]})]:[]),ga=`oxlint-tsgolint`;var _a=qt({legacyFindings:e=>e.devDependencies?.[ga]??e.dependencies?.[ga]?[{currentState:`\`package.json\` lists \`${ga}\`, which Adamantite no longer uses.`,goal:[`Remove \`${ga}\` from \`package.json\`, and install again.`],id:`legacy-${ga}`,integration:`tsrs`,notes:[`Adamantite runs the type-aware rules on tsrs, so Oxlint does not start oxlint-tsgolint.`],title:`Legacy ${ga}`}]:[],name:`tsrs`,purpose:`the type-aware rules of the managed lint scripts`,scripts:Oe(`oxlint`),version:`0.21.0-ts7.1.0-beta`});const va=[{path:`AGENTS.md`,type:`config`}];var ya=G({assess:({cwd:e,packageJson:n})=>T.gen(function*(){let r=t(n);if(r.length===0)return{applicable:!1};let i=yield*R.FileSystem,a=yield*P.Path;return{applicable:!0,findings:(yield*i.exists(a.join(e,va[0].path)))?[]:[{currentState:"The project root has no `AGENTS.md`.",goal:["Create `AGENTS.md` at the project root with the instructions that coding agents must follow in this project.","Run `adamantite doctor` again. It must not report this finding."],id:`missing-agents-md`,integration:`agents`,notes:["`AGENTS.md` is where coding agents start. It points to the other documentation of the project.",`To create the file with an Adamantite section that lists the package scripts, run \`${Ni({agents:!0,scripts:r})}\`.`],title:`Missing AGENTS.md`}],packageActions:[],warnings:[]}}),files:va,kind:`workspace`,name:`agents`});const Z=[{path:`tsconfig.json`,type:`config`}],ba=[`typescript`,`tsconfig`],Q={tsconfig:K(`./tsconfig`),typescript:K(`./typescript`)},xa=Object.values(Q);function Sa(e){let t=["Adamantite leaves the root `tsconfig.json` unchanged in a monorepo.",`Add \`"extends": "${Q[e]}"\` to each package's \`tsconfig.json\` or to a shared base config.`];return e===`typescript`&&t.push(`In a library package, extend \`${Q.tsconfig}\` instead.`),t}function Ca(e,t){let n=Q[t];if(F.isString(e))return e===n||xa.includes(e)?n:[e,n];if(D.isArray(e)){let t=e.filter(e=>e===n||!F.isString(e)||!xa.includes(e));return t.includes(n)?t:[...t,n]}return n}const wa=z.Struct({files:z.optional(z.Array(z.String))}),Ta=z.decodeUnknownOption(wa),Ea=T.fn(`readLoadsResets`)(function*(e){let t=yield*P.Path,n=yield*we(e,`typescript`);if(M.isNone(n))return M.none();let r=yield*T.option(u(n.value)),i=M.flatMapNullishOr(r,({bin:e})=>F.isObject(e)?e.tsc:void 0);if(M.isNone(i)||!F.isString(i.value))return M.none();let a=yield*(yield*E.ChildProcessSpawner).spawn(dt.make(`node`,[t.join(n.value,i.value),`--showConfig`,`--project`,e],{cwd:e,stdin:`ignore`})),[o,,s]=yield*T.all([H.mkString(H.decodeText(a.stdout)),H.runDrain(a.stderr),a.exitCode],{concurrency:`unbounded`});if(s!==0)return M.none();let c=yield*T.option(w(o,t.join(e,Z[0].path)));return M.flatMap(c,e=>M.map(Ta(e),e=>(e.files??[]).some(e=>e.endsWith(`/dist/presets/typescript/resets/index.d.ts`))))},T.scoped,T.catchTag(`PlatformError`,()=>T.succeed(M.none())));function Da(e){return F.isObject(e)?(D.isArray(e.extends)?e.extends:[e.extends]).filter(F.isString):[]}function Oa(e){return e.private!==!0&&(e.exports!==void 0||e.types!==void 0)}function ka(e){return{currentState:`\`${e}\` loads the type resets of \`${Q.typescript}\`, directly or through a base config, and its \`package.json\` is not private and declares \`exports\` or \`types\`.`,goal:[`Make \`${e}\` extend \`${Q.tsconfig}\` instead of reaching \`${Q.typescript}\`, directly or through a base config. Keep a shared base for the packages that use it, and preserve every other setting.`],id:`typescript-preset-in-library`,integration:`tsconfig`,notes:[`\`${Q.typescript}\` adds the type resets. A declaration file that the library emits can name the global \`AdamantiteTypeScript\` helper types, which projects without the resets do not have.`],title:`Type resets in a library`}}var Aa=G({assess:({cwd:e,packageJson:t,workspace:n})=>T.gen(function*(){let r=yield*P.Path,i=(yield*T.forEach([e,...n.packageDirectories],e=>T.gen(function*(){let t=yield*C(r.join(e,Z[0].path));if(M.isNone(t))return[];let n=yield*T.option(w(t.value,r.join(e,Z[0].path))),i=M.match(n,{onNone:()=>[],onSome:Da}),a=i.length!==0&&M.getOrElse(yield*Ea(e),()=>!1);return i.some(e=>xa.includes(e))||a?[{directory:e,loadsResets:a}]:[]}),{concurrency:4})).flat();return i.length===0?{applicable:!1}:{applicable:!0,findings:(yield*T.forEach(i,({directory:n,loadsResets:i})=>i?(n===e?T.succeed(t):u(n)).pipe(T.map(t=>Oa(t)?[ka(r.relative(e,r.join(n,Z[0].path)))]:[])):T.succeed([]))).flat(),packageActions:[],warnings:[]}}),config:Z[0].path,create:(e,t)=>T.gen(function*(){let n=yield*P.Path;yield*se(n.join(e,Z[0].path),{extends:Q[t]})}),detect:e=>T.gen(function*(){let t=yield*R.FileSystem,n=yield*P.Path;return yield*t.exists(n.join(e,Z[0].path))}),files:Z,kind:`workspace`,name:`tsconfig`,update:(e,t)=>T.gen(function*(){let n=(yield*P.Path).join(e,Z[0].path),i=yield*r(n),a=yield*w(i,n);if(!F.isObject(a))return yield*new Fe({path:n});let o=yield*m({fallback:{extends:Q[t]},preferred:a}),s=Object.fromEntries([...Object.entries(o),[`extends`,Ca(`extends`in a?a.extends:void 0,t)]]);yield*S(n,le(i,s))})});const ja=[tr,or,br,fa,...ha,Sr,_a,Aa,ya,Mi,Ui,$i],Ma=T.fn(`assessProject`)(function*(e){let t=yield*T.forEach(ja,t=>T.gen(function*(){let n=yield*t.assess(e);return n.applicable?[{assessment:n,name:t.name}]:[]}),{concurrency:`unbounded`}),n=D.flatten(t);return{applicableIntegrations:n.map(({name:e})=>e),findings:n.flatMap(({assessment:e})=>e.findings),packageActions:n.flatMap(({assessment:e})=>e.packageActions),warnings:n.flatMap(({assessment:e})=>e.warnings)}});function Na(e,t){return e.findings.length===0?Pa(e.warnings,t):Fa(e.findings,e.warnings,t)}function Pa(e,t){return Hr(`# Adamantite doctor warnings
106
+
107
+ Adamantite {{version}} detected no repair findings. The assessment reported these warnings:
108
+
109
+ {{warnings}}
110
+
111
+ Review the affected project state before deciding whether a warning needs a change.
112
+ Report each unresolved warning and the limit it places on verification.
113
+ If a required tool or source was unavailable, name it on the first line and state what you used instead.
114
+ The review is complete when each warning has an observed result or a stated limit.
115
+
116
+ ## Check the report
117
+
118
+ - Every warning is accounted for, including missing tools or sources.
119
+ - A successful Doctor exit is not reported as proof that all project checks pass.
120
+ `,{version:t,warnings:e.map(e=>`- ${e}`).join(`
121
+ `)})}function Fa(e,t,n){let r=e.map((e,t)=>{let n=e.goal.map(e=>` - ${e}`).join(`
117
122
  `),r=e.reference?`\n- **Reference:**\n\n\`\`\`${e.reference.language}\n${e.reference.content.trimEnd()}\n\`\`\``:``,i=e.notes&&e.notes.length>0?`\n- **Notes:**\n${e.notes.map(e=>` - ${e}`).join(`
118
- `)}`:``;return`## ${t+1}. ${e.title}\n\n- **Current state:** ${e.currentState}\n- **Goal:**\n${n}${r}${i}`}),i=t.length>0?[`## Assessment warnings`,``,`Account for these warnings while fixing the findings:`,``,...t.map(e=>`- ${e}`),``]:[];return[`# Adamantite doctor findings`,``,`This project uses Adamantite ${n} to manage linting, formatting, and type tooling.`,`\`adamantite doctor\` found ${e.length} issue(s). Fix them so that \`adamantite doctor\` exits 0.`,``,...i,r.join(`
123
+ `)}`:``;return`## ${t+1}. ${e.title}\n\n- **Current state:** ${e.currentState}\n- **Goal:**\n${n}${r}${i}`}),i=t.length>0?[`## Assessment warnings`,``,`Review these warnings before making repairs:`,``,...t.map(e=>`- ${e}`),``,``].join(`
124
+ `):``;return Hr(`# Adamantite doctor findings
125
+
126
+ Repair the findings below for the target project that uses Adamantite {{version}}.
127
+ Total findings: {{findingCount}}.
128
+
129
+ 1. If the project has \`AGENTS.md\`, read it and the instructions it names. Inspect the current files for each finding.
130
+ Continue when each finding's current state is confirmed, or rerun Doctor if the state has changed.
131
+ 2. Meet every finding's goal and preserve the settings its notes protect. Merge reference settings into the existing configuration.
132
+ For example, add a required plugin entry without replacing the project's other plugins.
133
+ Fix the cause of each finding. Do not suppress checks or add workarounds.
134
+ Continue when each goal is met or recorded as blocked with a reason. Keep unrelated project settings and code unchanged.
135
+
136
+ {{warnings}}{{findings}}
119
137
 
120
- `),``,`## Verify`,``,"Run `adamantite doctor` — through your package runner, such as `npx` or `pnpm exec`, if it is not on PATH.",`All findings above must be gone and it must exit 0.`,`Do not suppress or work around checks; fix the underlying state.`,``].join(`
121
- `)}const Di=[{command:`claude`,name:`Claude Code`,seedArguments:e=>[e]},{command:`codex`,name:`Codex`,seedArguments:e=>[e]},{command:`cursor-agent`,name:`Cursor`,seedArguments:e=>[e]},{command:`gemini`,name:`Gemini CLI`,seedArguments:e=>[`-i`,e]},{command:`grok`,name:`Grok Build`,probeArguments:[`version`],seedArguments:e=>[e]},{command:`opencode`,name:`OpenCode`,seedArguments:e=>[`--prompt`,e]}];var Oi=class extends y.TaggedError(`AgentSessionFailed`){};const ki=()=>{},Ai=t.acquireRelease(t.sync(()=>{let e=f.listeners(`SIGINT`);return f.removeAllListeners(`SIGINT`),f.on(`SIGINT`,ki),e}),e=>t.sync(()=>{f.removeAllListeners(`SIGINT`);for(let t of e)f.on(`SIGINT`,t)}));var ji=class e extends g.Service()(`CodingAgents`){static layer=l.effect(this,t.gen(function*(){let n=yield*j,r=(e,r)=>n.exitCode({args:[...e.probeArguments??[`--version`]],command:e.command,cwd:r,stderr:`ignore`,stdout:`ignore`}).pipe(t.timeout(`10 seconds`),t.isSuccess);return e.of({detectInstalled:t.fn(`CodingAgents.detectInstalled`)(e=>t.forEach(Di,t=>r(t,e),{concurrency:`unbounded`}).pipe(t.map(e=>Di.filter((t,n)=>e[n])))),runSession:t.fn(`CodingAgents.runSession`)(function*({agent:e,cwd:t,prompt:r}){yield*Ai,yield*n.exitCode({args:e.seedArguments(r),command:e.command,cwd:t,detached:!1,stderr:`inherit`,stdin:`inherit`,stdout:`inherit`})},t.scoped,t.mapError(e=>new Oi({cause:e,reason:e._tag===`CliNotFound`?`not-found`:`spawn-failed`})))})}))},Mi=class extends g.Service()(`TerminalCapabilities`){static layer=l.succeed(this)({copyToClipboard:e=>t.sync(()=>{let t=Buffer.from(e).toString(`base64`);f.stdout.write(`\u001B]52;c;${t}\u0007`)}),isInteractive:t.sync(()=>f.stdin.isTTY&&f.stdout.isTTY)})},Q=class extends g.Service()(`Prompter`){static layerWithSpinner(e){return l.succeed(this)({cancel:e=>t.sync(()=>{O.cancel(e)}),confirm:e=>t.promise(()=>O.confirm(e)).pipe(t.filterOrFail(e=>!O.isCancel(e),()=>new Le({}))),intro:e=>t.sync(()=>{O.intro(e)}),log:{error:e=>t.sync(()=>{O.log.error(e)}),info:e=>t.sync(()=>{O.log.info(e)}),success:e=>t.sync(()=>{O.log.success(e)}),warning:e=>t.sync(()=>{O.log.warning(e)})},message:e=>t.sync(()=>{O.log.message(e,{spacing:0,withGuide:!1})}),multiselect:e=>t.promise(()=>O.multiselect(e)).pipe(t.filterOrFail(e=>!O.isCancel(e),()=>new Le({}))),note:(e,n)=>t.sync(()=>{O.note(e,n)}),outro:e=>t.sync(()=>{O.outro(e)}),select:e=>t.promise(()=>O.select(e)).pipe(t.filterOrFail(e=>!O.isCancel(e),()=>new Le({}))),withSpinner:(r,i)=>t.acquireUseRelease(t.sync(()=>{let t=e();return t.start(i.start),t}),e=>r({message:n=>t.sync(()=>{e.message(n)})}),(e,r)=>t.sync(()=>{e.stop(n.match(r,{onFailure:()=>i.failure,onSuccess:e=>x.isFunction(i.success)?i.success(e):i.success}))}))})}static layer=this.layerWithSpinner(O.spinner)};function Ni(e){let t=[`Current state\n${e.currentState}`,`Goal\n${e.goal.map(e=>`• ${e}`).join(`
138
+ ## Verify
139
+
140
+ 1. Run the project's installed \`adamantite doctor\` from the project root through its package runner, such as \`npx\` or \`pnpm exec\`.
141
+ Reread and resolve new findings until Doctor exits with code 0 and reports no findings.
142
+ If a remaining goal is blocked, record the reason and stop the repair loop. Do not claim that the repair is complete.
143
+ Record assessment warnings separately. Warnings alone can exit with code 0.
144
+ 2. Run the project checks affected by the repairs and read their output.
145
+ Continue when those checks pass, or record each failed or unavailable check without claiming a verified repair.
146
+ 3. Report the repaired findings, changed files, commands, results, and any blocked goals or warnings.
147
+ If a required tool or source was unavailable, name it on the first line and state what you used instead.
148
+ The report is complete when every finding has a verified result or an explicit blocker.
149
+
150
+ ## Check the repair
151
+
152
+ - Every finding's goal is met or has a reported blocker.
153
+ - Reference settings were merged, and unrelated project settings remain intact.
154
+ - Doctor reports no findings, or the report names every remaining finding.
155
+ - The report separates findings, warnings, and checks that could not be verified.
156
+ `,{findingCount:e.length.toLocaleString(`en-US`),findings:r.join(`
157
+
158
+ `),version:n,warnings:i})}const Ia=T.fn(`readProject`)(function*(e){let t=yield*P.Path,[n,r,i]=yield*T.all([u(e),re(e),C(t.join(e,`oxlint.config.ts`))],{concurrency:`unbounded`});return{customRules:yield*sa([e,...r.packageDirectories]),cwd:e,lintConfig:i,packageJson:n,workspace:r}});var La=class extends N.Service()(`TerminalCapabilities`){static layer=k.succeed(this)({copyToClipboard:e=>T.sync(()=>{let t=Buffer.from(e).toString(`base64`);A.stdout.write(`\u001B]52;c;${t}\u0007`)}),isInteractive:T.sync(()=>A.stdin.isTTY&&A.stdout.isTTY)})},$=class extends N.Service()(`Prompter`){static layerWithSpinner(e){return k.succeed(this)({cancel:e=>T.sync(()=>{U.cancel(e)}),confirm:e=>T.promise(()=>U.confirm(e)).pipe(T.filterOrFail(e=>!U.isCancel(e),()=>new et({}))),intro:e=>T.sync(()=>{U.intro(e)}),log:{error:e=>T.sync(()=>{U.log.error(e)}),info:e=>T.sync(()=>{U.log.info(e)}),success:e=>T.sync(()=>{U.log.success(e)}),warning:e=>T.sync(()=>{U.log.warning(e)})},message:e=>T.sync(()=>{U.log.message(e,{spacing:0,withGuide:!1})}),multiselect:e=>T.promise(()=>U.multiselect(e)).pipe(T.filterOrFail(e=>!U.isCancel(e),()=>new et({}))),note:(e,t)=>T.sync(()=>{U.note(e,t)}),outro:e=>T.sync(()=>{U.outro(e)}),select:e=>T.promise(()=>U.select(e)).pipe(T.filterOrFail(e=>!U.isCancel(e),()=>new et({}))),withSpinner:(t,n)=>T.acquireUseRelease(T.sync(()=>{let t=e();return t.start(n.start),t}),e=>t({message:t=>T.sync(()=>{e.message(t)})}),(e,t)=>T.sync(()=>{at.match(t,{onFailure:t=>{Et.hasInterruptsOnly(t)?e.cancel(n.failure):e.error(n.failure)},onSuccess:t=>{e.stop(F.isFunction(n.success)?n.success(t):n.success)}})}))})}static layer=this.layerWithSpinner(U.spinner)};function Ra(e){let t=[`Current state\n${e.currentState}`,`Goal\n${e.goal.map(e=>`• ${e}`).join(`
122
159
  `)}`];return e.reference&&t.push(`Reference\n${e.reference.content.trimEnd()}`),e.notes&&e.notes.length>0&&t.push(`Notes\n${e.notes.map(e=>`• ${e}`).join(`
123
160
  `)}`),t.join(`
124
161
 
125
- `)}const Pi=t.fn(`printFindings`)(function*(e){let t=yield*Q;for(let[n,r]of e.entries())yield*t.note(Ni(r),`${n+1}. ${r.title}`)}),Fi=`0.45.0`;var Ii=c.make(`doctor`).pipe(c.withDescription(`Assess Adamantite-managed integrations in the current project`),c.withHandler(()=>t.gen(function*(){let e=f.cwd(),n=yield*ji,i=yield*Q,a=yield*Mi,o=yield*a.isInteractive;o&&(yield*i.intro(`💠 adamantite doctor`));let s=t.gen(function*(){return yield*i.outro(`⚠️ Doctor found issues.`),yield*new Se({command:`doctor`,exitCode:r.ExitCode(1)})}),c=yield*R(e);if(!c.devDependencies?.adamantite&&!c.dependencies?.adamantite){let e="`adamantite` is not installed in this project. Install it before running `adamantite doctor`.";return o?(yield*i.log.warning(e),yield*i.outro(`⚠️ Doctor found issues.`)):yield*i.message(e),yield*new Se({command:`doctor`,exitCode:r.ExitCode(1)})}let l=yield*Ci(e);if(o)for(let e of l.warnings)yield*i.log.warning(e);if(l.applicableIntegrations.length===0){o&&(yield*i.log.success(`No applicable integrations found.`),yield*i.outro(`✅ Doctor completed successfully!`));return}if(l.findings.length===0){o?(yield*i.log.success(`No issues found.`),yield*i.outro(`✅ Doctor completed successfully!`)):l.warnings.length>0&&(yield*i.message(wi(l,Fi)));return}if(!o)return yield*i.message(wi(l,Fi)),yield*new Se({command:`doctor`,exitCode:r.ExitCode(1)});let u=e=>t.gen(function*(){(yield*i.confirm({initialValue:!0,message:`Copy the Markdown prompt for a coding agent?`}))&&(yield*i.message(e),yield*a.copyToClipboard(e),yield*i.log.success(`The Markdown prompt was printed and sent to the terminal clipboard.`))});yield*Pi(l.findings);let d=yield*i.withSpinner(()=>n.detectInstalled(e),{start:`Checking for installed coding agents...`,success:e=>e.length===0?`No supported coding agent CLI was found on PATH.`:`Found ${e.map(e=>e.name).join(`, `)}.`});d.length===0&&(yield*i.log.info(`Doctor can hand findings off when one of these CLIs is installed: ${Di.map(e=>`\`${e.command}\``).join(`, `)}.`));let p=wi(l,Fi),m=yield*i.select({message:`How do you want to resolve these findings?`,options:[...d.map(e=>({label:`Hand off to ${e.name}`,value:e})),{label:`Copy the Markdown prompt for a coding agent`,value:`copy`},{label:`Do nothing`,value:`done`}]});if(m===`done`)return yield*s;if(m===`copy`)return yield*i.message(p),yield*a.copyToClipboard(p),yield*i.log.success(`The Markdown prompt was printed and sent to the terminal clipboard.`),yield*s;let h=m;if(yield*i.log.info(`Handing the terminal to ${h.name}. Exit the agent to return to Doctor.`),!(yield*n.runSession({agent:h,cwd:e,prompt:p}).pipe(t.as(!0),t.catchTag(`AgentSessionFailed`,e=>i.log.error(e.reason===`not-found`?`\`${h.command}\` was not found on PATH. Install ${h.name} or copy the prompt instead.`:`Failed to start ${h.name}: ${e.cause.message}`).pipe(t.as(!1))))))return yield*u(p),yield*s;let g=yield*Ci(e);if(g.findings.length===0)yield*i.log.success(`All findings were resolved by ${h.name}.`),yield*i.outro(`✅ Doctor completed successfully!`);else return yield*i.log.warning(`${g.findings.length} of ${l.findings.length} findings remain after the ${h.name} session.`),yield*Pi(g.findings),yield*u(wi(g,Fi)),yield*s}).pipe(t.catchTag(`OperationCancelled`,()=>t.gen(function*(){return yield*(yield*Q).cancel(`Doctor was cancelled. The findings remain.`),yield*new Se({command:`doctor`,exitCode:r.ExitCode(1)})})))));const Li=T.File(`files`,{mustExist:!0}).pipe(T.withDescription(`Specific files to fix (optional)`),T.variadic()),Ri=u.Boolean(`suggested`).pipe(u.withDefault(!1),u.withDescription(`Apply suggested fixes`)),zi=u.Boolean(`dangerous`).pipe(u.withDefault(!1),u.withDescription(`Apply dangerous fixes`)),Bi=u.Boolean(`all`).pipe(u.withDefault(!1),u.withDescription(`Apply all fixes, including suggested and dangerous fixes`)),Vi=u.Literals(`only`,[`format`,`lint`]).pipe(u.optional,u.withDescription("Run one stage: `format` (oxfmt) or `lint` (oxlint). Arguments after `--` go to that stage"));var Hi=c.make(`fix`,{all:Bi,dangerous:zi,files:Li,only:Vi,suggested:Ri}).pipe(c.withDescription(`Fix lint and formatting issues in code`),c.withHandler(({all:e,dangerous:n,files:r,only:i,suggested:a})=>t.gen(function*(){let t=yield*Ue,o=yield*j,c=d.getOrUndefined(i);if(c===`format`&&(e||n||a))return yield*new Pe({reason:"`--suggested`, `--dangerous`, and `--all` apply to the lint stage. Remove them or `--only format`."});let l=s.dedupe(r),u=c??`lint`,f=[{args:s.dedupe([`--fix`,...a||e?[`--fix-suggestions`]:[],...n||e?[`--fix-dangerously`]:[],...l]),command:W.name,name:`lint`,title:`🔧 Fixing lint issues`},{args:[`--write`,...l],command:U.name,name:`format`,title:`✨ Formatting`}];yield*o.runAll(f.filter(e=>c===void 0||e.name===c).map(e=>({args:[...e.args,...e.name===u?t:[]],command:e.command,title:e.title})))})));const Ui=' .o8 . o8o . \n "888 .o8 `"\' .o8 \n .oooo. .oooo888 .oooo. ooo. .oo. .oo. .oooo. ooo. .oo. .o888oo oooo .o888oo .ooooo. \n`P )88b d88\' `888 `P )88b `888P"Y88bP"Y88b `P )88b `888P"Y88b 888 `888 888 d88\' `88b \n .oP"888 888 888 .oP"888 888 888 888 .oP"888 888 888 888 888 888 888ooo888 \nd8( 888 888 888 d8( 888 888 888 888 d8( 888 888 888 888 . 888 888 . 888 .o \n`Y888""8o `Y8bod88P" `Y888""8o o888o o888o o888o `Y888""8o o888o o888o "888" o888o "888" `Y8bod8P\' \n \n \n ',Wi=t.gen(function*(){let e=yield*(yield*_e.Terminal).columns,t=Ui.split(`
126
- `).reduce((e,t)=>Math.max(e,t.trim().length),0);!e||e<t||(yield*h.info(Ui))}),Gi=[`check`,`fix`,`analyze`],Ki=[`vscode`,`zed`],qi=t.fn(`validateInitOptions`)(function*(e,t){let n={agents:e.agents,editors:s.dedupe(e.editors),githubActions:e.githubActions,installExtensions:e.installExtensions,overwriteScripts:e.overwriteScripts,presets:s.dedupe(e.presets),scripts:s.dedupe(e.scripts),typescript:e.typescript};if(n.scripts.length===0)return yield*new A({reason:"Select at least one script with `--script <name>`."});let r=n.scripts.includes(`check`)||n.scripts.includes(`fix`);return n.presets.length>0&&!r?yield*new A({reason:"`--preset` requires the `check` or `fix` script."}):n.presets.includes(`react-doctor`)&&!n.presets.includes(`react`)?yield*new A({reason:"`--preset react-doctor` requires `--preset react`."}):n.typescript&&!r?yield*new A({reason:"`--typescript` requires the `check` or `fix` script."}):n.installExtensions&&n.editors.length===0?yield*new A({reason:"`--install-extensions` requires at least one `--editor`."}):n.githubActions&&!zn(n.scripts)?yield*new A({reason:"`--github-actions` requires a CI-compatible script."}):n.githubActions&&t.nonInteractive&&!lt(t.packageManager)?yield*new A({reason:`\`--github-actions\` does not support the detected package manager \`${t.packageManager}\`. Use bun, deno, npm, pnpm, or yarn.`}):n}),Ji=u.Boolean(`non-interactive`).pipe(u.withDefault(!1),u.withDescription(`Configure without prompts; requires at least one --script`)),Yi=u.Literals(`script`,Gi).pipe(u.atMost(Gi.length),u.withDescription(`Package script to configure; repeatable and required in non-interactive mode`)),Xi=u.Literals(`preset`,Rt).pipe(u.atMost(Rt.length),u.withDescription(`Oxlint preset to configure; repeatable and requires --script check or fix`)),Zi=u.Literals(`editor`,Ki).pipe(u.atMost(Ki.length),u.withDescription(`Editor to configure; may be specified multiple times`)),Qi=u.Boolean(`typescript`).pipe(u.withDefault(!1),u.withDescription(`Configure the TypeScript preset; requires --script check or fix`)),$i=u.Boolean(`install-extensions`).pipe(u.withDefault(!1),u.withDescription(`Install recommended extensions; requires at least one --editor`)),ea=u.Boolean(`github-actions`).pipe(u.withDefault(!1),u.withDescription(`Configure CI; requires a compatible script and bun, deno, npm, pnpm, or yarn`)),ta={agents:u.Boolean(`agents`).pipe(u.withDefault(!1),u.withDescription(`Add Adamantite guidance to AGENTS.md`)),editors:Zi,githubActions:ea,installExtensions:$i,nonInteractive:Ji,overwriteScripts:u.Boolean(`overwrite-scripts`).pipe(u.withDefault(!1),u.withDescription(`Replace existing package scripts that conflict with Adamantite's managed commands`)),presets:Xi,scripts:Yi,typescript:Qi},na=e=>`\`${e.script}\` is currently \`${e.command}\`; Adamantite would replace it with \`${z[e.script]}\`.`,ra=t.fn(`collectInteractiveInitOptions`)(function*(e,t){let n=yield*Q,r=yield*n.multiselect({message:"Which scripts do you want to add to your `package.json`?",options:[{hint:`recommended`,label:`check - check formatting, lint issues, and type errors`,value:`check`},{hint:`recommended`,label:`fix - apply safe lint fixes and format code`,value:`fix`},{label:t?`analyze - check monorepo consistency using Sherif and find unused dependencies, exports, and files using knip`:`analyze - find unused dependencies, exports, and files using knip`,value:`analyze`}]}),i=dt(yield*R(e),r),a=!1;if(i.length>0){for(let e of i)yield*n.log.warning(na(e));a=yield*n.confirm({initialValue:!1,message:i.length===1?`Overwrite this existing script with Adamantite's command?`:`Overwrite these existing scripts with Adamantite's commands?`})}let o=r.includes(`check`)||r.includes(`fix`),s=[];o&&(s=yield*n.multiselect({message:`Which presets do you want to install? (core is always included)`,options:[{hint:`React correctness, JSX accessibility, and render performance rules`,label:`react`,value:`react`},{hint:`Strict React feature code: no state, effect, or memoization hooks outside hook modules`,label:`react-strict`,value:`react-strict`},{hint:`React state and effect misuse, such as effects used as event handlers and fetches in effects; requires react`,label:`react-doctor`,value:`react-doctor`},{hint:`TanStack Query: queries defined once with queryOptions() so route loaders can preload them, no query data copied into state`,label:`tanstack`,value:`tanstack`},{hint:`Next.js pitfalls around scripts, fonts, images, and document/head usage`,label:`next.js`,value:`nextjs`},{hint:`Vue 3 correctness rules and deprecated API detection`,label:`vue`,value:`vue`},{hint:`Effect misuse, such as effects that never run and unhandled errors; installs @effect/tsgo and patches Oxlint and TypeScript`,label:`effect`,value:`effect`},{hint:`Jest test hygiene: focused/disabled tests, matcher and snapshot discipline`,label:`jest`,value:`jest`},{hint:`Vitest test hygiene: focused/disabled tests, matcher and snapshot discipline`,label:`vitest`,value:`vitest`},{hint:`Node.js callback and CommonJS pitfalls`,label:`node`,value:`node`},{hint:`Framework-neutral strictness: no deep or wide destructuring, no type assertions outside tests`,label:`strict`,value:`strict`},{hint:`Rejects low-signal escape hatches: unjustified assertions, unknown leaks, module mocks`,label:`antislop`,value:`antislop`},{hint:`Tailwind v4 design system: no restyled components, raw colors, arbitrary values, or unknown classes`,label:`shadcn`,value:`shadcn`}],required:!1}),s.includes(`react-doctor`)&&!s.includes(`react`)&&(s=[`react`,...s],yield*n.log.info("Added the `react` preset, which `react-doctor` requires.")));let c=o?yield*n.confirm({initialValue:!0,message:t?"Adamantite provides a TypeScript preset to enforce strict type-safety. In a monorepo, each package's `tsconfig.json` must extend it. Would you like instructions on how to set it up?":`Adamantite provides a TypeScript preset to enforce strict type-safety. Would you like to use it?`}):!1,l=yield*n.multiselect({message:`Which editors do you want to configure? (optional)`,options:[{label:`VSCode / Cursor / Windsurf`,value:`vscode`},{label:`Zed`,value:`zed`}],required:!1}),u=l.length>0?yield*n.confirm({initialValue:!0,message:`Do you want to install the recommended editor extensions?`}):!1,d=zn(r)?yield*n.confirm({message:`Do you want to add a GitHub Actions workflow to run checks in CI?`}):!1;return{agents:yield*n.confirm({initialValue:!0,message:`Add Adamantite guidance to AGENTS.md so coding agents know how to run project checks?`}),editors:l,githubActions:d,installExtensions:u,overwriteScripts:a,presets:s,scripts:r,typescript:c}}),ia=[{path:`.vscode/settings.json`,type:`config`}],aa={"[css]":{"editor.defaultFormatter":`oxc.oxc-vscode`},"[graphql]":{"editor.defaultFormatter":`oxc.oxc-vscode`},"[javascript]":{"editor.defaultFormatter":`oxc.oxc-vscode`},"[javascriptreact]":{"editor.defaultFormatter":`oxc.oxc-vscode`},"[json]":{"editor.defaultFormatter":`oxc.oxc-vscode`},"[jsonc]":{"editor.defaultFormatter":`oxc.oxc-vscode`},"[typescript]":{"editor.defaultFormatter":`oxc.oxc-vscode`},"[typescriptreact]":{"editor.defaultFormatter":`oxc.oxc-vscode`},"editor.codeActionsOnSave":{"source.fixAll.oxc":`explicit`},"editor.defaultFormatter":`oxc.oxc-vscode`,"editor.formatOnPaste":!0,"editor.formatOnSave":!0,"oxc.typeAware":!0};var $=M({config:ia[0].path,create:e=>t.gen(function*(){let t=yield*w.Path,n=t.join(e,ia[0].path);yield*We(t.dirname(n)),yield*Ke(n,aa)}),detect:e=>t.gen(function*(){let t=yield*C.FileSystem,n=yield*w.Path;return yield*t.exists(n.join(e,ia[0].path))}),extension:(e=[])=>t.gen(function*(){let n=[];(e.includes(`check`)||e.includes(`fix`))&&n.push(`oxc.oxc-vscode`),e.includes(`analyze`)&&n.push(`webpro.vscode-knip`);for(let e of n)yield*(yield*j).run({args:[`--install-extension`,e],command:`code`}).pipe(t.mapError(t=>t._tag===`CliNotFound`&&t.command===`code`?new ze({cause:t}):new Ee({cause:t._tag===`CommandFailed`?t.exitCode:t,extension:e})))}),files:ia,kind:`editor`,name:`vscode`,update:e=>t.gen(function*(){let t=(yield*w.Path).join(e,ia[0].path),n=yield*N(t),r=yield*I(n,t);if(!x.isObject(r))return yield*new Me({path:t});let i=yield*Je(aa,r);yield*F(t,it(n,i))})});const oa=`<!-- ADAMANTITE:START -->`,sa=`<!-- ADAMANTITE:END -->`;function ca(e,t,n){let r=me(e,t),i=z[t];switch(t){case`analyze`:return`- Run \`${r}\` after changing dependencies, imports, or exports.${n?` It also checks monorepo package consistency.`:``} Direct command: \`${i}\`.`;case`check`:return`- Run \`${r}\` to catch formatting, lint, and type issues. Direct command: \`${i}\`.`;case`fix`:return`- Run \`${r}\` to apply safe lint fixes and format code. Direct command: \`${i}\`.`}}function la({isMonorepo:e,packageManager:t,scripts:n}){let r=[`check`,`fix`,`analyze`].filter(e=>n.includes(e)).map(n=>ca(t,n,e)),i=[`## Adamantite`,``,`This project uses Adamantite for its managed formatting, linting, type checking, and dependency-analysis setup.`,``,...r.length>0?[`- Prefer the package scripts Adamantite added for this workspace.`,...r]:[],...n.includes(`check`)||n.includes(`fix`)?["- Write project-specific lint rules in `.adamantite/rules/`, one rule for each file. Run `adamantite rule add <name>` to start a rule with its authoring guidance."]:[],"- Run `adamantite doctor` and follow its findings to repair managed setup."].join(`
127
- `);return[oa,``,i,``,sa,``].join(`
128
- `)}const ua=(e,n)=>t.gen(function*(){let t=(yield*w.Path).join(e,`AGENTS.md`),r=b(yield*P(t),d.getOrElse(()=>``)),i=b(r,S.indexOf(oa)),a=b(r,S.indexOf(sa)),o=b(d.all({end:a,start:i}),d.filter(({end:e,start:t})=>t<e)),s=la(n);if(d.isSome(o)){let{end:e,start:n}=o.value,i=e+23,a=`${r.slice(0,n)}${s.trimEnd()}${r.slice(i)}`;return yield*F(t,a.endsWith(`
129
- `)?a:`${a}\n`),`updated`}if(d.isSome(i)||d.isSome(a))return`malformed`;let c=r.length===0||r.endsWith(`
162
+ `)}const za=T.fn(`printFindings`)(function*(e){let t=yield*$;for(let[n,r]of e.entries())yield*t.note(Ra(r),`${n+1}. ${r.title}`)}),Ba=[{command:`claude`,name:`Claude Code`,seedArguments:e=>[e],skillsFolder:`.claude/skills`},{command:`codex`,name:`Codex`,seedArguments:e=>[e],skillsFolder:`.agents/skills`},{command:`cursor-agent`,name:`Cursor`,seedArguments:e=>[e],skillsFolder:`.agents/skills`},{command:`gemini`,name:`Gemini CLI`,seedArguments:e=>[`-i`,e],skillsFolder:`.agents/skills`},{command:`grok`,name:`Grok Build`,probeArguments:[`version`],seedArguments:e=>[e],skillsFolder:`.grok/skills`},{command:`opencode`,name:`OpenCode`,seedArguments:e=>[`--prompt`,e],skillsFolder:`.agents/skills`}];var Va=class extends I.TaggedError(`HandoffFailed`){};const Ha=()=>{},Ua=T.acquireRelease(T.sync(()=>{let e=A.listeners(`SIGINT`);return A.removeAllListeners(`SIGINT`),A.on(`SIGINT`,Ha),e}),e=>T.sync(()=>{A.removeAllListeners(`SIGINT`);for(let t of e)A.on(`SIGINT`,t)}));var Wa=class e extends N.Service()(`CodingAgents`){static layer=k.effect(this,T.gen(function*(){let t=yield*Pt,n=(e,n)=>t.exitCode({args:[...e.probeArguments??[`--version`]],command:e.command,cwd:n,stderr:`ignore`,stdout:`ignore`}).pipe(T.timeout(`10 seconds`),T.isSuccess);return e.of({detectInstalled:T.fn(`CodingAgents.detectInstalled`)(e=>T.filter(Ba,t=>n(t,e),{concurrency:`unbounded`})),handoff:T.fn(`CodingAgents.handoff`)(function*({agent:e,cwd:n,prompt:r}){yield*Ua,yield*t.exitCode({args:e.seedArguments(r),command:e.command,cwd:n,stderr:`inherit`,stdin:`inherit`,stdout:`inherit`})},T.scoped,T.mapError(e=>new Va({cause:e,reason:F.isTagged(e,`CliNotFound`)?`not-found`:`spawn-failed`})))})}))},Ga=class extends I.TaggedClass(`Copied`){},Ka=class extends I.TaggedClass(`Declined`){},qa=class extends I.TaggedClass(`Ended`){},Ja=class extends I.TaggedClass(`Failed`){};const Ya=T.fn(`copyPrompt`)(function*(e){let t=yield*$,n=yield*La;yield*t.message(e),yield*n.copyToClipboard(e),yield*t.log.success(`The agent prompt is printed above and sent to the terminal clipboard.`)}),Xa=T.fn(`offerPromptCopy`)(function*(e){(yield*(yield*$).confirm({initialValue:!0,message:`Copy the agent prompt?`}))&&(yield*Ya(e))}),Za=T.fn(`chooseResolution`)(function*(e){let t=yield*Wa,n=yield*$,r=yield*n.withSpinner(()=>t.detectInstalled(e.cwd),{failure:`Could not check for installed coding agents.`,start:`Checking for installed coding agents...`,success:e=>e.length===0?`No supported coding agent was found on PATH.`:`Found ${e.map(e=>e.name).join(`, `)}.`});r.length===0&&(yield*n.log.info(`${e.command} can hand ${e.subject} off when one of these CLIs is installed: ${Ba.map(e=>`\`${e.command}\``).join(`, `)}.`));let i=yield*n.select({message:e.message,options:[...r.map(e=>({label:`Hand off to ${e.name}`,value:e})),{label:`Copy the agent prompt`,value:`copy`},{label:`Finish without an agent`,value:`done`}]});if(i===`done`)return new Ka;if(i===`copy`)return yield*Ya(e.prompt),new Ga;let a=i;return yield*n.log.info(`Handing the terminal to ${a.name}. Exit the agent to return to ${e.command}.`),(yield*t.handoff({agent:a,cwd:e.cwd,prompt:e.prompt}).pipe(T.as(!0),T.catchTag(`HandoffFailed`,e=>n.log.error(e.reason===`not-found`?`\`${a.command}\` was not found on PATH. Install ${a.name} or copy the prompt instead.`:`Failed to start ${a.name}: ${e.cause.message}`).pipe(T.as(!1)))))?new qa({agent:a}):(yield*Xa(e.prompt),new Ja({agent:a}))}),Qa=`0.47.0`,$a="`adamantite` is not installed in this project. Install it before running `adamantite doctor`.",{$match:eo,Converged:to,NeedsRepair:no,NotInstalled:ro,Unmanaged:io}=I.taggedEnum();function ao(e){return e.applicableIntegrations.length===0?io():e.findings.length===0?to({assessment:e}):no({assessment:e})}function oo(){return new Le({command:`doctor`,exitCode:E.ExitCode(1)})}var so=O.make(`doctor`).pipe(O.withDescription(`Check Adamantite setup and report what needs repair`),O.withHandler(()=>T.gen(function*(){let e=A.cwd(),t=yield*$,n=yield*(yield*La).isInteractive;n&&(yield*t.intro(`💠 adamantite doctor`));let r=T.gen(function*(){return yield*t.outro(`⚠️ Doctor found issues.`),yield*oo()}),i=e=>T.gen(function*(){yield*t.log.success(e),yield*t.outro(`✅ Doctor finished.`)}),a=e=>T.forEach(e.warnings,e=>t.log.warning(e),{discard:!0}),o=T.fn(`resolveFindings`)(function*(n){yield*a(n),yield*za(n.findings);let o=yield*Za({command:`Doctor`,cwd:e,message:`How do you want to resolve these findings?`,prompt:Na(n,Qa),subject:`findings`});if(!(o instanceof qa))return yield*r;let{agent:s}=o,c=yield*Ma(yield*Ia(e));return c.findings.length===0?yield*i(`All findings were resolved by ${s.name}.`):(yield*t.log.warning(`Doctor still reports ${c.findings.length.toLocaleString(`en-US`)} unresolved ${c.findings.length===1?`finding`:`findings`} after the ${s.name} session.`),yield*za(c.findings),yield*Xa(Na(c,Qa)),yield*r)}),s=eo({Converged:({assessment:e})=>a(e).pipe(T.andThen(i(`No setup repairs needed.`))),NeedsRepair:({assessment:e})=>o(e),NotInstalled:()=>t.log.warning($a).pipe(T.andThen(r)),Unmanaged:()=>i("No Adamantite-managed setup found. Run `adamantite init` to configure the project.")}),c=eo({Converged:({assessment:e})=>e.warnings.length>0?t.message(Na(e,Qa)):T.void,NeedsRepair:({assessment:e})=>t.message(Na(e,Qa)).pipe(T.andThen(oo())),NotInstalled:()=>t.message($a).pipe(T.andThen(oo())),Unmanaged:()=>T.void}),l=yield*u(e),d=l.devDependencies?.adamantite||l.dependencies?.adamantite?ao(yield*Ma(yield*Ia(e))):ro();yield*n?s(d):c(d)}).pipe(T.catchTag(`OperationCancelled`,()=>T.gen(function*(){return yield*(yield*$).cancel(`Doctor was cancelled. The findings remain.`),yield*oo()})))));const co=V.File(`files`,{mustExist:!0}).pipe(V.withDescription(`Files to fix. Omit to fix the project`),V.variadic()),lo=j.Boolean(`suggested`).pipe(j.withDefault(!1),j.withDescription(`Apply Oxlint's suggested fixes`)),uo=j.Boolean(`dangerous`).pipe(j.withDefault(!1),j.withDescription(`Apply Oxlint's dangerous fixes`)),fo=j.Boolean(`all`).pipe(j.withDefault(!1),j.withDescription(`Apply all Oxlint fixes, including suggested and dangerous fixes`)),po=j.Literals(`only`,[`format`,`lint`]).pipe(j.optional,j.withDescription(`Run only format (Oxfmt) or lint (Oxlint). Pass tool arguments after --`));function mo(e){return e.all||e.suggested&&e.dangerous?`all`:e.suggested?`suggested`:e.dangerous?`dangerous`:`safe`}var ho=O.make(`fix`,{all:fo,dangerous:uo,files:co,only:po,suggested:lo}).pipe(O.withDescription(`Apply lint fixes and format code`),O.withHandler(({all:e,dangerous:t,files:n,only:r,suggested:i})=>T.gen(function*(){yield*wr({cwd:A.cwd(),files:n,forwardedArguments:yield*At,level:mo({all:e,dangerous:t,suggested:i}),only:M.getOrUndefined(r)})})));const go=/\.(?:md|mdx|mdc)$/u,_o=/^ {0,3}((`|~)\2{2,})[^\n]*\n[\s\S]*?(?:^ {0,3}\1\2*[\t ]*$|(?![\s\S]))/gmu,vo=/`([^`\n]+)`/gu,yo=/\]\(\s*<?([^\s)>]+)>?(?:\s[^)]*)?\)/gu,bo=/^ {0,3}\[[^\]]+\]:\s*<?([^\s>]+)>?/gmu,xo=/^[a-z][\d+.a-z-]*:/iu;function So(e){let[t=``]=e.split(/[#?]/u);try{return decodeURI(t)}catch{return t}}function Co(e,t){return[...e.matchAll(t)].map(e=>e[1]??``)}const wo=T.fn(`readAgentReach`)(function*(e,t,n){let r=yield*R.FileSystem,i=yield*P.Path,a=new Set(t),o=new Map(yield*T.forEach(t,t=>f(i.join(e,t)).pipe(T.map(e=>[t,M.getOrElse(e,()=>``).replaceAll(_o,``)])),{concurrency:`unbounded`})),s=e=>{let n=e.flatMap(e=>{let t=W.normalize(e);return t!==`.`&&!t.startsWith(`..`)?[t]:[]}),r=n.find(e=>a.has(e));if(r!==void 0)return[r];let i=n.find(e=>t.some(t=>W.dirname(t)===e));return i===void 0?[]:t.filter(e=>W.dirname(e)===i)},c=e=>{let t=(o.get(e)??``).replaceAll(vo,``);return[...Co(t,yo),...Co(t,bo)].flatMap(t=>{if(xo.test(t)||t.startsWith(`#`))return[];let n=So(t);return n.length===0?[]:[W.normalize(n.startsWith(`/`)?n.slice(1):W.join(W.dirname(e),n))]})},l=e=>[...c(e).flatMap(e=>s([e])),...Co(o.get(e)??``,vo).flatMap(t=>s([W.join(W.dirname(e),t),t]))],u=new Set(n),d=[...n];for(let e=d.shift();e!==void 0;e=d.shift())for(let t of l(e))u.has(t)||(u.add(t),d.push(t));let p=t.flatMap(e=>c(e).filter(e=>go.test(e)&&!a.has(e)).map(t=>({file:e,target:t})));return{brokenLinks:yield*T.filter(p,t=>r.exists(i.join(e,t.target)).pipe(T.map(e=>!e),T.orElseSucceed(()=>!0)),{concurrency:`unbounded`}),unreached:t.filter(e=>!u.has(e))}}),To=/^\{/mu,Eo=z.String.pipe(z.decodeTo(z.String,gt.transform({decode:e=>e.replaceAll(`\\`,`/`),encode:e=>e}))),Do=z.Struct({diagnostics:z.Array(z.Struct({code:z.optional(z.String),filename:Eo,labels:z.Array(z.Struct({span:z.Struct({column:z.Int,line:z.Int})})),message:z.String})),number_of_files:z.Int}),Oo=z.decodeUnknownOption(z.fromJsonString(Do)),ko=z.Array(z.Struct({scope:z.String,value:z.String})),Ao=z.decodeUnknownOption(z.fromJsonString(ko)),jo=z.Struct({rules:z.Record(z.String,z.Unknown)}),Mo=z.decodeUnknownOption(z.fromJsonString(jo)),No=N.Reference(`adamantite/OxlintCommand`,{defaultValue:()=>tt});function Po(e){let t=e.lastIndexOf(`/`);return t===-1?{name:e,plugin:`eslint`}:{name:e.slice(t+1),plugin:e.slice(0,t)}}function Fo(e,t){return e===`${t.plugin}(${t.name})`}function Io(){return[A.env.NODE_OPTIONS,`--disable-warning=MODULE_TYPELESS_PACKAGE_JSON`].filter(Boolean).join(` `)}const Lo=T.fn(`runOxlint`)(function*(e,t,n=e){let r=yield*E.ChildProcessSpawner,i=(yield*No)(n),a=yield*r.spawn(dt.make(i.command,[...i.args,...t],{cwd:e,env:{...i.env,NODE_OPTIONS:Io()},extendEnv:!0,stdin:`ignore`})),[o,s,c]=yield*T.all([H.mkString(H.decodeText(a.stdout)),H.mkString(H.decodeText(a.stderr)),a.exitCode],{concurrency:`unbounded`});return{exitCode:c,output:`${o}${s}`.trim(),stdout:o}},T.scoped,T.catchReason(`PlatformError`,`NotFound`,()=>T.fail(new qe({command:`node`})),(e,t)=>T.fail(new je({output:t.message}))));function Ro(e){let t=e.search(To);return t===-1?M.none():Oo(e.slice(t))}const zo=T.fn(`lintFiles`)(function*(e,t){let{output:n,stdout:r}=yield*Lo(e,[`-f`,`json`,...t]),i=Ro(r);return M.isNone(i)?yield*new je({output:n}):i.value}),Bo=T.fn(`listLintedFiles`)(function*(e,t=[]){let{exitCode:n,output:r,stdout:i}=yield*Lo(e,[`--debug=files`,...t]);return n===0?i.split(`
163
+ `).map(e=>e.trim().replaceAll(`\\`,`/`)).filter(e=>e.length>0):yield*new je({output:r})}),Vo=T.fn(`resolveRule`)(function*(e,t){let n=yield*R.FileSystem,r=yield*P.Path,i=yield*n.makeTempDirectoryScoped({prefix:`adamantite-rules-`}),a=yield*Lo(i,[`--rules`,`-f`,`json`],t),o=Ao(a.stdout);if(M.isNone(o))return yield*new je({output:a.output});let s=D.dedupe(o.value.map(e=>e.scope.replaceAll(`_`,`-`))),{name:c,plugin:l}=Po(e);yield*S(r.join(i,`.oxlintrc.json`),yield*ce({categories:{correctness:`off`},plugins:s,rules:{[e]:`error`}}));let u=yield*Lo(i,[`--print-config`],t),d=Mo(u.stdout).pipe(M.flatMap(e=>D.findFirst(Object.keys(e.rules),e=>Po(e).name===c)),M.map(e=>Po(e)));return M.match(d,{onNone:()=>({builtIn:!1,name:c,plugin:l}),onSome:e=>({builtIn:!0,name:e.name,plugin:e.plugin.replaceAll(`_`,`-`)})})},T.scoped),Ho=Ot.nominal();function Uo(e,t,n){return Ho((e.relative(t,n)||`.`).split(e.sep).join(`/`))}const Wo=T.fn(`listGitFiles`)(function*(e,t){let n=yield*(yield*E.ChildProcessSpawner).spawn(dt.make(`git`,[`ls-files`,`-z`,...t],{cwd:e,stderr:`ignore`,stdin:`ignore`})),[r,i]=yield*T.all([H.mkString(H.decodeText(n.stdout)),n.exitCode],{concurrency:`unbounded`}),a=L(r,pt.split(`\0`),D.filter(e=>pt.isNonEmpty(e)));return M.liftPredicate(a,()=>i===0)},T.scoped,T.orElseSucceed(()=>M.none()));function Go(e,t=[]){return Wo(e,[`--cached`,`--others`,`--exclude-standard`,`--`,...t])}function Ko(e,t){return Wo(e,[`--others`,`--ignored`,`--exclude-standard`,`--`,t,`:(exclude,glob)**/node_modules/**`])}var qo=class extends I.TaggedClass(`Current`){},Jo=class extends I.TaggedClass(`Error`){};function Yo(e,t){let n=e.indexOf(`=`),r=n===-1?e:e.slice(0,n),i=M.liftPredicate(e.slice(n+1),()=>n!==-1),a=W.normalize(r.replaceAll(`\\`,`/`));return r.length===0||M.exists(i,e=>e.length===0)?T.fail(new Xe({reason:"Give a path, or `<path>=<file>`.",value:e})):W.isAbsolute(a)||Dt.isAbsolute(a)||a===`..`||a.startsWith(`../`)||a===`.`?T.fail(new Xe({reason:`The path must be a file inside the project, relative to the project root.`,value:e})):T.succeed({expected:t,path:a,source:i})}function Xo(e){let t={files:e.files,...M.match(e.plugin,{onNone:()=>({}),onSome:e=>({plugins:[e]})}),rules:{[e.rule]:[`error`,...e.settingOptions]}};return["// `adamantite rule try` wrote this file in a copy of the project.",`import config from ${JSON.stringify(`./${e.config}`)}`,``,`export default {`,` ...config,`,` overrides: [...(config.overrides ?? []), ${JSON.stringify(t)}],`,`}`,``].join(`
164
+ `)}const Zo=Ot.nominal(),Qo=T.fn(`replaceConfigs`)(function*(e,t){let n=yield*R.FileSystem,r=yield*P.Path;for(let[i,a]of t){let t=r.join(e,i),o=`oxlint.trial-base.config${r.extname(i)}`;yield*n.rename(t,r.join(r.dirname(t),o)),yield*S(t,a(o))}});function $o(e){return["// `adamantite harden` wrote this file in a copy of the project.",`import config from ${JSON.stringify(`./${e.config}`)}`,``,`const removals = new Map(${JSON.stringify([...e.removals])})`,``,`export default {`,` ...config,`,` overrides: (config.overrides ?? []).map((override, index) => ({`,` ...override,`,` rules: Object.fromEntries(`,` Object.entries(override.rules ?? {}).filter(`,` ([rule]) => !(removals.get(index) ?? []).includes(rule)`,` )`,` ),`,` })),`,`}`,``].join(`
165
+ `)}const es=T.fn(`makeProjectCopy`)(function*(e,t){let r=yield*R.FileSystem,i=yield*P.Path,a=yield*Go(e);if(M.isNone(a))return yield*new n({cwd:e});let o=yield*r.makeTempDirectoryScoped({prefix:`adamantite-trial-`}),s=D.dedupe(a.value.map(e=>i.dirname(i.join(o,e))));yield*T.forEach(s,e=>r.makeDirectory(e,{recursive:!0}),{concurrency:16,discard:!0}),yield*T.forEach(a.value,t=>r.copyFile(i.join(e,t),i.join(o,t)).pipe(T.catchReason(`PlatformError`,`NotFound`,()=>T.void)),{concurrency:16,discard:!0});let c=[e,...t.packageDirectories],l=yield*r.realPath(e),u=e=>{let t=i.relative(l,e);return M.liftPredicate(t,()=>t!==``&&t!==`..`&&!t.startsWith(`..${i.sep}`)&&!i.isAbsolute(t)&&!t.split(i.sep).includes(`node_modules`))},d=T.fnUntraced(function*(e){let t=yield*rt(e),n=yield*T.forEach(M.getOrElse(t,()=>[]).filter(e=>e!==`.cache`),T.fnUntraced(function*(t){let n=t.startsWith(`@`)&&!(yield*r.readLink(i.join(e,t)).pipe(T.as(!0),T.orElseSucceed(()=>!1)))?yield*rt(i.join(e,t)):M.none();return M.match(n,{onNone:()=>[t],onSome:e=>e.map(e=>`${t}/${e}`)})}),{concurrency:`unbounded`});return t.pipe(M.as(n.flat()))}),f=yield*T.forEach(c,T.fnUntraced(function*(t){let n=i.join(t,`node_modules`),a=i.join(o,i.relative(e,t),`node_modules`),s=yield*d(n);return M.isSome(s)&&(yield*r.makeDirectory(a,{recursive:!0})),yield*T.forEach(M.getOrElse(s,()=>[]),T.fnUntraced(function*(e){let t=i.join(n,e),s=(yield*r.realPath(t).pipe(T.option)).pipe(M.flatMap(e=>u(e)));return yield*r.makeDirectory(i.dirname(i.join(a,e)),{recursive:!0}),yield*r.symlink(M.match(s,{onNone:()=>t,onSome:e=>i.join(o,e)}),i.join(a,e)),s}),{concurrency:1})}),{concurrency:1}),p=yield*T.forEach(D.dedupe(D.getSomes(f.flat())),t=>Ko(e,t.split(i.sep).join(`/`)).pipe(T.map(e=>M.getOrElse(e,()=>[]))),{concurrency:`unbounded`});return yield*T.forEach(D.dedupe(p.flat()),t=>r.makeDirectory(i.dirname(i.join(o,t)),{recursive:!0}).pipe(T.andThen(r.copyFile(i.join(e,t),i.join(o,t)))),{concurrency:16,discard:!0}),Zo(o)},T.catchTag(`PlatformError`,e=>T.fail(new Qe({cause:e})))),ts=T.fn(`findConfig`)(function*(e,t){let n=yield*P.Path,r=[];for(let i=n.dirname(n.join(e,t));i===e||i.startsWith(`${e}${n.sep}`);i=n.dirname(i))r.push(...ea.map(e=>n.join(i,e)));return yield*T.findFirst(r,e=>g(e))});function ns(e){let t=[];for(let n of e){let e=t.find(e=>e.every(e=>e.case.path!==n.case.path));e===void 0?t.push([n]):e.push(n)}return t}const rs=T.fn(`tryRule`)(function*(e){let t=yield*R.FileSystem,n=yield*P.Path,{cases:i,cwd:a,rule:o,setting:c,workspace:u}=e,{name:d,plugin:f}=Po(o),p=yield*Vo(o,a),m=yield*es(a,u),h=e=>n.relative(m,e).split(n.sep).join(`/`),g=e=>{let t=[`Rule '${d}' not found in plugin '${f}'`,`Plugin '${f}' not found`].find(t=>F.isTagged(e,`TrialLintFailed`)&&e.output.includes(t));return c instanceof Jo&&t!==void 0?new ke({detail:t,rule:o}):e},_=yield*T.forEach(i,T.fnUntraced(function*(e){if(M.isNone(e.source)&&!(yield*t.exists(n.join(m,e.path))))return yield*new Xe({reason:(yield*t.exists(n.join(a,e.path)))?"Git ignores this file, so the copy of the project does not have it. Use `<path>=<file>` to lint its content.":"The project has no such file. Use `<path>=<file>` to lint other content.",value:e.path});let r=yield*ts(m,e.path);return M.isNone(r)?yield*new te({path:e.path}):{case:e,config:r.value,configFile:n.relative(n.dirname(r.value),n.join(m,e.path)).split(n.sep).join(`/`)}}),{concurrency:1});c instanceof Jo&&(yield*Qo(m,new Map(D.dedupe(_.map(e=>e.config)).map(e=>[n.relative(m,e),t=>Xo({config:t,files:D.dedupe(_.filter(t=>t.config===e).map(e=>e.configFile)),plugin:M.liftPredicate(p.plugin,e=>p.builtIn&&e!==`eslint`),rule:o,settingOptions:c.options})]))));let v=/* @__PURE__ */ new Map;for(let e of ns(_)){let i=e.flatMap(e=>M.match(e.case.source,{onNone:()=>[],onSome:t=>[{source:n.resolve(a,t),target:n.join(m,e.case.path)}]})),o=yield*T.forEach(i,({target:e})=>t.readFileString(e).pipe(T.option),{concurrency:`unbounded`});for(let{source:e,target:a}of i)yield*t.makeDirectory(n.dirname(a),{recursive:!0}),yield*S(a,yield*r(e));let c=e.map(e=>e.case.path),u=yield*zo(m,c).pipe(T.mapError(e=>g(e)));if(u.number_of_files<c.length){let e=new Set(yield*Bo(m,c));return yield*new l({path:c.find(t=>!e.has(t))??c[0]??``})}yield*T.forEach(i,({target:e},n)=>M.match(o[n]??M.none(),{onNone:()=>t.remove(e),onSome:n=>t.writeFileString(e,n)}),{concurrency:1,discard:!0});for(let t of e){let e=u.diagnostics.filter(e=>e.filename===t.case.path),n=e.filter(e=>e.code===void 0);if(n.length>0)return yield*new s({errors:n.map(e=>e.message),path:t.case.path});v.set(t.case,{case:t.case,config:h(t.config),diagnostics:e.filter(e=>e.code!==void 0&&Fo(e.code,p)).map(e=>({column:e.labels[0]?.span.column??1,line:e.labels[0]?.span.line??1,message:e.message}))})}}return D.getSomes(i.map(e=>M.fromUndefinedOr(v.get(e))))},T.scoped,T.catchTag(`PlatformError`,e=>T.fail(new Qe({cause:e}))));var is=class extends I.TaggedClass(`Linted`){},as=class extends I.TaggedClass(`Failed`){};const os=/[!*?[\]{}]/u;function ss(e){return e===null?null:e.type===`Literal`&&F.isString(e.value)?e.value:e.type===`TemplateLiteral`&&e.expressions.length===0?e.quasis[0]?.value.cooked??null:null}function cs(e){return e.computed?null:e.key.type===`Identifier`?e.key.name:e.key.type===`Literal`&&F.isString(e.key.value)?e.key.value:null}function ls(e,t){let n=e.properties.find(e=>e.type===`Property`&&cs(e)===t);return n?.type===`Property`?n.value:void 0}function us(e){if(e.type===`ArrayExpression`){let[t]=e.elements;return t!=null&&t.type!==`SpreadElement`&&us(t)}return e.type===`Literal`&&(e.value===`off`||e.value===`allow`||e.value===0)}function ds(e){let[t]=e.body.flatMap(e=>e.type===`ExportDefaultDeclaration`?[e]:[]);if(t===void 0)return;let n=t=>{if(t.type===`ObjectExpression`)return t;if(t.type===`CallExpression`){let[e]=t.arguments;return e!==void 0&&e.type!==`SpreadElement`?n(e):void 0}if(t.type===`Identifier`){let r=e.body.flatMap(e=>e.type===`VariableDeclaration`?e.declarations:e.type===`ExportNamedDeclaration`&&e.declaration?.type===`VariableDeclaration`?e.declaration.declarations:[]).find(e=>e.id.type===`Identifier`&&e.id.name===t.name);return r?.init?n(r.init):void 0}if(t.type===`TSAsExpression`||t.type===`TSSatisfiesExpression`)return n(t.expression)},r=t.declaration;return r.type===`ObjectExpression`||r.type===`CallExpression`||r.type===`Identifier`||r.type===`TSAsExpression`||r.type===`TSSatisfiesExpression`?n(r):void 0}function fs(e,t){let{errors:n,program:r}=bt(e,t,{sourceType:`module`});if(n.length>0)return[];let i=ds(r),a=i===void 0?void 0:ls(i,`overrides`);if(a?.type!==`ArrayExpression`)return[];let o=a.elements.findIndex(e=>e?.type===`SpreadElement`);return(o===-1?a.elements:a.elements.slice(0,o)).flatMap((e,t)=>{if(e?.type!==`ObjectExpression`)return[];let n=ls(e,`files`),r=ls(e,`rules`);if(n?.type!==`ArrayExpression`||r?.type!==`ObjectExpression`)return[];let i=n.elements.map(e=>ss(e)),a=r.properties.flatMap(e=>{let t=e.type===`Property`?cs(e):null;return e.type===`Property`&&t!==null&&us(e.value)?[t]:[]});return i.every(e=>e!==null)&&a.length>0?[{files:i,index:t,rules:a}]:[]})}const ps=T.fn(`readOverrides`)(function*(e,t,n,i){let a=yield*P.Path,o=e=>i===null||i===`.`||e===i||e.startsWith(`${i}/`),s=(t,n)=>a.relative(e,a.join(e,a.dirname(t),n)).split(a.sep).join(`/`),c=(yield*T.forEach(n,t=>r(a.join(e,t)).pipe(T.map(e=>({config:t,overrides:fs(t,e)}))),{concurrency:`unbounded`})).flatMap(({config:e,overrides:t})=>t.flatMap(t=>t.rules.map(n=>({config:e,globs:t.files.filter(e=>os.test(e)),index:t.index,literals:t.files.filter(e=>!os.test(e)).map(t=>s(e,t)).filter(e=>o(e)),rule:n})))),l=new Set(yield*T.filter(D.dedupe(c.flatMap(e=>e.literals)),t=>g(a.join(e,t)),{concurrency:`unbounded`})),u=c.filter(e=>e.literals.some(e=>l.has(e))),d=/* @__PURE__ */ new Map;if(u.length>0){let n=new Map(yield*T.forEach(D.dedupe(u.map(e=>e.rule)),t=>Vo(t,e).pipe(T.map(e=>[t,e])),{concurrency:`unbounded`})),r=yield*es(e,t);yield*Qo(r,new Map(D.dedupe(u.map(e=>e.config)).map(e=>{let t=/* @__PURE__ */ new Map;for(let n of u.filter(t=>t.config===e))t.set(n.index,[...t.get(n.index)??[],n.rule]);return[e,e=>$o({config:e,removals:t})]})));let i=D.dedupe(u.flatMap(e=>e.literals)).filter(e=>l.has(e)),a=yield*zo(r,i),o=new Set(a.number_of_files<i.length?yield*Bo(r,i):i),s=new Set(a.diagnostics.filter(e=>e.code===void 0).map(e=>e.filename));for(let e of u){let t=n.get(e.rule);for(let n of e.literals.filter(e=>l.has(e))){let r=a.diagnostics.some(e=>e.filename===n&&e.code!==void 0&&t!==void 0&&Fo(e.code,t)),i=o.has(n)?s.has(n)?`unparsable`:r?`breaks`:`clean`:`ignored`;d.set(`${e.rule}\0${n}`,i)}}}return new is({rules:c.filter(e=>e.literals.length>0||e.globs.length>0).map(e=>({config:e.config,files:e.literals.map(t=>({file:t,mark:d.get(`${e.rule}\0${t}`)??`missing`})),globs:e.globs,rule:e.rule}))})},T.scoped,T.catch(e=>T.succeed(new as({reason:e.message})))),ms=`Custom rules`,hs=`AGENTS.md`;function gs(e){let t=e.split(`/`);return!t.includes(`.changeset`)&&t.at(-1)!==`CHANGELOG.md`}function _s(e,t,n,r){let i=(t,n)=>{let r=e.relative(t,n);return r!==`..`&&!r.startsWith(`..${e.sep}`)&&!e.isAbsolute(r)},a=B.mapInput(B.flip(B.Number),e=>e.length),o=[t,...n.packageDirectories],s=o.filter(e=>i(r,e)),c=D.sort(o.filter(e=>i(e,r)),a).slice(0,1),l=s.length>0?s:c;return{contains:i,isSelectedFile:n=>{let[r=t]=D.sort(o.filter(r=>i(r,e.join(t,n))),a);return r===t||l.includes(r)},packageDirectories:o,selectedPackages:l}}const vs=T.fn(`readScopedDocumentation`)(function*(e,t,n){let r=yield*P.Path,{contains:i,isSelectedFile:a}=_s(r,e,t,n),o=t=>{let a=r.dirname(r.join(e,t));return i(a,n)||i(n,a)},s=yield*T.transposeOption((yield*Go(e,[`*.md`,`*.mdx`,`*.mdc`])).pipe(M.map(t=>T.forEach(t.filter(e=>gs(e)),t=>g(r.join(e,t)).pipe(T.map(e=>e?[t]:[])),{concurrency:`unbounded`}).pipe(T.map(e=>e.flat())))));return{agentReach:(yield*T.transposeOption(s.pipe(M.map(t=>wo(e,t,t.filter(e=>r.basename(e)===hs&&o(e))))))).pipe(M.map(e=>({brokenLinks:e.brokenLinks.filter(e=>a(e.file)),unreached:e.unreached.filter(e=>a(e))}))),documentationFiles:s.pipe(M.map(e=>e.filter(e=>a(e))))}}),ys=T.fn(`readHardenReach`)(function*(e,t,n=e){return(yield*vs(e,t,n)).agentReach}),bs=T.fn(`readHardenContext`)(function*(e,t,n=e){let r=yield*P.Path,i=t=>r.relative(e,t)||`.`,{packageDirectories:a,selectedPackages:o}=_s(r,e,t,n),s=[.../* @__PURE__ */ new Set([e,...o])].map(e=>r.join(e,hs)),[{calls:c,configs:l,unresolvedCalls:u},d,f]=yield*T.all([sa(a,o),T.filter(s,e=>g(e),{concurrency:`unbounded`}),vs(e,t,n)],{concurrency:`unbounded`});return{agentReach:f.agentReach,configs:l.map(t=>Uo(r,e,t)),documentationFiles:f.documentationFiles,instructionFiles:d.map(e=>i(e)),rulesFolders:[...new Set(c.map(e=>i(e.dir)))],scope:n===e?null:Uo(r,e,n),unresolvedCalls:[...new Set(u.map(e=>i(e)))]}}),xs=/^[\w./-]+$/u;function Ss(e){return xs.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`}function Cs(e,t){return e.length===0?t:e.map(e=>`- \`${e}\``).join(`
166
+ `)}function ws(e){return[e.unreached.length===0?"Links and code spans from each `AGENTS.md` reach each Markdown file.":`No chain of links or code spans from an \`AGENTS.md\` reaches these Markdown files:\n\n${Cs(e.unreached,``)}`,...e.brokenLinks.length===0?[]:[`These links go to Markdown files that do not exist:\n\n${e.brokenLinks.map(e=>`- \`${e.file}\` links to \`${e.target}\``).join(`
167
+ `)}`]].join(`
168
+
169
+ `)}function Ts(e){return e.rulesFolders.length===0&&e.unresolvedCalls.length===0?`No \`custom()\` call loads a rules folder. Before you write the first custom rule, add \`custom()\` from \`adamantite/rules\` to the \`extends\` of the Oxlint config. It loads \`${q}\` by default.`:[...e.rulesFolders.map(e=>`- \`${e}\``),...e.unresolvedCalls.map(e=>`- A \`custom()\` call in \`${e}\` whose \`dir\` is not a string literal. Read the config to find its rules folder.`)].join(`
170
+ `)}function Es(e){return M.match(e,{onNone:()=>'Adamantite could not count the comments that turn a rule off, because Oxlint could not list the files that it lints. Count them yourself, for example with `rg -n "(oxlint|eslint)-disable"`, and leave out the files that the config ignores.',onSome:e=>e.length===0?"No `oxlint-disable` or `eslint-disable` comment turns a rule off.":["Adamantite counted the `oxlint-disable` and `eslint-disable` comments of each rule in the files that Oxlint lints. Oxlint obeys both. A comment that names no rule turns off all rules.",``,...e.map(({locations:e,rule:t})=>{let n=M.match(t,{onNone:()=>`All rules`,onSome:e=>`\`${e}\``}),r=e.slice(0,5).map(e=>`\`${e}\``).join(`, `),i=e.length>5?`, and ${e.length-5} more`:``;return`- ${n}: ${e.length} ${e.length===1?`comment`:`comments`}, in ${r}${i}`})].join(`
171
+ `)})}const Ds={breaks:`still breaks the rule`,clean:`no longer breaks the rule`,ignored:`the config ignores it, so Oxlint did not lint it`,missing:`does not exist`,unparsable:`does not parse, so Oxlint did not lint it`};function Os(e){return e instanceof as?[`Adamantite could not lint the files of the overrides that turn a rule off:`,``,"```text",e.reason,"```",``,`For each file in an override that turns a rule off, read the file and find the code that the rule reports.`].join(`
172
+ `):e.rules.length===0?`No override in the Oxlint config turns a rule off for files that it names.`:[`Adamantite turned each rule on again in a copy of the project, and linted each file that an override names and turns the rule off for. Paths are relative to the project root. An override that code builds, such as a spread, is not in this list.`,``,...e.rules.map(({config:e,files:t,globs:n,rule:r})=>[`- \`${r}\` in \`${e}\`:`,...t.map(({file:e,mark:t})=>` - \`${e}\`: ${Ds[t]}`),...n.map(e=>` - \`${e}\`: a glob, so Adamantite did not lint its files`)].join(`
173
+ `))].join(`
174
+ `)}function ks(e,{adamantiteVersion:t,commits:n,overrides:r,suppressions:i}){let a=Ss(e.scope??`.`);return Hr(`# Adamantite harden
175
+
176
+ Find the coding standards that this target project already follows. Propose the highest step of the enforcement ladder that can enforce each standard. The project uses Adamantite {{version}}.
177
+
178
+ Steps 1 to 8 are read-only for the target project. Keep trial case files outside the project and use stdin for RuleTester cases. Change project files only in step 9, for the candidates that the user approves.
179
+
180
+ ## Context
181
+
182
+ {{scope}}
183
+
184
+ ### Oxlint config
185
+
186
+ {{configs}}
187
+
188
+ ### Rules folders
189
+
190
+ {{rulesFolders}}
191
+
192
+ ### Instructions
193
+
194
+ {{instructionFiles}}
195
+
196
+ ### Documentation
197
+
198
+ These are the Markdown files of the project, without the changesets and the changelogs.
199
+
200
+ {{documentationFiles}}
201
+
202
+ ### Agent reach
203
+
204
+ {{agentReach}}
205
+
206
+ ### Suppressions
207
+
208
+ {{suppressions}}
209
+
210
+ ### Overrides that turn a rule off
211
+
212
+ {{overrides}}
213
+
214
+ ## 1. Explore the documentation
215
+
216
+ Start with each \`AGENTS.md\` above, then read each file in the documentation list. Follow the files that the instructions link to or tell agents to read, including files absent from the list. Read the comments in the Oxlint config. Read a linked file outside \`--path\`, but keep the code survey inside the selected scope. Read each file once.
217
+
218
+ Mark each file as "has standards" or "no standards". A file that states a standard, and that the agent reach above lists as not reached, is a **discovery gap**: an agent that starts from \`AGENTS.md\` never finds its standards. Record the file, its standards, and the \`AGENTS.md\` that should point to it. Each link to a Markdown file that does not exist is a discovery gap too. Record the file that the link must go to.
219
+
220
+ This step is done when each file in the documentation list, and each file that the instructions link to, has its mark.
221
+
222
+ ## 2. List the written standards
223
+
224
+ List each standard that a file marked "has standards" states, with its file and line. Each written standard is a candidate, and goes on to step 5, also when the code breaks it in many places.
225
+
226
+ Continue when every written standard has a source location and a candidate entry.
227
+
228
+ ## 3. Survey the code
229
+
230
+ Survey these areas: file names and placement, import direction, naming, API use, error handling, and test layout. In each area, find the patterns that the code follows and that no instruction states.
231
+
232
+ - A pattern is a candidate when the code follows it in several places and has few counterexamples. List each counterexample with its file and line.
233
+ - Give the scope of each count as globs, and the command that gives the count, such as an \`rg\` command. Count source, tests, and generated code apart.
234
+ - If the GitHub CLI \`gh\` is available and authenticated, read the review comments of recent merged pull requests. A correction that reviewers repeat is evidence of a standard. If reviews are unavailable, record that limit and use the documentation, code, and local history.
235
+ - A construct that the code never uses is not a standard by itself. It needs an instruction, a review comment, or a commit that states it.
236
+ - Read the git history of the Oxlint config, for example with \`git log -p -- oxlint.config.ts\`. A rule that a commit removed is a **decision** that the maintainer already made, not a candidate.
237
+
238
+ This step is done when each area has its candidates or the note "none found".
239
+
240
+ ## 4. Read the fix history
241
+
242
+ A mistake that a commit fixed, and that other code repeats, is a standard that a rule can hold. Run this command from the project root, and read the commits that it lists. When the history has fewer commits, read all of them, and say how many you read.
243
+
244
+ {{fixHistoryCommand}}
245
+
246
+ - Find the commits that fix a mistake: a bug fix, a revert, or a correction after a review. Read the diff of each one with \`git show <commit>\`.
247
+ - Name the mistake in one sentence, in terms of the code, such as "an \`await\` in a \`forEach\` callback" or "a date that the code parses without a time zone". Skip the fixes of logic that only one place has.
248
+ - Find the commit that added the mistake, for example with \`git log -L\` or \`git blame <commit>^ -- <file>\`. Record it with the fix.
249
+ - A mistake is a candidate when two or more fixes have it, or when one fix has it and the code still has the same form in other places. List each fix with its commit, and each other place with its file and line.
250
+ - The code before the fix is the case that the rule must report, and the code after the fix is the case that it must accept. Read the code before the fix with \`git show <commit>^:<file>\`.
251
+
252
+ If Git or the required history is unavailable, record the missing source and continue with the documentation and code candidates. Do not infer commit evidence.
253
+
254
+ This step is done when each fix has its mark: "candidate", "one-off", or "not a code mistake", or the missing history is recorded.
255
+
256
+ ## 5. Drop what a tool already enforces
257
+
258
+ For each written standard from step 2 and each candidate from steps 3 and 4, find out whether a tool already enforces it. Read the Oxlint config, the presets and plugins that it extends, its overrides, the custom rules, \`tsconfig.json\`, and the checks that the project runs in CI.
259
+
260
+ - To see whether the config reports a case, or to try a rule that is not on, or a rule with other options, run \`adamantite rule try\`. It lints the cases in a copy of the project, so the project stays unchanged.
261
+ - \`adamantite rule try <rule> --current --report <case>\` shows what the config reports now. Use a counterexample from step 3 or 4 as the case.
262
+ - \`adamantite rule try <rule> [--options '<json array>'] --report <case> --accept <case>\` tries a new rule or new options. The options are the items that come after the severity.
263
+
264
+ A case is a project path, such as \`src/cart.ts\`, or \`<path>=<file>\` to lint the content of \`<file>\` at \`<path>\`, such as \`src/cart.ts=/tmp/before.ts\`. Write the case files outside the project. Exit 2 means that the trial is not evidence: read its reason.
265
+
266
+ - A report from a rule that only the trial turns on is not enforcement: the rule is a proposal for step 7.
267
+ - When no counterexample exists, mark the enforcement as not confirmed.
268
+ - Drop each candidate that a tool enforces fully. When a tool enforces only part of a written standard, keep the other part as a candidate.
269
+
270
+ This step is done when each written standard and each candidate is marked as enforced, partly enforced, not enforced, or not confirmed, with the rule or the lint output as evidence.
271
+
272
+ ## 6. Find the gaps in the existing rules
273
+
274
+ Step 5 starts from the standards. This step starts from the rules that the project already has: each custom rule, each \`adamantite/layers\` map, each \`adamantite/import-owners\` option, and each \`no-restricted-imports\` setting and its overrides.
275
+
276
+ - **Forms that a rule misses:** list the forms of the same mistake that the rule does not report. For an import rule, check \`require()\`, \`import()\`, \`export … from\`, \`import type\`, and the path aliases of \`tsconfig.json\`. For a custom rule, read its logic and check the other syntax of the same mistake, such as a call through a variable, optional chaining, a computed member, or a re-export. Search the code for each form, and lint a file that has it. When the code does not have the form yet, run \`adamantite rule try <rule> --current --report <control> --report <missed form>\`, with a form that the rule reports as the control. The gap is confirmed when it reports the control and does not report the missed form. When no trial can show it, mark the gap as not confirmed: the temporary regression case of step 9 confirms it.
277
+ - **Files that a rule misses:** for each \`files\` glob of an override, list the files that the standard applies to and that the glob does not match, such as a new folder or another file extension.
278
+ - **Verification cases:** for each existing custom rule, prepare temporary valid and invalid cases for the forms above. Verify them with RuleTester from stdin. Do not write files in this step. Preserve user-owned saved rule tests.
279
+ - **Overrides that can shrink:** each file that the overrides above mark "no longer breaks the rule" or "does not exist" is a candidate: remove it from the override. A file that Oxlint did not lint, because the config ignores it or it does not parse, is not evidence. Check it yourself.
280
+ - **Suppressions:** read the counts in the suppressions above. Many suppressions of one rule are a **decision**: the rule is too wide, or the standard has exceptions that the rule must know.
281
+
282
+ Each gap is a candidate on the step of the rule that it extends: a wider custom rule, a new option, a new test case, a wider glob, or a smaller override. A gap that is not confirmed is a candidate too: show it with the mark "not confirmed". A gap in a rule that a preset or plugin ships, and that no option of the rule can close, is not a candidate: list it under **Decisions** as a report for the maintainers of that package.
283
+
284
+ This step is done when each rule has its gaps or the note "none found".
285
+
286
+ ## 7. Place each candidate on the enforcement ladder
287
+
288
+ Put each remaining candidate on the highest step that works:
289
+
290
+ 1. **Type or structure:** a type, a schema, a module boundary, or a stricter TypeScript option makes the mistake impossible.
291
+ 2. **Preset rule:** a rule in an Oxlint preset or plugin that the project can turn on, or an option of a rule that is already on. A native rule, such as a file-name rule, comes before a custom rule that checks the same thing.
292
+ 3. **Import rule:** \`adamantite/layers\` for one-way imports between the folders of a root, \`adamantite/import-owners\` for a package that only one file or folder imports, or \`no-restricted-imports\` with an override for the files that the standard applies to. In Oxlint, a later override replaces the options of a rule that an earlier override set for the same files. Write one combined \`no-restricted-imports\` for each set of files, with the paths of the existing overrides.
293
+ 4. **Project check:** a check that the project already runs, such as Turbo boundaries, Knip, or a script that reads \`package.json\`.
294
+ 5. **Custom rule:** a rule in the rules folder that checks the AST.
295
+ 6. **Instruction:** a line in \`CODING_STANDARDS.md\`, only when no tool can check the standard.
296
+
297
+ For each rule, give one case that the rule must report and one similar case that it must accept. For a candidate from step 4, use the code before and after one of its fixes. Say what the rule guarantees and what it does not, such as "bans named exports, but does not require a default export". When the rule checks only part of the standard, say which part stays an instruction.
298
+
299
+ A candidate that needs a choice from the maintainer before a rule is useful is a decision, not a candidate. Examples are two documents that state a policy differently, and a migration that changes how the code behaves. Put it in the Decisions list of step 8, and propose no rule for it.
300
+
301
+ Continue when every remaining candidate has a proposed step, evidence, limits, and cases, or is recorded as a decision.
302
+
303
+ ## 8. Show the candidates and wait for approval
304
+
305
+ If a tool or source was unavailable, name it on the first line of the report and state the fallback you used. Mark unverified evidence before scoring candidates.
306
+
307
+ Score each candidate from 1 to 5:
308
+
309
+ - **5:** a real standard, with correct counts, that no tool enforces, on the right step, with a precise rule. The maintainer can approve it as it is.
310
+ - **4:** real and useful, with one small problem, such as a count that is not exact.
311
+ - **3:** real but of low value.
312
+ - **2:** mostly enforced already, wrong evidence, or many false positives.
313
+ - **1:** not a standard.
314
+
315
+ Show the candidates with a score of 4 or 5, from the highest score to the lowest. Show each one with:
316
+
317
+ - the standard in one sentence
318
+ - its source: the instruction file and line, the code only, or the fix commits
319
+ - the number of places that follow it, its scope, and the counterexamples
320
+ - its step on the ladder, and the rule, option, or instruction that you propose
321
+ - the case that the rule must report, and the case that it must accept
322
+ - the part of the standard that stays an instruction, if a part stays
323
+ - the existing code that the new rule would report
324
+
325
+ Then show three short lists:
326
+
327
+ - **Decisions:** each written standard that the code does not follow, each rule that a commit removed, each choice from step 7, each rule with many suppressions, and each gap in a shipped rule that no option can close. Give the instruction, the code, and the choice that the maintainer must make.
328
+ - **Discovery gaps:** the gaps from step 1. Propose a pointer only for the standards that stay instructions, because a rule replaces the instruction that a pointer would lead to. For a broken link, propose the correct target.
329
+ - **Also considered:** the candidates with a score of 3 or lower, one line for each, with the reason.
330
+
331
+ When no human can approve, for example in CI or in an unattended session, report the candidates and stop after this step.
332
+
333
+ Otherwise, put the approval question last in the report, with no text after it. Ask the user which named candidates to write. Wait until the user names the candidates to write or approves none. If the user approves none, stop without changing project files.
334
+
335
+ ## 9. Write the approved standards
336
+
337
+ Write only the approved candidates:
338
+
339
+ - **Type, structure, preset rule, import rule, or project check:** change the types, the Oxlint config, \`tsconfig.json\`, or the check.
340
+ - **Custom rule:** read \`skills/adamantite/SKILL.md\` in the installed \`adamantite\` package. Follow its "{{customRulesSection}}" section and linked guide to write, verify, and clean up the approved rule. Run \`adamantite rule add <name>\`. When the rules folder above is not \`.adamantite/lint\`, pass it with \`--dir\`. A comment at the top of the rule file states the standard and why it exists.
341
+ - **Gap in a custom rule:** create a temporary regression case first, and use RuleTester to see it fail. Follow the custom-rule guide above until all valid and invalid cases pass and cleanup is complete.
342
+ - **Gap in the config of a rule,** such as a layer map, an import-owners option, a \`no-restricted-imports\` path, or an override glob: change the Oxlint config. Then lint a file that has the missed form, and read the report. When no file has the form, tell the user that the change is not verified. Do not change a rule that a preset or plugin ships.
343
+ - **Override that can shrink:** remove only the files that no longer break the rule.
344
+ - **Instruction that became a rule:** delete the instruction of each standard that a rule now checks. The rule is the only source of the standard. When the rule checks only part of the standard, keep the other part as the instruction.
345
+ - **Existing violations:** keep the code that a new rule reports as it is, and list the violations for the user. Keep the rule at \`error\`, and add an \`overrides\` entry to the Oxlint config that turns the rule off only in the files that break it now, such as \`{ files: ["src/legacy/cart.ts"], rules: { "project/no-foo": "off" } }\`. Do not set the rule to \`warn\`: \`adamantite check\` fails on warnings. New files must follow the rule. A separate change fixes the violations and removes each file from the override.
346
+ - **Instruction:** write each approved standard that no tool can check to \`CODING_STANDARDS.md\`, one line for each standard. When no \`AGENTS.md\` points to \`CODING_STANDARDS.md\`, add the pointer to the root \`AGENTS.md\`.
347
+ - **Discovery gap:** add each approved pointer to the \`AGENTS.md\` that the gap names, or to a file that it reaches, as a Markdown link. Fix each approved broken link.
348
+
349
+ Continue when every approved candidate is implemented and each changed custom rule has passed the guide's verification and cleanup checks.
350
+
351
+ ## Verify
352
+
353
+ Run \`adamantite check\` and \`adamantite doctor\` in this order, through the project's package runner. Both must exit 0. When you changed a project check, also run that check with the project's own command, from the folder where CI runs it. Read the output of every check.
354
+
355
+ When a new rule makes \`check\` fail, fix the rule or add the file to the override as step 9 says, not a disable comment. Do not add saved rule tests or CI steps unless the user requests them. Preserve user-owned tests and CI steps.
356
+
357
+ When you changed the documentation, run \`adamantite harden\` again without a terminal and read its agent reach. Do not restart this procedure. Each discovery gap that you closed must be gone, and no link that you added may go to a file that does not exist.
358
+
359
+ Continue when the required checks pass, the approved discovery gaps are closed, and no temporary verification cases, fixtures, or verification-only helpers remain. If a check is blocked, record its command and reason instead of claiming completion.
360
+
361
+ ## Report the result
362
+
363
+ Use the missing-source report format from step 8. Report the approved candidates implemented, changed files, verification cases and results, commands run, and remaining violations or decisions. State whether temporary verification files were removed. Keep unverified results separate from successful checks.
364
+
365
+ The report is complete when each approved candidate has a verified result or an explicit blocker. Use this report only after approval and implementation. Before approval, use the proposal and closing question in step 8.
366
+
367
+ ## Check the result
368
+
369
+ - Every project change implements an approved candidate and stays inside the selected scope.
370
+ - Each new or changed custom rule passed valid and invalid cases, including a regression case for a bug fix.
371
+ - Temporary verification files are removed, and user-owned tests and CI steps remain.
372
+ - Project checks and Doctor pass, or the report names each blocked check and remaining finding.
373
+ - Approved discovery gaps are closed, and added documentation links resolve.
374
+ `,{agentReach:M.match(e.agentReach,{onNone:()=>"Git could not list the files, so agent reach is unavailable. Follow the links from each `AGENTS.md` and record the files you checked. Report this fallback with the missing sources.",onSome:e=>ws(e)}),configs:Cs(e.configs,"No Oxlint config was found. When you show the candidates, tell the user to run `adamantite init` before step 9."),customRulesSection:ms,documentationFiles:M.match(e.documentationFiles,{onNone:()=>`Git could not list project files. Find Markdown files with a file search, excluding dependencies, build output, changesets, and changelogs. Record the search scope and report this fallback with the missing sources.`,onSome:e=>Cs(e,`The project has no Markdown file.`)}),fixHistoryCommand:`\`git log -n ${n} --no-merges --format="%h %s" -- ${a}\``,instructionFiles:Cs(e.instructionFiles,"No `AGENTS.md` was found. Each file that states a standard is a discovery gap, and the root `AGENTS.md` must point to it."),overrides:Os(r),rulesFolders:Ts(e),scope:e.scope===null?`Adamantite found these files in the project and its workspace packages. Paths are relative to the project root.`:`Adamantite found these files for \`${e.scope}\`, the folder that \`--path\` selects. Survey only the code in this folder. Paths are relative to the project root.`,suppressions:Es(i),version:t})}const As=/\.[cm]?[jt]sx?$/u,js=/^\s*(?:oxlint|eslint)-disable(?:-next-line|-line)?(?:\s(?<rules>[\s\S]*))?$/u,Ms=/\s--[\s\S]*$/u;function Ns(e,t){let{comments:n,errors:r}=bt(e,t);return r.length>0?[]:n.flatMap(e=>{let n=js.exec(e.value);if(n===null)return[];let r=(n.groups?.rules??``).replace(Ms,``).split(`,`).map(e=>e.trim()).filter(e=>e.length>0);return[{line:t.slice(0,e.start).split(`
375
+ `).length,rules:r}]})}const Ps=T.fn(`readSuppressions`)(function*(e,t){let n=yield*P.Path,r=yield*Bo(e).pipe(T.option),i=e=>t===null||t===`.`||e.startsWith(`${t}/`);return yield*T.transposeOption(r.pipe(M.map(t=>T.gen(function*(){let r=yield*T.forEach(t.filter(e=>As.test(e)&&i(e)),t=>f(n.join(e,t)).pipe(T.map(e=>M.match(e,{onNone:()=>[],onSome:e=>e.includes(`-disable`)?Ns(t,e).flatMap(({line:e,rules:n})=>(n.length===0?[void 0]:n).map(n=>({location:`${t}:${e}`,rule:M.fromUndefinedOr(n)}))):[]}))),{concurrency:16}),a=D.groupBy(r.flat(),e=>M.getOrElse(e.rule,()=>``));return D.sort(Object.values(a).map(e=>({locations:e.map(e=>e.location),rule:e[0].rule})),B.combine(B.mapInput(B.flip(B.Number),e=>e.locations.length),B.mapInput(B.String,e=>M.getOrElse(e.rule,()=>``))))}))))}),Fs=`0.47.0`,{$match:Is,BrokenLink:Ls,CheckFailed:Rs,Findings:zs}=I.taggedEnum();function Bs(e){return`${e.file}\0${e.target}`}const Vs=T.fn(`readInstalledVersion`)(function*(e){let t=yield*P.Path,n=yield*(yield*Pe).resolve(e,K(`./lint`));if(M.isNone(n))return M.none();for(let e=t.dirname(n.value);e!==t.dirname(e);e=t.dirname(e)){let t=yield*u(e).pipe(T.option);if(M.isSome(t)&&t.value.name===`adamantite`)return M.fromUndefinedOr(t.value.version)}return M.none()}),Hs=j.Directory(`path`,{mustExist:!0}).pipe(j.optional,j.withDescription(`Limit the session to a project folder or workspace package. The path is relative to the current directory`)),Us=j.Int(`commits`).pipe(j.withSchema(z.Int.pipe(z.check(z.isGreaterThan(0,{message:"`--commits` must be a positive number"})))),j.withDefault(200),j.withDescription(`Set how many recent commits the agent reads to find past fixes`)),Ws=T.fn(`preparePrompt`)(function*(e,t,n){let r=yield*re(e),i=yield*bs(e,r,t),[a,o]=yield*T.all([ps(e,r,i.configs,i.scope),Ps(e,i.scope)],{concurrency:`unbounded`});return{agentReach:i.agentReach,prompt:ks(i,{adamantiteVersion:Fs,commits:n,overrides:a,suppressions:o})}});var Gs=O.make(`harden`,{commits:Us,scope:Hs}).pipe(O.withDescription(`Ask a coding agent to turn project standards into custom rules and instructions`),O.withHandler(({commits:t,scope:n})=>T.gen(function*(){let r=A.cwd(),i=yield*R.FileSystem,a=yield*P.Path,o=yield*$,s=yield*(yield*La).isInteractive;s&&(yield*o.intro(`💠 adamantite harden`));let c=yield*u(r),l=c.name===`adamantite`;if(!l&&!c.devDependencies?.adamantite&&!c.dependencies?.adamantite)return yield*new e({command:`harden`});let d=l?M.fromUndefinedOr(c.version):yield*Vs(r);if(M.isNone(d))return yield*new ne({command:`harden`});if(d.value!==Fs)return yield*new ye({command:`harden`,installed:d.value,running:Fs});let f=M.isSome(n)?yield*i.realPath(a.resolve(r,n.value)).pipe(T.mapError(e=>new Ye({cause:e,path:n.value}))):void 0;if(f!==void 0){let e=a.relative(r,f);if(e===`..`||e.startsWith(`..${a.sep}`)||a.isAbsolute(e))return yield*new oe({cwd:r,scope:f})}let{agentReach:p,prompt:m}=yield*Ws(r,f,t);if(!s){yield*o.message(m);return}let h=yield*Za({command:`Harden`,cwd:r,message:`How do you want to harden this project?`,prompt:m,subject:`the prompt`});if(!(h instanceof qa)){yield*o.outro(`Harden ended without an agent session.`);return}let{agent:g}=h,_=yield*Cr({cwd:r}).pipe(T.as([]),T.catchTags({CliNotFound:e=>o.log.error(e.message).pipe(T.as([Rs()])),CommandFailed:()=>T.succeed([Rs()])})),v=yield*Ia(r),[ee,y]=yield*T.all([ys(r,v.workspace,f),Ma(v)],{concurrency:`unbounded`}),te=new Set(M.match(p,{onNone:()=>[],onSome:e=>e.brokenLinks.map(e=>Bs(e))})),b=M.match(ee,{onNone:()=>[],onSome:e=>e.brokenLinks.filter(e=>!te.has(Bs(e)))}),x=[..._,...y.findings.length>0?[zs({findings:y.findings})]:[],...b.map(e=>Ls({link:e}))];for(let e of y.warnings)yield*o.log.warning(e);if(yield*T.forEach(x,Is({BrokenLink:({link:e})=>o.log.error(`\`${e.file}\` links to \`${e.target}\`, which does not exist, after the ${g.name} session.`),CheckFailed:()=>o.log.error(`\`adamantite check\` failed after the ${g.name} session.`),Findings:({findings:e})=>o.log.warning(`Doctor found issues after the ${g.name} session.`).pipe(T.andThen(za(e)))}),{discard:!0}),x.length>0)return yield*o.outro(`⚠️ Harden verification failed.`),yield*new Le({command:`harden`,exitCode:E.ExitCode(1)});yield*o.log.success(`\`adamantite check\` and Doctor pass after the ${g.name} session.`),yield*o.outro(`✅ Harden checks passed.`)}).pipe(T.catchTag([`AdamantiteNotInstalled`,`AdamantiteNotInNodeModules`,`AdamantiteVersionMismatch`,`ScopeOutsideProject`],e=>T.gen(function*(){let t=yield*$;return(yield*(yield*La).isInteractive)?(yield*t.log.warning(e.message),yield*t.outro(`⚠️ Harden did not start.`)):yield*t.message(e.message),yield*new Le({command:`harden`,exitCode:E.ExitCode(1)})})),T.catchTag(`OperationCancelled`,()=>T.gen(function*(){return yield*(yield*$).cancel(`Harden was cancelled.`),yield*new Le({command:`harden`,exitCode:E.ExitCode(1)})})))));const Ks=' .o8 . o8o . \n "888 .o8 `"\' .o8 \n .oooo. .oooo888 .oooo. ooo. .oo. .oo. .oooo. ooo. .oo. .o888oo oooo .o888oo .ooooo. \n`P )88b d88\' `888 `P )88b `888P"Y88bP"Y88b `P )88b `888P"Y88b 888 `888 888 d88\' `88b \n .oP"888 888 888 .oP"888 888 888 888 .oP"888 888 888 888 888 888 888ooo888 \nd8( 888 888 888 d8( 888 888 888 888 d8( 888 888 888 888 . 888 888 . 888 .o \n`Y888""8o `Y8bod88P" `Y888""8o o888o o888o o888o `Y888""8o o888o o888o "888" o888o "888" `Y8bod8P\' \n \n \n ',qs=T.gen(function*(){let e=yield*(yield*kt.Terminal).columns,t=Ks.split(`
376
+ `).reduce((e,t)=>Math.max(e,t.trim().length),0);!e||e<t||(yield*ut.info(Ks))}),Js=[`vscode`,`zed`],Ys={vscode:`VS Code / Cursor / Windsurf`,zed:`Zed`},Xs=T.fn(`validateInitOptions`)(function*(e,t){let n={agents:e.agents,editors:D.dedupe(e.editors),githubActions:e.githubActions,installExtensions:e.installExtensions,overwriteScripts:e.overwriteScripts,presets:D.dedupe(e.presets),scripts:D.dedupe(e.scripts),typescript:e.typescript},r=y(n.scripts,`oxlint`);if(n.presets.length>0&&!r)return yield*new Ce({reason:"`--preset` requires the `check` or `fix` script."});let i=D.head(_e(n.presets));if(M.isSome(i)){let{required:e,requiredBy:t}=i.value;return yield*new Ce({reason:`\`--preset ${t}\` requires \`--preset ${e}\`.`})}return n.installExtensions&&n.editors.length===0?yield*new Ce({reason:"`--install-extensions` requires at least one `--editor`."}):n.githubActions&&!Gr(n.scripts)?yield*new Ce({reason:"`--github-actions` requires --script check or --script analyze."}):n.githubActions&&!o(t)?yield*new Ce({reason:`\`--github-actions\` does not support the detected package manager \`${t}\`. Use ${_(`disjunction`)}.`}):{agents:n.agents,editors:D.isReadonlyArrayNonEmpty(n.editors)?M.some({installExtensions:n.installExtensions,names:n.editors}):M.none(),githubActions:n.githubActions?M.liftPredicate(t,o):M.none(),lint:r?M.some({presets:n.presets}):M.none(),overwriteScripts:n.overwriteScripts,scripts:n.scripts,typescript:n.typescript}}),Zs=j.Boolean(J.nonInteractive).pipe(j.withDefault(!1),j.withDescription(`Configure without prompts. Select at least one --script or --typescript`)),Qs=j.Literals(J.script,ae).pipe(j.atMost(ae.length),j.withDescription(`Add a package script. Repeat --script to add more`)),$s=j.Literals(J.preset,he).pipe(j.atMost(he.length),j.withDescription(`Select an Oxlint preset. Repeat --preset to add more. Requires --script check or --script fix`)),ec=j.Literals(J.editor,Js).pipe(j.atMost(Js.length),j.withDescription(`Configure an editor. Repeat --editor to add more`)),tc=j.Literals(`typescript`,ba).pipe(j.optional,j.withDescription(`Use a TypeScript preset: typescript for strict types, tsconfig for strict config`)),nc=j.Boolean(`install-extensions`).pipe(j.withDefault(!1),j.withDescription(`Install recommended editor extensions. Select at least one --editor`)),rc=j.Boolean(`github-actions`).pipe(j.withDefault(!1),j.withDescription(`Add a GitHub Actions workflow. Requires --script check or --script analyze and ${_(`disjunction`)}`)),ic={agents:j.Boolean(J.agents).pipe(j.withDefault(!1),j.withDescription(`Add Adamantite guidance to AGENTS.md and the Adamantite skill to the skill folders of your coding agents`)),editors:ec,githubActions:rc,installExtensions:nc,nonInteractive:Zs,overwriteScripts:j.Boolean(`overwrite-scripts`).pipe(j.withDefault(!1),j.withDescription(`Replace existing package scripts that conflict with Adamantite's managed commands`)),presets:$s,scripts:Qs,typescript:tc},ac=e=>`\`${e.script}\` runs \`${e.command}\`. Adamantite would replace it with \`${Ze[e.script]}\`.`,oc=T.gen(function*(){let e=yield*$,t=yield*e.multiselect({message:`Which presets should Adamantite use with the core preset?`,options:be.map(e=>({hint:Je(e),label:e.label,value:e.name})),required:!1}),n=_e(t);for(let{required:t,requiredBy:r}of n)yield*e.log.info(`Added the \`${t}\` preset, which \`${r}\` requires.`);return[...n.map(({required:e})=>e),...t]}),sc=T.fn(`collectInteractiveInitOptions`)(function*(e,t,n){let r=yield*$,i=yield*r.multiselect({message:"Which scripts should Adamantite add to `package.json`?",options:[{hint:`recommended`,label:`check - find formatting, lint, and type errors`,value:`check`},{hint:`recommended`,label:`fix - apply safe lint fixes and format code`,value:`fix`},{label:t?`analyze - find unused code and check monorepo consistency`:`analyze - find unused dependencies, exports, and files`,value:`analyze`}],required:!1}),a=yield*u(e),s=Ae(a,i);for(let e of s)yield*r.log.warning(ac(e));let c=s.length>0?yield*r.confirm({initialValue:!1,message:s.length===1?`Replace this script with Adamantite's command?`:`Replace these scripts with Adamantite's commands?`}):!1,l=y(i,`oxlint`)?yield*oc:[],d=(yield*r.confirm({initialValue:!0,message:`Use an Adamantite TypeScript preset?`}))?M.some(yield*r.select({message:`Which TypeScript preset should Adamantite use?`,options:[{hint:`JSON.parse() returns unknown, not any. Avoid in libraries.`,label:`Strict types`,value:`typescript`},{hint:`No changes to built-in types. Use for libraries.`,label:`Strict config`,value:`tsconfig`}]})):M.none(),f=yield*r.multiselect({message:`Which editors should Adamantite configure?`,options:Js.map(e=>({label:Ys[e],value:e})),required:!1}),p=f.length>0?yield*r.confirm({initialValue:!0,message:`Install the recommended editor extensions?`}):!1,m=o(n),h=c?[]:s.map(e=>e.script),g=i.filter(e=>!h.includes(e));Gr(g)&&!m&&(yield*r.log.info(`Adamantite cannot generate a GitHub Actions workflow for \`${n}\`. It supports ${_(`conjunction`)}.`));let v=Gr(g)&&m?yield*r.confirm({message:`Add a GitHub Actions workflow to run the selected checks?`}):!1;return{agents:yield*r.confirm({initialValue:!0,message:`Teach coding agents to use Adamantite? This adds an AGENTS.md section and the Adamantite skill.`}),editors:f,githubActions:v,installExtensions:p,overwriteScripts:c,presets:l,scripts:i,typescript:d}}),cc=`adamantite`,lc={"SKILL.md":`---
377
+ name: adamantite
378
+ description: Use when setting up Adamantite, running its checks, repairing Doctor findings, updating managed dependencies, hardening coding standards, or writing and testing custom rules.
379
+ metadata:
380
+ type: core
381
+ library: adamantite
382
+ library_version: "0.45.0"
383
+ sources:
384
+ - "adelrodriguez/adamantite:src/cli.ts"
385
+ - "adelrodriguez/adamantite:src/commands/**/*.ts"
386
+ - "adelrodriguez/adamantite:src/lib/execution/skill.ts"
387
+ - "adelrodriguez/adamantite:src/lib/toolchain/index.ts"
388
+ - "adelrodriguez/adamantite:src/lib/integrations/tooling/oxlint/plugins/**/*.ts"
389
+ - "adelrodriguez/adamantite:src/lib/integrations/tooling/knip/config.ts"
390
+ - "adelrodriguez/adamantite:src/lib/workspace/custom-rules/*"
391
+ - "adelrodriguez/adamantite:presets/lint/*.ts"
392
+ - "adelrodriguez/adamantite:presets/rules/*.ts"
393
+ ---
394
+
395
+ # Adamantite
396
+
397
+ Use Adamantite to maintain the code-quality tools of a target project, the project that
398
+ Adamantite configures or checks.
399
+
400
+ ## Select the task
401
+
402
+ Read the target project's instructions and package scripts. Run commands from its root
403
+ with its package manager and installed Adamantite version. Use \`adamantite <command> --help\`
404
+ to check options that the task needs.
405
+
406
+ Use the section below that matches the request. Read a linked guide only when that case
407
+ applies. Continue when you have identified the target project, command, and requested scope.
408
+
409
+ ## Set up a target project
410
+
411
+ For a new installation, follow [How to set up Adamantite](references/setup.md).
412
+ Use Doctor for drift in an existing installation. A code-quality failure belongs in the
413
+ checks below, rather than another initialization.
414
+
415
+ Setup is complete when the selected scripts run and Doctor reports no findings.
416
+
417
+ ## Check and fix code
418
+
419
+ Use the project's managed scripts when they exist. Otherwise, run the CLI through the
420
+ project's package manager:
421
+
422
+ - Run \`adamantite check\` for read-only formatting, lint, and type checks. Fix warnings
423
+ instead of adding \`--allow-warnings\` to pass the check.
424
+ - Run \`adamantite fix\` for safe lint fixes and formatting. Review the effect and get explicit
425
+ permission before using \`--suggested\`, \`--dangerous\`, or \`--all\`.
426
+ - Run \`adamantite analyze\` for unused files, exports, and dependencies. In a monorepo it
427
+ runs Sherif before Knip. Inspect the findings before using \`--fix\`, which can remove files.
428
+
429
+ To repair preset rule reports or change their configuration, follow
430
+ [How to repair preset rule reports](references/lint-rules.md).
431
+
432
+ Pass underlying tool arguments after \`--\`. For \`check\` and \`fix\`, they go to Oxlint unless
433
+ \`--only\` selects another stage. For \`analyze\`, they go to Knip unless \`--only\` selects
434
+ Sherif. For example, use \`adamantite analyze --only monorepo -- --select highest\`.
435
+ When a package manager consumes a separator, add another, as in
436
+ \`npm run analyze -- -- --directory packages/app\`.
437
+
438
+ If Sherif needs a version choice without a terminal, set \`sherif.select\` to \`"highest"\`
439
+ in the root \`package.json\`, or pass \`--select highest\` to the monorepo stage.
440
+ Keep permanent Sherif settings in that \`sherif\` object, with camelCase option names.
441
+ Sherif refuses fixes when \`CI\` is set. Use \`analyze --only unused --fix\` to run only Knip fixes there.
442
+
443
+ The task is complete when the affected checks exit 0 and you have read their output.
444
+
445
+ ## Repair managed setup
446
+
447
+ Run \`adamantite doctor\`. It assesses managed integrations without changing files.
448
+ Without a terminal, it prints a Markdown repair prompt and exits 1 when findings remain.
449
+ Follow each finding's current state, goal, reference, and verification command.
450
+ For a finding about the previous custom-rules API, use the migration step in
451
+ [How to write and verify custom rules](references/custom-rules.md#repair-an-existing-rules-folder).
452
+
453
+ Run Doctor again after the repair. This step is complete when Doctor exits 0 with no
454
+ findings. Report assessment warnings separately, because warnings alone also exit 0.
455
+
456
+ ## Update managed dependencies
457
+
458
+ Run \`adamantite update\`. It updates managed dependencies and refreshes stale skill copies
459
+ that \`init\` installed from the package. It reports remaining setup findings but can exit 0
460
+ with findings still present.
461
+
462
+ Follow the repair step above. The update is complete when Doctor reports no findings and
463
+ the project's checks pass.
464
+
465
+ ## Harden coding standards
466
+
467
+ Run \`adamantite harden\` and follow its Markdown prompt. Use \`--path\` to limit the scope
468
+ when the request covers one package or folder. Show the candidate standards and wait for
469
+ the user's approval before writing. If no human can approve, report the candidates and stop.
470
+
471
+ For rule trials that the prompt requests, follow the trial step in
472
+ [How to repair preset rule reports](references/lint-rules.md#try-a-rule-setting).
473
+ For approved custom rules, follow [How to write and verify custom rules](references/custom-rules.md).
474
+
475
+ A non-interactive \`harden\` run only prints the prompt. Its exit code does not verify the
476
+ work. Hardening is complete when the approved standards are enforced, the checks pass,
477
+ and Doctor reports no findings.
478
+
479
+ ## Custom rules
480
+
481
+ To add, change, verify, or save tests for a project-owned rule, follow
482
+ [How to write and verify custom rules](references/custom-rules.md).
483
+
484
+ The task is complete when the guide's verification and cleanup checks pass.
485
+
486
+ ## Report the result
487
+
488
+ If a required tool or source was unavailable, name it on the first line and state what you
489
+ used instead. Report the changes, commands run, results, and remaining findings or warnings.
490
+ For a custom rule, include the cases tested and whether you removed temporary verification files.
491
+
492
+ The report is complete when every result has command output or an inspected artifact as evidence.
493
+
494
+ ## Check the result
495
+
496
+ - The selected command matches the requested task and scope.
497
+ - The affected checks passed, or the report names the checks that remain unverified.
498
+ - Doctor findings and assessment warnings are reported separately.
499
+ - Every new or changed custom rule passed verification, and temporary cases are removed.
500
+ `,"references/custom-rules.md":'# How to write and verify custom rules\n\n## Select the rules folder\n\nUse a custom rule for a recurring project coding standard that existing rules cannot check.\nKeep it in the target project. A first-party preset change is a different task.\n\nFind the `custom()` call imported from `adamantite/rules` in the project\'s Oxlint configuration.\nIt loads `.adamantite/lint` by default, relative to the file that calls it, and enables each\nrule as `error` under `project`. Thus `no-process-env.ts` becomes `project/no-process-env`.\nUse `dir` for another folder. In a monorepo, give each rules folder its own plugin `name`,\nbecause Oxlint rejects duplicate plugin names in one run. A nested Oxlint config replaces\nthe root config. Extend the root config when the package needs its rules.\n\nContinue when you have identified the loaded rules folder and its plugin name.\n\n## Repair an existing rules folder\n\nIf Doctor reports the previous API, replace `adamantite/lint/custom` with the default import\nfrom `adamantite/rules`. Move authoring imports to `adamantite/rules/plugin`.\nMove the old default folder to `.adamantite/lint`, or set its path with `dir`.\nPreserve rule behavior, plugin names, severity, and options.\n\nContinue when Doctor reports no custom-rule wiring findings.\n\n## Write the rule\n\nFor a new rule, run `adamantite rule add <name>`. It writes only a stub.\nUse `adamantite rule ast <file>` on real code to find the node types that visitors receive.\n\nApply these authoring constraints:\n\n- Export the rule as default with `defineRule` from `adamantite/rules/plugin`.\n Import `Context`, `Rule`, `Visitor`, and `ESTree` types from that module when needed.\n- Use `createOnce`, which runs once for the lint run. Reset per-file state in `before` and\n report collected results in `after`. Read `context.filename`, `context.sourceCode`, and\n `context.settings` in `before` or a visitor. They are unavailable in the `createOnce` body.\n- Write erasable TypeScript. Replace an `enum` with a plain object, for example.\n Node.js type stripping cannot load enums, namespaces with values, parameter properties,\n or `import x = require()`.\n- Use the AST and `context.sourceCode`. Custom rules receive no type information.\n- Report with a `messageId` defined in `meta.messages`. State what the author must do\n instead and link the coding standard. Define options in `meta.schema` and read `context.options`.\n- Keep substantial logic in plain functions in a `_<name>.ts` helper when that makes the\n rule clearer. Files that start with `_`, declaration files, and `.test.*` files are not rules.\n Subfolders are not loaded.\n\nContinue when the rule implements the standard and every report gives a repair.\n\n## Verify the rule\n\nUse `RuleTester` from `adamantite/rules/testing` with Node.js, also in a Bun project.\nPut code that must report in `invalid` and similar code that must pass in `valid`.\nCover the syntax forms and file paths to which the standard applies.\nFor a bug fix, first run a regression case and confirm that it fails. Fix the rule and rerun\nall cases. Change a case only when it is wrong, and explain the change.\n\nRun temporary cases from stdin or a temporary file beside the rule. For the generated\n`no-debugger` stub, this command checks the report and an accepted TypeScript declaration:\n\n```sh\nnode --input-type=module <<\'JS\'\nimport { RuleTester } from "adamantite/rules/testing"\nimport rule from "./.adamantite/lint/no-debugger.ts"\n\nnew RuleTester({ languageOptions: { parserOptions: { lang: "ts" } } }).run("no-debugger", rule, {\n invalid: [{ code: "debugger", errors: [{ messageId: "unexpected" }] }],\n valid: ["const value: number = 1"],\n})\nJS\n```\n\nAdapt the cases to the completed rule. Verify a helper directly only when its cases are too\nmany for RuleTester. During harden, use `adamantite rule test add <name>` to prepare temporary\ncases, adapt them, and run `adamantite rule test --path <test-file>`.\nIf a saved test already exists, preserve it and use stdin for additional temporary cases.\n\nRun lint and read all output. A rule that throws can print an error for every file while\nOxlint still exits 0. Restart the editor language server after changing a rule, because\nOxlint caches rules for each run.\n\nContinue when every valid and invalid case passes and lint output contains no rule errors.\n\n## Keep saved tests when requested\n\nIf the user requests new saved tests, run `adamantite rule test add <name>` and adapt its\nvalid and invalid cases. Use `--dir` for another rules folder or `--path` for another test location.\nKeep `.test.ts` for tests beside rules, so the plugin does not load them as rules.\nRun saved tests with `adamantite rule test`, or `adamantite rule test --path <file>` for a test elsewhere.\n\nSaved tests use `node:test`. Exclude them from Vitest `test.exclude` or Jest\n`testPathIgnorePatterns`, while keeping the runner\'s default and existing exclusions.\nInit, CI generation, and harden do not run saved tests by default. Preserve existing test\nfiles and CI steps. Add new CI test steps only when requested.\n\nContinue when the saved tests pass and the project\'s other test runners do not collect them.\n\n## Check project integration\n\nIf TypeScript must check the rules folder, add `.adamantite/lint` to tsconfig `include`.\nTypeScript skips the dot folder by default. Enable `allowImportingTsExtensions` when checking\ntests that import `.ts` rule files.\n\nKnip treats rules and optional `.test.*` files in `.adamantite/lint` as entry files in the\nroot and workspace packages. For another folder, keep the preset\'s entry patterns and add\nthe folder\'s rule and test patterns to `oxlint.entry` in `knip.config.ts`.\nAdd tests saved elsewhere to the Knip entry settings if needed.\n\nRemove temporary cases, fixtures, and verification-only helpers that you created.\nKeep the rule, its runtime helpers, required configuration, and user-owned saved tests.\nRun `adamantite check` and `adamantite doctor`.\n\nContinue when both commands pass and no temporary verification files remain.\n\n## Check the rule\n\n- Every valid and invalid case passes, including the regression case for a bug fix.\n- Lint output contains no rule errors, regardless of its exit code.\n- Doctor reports no findings, and the project\'s checks pass.\n- Temporary verification files are removed, and user-owned tests and CI steps remain.\n',"references/lint-rules.md":`# How to repair preset rule reports
501
+
502
+ ## Repair the reported code
503
+
504
+ Read the rule message and apply the section below that matches it.
505
+
506
+ - For \`adamantite/no-react-state-hooks\`, follow the message's replacement for the hook.
507
+ Moving the call into a hook module only to silence the report leaves the problem in place.
508
+ Set \`allow\` only when the project's hook layout differs from the default.
509
+ - For \`adamantite/no-overzealous-destructuring\`, keep the object and read its members, or split
510
+ the pattern. Raising \`maxDepth\` or \`maxProperties\` only to pass the check hides the problem.
511
+ - For \`adamantite/require-suppression-reason\`, first try to fix the code. If a suppression is
512
+ necessary, state why the rule does not apply after \`--\`. Naming the rule or adding a single
513
+ \`-\` gives no reason. For example, use
514
+ \`// oxlint-disable-next-line no-console -- the CLI writes its report to stdout\`.
515
+ - For \`no-warning-comments\`, fix the code or track the work in the project's issue tracker.
516
+ Renaming \`TODO\` to another marker only to pass the check leaves the work untracked.
517
+ - For \`adamantite/query-from-loader\` reports on \`useQuery\` or \`useSuspenseQuery\`, replace a
518
+ plain options object or a local \`queryOptions()\` call with shared options. Define them with
519
+ \`queryOptions()\` at module scope or in an exported factory. Preload them with
520
+ \`ensureQueryData()\` in the loader and pass the same options to the hook. For reports on
521
+ \`useInfiniteQuery\` or \`useSuspenseInfiniteQuery\`, use \`infiniteQueryOptions()\` with
522
+ \`ensureInfiniteQueryData()\`. Wrapping options in a spread or moving the hook out of the route
523
+ only to silence the report leaves the preload problem unresolved.
524
+ - For \`adamantite/no-query-data-in-state\`, read query data from the query result and keep
525
+ only the user's edits in state.
526
+ - For \`effecttsgo/unstable-api-usage\`, add a deliberately accepted module or package to
527
+ \`allowedUnstableApis\` in the \`@effect/language-service\` tsconfig entry. For example, list
528
+ \`"effect/cli"\` to allow that module instead of disabling the rule for every unstable API.
529
+
530
+ Continue when the reported code follows the rule's repair and the affected lint check passes.
531
+
532
+ ## Configure layer maps and import owners
533
+
534
+ If the task changes import rules, use the first-party plugin loaded by \`architecture\` or
535
+ \`strict\`. The \`architecture\` preset enables no rules until the project configures them.
536
+
537
+ Set \`adamantite/layers\` with a layer map. Give each layer an \`imports\` list of sibling
538
+ layers. Imports are transitive. Put a child map in the containing layer's \`layers\` property:
539
+
540
+ \`\`\`ts
541
+ import architecture from "adamantite/lint/architecture"
542
+ import { defineConfig } from "oxlint"
543
+
544
+ export default defineConfig({
545
+ extends: [architecture],
546
+ rules: {
547
+ "adamantite/layers": [
548
+ "error",
549
+ {
550
+ root: "src",
551
+ layers: {
552
+ lib: {
553
+ imports: [],
554
+ layers: {
555
+ shared: { imports: [] },
556
+ services: { imports: ["shared"] },
557
+ },
558
+ },
559
+ terminal: { imports: ["lib"] },
560
+ commands: { imports: ["terminal"] },
561
+ },
562
+ },
563
+ ],
564
+ },
565
+ })
566
+ \`\`\`
567
+
568
+ Resolve \`root\` from the nearest \`package.json\` folder. The \`lib\` child map has the root
569
+ \`src/lib\`, and its dependency names are local to that map. Every containing map checks a
570
+ file independently. A child permission cannot override a parent prohibition. Declaration
571
+ order does not change permissions.
572
+
573
+ Use \`entries\` for composition files, \`isolate\` for layers whose child folders cannot import
574
+ each other, and \`ignoreTypes\` when type-only imports do not count. Add import \`conditions\`
575
+ explicitly when resolution needs them. The rule does not read tsconfig \`customConditions\`.
576
+ An unresolved import is not checked. A folder missing from the map is reported. Move a
577
+ loose root file into a layer or declare it as an entry.
578
+
579
+ Place child settings beside the child's \`layers\`. Settings do not inherit. A parent's
580
+ \`ignore\`, \`entries\`, or \`ignoreTypes\` does not skip child checks. A child root uses the
581
+ parent's actual matched folder, including when the top root is a glob. Declare each
582
+ concrete scope once. Keep separate option objects for roots that cannot nest without a
583
+ new intermediate map.
584
+
585
+ For an import that belongs to one file or folder, set \`adamantite/import-owners\`:
586
+
587
+ \`\`\`ts
588
+ import architecture from "adamantite/lint/architecture"
589
+ import { defineConfig } from "oxlint"
590
+
591
+ export default defineConfig({
592
+ extends: [architecture],
593
+ rules: {
594
+ "adamantite/import-owners": [
595
+ "error",
596
+ { import: "giget", owners: ["src/services/download.ts"] },
597
+ { import: "react-native", names: ["Alert"], owners: ["src/shared/alerts.ts"] },
598
+ { import: "#lib/database.ts", owners: ["src/lib/repositories"] },
599
+ ],
600
+ },
601
+ })
602
+ \`\`\`
603
+
604
+ Resolve owners from the workspace root, or the \`package.json\` folder outside a workspace.
605
+ An owner folder covers every file below it. A package name covers its subpaths.
606
+ Use \`names\` to restrict selected exports. Namespace imports and \`export *\` are also reported
607
+ when names are restricted. An \`import\` that starts with \`#\`, \`.\`, or \`/\` names a file or folder of
608
+ the project, resolved from the same root as the owners. The rule resolves each import of a linted
609
+ file, so a relative path or another alias to that module counts too. An import that names a \`#\`
610
+ module as the option states it also counts, as for a package. In a monorepo, a \`#\` option restricts
611
+ that alias in every package. To restrict a folder of one package, name its path from the workspace
612
+ root, such as \`./apps/web/src/lib/db\`. Use layer maps for the dependencies between folders.
613
+
614
+ Repair a report by using what the owner exports or moving the code to its layer or owner.
615
+ Adding an owner, layer dependency, or \`ignore\` glob only to pass the check weakens the standard.
616
+ Continue when the configured maps and owners match the project's intended imports.
617
+
618
+ ## Change test rule configuration
619
+
620
+ If a Jest or Vitest preset needs different test paths or rule settings, replace its entry in
621
+ \`extends\` with a project override. Use the preset's exported \`testFiles\`, or the project's
622
+ test paths, with its \`plugins\` and \`rules\`. For example:
623
+
624
+ \`\`\`ts
625
+ import vitest, { testFiles } from "adamantite/lint/vitest"
626
+ import { defineConfig } from "oxlint"
627
+
628
+ export default defineConfig({
629
+ overrides: [{ files: testFiles, plugins: vitest.plugins, rules: { ...vitest.rules } }],
630
+ })
631
+ \`\`\`
632
+
633
+ Change test rules in that override. Top-level rules do not replace the preset's test override.
634
+ Keep \`plugins\` in it, because Oxlint ignores \`vitest/*\` rules without the plugin.
635
+ Continue when the intended test files receive the configured rules.
636
+
637
+ ## Try a rule setting
638
+
639
+ Before changing a rule setting, run \`adamantite rule try <rule> --report <case> --accept <case>\`
640
+ when the task requires evidence from cases. Use \`--options '<json array>'\` for options after
641
+ the severity, or \`--current\` for the setting in the config. A case is a project path, or
642
+ \`<path>=<file>\` to lint the content of \`<file>\` at \`<path>\` in a copy of the project.
643
+
644
+ Continue when every case gives the expected result. Exit code 1 means a case differs.
645
+ Exit code 2 means the trial could not supply evidence, such as when the rule does not exist.
646
+
647
+ ## Check the repair
648
+
649
+ - The changed code or configuration follows the project's coding standard.
650
+ - The affected lint check passes without a broader exception added only to silence it.
651
+ - Each requested trial ran successfully and gave the expected results.
652
+ `,"references/setup.md":"# How to set up Adamantite\n\n## Select the setup\n\nRead `adamantite init --help` for the available scripts, presets, and editors.\nUse explicit `--non-interactive` setup as an agent. Include at least one `--script` or `--typescript`.\nFor example, to configure checks, fixes, TypeScript, and agent instructions, run:\n\n```sh\nnpx adamantite init --non-interactive --script check --script fix --typescript typescript --agents\n```\n\n`--typescript typescript` writes `adamantite/typescript`, which adds type resets, so\n`JSON.parse()` returns `unknown`. Use `--typescript tsconfig` for a library that publishes\ndeclaration files, because those files can name reset helper types that consumers do not have.\nA project that already has ts-reset can delete its `reset.d.ts` files and the\n`@total-typescript/ts-reset` dependency after it extends `adamantite/typescript`.\n\nAdapt the selected options to the request. Omitted boolean flags are disabled.\n`--agents` adds instructions to `AGENTS.md` and writes this skill to `.agents/skills`, and\nto `.claude/skills` or `.grok/skills` when the project has `.claude/` or `.grok/`.\n\nBefore selecting `react-strict`, tell the user about its modified MIT license.\nThe installed `oxlint-plugin-react-doctor` license requires written permission for use as\nmachine learning training or evaluation data, and for certain paid or hosted services.\nRead that license for the exact restrictions.\n\nContinue when each selected option serves the requested setup.\n\n## Create the selected setup\n\nRun `init` with those options. It preserves existing package scripts whose commands differ\nfrom its managed commands. Use `--overwrite-scripts` only when the task includes replacing them.\nRead the output for preserved configuration that needs a Doctor repair.\n\nAdamantite requires TypeScript 7 or later in the target project's own `package.json`.\nCheck that declaration if npm cannot install or update a managed plugin.\n\nContinue when the selected dependencies are installed and the generated files match the request.\n\n## Complete managed plugin setup\n\nIf the selected presets include a managed plugin, check its setup:\n\n- For `react-strict`, include the `react` preset and keep `oxlint-plugin-react-doctor`\n installed. Init installs the pinned package, and Doctor and update maintain it.\n Its React Doctor checks also apply in hook modules.\n- For `effect`, run Oxlint through Adamantite. A plain `oxlint` call cannot load the\n `effecttsgo` rules and stops with `Unknown plugin: 'effecttsgo'`. Replace that call with\n `adamantite check --only lint` instead of removing the preset.\n Keep `{ \"name\": \"@effect/language-service\", \"diagnostics\": true }` in\n `compilerOptions.plugins`. In a monorepo, add it to each package's tsconfig or a shared base.\n Use `ignoreDependencies.effect` from `adamantite/analyze` in `knip.config.ts`.\n- For Effect editor support, follow Doctor's editor findings. After a dependency install or\n update, run `adamantite init --non-interactive --script check --editor vscode` to prepare\n or refresh the VS Code SDK cache. Keep the project's other setup options when needed.\n Select the workspace TypeScript version in VS Code. Zed uses the installed Effect CLI.\n- For `tailwind`, check that the project uses Tailwind v4. Init installs `@shadcn/lint`.\n If components are outside the directories that `components.json` identifies, set\n `settings.shadcn.ui` in `oxlint.config.ts`.\n Without `components.json`, the plugin looks in `components/ui` or `src/components/ui`.\n For another component directory, copy the preset's component-owned rule override to that directory.\n\nContinue when Doctor reports no findings for the selected plugins and editors.\n\n## Check the setup\n\n- Each selected managed script runs successfully.\n- Doctor reports no findings, and its assessment warnings are recorded.\n- Existing scripts and configuration are preserved unless the task includes replacing them.\n"},uc=D.sort(D.dedupe(Ba.map(e=>e.skillsFolder)),B.String),dc=T.fn(`detectSkillFolders`)(function*(e){let t=yield*R.FileSystem,n=yield*P.Path;return yield*T.filter(uc,r=>{let i=n.join(e,n.dirname(r));return r===`.agents/skills`?T.succeed(!0):t.exists(i).pipe(T.mapError(e=>new Ye({cause:e,path:i})))},{concurrency:`unbounded`})}),fc=T.fn(`readSkillCopy`)(function*(e){let t=yield*R.FileSystem,n=yield*P.Path,i=yield*rt(e,{recursive:!0});if(M.isNone(i))return M.none();let a=yield*T.forEach(i.value,i=>T.gen(function*(){let a=n.join(e,i);return(yield*t.stat(a).pipe(T.mapError(e=>new Ye({cause:e,path:a})))).type===`File`?M.some([i.split(n.sep).join(`/`),yield*r(a)]):M.none()}),{concurrency:`unbounded`});return M.some(Object.fromEntries(D.getSomes(a)))});function pc(e){let t=Object.entries(lc);return Object.keys(e).length===t.length&&t.every(([t,n])=>e[t]===n)}const mc=T.fn(`getSkillDirectory`)(function*(e,t){return(yield*P.Path).join(e,t,cc)}),hc=T.fn(`findStaleSkillFolders`)(function*(e){return(yield*T.forEach(uc,t=>mc(e,t).pipe(T.flatMap(e=>fc(e)),T.map(e=>({copy:e,folder:t}))),{concurrency:`unbounded`})).filter(({copy:e})=>M.isSome(e)&&!pc(e.value)).map(({folder:e})=>e)}),gc=T.fn(`writeSkill`)(function*(e,t){let n=yield*R.FileSystem,r=yield*P.Path;for(let i of t){let t=yield*mc(e,i),a=yield*fc(t);if(!(M.isSome(a)&&pc(a.value))){yield*n.remove(t,{force:!0,recursive:!0}).pipe(T.mapError(e=>new ve({cause:e,path:t})));for(let[e,n]of Object.entries(lc)){let i=r.join(t,...e.split(`/`));yield*x(r.dirname(i)),yield*S(i,n)}}}}),_c=T.fn(`removeSkillsLockEntry`)(function*(e){let t=yield*R.FileSystem,n=(yield*P.Path).join(e,`skills-lock.json`),r=yield*C(n);if(M.isNone(r))return!1;let i=yield*w(r.value,n);if(!h(i)||!h(i.skills))return!1;let{[cc]:a,...o}=i.skills;return F.isUndefined(a)?!1:Object.keys(o).length===0?(yield*t.remove(n).pipe(T.mapError(e=>new ve({cause:e,path:n}))),!0):(yield*se(n,{...i,skills:o}),!0)}),vc=`<!-- ADAMANTITE:START -->`,yc=`<!-- ADAMANTITE:END -->`;function bc(e,t,n){let r=Tt(e,t);switch(t){case`analyze`:return`- Run \`${r}\` after changing dependencies, imports, or exports.${n?` It also checks monorepo package consistency.`:``}`;case`check`:return`- Run \`${r}\` to catch formatting, lint, and type issues.`;case`fix`:return`- Run \`${r}\` to apply safe lint fixes and format code.`}}function xc({isMonorepo:e,packageManager:t,scripts:n}){let r=ae.flatMap(r=>n.includes(r)?[bc(t,r,e)]:[]);return Hr(`{{start}}
653
+
654
+ ## Adamantite
655
+
656
+ Use the Adamantite skill for managed setup, Doctor repairs, and hardening. If the skill is not installed, read \`skills/adamantite/SKILL.md\` in the installed \`adamantite\` package.
657
+
658
+ {{scripts}}{{customRules}}- Run \`adamantite doctor\` for managed setup findings. Follow its repair prompt and rerun Doctor to verify the result.
659
+
660
+ ### Check the result
661
+
662
+ - Read the output of the affected checks. Report failures or unavailable checks.
663
+ - Report unresolved Doctor findings and assessment warnings separately.
664
+
665
+ {{end}}
666
+ `,{customRules:y(n,`oxlint`)?`- For custom rules, follow the "${ms}" section and linked guide in the Adamantite skill. Complete its verification and cleanup checks.\n`:``,end:yc,scripts:r.length>0?[`- Prefer the package scripts Adamantite added for this workspace.`,...r,``].join(`
667
+ `):``,start:vc})}const Sc=(e,t)=>T.gen(function*(){let n=(yield*P.Path).join(e,`AGENTS.md`),r=L(yield*C(n),M.getOrElse(()=>``)),i=L(r,pt.indexOf(vc)),a=L(r,pt.indexOf(yc)),o=L(M.all({end:a,start:i}),M.filter(({end:e,start:t})=>t<e)),s=xc(t);if(M.isSome(o)){let{end:e,start:t}=o.value,i=e+23,a=`${r.slice(0,t)}${s.trimEnd()}${r.slice(i)}`;return yield*S(n,a.endsWith(`
668
+ `)?a:`${a}\n`),`updated`}if(M.isSome(i)||M.isSome(a))return`malformed`;let c=r.length===0||r.endsWith(`
130
669
 
131
670
  `)?``:r.endsWith(`
132
671
  `)?`
133
672
  `:`
134
673
 
135
- `;return yield*F(t,`${r}${c}${s}`),`updated`}),da=(e,n)=>t.gen(function*(){yield*(yield*Q).withSpinner(()=>Hn(e,n),{failure:`Failed to install dependencies.`,start:`Installing dependencies...`,success:`Dependencies installed.`})});function fa(e,n,r){return t.gen(function*(){let i=yield*Q,a=yield*i.withSpinner(a=>t.gen(function*(){let t=yield*n.detect(e);for(let e of t.warnings)yield*i.log.warning(e);return t.active===null?(yield*a.message(`\`${n.config}\` not found, creating...`),yield*r,{created:!0,legacyConfig:null}):t.active.format===`ts`?(yield*a.message(`Found \`${n.config}\`, keeping existing config.`),{created:!1,legacyConfig:null}):(yield*a.message(`Found \`${t.active.file}\`, keeping existing config.`),{created:!1,legacyConfig:t.active.file})}),{failure:`Failed to set up ${n.name} config.`,start:`Setting up ${n.name} config...`,success:e=>e.created?`${n.name} config created successfully.`:`${n.name} config is ready.`});a.legacyConfig&&(yield*i.log.info(`Legacy \`${a.legacyConfig}\` was preserved during \`adamantite init\`. Run \`adamantite doctor\` and follow its findings to migrate it to the latest ${n.name} config.`))})}const pa=(e,n,r)=>t.gen(function*(){let i=yield*Q,a=yield*R(e),o=r.overwriteScripts?[]:dt(a,n),s=new Set(o.map(e=>e.script)),c=n.filter(e=>!s.has(e));yield*i.withSpinner(()=>t.gen(function*(){if(c.length!==0){a.scripts??={};for(let e of c)a.scripts[e]=z[e];yield*ct(e,a)}}),{failure:"Failed to add scripts to `package.json`.",start:"Adding scripts to your `package.json`...",success:o.length===0?"Scripts added to your `package.json`":c.length===0?"Kept your existing `package.json` scripts.":"Scripts added to your `package.json`; conflicting scripts were kept."});let l=r.nonInteractive?"Use `--overwrite-scripts` to replace it.":"Re-run `adamantite init` and confirm overwriting to replace it.";for(let e of o)yield*i.log.warning(`Kept existing \`${e.script}\` script (\`${e.command}\`) instead of \`${z[e.script]}\`. ${l}`);return o.length>0&&(yield*i.log.info("Adamantite commands forward extra arguments after `--`, so custom flags can be kept, e.g. `adamantite analyze -- --directory packages/app`.")),c}),ma=(e,n)=>t.gen(function*(){let r=yield*Q;n?yield*b(vi,t.forEach(e=>r.log.info(e))):yield*r.withSpinner(n=>t.gen(function*(){return(yield*Z.detect(e))?(yield*n.message(`\`${Z.config}\` found, updating...`),yield*Z.update(e),!1):(yield*n.message(`\`${Z.config}\` not found, creating...`),yield*Z.create(e),!0)}),{failure:`Failed to set up TypeScript config.`,start:`Setting up TypeScript config...`,success:e=>e?`\`${Z.config}\` created successfully`:`\`${Z.config}\` updated successfully`})}),ha=e=>t.gen(function*(){let t=yield*Q,n=yield*Y.update(e);n.prepare===`merged`&&(yield*t.log.info("Added `adamantite prepare` to the start of your existing `prepare` script.")),n.tsconfig===`monorepo`&&(yield*t.log.info("In a monorepo, add the Effect language service entry to each package's `tsconfig.json` or to a shared base config. Run `adamantite doctor` for the reference entry.")),n.tsconfig===`missing`&&(yield*t.log.warning("No `tsconfig.json` found, so the Effect language service is not configured. Run `adamantite doctor` for the reference entry."))}),ga=e=>t.gen(function*(){let n=yield*Q;(yield*Y.detect(e))&&(yield*n.withSpinner(()=>Y.patch(e,{quiet:!0}),{failure:`Failed to patch Oxlint and TypeScript.`,start:`Patching Oxlint and TypeScript with @effect/tsgo...`,success:`Oxlint and TypeScript patched with @effect/tsgo.`}).pipe(t.catchTag([`CommandFailed`,`CliNotFound`,`PlatformError`],()=>n.log.warning("Run `adamantite prepare` to see why the patch failed. Oxlint cannot load the `effect` preset until it succeeds."))))}),_a=(e,n)=>t.gen(function*(){let r=yield*Q;n.includes(`vscode`)&&(yield*r.withSpinner(n=>t.gen(function*(){let t=yield*$.detect(e);return yield*n.message(`\`${$.config}\` ${t?`found, updating`:`not found, creating`}...`),yield*t?$.update(e):$.create(e),!t}),{failure:`Failed to set up VS Code config.`,start:`Checking for \`${$.config}\`...`,success:e=>`\`${$.config}\` ${e?`created`:`updated`} with Adamantite preset.`})),n.includes(`zed`)&&(yield*r.withSpinner(n=>t.gen(function*(){let t=yield*K.detect(e);return yield*n.message(`\`${K.config}\` ${t?`found, updating`:`not found, creating`}...`),yield*t?K.update(e):K.create(e),!t}),{failure:`Failed to set up Zed config.`,start:`Checking for \`${K.config}\`...`,success:e=>`\`${K.config}\` ${e?`created`:`updated`} with Adamantite preset.`}))}),va=(e,n)=>t.gen(function*(){let r=yield*Q,i=e.includes(`zed`),a=e.includes(`vscode`);yield*r.withSpinner(e=>t.gen(function*(){return a&&(yield*e.message(`Installing VS Code extension...`),yield*$.extension(n)),!0}),{start:`Installing editor extensions...`,success:i&&!a?`Zed extensions require manual install.`:`Editor extensions installed successfully.`}).pipe(t.catchTags({FailedToInstallExtension:e=>t.gen(function*(){return yield*r.log.warning(`⚠️ ${e.message}`),yield*r.log.warning(`Please install it manually after setup completes.`),!1}),VscodeCliNotFound:()=>t.gen(function*(){return yield*r.log.error(`VSCode CLI ('code' command) not found.`),yield*r.log.info(`To install it:`),yield*r.log.info(` 1. Open VS Code`),yield*r.log.info(` 2. Press Cmd+Shift+P (macOS) or Ctrl+Shift+P (Windows/Linux)`),yield*r.log.info(` 3. Run 'Shell Command: Install "code" command in PATH'`),!1})})),i&&(yield*r.log.info("Install the Zed `oxc` extension: zed://extension/oxc"))}),ya=(e,n,r)=>t.gen(function*(){let i=yield*Q,a=pr.files[0].path;yield*i.withSpinner(i=>t.gen(function*(){let t=yield*pr.detect(e);return yield*i.message(t?`\`${a}\` found, updating...`:`Creating \`${a}\`...`),yield*t?pr.update(e,{packageManager:n,scripts:r}):pr.create(e,{packageManager:n,scripts:r}),!t}),{failure:`Failed to set up GitHub Actions workflow.`,start:`Setting up GitHub Actions workflow...`,success:e=>`GitHub Actions workflow ${e?`created`:`updated`} successfully.`})}).pipe(t.catchTag([`FailedToCreateDirectory`,`FailedToParseFile`,`FailedToReadFile`,`FailedToWriteFile`,`PlatformError`],e=>t.gen(function*(){let t=yield*Q;yield*t.log.warning(`Could not set up the GitHub Actions workflow. ${e.message}`),yield*t.log.warning("Fix the reported problem and run `adamantite init` again, or create the workflow manually.")}))),ba=(e,n,r,i)=>t.gen(function*(){let a=yield*Q,o=yield*a.withSpinner(()=>ua(e,{isMonorepo:i,packageManager:n,scripts:r}),{failure:`Failed to update AGENTS.md.`,start:`Updating AGENTS.md...`,success:`AGENTS.md check complete.`}).pipe(t.catchTag([`FailedToReadFile`,`FailedToWriteFile`],e=>t.gen(function*(){return yield*a.log.warning(`Could not update AGENTS.md. ${e.message} Adamantite will continue initialization.`),`failed`})));o!==`failed`&&o===`malformed`&&(yield*a.log.warning(`Could not update AGENTS.md because Adamantite markers are incomplete. Remove the stale ADAMANTITE marker and run adamantite init again.`))});var xa=c.make(`init`,ta).pipe(c.withDescription(`Initialize Adamantite in the current directory. Setup flags require --non-interactive; omitted boolean setup flags are disabled`),c.withExamples([{command:`adamantite init --non-interactive --script check`,description:`Configure linting without prompts`},{command:`adamantite init --non-interactive --script check --preset react --editor vscode --typescript --install-extensions --github-actions --agents`,description:`Configure a React project with VS Code, TypeScript, CI, and agent guidance`},{command:`adamantite init --non-interactive --script analyze`,description:`Configure analysis; in a detected monorepo it includes Sherif`}]),c.withHandler(e=>t.gen(function*(){let t=f.cwd(),n=yield*Q;yield*Wi,yield*n.intro(`💠 adamantite init`);let r=yield*(yield*Bn).detectPackageManager(t);if(!r)return yield*new Ie({});if(r.warnings?.length)for(let e of r.warnings)yield*n.log.warning(e);yield*n.log.info(`Detected package manager: ${r.name}`);let i=yield*B(t);if(i&&(yield*n.log.info(`We've detected a monorepo setup in your project.`)),!e.nonInteractive&&s.some([e.scripts.length>0,e.presets.length>0,e.editors.length>0,e.typescript,e.installExtensions,e.githubActions,e.agents,e.overwriteScripts],x.isTruthy))return yield*new A({reason:"Setup flags require `--non-interactive`."});let a=e.nonInteractive?e:yield*ra(t,i),o=yield*qi(a,{nonInteractive:e.nonInteractive,packageManager:r.name}),c=o.scripts,l=o.presets,u=o.editors,d=o.typescript,p=o.installExtensions,m=o.githubActions,h=o.agents,g=c.includes(`check`)||c.includes(`fix`),_=c.includes(`analyze`),v=_&&i,y=yield*R(t),b=x.isNotUndefined(y.devDependencies?.adamantite??y.dependencies?.adamantite)?[]:[`adamantite`];g&&b.push(`${W.name}@${W.version}`,`${hi.name}@${hi.version}`,`${U.name}@${U.version}`,...mi.filter(e=>l.includes(e.preset)).map(e=>`${e.name}@${e.version}`)),v&&b.push(`${H.name}@${H.version}`),_&&b.push(`${V.name}@${V.version}`),yield*da(t,b),g&&(yield*fa(t,U,U.create(t)),yield*fa(t,W,W.create(t,l))),_&&(yield*fa(t,V,V.create(t)));let S=yield*pa(t,c,{nonInteractive:e.nonInteractive,overwriteScripts:o.overwriteScripts});if(h&&(yield*ba(t,r.name,S,i)),d&&(yield*ma(t,i)),l.includes(`effect`)&&(yield*ha(t)),g&&(yield*ga(t)),yield*_a(t,u),p&&(yield*va(u,c)),m){let e=r.name;lt(e)?yield*ya(t,e,c):yield*n.log.warning(`Skipping GitHub Actions setup: \`${e}\` is not a supported package manager for CI workflow generation.`)}yield*n.log.success(`Your project is now configured`),yield*n.outro(`💠 Adamantite initialized successfully!`)}).pipe(t.catchTags({OperationCancelled:()=>t.gen(function*(){yield*(yield*Q).cancel(`You've cancelled the initialization process.`)})})))),Sa=c.make(`prepare`).pipe(c.withDescription("Patch Oxlint and TypeScript for the effect preset. The `prepare` script runs it after each install"),c.withHandler(()=>t.gen(function*(){let e=f.cwd();(yield*Y.detect(e))&&(yield*Y.patch(e,{quiet:!1}))})));const Ca=T.File(`file`,{mustExist:!0}).pipe(T.withDescription(`The JavaScript or TypeScript file to parse`)),wa=c.make(`ast`,{file:Ca}).pipe(c.withDescription(`Print the ESTree-shaped AST that Oxlint rules visit, to find node names for a custom rule`),c.withHandler(({file:e})=>t.gen(function*(){let t=yield*Q,n=yield*N(e),r=de(e,n,{preserveParens:!1});if(r.errors.length>0)return yield*new ke({errors:r.errors.map(e=>e.message),path:e});yield*t.message(JSON.stringify(r.program,null,2))}))),Ta=T.String(`name`).pipe(T.withDescription(`The rule name in kebab-case, such as no-process-env`)),Ea=u.String(`dir`).pipe(u.optional,u.withDescription(`The rules folder, relative to the current directory. Default: ${Fr}. Pass the folder that \`custom({ dir })\` loads, such as a rules folder in a monorepo tooling package`)),Da=c.make(`add`,{dir:Ea,name:Ta}).pipe(c.withDescription(`Write a custom rule stub, and the authoring guidance when the rules folder has none`),c.withHandler(({dir:e,name:n})=>t.gen(function*(){let t=yield*Q,r=yield*w.Path,i=f.cwd(),a=yield*Rr(i,n,d.getOrUndefined(e));yield*t.log.success(`Wrote ${r.relative(i,a.rulePath)}.`),a.agentsPath!==void 0&&(yield*t.log.success(`Wrote ${r.relative(i,a.agentsPath)}.`)),yield*t.log.info("`custom()` from `adamantite/lint/custom` loads the rule. Run `adamantite doctor` to check the wiring.")})));var Oa=c.make(`rule`).pipe(c.withDescription(`Write and inspect custom Oxlint rules`),c.withSubcommands([Da,wa]));const ka=[W,hi,U,H,V];function Aa(e,t){return s.filterMap(ka,n=>{if(t.has(n.name))return v.failVoid;let r=e.devDependencies?.[n.name]??e.dependencies?.[n.name];return r&&st(r)!==n.version?v.succeed({currentVersion:r,name:n.name,targetVersion:n.version}):v.failVoid})}var ja=c.make(`update`).pipe(c.withDescription(`Update Adamantite-managed dependencies and report setup findings`),c.withHandler(()=>t.gen(function*(){let e=f.cwd(),t=yield*Q;yield*t.intro(`💠 adamantite update`);let n=yield*R(e),r=yield*Ci(e,n),i=r.packageActions,a=new Set(i.map(e=>e.package)),o=[...i.map(e=>({currentVersion:e.type===`install_package`?`not installed`:e.currentVersion,name:e.package,targetVersion:e.targetVersion})),...Aa(n,a)];if(o.length>0){yield*t.log.info(`The following dependencies will be updated:`);for(let e of o)yield*t.log.info(` ${e.name}: ${e.currentVersion} → ${e.targetVersion}`);yield*t.withSpinner(()=>Hn(e,o.map(e=>`${e.name}@${e.targetVersion}`)),{failure:`Failed to update dependencies`,start:`Updating dependencies...`,success:`Dependencies updated successfully`}),yield*t.log.success(`Dependencies updated successfully.`),(yield*Y.detect(e))&&(yield*t.withSpinner(()=>Y.patch(e,{quiet:!0}),{failure:"Failed to patch Oxlint and TypeScript. Run `adamantite prepare` to see why.",start:`Patching Oxlint and TypeScript with @effect/tsgo...`,success:`Oxlint and TypeScript patched with @effect/tsgo.`}))}let s=o.length===0?r:yield*Ci(e);for(let e of s.warnings)yield*t.log.warning(e);let c=s.findings;return c.length>0&&(yield*Pi(c),yield*t.log.info("Run `adamantite doctor` to get the combined Markdown repair prompt.")),o.length===0&&c.length===0?(yield*t.log.success(`No changes needed.`),`no-changes`):`success`}).pipe(t.tapError(()=>t.gen(function*(){yield*(yield*Q).outro(`❌ Update failed`)})),t.tap(e=>t.gen(function*(){yield*(yield*Q).outro(e===`no-changes`?`✅ Adamantite is already up to date.`:`✅ Update completed successfully!`)})))));const Ma=[Tn,In,Hi],Na=[Tn,In,Ii,Hi,xa,Sa,Oa,ja],Pa=new Set(Na.map(e=>e.name)),Fa=new Set(Ma.map(e=>e.name)),Ia=c.make(`adamantite`).pipe(c.withDescription(`Opinionated preset package for modern TypeScript applications`),c.withSubcommands(Na)),La=e=>l.mergeAll(o.layer,Qn.layer.pipe(l.provide(o.layer)),Q.layer,ji.layer.pipe(l.provideMerge(e),l.provide(o.layer)),Bn.layer,Mi.layer),Ra=t.fn(`runCli`)(function*(e,n){let[r,i]=s.splitWhere(e,e=>e===`--`),a=s.drop(i,1),o=r.find(e=>Pa.has(e));if(a.length>0&&o!==void 0&&!Fa.has(o))return yield*new Re({command:o});yield*c.runWith(Ia,{version:n})(r).pipe(t.provideService(Ue,a))}),za=t.gen(function*(){let e=yield*(yield*a.Stdio).args;yield*Ra(e,`0.45.0`)}).pipe(t.as(0),t.catchTag(`CommandFailed`,e=>t.succeed(e.exitCode)),t.catch(e=>t.service(Q).pipe(t.flatMap(t=>t.log.error(e.message)),t.as(r.ExitCode(1)))),t.provide(La(j.layer)));e.runMain(za,{teardown:(e,t)=>{n.isSuccess(e)?t(Number(e.value)):i.defaultTeardown(e,t)}});export{};
674
+ `;return yield*S(n,`${r}${c}${s}`),`updated`}),Cc=(e,t)=>T.gen(function*(){yield*(yield*$).withSpinner(()=>Jr(e,t),{failure:`Failed to install dependencies.`,start:`Installing dependencies...`,success:`Dependencies installed.`})});function wc(e,t,n){return T.gen(function*(){let r=yield*$,i=yield*r.withSpinner(i=>T.gen(function*(){let a=yield*t.detect(e);for(let e of a.warnings)yield*r.log.warning(e);return a.active instanceof Ft?(yield*i.message(`\`${t.config}\` not found, creating...`),yield*n):yield*i.message(`Found \`${a.active.file.file}\`, keeping it.`),a.active}),{failure:`Failed to set up ${t.name} config.`,start:`Setting up ${t.name} config...`,success:e=>e instanceof Ft?`${t.name} config created.`:`Existing ${t.name} config kept.`});i instanceof Lt&&(yield*r.log.info(`Legacy \`${i.file.file}\` was kept during \`adamantite init\`. Run \`adamantite doctor\` for instructions to migrate to the current ${t.name} config.`))})}const Tc=(e,n,r)=>T.gen(function*(){let i=yield*$,a=yield*u(e);if(n.length===0)return t(a);let o=r.overwriteScripts?[]:Ae(a,n),s=new Set(o.map(e=>e.script)),c=n.filter(e=>!s.has(e));yield*i.withSpinner(()=>T.gen(function*(){if(c.length!==0){a.scripts??={};for(let e of c)a.scripts[e]=Ze[e];yield*p(e,a)}}),{failure:"Failed to add scripts to `package.json`.",start:"Adding scripts to your `package.json`...",success:o.length===0?"Scripts added to `package.json`.":c.length===0?"Existing `package.json` scripts kept.":"Scripts added to `package.json`. Existing conflicting scripts were kept."});let l=r.nonInteractive?"Use `--overwrite-scripts` to replace it.":"Run `adamantite init` again and choose to replace the script.";for(let e of o)yield*i.log.warning(`Kept existing \`${e.script}\` script (\`${e.command}\`) instead of \`${Ze[e.script]}\`. ${l}`);return o.length>0&&(yield*i.log.info("Pass custom tool arguments after `--`, such as `adamantite analyze -- --directory packages/app`.")),t(a)}),Ec=(e,t,n)=>T.gen(function*(){let r=yield*$;t?yield*L(Sa(n),T.forEach(e=>r.log.info(e))):yield*r.withSpinner(t=>T.gen(function*(){return(yield*Aa.detect(e))?(yield*t.message(`\`${Aa.config}\` found, updating...`),yield*Aa.update(e,n),!1):(yield*t.message(`\`${Aa.config}\` not found, creating...`),yield*Aa.create(e,n),!0)}),{failure:`Failed to set up TypeScript config.`,start:`Setting up TypeScript config...`,success:e=>`\`${Aa.config}\` ${e?`created`:`updated`} with \`${Q[n]}\`.`})}),Dc=e=>T.gen(function*(){let t=yield*$,n=yield*ze.update(e);n===`monorepo`&&(yield*t.log.info("In a monorepo, add the Effect language service entry to each package's `tsconfig.json` or to a shared base config. Run `adamantite doctor` for the reference entry.")),n===`missing`&&(yield*t.log.warning("No `tsconfig.json` found, so the Effect language service is not configured. Run `adamantite doctor` for the reference entry."))}),Oc={vscode:{integration:Ui,name:`VS Code`},zed:{integration:$i,name:`Zed`}},kc=(e,t)=>T.gen(function*(){let n=yield*$;for(let r of Js.filter(e=>t.includes(e))){let{integration:t,name:i}=Oc[r];yield*n.withSpinner(n=>T.gen(function*(){let r=yield*t.detect(e);return yield*n.message(`\`${t.config}\` ${r?`found, updating`:`not found, creating`}...`),yield*r?t.update(e):t.create(e),!r}),{failure:`Failed to set up ${i} config.`,start:`Checking for \`${t.config}\`...`,success:e=>`\`${t.config}\` ${e?`created`:`updated`} with Adamantite preset.`})}}),Ac=(e,t,n=[])=>T.gen(function*(){let r=yield*$,i=e.includes(`zed`),a=e.includes(`vscode`);yield*r.withSpinner(e=>T.gen(function*(){return a&&(yield*e.message(`Installing VS Code extension...`),yield*Ui.extension(t,n)),!0}),{failure:`Failed to install editor extensions.`,start:`Installing editor extensions...`,success:i&&!a?`Install the Zed extensions using the links below.`:`Editor extensions installed.`}).pipe(T.catchTags({FailedToInstallExtension:e=>T.gen(function*(){return yield*r.log.warning(`⚠️ ${e.message}`),yield*r.log.warning(`Install the extension manually after setup finishes.`),!1}),VscodeCliNotFound:()=>T.gen(function*(){return yield*r.log.error("VS Code's `code` command was not found on PATH."),yield*r.log.info(`Add the code command to PATH:`),yield*r.log.info(` 1. Open VS Code`),yield*r.log.info(` 2. Press Cmd+Shift+P (macOS) or Ctrl+Shift+P (Windows/Linux)`),yield*r.log.info(` 3. Run 'Shell Command: Install "code" command in PATH'`),!1})})),i&&(yield*r.log.info("Install the Zed `oxc` extension: zed://extension/oxc"),n.includes(`effect`)&&(yield*r.log.info(`Install the Zed TypeScript language server extension: zed://extension/tsgo`)))}),jc=(e,t,n)=>T.gen(function*(){let r=yield*$;if(!Gr(n))return yield*r.log.warning("No CI script runs an Adamantite command, so `adamantite init` did not set up the GitHub Actions workflow.");let i=yield*Mi.detect(e),a=yield*r.withSpinner(r=>{let a=({path:i})=>r.message(`\`${i}\` found, updating...`).pipe(T.andThen(Mi.update(e,{packageManager:t,scripts:n})));return St.valueTags(i,{Legacy:a,Malformed:()=>T.succeed(`kept`),Managed:a,Missing:()=>r.message(`Creating \`${Mi.files[0].path}\`...`).pipe(T.andThen(Mi.create(e,{packageManager:t,scripts:n})),T.as(`created`))})},{failure:`Failed to set up GitHub Actions workflow.`,start:`Setting up GitHub Actions workflow...`,success:e=>`GitHub Actions workflow ${e}.`}),o=e=>a===`kept`?r.log.info(`\`${e}\` has changes that Adamantite did not make, so \`adamantite init\` kept it. Run \`adamantite doctor\` to see what to update.`):T.void;yield*St.valueTags(i,{Legacy:({path:e})=>o(e),Malformed:({paths:e,reason:t})=>r.log.warning(`Adamantite cannot read the managed block in ${e.map(e=>`\`${e}\``).join(`, `)}, so \`adamantite init\` kept the workflow. ${t} Run \`adamantite doctor\` for the repair.`),Managed:({path:e})=>o(e),Missing:()=>T.void})}).pipe(T.catchTag([`FailedToCreateDirectory`,`FailedToParseFile`,`FailedToReadFile`,`FailedToWriteFile`],e=>T.gen(function*(){let t=yield*$;yield*t.log.warning(`Could not set up the GitHub Actions workflow. ${e.message}`),yield*t.log.warning("Fix the reported problem and run `adamantite init` again, or create the workflow manually.")}))),Mc=(e,t,n,r)=>T.gen(function*(){let i=yield*$,a=yield*i.withSpinner(()=>Sc(e,{isMonorepo:r,packageManager:t,scripts:n}),{failure:`Failed to update AGENTS.md.`,start:`Updating AGENTS.md...`,success:`AGENTS.md check complete.`}).pipe(T.catchTag([`FailedToReadFile`,`FailedToWriteFile`],e=>T.gen(function*(){return yield*i.log.warning(`Could not update AGENTS.md. ${e.message} Adamantite will continue initialization.`),`failed`})));a!==`failed`&&a===`malformed`&&(yield*i.log.warning("AGENTS.md has an incomplete ADAMANTITE marker. Remove the incomplete marker and run `adamantite init` again."))}),Nc=new Intl.ListFormat(`en`,{type:`conjunction`}),Pc=e=>T.gen(function*(){let t=yield*$;yield*dc(e).pipe(T.flatMap(n=>t.withSpinner(()=>gc(e,n),{failure:`Failed to add the Adamantite skill.`,start:`Adding the Adamantite skill...`,success:`Adamantite skill added to ${Nc.format(n.map(e=>`\`${e}\``))}.`})),T.catchTag([`FailedToCreateDirectory`,`FailedToReadFile`,`FailedToWriteFile`],e=>t.log.warning(`Could not add the Adamantite skill. ${e.message} Adamantite will continue initialization.`)))});var Fc=O.make(`init`,ic).pipe(O.withDescription(`Configure Adamantite in the current directory. Use --non-interactive with setup flags and select each optional feature explicitly`),O.withExamples([{command:`adamantite init --non-interactive --script check`,description:`Configure linting without prompts`},{command:`adamantite init --non-interactive --script check --preset react --editor vscode --typescript typescript --install-extensions --github-actions --agents`,description:`Configure a React project with VS Code, TypeScript, CI, agent guidance, and the Adamantite skill`},{command:`adamantite init --non-interactive --script analyze`,description:`Configure analysis, including Sherif checks for a monorepo`}]),O.withHandler(e=>T.gen(function*(){let t=A.cwd(),n=yield*$;yield*qs,yield*n.intro(`💠 adamantite init`);let r=yield*(yield*Kr).detectPackageManager(t);if(!r)return yield*new me({});if(r.warnings?.length)for(let e of r.warnings)yield*n.log.warning(e);yield*n.log.info(`Detected package manager: ${r.name}`);let i=yield*$e(t);if(i&&(yield*n.log.info(`This project is a monorepo.`)),!e.nonInteractive&&D.some([e.scripts.length>0,e.presets.length>0,e.editors.length>0,M.isSome(e.typescript),e.installExtensions,e.githubActions,e.agents,e.overwriteScripts],F.isTruthy))return yield*new Ce({reason:"Setup flags require `--non-interactive`."});if(e.nonInteractive&&e.scripts.length===0&&M.isNone(e.typescript))return yield*new Ce({reason:"Select at least one script with `--script <name>`, or a TypeScript preset with `--typescript <preset>`."});let a=e.nonInteractive?e:yield*sc(t,i,r.name),o=yield*Xs(a,r.name);if(o.scripts.length===0&&M.isNone(o.typescript)&&M.isNone(o.editors)&&!o.agents){yield*n.outro(`💠 No setup selected, so Adamantite made no changes.`);return}let s=[...o.scripts],{lint:c}=o,l=M.match(c,{onNone:()=>[],onSome:e=>e.presets}),d=y(s,`knip`),f=y(s,`sherif`)&&i,p=yield*u(t),m=F.isNotUndefined(p.devDependencies?.adamantite??p.dependencies?.adamantite)?[]:[`adamantite`];M.isSome(c)&&m.push(`${br.name}@${br.version}`,`${_a.name}@${_a.version}`,`${or.name}@${or.version}`,...ha.filter(e=>l.includes(e.preset)).map(e=>`${e.name}@${e.version}`)),f&&m.push(`${Sr.name}@${Sr.version}`),d&&m.push(`${tr.name}@${tr.version}`),yield*Cc(t,m),M.isSome(c)&&(yield*wc(t,or,or.create(t)),yield*wc(t,br,br.create(t,l))),d&&(yield*wc(t,tr,tr.create(t)));let h=yield*Tc(t,s,{nonInteractive:e.nonInteractive,overwriteScripts:o.overwriteScripts});if(o.agents&&(yield*Mc(t,r.name,h,i),yield*Pc(t)),M.isSome(o.typescript)&&(yield*Ec(t,i,o.typescript.value)),l.includes(`effect`)&&(yield*Dc(t)),M.isSome(o.editors)){let{installExtensions:e,names:n}=o.editors.value;yield*kc(t,n),e&&(yield*Ac(n,s,l))}M.isSome(o.githubActions)&&(yield*jc(t,o.githubActions.value,h)),yield*n.outro(`💠 Setup finished.`)}).pipe(T.catchTags({OperationCancelled:()=>T.gen(function*(){yield*(yield*$).cancel(`Setup was cancelled.`)})}))));const Ic=/^[a-z][\da-z]*(?:-[\da-z]+)*$/;function Lc(e){return`import { defineRule } from "adamantite/rules/plugin"
675
+
676
+ export default defineRule({
677
+ createOnce(context) {
678
+ return {
679
+ // Run \`adamantite rule ast <file>\` to find the node types to visit.
680
+ DebuggerStatement(node) {
681
+ context.report({ messageId: "unexpected", node })
682
+ },
683
+ }
684
+ },
685
+ meta: {
686
+ docs: { description: "TODO: describe what {{name}} reports." },
687
+ messages: { unexpected: "TODO: tell the author what to do instead." },
688
+ schema: [],
689
+ type: "problem",
690
+ },
691
+ })
692
+ `.replaceAll(`{{name}}`,e)}const Rc=T.fn(`addCustomRule`)(function*(e,t,n=q){if(!Ic.test(t))return yield*new de({rule:t});let r=yield*P.Path,i=r.resolve(e,n),a=r.join(i,`${t}.ts`),o=(yield*zc(e,n)).filter(e=>e.slice(0,-r.extname(e).length)===t);return o.length>0?yield*new Ue({paths:o.map(e=>r.join(i,e))}):(yield*x(i),yield*S(a,Lc(t)),a)}),zc=T.fn(`listCustomRules`)(function*(e,t=q){let n=yield*P.Path,r=yield*R.FileSystem,i=n.resolve(e,t),a=yield*rt(i),o=yield*T.filter(M.getOrElse(a,()=>[]).filter(e=>Qt(e)),e=>r.stat(n.join(i,e)).pipe(T.mapBoth({onFailure:t=>new Ye({cause:t,path:n.join(i,e)}),onSuccess:e=>e.type===`File`})));return D.sort(o,B.String)}),Bc=T.fn(`addCustomRuleTest`)(function*(e,t,n=q,r){if(!Ic.test(t))return yield*new de({rule:t});let i=yield*P.Path,a=yield*R.FileSystem,o=i.resolve(e,n),s=(yield*zc(e,n)).find(e=>e.slice(0,-i.extname(e).length)===t);if(s===void 0)return yield*new De({directory:o,rule:t});let c=r===void 0?i.join(o,`${t}.test.ts`):i.resolve(e,r);if(yield*a.exists(c).pipe(T.mapError(e=>new Ye({cause:e,path:c}))))return yield*new Ue({paths:[c]});yield*x(i.dirname(c));let l=e=>a.realPath(e).pipe(T.mapError(t=>new Ye({cause:t,path:e}))),[u,d]=yield*T.all([l(i.dirname(c)),l(i.join(o,s))]),f=i.relative(u,d).split(i.sep).join(`/`),p=f.startsWith(`../`)?f:`./${f}`,m=yield*ce(p);return yield*S(c,`import { RuleTester } from "adamantite/rules/testing"
693
+ import rule from {{ruleImport}}
694
+
695
+ const tester = new RuleTester({ languageOptions: { parserOptions: { lang: "ts" } } })
696
+
697
+ // Replace these cases with valid and invalid code for this rule.
698
+ // oxlint-disable-next-line vitest/require-hook, jest/require-hook -- RuleTester registers its node:test suites here.
699
+ tester.run("{{name}}", rule, {
700
+ invalid: [{ code: "debugger", errors: [{ messageId: "unexpected" }] }],
701
+ valid: ["const value: number = 1"],
702
+ })
703
+ `.replaceAll(`{{name}}`,t).replace(`{{ruleImport}}`,m)),c}),Vc=T.fn(`findCustomRuleTests`)(function*(e){let t=yield*P.Path,n=D.dedupe(e.calls.map(e=>e.dir)),r=yield*T.forEach(n,e=>rt(e).pipe(T.map(n=>M.getOrElse(n,()=>[]).filter(e=>$t(e)).map(n=>t.join(e,n)))),{concurrency:`unbounded`});return D.sort(r.flat(),B.String)}),Hc=T.fn(`readCustomRuleTestCommand`)(function*({customRules:e,cwd:t}){let n=yield*P.Path,r=yield*Vc(e);return{command:r.length===0?M.none():M.some({args:[`--test`,...r.map(e=>n.relative(t,e))],command:`node`}),unresolvedCalls:D.dedupe(e.unresolvedCalls),unresolvedImports:e.unresolvedImports}}),Uc=V.File(`file`,{mustExist:!0}).pipe(V.withDescription(`The JavaScript or TypeScript file to parse`)),Wc=O.make(`ast`,{file:Uc}).pipe(O.withDescription(`Print the syntax tree Oxlint rules use, with node names for custom rules`),O.withHandler(({file:e})=>T.gen(function*(){let t=yield*$,n=yield*r(e),i=bt(e,n,{preserveParens:!1});if(i.errors.length>0)return yield*new ge({errors:i.errors.map(e=>e.message),path:e});yield*t.message(yield*Ve(i.program))}))),Gc=V.String(`name`).pipe(V.withDescription(`The rule name in kebab-case, such as no-process-env`)),Kc=j.String(`dir`).pipe(j.optional,j.withDescription(`The rules folder, relative to the current directory. Default: ${q}. Pass the folder that \`custom({ dir })\` loads, such as a rules folder in a monorepo tooling package`)),qc=j.String(`path`).pipe(j.optional,j.withDescription(`The test file path, relative to the current directory`)),Jc=O.make(`add`,{dir:Kc,name:Gc}).pipe(O.withDescription(`Create a custom rule file. See the Adamantite skill for authoring instructions`),O.withHandler(({dir:e,name:t})=>T.gen(function*(){let n=yield*$,r=yield*P.Path,i=A.cwd(),a=yield*Rc(i,t,M.getOrUndefined(e));yield*n.log.success(`Wrote ${r.relative(i,a)}.`),yield*n.log.info(`\`custom()\` from \`adamantite/rules\` loads the rule. Run \`adamantite doctor\` to check the wiring. The "${ms}" section of the Adamantite skill tells agents how to verify the rule with temporary cases.`)}))),Yc=O.make(`add`,{dir:Kc,name:Gc.pipe(V.optional),path:qc}).pipe(O.withDescription(`Create a test for an existing rule. Omit the name to choose a rule`),O.withHandler(({dir:e,name:t,path:n})=>T.gen(function*(){let r=yield*$,i=yield*P.Path,a=yield*La,o=M.getOrElse(e,()=>q),s=A.cwd(),c=M.getOrUndefined(t);if(c===void 0){let e=(yield*zc(s,o)).map(e=>e.slice(0,-i.extname(e).length));if(e.length===0)return yield*r.log.info(`No custom rules were found in \`${o}\`. Run \`adamantite rule add <name>\` first.`);if(!(yield*a.isInteractive))return yield*r.message(e.join(`
704
+ `)),yield*r.log.info("Pass a rule name with `adamantite rule test add <name>`.");c=yield*r.select({message:`Which rule needs a test?`,options:e.map(e=>({label:e,value:e}))})}let l=yield*Bc(s,c,o,M.getOrUndefined(n));yield*r.log.success(`Wrote ${i.relative(s,l)}.`),yield*r.log.info(`Adapt the valid and invalid cases to the rule, then run \`adamantite rule test\`${M.isSome(n)?" with `--path` and the test file path.":`.`}`),yield*r.log.info(`RuleTester uses node:test. Exclude this test from Vitest and Jest discovery. See Custom rules in the Adamantite README.`)}))),Xc=O.make(`test`,{path:qc}).pipe(O.withDescription(`Run custom rule tests with node --test. Use --path for a test outside the rules folder`),O.withHandler(({path:e})=>T.gen(function*(){let t=yield*$,n=yield*P.Path,r=yield*Pt,i=A.cwd();if(M.isSome(e))return yield*r.run({args:[`--test`,n.resolve(i,e.value)],command:`node`,title:`🧪 Testing custom rules`});let{command:a,unresolvedCalls:o,unresolvedImports:s}=yield*Hc(yield*Ia(i));for(let e of o)yield*t.log.warning(`\`rule test\` cannot read the \`dir\` of a \`custom()\` call in \`${n.relative(i,e)}\`, because it is not a string literal. It does not run the tests of that rules folder.`);for(let{from:e,specifier:r}of s)yield*t.log.warning(`\`rule test\` cannot resolve the import of \`${r}\` in \`${n.relative(i,e)}\`, so it does not run the tests of the rules folders behind it.`);if(M.isNone(a))return yield*t.log.info("No tests were found for loaded custom rules. Run `adamantite doctor` to check rule setup, or `adamantite rule test add` to add a test.");yield*r.run({...a.value,title:`🧪 Testing custom rules`})})),O.withSubcommands([Yc])),Zc=V.String(`rule`).pipe(V.withDescription(`The full rule name, such as no-restricted-imports, typescript/no-explicit-any, or project/no-foo`)),Qc=j.String(`report`).pipe(j.atLeast(1),j.withDescription(`Add a case the rule must report. Use a project path, or <path>=<file> to lint file contents at another path. Repeat --report for more cases`)),$c=j.String(`accept`).pipe(j.atLeast(0),j.withDescription(`Add a case the rule must accept, using the same path format as --report`)),el=j.String(`options`).pipe(j.withSchema(z.fromJsonString(z.Array(z.Json))),j.optional,j.withDescription(`The rule options that come after the severity, as a JSON array, such as '[{"paths":["node:fs"]}]'. The trial sets the rule to error`)),tl=j.Boolean(`current`).pipe(j.withDefault(!1),j.withDescription(`Use the project's current rule setting to see what it reports`));function nl(e,t){return t instanceof qo?`\`${e}\` as the project config sets it`:`\`${e}\` at ${JSON.stringify([`error`,...t.options])}`}function rl(e){return e.diagnostics.length>0==(e.case.expected===`reported`)}function il(e,t,n){let r=[...new Set(n.map(e=>`\`${e.config}\``))].join(`, `),i=n.map(e=>{let t=M.match(e.case.source,{onNone:()=>`\`${e.case.path}\``,onSome:t=>`\`${e.case.path}\` from \`${t}\``}),n=e.diagnostics.length>0?`reported`:`accepted`;return[rl(e)?`✓ ${t}: ${n}, as expected.`:`✗ ${t}: ${n}, but it must be ${e.case.expected}.`,...e.diagnostics.map(e=>` ${e.line}:${e.column} ${e.message}`)].join(`
705
+ `)}),a=n.filter(e=>!rl(e)).length,o=a===0?`All cases produced the expected result.`:n.length===1?`The case did not produce the expected result.`:`${a.toLocaleString(`en-US`)} of ${n.length.toLocaleString(`en-US`)} cases ${a===1?`is`:`are`} different from the expected result.`;return[`Trial of ${nl(e,t)}, in ${r}.`,``,...i,``,o].join(`
706
+ `)}const al=O.make(`try`,{accept:$c,current:tl,options:el,report:Qc,rule:Zc}).pipe(O.withDescription(`Test a rule against cases in a project copy. Exit codes: 0 for expected results, 1 for a mismatch, and 2 if a case could not be checked. Project files stay unchanged`),O.withHandler(({accept:e,current:t,options:n,report:r,rule:i})=>T.gen(function*(){let a=yield*$,o=t?new qo:new Jo({options:M.getOrElse(n,()=>[])}),s=yield*T.gen(function*(){if(t&&M.isSome(n))return yield*new nt({reason:"Give `--options` or `--current`, not both."});let a=yield*T.all([...r.map(e=>Yo(e,`reported`)),...e.map(e=>Yo(e,`accepted`))]),s=A.cwd();return yield*rs({cases:a,cwd:s,rule:i,setting:o,workspace:yield*re(s)})}).pipe(T.catch(e=>a.log.error(e.message).pipe(T.andThen(T.fail(new Le({command:`rule try`,exitCode:E.ExitCode(2)}))))));if(yield*a.message(il(i,o,s)),!s.every(e=>rl(e)))return yield*new Le({command:`rule try`,exitCode:E.ExitCode(1)})})));var ol=O.make(`rule`).pipe(O.withDescription(`Create and inspect custom Oxlint rules, try them against cases, and run saved tests`),O.withSubcommands([Jc,Wc,Xc,al]));const sl=[br,_a,or,Sr,tr];var cl=O.make(`update`).pipe(O.withDescription(`Update managed packages and the Adamantite skill, then report setup issues`),O.withHandler(()=>T.gen(function*(){let e=A.cwd(),t=yield*$;yield*t.intro(`💠 adamantite update`);let n=yield*Ia(e),r=yield*Ma(n),i=r.packageActions,a=new Set(i.map(e=>e.package)),o=sl.flatMap(e=>a.has(e.name)?[]:[Wt(n,e,`Adamantite`,`adamantite`)]),s=[...i,...o.flatMap(e=>e.packageActions).filter(e=>e.type===`update_package`)],c=o.filter(e=>e.packageActions.length===0);if(s.length>0){yield*t.log.info(`Packages to install or update:`);for(let e of s){let n=e.type===`install_package`?`not installed`:e.currentVersion;yield*t.log.info(` ${e.package}: ${n} → ${e.targetVersion}`)}yield*t.withSpinner(()=>Jr(e,s.map(e=>`${e.package}@${e.targetVersion}`)),{failure:`Failed to update dependencies`,start:`Updating dependencies...`,success:`Dependencies updated.`})}let l=s.length===0?`idle`:`applied`,u=yield*hc(e).pipe(T.flatMap(n=>n.length===0?T.succeed(`idle`):t.withSpinner(()=>gc(e,n),{failure:`Failed to refresh the Adamantite skill.`,start:`Refreshing the Adamantite skill...`,success:`Adamantite skill refreshed.`}).pipe(T.as(`applied`),T.catchTag([`FailedToCreateDirectory`,`FailedToReadFile`,`FailedToWriteFile`],e=>t.log.warning(`Could not refresh the Adamantite skill. ${e.message}`).pipe(T.as(`applyFailed`))))),T.catchTag(`FailedToReadFile`,e=>t.log.warning(`Could not check the Adamantite skill. ${e.message}`).pipe(T.as(`checkFailed`)))),d=e=>t.log.warning(`Could not update \`skills-lock.json\`. ${e.message}`),f=yield*_c(e).pipe(T.flatMap(e=>e?t.log.info("Removed the `adamantite` entry from `skills-lock.json`.").pipe(T.as(`applied`)):T.succeed(`idle`)),T.catchTag([`FailedToParseFile`,`FailedToReadFile`],e=>d(e).pipe(T.as(`checkFailed`))),T.catchTag(`FailedToWriteFile`,e=>d(e).pipe(T.as(`applyFailed`)))),p=l===`idle`?r:yield*Ma(yield*Ia(e)),m=new Set(p.findings.map(e=>e.id)),h=D.dedupe([...p.warnings,...c.flatMap(e=>e.warnings)]);for(let e of h)yield*t.log.warning(e);let g=[...p.findings,...c.flatMap(e=>e.findings).filter(e=>!m.has(e.id))];return g.length>0&&(yield*za(g),yield*t.log.info("Run `adamantite doctor` for the remaining repairs and an agent prompt.")),![l,u,f].some(e=>e===`applied`||e===`applyFailed`)&&g.length===0?`no-changes`:`success`}).pipe(T.tapError(()=>T.gen(function*(){yield*(yield*$).outro(`❌ Update failed`)})),T.tap(e=>T.gen(function*(){yield*(yield*$).outro(e===`no-changes`?`✅ No managed updates were applied.`:`✅ Update finished.`)})))));const ll=[kr,Nr,ho],ul=[kr,Nr,so,ho,Gs,Fc,ol,cl],dl=new Set(ul.map(e=>e.name)),fl=new Set(ll.map(e=>e.name)),pl=O.make(`adamantite`).pipe(O.withDescription(`Configure code checks for TypeScript projects`),O.withSubcommands(ul)),ml=e=>k.mergeAll(ct.layer,ai.layer.pipe(k.provide(ct.layer)),Pe.layer,$.layer,Wa.layer.pipe(k.provideMerge(e),k.provide(ct.layer)),Kr.layer,La.layer),hl=T.fn(`runCli`)(function*(e,t){let[n,r]=D.splitWhere(e,e=>e===`--`),i=D.drop(r,1),o=n.find(e=>dl.has(e));if(i.length>0&&o!==void 0&&!fl.has(o))return yield*new a({command:o});yield*O.runWith(pl,{version:t})(n).pipe(T.provideService(At,i))}),gl=T.gen(function*(){let e=yield*(yield*st.Stdio).args;yield*hl(e,`0.47.0`)}).pipe(T.as(0),T.catchTag(`CommandFailed`,e=>T.succeed(e.exitCode)),T.catch(e=>T.service($).pipe(T.flatMap(t=>t.log.error(e.message)),T.as(E.ExitCode(1)))),T.provide(ml(Pt.layer)));it.runMain(gl,{teardown:(e,t)=>{at.isSuccess(e)?t(Number(e.value)):ot.defaultTeardown(e,t)}});export{};