@lunora/cli 1.0.0-alpha.21 → 1.0.0-alpha.211

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 (110) hide show
  1. package/LICENSE.md +33 -0
  2. package/README.md +1 -1
  3. package/__assets__/package-og.svg +1 -1
  4. package/dist/bin.mjs +2 -10
  5. package/dist/index.d.mts +745 -341
  6. package/dist/index.d.ts +745 -341
  7. package/dist/index.mjs +1 -19
  8. package/dist/packem_chunks/handler.mjs +1 -150
  9. package/dist/packem_chunks/handler10.mjs +4 -22
  10. package/dist/packem_chunks/handler11.mjs +2 -192
  11. package/dist/packem_chunks/handler12.mjs +1 -131
  12. package/dist/packem_chunks/handler13.mjs +1 -65
  13. package/dist/packem_chunks/handler14.mjs +1 -58
  14. package/dist/packem_chunks/handler15.mjs +1 -79
  15. package/dist/packem_chunks/handler16.mjs +3 -43
  16. package/dist/packem_chunks/handler17.mjs +1 -105
  17. package/dist/packem_chunks/handler18.mjs +1 -170
  18. package/dist/packem_chunks/handler19.mjs +7 -89
  19. package/dist/packem_chunks/handler2.mjs +2 -114
  20. package/dist/packem_chunks/handler20.mjs +1 -94
  21. package/dist/packem_chunks/handler21.mjs +2 -311
  22. package/dist/packem_chunks/handler22.mjs +3 -0
  23. package/dist/packem_chunks/handler23.mjs +3 -0
  24. package/dist/packem_chunks/handler24.mjs +1 -0
  25. package/dist/packem_chunks/handler25.mjs +99 -0
  26. package/dist/packem_chunks/handler26.mjs +10 -0
  27. package/dist/packem_chunks/handler3.mjs +1 -204
  28. package/dist/packem_chunks/handler4.mjs +1 -33
  29. package/dist/packem_chunks/handler5.mjs +1 -49
  30. package/dist/packem_chunks/handler6.mjs +1 -91
  31. package/dist/packem_chunks/handler7.mjs +3 -42
  32. package/dist/packem_chunks/handler8.mjs +1 -174
  33. package/dist/packem_chunks/handler9.mjs +1 -16
  34. package/dist/packem_chunks/planDevCommand.mjs +7 -500
  35. package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
  36. package/dist/packem_chunks/runDeployCommand.mjs +1 -504
  37. package/dist/packem_chunks/runInitCommand.mjs +118 -1383
  38. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +9 -395
  39. package/dist/packem_chunks/runResetCommand.mjs +1 -41
  40. package/dist/packem_chunks/runRpcCommand.mjs +1 -68
  41. package/dist/packem_shared/COMMANDS-BXbrW8dd.mjs +1 -0
  42. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Cf8ZymM1.mjs +1 -0
  43. package/dist/packem_shared/admin-token-rxXZbVMZ.mjs +1 -0
  44. package/dist/packem_shared/admin-url-Cil3Or6N.mjs +1 -0
  45. package/dist/packem_shared/advisory-gate-Cl8IEFIj.mjs +1 -0
  46. package/dist/packem_shared/api-spec-lYyq4vL6.mjs +1 -0
  47. package/dist/packem_shared/binding-manifest-file-CQ1eQYy1.mjs +2 -0
  48. package/dist/packem_shared/buildRegistryIndex-Zi3bBqpc.mjs +1 -0
  49. package/dist/packem_shared/cli-C37AI4tr.mjs +3 -0
  50. package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
  51. package/dist/packem_shared/command-DwC11Cwe.mjs +1 -0
  52. package/dist/packem_shared/commands-BNKj7r1R.mjs +19 -0
  53. package/dist/packem_shared/createLogger-hGafwf-3.mjs +2 -0
  54. package/dist/packem_shared/createRecordingSpawner-DJlNacZ6.mjs +1 -0
  55. package/dist/packem_shared/deploy-target-D9GPy_tq.mjs +1 -0
  56. package/dist/packem_shared/diffSnapshots-CIOFQN_a.mjs +5 -0
  57. package/dist/packem_shared/docker-DpVxvYpL.mjs +1 -0
  58. package/dist/packem_shared/import-CdHdZRjj.mjs +12 -0
  59. package/dist/packem_shared/insertSchemaExtension-DY4pA8wE.mjs +8 -0
  60. package/dist/packem_shared/lint-ignore-report-DKZagpqk.mjs +2 -0
  61. package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
  62. package/dist/packem_shared/output-format-DfogXx0p.mjs +2 -0
  63. package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
  64. package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
  65. package/dist/packem_shared/platform-diagnostics-uOXqysk3.mjs +4 -0
  66. package/dist/packem_shared/prompt-cancelled-C8Sj7OqI.mjs +1 -0
  67. package/dist/packem_shared/resolve-DZAGzg67.mjs +1 -0
  68. package/dist/packem_shared/resolve-target-BRvw8Pf7.mjs +1 -0
  69. package/dist/packem_shared/runAddCommand-D1Dj8-pK.mjs +1 -0
  70. package/dist/packem_shared/runExportCommand-DmXKEWSq.mjs +5 -0
  71. package/dist/packem_shared/schema-drift-gate-DARCKocg.mjs +1 -0
  72. package/dist/packem_shared/schemaIrToSnapshot-qpRoV7HY.mjs +1 -0
  73. package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
  74. package/dist/packem_shared/storage-wIUel5Az.mjs +1 -0
  75. package/dist/packem_shared/tui-prompts-Dd0pDuNr.mjs +4 -0
  76. package/dist/packem_shared/vectorize-metadata-DbziRKpX.mjs +1 -0
  77. package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
  78. package/dist/packem_shared/wrangler-secrets-CCdt0mUl.mjs +1 -0
  79. package/package.json +39 -17
  80. package/skills/README.md +35 -17
  81. package/skills/lunora/SKILL.md +65 -9
  82. package/skills/lunora-functions/SKILL.md +38 -3
  83. package/skills/lunora-migration-helper/SKILL.md +70 -17
  84. package/skills/lunora-performance-audit/SKILL.md +36 -6
  85. package/skills/lunora-quickstart/SKILL.md +90 -24
  86. package/skills/lunora-realtime/SKILL.md +58 -30
  87. package/dist/packem_shared/COMMANDS-D3h9Iwvl.mjs +0 -944
  88. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
  89. package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
  90. package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
  91. package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
  92. package/dist/packem_shared/command-BC30oSBW.mjs +0 -14
  93. package/dist/packem_shared/commands-hl0mRqqg.mjs +0 -845
  94. package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
  95. package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
  96. package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
  97. package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
  98. package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
  99. package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
  100. package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
  101. package/dist/packem_shared/output-format-wUvAN6AL.mjs +0 -17
  102. package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
  103. package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
  104. package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
  105. package/dist/packem_shared/runAddCommand-vJdgiR5t.mjs +0 -4
  106. package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
  107. package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
  108. package/dist/packem_shared/storage-B7hHSTZP.mjs +0 -84
  109. package/dist/packem_shared/tui-prompts-M6OWsuyw.mjs +0 -663
  110. package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
