@forinda/kickjs-cli 8.15.0 → 8.16.1

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 (73) hide show
  1. package/dist/agent-docs-BVFt7K8T.mjs +591 -0
  2. package/dist/agent-docs-BVFt7K8T.mjs.map +1 -0
  3. package/dist/agent-docs-DBLN2Mp9.mjs +590 -0
  4. package/dist/{build-gqxIH3D8.mjs → build-BKGmBYPE.mjs} +3 -3
  5. package/dist/{build-gqxIH3D8.mjs.map → build-BKGmBYPE.mjs.map} +1 -1
  6. package/dist/{build-Czsf4CBN.mjs → build-BmjXHtAh.mjs} +2 -2
  7. package/dist/{builtins-6euI1-lN.mjs → builtins-C-qFcIBD.mjs} +2 -2
  8. package/dist/{builtins-xahWxQLw.mjs → builtins-NIDfVClB.mjs} +59 -59
  9. package/dist/cli.mjs +2 -2
  10. package/dist/{config-DCM2vXUJ.mjs → config-C881BGnv.mjs} +2 -2
  11. package/dist/{config-8jdSKLKJ.mjs → config-CgoZjmsu.mjs} +3 -3
  12. package/dist/{config-8jdSKLKJ.mjs.map → config-CgoZjmsu.mjs.map} +1 -1
  13. package/dist/{doctor-CwGU9orm.mjs → doctor-CWP1-2fB.mjs} +9 -9
  14. package/dist/{doctor-CwGU9orm.mjs.map → doctor-CWP1-2fB.mjs.map} +1 -1
  15. package/dist/{fullstack-9HywHQL-.mjs → fullstack-BPB6BkL8.mjs} +13 -13
  16. package/dist/{fullstack-9HywHQL-.mjs.map → fullstack-BPB6BkL8.mjs.map} +1 -1
  17. package/dist/{fullstack-BmIFnryN.mjs → fullstack-_0qGKsG7.mjs} +9 -9
  18. package/dist/index.d.mts.map +1 -1
  19. package/dist/index.mjs +2 -2
  20. package/dist/{plugin-BjmLRF7t.mjs → plugin-KpSiVmlT.mjs} +2 -2
  21. package/dist/{plugin-DLZP4hZ0.mjs → plugin-_Xkj7vNO.mjs} +2 -2
  22. package/dist/project-CO9buk5F.mjs +133 -0
  23. package/dist/project-CO9buk5F.mjs.map +1 -0
  24. package/dist/project-qHDV333j.mjs +132 -0
  25. package/dist/{project-root-Dk8r8FMi.mjs → project-root-BAZV1qId.mjs} +3 -3
  26. package/dist/{project-root-Dk8r8FMi.mjs.map → project-root-BAZV1qId.mjs.map} +1 -1
  27. package/dist/{project-root-8DH00M-b.mjs → project-root-DdPFoCw6.mjs} +2 -2
  28. package/dist/{rolldown-runtime-CRasMkPY.mjs → rolldown-runtime-B0Wm12ok.mjs} +1 -1
  29. package/dist/{run-plugins-R0bVf_nK.mjs → run-plugins-DLCZx7uc.mjs} +67 -67
  30. package/dist/run-plugins-DLCZx7uc.mjs.map +1 -0
  31. package/dist/{typegen-DNufBmjE.mjs → typegen-B8uRTy_3.mjs} +4 -4
  32. package/dist/{typegen-BZ8cQ1YM.mjs → typegen-DGq3DowV.mjs} +5 -5
  33. package/dist/{typegen-BZ8cQ1YM.mjs.map → typegen-DGq3DowV.mjs.map} +1 -1
  34. package/dist/{types-DOcxTXlP.mjs → types-CokUufqE.mjs} +1 -1
  35. package/package.json +4 -4
  36. package/templates/base/files/_dot_vscode/extensions.json +3 -0
  37. package/templates/base/files/kick.config.ts +4 -0
  38. package/templates/base/skills/add-adapter.txt +56 -0
  39. package/templates/base/skills/add-module.txt +53 -0
  40. package/templates/base/skills/add-plugin.txt +69 -0
  41. package/templates/base/skills/bootstrap-export.txt +21 -0
  42. package/templates/base/skills/cli-commands-cheatsheet.txt +46 -0
  43. package/templates/base/skills/cli-plugin.txt +61 -0
  44. package/templates/base/skills/context-contributor.txt +73 -0
  45. package/templates/base/skills/deny-list.txt +44 -0
  46. package/templates/base/skills/deploy.txt +99 -0
  47. package/templates/base/skills/docs-lookup.txt +40 -0
  48. package/templates/base/skills/env-wiring-check.txt +44 -0
  49. package/templates/base/skills/guard-vs-middleware-vs-contributor.txt +95 -0
  50. package/templates/base/skills/query-parsing-list-endpoint.txt +48 -0
  51. package/templates/base/skills/refresh-agent-docs.txt +27 -0
  52. package/templates/base/skills/route-flags.txt +73 -0
  53. package/templates/base/skills/thin-entry-file.txt +49 -0
  54. package/templates/base/skills/use-asset-manager.txt +61 -0
  55. package/templates/base/skills/write-controller-test.txt +63 -0
  56. package/templates/feature-views/feature.json +21 -0
  57. package/templates/feature-views/files/src/adapters/views.ts +5 -0
  58. package/templates/feature-views/files/src/views/home.kick +3 -0
  59. package/templates/feature-views/files/src/views/layouts/main.kick +13 -0
  60. package/templates/feature-views/files/src/views.ts +9 -0
  61. package/templates/feature-views/skills/views-forms.txt +68 -0
  62. package/templates/feature-views/skills/views.txt +49 -0
  63. package/templates/fullstack-root/files/_dot_vscode/extensions.json +3 -0
  64. package/dist/agent-docs-CrVQtJgn.mjs +0 -932
  65. package/dist/agent-docs-D7K6R5C3.mjs +0 -933
  66. package/dist/agent-docs-D7K6R5C3.mjs.map +0 -1
  67. package/dist/package-manager-9XxrErw1.mjs +0 -11
  68. package/dist/package-manager-Dwaolesm.mjs +0 -12
  69. package/dist/package-manager-Dwaolesm.mjs.map +0 -1
  70. package/dist/project-CFi3NvO9.mjs +0 -136
  71. package/dist/project-CFi3NvO9.mjs.map +0 -1
  72. package/dist/project-CO0D8B0V.mjs +0 -135
  73. package/dist/run-plugins-R0bVf_nK.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-docs-BVFt7K8T.mjs","names":["colors","__exportAll","execBin","runScript","loadKickConfig","PACKAGE_MANAGERS","clack","pc","_dryRun","setDryRun","enabled","FORMATTABLE","writeFileSafe","mkdir","dirname","filePath","writeFile","content","extname","formatFile","_oxfmt","resolveOxfmt","createRequire","join","cwd","oxfmt","options","loadOxfmtConfig","result","_oxfmtConfigCache","dir","startDir","configPath","existsSync","raw","readFile","parsed","\"$schema\"","parent","fileExists","access","METHOD_COLOR_MAP","httpMethodColor","method","severityColor","tag","severity","intro","title","outro","message","handleCancel","value","text","opts","select","multiSelect","confirm","spinner","log","here","fileURLToPath","TEMPLATES_DIR","outputPath","templatePath","segment","renderLayers","templatesDir","files","dependencies","devDependencies","builds","integrations","scripts","layer","layers","manifestPath","manifest","readFileSync","root","rel","readdirSync","abs","statSync","contents","path","sep","target","vars","fill","key","all","renderSlots","d","fillVars","MARKER","lines","source","slots","line","active","i","out","importsAt","match","indent","slot","rendered","entry","indentBlock","word","name","statements","own","body","used","specs","def","kept","names","renderImports","code","byModule","spec","from","n","LOCKFILES","detectFromLockfile","fromDir","hit","file","resolve","packageManagerFromPackageJson","pkgPath","field","resolvePackageManagerWithSource","flagPm","config","fromPkg","fromLock","fromAgent","resolvePackageManager","pm","detectPackageManager","skillVars","style","readLayerSkills","folder","f","m","filled","detectFeatureLayers","dirs","appDir","installed","pkg","deps","devCommand","p","template","generateClaude","generateAgents","generateKickJsSkillFiles","banner","skill","generateGemini","generateCopilot","agent_docs_exports","generateAgentDocs","writeLayerSkills","AGENTS_DIR","VALID_TEMPLATES","detectName","override","outDir","detectStyle","detectTemplate","pattern","only","wantsAgents","wantsClaude","wantsSkills","wantsGemini","wantsCopilot","targets","written","render","base","basename","s","relative"],"sources":["../src/utils/fs.ts","../src/utils/colors.ts","../src/utils/prompts.ts","../src/scaffold/overlay.ts","../src/utils/package-manager.ts","../src/scaffold/skills.ts","../src/generators/templates/project-docs.ts","../src/generators/agent-docs.ts"],"sourcesContent":["import { existsSync } from 'node:fs'\nimport { writeFile, mkdir, access, readFile } from 'node:fs/promises'\nimport { createRequire } from 'node:module'\nimport { dirname, extname, join } from 'node:path'\n\nlet _dryRun = false\nlet _format = true\n\n/** Enable/disable dry run mode globally for all writeFileSafe calls */\nexport function setDryRun(enabled: boolean): void {\n _dryRun = enabled\n}\n\n/**\n * Toggle oxfmt post-write formatting. Defaults to enabled — generators\n * always emit formatted output unless the caller opts out (rare; useful\n * for tests that want byte-stable assertions against raw template strings).\n */\nexport function setFormatOnWrite(enabled: boolean): void {\n _format = enabled\n}\n\n/** Extensions oxfmt can format. Anything else is written verbatim. */\nconst FORMATTABLE = new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.json', '.md'])\n\n/**\n * Write a file, creating parent directories if needed.\n *\n * After write, runs oxfmt against the file when:\n * - format-on-write is enabled (default)\n * - the extension is in {@link FORMATTABLE}\n * - oxfmt resolves from the user's project (or our own cwd)\n *\n * Failures (missing oxfmt, unparseable source, formatter crash) are\n * swallowed silently — formatting is a polish step, not a correctness\n * gate. The pre-commit hook still catches anything we couldn't format.\n *\n * Skips writing entirely in dry run mode.\n */\nexport async function writeFileSafe(filePath: string, content: string): Promise<void> {\n if (_dryRun) return\n await mkdir(dirname(filePath), { recursive: true })\n await writeFile(filePath, content, 'utf-8')\n if (_format && FORMATTABLE.has(extname(filePath))) {\n await formatFile(filePath, content).catch(() => {\n // Formatter missing or unparseable source — leave the unformatted\n // file in place. Pre-commit hook will catch shipping-blocker\n // formatting issues.\n })\n }\n}\n\ninterface OxfmtFormatResult {\n code: string\n errors: unknown[]\n}\n\ninterface OxfmtModule {\n format(\n fileName: string,\n sourceText: string,\n options?: Record<string, unknown>,\n ): Promise<OxfmtFormatResult>\n}\n\nlet _oxfmt: OxfmtModule | null | undefined = undefined\n\n/** Resolve oxfmt from the user's project, else the CLI's own; cache the result (or null) for the process. */\nasync function resolveOxfmt(cwd: string): Promise<OxfmtModule | null> {\n if (_oxfmt !== undefined) return _oxfmt\n try {\n const req = createRequire(join(cwd, 'package.json'))\n const oxfmtPath = req.resolve('oxfmt')\n _oxfmt = (await import(oxfmtPath)) as OxfmtModule\n } catch {\n // Not installed in the project — `vp migrate` removes it, Vite+ bundles\n // its own. Fall back to the copy the CLI depends on.\n _oxfmt = (await import('oxfmt').catch(() => null)) as OxfmtModule | null\n }\n return _oxfmt\n}\n\nasync function formatFile(filePath: string, content: string): Promise<void> {\n const oxfmt = await resolveOxfmt(process.cwd())\n if (!oxfmt) return\n // The CLI binary auto-discovers `.oxfmtrc.json`, but the JS API\n // does NOT — we walk up from the file being formatted so adopters'\n // workspace config drives the output. Skip formatting entirely\n // when no config is found (matches the old prettier failure mode:\n // raw templates already follow project conventions).\n const options = await loadOxfmtConfig(filePath)\n if (options === null) return\n const result = await oxfmt.format(filePath, content, options)\n if (result.code === content) return\n await writeFile(filePath, result.code, 'utf-8')\n}\n\nconst _oxfmtConfigCache = new Map<string, Record<string, unknown> | null>()\n\n/**\n * Walk up from `filePath`'s directory looking for `.oxfmtrc.json`.\n * Returns `null` when no config is found anywhere on the path —\n * generators then leave the raw template alone (which already\n * follows project conventions). Cached per starting directory so\n * the walk is one-shot per generator run.\n */\nasync function loadOxfmtConfig(filePath: string): Promise<Record<string, unknown> | null> {\n let dir = dirname(filePath)\n const startDir = dir\n if (_oxfmtConfigCache.has(startDir)) return _oxfmtConfigCache.get(startDir)!\n while (true) {\n const configPath = join(dir, '.oxfmtrc.json')\n if (existsSync(configPath)) {\n try {\n const raw = await readFile(configPath, 'utf-8')\n const parsed = JSON.parse(raw) as Record<string, unknown>\n // The `$schema` and `ignorePatterns` fields are runner-only —\n // strip before passing to format() so it doesn't reject them\n // as unknown options.\n delete parsed['$schema']\n delete parsed.ignorePatterns\n _oxfmtConfigCache.set(startDir, parsed)\n return parsed\n } catch {\n _oxfmtConfigCache.set(startDir, null)\n return null\n }\n }\n const parent = dirname(dir)\n if (parent === dir) {\n _oxfmtConfigCache.set(startDir, null)\n return null\n }\n dir = parent\n }\n}\n\n/** Reset cached oxfmt resolution. Tests use this; production code shouldn't. */\nexport function clearFormatCache(): void {\n _oxfmt = undefined\n _oxfmtConfigCache.clear()\n}\n\n/** Ensure a directory exists */\nexport async function ensureDirectory(dir: string): Promise<void> {\n await mkdir(dir, { recursive: true })\n}\n\n/** Check if a file exists */\nexport async function fileExists(filePath: string): Promise<boolean> {\n try {\n await access(filePath)\n return true\n } catch {\n return false\n }\n}\n\n/** Read a JSON file */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport async function readJsonFile<T = any>(filePath: string): Promise<T> {\n const content = await readFile(filePath, 'utf-8')\n return JSON.parse(content)\n}\n","import pc from 'picocolors'\n\nexport { pc as colors }\n\nconst METHOD_COLOR_MAP: Record<string, (s: string) => string> = {\n GET: pc.green,\n POST: pc.cyan,\n PUT: pc.yellow,\n PATCH: pc.magenta,\n DELETE: pc.red,\n}\n\n/** Color an HTTP method string for terminal display */\nexport function httpMethodColor(method: string): string {\n const fn = METHOD_COLOR_MAP[method] ?? pc.dim\n return fn(method.padEnd(7))\n}\n\n/** Color a severity tag for terminal display (padded to 10 chars) */\nexport function severityColor(severity: string): string {\n const tag = `[${severity}]`.padEnd(10)\n switch (severity) {\n case 'CRITICAL':\n return pc.red(tag)\n case 'WARNING':\n return pc.yellow(tag)\n case 'INFO':\n return pc.blue(pc.dim(tag))\n default:\n return tag\n }\n}\n","import * as clack from '@clack/prompts'\nimport { colors } from './colors'\n\nexport const symbols = {\n success: colors.green('✓'),\n error: colors.red('✖'),\n warning: colors.yellow('⚠'),\n info: colors.blue('ℹ'),\n}\n\n/** Show branded intro banner */\nexport function intro(title: string): void {\n clack.intro(colors.bgCyan(colors.black(` ${title} `)))\n}\n\n/** Show closing message */\nexport function outro(message: string): void {\n clack.outro(message)\n}\n\n/** Handle cancellation — print message and exit */\nfunction handleCancel(value: unknown): void {\n if (clack.isCancel(value)) {\n clack.cancel('Operation cancelled.')\n process.exit(0)\n }\n}\n\n/** Text input prompt */\nexport async function text(opts: {\n message: string\n placeholder?: string\n defaultValue?: string\n validate?: (value: string) => string | void\n}): Promise<string> {\n const value = await clack.text(opts as any)\n handleCancel(value)\n return value as string\n}\n\n/** Single select prompt */\nexport async function select<T>(opts: {\n message: string\n options: { value: T; label: string; hint?: string }[]\n initialValue?: T\n}): Promise<T> {\n const value = await clack.select(opts as any)\n handleCancel(value)\n return value as T\n}\n\n/** Multi-select prompt with checkboxes */\nexport async function multiSelect<T>(opts: {\n message: string\n options: { value: T; label: string; hint?: string }[]\n required?: boolean\n initialValues?: T[]\n}): Promise<T[]> {\n const value = await clack.multiselect(opts as any)\n handleCancel(value)\n return value as T[]\n}\n\n/** Yes/no confirmation prompt */\nexport async function confirm(opts: {\n message: string\n active?: string\n inactive?: string\n initialValue?: boolean\n}): Promise<boolean> {\n const value = await clack.confirm(opts)\n handleCancel(value)\n return value as boolean\n}\n\n/** Create a spinner for progress indication */\nexport function spinner() {\n return clack.spinner()\n}\n\n/** Log utilities for styled messages inside clack flow */\nexport const log = clack.log\n","/**\n * Overlay scaffolding — project files as real directories instead of TS\n * functions that return strings.\n *\n * A layer is a directory under `packages/cli/templates/`:\n *\n * - `files/` mirrors the project. Layers render in order; a later layer's\n * file replaces an earlier one at the same path, and a `<name>.append` file\n * is added to the end of `<name>` instead.\n * - `feature.json` (optional) lists the packages the layer needs and its\n * **integrations**: entries for the slots that shared files expose.\n *\n * File names: a `_dot_` path segment prefix becomes `.` (`_dot_gitignore` →\n * `.gitignore`), because npm publish drops or rewrites real dotfiles.\n *\n * Slots: a shared file marks where layers plug in with a comment line.\n * `// @kick:imports` becomes the merged import statements of every rendered\n * integration; `// @kick:<slot>` becomes that slot's entries, one `code,` per\n * line at the marker's indentation. An empty slot inside its own `key: [` …\n * `],` block drops the whole block, so an app with no adapters has no\n * `adapters: []`. This is what keeps layers out of each other's way: swagger\n * never edits the entry file, it declares an `adapter` entry.\n */\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport { dirname, join, sep } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst here = dirname(fileURLToPath(import.meta.url))\n\n/**\n * `packages/cli/templates` — one level above the bundle (`dist/*.mjs`), two\n * above this source file (`src/scaffold/overlay.ts`), so tests can import it\n * from source.\n */\nexport const TEMPLATES_DIR = [\n join(here, '..', 'templates'),\n join(here, '..', '..', 'templates'),\n].find((dir) => existsSync(join(dir, 'base')))!\n\n/** An import an integration needs. Merged per module across integrations. */\nexport interface ImportSpec {\n from: string\n names?: string[]\n default?: string\n}\n\n/**\n * What a layer contributes to shared files. With a `slot`, `code` is\n * rendered there and `import` only when that slot exists in the file — so an\n * `express.json()` middleware doesn't leave an unused `express` import in a\n * template without a middleware list. Without a `slot`, `import` is always\n * rendered.\n */\nexport interface Integration {\n import?: ImportSpec\n slot?: string\n code?: string\n}\n\n/** `feature.json`. Package versions come from the scaffold's resolved version map. */\nexport interface FeatureManifest {\n dependencies?: string[]\n devDependencies?: string[]\n /** Install-script answers for packages this layer pulls in (see `approveInstallScripts`). */\n builds?: Record<string, boolean>\n integrations?: Integration[]\n /** package.json scripts this layer adds or replaces. */\n scripts?: Record<string, string>\n}\n\nexport interface RenderedProject {\n files: Map<string, string>\n dependencies: string[]\n devDependencies: string[]\n builds: Record<string, boolean>\n /** Every layer's integrations plus `extra`, in layer order — `kick add` wires these. */\n integrations: Integration[]\n /** package.json scripts, later layers winning. */\n scripts: Record<string, string>\n}\n\n/** The project path a template file lands at: `_dot_` segment prefixes become `.`. */\nexport function outputPath(templatePath: string): string {\n return templatePath\n .split('/')\n .map((segment) => (segment.startsWith('_dot_') ? `.${segment.slice(5)}` : segment))\n .join('/')\n}\n\n/**\n * Render layers into project files plus the packages they need. Pure apart\n * from reading the template directories; the caller writes the files.\n *\n * `extra` adds integrations computed at scaffold time (a value the user\n * typed can't live in a static layer). `vars` fills `{{name}}` in\n * integration code.\n */\nexport function renderLayers(\n layers: readonly string[],\n options: {\n templatesDir?: string\n extra?: Integration[]\n vars?: Record<string, string>\n } = {},\n): RenderedProject {\n const templatesDir = options.templatesDir ?? TEMPLATES_DIR\n const files = new Map<string, string>()\n const dependencies: string[] = []\n const devDependencies: string[] = []\n const builds: Record<string, boolean> = {}\n const integrations: Integration[] = []\n const scripts: Record<string, string> = {}\n\n for (const layer of layers) {\n const dir = join(templatesDir, layer)\n if (!existsSync(dir)) throw new Error(`Unknown scaffold layer \"${layer}\" (${dir})`)\n\n const manifestPath = join(dir, 'feature.json')\n if (existsSync(manifestPath)) {\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as FeatureManifest\n dependencies.push(...(manifest.dependencies ?? []))\n devDependencies.push(...(manifest.devDependencies ?? []))\n Object.assign(builds, manifest.builds)\n integrations.push(...(manifest.integrations ?? []))\n Object.assign(scripts, manifest.scripts)\n }\n\n const root = join(dir, 'files')\n if (!existsSync(root)) continue\n // String entries, not Dirents: `Dirent.parentPath` needs Node 20.12.\n for (const rel of readdirSync(root, { recursive: true, encoding: 'utf-8' }).toSorted()) {\n const abs = join(root, rel)\n if (!statSync(abs).isFile()) continue\n const contents = readFileSync(abs, 'utf-8')\n const path = outputPath(rel.split(sep).join('/'))\n if (path.endsWith('.append')) {\n const target = path.slice(0, -'.append'.length)\n files.set(target, (files.get(target) ?? '') + contents)\n } else {\n files.set(path, contents)\n }\n }\n }\n\n integrations.push(...(options.extra ?? []))\n const vars = options.vars ?? {}\n const fill = (text: string) => text.replace(/\\{\\{(\\w+)\\}\\}/g, (all, key) => vars[key] ?? all)\n for (const [path, contents] of files) {\n if (contents.includes('// @kick:')) files.set(path, renderSlots(contents, integrations, fill))\n }\n\n return {\n files,\n dependencies: [...new Set(dependencies)],\n // A package a layer needs at runtime (ws for WsAdapter) stays out of devDependencies.\n devDependencies: [...new Set(devDependencies)].filter((d) => !dependencies.includes(d)),\n builds,\n integrations,\n scripts,\n }\n}\n\n/**\n * Fill `{{name}}` placeholders in rendered files. Separate from rendering so\n * a value can depend on the result (README lists the packages the layers\n * chose). Unknown names are left as written.\n */\nexport function fillVars(\n files: ReadonlyMap<string, string>,\n vars: Record<string, string>,\n): Map<string, string> {\n const fill = (text: string) =>\n text.replace(/\\{\\{(\\w+)\\}\\}/g, (all, key: string) => (key in vars ? vars[key]! : all))\n return new Map([...files].map(([path, contents]) => [path, fill(contents)]))\n}\n\nconst MARKER = /^([ \\t]*)\\/\\/ @kick:([\\w-]+)[ \\t]*$/\n\n/**\n * Fill one file's slot markers. `// @kick:imports` gets only the names the\n * rendered file uses and doesn't import itself, so one shared list of imports\n * serves every file — a test doesn't inherit the entry file's `bootstrap`.\n */\nexport function renderSlots(\n source: string,\n integrations: readonly Integration[],\n fill: (text: string) => string = (text) => text,\n): string {\n const lines = source.split('\\n')\n const slots = new Set(lines.map((line) => MARKER.exec(line)?.[2]).filter(Boolean))\n const active = integrations.filter((i) => !i.slot || slots.has(i.slot))\n\n const out: string[] = []\n let importsAt = -1\n for (let i = 0; i < lines.length; i++) {\n const match = MARKER.exec(lines[i]!)\n if (!match) {\n out.push(lines[i]!)\n continue\n }\n const [, indent, slot] = match as unknown as [string, string, string]\n if (slot === 'imports') {\n importsAt = out.length\n continue\n }\n const rendered = active\n .filter((entry) => entry.slot === slot && entry.code)\n .map((entry) => indentBlock(`${fill(entry.code!)},`, indent))\n if (rendered.length > 0) {\n out.push(...rendered)\n continue\n }\n // Empty: drop an enclosing `key: [` … `],` block that holds only this marker.\n const prev = out.at(-1)\n if (prev?.trimEnd().endsWith('[') && lines[i + 1]?.trim().startsWith(']')) {\n out.pop()\n i++\n }\n }\n if (importsAt >= 0) {\n const word = (name: string) => new RegExp(`(?<![\\\\w$])${name.replace(/\\$/g, '\\\\$')}(?![\\\\w$])`)\n // Imports the file already writes itself, and the rest of its code.\n const text = out.join('\\n')\n const statements = /^import\\b[^;]*?\\bfrom\\s*['\"][^'\"]+['\"]/gm\n const own = (text.match(statements) ?? []).join('\\n')\n // Whole-line comments don't use a name: kick.config.ts mentions `bootstrap({ runtime })`.\n const body = text.replace(statements, '').replace(/^[ \\t]*\\/\\/.*$/gm, '')\n const used = (name: string) => word(name).test(body) && !word(name).test(own)\n const specs = active.flatMap((entry) => {\n if (!entry.import) return []\n const { names, default: def, from } = entry.import\n const kept = { from, names: names?.filter(used), default: def && used(def) ? def : undefined }\n return kept.names?.length || kept.default ? [kept] : []\n })\n out.splice(importsAt, 0, ...renderImports(specs))\n }\n return out.join('\\n')\n}\n\nfunction indentBlock(code: string, indent: string): string {\n return code\n .split('\\n')\n .map((line) => (line ? indent + line : line))\n .join('\\n')\n}\n\n/** One statement per module, names merged in first-seen order; wrapped past 100 columns. */\nexport function renderImports(specs: readonly ImportSpec[]): string[] {\n const byModule = new Map<string, { names: string[]; default?: string }>()\n for (const spec of specs) {\n const entry = byModule.get(spec.from) ?? { names: [] }\n entry.default ??= spec.default\n for (const name of spec.names ?? []) if (!entry.names.includes(name)) entry.names.push(name)\n byModule.set(spec.from, entry)\n }\n return [...byModule].map(([from, { names, default: def }]) => {\n const parts = [def, names.length ? `{ ${names.join(', ')} }` : undefined].filter(Boolean)\n const line = `import ${parts.join(', ')} from '${from}'`\n if (line.length <= 100 || names.length === 0) return line\n const head = def ? `${def}, ` : ''\n return `import ${head}{\\n${names.map((n) => ` ${n},`).join('\\n')}\\n} from '${from}'`\n })\n}\n","/**\n * Which package manager a project uses — for installing (`kick add`) and for\n * the commands the CLI prints.\n */\nimport { existsSync, readFileSync } from 'node:fs'\nimport { dirname, resolve } from 'node:path'\nimport { loadKickConfig, PACKAGE_MANAGERS, type PackageManager } from '../config'\n\nconst LOCKFILES: [string, PackageManager][] = [\n ['pnpm-lock.yaml', 'pnpm'],\n ['yarn.lock', 'yarn'],\n ['bun.lock', 'bun'],\n ['bun.lockb', 'bun'],\n ['package-lock.json', 'npm'],\n]\n\n/** The package manager of the nearest folder up from `fromDir` holding a lockfile. */\nfunction detectFromLockfile(fromDir: string): PackageManager | null {\n for (let dir = fromDir; ; dir = dirname(dir)) {\n const hit = LOCKFILES.find(([file]) => existsSync(resolve(dir, file)))\n if (hit) return hit[1]\n if (dirname(dir) === dir) return null\n }\n}\n\n/**\n * Read `packageManager` from the nearest ancestor `package.json` that\n * declares the field (corepack convention: `\"pnpm@10.0.0\"`). Climbs so\n * monorepo sub-packages inherit the workspace pm even when their own\n * package.json omits the field.\n */\nfunction packageManagerFromPackageJson(fromDir: string): PackageManager | null {\n let dir: string | null = fromDir\n while (dir) {\n const pkgPath = resolve(dir, 'package.json')\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'))\n const field: unknown = pkg.packageManager\n if (typeof field === 'string') {\n const name = field.split('@')[0] as PackageManager\n if (PACKAGE_MANAGERS.includes(name)) return name\n }\n } catch {\n // ignore — keep climbing\n }\n }\n const parent = dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n return null\n}\n\nexport type PackageManagerSource =\n | 'flag'\n | 'config'\n | 'package.json'\n | 'lockfile'\n | 'user-agent'\n | 'default'\n\n/**\n * Resolve which package manager to use, in priority order:\n * 1. `--pm` CLI flag\n * 2. `packageManager` in kick.config\n * 3. `packageManager` in nearest ancestor package.json (corepack)\n * 4. The nearest ancestor folder's lockfile\n * 5. The package manager that launched the CLI (`npm_config_user_agent`)\n * 6. `'npm'` fallback\n *\n * Returns the chosen pm plus the source for callers that want to log\n * the resolution path.\n */\nexport async function resolvePackageManagerWithSource(\n flagPm: string | undefined,\n fromDir = process.cwd(),\n): Promise<{ pm: PackageManager; source: PackageManagerSource }> {\n if (flagPm && PACKAGE_MANAGERS.includes(flagPm as PackageManager)) {\n return { pm: flagPm as PackageManager, source: 'flag' }\n }\n\n const config = await loadKickConfig(fromDir)\n if (config?.packageManager && PACKAGE_MANAGERS.includes(config.packageManager)) {\n return { pm: config.packageManager, source: 'config' }\n }\n\n const fromPkg = packageManagerFromPackageJson(fromDir)\n if (fromPkg) return { pm: fromPkg, source: 'package.json' }\n\n const fromLock = detectFromLockfile(fromDir)\n if (fromLock) return { pm: fromLock, source: 'lockfile' }\n\n // Outside any project: the one that launched the CLI (`pnpm dlx`, `bunx`,\n // `yarn dlx`, `npx`) — e.g. `pnpm dlx @forinda/kickjs-cli new app --yes`.\n const fromAgent = process.env.npm_config_user_agent?.split('/')[0] as PackageManager | undefined\n if (fromAgent && PACKAGE_MANAGERS.includes(fromAgent)) {\n return { pm: fromAgent, source: 'user-agent' }\n }\n\n return { pm: 'npm', source: 'default' }\n}\n\n/** Convenience wrapper for callers that don't care about the source. */\nexport async function resolvePackageManager(\n flagPm: string | undefined,\n fromDir = process.cwd(),\n): Promise<PackageManager> {\n const { pm } = await resolvePackageManagerWithSource(flagPm, fromDir)\n return pm\n}\n\n/**\n * The project's package manager without reading kick.config — for messages\n * printed from synchronous code: `packageManager`, then the lockfile, then npm.\n */\nexport function detectPackageManager(fromDir = process.cwd()): PackageManager {\n return packageManagerFromPackageJson(fromDir) ?? detectFromLockfile(fromDir) ?? 'npm'\n}\n","/**\n * Agent skills as text files in scaffold layers: `templates/<layer>/skills/<slug>.txt`,\n * a frontmatter block (`name`, `description`) and the body. Plain text, so no\n * formatter touches them; `{{pm}}`, `{{kick}}`, `{{test}}` and `{{moduleEntry}}`\n * are filled when they're written out as `.agents/skills/<slug>/SKILL.md`.\n */\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport { execBin, runScript, type PackageManager } from '../config'\nimport type { ModuleStyle } from '../generators/templates/types'\nimport { fillVars, TEMPLATES_DIR } from './overlay'\n\nexport interface SkillVars {\n pm: string\n kick: string\n test: string\n moduleEntry: string\n}\n\nexport interface LayerSkill {\n slug: string\n name: string\n description: string\n body: string\n}\n\n/** The values a skill's placeholders take for this package manager and module style. */\nexport function skillVars(pm: string, style: ModuleStyle): SkillVars {\n return {\n pm,\n kick: execBin(pm as PackageManager, 'kick'),\n test: runScript(pm as PackageManager, 'test'),\n // A class module is passed bare; a define module is invoked.\n moduleEntry: style === 'class' ? 'UserModule' : 'UserModule()',\n }\n}\n\n/** Every skill the `layers` carry, in layer order, each layer's by slug. */\nexport function readLayerSkills(\n layers: readonly string[],\n vars: SkillVars,\n dir = TEMPLATES_DIR,\n): LayerSkill[] {\n const out: LayerSkill[] = []\n for (const layer of layers) {\n const folder = join(dir, layer, 'skills')\n if (!existsSync(folder)) continue\n for (const file of readdirSync(folder)\n .filter((f) => f.endsWith('.txt'))\n .toSorted()) {\n const text = readFileSync(join(folder, file), 'utf8')\n const m = /^---\\nname: (.*)\\ndescription: (.*)\\n---\\n\\n([\\s\\S]*)$/.exec(text)\n if (!m) throw new Error(`${layer}/skills/${file}: expected a name / description frontmatter`)\n // A text file ends with a newline; SKILL.md adds its own.\n const filled = fillVars(new Map([['body', m[3]!.replace(/\\n$/, '')]]), { ...vars })\n out.push({\n slug: file.slice(0, -'.txt'.length),\n name: m[1]!,\n description: m[2]!,\n body: filled.get('body')!,\n })\n }\n }\n return out\n}\n\n/**\n * The feature layers an app uses: each `feature-*` layer whose `feature.json`\n * lists dependencies that are all in `package.json` (dependencies or\n * devDependencies). A layer that lists none (devtools) never counts.\n */\nexport function detectFeatureLayers(appDir: string, dir = TEMPLATES_DIR): string[] {\n // A fullstack workspace root keeps .agents/ but the app's packages are server/'s.\n const dirs = [appDir]\n if (\n !existsSync(join(appDir, 'kick.config.ts')) &&\n existsSync(join(appDir, 'server/kick.config.ts'))\n )\n dirs.push(join(appDir, 'server'))\n const installed = new Set<string>()\n for (const d of dirs) {\n let pkg: { dependencies?: Record<string, string>; devDependencies?: Record<string, string> }\n try {\n pkg = JSON.parse(readFileSync(join(d, 'package.json'), 'utf8'))\n } catch {\n continue\n }\n for (const name of Object.keys({ ...pkg.dependencies, ...pkg.devDependencies }))\n installed.add(name)\n }\n if (!installed.size) return []\n return readdirSync(dir)\n .filter((layer) => layer.startsWith('feature-'))\n .toSorted()\n .filter((layer) => {\n const file = join(dir, layer, 'feature.json')\n if (!existsSync(file)) return false\n const deps = (JSON.parse(readFileSync(file, 'utf8')) as { dependencies?: string[] })\n .dependencies\n return !!deps?.length && deps.every((d) => installed.has(d))\n })\n}\n","import { execBin, runScript, type PackageManager } from '../../config'\nimport type { ModuleStyle } from './types'\nimport { readLayerSkills, skillVars } from '../../scaffold/skills'\n\n/** How to start the dev server: a non-pnpm fullstack root has `dev:server` and `dev:web`, no `dev`. */\nfunction devCommand(pm: string, template: ProjectTemplate): string {\n const p = pm as PackageManager\n return template === 'fullstack' && p !== 'pnpm'\n ? `${runScript(p, 'dev:server')} + ${runScript(p, 'dev:web')}`\n : runScript(p, 'dev')\n}\ntype ProjectTemplate = 'rest' | 'minimal' | 'fullstack' | 'inertia'\n\n/**\n * Generate CLAUDE.md.\n *\n * v4 update: this file is intentionally thin. AGENTS.md is the\n * canonical, multi-agent project reference (Claude / Copilot /\n * Codex / Gemini / etc.) — duplicating it here meant two files\n * drifting out of sync after every framework change. The generated\n * CLAUDE.md now redirects there + adds Claude-specific affordances\n * only.\n */\nexport function generateClaude(name: string, template: ProjectTemplate, pm: string): string {\n return `# CLAUDE.md — ${name}\n\n**Read \\`./.agents/AGENTS.md\\` first.** It is the canonical, multi-agent\nreference for this project (Claude, Copilot, Codex, Gemini, etc.) —\nproject conventions, structure, decorator patterns, env wiring, CLI\ngenerators, every gotcha.\n\n**Skills, when you want them:** \\`kick g agents --only skills\\` writes\n\\`./.agents/skills/\\` — one task-oriented skill per subdirectory\n(\\`add-module/\\`, \\`write-controller-test/\\`, \\`bootstrap-export/\\`,\n\\`deny-list/\\`, …), each a \\`SKILL.md\\` with YAML frontmatter (\\`name\\`,\n\\`description\\`) and the recipe body. The structure follows the Claude\nCode skills convention — agents that auto-load skills from\n\\`.agents/skills/\\` pick each up by its frontmatter. \\`kick g agents\\`\nalone also adds \\`GEMINI.md\\` and \\`COPILOT.md\\`.\n\nThis file is a thin Claude-specific layer on top of those two; when\nthey disagree on anything substantive, treat \\`.agents/AGENTS.md\\` as\nauthoritative and flag the discrepancy.\n\n## Why \\`.agents/\\` + this thin pointer\n\n\\`.agents/AGENTS.md\\` is what every agent reads (Codex, Cursor, Gemini,\nCopilot, Aider, …) — one canonical source so the prose doesn't drift\nacross copies. \\`CLAUDE.md\\` is what Claude Code automatically loads as\nproject context on each conversation, so it stays at the project root.\nKeeping CLAUDE.md slim and pointing at \\`.agents/\\` avoids two\nout-of-sync copies of the same content. Per-agent files\n(\\`.agents/GEMINI.md\\`, \\`.agents/COPILOT.md\\`) live alongside\n\\`AGENTS.md\\` for tool-specific notes that don't belong in the shared\nprose.\n\n## Claude-specific notes\n\n- **Slash commands** — \\`/help\\` for Claude Code commands; \\`/init\\`\n to refresh project memory if AGENTS.md changes substantially.\n- **Feedback** — file issues at <https://github.com/anthropics/claude-code/issues>.\n- **Persistent memory** — Claude maintains user/feedback/project/\n reference memories under \\`.claude/memory/\\`. If you ask for\n something that contradicts a remembered preference, Claude flags\n it before acting; corrections update memory automatically.\n- **Long-running tasks** — \\`/loop\\` and \\`/schedule\\` for recurring\n or background work. Useful for \"wait for the deploy then open a\n cleanup PR\" or \"every Monday triage the issue board\" patterns.\n\n## Quick reference (full version in .agents/AGENTS.md)\n\n\\`\\`\\`bash\n${pm} install\n${devCommand(pm, template)} # Dev server with HMR + typegen\n${runScript(pm as PackageManager, 'build')} && ${runScript(pm as PackageManager, 'start')} # Production\n${runScript(pm as PackageManager, 'test')} # Vitest\n${template === 'fullstack' ? runScript(pm as PackageManager, 'typecheck') : `${execBin(pm as PackageManager, 'kick')} typecheck`} # tsc/tsgo, whichever the project has\n${template === 'fullstack' ? runScript(pm as PackageManager, 'format') : `${execBin(pm as PackageManager, 'kick')} format`} # oxfmt\n\\`\\`\\`\n\n\\`kick\\` is this project's dev dependency, not a global command: every \\`kick …\\`\nin these docs runs as \\`${execBin(pm as PackageManager, 'kick')} …\\` in a shell.\n\n## v4 framework reminders\n\nWhen generating or modifying code in this project, stay aligned with the v4 conventions documented in \\`.agents/AGENTS.md\\`:\n\n- **Adapters**: \\`defineAdapter()\\` factory — never \\`class implements AppAdapter\\`.\n- **Plugins**: \\`definePlugin()\\` factory — never plain function returning \\`KickPlugin\\`.\n- **DI tokens**: \\`<scope>/<area>/<key>[:<instance>]\\` — a lowercase scope, then slash-separated segments (e.g. \\`'app/users/repository'\\`, \\`'app/Users/repository'\\`, \\`'mycorp/cache/redis'\\`). First-party uses the reserved \\`'kick/'\\` prefix; this project owns its own scope.\n- **Decorators**: \\`@Controller()\\` (no path arg — mount prefix comes from \\`routes().path\\`).\n- **HTTP runtime**: this app may run on Express, Fastify, or h3 — check \\`kick.config.ts\\` \\`runtime\\` (or \\`bootstrap({ runtime })\\`) before writing engine-specific code. Prefer engine-neutral \\`ctx\\` APIs (\\`ctx.json\\`/\\`ctx.body\\`/\\`ctx.params\\`/\\`ctx.sse\\`); don't assume \\`ctx.req\\` is an Express request. Uploads (\\`@FileUpload\\` → \\`ctx.file\\`/\\`ctx.files\\`) work on all three (\\`kick add upload\\` installs the driver). Full rules in \\`.agents/AGENTS.md\\` → \"HTTP runtime\".\n- **Module entry file** MUST be named \\`<name>.module.ts\\` and live under \\`src/modules/<name>/\\`. The Vite plugin auto-discovers \\`*.module.[tj]sx?\\` for graceful HMR — a misnamed \\`projects.ts\\` silently degrades every save into a full restart.\n- **Env**: schema lives in \\`src/config/index.ts\\`; \\`import './config'\\` MUST be the first import in \\`src/index.ts\\` (side-effect registers the schema before any \\`@Value\\` resolves).\n- **Assets**: drop new template files into \\`src/templates/<namespace>/\\`; the dev watcher auto-rebuilds the \\`KickAssets\\` augmentation + \\`assets.x.y()\\` re-walks on next call. No restart, no manual build.\n- **Context Contributors** (\\`defineContextDecorator\\`) over \\`@Middleware()\\` for ctx-population work.\n- **Repos under tests**: \\`Container.create()\\` for isolation — never \\`new Container()\\` or \\`getInstance().reset()\\`.\n- **Bootstrap export**: \\`src/index.ts\\` must end with \\`export const app = await bootstrap({ ... })\\`. The Vite plugin and \\`createTestApp\\` import the named \\`app\\`; without the export, HMR silently degrades to full restarts.\n- **Thin entry file**: aggregate \\`modules\\`, \\`middlewares\\`, \\`plugins\\`, \\`adapters\\` in their own folders (\\`src/modules/index.ts\\`, \\`src/middleware/index.ts\\`, …) and pass them by name to \\`bootstrap()\\` — never inline the lists in \\`src/index.ts\\`.\n- **Refresh these files**: \\`kick g agents -f\\` regenerates \\`CLAUDE.md\\` at the project root and \\`.agents/AGENTS.md\\` + \\`.agents/GEMINI.md\\` + \\`.agents/COPILOT.md\\` + every \\`.agents/skills/<name>/SKILL.md\\` from the latest CLI templates. Hand-edited content is overwritten — keep customisation in \\`.agents/AGENTS.local.md\\` or per-skill \\`SKILL.local.md\\` files alongside.\n\nFor everything else (controllers, services, modules, RequestContext API, generators, CLI commands, package additions, env wiring, troubleshooting) → \\`.agents/AGENTS.md\\`.\n`\n}\n\n/** Generate AGENTS.md with AI agent guide */\nexport function generateAgents(name: string, template: ProjectTemplate, pm: string): string {\n return `# AGENTS.md — AI Agent Guide for ${name}\n\nThis guide is the **canonical, multi-agent reference** for this KickJS\napplication — Claude, Copilot, Codex, Gemini, etc. all read it first.\nPer-agent files (\\`CLAUDE.md\\`, \\`GEMINI.md\\`, etc.) are thin layers that\nadd tool-specific affordances on top.\n\n## Before You Start\n\n1. Run \\`${pm} install\\` to install dependencies\n2. Run \\`${devCommand(pm, template)}\\` to verify the app starts\n\n\\`kick\\` is this project's dev dependency, not a global command: every \\`kick …\\`\nbelow runs as \\`${execBin(pm as PackageManager, 'kick')} …\\` in a shell.${\n template === 'fullstack'\n ? `\n\n## Fullstack workspace layout\n\nThis is a WORKSPACE root — the KickJS API lives in \\`server/\\`, the typed web\napp in \\`web/\\`. Run both with \\`${devCommand(pm, template)}\\`. From this root,\n\\`${runScript(pm as PackageManager, 'test')}\\`, \\`${runScript(pm as PackageManager, 'typecheck')}\\` and \\`${runScript(pm as PackageManager, 'format')}\\` reach into\n\\`server/\\` (and \\`web/\\` for typecheck).\n\nThe type loop (do not break it):\n1. \\`server/\\` handlers RETURN their payloads → \\`kick typegen\\` emits\n \\`server/.kickjs/types/kick__client.d.ts\\`: the ambient \\`KickClientApi\\`\n namespace, every response resolved to a plain shape. \\`kick dev\\` writes it\n at startup but NOT on save — run \\`kick typegen\\` in \\`server/\\` after changing a route or a\n response (the root \\`build\\` script runs it too).\n2. \\`web/tsconfig.json\\` lists that file in \\`compilerOptions.types\\`.\n3. \\`web/src/api.ts\\` = \\`createClient<KickClientApi.Api>({ baseUrl })\\`\n — every call site is typed from the server's handlers. \\`baseUrl\\` is the\n relative \\`/api/v1\\` (Vite proxies it in dev) unless \\`VITE_API_URL\\` points at\n an API on another origin.\n\nRules: kick commands (\\`kick g\\`, \\`kick typegen\\`, \\`kick dev\\`, \\`kick typecheck\\`)\nrun in \\`server/\\` — the root has no \\`kick.config.ts\\`; never import server runtime code into \\`web/\\` (the d.ts bridge is\ntype-only); prefer return-value handlers so responses stay inferable.`\n : ''\n }\n3. Read the [KickJS documentation](https://kickjs.app/) for framework details\n\n## HTTP runtime — DON'T assume Express-only\n\nKickJS is **engine-pluggable**. It runs on **Express (default), Fastify, or h3** —\nchosen with one line: \\`bootstrap({ runtime: fastifyRuntime() })\\`. Before writing\nany engine-specific code, **check which engine this project uses**:\n\n- \\`kick.config.ts\\` → the \\`runtime\\` field (\\`'express'\\` | \\`'fastify'\\` | \\`'h3'\\`), and/or\n- \\`src/index.ts\\` → the \\`runtime:\\` passed to \\`bootstrap()\\`, and/or\n- \\`package.json\\` → \\`fastify\\` / \\`h3\\` in deps.\n\nRules that keep generated code correct on **every** engine:\n\n- **Prefer return-value handlers.** \\`return payload\\` sends 200 json on every\n engine and lets \\`kick typegen\\` infer the response type into\n \\`KickRoutes.Api\\` (consumed by the \\`@forinda/kickjs-client\\` typed client);\n \\`reply(status, body)\\` for non-200, \\`reply.noContent()\\` for 204. A declared\n \\`{ response: schema }\\` on the route feeds BOTH the OpenAPI success response\n and the typegen response type. \\`ctx.json(...)\\` stays fully supported but\n infers \\`unknown\\`.\n- **Lifecycle hooks:** \\`@PostConstruct()\\` after instantiation; \\`@PreDestroy()\\`\n when a REQUEST-scoped service's request closes (release transactions/handles).\n- **Write to \\`ctx\\`, not the raw request/response.** \\`ctx.json()\\`, \\`ctx.body\\`,\n \\`ctx.params\\`, \\`ctx.query\\`, \\`ctx.set/get\\`, \\`ctx.sse()\\` are engine-neutral and\n work identically everywhere. \\`ctx.req\\` / \\`ctx.res\\` are the engine-native\n objects — their **type follows the active runtime** (Express by default; the\n \\`kick/runtime\\` typegen retypes them to Fastify / h3 when \\`runtime\\` is set).\n Don't assume \\`ctx.req\\` is an \\`express.Request\\` in portable code.\n- **Global middleware** in \\`bootstrap({ middlewares })\\` is connect-style\n \\`(req, res, next)\\` — it runs on all engines (Fastify via \\`@fastify/middie\\`,\n h3 via \\`fromNodeHandler\\`). But on Fastify / h3 the engine parses the body\n natively, so the default \\`express.json()\\` is **auto-skipped** (\\`nativeBodyParsing\\`).\n Don't add \\`express.json()\\` manually on those engines.\n- **File uploads** work on all three: \\`@FileUpload({ mode, fieldName, ... })\\` →\n \\`ctx.file\\` / \\`ctx.files\\` (same Multer-shaped object everywhere). Backends:\n Express \\`multer\\`, Fastify \\`@fastify/multipart\\`, h3 native. Run\n \\`kick add upload\\` to install the runtime-correct driver. The \\`@FileUpload\\`\n decorator is **memory-only** (portable); disk / custom-storage (\\`storage\\` /\n \\`dest\\`) is Express-only via the \\`upload.single/array()\\` middleware.\n- **Engine subpaths**: \\`import { fastifyRuntime } from '@forinda/kickjs/fastify'\\`\n or \\`h3Runtime\\` from \\`'@forinda/kickjs/h3'\\`. Express is the zero-config default\n (no import, nothing to install).\n- **Not supported on Fastify / h3**: \\`ctx.render()\\` (no view engine). Calling it\n throws a clear error rather than failing silently.\n- Run \\`kick doctor\\` to verify the runtime's engine peers + upload driver are installed.\n\n## v4 Conventions (don't skip)\n\nKickJS v4 made a handful of structural changes from v3. Internalise these\nbefore generating or modifying code — they are the source of most agent\nmistakes:\n\n- **Adapters** — \\`defineAdapter()\\` factory. Never write \\`class Foo implements AppAdapter\\`.\n\n \\`\\`\\`ts\n export const MyAdapter = defineAdapter<MyOptions>({\n name: 'MyAdapter',\n defaults: { ... },\n build: (config) => ({\n beforeMount({ app }) { /* ... */ },\n afterStart({ server }) { /* ... */ },\n }),\n })\n \\`\\`\\`\n\n- **Plugins** — \\`definePlugin()\\` factory. Same shape, never plain function returning \\`KickPlugin\\`.\n\n- **DI tokens** — \\`<scope>/<area>/<key>[:<instance>]\\`. The scope is\n lowercase; the segments after it are identifiers (\\`kick typegen\\` warns\n on names that don't fit — a bare \\`'UserRepository'\\`, a dotted\n \\`'app.db'\\`):\n\n \\`\\`\\`ts\n const USERS_REPO = createToken<UsersRepo>('app/Users/repository')\n const DB = createToken<Database>('app/Db/connection')\n \\`\\`\\`\n\n The \\`kick/\\` prefix is reserved for first-party packages; this project\n owns its own scope (\\`app/\\`, your domain name, etc.).\n\n- **\\`@Controller()\\`** takes **no arguments**. Set the route prefix with the\n module's \\`routes().path\\`.\n\n- **Env** — the schema lives in \\`src/config/index.ts\\`. \\`src/index.ts\\` imports\n it once, as its **first** import (\\`import './config'\\`, before \\`bootstrap()\\`);\n tests that read config import it too (\\`import '@/config'\\`). Nothing else\n imports from \\`src/config\\`: read values with \\`getEnv('KEY')\\`, an injected\n \\`ConfigService\\` (\\`config.get('KEY')\\`), or \\`@Value('KEY')\\` typed as\n \\`Env<'KEY'>\\` — never \\`process.env\\`. Add a key to the schema before reading it.\n A concern with several keys (a database, a mail provider) gets a typed section\n instead: \\`defineSettings('DB', schema)\\` in the module's own\n \\`<name>.settings.ts\\` — not in \\`src/config\\` — declared by the module that\n needs it (\\`settings: () => [DbSettings]\\`) and read through\n \\`@Inject(DbSettings)\\` or \\`DbSettings.get()\\`. Its variables are \\`DB_*\\`.\n\n- **Module entry files MUST be named \\`<name>.module.ts\\`** — see the Vite\n HMR contract at the top of \"Module Pattern\" below. The CLI enforces this;\n hand-rolled files must too.\n\n- **Assets** — drop new template files into \\`src/templates/<namespace>/\\`\n (or wherever \\`kick.config.ts\\` points). The dev watcher auto-rebuilds the\n \\`KickAssets\\` augmentation; \\`assets.x.y()\\` re-walks on next call. No restart,\n no manual build step.\n\n- **Context over \\`@Middleware()\\`** — when a middleware's only job is to\n populate \\`ctx.set('key', value)\\`, use \\`defineHttpContextDecorator()\\`\n (HTTP) or \\`defineContextDecorator()\\` (transport-agnostic) instead.\n Typed via \\`ContextMeta\\`, ordered via \\`dependsOn\\`, validated at boot.\n Reserve \\`@Middleware()\\` for response short-circuit / stream mutation /\n pre-route-matching work.\n\n Two ground rules around the data flow — both stem from the fact that\n every per-request stage gets its OWN \\`RequestContext\\` instance, all\n reading/writing the SAME \\`AsyncLocalStorage\\`-backed Map:\n - **\\`resolve\\` and \\`onError\\` must RETURN the value.** The runner\n writes it via \\`ctx.set(reg.key, value)\\` on your behalf. Direct\n property assignment (\\`ctx.tenant = …\\`) sticks to the contributor\n instance only — the handler instance never sees it.\n - **Read across instances via \\`ctx.set\\` / \\`ctx.get\\`** (or\n \\`getRequestValue(key)\\` from a service that has no \\`ctx\\` reference\n — typed via \\`MetaValue<K>\\`). \\`ctx.req\\` works because the underlying\n Express request is shared; bespoke property assignments don't.\n\n- **Test isolation** — default to \\`Container.create()\\` for fresh DI state.\n Never \\`new Container()\\` and never \\`getInstance().reset()\\` — both leak\n registrations between tests.\n\n \\`\\`\\`ts\n const container = Container.create()\n // ... register test-scoped providers, run, discard\n \\`\\`\\`\n\n- **Bootstrap export** — \\`src/index.ts\\` MUST end with\n \\`export const app = await bootstrap({ ... })\\`. The Vite plugin imports\n the named \\`app\\` symbol to drive HMR module swaps; testing helpers\n (\\`createTestApp\\`) and the OpenAPI introspector also rely on it. Drop\n the \\`export\\` and \\`kick dev\\` will silently fall back to a full restart\n on every save while \\`createTestApp\\` complains about a missing handle.\n\n- **Keep \\`src/index.ts\\` thin** — collect plugins, modules, middleware, and\n adapters in dedicated folders and re-export aggregated arrays. Do **not**\n inline registration in the entry file:\n\n \\`\\`\\`ts\n // src/modules/index.ts — fluent chain (default for \\`modules.style: 'define'\\`)\n export const modules = defineModules().mount(HelloModule()).mount(UsersModule())\n // OR with \\`modules.style: 'class'\\`:\n // export const modules: AppModuleEntry[] = [HelloModule, UsersModule]\n\n // src/middleware/index.ts\n export const middleware = [helmet(), cors(), requestId(), ...]\n\n // src/plugins/index.ts\n export const plugins = [MetricsPlugin(), AuditPlugin()]\n\n // src/adapters/index.ts\n export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]\n \\`\\`\\`\n\n \\`\\`\\`ts\n // src/index.ts — stays small; one import per category\n import 'reflect-metadata'\n import './config'\n import { bootstrap } from '@forinda/kickjs'\n import { modules } from './modules'\n import { middleware } from './middleware'\n import { plugins } from './plugins'\n import { adapters } from './adapters'\n\n export const app = await bootstrap({ modules, middlewares, plugins, adapters })\n \\`\\`\\`\n\n This keeps the entry file diff-friendly, scales to dozens of modules\n without git churn, and lets each domain own its own registration list.\n The generators (\\`kick g module\\`, \\`kick g middleware\\`, \\`kick g plugin\\`,\n \\`kick g adapter\\`) follow this layout — manual additions should too.\n\nEverything else (controllers, services, modules, RequestContext API, generators,\npackage additions, env access patterns, troubleshooting) is detailed below.\n\n## Where to Find Things\n\n### Application Structure\n\n| What | Where |\n|------|-------|\n| Entry point | \\`src/index.ts\\` |\n| Module registry | \\`src/modules/index.ts\\` |\n| Feature modules | \\`src/modules/<module-name>/\\` |\n| **Module entry file** | \\`src/modules/<name>/<name>.module.ts\\` (filename suffix is required — see Vite HMR contract below) |\n| Env values | \\`.env\\` |\n| Env schema (Zod) | \\`src/config/index.ts\\` |\n| TypeScript config | \\`tsconfig.json\\` |\n| Vite config (HMR) | \\`vite.config.ts\\` |\n| Vitest config | \\`vitest.config.ts\\` |\n| Formatter config | \\`.oxfmtrc.json\\` (oxfmt) |\n| CLI config | \\`kick.config.ts\\` |\n\n### Module Pattern (${template.toUpperCase()})\n\n> **Vite HMR auto-discovery contract:** module files **must** be named \\`<name>.module.ts\\` (or \\`.tsx\\`/\\`.js\\`/\\`.jsx\\`) and live under \\`src/modules/\\`. The Vite plugin scans for \\`*.module.[tj]sx?\\` to drive graceful HMR rebuilds; renaming a file to \\`projects.ts\\` (no \\`.module\\`) silently breaks HMR — saves trigger a full restart instead of a swap. The CLI generator (\\`kick g module <name>\\`) follows the convention; manual files must too.\n\nEach module in \\`src/modules/<name>/\\` typically contains:\n\n${\n template === 'rest'\n ? `\\`\\`\\`\n<name>/\n├── <name>.controller.ts # HTTP routes (@Controller)\n├── <name>.service.ts # Business logic (@Service)\n├── <name>.repository.ts # Data access — factory + contract + token\n├── dtos/ # Request/response schemas (Zod)\n└── <name>.module.ts # Module definition (defineModule factory)\n\\`\\`\\`\n`\n : `\\`\\`\\`\nsrc/\n├── index.ts # Add routes here\n└── ... # Custom structure\n\\`\\`\\`\n`\n}\n\n## Checklist: Adding a Feature\n\nFollow the **\\`kickjs-add-module\\`** skill — it has the ordered steps, the\ncanonical \\`defineModule\\` shape, and the \\`import.meta.glob\\` requirement that\nsilently breaks DI when omitted.\n\n## Common Tasks\n\nEach of these has a skill with the steps and the traps:\n\n| Task | Skill |\n| --- | --- |\n| Add a feature module | \\`kickjs-add-module\\` |\n| Add an adapter | \\`kickjs-add-adapter\\` |\n| Add a plugin | \\`kickjs-add-plugin\\` |\n| Add a context contributor | \\`kickjs-context-contributor\\` |\n| Write a controller test | \\`kickjs-write-controller-test\\` |\n| List endpoint with filters / pagination | \\`kickjs-query-parsing-list-endpoint\\` |\n| Serve bundled assets | \\`kickjs-use-asset-manager\\` |\n| Flag a route (public, exempt, unmetered) | \\`kickjs-route-flags\\` |\n| Add a kick CLI command or generator | \\`kickjs-cli-plugin\\` |\n| Deploy to Netlify / Vercel / Cloudflare | \\`kickjs-deploy\\` |\n| Server-rendered pages with \\`.kick\\` views | \\`kickjs-views\\` |\n| HTML forms: errors, flash, browser checks, CSRF | \\`kickjs-views-forms\\` |\n| Anything else | \\`kickjs-docs-lookup\\` |\n\n## Testing Guidelines\n\nSee the **\\`kickjs-write-controller-test\\`** skill for the canonical test — it\ncarries the call shape, the DI reset, and the env side-effect import, each of\nwhich has its own failure mode.\n\nRun with \\`${pm} run test\\` (\\`test:watch\\` for watch mode).\n\n## Environment Variables\n\nThe schema lives in \\`src/config/index.ts\\` and registers itself with kickjs **at\nmodule load**; \\`src/index.ts\\` imports it (\\`import './config'\\`) before\n\\`bootstrap()\\` so the cache is populated before DI resolves anything. Add a key\nto the schema, put its value in \\`.env\\`, and it is typed everywhere.\n\nRead it with \\`@Value('KEY')\\` for construction-time values, or inject\n\\`ConfigService\\` for dynamic access.\n\nWhen a key reads as \\`undefined\\`, use the **\\`kickjs-env-wiring-check\\`** skill or\nrun \\`kick explain \"ConfigService.get('KEY') returned undefined\"\\`. The cause\ndiffers between app code and tests and the two look identical, which is what\nmakes it slow to spot.\n\n## Standalone Utilities (No DI Required)\n\nThese work anywhere — scripts, plain files, outside \\`@Service\\`/\\`@Controller\\`:\n\n| Utility | Import | Example |\n|---------|--------|---------|\n| \\`Logger.for(name)\\` | \\`@forinda/kickjs\\` | \\`const log = Logger.for('MyScript')\\` |\n| \\`createLogger(name)\\` | \\`@forinda/kickjs\\` | \\`const log = createLogger('Worker')\\` |\n| \\`createToken<T>(name)\\` | \\`@forinda/kickjs\\` | \\`const TOKEN = createToken<string>('app/Db/url')\\` |\n| \\`ref(value)\\` | \\`@forinda/kickjs\\` | \\`const count = ref(0)\\` |\n| \\`computed(fn)\\` | \\`@forinda/kickjs\\` | \\`const doubled = computed(() => count.value * 2)\\` |\n| \\`watch(source, cb)\\` | \\`@forinda/kickjs\\` | \\`watch(() => count.value, (v) => log(v))\\` |\n| \\`reactive(obj)\\` | \\`@forinda/kickjs\\` | \\`const state = reactive({ count: 0 })\\` |\n| \\`HttpException\\` | \\`@forinda/kickjs\\` | \\`throw new HttpException(404, 'Not found')\\` |\n| \\`HttpStatus\\` | \\`@forinda/kickjs\\` | \\`HttpStatus.NOT_FOUND // 404\\` |\n\n## Key Decorators\n\n### HTTP Routes\n| Decorator | Purpose |\n|-----------|---------|\n| \\`@Controller()\\` | Define route prefix |\n| \\`@Get('/'), @Post('/')\\` | HTTP method handlers |\n| \\`@Middleware(fn)\\` | Attach middleware |\n| \\`@Public()\\` | Skip auth (requires auth adapter) |\n| \\`@Roles('admin')\\` | Role-based access |\n\n### Dependency Injection\n| Decorator | Purpose |\n|-----------|---------|\n| \\`defineModule({...})\\` | Define feature module (factory; preferred — paired with \\`defineModules()\\` registry) |\n| \\`defineModules()\\` | Build the modules registry as a chainable list (\\`.mount(X())\\`) |\n| \\`AppModule\\` interface | Legacy module shape — \\`class X implements AppModule\\` (toggle via \\`modules.style: 'class'\\`) |\n| \\`@Service()\\` | Register singleton service |\n| \\`@Repository()\\` | Register repository |\n| \\`@Autowired()\\` | Property injection |\n| \\`@Inject('token')\\` | Token-based injection |\n| \\`@Value('VAR')\\` | Inject env variable |\n\n### Context Decorators\n\nTyped, ordered way to populate \\`ctx.set/get\\` keys before the handler runs.\nUse this **instead of \\`@Middleware()\\`** when the middleware's only output\nis a value other code reads off \\`ctx\\`.\n\n**Authoring** — pick the right factory:\n\n| Factory | When |\n|---------|------|\n| \\`defineHttpContextDecorator(spec)\\` | HTTP only (the common case). \\`Ctx\\` is \\`RequestContext\\`, so \\`ctx.req\\` / \\`ctx.params\\` / \\`ctx.query\\` are typed. |\n| \\`defineContextDecorator(spec)\\` | Transport-agnostic (HTTP + WS + queue + cron). \\`Ctx\\` is \\`ExecutionContext\\` — only \\`get\\` / \\`require\\` / \\`set\\` / \\`requestId\\`. |\n| \\`<either>.withParams<P>()(spec)\\` | The contributor takes per-call params. **Always use the curried form for params** — the positional form forces you to spell \\`K\\` and \\`D\\` and loses \\`deps\\` inference. |\n\nSpec fields: \\`{ key, deps, dependsOn, optional, paramDefaults, requiredParams, onError, resolve }\\`.\n\n**Call sites — all five, precedence high → low:**\n\n| # | Site | Form |\n|---|------|------|\n| 1 | Method | \\`@LoadX\\` / \\`@LoadX({ ... })\\` above a controller method |\n| 2 | Class | \\`@LoadX\\` / \\`@LoadX({ ... })\\` above the controller class |\n| 3 | Module | \\`defineModule({ build: () => ({ contributors: () => [LoadX.registration] }) })\\` — or \\`AppModule.contributors?()\\` in class form |\n| 4 | Adapter | \\`AppAdapter.contributors?(): ContributorRegistration[]\\` |\n| 5 | Global | \\`bootstrap({ contributors: [LoadX.registration] })\\` |\n\nSites 3–5 take **registrations**, not decorators:\n\n- \\`LoadX.registration\\` — uses \\`paramDefaults\\` as-is.\n- \\`LoadX.with({ ...params }).registration\\` — call-site params merged over \\`paramDefaults\\`.\n\nDuplicate keys are resolved by precedence; the lower-precedence one is\ndropped silently, which is how a method-level decorator overrides an\nadapter-shipped default.\n\n**Params:** a **required** field of \\`P\\` with no \\`paramDefaults\\` entry must be\nsupplied at every call site — \\`@LoadX\\` bare, \\`@LoadX()\\`, and \\`.registration\\`\nare compile errors for such a decorator. Never invent a placeholder default\njust to make the type check; add \\`requiredParams: ['field']\\` for runtime\nenforcement at JS call sites.\n\n**Reading values:** \\`ctx.require('key')\\` for values a contributor guarantees\n(throws \\`MissingContextValueError\\`, returns a non-optional type);\n\\`ctx.get('key')\\` for \\`optional: true\\` contributors and ad-hoc keys (returns\n\\`| undefined\\`). Never \\`ctx.get('key')!\\` — it compiles even when the producing\ndecorator isn't applied to the route.\n\n| Concept | Where it lives |\n|---------|----------------|\n| Type augmentation (value types) | \\`declare module '@forinda/kickjs' { interface ContextMeta { ... } }\\` |\n| Type augmentation (key-only) | \\`declare module '@forinda/kickjs' { interface ContextKeys { ... } }\\` — valid in \\`dependsOn\\`, value stays \\`unknown\\` |\n\nCycles and missing \\`dependsOn\\` keys throw at \\`app.setup()\\` (boot fails\nfast). The \\`onError\\` hook is async-permitted.\n\nFull guide: <https://kickjs.app/guide/context-decorators>.\n\n## Common Pitfalls\n\nSee the **\\`kickjs-deny-list\\`** skill — the maintained list of things that\ncompile, run, and are still wrong.\n\nFor a specific failure, \\`kick explain \"<error message>\"\\` beats reading either:\nit matches the message against known causes and prints the fix.\n\n## CLI Commands Reference\n\nSee the **\\`kickjs-cli-commands-cheatsheet\\`** skill for the full table, the\nshell-safe field syntax, and the non-obvious flags. \\`kick --help\\` and\n\\`kick <cmd> --help\\` are authoritative for the installed version.\n\n## Learn More\n\nUse the **\\`kickjs-docs-lookup\\`** skill — it maps questions to the right guide\npage and lists the local tools (\\`kick explain\\`, \\`kick doctor\\`, \\`kick inspect\\`,\n\\`.kickjs/types/\\`) that usually answer faster than a search.\n\nStart at <https://kickjs.app/>.\n\n`\n}\n\n/**\n * One emitted skill — slug becomes the directory name under\n * `.agents/skills/<slug>/SKILL.md`. `frontmatterName` is the value\n * agents use to look the skill up at activation time and follows the\n * `kickjs-<slug>` convention to keep the skill registry namespaced.\n */\nexport interface KickJsSkillFile {\n /** kebab-case directory name (`add-module`, `write-controller-test`). */\n slug: string\n /** Full SKILL.md content with YAML frontmatter + body. */\n content: string\n}\n\n/**\n * Render every KickJS task-skill as its own `SKILL.md` file, ready to\n * write under `.agents/skills/<slug>/SKILL.md`. Each file follows the\n * standard Claude Code skill format:\n *\n * ```\n * ---\n * name: kickjs-<slug>\n * description: <when to use this skill>\n * ---\n *\n * <body>\n * ```\n *\n * Agents that auto-discover skills from `.agents/skills/` (Claude\n * Code, Copilot CLI plugins, Gemini's activate_skill) pick each up by\n * its frontmatter without us shipping an index file. The legacy\n * single-file format (`kickjs-skills.md`) is gone — adopters with\n * existing root-level copies keep them untouched until they run\n * `kick g agents -f --only skills`, which emits the new layout\n * alongside without deleting the old file.\n */\nexport function generateKickJsSkillFiles(\n name: string,\n _template: ProjectTemplate,\n pm: string,\n style: ModuleStyle = 'define',\n /** Feature layers the app uses (`feature-views`, …): their skills join the base ones. */\n layers: readonly string[] = [],\n): KickJsSkillFile[] {\n const banner = `<!-- Generated by \\`kick g agents\\` for ${name}. Edits are overwritten on the next refresh; keep customisation in a SKILL.local.md alongside. -->`\n\n const skills = readLayerSkills(['base', ...layers], skillVars(pm, style))\n\n return skills.map((skill) => ({\n slug: skill.slug,\n content: `---\nname: ${skill.name}\ndescription: ${skill.description}\n---\n\n${banner}\n\n${skill.body}\n`,\n }))\n}\n\n/**\n * @deprecated Kept only for back-compat with adopters who programmatically\n * import this function from `@forinda/kickjs-cli`. The CLI itself no\n * longer calls it — `kick g agents` emits per-skill SKILL.md files via\n * {@link generateKickJsSkillFiles}. Will be removed in a future minor.\n */\nexport function generateGemini(name: string, _template: ProjectTemplate, _pm: string): string {\n return `# GEMINI.md — ${name}\n\n**Read \\`./AGENTS.md\\` first.** It is the canonical, multi-agent\nreference for this project — every convention, structure, decorator\npattern, env wiring rule, generator usage. This file is a thin\nGemini-specific layer; when the two disagree on anything substantive,\ntreat \\`AGENTS.md\\` as authoritative and flag the discrepancy.\n\n## Why this file\n\nGemini CLI auto-loads \\`GEMINI.md\\` when it lives alongside the\nagent-context files. Keeping it in \\`.agents/\\` next to \\`AGENTS.md\\`\nmeans Gemini reads the same shared prose as Codex / Cursor / Copilot\nwithout us copy-pasting.\n\n## Gemini-specific notes\n\n- **Skills activation** — Gemini activates skills via\n \\`activate_skill\\` (its native MCP-style tool); the equivalent on\n Claude Code is the \\`Skill\\` tool. Cross-reference the\n \\`kickjs-skills.md\\` index for the available triggers.\n- **Tool naming** — Gemini's tool names differ from Claude Code's\n (e.g. \\`read_file\\` vs \\`Read\\`, \\`run_terminal_command\\` vs\n \\`Bash\\`). The shared prose in \\`AGENTS.md\\` describes intents, not\n tool names; consult Gemini's docs for the concrete invocation.\n- **File ops** — Gemini's file edits are sandboxed; large refactors\n may need explicit confirmation. Prefer the smallest-possible-edit\n pattern.\n\n## Refreshing this file\n\n\\`kick g agents --only gemini -f\\` regenerates this file from the\nCLI template. Hand-edited content is overwritten — keep customisation\nin \\`.agents/GEMINI.local.md\\`.\n`\n}\n\n/**\n * Render the GitHub Copilot CLI agent file emitted at\n * `.agents/COPILOT.md`. Same pattern as `generateGemini` — thin\n * pointer to `.agents/AGENTS.md` with notes specific to Copilot\n * CLI's tool surface and conventions.\n */\nexport function generateCopilot(name: string, _template: ProjectTemplate, _pm: string): string {\n return `# COPILOT.md — ${name}\n\n**Read \\`./AGENTS.md\\` first.** It is the canonical, multi-agent\nreference for this project — every convention, structure, decorator\npattern, env wiring rule, generator usage. This file is a thin\nCopilot-specific layer; when the two disagree on anything substantive,\ntreat \\`AGENTS.md\\` as authoritative and flag the discrepancy.\n\n## Why this file\n\nGitHub Copilot CLI auto-loads \\`COPILOT.md\\` when it lives alongside\nthe agent-context files. Keeping it in \\`.agents/\\` next to\n\\`AGENTS.md\\` means Copilot reads the same shared prose as\nCodex / Cursor / Gemini / Claude Code without copy-pasting.\n\n## Copilot-specific notes\n\n- **Skills** — Copilot CLI auto-discovers skills from installed\n plugins; cross-reference \\`kickjs-skills.md\\` for available\n triggers in this project.\n- **Tool naming** — Copilot's tool names differ from Claude Code's\n (\\`edit\\` vs \\`Edit\\`, \\`shell\\` vs \\`Bash\\`, etc.). The shared\n prose in \\`AGENTS.md\\` describes intents, not tool names; consult\n Copilot's docs for the concrete invocation.\n- **Confirmation flows** — Copilot CLI surfaces destructive\n operations through an explicit approval gate. Stage edits with\n short, focused diffs so each one is easy to review at the prompt.\n\n## Refreshing this file\n\n\\`kick g agents --only copilot -f\\` regenerates this file from the\nCLI template. Hand-edited content is overwritten — keep customisation\nin \\`.agents/COPILOT.local.md\\`.\n`\n}\n","import { basename, dirname, join, relative } from 'node:path'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { writeFileSafe } from '../utils/fs'\nimport { confirm } from '../utils/prompts'\nimport {\n generateClaude,\n generateAgents,\n generateKickJsSkillFiles,\n generateGemini,\n generateCopilot,\n} from './templates/project-docs'\nimport { loadKickConfig } from '../config'\nimport { resolvePackageManager } from '../utils/package-manager'\nimport type { ModuleStyle } from './templates/types'\nimport { detectFeatureLayers, readLayerSkills, skillVars } from '../scaffold/skills'\n\ntype ProjectTemplate = 'rest' | 'minimal' | 'fullstack' | 'inertia'\n\n/**\n * Subdirectory (relative to the project root) where every shared\n * agent-context file lands. CLAUDE.md is the only exception — it stays\n * at the project root because Claude Code auto-loads CLAUDE.md from\n * there. CLAUDE.md is generated as a thin pointer that tells Claude\n * to read `.agents/AGENTS.md` first.\n *\n * Existing root-level AGENTS.md / kickjs-skills.md files (from older\n * scaffolds before this restructure) are left untouched — the\n * generator emits the new layout alongside them and leaves migration\n * to the adopter.\n */\nconst AGENTS_DIR = '.agents'\n\nexport interface GenerateAgentDocsOptions {\n outDir: string\n /** Override project name (defaults to package.json `name`). */\n name?: string\n /** Override package manager (default: detected as `kick add` does — config, `packageManager`, lockfile, then npm). */\n pm?: string\n /** Override template (defaults to kick.config.ts `pattern`, then 'rest'). */\n template?: ProjectTemplate\n /**\n * Which file(s) to (re)generate. All `.agents/`-bound files land in\n * the project's `.agents/` subdirectory; `claude` is the only file\n * that stays at the project root.\n *\n * - `agents` → `.agents/AGENTS.md`\n * - `claude` → `CLAUDE.md` (root; thin pointer to .agents/)\n * - `skills` → `.agents/skills/<slug>/SKILL.md` (one per skill)\n * - `gemini` → `.agents/GEMINI.md`\n * - `copilot` → `.agents/COPILOT.md`\n * - `both` → `.agents/AGENTS.md` + `CLAUDE.md` (legacy alias)\n * - `all` → every file above\n */\n only?: 'agents' | 'claude' | 'skills' | 'gemini' | 'copilot' | 'both' | 'all'\n /** Skip the overwrite prompt. */\n force?: boolean\n}\n\nconst VALID_TEMPLATES = new Set<ProjectTemplate>(['rest', 'minimal', 'fullstack', 'inertia'])\n\nfunction detectName(outDir: string, override?: string): string {\n if (override) return override\n try {\n const pkg = JSON.parse(readFileSync(join(outDir, 'package.json'), 'utf-8')) as { name?: string }\n if (pkg.name) return pkg.name.replace(/^@[^/]+\\//, '')\n } catch {\n // No package.json — fall back to folder name\n }\n return outDir.split('/').findLast(Boolean) ?? 'app'\n}\n\n/**\n * Module declaration style, so generated examples show the form this project\n * actually uses. A `class` module passed as `UserModule()` calls a class\n * without `new`; a `define` module passed bare is refused when it takes config.\n */\nasync function detectStyle(outDir: string): Promise<ModuleStyle> {\n try {\n const cfg = await loadKickConfig(outDir)\n return cfg?.modules?.style === 'class' ? 'class' : 'define'\n } catch {\n return 'define'\n }\n}\n\nasync function detectTemplate(\n outDir: string,\n override?: ProjectTemplate,\n): Promise<ProjectTemplate> {\n if (override) return override\n try {\n const cfg = await loadKickConfig(outDir)\n const pattern = cfg?.pattern as ProjectTemplate | undefined\n if (pattern && VALID_TEMPLATES.has(pattern)) return pattern\n } catch {\n // ignore\n }\n return 'rest'\n}\n\nexport async function generateAgentDocs(options: GenerateAgentDocsOptions): Promise<string[]> {\n const only = options.only ?? 'all'\n const name = detectName(options.outDir, options.name)\n const pm = await resolvePackageManager(options.pm, options.outDir)\n const template = await detectTemplate(options.outDir, options.template)\n const style = await detectStyle(options.outDir)\n\n const wantsAgents = only === 'agents' || only === 'both' || only === 'all'\n const wantsClaude = only === 'claude' || only === 'both' || only === 'all'\n const wantsSkills = only === 'skills' || only === 'all'\n const wantsGemini = only === 'gemini' || only === 'all'\n const wantsCopilot = only === 'copilot' || only === 'all'\n\n // CLAUDE.md stays at the project root because Claude Code auto-loads\n // it from there. Every other shared-context file lands under\n // `.agents/` so the root stays uncluttered. `writeFileSafe` creates\n // parent directories automatically — no need to pre-mkdir.\n const targets: { file: string; render: () => string }[] = []\n if (wantsAgents) {\n targets.push({\n file: join(options.outDir, AGENTS_DIR, 'AGENTS.md'),\n render: () => generateAgents(name, template, pm),\n })\n }\n if (wantsClaude) {\n targets.push({\n file: join(options.outDir, 'CLAUDE.md'),\n render: () => generateClaude(name, template, pm),\n })\n }\n if (wantsSkills) {\n // Per-skill SKILL.md under `.agents/skills/<slug>/` so agents that\n // auto-discover skills (Claude Code, Copilot CLI plugins, Gemini's\n // activate_skill) pick each up by its frontmatter without needing\n // a separate index file.\n // Base skills, plus those of the features this app uses (from package.json).\n const layers = detectFeatureLayers(options.outDir)\n for (const skill of generateKickJsSkillFiles(name, template, pm, style, layers)) {\n targets.push({\n file: join(options.outDir, AGENTS_DIR, 'skills', skill.slug, 'SKILL.md'),\n render: () => skill.content,\n })\n }\n }\n if (wantsGemini) {\n targets.push({\n file: join(options.outDir, AGENTS_DIR, 'GEMINI.md'),\n render: () => generateGemini(name, template, pm),\n })\n }\n if (wantsCopilot) {\n targets.push({\n file: join(options.outDir, AGENTS_DIR, 'COPILOT.md'),\n render: () => generateCopilot(name, template, pm),\n })\n }\n\n const written: string[] = []\n for (const { file, render } of targets) {\n if (existsSync(file) && !options.force) {\n const overwrite = await confirm({\n message: `${file.replace(options.outDir + '/', '')} already exists. Overwrite?`,\n initialValue: false,\n })\n if (!overwrite) {\n console.log(` Skipped — existing ${file.replace(options.outDir + '/', '')} preserved.`)\n continue\n }\n }\n await writeFileSafe(file, render())\n written.push(file)\n }\n return written\n}\n\n/**\n * `kick add <feature>`: the feature's own skills, into an app that already\n * keeps skills in `.agents/skills/` (`kick g agents --only skills` creates it).\n * An existing SKILL.md is left alone — refreshing is `kick g agents -f`'s job.\n * Returns the paths written, relative to `cwd`.\n */\nexport async function writeLayerSkills(\n cwd: string,\n layers: readonly string[],\n pm: string,\n): Promise<string[]> {\n // The app's own .agents/, else a fullstack workspace's, one folder up from server/.\n const candidates = basename(cwd) === 'server' ? [cwd, dirname(cwd)] : [cwd]\n const base = candidates.find((d) => existsSync(join(d, AGENTS_DIR, 'skills')))\n if (!layers.length || !base) return []\n const style = await detectStyle(cwd)\n const own = new Set(readLayerSkills(layers, skillVars(pm, style)).map((s) => s.slug))\n const files = generateKickJsSkillFiles(\n detectName(cwd),\n await detectTemplate(cwd),\n pm,\n style,\n layers,\n ).filter((f) => own.has(f.slug))\n const written: string[] = []\n for (const f of files) {\n const abs = join(base, AGENTS_DIR, 'skills', f.slug, 'SKILL.md')\n if (existsSync(abs)) continue\n await writeFileSafe(abs, f.content)\n written.push(relative(cwd, abs))\n }\n return written\n}\n"],"mappings":";;;;;;;;;;2hBAKA,IAAIQ,EAAU,GAId,SAAgBC,EAAU,EAAwB,CAChD,EAAUC,CACZ,CAYA,MAAMC,kBAAc,IAAI,IAAI,CAAC,MAAO,OAAQ,MAAO,OAAQ,OAAQ,OAAQ,QAAS,KAAK,CAAC,EAgB1F,eAAsBC,EAAc,EAAkB,EAAgC,CAChFJ,IACJ,MAAMK,GAAMC,EAAQC,CAAQ,EAAG,CAAE,UAAW,EAAK,CAAC,EAClD,MAAMC,EAAUD,EAAUE,EAAS,OAAO,EAC3BN,EAAY,IAAIO,EAAQH,CAAQ,CAAC,GAC9C,MAAMI,GAAWJ,EAAUE,CAAO,CAAC,CAAC,UAAY,CAIhD,CAAC,EAEL,CAeA,IAAIG,EAGJ,eAAeC,GAAa,EAA0C,C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