ipal-doctor: one command that checks a site against the team rules

bin ipal-doctor + @intecion/ipal-kit/doctor: static rules (versions, Node 22, AGENT.md §3
layout and naming, database names, env rules, headers, X-Powered-By, CSP, 2FA, cookie
scanner, adminMeta, AGENTS.md, skills, seeds, block library via blockLibraryManifest,
ipal-audit --quick), registry rules (latest plugin, pnpm audit --prod), live rules (--url,
ipal-seo-check), deep rules (--deep via payload run; GET /api/ipal/doctor, off until
IPAL_DOCTOR_TOKEN). Human / JSON output, --strict, exit codes 0/1/2/3, --sites drift table,
ipal-doctor.json with reasons, until, files, seen.

Fixes found on the way: sitemap leaves out the System pages 404 page; ipal-audit finds
array labels after fields, any form seed, runs grep in UTF-8; ipal-seo-check counts
duplicate titles per language. Reference site at zero findings (static), CI steps on.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-29 16:03:00 +01:00
co-authored by Claude Opus 5.5
parent 0ab133fbd7
commit a4e8cfeae8
62 changed files with 2998 additions and 70 deletions
+85
View File
@@ -0,0 +1,85 @@
import { createHash } from 'node:crypto'
import { readdirSync, readFileSync, statSync } from 'node:fs'
import { join } from 'node:path'
import type { DoctorRule, RuleFinding } from '../types.js'
/** Content hash of a folder (names + bytes), so two copies of a skill compare equal. */
export function hashDir(dir: string): string {
const hash = createHash('sha256')
const walk = (d: string, prefix: string) => {
for (const name of readdirSync(d).sort()) {
if (name === '.DS_Store') {continue}
const path = join(d, name)
if (statSync(path).isDirectory()) {walk(path, `${prefix}${name}/`)}
else {hash.update(`${prefix}${name}\0`).update(readFileSync(path))}
}
}
walk(dir, '')
return hash.digest('hex')
}
/** What `ipal-skills` would change in a skills folder: missing, stale (different content) and retired skills. */
export function planSkills({ dest, source }: { dest: string; source: string }): { missing: string[]; retired: string[]; stale: string[] } {
const ls = (d: string) => {
try {
return readdirSync(d).filter((n) => n.startsWith('ipal-') && statSync(join(d, n)).isDirectory())
} catch {
return []
}
}
const shipped = ls(source)
const have = ls(dest)
return {
missing: shipped.filter((n) => !have.includes(n)),
retired: have.filter((n) => !shipped.includes(n)),
stale: shipped.filter((n) => have.includes(n) && hashDir(join(dest, n)) !== hashDir(join(source, n))),
}
}
export const agentRules: DoctorRule[] = [
{
id: 'agents-md',
check: (ctx) => {
const agents = ctx.read('AGENTS.md')
if (!agents) {return [{ fix: 'AGENT.md §13 template, then pnpm exec ipal-skills', message: 'no AGENTS.md', severity: 'error' }]}
const out: RuleFinding[] = []
const parts = agents.split(/^## Project decisions[ \t]*$/m)
if (parts.length < 2) {out.push({ file: 'AGENTS.md', fix: 'add "## Project decisions" with the architecture answers (AGENT.md "Ask before you build")', message: 'AGENTS.md has no "## Project decisions" section', severity: 'error' })}
else {
const body = parts[1].split(/^## /m)[0].replace(/<!--[\s\S]*?-->/g, '')
if (!/^\s*[-*] +\S/m.test(body)) {out.push({ file: 'AGENTS.md', message: '"## Project decisions" is empty', severity: 'warning' })}
}
const pointer = agents.match(/<!-- ipal-kit:start -->[\s\S]*?## ipal-kit ([\w.-]+) — agent guide[\s\S]*?<!-- ipal-kit:end -->/)
if (!pointer) {out.push({ file: 'AGENTS.md', fix: 'pnpm exec ipal-skills', message: 'no ipal-kit pointer block in AGENTS.md', severity: 'warning' })}
else if (ctx.pluginVersion && pointer[1] !== ctx.pluginVersion) {out.push({ file: 'AGENTS.md', fix: 'pnpm exec ipal-skills', message: `the pointer block names ipal-kit ${pointer[1]}, installed ${ctx.pluginVersion}`, severity: 'warning' })}
const claude = ctx.read('CLAUDE.md')
if (!claude) {out.push({ fix: 'pnpm exec ipal-skills (creates CLAUDE.md with @AGENTS.md)', message: 'no CLAUDE.md', severity: 'warning' })}
else if (!/^@AGENTS\.md\s*$/m.test(claude) && !claude.includes('<!-- ipal-kit:start -->')) {out.push({ file: 'CLAUDE.md', fix: 'add a line @AGENTS.md', message: 'CLAUDE.md neither imports AGENTS.md nor has the pointer block', severity: 'warning' })}
return out
},
docs: 'docs/agent/AGENT.md#13-agentsmd-template-for-a-project',
group: 'agents',
source: 'static',
},
{
id: 'skills-current',
check: (ctx) => {
const dest = ['.agents/skills', '.claude/skills'].find((d) => ctx.list(d).some((n) => n.startsWith('ipal-')))
if (!dest) {return [{ fix: 'pnpm exec ipal-skills', message: 'no ipal-* skills in .agents/skills or .claude/skills', severity: 'error' }]}
// Compare with the skills the project's installed plugin ships (what `pnpm exec ipal-skills` copies).
const installedSkills = join(ctx.root, 'node_modules/@intecion/ipal-kit/docs/agent/skills')
const source = ctx.exists('node_modules/@intecion/ipal-kit/docs/agent/skills') ? installedSkills : join(ctx.packageRoot, 'docs/agent/skills')
const plan = planSkills({ dest: join(ctx.root, dest), source })
const parts = [
plan.stale.length ? `${plan.stale.length} outdated (${plan.stale.join(', ')})` : '',
plan.missing.length ? `missing ${plan.missing.join(', ')}` : '',
plan.retired.length ? `retired ${plan.retired.join(', ')}` : '',
].filter(Boolean)
return parts.length ? [{ file: dest, fix: 'pnpm exec ipal-skills and commit', message: `skills differ from the installed ipal-kit: ${parts.join('; ')}`, severity: 'warning' }] : []
},
docs: 'docs/agent/AGENT.md#14-skills-antigravity-claude-code-cursor',
group: 'agents',
source: 'static',
},
]
+137
View File
@@ -0,0 +1,137 @@
import type { DoctorContext } from '../project.js'
import type { DoctorRule, RuleFinding } from '../types.js'
import { stripComments } from '../util.js'
import { usesBlockRegistry } from './layout.js'
type Manifest = { blocks: Array<{ interfaceName: string; slug: string }>; fieldBuilders: string[]; primitives: string[] }
/** The five primitives a project without the library registry writes itself (AGENT.md §6.3). */
const OWN_PRIMITIVES = ['Section', 'SectionHeader', 'Media', 'CMSLink', 'Button']
/** Helpers the plugin exports that projects used to copy (not field builders, so not in the manifest). */
const OTHER_HELPERS = ['ctaHref', 'buildActionButtonsField']
let manifest: Manifest | null | undefined
/** blockLibraryManifest from the plugin (plain data); null when it cannot be loaded. */
export async function loadBlockManifest(): Promise<Manifest | null> {
if (manifest !== undefined) {return manifest}
try {
manifest = (await import('../../block-library/manifest.js')).blockLibraryManifest as Manifest
} catch {
manifest = null
}
return manifest
}
/** Every .ts/.tsx file under a project folder (relative paths). */
export function sourceFiles(ctx: DoctorContext, dir: string): string[] {
return ctx.list(dir).flatMap((name) => {
const path = `${dir}/${name}`
if (/\.tsx?$/.test(name)) {return [path]}
if (name.includes('.') || name === 'node_modules') {return []}
return sourceFiles(ctx, path)
})
}
const registry = (ctx: DoctorContext) => stripComments(ctx.read(`${ctx.src}blocks/registry.ts`))
/** Keys of an object literal passed as `<option>: { … }` in the registry (`ui`, `components`). */
function optionKeys(code: string, option: string): string[] {
const body = code.match(new RegExp(`\\b${option}\\s*:\\s*\\{([^}]*)\\}`))?.[1] ?? ''
return [...body.matchAll(/(?:^|[,{\s])([A-Z_$][\w$]*)\s*(?=[:,}]|$)/gi)].map((m) => m[1])
}
export const blockRules: DoctorRule[] = [
{
id: 'blocks-registry',
check: (ctx) => {
const file = `${ctx.src}blocks/registry.ts`
if (!ctx.exists(file)) {return []} // layout-required reports the missing file
const code = registry(ctx)
if (/createBlockRegistry\s*\(/.test(code) || /RenderBlocks/.test(code)) {return []}
return [{ file, fix: 'export const blockRegistry = createBlockRegistry(content, { … }) from @intecion/ipal-kit/blocks/rsc', message: 'blocks/registry.ts uses neither createBlockRegistry nor RenderBlocks', severity: 'error' }]
},
docs: 'docs/blocks.md',
group: 'blocks',
source: 'static',
},
{
id: 'blocks-ui-required',
check: (ctx) => {
if (usesBlockRegistry(ctx)) {return []}
const have = ctx.list(`${ctx.src}components/ui`).map((n) => n.replace(/\.tsx?$/, ''))
const missing = OWN_PRIMITIVES.filter((p) => !have.includes(p))
return missing.length
? [{ fix: 'use createBlockRegistry (primitives from the plugin) or write them (AGENT.md §6.3)', message: `without createBlockRegistry, components/ui/ needs ${missing.join(', ')}`, severity: 'error' }]
: []
},
docs: 'docs/agent/AGENT.md#63-layer-2--ui-primitives',
group: 'blocks',
source: 'static',
},
{
id: 'blocks-ui-override',
check: async (ctx) => {
if (!usesBlockRegistry(ctx)) {return []}
const m = await loadBlockManifest()
const primitives = m?.primitives ?? OWN_PRIMITIVES
const passed = optionKeys(registry(ctx), 'ui')
const own = ctx.list(`${ctx.src}components/ui`).map((n) => n.replace(/\.tsx?$/, '')).filter((n) => primitives.includes(n))
const loose = own.filter((n) => !passed.includes(n))
return loose.length
? [{ file: `${ctx.src}blocks/registry.ts`, fix: `createBlockRegistry(content, { ui: { ${loose.join(', ')} } })`, message: `components/ui/ overrides ${loose.join(', ')} but the registry does not pass them — library blocks keep the plugin's look`, severity: 'warning' }]
: []
},
docs: 'docs/blocks.md',
group: 'blocks',
source: 'static',
},
{
id: 'blocks-duplicate',
check: async (ctx) => {
const m = await loadBlockManifest()
if (!m) {return []}
const out: RuleFinding[] = []
const code = sourceFiles(ctx, `${ctx.src.replace(/\/$/, '') || '.'}`)
.filter((f) => !f.includes('payload-types'))
.map((f) => stripComments(ctx.read(f)))
.join('\n')
// A library block renamed through its slug option (testimonials → reviews) is still the library block.
const renamed = [...code.matchAll(/build\w+Block\s*\(\s*\{[^}]*\bslug\s*:\s*['"]([\w-]+)['"]/g)].map((x) => x[1])
const librarySlugs = new Set([...m.blocks.map((b) => b.slug), ...renamed])
const libraryInterfaces = new Set(m.blocks.map((b) => b.interfaceName).filter(Boolean))
const overrides = new Set(optionKeys(registry(ctx), 'components'))
for (const folder of ctx.list(`${ctx.src}blocks`).filter((n) => !n.includes('.'))) {
const file = `${ctx.src}blocks/${folder}/config.ts`
const config = stripComments(ctx.read(file))
const slug = config.match(/\bslug\s*:\s*['"]([\w-]+)['"]/)?.[1]
const iface = config.match(/\binterfaceName\s*:\s*['"](\w+)['"]/)?.[1]
if (!slug) {continue}
if ((librarySlugs.has(slug) || (iface && libraryInterfaces.has(iface))) && !overrides.has(slug)) {
out.push({ file, fix: 'use the library block (+ variant), or eject it (pnpm exec ipal-blocks eject) and pass it in createBlockRegistry({ components })', message: `project block "${slug}" duplicates a library block`, severity: 'warning' })
}
}
return out
},
docs: 'docs/blocks.md',
group: 'blocks',
source: 'static',
},
{
id: 'blocks-helper-copy',
check: async (ctx) => {
const m = await loadBlockManifest()
const names = [...(m?.fieldBuilders ?? []), ...OTHER_HELPERS]
const out: RuleFinding[] = []
for (const file of sourceFiles(ctx, ctx.src.replace(/\/$/, '') || '.')) {
const code = stripComments(ctx.read(file))
const copies = names.filter((n) => new RegExp(`(?:function\\s+${n}\\b|(?:const|let)\\s+${n}\\s*=)`).test(code))
if (copies.length) {out.push({ file, fix: `import { ${copies.join(', ')} } from the plugin`, message: `local copy of ${copies.join(', ')}`, severity: 'warning' })}
}
return out
},
docs: 'docs/blocks.md',
group: 'blocks',
source: 'static',
},
]
+105
View File
@@ -0,0 +1,105 @@
import type { DoctorRule, RuleFinding } from '../types.js'
import { databaseNameFromUri, databaseNamesFor } from '../../env/databaseName.js'
import { configFile } from '../project.js'
import { stripComments } from '../util.js'
/** The database name of a URI; also for placeholder URIs (`HOST:PORT`) that `new URL` rejects. */
const dbName = (uri: string | undefined) => databaseNameFromUri(uri) ?? (uri?.match(/^[a-z+]+:\/\/[^/]*\/([^/?#]+)/i)?.[1] ?? null)
/** Placeholder hosts, users or names in .env.example — fine, they carry no secret. */
const PLACEHOLDER = /[<>]|\b(?:HOST|PORT|USER|PASS(?:WORD)?|DATABASE|example)\b|\$\{/i
export const envRules: DoctorRule[] = [
{
id: 'db-name',
check: (ctx) => {
const out: RuleFinding[] = []
if (!ctx.domain) {
return [{ fix: 'add "domain": "<site domain>" to ipal-doctor.json', message: 'no site domain (ipal-doctor.json "domain", or a non-local NEXT_PUBLIC_SERVER_URL) — database names not checked', severity: 'warning' }]
}
const { dev, prod } = databaseNamesFor(ctx.domain)
for (const [file, env] of [['.env', ctx.env.local], ['.env.example', ctx.env.example]] as const) {
if (!env) {continue}
const uri = env.DATABASE_URI
if (!uri) {
if (file === '.env.example') {out.push({ file, fix: `DATABASE_URI=mongodb://USER:PASS@HOST:PORT/${dev}?authSource=admin`, message: `${file} has no DATABASE_URI`, severity: 'warning' })}
continue
}
if (/^file:/i.test(uri)) {
out.push({ file, fix: `a MongoDB database named ${dev}`, message: `${file}: SQLite file — the team standard is a database named ${dev}`, severity: 'warning' })
continue
}
const name = dbName(uri)
if (name === prod) {
out.push({ file, fix: `point it at ${dev}`, message: `${file} points at the production database ${prod} — a local run or seed writes to production`, severity: 'error' })
} else if (name !== dev) {
out.push({ file, fix: `rename the database to ${dev} (production: ${prod}) — deployment.md backup + restore`, message: `${file}: database "${name ?? '(none)'}", expected ${dev}`, severity: 'error' })
}
}
const prodName = ctx.env.prod ? dbName(ctx.env.prod.DATABASE_URI) : undefined
if (ctx.env.prod && prodName !== prod) {out.push({ fix: `name the production database ${prod}`, message: `--env-file: database "${prodName ?? '(none)'}", expected ${prod}`, severity: 'error' })}
return out
},
docs: 'docs/deployment.md',
group: 'env',
source: 'static',
},
{
id: 'env-rules',
check: (ctx) => {
const file = ctx.exists(`${ctx.src}instrumentation.ts`) ? `${ctx.src}instrumentation.ts` : 'instrumentation.ts'
const code = stripComments(ctx.read(file))
if (!/assertEnv\s*\(/.test(code)) {
return [{ file, fix: "register(): assertEnv(ipalEnvRules({ storage: true, ipHeader: true })) from '@intecion/ipal-kit/env'", message: 'instrumentation.ts does not call assertEnv(ipalEnvRules(…))', severity: 'error' }]
}
const out: RuleFinding[] = []
if (!/ipalEnvRules\s*\(/.test(code)) {out.push({ file, message: 'assertEnv without ipalEnvRules — the plugin variables are not checked', severity: 'warning' })}
if (/from\s+['"]@intecion\/ipal-kit['"]/.test(code)) {out.push({ file, fix: "import from '@intecion/ipal-kit/env'", message: 'instrumentation.ts imports the package root (Edge build breaks)', severity: 'error' })}
const cfg = stripComments(ctx.read(configFile(ctx) ?? ''))
const flag = (name: string) => new RegExp(`\\b${name}\\s*:`).test(code)
if (/buildR2Storage/.test(cfg) && !flag('storage')) {out.push({ file, fix: 'ipalEnvRules({ storage: true })', message: 'R2 is wired but ipalEnvRules has no storage flag', severity: 'warning' })}
if (/cookieScanner\s*:\s*\{[^}]*\bcrawl\s*:\s*(?!false)/.test(cfg) && !flag('cookieCrawl')) {out.push({ file, fix: 'ipalEnvRules({ cookieCrawl: true })', message: 'cookieScanner.crawl is on but ipalEnvRules has no cookieCrawl flag', severity: 'warning' })}
if (!flag('ipHeader')) {out.push({ file, fix: 'ipalEnvRules({ ipHeader: true })', message: 'ipalEnvRules has no ipHeader flag — rate limits trust no client-IP header', severity: 'warning' })}
if (!flag('databaseName')) {out.push({ file, fix: "ipalEnvRules({ databaseName: { domain: '<domain>' } })", message: 'ipalEnvRules has no databaseName check', severity: 'info' })}
return out
},
docs: 'docs/env.md',
group: 'env',
source: 'static',
},
{
id: 'env-example',
check: (ctx) => {
if (!ctx.env.example) {return [{ fix: 'add .env.example (names, placeholder values)', message: 'no .env.example', severity: 'error' }]}
const out: RuleFinding[] = []
const cfg = stripComments(ctx.read(configFile(ctx) ?? ''))
const want = ['DATABASE_URI', 'PAYLOAD_SECRET', 'NEXT_PUBLIC_SERVER_URL', 'IPAL_IP_HEADER']
if (/buildR2Storage/.test(cfg) && !ctx.auditSkips.has('r2')) {want.push('R2_BUCKET', 'R2_ENDPOINT', 'R2_ACCESS_KEY_ID', 'R2_SECRET_ACCESS_KEY', 'R2_PUBLIC_URL')}
if (/cookieScanner\s*:\s*\{[^}]*\bcrawl\s*:\s*(?!false)/.test(cfg)) {want.push('IPAL_COOKIE_SCAN_URL', 'IPAL_COOKIE_SCAN_TOKEN')}
const missing = want.filter((v) => !(v in ctx.env.example!))
if (missing.length) {out.push({ file: '.env.example', fix: 'add the names (empty or placeholder values)', message: `.env.example lacks ${missing.join(', ')}`, severity: 'warning' })}
// A real-looking credential in a committed file.
const creds = (ctx.env.example.DATABASE_URI ?? '').match(/^[a-z+]+:\/\/([^@/]+)@/i)?.[1]
if (creds && !PLACEHOLDER.test(creds)) {out.push({ file: '.env.example', fix: 'replace with USER:PASS', message: 'DATABASE_URI in .env.example carries credentials', severity: 'error' })}
for (const key of ['PAYLOAD_SECRET', 'R2_SECRET_ACCESS_KEY', 'GRAPH_CLIENT_SECRET', 'IPAL_DOCTOR_TOKEN']) {
const value = ctx.env.example[key]
if (value && value.length >= 16 && !PLACEHOLDER.test(value)) {out.push({ file: '.env.example', fix: `leave ${key} empty`, message: `${key} in .env.example has a value`, severity: 'error' })}
}
return out
},
docs: 'docs/env.md',
group: 'env',
source: 'static',
},
{
id: 'env-live',
check: (ctx) =>
ctx.deep?.envProblems?.length
? [{ fix: 'set the variable (Coolify → Environment Variables, or .env) and redeploy', message: `the project's env rules fail: ${ctx.deep.envProblems.join(', ')}`, severity: 'error' }]
: [],
docs: 'docs/env.md',
group: 'env',
source: 'deep',
},
]
+188
View File
@@ -0,0 +1,188 @@
import type { DoctorContext } from '../project.js'
import type { DoctorRule, RuleFinding } from '../types.js'
import { configFile } from '../project.js'
import { lt, stripComments } from '../util.js'
/** Top-level entries of src/ the convention allows (AGENT.md §3 + the starter, reference site and token drafts). */
export const DEFAULT_SRC_ALLOW = [
'access',
'app',
'blocks',
'collections',
'components',
'content.config.ts',
'db.ts',
'design',
'env.rules.ts',
'fields',
'fonts',
'globals',
'hooks',
'i18n.config.ts',
'instrumentation.ts',
'lib',
'migrations',
'payload-types.ts',
'payload.config.ts',
'proxy.ts',
'seed',
'utilities',
]
/** The project renders blocks through the library registry — then components/ui/ only holds overrides. */
export const usesBlockRegistry = (ctx: DoctorContext) => /createBlockRegistry\s*\(/.test(stripComments(ctx.read(`${ctx.src}blocks/registry.ts`)))
/** Files AGENT.md §3 expects, with the `ipal-audit-skip` key that drops each one. */
function requiredFiles(ctx: DoctorContext): Array<[string, string?]> {
const multi = ctx.exists(`${ctx.src}app/(frontend)/[locale]`)
const fe = multi ? 'app/(frontend)/[locale]' : 'app/(frontend)'
return [
['proxy.ts'],
['i18n.config.ts'],
['instrumentation.ts'],
['payload.config.ts'],
['lib/content.ts'],
['app/manifest.ts'],
['app/robots.ts'],
['app/sitemap.xml/route.ts'],
['app/llms.txt/route.ts', 'llms'],
['app/llms-full.txt/route.ts', 'llms-full'],
[multi ? 'app/md/[locale]/[[...slug]]/route.ts' : 'app/md/[[...slug]]/route.ts', 'markdown'],
['app/api/mcp/route.ts', 'mcp'],
['app/api/health/route.ts'],
['app/indexnow-key.txt/route.ts', 'indexnow'],
[`${fe}/layout.tsx`],
[`${fe}/actions.ts`],
[`${fe}/not-found.tsx`],
[`${fe}/notFoundView.ts`],
[`${fe}/[[...slug]]/page.tsx`],
['blocks/registry.ts'],
['collections/Pages.ts'],
['collections/Media.ts'],
['components/layout'],
['components/forms/formClasses.ts'],
// components/ui/: blocks-ui-required (only without createBlockRegistry)
]
}
const PASCAL = /^[A-Z][A-Za-z0-9]*$/
const KEBAB = /^[a-z0-9]+(?:-[a-z0-9]+)*(?:\.[a-z0-9]+)*$/
export const layoutRules: DoctorRule[] = [
{
id: 'layout-required',
check: (ctx) => {
if (!ctx.src) {return [{ message: 'no src/ folder (AGENT.md §3)', severity: 'error' }]}
const missing = requiredFiles(ctx).filter(([file, key]) => !(key && ctx.auditSkips.has(key)) && !ctx.exists(`${ctx.src}${file}`))
return missing.length
? [{ fix: 'the ipal-setup skill (stage named by the file)', message: `missing: ${missing.map(([f]) => `${ctx.src}${f}`).join(', ')}`, severity: 'error' }]
: []
},
docs: 'docs/agent/AGENT.md#3-project-structure-and-naming',
group: 'layout',
source: 'static',
},
{
id: 'layout-forbidden',
check: (ctx) => {
const files = ['middleware.ts', `${ctx.src}middleware.ts`, ...['lib/pages.ts', 'lib/locales.ts', 'lib/navigation.ts', 'fields/link.ts', 'fields/sectionHeader.ts', 'fields/sectionSettings.ts'].map((f) => `${ctx.src}${f}`)]
const found = [...new Set(files)].filter((f) => ctx.exists(f))
return found.length
? [{ fix: 'delete — Next 16 uses proxy.ts; the plugin has resolveRoute, getConfiguredLocales, resolveNav, buildLinkField and the section fields', message: `files the plugin replaces: ${found.join(', ')}`, severity: 'error' }]
: []
},
docs: 'docs/agent/AGENT.md#3-project-structure-and-naming',
group: 'layout',
source: 'static',
},
{
id: 'layout-extra',
check: (ctx) => {
if (!ctx.src) {return []}
const allow = new Set([...(ctx.config.layout?.allow ?? []), ...DEFAULT_SRC_ALLOW])
const extra = ctx.list('src').filter((n) => !allow.has(n) && !n.startsWith('.'))
return extra.length
? [{ fix: 'move into the convention, or add to ipal-doctor.json "layout": { "allow": [...] }', message: `src/ entries outside the convention: ${extra.join(', ')}`, severity: 'info' }]
: []
},
docs: 'docs/agent/AGENT.md#3-project-structure-and-naming',
group: 'layout',
source: 'static',
},
{
id: 'naming',
check: (ctx) => {
const out: RuleFinding[] = []
const bad: string[] = []
// Block folders PascalCase; files in blocks/ (registry.ts, configs.ts) are helpers — camelCase is fine.
for (const name of ctx.list(`${ctx.src}blocks`)) {
if (!name.includes('.') && !PASCAL.test(name)) {bad.push(`blocks/${name}`)}
}
// A collection / global file (it has a slug) PascalCase; helper files next to them camelCase.
for (const dir of ['collections', 'globals']) {
for (const name of ctx.list(`${ctx.src}${dir}`)) {
const file = `${ctx.src}${dir}/${name}`
if (!/\.tsx?$/.test(name)) {continue}
const isConfig = /\bslug\s*:/.test(ctx.read(file)) && /(?:CollectionConfig|GlobalConfig)\b/.test(ctx.read(file))
if (isConfig && !PASCAL.test(name.replace(/\.tsx?$/, ''))) {bad.push(`${dir}/${name}`)}
}
}
for (const name of ctx.list('scripts')) {
if (/\.[cm]?[jt]s$/.test(name) && !KEBAB.test(name)) {bad.push(`scripts/${name}`)}
}
if (bad.length) {out.push({ fix: 'rename (blocks, collections, globals: PascalCase; scripts: kebab-case)', message: `names off the convention: ${bad.join(', ')}`, severity: 'warning' })}
const barrels = ['blocks', 'components'].flatMap((d) => (ctx.exists(`${ctx.src}${d}/index.ts`) ? [`${ctx.src}${d}/index.ts`] : []))
if (barrels.length) {out.push({ fix: 'delete — import files directly (§6.12)', message: `barrel files: ${barrels.join(', ')}`, severity: 'warning' })}
return out
},
docs: 'docs/agent/AGENT.md#3-project-structure-and-naming',
group: 'layout',
source: 'static',
},
{
id: 'importmap',
check: (ctx) => {
if (!ctx.importMap) {return [{ fix: 'pnpm payload generate:importmap', message: 'no importMap.js under app/(payload)/<admin>/', severity: 'error' }]}
const out: RuleFinding[] = []
const im = ctx.read(ctx.importMap)
const cfg = stripComments(ctx.read(configFile(ctx) ?? ''))
const v = ctx.pluginVersion
const need: string[] = []
if (/payloadTotp/.test(cfg)) {
need.push('@clocklimited/payload-2fa/rsc#TOTPSetup')
if (!lt(v, '1.14.2')) {need.push('@intecion/ipal-kit/admin#TotpRedirectProvider')}
}
if (/buildR2Storage/.test(cfg)) {need.push('S3ClientUploadHandler')}
if (/cookieScanner\s*:\s*(?!false)/.test(cfg) && !lt(v, '1.14.4')) {need.push('@intecion/ipal-kit/admin#CookieReviewTab')}
if (!lt(v, '1.14.5') && !/adminMeta\s*:\s*false/.test(cfg)) {need.push('@intecion/ipal-kit/admin#AdminIcon')}
const missing = need.filter((n) => !im.includes(n))
if (missing.length) {out.push({ file: ctx.importMap, fix: 'pnpm payload generate:importmap and commit', message: `import map lacks ${missing.join(', ')}`, severity: 'error' })}
// Entries that name exports the installed plugin no longer has (a removed admin component → blank admin).
const adminIndex = ctx.read('node_modules/@intecion/ipal-kit/dist/exports/admin.js')
if (adminIndex) {
const names = [...new Set([...im.matchAll(/['"]@intecion\/ipal-kit\/admin#(\w+)['"]/g)].map((m) => m[1]))]
const gone = names.filter((n) => !new RegExp(`\\b${n}\\b`).test(adminIndex))
if (gone.length) {out.push({ file: ctx.importMap, fix: 'pnpm payload generate:importmap and commit', message: `import map names exports the installed plugin no longer has: ${gone.join(', ')}`, severity: 'error' })}
}
if (ctx.deep?.importMapCurrent === false) {out.push({ file: ctx.importMap, fix: 'pnpm payload generate:importmap and commit', message: 'the committed import map differs from a freshly generated one', severity: 'error' })}
return out
},
docs: 'docs/agent/skills/ipal-reference/SKILL.md',
group: 'layout',
source: 'static',
},
{
id: 'tsconfig-skills',
check: (ctx) => {
const dirs = ['.agents', '.claude'].filter((d) => ctx.list(`${d}/skills`).some((n) => n.startsWith('ipal-')))
if (!dirs.length || !ctx.exists('tsconfig.json')) {return []}
const exclude = ctx.read('tsconfig.json').replace(/\s/g, '').match(/"exclude":\[([^\]]*)\]/)?.[1] ?? ''
const missing = dirs.filter((d) => !new RegExp(`"(?:\\./)?${d.replace('.', '\\.')}(?:/[^"]*)?"`).test(exclude))
return missing.length ? [{ file: 'tsconfig.json', fix: `"exclude": ["node_modules", "${missing.join('", "')}"]`, message: `tsconfig.json does not exclude ${missing.join(', ')} — skill templates break tsc / next build`, severity: 'error' }] : []
},
docs: 'docs/agent/AGENT.md#14-skills-antigravity-claude-code-cursor',
group: 'layout',
source: 'static',
},
]
+94
View File
@@ -0,0 +1,94 @@
import { existsSync } from 'node:fs'
import { join } from 'node:path'
import type { DoctorLive, DoctorRule, LiveResponse, RuleFinding } from '../types.js'
import { run } from '../util.js'
import { noindex } from './security.js'
import { parseToolOutput, titleSlug } from './tooling.js'
/** GET-only fetcher with a cache (each path is requested once per run) and a doctor user agent. */
export function createLiveFetcher(url: string, options: { adminRoute?: string; staging?: boolean } = {}): DoctorLive {
const base = url.replace(/\/+$/, '')
const cache = new Map<string, Promise<LiveResponse>>()
const fetchOnce = (path: string, init: { redirect?: 'follow' | 'manual' } = {}) => {
const key = `${init.redirect ?? 'follow'} ${path}`
if (!cache.has(key)) {
cache.set(
key,
(async () => {
try {
const res = await fetch(base + path, {
headers: { 'user-agent': 'ipal-doctor (+https://intecion.com; read-only)' },
redirect: init.redirect ?? 'follow',
signal: AbortSignal.timeout(20_000),
})
return { headers: res.headers, status: res.status, text: await res.text() }
} catch (err) {
const e = err as { cause?: { code?: string }; message?: string }
return { error: e.cause?.code ?? e.message ?? 'unreachable', headers: new Headers(), status: 0, text: '' }
}
})(),
)
}
return cache.get(key)!
}
return { adminRoute: options.adminRoute ?? '/admin', fetch: fetchOnce, staging: options.staging ?? false, url: base }
}
export const liveRules: DoctorRule[] = [
{
id: 'live-reachable',
check: async (ctx) => {
const home = await ctx.live!.fetch('/', { redirect: 'manual' })
return home.status ? [] : [{ message: `${ctx.live!.url} is unreachable (${home.error})`, severity: 'error' }]
},
group: 'live',
source: 'live',
},
{
id: 'live-health',
check: async (ctx) => {
const res = await ctx.live!.fetch('/api/health')
return res.status === 200 ? [] : [{ fix: 'src/app/api/health/route.ts → healthRoute (Coolify health check)', message: `/api/health → ${res.status || res.error}`, severity: 'error' }]
},
docs: 'docs/deployment.md',
group: 'live',
source: 'live',
},
{
id: 'live-noindex',
check: async (ctx) => {
const home = await ctx.live!.fetch('/')
if (!home.status) {return []}
const isNoindex = noindex(home.text, home.headers.get('x-robots-tag'))
if (ctx.live!.staging) {return isNoindex ? [] : [{ fix: 'IPAL_NOINDEX=1 on the staging app', message: 'the staging site is indexable', severity: 'error' }]}
return isNoindex ? [{ fix: 'unset IPAL_NOINDEX on production and redeploy', message: 'the production home page is noindex', severity: 'error' }] : []
},
docs: 'docs/seo.md',
group: 'live',
source: 'live',
},
{
id: 'live-seo',
check: async (ctx) => {
// ipal-seo-check of the doctor's own version: robots, sitemap, canonical, hreflang, noindex, JSON-LD, llms, MCP.
const script = join(ctx.packageRoot, 'docs/agent/skills/ipal-seo-check/scripts/seo-check.mjs')
if (!existsSync(script)) {return [{ message: 'ipal-seo-check not found', severity: 'warning' }]}
const home = await ctx.live!.fetch('/', { redirect: 'manual' })
if (!home.status) {return []}
const res = run(process.execPath, [script, ctx.live!.url, '--max', '10'], ctx.root, 300_000)
const out: RuleFinding[] = []
// INFO lines are notes (e.g. "no verification meta" with DNS verification) — not findings.
for (const line of parseToolOutput(res.stdout).filter((l) => l.level !== 'info')) {
const items = line.items.length ? `: ${line.items.slice(0, 3).join('; ')}${line.items.length > 3 ? ` … +${line.items.length - 3}` : ''}` : ''
out.push({ fix: line.rule, message: `${line.title}${items}`, rule: `live-seo:${titleSlug(line.title.replace(/[\d/]+/g, ' '))}`, severity: line.level })
}
if (res.code === 2) {out.push({ message: `ipal-seo-check: ${res.stderr.trim()}`, severity: 'error' })}
return out
},
docs: 'docs/agent/skills/ipal-seo-check/SKILL.md',
group: 'live',
source: 'live',
},
]
+162
View File
@@ -0,0 +1,162 @@
import type { DoctorContext } from '../project.js'
import type { DoctorRule, RuleFinding } from '../types.js'
import { configFile, nextConfigFile } from '../project.js'
import { lt, stripComments } from '../util.js'
const next = (ctx: DoctorContext) => stripComments(ctx.read(nextConfigFile(ctx) ?? ''))
const cfg = (ctx: DoctorContext) => stripComments(ctx.read(configFile(ctx) ?? ''))
const isLocal = (url: string) => /^https?:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::|\/|$)/i.test(url)
const noindex = (html: string, robotsHeader: null | string) =>
/<meta[^>]+name=["']robots["'][^>]*content=["'][^"']*noindex/i.test(html) || /<meta[^>]+content=["'][^"']*noindex[^>]+name=["']robots["']/i.test(html) || /noindex/i.test(robotsHeader ?? '')
/** Days between two ISO dates. */
const daysBetween = (from: string, to: string) => Math.floor((Date.parse(to) - Date.parse(from)) / 86_400_000)
export const securityRules: DoctorRule[] = [
{
id: 'security-headers',
check: async (ctx) => {
const out: RuleFinding[] = []
const file = nextConfigFile(ctx)
if (!/buildSecurityHeaders\s*\(/.test(next(ctx))) {out.push({ file: file ?? 'next.config.ts', fix: 'headers(): [{ source: "/:path*", headers: buildSecurityHeaders({ csp }) }]', message: 'next.config does not use buildSecurityHeaders', severity: 'error' })}
if (ctx.live) {
const home = await ctx.live.fetch('/')
if (home.status) {
const h = home.headers
const missing = [
...(isLocal(ctx.live.url) || h.get('strict-transport-security') ? [] : ['Strict-Transport-Security']),
...(h.get('x-content-type-options') ? [] : ['X-Content-Type-Options']),
...(h.get('referrer-policy') ? [] : ['Referrer-Policy']),
...(h.get('permissions-policy') ? [] : ['Permissions-Policy']),
...(h.get('x-frame-options') || /frame-ancestors/.test(h.get('content-security-policy') ?? '') ? [] : ['X-Frame-Options / frame-ancestors']),
]
if (missing.length) {out.push({ fix: 'buildSecurityHeaders on /:path* (security.md)', message: `live / lacks ${missing.join(', ')}`, severity: 'error' })}
}
}
return out
},
docs: 'docs/security.md',
group: 'security',
source: 'static',
},
{
id: 'powered-by',
check: async (ctx) => {
const out: RuleFinding[] = []
if (!/withSecurityConfig\s*\(|poweredByHeader\s*:\s*false/.test(next(ctx))) {
out.push({ file: nextConfigFile(ctx) ?? 'next.config.ts', fix: 'export default withPayload(withSecurityConfig(nextConfig))', message: 'X-Powered-By is not hidden (withSecurityConfig)', severity: 'error' })
}
if (ctx.live) {
for (const path of ['/', `${ctx.live.adminRoute}/login`]) {
const res = await ctx.live.fetch(path)
const value = res.headers.get('x-powered-by')
if (value) {out.push({ fix: 'withSecurityConfig (security.md → X-Powered-By)', message: `live ${path} sends X-Powered-By: ${value}`, severity: 'error' })}
}
}
return out
},
docs: 'docs/security.md',
group: 'security',
source: 'static',
},
{
id: 'csp',
check: async (ctx) => {
const code = next(ctx) + stripComments(ctx.read(`${ctx.src}proxy.ts`))
if (!/\bcsp\s*[:,}]|buildCsp|Content-Security-Policy/i.test(code)) {
return [{ file: nextConfigFile(ctx) ?? 'next.config.ts', fix: "buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report' } }) + buildAdminCspHeaders on /admin/:path*", message: 'no Content-Security-Policy', severity: 'warning' }]
}
const out: RuleFinding[] = []
if (!/buildAdminCspHeaders\s*\(/.test(code)) {out.push({ file: nextConfigFile(ctx) ?? 'next.config.ts', fix: "{ source: '/admin/:path*', headers: buildAdminCspHeaders(csp) }", message: 'no CSP for the admin (buildAdminCspHeaders)', severity: 'warning' })}
let reportOnly = /mode\s*:\s*['"]report-only['"]/.test(code) || !/mode\s*:\s*['"]enforce['"]/.test(code)
if (ctx.live) {
for (const path of ['/', `${ctx.live.adminRoute}/login`]) {
const h = (await ctx.live.fetch(path)).headers
if (h.get('content-security-policy')) {
if (path === '/') {reportOnly = false}
} else if (h.get('content-security-policy-report-only')) {
reportOnly = true
} else {
out.push({ fix: 'security.md → ROLL OUT CSP', message: `live ${path} has no CSP header`, severity: 'warning' })
}
}
}
if (reportOnly) {
const seen = ctx.config.seen?.['csp-report-only'] ?? ctx.today
const days = daysBetween(seen, ctx.today)
out.push({
fix: "switch to mode: 'enforce' once the reports are clean (security.md → ROLL OUT CSP)",
message: `CSP is report-only (since ${seen}${days ? `, ${days} days` : ''})`,
severity: days >= 28 ? 'warning' : 'info',
})
}
return out
},
docs: 'docs/security.md',
group: 'security',
source: 'static',
},
{
id: '2fa',
check: (ctx) => {
const out: RuleFinding[] = []
if (!/twoFactor\s*:\s*\{[\s\S]*?plugin\s*:\s*payloadTotp/.test(cfg(ctx))) {out.push({ file: configFile(ctx) ?? 'payload.config.ts', fix: "ipalKit({ twoFactor: { issuer: '<site>', plugin: payloadTotp } })", message: '2FA is not on (twoFactor with plugin: payloadTotp)', severity: 'error' })}
else if (!ctx.installed('@clocklimited/payload-2fa')) {out.push({ fix: 'pnpm add @clocklimited/payload-2fa', message: '@clocklimited/payload-2fa is not installed', severity: 'error' })}
if (ctx.deep?.usersWithout2fa) {out.push({ fix: 'each of them signs in and sets up TOTP (forceSetup)', message: `${ctx.deep.usersWithout2fa} panel user(s) without TOTP`, severity: 'error' })}
return out
},
docs: 'docs/security.md#2fa-totp--enforced-for-every-user',
group: 'security',
source: 'static',
},
{
id: 'cookie-scanner',
check: (ctx) => {
const code = cfg(ctx)
if (!/cookieScanner\s*:/.test(code) || /cookieScanner\s*:\s*false/.test(code)) {
return [{ file: configFile(ctx) ?? 'payload.config.ts', fix: 'ipalKit({ cookieScanner: { crawl: true } }) + generate:importmap', message: 'the cookie scanner is off', severity: 'error' }]
}
const out: RuleFinding[] = []
if (!/cookieScanner\s*:\s*\{[^}]*\bcrawl\s*:\s*(?!false)/.test(code)) {out.push({ fix: 'cookieScanner: { crawl: true } (shared cookie-crawler service)', message: 'cookie scanner without crawl — no scheduled site check', severity: 'info' })}
if (ctx.deep?.pendingCookies) {out.push({ fix: 'Privacy → Cookies → Review and approve → Approve and add', message: `${ctx.deep.pendingCookies} cookie(s) wait for approval`, severity: 'warning' })}
return out
},
docs: 'docs/cookie-scanner.md',
group: 'security',
source: 'static',
},
{
id: 'admin-meta',
check: async (ctx) => {
const out: RuleFinding[] = []
const code = cfg(ctx)
if (lt(ctx.pluginVersion, '1.14.5')) {out.push({ message: `admin link previews (adminMeta) need ipal-kit ≥ 1.14.5 (installed ${ctx.pluginVersion ?? 'none'})`, severity: 'warning' })}
if (/adminMeta\s*:\s*false/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, message: 'adminMeta: false — the panel has no link preview and no noindex from the plugin', severity: 'warning' })}
if (/agency\s*:\s*false/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, message: 'agency: false — no technology credit', severity: 'warning' })}
if (ctx.live && !out.length) {
const res = await ctx.live.fetch(`${ctx.live.adminRoute}/login`)
if (res.status && res.status < 400 && !/\/api\/ipal\/admin-og/.test(res.text)) {out.push({ fix: 'adminMeta on (default) and generate:importmap', message: 'the live admin has no ipal link preview (og:image /api/ipal/admin-og)', severity: 'warning' })}
}
return out
},
docs: 'docs/white-label.md',
group: 'admin',
source: 'static',
},
{
id: 'admin-noindex',
check: async (ctx) => {
if (!ctx.live) {return []}
const path = `${ctx.live.adminRoute}/login`
const res = await ctx.live.fetch(path)
if (!res.status || res.status >= 400) {return [{ message: `live ${path} → ${res.status || res.error}`, severity: 'warning' }]}
return noindex(res.text, res.headers.get('x-robots-tag')) ? [] : [{ fix: 'adminMeta robots (default noindex, nofollow)', message: `live ${path} is not noindex`, severity: 'error' }]
},
docs: 'docs/white-label.md',
group: 'admin',
source: 'live',
},
]
export { noindex }
+56
View File
@@ -0,0 +1,56 @@
import { dirname, join, normalize } from 'node:path'
import type { DoctorContext } from '../project.js'
import type { DoctorRule, RuleFinding } from '../types.js'
import { stripComments } from '../util.js'
/** The seed entry file and the project files it imports (relative imports, two levels deep). */
function seedFiles(ctx: DoctorContext, entry: string): string[] {
const seen = new Set<string>()
const visit = (file: string, depth: number) => {
if (seen.has(file) || !ctx.exists(file)) {return}
seen.add(file)
if (depth >= 2) {return}
for (const m of ctx.read(file).matchAll(/from\s+['"](\.{1,2}\/[^'"]+)['"]/g)) {
const base = normalize(join(dirname(file), m[1])).replace(/\.js$/, '')
const hit = ['.ts', '.tsx', '.mjs', '.js', '/index.ts'].map((ext) => base + ext).find((f) => ctx.exists(f))
if (hit) {visit(hit, depth + 1)}
}
}
visit(entry, 0)
return [...seen]
}
const DELETES = /payload\s*\.\s*delete\s*\(|\.deleteMany\s*\(|dropDatabase|SEED_FRESH|--fresh\b/
export const seedRules: DoctorRule[] = [
{
id: 'seed-named',
check: (ctx) => {
const out: RuleFinding[] = []
for (const [name, command] of Object.entries(ctx.pkg.scripts ?? {})) {
if (!/seed/i.test(name)) {continue}
if (/fresh|reset/i.test(name)) {out.push({ file: 'package.json', fix: 'remove it — seeds never delete (seeding.md)', message: `script "${name}" re-creates content from scratch`, severity: 'error' })}
if (/IPAL_SEED_ALLOW_FULL=1/.test(command)) {out.push({ file: 'package.json', fix: 'set IPAL_SEED_ALLOW_FULL=1 by hand for one run, only with the owner\'s OK', message: `script "${name}" switches the full-seed guard off`, severity: 'error' })}
const entry = command.match(/(?:^|\s)([\w./@-]+\.[cm]?[jt]s)(?:\s|$)/)?.[1]?.replace(/^\.\//, '')
if (!entry) {continue}
if (!ctx.exists(entry)) {out.push({ file: 'package.json', message: `script "${name}" runs ${entry}, which does not exist`, severity: 'warning' }); continue}
const files = seedFiles(ctx, entry)
const code = files.map((f) => stripComments(ctx.read(f))).join('\n')
if (!/createSeeder\s*\(/.test(code)) {out.push({ file: entry, fix: "createSeeder(payload) from '@intecion/ipal-kit/seed' (only / SEED_ONLY, full-seed guard)", message: `script "${name}" does not use the ipal-kit seed helper`, severity: 'warning' })}
const deleting = files.filter((f) => DELETES.test(stripComments(ctx.read(f))))
if (deleting.length) {out.push({ file: deleting[0], fix: 'seeds never delete — an editor removes records in the panel (seeding.md)', message: `script "${name}" deletes records (${deleting.join(', ')})`, severity: 'error' })}
if (/guard\s*:\s*false|allowFull\s*:\s*true/.test(code)) {out.push({ file: entry, fix: 'keep the guard; IPAL_SEED_ALLOW_FULL=1 for one run with the owner\'s OK', message: `script "${name}" turns the full-seed guard off in code`, severity: 'error' })}
if (ctx.launched && /createSeeder\s*\(/.test(code) && !/\bonly\s*:/.test(code)) {out.push({ file: entry, fix: 'run it with SEED_ONLY="pages:<slug>,global:<slug>" or pass only: [...] (seeding.md → after launch)', message: `script "${name}" has no record list — after launch every run needs SEED_ONLY`, severity: 'warning' })}
}
for (const file of ['.env.example', '.env.production']) {
if (/^\s*IPAL_SEED_ALLOW_FULL\s*=\s*1/m.test(ctx.read(file))) {out.push({ file, message: `${file} sets IPAL_SEED_ALLOW_FULL=1`, severity: 'error' })}
}
return out
},
docs: 'docs/seeding.md',
group: 'seeds',
source: 'static',
},
]
+83
View File
@@ -0,0 +1,83 @@
import { existsSync } from 'node:fs'
import { join } from 'node:path'
import type { DoctorRule, DoctorSeverity, RuleFinding } from '../types.js'
import { run } from '../util.js'
export type ToolLine = { items: string[]; level: DoctorSeverity; rule: string; title: string }
/** `[ERROR] title (n) — rule` blocks with their indented items (the output of audit.sh and seo-check.mjs). */
export function parseToolOutput(text: string): ToolLine[] {
const out: ToolLine[] = []
for (const line of text.split('\n')) {
const head = line.match(/^\[(ERROR|WARNING|INFO)\] (.+?)(?: \(\d+\))? — (.*)$/)
if (head) {
out.push({ items: [], level: head[1] === 'ERROR' ? 'error' : head[1] === 'WARNING' ? 'warning' : 'info', rule: head[3], title: head[2] })
continue
}
const item = line.match(/^ {2}(\S.*)$/)
if (item && out.length) {out.at(-1)!.items.push(item[1])}
}
return out
}
/**
* ipal-audit titles that are a doctor rule of their own — the finding is reported under that id
* (one place per check: the audit script). Everything else lands under `audit`.
*/
export const AUDIT_RULE_MAP: Array<[RegExp, string]> = [
[/^missing: security headers$/, 'security-headers'],
[/^missing: X-Powered-By hidden$/, 'powered-by'],
[/^missing: Content-Security-Policy$/, 'csp'],
[/^missing: 2FA$/, '2fa'],
[/^missing: env validation$/, 'env-rules'],
[/^import map without the R2 upload handler$/, 'importmap'],
[/^tsconfig\.json does not exclude \.agents$/, 'tsconfig-skills'],
[/^middleware\.ts exists$/, 'layout-forbidden'],
[/^barrel index\.ts$/, 'naming'],
[/^hardcoded text in (blocks|components\/layout)$|^hardcoded Polish text in code$/, 'i18n-literals'],
[/^hex colors in (classes|inline styles)$|^design-token standard not wired$|^ipal-tokens --check$/, 'blocks-tokens'],
[/^own block renderer switch$/, 'blocks-registry'],
]
/** Rules the doctor already reports itself — the audit copy is dropped instead of reported twice. */
const AUDIT_DUPLICATES = new Set(['2fa', 'csp', 'env-rules', 'importmap', 'layout-forbidden', 'naming', 'powered-by', 'security-headers', 'tsconfig-skills'])
/** `duplicate titles` → `duplicate-titles` (the id part of `audit:<slug>` / `live-seo:<slug>`). */
export const titleSlug = (title: string) => title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
export const toolingRules: DoctorRule[] = [
{
id: 'audit',
check: (ctx) => {
// The audit script of the doctor's own version (the project's copy in .agents may be stale).
const script = join(ctx.packageRoot, 'docs/agent/skills/ipal-audit/scripts/audit.sh')
if (!existsSync(script)) {return [{ message: `ipal-audit not found (${script})`, severity: 'warning' }]}
if (!ctx.src) {return []}
const res = run('bash', [script, '--quick'], ctx.root, 300_000)
if (res.code !== 0 && res.code !== 1) {return [{ message: `ipal-audit --quick could not run (exit ${res.code}): ${res.stderr.trim().split('\n')[0] ?? ''}`, severity: 'warning' }]}
const out: RuleFinding[] = []
for (const line of parseToolOutput(res.stdout)) {
const mapped = AUDIT_RULE_MAP.find(([re]) => re.test(line.title))?.[1]
if (mapped && AUDIT_DUPLICATES.has(mapped)) {continue}
const rule = mapped ?? `audit:${titleSlug(line.title)}`
// One finding per file (`file:line: text` items), so a silenced file does not hide the others.
const byFile = new Map<string, string[]>()
for (const item of line.items) {
const file = item.match(/^([\w@()[\].\-/]+\.[a-z]+):\d+:/)?.[1] ?? ''
byFile.set(file, [...(byFile.get(file) ?? []), item])
}
if (!byFile.size) {byFile.set('', [])}
for (const [file, items] of byFile) {
const list = items.length ? `: ${items.slice(0, 5).join('; ')}${items.length > 5 ? ` … +${items.length - 5}` : ''}` : ''
out.push({ file: file || undefined, fix: line.rule, message: `${line.title}${list}`, rule, severity: line.level })
}
}
return out
},
docs: 'docs/agent/skills/ipal-audit/SKILL.md',
group: 'audit',
source: 'static',
},
]
+125
View File
@@ -0,0 +1,125 @@
import type { DoctorRule, RuleFinding } from '../types.js'
import { compareVersions, isSemverSpec, lt, parseVersion, run } from '../util.js'
const PKG = '@intecion/ipal-kit'
export const versionRules: DoctorRule[] = [
{
id: 'plugin-installed',
check: (ctx) => {
const spec = ctx.deps[PKG]
if (!spec) {return [{ fix: `pnpm add ${PKG}`, message: `${PKG} is not a dependency`, severity: 'error' }]}
if (!ctx.pluginVersion) {return [{ fix: 'pnpm install', message: `${PKG} is not installed (no node_modules/${PKG})`, severity: 'error' }]}
if (isSemverSpec(spec) && lt(ctx.pluginVersion, spec)) {
return [{ file: 'package.json', fix: 'pnpm install', message: `package.json asks ${spec}, node_modules has ${ctx.pluginVersion}`, severity: 'error' }]
}
return []
},
docs: 'docs/agent/skills/ipal-upgrade/SKILL.md',
group: 'versions',
source: 'static',
},
{
id: 'next-min',
check: (ctx) => {
const out: RuleFinding[] = []
const next = ctx.installed('next')
if (!next) {return [{ fix: 'pnpm install', message: 'next is not installed', severity: 'error' }]}
if (lt(next, '16.4.1')) {out.push({ fix: 'pnpm add [email protected] [email protected]', message: `next ${next} < 16.4.1 (RCE and DoS advisories)`, severity: 'error' })}
const eslint = ctx.installed('eslint-config-next')
if (eslint && parseVersion(eslint)?.slice(0, 2).join('.') !== parseVersion(next)?.slice(0, 2).join('.')) {
out.push({ fix: `pnpm add -D eslint-config-next@${next}`, message: `eslint-config-next ${eslint} is not on next's ${next}`, severity: 'warning' })
}
return out
},
docs: 'docs/agent/AGENT.md#4-next-16--rendering-seo-build',
group: 'versions',
source: 'static',
},
{
id: 'sharp-min',
check: (ctx) => {
const sharp = ctx.installed('sharp')
if (!sharp) {return [{ fix: 'pnpm add sharp@^0.35.5', message: 'sharp is not installed (next/image and Payload need it)', severity: 'error' }]}
return lt(sharp, '0.35.5') ? [{ fix: 'pnpm add sharp@^0.35.5 (or a pnpm.overrides entry)', message: `sharp ${sharp} < 0.35.5`, severity: 'error' }] : []
},
docs: 'docs/agent/AGENT.md#4-next-16--rendering-seo-build',
group: 'versions',
source: 'static',
},
{
id: 'node-22',
check: (ctx) => {
const out: RuleFinding[] = []
const engines = ctx.pkg.engines?.node?.trim()
// Only 22: a lower bound of 22 and an upper bound below 23 (or a 22.x / ^22 / ~22 range).
const only22 = !!engines && (/^(?:\^|~)?22(?:\.\d+){0,2}(?:\.x)?$/.test(engines) || /^>=\s*22(?:\.\d+){0,2}\s+<\s*23(?:\.0){0,2}$/.test(engines))
if (!only22) {out.push({ file: 'package.json', fix: 'set "engines": { "node": ">=22 <23" }', message: `engines.node is ${engines ? `"${engines}"` : 'missing'} — want ">=22 <23"`, severity: 'warning' })}
for (const file of ['.nvmrc', '.node-version']) {
const v = ctx.read(file).trim()
if (v && !/^v?22(?:\.|$)/.test(v)) {out.push({ file, fix: `write 22 to ${file}`, message: `${file} says ${v}`, severity: 'warning' })}
}
if (!ctx.exists('.nvmrc') && !ctx.exists('.node-version')) {out.push({ fix: 'echo 22 > .nvmrc', message: 'no .nvmrc (Nixpacks and nvm pick Node from it)', severity: 'warning' })}
if (ctx.deep?.node && !/^v?22\./.test(ctx.deep.node)) {out.push({ message: `the site runs on Node ${ctx.deep.node}`, severity: 'warning' })}
return out
},
docs: 'docs/deployment.md',
group: 'versions',
source: 'static',
},
{
id: 'pnpm-pinned',
check: (ctx) => (ctx.pkg.packageManager ? [] : [{ file: 'package.json', fix: 'corepack use pnpm@10', message: 'no packageManager — builds may use another pnpm', severity: 'info' }]),
group: 'versions',
source: 'static',
},
{
id: 'plugin-latest',
check: (ctx) => {
if (!ctx.pluginVersion) {return []}
const res = run('pnpm', ['view', PKG, 'version', '--json'], ctx.root, 30_000)
let latest: null | string = null
try {
const parsed = JSON.parse(res.stdout) as string | string[]
latest = Array.isArray(parsed) ? (parsed.at(-1) ?? null) : parsed
} catch {
latest = null
}
if (!latest) {return [{ message: `could not read the latest ${PKG} from the registry (${res.stderr.trim().split('\n')[0] || 'no answer'}) — use --offline`, severity: 'info' }]}
if (compareVersions(ctx.pluginVersion, latest) >= 0) {return []}
const [a, b] = [parseVersion(ctx.pluginVersion)!, parseVersion(latest)!]
const minorsBehind = a[0] < b[0] ? 99 : b[1] - a[1]
return [{
fix: `pnpm add ${PKG}@${latest} — then the ipal-upgrade skill`,
message: `${PKG} ${ctx.pluginVersion} installed, ${latest} is out`,
severity: minorsBehind >= 2 ? 'error' : 'warning',
}]
},
docs: 'docs/agent/skills/ipal-upgrade/SKILL.md',
group: 'versions',
source: 'registry',
},
{
id: 'deps-audit',
check: (ctx) => {
const res = run('pnpm', ['audit', '--prod', '--json', '--ignore-workspace'], ctx.root, 120_000)
let v: Record<string, number> | undefined
try {
v = (JSON.parse(res.stdout) as { metadata?: { vulnerabilities?: Record<string, number> } }).metadata?.vulnerabilities
} catch {
v = undefined
}
if (!v) {return [{ message: `pnpm audit --prod gave no result (${res.stderr.trim().split('\n')[0] || 'no output'}) — use --offline`, severity: 'info' }]}
const high = (v.critical ?? 0) + (v.high ?? 0)
if (high) {
return [{ fix: 'pnpm up <package>, upgrade the plugin, or a pnpm.overrides entry (AGENT.md §4 item 12)', message: `pnpm audit --prod: ${v.critical ?? 0} critical, ${v.high ?? 0} high`, severity: 'error' }]
}
const low = (v.moderate ?? 0) + (v.low ?? 0)
return low ? [{ message: `pnpm audit --prod: ${v.moderate ?? 0} moderate, ${v.low ?? 0} low`, severity: 'info' }] : []
},
docs: 'docs/agent/AGENT.md#4-next-16--rendering-seo-build',
group: 'versions',
source: 'registry',
},
]