@@ -1,58 +1 @@
1
- import { readLinkedProject } from '@lunora/config';
2
- import { d as defineHandler } from '../packem_shared/command-BC30oSBW.mjs';
3
- import { defaultSpawner } from '../packem_shared/createRecordingSpawner-DxI3mebw.mjs';
4
-
5
- const LOG_FORMATS = /* @__PURE__ */ new Set(["json", "pretty"]);
6
- const runLogsCommand = async (options) => {
7
- const cwd = options.cwd ?? process.cwd();
8
- if (options.format !== void 0 && !LOG_FORMATS.has(options.format)) {
9
- options.logger.error(`logs: unknown --format "${options.format}" — expected pretty | json`);
10
- return { code: 1, descriptor: void 0, error: "invalid format" };
11
- }
12
- const args = ["exec", "wrangler", "tail"];
13
- if (options.worker !== void 0) {
14
- args.push(options.worker);
15
- }
16
- const env = options.env ?? readLinkedProject(cwd)?.env;
17
- if (env !== void 0) {
18
- args.push("--env", env);
19
- }
20
- if (options.format !== void 0) {
21
- args.push("--format", options.format);
22
- }
23
- if (options.status !== void 0) {
24
- args.push("--status", options.status);
25
- }
26
- if (options.search !== void 0) {
27
- args.push("--search", options.search);
28
- }
29
- if (options.temporary) {
30
- args.push("--temporary");
31
- }
32
- const descriptor = {
33
- args,
34
- command: "pnpm",
35
- cwd
36
- };
37
- options.logger.info(`tailing logs via ${descriptor.command} ${descriptor.args.join(" ")}`);
38
- const spawner = options.spawner ?? defaultSpawner;
39
- const result = await spawner(descriptor);
40
- return {
41
- code: result.code,
42
- descriptor
43
- };
44
- };
45
- const execute = defineHandler(
46
- ({ argument, cwd, logger, options }) => runLogsCommand({
47
- cwd,
48
- env: options.env,
49
- format: options.format,
50
- logger,
51
- search: options.search,
52
- status: options.status,
53
- temporary: options.temporary === true,
54
- worker: argument[0]
55
- })
56
- );
57
-
58
- export { execute, runLogsCommand };
1
+ import{d as c}from"../packem_shared/command-DwC11Cwe.mjs";import{r as d,b as s,a as n}from"../packem_shared/commands-BNKj7r1R.mjs";const w=c(({argument:a,cwd:u,logger:e,options:r})=>{const f=a[0],m=a.slice(1);return f==="add"?d({allowUnsafeSource:r.allowUnsafeSource===!0,cwd:u,diff:r.diff===!0,dryRun:r.dryRun===!0,from:r.from,json:r.json===!0,logger:e,names:m,overwrite:r.overwrite===!0,ref:r.ref,source:r.source,yes:r.yes===!0}):f==="list"?d({cwd:u,from:r.from,json:r.json===!0,list:!0,logger:e,names:[],ref:r.ref,source:r.source}):f==="view"?s({allowUnsafeSource:r.allowUnsafeSource===!0,cwd:u,from:r.from,logger:e,names:m,ref:r.ref,source:r.source}):f==="build"?n({check:r.check===!0,cwd:u,from:r.from,logger:e,names:[],out:r.out}):(e.error("registry: unknown subcommand. Usage: lunora registry <add|list|view|build> [names…]"),{code:1})});export{w as execute};
@@ -1,79 +1 @@
1
- import { runCodegen } from '@lunora/codegen';
2
- import { validateWranglerProject, inferLunoraBindings, reconcileWranglerBindings } from '@lunora/config';
3
- import { p as parseApiSpec } from '../packem_shared/api-spec-CtA6ilu4.mjs';
4
- import { d as defineHandler } from '../packem_shared/command-BC30oSBW.mjs';
5
- import { r as runSchemaDriftGate } from '../packem_shared/schema-drift-gate-BtBt0as0.mjs';
6
-
7
- const provisionBindings = async (cwd, logger) => {
8
- try {
9
- const inferred = await inferLunoraBindings({ projectRoot: cwd });
10
- const reconciled = reconcileWranglerBindings(cwd, inferred);
11
- if (reconciled.changed) {
12
- logger.success(`provisioned bindings: ${reconciled.added.join(", ")} → ${reconciled.wranglerPath ?? "wrangler.jsonc"}`);
13
- }
14
- for (const warning of reconciled.warnings) {
15
- logger.warn(warning);
16
- }
17
- } catch (error) {
18
- const message = error instanceof Error ? error.message : String(error);
19
- logger.warn(`binding inference skipped: ${message}`);
20
- }
21
- };
22
- const runPrepareCommand = async (options) => {
23
- const cwd = options.cwd ?? process.cwd();
24
- options.logger.info("running codegen");
25
- let codegen;
26
- try {
27
- codegen = runCodegen({ apiSpec: options.apiSpec, projectRoot: cwd });
28
- options.logger.success("codegen complete");
29
- } catch (error) {
30
- const message = error instanceof Error ? error.message : String(error);
31
- options.logger.error(`codegen failed: ${message}`);
32
- return {
33
- code: 1,
34
- error: `codegen failed: ${message}`,
35
- validation: { problems: [], wranglerPath: void 0 }
36
- };
37
- }
38
- const gate = runSchemaDriftGate({
39
- allowDrift: options.allowSchemaDrift === true,
40
- codegen,
41
- logger: options.logger,
42
- updateBaseline: options.updateSchemaBaseline === true
43
- });
44
- if (gate.blocked) {
45
- return {
46
- code: 1,
47
- error: "schema drift gate blocked prepare",
48
- schemaDrift: { blocked: true, reason: gate.reason },
49
- validation: { problems: [], wranglerPath: void 0 }
50
- };
51
- }
52
- await provisionBindings(cwd, options.logger);
53
- const validation = validateWranglerProject({ projectRoot: cwd });
54
- if (validation.problems.length > 0) {
55
- options.logger.error("wrangler.jsonc validation failed:");
56
- for (const problem of validation.problems) {
57
- options.logger.error(` - ${problem}`);
58
- }
59
- return {
60
- code: 1,
61
- error: "wrangler validation failed",
62
- validation
63
- };
64
- }
65
- gate.rebless?.();
66
- options.logger.success("project is ready to deploy");
67
- return { code: 0, validation };
68
- };
69
- const execute = defineHandler(
70
- ({ cwd, logger, options }) => runPrepareCommand({
71
- allowSchemaDrift: options.allowSchemaDrift === true,
72
- apiSpec: parseApiSpec(options.apiSpec),
73
- cwd,
74
- logger,
75
- updateSchemaBaseline: options.updateSchemaBaseline === true
76
- })
77
- );
78
-
79
- export { execute, runPrepareCommand };
1
+ import{existsSync as c,readFileSync as g,readdirSync as f,statSync as k,mkdirSync as w,writeFileSync as y}from"node:fs";import{fileURLToPath as R}from"node:url";import{AGENT_RULES_DIR as u,detectAgentRules as v,LUNORA_SKILL_NAMES as L}from"@lunora/config";import{join as i,relative as A,resolve as $,dirname as d}from"@visulima/path";import{d as b}from"../packem_shared/command-DwC11Cwe.mjs";const I=(e=d(R(import.meta.url)))=>{let r=e;for(let n=0;n<6;n+=1){const t=i(r,"package.json");if(c(t))try{if(JSON.parse(g(t,"utf8")).name==="@lunora/cli"){const l=i(r,"skills");return c(l)?l:void 0}}catch{}const s=d(r);if(s===r)break;r=s}},j=e=>f(e).filter(r=>{const n=i(e,r);return k(n).isDirectory()&&c(i(n,"SKILL.md"))}),m=(e,r,n)=>{w(r,{recursive:!0});let t=!1;for(const s of f(e)){const o=i(e,s),l=i(r,s);if(k(o).isDirectory()){t=m(o,l,n)||t;continue}c(l)&&!n||(y(l,g(o)),t=!0)}return t},_=["pnpm-workspace.yaml","pnpm-lock.yaml","yarn.lock","package-lock.json","bun.lock","bun.lockb",".git"],x=e=>{let r=e;for(;;){if(_.some(t=>c(i(r,t))))return r;const n=d(r);if(n===r)return e;r=n}},p=(e,r)=>r===void 0?x(e):$(e,r),E=e=>{const r=e.cwd??process.cwd(),n=p(r,e.dir),t=e.overwrite===!0,s=I();if(s===void 0)return e.logger.error("rules: could not locate the bundled skills (is @lunora/cli installed correctly?)."),{code:1,installed:[],skipped:[]};const o=[],l=[];for(const a of j(s)){const S=i(n,u,a);m(i(s,a),S,t)?o.push(a):l.push(a)}const h=A(r,i(n,u))||u;return o.length>0&&e.logger.success(`Installed ${String(o.length)} Lunora skill(s) into ${h}/: ${o.join(", ")}.`),l.length>0&&e.logger.info(`Skipped ${String(l.length)} existing skill(s) (re-run with --overwrite to replace): ${l.join(", ")}.`),e.logger.info("Your AI coding agent will pick these up automatically. Start with the `lunora` skill."),{code:0,installed:o,skipped:l}},O=e=>{const r=e.cwd??process.cwd(),n=p(r,e.dir),t=v(n);return t.installed?(e.logger.success(`Lunora agent rules are installed (${String(t.present.length)}/${String(L.length)} skills).`),t.missing.length>0&&e.logger.info(`Missing: ${t.missing.join(", ")}. Run \`lunora rules install\` to add them.`),{code:0,installed:t.present,skipped:[]}):(e.logger.warn("Lunora agent rules are not installed. Run `lunora rules install` so your AI agent knows how to use Lunora."),{code:e.strict===!0?1:0,installed:t.present,skipped:[]})},T=b(({argument:e,cwd:r,logger:n,options:t})=>{const s=e[0]??"check";return s==="install"?E({cwd:r,dir:t.dir,logger:n,overwrite:t.overwrite===!0}):s==="check"?O({cwd:r,dir:t.dir,logger:n,strict:t.strict===!0}):(n.error("rules: unknown subcommand. Usage: lunora rules <install|check>"),{code:1})});export{T as execute,I as resolveBundledSkillsDirectory,O as runRulesCheck,E as runRulesInstall};
@@ -1,43 +1,3 @@
1
- import { d as defineHandler } from '../packem_shared/command-BC30oSBW.mjs';
2
- import { r as runAddCommand, b as runRegistryViewCommand, a as runBuildIndexCommand } from '../packem_shared/commands-hl0mRqqg.mjs';
3
-
4
- const execute = defineHandler(({ argument, cwd, logger, options }) => {
5
- const subcommand = argument[0];
6
- const names = argument.slice(1);
7
- if (subcommand === "add") {
8
- return runAddCommand({
9
- allowUnsafeSource: options.allowUnsafeSource === true,
10
- cwd,
11
- diff: options.diff === true,
12
- dryRun: options.dryRun === true,
13
- from: options.from,
14
- json: options.json === true,
15
- logger,
16
- names,
17
- overwrite: options.overwrite === true,
18
- ref: options.ref,
19
- source: options.source,
20
- yes: options.yes === true
21
- });
22
- }
23
- if (subcommand === "list") {
24
- return runAddCommand({ cwd, from: options.from, json: options.json === true, list: true, logger, names: [], ref: options.ref, source: options.source });
25
- }
26
- if (subcommand === "view") {
27
- return runRegistryViewCommand({
28
- allowUnsafeSource: options.allowUnsafeSource === true,
29
- from: options.from,
30
- logger,
31
- names,
32
- ref: options.ref,
33
- source: options.source
34
- });
35
- }
36
- if (subcommand === "build") {
37
- return runBuildIndexCommand({ check: options.check === true, from: options.from, logger, out: options.out });
38
- }
39
- logger.error("registry: unknown subcommand. Usage: lunora registry <add|list|view|build> [names…]");
40
- return { code: 1 };
41
- });
42
-
43
- export { execute };
1
+ import{existsSync as S}from"node:fs";import{mkdtemp as k,writeFile as v,rm as R}from"node:fs/promises";import{tmpdir as T}from"node:os";import{discoverSchema as $,schemaFromIr as j}from"@lunora/codegen";import{seedPlan as C}from"@lunora/seed";import{join as m}from"@visulima/path";import{Project as F}from"ts-morph";import{i as x}from"../packem_shared/admin-token-rxXZbVMZ.mjs";import{d as z}from"../packem_shared/command-DwC11Cwe.mjs";import{r as I}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import{b as A}from"../packem_shared/tui-prompts-Dd0pDuNr.mjs";import{runResetCommand as P}from"./runResetCommand.mjs";import{r as U}from"../packem_shared/import-CdHdZRjj.mjs";const b=e=>e===""?!1:x(e),L=(e,r)=>typeof r=="bigint"?Number(r):r instanceof ArrayBuffer?[...new Uint8Array(r)]:r,l=e=>({code:e,conflicts:0,generated:0,inserted:0,ndjson:""}),N=(e,r)=>{if(!S(r))return e.logger.error(`schema not found: ${r} — run \`vis generate lunora-table --name=<name>\` to create one`),l(1);if(e.reset===!0&&(e.prod===!0||!b(e.url)))return e.logger.error("--reset only clears local .wrangler/state and cannot be combined with --prod or a remote --url"),l(1)},_=async(e,r,t,n)=>{const i=await k(m(T(),"lunora-seed-")),s=m(i,"rows.ndjson");await v(s,e,"utf8");try{const o=await U({batchSize:n.batchSize,cwd:t,fetchImpl:n.fetchImpl,file:s,logger:n.logger,prod:n.prod,token:n.token,url:n.url}),d=o.body?.conflicts??0;return d>0&&n.logger.warn(`${String(d)} row(s) skipped — their _id already exists. Seeding is deterministic; re-run with --reset to wipe local state first, or a different --seed for fresh ids.`),{code:o.code,conflicts:d,generated:r,inserted:o.inserted,ndjson:e}}finally{await R(i,{force:!0,recursive:!0}).catch(()=>{})}},B=(e,r)=>{if(e.table===void 0||r.tables.some(n=>n.name===e.table))return;const t=r.tables.map(n=>n.name).join(", ");return e.logger.error(`unknown table "${e.table}" — schema defines: ${t||"(no tables)"}`),l(1)},D=async(e,r)=>{if(!(e.prod===!0||!b(e.url))||e.yes===!0)return;if(!process.stdin.isTTY&&e.confirm===void 0)return e.logger.error("seed: refusing to insert into a non-local target without confirmation — re-run with --yes"),l(1);if(!await(e.confirm??A)(`This will insert ${String(r)} generated row(s) into ${e.url??"the production worker"}. Continue?`))return e.logger.info("seed: aborted"),l(1)},H=async e=>{const r=e.cwd??process.cwd(),t=m(r,"lunora","schema.ts"),n=N(e,t);if(n!==void 0)return n;const i=new F({skipAddingFilesFromTsConfig:!0}),s=$(i,t),o=B(e,s);if(o!==void 0)return o;const d=j(s),g=C(d,{defaultCount:e.count??10,now:e.now,only:e.table===void 0?void 0:[e.table],seed:e.seed??0}),u=[];for(const{rows:f,table:h}of g)for(const y of f)u.push(JSON.stringify({doc:y,table:h},L));const a=u.length>0?`${u.join(`
2
+ `)}
3
+ `:"",c=u.length;if(e.dryRun===!0)return a.length>0&&process.stdout.write(a),e.logger.info(`generated ${String(c)} row(s) across ${String(g.length)} table(s) — dry run, nothing inserted`),{code:0,conflicts:0,generated:c,inserted:0,ndjson:a};if(e.reset===!0){const f=await P({cwd:r,logger:e.logger,yes:!0});if(f.code!==0)return{code:f.code,conflicts:0,generated:c,inserted:0,ndjson:a}}if(c===0)return e.logger.warn("no rows generated — nothing to insert"),{code:0,conflicts:0,generated:0,inserted:0,ndjson:a};const w=await D(e,c);return w!==void 0?w:_(a,c,r,e)},p=z(async({cwd:e,logger:r,options:t})=>({code:(await H({batchSize:t.batchSize,count:t.count,cwd:e,dryRun:t.dryRun===!0,logger:r,prod:t.prod===!0,reset:t.reset===!0,now:t.now,seed:t.seed,table:t.table,token:t.token,url:I({cwd:e,prod:t.prod===!0,url:t.url}),yes:t.yes===!0})).code}));export{p as execute,H as runSeedCommand};
@@ -1,105 +1 @@
1
- import { existsSync, readFileSync, readdirSync, statSync, mkdirSync, writeFileSync } from 'node:fs';
2
- import { fileURLToPath } from 'node:url';
3
- import { AGENT_RULES_DIR, detectAgentRules, LUNORA_SKILL_NAMES } from '@lunora/config';
4
- import { join, relative, dirname } from '@visulima/path';
5
- import { d as defineHandler } from '../packem_shared/command-BC30oSBW.mjs';
6
-
7
- const resolveBundledSkillsDirectory = (startDirectory = dirname(fileURLToPath(import.meta.url))) => {
8
- let directory = startDirectory;
9
- for (let index = 0; index < 6; index += 1) {
10
- const packageJson = join(directory, "package.json");
11
- if (existsSync(packageJson)) {
12
- try {
13
- const parsed = JSON.parse(readFileSync(packageJson, "utf8"));
14
- if (parsed.name === "@lunora/cli") {
15
- const skills = join(directory, "skills");
16
- return existsSync(skills) ? skills : void 0;
17
- }
18
- } catch {
19
- }
20
- }
21
- const parent = dirname(directory);
22
- if (parent === directory) {
23
- break;
24
- }
25
- directory = parent;
26
- }
27
- return void 0;
28
- };
29
- const listBundledSkills = (skillsDirectory) => readdirSync(skillsDirectory).filter((name) => {
30
- const directory = join(skillsDirectory, name);
31
- return statSync(directory).isDirectory() && existsSync(join(directory, "SKILL.md"));
32
- });
33
- const copySkill = (source, destination, overwrite) => {
34
- mkdirSync(destination, { recursive: true });
35
- let wrote = false;
36
- for (const entry of readdirSync(source)) {
37
- const from = join(source, entry);
38
- const to = join(destination, entry);
39
- if (statSync(from).isDirectory()) {
40
- wrote = copySkill(from, to, overwrite) || wrote;
41
- continue;
42
- }
43
- if (existsSync(to) && !overwrite) {
44
- continue;
45
- }
46
- writeFileSync(to, readFileSync(from));
47
- wrote = true;
48
- }
49
- return wrote;
50
- };
51
- const runRulesInstall = (options) => {
52
- const cwd = options.cwd ?? process.cwd();
53
- const overwrite = options.overwrite === true;
54
- const skillsDirectory = resolveBundledSkillsDirectory();
55
- if (skillsDirectory === void 0) {
56
- options.logger.error("rules: could not locate the bundled skills (is @lunora/cli installed correctly?).");
57
- return { code: 1, installed: [], skipped: [] };
58
- }
59
- const installed = [];
60
- const skipped = [];
61
- for (const name of listBundledSkills(skillsDirectory)) {
62
- const destination = join(cwd, AGENT_RULES_DIR, name);
63
- const wrote = copySkill(join(skillsDirectory, name), destination, overwrite);
64
- if (wrote) {
65
- installed.push(name);
66
- } else {
67
- skipped.push(name);
68
- }
69
- }
70
- const target = relative(cwd, join(cwd, AGENT_RULES_DIR)) || AGENT_RULES_DIR;
71
- if (installed.length > 0) {
72
- options.logger.success(`Installed ${String(installed.length)} Lunora skill(s) into ${target}/: ${installed.join(", ")}.`);
73
- }
74
- if (skipped.length > 0) {
75
- options.logger.info(`Skipped ${String(skipped.length)} existing skill(s) (re-run with --overwrite to replace): ${skipped.join(", ")}.`);
76
- }
77
- options.logger.info("Your AI coding agent will pick these up automatically. Start with the `lunora` skill.");
78
- return { code: 0, installed, skipped };
79
- };
80
- const runRulesCheck = (options) => {
81
- const cwd = options.cwd ?? process.cwd();
82
- const status = detectAgentRules(cwd);
83
- if (status.installed) {
84
- options.logger.success(`Lunora agent rules are installed (${String(status.present.length)}/${String(LUNORA_SKILL_NAMES.length)} skills).`);
85
- if (status.missing.length > 0) {
86
- options.logger.info(`Missing: ${status.missing.join(", ")}. Run \`lunora rules install\` to add them.`);
87
- }
88
- return { code: 0, installed: status.present, skipped: [] };
89
- }
90
- options.logger.warn("Lunora agent rules are not installed. Run `lunora rules install` so your AI agent knows how to use Lunora.");
91
- return { code: options.strict === true ? 1 : 0, installed: status.present, skipped: [] };
92
- };
93
- const execute = defineHandler(({ argument, cwd, logger, options }) => {
94
- const subcommand = argument[0] ?? "check";
95
- if (subcommand === "install") {
96
- return runRulesInstall({ cwd, logger, overwrite: options.overwrite === true });
97
- }
98
- if (subcommand === "check") {
99
- return runRulesCheck({ cwd, logger, strict: options.strict === true });
100
- }
101
- logger.error("rules: unknown subcommand. Usage: lunora rules <install|check>");
102
- return { code: 1 };
103
- });
104
-
105
- export { execute, resolveBundledSkillsDirectory, runRulesCheck, runRulesInstall };
1
+ import{existsSync as p}from"node:fs";import{join as h}from"node:path";import{runCodegen as u}from"@lunora/codegen";import{p as g}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{r as v}from"../packem_shared/codegen-error-AmH54ofi.mjs";import{d as y}from"../packem_shared/command-DwC11Cwe.mjs";import{r as w}from"../packem_shared/deploy-target-D9GPy_tq.mjs";import{r as S,p as k}from"../packem_shared/schema-drift-gate-DARCKocg.mjs";import{v as j,i as b,p as x,l as E}from"../packem_shared/output-format-DfogXx0p.mjs";import{defaultSpawner as F}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{validateWranglerProject as U}from"@lunora/config/cloudflare";import{execArgsFor as D,detectPackageManager as R}from"@lunora/config";const $=async(r,t)=>{if(!p(h(r,"tsconfig.json")))return{warning:"no tsconfig.json found — skipping TypeScript type-check"};const e=D(R(r),"tsc",["--noEmit","-p","tsconfig.json"]),a=await t({args:e.args,command:e.command,cwd:r});return a.code===0?{}:{error:`type errors: tsc --noEmit exited ${String(a.code)}`}},H=async(r,t)=>{if(r.healthUrl===void 0||r.healthUrl==="")return;const e=await k({baseUrl:r.healthUrl,fetchImpl:r.healthFetch});if(e.error===void 0){t.success(`verify: health probe ok (${e.url})`);return}return e.error},T=(r,t,e,a)=>{if(t.length===0&&e.length===0)return r.success("verify: project is valid"),{code:0,errors:[],warnings:[],wranglerPath:a};if(e.length>0){r.warn("verify: warnings:");for(const c of e)r.warn(` - ${c}`)}if(t.length>0){r.error("verify: errors:");for(const c of t){r.error(` - ${c}`);const n=v(c);n!==void 0&&r.error(n)}return{code:1,errors:t,warnings:e,wranglerPath:a}}return r.success("verify: project is valid (with warnings)"),{code:0,errors:[],warnings:e,wranglerPath:a}},C=async r=>{const t=r.cwd??process.cwd(),e=E(r.format,r.logger),a=j("verify",r.format);if(a!==void 0)return r.logger.error(a),{code:1,error:a,errors:[],warnings:[],wranglerPath:void 0};const c=U({projectRoot:t}),n=[...c.report.errors],f=[...c.report.warnings];try{const o=w(t,r.target);if(o.target===void 0){const i=o.error??"unknown deploy target";return e.error(i),{code:1,error:i,errors:[i],warnings:[],wranglerPath:void 0}}const s=u({apiSpec:r.apiSpec,dryRun:!0,projectRoot:t,target:o.target}),m=S({allowDrift:r.allowSchemaDrift===!0,codegen:s,command:"verify",logger:e,readOnly:!0});m.blocked&&n.push(m.reason)}catch(o){const s=o instanceof Error?o.message:String(o);n.push(`codegen failed: ${s}`)}if(r.typecheck!==!1){const o=await $(t,r.spawner??F);o.error!==void 0&&n.push(o.error),o.warning!==void 0&&f.push(o.warning)}const l=await H(r,e);l!==void 0&&n.push(l);const d=T(e,n,f,c.wranglerPath);return b(r.format)&&x(d),d},K=y(async({cwd:r,logger:t,options:e})=>({code:(await C({allowSchemaDrift:e.allowSchemaDrift===!0,apiSpec:g(e.apiSpec),cwd:r,format:e.format,healthUrl:e.healthUrl,logger:t,target:e.target,typecheck:e.typecheck===!1?!1:void 0})).code}));export{K as execute,C as runVerifyCommand};
@@ -1,170 +1 @@
1
- import { existsSync } from 'node:fs';
2
- import { mkdtemp, writeFile, rm } from 'node:fs/promises';
3
- import { tmpdir } from 'node:os';
4
- import { discoverSchema, schemaFromIr } from '@lunora/codegen';
5
- import { seedPlan } from '@lunora/seed';
6
- import { join } from '@visulima/path';
7
- import { Project } from 'ts-morph';
8
- import { d as defineHandler } from '../packem_shared/command-BC30oSBW.mjs';
9
- import { a as resolveProductionWorkerUrl } from '../packem_shared/resolve-target-qbsJ_5sF.mjs';
10
- import { b as tuiConfirm } from '../packem_shared/tui-prompts-M6OWsuyw.mjs';
11
- import { runImportCommand } from '../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs';
12
- import { runResetCommand } from './runResetCommand.mjs';
13
-
14
- const isLocalUrl = (url) => {
15
- if (url === void 0) {
16
- return true;
17
- }
18
- try {
19
- const { hostname } = new URL(url);
20
- return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
21
- } catch {
22
- return false;
23
- }
24
- };
25
- const ndjsonReplacer = (_key, value) => {
26
- if (typeof value === "bigint") {
27
- return Number(value);
28
- }
29
- if (value instanceof ArrayBuffer) {
30
- return [...new Uint8Array(value)];
31
- }
32
- return value;
33
- };
34
- const seedFailure = (code) => {
35
- return { code, conflicts: 0, generated: 0, inserted: 0, ndjson: "" };
36
- };
37
- const guardSeedTargets = (options, schemaPath) => {
38
- if (!existsSync(schemaPath)) {
39
- options.logger.error(`schema not found: ${schemaPath} — run \`vis generate lunora-table --name=<name>\` to create one`);
40
- return seedFailure(1);
41
- }
42
- if (options.reset === true && (options.prod === true || !isLocalUrl(options.url))) {
43
- options.logger.error("--reset only clears local .wrangler/state and cannot be combined with --prod or a remote --url");
44
- return seedFailure(1);
45
- }
46
- return void 0;
47
- };
48
- const insertSeedRows = async (ndjson, generated, cwd, options) => {
49
- const scratchDirectory = await mkdtemp(join(tmpdir(), "lunora-seed-"));
50
- const temporaryFile = join(scratchDirectory, "rows.ndjson");
51
- await writeFile(temporaryFile, ndjson, "utf8");
52
- try {
53
- const result = await runImportCommand({
54
- batchSize: options.batchSize,
55
- fetchImpl: options.fetchImpl,
56
- file: temporaryFile,
57
- logger: options.logger,
58
- prod: options.prod,
59
- token: options.token,
60
- url: options.url
61
- });
62
- const conflicts = result.body?.conflicts ?? 0;
63
- if (conflicts > 0) {
64
- options.logger.warn(
65
- `${String(conflicts)} row(s) skipped — their _id already exists. Seeding is deterministic; re-run with --reset to wipe local state first, or a different --seed for fresh ids.`
66
- );
67
- }
68
- return { code: result.code, conflicts, generated, inserted: result.inserted, ndjson };
69
- } finally {
70
- await rm(scratchDirectory, { force: true, recursive: true }).catch(() => {
71
- });
72
- }
73
- };
74
- const validateSeedTable = (options, ir) => {
75
- if (options.table === void 0 || ir.tables.some((table) => table.name === options.table)) {
76
- return void 0;
77
- }
78
- const available = ir.tables.map((table) => table.name).join(", ");
79
- options.logger.error(`unknown table "${options.table}" — schema defines: ${available || "(no tables)"}`);
80
- return seedFailure(1);
81
- };
82
- const confirmRemoteSeedTarget = async (options, generated) => {
83
- const targetsRemote = options.prod === true || !isLocalUrl(options.url);
84
- if (!targetsRemote || options.yes === true) {
85
- return void 0;
86
- }
87
- if (!process.stdin.isTTY && options.confirm === void 0) {
88
- options.logger.error("seed: refusing to insert into a non-local target without confirmation — re-run with --yes");
89
- return seedFailure(1);
90
- }
91
- const confirmer = options.confirm ?? tuiConfirm;
92
- const confirmed = await confirmer(`This will insert ${String(generated)} generated row(s) into ${options.url ?? "the production worker"}. Continue?`);
93
- if (!confirmed) {
94
- options.logger.info("seed: aborted");
95
- return seedFailure(1);
96
- }
97
- return void 0;
98
- };
99
- const runSeedCommand = async (options) => {
100
- const cwd = options.cwd ?? process.cwd();
101
- const schemaPath = join(cwd, "lunora", "schema.ts");
102
- const guard = guardSeedTargets(options, schemaPath);
103
- if (guard !== void 0) {
104
- return guard;
105
- }
106
- const project = new Project({ skipAddingFilesFromTsConfig: true });
107
- const ir = discoverSchema(project, schemaPath);
108
- const unknownTable = validateSeedTable(options, ir);
109
- if (unknownTable !== void 0) {
110
- return unknownTable;
111
- }
112
- const schema = schemaFromIr(ir);
113
- const plan = seedPlan(schema, {
114
- defaultCount: options.count ?? 10,
115
- only: options.table === void 0 ? void 0 : [options.table],
116
- seed: options.seed ?? 0
117
- });
118
- const lines = [];
119
- for (const { rows, table } of plan) {
120
- for (const row of rows) {
121
- lines.push(JSON.stringify({ doc: row, table }, ndjsonReplacer));
122
- }
123
- }
124
- const ndjson = lines.length > 0 ? `${lines.join("\n")}
125
- ` : "";
126
- const generated = lines.length;
127
- if (options.dryRun === true) {
128
- if (ndjson.length > 0) {
129
- process.stdout.write(ndjson);
130
- }
131
- options.logger.info(`generated ${String(generated)} row(s) across ${String(plan.length)} table(s) — dry run, nothing inserted`);
132
- return { code: 0, conflicts: 0, generated, inserted: 0, ndjson };
133
- }
134
- if (options.reset === true) {
135
- const reset = await runResetCommand({ cwd, logger: options.logger, yes: true });
136
- if (reset.code !== 0) {
137
- return { code: reset.code, conflicts: 0, generated, inserted: 0, ndjson };
138
- }
139
- }
140
- if (generated === 0) {
141
- options.logger.warn("no rows generated — nothing to insert");
142
- return { code: 0, conflicts: 0, generated: 0, inserted: 0, ndjson };
143
- }
144
- const aborted = await confirmRemoteSeedTarget(options, generated);
145
- if (aborted !== void 0) {
146
- return aborted;
147
- }
148
- return insertSeedRows(ndjson, generated, cwd, options);
149
- };
150
- const execute = defineHandler(async ({ cwd, logger, options }) => {
151
- const result = await runSeedCommand({
152
- batchSize: options.batchSize,
153
- count: options.count,
154
- cwd,
155
- dryRun: options.dryRun === true,
156
- logger,
157
- prod: options.prod === true,
158
- reset: options.reset === true,
159
- seed: options.seed,
160
- table: options.table,
161
- token: options.token,
162
- // Resolve the link here (only under --prod) so seed's own remote/confirm
163
- // logic and the downstream import both see the same effective target.
164
- url: resolveProductionWorkerUrl({ cwd, prod: options.prod === true, url: options.url }),
165
- yes: options.yes === true
166
- });
167
- return { code: result.code };
168
- });
169
-
170
- export { execute, runSeedCommand };
1
+ import{readFileSync as l,existsSync as u}from"node:fs";import{join as a}from"node:path";import{parse as d}from"jsonc-parser";import{d as m}from"../packem_shared/command-DwC11Cwe.mjs";import{o as p}from"../packem_shared/open-url-EnKy--w-.mjs";const c=8787,s="/_lunora/studio",g=r=>{for(const t of["wrangler.jsonc","wrangler.json"]){const e=a(r,t);if(u(e))return e}},v=r=>{const t=g(r);if(t)try{const e=d(l(t,"utf8"));return e!==null&&typeof e=="object"?e:void 0}catch{return}},y=r=>{if(!r)return c;const{dev:t}=r;if(t!==null&&typeof t=="object"){const{port:e}=t;if(typeof e=="number"&&Number.isFinite(e))return e}return c},h=r=>{if(!r)return;const{routes:t}=r;if(Array.isArray(t)&&t.length>0){const n=t[0];if(typeof n=="string")return`https://${n.split("/")[0]??n}${s}`;if(n!==null&&typeof n=="object"){const{pattern:o}=n;if(typeof o=="string"&&o.length>0)return`https://${o.split("/")[0]??o}${s}`}}const{name:e}=r;if(typeof e=="string"&&e.length>0)return`https://${e}.workers.dev${s}`},$=async r=>{const t=r.cwd??process.cwd(),e=v(t),{logger:n}=r;let o;if(r.remote){if(o=h(e),!o)return n.error("view --remote: could not determine the remote URL from wrangler config (set `routes` or `name`)."),{code:1,url:void 0}}else o=`http://localhost:${String(y(e))}${s}`;n.info(`opening ${o}`);try{await p(o,{opener:r.opener})}catch(i){const f=i instanceof Error?i.message:String(i);return n.error(`view: failed to open URL: ${f}`),{code:1,url:o}}return{code:0,url:o}},A=m(({cwd:r,logger:t,options:e})=>$({cwd:r,logger:t,remote:e.remote===!0}));export{A as execute,$ as runViewCommand};
@@ -1,89 +1,7 @@
1
- import { existsSync } from 'node:fs';
2
- import { join } from 'node:path';
3
- import { runCodegen } from '@lunora/codegen';
4
- import { p as parseApiSpec } from '../packem_shared/api-spec-CtA6ilu4.mjs';
5
- import { d as defineHandler } from '../packem_shared/command-BC30oSBW.mjs';
6
- import { v as validateOutputFormat, i as isJsonFormat, p as printJson, l as loggerForFormat } from '../packem_shared/output-format-wUvAN6AL.mjs';
7
- import { r as runSchemaDriftGate } from '../packem_shared/schema-drift-gate-BtBt0as0.mjs';
8
- import { defaultSpawner } from '../packem_shared/createRecordingSpawner-DxI3mebw.mjs';
9
- import { validateWranglerProject } from '@lunora/config';
10
-
11
- const runTypecheckStep = async (cwd, spawner) => {
12
- if (!existsSync(join(cwd, "tsconfig.json"))) {
13
- return { warning: "no tsconfig.json found — skipping TypeScript type-check" };
14
- }
15
- const result = await spawner({ args: ["exec", "tsc", "--noEmit", "-p", "tsconfig.json"], command: "pnpm", cwd });
16
- return result.code === 0 ? {} : { error: `type errors: tsc --noEmit exited ${String(result.code)}` };
17
- };
18
- const reportVerifyResult = (logger, errors, warnings, wranglerPath) => {
19
- if (errors.length === 0 && warnings.length === 0) {
20
- logger.success("verify: project is valid");
21
- return { code: 0, errors: [], warnings: [], wranglerPath };
22
- }
23
- if (warnings.length > 0) {
24
- logger.warn("verify: warnings:");
25
- for (const warning of warnings) {
26
- logger.warn(` - ${warning}`);
27
- }
28
- }
29
- if (errors.length > 0) {
30
- logger.error("verify: errors:");
31
- for (const error of errors) {
32
- logger.error(` - ${error}`);
33
- }
34
- return { code: 1, errors, warnings, wranglerPath };
35
- }
36
- logger.success("verify: project is valid (with warnings)");
37
- return { code: 0, errors: [], warnings, wranglerPath };
38
- };
39
- const runVerifyCommand = async (options) => {
40
- const cwd = options.cwd ?? process.cwd();
41
- const logger = loggerForFormat(options.format, options.logger);
42
- const formatError = validateOutputFormat("verify", options.format);
43
- if (formatError !== void 0) {
44
- options.logger.error(formatError);
45
- return { code: 1, error: formatError, errors: [], warnings: [], wranglerPath: void 0 };
46
- }
47
- const validation = validateWranglerProject({ projectRoot: cwd });
48
- const errors = [...validation.report.errors];
49
- const warnings = [...validation.report.warnings];
50
- try {
51
- const codegen = runCodegen({ apiSpec: options.apiSpec, dryRun: true, projectRoot: cwd });
52
- const gate = runSchemaDriftGate({ allowDrift: options.allowSchemaDrift === true, codegen, logger, readOnly: true });
53
- if (gate.blocked) {
54
- errors.push(gate.reason);
55
- }
56
- } catch (error) {
57
- const message = error instanceof Error ? error.message : String(error);
58
- errors.push(`codegen failed: ${message}`);
59
- }
60
- if (options.typecheck !== false) {
61
- const typecheck = await runTypecheckStep(cwd, options.spawner ?? defaultSpawner);
62
- if (typecheck.error !== void 0) {
63
- errors.push(typecheck.error);
64
- }
65
- if (typecheck.warning !== void 0) {
66
- warnings.push(typecheck.warning);
67
- }
68
- }
69
- const result = reportVerifyResult(logger, errors, warnings, validation.wranglerPath);
70
- if (isJsonFormat(options.format)) {
71
- printJson(result);
72
- }
73
- return result;
74
- };
75
- const execute = defineHandler(async ({ cwd, logger, options }) => {
76
- const result = await runVerifyCommand({
77
- allowSchemaDrift: options.allowSchemaDrift === true,
78
- apiSpec: parseApiSpec(options.apiSpec),
79
- cwd,
80
- format: options.format,
81
- logger,
82
- // `--no-typecheck` is declared as a `no-*` option but cerebro exposes it
83
- // under the negated `typecheck` key (false when passed, true when absent).
84
- typecheck: options.typecheck === false ? false : void 0
85
- });
86
- return { code: result.code };
87
- });
88
-
89
- export { execute, runVerifyCommand };
1
+ import{writeFileSync as h,existsSync as S,readFileSync as b}from"node:fs";import{isAbsolute as w,join as p}from"node:path";import{byCodepoint as y,scoreAdvisor as x,parseAdvisorMap as j,compareToBaseline as A}from"@lunora/advisor";import{runCodegen as F}from"@lunora/codegen";import{d as M}from"../packem_shared/command-DwC11Cwe.mjs";import{v as R,p as D,l as k,i as E}from"../packem_shared/output-format-DfogXx0p.mjs";import{D as f}from"../packem_shared/cli-C37AI4tr.mjs";const l={clean:"·",exempt:"–",failing:"✗",warned:"!"},u=(e,r)=>e.length>=r?e:e+" ".repeat(r-e.length),B=e=>`${e.id} (${e.visibility} ${e.kind})`,g=e=>{let r=0;for(const n of e)r=Math.max(r,n.id.length);return r},m=(e,r)=>` ${u(String(e.score),3)} ${l[e.coverage]} ${u(e.id,r)} ${e.visibility} ${e.kind}`,T=e=>{if(!e.comparable)return[` baseline not comparable (${e.reason}) — regenerate it; this run cannot verify anything`];if(!e.regressed)return[` no regression against baseline (score ${e.scoreDelta>=0?"+":""}${String(e.scoreDelta)})`];const r=[` REGRESSED against baseline (score ${e.scoreDelta>=0?"+":""}${String(e.scoreDelta)})`];for(const n of e.dropped)r.push(` ${n.id}: ${String(n.before)} → ${String(n.after)}`);for(const n of e.newFailing)r.push(` ${n}: now failing`);for(const n of e.worsened)r.push(` ${n}: more findings than the baseline`);return e.projectRegressed&&r.push(" project: new schema/config rules fired"),r},C=(e,r)=>{const n=e.procedures.filter(i=>i.coverage!=="clean"&&i.coverage!=="exempt"),o=g(n),t=[`advisor health ${String(e.score)}/100 — ${e.grade}`,` ${String(e.summary.clean)} clean · ${String(e.summary.warned)} warned · ${String(e.summary.failing)} failing · ${String(e.summary.exempt)} exempt (${String(e.summary.procedures)} procedures, ${String(e.summary.rulesFired)} rules fired)`];return e.project.checks.length>0&&t.push("",` project ${String(e.project.score)}/100 — ${e.project.checks.map(i=>i.name).join(", ")}`),n.length>0&&t.push("",...n.map(i=>m(i,o)),""," run with --all for every procedure, or --entry <file#export> for one"),r!==void 0&&t.push("",...T(r)),t.join(`
2
+ `)},J=e=>e.coverage==="exempt"?[` exempt: ${e.exemptReason===void 0||e.exemptReason===""?"no reason given":e.exemptReason}`]:e.checks.map(r=>{const n=r.occurrences>1?`, ×${String(r.occurrences)}`:"";return` ${r.name} (−${String(r.weight)}${n})`}),L=e=>{const r=new Map;for(const n of e){const o=r.get(n.file);o===void 0?r.set(n.file,[n]):o.push(n)}return[...r].toSorted(([n],[o])=>y(n,o))},N=e=>{const r=g(e.procedures),n=[`advisor health ${String(e.score)}/100 — ${e.grade}`,"",` legend: ${l.clean} clean ${l.warned} warned ${l.failing} failing ${l.exempt} exempt`];for(const[o,t]of L(e.procedures)){n.push("",` ${o}`);for(const i of t)n.push(m(i,r),...J(i))}return n.join(`
3
+ `)},P=(e,r)=>{const n=e.procedures.find(t=>t.id===r);if(n===void 0){const t=e.procedures.slice(0,10).map(i=>` ${i.id}`);return[`no procedure ${r} in the map. Known ids:`,...t,e.procedures.length>10?" …":""].filter(Boolean).join(`
4
+ `)}const o=[`${B(n)} ${String(n.score)}/100, ${n.coverage}`,` weight in the global mean: ${String(n.weight)}`];if(n.checks.length===0)return o.push(""," no rule fired"),o.join(`
5
+ `);o.push(""," rules fired:");for(const t of n.checks)o.push(` [${t.level}] ${t.name} −${String(t.weight)}${t.occurrences>1?` (×${String(t.occurrences)})`:""}`);return o.join(`
6
+ `)},I=new Date(0).toISOString(),$=(e,r)=>w(r)?r:p(e,r),_=e=>{if(e===void 0)return{value:void 0};if(e===null||e==="")return{error:"--min-score needs a value between 0 and 100"};const r=Number(e);return Number.isFinite(r)&&r>=0&&r<=100?{value:r}:{error:"--min-score must be a number between 0 and 100"}},H=(e,r,n)=>{const o=$(r,n===null||n===""?f:n);if(!S(o))return{error:`baseline not found at ${o} — generate one with \`lunora advisor\` and commit it`};const t=j(JSON.parse(b(o,"utf8")));return t===void 0?{error:`baseline at ${o} is malformed — regenerate it with \`lunora advisor\``}:{comparison:A(e,t)}},K=e=>`baseline is not comparable (${e}) regenerate it; this run verified nothing`,O=(e,r,n)=>r.entry!==void 0?P(e,r.entry):r.all===!0?N(e):C(e,n),q=e=>{const r=e.cwd??process.cwd(),n=E(e.format),o=k(e.format,e.logger),t=R("advisor",e.format);if(t!==void 0)return e.logger.error(t),{error:t};const i=_(e.minScore);if("error"in i)return e.logger.error(i.error),{error:i.error};const{advisorContext:d,advisories:v}=F({dryRun:!0,projectRoot:r});if(d===void 0){const s="advisor evidence unavailable — codegen ran with linting disabled";return e.logger.error(s),{error:s}}const a=x(d.procedureProtections??[],v,{generatedAt:e.generatedAt??I}),c={map:a};if(e.baseline!==void 0){const s=H(a,r,e.baseline);if("error"in s)return e.logger.error(s.error),{...c,error:s.error};c.comparison=s.comparison,s.comparison.comparable||e.logger.error(K(s.comparison.reason))}if(e.write!==!1){const s=$(r,e.out??f);h(s,`${JSON.stringify(a,void 0,4)}
7
+ `,"utf8"),c.written=s}return c.belowMinScore=i.value!==void 0&&a.score<i.value,c.belowMinScore&&o.error(`advisor score ${String(a.score)} is below the required ${String(i.value)}`),n?(D(c),c):(o.info(O(a,e,c.comparison)),c.written!==void 0&&o.success(`wrote ${c.written}`),c)},G=e=>e.error!==void 0||e.belowMinScore===!0?!0:e.comparison!==void 0&&(!e.comparison.comparable||e.comparison.regressed),Z=M(({cwd:e,logger:r,options:n})=>{const o=q({all:n.all,baseline:n.baseline,cwd:e,entry:n.entry,format:n.format,logger:r,minScore:n.minScore,out:n.out,write:n.write});return{code:G(o)?1:0}});export{Z as execute,q as runAdvisorCommand};